hexsha
stringlengths
40
40
size
int64
7
1.04M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
247
max_stars_repo_name
stringlengths
4
125
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
368k
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
247
max_issues_repo_name
stringlengths
4
125
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
116k
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
247
max_forks_repo_name
stringlengths
4
125
max_forks_repo_head_hexsha
stringlengths
40
78
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
1
1.04M
avg_line_length
float64
1.77
618k
max_line_length
int64
1
1.02M
alphanum_fraction
float64
0
1
original_content
stringlengths
7
1.04M
filtered:remove_function_no_docstring
int64
-102
942k
filtered:remove_class_no_docstring
int64
-354
977k
filtered:remove_delete_markers
int64
0
60.1k
0ceebdf9d3bde890ba7f5356745ce15744d0659d
2,717
py
Python
services/dy-static-file-server/tests/integration/test_docker_image.py
odeimaiz/osparc-services
1a572cc35c742889f39f9d0aae6ad82d1610d33e
[ "MIT" ]
null
null
null
services/dy-static-file-server/tests/integration/test_docker_image.py
odeimaiz/osparc-services
1a572cc35c742889f39f9d0aae6ad82d1610d33e
[ "MIT" ]
null
null
null
services/dy-static-file-server/tests/integration/test_docker_image.py
odeimaiz/osparc-services
1a572cc35c742889f39f9d0aae6ad82d1610d33e
[ "MIT" ]
null
null
null
# pylint:disable=unused-variable # pylint:disable=unused-argument # pylint:disable=redefined-outer-name import json import shutil import urllib.request from pathlib import Path from typing import Dict import pytest import docker import jsonschema import yaml # HELPERS # FIXTURES @pytest.fixture(scope="function") @pytest.fixture(scope="function") # TESTS
31.229885
129
0.726537
# pylint:disable=unused-variable # pylint:disable=unused-argument # pylint:disable=redefined-outer-name import json import shutil import urllib.request from pathlib import Path from typing import Dict import pytest import docker import jsonschema import yaml # HELPERS def _download_url(url: str, file: Path): # Download the file from `url` and save it locally under `file_name`: with urllib.request.urlopen(url) as response, file.open("wb") as out_file: shutil.copyfileobj(response, out_file) assert file.exists() def _convert_to_simcore_labels(image_labels: Dict) -> Dict: io_simcore_labels = {} for key, value in image_labels.items(): if str(key).startswith("io.simcore."): simcore_label = json.loads(value) simcore_keys = list(simcore_label.keys()) assert len(simcore_keys) == 1 simcore_key = simcore_keys[0] simcore_value = simcore_label[simcore_key] io_simcore_labels[simcore_key] = simcore_value assert len(io_simcore_labels) > 0 return io_simcore_labels # FIXTURES @pytest.fixture(scope="function") def osparc_service_labels_jsonschema(tmp_path) -> Dict: url = "https://raw.githubusercontent.com/ITISFoundation/osparc-simcore/master/api/specs/common/schemas/node-meta-v0.0.1.json" file_name = tmp_path / "service_label.json" _download_url(url, file_name) with file_name.open() as fp: json_schema = json.load(fp) return json_schema @pytest.fixture(scope="function") def metadata_labels(metadata_file: Path) -> Dict: with metadata_file.open() as fp: metadata = yaml.safe_load(fp) return metadata # TESTS def test_docker_io_simcore_labels_against_files( docker_image: docker.models.images.Image, metadata_labels: Dict ): image_labels = docker_image.labels io_simcore_labels = _convert_to_simcore_labels(image_labels) # check files are identical for key, value in io_simcore_labels.items(): assert key in metadata_labels assert value == metadata_labels[key] def test_validate_docker_io_simcore_labels( docker_image: docker.models.images.Image, osparc_service_labels_jsonschema: Dict ): image_labels = docker_image.labels # get io labels io_simcore_labels = _convert_to_simcore_labels(image_labels) # validate schema try: jsonschema.validate(io_simcore_labels, osparc_service_labels_jsonschema) except jsonschema.SchemaError: pytest.fail( "Schema {} contains errors".format(osparc_service_labels_jsonschema) ) except jsonschema.ValidationError: pytest.fail("Failed to validate docker image io labels against schema")
2,212
0
135
db27575a4dedb67b2788e5baf45d5a75003ca35f
1,172
py
Python
setup.py
jni/h5cat
98bf0ad301b65ee95f947b3fc764a1fc31ea73b7
[ "MIT" ]
11
2017-03-15T22:16:20.000Z
2020-12-20T05:27:05.000Z
setup.py
jni/h5cat
98bf0ad301b65ee95f947b3fc764a1fc31ea73b7
[ "MIT" ]
1
2018-10-02T09:40:39.000Z
2018-10-05T04:28:06.000Z
setup.py
jni/h5cat
98bf0ad301b65ee95f947b3fc764a1fc31ea73b7
[ "MIT" ]
null
null
null
from setuptools import setup descr = """h5cat: Quick preview of hdf5 files Quickly check the contents of multiple hdf5 files. Usage: `h5cat -h` `h5cat path/to/hdffiles/*.h5` Note: h5cat is no longer maintained. For similar functionality, see h5glance at https://pypi.org/project/h5glance/#description """ DISTNAME = 'h5cat' DESCRIPTION = 'Quick preview of hdf5 files' LONG_DESCRIPTION = descr MAINTAINER = 'Juan Nunez-Iglesias' MAINTAINER_EMAIL = 'juan.nunez-iglesias@monash.edu' URL = 'https://github.com/jni/h5cat' LICENSE = 'BSD 3-clause' DOWNLOAD_URL = 'https://github.com/jni/h5cat' VERSION = '0.1' INST_DEPENDENCIES = [] if __name__ == '__main__': setup(name=DISTNAME, version=VERSION, url=URL, description=DESCRIPTION, long_description=LONG_DESCRIPTION, author=MAINTAINER, author_email=MAINTAINER_EMAIL, license=LICENSE, py_modules=['h5cat'], package_data={}, install_requires=INST_DEPENDENCIES, entry_points = { 'console_scripts': ['h5cat=h5cat:main'] } )
26.636364
67
0.633106
from setuptools import setup descr = """h5cat: Quick preview of hdf5 files Quickly check the contents of multiple hdf5 files. Usage: `h5cat -h` `h5cat path/to/hdffiles/*.h5` Note: h5cat is no longer maintained. For similar functionality, see h5glance at https://pypi.org/project/h5glance/#description """ DISTNAME = 'h5cat' DESCRIPTION = 'Quick preview of hdf5 files' LONG_DESCRIPTION = descr MAINTAINER = 'Juan Nunez-Iglesias' MAINTAINER_EMAIL = 'juan.nunez-iglesias@monash.edu' URL = 'https://github.com/jni/h5cat' LICENSE = 'BSD 3-clause' DOWNLOAD_URL = 'https://github.com/jni/h5cat' VERSION = '0.1' INST_DEPENDENCIES = [] if __name__ == '__main__': setup(name=DISTNAME, version=VERSION, url=URL, description=DESCRIPTION, long_description=LONG_DESCRIPTION, author=MAINTAINER, author_email=MAINTAINER_EMAIL, license=LICENSE, py_modules=['h5cat'], package_data={}, install_requires=INST_DEPENDENCIES, entry_points = { 'console_scripts': ['h5cat=h5cat:main'] } )
0
0
0
6b8173f66801745c7fe6b93e230a6d0f560b3218
1,343
py
Python
src/feecc_workbench/_db_utils.py
Multi-Agent-io/feecc-workbench-daemon
87f0015fd6fc8e98dde3cde7825573b6c86c1e25
[ "Apache-2.0" ]
null
null
null
src/feecc_workbench/_db_utils.py
Multi-Agent-io/feecc-workbench-daemon
87f0015fd6fc8e98dde3cde7825573b6c86c1e25
[ "Apache-2.0" ]
1
2021-11-08T16:07:08.000Z
2021-11-08T16:07:08.000Z
src/feecc_workbench/_db_utils.py
Multi-Agent-io/feecc-workbench-daemon
87f0015fd6fc8e98dde3cde7825573b6c86c1e25
[ "Apache-2.0" ]
2
2021-12-09T13:23:17.000Z
2022-03-23T13:04:41.000Z
import datetime as dt import sys import typing as tp from loguru import logger from motor.motor_asyncio import AsyncIOMotorClient from .Unit import Unit def _get_database_client(mongo_connection_uri: str) -> AsyncIOMotorClient: """Get MongoDB connection url""" try: db_client = AsyncIOMotorClient(mongo_connection_uri, serverSelectionTimeoutMS=10000) db_client.server_info() return db_client except Exception as E: message = ( f"Failed to establish database connection: {E}. " f"Is the provided URI correct? {mongo_connection_uri=} Exiting." ) logger.critical(message) sys.exit(1)
31.97619
106
0.676843
import datetime as dt import sys import typing as tp from loguru import logger from motor.motor_asyncio import AsyncIOMotorClient from .Unit import Unit def _get_database_client(mongo_connection_uri: str) -> AsyncIOMotorClient: """Get MongoDB connection url""" try: db_client = AsyncIOMotorClient(mongo_connection_uri, serverSelectionTimeoutMS=10000) db_client.server_info() return db_client except Exception as E: message = ( f"Failed to establish database connection: {E}. " f"Is the provided URI correct? {mongo_connection_uri=} Exiting." ) logger.critical(message) sys.exit(1) def _get_unit_dict_data(unit: Unit) -> tp.Dict[str, tp.Union[str, bool, None, tp.List[str], dt.datetime]]: return { "schema_id": unit.schema.schema_id, "uuid": unit.uuid, "internal_id": unit.internal_id, "is_in_db": unit.is_in_db, "passport_short_url": unit.passport_short_url, "passport_ipfs_cid": unit.passport_ipfs_cid, "txn_hash": unit.txn_hash, "serial_number": unit.serial_number, "components_internal_ids": unit.components_internal_ids, "featured_in_int_id": unit.featured_in_int_id, "creation_time": unit.creation_time, "status": unit.status.value, }
641
0
23
aa50f0672f8070eb71fc01f9ec83eb2495ef596a
27,913
py
Python
kits/python/dev/tests/test_agent.py
ppinchuk/Lux-Design-2021
8a04ad48c6749cafc9aca986f14e75daaa31c789
[ "Apache-2.0" ]
null
null
null
kits/python/dev/tests/test_agent.py
ppinchuk/Lux-Design-2021
8a04ad48c6749cafc9aca986f14e75daaa31c789
[ "Apache-2.0" ]
null
null
null
kits/python/dev/tests/test_agent.py
ppinchuk/Lux-Design-2021
8a04ad48c6749cafc9aca986f14e75daaa31c789
[ "Apache-2.0" ]
null
null
null
import pytest import sys import agent as agent import lux.game as g import lux.game_objects as go import lux.game_map as gm import lux.constants as c from collections import deque """ [WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'rp 0 0' <- research points (player id, num) [WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'rp 1 0' [WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'r coal 0 3 419' <- resource (type, x, y, amount) [WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'r wood 0 9 314' [WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'r uranium 6 10 331' [WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'u 0 0 u_1 13 7 0 0 0 0' <- unit (type, team, id, x, y, cooldown, wood, coal, uranium) [WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'u 0 1 u_2 13 16 0 0 0 0' [WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'c 0 c_1 0 23' <- city (team, id, fuel, lightupkeep) [WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'c 1 c_2 0 23' [WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'ct 0 c_1 13 7 0' <- citytile (team, id, x, y, cooldown) [WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'ct 1 c_2 13 16 0' [WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'ccd 13 7 6' <- road (x, y, level) [WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'ccd 13 16 6' [WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'D_DONE' """
32.344148
164
0.513202
import pytest import sys import agent as agent import lux.game as g import lux.game_objects as go import lux.game_map as gm import lux.constants as c from collections import deque """ [WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'rp 0 0' <- research points (player id, num) [WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'rp 1 0' [WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'r coal 0 3 419' <- resource (type, x, y, amount) [WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'r wood 0 9 314' [WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'r uranium 6 10 331' [WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'u 0 0 u_1 13 7 0 0 0 0' <- unit (type, team, id, x, y, cooldown, wood, coal, uranium) [WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'u 0 1 u_2 13 16 0 0 0 0' [WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'c 0 c_1 0 23' <- city (team, id, fuel, lightupkeep) [WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'c 1 c_2 0 23' [WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'ct 0 c_1 13 7 0' <- citytile (team, id, x, y, cooldown) [WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'ct 1 c_2 13 16 0' [WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'ccd 13 7 6' <- road (x, y, level) [WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'ccd 13 16 6' [WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'D_DONE' """ class TestManageAction: @pytest.mark.parametrize("initialize_game", [3], indirect=['initialize_game']) def test_manage_with_no_more_resources(self, initialize_game): c.LogicGlobals.game_state.update( [ 'u 0 0 u_1 1 0 0 0 0 0', 'c 0 c_1 0 23', 'ct 0 c_1 1 1 0', 'ccd 1 1 6', ], 0 ) # 0 1 2 # 0 __ u1 __ # 1 __ __ __ # 2 __ __ __ unit_actions_this_turn = { 'u_1': (c.ValidActions.MANAGE, 'c_1'), } for unit in c.LogicGlobals.player.units: unit.set_task(*unit_actions_this_turn[unit.id]) actions, debug = agent.unit_actions( c.LogicGlobals.player, c.LogicGlobals.opponent ) assert not actions @pytest.mark.parametrize("initialize_game", [3], indirect=['initialize_game']) def test_manage_at_resource_during_day(self, initialize_game): c.LogicGlobals.game_state.update( [ 'r wood 2 2 314', 'u 0 0 u_1 1 2 0 96 0 0', 'c 0 c_1 0 23', 'ct 0 c_1 1 1 0', 'ccd 1 1 6', ], 0 ) # 0 1 2 # 0 __ __ __ # 1 __ c1 __ # 2 __ u1 wo unit_actions_this_turn = { 'u_1': (c.ValidActions.COLLECT, gm.Position(2, 2)), } for unit in c.LogicGlobals.player.units: unit.set_task(*unit_actions_this_turn[unit.id]) unit.task_q = deque([(c.ValidActions.MANAGE, 'c_1')]) actions, debug = agent.unit_actions( c.LogicGlobals.player, c.LogicGlobals.opponent ) assert actions == ['m u_1 n'] @pytest.mark.parametrize("initialize_game", [3], indirect=['initialize_game']) def test_manage_at_resource_at_night(self, initialize_game): for __ in range(70): c.LogicGlobals.game_state.update([], 0) c.LogicGlobals.game_state.update( [ 'r wood 2 2 314', 'u 0 0 u_1 1 2 0 96 0 0', 'c 0 c_1 0 23', 'ct 0 c_1 1 1 0', 'ccd 1 1 6', ], 0 ) # 0 1 2 # 0 __ __ __ # 1 __ c1 __ # 2 __ u1 wo unit_actions_this_turn = { 'u_1': (c.ValidActions.COLLECT, gm.Position(2, 2)), } for unit in c.LogicGlobals.player.units: unit.set_task(*unit_actions_this_turn[unit.id]) unit.task_q = deque([(c.ValidActions.MANAGE, 'c_1')]) actions, debug = agent.unit_actions( c.LogicGlobals.player, c.LogicGlobals.opponent ) assert actions == ['m u_1 n'] @pytest.mark.parametrize("initialize_game", [3], indirect=['initialize_game']) def test_manage_at_adjacent_resource_at_night(self, initialize_game): for __ in range(71): c.LogicGlobals.game_state.update([], 0) c.LogicGlobals.game_state.update( [ 'r wood 1 2 514', 'u 0 0 u_1 1 0 0 0 0 0', 'c 0 c_1 200 23', 'ct 0 c_1 1 0 0', 'ccd 1 1 6', ], 0 ) # 0 1 2 # 0 __ u1 __ # 1 __ __ __ # 2 __ wo __ unit_actions_this_turn = { 'u_1': (c.ValidActions.MANAGE, 'c_1'), } for unit in c.LogicGlobals.player.units: unit.set_task(*unit_actions_this_turn[unit.id]) actions, debug = agent.unit_actions( c.LogicGlobals.player, c.LogicGlobals.opponent ) assert actions == ['m u_1 s'] @pytest.mark.parametrize("initialize_game", [3], indirect=['initialize_game']) def test_manage_at_not_adjacent_resource_at_night(self, initialize_game): for __ in range(71): c.LogicGlobals.game_state.update([], 0) c.LogicGlobals.game_state.update( [ 'r wood 2 2 514', 'u 0 0 u_1 1 0 0 0 0 0', 'c 0 c_1 200 23', 'ct 0 c_1 1 0 0', 'ccd 1 1 6', ], 0 ) # 0 1 2 # 0 __ u1 __ # 1 __ __ __ # 2 __ wo __ unit_actions_this_turn = { 'u_1': (c.ValidActions.MANAGE, 'c_1'), } for unit in c.LogicGlobals.player.units: unit.set_task(*unit_actions_this_turn[unit.id]) actions, debug = agent.unit_actions( c.LogicGlobals.player, c.LogicGlobals.opponent ) assert not actions class TestUnitMovement: @pytest.mark.parametrize("initialize_game", [3], indirect=['initialize_game']) def test_single_unit_movement(self, initialize_game): c.LogicGlobals.game_state.update( [ 'u 0 0 u_1 1 0 0 0 0 0', ], 0 ) # 0 1 2 # 0 __ u1 __ # 1 __ __ __ # 2 __ __ __ unit_actions_this_turn = { 'u_1': (c.ValidActions.MOVE, gm.Position(1, 2)), } for unit in c.LogicGlobals.player.units: unit.set_task(*unit_actions_this_turn[unit.id]) actions, debug = agent.unit_actions( c.LogicGlobals.player, c.LogicGlobals.opponent ) assert actions == ['m u_1 s'] @pytest.mark.parametrize("initialize_game", [3], indirect=['initialize_game']) def test_movement_with_road(self, initialize_game): c.LogicGlobals.game_state.update( [ 'u 0 0 u_1 0 0 0 0 0 0', 'ccd 0 1 6', 'ccd 1 1 6', 'ccd 2 1 6', 'ccd 2 2 6', ], 0 ) # 0 1 2 # 0 u1 __ __ # 1 == == == # 2 __ __ == unit_actions_this_turn = { 'u_1': (c.ValidActions.MOVE, gm.Position(2, 2)), } for unit in c.LogicGlobals.player.units: unit.set_task(*unit_actions_this_turn[unit.id]) actions, debug = agent.unit_actions( c.LogicGlobals.player, c.LogicGlobals.opponent ) assert actions == ['m u_1 s'] @pytest.mark.parametrize("initialize_game", [3], indirect=['initialize_game']) def test_moving_from_city_tile_at_night(self, initialize_game): for _ in range(c.GAME_CONSTANTS['PARAMETERS']['DAY_LENGTH'] - 1): c.LogicGlobals.game_state.update( [ 'u 0 0 u_1 0 0 0 0 0 0', 'c 0 c_1 0 23', 'ct 0 c_1 0 0 0', 'ccd 0 0 6', ], 0 ) # 0 1 2 # 0 u1 __ __ # 1 __ __ __ # 2 __ __ __ for _ in range(c.GAME_CONSTANTS['PARAMETERS']['NIGHT_LENGTH'] + 1): c.LogicGlobals.game_state.update( [ 'u 0 0 u_1 0 0 0 0 0 0', 'c 0 c_1 0 23', 'ct 0 c_1 0 0 0', 'ccd 0 0 6', ], 0 ) unit_actions_this_turn = { 'u_1': (c.ValidActions.MOVE, gm.Position(2, 2)), } for unit in c.LogicGlobals.player.units: unit.set_task(*unit_actions_this_turn[unit.id]) actions, debug = agent.unit_actions( c.LogicGlobals.player, c.LogicGlobals.opponent ) assert not actions c.LogicGlobals.game_state.update( [ 'u 0 0 u_1 0 0 0 0 0 0', 'c 0 c_1 0 23', 'ct 0 c_1 0 0 0', 'ccd 0 0 6', ], 0 ) unit_actions_this_turn = { 'u_1': (c.ValidActions.MOVE, gm.Position(2, 2)), } for unit in c.LogicGlobals.player.units: unit.set_task(*unit_actions_this_turn[unit.id]) actions, debug = agent.unit_actions( c.LogicGlobals.player, c.LogicGlobals.opponent ) assert len(actions) == 1 class TestUnitCollisions: @pytest.mark.parametrize("initialize_game", [3], indirect=['initialize_game']) def test_collision_when_equidistant_move_loc(self, initialize_game): c.LogicGlobals.game_state.update( [ 'u 0 0 u_1 0 0 0 0 0 0', 'u 0 0 u_2 1 1 0 0 0 0', ], 0 ) # 0 1 2 # 0 u1 __ __ # 1 __ u2 __ # 2 __ __ __ unit_actions_this_turn = { 'u_1': (c.ValidActions.MOVE, gm.Position(2, 2)), 'u_2': (c.ValidActions.MOVE, gm.Position(0, 1)) } for unit in c.LogicGlobals.player.units: unit.set_task(*unit_actions_this_turn[unit.id]) actions, debug = agent.unit_actions( c.LogicGlobals.player, c.LogicGlobals.opponent ) assert len(actions) == 2 assert 'm u_2 w' in actions assert 'm u_1 e' in actions @pytest.mark.parametrize("initialize_game", [3], indirect=['initialize_game']) def test_collision_moving_through(self, initialize_game): c.LogicGlobals.game_state.update( [ 'u 0 0 u_1 1 0 0 0 0 0', 'u 0 0 u_2 0 1 0 0 0 0', ], 0 ) # 0 1 2 # 0 __ u1 __ # 1 u2 __ __ # 2 __ __ __ unit_actions_this_turn = { 'u_1': (c.ValidActions.MOVE, gm.Position(1, 2)), 'u_2': (c.ValidActions.MOVE, gm.Position(2, 1)) } for unit in c.LogicGlobals.player.units: unit.set_task(*unit_actions_this_turn[unit.id]) actions, debug = agent.unit_actions( c.LogicGlobals.player, c.LogicGlobals.opponent ) assert len(actions) == 1 assert ('m u_2 e' in actions) or ('m u_1 s' in actions) @pytest.mark.parametrize("initialize_game", [3], indirect=['initialize_game']) def test_collision_mix_of_through_and_target(self, initialize_game): c.LogicGlobals.game_state.update( [ 'u 0 0 u_1 1 0 0 0 0 0', 'u 0 0 u_2 0 1 0 0 0 0', ], 0 ) # 0 1 2 # 0 __ u1 __ # 1 u2 __ __ # 2 __ __ __ unit_actions_this_turn = { 'u_1': (c.ValidActions.MOVE, gm.Position(1, 1)), 'u_2': (c.ValidActions.MOVE, gm.Position(2, 1)) } for unit in c.LogicGlobals.player.units: unit.set_task(*unit_actions_this_turn[unit.id]) actions, debug = agent.unit_actions( c.LogicGlobals.player, c.LogicGlobals.opponent ) assert len(actions) == 1 assert 'm u_2 e' in actions for unit in c.LogicGlobals.player.units: if unit.id == 'u_1': assert unit.turns_spent_waiting_to_move == 1 if unit.id == 'u_2': assert unit.turns_spent_waiting_to_move == 0 @pytest.mark.parametrize("initialize_game", [3], indirect=['initialize_game']) def test_collision_mix_of_through_and_target_with_city(self, initialize_game): c.LogicGlobals.game_state.update( [ 'u 0 0 u_1 1 0 0 0 0 0', 'u 0 0 u_2 0 1 0 0 0 0', 'c 0 c_1 0 23', 'ct 0 c_1 1 1 0' ], 0 ) # 0 1 2 # 0 __ u1 __ # 1 u2 c1 __ # 2 __ __ __ unit_actions_this_turn = { 'u_1': (c.ValidActions.MOVE, gm.Position(1, 2)), 'u_2': (c.ValidActions.MOVE, gm.Position(2, 1)) } for unit in c.LogicGlobals.player.units: unit.set_task(*unit_actions_this_turn[unit.id]) actions, debug = agent.unit_actions( c.LogicGlobals.player, c.LogicGlobals.opponent ) assert len(actions) == 2 assert 'm u_2 e' in actions assert 'm u_1 s' in actions @pytest.mark.parametrize("initialize_game", [5], indirect=['initialize_game']) def test_collision_mix_of_through_and_target_multi(self, initialize_game): c.LogicGlobals.game_state.update( [ 'u 0 0 u_1 2 0 0 0 0 0', 'u 0 0 u_2 1 1 0 0 0 0', 'u 0 0 u_3 0 1 0 0 0 0', ], 0 ) # 0 1 2 3 4 # 0 __ __ u1 __ __ # 1 u3 u2 __ __ __ # 2 __ __ __ __ __ # 4 __ __ __ __ __ # 5 __ __ __ __ __ unit_actions_this_turn = { 'u_1': (c.ValidActions.MOVE, gm.Position(2, 1)), 'u_2': (c.ValidActions.MOVE, gm.Position(4, 1)), 'u_3': (c.ValidActions.MOVE, gm.Position(3, 1)) } for unit in c.LogicGlobals.player.units: unit.set_task(*unit_actions_this_turn[unit.id]) actions, debug = agent.unit_actions( c.LogicGlobals.player, c.LogicGlobals.opponent ) assert len(actions) == 2 assert 'm u_2 e' in actions assert 'm u_3 e' in actions for unit in c.LogicGlobals.player.units: if unit.id == 'u_1': assert unit.turns_spent_waiting_to_move == 1 if unit.id in {'u_2', 'u_3'}: assert unit.turns_spent_waiting_to_move == 0 c.LogicGlobals.game_state.update( [ 'u 0 0 u_1 2 0 0 0 0 0', 'u 0 0 u_2 2 1 0 0 0 0', 'u 0 0 u_3 1 1 0 0 0 0', ], 0 ) # 0 1 2 3 4 # 0 __ __ u1 __ __ # 1 __ u3 u2 __ __ # 2 __ __ __ __ __ # 4 __ __ __ __ __ # 5 __ __ __ __ __ unit_actions_this_turn = { 'u_1': (c.ValidActions.MOVE, gm.Position(2, 1)), 'u_2': (c.ValidActions.MOVE, gm.Position(4, 1)), 'u_3': (c.ValidActions.MOVE, gm.Position(3, 1)) } for unit in c.LogicGlobals.player.units: unit.set_task(*unit_actions_this_turn[unit.id]) actions, debug = agent.unit_actions( c.LogicGlobals.player, c.LogicGlobals.opponent ) assert len(actions) == 2 assert 'm u_2 e' in actions assert 'm u_3 e' in actions for unit in c.LogicGlobals.player.units: if unit.id == 'u_1': assert unit.turns_spent_waiting_to_move == 2 if unit.id in {'u_2', 'u_3'}: assert unit.turns_spent_waiting_to_move == 0 c.LogicGlobals.game_state.update( [ 'u 0 0 u_1 2 0 0 0 0 0', 'u 0 0 u_2 3 1 0 0 0 0', 'u 0 0 u_3 2 1 0 0 0 0', ], 0 ) # 0 1 2 3 4 # 0 __ __ u1 __ __ # 1 __ __ u3 u2 __ # 2 __ __ __ __ __ # 4 __ __ __ __ __ # 5 __ __ __ __ __ unit_actions_this_turn = { 'u_1': (c.ValidActions.MOVE, gm.Position(2, 1)), 'u_2': (c.ValidActions.MOVE, gm.Position(4, 1)), 'u_3': (c.ValidActions.MOVE, gm.Position(3, 1)) } for unit in c.LogicGlobals.player.units: unit.set_task(*unit_actions_this_turn[unit.id]) actions, debug = agent.unit_actions( c.LogicGlobals.player, c.LogicGlobals.opponent ) assert len(actions) == 3 assert 'm u_1 s' in actions assert 'm u_2 e' in actions assert 'm u_3 e' in actions for unit in c.LogicGlobals.player.units: assert unit.turns_spent_waiting_to_move == 0 """ [WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'rp 0 0' <- research points (player id, num) [WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'rp 1 0' [WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'r coal 0 3 419' <- resource (type, x, y, amount) [WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'r wood 0 9 314' [WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'r uranium 6 10 331' [WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'u 0 0 u_1 13 7 0 0 0 0' <- unit (type, team, id, x, y, cooldown, wood, coal, uranium) [WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'u 0 1 u_2 13 16 0 0 0 0' [WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'c 0 c_1 0 23' <- city (team, id, fuel, lightupkeep) [WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'c 1 c_2 0 23' [WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'ct 0 c_1 13 7 0' <- citytile (team, id, x, y, cooldown) [WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'ct 1 c_2 13 16 0' [WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'ccd 13 7 6' <- road (x, y, level) [WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'ccd 13 16 6' [WARN] (match_NF4VsaRK1hf9) - Agent 0 sent malformed command: 'D_DONE' """ @pytest.mark.parametrize("initialize_game", [3], indirect=['initialize_game']) def test_collision_snake1(self, initialize_game): c.LogicGlobals.game_state.update( [ 'u 0 0 u_1 0 1 0 0 0 0', 'u 0 0 u_2 1 1 0 0 0 0', 'u 0 0 u_3 1 2 0 0 0 0', 'c 1 c_1 0 23', 'ct 1 c_1 0 2 0', 'c 1 c_2 0 23', 'ct 1 c_2 1 0 0', ], 0 ) # 0 1 2 # 0 __ c2 __ # 1 u1 u2 __ # 2 c1 u3 __ c.LogicGlobals.player.current_strategy = c.StrategyTypes.STARTER unit_actions_this_turn = { 'u_1': (c.ValidActions.MOVE, gm.Position(1, 2)), 'u_2': (c.ValidActions.MOVE, gm.Position(0, 0)), 'u_3': (c.ValidActions.MOVE, gm.Position(0, 1)) } for unit in c.LogicGlobals.player.units: unit.set_task(*unit_actions_this_turn[unit.id]) actions, debug = agent.unit_actions( c.LogicGlobals.player, c.LogicGlobals.opponent ) assert len(actions) == 2, actions assert 'm u_1 e' in actions assert 'm u_2 w' in actions c.LogicGlobals.game_state.update( [ 'u 0 0 u_1 1 1 0 0 0 0', 'u 0 0 u_2 0 1 3 0 0 0', 'u 0 0 u_3 1 2 0 0 0 0', 'c 1 c_1 0 23', 'ct 1 c_1 0 2 0', 'c 1 c_2 0 23', 'ct 1 c_2 1 0 0', ], 0 ) # 0 1 2 # 0 __ c2 __ # 1 u2 u1 __ # 2 c1 u3 __ unit_actions_this_turn = { 'u_1': (c.ValidActions.MOVE, gm.Position(1, 2)), 'u_2': (c.ValidActions.MOVE, gm.Position(0, 1)), 'u_3': (c.ValidActions.MOVE, gm.Position(1, 1)) } lslsdldl = c.LogicGlobals.player for unit in c.LogicGlobals.player.units: unit.set_task(*unit_actions_this_turn[unit.id]) actions, debug = agent.unit_actions( c.LogicGlobals.player, c.LogicGlobals.opponent ) assert len(actions) == 2, actions assert 'm u_1 s' in actions assert 'm u_3 n' in actions @pytest.mark.parametrize("initialize_game", [3], indirect=['initialize_game']) def test_collision_snake2(self, initialize_game): c.LogicGlobals.game_state.update( [ 'u 0 0 u_1 0 1 0 0 0 0', 'u 0 0 u_2 1 1 0 0 0 0', 'u 0 0 u_3 1 2 0 0 0 0', 'u 0 0 u_4 2 2 0 0 0 0', 'c 1 c_1 0 23', 'c 1 c_2 0 23', 'ct 1 c_1 0 2 0', 'ct 1 c_2 2 1 0', ], 0 ) # 0 1 2 # 0 __ __ __ # 1 u1 u2 c2 # 2 c1 u3 u4 c.LogicGlobals.player.current_strategy = c.StrategyTypes.STARTER unit_actions_this_turn = { 'u_1': (c.ValidActions.MOVE, gm.Position(2, 2)), 'u_2': (c.ValidActions.MOVE, gm.Position(0, 1)), 'u_3': (c.ValidActions.MOVE, gm.Position(1, 1)), 'u_4': (c.ValidActions.MOVE, gm.Position(1, 2)) } for unit in c.LogicGlobals.player.units: unit.set_task(*unit_actions_this_turn[unit.id]) actions, debug = agent.unit_actions( c.LogicGlobals.player, c.LogicGlobals.opponent ) assert len(actions) == 2, actions assert 'm u_1 e' in actions assert 'm u_2 w' in actions c.LogicGlobals.game_state.update( [ 'u 0 0 u_1 1 1 0 0 0 0', 'u 0 0 u_2 0 1 0 0 0 0', 'u 0 0 u_3 1 2 0 0 0 0', 'u 0 0 u_4 2 2 0 0 0 0', 'c 1 c_1 0 23', 'c 1 c_2 0 23', 'ct 1 c_1 0 2 0', 'ct 1 c_2 2 1 0', ], 0 ) # 0 1 2 # 0 __ __ __ # 1 u2 u1 c2 # 2 c1 u3 u4 unit_actions_this_turn = { 'u_1': (c.ValidActions.MOVE, gm.Position(2, 2)), 'u_2': (c.ValidActions.MOVE, gm.Position(0, 1)), 'u_3': (c.ValidActions.MOVE, gm.Position(1, 1)), 'u_4': (c.ValidActions.MOVE, gm.Position(1, 2)) } for unit in c.LogicGlobals.player.units: unit.set_task(*unit_actions_this_turn[unit.id]) actions, debug = agent.unit_actions( c.LogicGlobals.player, c.LogicGlobals.opponent ) assert len(actions) == 2, actions assert 'm u_1 s' in actions assert 'm u_3 n' in actions c.LogicGlobals.game_state.update( [ 'u 0 0 u_1 1 2 0 0 0 0', 'u 0 0 u_2 0 1 0 0 0 0', 'u 0 0 u_3 1 1 0 0 0 0', 'u 0 0 u_4 2 2 0 0 0 0', 'c 1 c_1 0 23', 'c 1 c_2 0 23', 'ct 1 c_1 0 2 0', 'ct 1 c_2 2 1 0', ], 0 ) # 0 1 2 # 0 __ __ __ # 1 u2 u3 c2 # 2 c1 u1 u4 unit_actions_this_turn = { 'u_1': (c.ValidActions.MOVE, gm.Position(2, 2)), 'u_2': (c.ValidActions.MOVE, gm.Position(0, 1)), 'u_3': (c.ValidActions.MOVE, gm.Position(1, 1)), 'u_4': (c.ValidActions.MOVE, gm.Position(1, 2)) } for unit in c.LogicGlobals.player.units: unit.set_task(*unit_actions_this_turn[unit.id]) actions, debug = agent.unit_actions( c.LogicGlobals.player, c.LogicGlobals.opponent ) assert len(actions) == 2 assert 'm u_1 e' in actions assert 'm u_4 w' in actions @pytest.mark.parametrize("initialize_game", [4], indirect=['initialize_game']) def test_collision_snake2(self, initialize_game): c.LogicGlobals.game_state.update( [ 'u 0 0 u_1 0 1 0 0 0 0', 'u 0 0 u_2 1 1 0 0 0 0', 'u 0 0 u_3 1 2 0 0 0 0', 'u 0 0 u_4 2 2 0 0 0 0', 'c 1 c_1 0 23', 'c 1 c_2 0 23', 'ct 1 c_1 0 2 0', 'ct 1 c_2 2 1 0', ], 0 ) # 0 1 2 3 # 0 __ __ __ __ # 1 u5 c1 __ __ # 2 u1 u2 c2 __ # 3 u6 u3 u4 c3 c.LogicGlobals.player.current_strategy = c.StrategyTypes.STARTER unit_actions_this_turn = { 'u_1': (c.ValidActions.MOVE, gm.Position(2, 2)), 'u_2': (c.ValidActions.MOVE, gm.Position(0, 1)), 'u_3': (c.ValidActions.MOVE, gm.Position(1, 1)), 'u_4': (c.ValidActions.MOVE, gm.Position(1, 2)) } for unit in c.LogicGlobals.player.units: unit.set_task(*unit_actions_this_turn[unit.id]) actions, debug = agent.unit_actions( c.LogicGlobals.player, c.LogicGlobals.opponent ) assert len(actions) == 2, actions assert 'm u_1 e' in actions assert 'm u_2 w' in actions c.LogicGlobals.game_state.update( [ 'u 0 0 u_1 1 1 0 0 0 0', 'u 0 0 u_2 0 1 0 0 0 0', 'u 0 0 u_3 1 2 0 0 0 0', 'u 0 0 u_4 2 2 0 0 0 0', 'c 1 c_1 0 23', 'c 1 c_2 0 23', 'ct 1 c_1 0 2 0', 'ct 1 c_2 2 1 0', ], 0 ) # 0 1 2 # 0 __ __ __ # 1 u2 u1 c2 # 2 c1 u3 u4 unit_actions_this_turn = { 'u_1': (c.ValidActions.MOVE, gm.Position(2, 2)), 'u_2': (c.ValidActions.MOVE, gm.Position(0, 1)), 'u_3': (c.ValidActions.MOVE, gm.Position(1, 1)), 'u_4': (c.ValidActions.MOVE, gm.Position(1, 2)) } for unit in c.LogicGlobals.player.units: unit.set_task(*unit_actions_this_turn[unit.id]) actions, debug = agent.unit_actions( c.LogicGlobals.player, c.LogicGlobals.opponent ) assert len(actions) == 2, actions assert 'm u_1 s' in actions assert 'm u_3 n' in actions c.LogicGlobals.game_state.update( [ 'u 0 0 u_1 1 2 0 0 0 0', 'u 0 0 u_2 0 1 0 0 0 0', 'u 0 0 u_3 1 1 0 0 0 0', 'u 0 0 u_4 2 2 0 0 0 0', 'c 1 c_1 0 23', 'c 1 c_2 0 23', 'ct 1 c_1 0 2 0', 'ct 1 c_2 2 1 0', ], 0 ) # 0 1 2 # 0 __ __ __ # 1 u2 u3 c2 # 2 c1 u1 u4 unit_actions_this_turn = { 'u_1': (c.ValidActions.MOVE, gm.Position(2, 2)), 'u_2': (c.ValidActions.MOVE, gm.Position(0, 1)), 'u_3': (c.ValidActions.MOVE, gm.Position(1, 1)), 'u_4': (c.ValidActions.MOVE, gm.Position(1, 2)) } for unit in c.LogicGlobals.player.units: unit.set_task(*unit_actions_this_turn[unit.id]) actions, debug = agent.unit_actions( c.LogicGlobals.player, c.LogicGlobals.opponent ) assert len(actions) == 2 assert 'm u_1 e' in actions assert 'm u_4 w' in actions
24,540
1,765
69
621096e7d688e913ac0b40cc8fa82008f8dc4e01
2,304
py
Python
mydata_a03.py
g-mitu/timeseries
3b2daf33f9af022d1aae7c4a9caf69b8abd58348
[ "BSD-3-Clause" ]
null
null
null
mydata_a03.py
g-mitu/timeseries
3b2daf33f9af022d1aae7c4a9caf69b8abd58348
[ "BSD-3-Clause" ]
null
null
null
mydata_a03.py
g-mitu/timeseries
3b2daf33f9af022d1aae7c4a9caf69b8abd58348
[ "BSD-3-Clause" ]
null
null
null
import datetime import pandas as pd import numpy as np import matplotlib.pyplot as plt from time import * program_begin = time() # a=pd.DataFrame(pd.date_range("2022-2-14 0:0:02","2022-2-15 23:59:58",freq='2S')) workdir = r"C:\Users\zyhly\Downloads\mydata" df = pd.read_excel(f"{workdir}/a03_data.xlsx", index_col=None) # 以datetime形式将字符串拆分为日期和时间 date2 = pd.to_datetime(df["Date"], errors="coerce") # 方便人查看 df["Date2"] = date2.dt.date # 方便人查看 df["Time"] = date2.dt.time # 方便人查看 df["stime"] = date2.apply(lambda t: t.value // 10 ** 9) # 转化为unix时间戳最小单位是秒s df.set_index("Date", inplace=True) df = df.sort_index(ascending=True) print("Line 17#", df.head()) df["bool_stop"] = df["车速"].between(0, 1000 / 3, inclusive="both") # returning dataframe with salary between above values # making a bool series start_time = datetime.datetime.strptime("6:50:00", "%H:%M:%S").time() end_time = datetime.datetime.strptime("15:29:59", "%H:%M:%S").time() start_time2 = datetime.datetime.strptime("15:30:00", "%H:%M:%S").time() end_time2 = datetime.datetime.strptime("23:59:59", "%H:%M:%S").time() locs_morning = df.index.indexer_between_time(start_time, end_time) # 返回的是符合条件的数据的行号 locs_afternoon = df.index.indexer_between_time(start_time2, end_time2) # 返回的是符合条件的数据的行号 # df1 = df.iloc[locs_morning] # 早班 df1 = df.iloc[locs_afternoon] # 中班 df1 = df1.loc["2022-02-14"] df1.to_excel(f"{workdir}/baseline.xlsx") df1 = df1.loc[df1["bool_stop"] == False] # 这里的False一定不能用引号 df2 = df1["stime"] print(type(df2)) # class 'pandas.core.series.Series' df2 = df2.diff() df2 = df2.fillna(0) # """ ser_diff = df3.index.to_series().diff() df3["ser_diff"] = ser_diff.dt.seconds.div(60, fill_value=0) # df3["总秒数"] = df3.index.to_series().diff().dt.total_seconds() """ # between_time() got an unexpected keyword argument 'inclusive' print("Line 47#", df2.head()) # df2 = df2[df2>2] print(df2[df2 > 2].value_counts()) df2.to_excel(f"{workdir}/01.xlsx") program_finish = time() print("用时:", program_finish - program_begin) plt.rcParams["font.sans-serif"] = ["SimHei"] # 用来正常显示中文标签 plt.rcParams["axes.unicode_minus"] = False # 用来正常显示负号 plt.subplot(211) df2.plot() # plt.show() plt.subplot(212) df2[df2 > 2].value_counts().sort_index().plot(kind="bar") plt.show()
36
89
0.683594
import datetime import pandas as pd import numpy as np import matplotlib.pyplot as plt from time import * program_begin = time() # a=pd.DataFrame(pd.date_range("2022-2-14 0:0:02","2022-2-15 23:59:58",freq='2S')) workdir = r"C:\Users\zyhly\Downloads\mydata" df = pd.read_excel(f"{workdir}/a03_data.xlsx", index_col=None) # 以datetime形式将字符串拆分为日期和时间 date2 = pd.to_datetime(df["Date"], errors="coerce") # 方便人查看 df["Date2"] = date2.dt.date # 方便人查看 df["Time"] = date2.dt.time # 方便人查看 df["stime"] = date2.apply(lambda t: t.value // 10 ** 9) # 转化为unix时间戳最小单位是秒s df.set_index("Date", inplace=True) df = df.sort_index(ascending=True) print("Line 17#", df.head()) df["bool_stop"] = df["车速"].between(0, 1000 / 3, inclusive="both") # returning dataframe with salary between above values # making a bool series start_time = datetime.datetime.strptime("6:50:00", "%H:%M:%S").time() end_time = datetime.datetime.strptime("15:29:59", "%H:%M:%S").time() start_time2 = datetime.datetime.strptime("15:30:00", "%H:%M:%S").time() end_time2 = datetime.datetime.strptime("23:59:59", "%H:%M:%S").time() locs_morning = df.index.indexer_between_time(start_time, end_time) # 返回的是符合条件的数据的行号 locs_afternoon = df.index.indexer_between_time(start_time2, end_time2) # 返回的是符合条件的数据的行号 # df1 = df.iloc[locs_morning] # 早班 df1 = df.iloc[locs_afternoon] # 中班 df1 = df1.loc["2022-02-14"] df1.to_excel(f"{workdir}/baseline.xlsx") df1 = df1.loc[df1["bool_stop"] == False] # 这里的False一定不能用引号 df2 = df1["stime"] print(type(df2)) # class 'pandas.core.series.Series' df2 = df2.diff() df2 = df2.fillna(0) # """ ser_diff = df3.index.to_series().diff() df3["ser_diff"] = ser_diff.dt.seconds.div(60, fill_value=0) # df3["总秒数"] = df3.index.to_series().diff().dt.total_seconds() """ # between_time() got an unexpected keyword argument 'inclusive' print("Line 47#", df2.head()) # df2 = df2[df2>2] print(df2[df2 > 2].value_counts()) df2.to_excel(f"{workdir}/01.xlsx") program_finish = time() print("用时:", program_finish - program_begin) plt.rcParams["font.sans-serif"] = ["SimHei"] # 用来正常显示中文标签 plt.rcParams["axes.unicode_minus"] = False # 用来正常显示负号 plt.subplot(211) df2.plot() # plt.show() plt.subplot(212) df2[df2 > 2].value_counts().sort_index().plot(kind="bar") plt.show()
0
0
0
c9b2dbf72c565bc1542f3e6d08c018c4e78c0cda
103
py
Python
nand_io/__init__.py
Noltari/nand-io
23442ed57950360cd4104d77959bd3001170b333
[ "MIT" ]
null
null
null
nand_io/__init__.py
Noltari/nand-io
23442ed57950360cd4104d77959bd3001170b333
[ "MIT" ]
null
null
null
nand_io/__init__.py
Noltari/nand-io
23442ed57950360cd4104d77959bd3001170b333
[ "MIT" ]
null
null
null
# SPDX-License-Identifier: MIT """NAND IO init.""" from .interface import NandIO __all__ = ["NandIO"]
17.166667
30
0.699029
# SPDX-License-Identifier: MIT """NAND IO init.""" from .interface import NandIO __all__ = ["NandIO"]
0
0
0
95d97919eee63e1b9918f1593a33f34ae3379e23
18,341
py
Python
stanCode_Projects/my_drawing/my_drawing.py
JohnsonWang0319/MystanCodeProjects
9a961761b91ef145847405b0b8c1e958c44e7347
[ "MIT" ]
null
null
null
stanCode_Projects/my_drawing/my_drawing.py
JohnsonWang0319/MystanCodeProjects
9a961761b91ef145847405b0b8c1e958c44e7347
[ "MIT" ]
null
null
null
stanCode_Projects/my_drawing/my_drawing.py
JohnsonWang0319/MystanCodeProjects
9a961761b91ef145847405b0b8c1e958c44e7347
[ "MIT" ]
null
null
null
""" File: Drawing Name: Johnson ---------------------- TODO: """ from campy.graphics.gobjects import GOval, GRect, GPolygon from campy.graphics.gwindow import GWindow if __name__ == '__main__': main()
28.70266
80
0.635571
""" File: Drawing Name: Johnson ---------------------- TODO: """ from campy.graphics.gobjects import GOval, GRect, GPolygon from campy.graphics.gwindow import GWindow def main(): window = GWindow(width=1130, height=1000, title='Girl with a Pearl Earring') background = GRect(1130, 1413) background.filled = True background.fill_color = 'black' background.color = 'black' window.add(background) face5 = GPolygon() face5.add_vertex((306, 189)) face5.add_vertex((248, 277)) face5.add_vertex((225, 354)) face5.add_vertex((206, 489)) face5.add_vertex((194, 677)) face5.add_vertex((251, 686)) face5.add_vertex((251, 730)) face5.add_vertex((256, 774)) face5.add_vertex((270, 818)) face5.add_vertex((284, 842)) face5.add_vertex((306, 864)) face5.add_vertex((330, 875)) face5.add_vertex((359, 880)) face5.add_vertex((401, 874)) face5.add_vertex((435, 861)) face5.add_vertex((470, 845)) face5.add_vertex((558, 794)) face5.add_vertex((578, 776)) face5.add_vertex((544, 759)) face5.add_vertex((569, 728)) face5.add_vertex((601, 691)) face5.add_vertex((626, 657)) face5.add_vertex((639, 629)) face5.add_vertex((651, 588)) face5.add_vertex((660, 551)) face5.add_vertex((668, 505)) face5.add_vertex((670, 459)) face5.add_vertex((672, 431)) face5.add_vertex((657, 387)) face5.add_vertex((640, 342)) face5.add_vertex((612, 292)) face5.add_vertex((585, 245)) face5.add_vertex((566, 217)) face5.add_vertex((538, 185)) face5.add_vertex((515, 162)) face5.add_vertex((489, 141)) face5.add_vertex((474, 129)) face5.add_vertex((433, 93)) face5.add_vertex((396, 111)) face5.add_vertex((365, 129)) face5.add_vertex((340, 152)) face5.add_vertex((320, 171)) face5.filled = True face5.fill_color = 'wheat' face5.color = 'wheat' window.add(face5) face1 = GPolygon() face1.add_vertex((230, 368)) face1.add_vertex((208, 584)) face1.add_vertex((286, 602)) face1.add_vertex((280, 380)) face1.filled = True face1.fill_color = 'cornsilk' face1.color = 'cornsilk' window.add(face1) face2 = GPolygon() face2.add_vertex((410, 133)) face2.add_vertex((340, 217)) face2.add_vertex((511, 311)) face2.add_vertex((546, 290)) face2.add_vertex((490, 202)) face2.filled = True face2.fill_color = 'cornsilk' face2.color = 'cornsilk' window.add(face2) face3 = GPolygon() face3.add_vertex((662, 371)) face3.add_vertex((600, 549)) face3.add_vertex((515, 700)) face3.add_vertex((567, 704)) face3.add_vertex((630, 603)) face3.add_vertex((658, 507)) face3.add_vertex((659, 451)) face3.filled = True face3.fill_color = 'tan' face3.color = 'tan' window.add(face3) face4 = GOval(10, 10, x=419, y=764) face4.filled = True face4.fill_color = 'black' face4.color = 'black' window.add(face4) eyelash1 = GPolygon() eyelash1.add_vertex((270, 256)) eyelash1.add_vertex((270, 256)) eyelash1.add_vertex((288, 269)) eyelash1.add_vertex((304, 287)) eyelash1.add_vertex((314, 305)) eyelash1.filled = True eyelash1.fill_color = 'brown' eyelash1.color = 'brown' window.add(eyelash1) eyelash2 = GPolygon() eyelash2.add_vertex((372, 468)) eyelash2.add_vertex((383, 486)) eyelash2.add_vertex((404, 403)) eyelash2.add_vertex((435, 378)) eyelash2.add_vertex((467, 364)) eyelash2.add_vertex((504, 354)) eyelash2.add_vertex((528, 356)) eyelash2.add_vertex((545, 367)) eyelash2.add_vertex((561, 385)) eyelash2.add_vertex((586, 429)) eyelash2.add_vertex((578, 422)) eyelash2.add_vertex((551, 381)) eyelash2.add_vertex((530, 368)) eyelash2.add_vertex((506, 364)) eyelash2.add_vertex((459, 377)) eyelash2.add_vertex((424, 404)) eyelash2.add_vertex((387, 445)) eyelash2.filled = True eyelash2.fill_color = 'brown' eyelash2.color = 'brown' window.add(eyelash2) eyelash3 = GPolygon() eyelash3.add_vertex((380, 497)) eyelash3.add_vertex((404, 470)) eyelash3.add_vertex((438, 444)) eyelash3.add_vertex((464, 425)) eyelash3.add_vertex((500, 434)) eyelash3.add_vertex((536, 444)) eyelash3.add_vertex((554, 457)) eyelash3.add_vertex((570, 476)) eyelash3.add_vertex((580, 501)) eyelash3.add_vertex((560, 478)) eyelash3.add_vertex((539, 454)) eyelash3.add_vertex((500, 438)) eyelash3.add_vertex((467, 438)) eyelash3.add_vertex((440, 449)) eyelash3.add_vertex((414, 467)) eyelash3.filled = True eyelash3.fill_color = 'brown' eyelash3.color = 'brown' window.add(eyelash3) eyelash4 = GPolygon() eyelash4.add_vertex((243, 302)) eyelash4.add_vertex((260, 303)) eyelash4.add_vertex((278, 305)) eyelash4.add_vertex((295, 316)) eyelash4.add_vertex((308, 327)) eyelash4.add_vertex((281, 315)) eyelash4.add_vertex((264, 310)) eyelash4.add_vertex((246, 308)) eyelash4.filled = True eyelash4.fill_color = 'brown' eyelash4.color = 'brown' window.add(eyelash4) eyelash5 = GPolygon() eyelash5.add_vertex((393, 523)) eyelash5.add_vertex((410, 549)) eyelash5.add_vertex((438, 567)) eyelash5.add_vertex((473, 572)) eyelash5.add_vertex((504, 569)) eyelash5.add_vertex((538, 555)) eyelash5.add_vertex((567, 531)) eyelash5.add_vertex((549, 554)) eyelash5.add_vertex((507, 571)) eyelash5.add_vertex((476, 577)) eyelash5.add_vertex((442, 575)) eyelash5.add_vertex((416, 561)) eyelash5.filled = True eyelash5.fill_color = 'brown' eyelash5.color = 'brown' window.add(eyelash5) eye1 = GPolygon() eye1.add_vertex((386, 507)) eye1.add_vertex((411, 494)) eye1.add_vertex((438, 483)) eye1.add_vertex((468, 477)) eye1.add_vertex((500, 480)) eye1.add_vertex((530, 487)) eye1.add_vertex((550, 499)) eye1.add_vertex((562, 507)) eye1.add_vertex((548, 523)) eye1.add_vertex((529, 535)) eye1.add_vertex((499, 544)) eye1.add_vertex((469, 549)) eye1.add_vertex((439, 543)) eye1.add_vertex((415, 529)) eye1.filled = True eye1.fill_color = 'white' eye1.color = 'brown' window.add(eye1) eye2 = GPolygon() eye2.add_vertex((240, 317)) eye2.add_vertex((260, 320)) eye2.add_vertex((283, 327)) eye2.add_vertex((301, 336)) eye2.add_vertex((288, 346)) eye2.add_vertex((270, 350)) eye2.add_vertex((254, 352)) eye2.add_vertex((237, 350)) eye2.add_vertex((230, 346)) eye2.filled = True eye2.fill_color = 'white' eye2.color = 'brown' window.add(eye2) eye3 = GOval(31, 29, x=250, y=323) eye3.filled = True eye3.fill_color = 'black' eye3.color = 'white' window.add(eye3) eye5 = GOval(68, 70, x=442, y=478) eye5.filled = True eye5.fill_color = 'black' eye5.color = 'white' window.add(eye5) eye5 = GOval(18, 18, x=448, y=492) eye5.filled = True eye5.fill_color = 'white' eye5.color = 'black' window.add(eye5) eye4 = GOval(11, 11, x=253, y=323) eye4.filled = True eye4.fill_color = 'white' eye4.color = 'black' window.add(eye4) nose1 = GPolygon() nose1.add_vertex((250, 685)) nose1.add_vertex((349, 685)) nose1.add_vertex((354, 656)) nose1.add_vertex((339, 632)) nose1.add_vertex((314, 621)) nose1.add_vertex((285, 632)) nose1.add_vertex((268, 648)) nose1.filled = True nose1.fill_color = 'tan' nose1.color = 'tan' window.add(nose1) nose2 = GPolygon() nose2.add_vertex((279, 685)) nose2.add_vertex((349, 685)) nose2.add_vertex((339, 669)) nose2.add_vertex((320, 662)) nose2.add_vertex((304, 657)) nose2.add_vertex((292, 666)) nose2.filled = True nose2.fill_color = 'brown' nose2.color = 'brown' window.add(nose2) mouth = GPolygon() mouth.add_vertex((287, 774)) mouth.add_vertex((304, 755)) mouth.add_vertex((314, 752)) mouth.add_vertex((329, 764)) mouth.add_vertex((336, 769)) mouth.add_vertex((354, 751)) mouth.add_vertex((366, 747)) mouth.add_vertex((389, 755)) mouth.add_vertex((404, 779)) mouth.add_vertex((411, 788)) mouth.add_vertex((421, 793)) mouth.add_vertex((430, 795)) mouth.add_vertex((439, 799)) mouth.add_vertex((423, 822)) mouth.add_vertex((400, 833)) mouth.add_vertex((379, 845)) mouth.add_vertex((353, 848)) mouth.add_vertex((333, 843)) mouth.add_vertex((320, 828)) mouth.add_vertex((314, 815)) mouth.add_vertex((310, 800)) mouth.add_vertex((311, 785)) mouth.filled = True mouth.fill_color = 'chocolate' mouth.color = 'chocolate' window.add(mouth) mouth1 = GPolygon() mouth1.add_vertex((313, 792)) mouth1.add_vertex((434, 800)) mouth1.add_vertex((372, 798)) mouth1.filled = True mouth1.fill_color = 'brown' mouth1.color = 'brown' window.add(mouth1) hair1 = GPolygon() hair1.add_vertex((672, 431)) hair1.add_vertex((657, 387)) hair1.add_vertex((640, 342)) hair1.add_vertex((612, 292)) hair1.add_vertex((585, 245)) hair1.add_vertex((566, 217)) hair1.add_vertex((538, 185)) hair1.add_vertex((515, 162)) hair1.add_vertex((489, 141)) hair1.add_vertex((474, 129)) hair1.add_vertex((433, 93)) hair1.add_vertex((460, 80)) hair1.add_vertex((485, 79)) hair1.add_vertex((516, 79)) hair1.add_vertex((550, 86)) hair1.add_vertex((716, 244)) hair1.add_vertex((681, 322)) hair1.filled = True hair1.fill_color = 'lightblue' hair1.color = 'lightblue' window.add(hair1) hair2 = GPolygon() hair2.add_vertex((680, 322)) hair2.add_vertex((713, 248)) hair2.add_vertex((738, 207)) hair2.add_vertex((774, 168)) hair2.add_vertex((859, 216)) hair2.add_vertex((852, 287)) hair2.add_vertex((808, 322)) hair2.add_vertex((752, 527)) hair2.add_vertex((730, 438)) hair2.filled = True hair2.fill_color = 'navy' hair2.color = 'navy' window.add(hair2) hair3 = GPolygon() hair3.add_vertex((675, 305)) hair3.add_vertex((632, 323)) hair3.add_vertex((673, 424)) hair3.add_vertex((705, 487)) hair3.add_vertex((721, 653)) hair3.add_vertex((753, 521)) hair3.add_vertex((730, 439)) hair3.filled = True hair3.fill_color = 'darkgray' hair3.color = 'darkgray' window.add(hair3) hair4 = GPolygon() hair4.add_vertex((555, 89)) hair4.add_vertex((715, 248)) hair4.add_vertex((740, 206)) hair4.add_vertex((776, 168)) hair4.add_vertex((687, 67)) hair4.add_vertex((645, 63)) hair4.add_vertex((616, 65)) hair4.add_vertex((584, 75)) hair4.filled = True hair4.fill_color = 'lightskyblue' hair4.color = 'lightskyblue' window.add(hair4) hair5 = GPolygon() hair5.add_vertex((683, 61)) hair5.add_vertex((720, 47)) hair5.add_vertex((769, 39)) hair5.add_vertex((820, 45)) hair5.add_vertex((840, 55)) hair5.add_vertex((872, 74)) hair5.add_vertex((880, 85)) hair5.add_vertex((904, 112)) hair5.add_vertex((918, 151)) hair5.add_vertex((942, 194)) hair5.add_vertex((951, 217)) hair5.add_vertex((958, 263)) hair5.add_vertex((964, 301)) hair5.add_vertex((772, 435)) hair5.add_vertex((807, 325)) hair5.add_vertex((851, 289)) hair5.add_vertex((858, 215)) hair5.add_vertex((824, 196)) hair5.add_vertex((777, 168)) hair5.filled = True hair5.fill_color = 'coral' hair5.color = 'coral' window.add(hair5) hair6 = GPolygon() hair6.add_vertex((850, 292)) hair6.add_vertex((808, 322)) hair6.add_vertex((752, 527)) hair6.add_vertex((680, 840)) hair6.add_vertex((786, 855)) hair6.filled = True hair6.fill_color = 'yellow' hair6.color = 'yellow' window.add(hair6) hair7 = GPolygon() hair7.add_vertex((786, 855)) hair7.add_vertex((850, 292)) hair7.add_vertex((884, 287)) hair7.add_vertex((825, 860)) hair7.filled = True hair7.fill_color = 'gold' hair7.color = 'gold' window.add(hair7) hair8 = GPolygon() hair8.add_vertex((884, 287)) hair8.add_vertex((916, 282)) hair8.add_vertex((891, 860)) hair8.add_vertex((825, 860)) hair8.filled = True hair8.fill_color = 'yellow' hair8.color = 'yellow' window.add(hair8) hair9 = GPolygon() hair9.add_vertex((888, 810)) hair9.add_vertex((990, 786)) hair9.add_vertex((996, 474)) hair9.add_vertex((957, 261)) hair9.add_vertex((916, 282)) hair9.filled = True hair9.fill_color = 'gold' hair9.color = 'gold' window.add(hair9) hair10 = GPolygon() hair10.add_vertex((960, 263)) hair10.add_vertex((981, 302)) hair10.add_vertex((997, 364)) hair10.add_vertex((1016, 427)) hair10.add_vertex((1036, 474)) hair10.add_vertex((1056, 530)) hair10.add_vertex((1075, 595)) hair10.add_vertex((1064, 939)) hair10.add_vertex((995, 868)) hair10.add_vertex((990, 786)) hair10.add_vertex((996, 474)) hair10.add_vertex((957, 261)) hair10.filled = True hair10.fill_color = 'lightskyblue' hair10.color = 'lightskyblue' window.add(hair10) hair11 = GPolygon() hair11.add_vertex((988, 787)) hair11.add_vertex((896, 813)) hair11.add_vertex((895, 893)) hair11.add_vertex((981, 906)) hair11.filled = True hair11.fill_color = 'lightblue' hair11.color = 'lightblue' window.add(hair11) hair12 = GPolygon() hair12.add_vertex((787, 858)) hair12.add_vertex((896, 867)) hair12.add_vertex((880, 959)) hair12.add_vertex((784, 962)) hair12.filled = True hair12.fill_color = 'lightskyblue' hair12.color = 'lightskyblue' window.add(hair12) ear1 = GPolygon() ear1.add_vertex((672, 422)) ear1.add_vertex((669, 467)) ear1.add_vertex((666, 513)) ear1.add_vertex((660, 548)) ear1.add_vertex((648, 589)) ear1.add_vertex((635, 632)) ear1.add_vertex((619, 664)) ear1.add_vertex((595, 697)) ear1.add_vertex((572, 724)) ear1.add_vertex((543, 753)) ear1.add_vertex((557, 766)) ear1.add_vertex((582, 773)) ear1.add_vertex((600, 768)) ear1.add_vertex((684, 686)) ear1.add_vertex((708, 671)) ear1.add_vertex((720, 664)) ear1.add_vertex((708, 489)) ear1.filled = True ear1.fill_color = 'brown' ear1.color = 'brown' window.add(ear1) ear2 = GPolygon() ear2.add_vertex((672, 555)) ear2.add_vertex((662, 599)) ear2.add_vertex((659, 653)) ear2.add_vertex((689, 647)) ear2.add_vertex((704, 631)) ear2.add_vertex((688, 627)) ear2.add_vertex((680, 620)) ear2.add_vertex((677, 608)) ear2.add_vertex((684, 599)) ear2.add_vertex((694, 599)) ear2.add_vertex((705, 601)) ear2.add_vertex((708, 576)) ear2.add_vertex((701, 559)) ear2.add_vertex((680, 555)) ear2.filled = True ear2.fill_color = 'wheat' ear2.color = 'wheat' window.add(ear2) neck = GPolygon() neck.add_vertex((719, 664)) neck.add_vertex((672, 686)) neck.add_vertex((587, 773)) neck.add_vertex((578, 776)) neck.add_vertex((558, 794)) neck.add_vertex((470, 845)) neck.add_vertex((435, 861)) neck.add_vertex((401, 874)) neck.add_vertex((397, 971)) neck.add_vertex((559, 885)) neck.add_vertex((605, 866)) neck.add_vertex((637, 855)) neck.add_vertex((700, 838)) neck.add_vertex((723, 686)) neck.filled = True neck.fill_color = 'tan' neck.color = 'tan' window.add(neck) earring1 = GOval(116, 125, x=600, y=686) earring1.filled = True earring1.fill_color = 'brown' earring1.color = 'brown' window.add(earring1) earring2 = GOval(101, 107, x=608, y=692) earring2.filled = True earring2.fill_color = 'silver' earring2.color = 'silver' window.add(earring2) earring3 = GOval(65, 84, x=629, y=707) earring3.filled = True earring3.fill_color = 'brown' earring3.color = 'brown' window.add(earring3) earring4 = GOval(56, 68, x=633, y=715) earring4.filled = True earring4.fill_color = 'silver' earring4.color = 'silver' window.add(earring4) earring5 = GPolygon() earring5.add_vertex((657, 692)) earring5.add_vertex((664, 708)) earring5.add_vertex((666, 726)) earring5.add_vertex((655, 753)) earring5.add_vertex((645, 762)) earring5.add_vertex((632, 769)) earring5.add_vertex((617, 769)) earring5.add_vertex((605, 766)) earring5.add_vertex((607, 761)) earring5.add_vertex((616, 762)) earring5.add_vertex((627, 762)) earring5.add_vertex((640, 760)) earring5.add_vertex((647, 754)) earring5.add_vertex((653, 740)) earring5.add_vertex((657, 726)) earring5.add_vertex((657, 692)) earring5.add_vertex((658, 713)) earring5.add_vertex((652, 702)) earring5.add_vertex((648, 697)) earring5.add_vertex((644, 693)) earring5.filled = True earring5.fill_color = 'brown' earring5.color = 'brown' window.add(earring5) shirt1 = GPolygon() shirt1.add_vertex((337, 1000)) shirt1.add_vertex((870, 1000)) shirt1.add_vertex((872, 996)) shirt1.add_vertex((784, 964)) shirt1.add_vertex((786, 856)) shirt1.add_vertex((707, 850)) shirt1.add_vertex((702, 836)) shirt1.add_vertex((648, 848)) shirt1.add_vertex((594, 868)) shirt1.add_vertex((547, 889)) shirt1.add_vertex((508, 910)) shirt1.add_vertex((468, 931)) shirt1.add_vertex((438, 947)) shirt1.add_vertex((401, 970)) shirt1.add_vertex((374, 991)) shirt1.filled = True shirt1.fill_color = 'brown' shirt1.color = 'brown' window.add(shirt1) shirt2 = GPolygon() shirt2.add_vertex((475, 970)) shirt2.add_vertex((544, 946)) shirt2.add_vertex((621, 932)) shirt2.add_vertex((694, 930)) shirt2.add_vertex((696, 855)) shirt2.add_vertex((498, 924)) shirt2.add_vertex((440, 952)) shirt2.add_vertex((402, 977)) shirt2.add_vertex((370, 1000)) shirt2.filled = True shirt2.fill_color = 'white' shirt2.color = 'white' window.add(shirt2) if __name__ == '__main__': main()
18,109
0
23
d39e71ce888078189411c4e7f6286a6a8096b59c
3,577
py
Python
webviz_config/webviz_factory_registry.py
antoneskov/webviz-config
ce8aa7b40bad5e724fd9b003283cc33a1c474a6c
[ "MIT" ]
null
null
null
webviz_config/webviz_factory_registry.py
antoneskov/webviz-config
ce8aa7b40bad5e724fd9b003283cc33a1c474a6c
[ "MIT" ]
null
null
null
webviz_config/webviz_factory_registry.py
antoneskov/webviz-config
ce8aa7b40bad5e724fd9b003283cc33a1c474a6c
[ "MIT" ]
null
null
null
from typing import Any, Dict, Optional, Type, TypeVar import warnings from .webviz_factory import WebvizFactory from .webviz_instance_info import WebvizInstanceInfo, WEBVIZ_INSTANCE_INFO T = TypeVar("T", bound=WebvizFactory) class WebvizFactoryRegistry: """Global registry for factories that allows the actual factory instances to be shared between plugins. Also facilitates storage of optional factory settings that are read from the YAML config file for later consumption when an actual factory gets created and added to the registry. The registry is exposed globally through WEBVIZ_FACTORY_REGISTRY below. This is also the reason for the two-stage initialization approach. Note that the registry instance is useless until the initialize() method has been called. Note that this functionality is provisional/experimental, and will not necessarily see a deprecation phase and "may deviate from the usual version semantics." """ def initialize( self, factory_settings_dict: Optional[Dict[str, Any]], ) -> None: """Does the actual initialization of the object instance. This function will be called as part of the webviz_app.py / jinja2 template. """ if self._is_initialized: raise RuntimeError("Registry already initialized") if factory_settings_dict: if not isinstance(factory_settings_dict, dict): raise TypeError("factory_settings_dict must be of type dict") self._factory_settings_dict = factory_settings_dict self._is_initialized = True @property @property WEBVIZ_FACTORY_REGISTRY = WebvizFactoryRegistry()
38.462366
94
0.70534
from typing import Any, Dict, Optional, Type, TypeVar import warnings from .webviz_factory import WebvizFactory from .webviz_instance_info import WebvizInstanceInfo, WEBVIZ_INSTANCE_INFO T = TypeVar("T", bound=WebvizFactory) class WebvizFactoryRegistry: """Global registry for factories that allows the actual factory instances to be shared between plugins. Also facilitates storage of optional factory settings that are read from the YAML config file for later consumption when an actual factory gets created and added to the registry. The registry is exposed globally through WEBVIZ_FACTORY_REGISTRY below. This is also the reason for the two-stage initialization approach. Note that the registry instance is useless until the initialize() method has been called. Note that this functionality is provisional/experimental, and will not necessarily see a deprecation phase and "may deviate from the usual version semantics." """ def __init__(self) -> None: self._is_initialized: bool = False self._factory_settings_dict: Dict[str, Any] = {} self._factories: Dict[Type, WebvizFactory] = {} def initialize( self, factory_settings_dict: Optional[Dict[str, Any]], ) -> None: """Does the actual initialization of the object instance. This function will be called as part of the webviz_app.py / jinja2 template. """ if self._is_initialized: raise RuntimeError("Registry already initialized") if factory_settings_dict: if not isinstance(factory_settings_dict, dict): raise TypeError("factory_settings_dict must be of type dict") self._factory_settings_dict = factory_settings_dict self._is_initialized = True def set_factory(self, factory_class: Type[T], factory_obj: T) -> None: if not self._is_initialized: raise RuntimeError("Illegal access, factory registry is not initialized") if not isinstance(factory_obj, factory_class): raise TypeError("The type of the factory does not match factory_class") self._factories[factory_class] = factory_obj def get_factory(self, factory_class: Type[T]) -> Optional[T]: if not self._is_initialized: raise RuntimeError("Illegal access, factory registry is not initialized") if not factory_class in self._factories: return None factory_obj = self._factories[factory_class] if not isinstance(factory_obj, factory_class): raise TypeError("The stored factory object has wrong type") return factory_obj def cleanup_resources_after_plugin_init(self) -> None: if not self._is_initialized: raise RuntimeError("Illegal access, factory registry is not initialized") for factory in self._factories.values(): factory.cleanup_resources_after_plugin_init() @property def all_factory_settings(self) -> Dict[str, Any]: if not self._is_initialized: raise RuntimeError("Illegal access, factory registry is not initialized") return self._factory_settings_dict @property def app_instance_info(self) -> WebvizInstanceInfo: warnings.warn( "Accessing WebvizInstanceInfo through WebvizFactoryRegistry has been deprecated, " "please use global WEBVIZ_INSTANCE_INFO instead", DeprecationWarning, ) return WEBVIZ_INSTANCE_INFO WEBVIZ_FACTORY_REGISTRY = WebvizFactoryRegistry()
1,721
0
160
e6a2d90f8fe61d65cbb547f64ae25d50e12059d5
6,729
py
Python
transformer_train.py
phamduyhk/signate_student_cup_2020
19e158b08a86f2df8e4ee45445169ae396c91409
[ "MIT" ]
null
null
null
transformer_train.py
phamduyhk/signate_student_cup_2020
19e158b08a86f2df8e4ee45445169ae396c91409
[ "MIT" ]
null
null
null
transformer_train.py
phamduyhk/signate_student_cup_2020
19e158b08a86f2df8e4ee45445169ae396c91409
[ "MIT" ]
null
null
null
# coding: utf-8 """ Author: Pham Duy Created date: 2020/08/05 """ # coding: utf-8 import numpy as np import random import torch import torch.nn as nn import torch.optim as optim from sklearn.metrics import roc_auc_score, accuracy_score, f1_score import torchtext import pandas as pd import datetime import os import sys from utils.EarlyStopping import EarlyStopping from utils.transformer import TransformerClassification from utils.dataloader import Preprocessing preprocessing = Preprocessing() es = EarlyStopping(patience=10) sigmoid = nn.Sigmoid() if __name__ == '__main__': path = "./data/" train_file = "train.csv" test_file = "test.csv" vector_list_file = "wiki-news-300d-1M.vec" train(data_path=path, train_file=train_file, test_file=test_file, vector_list=vector_list_file)
31.890995
120
0.593104
# coding: utf-8 """ Author: Pham Duy Created date: 2020/08/05 """ # coding: utf-8 import numpy as np import random import torch import torch.nn as nn import torch.optim as optim from sklearn.metrics import roc_auc_score, accuracy_score, f1_score import torchtext import pandas as pd import datetime import os import sys from utils.EarlyStopping import EarlyStopping from utils.transformer import TransformerClassification from utils.dataloader import Preprocessing preprocessing = Preprocessing() es = EarlyStopping(patience=10) sigmoid = nn.Sigmoid() def train(data_path, train_file, test_file, vector_list, max_sequence_length=512, num_epochs=1000, learning_rate=3e-5, device=None, train_mode=True, load_trained=False, early_stop=False): if device is None: device = torch.device("cuda:1" if torch.cuda.is_available() else "cpu") torch.manual_seed(1234) np.random.seed(1234) random.seed(1234) train_dl, val_dl, test_dl, TEXT = preprocessing.get_data(path=data_path, train_file=train_file, test_file=test_file, vectors=vector_list, max_length=max_sequence_length, batch_size=1024) dataloaders_dict = {"train": train_dl, "val": val_dl} # define output dataframe sample = pd.read_csv("./data/submit_sample.csv") label_cols = ['jobflag'] num_labels = 4 if load_trained is True: net = torch.load("net_trained_transformer.weights", map_location=device) else: net = TransformerClassification( text_embedding_vectors=TEXT.vocab.vectors, d_model=300, max_seq_len=max_sequence_length, output_dim=num_labels, device=device) net.train() net.net3_1.apply(weights_init) net.net3_2.apply(weights_init) print('done setup network') print("running mode: {}".format("training" if train_mode else "predict")) # Define loss function # criterion = nn.BCEWithLogitsLoss() # criterion = nn.BCELoss() """or""" criterion = nn.MultiLabelSoftMarginLoss() # criterion = nn.MSELoss() optimizer = optim.Adam(net.parameters(), lr=learning_rate) if not os.path.exists("./transformers"): os.mkdir("./transformers") net_trained_save_path = os.path.join("./transformers", "net_trained_transformer.weights") if train_mode: net_trained = train_model(net, dataloaders_dict, criterion, optimizer, num_epochs=num_epochs, label_cols=label_cols, device=device, early_stop=early_stop) # net_trainedを保存 torch.save(net_trained, net_trained_save_path) else: net_trained = net net_trained.eval() net_trained.to(device) pred_probs = np.array([]).reshape(0, num_labels) raw_pred = np.array([]).reshape(0, num_labels) for batch in (test_dl): inputs = batch.Text[0].to(device) with torch.set_grad_enabled(False): input_pad = 1 input_mask = (inputs != input_pad) outputs, _, _ = net_trained(inputs, input_mask) raw_output = outputs.cpu() raw_pred = np.vstack([raw_pred, raw_output]) preds = torch.argmax(outputs, 1) preds = preds.cpu() for index, label in enumerate(label_cols): sample[label] = preds # save predictions if not os.path.exists("./submission"): os.mkdir("./submission") sample.to_csv("./submission/submission_Transformer_{}_{}ep.csv".format( datetime.datetime.now().date(), num_epochs), index=False) def roc_auc_score_FIXED(y_true, y_pred): try: score = roc_auc_score(y_true, y_pred) except ValueError: score = accuracy_score(y_true, np.rint(y_pred)) return score def weights_init(m): classname = m.__class__.__name__ if classname.find('Linear') != -1: nn.init.kaiming_normal_(m.weight) if m.bias is not None: nn.init.constant_(m.bias, 0.0) def train_model(net, dataloaders_dict, criterion, optimizer, num_epochs, label_cols, device="cpu", early_stop=False): print("using device: ", device) # if torch.cuda.device_count() > 1: # print("Let's use", torch.cuda.device_count(), "GPUs!") # net = nn.DataParallel(net) net.to(device) torch.backends.cudnn.benchmark = True for epoch in range(num_epochs): for phase in ['train', 'val']: if phase == 'train': net.train() else: net.eval() epoch_loss = 0.0 epoch_metrics = 0 for batch in (dataloaders_dict[phase]): inputs = batch.Text[0].to(device) y_true = torch.cat([getattr(batch, feat).unsqueeze(1) for feat in label_cols], dim=1).float() y_true = y_true.to(device) optimizer.zero_grad() with torch.set_grad_enabled(phase == 'train'): input_pad = 1 input_mask = (inputs != input_pad) outputs, _, _ = net(inputs, input_mask) loss = criterion(outputs, y_true) preds = torch.argmax(outputs, 1) # training mode if phase == 'train': loss.backward() optimizer.step() # validation mode epoch_loss += loss.item() * inputs.size(0) y_true = y_true.data.cpu() preds = preds.cpu() # print("y_true {}, y_pred {}".format(y_true, preds)) epoch_metrics += f1_score(y_true, preds, average='macro') epoch_loss = epoch_loss / len(dataloaders_dict[phase].dataset) epoch_eval = epoch_metrics / len(dataloaders_dict[phase]) print('Epoch {}/{} | {:^5} | Loss: {:.4f} F1 Score: {:.4f}'.format(epoch + 1, num_epochs, phase, epoch_loss, epoch_eval)) if early_stop: if es.step(torch.tensor(epoch_eval)): print("Early stoped at epoch: {}".format(num_epochs)) break # early stop criterion is met, we can stop now return net if __name__ == '__main__': path = "./data/" train_file = "train.csv" test_file = "test.csv" vector_list_file = "wiki-news-300d-1M.vec" train(data_path=path, train_file=train_file, test_file=test_file, vector_list=vector_list_file)
5,830
0
92
eea56c022f4a7d158e92d3208591a21db5b1df19
326
py
Python
pdq/python/pdqhashing/types/exceptions.py
b-bold/ThreatExchange
6f8d0dc803faccf576c9398569bb52d54a4f9a87
[ "BSD-3-Clause" ]
997
2015-03-13T18:04:03.000Z
2022-03-30T12:09:10.000Z
pdq/python/pdqhashing/types/exceptions.py
b-bold/ThreatExchange
6f8d0dc803faccf576c9398569bb52d54a4f9a87
[ "BSD-3-Clause" ]
444
2015-03-26T17:28:49.000Z
2022-03-28T19:34:05.000Z
pdq/python/pdqhashing/types/exceptions.py
b-bold/ThreatExchange
6f8d0dc803faccf576c9398569bb52d54a4f9a87
[ "BSD-3-Clause" ]
294
2015-03-13T22:19:43.000Z
2022-03-30T08:42:45.000Z
#!/usr/bin/env python # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
40.75
70
0.763804
#!/usr/bin/env python # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved class PDQHashFormatException(Exception): def __init__(self, error_message, unacceptableInput=None) -> None: super(PDQHashFormatException, self).__init__(error_message) self._unacceptableInput = unacceptableInput
165
19
49
07c925215830c65a8bf11878e7f44902e2cda624
48,224
py
Python
corehq/apps/reports/tests/test_esaccessors.py
dimagilg/commcare-hq
ea1786238eae556bb7f1cbd8d2460171af1b619c
[ "BSD-3-Clause" ]
null
null
null
corehq/apps/reports/tests/test_esaccessors.py
dimagilg/commcare-hq
ea1786238eae556bb7f1cbd8d2460171af1b619c
[ "BSD-3-Clause" ]
94
2020-12-11T06:57:31.000Z
2022-03-15T10:24:06.000Z
corehq/apps/reports/tests/test_esaccessors.py
dimagilg/commcare-hq
ea1786238eae556bb7f1cbd8d2460171af1b619c
[ "BSD-3-Clause" ]
null
null
null
import uuid from datetime import datetime, timedelta from django.test import SimpleTestCase, TestCase from django.test.utils import override_settings import pytz from corehq.util.es.elasticsearch import ConnectionError from mock import MagicMock, patch from casexml.apps.case.const import CASE_ACTION_CREATE from casexml.apps.case.models import CommCareCase, CommCareCaseAction from corehq.apps.commtrack.tests.util import bootstrap_domain from dimagi.utils.dates import DateSpan from pillowtop.es_utils import initialize_index_and_mapping from corehq.apps.custom_data_fields.models import ( CustomDataFieldsDefinition, CustomDataFieldsProfile, Field, PROFILE_SLUG, ) from corehq.apps.domain.calculations import cases_in_last, inactive_cases_in_last from corehq.apps.es import CaseES, UserES from corehq.apps.es.aggregations import MISSING_KEY from corehq.apps.es.tests.utils import es_test from corehq.apps.groups.models import Group from corehq.apps.hqcase.utils import SYSTEM_FORM_XMLNS, get_case_by_identifier from corehq.apps.locations.tests.util import setup_locations_and_types, restrict_user_by_location from corehq.apps.reports.analytics.esaccessors import ( get_active_case_counts_by_owner, get_all_user_ids_submitted, get_case_counts_closed_by_user, get_case_counts_opened_by_user, get_case_types_for_domain_es, get_case_and_action_counts_for_domains, get_completed_counts_by_user, get_form_counts_by_user_xmlns, get_form_counts_for_domains, get_form_duration_stats_by_user, get_form_duration_stats_for_users, get_form_ids_having_multimedia, get_forms, get_last_submission_time_for_users, get_group_stubs, get_form_name_from_last_submission_for_xmlns, get_paged_forms_by_type, get_submission_counts_by_date, get_submission_counts_by_user, get_total_case_counts_by_owner, get_user_stubs, get_groups_by_querystring, get_username_in_last_form_user_id_submitted, guess_form_name_from_submissions_using_xmlns, scroll_case_names, ) from corehq.apps.reports.standard.cases.utils import query_location_restricted_cases from corehq.apps.users.models import CommCareUser, DomainPermissionsMirror from corehq.apps.users.views.mobile.custom_data_fields import UserFieldsView from corehq.blobs.mixin import BlobMetaRef from corehq.elastic import get_es_new, send_to_elasticsearch from corehq.form_processor.interfaces.dbaccessors import CaseAccessors from corehq.form_processor.models import CaseTransaction, CommCareCaseSQL from corehq.form_processor.tests.utils import run_with_all_backends from corehq.form_processor.utils import TestFormMetadata from corehq.pillows.case import transform_case_for_elasticsearch from corehq.pillows.mappings.case_mapping import CASE_INDEX, CASE_INDEX_INFO from corehq.pillows.mappings.group_mapping import GROUP_INDEX_INFO from corehq.pillows.mappings.user_mapping import USER_INDEX, USER_INDEX_INFO from corehq.pillows.mappings.xform_mapping import XFORM_INDEX_INFO from corehq.pillows.user import transform_user_for_elasticsearch from corehq.pillows.utils import MOBILE_USER_TYPE, WEB_USER_TYPE from corehq.pillows.xform import transform_xform_for_elasticsearch from corehq.util.elastic import ensure_index_deleted, reset_es_index from corehq.util.test_utils import make_es_ready_form, trap_extra_setup @es_test @es_test @es_test @override_settings(TESTS_SHOULD_USE_SQL_BACKEND=True)
34.944928
112
0.623963
import uuid from datetime import datetime, timedelta from django.test import SimpleTestCase, TestCase from django.test.utils import override_settings import pytz from corehq.util.es.elasticsearch import ConnectionError from mock import MagicMock, patch from casexml.apps.case.const import CASE_ACTION_CREATE from casexml.apps.case.models import CommCareCase, CommCareCaseAction from corehq.apps.commtrack.tests.util import bootstrap_domain from dimagi.utils.dates import DateSpan from pillowtop.es_utils import initialize_index_and_mapping from corehq.apps.custom_data_fields.models import ( CustomDataFieldsDefinition, CustomDataFieldsProfile, Field, PROFILE_SLUG, ) from corehq.apps.domain.calculations import cases_in_last, inactive_cases_in_last from corehq.apps.es import CaseES, UserES from corehq.apps.es.aggregations import MISSING_KEY from corehq.apps.es.tests.utils import es_test from corehq.apps.groups.models import Group from corehq.apps.hqcase.utils import SYSTEM_FORM_XMLNS, get_case_by_identifier from corehq.apps.locations.tests.util import setup_locations_and_types, restrict_user_by_location from corehq.apps.reports.analytics.esaccessors import ( get_active_case_counts_by_owner, get_all_user_ids_submitted, get_case_counts_closed_by_user, get_case_counts_opened_by_user, get_case_types_for_domain_es, get_case_and_action_counts_for_domains, get_completed_counts_by_user, get_form_counts_by_user_xmlns, get_form_counts_for_domains, get_form_duration_stats_by_user, get_form_duration_stats_for_users, get_form_ids_having_multimedia, get_forms, get_last_submission_time_for_users, get_group_stubs, get_form_name_from_last_submission_for_xmlns, get_paged_forms_by_type, get_submission_counts_by_date, get_submission_counts_by_user, get_total_case_counts_by_owner, get_user_stubs, get_groups_by_querystring, get_username_in_last_form_user_id_submitted, guess_form_name_from_submissions_using_xmlns, scroll_case_names, ) from corehq.apps.reports.standard.cases.utils import query_location_restricted_cases from corehq.apps.users.models import CommCareUser, DomainPermissionsMirror from corehq.apps.users.views.mobile.custom_data_fields import UserFieldsView from corehq.blobs.mixin import BlobMetaRef from corehq.elastic import get_es_new, send_to_elasticsearch from corehq.form_processor.interfaces.dbaccessors import CaseAccessors from corehq.form_processor.models import CaseTransaction, CommCareCaseSQL from corehq.form_processor.tests.utils import run_with_all_backends from corehq.form_processor.utils import TestFormMetadata from corehq.pillows.case import transform_case_for_elasticsearch from corehq.pillows.mappings.case_mapping import CASE_INDEX, CASE_INDEX_INFO from corehq.pillows.mappings.group_mapping import GROUP_INDEX_INFO from corehq.pillows.mappings.user_mapping import USER_INDEX, USER_INDEX_INFO from corehq.pillows.mappings.xform_mapping import XFORM_INDEX_INFO from corehq.pillows.user import transform_user_for_elasticsearch from corehq.pillows.utils import MOBILE_USER_TYPE, WEB_USER_TYPE from corehq.pillows.xform import transform_xform_for_elasticsearch from corehq.util.elastic import ensure_index_deleted, reset_es_index from corehq.util.test_utils import make_es_ready_form, trap_extra_setup @es_test class BaseESAccessorsTest(TestCase): es_index_info = None def setUp(self): super(BaseESAccessorsTest, self).setUp() with trap_extra_setup(ConnectionError): self.es = get_es_new() self._delete_es_index() self.domain = uuid.uuid4().hex if isinstance(self.es_index_info, (list, tuple)): for index_info in self.es_index_info: initialize_index_and_mapping(self.es, index_info) else: initialize_index_and_mapping(self.es, self.es_index_info) def tearDown(self): self._delete_es_index() super(BaseESAccessorsTest, self).tearDown() def _delete_es_index(self): if isinstance(self.es_index_info, (list, tuple)): for index_info in self.es_index_info: ensure_index_deleted(index_info.index) else: ensure_index_deleted(self.es_index_info.index) class TestFormESAccessors(BaseESAccessorsTest): es_index_info = [XFORM_INDEX_INFO, GROUP_INDEX_INFO] def _send_form_to_es( self, domain=None, completion_time=None, received_on=None, attachment_dict=None, **metadata_kwargs): attachment_dict = attachment_dict or {} metadata = TestFormMetadata( domain=domain or self.domain, time_end=completion_time or datetime.utcnow(), received_on=received_on or datetime.utcnow(), ) for attr, value in metadata_kwargs.items(): setattr(metadata, attr, value) form_pair = make_es_ready_form(metadata) if attachment_dict: form_pair.wrapped_form.external_blobs = {name: BlobMetaRef(**meta) for name, meta in attachment_dict.items()} form_pair.json_form['external_blobs'] = attachment_dict es_form = transform_xform_for_elasticsearch(form_pair.json_form) send_to_elasticsearch('forms', es_form) self.es.indices.refresh(XFORM_INDEX_INFO.index) return form_pair def _send_group_to_es(self, _id=None, users=None): group = Group( domain=self.domain, name='narcos', users=users or [], case_sharing=False, reporting=False, _id=_id or uuid.uuid4().hex, ) send_to_elasticsearch('groups', group.to_json()) self.es.indices.refresh(GROUP_INDEX_INFO.index) return group @run_with_all_backends def test_get_forms(self): start = datetime(2013, 7, 1) end = datetime(2013, 7, 30) xmlns = 'http://a.b.org' app_id = '1234' user_id = 'abc' self._send_form_to_es( app_id=app_id, xmlns=xmlns, received_on=datetime(2013, 7, 2), user_id=user_id, ) paged_result = get_forms( self.domain, start, end, user_ids=[user_id], app_ids=app_id, xmlnss=xmlns, ) self.assertEqual(paged_result.total, 1) self.assertEqual(paged_result.hits[0]['xmlns'], xmlns) self.assertEqual(paged_result.hits[0]['form']['meta']['userID'], user_id) self.assertEqual(paged_result.hits[0]['received_on'], '2013-07-02T00:00:00.000000Z') @run_with_all_backends def test_get_form_ids_having_multimedia(self): start = datetime(2013, 7, 1) end = datetime(2013, 7, 30) xmlns = 'http://a.b.org' app_id = '1234' user_id = 'abc' self._send_form_to_es( app_id=app_id, xmlns=xmlns, received_on=datetime(2013, 7, 2), user_id=user_id, attachment_dict={ 'my_image': {'content_type': 'image/jpg'} } ) # Decoy form self._send_form_to_es( app_id=app_id, xmlns=xmlns, received_on=datetime(2013, 7, 2), user_id=user_id, ) form_ids = get_form_ids_having_multimedia( self.domain, app_id, xmlns, DateSpan(start, end), [], ) self.assertEqual(len(form_ids), 1) @run_with_all_backends def test_get_form_ids_having_multimedia_with_user_types(self): start = datetime(2013, 7, 1) end = datetime(2013, 7, 30) xmlns = 'http://a.b.org' app_id = '1234' user_id = 'abc' with patch('corehq.pillows.xform.get_user_type', lambda _: MOBILE_USER_TYPE): self._send_form_to_es( app_id=app_id, xmlns=xmlns, received_on=datetime(2013, 7, 2), user_id=user_id, attachment_dict={ 'my_image': {'content_type': 'image/jpg'} } ) with patch('corehq.pillows.xform.get_user_type', lambda _: WEB_USER_TYPE): self._send_form_to_es( app_id=app_id, xmlns=xmlns, received_on=datetime(2013, 7, 2), user_id=user_id, attachment_dict={ 'my_image': {'content_type': 'image/jpg'} } ) form_ids = get_form_ids_having_multimedia( self.domain, app_id, xmlns, DateSpan(start, end), [MOBILE_USER_TYPE] ) self.assertEqual(len(form_ids), 1) form_ids = get_form_ids_having_multimedia( self.domain, app_id, xmlns, DateSpan(start, end), [MOBILE_USER_TYPE, WEB_USER_TYPE] ) self.assertEqual(len(form_ids), 2) form_ids = get_form_ids_having_multimedia( self.domain, app_id, xmlns, DateSpan(start, end), [] ) self.assertEqual(len(form_ids), 2) @run_with_all_backends def test_get_forms_multiple_apps_xmlnss(self): start = datetime(2013, 7, 1) end = datetime(2013, 7, 30) xmlns1, xmlns2 = 'http://a.b.org', 'http://b.c.org' app_id1, app_id2 = '1234', '4567' user_id = 'abc' self._send_form_to_es( app_id=app_id1, xmlns=xmlns1, received_on=datetime(2013, 7, 2), user_id=user_id, ) self._send_form_to_es( app_id=app_id2, xmlns=xmlns2, received_on=datetime(2013, 7, 2), user_id=user_id, ) self._send_form_to_es( app_id=app_id1, xmlns=xmlns1, received_on=datetime(2013, 7, 2), user_id=None, ) paged_result = get_forms( self.domain, start, end, user_ids=[user_id], app_ids=[app_id1, app_id2], xmlnss=[xmlns1, xmlns2], ) self.assertEqual(paged_result.total, 2) paged_result = get_forms( self.domain, start, end, user_ids=[user_id], app_ids=[app_id1, app_id2], xmlnss=[xmlns1], ) self.assertEqual(paged_result.total, 1) paged_result = get_forms( self.domain, start, end, user_ids=[user_id], app_ids=[app_id1], xmlnss=[xmlns2], ) self.assertEqual(paged_result.total, 0) paged_result = get_forms( self.domain, start, end, user_ids=[None], app_ids=[app_id1], xmlnss=[xmlns1], ) self.assertEqual(paged_result.total, 1) @run_with_all_backends def test_basic_completed_by_user(self): start = datetime(2013, 7, 1) end = datetime(2013, 7, 30) self._send_form_to_es(completion_time=datetime(2013, 7, 2)) results = get_completed_counts_by_user(self.domain, DateSpan(start, end)) self.assertEqual(results['cruella_deville'], 1) def test_get_last_submission_time_for_users(self): start = datetime(2013, 7, 1) end = datetime(2013, 7, 30) self._send_form_to_es(completion_time=datetime(2013, 7, 2)) results = get_last_submission_time_for_users(self.domain, ['cruella_deville'], DateSpan(start, end)) self.assertEqual(results['cruella_deville'], datetime(2013, 7, 2).date()) def test_get_form_counts_for_domains(self): self._send_form_to_es() self._send_form_to_es() self._send_form_to_es(domain='other') self.assertEqual( get_form_counts_for_domains([self.domain, 'other']), {self.domain: 2, 'other': 1} ) @run_with_all_backends def test_completed_out_of_range_by_user(self): start = datetime(2013, 7, 1) end = datetime(2013, 7, 30) self._send_form_to_es(completion_time=datetime(2013, 8, 2)) self._send_form_to_es(completion_time=datetime(2013, 7, 2)) results = get_completed_counts_by_user(self.domain, DateSpan(start, end)) self.assertEqual(results['cruella_deville'], 1) def test_completed_different_domain_by_user(self): start = datetime(2013, 7, 1) end = datetime(2013, 7, 30) self._send_form_to_es(completion_time=datetime(2013, 7, 3), domain='not-in-my-backyard') self._send_form_to_es(completion_time=datetime(2013, 7, 2)) results = get_completed_counts_by_user(self.domain, DateSpan(start, end)) self.assertEqual(results['cruella_deville'], 1) @run_with_all_backends def test_basic_submission_by_user(self): start = datetime(2013, 7, 1) end = datetime(2013, 7, 30) received_on = datetime(2013, 7, 15) self._send_form_to_es(received_on=received_on) results = get_submission_counts_by_user(self.domain, DateSpan(start, end)) self.assertEqual(results['cruella_deville'], 1) @run_with_all_backends def test_get_form_name_from_last_submission_for_xmlns(self): xmlns = 'http://a.b.org' kwargs = { 'user_id': 'u1', 'app_id': '1234', 'domain': self.domain, 'xmlns': xmlns } first = datetime(2013, 7, 15, 0, 0, 0) second = datetime(2013, 7, 16, 0, 0, 0) third = datetime(2013, 7, 17, 0, 0, 0) self._send_form_to_es(received_on=second, form_name='2', **kwargs) self._send_form_to_es(received_on=third, form_name='3', **kwargs) self._send_form_to_es(received_on=first, form_name='1', **kwargs) name = get_form_name_from_last_submission_for_xmlns(self.domain, xmlns) self.assertEqual(name, '3') name = get_form_name_from_last_submission_for_xmlns(self.domain, 'missing') self.assertIsNone(name) @run_with_all_backends def test_guess_form_name_from_xmlns_not_found(self): self.assertEqual(None, guess_form_name_from_submissions_using_xmlns('missing', 'missing')) @run_with_all_backends def test_guess_form_name_from_xmlns(self): form_name = 'my cool form' xmlns = 'http://a.b.org' self._send_form_to_es( xmlns=xmlns, form_name=form_name, ) self.assertEqual(form_name, guess_form_name_from_submissions_using_xmlns(self.domain, xmlns)) @run_with_all_backends def test_submission_out_of_range_by_user(self): start = datetime(2013, 7, 1) end = datetime(2013, 7, 30) self._send_form_to_es(received_on=datetime(2013, 8, 15)) self._send_form_to_es(received_on=datetime(2013, 7, 15)) results = get_submission_counts_by_user(self.domain, DateSpan(start, end)) self.assertEqual(results['cruella_deville'], 1) @run_with_all_backends def test_submission_different_domain_by_user(self): start = datetime(2013, 7, 1) end = datetime(2013, 7, 30) received_on = datetime(2013, 7, 15) self._send_form_to_es(received_on=received_on) self._send_form_to_es(received_on=received_on, domain='not-in-my-backyard') results = get_submission_counts_by_user(self.domain, DateSpan(start, end)) self.assertEqual(results['cruella_deville'], 1) @run_with_all_backends def test_basic_submission_by_date(self): start = datetime(2013, 7, 1) end = datetime(2013, 7, 30) received_on = datetime(2013, 7, 15) self._send_form_to_es(received_on=received_on) self._send_form_to_es(received_on=received_on, xmlns=SYSTEM_FORM_XMLNS) results = get_submission_counts_by_date( self.domain, ['cruella_deville'], DateSpan(start, end), pytz.utc ) self.assertEqual(results['2013-07-15'], 1) @run_with_all_backends def test_get_paged_forms_by_type(self): self._send_form_to_es() self._send_form_to_es() paged_result = get_paged_forms_by_type(self.domain, ['xforminstance'], size=1) self.assertEqual(len(paged_result.hits), 1) self.assertEqual(paged_result.total, 2) @run_with_all_backends def test_timezone_differences(self): """ Our received_on dates are always in UTC, so if we submit a form right at midnight UTC, then the report should show that form being submitted the day before if viewing from an earlier timezone like New York """ start = datetime(2013, 7, 1) end = datetime(2013, 7, 30) received_on = datetime(2013, 7, 15, 0, 0, 0) timezone = pytz.timezone('America/New_York') self._send_form_to_es(received_on=received_on) results = get_submission_counts_by_date( self.domain, ['cruella_deville'], DateSpan(start, end), timezone ) self.assertEqual(results['2013-07-14'], 1) @run_with_all_backends def test_timezones_ahead_utc_in_get_submission_counts_by_date(self): """ When bucketing form submissions, the returned bucket key needs to be converted to a datetime with the timezone specified. Specifically an issue for timezones ahead of UTC (positive offsets) """ start = datetime(2013, 7, 1) end = datetime(2013, 7, 30) received_on = datetime(2013, 7, 15) self._send_form_to_es(received_on=received_on) self._send_form_to_es(received_on=received_on, xmlns=SYSTEM_FORM_XMLNS) results = get_submission_counts_by_date( self.domain, ['cruella_deville'], DateSpan(start, end), pytz.timezone('Africa/Johannesburg') ) self.assertEqual(results['2013-07-15'], 1) @run_with_all_backends def test_get_form_counts_by_user_xmlns(self): user1, user2 = 'u1', 'u2' app1, app2 = '123', '567' xmlns1, xmlns2 = 'abc', 'efg' start = datetime(2013, 7, 1) end = datetime(2013, 7, 30) received_on = datetime(2013, 7, 15, 0, 0, 0) received_on_out = datetime(2013, 6, 15, 0, 0, 0) self._send_form_to_es(received_on=received_on_out, completion_time=received_on, user_id=user1, app_id=app1, xmlns=xmlns1) self._send_form_to_es(received_on=received_on, user_id=user1, app_id=app1, xmlns=xmlns1) self._send_form_to_es(received_on=received_on, user_id=user1, app_id=app1, xmlns=xmlns1) self._send_form_to_es(received_on=received_on, user_id=user1, app_id=app2, xmlns=xmlns2) self._send_form_to_es(received_on=received_on, user_id=user2, app_id=app2, xmlns=xmlns2) self._send_form_to_es(received_on=received_on, user_id=None, app_id=app2, xmlns=xmlns2) counts = get_form_counts_by_user_xmlns(self.domain, start, end) self.assertEqual(counts, { (user1, app1, xmlns1): 2, (user1, app2, xmlns2): 1, (user2, app2, xmlns2): 1, }) counts_user1 = get_form_counts_by_user_xmlns(self.domain, start, end, user_ids=[user1]) self.assertEqual(counts_user1, { (user1, app1, xmlns1): 2, (user1, app2, xmlns2): 1, }) counts_xmlns2 = get_form_counts_by_user_xmlns(self.domain, start, end, xmlnss=[xmlns2]) self.assertEqual(counts_xmlns2, { (user1, app2, xmlns2): 1, (user2, app2, xmlns2): 1, }) by_completion = get_form_counts_by_user_xmlns(self.domain, start, end, by_submission_time=False) self.assertEqual(by_completion, { (user1, app1, xmlns1): 1 }) counts_missing_user = get_form_counts_by_user_xmlns(self.domain, start, end, user_ids=[None]) self.assertEqual(counts_missing_user, { (None, app2, xmlns2): 1, }) @run_with_all_backends def test_xmlns_case_sensitivity_for_get_form_counts_by_user_xmlns(self): user = 'u1' app = '123' # the important part of this test is an xmlns identifier with both lower and uppercase characters xmlns = 'LmN' start = datetime(2013, 7, 1) end = datetime(2013, 7, 30) received_on = datetime(2013, 7, 15, 0, 0, 0) self._send_form_to_es(received_on=received_on, user_id=user, app_id=app, xmlns=xmlns) check_case_sensitivity = get_form_counts_by_user_xmlns(self.domain, start, end, user_ids=[user], xmlnss=[xmlns]) self.assertEqual(check_case_sensitivity, { (user, app, xmlns): 1, }) @run_with_all_backends def test_get_form_duration_stats_by_user(self): """ Tests the get_form_duration_stats_by_user basic ability to get duration stats grouped by user """ user1, user2 = 'u1', 'u2' app1 = '123' xmlns1 = 'abc' start = datetime(2013, 7, 1) end = datetime(2013, 7, 30) time_start = datetime(2013, 6, 15, 0, 0, 0) completion_time = datetime(2013, 7, 15, 0, 0, 0) self._send_form_to_es( completion_time=completion_time, user_id=user1, app_id=app1, xmlns=xmlns1, time_start=time_start, ) self._send_form_to_es( completion_time=completion_time, user_id=user2, app_id=app1, xmlns=xmlns1, time_start=time_start, ) self._send_form_to_es( completion_time=completion_time, user_id=None, app_id=app1, xmlns=xmlns1, time_start=time_start, ) results = get_form_duration_stats_by_user( self.domain, app1, xmlns1, [user1, user2, None], start, end, by_submission_time=False ) self.assertEqual(results[user1]['count'], 1) self.assertEqual(timedelta(milliseconds=results[user1]['max']), completion_time - time_start) self.assertEqual(results[user2]['count'], 1) self.assertEqual(timedelta(milliseconds=results[user2]['max']), completion_time - time_start) self.assertEqual(results[MISSING_KEY]['count'], 1) self.assertEqual(timedelta(milliseconds=results[MISSING_KEY]['max']), completion_time - time_start) @run_with_all_backends def test_get_form_duration_stats_by_user_decoys(self): """ Tests the get_form_duration_stats_by_user ability to filter out forms that do not fit within the filters specified """ user1, user2 = 'u1', 'u2' app1, app2 = '123', '456' xmlns1, xmlns2 = 'abc', 'def' start = datetime(2013, 7, 1) end = datetime(2013, 7, 30) time_start = datetime(2013, 7, 2, 0, 0, 0) completion_time = datetime(2013, 7, 15, 0, 0, 0) received_on = datetime(2013, 7, 20, 0, 0, 0) received_on_late = datetime(2013, 7, 20, 0, 0, 0) self._send_form_to_es( completion_time=completion_time, user_id=user1, app_id=app1, xmlns=xmlns1, time_start=time_start, received_on=received_on, ) # different app self._send_form_to_es( completion_time=completion_time, user_id=user1, app_id=app2, xmlns=xmlns1, time_start=time_start, received_on=received_on, ) # different xmlns self._send_form_to_es( completion_time=completion_time, user_id=user1, app_id=app1, xmlns=xmlns2, time_start=time_start, received_on=received_on, ) # out of time range self._send_form_to_es( completion_time=completion_time, user_id=user2, app_id=app1, xmlns=xmlns1, time_start=time_start, received_on=received_on_late, ) results = get_form_duration_stats_by_user( self.domain, app1, xmlns1, [user1, user2], start, end, by_submission_time=True ) self.assertEqual(results[user1]['count'], 1) self.assertEqual(timedelta(milliseconds=results[user1]['max']), completion_time - time_start) self.assertIsNone(results.get('user2')) @run_with_all_backends def test_get_form_duration_stats_for_users(self): """ Tests the get_form_duration_stats_for_users basic ability to get duration stats """ user1, user2 = 'u1', 'u2' app1 = '123' xmlns1 = 'abc' start = datetime(2013, 7, 1) end = datetime(2013, 7, 30) time_start = datetime(2013, 6, 15, 0, 0, 0) completion_time = datetime(2013, 7, 15, 0, 0, 0) self._send_form_to_es( completion_time=completion_time, user_id=user1, app_id=app1, xmlns=xmlns1, time_start=time_start, ) self._send_form_to_es( completion_time=completion_time, user_id=user2, app_id=app1, xmlns=xmlns1, time_start=time_start, ) self._send_form_to_es( completion_time=completion_time, user_id=None, app_id=app1, xmlns=xmlns1, time_start=time_start, ) results = get_form_duration_stats_for_users( self.domain, app1, xmlns1, [user1, user2, None], start, end, by_submission_time=False ) self.assertEqual(results['count'], 3) self.assertEqual(timedelta(milliseconds=results['max']), completion_time - time_start) @run_with_all_backends def test_get_form_duration_stats_for_users_decoys(self): """ Tests the get_form_duration_stats_for_users ability to filter out forms that do not fit within the filters specified """ user1, user2 = 'u1', 'u2' app1, app2 = '123', '456' xmlns1, xmlns2 = 'abc', 'def' start = datetime(2013, 7, 1) end = datetime(2013, 7, 30) time_start = datetime(2013, 7, 2, 0, 0, 0) completion_time = datetime(2013, 7, 15, 0, 0, 0) received_on = datetime(2013, 7, 20, 0, 0, 0) received_on_late = datetime(2013, 8, 20, 0, 0, 0) self._send_form_to_es( completion_time=completion_time, user_id=user1, app_id=app1, xmlns=xmlns1, time_start=time_start, received_on=received_on, ) # different app self._send_form_to_es( completion_time=completion_time, user_id=user1, app_id=app2, xmlns=xmlns1, time_start=time_start, received_on=received_on, ) # different xmlns self._send_form_to_es( completion_time=completion_time, user_id=user1, app_id=app1, xmlns=xmlns2, time_start=time_start, received_on=received_on, ) # out of time range self._send_form_to_es( completion_time=completion_time, user_id=user2, app_id=app1, xmlns=xmlns1, time_start=time_start, received_on=received_on_late, ) results = get_form_duration_stats_for_users( self.domain, app1, xmlns1, [user1, user2], start, end, by_submission_time=True ) self.assertEqual(results['count'], 1) self.assertEqual(timedelta(milliseconds=results['max']), completion_time - time_start) @run_with_all_backends def test_get_all_user_ids_submitted_without_app_id(self): user1, user2 = 'u1', 'u2' app1, app2 = '123', '567' xmlns1, xmlns2 = 'abc', 'efg' received_on = datetime(2013, 7, 15, 0, 0, 0) self._send_form_to_es(received_on=received_on, user_id=user1, app_id=app1, xmlns=xmlns1) self._send_form_to_es(received_on=received_on, user_id=user2, app_id=app2, xmlns=xmlns2) user_ids = get_all_user_ids_submitted(self.domain) self.assertEqual(user_ids, ['u1', 'u2']) @run_with_all_backends def test_get_all_user_ids_submitted_with_app_id(self): user1, user2 = 'u1', 'u2' app1, app2 = '123', '567' xmlns1, xmlns2 = 'abc', 'efg' received_on = datetime(2013, 7, 15, 0, 0, 0) self._send_form_to_es(received_on=received_on, user_id=user1, app_id=app1, xmlns=xmlns1) self._send_form_to_es(received_on=received_on, user_id=user2, app_id=app2, xmlns=xmlns2) user_ids = get_all_user_ids_submitted(self.domain, app1) self.assertEqual(user_ids, ['u1']) user_ids = get_all_user_ids_submitted(self.domain, app2) self.assertEqual(user_ids, ['u2']) @run_with_all_backends def test_get_username_in_last_form_submitted(self): user1, user2 = 'u1', 'u2' app1 = '123' xmlns1 = 'abc' received_on = datetime(2013, 7, 15, 0, 0, 0) self._send_form_to_es(received_on=received_on, user_id=user1, app_id=app1, xmlns=xmlns1, username=user1) self._send_form_to_es(received_on=received_on, user_id=user2, app_id=app1, xmlns=xmlns1, username=user2) user_ids = get_username_in_last_form_user_id_submitted(self.domain, user1) self.assertEqual(user_ids, 'u1') user_ids = get_username_in_last_form_user_id_submitted(self.domain, user2) self.assertEqual(user_ids, 'u2') @es_test class TestUserESAccessors(TestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.domain = 'user-esaccessors-test' cls.definition = CustomDataFieldsDefinition(domain=cls.domain, field_type=UserFieldsView.field_type) cls.definition.save() cls.definition.set_fields([ Field(slug='job', label='Job'), ]) cls.definition.save() cls.profile = CustomDataFieldsProfile( name='daily_planet_staff', fields={'job': 'reporter'}, definition=cls.definition, ) cls.profile.save() cls.user = CommCareUser.create( cls.domain, 'superman', 'secret agent man', None, None, first_name='clark', last_name='kent', is_active=True, metadata={PROFILE_SLUG: cls.profile.id, 'office': 'phone_booth'}, ) cls.user.save() def setUp(self): super(TestUserESAccessors, self).setUp() self.es = get_es_new() ensure_index_deleted(USER_INDEX) initialize_index_and_mapping(self.es, USER_INDEX_INFO) @classmethod def tearDownClass(cls): cls.definition.delete() ensure_index_deleted(USER_INDEX) super(TestUserESAccessors, cls).tearDownClass() def _send_user_to_es(self, is_active=True): self.user.is_active = is_active send_to_elasticsearch('users', transform_user_for_elasticsearch(self.user.to_json())) self.es.indices.refresh(USER_INDEX) def test_active_user_query(self): self._send_user_to_es() results = get_user_stubs([self.user._id], ['user_data_es']) self.assertEqual(len(results), 1) metadata = results[0].pop('user_data_es') self.assertEqual({ 'commcare_project': 'user-esaccessors-test', PROFILE_SLUG: self.profile.id, 'job': 'reporter', 'office': 'phone_booth', }, {item['key']: item['value'] for item in metadata}) self.assertEqual(results[0], { '_id': self.user._id, '__group_ids': [], 'username': self.user.username, 'is_active': True, 'first_name': self.user.first_name, 'last_name': self.user.last_name, 'doc_type': 'CommCareUser', 'location_id': None, }) def test_inactive_user_query(self): self._send_user_to_es(is_active=False) results = get_user_stubs([self.user._id]) self.assertEqual(len(results), 1) self.assertEqual(results[0], { '_id': self.user._id, '__group_ids': [], 'username': self.user.username, 'is_active': False, 'first_name': self.user.first_name, 'last_name': self.user.last_name, 'doc_type': 'CommCareUser', 'location_id': None }) def test_domain_allow_mirroring(self): source_domain = self.domain + "-source" mirror = DomainPermissionsMirror(source=source_domain, mirror=self.domain) mirror.save() self._send_user_to_es() self.assertEqual(['superman'], UserES().domain(self.domain).values_list('username', flat=True)) self.assertEqual([], UserES().domain(source_domain).values_list('username', flat=True)) self.assertEqual( ['superman'], UserES().domain(self.domain, allow_mirroring=True).values_list('username', flat=True) ) mirror.delete() @es_test class TestGroupESAccessors(SimpleTestCase): def setUp(self): self.domain = 'group-esaccessors-test' self.reporting = True self.es = get_es_new() reset_es_index(GROUP_INDEX_INFO) def _send_group_to_es(self, name, _id=None, case_sharing=False): group = Group( domain=self.domain, name=name, case_sharing=case_sharing, reporting=self.reporting, _id=_id or uuid.uuid4().hex, ) send_to_elasticsearch('groups', group.to_json()) self.es.indices.refresh(GROUP_INDEX_INFO.index) return group def test_group_query(self): name = 'justice-league' self._send_group_to_es(name, '123') results = get_group_stubs(['123']) self.assertEqual(len(results), 1) self.assertEqual(results[0], { '_id': '123', 'name': name, 'case_sharing': False, 'reporting': self.reporting, }) def test_group_search_query(self): self._send_group_to_es('Milkyway', '1') self._send_group_to_es('Freeroad', '2') self._send_group_to_es('Freeway', '3', True) self.assertEqual( get_groups_by_querystring(self.domain, 'Free', False), [ {'id': '2', 'text': 'Freeroad'}, {'id': '3', 'text': 'Freeway'}, ] ) self.assertEqual( get_groups_by_querystring(self.domain, 'way', True), [ {'id': '3', 'text': 'Freeway'}, ] ) class TestCaseESAccessors(BaseESAccessorsTest): es_index_info = CASE_INDEX_INFO def setUp(self): super(TestCaseESAccessors, self).setUp() self.owner_id = 'batman' self.user_id = 'robin' self.case_type = 'heroes' def _send_case_to_es(self, domain=None, owner_id=None, user_id=None, case_type=None, opened_on=None, closed_on=None, modified_on=None): actions = [CommCareCaseAction( action_type=CASE_ACTION_CREATE, date=opened_on, )] case = CommCareCase( _id=uuid.uuid4().hex, domain=domain or self.domain, owner_id=owner_id or self.owner_id, user_id=user_id or self.user_id, type=case_type or self.case_type, opened_on=opened_on or datetime.now(), opened_by=user_id or self.user_id, modified_on=modified_on or datetime.now(), closed_on=closed_on, closed_by=user_id or self.user_id, actions=actions, ) send_to_elasticsearch('cases', case.to_json()) self.es.indices.refresh(CASE_INDEX_INFO.index) return case def test_scroll_case_names(self): case_one = self._send_case_to_es() case_two = self._send_case_to_es() self.assertEqual( len(list(scroll_case_names(self.domain, [case_one.case_id, case_two.case_id]))), 2 ) self.assertEqual( len(list(scroll_case_names('wrong-domain', [case_one.case_id, case_two.case_id]))), 0 ) self.assertEqual( len(list(scroll_case_names(self.domain, [case_one.case_id]))), 1 ) def test_get_active_case_counts(self): datespan = DateSpan(datetime(2013, 7, 1), datetime(2013, 7, 30)) opened_on = datetime(2013, 7, 15) opened_on_not_active_range = datetime(2013, 6, 15) self._send_case_to_es(opened_on=opened_on) self._send_case_to_es(opened_on=opened_on_not_active_range) results = get_active_case_counts_by_owner(self.domain, datespan) self.assertEqual(results[self.owner_id], 1) def test_get_total_case_counts(self): datespan = DateSpan(datetime(2013, 7, 1), datetime(2013, 7, 30)) opened_on = datetime(2013, 7, 15) opened_on_not_active_range = datetime(2013, 6, 15) self._send_case_to_es(opened_on=opened_on) self._send_case_to_es(opened_on=opened_on_not_active_range) self._send_case_to_es(opened_on=opened_on, case_type='commcare-user') results = get_total_case_counts_by_owner(self.domain, datespan) self.assertEqual(results[self.owner_id], 2) def test_get_active_case_counts_case_type(self): """Ensures that you can get cases by type""" datespan = DateSpan(datetime(2013, 7, 1), datetime(2013, 7, 30)) opened_on = datetime(2013, 7, 15) self._send_case_to_es(opened_on=opened_on, case_type='villians') self._send_case_to_es(opened_on=opened_on, case_type=self.case_type) results = get_active_case_counts_by_owner(self.domain, datespan, [self.case_type]) self.assertEqual(results[self.owner_id], 1) def test_get_active_case_counts_domain(self): """Ensure that cases only get grabbed if in the domain""" datespan = DateSpan(datetime(2013, 7, 1), datetime(2013, 7, 30)) opened_on = datetime(2013, 7, 15) self._send_case_to_es(opened_on=opened_on, domain='villians') self._send_case_to_es(opened_on=opened_on, domain=self.domain) results = get_active_case_counts_by_owner(self.domain, datespan) self.assertEqual(results[self.owner_id], 1) def test_get_total_case_counts_closed(self): """Test a case closure before the startdate""" datespan = DateSpan(datetime(2013, 7, 1), datetime(2013, 7, 30)) opened_on = datetime(2013, 7, 15) opened_on_early = datetime(2013, 6, 14) closed_on = datetime(2013, 6, 15) self._send_case_to_es(opened_on=opened_on) self._send_case_to_es(opened_on=opened_on_early, closed_on=closed_on) results = get_total_case_counts_by_owner(self.domain, datespan) self.assertEqual(results[self.owner_id], 1) def test_get_case_and_action_counts_for_domains(self): self._send_case_to_es() self._send_case_to_es() self._send_case_to_es('other') results = get_case_and_action_counts_for_domains([self.domain, 'other']) self.assertEqual( results, { self.domain: {'cases': 2, 'case_actions': 2}, 'other': {'cases': 1, 'case_actions': 1} } ) def test_get_total_case_counts_opened_after(self): """Test a case opened after the startdate datespan""" datespan = DateSpan(datetime(2013, 7, 1), datetime(2013, 7, 30)) opened_on = datetime(2013, 8, 15) self._send_case_to_es(opened_on=opened_on) results = get_total_case_counts_by_owner(self.domain, datespan) self.assertEqual(results, {}) def test_get_case_counts_opened_by_user(self): datespan = DateSpan(datetime(2013, 7, 1), datetime(2013, 7, 30)) opened_on = datetime(2013, 7, 15) self._send_case_to_es(opened_on=opened_on) self._send_case_to_es(opened_on=opened_on, case_type='commcare-user') results = get_case_counts_opened_by_user(self.domain, datespan) self.assertEqual(results[self.user_id], 1) def test_get_case_counts_closed_by_user(self): datespan = DateSpan(datetime(2013, 7, 1), datetime(2013, 7, 30)) opened_on = datetime(2013, 7, 15) self._send_case_to_es(opened_on=opened_on) results = get_case_counts_closed_by_user(self.domain, datespan) self.assertEqual(results, {}) self._send_case_to_es(opened_on=opened_on, closed_on=opened_on) results = get_case_counts_closed_by_user(self.domain, datespan) self.assertEqual(results[self.user_id], 1) def test_get_case_counts_opened_domain(self): datespan = DateSpan(datetime(2013, 7, 1), datetime(2013, 7, 30)) opened_on = datetime(2013, 7, 15) self._send_case_to_es(opened_on=opened_on, domain='not here') results = get_case_counts_opened_by_user(self.domain, datespan) self.assertEqual(results, {}) def test_get_case_counts_opened_case_type(self): datespan = DateSpan(datetime(2013, 7, 1), datetime(2013, 7, 30)) opened_on = datetime(2013, 7, 15) self._send_case_to_es(opened_on=opened_on) results = get_case_counts_opened_by_user(self.domain, datespan, case_types=['not-here']) self.assertEqual(results, {}) def test_get_case_counts_in_last(self): self._send_case_to_es(modified_on=datetime.now() - timedelta(days=2)) self._send_case_to_es(modified_on=datetime.now() - timedelta(days=2), case_type='new') self._send_case_to_es(modified_on=datetime.now() - timedelta(days=5), case_type='new') self.assertEqual( cases_in_last(self.domain, 3), 2 ) self.assertEqual( cases_in_last(self.domain, 3, self.case_type), 1 ) self.assertEqual( inactive_cases_in_last(self.domain, 6), 0 ) self.assertEqual( inactive_cases_in_last(self.domain, 1), 3 ) def test_get_case_types(self): self._send_case_to_es(case_type='t1') self._send_case_to_es(case_type='t2') self._send_case_to_es(case_type='t3', closed_on=datetime.utcnow()) self._send_case_to_es(domain='other', case_type='t4') case_types = get_case_types_for_domain_es(self.domain) self.assertEqual(case_types, {'t1', 't2', 't3'}) self.assertEqual({'t4'}, get_case_types_for_domain_es('other')) self.assertEqual(set(), get_case_types_for_domain_es('none')) def test_get_case_types_case_sensitive(self): self._send_case_to_es(case_type='child') self._send_case_to_es(case_type='Child') case_types = get_case_types_for_domain_es(self.domain) self.assertEqual(case_types, {'child', 'Child'}) def test_get_case_types_caching(self): self._send_case_to_es(case_type='t1') self.assertEqual({'t1'}, get_case_types_for_domain_es(self.domain)) self._send_case_to_es(case_type='t2') # cached response self.assertEqual({'t1'}, get_case_types_for_domain_es(self.domain)) # simulate a save from casexml.apps.case.signals import case_post_save case_post_save.send(self, case=CommCareCase(domain=self.domain, type='t2')) self.assertEqual({'t1', 't2'}, get_case_types_for_domain_es(self.domain)) def test_case_by_identifier(self): self._send_case_to_es(case_type='ccuser') case = self._send_case_to_es() case.external_id = '123' case.save() case = CaseAccessors(self.domain).get_case(case.case_id) case_json = case.to_json() case_json['contact_phone_number'] = '234' es_case = transform_case_for_elasticsearch(case_json) send_to_elasticsearch('cases', es_case) self.es.indices.refresh(CASE_INDEX) self.assertEqual( get_case_by_identifier(self.domain, case.case_id).case_id, case.case_id ) self.assertEqual( get_case_by_identifier(self.domain, '234').case_id, case.case_id ) self.assertEqual( get_case_by_identifier(self.domain, '123').case_id, case.case_id ) def test_location_restricted_cases(self): domain_obj = bootstrap_domain(self.domain) self.addCleanup(domain_obj.delete) location_type_names = ['state', 'county', 'city'] location_structure = [ ('Massachusetts', [ ('Middlesex', [ ('Cambridge', []), ('Somerville', []), ]), ('Suffolk', [ ('Boston', []), ]) ]) ] locations = setup_locations_and_types(self.domain, location_type_names, [], location_structure)[1] middlesex_user = CommCareUser.create(self.domain, 'guy-from-middlesex', '***', None, None) middlesex_user.add_to_assigned_locations(locations['Middlesex']) restrict_user_by_location(self.domain, middlesex_user) fake_request = MagicMock() fake_request.domain = self.domain fake_request.couch_user = middlesex_user self._send_case_to_es(owner_id=locations['Boston'].get_id) middlesex_case = self._send_case_to_es(owner_id=locations['Middlesex'].get_id) cambridge_case = self._send_case_to_es(owner_id=locations['Cambridge'].get_id) returned_case_ids = query_location_restricted_cases( CaseES().domain(self.domain), fake_request).get_ids() self.assertItemsEqual(returned_case_ids, [middlesex_case.case_id, cambridge_case.case_id]) @override_settings(TESTS_SHOULD_USE_SQL_BACKEND=True) class TestCaseESAccessorsSQL(TestCaseESAccessors): def _send_case_to_es(self, domain=None, owner_id=None, user_id=None, case_type=None, opened_on=None, closed_on=None, modified_on=None): case = CommCareCaseSQL( case_id=uuid.uuid4().hex, domain=domain or self.domain, owner_id=owner_id or self.owner_id, modified_by=user_id or self.user_id, type=case_type or self.case_type, opened_on=opened_on or datetime.now(), opened_by=user_id or self.user_id, closed_on=closed_on, modified_on=modified_on or datetime.now(), closed_by=user_id or self.user_id, server_modified_on=datetime.utcnow(), closed=bool(closed_on) ) case.track_create(CaseTransaction( type=CaseTransaction.TYPE_FORM, form_id=uuid.uuid4().hex, case=case, server_date=opened_on, )) es_case = transform_case_for_elasticsearch(case.to_json()) send_to_elasticsearch('cases', es_case) self.es.indices.refresh(CASE_INDEX) return case
31,406
13,099
269
0cc2b8d1e2e48904a6802e7fd69a28af9c162b77
468
py
Python
Lexicographical Numbers.py
sugia/leetcode
6facec2a54d1d9f133f420c9bce1d1043f57ebc6
[ "Apache-2.0" ]
null
null
null
Lexicographical Numbers.py
sugia/leetcode
6facec2a54d1d9f133f420c9bce1d1043f57ebc6
[ "Apache-2.0" ]
null
null
null
Lexicographical Numbers.py
sugia/leetcode
6facec2a54d1d9f133f420c9bce1d1043f57ebc6
[ "Apache-2.0" ]
null
null
null
''' Given an integer n, return 1 - n in lexicographical order. For example, given 13, return: [1,10,11,12,13,2,3,4,5,6,7,8,9]. Please optimize your algorithm to use less time and space. The input size may be as large as 5,000,000. '''
26
104
0.58547
''' Given an integer n, return 1 - n in lexicographical order. For example, given 13, return: [1,10,11,12,13,2,3,4,5,6,7,8,9]. Please optimize your algorithm to use less time and space. The input size may be as large as 5,000,000. ''' class Solution(object): def lexicalOrder(self, n): """ :type n: int :rtype: List[int] """ res = [i for i in xrange(1, n+1)] res.sort(key = lambda x: str(x)) return res
0
206
23
3db8895c7bd1fb7862c3328d0e371202bd92039d
1,720
py
Python
neutron/tests/unit/objects/extensions/test_standardattributes.py
ISCAS-VDI/neutron-base
687f03d7131839ae8bc324d5823194d1245bb050
[ "Apache-2.0" ]
null
null
null
neutron/tests/unit/objects/extensions/test_standardattributes.py
ISCAS-VDI/neutron-base
687f03d7131839ae8bc324d5823194d1245bb050
[ "Apache-2.0" ]
3
2015-02-27T00:48:55.000Z
2015-04-21T05:29:37.000Z
neutron/tests/unit/objects/extensions/test_standardattributes.py
ISCAS-VDI/neutron-base
687f03d7131839ae8bc324d5823194d1245bb050
[ "Apache-2.0" ]
3
2015-02-26T00:55:17.000Z
2020-03-01T17:05:40.000Z
# 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 oslo_versionedobjects import base as obj_base from oslo_versionedobjects import fields as obj_fields import sqlalchemy as sa from neutron.db import model_base from neutron.objects import base as objects_base from neutron.tests.unit.objects import test_base from neutron.tests.unit import testlib_api @obj_base.VersionedObjectRegistry.register_if(False)
35.833333
78
0.75814
# 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 oslo_versionedobjects import base as obj_base from oslo_versionedobjects import fields as obj_fields import sqlalchemy as sa from neutron.db import model_base from neutron.objects import base as objects_base from neutron.tests.unit.objects import test_base from neutron.tests.unit import testlib_api class FakeDbModelWithStandardAttributes( model_base.HasStandardAttributes, model_base.BASEV2): id = sa.Column(sa.String(36), primary_key=True, nullable=False) item = sa.Column(sa.String(64)) @obj_base.VersionedObjectRegistry.register_if(False) class FakeObjectWithStandardAttributes(objects_base.NeutronDbObject): VERSION = '1.0' db_model = FakeDbModelWithStandardAttributes fields = { 'id': obj_fields.UUIDField(), 'item': obj_fields.StringField(), } class HasStandardAttributesDbTestCase(test_base.BaseDbObjectTestCase, testlib_api.SqlTestCase): _test_class = FakeObjectWithStandardAttributes class HasStandardAttributesTestCase(test_base.BaseObjectIfaceTestCase): _test_class = FakeObjectWithStandardAttributes
0
667
91
bf14bb395190045dc72a9505d2f34a4ecfb28428
7,724
py
Python
tests/test_bootstrap.py
yuxiaoy1/bootstrap-flask
a1ded400dbc91332a4e23fbc29ab791d92169325
[ "BSD-3-Clause" ]
null
null
null
tests/test_bootstrap.py
yuxiaoy1/bootstrap-flask
a1ded400dbc91332a4e23fbc29ab791d92169325
[ "BSD-3-Clause" ]
null
null
null
tests/test_bootstrap.py
yuxiaoy1/bootstrap-flask
a1ded400dbc91332a4e23fbc29ab791d92169325
[ "BSD-3-Clause" ]
null
null
null
import pytest from flask import current_app from flask_bootstrap import ( VERSION_BOOTSTRAP, VERSION_JQUERY, VERSION_POPPER, BOOTSTRAP_CSS_INTEGRITY, BOOTSTRAP_JS_INTEGRITY, JQUERY_INTEGRITY, POPPER_INTEGRITY ) @pytest.mark.usefixtures('client')
44.137143
110
0.635293
import pytest from flask import current_app from flask_bootstrap import ( VERSION_BOOTSTRAP, VERSION_JQUERY, VERSION_POPPER, BOOTSTRAP_CSS_INTEGRITY, BOOTSTRAP_JS_INTEGRITY, JQUERY_INTEGRITY, POPPER_INTEGRITY ) @pytest.mark.usefixtures('client') class TestBootstrap: def test_extension_init(self, bootstrap): assert 'bootstrap' in current_app.extensions def test_load_css_with_default_versions(self, bootstrap): rv = bootstrap.load_css() bootstrap_css = ('<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@%s/dist/css/%s"' ' integrity="%s" crossorigin="anonymous">' % (VERSION_BOOTSTRAP, 'bootstrap.min.css', BOOTSTRAP_CSS_INTEGRITY)) assert bootstrap_css in rv def test_load_css_with_non_default_versions(self, bootstrap): def _check_assertions(rv): assert 'bootstrap.min.css' in rv assert 'integrity="' not in rv assert 'crossorigin="anonymous"' not in rv rv = bootstrap.load_css(version='1.2.3') _check_assertions(rv) rv = bootstrap.load_css(version='5.0.0') _check_assertions(rv) def test_load_js_with_default_versions(self, bootstrap): rv = bootstrap.load_js() bootstrap_js = ('<script src="https://cdn.jsdelivr.net/npm/bootstrap@%s/dist/js/%s"' ' integrity="%s" crossorigin="anonymous"></script>' % (VERSION_BOOTSTRAP, 'bootstrap.min.js', BOOTSTRAP_JS_INTEGRITY)) jquery_js = ('<script src="https://cdn.jsdelivr.net/npm/jquery@%s/dist/%s"' ' integrity="%s" crossorigin="anonymous"></script>' % (VERSION_JQUERY, 'jquery.min.js', JQUERY_INTEGRITY)) popper_js = ('<script src="https://cdn.jsdelivr.net/npm/popper.js@%s/dist/umd/%s"' ' integrity="%s" crossorigin="anonymous"></script>' % (VERSION_POPPER, 'popper.min.js', POPPER_INTEGRITY)) assert bootstrap_js in rv assert jquery_js in rv assert popper_js in rv def test_load_js_with_non_default_versions(self, bootstrap): def _check_assertions(rv): assert 'bootstrap.min.js' in rv assert 'jquery.min.js' in rv assert 'popper.min.js' in rv assert 'integrity="' not in rv assert 'crossorigin="anonymous"' not in rv rv = bootstrap.load_js(version='1.2.3', jquery_version='1.2.3', popper_version='1.2.3') _check_assertions(rv) rv = bootstrap.load_js(version='5.0.0', jquery_version='5.0.0', popper_version='5.0.0') _check_assertions(rv) def test_local_resources(self, bootstrap, client): current_app.config['BOOTSTRAP_SERVE_LOCAL'] = True response = client.get('/') data = response.get_data(as_text=True) assert 'https://cdn.jsdelivr.net/npm/bootstrap' not in data assert 'bootstrap.min.js' in data assert 'bootstrap.min.css' in data assert 'jquery.min.js' in data assert 'integrity="' not in data assert 'crossorigin="anonymous"' not in data with client.get('/bootstrap/static/css/bootstrap.min.css') as css_response: assert css_response.status_code != 404 with client.get('/bootstrap/static/js/bootstrap.min.js') as js_response: assert js_response.status_code != 404 with client.get('/bootstrap/static/jquery.min.js') as jquery_response: assert jquery_response.status_code != 404 css_rv = bootstrap.load_css() js_rv = bootstrap.load_js() assert '/bootstrap/static/css/bootstrap.min.css' in css_rv assert '/bootstrap/static/js/bootstrap.min.js' in js_rv assert 'https://cdn.jsdelivr.net/npm/bootstrap' not in css_rv assert 'https://cdn.jsdelivr.net/npm/bootstrap' not in js_rv assert 'integrity="' not in css_rv assert 'crossorigin="anonymous"' not in css_rv assert 'integrity="' not in js_rv assert 'crossorigin="anonymous"' not in js_rv def test_local_resources_with_sri(self, bootstrap): current_app.config['BOOTSTRAP_SERVE_LOCAL'] = True css_rv = bootstrap.load_css(bootstrap_sri='sha384-bootstrap-sri') js_rv = bootstrap.load_js( bootstrap_sri='sha384-bootstrap-sri', jquery_sri='sha384-jquery-sri', popper_sri='sha384-popper-sri' ) assert '/bootstrap/static/css/bootstrap.min.css' in css_rv assert '/bootstrap/static/js/bootstrap.min.js' in js_rv assert 'https://cdn.jsdelivr.net/npm/bootstrap' not in css_rv assert 'https://cdn.jsdelivr.net/npm/bootstrap' not in js_rv assert 'integrity="sha384-bootstrap-sri"' in css_rv assert 'crossorigin="anonymous"' in css_rv assert 'integrity="sha384-bootstrap-sri"' in js_rv assert 'integrity="sha384-jquery-sri"' in js_rv assert 'integrity="sha384-popper-sri"' in js_rv assert 'crossorigin="anonymous"' in js_rv def test_cdn_resources(self, bootstrap, client): current_app.config['BOOTSTRAP_SERVE_LOCAL'] = False response = client.get('/') data = response.get_data(as_text=True) assert current_app.config['BOOTSTRAP_SERVE_LOCAL'] is not True assert 'https://cdn.jsdelivr.net/npm/bootstrap' in data assert 'bootstrap.min.js' in data assert 'bootstrap.min.css' in data css_rv = bootstrap.load_css() js_rv = bootstrap.load_js() assert '/bootstrap/static/css/bootstrap.min.css' not in css_rv assert '/bootstrap/static/js/bootstrap.min.js' not in js_rv assert 'https://cdn.jsdelivr.net/npm/bootstrap' in css_rv assert 'https://cdn.jsdelivr.net/npm/bootstrap' in js_rv def test_cdn_resources_with_custom_sri_hash(self, bootstrap, client): current_app.config['BOOTSTRAP_SERVE_LOCAL'] = False css_rv = bootstrap.load_css(bootstrap_sri='sha384-bootstrap-sri') js_rv = bootstrap.load_js( bootstrap_sri='sha384-bootstrap-sri', jquery_sri='sha384-jquery-sri', popper_sri='sha384-popper-sri' ) assert 'integrity="sha384-bootstrap-sri"' in css_rv assert 'crossorigin="anonymous"' in css_rv assert 'integrity="sha384-bootstrap-sri"' in js_rv assert 'integrity="sha384-jquery-sri"' in js_rv assert 'integrity="sha384-popper-sri"' in js_rv assert 'crossorigin="anonymous"' in js_rv def test_disabling_sri(self, bootstrap): css_rv = bootstrap.load_css(bootstrap_sri=False) js_rv = bootstrap.load_js( bootstrap_sri=False, jquery_sri=False, popper_sri=False ) assert 'href="' in css_rv assert 'integrity="' not in css_rv assert 'crossorigin="anonymous"' not in css_rv assert 'src="' in js_rv assert 'integrity="' not in js_rv assert 'crossorigin="anonymous"' not in js_rv @pytest.mark.parametrize( ['with_jquery', 'with_popper'], [ (True, True), (False, False), (True, False), (False, True), ] ) def test_load_js_args(self, with_jquery, with_popper, bootstrap, client): current_app.config['BOOTSTRAP_SERVE_LOCAL'] = True js_rv = bootstrap.load_js(with_jquery=with_jquery, with_popper=with_popper) assert ('jquery.min.js' in js_rv) == with_jquery assert ('popper.min.js' in js_rv) == with_popper
6,943
499
22
c4719df6f511aafdfcd1b7e967fc0f7e8a39c9dc
1,054
py
Python
users/views.py
vostavhy/yatube
fd02f6f9e3f4249feb4f2f4085c5fb00b1d0c0a1
[ "BSD-3-Clause" ]
null
null
null
users/views.py
vostavhy/yatube
fd02f6f9e3f4249feb4f2f4085c5fb00b1d0c0a1
[ "BSD-3-Clause" ]
11
2021-03-19T14:21:23.000Z
2022-03-12T00:42:49.000Z
users/views.py
vostavhy/yatube
fd02f6f9e3f4249feb4f2f4085c5fb00b1d0c0a1
[ "BSD-3-Clause" ]
null
null
null
from django.shortcuts import redirect, render from django.core import mail from django.views.generic import CreateView from .forms import CreationForm
31.939394
109
0.634725
from django.shortcuts import redirect, render from django.core import mail from django.views.generic import CreateView from .forms import CreationForm class SignUP(CreateView): form_class = CreationForm success_url = '/auth/login/' template_name = 'registration/signup.html' def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) user.save() subject = f"Greetings {user.username}" message = f"Greetings {user.username} on our site! Your registration was successfully confirmed!" to_mail = user.email_user from_email = 'example@my_email.com' mail.send_mail( subject=subject, message=message, from_email=from_email, recipient_list=[to_mail], fail_silently=False, # выводить описание ошибок ) return redirect('login') return render(request, self.template_name, {'form': form})
759
141
23
6094e952a0271bf9ce85d30b95bb510c07927fcd
1,997
py
Python
tangos/properties/yt/basic.py
anchwr/tangos
a66740258e0987d90d921cd9c6f92658ce8375a8
[ "BSD-3-Clause" ]
null
null
null
tangos/properties/yt/basic.py
anchwr/tangos
a66740258e0987d90d921cd9c6f92658ce8375a8
[ "BSD-3-Clause" ]
4
2021-08-14T19:28:36.000Z
2021-11-27T04:43:01.000Z
tangos/properties/yt/basic.py
anchwr/tangos
a66740258e0987d90d921cd9c6f92658ce8375a8
[ "BSD-3-Clause" ]
null
null
null
from .. import PropertyCalculation, LivePropertyCalculation import numpy as np from tangos import get_halo
39.156863
110
0.64697
from .. import PropertyCalculation, LivePropertyCalculation import numpy as np from tangos import get_halo class FindCenter(PropertyCalculation): names = "Center", "Center_cu" def requires_property(self): return ["X", "Y", "Z", "X_cu", "Y_cu", "Z_cu"] def calculate(self, particle_data, existing_properties): return np.array([existing_properties["X"],existing_properties["Y"],existing_properties["Z"]]),\ np.array([existing_properties["X_cu"],existing_properties["Y_cu"],existing_properties["Z_cu"]]) class FindHosts(LivePropertyCalculation): names = "Hosts" def requires_property(self): return ["Mvir", "Center", "Rvir"] def live_calculate(self, halo_entry): centers, radii, dbid, masses = halo_entry.timestep.calculate_all("Center","Rvir","dbid()","Mvir") offsets = np.linalg.norm(halo_entry['Center'] - centers[masses>halo_entry['Mvir']], axis=1) host_mask = offsets<(radii[masses>halo_entry['Mvir']]/1000.) potids = dbid[masses>halo_entry['Mvir']] return np.array([get_halo(x) for x in potids[host_mask]]) class FindSats(LivePropertyCalculation): names = "Satellites" def requires_property(self): return ["Mvir", "Center", "Rvir"] def live_calculate(self, halo_entry): centers, radii, dbid, masses = halo_entry.timestep.calculate_all("Center","Rvir","dbid()","Mvir") offsets = np.linalg.norm(halo_entry['Center'] - centers[masses<halo_entry['Mvir']], axis=1) host_mask = offsets<(halo_entry['Rvir']/1000.) potids = dbid[masses<halo_entry['Mvir']] return np.array([get_halo(x) for x in potids[host_mask]]) class GetTimestepName(LivePropertyCalculation): names = "TimeStep" def requires_property(self): return [] def live_calculate(self, halo_entry): tsn = str(halo_entry.timestep).split('/')[1] return tsn
1,321
456
112
f0d37e204a5220a31dfe82a01ceae971839adf96
32,757
py
Python
tests/st/ops/ascend/perf_benchmark/test_alexnet_all_001.py
tianjiashuo/akg
a9cbf642063fb1086a93e8bc6be6feb145689817
[ "Apache-2.0" ]
286
2020-06-23T06:40:44.000Z
2022-03-30T01:27:49.000Z
tests/st/ops/ascend/perf_benchmark/test_alexnet_all_001.py
tianjiashuo/akg
a9cbf642063fb1086a93e8bc6be6feb145689817
[ "Apache-2.0" ]
10
2020-07-31T03:26:59.000Z
2021-12-27T15:00:54.000Z
tests/st/ops/ascend/perf_benchmark/test_alexnet_all_001.py
tianjiashuo/akg
a9cbf642063fb1086a93e8bc6be6feb145689817
[ "Apache-2.0" ]
30
2020-07-17T01:04:14.000Z
2021-12-27T14:05:19.000Z
# Copyright 2019 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import sys sys.path.append(os.path.dirname(os.path.realpath(__file__))) from base_all_run import BaseCaseRun from tests.common.test_run.ascend.conv_run import conv_run from tests.common.test_run.ascend.conv_backprop_input_run import conv_backprop_input_run from tests.common.test_run.ascend.conv_backprop_filter_run import conv_backprop_filter_run from tests.common.test_run.ascend.fused_batch_norm_run import fused_batch_norm_run from tests.common.test_run.ascend.fused_batch_norm_grad_run import fused_batch_norm_grad_run from tests.common.test_run.ascend.batch_norm_ad_run import batch_norm_ad_run from tests.common.test_run.ascend.batchmatmul_run import batchmatmul_execute from tests.common.test_run.ascend.maxpool_with_argmax_run import maxpool_with_argmax_run from tests.common.test_run.ascend.mean_run import mean_execute from tests.common.test_run.ascend.mean_ad_run import mean_ad_run from tests.common.test_run.ascend.relu_run import relu_run from tests.common.test_run.ascend.relu_grad_run import relu_grad_run from tests.common.test_run.ascend.relu_ad_run import relu_ad_run from tests.common.test_run import add_run from tests.common.test_run import addn_run from tests.common.test_run.ascend.sparse_softmax_cross_entropy_with_logits_run import sparse_softmax_cross_entropy_with_logits_run from tests.common.test_run.ascend.sparse_softmax_cross_entropy_with_logits_ad_run import sparse_softmax_cross_entropy_with_logits_ad_run from tests.common.test_run.ascend.bias_add_ad_run import bias_add_ad_run from tests.common.test_run import reshape_run from tests.common.test_run.ascend.apply_momentum_run import apply_momentum_run from tests.common.test_run import cast_run from tests.common.test_run.ascend.conv_bn1_run import conv_bn1_run from tests.common.test_run.ascend.conv_input_ad_run import conv_input_ad_run from tests.common.test_run.ascend.conv_filter_ad_run import conv_filter_ad_run if __name__ == "__main__": print_args()
63.729572
136
0.562475
# Copyright 2019 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import sys sys.path.append(os.path.dirname(os.path.realpath(__file__))) from base_all_run import BaseCaseRun from tests.common.test_run.ascend.conv_run import conv_run from tests.common.test_run.ascend.conv_backprop_input_run import conv_backprop_input_run from tests.common.test_run.ascend.conv_backprop_filter_run import conv_backprop_filter_run from tests.common.test_run.ascend.fused_batch_norm_run import fused_batch_norm_run from tests.common.test_run.ascend.fused_batch_norm_grad_run import fused_batch_norm_grad_run from tests.common.test_run.ascend.batch_norm_ad_run import batch_norm_ad_run from tests.common.test_run.ascend.batchmatmul_run import batchmatmul_execute from tests.common.test_run.ascend.maxpool_with_argmax_run import maxpool_with_argmax_run from tests.common.test_run.ascend.mean_run import mean_execute from tests.common.test_run.ascend.mean_ad_run import mean_ad_run from tests.common.test_run.ascend.relu_run import relu_run from tests.common.test_run.ascend.relu_grad_run import relu_grad_run from tests.common.test_run.ascend.relu_ad_run import relu_ad_run from tests.common.test_run import add_run from tests.common.test_run import addn_run from tests.common.test_run.ascend.sparse_softmax_cross_entropy_with_logits_run import sparse_softmax_cross_entropy_with_logits_run from tests.common.test_run.ascend.sparse_softmax_cross_entropy_with_logits_ad_run import sparse_softmax_cross_entropy_with_logits_ad_run from tests.common.test_run.ascend.bias_add_ad_run import bias_add_ad_run from tests.common.test_run import reshape_run from tests.common.test_run.ascend.apply_momentum_run import apply_momentum_run from tests.common.test_run import cast_run from tests.common.test_run.ascend.conv_bn1_run import conv_bn1_run from tests.common.test_run.ascend.conv_input_ad_run import conv_input_ad_run from tests.common.test_run.ascend.conv_filter_ad_run import conv_filter_ad_run class TestAlexnet(BaseCaseRun): def setup(self): """ testcase preparcondition :return: """ case_name = "test_alexnet_all_001" case_path = os.getcwd() # params init self.params_init(case_name, case_path) if not super(TestAlexnet, self).setup(): return False self.test_args = [ # Applymomentum ("test_alexnet_v1_apply_momentum_001", apply_momentum_run, ((10, 4096), "float32", False), ["level0", "rpc", "rpc_cloud"]), ("test_alexnet_v1_apply_momentum_002", apply_momentum_run, ((10,), "float32", False), ["level0", "rpc", "rpc_cloud"]), ("test_alexnet_v1_apply_momentum_003", apply_momentum_run, ((121, 6, 16, 16), "float32", False), ["level0", "rpc", "rpc_cloud"]), ("test_alexnet_v1_apply_momentum_004", apply_momentum_run, ((144, 24, 16, 16), "float32", False), ["level0", "rpc", "rpc_cloud"]), ("test_alexnet_v1_apply_momentum_005", apply_momentum_run, ((150, 16, 16, 16), "float32", False), ["level0", "rpc", "rpc_cloud"]), ("test_alexnet_v1_apply_momentum_006", apply_momentum_run, ((216, 16, 16, 16), "float32", False), ["level0", "rpc", "rpc_cloud"]), ("test_alexnet_v1_apply_momentum_007", apply_momentum_run, ((216, 24, 16, 16), "float32", False), ["level0", "rpc", "rpc_cloud"]), ("test_alexnet_v1_apply_momentum_008", apply_momentum_run, ((4096, 4096), "float32", False), ["level0", "rpc", "rpc_cloud"]), ("test_alexnet_v1_apply_momentum_009", apply_momentum_run, ((4096, 9216), "float32", False), ["level0", "rpc", "rpc_cloud"]), ("test_alexnet_v1_apply_momentum_010", apply_momentum_run, ((4096,), "float32", False), ["level0", "rpc", "rpc_cloud"]), # Cast ("test_alexnet_cast_000", cast_run, ([10], "float32", "float16"), ["level0", "rpc", "rpc_cloud"]), ("test_alexnet_cast_001", cast_run, ([10, 4096], "float32", "float16"), ["level0", "rpc", "rpc_cloud"]), ("test_alexnet_cast_002", cast_run, ([4096], "float32", "float16"), ["level0", "rpc", "rpc_cloud"]), ("test_alexnet_cast_003", cast_run, ([4096, 4096], "float32", "float16"), ["level0", "rpc", "rpc_cloud"]), ("test_alexnet_cast_004", cast_run, ([4096, 9216], "float32", "float16"), ["level0", "rpc", "rpc_cloud"]), ("test_alexnet_cast_005", cast_run, ([216, 16, 16, 16], "float32", "float16"), ["level0", "rpc", "rpc_cloud"]), ("test_alexnet_cast_006", cast_run, ([216, 24, 16, 16], "float32", "float16"), ["level0", "rpc", "rpc_cloud"]), ("test_alexnet_cast_007", cast_run, ([144, 24, 16, 16], "float32", "float16"), ["level0", "rpc", "rpc_cloud"]), ("test_alexnet_cast_008", cast_run, ([150, 16, 16, 16], "float32", "float16"), ["level0", "rpc", "rpc_cloud"]), ("test_alexnet_cast_009", cast_run, ([121, 6, 16, 16], "float32", "float16"), ["level0", "rpc", "rpc_cloud"]), ("test_alexnet_cast_010", cast_run, ([32, 10], "float16", "float32"), ["level0", "rpc", "rpc_cloud"]), ("test_alexnet_cast_011", cast_run, ([32, 4096], "float16", "float32"), ["level0", "rpc", "rpc_cloud"]), ("test_alexnet_cast_012", cast_run, ([32, 9216], "float16", "float32"), ["level0", "rpc", "rpc_cloud"]), ("test_alexnet_cast_014", cast_run, ([216, 16, 16, 16], "float16", "float32"), ["level0", "rpc", "rpc_cloud"]), ("test_alexnet_cast_015", cast_run, ([216, 24, 16, 16], "float16", "float32"), ["level0", "rpc", "rpc_cloud"]), ("test_alexnet_cast_016", cast_run, ([144, 24, 16, 16], "float16", "float32"), ["level0", "rpc", "rpc_cloud"]), ("test_alexnet_cast_017", cast_run, ([150, 16, 16, 16], "float16", "float32"), ["level0", "rpc", "rpc_cloud"]), ("test_alexnet_cast_018", cast_run, ([121, 6, 16, 16], "float16", "float32"), ["level0", "rpc", "rpc_cloud"]), ("test_alexnet_cast_019", cast_run, ([10], "float16", "float32"), ["level1", "rpc", "rpc_cloud", "Unavailable"]), ("test_alexnet_cast_020", cast_run, ([10, 4096], "float16", "float32"), ["level1", "rpc", "rpc_cloud", "Unavailable"]), ("test_alexnet_cast_021", cast_run, ([4096], "float16", "float32"), ["level1", "rpc", "rpc_cloud", "Unavailable"]), ("test_alexnet_cast_022", cast_run, ([4096, 4096], "float16", "float32"), ["level1", "rpc", "rpc_cloud", "Unavailable"]), ("test_alexnet_cast_023", cast_run, ([4096, 9216], "float16", "float32"), ["level1", "rpc", "rpc_cloud", "Unavailable"]), ("test_alexnet_cast_024", cast_run, ([216, 16, 16, 16], "float16", "float32"), ["level1", "rpc", "rpc_cloud", "Unavailable"]), ("test_alexnet_cast_025", cast_run, ([216, 24, 16, 16], "float16", "float32"), ["level1", "rpc", "rpc_cloud", "Unavailable"]), ("test_alexnet_cast_026", cast_run, ([144, 24, 16, 16], "float16", "float32"), ["level1", "rpc", "rpc_cloud", "Unavailable"]), ("test_alexnet_cast_027", cast_run, ([150, 16, 16, 16], "float16", "float32"), ["level1", "rpc", "rpc_cloud", "Unavailable"]), ("test_alexnet_cast_028", cast_run, ([121, 6, 16, 16], "float16", "float32"), ["level1", "rpc", "rpc_cloud", "Unavailable"]), ("test_alexnet_cast_029", cast_run, ([32, 10], "float32", "float16"), ["level1", "rpc", "rpc_cloud", "Unavailable"]), ("test_alexnet_cast_030", cast_run, ([32, 4096], "float32", "float16"), ["level1", "rpc", "rpc_cloud", "Unavailable"]), ("test_alexnet_cast_031", cast_run, ([32, 9216], "float32", "float16"), ["level1", "rpc", "rpc_cloud", "Unavailable"]), ("test_alexnet_cast_032", cast_run, ([216, 16, 16, 16], "float32", "float16"), ["level1", "rpc", "rpc_cloud", "Unavailable"]), ("test_alexnet_cast_033", cast_run, ([216, 24, 16, 16], "float32", "float16"), ["level1", "rpc", "rpc_cloud", "Unavailable"]), ("test_alexnet_cast_034", cast_run, ([144, 24, 16, 16], "float32", "float16"), ["level1", "rpc", "rpc_cloud", "Unavailable"]), ("test_alexnet_cast_035", cast_run, ([150, 16, 16, 16], "float32", "float16"), ["level1", "rpc", "rpc_cloud", "Unavailable"]), ("test_alexnet_cast_036", cast_run, ([121, 6, 16, 16], "float32", "float16"), ["level1", "rpc", "rpc_cloud", "Unavailable"]), # Five2Four ("five2four_001", "five2four_run", ([32, 256, 6, 6], "float16", 'NCHW', "float16"), ["level0", "rpc", "rpc_cloud"]), ("five2four_002", "five2four_run", ([32, 256, 6, 6], "float32", 'NCHW', "float32"), ["level1", "rpc", "rpc_cloud", "Unavailable"]), # four2five ("test_alexnet_four2five_000", "four2five_run", ([32, 3, 227, 227], "float32", "NCHW", "float32"), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ("test_alexnet_four2five_001", "four2five_run", ([32, 256, 6, 6], "float32", "NCHW", "float32"), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ("test_alexnet_four2five_002", "four2five_run", ([32, 3, 227, 227], "float16", "NCHW", "float16"), ["level1", "rpc", "rpc_cloud", "Unavailable"]), ("test_alexnet_four2five_003", "four2five_run", ([32, 256, 6, 6], "float16", "NCHW", "float16"), ["level1", "rpc", "rpc_cloud", "Unavailable"]), # FullConnection ('FullConnection_alexnet_001', batchmatmul_execute, ((), 32, 10, 4096, (10,), 'float16', False, True, 'batchmatmul_output'), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ('FullConnection_alexnet_002', batchmatmul_execute, ((), 32, 4096, 4096, (4096,), 'float16', False, True, 'batchmatmul_output'), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ('FullConnection_alexnet_003', batchmatmul_execute, ((), 32, 4096, 9216, (4096,), 'float16', False, True, 'batchmatmul_output'), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ('FullConnection_alexnet_004', batchmatmul_execute, ((), 32, 1001, 4096, (1001,), 'float16', False, True, 'batchmatmul_output'), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ('FullConnection_alexnet_005', batchmatmul_execute, ((), 32, 1000, 4096, (1000,), 'float16', False, True, 'batchmatmul_output'), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ('FullConnection_alexnet_006', batchmatmul_execute, ((), 32, 10, 4096, (10,), 'float32', False, True, 'batchmatmul_output'), ["level1", "rpc", "rpc_cloud", "Unavailable"]), ('FullConnection_alexnet_007', batchmatmul_execute, ((), 32, 4096, 4096, (4096,), 'float32', False, True, 'batchmatmul_output'), ["level1", "rpc", "rpc_cloud", "Unavailable"]), ('FullConnection_alexnet_008', batchmatmul_execute, ((), 32, 4096, 9216, (4096,), 'float32', False, True, 'batchmatmul_output'), ["level1", "rpc", "rpc_cloud", "Unavailable"]), ('FullConnection_alexnet_009', batchmatmul_execute, ((), 32, 1001, 4096, (1001,), 'float32', False, True, 'batchmatmul_output'), ["level1", "rpc", "rpc_cloud", "Unavailable"]), ('FullConnection_alexnet_010', batchmatmul_execute, ((), 32, 1000, 4096, (1000,), 'float32', False, True, 'batchmatmul_output'), ["level1", "rpc", "rpc_cloud", "Unavailable"]), ('FullConnection_alexnet_011', batchmatmul_execute, ((), 32, 100, 4096, (100,), 'float16', False, True, 'batchmatmul_output'), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ('FullConnection_alexnet_012', batchmatmul_execute, ((), 32, 100, 4096, (100,), 'float32', False, True, 'batchmatmul_output'), ["level1", "rpc", "rpc_cloud", "Unavailable"]), # MatMul ('MatMul_alexnet_001', batchmatmul_execute, ((), 32, 4096, 4096, (), 'float32', False, False, 'batchmatmul_output'), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ('MatMul_alexnet_002', batchmatmul_execute, ((), 32, 9216, 4096, (), 'float32', False, False, 'batchmatmul_output'), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ('MatMul_alexnet_003', batchmatmul_execute, ((), 32, 4096, 10, (), 'float32', False, False, 'batchmatmul_output'), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ('MatMul_alexnet_004', batchmatmul_execute, ((), 32, 4096, 1001, (), 'float32', False, False, 'batchmatmul_output'), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ('MatMul_alexnet_005', batchmatmul_execute, ((), 32, 4096, 1000, (), 'float32', False, False, 'batchmatmul_output'), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ('MatMul_alexnet_006', batchmatmul_execute, ((), 32, 4096, 4096, (), 'float16', False, False, 'batchmatmul_output'), ["level1", "rpc", "rpc_cloud", "Unavailable"]), ('MatMul_alexnet_007', batchmatmul_execute, ((), 32, 9216, 4096, (), 'float16', False, False, 'batchmatmul_output'), ["level1", "rpc", "rpc_cloud", "Unavailable"]), ('MatMul_alexnet_008', batchmatmul_execute, ((), 32, 4096, 10, (), 'float16', False, False, 'batchmatmul_output'), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ('MatMul_alexnet_009', batchmatmul_execute, ((), 32, 4096, 1001, (), 'float16', False, False, 'batchmatmul_output'), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ('MatMul_alexnet_010', batchmatmul_execute, ((), 32, 4096, 1000, (), 'float16', False, False, 'batchmatmul_output'), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ('MatMul_alexnet_011', batchmatmul_execute, ((), 32, 4096, 100, (), 'float32', False, False, 'batchmatmul_output'), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ('MatMul_alexnet_012', batchmatmul_execute, ((), 32, 4096, 100, (), 'float16', False, False, 'batchmatmul_output'), ["level0", "rpc", "rpc_cloud", "Unavailable"]), # MatMulGe ('MatMulGe_alexnet_001', batchmatmul_execute, ((), 4096, 10, 32, (), 'float32', True, False, 'batchmatmul_output'), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ('MatMulGe_alexnet_002', batchmatmul_execute, ((), 4096, 4096, 32, (), 'float32', True, False, 'batchmatmul_output'), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ('MatMulGe_alexnet_003', batchmatmul_execute, ((), 9216, 4096, 32, (), 'float32', True, False, 'batchmatmul_output'), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ('MatMulGe_alexnet_004', batchmatmul_execute, ((), 4096, 1001, 32, (), 'float32', True, False, 'batchmatmul_output'), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ('MatMulGe_alexnet_005', batchmatmul_execute, ((), 4096, 1000, 32, (), 'float32', True, False, 'batchmatmul_output'), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ('MatMulGe_alexnet_006', batchmatmul_execute, ((), 4096, 10, 32, (), 'float16', True, False, 'batchmatmul_output'), ["level1", "rpc", "rpc_cloud", "Unavailable"]), ('MatMulGe_alexnet_007', batchmatmul_execute, ((), 4096, 4096, 32, (), 'float16', True, False, 'batchmatmul_output'), ["level1", "rpc", "rpc_cloud", "Unavailable"]), ('MatMulGe_alexnet_008', batchmatmul_execute, ((), 9216, 4096, 32, (), 'float16', True, False, 'batchmatmul_output'), ["level1", "rpc", "rpc_cloud", "Unavailable"]), ('MatMulGe_alexnet_009', batchmatmul_execute, ((), 4096, 1001, 32, (), 'float16', True, False, 'batchmatmul_output'), ["level1", "rpc", "rpc_cloud", "Unavailable"]), ('MatMulGe_alexnet_010', batchmatmul_execute, ((), 4096, 1000, 32, (), 'float16', True, False, 'batchmatmul_output'), ["level1", "rpc", "rpc_cloud", "Unavailable"]), ('MatMulGe_alexnet_011', batchmatmul_execute, ((), 4096, 100, 32, (), 'float32', True, False, 'batchmatmul_output'), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ('MatMulGe_alexnet_012', batchmatmul_execute, ((), 4096, 100, 32, (), 'float16', True, False, 'batchmatmul_output'), ["level1", "rpc", "rpc_cloud", "Unavailable"]), # maxpool_with_argmax_ ("alexnet_maxpool_with_argmax_fp16_001", maxpool_with_argmax_run, ((32, 16, 13, 13, 16), (3, 3), (2, 2), "VALID", True, "float16"), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ("alexnet_maxpool_with_argmax_fp16_002", maxpool_with_argmax_run, ((32, 16, 27, 27, 16), (3, 3), (2, 2), "VALID", True, "float16"), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ("alexnet_maxpool_with_argmax_fp16_003", maxpool_with_argmax_run, ((32, 6, 55, 55, 16), (3, 3), (2, 2), "VALID", True, "float16"), ["level0", "rpc", "rpc_cloud", "Unavailable"]), # relu ("test_alexnet_relu_000", relu_run, ([32, 6, 55, 55, 16], "float16", 1e-5), ["level0", "rpc", "rpc_cloud"]), ("test_alexnet_relu_001", relu_run, ([32, 16, 27, 27, 16], "float16", 1e-5), ["level0", "rpc", "rpc_cloud"]), ("test_alexnet_relu_003", relu_run, ([32, 24, 13, 13, 16], "float16", 1e-5), ["level0", "rpc", "rpc_cloud"]), ("test_alexnet_relu_004", relu_run, ([32, 16, 13, 13, 16], "float16", 1e-5), ["level0", "rpc", "rpc_cloud"]), ("test_alexnet_relu_005", relu_run, ([32, 4096], "float16", 1e-5), ["level0", "rpc", "rpc_cloud"]), ("test_alexnet_relu_006", relu_run, ([32, 6, 55, 55, 16], "float32", 1e-5), ["level1", "rpc", "rpc_cloud", "Unavailable"]), ("test_alexnet_relu_007", relu_run, ([32, 16, 27, 27, 16], "float32", 1e-5), ["level1", "rpc", "rpc_cloud", "Unavailable"]), ("test_alexnet_relu_008", relu_run, ([32, 24, 13, 13, 16], "float32", 1e-5), ["level1", "rpc", "rpc_cloud", "Unavailable"]), ("test_alexnet_relu_009", relu_run, ([32, 16, 13, 13, 16], "float32", 1e-5), ["level1", "rpc", "rpc_cloud", "Unavailable"]), ("test_alexnet_relu_010", relu_run, ([32, 4096], "float32", 1e-5), ["level1", "rpc", "rpc_cloud", "Unavailable"]), # Reshape ("reshape_001", reshape_run, [(32, 256, 6, 6), (32, -1), "float16"], ["level0", "rpc", "rpc_cloud"]), ("reshape_002", reshape_run, [(32, 9216), (32, 256, 6, 6), "float32"], ["level0", "rpc", "rpc_cloud"]), ("test_alexnet_reshape_003", reshape_run, [(32, 256, 6, 6), (32, -1), "float32"], ["level0", "rpc", "rpc_cloud", "Unavailable"]), ("test_alexnet_reshape_004", reshape_run, [(32, 9216), (32, 256, 6, 6), "float16"], ["level0", "rpc", "rpc_cloud", "Unavailable"]), # Conv ("Alexnet_Conv2D_32_1_227_227_16", conv_run, ((32, 3, 227, 227), (96, 3, 11, 11), (0, 0, 0, 0), (4, 4), (1, 1), False), ["level0", "rpc", "rpc_cloud"]), ("Alexnet_Conv2D_32_16_13_13_16", conv_run, ((32, 256, 13, 13), (384, 256, 3, 3), (1, 1, 1, 1), (1, 1), (1, 1), False), ["level0", "rpc", "rpc_cloud"]), ("Alexnet_Conv2D_32_24_13_13_16", conv_run, ((32, 384, 13, 13), (256, 384, 3, 3), (1, 1, 1, 1), (1, 1), (1, 1), False), ["level0", "rpc", "rpc_cloud"]), ("Alexnet_Conv2D_32_24_13_13_16_v2", conv_run, ((32, 384, 13, 13), (384, 384, 3, 3), (1, 1, 1, 1), (1, 1), (1, 1), False), ["level0", "rpc", "rpc_cloud"]), ("Alexnet_Conv2D_32_6_27_27_16", conv_run, ((32, 96, 27, 27), (256, 96, 5, 5), (2, 2, 2, 2), (1, 1), (1, 1), False), ["level0", "rpc", "rpc_cloud", "Unavailable"]), # ConvBackward ("Alexnet_Conv2DBackpropInput_32_24_13_13_16", conv_backprop_input_run, ((32, 384, 13, 13), (256, 384, 3, 3), (1, 1, 1, 1), (1, 1), (1, 1)), ["level0", "rpc", "rpc_cloud"]), ("Alexnet_Conv2DBackpropInput_32_6_27_27_16", conv_backprop_input_run, ((32, 96, 27, 27), (256, 96, 5, 5), (2, 2, 2, 2), (1, 1), (1, 1)), ["level0", "rpc", "rpc_cloud"]), ("Alexnet_Conv2DBackpropInput_32_16_13_13_16", conv_backprop_input_run, ((32, 256, 13, 13), (384, 256, 3, 3), (1, 1, 1, 1), (1, 1), (1, 1)), ["level0", "rpc", "rpc_cloud"]), ("Alexnet_Conv2DBackpropInput_32_24_13_13_16_v2", conv_backprop_input_run, ((32, 384, 13, 13), (384, 384, 3, 3), (1, 1, 1, 1), (1, 1), (1, 1)), ["level0", "rpc", "rpc_cloud"]), # ConvBackwardFilter ("test_alexnet_conv_backprop_filter_000", conv_backprop_filter_run, ([32, 3, 227, 227], [96, 3, 11, 11], (0, 0, 0, 0), (4, 4), (1, 1)), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ("Alexnet_conv_backprop_filter_run_001", conv_backprop_filter_run, ((32, 384, 13, 13), (256, 384, 3, 3), (1, 1, 1, 1), (1, 1), (1, 1)), ["level0", "rpc", "rpc_cloud"]), ("Alexnet_conv_backprop_filter_run_002", conv_backprop_filter_run, ((32, 96, 27, 27), (256, 96, 5, 5), (2, 2, 2, 2), (1, 1), (1, 1)), ["level0", "rpc", "rpc_cloud"]), ("Alexnet_conv_backprop_filter_run_003", conv_backprop_filter_run, ((32, 256, 13, 13), (384, 256, 3, 3), (1, 1, 1, 1), (1, 1), (1, 1)), ["level0", "rpc", "rpc_cloud"]), ("Alexnet_conv_backprop_filter_run_004", conv_backprop_filter_run, ((32, 384, 13, 13), (384, 384, 3, 3), (1, 1, 1, 1), (1, 1), (1, 1)), ["level0", "rpc", "rpc_cloud"]), # maxpool_grad_with_argmax # ("test_alexnet_maxpool_grad_with_argmax_001", maxpool_grad_with_argmax_run, # ([32, 16, 13, 13, 16], (3, 3), (2, 2), "VALID", "float16", False, True), # ["level0", "rpc", "rpc_cloud", "Unavailable"]), # ("test_alexnet_maxpool_grad_with_argmax_002", maxpool_grad_with_argmax_run, # ([32, 16, 27, 27, 16], (3, 3), (2, 2), "VALID", "float16", False, True), # ["level0", "rpc", "rpc_cloud", "Unavailable"]), # ("test_alexnet_maxpool_grad_with_argmax_003", maxpool_grad_with_argmax_run, # ([32, 6, 55, 55, 16], (3, 3), (2, 2), "VALID", "float16", False, True), # ["level0", "rpc", "rpc_cloud", "Unavailable"]), # ("test_alexnet_maxpool_grad_with_argmax_004", maxpool_grad_with_argmax_run, # ((32, 16, 13, 13, 16), (3, 3), (2, 2), "VALID", "float32", False, True), # ["level0", "rpc", "rpc_cloud", "Unavailable"]), # ("test_alexnet_maxpool_grad_with_argmax_005", maxpool_grad_with_argmax_run, # ((32, 16, 27, 27, 16), (3, 3), (2, 2), "VALID", "float32", False, True), # ["level0", "rpc", "rpc_cloud", "Unavailable"]), # ("test_alexnet_maxpool_grad_with_argmax_006", maxpool_grad_with_argmax_run, # ((32, 6, 55, 55, 16), (3, 3), (2, 2), "VALID", "float32", False, True), # ["level0", "rpc", "rpc_cloud", "Unavailable"]), # conv_bn1 ("Alexnet_conv_bn1_32_1_227_227_16", conv_bn1_run, ((32, 3, 227, 227), (96, 3, 11, 11), (0, 0, 0, 0), (4, 4), (1, 1), False), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ("Alexnet_conv_bn1_32_16_13_13_16", conv_bn1_run, ((32, 256, 13, 13), (384, 256, 3, 3), (1, 1, 1, 1), (1, 1), (1, 1), False), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ("Alexnet_conv_bn1_32_24_13_13_16", conv_bn1_run, ((32, 384, 13, 13), (256, 384, 3, 3), (1, 1, 1, 1), (1, 1), (1, 1), False), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ("Alexnet_conv_bn1_32_24_13_13_16_v2", conv_bn1_run, ((32, 384, 13, 13), (384, 384, 3, 3), (1, 1, 1, 1), (1, 1), (1, 1), False), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ("Alexnet_conv_bn1_32_6_27_27_16", conv_bn1_run, ((32, 96, 27, 27), (256, 96, 5, 5), (2, 2, 2, 2), (1, 1), (1, 1), False), ["level0", "rpc", "rpc_cloud", "Unavailable"]), # relu_ad ("test_alexnet_relu_ad_001", relu_ad_run, ([32, 4096], "float32"), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ("test_alexnet_relu_ad_002", relu_ad_run, ([32, 16, 13, 13, 16], "float32"), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ("test_alexnet_relu_ad_003", relu_ad_run, ([32, 24, 13, 13, 16], "float32"), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ("test_alexnet_relu_ad_004", relu_ad_run, ([32, 24, 13, 13, 16], "float16"), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ("test_alexnet_relu_ad_005", relu_ad_run, ([32, 16, 27, 27, 16], "float16"), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ("test_alexnet_relu_ad_006", relu_ad_run, ([32, 6, 55, 55, 16], "float16"), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ("test_alexnet_relu_ad_007", relu_ad_run, ((32, 16, 13, 13, 16), "float16"), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ("test_alexnet_relu_ad_008", relu_ad_run, ((32, 16, 28, 28, 16), "float32"), ["level1", "rpc", "rpc_cloud", "Unavailable"]), ("test_alexnet_relu_ad_009", relu_ad_run, ((32, 16, 28, 28, 16), "float16"), ["level1", "rpc", "rpc_cloud", "Unavailable"]), ("test_alexnet_relu_ad_010", relu_ad_run, ((32, 4096), "float16"), ["level1", "rpc", "rpc_cloud", "Unavailable"]), ("test_alexnet_relu_ad_011", relu_ad_run, ((32, 6, 55, 55, 16), "float32"), ["level1", "rpc", "rpc_cloud", "Unavailable"]), ("test_alexnet_relu_ad_012", relu_ad_run, ([32, 16, 27, 27, 16], "float32"), ["level1", "rpc", "rpc_cloud", "Unavailable"]), # conv_input_ad ("Alexnet_conv_input_ad_32_24_13_13_16", conv_input_ad_run, ((32, 384, 13, 13), (256, 384, 3, 3), (1, 1, 1, 1), (1, 1), (1, 1)), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ("Alexnet_conv_input_ad_32_6_27_27_16", conv_input_ad_run, ((32, 96, 27, 27), (256, 96, 5, 5), (2, 2, 2, 2), (1, 1), (1, 1)), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ("Alexnet_conv_input_ad_32_16_13_13_16", conv_input_ad_run, ((32, 256, 13, 13), (384, 256, 3, 3), (1, 1, 1, 1), (1, 1), (1, 1)), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ("Alexnet_conv_input_ad_32_24_13_13_16_v2", conv_input_ad_run, ((32, 384, 13, 13), (384, 384, 3, 3), (1, 1, 1, 1), (1, 1), (1, 1)), ["level0", "rpc", "rpc_cloud", "Unavailable"]), # conv_filter_ad ("test_alexnet_conv_filter_ad_000", conv_filter_ad_run, ([32, 3, 227, 227], [96, 3, 11, 11], (0, 0, 0, 0), (4, 4), (1, 1)), ["level1", "rpc", "rpc_cloud", "Unavailable"]), ("Alexnet_conv_filter_ad_001", conv_filter_ad_run, ((32, 384, 13, 13), (256, 384, 3, 3), (1, 1, 1, 1), (1, 1), (1, 1)), ["level1", "rpc", "rpc_cloud", "Unavailable"]), ("Alexnet_conv_filter_ad_002", conv_filter_ad_run, ((32, 96, 27, 27), (256, 96, 5, 5), (2, 2, 2, 2), (1, 1), (1, 1)), ["level1", "rpc", "rpc_cloud", "Unavailable"]), ("Alexnet_conv_filter_ad_003", conv_filter_ad_run, ((32, 256, 13, 13), (384, 256, 3, 3), (1, 1, 1, 1), (1, 1), (1, 1)), ["level1", "rpc", "rpc_cloud", "Unavailable"]), ("Alexnet_conv_filter_ad_004", conv_filter_ad_run, ((32, 384, 13, 13), (384, 384, 3, 3), (1, 1, 1, 1), (1, 1), (1, 1)), ["level1", "rpc", "rpc_cloud", "Unavailable"]), # sparse_softmax_cross_entropy_with_logits_ad ("Alexnet_sparse_softmax_cross_entropy_with_logits_ad_001", sparse_softmax_cross_entropy_with_logits_ad_run, [(32,), "int32", (32, 10), "float32", "mean", "sparse_softmax_cross_entropy_with_logits_ad_fp32"], ["level0", "rpc", "rpc_cloud", "Unavailable"]), ("Alexnet_sparse_softmax_cross_entropy_with_logits_ad_002", sparse_softmax_cross_entropy_with_logits_ad_run, [(32,), "int32", (32, 1001), "float32", "mean", "sparse_softmax_cross_entropy_with_logits_ad_fp32"], ["level0", "rpc", "rpc_cloud", "Unavailable"]), ("Alexnet_sparse_softmax_cross_entropy_with_logits_ad_003", sparse_softmax_cross_entropy_with_logits_ad_run, [(32,), "int32", (32, 1000), "float32", "mean", "sparse_softmax_cross_entropy_with_logits_ad_fp32"], ["level0", "rpc", "rpc_cloud", "Unavailable"]), # bias_add_ad ("test_lenet_bias_add_ad_fp16_001", bias_add_ad_run, ([32, 10], "DefaultFormat", "float16"), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ("test_lenet_bias_add_ad_fp16_002", bias_add_ad_run, ([32, 120], "DefaultFormat", "float16"), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ("test_lenet_bias_add_ad_fp16_003", bias_add_ad_run, ([32, 84], "DefaultFormat", "float16"), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ("test_lenet_bias_add_ad_fp32_004", bias_add_ad_run, ([32, 10], "DefaultFormat", "float32"), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ("test_lenet_bias_add_ad_fp32_005", bias_add_ad_run, ([32, 120], "DefaultFormat", "float32"), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ("test_lenet_bias_add_ad_fp32_006", bias_add_ad_run, ([32, 84], "DefaultFormat", "float32"), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ("test_lenet_bias_add_ad_fp32_007", bias_add_ad_run, ([32, 1001], "DefaultFormat", "float32"), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ("test_lenet_bias_add_ad_fp16_008", bias_add_ad_run, ([32, 1001], "DefaultFormat", "float16"), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ("test_lenet_bias_add_ad_fp32_009", bias_add_ad_run, ([32, 1000], "DefaultFormat", "float32"), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ("test_lenet_bias_add_ad_fp16_010", bias_add_ad_run, ([32, 1000], "DefaultFormat", "float16"), ["level0", "rpc", "rpc_cloud", "Unavailable"]), ] def print_args(): cls = TestAlexnet() cls.setup() cls.print_args() if __name__ == "__main__": print_args()
57
30,102
46
45b00b5a30e65a211d3af958899854a636b1088d
805
py
Python
artifacts/migrations/0013_auto_20201203_1112.py
Joe-Bentley/team_totem
0458447619b1480027168d3b704c401ab7db1e0e
[ "Unlicense" ]
null
null
null
artifacts/migrations/0013_auto_20201203_1112.py
Joe-Bentley/team_totem
0458447619b1480027168d3b704c401ab7db1e0e
[ "Unlicense" ]
25
2020-11-30T14:32:43.000Z
2020-12-04T10:35:58.000Z
artifacts/migrations/0013_auto_20201203_1112.py
Joe-Bentley/team_totem
0458447619b1480027168d3b704c401ab7db1e0e
[ "Unlicense" ]
2
2020-12-01T18:08:24.000Z
2020-12-04T10:44:11.000Z
# Generated by Django 3.1.3 on 2020-12-03 11:12 from django.db import migrations, models import django.db.models.deletion
27.758621
117
0.608696
# Generated by Django 3.1.3 on 2020-12-03 11:12 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('artifacts', '0012_auto_20201201_1420'), ] operations = [ migrations.RemoveField( model_name='location', name='artifact', ), migrations.AddField( model_name='artifact', name='location', field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='artifacts.location'), ), migrations.AddField( model_name='location', name='image', field=models.ImageField(default='artifacts/uploads/qmark.png', upload_to='artifacts/uploads'), ), ]
0
658
23
87e1e00bba8e9feced9644dd23c8931b4a3025a9
2,705
py
Python
factorio_status_ui/serve.py
adamcharnock/factorio-status-ui
80fb4200d226b1037c61f4dd655462cb4acf6e16
[ "MIT" ]
7
2019-04-11T11:38:40.000Z
2020-08-25T12:59:16.000Z
factorio_status_ui/serve.py
carsso/factorio-status-ui
bf184fdd7eea6494ecadff966535175a9df8a6ff
[ "MIT" ]
1
2020-04-28T08:34:59.000Z
2020-04-28T17:25:43.000Z
factorio_status_ui/serve.py
carsso/factorio-status-ui
bf184fdd7eea6494ecadff966535175a9df8a6ff
[ "MIT" ]
1
2020-04-27T20:10:44.000Z
2020-04-27T20:10:44.000Z
import argparse import logging import signal import sys from pathlib import Path from aiohttp import web from factorio_status_ui.state import application_config from factorio_status_ui.web import setup_routes, setup_templates, start_background_tasks, cleanup_background_tasks, \ get_version if __name__ == '__main__': main()
38.098592
117
0.712754
import argparse import logging import signal import sys from pathlib import Path from aiohttp import web from factorio_status_ui.state import application_config from factorio_status_ui.web import setup_routes, setup_templates, start_background_tasks, cleanup_background_tasks, \ get_version def main(): print(sys.argv) # Logging logger = logging.getLogger('factorio_status_ui') logger.setLevel(logging.DEBUG) handler = logging.StreamHandler() handler.setLevel(logging.DEBUG) handler.setFormatter(logging.Formatter('%(asctime)s | %(levelname)s | %(msg)s')) logger.addHandler(handler) # Arguments parser = argparse.ArgumentParser( description='Factorio status UI', formatter_class=argparse.ArgumentDefaultsHelpFormatter ) required = parser.add_argument_group('required arguments') parser.add_argument('--port', help='The port on which to serve the status page.', type=int, default=8080) parser.add_argument('--host', help='The IP on which to serve the status page.', default='0.0.0.0') parser.add_argument('--server-name', help='Server name. For display purposes only.', default='Factorio Server') parser.add_argument('--server-host', help='Factorio server IP address. For display purposes only. ' 'Will attempt to autodetect.') parser.add_argument('--server-port', help='Factorio server port. For display purposes only.', default=34197) required.add_argument('--rcon-host', help='RCON host address.', required=True) required.add_argument('--rcon-port', help='RCON port.', type=int, required=True, default=27015) required.add_argument('--rcon-password', help='RCON password.', required=True) parser.add_argument('--rcon-timeout', help='RCON timeout in seconds.', default=1, type=int) required.add_argument('--mods-directory', help='Path to factorio mods directory.', type=Path, required=True) required.add_argument('--saves-directory', help='Path to factorio saves directory.', type=Path, required=True) args = parser.parse_args() for option in dir(application_config): if option.startswith('_'): continue setattr(application_config, option, getattr(args, option)) logger.info('Starting up') logger.info('Arguments: {}'.format(args.__dict__)) # App app = web.Application() setup_routes(app) setup_templates(app) app.on_startup.append(start_background_tasks) app.on_startup.append(get_version) app.on_cleanup.append(cleanup_background_tasks) web.run_app(app, host=application_config.host, port=application_config.port) if __name__ == '__main__': main()
2,344
0
23
c902e68cbf844338c9dd8d461f5075813e9543ef
1,047
py
Python
utils.py
tat-nlp/sart
24d15d25ba29cb82320287fa7787ada5a8643771
[ "CC-BY-4.0" ]
2
2019-06-17T15:38:30.000Z
2021-09-16T07:07:23.000Z
utils.py
tat-nlp/SART
24d15d25ba29cb82320287fa7787ada5a8643771
[ "CC-BY-4.0" ]
null
null
null
utils.py
tat-nlp/SART
24d15d25ba29cb82320287fa7787ada5a8643771
[ "CC-BY-4.0" ]
null
null
null
import io import numpy as np # Read embeddings to a numpy array and word2id dictionary # Normalize embeddings # Read lines from .txt file into a list of lists of words
29.914286
86
0.595033
import io import numpy as np # Read embeddings to a numpy array and word2id dictionary def read_embeddings(emb_path): words2ids = {} vectors = None # load pre-trained embeddings with io.open(emb_path, 'r', encoding='utf-8', newline='\n', errors='ignore') as f: for i, line in enumerate(f): if i == 0: split = line.split() vectors = np.empty([int(split[0]), int(split[1])]) else: word, vect = line.rstrip().split(' ', 1) vect = np.fromstring(vect, sep=' ') vectors[len(words2ids)] = vect words2ids[word] = len(words2ids) return vectors, words2ids # Normalize embeddings def normalize_embeddings(emb): norm = np.linalg.norm(emb, axis=1) return emb / norm[:, None] # Read lines from .txt file into a list of lists of words def read_lines(filepath): split_lines = [] for line in open(filepath, 'r', encoding="utf8"): split_lines.append(line.split()) return split_lines
807
0
66
79fd6ea6cf65fd3990bea9da8f17955107286294
3,241
py
Python
dglt/contrib/grover/mol2features.py
uta-smile/CD-MVGNN
b48f4cd14befed298980a83edb417ab6809f0af6
[ "MIT" ]
3
2022-02-06T09:13:51.000Z
2022-02-19T15:03:35.000Z
dglt/contrib/grover/mol2features.py
uta-smile/CD-MVGNN
b48f4cd14befed298980a83edb417ab6809f0af6
[ "MIT" ]
1
2022-02-14T23:16:27.000Z
2022-02-14T23:16:27.000Z
dglt/contrib/grover/mol2features.py
uta-smile/CD-MVGNN
b48f4cd14befed298980a83edb417ab6809f0af6
[ "MIT" ]
null
null
null
from collections import Counter from typing import Callable, Union import numpy as np from rdkit import Chem from dglt.data.featurization.mol2features import register_features_generator from third_party.descriptastorus.descriptors import rdDescriptors Molecule = Union[str, Chem.Mol] FeaturesGenerator = Callable[[Molecule], np.ndarray] RDKIT_PROPS = ['fr_Al_COO', 'fr_Al_OH', 'fr_Al_OH_noTert', 'fr_ArN', 'fr_Ar_COO', 'fr_Ar_N', 'fr_Ar_NH', 'fr_Ar_OH', 'fr_COO', 'fr_COO2', 'fr_C_O', 'fr_C_O_noCOO', 'fr_C_S', 'fr_HOCCN', 'fr_Imine', 'fr_NH0', 'fr_NH1', 'fr_NH2', 'fr_N_O', 'fr_Ndealkylation1', 'fr_Ndealkylation2', 'fr_Nhpyrrole', 'fr_SH', 'fr_aldehyde', 'fr_alkyl_carbamate', 'fr_alkyl_halide', 'fr_allylic_oxid', 'fr_amide', 'fr_amidine', 'fr_aniline', 'fr_aryl_methyl', 'fr_azide', 'fr_azo', 'fr_barbitur', 'fr_benzene', 'fr_benzodiazepine', 'fr_bicyclic', 'fr_diazo', 'fr_dihydropyridine', 'fr_epoxide', 'fr_ester', 'fr_ether', 'fr_furan', 'fr_guanido', 'fr_halogen', 'fr_hdrzine', 'fr_hdrzone', 'fr_imidazole', 'fr_imide', 'fr_isocyan', 'fr_isothiocyan', 'fr_ketone', 'fr_ketone_Topliss', 'fr_lactam', 'fr_lactone', 'fr_methoxy', 'fr_morpholine', 'fr_nitrile', 'fr_nitro', 'fr_nitro_arom', 'fr_nitro_arom_nonortho', 'fr_nitroso', 'fr_oxazole', 'fr_oxime', 'fr_para_hydroxylation', 'fr_phenol', 'fr_phenol_noOrthoHbond', 'fr_phos_acid', 'fr_phos_ester', 'fr_piperdine', 'fr_piperzine', 'fr_priamide', 'fr_prisulfonamd', 'fr_pyridine', 'fr_quatN', 'fr_sulfide', 'fr_sulfonamd', 'fr_sulfone', 'fr_term_acetylene', 'fr_tetrazole', 'fr_thiazole', 'fr_thiocyan', 'fr_thiophene', 'fr_unbrch_alkane', 'fr_urea'] @register_features_generator('fgtasklabel') def rdkit_functional_group_label_features_generator(mol: Molecule) -> np.ndarray: """ Generates functional group label for a molecule in RDKit. :param mol: A molecule (i.e. either a SMILES string or an RDKit molecule). :return: A 1D numpy array containing the RDKit 2D features. """ smiles = Chem.MolToSmiles(mol, isomericSmiles=True) if type(mol) != str else mol generator = rdDescriptors.RDKit2D(RDKIT_PROPS) features = generator.process(smiles)[1:] features = np.array(features) features[features != 0] = 1 return features def atom_to_vocab(mol, atom): """ Convert atom to vocabulary. The convention is based on atom type and bond type. :param mol: the molecular. :param atom: the target atom. :return: """ nei = Counter() for a in atom.GetNeighbors(): bond = mol.GetBondBetweenAtoms(atom.GetIdx(), a.GetIdx()) nei[str(a.GetSymbol()) + "-" + str(bond.GetBondType())] += 1 keys = nei.keys() keys = list(keys) keys.sort() output = atom.GetSymbol() for k in keys: output = "%s_%s%d" % (output, k, nei[k]) # The generated vocab is too long? return output smiles = "CC(C)Nc1c(nc2ncccn12)c3ccc4[nH]ncc4c3" mol = Chem.MolFromSmiles(smiles) for i, atom in enumerate(mol.GetAtoms()): atom_to_vocab(mol, atom)
44.39726
95
0.659673
from collections import Counter from typing import Callable, Union import numpy as np from rdkit import Chem from dglt.data.featurization.mol2features import register_features_generator from third_party.descriptastorus.descriptors import rdDescriptors Molecule = Union[str, Chem.Mol] FeaturesGenerator = Callable[[Molecule], np.ndarray] RDKIT_PROPS = ['fr_Al_COO', 'fr_Al_OH', 'fr_Al_OH_noTert', 'fr_ArN', 'fr_Ar_COO', 'fr_Ar_N', 'fr_Ar_NH', 'fr_Ar_OH', 'fr_COO', 'fr_COO2', 'fr_C_O', 'fr_C_O_noCOO', 'fr_C_S', 'fr_HOCCN', 'fr_Imine', 'fr_NH0', 'fr_NH1', 'fr_NH2', 'fr_N_O', 'fr_Ndealkylation1', 'fr_Ndealkylation2', 'fr_Nhpyrrole', 'fr_SH', 'fr_aldehyde', 'fr_alkyl_carbamate', 'fr_alkyl_halide', 'fr_allylic_oxid', 'fr_amide', 'fr_amidine', 'fr_aniline', 'fr_aryl_methyl', 'fr_azide', 'fr_azo', 'fr_barbitur', 'fr_benzene', 'fr_benzodiazepine', 'fr_bicyclic', 'fr_diazo', 'fr_dihydropyridine', 'fr_epoxide', 'fr_ester', 'fr_ether', 'fr_furan', 'fr_guanido', 'fr_halogen', 'fr_hdrzine', 'fr_hdrzone', 'fr_imidazole', 'fr_imide', 'fr_isocyan', 'fr_isothiocyan', 'fr_ketone', 'fr_ketone_Topliss', 'fr_lactam', 'fr_lactone', 'fr_methoxy', 'fr_morpholine', 'fr_nitrile', 'fr_nitro', 'fr_nitro_arom', 'fr_nitro_arom_nonortho', 'fr_nitroso', 'fr_oxazole', 'fr_oxime', 'fr_para_hydroxylation', 'fr_phenol', 'fr_phenol_noOrthoHbond', 'fr_phos_acid', 'fr_phos_ester', 'fr_piperdine', 'fr_piperzine', 'fr_priamide', 'fr_prisulfonamd', 'fr_pyridine', 'fr_quatN', 'fr_sulfide', 'fr_sulfonamd', 'fr_sulfone', 'fr_term_acetylene', 'fr_tetrazole', 'fr_thiazole', 'fr_thiocyan', 'fr_thiophene', 'fr_unbrch_alkane', 'fr_urea'] @register_features_generator('fgtasklabel') def rdkit_functional_group_label_features_generator(mol: Molecule) -> np.ndarray: """ Generates functional group label for a molecule in RDKit. :param mol: A molecule (i.e. either a SMILES string or an RDKit molecule). :return: A 1D numpy array containing the RDKit 2D features. """ smiles = Chem.MolToSmiles(mol, isomericSmiles=True) if type(mol) != str else mol generator = rdDescriptors.RDKit2D(RDKIT_PROPS) features = generator.process(smiles)[1:] features = np.array(features) features[features != 0] = 1 return features def atom_to_vocab(mol, atom): """ Convert atom to vocabulary. The convention is based on atom type and bond type. :param mol: the molecular. :param atom: the target atom. :return: """ nei = Counter() for a in atom.GetNeighbors(): bond = mol.GetBondBetweenAtoms(atom.GetIdx(), a.GetIdx()) nei[str(a.GetSymbol()) + "-" + str(bond.GetBondType())] += 1 keys = nei.keys() keys = list(keys) keys.sort() output = atom.GetSymbol() for k in keys: output = "%s_%s%d" % (output, k, nei[k]) # The generated vocab is too long? return output smiles = "CC(C)Nc1c(nc2ncccn12)c3ccc4[nH]ncc4c3" mol = Chem.MolFromSmiles(smiles) for i, atom in enumerate(mol.GetAtoms()): atom_to_vocab(mol, atom)
0
0
0
9b6b876677d434054b342ff5d8cddbadf3ed7456
185
py
Python
dffml/util/config/fields.py
agriyakhetarpal/dffml
f76f2ce94c3972634053377b00e7c16530f7f0a4
[ "MIT" ]
171
2019-03-08T19:02:06.000Z
2022-03-29T16:17:23.000Z
dffml/util/config/fields.py
agriyakhetarpal/dffml
f76f2ce94c3972634053377b00e7c16530f7f0a4
[ "MIT" ]
1,158
2019-03-08T19:07:50.000Z
2022-03-25T08:28:27.000Z
dffml/util/config/fields.py
agriyakhetarpal/dffml
f76f2ce94c3972634053377b00e7c16530f7f0a4
[ "MIT" ]
183
2019-03-10T02:40:56.000Z
2022-03-27T18:51:26.000Z
from ...source.source import Sources from ...base import field FIELD_SOURCES = field( "Sources for loading and saving", default_factory=lambda: Sources(), labeled=True, )
18.5
38
0.708108
from ...source.source import Sources from ...base import field FIELD_SOURCES = field( "Sources for loading and saving", default_factory=lambda: Sources(), labeled=True, )
0
0
0
812e36181c5e33bf18aa10f386c28ab03541752a
1,437
py
Python
utils/helper.py
zawlinnnaing/my-wiki-crawler
68458dd7b5548edd0a4e088f9905b53406ff5a4f
[ "MIT" ]
null
null
null
utils/helper.py
zawlinnnaing/my-wiki-crawler
68458dd7b5548edd0a4e088f9905b53406ff5a4f
[ "MIT" ]
null
null
null
utils/helper.py
zawlinnnaing/my-wiki-crawler
68458dd7b5548edd0a4e088f9905b53406ff5a4f
[ "MIT" ]
null
null
null
from requests import get from requests import RequestException from collections import OrderedDict from contextlib import closing import os import logging from .file import FileUtil from datetime import date import json os.chdir(os.getcwd()) def simple_get(url): """ Attempts to get the content at `url` by making an HTTP GET request. If the content-type of response is some kind of HTML/XML, return the text content, otherwise return None. """ try: with closing(get(url, stream=True)) as res: if is_good_response(res): return res.content else: return None except RequestException as e: raise e def is_good_response(res, content_type='html'): """ Returns True if the response seems to be Content type (default html), False otherwise. """ content_type = res.headers['Content-Type'].lower() return (res.status_code == 200 and content_type is not None and content_type.find(content_type) > -1)
26.127273
105
0.675713
from requests import get from requests import RequestException from collections import OrderedDict from contextlib import closing import os import logging from .file import FileUtil from datetime import date import json os.chdir(os.getcwd()) def request_api(url, params): try: with closing(get(url, params=params)) as res: return res.json() except RequestException as e: raise e def simple_get(url): """ Attempts to get the content at `url` by making an HTTP GET request. If the content-type of response is some kind of HTML/XML, return the text content, otherwise return None. """ try: with closing(get(url, stream=True)) as res: if is_good_response(res): return res.content else: return None except RequestException as e: raise e def is_good_response(res, content_type='html'): """ Returns True if the response seems to be Content type (default html), False otherwise. """ content_type = res.headers['Content-Type'].lower() return (res.status_code == 200 and content_type is not None and content_type.find(content_type) > -1) def log_error(e: str, log_dir: str = 'logs'): FileUtil.mkdir_if_not_exists(log_dir) log_file = os.path.join(log_dir, str(date.today()) + '.log') logging.basicConfig(filename=log_file, level=logging.WARNING) logging.error(e)
369
0
46
be4bb0ec766c786bc8be57bd96e623364b9c8b8c
2,196
py
Python
profiling/ms_io/mzxml_io.py
wh-xu/falcon
f44f19b5cc49643ff20e3dfe40264f3e08a75f53
[ "BSD-3-Clause" ]
null
null
null
profiling/ms_io/mzxml_io.py
wh-xu/falcon
f44f19b5cc49643ff20e3dfe40264f3e08a75f53
[ "BSD-3-Clause" ]
null
null
null
profiling/ms_io/mzxml_io.py
wh-xu/falcon
f44f19b5cc49643ff20e3dfe40264f3e08a75f53
[ "BSD-3-Clause" ]
null
null
null
import logging import os from typing import Dict, IO, Iterable, Union import pyteomics.mzxml import spectrum_utils.spectrum as sus from lxml.etree import LxmlError logger = logging.getLogger('falcon') def get_spectra(source: Union[IO, str]) -> Iterable[sus.MsmsSpectrum]: """ Get the MS/MS spectra from the given mzXML file. Parameters ---------- source : Union[IO, str] The mzXML source (file name or open file object) from which the spectra are read. Returns ------- Iterable[MsmsSpectrum] An iterator over the spectra in the given file. """ with pyteomics.mzxml.MzXML(source) as f_in: filename = os.path.splitext(os.path.basename(f_in.name))[0] try: for spectrum_dict in f_in: if int(spectrum_dict.get('msLevel', -1)) == 2: # USI-inspired cluster identifier. scan_nr = int(spectrum_dict['id']) spectrum_dict['id'] = f'{filename}:scan:{scan_nr}' try: yield _parse_spectrum(spectrum_dict) except (ValueError, KeyError): pass except LxmlError as e: logger.warning('Failed to read file %s: %s', source, e) def _parse_spectrum(spectrum_dict: Dict) -> sus.MsmsSpectrum: """ Parse the Pyteomics cluster dict. Parameters ---------- spectrum_dict : Dict The Pyteomics cluster dict to be parsed. Returns ------- MsmsSpectrum The parsed cluster. """ spectrum_id = spectrum_dict['id'] mz_array = spectrum_dict['m/z array'] intensity_array = spectrum_dict['intensity array'] retention_time = spectrum_dict.get('retentionTime', -1) precursor_mz = spectrum_dict['precursorMz'][0]['precursorMz'] if 'precursorCharge' in spectrum_dict['precursorMz'][0]: precursor_charge = spectrum_dict['precursorMz'][0]['precursorCharge'] else: raise ValueError('Unknown precursor charge') return sus.MsmsSpectrum(spectrum_id, precursor_mz, precursor_charge, mz_array, intensity_array, None, retention_time)
30.929577
79
0.617942
import logging import os from typing import Dict, IO, Iterable, Union import pyteomics.mzxml import spectrum_utils.spectrum as sus from lxml.etree import LxmlError logger = logging.getLogger('falcon') def get_spectra(source: Union[IO, str]) -> Iterable[sus.MsmsSpectrum]: """ Get the MS/MS spectra from the given mzXML file. Parameters ---------- source : Union[IO, str] The mzXML source (file name or open file object) from which the spectra are read. Returns ------- Iterable[MsmsSpectrum] An iterator over the spectra in the given file. """ with pyteomics.mzxml.MzXML(source) as f_in: filename = os.path.splitext(os.path.basename(f_in.name))[0] try: for spectrum_dict in f_in: if int(spectrum_dict.get('msLevel', -1)) == 2: # USI-inspired cluster identifier. scan_nr = int(spectrum_dict['id']) spectrum_dict['id'] = f'{filename}:scan:{scan_nr}' try: yield _parse_spectrum(spectrum_dict) except (ValueError, KeyError): pass except LxmlError as e: logger.warning('Failed to read file %s: %s', source, e) def _parse_spectrum(spectrum_dict: Dict) -> sus.MsmsSpectrum: """ Parse the Pyteomics cluster dict. Parameters ---------- spectrum_dict : Dict The Pyteomics cluster dict to be parsed. Returns ------- MsmsSpectrum The parsed cluster. """ spectrum_id = spectrum_dict['id'] mz_array = spectrum_dict['m/z array'] intensity_array = spectrum_dict['intensity array'] retention_time = spectrum_dict.get('retentionTime', -1) precursor_mz = spectrum_dict['precursorMz'][0]['precursorMz'] if 'precursorCharge' in spectrum_dict['precursorMz'][0]: precursor_charge = spectrum_dict['precursorMz'][0]['precursorCharge'] else: raise ValueError('Unknown precursor charge') return sus.MsmsSpectrum(spectrum_id, precursor_mz, precursor_charge, mz_array, intensity_array, None, retention_time)
0
0
0
2bb34ac2db8359edf6ca8b20a92cb720faf5a20c
6,236
py
Python
forastudent/person/forum_view.py
rautNitesh/job_system
6ea2cdde14c5147b7afb4d1d4aaf7d384486268c
[ "MIT" ]
1
2020-10-13T03:46:22.000Z
2020-10-13T03:46:22.000Z
forastudent/person/forum_view.py
rautNitesh/job_system
6ea2cdde14c5147b7afb4d1d4aaf7d384486268c
[ "MIT" ]
12
2021-03-30T14:08:41.000Z
2022-03-12T00:42:30.000Z
forastudent/person/forum_view.py
rautNitesh/job_system
6ea2cdde14c5147b7afb4d1d4aaf7d384486268c
[ "MIT" ]
1
2020-07-07T10:26:54.000Z
2020-07-07T10:26:54.000Z
from math import ceil from django import http from rest_framework.pagination import PageNumberPagination from rest_framework.viewsets import ModelViewSet from rest_framework.decorators import action from person.models import Post, Reply, ForumCategory, Person from person.serializers import PostSerializer, LogicalDeletePostSerializer, CommentSerializer, TopicSerializer # self-customized Pagination attributes # View for processing model Post # View for processing model reply # view for processing model topic
37.341317
129
0.707826
from math import ceil from django import http from rest_framework.pagination import PageNumberPagination from rest_framework.viewsets import ModelViewSet from rest_framework.decorators import action from person.models import Post, Reply, ForumCategory, Person from person.serializers import PostSerializer, LogicalDeletePostSerializer, CommentSerializer, TopicSerializer # self-customized Pagination attributes class MyPageNumber(PageNumberPagination): page_size = 8 page_size_query_param = 'size' page_query_param = 'page' max_page_size = None # View for processing model Post class PostView(ModelViewSet): queryset = Post.objects.all() serializer_class = PostSerializer # overwrite the function for GET request # return a pagination post list with json format @action(methods=['get'], detail=True) def getPostList(self, request, *args, **kwargs): postList = Post.objects.all().filter(isDeleted=False).order_by('-createdAt') count = ceil(postList.count()/8) pg = MyPageNumber() page_posts = pg.paginate_queryset(queryset=postList, request=request, view=self) postListSerializer = PostSerializer(instance=page_posts, many=True) for post in postListSerializer.data: queryUser = Person.objects.get(id=post['poster']) post['count'] = count post['username'] = queryUser.name return http.JsonResponse(postListSerializer.data, safe=False) # overwrite the function for GET request with another url # return a individual pagination post list with json format @action(methods=['get'], detail=True) def getMyPostsList(self, request, poster): myPostsList = Post.objects.all().filter(poster_id=poster).filter(isDeleted=False) count = ceil(myPostsList.count() / 8) pg = MyPageNumber() page_myPosts = pg.paginate_queryset(queryset=myPostsList, request=request, view=self) myPostListSerializer = PostSerializer(instance=page_myPosts, many=True) for myPost in myPostListSerializer.data: queryUser = Person.objects.get(id=myPost['poster']) myPost['count'] = count myPost['username'] = queryUser.name return http.JsonResponse(myPostListSerializer.data, safe=False) # overwrite the function for GET request with another url # return a single post record with json format @action(methods=['get'], detail=True) def getCurrentPost(self, request, pk): currentPost = Post.objects.get(id=pk) currentPostSerializer = PostSerializer(instance=currentPost) return http.JsonResponse(currentPostSerializer.data, safe=False) # overwrite delete function # apply a locally deleted method @action(methods=['delete'], detail=True) def deletePost(self, request, pk): post_01 = Post.objects.get(id=pk) post_02 = Post.objects.get(id=pk) post_02.isDeleted = True updated_post = LogicalDeletePostSerializer(instance=post_01, data=post_02.__dict__) updated_post.is_valid(raise_exception=True) updated_post.save() return http.HttpResponse(status=204) # View for processing model reply class CommentView(ModelViewSet): queryset = Reply.objects.all() serializer_class = CommentSerializer # overwrite get function # return a pagination comment list under a post with json format @action(methods=['get'], detail=True) def getCommentList(self, request, *args, **kwargs): post = request.GET.get('post') commentList = Reply.objects.all().filter(post_id=post).filter(parent_id=0).filter(isDeleted=False).order_by('-createdAt') count = ceil(commentList.count() / 8) pg = MyPageNumber() page_comments = pg.paginate_queryset(queryset=commentList, request=request, view=self) commentListSerializer = CommentSerializer(instance=page_comments, many=True) for comment in commentListSerializer.data: query_reply_to_user = Person.objects.get(id=comment['replyTo_id']) query_replies_number = Reply.objects.filter(parent_id=comment['id']).count() query_current_user_name = Person.objects.get(id=comment['poster']) comment['count'] = count comment['replyToName'] = query_reply_to_user.name comment['replyNumber'] = query_replies_number comment['currentName'] = query_current_user_name.name return http.JsonResponse(commentListSerializer.data, safe=False) # overwrite get function for another url # return a pagination comment list under another comment with json format @action(methods=['get'], detail=True) def getCurrentReplyList(self, request, *args, **kwargs): parent_id = request.GET.get('id') replyReplyList = Reply.objects.all().filter(parent_id=parent_id).filter(isDeleted=False).order_by('-createdAt') count = ceil(replyReplyList.count() / 8) pg = MyPageNumber() page_reply_reply = pg.paginate_queryset(queryset=replyReplyList, request=request, view=self) replyReplyListSerializer = CommentSerializer(instance=page_reply_reply, many=True) for replyReply in replyReplyListSerializer.data: query_reply_reply_to_user = Person.objects.get(id=replyReply['replyTo_id']) query_reply_current_user = Person.objects.get(id=replyReply['poster']) replyReply['count'] = count replyReply['replyReplyToName'] = query_reply_reply_to_user.name replyReply['replyReplyCurrentName'] = query_reply_current_user.name return http.JsonResponse(replyReplyListSerializer.data, safe=False) # view for processing model topic class TopicView(ModelViewSet): queryset = ForumCategory.objects.all() serializer_class = TopicSerializer # overwrite get function # return a topic list with json format @action(methods=['get'], detail=True) def getTopicList(self, request, *args, **kwargs): topicList = ForumCategory.objects.all() topicListSerializer = TopicSerializer(instance=topicList, many=True) return http.JsonResponse(topicListSerializer.data, safe=False)
4,055
1,571
88
7000a798809bded20344d85213ff9f9e4e52601b
1,771
py
Python
Structural/Flyweight/python/FlyWheight.py
Hkataya/design-patterns
cfdebd756a64ee682e90a707747ac4b973a27c55
[ "CC0-1.0" ]
294
2017-10-14T01:18:09.000Z
2022-03-25T12:11:27.000Z
Structural/Flyweight/python/FlyWheight.py
dsfb/design-patterns
7e8fd8157488777a97d33249782d8b751e80e5b5
[ "CC0-1.0" ]
68
2017-10-14T10:06:36.000Z
2021-10-05T07:12:01.000Z
Structural/Flyweight/python/FlyWheight.py
dsfb/design-patterns
7e8fd8157488777a97d33249782d8b751e80e5b5
[ "CC0-1.0" ]
329
2017-10-14T10:27:58.000Z
2021-11-13T11:51:29.000Z
if __name__ == "__main__": main()
26.833333
92
0.648221
class FlyWheight(): def __init__(self, shared_state): self.shared_state = shared_state class Context(): def __init__(self, unique_state, flywheight: FlyWheight): self.unique_state = unique_state self.flywheight = flywheight def __repr__(self): return "unique: %s - shared: %s" % (self.unique_state, self.flywheight.shared_state) class FlyWheightFactory(): def __init__(self): self.flywheights = [] def get_flyweight(self, shared_state) -> FlyWheight: flywheights = list(filter(lambda x: x.shared_state == shared_state, self.flywheights)) if len(flywheights) > 0: return flywheights[0] else: flywheight = FlyWheight(shared_state) self.flywheights.append(flywheight) return flywheight @property def total(self): return len(self.flywheights) class Client(): def __init__(self, flywheight_factory: FlyWheightFactory): self.flywheight_factory = flywheight_factory self.contexts = [] def get_context(self, unique_state, shared_state) -> Context: flywheight = self.flywheight_factory.get_flyweight(shared_state) context = Context(unique_state, flywheight) self.contexts.append(context) return context def main(): flywheight_factory = FlyWheightFactory() client = Client(flywheight_factory) shared_states = ['Alpha', 'Beta', 'Gamma'] unique_states = list(range(10)) contexts = [client.get_context(x, y) for x in unique_states for y in shared_states] print("Contexts:", len(contexts)) print("Flywheights:", flywheight_factory.total) if __name__ == "__main__": main()
1,388
87
249
0eee2137f04fdd8f534a676c62eaf75ebe9af0a0
4,443
py
Python
Python/_Movidius/Data.py
epicalyx/AML-Classifiers
051d33a6e458ad04548f056a6a3048ecf47c5293
[ "MIT" ]
1
2019-08-21T15:12:29.000Z
2019-08-21T15:12:29.000Z
Python/_Movidius/Data.py
epicalyx/AML-Classifiers
051d33a6e458ad04548f056a6a3048ecf47c5293
[ "MIT" ]
null
null
null
Python/_Movidius/Data.py
epicalyx/AML-Classifiers
051d33a6e458ad04548f056a6a3048ecf47c5293
[ "MIT" ]
1
2019-08-31T17:20:51.000Z
2019-08-31T17:20:51.000Z
################################################################################################## # # The MIT License (MIT) # # Peter Moss Acute Myeloid Leukemia Research Project # Copyright (C) 2018 Adam Milton-Barker (AdamMiltonBarker.com) # # 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. # # Title: Acute Myeloid Leukemia Movidius Classifier Data Class # Description: Class for sorting the data for the Acute Myeloid Leukemia Movidius Classifier. # Configuration: required/confs.json # Last Modified: 2018-12-23 # ################################################################################################## import os, sys, random from Classes.Helpers import Helpers from Classes.Data import Data as DataProcess ############################################################### # # Core Data class wrapper. # ############################################################### if __name__ == "__main__": ############################################################### # # Sorts the data ready for training # ############################################################### ProcessData = Data() ProcessData.sortData()
41.138889
102
0.574387
################################################################################################## # # The MIT License (MIT) # # Peter Moss Acute Myeloid Leukemia Research Project # Copyright (C) 2018 Adam Milton-Barker (AdamMiltonBarker.com) # # 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. # # Title: Acute Myeloid Leukemia Movidius Classifier Data Class # Description: Class for sorting the data for the Acute Myeloid Leukemia Movidius Classifier. # Configuration: required/confs.json # Last Modified: 2018-12-23 # ################################################################################################## import os, sys, random from Classes.Helpers import Helpers from Classes.Data import Data as DataProcess class Data(): ############################################################### # # Core Data class wrapper. # ############################################################### def __init__(self): ############################################################### # # Sets up all default requirements and placeholders # needed for this class. # ############################################################### self.Helpers = Helpers() self.confs = self.Helpers.loadConfs() self.logFile = self.Helpers.setLogFile(self.confs["Settings"]["Logs"]["DataLogDir"]) self.DataProcess = DataProcess() self.labelsToName = {} self.Helpers.logMessage(self.logFile, "init", "INFO", "Init complete") def sortData(self): ############################################################### # # Sorts the data # ############################################################### humanStart, clockStart = self.Helpers.timerStart() self.Helpers.logMessage(self.logFile, "sortData", "INFO", "Loading & preparing training data") dataPaths, classes = self.DataProcess.processFilesAndClasses() classId = [ int(i) for i in classes] classNamesToIds = dict(zip(classes, classId)) # Divide the training datasets into train and test numValidation = int(self.confs["Classifier"]["ValidationSize"] * len(dataPaths)) self.Helpers.logMessage(self.logFile, "sortData", "Validation Size", str(numValidation)) self.Helpers.logMessage(self.logFile, "sortData", "Class Size", str(len(classes))) random.seed(self.confs["Classifier"]["RandomSeed"]) random.shuffle(dataPaths) trainingFiles = dataPaths[numValidation:] validationFiles = dataPaths[:numValidation] # Convert the training and validation sets self.DataProcess.convertToTFRecord('train', trainingFiles, classNamesToIds) self.DataProcess.convertToTFRecord('validation', validationFiles, classNamesToIds) # Write the labels to file labelsToClassNames = dict(zip(classId, classes)) self.DataProcess.writeLabels(labelsToClassNames) self.Helpers.logMessage(self.logFile, "sortData", "COMPLETE", "Completed sorting data!") if __name__ == "__main__": ############################################################### # # Sorts the data ready for training # ############################################################### ProcessData = Data() ProcessData.sortData()
2,163
-8
77
3fe5950b768aca8bc2bfe65c6bc3afa3e2e962a2
318
py
Python
prac/app1/migrations/0002_remove_comment_item_name.py
32-Adarsha/Shopping-Site-Django-Backend-
013b6593f98f7d0565c047d46b74f3a22620af31
[ "Unlicense" ]
1
2021-12-10T16:16:56.000Z
2021-12-10T16:16:56.000Z
prac/app1/migrations/0002_remove_comment_item_name.py
32-Adarsha/Shopping-Site-Django-Backend-
013b6593f98f7d0565c047d46b74f3a22620af31
[ "Unlicense" ]
null
null
null
prac/app1/migrations/0002_remove_comment_item_name.py
32-Adarsha/Shopping-Site-Django-Backend-
013b6593f98f7d0565c047d46b74f3a22620af31
[ "Unlicense" ]
null
null
null
# Generated by Django 3.2.8 on 2021-11-15 04:55 from django.db import migrations
17.666667
47
0.578616
# Generated by Django 3.2.8 on 2021-11-15 04:55 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('app1', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='comment', name='item_name', ), ]
0
212
23
feb9ced6fb55d2d8f9e10087092ee53d1de5ffd1
1,898
py
Python
api/app/main/service/token_service.py
Stevencibambo/face-detection-based-web
9e7d2d37977f242ef1ec8701ef61e8b79a64941b
[ "MIT" ]
null
null
null
api/app/main/service/token_service.py
Stevencibambo/face-detection-based-web
9e7d2d37977f242ef1ec8701ef61e8b79a64941b
[ "MIT" ]
null
null
null
api/app/main/service/token_service.py
Stevencibambo/face-detection-based-web
9e7d2d37977f242ef1ec8701ef61e8b79a64941b
[ "MIT" ]
null
null
null
# import the necessary package from app.main import db from app.main.service.user_service import get_a_user from app.main.model.tokens import Token from datetime import datetime def check_token(access_token): """check if the token is opened""" token = Token.check_opened_token_by_token(access_token) if token: response_object = { 'status': 'successful', 'message': "token's state opened", 'access_token': token.token } return response_object, 201 else: response_object = { "status": "fail", "message": "token's status close", "access_token": "" } return response_object, 501
29.65625
65
0.530032
# import the necessary package from app.main import db from app.main.service.user_service import get_a_user from app.main.model.tokens import Token from datetime import datetime def save_token(token): # token = Token(token=token) try: db.session.add(token) db.session.commit() except Exception as e: response_object = { 'status': 'fail', 'message': e } return response_object, 500 def check_token(access_token): """check if the token is opened""" token = Token.check_opened_token_by_token(access_token) if token: response_object = { 'status': 'successful', 'message': "token's state opened", 'access_token': token.token } return response_object, 201 else: response_object = { "status": "fail", "message": "token's status close", "access_token": "" } return response_object, 501 def token_is_opened(id): try: # get a user uid = int(id) if uid: # check if user don't have an opened session token = Token.check_opened_user_token(uid) if token: now = datetime.utcnow() timestamp = int(datetime.timestamp(now)) if (timestamp - token.start_on) > (45 * 60 * 60): # close first the opened token token.status = 0 token.end_on = timestamp db.session.commit() return False else: return True else: return False except Exception as e: response_object = { "status": "fail", "message": "error to close opened token", "error": e } return response_object, 501
1,140
0
46
f40d87a3418de3d5ebd83c246b98d27ee3ac24eb
4,380
py
Python
PYSEQM/seqm/seqm_functions/energy.py
roehr-lab/SFast-Singlet-Fission-adiabatic-basis-screening
dfda08400bb1328ce6cd45ac6b1dd3e7f9d7d4a6
[ "MIT" ]
null
null
null
PYSEQM/seqm/seqm_functions/energy.py
roehr-lab/SFast-Singlet-Fission-adiabatic-basis-screening
dfda08400bb1328ce6cd45ac6b1dd3e7f9d7d4a6
[ "MIT" ]
null
null
null
PYSEQM/seqm/seqm_functions/energy.py
roehr-lab/SFast-Singlet-Fission-adiabatic-basis-screening
dfda08400bb1328ce6cd45ac6b1dd3e7f9d7d4a6
[ "MIT" ]
null
null
null
import torch from .constants import a0 def elec_energy_isolated_atom(const, Z, uss, upp, gss, gpp, gsp, gp2, hsp): """ electrionc energy for a single atom #eisol in block.f or in calpar.f return Eiso, shape (natoms,) """ Eiso = uss*const.ussc[Z] \ + upp*const.uppc[Z] \ + gss*const.gssc[Z] \ + gpp*const.gppc[Z] \ + gsp*const.gspc[Z] \ + gp2*const.gp2c[Z] \ + hsp*const.hspc[Z] return Eiso def elec_energy(P,F,Hcore): """ Get the electronic energy P: density matrix, shape (nmol, molsize*4, molsize*4) F: fock matrix, shape same as P Hcore: Hcore matrix, shape (nmol, 4*molsize, 4*molsize) return Eelec : electronic energy, shape (nmol,) P, F: full, has upper and lower triangle Hcore : only have upper triangle as constructed from hcore.py """ h = Hcore.triu()+Hcore.triu(1).transpose(1,2) # Eelec = 0.5 * tr(P(Hcore+F)) # matmul # Eelec = 0.5 * \sum P*(H+F) # elementwise product Eelec = 0.5*torch.sum(P*(h+F),dim=(1,2)) return Eelec def pair_nuclear_energy(const, nmol, ni, nj, idxi, idxj, rij, gam, method='AM1', parameters=None): """ Compute Nuclear Energy method='MNDO', 'AM1', 'PM3' nmol : number of molecules pair_molid : molecule id for each pair, shape (npairs,) ni, nj: atomic number, shape (npairs,) rij: pair distance in atomic units, shape (npairs,) gam : (s^A s^A, s^B, s^B) = w[...,0,0], shape(npairs,): w ==> second return vaule of hcore parameters : tuple, (alpha,) or (alpha, K, L, M) alpha : shape (natoms,) K,L,M : guassian terms in PM3 or AM1, shape (natoms, 2 or 4) return nuclear interaction energy for each molecule, (nmol, ) """ rija=rij*a0 tore = const.tore alpha = parameters[0] t1 = tore[ni]*tore[nj]*gam #special case for C-H and O-H XH = ((ni==7) | (ni==8)) & (nj==1) t2 = torch.zeros_like(t1) tmp = torch.exp(-alpha[idxi]*rija) t2[~XH] = tmp[~XH] t2[XH] = tmp[XH]*rija[XH] t3 = torch.exp(-alpha[idxj]*rija) if method=='MNDO': #in mopac, rij is in unit of angstrom #EnucAB = torch.abs(t1*(1.0+t2+t3)) EnucAB = t1*(1.0+t2+t3) elif method=='PM3' or method=='AM1': #two gaussian terms for PM3 # 3~4 terms for AM1 _, K, L, M = parameters #K, L , M shape (natoms,2 or 4) t4 = tore[ni]*tore[nj]/rija t5 = torch.sum(K[idxi]*torch.exp(-L[idxi]*(rija.reshape((-1,1))-M[idxi])**2),dim=1) t6 = torch.sum(K[idxj]*torch.exp(-L[idxj]*(rija.reshape((-1,1))-M[idxj])**2),dim=1) EnucAB = t1*(1.0+t2+t3) + t4*(t5 + t6) else: raise ValueError("Supported Method: MNDO, AM1, PM3") return EnucAB def total_energy(nmol, pair_molid, EnucAB, Eelec): """ total energy for each molecule total energy E_tot^mol= Eelec + \sum{pair A,B,A<B} E_nuc^AB #nuclear energy between pair of atom A and B: E_nuc^AB as index_add is expensive, there is no need to do this during training EnucAB :computed from pair_nuclear_energy, shape (npairs,) pair_molid : molecule id for each pair Eelec : electronic energy for each molecule, computed from elec_energy, shape (nmol) """ Enuc = torch.zeros((nmol,),dtype=EnucAB.dtype, device=EnucAB.device) Enuc.index_add_(0,pair_molid, EnucAB) Etot = Eelec + Enuc return Etot, Enuc def heat_formation(const, nmol, atom_molid, Z, Etot, Eiso, flag=True): """ get the heat of formation for each molecule return Hf : shape (nmol,) #heat of formation : delta H_f^mol #electronic energies of isolated atom: E_el^A #experimental heat of formation of isolatied atom : delta_H_f^A # delta H_f^mol = E_tot^mol - \sum_A E_el^A + \sum_A delta_H_f^A #flag: True, return Hf = Etot - Eiso_sum + eheat_sum False, return Etot - Eiso_sum """ # electronic energy for isolated atom, sum for each molecule Eiso_sum = torch.zeros_like(Etot) Eiso_sum.index_add_(0,atom_molid,Eiso) if flag: # experimental heat of formation for each atom, sum for each molecule eheat_sum = torch.zeros_like(Etot) eheat_sum.index_add_(0,atom_molid,const.eheat[Z]) #Hf = Etot - Eiso_sum + eheat_sum return Etot - Eiso_sum + eheat_sum else: return Etot - Eiso_sum
36.806723
98
0.61895
import torch from .constants import a0 def elec_energy_isolated_atom(const, Z, uss, upp, gss, gpp, gsp, gp2, hsp): """ electrionc energy for a single atom #eisol in block.f or in calpar.f return Eiso, shape (natoms,) """ Eiso = uss*const.ussc[Z] \ + upp*const.uppc[Z] \ + gss*const.gssc[Z] \ + gpp*const.gppc[Z] \ + gsp*const.gspc[Z] \ + gp2*const.gp2c[Z] \ + hsp*const.hspc[Z] return Eiso def elec_energy(P,F,Hcore): """ Get the electronic energy P: density matrix, shape (nmol, molsize*4, molsize*4) F: fock matrix, shape same as P Hcore: Hcore matrix, shape (nmol, 4*molsize, 4*molsize) return Eelec : electronic energy, shape (nmol,) P, F: full, has upper and lower triangle Hcore : only have upper triangle as constructed from hcore.py """ h = Hcore.triu()+Hcore.triu(1).transpose(1,2) # Eelec = 0.5 * tr(P(Hcore+F)) # matmul # Eelec = 0.5 * \sum P*(H+F) # elementwise product Eelec = 0.5*torch.sum(P*(h+F),dim=(1,2)) return Eelec def pair_nuclear_energy(const, nmol, ni, nj, idxi, idxj, rij, gam, method='AM1', parameters=None): """ Compute Nuclear Energy method='MNDO', 'AM1', 'PM3' nmol : number of molecules pair_molid : molecule id for each pair, shape (npairs,) ni, nj: atomic number, shape (npairs,) rij: pair distance in atomic units, shape (npairs,) gam : (s^A s^A, s^B, s^B) = w[...,0,0], shape(npairs,): w ==> second return vaule of hcore parameters : tuple, (alpha,) or (alpha, K, L, M) alpha : shape (natoms,) K,L,M : guassian terms in PM3 or AM1, shape (natoms, 2 or 4) return nuclear interaction energy for each molecule, (nmol, ) """ rija=rij*a0 tore = const.tore alpha = parameters[0] t1 = tore[ni]*tore[nj]*gam #special case for C-H and O-H XH = ((ni==7) | (ni==8)) & (nj==1) t2 = torch.zeros_like(t1) tmp = torch.exp(-alpha[idxi]*rija) t2[~XH] = tmp[~XH] t2[XH] = tmp[XH]*rija[XH] t3 = torch.exp(-alpha[idxj]*rija) if method=='MNDO': #in mopac, rij is in unit of angstrom #EnucAB = torch.abs(t1*(1.0+t2+t3)) EnucAB = t1*(1.0+t2+t3) elif method=='PM3' or method=='AM1': #two gaussian terms for PM3 # 3~4 terms for AM1 _, K, L, M = parameters #K, L , M shape (natoms,2 or 4) t4 = tore[ni]*tore[nj]/rija t5 = torch.sum(K[idxi]*torch.exp(-L[idxi]*(rija.reshape((-1,1))-M[idxi])**2),dim=1) t6 = torch.sum(K[idxj]*torch.exp(-L[idxj]*(rija.reshape((-1,1))-M[idxj])**2),dim=1) EnucAB = t1*(1.0+t2+t3) + t4*(t5 + t6) else: raise ValueError("Supported Method: MNDO, AM1, PM3") return EnucAB def total_energy(nmol, pair_molid, EnucAB, Eelec): """ total energy for each molecule total energy E_tot^mol= Eelec + \sum{pair A,B,A<B} E_nuc^AB #nuclear energy between pair of atom A and B: E_nuc^AB as index_add is expensive, there is no need to do this during training EnucAB :computed from pair_nuclear_energy, shape (npairs,) pair_molid : molecule id for each pair Eelec : electronic energy for each molecule, computed from elec_energy, shape (nmol) """ Enuc = torch.zeros((nmol,),dtype=EnucAB.dtype, device=EnucAB.device) Enuc.index_add_(0,pair_molid, EnucAB) Etot = Eelec + Enuc return Etot, Enuc def heat_formation(const, nmol, atom_molid, Z, Etot, Eiso, flag=True): """ get the heat of formation for each molecule return Hf : shape (nmol,) #heat of formation : delta H_f^mol #electronic energies of isolated atom: E_el^A #experimental heat of formation of isolatied atom : delta_H_f^A # delta H_f^mol = E_tot^mol - \sum_A E_el^A + \sum_A delta_H_f^A #flag: True, return Hf = Etot - Eiso_sum + eheat_sum False, return Etot - Eiso_sum """ # electronic energy for isolated atom, sum for each molecule Eiso_sum = torch.zeros_like(Etot) Eiso_sum.index_add_(0,atom_molid,Eiso) if flag: # experimental heat of formation for each atom, sum for each molecule eheat_sum = torch.zeros_like(Etot) eheat_sum.index_add_(0,atom_molid,const.eheat[Z]) #Hf = Etot - Eiso_sum + eheat_sum return Etot - Eiso_sum + eheat_sum else: return Etot - Eiso_sum
0
0
0
4224f26cc7a0ac2b792ba98188c1c53c1d78548e
463
py
Python
test/generate/autotest/66_67_XRL_A_Ri.py
Aimini/hm-51
2d46323388a0679b2f99d1a33f5a0d55a5f838e6
[ "MIT" ]
null
null
null
test/generate/autotest/66_67_XRL_A_Ri.py
Aimini/hm-51
2d46323388a0679b2f99d1a33f5a0d55a5f838e6
[ "MIT" ]
20
2020-01-13T04:19:37.000Z
2020-02-12T14:25:44.000Z
test/generate/autotest/66_67_XRL_A_Ri.py
Aimini/hm-51
2d46323388a0679b2f99d1a33f5a0d55a5f838e6
[ "MIT" ]
null
null
null
######################################################### # 2020-01-23 12:41:37 # AI # ins: XRL A, @Ri ######################################################### from .common.INS_XXX_A_Ri import XXX_A_Ri from ..asmconst import * p = XRL_A_Ri().gen(0, 15, 1)
23.15
57
0.455724
######################################################### # 2020-01-23 12:41:37 # AI # ins: XRL A, @Ri ######################################################### from .common.INS_XXX_A_Ri import XXX_A_Ri from ..asmconst import * class XRL_A_Ri(XXX_A_Ri): def __init__(self): super().__init__("XRL") def op_func(self, B): A = self.ram.get_direct(SFR_A.x) self.ram.set_direct(SFR_A.x, A ^ B) p = XRL_A_Ri().gen(0, 15, 1)
115
4
76
dbeec67ba9d7093ff775b134cff749dd0646925c
13,350
py
Python
tests/test_usecases.py
ajhynes7/datatest
78742e98de992807286655f5685a2dc33a7b452e
[ "Apache-2.0" ]
277
2016-05-12T13:22:49.000Z
2022-03-11T00:18:32.000Z
tests/test_usecases.py
ajhynes7/datatest
78742e98de992807286655f5685a2dc33a7b452e
[ "Apache-2.0" ]
57
2016-05-18T01:03:32.000Z
2022-02-17T13:48:43.000Z
tests/test_usecases.py
ajhynes7/datatest
78742e98de992807286655f5685a2dc33a7b452e
[ "Apache-2.0" ]
16
2016-05-22T11:35:19.000Z
2021-12-01T19:41:42.000Z
# -*- coding: utf-8 -*- """A handful of integration tests to check for idiomatic use cases that we want make sure are as convinient as possible for users. """ from . import _unittest as unittest import math import datetime import datatest try: import squint except ImportError: squint = None try: import pandas except ImportError: pandas = None try: import numpy except ImportError: numpy = None # Remove for datatest version 0.9.8. import warnings warnings.filterwarnings('ignore', message='subset and superset warning') @unittest.skipUnless(squint, 'requires squint') class TestAcceptedKeysDecorator(unittest.TestCase): """The accepted.keys() method should be usable as a decorator.""" class TestAcceptedArgsDecorator(unittest.TestCase): """The accepted.args() method should be usable as a decorator.""" def test_single_arg_tuple(self): """Compare with `test_multiple_args()` wrapping and unwrapping.""" Invalid = datatest.Invalid ValidationError = datatest.ValidationError # Check args where first arg is a tuple: with self.assertRaises(ValidationError) as cm: @datatest.accepted.args # <- Use as decorator! with args_is_known_tuple: raise ValidationError([Invalid(('a', 'A')), Invalid(('c', 'C'))]) self.assertEqual(cm.exception.differences, [Invalid(('c', 'C'))]) def test_multiple_args(self): """Compare with `test_single_arg_tuple()` wrapping and unwrapping.""" Invalid = datatest.Invalid ValidationError = datatest.ValidationError with self.assertRaises(ValidationError) as cm: @datatest.accepted.args # <- Use as decorator! with args_is_known_tuple: raise ValidationError([Invalid('a', 'A'), Invalid('c', 'C')]) self.assertEqual(cm.exception.differences, [Invalid('c', 'C')])
35.131579
83
0.597228
# -*- coding: utf-8 -*- """A handful of integration tests to check for idiomatic use cases that we want make sure are as convinient as possible for users. """ from . import _unittest as unittest import math import datetime import datatest try: import squint except ImportError: squint = None try: import pandas except ImportError: pandas = None try: import numpy except ImportError: numpy = None # Remove for datatest version 0.9.8. import warnings warnings.filterwarnings('ignore', message='subset and superset warning') class TestNamespaces(unittest.TestCase): def test_root_namespace(self): """Make sure important objects are in root namespace for easy access. """ # Core objects. self.assertTrue(hasattr(datatest, 'validate')) self.assertTrue(hasattr(datatest, 'accepted')) # Internal sub-module. self.assertTrue(hasattr(datatest, 'requirements')) # Error and difference objects. self.assertTrue(hasattr(datatest, 'ValidationError')) self.assertTrue(hasattr(datatest, 'Missing')) self.assertTrue(hasattr(datatest, 'Extra')) self.assertTrue(hasattr(datatest, 'Deviation')) self.assertTrue(hasattr(datatest, 'Invalid')) # Data handling support. self.assertTrue(hasattr(datatest, 'working_directory')) self.assertTrue(hasattr(datatest, 'RepeatingContainer')) # Unittest-style support. self.assertTrue(hasattr(datatest, 'DataTestCase')) self.assertTrue(hasattr(datatest, 'main')) self.assertTrue(hasattr(datatest, 'mandatory')) def test_pytest_flag(self): """Pytest should not try to rewrite the datatest module itself. If Pytest does try to rewrite datatest, it will give a warning in cases where datatest is imported before asserting rewriting begins. But there's no reason to rewrite datatest in the first place so pytest shouldn't even be trying this. See "PYTEST_DONT_REWRITE" in the Pytest documentation: https://docs.pytest.org/latest/reference.html """ self.assertIn('PYTEST_DONT_REWRITE', datatest.__doc__) @unittest.skipUnless(squint, 'requires squint') class TestSquintIdioms(unittest.TestCase): @classmethod def setUpClass(cls): cls.select_a = squint.Select([ ['A', 'B', 'C'], ['x', 1, 100], ['y', 2, 200], ['z', 3, 300], ]) cls.select_b = squint.Select([ ['A', 'B'], ['x', 1], ['y', 2], ['z', 3], ]) def setUp(self): if not hasattr(unittest.TestCase, 'setUpClass'): self.setUpClass() # setUpClass() is new in Python 2.7 and 3.2 def test_compare_fieldnames(self): """Should be able to compare ``fieldnames`` between Selects by simply casting the *requirement* as a set and comparing it directly against the ``fieldnames`` parameter of the other Select. """ a = self.select_a b = self.select_b # A case we want to optimize. datatest.validate(a.fieldnames, set(a.fieldnames)) # A case we want to optimize. with datatest.accepted(datatest.Extra('C')): datatest.validate(a.fieldnames, set(b.fieldnames)) def test_compare_rows(self): """Should be able to compare rows by calling a Select using its own fieldnames. """ a = self.select_a b = self.select_b # A case we want to optimize. datatest.validate(a(a.fieldnames), a(a.fieldnames)) # A case we want to optimize (using ordered intersection of fieldnames). common_fields = tuple(x for x in a.fieldnames if x in b.fieldnames) datatest.validate(a(common_fields), b(common_fields)) class TestValidateIdioms(unittest.TestCase): def test_concise_reference_testing(self): """Should be able to use a two-item RepeatingContainer to easily compare results by unpacking the RepeatingContainer directly in to the validate() function call. """ compare = datatest.RepeatingContainer(['foo', 'FOO']) datatest.validate(*compare.lower()) def test_mapping_of_sequences_for_order(self): """Should be able to compare mapping of sequences for order and accept differences across keys (e.g., with accepted.extra() and accepted.missing()). """ # Pull objects into local name space to improve readability. validate = datatest.validation.validate accepted = datatest.accepted ValidationError = datatest.ValidationError Missing = datatest.Missing Extra = datatest.Extra requirement = ['a', 'b', 'c'] data = { 'foo': ['a', 'x', 'c'], # -> [Missing((1, 'b')), Extra((1, 'x'))] 'bar': ['a', 'b'], # -> [Missing((2, 'c'))] 'baz': ['a', 'b', 'c', 'd'], # -> [Extra((3, 'd'))] } expected_extras = accepted({ 'foo': [Extra((1, 'x'))], 'baz': [Extra((3, 'd'))], }) with accepted(Missing) | expected_extras: validate.order(data, requirement) def test_enumerate_to_dict(self): """Enumerations should be interpreted as mappings before validation.""" validate = datatest.validate ValidationError = datatest.ValidationError Invalid = datatest.Invalid Missing = datatest.Missing with self.assertRaises(ValidationError) as cm: data = ['a', 'b', 'x', 'd'] requirement = ['a', 'b', 'c', 'd', 'e'] validate(enumerate(data), enumerate(requirement)) differences = cm.exception.differences expected = { 2: Invalid('x', expected='c'), 4: Missing('e'), } self.assertEqual(differences, expected) class TestAcceptedKeysDecorator(unittest.TestCase): """The accepted.keys() method should be usable as a decorator.""" def test_single_value_keys(self): Missing = datatest.Missing ValidationError = datatest.ValidationError with self.assertRaises(ValidationError) as cm: @datatest.accepted.keys # <- Use as decorator! def key_is_vowel(key): return key in set(['a', 'e', 'i', 'o', 'u']) with key_is_vowel: raise ValidationError({'a': Missing(1), 'b': Missing(2)}) self.assertEqual(cm.exception.differences, {'b': Missing(2)}) def test_composite_keys(self): Missing = datatest.Missing ValidationError = datatest.ValidationError with self.assertRaises(ValidationError) as cm: @datatest.accepted.keys # <- Use as decorator! def key_is_known_tuple(key): return key in set([('a', 1), ('b', 2)]) with key_is_known_tuple: raise ValidationError({('a', 1): Missing(1), ('c', 3): Missing(3)}) self.assertEqual(cm.exception.differences, {('c', 3): Missing(3)}) class TestAcceptedArgsDecorator(unittest.TestCase): """The accepted.args() method should be usable as a decorator.""" def test_single_arg(self): Missing = datatest.Missing ValidationError = datatest.ValidationError # Check single-value args: with self.assertRaises(ValidationError) as cm: @datatest.accepted.args # <- Use as decorator! def arg_is_vowel(arg): return arg in set(['a', 'e', 'i', 'o', 'u']) with arg_is_vowel: raise ValidationError([Missing('a'), Missing('b')]) self.assertEqual(cm.exception.differences, [Missing('b')]) def test_single_arg_tuple(self): """Compare with `test_multiple_args()` wrapping and unwrapping.""" Invalid = datatest.Invalid ValidationError = datatest.ValidationError # Check args where first arg is a tuple: with self.assertRaises(ValidationError) as cm: @datatest.accepted.args # <- Use as decorator! def args_is_known_tuple(args): return args in set([('a', 'A'), ('b', 'B')]) with args_is_known_tuple: raise ValidationError([Invalid(('a', 'A')), Invalid(('c', 'C'))]) self.assertEqual(cm.exception.differences, [Invalid(('c', 'C'))]) def test_multiple_args(self): """Compare with `test_single_arg_tuple()` wrapping and unwrapping.""" Invalid = datatest.Invalid ValidationError = datatest.ValidationError with self.assertRaises(ValidationError) as cm: @datatest.accepted.args # <- Use as decorator! def args_is_known_tuple(args): return args in set([('a', 'A'), ('b', 'B')]) with args_is_known_tuple: raise ValidationError([Invalid('a', 'A'), Invalid('c', 'C')]) self.assertEqual(cm.exception.differences, [Invalid('c', 'C')]) class TestNanHandling(unittest.TestCase): def test_accepting_builtin(self): data = ['a', 'a', 'b', 'b', float('nan')] with datatest.accepted(datatest.Invalid(float('nan'))): datatest.validate(data, str) with datatest.accepted(datatest.Extra(float('nan'))): datatest.validate(data, set(['a', 'b'])) with datatest.accepted.args(float('nan')): datatest.validate(data, set(['a', 'b'])) @unittest.skipUnless(pandas, 'requires pandas') def test_pandas_requirement(self): """Pandas objects should work as data and requirements.""" # Series with specified index. series_index = pandas.Series([1, 2, 3], index=['x', 'y', 'z']) datatest.validate(series_index, series_index) # Series with default RangeIndex. series_rangeindex = pandas.Series([1, 2, 3]) datatest.validate(series_rangeindex, series_rangeindex) # DataFrame with specified index. df_index = pandas.DataFrame( data=[['foo', 1], ['bar', 2], ['baz', 3]], columns=['B', 'C'], index=['x', 'y', 'z'], ) datatest.validate(df_index, df_index) # DataFrame with default RangeIndex. df_rangeindex = pandas.DataFrame( data=[['foo', 1], ['bar', 2], ['baz', 3]], columns=['B', 'C'], ) datatest.validate(df_rangeindex, df_rangeindex) # Index index = pandas.Index(['x', 'y', 'z']) datatest.validate(index, index) # MultiIndex multi = pandas.MultiIndex.from_tuples( tuples=[('x', 'foo'), ('y', 'bar'), ('z', 'baz')], names=('A', 'B'), ) datatest.validate(multi, multi) @unittest.skipUnless(pandas and numpy, 'requires pandas and numpy') def test_accepting_pandas_numpy(self): data = pandas.Series([1, 1, 2, 2, numpy.float64('nan')], dtype='float64') with datatest.accepted(datatest.Extra(numpy.float64('nan'))): datatest.validate(data, set([1.0, 2.0])) with datatest.accepted(datatest.Extra(numpy.nan)): datatest.validate(data, set([1.0, 2.0])) with datatest.accepted(datatest.Extra(float('nan'))): datatest.validate(data, set([1.0, 2.0])) def test_validating_builtin(self): """NaN values do not compare as equal, to use them for set membership or other types of validation, replace the NaN with a token that can be tested for equality, membership, etc. """ nantoken = type( 'nantoken', (object,), {'__repr__': (lambda x: '<nantoken>')}, )() data = ['a', 'a', 'b', 'b', float('nan')] def nan_to_token(x): try: return nantoken if math.isnan(x) else x except TypeError: return x data = [nan_to_token(x) for x in data] datatest.validate.superset(data, set(['a', 'b', nantoken])) @unittest.skipUnless(pandas and numpy, 'requires pandas and numpy') def test_validating_pandas_numpy(self): # While the following example works for 'object' dtypes, the # pattern should be avoided because it is not reliable when # working with other dtypes. DO NOT use it in practice: # # data = pandas.Series(['a', 'a', 'b', 'b', numpy.nan], dtype='object') # datatest.validate.superset(data, set(['a', 'b', numpy.nan])) # A more reliable method is to replace NaNs with a token value: data = pandas.Series([1, 1, 2, 2, numpy.float64('nan')], dtype='float64') nantoken = type( 'nantoken', (object,), {'__repr__': (lambda x: '<nantoken>')}, )() data = data.fillna(nantoken) # <- Normalized! datatest.validate.superset(data, set([1, 2, nantoken])) class TestDateHandling(unittest.TestCase): def test_timedelta_tolerance(self): data = datetime.datetime(1989, 2, 24, hour=10, minute=30) requirement = datetime.datetime(1989, 2, 24, hour=11, minute=30) with datatest.accepted.tolerance(datetime.timedelta(hours=1)): datatest.validate(data, requirement)
4,107
7,035
289
c7101538571949bc2d9a16b432738d706b6d0506
968
py
Python
test/test_day03.py
frangiz/AdventOfCode2018
dffbc0a8467d3c31678d9719923c461b0b12d67f
[ "MIT" ]
null
null
null
test/test_day03.py
frangiz/AdventOfCode2018
dffbc0a8467d3c31678d9719923c461b0b12d67f
[ "MIT" ]
null
null
null
test/test_day03.py
frangiz/AdventOfCode2018
dffbc0a8467d3c31678d9719923c461b0b12d67f
[ "MIT" ]
null
null
null
"""The tests for day03.""" from days import day03 from ddt import ddt, data, unpack import unittest import helpers @ddt
31.225806
69
0.628099
"""The tests for day03.""" from days import day03 from ddt import ddt, data, unpack import unittest import helpers @ddt class MyTestCase(unittest.TestCase): # noqa D101 @data( [['#1 @ 1,3: 4x4', '#2 @ 3,1: 4x4', '#3 @ 5,5: 2x2'], '4']) @unpack def test_example_a(self, test_input, expected): # noqa D102 result = day03.part_a(test_input) self.assertEqual(result, expected) def test_answer_part_a(self): # noqa D102 result = day03.part_a(helpers.get_file_contents('day03.txt')) self.assertEqual(result, '98005') @data( [['#1 @ 1,3: 4x4', '#2 @ 3,1: 4x4', '#3 @ 5,5: 2x2'], '3']) @unpack def test_example_b(self, test_input, expected): # noqa D102 result = day03.part_b(test_input) self.assertEqual(result, expected) def test_answer_part_b(self): # noqa D102 result = day03.part_b(helpers.get_file_contents('day03.txt')) self.assertEqual(result, '331')
508
316
22
67e483507c8bb1197e202652649ae79f6a212d7d
11,767
py
Python
skbio/util/_decorator.py
jairideout/scikit-bio
81a1ce5acb434603c537f832caee64a76db19190
[ "BSD-3-Clause" ]
null
null
null
skbio/util/_decorator.py
jairideout/scikit-bio
81a1ce5acb434603c537f832caee64a76db19190
[ "BSD-3-Clause" ]
null
null
null
skbio/util/_decorator.py
jairideout/scikit-bio
81a1ce5acb434603c537f832caee64a76db19190
[ "BSD-3-Clause" ]
null
null
null
# ---------------------------------------------------------------------------- # Copyright (c) 2013--, scikit-bio development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. # ---------------------------------------------------------------------------- from __future__ import absolute_import, division, print_function import warnings import textwrap import decorator from ._exception import OverrideError class _state_decorator(object): """ Base class for decorators of all public functionality. """ _required_kwargs = () def _get_indentation_level(self, docstring_lines, default_existing_docstring=4, default_no_existing_docstring=0): """ Determine the level of indentation of the docstring to match it. The indented content after the first line of a docstring can differ based on the nesting of the functionality being documented. For example, a top-level function may have its "Parameters" section indented four-spaces, but a method nested under a class may have its "Parameters" section indented eight spaces. This function determines the indentation level of the first non-whitespace line following the initial summary line. """ # if there is no existing docstring, return the corresponding default if len(docstring_lines) == 0: return default_no_existing_docstring # if there is an existing docstring with only a single line, return # the corresponding default if len(docstring_lines) == 1: return default_existing_docstring # find the first non-blank line (after the initial summary line) and # return the number of leading spaces on that line for line in docstring_lines[1:]: if len(line.strip()) == 0: # ignore blank lines continue else: return len(line) - len(line.lstrip()) # if there is an existing docstring with only a single non-whitespace # line, return the corresponding default return default_existing_docstring class stable(_state_decorator): """ State decorator indicating stable functionality. Used to indicate that public functionality is considered ``stable``, meaning that its API will be backward compatible unless it is deprecated. Decorating functionality as stable will update its doc string to indicate the first version of scikit-bio when the functionality was considered stable. Parameters ---------- as_of : str First release version where functionality is considered to be stable. See Also -------- experimental deprecated Examples -------- >>> @stable(as_of='0.3.0') ... def f_stable(): ... \"\"\" An example stable function. ... \"\"\" ... pass >>> help(f_stable) Help on function f_stable in module skbio.util._decorator: <BLANKLINE> f_stable() An example stable function. <BLANKLINE> State: Stable as of 0.3.0. <BLANKLINE> """ _required_kwargs = ('as_of', ) class experimental(_state_decorator): """ State decorator indicating experimental functionality. Used to indicate that public functionality is considered experimental, meaning that its API is subject to change or removal with little or (rarely) no warning. Decorating functionality as experimental will update its doc string to indicate the first version of scikit-bio when the functionality was considered experimental. Parameters ---------- as_of : str First release version where feature is considered to be experimental. See Also -------- stable deprecated Examples -------- >>> @experimental(as_of='0.3.0') ... def f_experimental(): ... \"\"\" An example experimental function. ... \"\"\" ... pass >>> help(f_experimental) Help on function f_experimental in module skbio.util._decorator: <BLANKLINE> f_experimental() An example experimental function. <BLANKLINE> State: Experimental as of 0.3.0. <BLANKLINE> """ _required_kwargs = ('as_of', ) class deprecated(_state_decorator): """ State decorator indicating deprecated functionality. Used to indicate that a public class or function is deprecated, meaning that its API will be removed in a future version of scikit-bio. Decorating functionality as deprecated will update its doc string to indicate the first version of scikit-bio when the functionality was deprecated, the first version of scikit-bio when the functionality will no longer exist, and the reason for deprecation of the API. It will also cause calls to the API to raise a ``DeprecationWarning``. Parameters ---------- as_of : str First development version where feature is considered to be deprecated. until : str First release version where feature will no longer exist. reason : str Brief description of why the API is deprecated. See Also -------- stable experimental Examples -------- >>> @deprecated(as_of='0.3.0', until='0.3.3', ... reason='Use skbio.g().') ... def f_deprecated(x, verbose=False): ... \"\"\" An example deprecated function. ... \"\"\" ... pass >>> help(f_deprecated) Help on function f_deprecated in module skbio.util._decorator: <BLANKLINE> f_deprecated(x, verbose=False) An example deprecated function. <BLANKLINE> .. note:: Deprecated as of 0.3.0 for removal in 0.3.3. Use skbio.g(). <BLANKLINE> """ _required_kwargs = ('as_of', 'until', 'reason') # Adapted from http://stackoverflow.com/a/8313042/579416 def overrides(interface_class): """Decorator for class-level members. Used to indicate that a member is being overridden from a specific parent class. If the member does not have a docstring, it will pull one from the parent class. When chaining decorators, this should be first as it is relatively nondestructive. Parameters ---------- interface_class : class The class which has a member overridden by the decorated member. Returns ------- function The function is not changed or replaced. Raises ------ OverrideError If the `interface_class` does not possess a member of the same name as the decorated member. """ return overrider class classproperty(property): """Decorator for class-level properties. Supports read access only. The property will be read-only within an instance. However, the property can always be redefined on the class, since Python classes are mutable. Parameters ---------- func : function Method to make a class property. Returns ------- property Decorated method. Raises ------ AttributeError If the property is set on an instance. """
34.710914
79
0.624968
# ---------------------------------------------------------------------------- # Copyright (c) 2013--, scikit-bio development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. # ---------------------------------------------------------------------------- from __future__ import absolute_import, division, print_function import warnings import textwrap import decorator from ._exception import OverrideError class _state_decorator(object): """ Base class for decorators of all public functionality. """ _required_kwargs = () def _get_indentation_level(self, docstring_lines, default_existing_docstring=4, default_no_existing_docstring=0): """ Determine the level of indentation of the docstring to match it. The indented content after the first line of a docstring can differ based on the nesting of the functionality being documented. For example, a top-level function may have its "Parameters" section indented four-spaces, but a method nested under a class may have its "Parameters" section indented eight spaces. This function determines the indentation level of the first non-whitespace line following the initial summary line. """ # if there is no existing docstring, return the corresponding default if len(docstring_lines) == 0: return default_no_existing_docstring # if there is an existing docstring with only a single line, return # the corresponding default if len(docstring_lines) == 1: return default_existing_docstring # find the first non-blank line (after the initial summary line) and # return the number of leading spaces on that line for line in docstring_lines[1:]: if len(line.strip()) == 0: # ignore blank lines continue else: return len(line) - len(line.lstrip()) # if there is an existing docstring with only a single non-whitespace # line, return the corresponding default return default_existing_docstring def _update_docstring(self, docstring, state_desc, state_desc_prefix='State: '): # Hande the case of no initial docstring if docstring is None: return "%s%s" % (state_desc_prefix, state_desc) docstring_lines = docstring.split('\n') docstring_content_indentation = \ self._get_indentation_level(docstring_lines) # wrap lines at 79 characters, accounting for the length of # docstring_content_indentation and start_desc_prefix len_state_desc_prefix = len(state_desc_prefix) wrap_at = 79 - (docstring_content_indentation + len_state_desc_prefix) state_desc_lines = textwrap.wrap(state_desc, wrap_at) # The first line of the state description should start with # state_desc_prefix, while the others should start with spaces to align # the text in this section. This is for consistency with numpydoc # formatting of deprecation notices, which are done using the note # Sphinx directive. state_desc_lines[0] = '%s%s%s' % (' ' * docstring_content_indentation, state_desc_prefix, state_desc_lines[0]) header_spaces = ' ' * (docstring_content_indentation + len_state_desc_prefix) for i, line in enumerate(state_desc_lines[1:], 1): state_desc_lines[i] = '%s%s' % (header_spaces, line) new_doc_lines = '\n'.join(state_desc_lines) docstring_lines[0] = '%s\n\n%s' % (docstring_lines[0], new_doc_lines) return '\n'.join(docstring_lines) def _validate_kwargs(self, **kwargs): for required_kwarg in self._required_kwargs: if required_kwarg not in kwargs: raise ValueError('%s decorator requires parameter: %s' % (self.__class__, required_kwarg)) class stable(_state_decorator): """ State decorator indicating stable functionality. Used to indicate that public functionality is considered ``stable``, meaning that its API will be backward compatible unless it is deprecated. Decorating functionality as stable will update its doc string to indicate the first version of scikit-bio when the functionality was considered stable. Parameters ---------- as_of : str First release version where functionality is considered to be stable. See Also -------- experimental deprecated Examples -------- >>> @stable(as_of='0.3.0') ... def f_stable(): ... \"\"\" An example stable function. ... \"\"\" ... pass >>> help(f_stable) Help on function f_stable in module skbio.util._decorator: <BLANKLINE> f_stable() An example stable function. <BLANKLINE> State: Stable as of 0.3.0. <BLANKLINE> """ _required_kwargs = ('as_of', ) def __init__(self, *args, **kwargs): self._validate_kwargs(**kwargs) self.as_of = kwargs['as_of'] def __call__(self, func): state_desc = 'Stable as of %s.' % self.as_of func.__doc__ = self._update_docstring(func.__doc__, state_desc) return func class experimental(_state_decorator): """ State decorator indicating experimental functionality. Used to indicate that public functionality is considered experimental, meaning that its API is subject to change or removal with little or (rarely) no warning. Decorating functionality as experimental will update its doc string to indicate the first version of scikit-bio when the functionality was considered experimental. Parameters ---------- as_of : str First release version where feature is considered to be experimental. See Also -------- stable deprecated Examples -------- >>> @experimental(as_of='0.3.0') ... def f_experimental(): ... \"\"\" An example experimental function. ... \"\"\" ... pass >>> help(f_experimental) Help on function f_experimental in module skbio.util._decorator: <BLANKLINE> f_experimental() An example experimental function. <BLANKLINE> State: Experimental as of 0.3.0. <BLANKLINE> """ _required_kwargs = ('as_of', ) def __init__(self, *args, **kwargs): self._validate_kwargs(**kwargs) self.as_of = kwargs['as_of'] def __call__(self, func): state_desc = 'Experimental as of %s.' % self.as_of func.__doc__ = self._update_docstring(func.__doc__, state_desc) return func class deprecated(_state_decorator): """ State decorator indicating deprecated functionality. Used to indicate that a public class or function is deprecated, meaning that its API will be removed in a future version of scikit-bio. Decorating functionality as deprecated will update its doc string to indicate the first version of scikit-bio when the functionality was deprecated, the first version of scikit-bio when the functionality will no longer exist, and the reason for deprecation of the API. It will also cause calls to the API to raise a ``DeprecationWarning``. Parameters ---------- as_of : str First development version where feature is considered to be deprecated. until : str First release version where feature will no longer exist. reason : str Brief description of why the API is deprecated. See Also -------- stable experimental Examples -------- >>> @deprecated(as_of='0.3.0', until='0.3.3', ... reason='Use skbio.g().') ... def f_deprecated(x, verbose=False): ... \"\"\" An example deprecated function. ... \"\"\" ... pass >>> help(f_deprecated) Help on function f_deprecated in module skbio.util._decorator: <BLANKLINE> f_deprecated(x, verbose=False) An example deprecated function. <BLANKLINE> .. note:: Deprecated as of 0.3.0 for removal in 0.3.3. Use skbio.g(). <BLANKLINE> """ _required_kwargs = ('as_of', 'until', 'reason') def __init__(self, *args, **kwargs): self._validate_kwargs(**kwargs) self.as_of = kwargs['as_of'] self.until = kwargs['until'] self.reason = kwargs['reason'] def __call__(self, func, *args, **kwargs): state_desc = 'Deprecated as of %s for removal in %s. %s' %\ (self.as_of, self.until, self.reason) func.__doc__ = self._update_docstring(func.__doc__, state_desc, state_desc_prefix='.. note:: ') def wrapped_f(*args, **kwargs): warnings.warn('%s is deprecated as of scikit-bio version %s, and ' 'will be removed in version %s. %s' % (func.__name__, self.as_of, self.until, self.reason), DeprecationWarning) # args[0] is the function being wrapped when this is called # after wrapping with decorator.decorator, but why??? return func(*args[1:], **kwargs) return decorator.decorator(wrapped_f, func) # Adapted from http://stackoverflow.com/a/8313042/579416 def overrides(interface_class): """Decorator for class-level members. Used to indicate that a member is being overridden from a specific parent class. If the member does not have a docstring, it will pull one from the parent class. When chaining decorators, this should be first as it is relatively nondestructive. Parameters ---------- interface_class : class The class which has a member overridden by the decorated member. Returns ------- function The function is not changed or replaced. Raises ------ OverrideError If the `interface_class` does not possess a member of the same name as the decorated member. """ def overrider(method): if method.__name__ not in dir(interface_class): raise OverrideError("%r is not present in parent class: %r." % (method.__name__, interface_class.__name__)) backup = classproperty.__get__ classproperty.__get__ = lambda x, y, z: x if method.__doc__ is None: method.__doc__ = getattr(interface_class, method.__name__).__doc__ classproperty.__get__ = backup return method return overrider class classproperty(property): """Decorator for class-level properties. Supports read access only. The property will be read-only within an instance. However, the property can always be redefined on the class, since Python classes are mutable. Parameters ---------- func : function Method to make a class property. Returns ------- property Decorated method. Raises ------ AttributeError If the property is set on an instance. """ def __init__(self, func): name = func.__name__ doc = func.__doc__ super(classproperty, self).__init__(classmethod(func)) self.__name__ = name self.__doc__ = doc def __get__(self, cls, owner): return self.fget.__get__(None, owner)() def __set__(self, obj, value): raise AttributeError("can't set attribute")
4,156
0
322
3a62db4bd65765d304546ab9bbecde61034b3928
10,485
py
Python
datablox_framework/datablox_framework/loader.py
mpi-sws-rse/datablox
93af071e5f8a68dc83df1700ed657bd64aca8849
[ "Apache-2.0" ]
null
null
null
datablox_framework/datablox_framework/loader.py
mpi-sws-rse/datablox
93af071e5f8a68dc83df1700ed657bd64aca8849
[ "Apache-2.0" ]
null
null
null
datablox_framework/datablox_framework/loader.py
mpi-sws-rse/datablox
93af071e5f8a68dc83df1700ed657bd64aca8849
[ "Apache-2.0" ]
null
null
null
"""This is the command line interface to the master. """ import os import os.path import sys from optparse import OptionParser import logging from logging.handlers import RotatingFileHandler logger = logging.getLogger(__name__) from master import * import defs try: import datablox_engage_adapter.file_locator using_engage = True except ImportError: using_engage = False if using_engage: engage_file_locator = datablox_engage_adapter.file_locator.FileLocator() print "Running with Engage deployment home at %s" % \ engage_file_locator.get_dh() import datablox_engage_adapter.install else: engage_file_locator = None # error definitions from engage_utils.user_error import UserError, ErrorInfo, convert_exc_to_user_error import gettext _ = gettext.gettext AREA_DATABLOX = "Datablox Framework" errors = {} ERR_UNEXPECTED_EXC = 1 define_error(ERR_UNEXPECTED_EXC, _("Aborting run due to unexpected error.")) error_file = None # if set by command line option, we'll write fatal errors to this file def build_args(flat_args): """Given flattened arguments provided by the user """ args = {} # map where key is block id, value is a map from arg name to arg value for k in flat_args.keys(): k_comps = k.split(".") if (len(k_comps) < 2) or (len(k_comps) > 3): raise Exception("invalid key %s: should have form [group_id].block_id.arg_name" % k) if len(k_comps)==2: gid = "main" bid = k_comps[0] an = k_comps[1] else: gid = k_comps[0] bid = k_comps[1] an = k_comps[2] if not args.has_key(gid): args[gid] = {} group = args[gid] if not group.has_key(bid): group[bid] = {} block = group[bid] block[an] = flat_args[k] return args log_levels = { "ERROR": logging.ERROR, "WARN": logging.WARN, "INFO": logging.INFO, "DEBUG": logging.DEBUG, "ALL": 1 } running_from_command_line = False if __name__ == "__main__": call_from_console_script()
40.797665
272
0.686218
"""This is the command line interface to the master. """ import os import os.path import sys from optparse import OptionParser import logging from logging.handlers import RotatingFileHandler logger = logging.getLogger(__name__) from master import * import defs try: import datablox_engage_adapter.file_locator using_engage = True except ImportError: using_engage = False if using_engage: engage_file_locator = datablox_engage_adapter.file_locator.FileLocator() print "Running with Engage deployment home at %s" % \ engage_file_locator.get_dh() import datablox_engage_adapter.install else: engage_file_locator = None # error definitions from engage_utils.user_error import UserError, ErrorInfo, convert_exc_to_user_error import gettext _ = gettext.gettext AREA_DATABLOX = "Datablox Framework" errors = {} def define_error(error_code, msg): global errors error_info = ErrorInfo(AREA_DATABLOX, __name__, error_code, msg) errors[error_code] = error_info ERR_UNEXPECTED_EXC = 1 define_error(ERR_UNEXPECTED_EXC, _("Aborting run due to unexpected error.")) error_file = None # if set by command line option, we'll write fatal errors to this file def build_args(flat_args): """Given flattened arguments provided by the user """ args = {} # map where key is block id, value is a map from arg name to arg value for k in flat_args.keys(): k_comps = k.split(".") if (len(k_comps) < 2) or (len(k_comps) > 3): raise Exception("invalid key %s: should have form [group_id].block_id.arg_name" % k) if len(k_comps)==2: gid = "main" bid = k_comps[0] an = k_comps[1] else: gid = k_comps[0] bid = k_comps[1] an = k_comps[2] if not args.has_key(gid): args[gid] = {} group = args[gid] if not group.has_key(bid): group[bid] = {} block = group[bid] block[an] = flat_args[k] return args log_levels = { "ERROR": logging.ERROR, "WARN": logging.WARN, "INFO": logging.INFO, "DEBUG": logging.DEBUG, "ALL": 1 } running_from_command_line = False def main(argv, callbacks=None): if using_engage: usage = "%prog [options] config_file node_name_1 node_name_2 ..." else: usage = "%prog [options] config_file ip_address1 ip_address2 ..." parser = OptionParser(usage=usage) parser.add_option("-a", "--args", dest="args", default=None, help="JSON map containing overrides of block arguments in the topology. The keys in the map have the form [group_id].block_id.arg_name. Example: --args '{\"source.sleep\":5, \"sink.sleep\":10}' Note that --args is mutually exclusive with --args-file.") parser.add_option("--args-file", dest="args_file", default=None, help="File containing JSON map containing overrides of block arguments in the topology. The keys in the map have the form [group_id].block_id.arg_name. Mutually exclusive with --args.") parser.add_option("-b", "--bloxpath", dest="bloxpath", default=None, help="use this path instead of the environment variable BLOXPATH") parser.add_option("-p", "--poll-interval", dest="poll_interval", type="int", default=DEFAULT_POLL_INTERVAL, help="Time in seconds between polls of the caretakers, defaults to %d" % DEFAULT_POLL_INTERVAL) parser.add_option('--stats-multiple', dest='stats_multiple', type="int", default=DEFAULT_STATS_MULTIPLE, help="Number of polls between stats gathering, defaults to %d" % DEFAULT_STATS_MULTIPLE) parser.add_option("-l", "--log-level", dest="log_level", default="INFO", help="Log level: ERROR|WARN|INFO|DEBUG|ALL") parser.add_option("-d", "--debug-blocks", dest="debug_blocks", default=None, help="Comma-separated list of blocks for which to enable debug-level logging") parser.add_option("--loads-file", dest="loads_file", default=None, help="If specified, write block load history to this file in csv format at end of run") parser.add_option('--log-stats-hist', dest='log_stats_hist', default=False, action="store_true", help="If specified, save gathered performance statistics to the log file") parser.add_option('--error_file', dest='error_file', default=None, help="If specified, write fatal errors to this file in JSON form") parser.add_option('--time-limit', dest='time_limit', default=None, type="int", help="If specified, abort the run if it exceeds the specified time limit (in minutes)") if using_engage: parser.add_option("--reuse-existing-installs", default=None, action="store_true", help="Reuse existing Datablox installs on worker nodes, if present (This is the default behavior).") parser.add_option("--always-reinstall-workers", default=False, action="store_true", help="Always reinstall Datablox on worker nodes") (options, args) = parser.parse_args(argv) if using_engage and options.reuse_existing_installs and \ options.always_reinstall_workers: parser.error("--reuse-existing-installs and --always-reinstall-workers are mutually exclusive") elif using_engage and options.always_reinstall_workers==False: reuse_existing_installs = True else: reuse_existing_installs = False if len(args)<1: parser.error("Need to specify config file and nodes.") elif len(args)<2: #and options.pool==None: parser.error("Need to specify list of nodes/ip_addreses or a DJM pool name") bloxpath = options.bloxpath if options.args and options.args_file: parser.error("Cannot specify both --args and --args-file") if options.args: try: block_args_flat = json.loads(options.args) except Exception, e: parser.error("--args option value %s is not valid JSON: %s" % (options.args, e)) try: block_args = build_args(block_args_flat) except Exception, e: parser.error("--args option: %s" % e) elif options.args_file: args_filepath = os.path.abspath(os.path.expanduser(options.args_file)) if not os.path.exists(args_filepath): parser.error("--args-file: file %s does not exist" % args_filepath) try: with open(args_filepath, "rb") as f: block_args_flat = json.load(f) except Exception, e: parser.error("--args-file %s is not valid JSON: %s" % (args_filepath, e)) try: block_args = build_args(block_args_flat) except Exception, e: parser.error("--args-file option: %s" % e) else: block_args = None if options.debug_blocks: debug_block_list = options.debug_blocks.split(',') else: debug_block_list = [] if options.error_file: options.error_file = os.path.abspath(os.path.expanduser(options.error_file)) if not os.path.exists(os.path.dirname(options.error_file)): parser.error("Parent directory of error file %s does not exist" % options.error_file) global error_file error_file = options.error_file # The priorities for obtaining bloxpath are: # 1. Command line option # 2. If engage is installed, use file locator to get bloxpath # 3. Otherwise, lookfor BLOXPATH environment variable if bloxpath == None: if using_engage: bloxpath = engage_file_locator.get_blox_dir() elif not os.environ.has_key("BLOXPATH"): parser.error("Need to set BLOXPATH environment variable or pass it as an argument") else: bloxpath = os.environ["BLOXPATH"] if not os.path.isdir(bloxpath): parser.error("BLOXPATH %s does not exist or is not a directory" % bloxpath) if options.log_level not in log_levels.keys(): parser.error("--log-level must be one of %s" % log_levels.keys()) # setup logging root_logger = logging.getLogger() if len(root_logger.handlers)==0: console_handler = logging.StreamHandler(sys.stdout) console_handler.setLevel(log_levels[options.log_level]) root_logger.addHandler(console_handler) root_logger.log(logging.INFO, "Datablox added console handler to root logger") if using_engage: root_logger.setLevel(min(root_logger.level, logging.DEBUG)) if running_from_command_line: # we only create the master.log logfile if we are running directly in the command # line. If we are called as a library, we let the caller setup the logfile log_dir = engage_file_locator.get_log_directory() if not os.path.exists(log_dir): os.makedirs(log_dir) log_file = os.path.join(log_dir, "master.log") do_log_rollover = os.path.exists(log_file) handler = RotatingFileHandler(log_file, backupCount=5) formatter = logging.Formatter(defs.DATABLOX_LOG_FORMAT, defs.DATABLOX_LOG_DATEFMT) handler.setFormatter(formatter) if do_log_rollover: # we do a rollover each time the master is run handler.doRollover() handler.setLevel(logging.DEBUG) root_logger.addHandler(handler) else: root_logger.setLevel(min(root_logger.level, log_levels[options.log_level])) Master(bloxpath, args[0], args[1:], using_engage, _log_level=log_levels[options.log_level], _debug_block_list=debug_block_list, reuse_existing_installs=reuse_existing_installs, poll_interval=options.poll_interval, stats_multiple=options.stats_multiple, block_args=block_args, loads_file=options.loads_file, log_stats_hist=options.log_stats_hist, time_limit=options.time_limit, callbacks=callbacks) return 0 def call_from_console_script(): global error_file, running_from_command_line running_from_command_line = True try: rc = main(sys.argv[1:]) except UserError, e: rc = 1 e.write_error_to_log(logger) if error_file and not os.path.exists(error_file): e.write_error_to_file(error_file) except: rc = 1 (ec, ev, et) = sys.exc_info() logger.exception("Unexpected exception: %s(%s)" % (ec.__name__, ev)) user_error = convert_exc_to_user_error(sys.exc_info(), errors[ERR_UNEXPECTED_EXC]) user_error.write_error_to_log(logger) if error_file and not os.path.exists(error_file): user_error.write_error_to_file(error_file) sys.exit(rc) if __name__ == "__main__": call_from_console_script()
8,437
0
68
75b153c2471d475e880de834fc7fd9faf3ad3d81
541
py
Python
supplier_image_upload.py
martroben/Google-automation-with-Python-exam
0e6c1144def8c06a01da6e1c63df492b3a383f50
[ "MIT" ]
null
null
null
supplier_image_upload.py
martroben/Google-automation-with-Python-exam
0e6c1144def8c06a01da6e1c63df492b3a383f50
[ "MIT" ]
null
null
null
supplier_image_upload.py
martroben/Google-automation-with-Python-exam
0e6c1144def8c06a01da6e1c63df492b3a383f50
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 import os import re import requests # Inputs images_dir = "/home/student/supplier-data/images/" upload_url = "http://xxx.xxx.xxx.xxx/upload/" # Get a list of paths of all .jpeg files in directory file_list = os.listdir(images_dir) jpeg_paths = [images_dir + item for item in file_list if bool(re.search(r"jpeg", item))] # Post all .jpeg files to a web service for path in jpeg_paths: with open(path, "rb") as image: response = requests.post(upload_url, files={"file": image}) print(response.status_code)
27.05
88
0.726433
#!/usr/bin/env python3 import os import re import requests # Inputs images_dir = "/home/student/supplier-data/images/" upload_url = "http://xxx.xxx.xxx.xxx/upload/" # Get a list of paths of all .jpeg files in directory file_list = os.listdir(images_dir) jpeg_paths = [images_dir + item for item in file_list if bool(re.search(r"jpeg", item))] # Post all .jpeg files to a web service for path in jpeg_paths: with open(path, "rb") as image: response = requests.post(upload_url, files={"file": image}) print(response.status_code)
0
0
0
3e1ad8fd7e80b6c65c87c128c1ec33be6f4f13f9
3,346
py
Python
LED2Net/DuLaPost/objs/WallPlane.py
zhigangjiang/LED2-Net
28528b2180d6af0caee54a60560b88dd0f218f1b
[ "MIT" ]
57
2021-03-25T05:42:34.000Z
2022-03-30T02:50:30.000Z
LED2Net/DuLaPost/objs/WallPlane.py
zhigangjiang/LED2-Net
28528b2180d6af0caee54a60560b88dd0f218f1b
[ "MIT" ]
8
2021-04-09T09:50:22.000Z
2022-02-17T17:36:27.000Z
LED2Net/DuLaPost/objs/WallPlane.py
zhigangjiang/LED2-Net
28528b2180d6af0caee54a60560b88dd0f218f1b
[ "MIT" ]
6
2021-04-11T10:15:07.000Z
2022-03-31T06:56:56.000Z
import random import objs import utils #manh only
31.566038
85
0.504782
import random import objs import utils class WallPlane(object): def __init__(self, scene, gPoints): self.scene = scene self.attached = [] self.gPoints = gPoints self.color = (0, 0, 0) self.normal = (0, 0, 0) self.planeEquation = (0, 0, 0, 0) self.width = 0 self.corners = [] self.edges = [] self.bbox2d = ((0,0),(1,1)) self.id = 0 self.updateGeometry() def updateGeometry(self): self.updateCorners() self.updateEdges() self.updateBbox2d() self.normal = utils.pointsNormal(self.corners[0].xyz,self.corners[1].xyz, self.corners[3].xyz) self.color = utils.normal2color(self.normal) self.planeEquation = utils.planeEquation(self.normal, self.corners[0].xyz) self.width = utils.pointsDistance(self.corners[0].xyz, self.corners[1].xyz) for obj2d in self.attached: obj2d.updateGeometry() def updateCorners(self): gps = self.gPoints cameraH = self.scene.cameraHeight cam2ceilH = self.scene.layoutHeight - cameraH self.corners = [objs.GeoPoint(self.scene, None, (gps[0].xyz[0], cam2ceilH, gps[0].xyz[2])), objs.GeoPoint(self.scene, None, (gps[1].xyz[0], cam2ceilH, gps[1].xyz[2])), objs.GeoPoint(self.scene, None, (gps[1].xyz[0], -cameraH, gps[1].xyz[2])), objs.GeoPoint(self.scene, None, (gps[0].xyz[0], -cameraH, gps[0].xyz[2]))] def updateEdges(self): self.edges = [objs.GeoEdge(self.scene, (self.corners[0], self.corners[1])), objs.GeoEdge(self.scene, (self.corners[1], self.corners[2])), objs.GeoEdge(self.scene, (self.corners[2], self.corners[3])), objs.GeoEdge(self.scene, (self.corners[3], self.corners[0]))] self.edges[3].type = self.gPoints[0].type self.edges[1].type = self.gPoints[1].type def updateBbox2d(self): coords = [] for c in [e.coords for e in self.edges]: coords += c self.bbox2d = utils.imagePointsBox(coords) #manh only def checkRayHit(self, vec, orig=(0,0,0)): point = utils.vectorPlaneHit(vec, self.planeEquation) if point is None: return False, None cs = self.corners if cs[2].xyz[1] <= point[1] <= cs[0].xyz[1]: p1 = (point[0], cs[0].xyz[1], point[2]) dis1 = utils.pointsDistance(p1, cs[0].xyz) dis2 = utils.pointsDistance(p1, cs[1].xyz) dis3 = utils.pointsDistance(cs[0].xyz, cs[1].xyz) if dis1 + dis2 <= dis3 * 1.0005: return True, point return False, None def getintersection(self, plane): for point in self.gPoints: if point in plane.gPoints: pc = point else: p1 = point for point in plane.gPoints: if not point == pc: p2 = point return (pc, p1, p2)
3,043
3
237
68c2f80d3dee75eb3408b80fb12d6266c87ba3a0
70
py
Python
Configuration/Eras/python/Modifier_run3_RPC_cff.py
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
Configuration/Eras/python/Modifier_run3_RPC_cff.py
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
Configuration/Eras/python/Modifier_run3_RPC_cff.py
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
import FWCore.ParameterSet.Config as cms run3_RPC = cms.Modifier()
14
40
0.771429
import FWCore.ParameterSet.Config as cms run3_RPC = cms.Modifier()
0
0
0
e830322abcfe2b89b4741f5180a64f7028796c88
6,997
py
Python
cloudify_cli/tests/commands/test_uninstall.py
cloudify-cosmo/cloudify-cli
c6370012a25335f773ec0c449f46b526874c87fe
[ "Apache-2.0" ]
41
2015-03-11T17:45:28.000Z
2021-11-07T19:50:26.000Z
cloudify_cli/tests/commands/test_uninstall.py
cloudify-cosmo/cloudify-cli
c6370012a25335f773ec0c449f46b526874c87fe
[ "Apache-2.0" ]
134
2015-01-04T20:51:41.000Z
2022-03-29T10:13:25.000Z
cloudify_cli/tests/commands/test_uninstall.py
cloudify-cosmo/cloudify-cli
c6370012a25335f773ec0c449f46b526874c87fe
[ "Apache-2.0" ]
61
2015-01-09T12:10:49.000Z
2022-03-24T07:22:53.000Z
import os from mock import patch from cloudify_rest_client import deployments from ... import local from .test_base import CliCommandTest from ...constants import DEFAULT_UNINSTALL_WORKFLOW, \ DEFAULT_TIMEOUT, DEFAULT_PARAMETERS from .constants import BLUEPRINTS_DIR, DEFAULT_BLUEPRINT_FILE_NAME
37.218085
78
0.580106
import os from mock import patch from cloudify_rest_client import deployments from ... import local from .test_base import CliCommandTest from ...constants import DEFAULT_UNINSTALL_WORKFLOW, \ DEFAULT_TIMEOUT, DEFAULT_PARAMETERS from .constants import BLUEPRINTS_DIR, DEFAULT_BLUEPRINT_FILE_NAME class UninstallTest(CliCommandTest): def setUp(self): super(UninstallTest, self).setUp() self.use_manager() @patch('cloudify_cli.commands.blueprints.delete') @patch('cloudify_cli.commands.deployments.manager_delete') @patch('cloudify_cli.env.get_rest_client') @patch('cloudify_cli.commands.executions.manager_start') def test_default_executions_start_arguments(self, executions_start_mock, *_): self.invoke('cfy uninstall did', context='manager') executions_start_mock.assert_called_with( workflow_id=DEFAULT_UNINSTALL_WORKFLOW, deployment_id='did', timeout=DEFAULT_TIMEOUT, force=False, include_logs=True, allow_custom_parameters=False, parameters=DEFAULT_PARAMETERS, json_output=False, tenant_name=None ) @patch('cloudify_cli.commands.blueprints.delete') @patch('cloudify_cli.commands.deployments.manager_delete') @patch('cloudify_cli.env.get_rest_client') @patch('cloudify_cli.commands.executions.manager_start') def test_custom_executions_start_arguments(self, executions_start_mock, *_ ): uninstall_command = 'cfy uninstall ' \ '-w my_uninstall ' \ 'did ' \ '--timeout 1987 ' \ '--allow-custom-parameters ' \ '--include-logs ' \ '--parameters key=value ' \ '--json ' \ '--tenant-name tenant_name' self.invoke(uninstall_command, context='manager') executions_start_mock.assert_called_with( workflow_id=u'my_uninstall', deployment_id=u'did', timeout=1987, force=False, include_logs=True, allow_custom_parameters=True, parameters={'key': 'value'}, json_output=False, tenant_name='tenant_name' ) @patch('cloudify_cli.commands.executions.manager_start') @patch('cloudify_cli.commands.deployments.manager_delete') @patch('cloudify_cli.commands.blueprints.delete') def test_getting_blueprint_id_from_deployment(self, mock_blueprints_delete, *_): def mock_deployments_get(*args, **kwargs): return deployments.Deployment({'blueprint_id': 'bid'}) self.client.deployments.get = mock_deployments_get self.invoke('cfy uninstall did', context='manager') mock_blueprints_delete.assert_called_with(blueprint_id=u'bid', force=False, tenant_name=None) @patch('cloudify_cli.commands.blueprints.delete') @patch('cloudify_cli.env.get_rest_client') @patch('cloudify_cli.commands.executions.manager_start') @patch('cloudify_cli.commands.deployments.manager_delete') def test_deployments_delete_arguments(self, deployments_delete_mock, *_): self.invoke('cfy uninstall did', context='manager') deployments_delete_mock.assert_called_with( deployment_id=u'did', force=False, tenant_name=None ) @patch('cloudify_cli.env.get_rest_client') @patch('cloudify_cli.commands.executions.manager_start') @patch('cloudify_cli.commands.deployments.manager_delete') @patch('cloudify_cli.commands.blueprints.delete') def test_blueprint_is_deleted(self, blueprints_delete_mock, *_): self.invoke('cfy uninstall did', context='manager') self.assertTrue(blueprints_delete_mock.called) @patch('cloudify_cli.commands.executions.local_start') def test_local_uninstall_default_values(self, local_start_mock): blueprint_path = os.path.join( BLUEPRINTS_DIR, 'local', DEFAULT_BLUEPRINT_FILE_NAME ) self.invoke('cfy init {0}'.format(blueprint_path)) self.invoke('cfy uninstall -b local', context='local') args = local_start_mock.call_args_list[0][1] self.assertDictEqual( args, { 'parameters': DEFAULT_PARAMETERS, 'blueprint_id': 'local', 'allow_custom_parameters': False, 'workflow_id': 'uninstall', 'task_retries': 0, 'task_retry_interval': 1, 'task_thread_pool_size': 1 } ) @patch('cloudify_cli.commands.executions.local_start') def test_local_uninstall_custom_values(self, local_start_mock): blueprint_path = os.path.join( BLUEPRINTS_DIR, 'local', DEFAULT_BLUEPRINT_FILE_NAME ) self.invoke('cfy init {0}'.format(blueprint_path)) self.invoke('cfy uninstall' ' -b local' ' -w my_uninstall' ' --parameters key=value' ' --allow-custom-parameters' ' --task-retries 14' ' --task-retry-interval 7' ' --task-thread-pool-size 87', context='local') args = local_start_mock.call_args_list[0][1] self.assertDictEqual( args, { 'parameters': {u'key': u'value'}, 'blueprint_id': 'local', 'allow_custom_parameters': True, 'workflow_id': u'my_uninstall', 'task_retries': 14, 'task_retry_interval': 7, 'task_thread_pool_size': 87 } ) def test_uninstall_removes_local_storage_dir(self): blueprint_path = os.path.join( BLUEPRINTS_DIR, 'local', DEFAULT_BLUEPRINT_FILE_NAME ) storage_dir = os.path.join(local.storage_dir(), 'blueprints', 'local') # Using run_test_op_on_nodes because the blueprint doesn't have # install/uninstall workflows self.invoke( 'cfy install {0} -b local -w run_test_op_on_nodes' .format(blueprint_path), context='local' ) self.assertTrue(os.path.isdir(storage_dir)) self.invoke( 'cfy uninstall -b local -w run_test_op_on_nodes', context='local', ) self.assertFalse(os.path.isdir(storage_dir))
5,217
1,453
23
f41ea368edf3bae3763987ab2fcc2150623e0568
3,112
py
Python
firmware/adafruit-circuitpython-bundle-5.x-mpy-20200915/examples/gps_datalogging.py
freeglow/microcontroller-cpy
5adfda49da6eefaece81be2a2f26122d68736355
[ "MIT" ]
null
null
null
firmware/adafruit-circuitpython-bundle-5.x-mpy-20200915/examples/gps_datalogging.py
freeglow/microcontroller-cpy
5adfda49da6eefaece81be2a2f26122d68736355
[ "MIT" ]
null
null
null
firmware/adafruit-circuitpython-bundle-5.x-mpy-20200915/examples/gps_datalogging.py
freeglow/microcontroller-cpy
5adfda49da6eefaece81be2a2f26122d68736355
[ "MIT" ]
null
null
null
# Simple GPS datalogging demonstration. # This example uses the GPS library and to read raw NMEA sentences # over I2C or UART from the GPS unit and dumps them to a file on an SD card # (recommended), microcontroller internal storage (be careful as only a few # kilobytes are available), or to a filesystem. # If you are using a microcontroller, before writing to internal storage you # MUST carefully follow the steps in this guide to enable writes to the # internal filesystem: # https://learn.adafruit.com/adafruit-ultimate-gps-featherwing/circuitpython-library import board import busio import adafruit_gps # Path to the file to log GPS data. By default this will be appended to # which means new lines are added at the end and all old data is kept. # Change this path to point at internal storage (like '/gps.txt') or SD # card mounted storage ('/sd/gps.txt') as desired. LOG_FILE = "gps.txt" # Example for writing to internal path gps.txt # File more for opening the log file. Mode 'ab' means append or add new lines # to the end of the file rather than erasing it and starting over. If you'd # like to erase the file and start clean each time use the value 'wb' instead. LOG_MODE = "ab" # If writing to SD card on a microcontroller customize and uncomment these # lines to import the necessary library and initialize the SD card: # NOT for use with a single board computer like Raspberry Pi! """ import adafruit_sdcard import digitalio import storage SD_CS_PIN = board.D10 # CS for SD card using Adalogger Featherwing spi = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO) sd_cs = digitalio.DigitalInOut(SD_CS_PIN) sdcard = adafruit_sdcard.SDCard(spi, sd_cs) vfs = storage.VfsFat(sdcard) storage.mount(vfs, '/sd') # Mount SD card under '/sd' path in filesystem. LOG_FILE = '/sd/gps.txt' # Example for writing to SD card path /sd/gps.txt """ # Create a serial connection for the GPS connection using default speed and # a slightly higher timeout (GPS modules typically update once a second). # These are the defaults you should use for the GPS FeatherWing. # For other boards set RX = GPS module TX, and TX = GPS module RX pins. uart = busio.UART(board.TX, board.RX, baudrate=9600, timeout=10) # If using a USB/Serial converter, use pyserial and update the serial # port name to match the serial connection for the GPS! # import serial # uart = serial.Serial("/dev/ttyUSB0", baudrate=9600, timeout=10) # If using I2C, we'll create an I2C interface to talk to using default pins # i2c = board.I2C() # Create a GPS module instance. gps = adafruit_gps.GPS(uart) # Use UART/pyserial # gps = adafruit_gps.GPS_GtopI2C(i2c) # Use I2C interface # Main loop just reads data from the GPS module and writes it back out to # the output file while also printing to serial output. with open(LOG_FILE, LOG_MODE) as outfile: while True: sentence = gps.readline() if not sentence: continue print(str(sentence, "ascii").strip()) outfile.write(sentence) outfile.flush()
44.457143
86
0.726864
# Simple GPS datalogging demonstration. # This example uses the GPS library and to read raw NMEA sentences # over I2C or UART from the GPS unit and dumps them to a file on an SD card # (recommended), microcontroller internal storage (be careful as only a few # kilobytes are available), or to a filesystem. # If you are using a microcontroller, before writing to internal storage you # MUST carefully follow the steps in this guide to enable writes to the # internal filesystem: # https://learn.adafruit.com/adafruit-ultimate-gps-featherwing/circuitpython-library import board import busio import adafruit_gps # Path to the file to log GPS data. By default this will be appended to # which means new lines are added at the end and all old data is kept. # Change this path to point at internal storage (like '/gps.txt') or SD # card mounted storage ('/sd/gps.txt') as desired. LOG_FILE = "gps.txt" # Example for writing to internal path gps.txt # File more for opening the log file. Mode 'ab' means append or add new lines # to the end of the file rather than erasing it and starting over. If you'd # like to erase the file and start clean each time use the value 'wb' instead. LOG_MODE = "ab" # If writing to SD card on a microcontroller customize and uncomment these # lines to import the necessary library and initialize the SD card: # NOT for use with a single board computer like Raspberry Pi! """ import adafruit_sdcard import digitalio import storage SD_CS_PIN = board.D10 # CS for SD card using Adalogger Featherwing spi = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO) sd_cs = digitalio.DigitalInOut(SD_CS_PIN) sdcard = adafruit_sdcard.SDCard(spi, sd_cs) vfs = storage.VfsFat(sdcard) storage.mount(vfs, '/sd') # Mount SD card under '/sd' path in filesystem. LOG_FILE = '/sd/gps.txt' # Example for writing to SD card path /sd/gps.txt """ # Create a serial connection for the GPS connection using default speed and # a slightly higher timeout (GPS modules typically update once a second). # These are the defaults you should use for the GPS FeatherWing. # For other boards set RX = GPS module TX, and TX = GPS module RX pins. uart = busio.UART(board.TX, board.RX, baudrate=9600, timeout=10) # If using a USB/Serial converter, use pyserial and update the serial # port name to match the serial connection for the GPS! # import serial # uart = serial.Serial("/dev/ttyUSB0", baudrate=9600, timeout=10) # If using I2C, we'll create an I2C interface to talk to using default pins # i2c = board.I2C() # Create a GPS module instance. gps = adafruit_gps.GPS(uart) # Use UART/pyserial # gps = adafruit_gps.GPS_GtopI2C(i2c) # Use I2C interface # Main loop just reads data from the GPS module and writes it back out to # the output file while also printing to serial output. with open(LOG_FILE, LOG_MODE) as outfile: while True: sentence = gps.readline() if not sentence: continue print(str(sentence, "ascii").strip()) outfile.write(sentence) outfile.flush()
0
0
0
a6023474ac04ec797be0cf1bec09097eb38be8bb
8,502
py
Python
category_diagram_editor.py
lbordowitz/AssistiveDiagramChaser
b843791a6fb66bd91d5a63e8ccd5bf5aca2784ed
[ "MIT" ]
null
null
null
category_diagram_editor.py
lbordowitz/AssistiveDiagramChaser
b843791a6fb66bd91d5a63e8ccd5bf5aca2784ed
[ "MIT" ]
null
null
null
category_diagram_editor.py
lbordowitz/AssistiveDiagramChaser
b843791a6fb66bd91d5a63e8ccd5bf5aca2784ed
[ "MIT" ]
null
null
null
from graph_editor import GraphEditor from category_object import CategoryObject from category_arrow import CategoryArrow from qt_tools import simpleMaxContrastingColor, Pen, firstParentGfxItemOfType from PyQt5.QtGui import QTransform from PyQt5.QtWidgets import QMenu import re from PyQt5.QtCore import Qt from graph_arrow import ControlPoint from category_diagram import CategoryDiagram from functor import Functor from commands import MethodCallCommand, DeleteItemsCommand from op_functor import OpFunctor
39.544186
117
0.53211
from graph_editor import GraphEditor from category_object import CategoryObject from category_arrow import CategoryArrow from qt_tools import simpleMaxContrastingColor, Pen, firstParentGfxItemOfType from PyQt5.QtGui import QTransform from PyQt5.QtWidgets import QMenu import re from PyQt5.QtCore import Qt from graph_arrow import ControlPoint from category_diagram import CategoryDiagram from functor import Functor from commands import MethodCallCommand, DeleteItemsCommand from op_functor import OpFunctor class CategoryDiagramEditor(GraphEditor): def __init__(self, window, new=True): super().__init__(window, new) self.NodeType = CategoryObject self.ArrowType = CategoryArrow if new: pass self._focusedNode = None def setScene(self, scene): super().setScene(scene) scene.backgroundColorChanged.connect(lambda color: self._autoSetCodeColor(simpleMaxContrastingColor(color))) scene.setGridEnabled(True) self.setupDefaultUserExperience() def placeArrow(self, arr=None, item=None, pos=None): if pos is None: pos = self.scene().menuEventScenePos() item = self.scene().itemAt(pos, QTransform()) if item: if isinstance(item, CategoryDiagram): C = item if arr: F = arr else: F = Functor() F.setLabelText(0, "F") F.setEditor(self) F.setDomain(C) F.setContextMenu(self.buildArrowContextMenu(F)) self.addArrow(F) self.scene().placeItems(F.toPoint(), pos) item = F elif isinstance(item, CategoryObject): if not arr: arr = self.ArrowType() self.setupArrowConnections(arr) arr.setEditor(self) arr.setDomain(item) parent = item.parentItem() if parent: parent.addMorphism(arr, undoable=True) add = False pos = parent.mapFromScene(pos) else: add = True self.scene().placeItems(arr.toPoint(), pos, add=add) item = arr if isinstance(item, CategoryArrow): item.setFlag(item.ItemIsMovable, False) return item def placeItem(self, pos): item = self.scene().itemAt(pos, QTransform()) if item: if isinstance(item, CategoryDiagram) and item.editing(): node = self.NodeType() node.setEditor(self) node.setContextMenu(self.buildNodeContextMenu(node)) #node.zoomedIn.connect(lambda: self.nodeZoomedIn(node)) node.focusedIn.connect(lambda: self.nodeFocusedIn(node)) node.setZValue(-1.0) #self.scene().placeItems(node, pos) item.addObject(node, undoable=True) node.setPos(item.mapFromScene(pos)) self.scene().placeItems(node, add=False) item = node elif isinstance(item, CategoryDiagram): C = item F = Functor() F.setLabelText(0, "F") F.setEditor(self) F.setDomain(C) F.setContextMenu(self.buildArrowContextMenu(F)) self.addArrow(F) self.scene().placeItems(F.toPoint(), pos) item = F elif isinstance(item, CategoryObject): arr = self.ArrowType() self.setupArrowConnections(arr) arr.setEditor(self) arr.setDomain(item) parent = item.parentItem() if parent: parent.addMorphism(arr, undoable=True) add = False pos = parent.mapFromScene(pos) else: add = True self.scene().placeItems(arr.toPoint(), pos, add=add) item = arr else: node = CategoryDiagram() node.setEditor(self) node.setContextMenu(self.buildCategoryContextMenu(node)) #node.zoomedIn.connect(lambda: self.nodeZoomedIn(node)) node.focusedIn.connect(lambda: self.nodeFocusedIn(node)) node.setZValue(0.0) self.addNode(node) self.scene().placeItems(node, pos) item = node if isinstance(item, CategoryArrow): item.setFlag(item.ItemIsMovable, False) if not isinstance(item, ControlPoint): item.label(0).setEditable(True) return item def nodeFocusedIn(self, node): self._focusedNode = node def arrowFocusedIn(self, arrow): pass def sceneItemsPlaced(self, items): if len(items) == 1: item = items[0] if isinstance(item, ControlPoint): item.parentItem().label(0).setTextInteraction(True) elif isinstance(item, self.NodeType): item.label(0).setTextInteraction(True) def buildCategoryContextMenu(self, cat, menu=None): if menu is None: menu = QMenu() functors = menu.addMenu("Functor") op = functors.addAction("op") op.triggered.connect(lambda: self.placeArrow(OpFunctor())) menu.addSeparator() menu = self.buildNodeContextMenu(cat, menu) menu.addSeparator() menu.addAction("Compose Arrows").triggered.connect(lambda b: cat.composeArrows()) menu.addSeparator() action = menu.addAction("Edit Diagram") action.setCheckable(True) action.setChecked(False) action.toggled.connect(lambda b: cat.setEditing(b)) return menu def arrowExtremityAboutToChange(self, arr, pos, is_start=False): if is_start: if arr.domain(): arr.domain().updateArrowsAndClearResidual() arr.setDomain(None, undoable=True) else: if arr.codomain(): arr.codomain().updateArrowsAndClearResidual() arr.setCodomain(None, undoable=True) def arrowExtremityHasChanged(self, arr, pos, is_start=False): items = self.scene().items(pos) filtered = [] for item in items: if item is arr.parentItem(): continue if item is arr: continue if isinstance(item, ControlPoint): continue filtered.append(item) if filtered: for item in filtered: item = firstParentGfxItemOfType(item, self.NodeType) if item: # There is a node! if arr.canConnectTo(item, is_start): if is_start: arr.setDomain(item, undoable=True) else: arr.setCodomain(item, undoable=True) break else: # There is no sufficient item at pos if is_start: arr.setDomain(None, undoable=True) else: arr.setCodomain(None, undoable=True) def buildSceneContextMenu(self, menu=None): if menu is None: menu = QMenu() #self.buildBuiltinsMenu(menu) return super().buildSceneContextMenu(menu) def deleteItems(self, items=None, undoable=False): if items is None: items = self.scene().selectedItems() children = [] for item in items: children += item.childItems() filtered = [] for item in items: if item not in children: filtered.append(item) if undoable: command = DeleteItemsCommand("Deleting items", filtered, editor=self) self.pushCommand(command) else: for item in filtered: item.delete() def categoryLabel(self): return self.symbolLabel()
7,438
20
524
ee27a28302f204f9ca3634ac2f0132205190bb14
573
py
Python
honeybadger/tests/utils.py
dstuebe/honeybadger-python
81519b40d3e446b62035f64e34900e08ff91938c
[ "MIT" ]
1
2019-06-12T10:45:30.000Z
2019-06-12T10:45:30.000Z
honeybadger/tests/utils.py
dstuebe/honeybadger-python
81519b40d3e446b62035f64e34900e08ff91938c
[ "MIT" ]
null
null
null
honeybadger/tests/utils.py
dstuebe/honeybadger-python
81519b40d3e446b62035f64e34900e08ff91938c
[ "MIT" ]
2
2021-01-15T21:36:06.000Z
2021-01-26T10:17:17.000Z
from contextlib import contextmanager from mock import patch from mock import DEFAULT import six import time from threading import Event @contextmanager
27.285714
96
0.734729
from contextlib import contextmanager from mock import patch from mock import DEFAULT import six import time from threading import Event @contextmanager def mock_urlopen(func, status=201): mock_called_event = Event() def mock_was_called(*args, **kwargs): mock_called_event.set() return DEFAULT with patch('six.moves.urllib.request.urlopen', side_effect=mock_was_called) as request_mock: yield request_mock mock_called_event.wait() ((request_object,), mock_kwargs) = request_mock.call_args func(request_object)
397
0
22
9a27497b26f4a836550b82849252fb5b4de17d7e
6,405
py
Python
app.py
tfausten/bokehwise
7ffb10a757e4d93b74df3913c5b400165d4aff2b
[ "MIT" ]
null
null
null
app.py
tfausten/bokehwise
7ffb10a757e4d93b74df3913c5b400165d4aff2b
[ "MIT" ]
null
null
null
app.py
tfausten/bokehwise
7ffb10a757e4d93b74df3913c5b400165d4aff2b
[ "MIT" ]
null
null
null
import data_preparation from bokeh.models import ColumnDataSource, BooleanFilter, CDSView from bokeh.plotting import figure from bokeh.io import curdoc from bokeh.palettes import Category20c from bokeh.models.formatters import NumeralTickFormatter from bokeh.models.widgets import ( Panel, Tabs, DataTable, TableColumn, DateFormatter ) from bokeh.layouts import row from bokeh.events import Tap import itertools import pandas as pd def get_cycled_list(iterable, length): """ returns cycled list of fixed length """ cycled = itertools.cycle(iterable) sliced = itertools.islice(cycled, 0, length) return list(sliced) # get data and prepare monthly data by category expenses_df = data_preparation.get_expenses_df() monthly_category_df = expenses_df.groupby('Category').resample('BMS').sum() monthly_category_df = monthly_category_df.Cost.unstack(level=0) monthly_category_df = monthly_category_df.fillna(0) monthly_category_source = ColumnDataSource(monthly_category_df) col_names = monthly_category_df.columns.tolist() print('\nMonthly data by category\n', monthly_category_df.head()) # TODO make color-selection more understandable palette = Category20c[20] main_color_idxs = [0, 4, 8, 12, 16] category_colors = [palette[i+2] for i in main_color_idxs] category_colors = get_cycled_list(category_colors, len(col_names)) # create monthly bars of stacked categories monthly_overview = MonthlyGraph() monthly_overview.vbar_stack(stackers=col_names, x='Date', width=2e9, color=category_colors, source=monthly_category_source, legend_label=col_names) expenses_source = ColumnDataSource(expenses_df) expenses_table = get_expenses_table() overview_row = row([monthly_overview, expenses_table], sizing_mode='stretch_both') overview_panel = Panel( child=overview_row, title='Overview') def bar_tap_callback(event): """ update the expenses table to show only entries of the selected month """ # TODO when no bar is selected list index out of range try: selected = monthly_category_source.selected.indices[-1] print(selected) selected_month = monthly_category_df.index[selected].month except IndexError: selected_month = None expenses_table = get_expenses_table(selected_month) overview_row.children[1] = expenses_table monthly_overview.on_event(Tap, bar_tap_callback) panels = [overview_panel] # make single-category plots, and group the data by subcategories main_color_idxs_cycled = itertools.cycle(main_color_idxs) for category in col_names: subcat_df = expenses_df[expenses_df['Category'] == category] monthly_subcat_df = subcat_df.groupby('Subcategory').resample('BMS').sum() monthly_subcat_df = monthly_subcat_df.Cost.unstack(level=0) monthly_subcat_df = monthly_subcat_df.fillna(0) subcat_source = (ColumnDataSource(monthly_subcat_df)) subcats = monthly_subcat_df.columns.tolist() color_idx = next(main_color_idxs_cycled) colors = palette[color_idx:color_idx+4] colors = get_cycled_list(colors, len(subcats)) p = MonthlyGraph() p.vbar_stack(stackers=subcats, x='Date', width=2e9, color=colors, line_color='white', source=subcat_source, legend_label=subcats) expenses_table = get_expenses_table(category=category) subcat_row = row([p, expenses_table], sizing_mode='stretch_both') panel = Panel( child=subcat_row, title=category) def bar_tap_callback_subcat(event, subcat_source=subcat_source, monthly_subcat_df=monthly_subcat_df, subcat_row=subcat_row): """ update the expenses table to show only entries of the selected month """ # TODO does not work for panels because monthly subcat source # get overwritten in each pass through the loop. source needs # to be created as a list and then referenced by index print(subcat_source.selected.indices) try: selected = subcat_source.selected.indices[-1] print(selected) selected_month = monthly_subcat_df.index[selected].month except IndexError: selected_month = None expenses_table = get_expenses_table(selected_month, category) subcat_row.children[1] = expenses_table p.on_event(Tap, bar_tap_callback_subcat) panels.append(panel) tabs = Tabs(tabs=panels) curdoc().title = 'Bokehwise' curdoc().add_root(tabs)
37.238372
78
0.704606
import data_preparation from bokeh.models import ColumnDataSource, BooleanFilter, CDSView from bokeh.plotting import figure from bokeh.io import curdoc from bokeh.palettes import Category20c from bokeh.models.formatters import NumeralTickFormatter from bokeh.models.widgets import ( Panel, Tabs, DataTable, TableColumn, DateFormatter ) from bokeh.layouts import row from bokeh.events import Tap import itertools import pandas as pd def get_cycled_list(iterable, length): """ returns cycled list of fixed length """ cycled = itertools.cycle(iterable) sliced = itertools.islice(cycled, 0, length) return list(sliced) def MonthlyGraph(): monthly_graph = figure(x_axis_label='Month', y_axis_label='Expenses', x_axis_type='datetime', sizing_mode='stretch_both', tools="hover, tap", tooltips="$name: @$name") monthly_graph.y_range.start = 0 y_formatter = NumeralTickFormatter(format='0a') # date_formatter = DatetimeTickFormatter(months=["%m/%y"]) monthly_graph.yaxis.formatter = y_formatter return monthly_graph # get data and prepare monthly data by category expenses_df = data_preparation.get_expenses_df() monthly_category_df = expenses_df.groupby('Category').resample('BMS').sum() monthly_category_df = monthly_category_df.Cost.unstack(level=0) monthly_category_df = monthly_category_df.fillna(0) monthly_category_source = ColumnDataSource(monthly_category_df) col_names = monthly_category_df.columns.tolist() print('\nMonthly data by category\n', monthly_category_df.head()) # TODO make color-selection more understandable palette = Category20c[20] main_color_idxs = [0, 4, 8, 12, 16] category_colors = [palette[i+2] for i in main_color_idxs] category_colors = get_cycled_list(category_colors, len(col_names)) # create monthly bars of stacked categories monthly_overview = MonthlyGraph() monthly_overview.vbar_stack(stackers=col_names, x='Date', width=2e9, color=category_colors, source=monthly_category_source, legend_label=col_names) expenses_source = ColumnDataSource(expenses_df) def get_expenses_table(selected_month=None, category=None): table_columns = [ TableColumn(field='Date', title='Date', formatter=DateFormatter()), TableColumn(field='Description', title='Description'), TableColumn(field='Category', title='Category'), TableColumn(field='Subcategory', title='Subcategory'), TableColumn(field='Cost', title='Cost') ] # which month is currently selected? subset data according to selection if selected_month is None: month_filter = [True] * len(expenses_source.data['Date']) else: source_datetimes = pd.DatetimeIndex(expenses_source.data['Date']) month_filter = [ date.month == selected_month for date in source_datetimes] month_filter = BooleanFilter(month_filter) # filter for current category if category is None: category_filter = [True] * len(expenses_source.data['Category']) else: category_filter = [ cat == category for cat in expenses_source.data['Category']] category_filter = BooleanFilter(category_filter) view = CDSView(source=expenses_source, filters=[month_filter, category_filter]) return DataTable(source=expenses_source, columns=table_columns, view=view, sizing_mode='stretch_both') expenses_table = get_expenses_table() overview_row = row([monthly_overview, expenses_table], sizing_mode='stretch_both') overview_panel = Panel( child=overview_row, title='Overview') def bar_tap_callback(event): """ update the expenses table to show only entries of the selected month """ # TODO when no bar is selected list index out of range try: selected = monthly_category_source.selected.indices[-1] print(selected) selected_month = monthly_category_df.index[selected].month except IndexError: selected_month = None expenses_table = get_expenses_table(selected_month) overview_row.children[1] = expenses_table monthly_overview.on_event(Tap, bar_tap_callback) panels = [overview_panel] # make single-category plots, and group the data by subcategories main_color_idxs_cycled = itertools.cycle(main_color_idxs) for category in col_names: subcat_df = expenses_df[expenses_df['Category'] == category] monthly_subcat_df = subcat_df.groupby('Subcategory').resample('BMS').sum() monthly_subcat_df = monthly_subcat_df.Cost.unstack(level=0) monthly_subcat_df = monthly_subcat_df.fillna(0) subcat_source = (ColumnDataSource(monthly_subcat_df)) subcats = monthly_subcat_df.columns.tolist() color_idx = next(main_color_idxs_cycled) colors = palette[color_idx:color_idx+4] colors = get_cycled_list(colors, len(subcats)) p = MonthlyGraph() p.vbar_stack(stackers=subcats, x='Date', width=2e9, color=colors, line_color='white', source=subcat_source, legend_label=subcats) expenses_table = get_expenses_table(category=category) subcat_row = row([p, expenses_table], sizing_mode='stretch_both') panel = Panel( child=subcat_row, title=category) def bar_tap_callback_subcat(event, subcat_source=subcat_source, monthly_subcat_df=monthly_subcat_df, subcat_row=subcat_row): """ update the expenses table to show only entries of the selected month """ # TODO does not work for panels because monthly subcat source # get overwritten in each pass through the loop. source needs # to be created as a list and then referenced by index print(subcat_source.selected.indices) try: selected = subcat_source.selected.indices[-1] print(selected) selected_month = monthly_subcat_df.index[selected].month except IndexError: selected_month = None expenses_table = get_expenses_table(selected_month, category) subcat_row.children[1] = expenses_table p.on_event(Tap, bar_tap_callback_subcat) panels.append(panel) tabs = Tabs(tabs=panels) curdoc().title = 'Bokehwise' curdoc().add_root(tabs)
1,753
0
46
a1f7bd879a15010325df7cd01a71db2a87d16e6f
3,717
py
Python
n_step.py
m4n4n-j/subway-surfers-AI-main
5907754a1dee3cb9e395709834db93bcd2244536
[ "MIT" ]
2
2021-09-30T02:35:26.000Z
2021-11-20T08:58:34.000Z
n_step.py
m4n4n-j/subway-surfers-AI-main
5907754a1dee3cb9e395709834db93bcd2244536
[ "MIT" ]
null
null
null
n_step.py
m4n4n-j/subway-surfers-AI-main
5907754a1dee3cb9e395709834db93bcd2244536
[ "MIT" ]
2
2021-05-19T03:47:24.000Z
2021-07-06T15:51:37.000Z
# Importing the libraries import matplotlib.pyplot as plt import torch from torch.autograd import Variable import numpy as np from collections import namedtuple, deque #This step/experience includes the state of game, action performed, the reward for the state # whether the game had ended after this state and the LSTM values Step = namedtuple('Step', ['state', 'action', 'reward', 'done', 'lstm']) #This is a storage of one step that our agent performs
40.402174
153
0.554479
# Importing the libraries import matplotlib.pyplot as plt import torch from torch.autograd import Variable import numpy as np from collections import namedtuple, deque #This step/experience includes the state of game, action performed, the reward for the state # whether the game had ended after this state and the LSTM values Step = namedtuple('Step', ['state', 'action', 'reward', 'done', 'lstm']) #This is a storage of one step that our agent performs class NStepProgress: def __init__(self, env, ai, n_step): self.ai = ai #ai object self.rewards = [] self.env = env #Importing our manual subway surfers enviornment self.n_step = n_step #Number of steps to look forward def __iter__(self): #Function to play game and collect/return samples state = self.env.reset() #Resetting the game by clicking the green play button history = deque() reward = 0.0 #Initial reward = 0 is_done = True end_buffer = [] #To remove unwanted images that were added because of the late detection of end of game while True: if is_done: cx = Variable(torch.zeros(1,256)) hx = Variable(torch.zeros(1,256)) else: cx = Variable(cx.data) hx = Variable(hx.data) action, (hx, cx) = self.ai(Variable(torch.from_numpy(np.array([state], dtype = np.float32))), (hx, cx)) #Calculating action for a state/image end_buffer.append((state, action)) while len(end_buffer) > 3: #By observation at max 3 extra steps played by the agent after dying so a buffer of size 3 del end_buffer[0] # Printing action output from softmax. t = action[0][0] if(t == 1): #left print("left") elif (t == 2): #right print("right") elif (t == 3): #roll print("jump") elif (t == 4): #jump print("roll") elif (t == 0): #no op print("do nothing") # Taking Action next_state, r, is_done, _ = self.env.step(action) #Performing action and returning next state # If game over, if(is_done): print("\nGame Ended\n") if len(end_buffer)>=3: state, action = end_buffer[-3] history.pop() #Removing unwanted experience that includes images such as when cop was holding the runner r=-10 reward += r history.append(Step(state = state, action = action, reward = r, done = is_done, lstm = (hx, cx))) #Adding this experience to history # Returning the experiences generated to the replay memory while len(history) > self.n_step + 1: history.popleft() if len(history) == self.n_step + 1: yield tuple(history) state = next_state # If game is over if is_done: if len(history) > self.n_step + 1: history.popleft() while len(history) >= 1: yield tuple(history) history.popleft() #Resetting the variables self.rewards.append(reward) reward = 0.0 state = self.env.reset() end_buffer=[] history.clear() def rewards_steps(self): #Function to store the rewards whenever the game ends/for one instance of game rewards_steps = self.rewards self.rewards = [] return rewards_steps
3,150
-1
112
6122b93d979e921a9799ec641b0843ae9a17bddc
15,597
py
Python
aoc/src/8.py
1pkg/dump
0ee579cb6a97ae64d5367cc624b2407d7d4b1c7b
[ "MIT" ]
null
null
null
aoc/src/8.py
1pkg/dump
0ee579cb6a97ae64d5367cc624b2407d7d4b1c7b
[ "MIT" ]
3
2020-12-11T10:01:27.000Z
2022-02-13T22:12:05.000Z
aoc/src/8.py
1pkg/dump
0ee579cb6a97ae64d5367cc624b2407d7d4b1c7b
[ "MIT" ]
null
null
null
data = '222221202212222122222211222222222222222222222202222022222222222002221222222222220222202222202122222020222222021020220022122222222220222222202222222222222221202202222122222222222222222222222222222202222022222222222022220222222222220222212222212222222220222222221121222022022222222222222222212222222222222220202202222122222210222222222222222222222202222122222222222212222222222022222222212022212122222020222222122021221222122222222221222222222222222222222221202202222022222221222222222222222222222212222022222222222022220222222122222222202122222022222021222222220220220022222222222220222222202222222222222221202222222122222220222212222222222222222202222222222222222022222212222022220222202022202022222120222222121020222122222222222221222222202222222222222221202212222022222221222222222222222222222202222022222222222212220222202022220222202222202022222121222222020021222122022222222220222222212222222220222220212222222122222211222212222222222222222222222122222222222102222202222022222222202222202022222021222222120221220222122222222020222222212222222222222222202212222022222222222222222222222222222212222122222222222012222222202022222222212222222222222120222222122021222122222222222120222222202222222221222121202222222222222201222202222222222222222222222222222222222112221212202222222222202122212122222121222222122020221122122222222220222222212222222222222120212212222222222210222212222222222222222212222122222222222102221212202022222222212022222022222122222222221221222222022222222021222222222222222221222222222212222022222211222202222222222222222212202222222222222112221202222022220222202222202021222121222222220022220122022222222222222222212022222220222020202202222122222211222202222222202222222222222022222222222022222202222222222222202222222120222121222222222120222122122222222221222222202222222222222122202222222122222211220222222222212222022212202122222222222212222222222122222222212022212020222022222222021022221222222222222220222222202022222222222120222222222022222222222222222222202222022202202122222222222012222202212022221222202122212220222120222222222022222022222222222021222221222122222220022220212202222122222200220202222222222222022202200122222222222002221212202122221222202122212222222121222222221120222222122222222221222222212222222220222020222212222022222222220212222222202222122202221122222222222202222222222122222022222122212022222120222222222121220222022222222021222222212022222220122022212202222122222212220212222222212222122222212022222222222222220202212122220122202022212122222022222222021122221122122222222021222221202222222220122100222202122122222200221202222222202222122212201022222222222122220202122022222122212122212020222120222222120121220122222222222220222222212122222220122122222202122022222201222202222222222222022212201122222222222102220212202122222122222022222020222022222222221021222022022222222022222222222122222220222011202222122222222200221222222222212212222202220222222222222002221212022122221022222222212021222220222222122220221222022222222122222221222222222220022201222202122222222212221212222222212002022222201122222222222112222212022022221122222222202120222221222222220020222022122222222122222222212022222220222001202212122122222222222212222222212222022222222222022222222212222222212122221122212122202122222222222222222021220222122222222022222222202222222222222101212212222122222201222222222222212202122212210122122222222002222202202122220222202022212221222122212222020220221022222222222101222220202022222220122110222212122222222222220202222222202122122212202022122222222102221212022222222222202122202022222122222222020221221122022222222122222221202022222221022202202222022122222221220222222222222022222202202222221222222222222202202122220222202122222220222020212222021122220122222222222121222220222022222221122120212222122122222222221202222222202122222222211022222222222222222222102122220122202222212120222122222222122222221022122222222022222222202122222222022021222222222122222210221212222222202022122222202022222222222112222222122222222022222222212220222120202222220021221122022222222121222220202222222221022200212212222022222220221202222222212212022222221122022222222222220222022022221122212222212022222221222222122122221022222222222001222221202022222222022001222212222122222200220212222222212212022222200122220222222212221202022222221222222022222122222020222222020022222222222222222010222222202122222222222122202222022022122221222202222222212012022212200122120222222022220202102222221022212122222122222220212222220222222222022222222001222222202122222222022202222212222022222220221202222222202202222222221022222222222212222212122022222122202122222020222222222222121222222022122222222121222222212022222220222212222202222122022212222202222222212102022202221022222222022222220202002022221022202222202120222020212222220121221222122222222002222220222022222220222021222221222222022200222222222222202002022212220022222222222112221202212222222022212022212222222221212222120220221022222222222201222222221222222222122200202200222222122211221212222222222222222222220222222222122112221202112122221022212022212120222220212222121020222222122222222021222222222022222221222121212210222222122222221202222222202102012212221022022222122002220212122222221222222222202221222021202222121221220022222222222211222221221022222220022021202212022122122220220222222222212022112212220022220222222102220212122222220022222222202020222021222222020221221022222222222102222221200222222221022212202210222022122200220202222222222002222222212122222222222022220212112222220222212222202121222121212222221021222122122222222121222220211222222221222120222210022222222220220202222222212122102202202022020222022212220222002022222222202022202221222222212222121021020222022222222102222220210022222222222010202222122022222212221212222222222202122202201222120222002022220202022222221022222122222120222021222222222121122022222222222022222220211202222200022221212212120022022201220202222222222002102222212222121222102112220222102222220122202022212120222222202222121120120022022222222210222221220212222202222202212200220222222200222212222222202022022222212222221222012102220212102022222022012222212021222121222222021120120122022222222202222221222022222202022012222222122022122220221212222222212122002212220221021222002222222222002022222222202122212221222021222222120020221122022222222202222221212222222202222022212200021122222221220202222222202212202222201020120222222012222202202122221222002122112220222021212222120122021122122222222122222222200102222202022212012221022122122212222212222222012012122222212022022222122012221212002122222122112222102022222022212222222220121022022222222011222221200202222220122021002200022022022201222222222222122212002202212120022222012212222202002122222022002222212021222022202221221020022022122222222120222220212112222222222210102222120222022200220202222222102112012222221222120222002112220212112122220222202122212220222121222220020101022122222222222110222220202202222201122011122200220222222222220222222222122102202222212120120222212002221212112022222022002022002120222020222220121112221122222222222210222221200202222212022112222220022222122220221212222222112212022222222020020222012022221212112122221022202022202221222120212200220021221022222222222221222220221022222220022010222212020022222222220202222222102112102202210020221022022112222202102122222222112222012222222120212221121001020222222222222221222221211222222212122122122200220222122211221202222022002222212222000221121022122012220202122122221022122222012221222120212210221110022022222222222022222222220012222221222200212202120222122220220212222122212002202222021222122222102212121212112022222022102002102020222020212211220001022022222222222121222222222112222202022121002202121122222221220202122222002022022222110222222222222222020212222122220122002222022022222022212211020122121122022222222221222221210002222212022101122200020222122221220222122122112122002222020022222122202012021212222122222222002002122220222021212222121202122022222222222210222221211022222221122122022212220122222200222202122122022012112212112021122022112202222212022022221122222102222122222022222222020210220222122222222122222220211002222201122202022221222122022202220222122122222022222222221120020222222212121212102122222022022212122120222122222221120210122222222022222100222221210122222202122112222211222022222201222202220122102002222222111221201222101212020222122222221222022002222220222022202221120011022122022122222202222220221202222002122011122201120122022220222202021022012112102202000121201222210212020212122022221222112112112020222222222222220211110122022122222012222222202202222202022022222211122022122201220212221122002002112212221120121022000212220202102122222222112122022220222021202220220020010022122122222210222220221112222200122201012200122222122200222212122220121212222202000120110122101212220212202122220122222022022020222120222220122201112022122122222010222220220012222001222211112222022122122202220222121220110222202222001220101122100112122212002122221122122212202020222020212210022212111022022222222121222222221112222112222202102222222222122200222222120222012102122202221220102022100022120222122222220122122120102122222222212212020200201122022022222221222221220002222211022111012212221222222220221212120120112222012202120121101222101002220202120120122222222111112221222121202210221001000222122022222000222222211222222001222110202212022222222212221212221120100012102202210020211022101122021212122222022122112221102120222022212201022120111222022222222210222222211112222120122100012201020122022212221222220120200012122202200222121122101112221221211022120222122222022221222021222210120211112022122222222112222221210112222022222000212201020222222211221210221121000102102212020121120022102022120202201220220222222010012222222121202202000002222222022022222010222222202202222020222002122212122222022222221010121221212112202212111021111222022022020221000120122222202012212120222012222210012221102022222022222021222220201102222110022110002220020222122212220021222120002212202202121222200022200112021202110020221122122222122220222110222211211022111222022122222011222221210012222210022100212212222222002122220202222222102222222112110022111222020022221211110121221022112020012220222011212210220101100222122122222000222221210112222100122001222222120222202021222000120221221122102112121020210222010222122210212120122222012211102122222021212201211202220222022122222221222220201202222221222222212200220122202110222202120020122022222112010021000222210122022220011122022222222022222021220002222020011212102122122222222002222222221112222112222011002212122222112002201200022120221002102012220022000122220002222200010021121122002002122221222121202101121101012022222222222121222222200002222112022020102202122022112210200101021221100222202212021021111022120222020200110222220222122220222222220000222110211022120122222222222000222221210112222020122012202212122222002001210210120122220212202002100021220022212122121200102021021222202120122021222220202220001001221022122122222122222220212122222112022210122212121022012011201010020220222022112112211222011122212112022212022221022022002012112221221221202022022200210122222222222222222221212112222002222122102222020222102222222020220220120212112202111020212222012102122221222122121222212222212222221210022021222212101222022122222211122222201021222121002112202210220122022020221212121122110222212102222020210022122022022222102021122222212002012122200000022102111201200222122022222000122222220000222110102200012220022222122022221220220221011122102212102220002022101102222220121120022122212200102122200102022102200202122022122022222122122221222200222120222002122202022022112220211122021022111222002022120121220022122022222211211021122022122102022222220201112112112002002122122022222020222222200111220102222020122221221222202122202210221220121122022212220120011022011002121211212121022222022022212221212221102212022022101122122222222110222222220021220202202100012212221122202022220211021222012112222002100120010022022212221201121222221222212001122020200212002202110101121122022122222002022222120011222001002210112202022222002022212121121120021102012202002221120022221002022002211021120222222201020221220110012120201202111022222222222202022220212020221002022202002202020022112222221022121020221102212022121221220022121012122000101020020222212111202020210200102121101001210122022022222021122221002222222111112002012221220022102201220012122222101022212122200220021122220112120220202020020222022120002122210121002121001211222022122022222101122221211121220202022120112212021222022100201100020120112002212002001022021222121102222101001120220222212200121122210112122011211010220022022022222100122222010200222222212100222222020122022202211121020122002102222112020022200222122022222002001121120222102001001020221220222220021121202022222022222011022221120212222111222100122202222222211220210211020120212102112212021020020022112012122202110220120122102221011121211000012112201221211012122022222120222222000021222212222211012220022222102021201222022220022022222002201122100022201212022011000021000222002200100222220212022212111002222012122122222201222220020100221120022102212200120222102002201101221120001122022022010121121222220222222210202120101022122121011020020121022222102012010202122122222212022221002101222101012100222220120022202111211202221221201002202222022121110222200202022021100020010122012102011222220122022201212020200222022022222010122222021222021001122210002221120122111220221121220220110002002112001122000022012122121000212022212122212121100122122201110221211112102002122022222020022220001112221112202020102221022022022012201221120221111022212112112121111122022202221110101021122122222210111020111221200011001021020002222122222201222220202101121201112010122211122222011112201102221022200122022012121121200122010212021111022021112122122000021122210100000021000220122222022122222121122220020012222020202112122220122022122112202211220222202212202000120022200222201012022201220020200122112022010221011022120220102201222202022122222220020222201010022010122222012222022222102100212200221121221022102110021220010222201211120121120120020022212110002120220112122111220111221202022222222211121220110021020102012100102220222222211202220222021021002202212110222120012022121222121212202122220022222112020022122112121112111202212122022122222101221221001210122220202102222202220022012222210021120221211012212022222021011122012021222022110220020022112000022022200122012220212102100022122022222000121120211020120100212200012200122022112211210212122021212202022121011022000120022012221220220020121122122222120120201000121220210002210002122222220201121121101101022110122010112202021222122120222021020020001022102120202021212121210011121110021021012122012111212021121201200021010001200012122222220201021120000011020212002210222201220022220222211122022120111012022101201221220212002122120112112221001122101021212121020100202201020202020012222222222010021222201002121221201202010111012000000120021022102012211120100001100000220102221021011011002200112010111012101102112201021120220001010120200100111202002112122101210121' wide, tall = 25, 6 img = split(data) bm = wide * tall it = int(len(img) / bm) layer_zeros = {} for i in range(it): layer = img[(bm*i):(bm*(i+1))] print((bm*i),(bm*(i+1))) zeros = 0 for num in layer: if num == 0: zeros += 1 layer_zeros[i] = zeros min_layer = 0 minl = layer_zeros[0] for k, v in layer_zeros.items(): if minl > v: min_layer = k minl = v layer = img[(bm*min_layer):(bm*(min_layer+1))] num_1 = 0 num_2 = 0 for num in layer: if num == 1: num_1 += 1 elif num == 2: num_2 += 1 print(num_1 * num_2)
421.540541
15,009
0.984484
def split(word): return [int(char) for char in word] data = '222221202212222122222211222222222222222222222202222022222222222002221222222222220222202222202122222020222222021020220022122222222220222222202222222222222221202202222122222222222222222222222222222202222022222222222022220222222222220222212222212222222220222222221121222022022222222222222222212222222222222220202202222122222210222222222222222222222202222122222222222212222222222022222222212022212122222020222222122021221222122222222221222222222222222222222221202202222022222221222222222222222222222212222022222222222022220222222122222222202122222022222021222222220220220022222222222220222222202222222222222221202222222122222220222212222222222222222202222222222222222022222212222022220222202022202022222120222222121020222122222222222221222222202222222222222221202212222022222221222222222222222222222202222022222222222212220222202022220222202222202022222121222222020021222122022222222220222222212222222220222220212222222122222211222212222222222222222222222122222222222102222202222022222222202222202022222021222222120221220222122222222020222222212222222222222222202212222022222222222222222222222222222212222122222222222012222222202022222222212222222222222120222222122021222122222222222120222222202222222221222121202222222222222201222202222222222222222222222222222222222112221212202222222222202122212122222121222222122020221122122222222220222222212222222222222120212212222222222210222212222222222222222212222122222222222102221212202022222222212022222022222122222222221221222222022222222021222222222222222221222222222212222022222211222202222222222222222212202222222222222112221202222022220222202222202021222121222222220022220122022222222222222222212022222220222020202202222122222211222202222222202222222222222022222222222022222202222222222222202222222120222121222222222120222122122222222221222222202222222222222122202222222122222211220222222222212222022212202122222222222212222222222122222222212022212020222022222222021022221222222222222220222222202022222222222120222222222022222222222222222222202222022202202122222222222012222202212022221222202122212220222120222222222022222022222222222021222221222122222220022220212202222122222200220202222222222222022202200122222222222002221212202122221222202122212222222121222222221120222222122222222221222222212222222220222020222212222022222222220212222222202222122202221122222222222202222222222122222022222122212022222120222222222121220222022222222021222222212022222220122022212202222122222212220212222222212222122222212022222222222222220202212122220122202022212122222022222222021122221122122222222021222221202222222220122100222202122122222200221202222222202222122212201022222222222122220202122022222122212122212020222120222222120121220122222222222220222222212122222220122122222202122022222201222202222222222222022212201122222222222102220212202122222122222022222020222022222222221021222022022222222022222222222122222220222011202222122222222200221222222222212212222202220222222222222002221212022122221022222222212021222220222222122220221222022222222122222221222222222220022201222202122222222212221212222222212002022222201122222222222112222212022022221122222222202120222221222222220020222022122222222122222222212022222220222001202212122122222222222212222222212222022222222222022222222212222222212122221122212122202122222222222222222021220222122222222022222222202222222222222101212212222122222201222222222222212202122212210122122222222002222202202122220222202022212221222122212222020220221022222222222101222220202022222220122110222212122222222222220202222222202122122212202022122222222102221212022222222222202122202022222122222222020221221122022222222122222221202022222221022202202222022122222221220222222222222022222202202222221222222222222202202122220222202122222220222020212222021122220122222222222121222220222022222221122120212222122122222222221202222222202122222222211022222222222222222222102122220122202222212120222122222222122222221022122222222022222222202122222222022021222222222122222210221212222222202022122222202022222222222112222222122222222022222222212220222120202222220021221122022222222121222220202222222221022200212212222022222220221202222222212212022222221122022222222222220222022022221122212222212022222221222222122122221022222222222001222221202022222222022001222212222122222200220212222222212212022222200122220222222212221202022222221222222022222122222020222222020022222222222222222010222222202122222222222122202222022022122221222202222222212012022212200122120222222022220202102222221022212122222122222220212222220222222222022222222001222222202122222222022202222212222022222220221202222222202202222222221022222222222212222212122022222122202122222020222222222222121222222022122222222121222222212022222220222212222202222122022212222202222222212102022202221022222222022222220202002022221022202222202120222020212222220121221222122222222002222220222022222220222021222221222222022200222222222222202002022212220022222222222112221202212222222022212022212222222221212222120220221022222222222201222222221222222222122200202200222222122211221212222222222222222222220222222222122112221202112122221022212022212120222220212222121020222222122222222021222222222022222221222121212210222222122222221202222222202102012212221022022222122002220212122222221222222222202221222021202222121221220022222222222211222221221022222220022021202212022122122220220222222222212022112212220022220222222102220212122222220022222222202020222021222222020221221022222222222102222221200222222221022212202210222022122200220202222222222002222222212122222222222022220212112222220222212222202121222121212222221021222122122222222121222220211222222221222120222210022222222220220202222222212122102202202022020222022212220222002022222222202022202221222222212222121021020222022222222102222220210022222222222010202222122022222212221212222222222202122202201222120222002022220202022222221022222122222120222021222222222121122022222222222022222220211202222200022221212212120022022201220202222222222002102222212222121222102112220222102222220122202022212120222222202222121120120022022222222210222221220212222202222202212200220222222200222212222222202022022222212222221222012102220212102022222022012222212021222121222222021120120122022222222202222221222022222202022012222222122022122220221212222222212122002212220221021222002222222222002022222222202122212221222021222222120020221122022222222202222221212222222202222022212200021122222221220202222222202212202222201020120222222012222202202122221222002122112220222021212222120122021122122222222122222222200102222202022212012221022122122212222212222222012012122222212022022222122012221212002122222122112222102022222022212222222220121022022222222011222221200202222220122021002200022022022201222222222222122212002202212120022222012212222202002122222022002222212021222022202221221020022022122222222120222220212112222222222210102222120222022200220202222222102112012222221222120222002112220212112122220222202122212220222121222220020101022122222222222110222220202202222201122011122200220222222222220222222222122102202222212120120222212002221212112022222022002022002120222020222220121112221122222222222210222221200202222212022112222220022222122220221212222222112212022222222020020222012022221212112122221022202022202221222120212200220021221022222222222221222220221022222220022010222212020022222222220202222222102112102202210020221022022112222202102122222222112222012222222120212221121001020222222222222221222221211222222212122122122200220222122211221202222022002222212222000221121022122012220202122122221022122222012221222120212210221110022022222222222022222222220012222221222200212202120222122220220212222122212002202222021222122222102212121212112022222022102002102020222020212211220001022022222222222121222222222112222202022121002202121122222221220202122222002022022222110222222222222222020212222122220122002222022022222022212211020122121122022222222221222221210002222212022101122200020222122221220222122122112122002222020022222122202012021212222122222222002002122220222021212222121202122022222222222210222221211022222221122122022212220122222200222202122122022012112212112021122022112202222212022022221122222102222122222022222222020210220222122222222122222220211002222201122202022221222122022202220222122122222022222222221120020222222212121212102122222022022212122120222122222221120210122222222022222100222221210122222202122112222211222022222201222202220122102002222222111221201222101212020222122222221222022002222220222022202221120011022122022122222202222220221202222002122011122201120122022220222202021022012112102202000121201222210212020212122022221222112112112020222222222222220211110122022122222012222222202202222202022022222211122022122201220212221122002002112212221120121022000212220202102122222222112122022220222021202220220020010022122122222210222220221112222200122201012200122222122200222212122220121212222202000120110122101212220212202122220122222022022020222120222220122201112022122122222010222220220012222001222211112222022122122202220222121220110222202222001220101122100112122212002122221122122212202020222020212210022212111022022222222121222222221112222112222202102222222222122200222222120222012102122202221220102022100022120222122222220122122120102122222222212212020200201122022022222221222221220002222211022111012212221222222220221212120120112222012202120121101222101002220202120120122222222111112221222121202210221001000222122022222000222222211222222001222110202212022222222212221212221120100012102202210020211022101122021212122222022122112221102120222022212201022120111222022222222210222222211112222120122100012201020122022212221222220120200012122202200222121122101112221221211022120222122222022221222021222210120211112022122222222112222221210112222022222000212201020222222211221210221121000102102212020121120022102022120202201220220222222010012222222121202202000002222222022022222010222222202202222020222002122212122222022222221010121221212112202212111021111222022022020221000120122222202012212120222012222210012221102022222022222021222220201102222110022110002220020222122212220021222120002212202202121222200022200112021202110020221122122222122220222110222211211022111222022122222011222221210012222210022100212212222222002122220202222222102222222112110022111222020022221211110121221022112020012220222011212210220101100222122122222000222221210112222100122001222222120222202021222000120221221122102112121020210222010222122210212120122222012211102122222021212201211202220222022122222221222220201202222221222222212200220122202110222202120020122022222112010021000222210122022220011122022222222022222021220002222020011212102122122222222002222222221112222112222011002212122222112002201200022120221002102012220022000122220002222200010021121122002002122221222121202101121101012022222222222121222222200002222112022020102202122022112210200101021221100222202212021021111022120222020200110222220222122220222222220000222110211022120122222222222000222221210112222020122012202212122222002001210210120122220212202002100021220022212122121200102021021222202120122021222220202220001001221022122122222122222220212122222112022210122212121022012011201010020220222022112112211222011122212112022212022221022022002012112221221221202022022200210122222222222222222221212112222002222122102222020222102222222020220220120212112202111020212222012102122221222122121222212222212222221210022021222212101222022122222211122222201021222121002112202210220122022020221212121122110222212102222020210022122022022222102021122222212002012122200000022102111201200222122022222000122222220000222110102200012220022222122022221220220221011122102212102220002022101102222220121120022122212200102122200102022102200202122022122022222122122221222200222120222002122202022022112220211122021022111222002022120121220022122022222211211021122022122102022222220201112112112002002122122022222020222222200111220102222020122221221222202122202210221220121122022212220120011022011002121211212121022222022022212221212221102212022022101122122222222110222222220021220202202100012212221122202022220211021222012112222002100120010022022212221201121222221222212001122020200212002202110101121122022122222002022222120011222001002210112202022222002022212121121120021102012202002221120022221002022002211021120222222201020221220110012120201202111022222222222202022220212020221002022202002202020022112222221022121020221102212022121221220022121012122000101020020222212111202020210200102121101001210122022022222021122221002222222111112002012221220022102201220012122222101022212122200220021122220112120220202020020222022120002122210121002121001211222022122022222101122221211121220202022120112212021222022100201100020120112002212002001022021222121102222101001120220222212200121122210112122011211010220022022022222100122222010200222222212100222222020122022202211121020122002102222112020022200222122022222002001121120222102001001020221220222220021121202022222022222011022221120212222111222100122202222222211220210211020120212102112212021020020022112012122202110220120122102221011121211000012112201221211012122022222120222222000021222212222211012220022222102021201222022220022022222002201122100022201212022011000021000222002200100222220212022212111002222012122122222201222220020100221120022102212200120222102002201101221120001122022022010121121222220222222210202120101022122121011020020121022222102012010202122122222212022221002101222101012100222220120022202111211202221221201002202222022121110222200202022021100020010122012102011222220122022201212020200222022022222010122222021222021001122210002221120122111220221121220220110002002112001122000022012122121000212022212122212121100122122201110221211112102002122022222020022220001112221112202020102221022022022012201221120221111022212112112121111122022202221110101021122122222210111020111221200011001021020002222122222201222220202101121201112010122211122222011112201102221022200122022012121121200122010212021111022021112122122000021122210100000021000220122222022122222121122220020012222020202112122220122022122112202211220222202212202000120022200222201012022201220020200122112022010221011022120220102201222202022122222220020222201010022010122222012222022222102100212200221121221022102110021220010222201211120121120120020022212110002120220112122111220111221202022222222211121220110021020102012100102220222222211202220222021021002202212110222120012022121222121212202122220022222112020022122112121112111202212122022122222101221221001210122220202102222202220022012222210021120221211012212022222021011122012021222022110220020022112000022022200122012220212102100022122022222000121120211020120100212200012200122022112211210212122021212202022121011022000120022012221220220020121122122222120120201000121220210002210002122222220201121121101101022110122010112202021222122120222021020020001022102120202021212121210011121110021021012122012111212021121201200021010001200012122222220201021120000011020212002210222201220022220222211122022120111012022101201221220212002122120112112221001122101021212121020100202201020202020012222222222010021222201002121221201202010111012000000120021022102012211120100001100000220102221021011011002200112010111012101102112201021120220001010120200100111202002112122101210121' wide, tall = 25, 6 img = split(data) bm = wide * tall it = int(len(img) / bm) layer_zeros = {} for i in range(it): layer = img[(bm*i):(bm*(i+1))] print((bm*i),(bm*(i+1))) zeros = 0 for num in layer: if num == 0: zeros += 1 layer_zeros[i] = zeros min_layer = 0 minl = layer_zeros[0] for k, v in layer_zeros.items(): if minl > v: min_layer = k minl = v layer = img[(bm*min_layer):(bm*(min_layer+1))] num_1 = 0 num_2 = 0 for num in layer: if num == 1: num_1 += 1 elif num == 2: num_2 += 1 print(num_1 * num_2)
32
0
22
84afb8ee0a1db12ea2f24da153608e4935cd8f4c
1,924
py
Python
cl_app/models.py
talley/craigslistpython
fbc6e9fc64a7bcaaded0d369259a338cf1c91194
[ "MIT" ]
22
2018-06-03T08:30:49.000Z
2021-12-31T19:10:36.000Z
cl_app/models.py
talley/craigslistpython
fbc6e9fc64a7bcaaded0d369259a338cf1c91194
[ "MIT" ]
10
2019-02-19T13:08:47.000Z
2022-03-11T23:15:44.000Z
cl_app/models.py
talley/craigslistpython
fbc6e9fc64a7bcaaded0d369259a338cf1c91194
[ "MIT" ]
20
2018-07-30T17:19:59.000Z
2022-03-23T23:58:13.000Z
from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token # Create your models here. @receiver(post_save, sender='auth.User') @receiver(post_save, sender='auth.User')
27.884058
110
0.703222
from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token # Create your models here. class City(models.Model): city = models.CharField(max_length=20) def __str__(self): return self.city class Profile(models.Model): user = models.OneToOneField('auth.User') profile_city = models.ForeignKey(City, verbose_name='Preferred City', null=True) preferred_contact = models.CharField(max_length=30, null=True) def __str__(self): return str(self.user) class ListingType(models.Model): name = models.CharField(max_length=20) parent = models.ForeignKey("self", null=True, blank=True, related_name='subcat') def __str__(self): return self.name class Listing(models.Model): user = models.ForeignKey('auth.User') listing_city = models.ForeignKey(City) category = models.ForeignKey(ListingType) title = models.CharField(max_length=40) price = models.IntegerField() description = models.TextField() photo = models.ImageField(upload_to="listing_photos", null=True, blank=True, verbose_name="Listing Photo") created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Meta: ordering = ['-created'] @property def photo_url(self): if self.photo: return self.photo.url return "/media/listing_photos/classifieds-default.jpg" @receiver(post_save, sender='auth.User') def create_user_profile(**kwargs): created = kwargs.get("created") instance = kwargs.get("instance") if created: Profile.objects.create(user=instance) @receiver(post_save, sender='auth.User') def create_token(**kwargs): created = kwargs.get('created') instance = kwargs.get('instance') if created: Token.objects.create(user=instance)
502
1,006
135
1e722a1d7391c3f290ab84597dac0ae35ca009d8
117,805
py
Python
openapi_netdisco/api/reports_api.py
mksoska/openapi-client-netdisco
d6444505307e4897a9fef1ded60a180eb764d4b8
[ "MIT" ]
null
null
null
openapi_netdisco/api/reports_api.py
mksoska/openapi-client-netdisco
d6444505307e4897a9fef1ded60a180eb764d4b8
[ "MIT" ]
null
null
null
openapi_netdisco/api/reports_api.py
mksoska/openapi-client-netdisco
d6444505307e4897a9fef1ded60a180eb764d4b8
[ "MIT" ]
null
null
null
# coding: utf-8 """ App::Netdisco No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: 2.050003 Generated by: https://openapi-generator.tech """ from __future__ import absolute_import import re # noqa: F401 # python 2 and python 3 compatibility library import six from openapi_netdisco.api_client import ApiClient from openapi_netdisco.exceptions import ( # noqa: F401 ApiTypeError, ApiValueError ) class ReportsApi(object): """NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. """ def api_v1_report_device_deviceaddrnodns_get(self, **kwargs): # noqa: E501 """api_v1_report_device_deviceaddrnodns_get # noqa: E501 Addresses without DNS Entries Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_device_deviceaddrnodns_get(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ kwargs['_return_http_data_only'] = True return self.api_v1_report_device_deviceaddrnodns_get_with_http_info(**kwargs) # noqa: E501 def api_v1_report_device_deviceaddrnodns_get_with_http_info(self, **kwargs): # noqa: E501 """api_v1_report_device_deviceaddrnodns_get # noqa: E501 Addresses without DNS Entries Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_device_deviceaddrnodns_get_with_http_info(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ local_var_params = locals() all_params = [ ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method api_v1_report_device_deviceaddrnodns_get" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # Authentication setting auth_settings = ['APIKeyHeader'] # noqa: E501 response_types_map = {} return self.api_client.call_api( '/api/v1/report/device/deviceaddrnodns', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) def api_v1_report_device_devicebylocation_get(self, **kwargs): # noqa: E501 """api_v1_report_device_devicebylocation_get # noqa: E501 By Location Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_device_devicebylocation_get(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ kwargs['_return_http_data_only'] = True return self.api_v1_report_device_devicebylocation_get_with_http_info(**kwargs) # noqa: E501 def api_v1_report_device_devicebylocation_get_with_http_info(self, **kwargs): # noqa: E501 """api_v1_report_device_devicebylocation_get # noqa: E501 By Location Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_device_devicebylocation_get_with_http_info(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ local_var_params = locals() all_params = [ ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method api_v1_report_device_devicebylocation_get" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # Authentication setting auth_settings = ['APIKeyHeader'] # noqa: E501 response_types_map = {} return self.api_client.call_api( '/api/v1/report/device/devicebylocation', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) def api_v1_report_device_devicednsmismatch_get(self, **kwargs): # noqa: E501 """api_v1_report_device_devicednsmismatch_get # noqa: E501 Device Name / DNS Mismatches Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_device_devicednsmismatch_get(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ kwargs['_return_http_data_only'] = True return self.api_v1_report_device_devicednsmismatch_get_with_http_info(**kwargs) # noqa: E501 def api_v1_report_device_devicednsmismatch_get_with_http_info(self, **kwargs): # noqa: E501 """api_v1_report_device_devicednsmismatch_get # noqa: E501 Device Name / DNS Mismatches Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_device_devicednsmismatch_get_with_http_info(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ local_var_params = locals() all_params = [ ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method api_v1_report_device_devicednsmismatch_get" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # Authentication setting auth_settings = ['APIKeyHeader'] # noqa: E501 response_types_map = {} return self.api_client.call_api( '/api/v1/report/device/devicednsmismatch', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) def api_v1_report_device_devicepoestatus_get(self, **kwargs): # noqa: E501 """api_v1_report_device_devicepoestatus_get # noqa: E501 Power over Ethernet (PoE) Status Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_device_devicepoestatus_get(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ kwargs['_return_http_data_only'] = True return self.api_v1_report_device_devicepoestatus_get_with_http_info(**kwargs) # noqa: E501 def api_v1_report_device_devicepoestatus_get_with_http_info(self, **kwargs): # noqa: E501 """api_v1_report_device_devicepoestatus_get # noqa: E501 Power over Ethernet (PoE) Status Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_device_devicepoestatus_get_with_http_info(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ local_var_params = locals() all_params = [ ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method api_v1_report_device_devicepoestatus_get" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # Authentication setting auth_settings = ['APIKeyHeader'] # noqa: E501 response_types_map = {} return self.api_client.call_api( '/api/v1/report/device/devicepoestatus', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) def api_v1_report_device_portutilization_get(self, **kwargs): # noqa: E501 """api_v1_report_device_portutilization_get # noqa: E501 Port Utilization Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_device_portutilization_get(async_req=True) >>> result = thread.get() :param age_num: Mark as Free if down for (quantity) :type age_num: str :param age_unit: Mark as Free if down for (period) :type age_unit: str :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: list[PortUtilization] """ kwargs['_return_http_data_only'] = True return self.api_v1_report_device_portutilization_get_with_http_info(**kwargs) # noqa: E501 def api_v1_report_device_portutilization_get_with_http_info(self, **kwargs): # noqa: E501 """api_v1_report_device_portutilization_get # noqa: E501 Port Utilization Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_device_portutilization_get_with_http_info(async_req=True) >>> result = thread.get() :param age_num: Mark as Free if down for (quantity) :type age_num: str :param age_unit: Mark as Free if down for (period) :type age_unit: str :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: tuple(list[PortUtilization], status_code(int), headers(HTTPHeaderDict)) """ local_var_params = locals() all_params = [ 'age_num', 'age_unit' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method api_v1_report_device_portutilization_get" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] if 'age_num' in local_var_params and local_var_params['age_num'] is not None: # noqa: E501 query_params.append(('age_num', local_var_params['age_num'])) # noqa: E501 if 'age_unit' in local_var_params and local_var_params['age_unit'] is not None: # noqa: E501 query_params.append(('age_unit', local_var_params['age_unit'])) # 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 # Authentication setting auth_settings = ['APIKeyHeader'] # noqa: E501 response_types_map = { 200: "list[PortUtilization]", } return self.api_client.call_api( '/api/v1/report/device/portutilization', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) def api_v1_report_ip_ipinventory_get(self, **kwargs): # noqa: E501 """api_v1_report_ip_ipinventory_get # noqa: E501 IP Inventory Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_ip_ipinventory_get(async_req=True) >>> result = thread.get() :param subnet: IP Prefix to search :type subnet: str :param daterange: Date range to search :type daterange: str :param age_invert: Results should NOT be within daterange :type age_invert: bool :param limit: Maximum number of historical records :type limit: str :param never: Include in the report IPs never seen :type never: bool :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ kwargs['_return_http_data_only'] = True return self.api_v1_report_ip_ipinventory_get_with_http_info(**kwargs) # noqa: E501 def api_v1_report_ip_ipinventory_get_with_http_info(self, **kwargs): # noqa: E501 """api_v1_report_ip_ipinventory_get # noqa: E501 IP Inventory Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_ip_ipinventory_get_with_http_info(async_req=True) >>> result = thread.get() :param subnet: IP Prefix to search :type subnet: str :param daterange: Date range to search :type daterange: str :param age_invert: Results should NOT be within daterange :type age_invert: bool :param limit: Maximum number of historical records :type limit: str :param never: Include in the report IPs never seen :type never: bool :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ local_var_params = locals() all_params = [ 'subnet', 'daterange', 'age_invert', 'limit', 'never' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method api_v1_report_ip_ipinventory_get" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] if 'subnet' in local_var_params and local_var_params['subnet'] is not None: # noqa: E501 query_params.append(('subnet', local_var_params['subnet'])) # noqa: E501 if 'daterange' in local_var_params and local_var_params['daterange'] is not None: # noqa: E501 query_params.append(('daterange', local_var_params['daterange'])) # noqa: E501 if 'age_invert' in local_var_params and local_var_params['age_invert'] is not None: # noqa: E501 query_params.append(('age_invert', local_var_params['age_invert'])) # noqa: E501 if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501 query_params.append(('limit', local_var_params['limit'])) # noqa: E501 if 'never' in local_var_params and local_var_params['never'] is not None: # noqa: E501 query_params.append(('never', local_var_params['never'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # Authentication setting auth_settings = ['APIKeyHeader'] # noqa: E501 response_types_map = {} return self.api_client.call_api( '/api/v1/report/ip/ipinventory', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) def api_v1_report_ip_subnets_get(self, **kwargs): # noqa: E501 """api_v1_report_ip_subnets_get # noqa: E501 Subnet Utilization Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_ip_subnets_get(async_req=True) >>> result = thread.get() :param subnet: IP Prefix to search :type subnet: str :param daterange: Date range to search :type daterange: str :param age_invert: Results should NOT be within daterange :type age_invert: bool :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ kwargs['_return_http_data_only'] = True return self.api_v1_report_ip_subnets_get_with_http_info(**kwargs) # noqa: E501 def api_v1_report_ip_subnets_get_with_http_info(self, **kwargs): # noqa: E501 """api_v1_report_ip_subnets_get # noqa: E501 Subnet Utilization Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_ip_subnets_get_with_http_info(async_req=True) >>> result = thread.get() :param subnet: IP Prefix to search :type subnet: str :param daterange: Date range to search :type daterange: str :param age_invert: Results should NOT be within daterange :type age_invert: bool :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ local_var_params = locals() all_params = [ 'subnet', 'daterange', 'age_invert' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method api_v1_report_ip_subnets_get" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] if 'subnet' in local_var_params and local_var_params['subnet'] is not None: # noqa: E501 query_params.append(('subnet', local_var_params['subnet'])) # noqa: E501 if 'daterange' in local_var_params and local_var_params['daterange'] is not None: # noqa: E501 query_params.append(('daterange', local_var_params['daterange'])) # noqa: E501 if 'age_invert' in local_var_params and local_var_params['age_invert'] is not None: # noqa: E501 query_params.append(('age_invert', local_var_params['age_invert'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # Authentication setting auth_settings = ['APIKeyHeader'] # noqa: E501 response_types_map = {} return self.api_client.call_api( '/api/v1/report/ip/subnets', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) def api_v1_report_node_nodemultiips_get(self, **kwargs): # noqa: E501 """api_v1_report_node_nodemultiips_get # noqa: E501 Nodes with multiple active IP addresses Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_node_nodemultiips_get(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ kwargs['_return_http_data_only'] = True return self.api_v1_report_node_nodemultiips_get_with_http_info(**kwargs) # noqa: E501 def api_v1_report_node_nodemultiips_get_with_http_info(self, **kwargs): # noqa: E501 """api_v1_report_node_nodemultiips_get # noqa: E501 Nodes with multiple active IP addresses Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_node_nodemultiips_get_with_http_info(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ local_var_params = locals() all_params = [ ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method api_v1_report_node_nodemultiips_get" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # Authentication setting auth_settings = ['APIKeyHeader'] # noqa: E501 response_types_map = {} return self.api_client.call_api( '/api/v1/report/node/nodemultiips', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) def api_v1_report_node_nodesdiscovered_get(self, **kwargs): # noqa: E501 """api_v1_report_node_nodesdiscovered_get # noqa: E501 Nodes discovered through LLDP/CDP Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_node_nodesdiscovered_get(async_req=True) >>> result = thread.get() :param remote_id: Host Name reported :type remote_id: str :param remote_type: Platform reported :type remote_type: str :param aps: Include Wireless APs in the report :type aps: bool :param phones: Include IP Phones in the report :type phones: bool :param matchall: Match all parameters (true) or any (false) :type matchall: bool :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ kwargs['_return_http_data_only'] = True return self.api_v1_report_node_nodesdiscovered_get_with_http_info(**kwargs) # noqa: E501 def api_v1_report_node_nodesdiscovered_get_with_http_info(self, **kwargs): # noqa: E501 """api_v1_report_node_nodesdiscovered_get # noqa: E501 Nodes discovered through LLDP/CDP Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_node_nodesdiscovered_get_with_http_info(async_req=True) >>> result = thread.get() :param remote_id: Host Name reported :type remote_id: str :param remote_type: Platform reported :type remote_type: str :param aps: Include Wireless APs in the report :type aps: bool :param phones: Include IP Phones in the report :type phones: bool :param matchall: Match all parameters (true) or any (false) :type matchall: bool :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ local_var_params = locals() all_params = [ 'remote_id', 'remote_type', 'aps', 'phones', 'matchall' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method api_v1_report_node_nodesdiscovered_get" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] if 'remote_id' in local_var_params and local_var_params['remote_id'] is not None: # noqa: E501 query_params.append(('remote_id', local_var_params['remote_id'])) # noqa: E501 if 'remote_type' in local_var_params and local_var_params['remote_type'] is not None: # noqa: E501 query_params.append(('remote_type', local_var_params['remote_type'])) # noqa: E501 if 'aps' in local_var_params and local_var_params['aps'] is not None: # noqa: E501 query_params.append(('aps', local_var_params['aps'])) # noqa: E501 if 'phones' in local_var_params and local_var_params['phones'] is not None: # noqa: E501 query_params.append(('phones', local_var_params['phones'])) # noqa: E501 if 'matchall' in local_var_params and local_var_params['matchall'] is not None: # noqa: E501 query_params.append(('matchall', local_var_params['matchall'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # Authentication setting auth_settings = ['APIKeyHeader'] # noqa: E501 response_types_map = {} return self.api_client.call_api( '/api/v1/report/node/nodesdiscovered', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) def api_v1_report_port_duplexmismatch_get(self, **kwargs): # noqa: E501 """api_v1_report_port_duplexmismatch_get # noqa: E501 Duplex Mismatches Between Devices Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_port_duplexmismatch_get(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ kwargs['_return_http_data_only'] = True return self.api_v1_report_port_duplexmismatch_get_with_http_info(**kwargs) # noqa: E501 def api_v1_report_port_duplexmismatch_get_with_http_info(self, **kwargs): # noqa: E501 """api_v1_report_port_duplexmismatch_get # noqa: E501 Duplex Mismatches Between Devices Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_port_duplexmismatch_get_with_http_info(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ local_var_params = locals() all_params = [ ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method api_v1_report_port_duplexmismatch_get" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # Authentication setting auth_settings = ['APIKeyHeader'] # noqa: E501 response_types_map = {} return self.api_client.call_api( '/api/v1/report/port/duplexmismatch', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) def api_v1_report_port_halfduplex_get(self, **kwargs): # noqa: E501 """api_v1_report_port_halfduplex_get # noqa: E501 Ports in Half Duplex Mode Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_port_halfduplex_get(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ kwargs['_return_http_data_only'] = True return self.api_v1_report_port_halfduplex_get_with_http_info(**kwargs) # noqa: E501 def api_v1_report_port_halfduplex_get_with_http_info(self, **kwargs): # noqa: E501 """api_v1_report_port_halfduplex_get # noqa: E501 Ports in Half Duplex Mode Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_port_halfduplex_get_with_http_info(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ local_var_params = locals() all_params = [ ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method api_v1_report_port_halfduplex_get" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # Authentication setting auth_settings = ['APIKeyHeader'] # noqa: E501 response_types_map = {} return self.api_client.call_api( '/api/v1/report/port/halfduplex', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) def api_v1_report_port_portadmindown_get(self, **kwargs): # noqa: E501 """api_v1_report_port_portadmindown_get # noqa: E501 Ports administratively disabled Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_port_portadmindown_get(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ kwargs['_return_http_data_only'] = True return self.api_v1_report_port_portadmindown_get_with_http_info(**kwargs) # noqa: E501 def api_v1_report_port_portadmindown_get_with_http_info(self, **kwargs): # noqa: E501 """api_v1_report_port_portadmindown_get # noqa: E501 Ports administratively disabled Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_port_portadmindown_get_with_http_info(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ local_var_params = locals() all_params = [ ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method api_v1_report_port_portadmindown_get" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # Authentication setting auth_settings = ['APIKeyHeader'] # noqa: E501 response_types_map = {} return self.api_client.call_api( '/api/v1/report/port/portadmindown', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) def api_v1_report_port_portblocking_get(self, **kwargs): # noqa: E501 """api_v1_report_port_portblocking_get # noqa: E501 Ports that are blocking Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_port_portblocking_get(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ kwargs['_return_http_data_only'] = True return self.api_v1_report_port_portblocking_get_with_http_info(**kwargs) # noqa: E501 def api_v1_report_port_portblocking_get_with_http_info(self, **kwargs): # noqa: E501 """api_v1_report_port_portblocking_get # noqa: E501 Ports that are blocking Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_port_portblocking_get_with_http_info(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ local_var_params = locals() all_params = [ ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method api_v1_report_port_portblocking_get" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # Authentication setting auth_settings = ['APIKeyHeader'] # noqa: E501 response_types_map = {} return self.api_client.call_api( '/api/v1/report/port/portblocking', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) def api_v1_report_port_portmultinodes_get(self, **kwargs): # noqa: E501 """api_v1_report_port_portmultinodes_get # noqa: E501 Ports with multiple nodes attached Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_port_portmultinodes_get(async_req=True) >>> result = thread.get() :param vlan: Filter by VLAN :type vlan: int :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ kwargs['_return_http_data_only'] = True return self.api_v1_report_port_portmultinodes_get_with_http_info(**kwargs) # noqa: E501 def api_v1_report_port_portmultinodes_get_with_http_info(self, **kwargs): # noqa: E501 """api_v1_report_port_portmultinodes_get # noqa: E501 Ports with multiple nodes attached Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_port_portmultinodes_get_with_http_info(async_req=True) >>> result = thread.get() :param vlan: Filter by VLAN :type vlan: int :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ local_var_params = locals() all_params = [ 'vlan' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method api_v1_report_port_portmultinodes_get" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] if 'vlan' in local_var_params and local_var_params['vlan'] is not None: # noqa: E501 query_params.append(('vlan', local_var_params['vlan'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # Authentication setting auth_settings = ['APIKeyHeader'] # noqa: E501 response_types_map = {} return self.api_client.call_api( '/api/v1/report/port/portmultinodes', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) def api_v1_report_port_portserrordisabled_get(self, **kwargs): # noqa: E501 """api_v1_report_port_portserrordisabled_get # noqa: E501 Error Disabled Ports Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_port_portserrordisabled_get(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ kwargs['_return_http_data_only'] = True return self.api_v1_report_port_portserrordisabled_get_with_http_info(**kwargs) # noqa: E501 def api_v1_report_port_portserrordisabled_get_with_http_info(self, **kwargs): # noqa: E501 """api_v1_report_port_portserrordisabled_get # noqa: E501 Error Disabled Ports Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_port_portserrordisabled_get_with_http_info(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ local_var_params = locals() all_params = [ ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method api_v1_report_port_portserrordisabled_get" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # Authentication setting auth_settings = ['APIKeyHeader'] # noqa: E501 response_types_map = {} return self.api_client.call_api( '/api/v1/report/port/portserrordisabled', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) def api_v1_report_port_portssid_get(self, **kwargs): # noqa: E501 """api_v1_report_port_portssid_get # noqa: E501 Port SSID Inventory Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_port_portssid_get(async_req=True) >>> result = thread.get() :param ssid: Get details for this SSID :type ssid: str :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ kwargs['_return_http_data_only'] = True return self.api_v1_report_port_portssid_get_with_http_info(**kwargs) # noqa: E501 def api_v1_report_port_portssid_get_with_http_info(self, **kwargs): # noqa: E501 """api_v1_report_port_portssid_get # noqa: E501 Port SSID Inventory Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_port_portssid_get_with_http_info(async_req=True) >>> result = thread.get() :param ssid: Get details for this SSID :type ssid: str :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ local_var_params = locals() all_params = [ 'ssid' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method api_v1_report_port_portssid_get" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] if 'ssid' in local_var_params and local_var_params['ssid'] is not None: # noqa: E501 query_params.append(('ssid', local_var_params['ssid'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # Authentication setting auth_settings = ['APIKeyHeader'] # noqa: E501 response_types_map = {} return self.api_client.call_api( '/api/v1/report/port/portssid', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) def api_v1_report_port_portvlanmismatch_get(self, **kwargs): # noqa: E501 """api_v1_report_port_portvlanmismatch_get # noqa: E501 Port VLAN Mismatches Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_port_portvlanmismatch_get(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ kwargs['_return_http_data_only'] = True return self.api_v1_report_port_portvlanmismatch_get_with_http_info(**kwargs) # noqa: E501 def api_v1_report_port_portvlanmismatch_get_with_http_info(self, **kwargs): # noqa: E501 """api_v1_report_port_portvlanmismatch_get # noqa: E501 Port VLAN Mismatches Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_port_portvlanmismatch_get_with_http_info(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ local_var_params = locals() all_params = [ ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method api_v1_report_port_portvlanmismatch_get" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # Authentication setting auth_settings = ['APIKeyHeader'] # noqa: E501 response_types_map = {} return self.api_client.call_api( '/api/v1/report/port/portvlanmismatch', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) def api_v1_report_vlan_vlaninventory_get(self, **kwargs): # noqa: E501 """api_v1_report_vlan_vlaninventory_get # noqa: E501 VLAN Inventory Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_vlan_vlaninventory_get(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ kwargs['_return_http_data_only'] = True return self.api_v1_report_vlan_vlaninventory_get_with_http_info(**kwargs) # noqa: E501 def api_v1_report_vlan_vlaninventory_get_with_http_info(self, **kwargs): # noqa: E501 """api_v1_report_vlan_vlaninventory_get # noqa: E501 VLAN Inventory Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_vlan_vlaninventory_get_with_http_info(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ local_var_params = locals() all_params = [ ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method api_v1_report_vlan_vlaninventory_get" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # Authentication setting auth_settings = ['APIKeyHeader'] # noqa: E501 response_types_map = {} return self.api_client.call_api( '/api/v1/report/vlan/vlaninventory', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) def api_v1_report_wireless_apchanneldist_get(self, **kwargs): # noqa: E501 """api_v1_report_wireless_apchanneldist_get # noqa: E501 Access Point Channel Distribution Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_wireless_apchanneldist_get(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ kwargs['_return_http_data_only'] = True return self.api_v1_report_wireless_apchanneldist_get_with_http_info(**kwargs) # noqa: E501 def api_v1_report_wireless_apchanneldist_get_with_http_info(self, **kwargs): # noqa: E501 """api_v1_report_wireless_apchanneldist_get # noqa: E501 Access Point Channel Distribution Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_wireless_apchanneldist_get_with_http_info(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ local_var_params = locals() all_params = [ ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method api_v1_report_wireless_apchanneldist_get" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # Authentication setting auth_settings = ['APIKeyHeader'] # noqa: E501 response_types_map = {} return self.api_client.call_api( '/api/v1/report/wireless/apchanneldist', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) def api_v1_report_wireless_apclients_get(self, **kwargs): # noqa: E501 """api_v1_report_wireless_apclients_get # noqa: E501 Access Point Client Count Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_wireless_apclients_get(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ kwargs['_return_http_data_only'] = True return self.api_v1_report_wireless_apclients_get_with_http_info(**kwargs) # noqa: E501 def api_v1_report_wireless_apclients_get_with_http_info(self, **kwargs): # noqa: E501 """api_v1_report_wireless_apclients_get # noqa: E501 Access Point Client Count Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_wireless_apclients_get_with_http_info(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ local_var_params = locals() all_params = [ ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method api_v1_report_wireless_apclients_get" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # Authentication setting auth_settings = ['APIKeyHeader'] # noqa: E501 response_types_map = {} return self.api_client.call_api( '/api/v1/report/wireless/apclients', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) def api_v1_report_wireless_apradiochannelpower_get(self, **kwargs): # noqa: E501 """api_v1_report_wireless_apradiochannelpower_get # noqa: E501 Access Point Radios Channel and Power Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_wireless_apradiochannelpower_get(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ kwargs['_return_http_data_only'] = True return self.api_v1_report_wireless_apradiochannelpower_get_with_http_info(**kwargs) # noqa: E501 def api_v1_report_wireless_apradiochannelpower_get_with_http_info(self, **kwargs): # noqa: E501 """api_v1_report_wireless_apradiochannelpower_get # noqa: E501 Access Point Radios Channel and Power Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_wireless_apradiochannelpower_get_with_http_info(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ local_var_params = locals() all_params = [ ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method api_v1_report_wireless_apradiochannelpower_get" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # Authentication setting auth_settings = ['APIKeyHeader'] # noqa: E501 response_types_map = {} return self.api_client.call_api( '/api/v1/report/wireless/apradiochannelpower', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) def api_v1_report_wireless_ssidinventory_get(self, **kwargs): # noqa: E501 """api_v1_report_wireless_ssidinventory_get # noqa: E501 SSID Inventory Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_wireless_ssidinventory_get(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ kwargs['_return_http_data_only'] = True return self.api_v1_report_wireless_ssidinventory_get_with_http_info(**kwargs) # noqa: E501 def api_v1_report_wireless_ssidinventory_get_with_http_info(self, **kwargs): # noqa: E501 """api_v1_report_wireless_ssidinventory_get # noqa: E501 SSID Inventory Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_wireless_ssidinventory_get_with_http_info(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ local_var_params = locals() all_params = [ ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method api_v1_report_wireless_ssidinventory_get" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # Authentication setting auth_settings = ['APIKeyHeader'] # noqa: E501 response_types_map = {} return self.api_client.call_api( '/api/v1/report/wireless/ssidinventory', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth'))
42.698441
124
0.594796
# coding: utf-8 """ App::Netdisco No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: 2.050003 Generated by: https://openapi-generator.tech """ from __future__ import absolute_import import re # noqa: F401 # python 2 and python 3 compatibility library import six from openapi_netdisco.api_client import ApiClient from openapi_netdisco.exceptions import ( # noqa: F401 ApiTypeError, ApiValueError ) class ReportsApi(object): """NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. """ def __init__(self, api_client=None): if api_client is None: api_client = ApiClient() self.api_client = api_client def api_v1_report_device_deviceaddrnodns_get(self, **kwargs): # noqa: E501 """api_v1_report_device_deviceaddrnodns_get # noqa: E501 Addresses without DNS Entries Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_device_deviceaddrnodns_get(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ kwargs['_return_http_data_only'] = True return self.api_v1_report_device_deviceaddrnodns_get_with_http_info(**kwargs) # noqa: E501 def api_v1_report_device_deviceaddrnodns_get_with_http_info(self, **kwargs): # noqa: E501 """api_v1_report_device_deviceaddrnodns_get # noqa: E501 Addresses without DNS Entries Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_device_deviceaddrnodns_get_with_http_info(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ local_var_params = locals() all_params = [ ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method api_v1_report_device_deviceaddrnodns_get" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # Authentication setting auth_settings = ['APIKeyHeader'] # noqa: E501 response_types_map = {} return self.api_client.call_api( '/api/v1/report/device/deviceaddrnodns', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) def api_v1_report_device_devicebylocation_get(self, **kwargs): # noqa: E501 """api_v1_report_device_devicebylocation_get # noqa: E501 By Location Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_device_devicebylocation_get(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ kwargs['_return_http_data_only'] = True return self.api_v1_report_device_devicebylocation_get_with_http_info(**kwargs) # noqa: E501 def api_v1_report_device_devicebylocation_get_with_http_info(self, **kwargs): # noqa: E501 """api_v1_report_device_devicebylocation_get # noqa: E501 By Location Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_device_devicebylocation_get_with_http_info(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ local_var_params = locals() all_params = [ ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method api_v1_report_device_devicebylocation_get" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # Authentication setting auth_settings = ['APIKeyHeader'] # noqa: E501 response_types_map = {} return self.api_client.call_api( '/api/v1/report/device/devicebylocation', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) def api_v1_report_device_devicednsmismatch_get(self, **kwargs): # noqa: E501 """api_v1_report_device_devicednsmismatch_get # noqa: E501 Device Name / DNS Mismatches Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_device_devicednsmismatch_get(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ kwargs['_return_http_data_only'] = True return self.api_v1_report_device_devicednsmismatch_get_with_http_info(**kwargs) # noqa: E501 def api_v1_report_device_devicednsmismatch_get_with_http_info(self, **kwargs): # noqa: E501 """api_v1_report_device_devicednsmismatch_get # noqa: E501 Device Name / DNS Mismatches Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_device_devicednsmismatch_get_with_http_info(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ local_var_params = locals() all_params = [ ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method api_v1_report_device_devicednsmismatch_get" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # Authentication setting auth_settings = ['APIKeyHeader'] # noqa: E501 response_types_map = {} return self.api_client.call_api( '/api/v1/report/device/devicednsmismatch', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) def api_v1_report_device_devicepoestatus_get(self, **kwargs): # noqa: E501 """api_v1_report_device_devicepoestatus_get # noqa: E501 Power over Ethernet (PoE) Status Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_device_devicepoestatus_get(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ kwargs['_return_http_data_only'] = True return self.api_v1_report_device_devicepoestatus_get_with_http_info(**kwargs) # noqa: E501 def api_v1_report_device_devicepoestatus_get_with_http_info(self, **kwargs): # noqa: E501 """api_v1_report_device_devicepoestatus_get # noqa: E501 Power over Ethernet (PoE) Status Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_device_devicepoestatus_get_with_http_info(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ local_var_params = locals() all_params = [ ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method api_v1_report_device_devicepoestatus_get" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # Authentication setting auth_settings = ['APIKeyHeader'] # noqa: E501 response_types_map = {} return self.api_client.call_api( '/api/v1/report/device/devicepoestatus', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) def api_v1_report_device_portutilization_get(self, **kwargs): # noqa: E501 """api_v1_report_device_portutilization_get # noqa: E501 Port Utilization Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_device_portutilization_get(async_req=True) >>> result = thread.get() :param age_num: Mark as Free if down for (quantity) :type age_num: str :param age_unit: Mark as Free if down for (period) :type age_unit: str :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: list[PortUtilization] """ kwargs['_return_http_data_only'] = True return self.api_v1_report_device_portutilization_get_with_http_info(**kwargs) # noqa: E501 def api_v1_report_device_portutilization_get_with_http_info(self, **kwargs): # noqa: E501 """api_v1_report_device_portutilization_get # noqa: E501 Port Utilization Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_device_portutilization_get_with_http_info(async_req=True) >>> result = thread.get() :param age_num: Mark as Free if down for (quantity) :type age_num: str :param age_unit: Mark as Free if down for (period) :type age_unit: str :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: tuple(list[PortUtilization], status_code(int), headers(HTTPHeaderDict)) """ local_var_params = locals() all_params = [ 'age_num', 'age_unit' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method api_v1_report_device_portutilization_get" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] if 'age_num' in local_var_params and local_var_params['age_num'] is not None: # noqa: E501 query_params.append(('age_num', local_var_params['age_num'])) # noqa: E501 if 'age_unit' in local_var_params and local_var_params['age_unit'] is not None: # noqa: E501 query_params.append(('age_unit', local_var_params['age_unit'])) # 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 # Authentication setting auth_settings = ['APIKeyHeader'] # noqa: E501 response_types_map = { 200: "list[PortUtilization]", } return self.api_client.call_api( '/api/v1/report/device/portutilization', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) def api_v1_report_ip_ipinventory_get(self, **kwargs): # noqa: E501 """api_v1_report_ip_ipinventory_get # noqa: E501 IP Inventory Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_ip_ipinventory_get(async_req=True) >>> result = thread.get() :param subnet: IP Prefix to search :type subnet: str :param daterange: Date range to search :type daterange: str :param age_invert: Results should NOT be within daterange :type age_invert: bool :param limit: Maximum number of historical records :type limit: str :param never: Include in the report IPs never seen :type never: bool :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ kwargs['_return_http_data_only'] = True return self.api_v1_report_ip_ipinventory_get_with_http_info(**kwargs) # noqa: E501 def api_v1_report_ip_ipinventory_get_with_http_info(self, **kwargs): # noqa: E501 """api_v1_report_ip_ipinventory_get # noqa: E501 IP Inventory Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_ip_ipinventory_get_with_http_info(async_req=True) >>> result = thread.get() :param subnet: IP Prefix to search :type subnet: str :param daterange: Date range to search :type daterange: str :param age_invert: Results should NOT be within daterange :type age_invert: bool :param limit: Maximum number of historical records :type limit: str :param never: Include in the report IPs never seen :type never: bool :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ local_var_params = locals() all_params = [ 'subnet', 'daterange', 'age_invert', 'limit', 'never' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method api_v1_report_ip_ipinventory_get" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] if 'subnet' in local_var_params and local_var_params['subnet'] is not None: # noqa: E501 query_params.append(('subnet', local_var_params['subnet'])) # noqa: E501 if 'daterange' in local_var_params and local_var_params['daterange'] is not None: # noqa: E501 query_params.append(('daterange', local_var_params['daterange'])) # noqa: E501 if 'age_invert' in local_var_params and local_var_params['age_invert'] is not None: # noqa: E501 query_params.append(('age_invert', local_var_params['age_invert'])) # noqa: E501 if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501 query_params.append(('limit', local_var_params['limit'])) # noqa: E501 if 'never' in local_var_params and local_var_params['never'] is not None: # noqa: E501 query_params.append(('never', local_var_params['never'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # Authentication setting auth_settings = ['APIKeyHeader'] # noqa: E501 response_types_map = {} return self.api_client.call_api( '/api/v1/report/ip/ipinventory', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) def api_v1_report_ip_subnets_get(self, **kwargs): # noqa: E501 """api_v1_report_ip_subnets_get # noqa: E501 Subnet Utilization Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_ip_subnets_get(async_req=True) >>> result = thread.get() :param subnet: IP Prefix to search :type subnet: str :param daterange: Date range to search :type daterange: str :param age_invert: Results should NOT be within daterange :type age_invert: bool :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ kwargs['_return_http_data_only'] = True return self.api_v1_report_ip_subnets_get_with_http_info(**kwargs) # noqa: E501 def api_v1_report_ip_subnets_get_with_http_info(self, **kwargs): # noqa: E501 """api_v1_report_ip_subnets_get # noqa: E501 Subnet Utilization Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_ip_subnets_get_with_http_info(async_req=True) >>> result = thread.get() :param subnet: IP Prefix to search :type subnet: str :param daterange: Date range to search :type daterange: str :param age_invert: Results should NOT be within daterange :type age_invert: bool :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ local_var_params = locals() all_params = [ 'subnet', 'daterange', 'age_invert' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method api_v1_report_ip_subnets_get" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] if 'subnet' in local_var_params and local_var_params['subnet'] is not None: # noqa: E501 query_params.append(('subnet', local_var_params['subnet'])) # noqa: E501 if 'daterange' in local_var_params and local_var_params['daterange'] is not None: # noqa: E501 query_params.append(('daterange', local_var_params['daterange'])) # noqa: E501 if 'age_invert' in local_var_params and local_var_params['age_invert'] is not None: # noqa: E501 query_params.append(('age_invert', local_var_params['age_invert'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # Authentication setting auth_settings = ['APIKeyHeader'] # noqa: E501 response_types_map = {} return self.api_client.call_api( '/api/v1/report/ip/subnets', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) def api_v1_report_node_nodemultiips_get(self, **kwargs): # noqa: E501 """api_v1_report_node_nodemultiips_get # noqa: E501 Nodes with multiple active IP addresses Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_node_nodemultiips_get(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ kwargs['_return_http_data_only'] = True return self.api_v1_report_node_nodemultiips_get_with_http_info(**kwargs) # noqa: E501 def api_v1_report_node_nodemultiips_get_with_http_info(self, **kwargs): # noqa: E501 """api_v1_report_node_nodemultiips_get # noqa: E501 Nodes with multiple active IP addresses Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_node_nodemultiips_get_with_http_info(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ local_var_params = locals() all_params = [ ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method api_v1_report_node_nodemultiips_get" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # Authentication setting auth_settings = ['APIKeyHeader'] # noqa: E501 response_types_map = {} return self.api_client.call_api( '/api/v1/report/node/nodemultiips', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) def api_v1_report_node_nodesdiscovered_get(self, **kwargs): # noqa: E501 """api_v1_report_node_nodesdiscovered_get # noqa: E501 Nodes discovered through LLDP/CDP Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_node_nodesdiscovered_get(async_req=True) >>> result = thread.get() :param remote_id: Host Name reported :type remote_id: str :param remote_type: Platform reported :type remote_type: str :param aps: Include Wireless APs in the report :type aps: bool :param phones: Include IP Phones in the report :type phones: bool :param matchall: Match all parameters (true) or any (false) :type matchall: bool :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ kwargs['_return_http_data_only'] = True return self.api_v1_report_node_nodesdiscovered_get_with_http_info(**kwargs) # noqa: E501 def api_v1_report_node_nodesdiscovered_get_with_http_info(self, **kwargs): # noqa: E501 """api_v1_report_node_nodesdiscovered_get # noqa: E501 Nodes discovered through LLDP/CDP Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_node_nodesdiscovered_get_with_http_info(async_req=True) >>> result = thread.get() :param remote_id: Host Name reported :type remote_id: str :param remote_type: Platform reported :type remote_type: str :param aps: Include Wireless APs in the report :type aps: bool :param phones: Include IP Phones in the report :type phones: bool :param matchall: Match all parameters (true) or any (false) :type matchall: bool :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ local_var_params = locals() all_params = [ 'remote_id', 'remote_type', 'aps', 'phones', 'matchall' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method api_v1_report_node_nodesdiscovered_get" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] if 'remote_id' in local_var_params and local_var_params['remote_id'] is not None: # noqa: E501 query_params.append(('remote_id', local_var_params['remote_id'])) # noqa: E501 if 'remote_type' in local_var_params and local_var_params['remote_type'] is not None: # noqa: E501 query_params.append(('remote_type', local_var_params['remote_type'])) # noqa: E501 if 'aps' in local_var_params and local_var_params['aps'] is not None: # noqa: E501 query_params.append(('aps', local_var_params['aps'])) # noqa: E501 if 'phones' in local_var_params and local_var_params['phones'] is not None: # noqa: E501 query_params.append(('phones', local_var_params['phones'])) # noqa: E501 if 'matchall' in local_var_params and local_var_params['matchall'] is not None: # noqa: E501 query_params.append(('matchall', local_var_params['matchall'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # Authentication setting auth_settings = ['APIKeyHeader'] # noqa: E501 response_types_map = {} return self.api_client.call_api( '/api/v1/report/node/nodesdiscovered', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) def api_v1_report_port_duplexmismatch_get(self, **kwargs): # noqa: E501 """api_v1_report_port_duplexmismatch_get # noqa: E501 Duplex Mismatches Between Devices Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_port_duplexmismatch_get(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ kwargs['_return_http_data_only'] = True return self.api_v1_report_port_duplexmismatch_get_with_http_info(**kwargs) # noqa: E501 def api_v1_report_port_duplexmismatch_get_with_http_info(self, **kwargs): # noqa: E501 """api_v1_report_port_duplexmismatch_get # noqa: E501 Duplex Mismatches Between Devices Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_port_duplexmismatch_get_with_http_info(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ local_var_params = locals() all_params = [ ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method api_v1_report_port_duplexmismatch_get" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # Authentication setting auth_settings = ['APIKeyHeader'] # noqa: E501 response_types_map = {} return self.api_client.call_api( '/api/v1/report/port/duplexmismatch', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) def api_v1_report_port_halfduplex_get(self, **kwargs): # noqa: E501 """api_v1_report_port_halfduplex_get # noqa: E501 Ports in Half Duplex Mode Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_port_halfduplex_get(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ kwargs['_return_http_data_only'] = True return self.api_v1_report_port_halfduplex_get_with_http_info(**kwargs) # noqa: E501 def api_v1_report_port_halfduplex_get_with_http_info(self, **kwargs): # noqa: E501 """api_v1_report_port_halfduplex_get # noqa: E501 Ports in Half Duplex Mode Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_port_halfduplex_get_with_http_info(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ local_var_params = locals() all_params = [ ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method api_v1_report_port_halfduplex_get" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # Authentication setting auth_settings = ['APIKeyHeader'] # noqa: E501 response_types_map = {} return self.api_client.call_api( '/api/v1/report/port/halfduplex', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) def api_v1_report_port_portadmindown_get(self, **kwargs): # noqa: E501 """api_v1_report_port_portadmindown_get # noqa: E501 Ports administratively disabled Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_port_portadmindown_get(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ kwargs['_return_http_data_only'] = True return self.api_v1_report_port_portadmindown_get_with_http_info(**kwargs) # noqa: E501 def api_v1_report_port_portadmindown_get_with_http_info(self, **kwargs): # noqa: E501 """api_v1_report_port_portadmindown_get # noqa: E501 Ports administratively disabled Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_port_portadmindown_get_with_http_info(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ local_var_params = locals() all_params = [ ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method api_v1_report_port_portadmindown_get" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # Authentication setting auth_settings = ['APIKeyHeader'] # noqa: E501 response_types_map = {} return self.api_client.call_api( '/api/v1/report/port/portadmindown', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) def api_v1_report_port_portblocking_get(self, **kwargs): # noqa: E501 """api_v1_report_port_portblocking_get # noqa: E501 Ports that are blocking Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_port_portblocking_get(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ kwargs['_return_http_data_only'] = True return self.api_v1_report_port_portblocking_get_with_http_info(**kwargs) # noqa: E501 def api_v1_report_port_portblocking_get_with_http_info(self, **kwargs): # noqa: E501 """api_v1_report_port_portblocking_get # noqa: E501 Ports that are blocking Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_port_portblocking_get_with_http_info(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ local_var_params = locals() all_params = [ ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method api_v1_report_port_portblocking_get" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # Authentication setting auth_settings = ['APIKeyHeader'] # noqa: E501 response_types_map = {} return self.api_client.call_api( '/api/v1/report/port/portblocking', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) def api_v1_report_port_portmultinodes_get(self, **kwargs): # noqa: E501 """api_v1_report_port_portmultinodes_get # noqa: E501 Ports with multiple nodes attached Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_port_portmultinodes_get(async_req=True) >>> result = thread.get() :param vlan: Filter by VLAN :type vlan: int :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ kwargs['_return_http_data_only'] = True return self.api_v1_report_port_portmultinodes_get_with_http_info(**kwargs) # noqa: E501 def api_v1_report_port_portmultinodes_get_with_http_info(self, **kwargs): # noqa: E501 """api_v1_report_port_portmultinodes_get # noqa: E501 Ports with multiple nodes attached Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_port_portmultinodes_get_with_http_info(async_req=True) >>> result = thread.get() :param vlan: Filter by VLAN :type vlan: int :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ local_var_params = locals() all_params = [ 'vlan' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method api_v1_report_port_portmultinodes_get" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] if 'vlan' in local_var_params and local_var_params['vlan'] is not None: # noqa: E501 query_params.append(('vlan', local_var_params['vlan'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # Authentication setting auth_settings = ['APIKeyHeader'] # noqa: E501 response_types_map = {} return self.api_client.call_api( '/api/v1/report/port/portmultinodes', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) def api_v1_report_port_portserrordisabled_get(self, **kwargs): # noqa: E501 """api_v1_report_port_portserrordisabled_get # noqa: E501 Error Disabled Ports Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_port_portserrordisabled_get(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ kwargs['_return_http_data_only'] = True return self.api_v1_report_port_portserrordisabled_get_with_http_info(**kwargs) # noqa: E501 def api_v1_report_port_portserrordisabled_get_with_http_info(self, **kwargs): # noqa: E501 """api_v1_report_port_portserrordisabled_get # noqa: E501 Error Disabled Ports Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_port_portserrordisabled_get_with_http_info(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ local_var_params = locals() all_params = [ ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method api_v1_report_port_portserrordisabled_get" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # Authentication setting auth_settings = ['APIKeyHeader'] # noqa: E501 response_types_map = {} return self.api_client.call_api( '/api/v1/report/port/portserrordisabled', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) def api_v1_report_port_portssid_get(self, **kwargs): # noqa: E501 """api_v1_report_port_portssid_get # noqa: E501 Port SSID Inventory Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_port_portssid_get(async_req=True) >>> result = thread.get() :param ssid: Get details for this SSID :type ssid: str :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ kwargs['_return_http_data_only'] = True return self.api_v1_report_port_portssid_get_with_http_info(**kwargs) # noqa: E501 def api_v1_report_port_portssid_get_with_http_info(self, **kwargs): # noqa: E501 """api_v1_report_port_portssid_get # noqa: E501 Port SSID Inventory Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_port_portssid_get_with_http_info(async_req=True) >>> result = thread.get() :param ssid: Get details for this SSID :type ssid: str :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ local_var_params = locals() all_params = [ 'ssid' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method api_v1_report_port_portssid_get" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] if 'ssid' in local_var_params and local_var_params['ssid'] is not None: # noqa: E501 query_params.append(('ssid', local_var_params['ssid'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # Authentication setting auth_settings = ['APIKeyHeader'] # noqa: E501 response_types_map = {} return self.api_client.call_api( '/api/v1/report/port/portssid', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) def api_v1_report_port_portvlanmismatch_get(self, **kwargs): # noqa: E501 """api_v1_report_port_portvlanmismatch_get # noqa: E501 Port VLAN Mismatches Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_port_portvlanmismatch_get(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ kwargs['_return_http_data_only'] = True return self.api_v1_report_port_portvlanmismatch_get_with_http_info(**kwargs) # noqa: E501 def api_v1_report_port_portvlanmismatch_get_with_http_info(self, **kwargs): # noqa: E501 """api_v1_report_port_portvlanmismatch_get # noqa: E501 Port VLAN Mismatches Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_port_portvlanmismatch_get_with_http_info(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ local_var_params = locals() all_params = [ ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method api_v1_report_port_portvlanmismatch_get" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # Authentication setting auth_settings = ['APIKeyHeader'] # noqa: E501 response_types_map = {} return self.api_client.call_api( '/api/v1/report/port/portvlanmismatch', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) def api_v1_report_vlan_vlaninventory_get(self, **kwargs): # noqa: E501 """api_v1_report_vlan_vlaninventory_get # noqa: E501 VLAN Inventory Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_vlan_vlaninventory_get(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ kwargs['_return_http_data_only'] = True return self.api_v1_report_vlan_vlaninventory_get_with_http_info(**kwargs) # noqa: E501 def api_v1_report_vlan_vlaninventory_get_with_http_info(self, **kwargs): # noqa: E501 """api_v1_report_vlan_vlaninventory_get # noqa: E501 VLAN Inventory Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_vlan_vlaninventory_get_with_http_info(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ local_var_params = locals() all_params = [ ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method api_v1_report_vlan_vlaninventory_get" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # Authentication setting auth_settings = ['APIKeyHeader'] # noqa: E501 response_types_map = {} return self.api_client.call_api( '/api/v1/report/vlan/vlaninventory', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) def api_v1_report_wireless_apchanneldist_get(self, **kwargs): # noqa: E501 """api_v1_report_wireless_apchanneldist_get # noqa: E501 Access Point Channel Distribution Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_wireless_apchanneldist_get(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ kwargs['_return_http_data_only'] = True return self.api_v1_report_wireless_apchanneldist_get_with_http_info(**kwargs) # noqa: E501 def api_v1_report_wireless_apchanneldist_get_with_http_info(self, **kwargs): # noqa: E501 """api_v1_report_wireless_apchanneldist_get # noqa: E501 Access Point Channel Distribution Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_wireless_apchanneldist_get_with_http_info(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ local_var_params = locals() all_params = [ ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method api_v1_report_wireless_apchanneldist_get" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # Authentication setting auth_settings = ['APIKeyHeader'] # noqa: E501 response_types_map = {} return self.api_client.call_api( '/api/v1/report/wireless/apchanneldist', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) def api_v1_report_wireless_apclients_get(self, **kwargs): # noqa: E501 """api_v1_report_wireless_apclients_get # noqa: E501 Access Point Client Count Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_wireless_apclients_get(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ kwargs['_return_http_data_only'] = True return self.api_v1_report_wireless_apclients_get_with_http_info(**kwargs) # noqa: E501 def api_v1_report_wireless_apclients_get_with_http_info(self, **kwargs): # noqa: E501 """api_v1_report_wireless_apclients_get # noqa: E501 Access Point Client Count Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_wireless_apclients_get_with_http_info(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ local_var_params = locals() all_params = [ ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method api_v1_report_wireless_apclients_get" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # Authentication setting auth_settings = ['APIKeyHeader'] # noqa: E501 response_types_map = {} return self.api_client.call_api( '/api/v1/report/wireless/apclients', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) def api_v1_report_wireless_apradiochannelpower_get(self, **kwargs): # noqa: E501 """api_v1_report_wireless_apradiochannelpower_get # noqa: E501 Access Point Radios Channel and Power Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_wireless_apradiochannelpower_get(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ kwargs['_return_http_data_only'] = True return self.api_v1_report_wireless_apradiochannelpower_get_with_http_info(**kwargs) # noqa: E501 def api_v1_report_wireless_apradiochannelpower_get_with_http_info(self, **kwargs): # noqa: E501 """api_v1_report_wireless_apradiochannelpower_get # noqa: E501 Access Point Radios Channel and Power Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_wireless_apradiochannelpower_get_with_http_info(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ local_var_params = locals() all_params = [ ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method api_v1_report_wireless_apradiochannelpower_get" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # Authentication setting auth_settings = ['APIKeyHeader'] # noqa: E501 response_types_map = {} return self.api_client.call_api( '/api/v1/report/wireless/apradiochannelpower', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) def api_v1_report_wireless_ssidinventory_get(self, **kwargs): # noqa: E501 """api_v1_report_wireless_ssidinventory_get # noqa: E501 SSID Inventory Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_wireless_ssidinventory_get(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ kwargs['_return_http_data_only'] = True return self.api_v1_report_wireless_ssidinventory_get_with_http_info(**kwargs) # noqa: E501 def api_v1_report_wireless_ssidinventory_get_with_http_info(self, **kwargs): # noqa: E501 """api_v1_report_wireless_ssidinventory_get # noqa: E501 SSID Inventory Report # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.api_v1_report_wireless_ssidinventory_get_with_http_info(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: None """ local_var_params = locals() all_params = [ ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method api_v1_report_wireless_ssidinventory_get" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # Authentication setting auth_settings = ['APIKeyHeader'] # noqa: E501 response_types_map = {} return self.api_client.call_api( '/api/v1/report/wireless/ssidinventory', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth'))
120
0
27
ceb54fb28a4ee266bcaafabf6b90e122e97a5575
2,319
py
Python
st2common/st2common/constants/meta.py
muyouming/st2
a80fa2b6b0f7ff3281ed8dee8ca6e97910fbd00e
[ "Apache-2.0" ]
4,920
2015-01-01T15:12:17.000Z
2022-03-31T19:31:15.000Z
st2common/st2common/constants/meta.py
muyouming/st2
a80fa2b6b0f7ff3281ed8dee8ca6e97910fbd00e
[ "Apache-2.0" ]
3,563
2015-01-05T19:02:19.000Z
2022-03-31T19:23:09.000Z
st2common/st2common/constants/meta.py
muyouming/st2
a80fa2b6b0f7ff3281ed8dee8ca6e97910fbd00e
[ "Apache-2.0" ]
774
2015-01-01T20:41:24.000Z
2022-03-31T13:25:29.000Z
# Copyright 2020 The StackStorm Authors. # Copyright 2019 Extreme Networks, Inc. # # 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 __future__ import absolute_import import logging import yaml try: from yaml import CSafeLoader as YamlSafeLoader from yaml import CSafeDumper as YamlSafeDumper except ImportError: # NOTE: We install libyaml-dev in our packages so libyaml will always be available when using # official StackStorm packages. # Only time it may not be available is if the user is doing custom install from source or # similar. logging.getLogger(__name__).warn( "libYAML C bindings are not available. This means YAML " "parsing and serialization will be significantly slower. You are " "strongly recommended to install libyaml (libyaml-dev package " "on Debian). For more information, see https://pyyaml.org/wiki/LibYAML" ) from yaml import SafeLoader as YamlSafeLoader from yaml import SafeDumper as YamlSafeDumper __all__ = ["ALLOWED_EXTS", "PARSER_FUNCS"] # NOTE: We utilize CSafeLoader if available since it uses C extensions and is faster. # # SafeLoader / CSafeLoader are both safe to use and don't allow loading arbitrary Python objects. # # That's the actual class which is used internally by ``yaml.safe_load()``, but we can't use that # method directly since we want to use C extension if available (CSafeLoader) for faster parsing. # # Same goes for dumper class. # # See pyyaml docs for details https://pyyaml.org/wiki/PyYAMLDocumentation ALLOWED_EXTS = [".yaml", ".yml"] PARSER_FUNCS = {".yml": yaml_safe_load, ".yaml": yaml_safe_load}
37.403226
97
0.749461
# Copyright 2020 The StackStorm Authors. # Copyright 2019 Extreme Networks, Inc. # # 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 __future__ import absolute_import import logging import yaml try: from yaml import CSafeLoader as YamlSafeLoader from yaml import CSafeDumper as YamlSafeDumper except ImportError: # NOTE: We install libyaml-dev in our packages so libyaml will always be available when using # official StackStorm packages. # Only time it may not be available is if the user is doing custom install from source or # similar. logging.getLogger(__name__).warn( "libYAML C bindings are not available. This means YAML " "parsing and serialization will be significantly slower. You are " "strongly recommended to install libyaml (libyaml-dev package " "on Debian). For more information, see https://pyyaml.org/wiki/LibYAML" ) from yaml import SafeLoader as YamlSafeLoader from yaml import SafeDumper as YamlSafeDumper __all__ = ["ALLOWED_EXTS", "PARSER_FUNCS"] # NOTE: We utilize CSafeLoader if available since it uses C extensions and is faster. # # SafeLoader / CSafeLoader are both safe to use and don't allow loading arbitrary Python objects. # # That's the actual class which is used internally by ``yaml.safe_load()``, but we can't use that # method directly since we want to use C extension if available (CSafeLoader) for faster parsing. # # Same goes for dumper class. # # See pyyaml docs for details https://pyyaml.org/wiki/PyYAMLDocumentation def yaml_safe_load(stream): return yaml.load(stream, Loader=YamlSafeLoader) def yaml_safe_dump(data, **kwargs): return yaml.dump(data, Dumper=YamlSafeDumper, **kwargs) ALLOWED_EXTS = [".yaml", ".yml"] PARSER_FUNCS = {".yml": yaml_safe_load, ".yaml": yaml_safe_load}
132
0
45
ab103eb0478ae2e88967e12bbd8ec3c12d4d930c
2,531
py
Python
parserg/lexer.py
teddynecsoiu/parserg
15d8409efaadd2d39e2a10ec478a4df9dbaa9b40
[ "MIT" ]
null
null
null
parserg/lexer.py
teddynecsoiu/parserg
15d8409efaadd2d39e2a10ec478a4df9dbaa9b40
[ "MIT" ]
null
null
null
parserg/lexer.py
teddynecsoiu/parserg
15d8409efaadd2d39e2a10ec478a4df9dbaa9b40
[ "MIT" ]
null
null
null
from .constants import * JSON_QUOTE = '"' JSON_WHITESPACE = [' ', '\t', '\b', '\n', '\r'] JSON_SYNTAX = [JSON_COMMA, JSON_COLON, JSON_LEFTBRACKET, JSON_RIGHTBRACKET, JSON_LEFTBRACE, JSON_RIGHTBRACE] FALSE_LEN = len('false') TRUE_LEN = len('true') NULL_LEN = len('null')
23.220183
75
0.583564
from .constants import * JSON_QUOTE = '"' JSON_WHITESPACE = [' ', '\t', '\b', '\n', '\r'] JSON_SYNTAX = [JSON_COMMA, JSON_COLON, JSON_LEFTBRACKET, JSON_RIGHTBRACKET, JSON_LEFTBRACE, JSON_RIGHTBRACE] FALSE_LEN = len('false') TRUE_LEN = len('true') NULL_LEN = len('null') def lex_string(string): json_string = '' if string[0] == JSON_QUOTE: string = string[1:] else: return None, string for c in string: if c == JSON_QUOTE: return json_string, string[len(json_string)+1:] else: json_string += c raise Exception('Expected end-of-string quote') def lex_number(string): json_number = '' number_characters = [str(d) for d in range(0, 10)] + ['-', 'e', '.'] for c in string: if c in number_characters: json_number += c else: break rest = string[len(json_number):] if not len(json_number): return None, string if '.' in json_number: return float(json_number), rest return int(json_number), rest def lex_bool(string): string_len = len(string) if string_len >= TRUE_LEN and \ string[:TRUE_LEN] == 'true': return True, string[TRUE_LEN:] elif string_len >= FALSE_LEN and \ string[:FALSE_LEN] == 'false': return False, string[FALSE_LEN:] return None, string def lex_null(string): string_len = len(string) if string_len >= NULL_LEN and \ string[:NULL_LEN] == 'null': return True, string[NULL_LEN] return None, string def lex(string): tokens = [] while len(string): json_string, string = lex_string(string) if json_string is not None: tokens.append(json_string) continue json_number, string = lex_number(string) if json_number is not None: tokens.append(json_number) continue json_bool, string = lex_bool(string) if json_bool is not None: tokens.append(json_bool) continue json_null, string = lex_null(string) if json_null is not None: tokens.append(None) continue # TODO: lex booleans, nulls, numbers if string[0] in JSON_WHITESPACE: string = string[1:] elif string[0] in JSON_SYNTAX: tokens.append(string[0]) string = string[1:] else: raise Exception('Unexpected character: {}'.format(string[0])) return tokens
2,126
0
115
8281b73e609e9dd3e292e156482a6cf9a7ef9667
202
py
Python
Getting_Started_With_Raspberry_Pi_Pico/data_logger_no_ground_wire_boot/code.py
gamblor21/Adafruit_Learning_System_Guides
f5dab4a758bc82d0bfc3c299683fe89dc093912a
[ "MIT" ]
665
2017-09-27T21:20:14.000Z
2022-03-31T09:09:25.000Z
Getting_Started_With_Raspberry_Pi_Pico/data_logger_no_ground_wire_boot/code.py
gamblor21/Adafruit_Learning_System_Guides
f5dab4a758bc82d0bfc3c299683fe89dc093912a
[ "MIT" ]
641
2017-10-03T19:46:37.000Z
2022-03-30T18:28:46.000Z
Getting_Started_With_Raspberry_Pi_Pico/data_logger_no_ground_wire_boot/code.py
gamblor21/Adafruit_Learning_System_Guides
f5dab4a758bc82d0bfc3c299683fe89dc093912a
[ "MIT" ]
734
2017-10-02T22:47:38.000Z
2022-03-30T14:03:51.000Z
""" boot.py file for Pico data logging example. If this file is present when the pico starts up, make the filesystem writeable by CircuitPython. """ import storage storage.remount("/", readonly=False)
25.25
72
0.762376
""" boot.py file for Pico data logging example. If this file is present when the pico starts up, make the filesystem writeable by CircuitPython. """ import storage storage.remount("/", readonly=False)
0
0
0
736cc4a08b4adca06311b8ad6d9e03beccd10663
21,253
py
Python
athenet/tests/test_derivative.py
heurezjusz/Athena
0bdda97b0e06dbb3c1699d4ed7875e4adc96d580
[ "BSD-2-Clause" ]
2
2016-02-02T12:59:39.000Z
2018-03-29T17:17:11.000Z
athenet/tests/test_derivative.py
heurezjusz/Athenet
0bdda97b0e06dbb3c1699d4ed7875e4adc96d580
[ "BSD-2-Clause" ]
5
2016-01-10T23:23:57.000Z
2016-03-26T16:29:42.000Z
athenet/tests/test_derivative.py
heurezjusz/Athena
0bdda97b0e06dbb3c1699d4ed7875e4adc96d580
[ "BSD-2-Clause" ]
1
2020-02-26T20:19:17.000Z
2020-02-26T20:19:17.000Z
"""Testing athenet.algorithm.derest.derivative functions. """ import numpy as np import theano import unittest from athenet.algorithm.derest.layers.fully_connected import d_fully_connected from athenet.algorithm.derest.layers.convolutional import d_conv from athenet.algorithm.derest.layers.pool import d_pool from athenet.algorithm.derest.layers.dropout import d_dropout from athenet.algorithm.derest.layers.norm import d_norm from athenet.algorithm.derest.layers.relu import d_relu from athenet.algorithm.derest.layers.softmax import d_softmax from nose.tools import assert_almost_equal from numpy.testing import assert_array_almost_equal from athenet.algorithm.numlike import TheanoInterval theano.config.exception_verbosity = 'high' if __name__ == '__main__': unittest.main(verbosity=2, catchbreak=True)
38.99633
78
0.399802
"""Testing athenet.algorithm.derest.derivative functions. """ import numpy as np import theano import unittest from athenet.algorithm.derest.layers.fully_connected import d_fully_connected from athenet.algorithm.derest.layers.convolutional import d_conv from athenet.algorithm.derest.layers.pool import d_pool from athenet.algorithm.derest.layers.dropout import d_dropout from athenet.algorithm.derest.layers.norm import d_norm from athenet.algorithm.derest.layers.relu import d_relu from athenet.algorithm.derest.layers.softmax import d_softmax from nose.tools import assert_almost_equal from numpy.testing import assert_array_almost_equal from athenet.algorithm.numlike import TheanoInterval theano.config.exception_verbosity = 'high' def array_almost_equal(x, y): if theano.config.floatX == 'float32': return assert_array_almost_equal(x, y, decimal=3) else: return assert_array_almost_equal(x, y) def A(x): return np.array(x, dtype=theano.config.floatX) def theano_var(x): return theano.shared(A(x)) def theano_interval(x): v = theano_var(x) return TheanoInterval(v, v) class DerivativeTest(unittest.TestCase): def prepare(self): self.v = np.arange(24) + 3.0 self.at_v = 0 return self.s, self.v, self.make_arr def s(self): if self.at_v >= len(self.v): raise ValueError ret = self.v[self.at_v] self.at_v += 1 return ret def make_arr(self, shp): sz = np.prod(shp) a = np.ndarray(sz) for i in range(sz): a[i] = self.s() return a.reshape(shp) class DerivativeTest(unittest.TestCase): pass class FullyConnectedDerivativeTest(DerivativeTest): def test_1D_simple(self): dout = theano_var([[1]]) idout = TheanoInterval(dout, dout) w = theano_var([[2]]) shp = (1, 1) din = d_fully_connected(idout, w, shp) l, u = din.eval() array_almost_equal(l, u) array_almost_equal(l, A([[2]])) def test_2D_simple_used_1D_of_weights(self): dout = theano_var([[3, 6]]) idout = TheanoInterval(dout, dout) w = theano_var([9, 12]) shp = (1, 1) din = d_fully_connected(idout, w, shp) l, u = din.eval() array_almost_equal(l, u) array_almost_equal(l, A([[99]])) def test_2D_simple_used_2D_of_weights(self): dout = theano_var([[3, 0]]) idout = TheanoInterval(dout, dout) w = theano_var([[6, 0], [9, 0]]) shp = (1, 2) din = d_fully_connected(idout, w, shp) l, u = din.eval() array_almost_equal(l, u) array_almost_equal(l, A([[18, 27]])) def test_2D_1(self): dout = theano_var([[3, 6]]) idout = TheanoInterval(dout, dout) w = theano_var([[9, 15], [12, 18]]) shp = (1, 2) din = d_fully_connected(idout, w, shp) l, u = din.eval() array_almost_equal(l, u) array_almost_equal(l, A([[117, 144]])) def test_2D_Intervals(self): doutl = theano_var([[-3, -6, 3]]) doutu = theano_var([[9, -3, 6]]) idout = TheanoInterval(doutl, doutu) w = theano_var([[2, -3, -3], [-3, 1, 2], [5, -4, 3], [-2, -3, -4]]) shp = (1, 2, 2) din = d_fully_connected(idout, w, shp) l, u = din.eval() array_almost_equal(l, A([[[-15, -27], [6, -33]]])) array_almost_equal(u, A([[[27, 18], [87, 12]]])) def test_2D_batches(self): dout = theano_var([[3, 6], [1, 2]]) idout = TheanoInterval(dout, dout) w = theano_var([[9, 15], [12, 18]]) shp = (2, 2) din = d_fully_connected(idout, w, shp) l, u = din.eval() array_almost_equal(l, u) array_almost_equal(l, A([[117, 144], [39, 48]])) class ConvolutionalDerivativeTest(DerivativeTest): def test_dims(self): dout = theano_interval(np.ones((1, 2, 2, 4))) w = theano_var(np.ones((2, 1, 3, 4))) w = w[:, :, ::-1, ::-1] din = d_conv(dout, (1, 1, 4, 7), (2, 3, 4), w) l, u = din.eval() array_almost_equal(l, u) array_almost_equal(l, A([[[[2, 4, 6, 8, 6, 4, 2], [4, 8, 12, 16, 12, 8, 4], [4, 8, 12, 16, 12, 8, 4], [2, 4, 6, 8, 6, 4, 2]]]])) def test_2x2_float(self): dout = theano_interval(A([[[[4, 8], [2, 3]]]])) w = theano_var(A([[[[2, 3, 0], [5, 7, 0], [0, 0, 0]]]])) w = w[:, :, ::-1, ::-1] din = d_conv(dout, (1, 1, 2, 2), (1, 3, 3), w, padding=(1, 1)) l, u = din.eval() array_almost_equal(l, u) array_almost_equal(l, A([[[[80, 65], [29, 21]]]])) def test_all_dims(self): dout = theano_interval(A([[[[2, 3], [5, 7]], [[0.2, 0.3], [0.5, 0.7]]]])) w = theano_var(A([[[[1, 0, 2], [0, 4, 0], [3, 0, 0]], [[0, 0, 0], [0, 9, 10], [0, 11, 12]]], [[[5, 0, 6], [0, 0, 0], [7, 0, 8]], [[13, 15, 0], [0, 0, 0], [14, 16, 0]]]])) w = w[:, :, ::-1, ::-1] din = d_conv(dout, (1, 2, 2, 2), (2, 3, 3), w, padding=(1, 1)) l, u = din.eval() array_almost_equal(l, u) array_almost_equal(l, A([[[[18.5, 25], [31.1, 29.6]], [[34.6, 57.5], [74.4, 174.8]]]])) class MaxPoolDerivativeTest(DerivativeTest): def test_simple(self): inpl = theano_var([[[[1, 1], [1, 1]]]]) inpu = theano_var([[[[2, 2], [2, 2]]]]) iinp = TheanoInterval(inpl, inpu) idout = theano_interval([[[[5]]]]) shp = (1, 1, 2, 2) din = d_pool(idout, iinp, shp, poolsize=(2, 2), mode='max') l, u = din.eval() array_almost_equal(l, A([[[[0, 0], [0, 0]]]])) array_almost_equal(u, A([[[[5, 5], [5, 5]]]])) def test_neg_output(self): inpl = theano_var([[[[1, 1], [1, 1]]]]) inpu = theano_var([[[[2, 2], [2, 2]]]]) iinp = TheanoInterval(inpl, inpu) idout = theano_interval([[[[-3]]]]) shp = (1, 1, 2, 2) din = d_pool(idout, iinp, shp, poolsize=(2, 2), mode='max') l, u = din.eval() array_almost_equal(l, A([[[[-3, -3], [-3, -3]]]])) array_almost_equal(u, A([[[[0, 0], [0, 0]]]])) def test_2D(self): inpl = theano_var([[[[0, 0, 0], [0, 0, 0], [0, 0, 0]]]]) inpu = theano_var([[[[1, 1, 1], [1, 1, 1], [1, 1, 1]]]]) iinp = TheanoInterval(inpl, inpu) doutl = theano_var([[[[-1, -2], [-3, -4]]]]) doutu = theano_var([[[[5, 4], [3, 2]]]]) idout = TheanoInterval(doutl, doutu) shp = (1, 1, 3, 3) din = d_pool(idout, iinp, shp, poolsize=(2, 2), mode='max') l, u = din.eval() array_almost_equal(l, A([[[[-1, -3, -2], [-4, -10, -6], [-3, -7, -4]]]])) array_almost_equal(u, A([[[[5, 9, 4], [8, 14, 6], [3, 5, 2]]]])) def test_channels_batch(self): inpl = theano_var([[ [[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [3, 0, 0]] ], [ [[0, 3, 3], [4, 5, 6], [7, 8, 4]], [[-3, -3, -3], [-3, -3, -3], [3, 3, 3]] ]]) inpu = theano_var([[ [[1, 1, 1], [1, 1, 1], [1, 1, 1]], [[1, 1, 1], [1, 1, 1], [4, 1, 1]] ], [ [[2, 4, 4], [9, 9, 9], [9, 9, 9]], [[2, 2, 2], [2, 2, 2], [5, 5, 5]] ]]) iinp = TheanoInterval(inpl, inpu) doutl = theano_var([[ [[-1, -2], [-3, -4]], [[1, 2], [-3, -2]] ], [ [[1, 2], [-3, -2]], [[-1, 1], [-1, 1]] ]]) doutu = theano_var([[ [[5, 4], [3, 2]], [[4, 4], [4, 4]], ], [ [[4, 5], [0, 1]], [[0, 2], [0, 2]] ]]) idout = TheanoInterval(doutl, doutu) shp = (2, 2, 3, 3) din = d_pool(idout, iinp, shp, poolsize=(2, 2), mode='max') l, u = din.eval() array_almost_equal(l, A([[ [[-1, -3, -2], [-4, -10, -6], [-3, -7, -4]], [[0, 0, 0], [0, -2, -2], [-3, -2, -2]] ], [ [[0, 0, 0], [-3, -5, -2], [-3, -5, -2]], [[-1, -1, 0], [-1, -1, 0], [-1, -1, 0]] ]])) array_almost_equal(u, A([[ [[5, 9, 4], [8, 14, 6], [3, 5, 2]], [[4, 8, 4], [4, 12, 8], [4, 4, 4]] ], [ [[0, 0, 0], [4, 10, 6], [0, 1, 1]], [[0, 2, 2], [0, 2, 2], [0, 2, 2]] ]])) def test_stride(self): tinpl = theano.shared(np.arange(25).reshape((1, 1, 5, 5))) tinpu = theano.shared(np.arange(25).reshape((1, 1, 5, 5)) + 2) iinp = TheanoInterval(tinpl, tinpu) idout = theano_interval([[[[-1, 2], [-3, 4]]]]) shp = (1, 1, 5, 5) din = d_pool(idout, iinp, shp, poolsize=(2, 2), stride=(3, 3), mode='max') l, u = din.eval() array_almost_equal(l, A([[[[0, 0, 0, 0, 0], [-1, -1, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [-3, -3, 0, 0, 0]]]])) array_almost_equal(u, A([[[[0, 0, 0, 0, 0], [0, 0, 0, 2, 2], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 4, 4]]]])) def test_padding(self): inpl = theano_var([[[[0, 0, 0], [0, 0, 0], [0, 0, 0]]]]) inpu = theano_var([[[[1, 1, 1], [1, 1, 1], [1, 1, 1]]]]) iinp = TheanoInterval(inpl, inpu) doutl = theano_var([[[[-1, -2], [-3, -4]]]]) doutu = theano_var([[[[5, 4], [3, 2]]]]) idout = TheanoInterval(doutl, doutu) shp = (1, 1, 3, 3) din = d_pool(idout, iinp, shp, poolsize=(2, 2), padding=(1, 1), stride=(3, 3), mode='max') l, u = din.eval() array_almost_equal(l, A([[[[-1, 0, -2], [0, 0, 0], [-3, 0, -4]]]])) array_almost_equal(u, A([[[[5, 0, 4], [0, 0, 0], [3, 0, 2]]]])) class AvgPoolDerivativeTest(DerivativeTest): def test_simple(self): inpl = theano_var([[[[0, 0, 0], [0, 0, 0], [0, 0, 0]]]]) inpu = theano_var([[[[1, 1, 1], [1, 1, 1], [1, 1, 1]]]]) iinp = TheanoInterval(inpl, inpu) doutl = theano_var([[[[-1, -2], [-3, -4]]]]) doutu = theano_var([[[[5, 4], [3, 2]]]]) idout = TheanoInterval(doutl, doutu) shp = (1, 1, 3, 3) din = d_pool(idout, iinp, shp, poolsize=(2, 2), mode='avg') l, u = din.eval() array_almost_equal(l, A([[[[-1, -3, -2], [-4, -10, -6], [-3, -7, -4]]]]) / 4.0) array_almost_equal(u, A([[[[5, 9, 4], [8, 14, 6], [3, 5, 2]]]]) / 4.0) def test_channels_batch(self): inpl = theano_var([[ [[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [3, 0, 0]] ], [ [[0, 3, 3], [4, 5, 6], [7, 8, 4]], [[-3, -3, -3], [-3, -3, -3], [3, 3, 3]] ]]) inpu = theano_var([[ [[1, 1, 1], [1, 1, 1], [1, 1, 1]], [[1, 1, 1], [1, 1, 1], [4, 1, 1]] ], [ [[2, 4, 4], [9, 9, 9], [9, 9, 9]], [[2, 2, 2], [2, 2, 2], [5, 5, 5]] ]]) iinp = TheanoInterval(inpl, inpu) doutl = theano_var([[ [[-1, -2], [-3, -4]], [[1, 2], [-3, -2]] ], [ [[1, 2], [-3, -2]], [[-1, 1], [-1, 1]] ]]) doutu = theano_var([[ [[5, 4], [3, 2]], [[4, 4], [4, 4]], ], [ [[4, 5], [0, 1]], [[0, 2], [0, 2]] ]]) idout = TheanoInterval(doutl, doutu) shp = (2, 2, 3, 3) din = d_pool(idout, iinp, shp, poolsize=(2, 2), mode='avg') l, u = din.eval() array_almost_equal(l, A([[ [[-1, -3, -2], [-4, -10, -6], [-3, -7, -4]], [[1, 3, 2], [-2, -2, 0], [-3, -5, -2]] ], [ [[1, 3, 2], [-2, -2, 0], [-3, -5, -2]], [[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]] ]]) / 4.0) array_almost_equal(u, A([[ [[5, 9, 4], [8, 14, 6], [3, 5, 2]], [[4, 8, 4], [8, 16, 8], [4, 8, 4]] ], [ [[4, 9, 5], [4, 10, 6], [0, 1, 1]], [[0, 2, 2], [0, 4, 4], [0, 2, 2]] ]]) / 4.0) def test_stride(self): tinpl = theano.shared(np.arange(25).reshape((1, 1, 5, 5))) tinpu = theano.shared(np.arange(25).reshape((1, 1, 5, 5)) + 2) iinp = TheanoInterval(tinpl, tinpu) idout = theano_interval([[[[-1, 2], [-3, 4]]]]) shp = (1, 1, 5, 5) din = d_pool(idout, iinp, shp, poolsize=(2, 2), stride=(3, 3), mode='avg') l, u = din.eval() array_almost_equal(l, A([[[[-1, -1, 0, 2, 2], [-1, -1, 0, 2, 2], [0, 0, 0, 0, 0], [-3, -3, 0, 4, 4], [-3, -3, 0, 4, 4]]]]) / 4.0) array_almost_equal(u, A([[[[-1, -1, 0, 2, 2], [-1, -1, 0, 2, 2], [0, 0, 0, 0, 0], [-3, -3, 0, 4, 4], [-3, -3, 0, 4, 4]]]]) / 4.0) def test_padding(self): inpl = theano_var([[[[0, 0, 0], [0, 0, 0], [0, 0, 0]]]]) inpu = theano_var([[[[1, 1, 1], [1, 1, 1], [1, 1, 1]]]]) iinp = TheanoInterval(inpl, inpu) doutl = theano_var([[[[-1, -2], [-3, -4]]]]) doutu = theano_var([[[[5, 4], [3, 2]]]]) idout = TheanoInterval(doutl, doutu) shp = (1, 1, 3, 3) din = d_pool(idout, iinp, shp, poolsize=(2, 2), padding=(1, 1), stride=(3, 3), mode='avg') l, u = din.eval() array_almost_equal(l, A([[[[-1, 0, -2], [0, 0, 0], [-3, 0, -4]]]]) / 4.0) array_almost_equal(u, A([[[[5, 0, 4], [0, 0, 0], [3, 0, 2]]]]) / 4.0) class SoftmaxDerivativeTest(DerivativeTest): def test_1_output(self): dout = TheanoInterval.derest_output(1) din = d_softmax(dout) l, u = din.eval() array_almost_equal(l, u) array_almost_equal(l, A([[1]])) def test_3_outputs(self): dout = TheanoInterval.derest_output(3) din = d_softmax(dout) l, u = din.eval() array_almost_equal(l, u) array_almost_equal(l, A([[1, 0, 0], [0, 1, 0], [0, 0, 1]])) class NormDerivativeTest(DerivativeTest): alpha = 0.00002 beta = 0.75 k = 1.0 n = 5 def test_simple(self): iint = theano_interval([[[[100]]]]) idout = theano_interval([[[[100]]]]) ishp = (1, 1, 1, 1) din = d_norm(idout, iint, ishp, self.n, self.k, self.alpha, self.beta) l, u = din.eval() array_almost_equal(l, A([[[[65.4146962]]]])) array_almost_equal(u, A([[[[65.4146962]]]])) def test_2x2(self): iint = theano_interval([[[[1, 10], [100, 1000]]]]) idout = theano_interval([[[[1, 10], [100, 1000]]]]) ishp = (1, 1, 2, 2) din = d_norm(idout, iint, ishp, self.n, self.k, self.alpha, self.beta) l, u = din.eval() array_almost_equal(l, A([[[[0.9999550, 9.9551309], [65.4146962, -43.6876559]]]])) array_almost_equal(u, A([[[[0.9999550, 9.9551309], [65.4146962, -43.6876559]]]])) def test_batches(self): iint = theano_interval([[[[1, 10], [100, 1000]]], [[[1, 10], [100, 1000]]]]) idout = theano_interval([[[[1, 10], [100, 1000]]], [[[1, 10], [100, 1000]]]]) ishp = (2, 1, 2, 2) din = d_norm(idout, iint, ishp, self.n, self.k, self.alpha, self.beta) l, u = din.eval() array_almost_equal(l, A([[[[0.9999550, 9.9551309], [65.4146962, -43.6876559]]], [[[0.9999550, 9.9551309], [65.4146962, -43.6876559]]]])) array_almost_equal(u, A([[[[0.9999550, 9.9551309], [65.4146962, -43.6876559]]], [[[0.9999550, 9.9551309], [65.4146962, -43.6876559]]]])) def test_channels_2(self): iint = theano_interval([[[[100]], [[100]]]]) idout = theano_interval([[[[100]], [[100]]]]) ishp = (1, 2, 1, 1) din = d_norm(idout, iint, ishp, self.n, self.k, self.alpha, self.beta) l, u = din.eval() class DropoutDerivativeTest(DerivativeTest): def test_interval_3x3n(self): doutl = theano_var([[-3, 0, 3], [3, -3, -5], [-3, -2, 1]]) doutu = theano_var([[-3, 2, 3], [5, 3, 2], [-1, 3, 3]]) idout = TheanoInterval(doutl, doutu) idin = d_dropout(idout, 0.8) l, u = idin.eval() rl = A([[-0.6, 0, 0.6], [0.6, -0.6, -1], [-0.6, -0.4, 0.2]]) ru = A([[-0.6, 0.4, 0.6], [1, 0.6, 0.4], [-0.2, 0.6, 0.6]]) array_almost_equal(l, rl) array_almost_equal(u, ru) class ReluDerivativeTest(DerivativeTest): def test_4x3x2(self): shp = (4, 3, 2) act = np.zeros(shp) ind_n_in, ind_h, ind_w = np.indices(shp) act = 100 * ind_n_in + 10 * ind_h + ind_w thact = theano.shared(act) iact = TheanoInterval(thact, thact) thdout = theano.shared(np.ones(shp)) idout = TheanoInterval(thdout, thdout) idin = d_relu(idout, iact) l, u = idin.eval() assert_almost_equal(l[0, 0, 0], 0.0) assert_almost_equal(u[0, 0, 0], 1.0) assert_almost_equal(l[2, 1, 1], 1.0) assert_almost_equal(l[2, 2, 1], 1.0) assert_almost_equal(l[1, 0, 1], 1.0) assert_almost_equal(l[2, 1, 1], 1.0) assert_almost_equal(l[2, 2, 0], 1.0) assert_almost_equal(l[1, 0, 1], 1.0) def test_interval(self): actl = theano_var([-2, -1, -1, 0, 0, 1]) actu = theano_var([-1, 1, 0, 0, 1, 2]) doutl = theano_var([2, 3, 4, 7, 11, 13]) doutu = theano_var([3, 5, 7, 11, 13, 17]) iact = TheanoInterval(actl, actu) idout = TheanoInterval(doutl, doutu) idin = d_relu(idout, iact) l, u = idin.eval() rl = A([0, 0, 0, 0, 0, 13]) ru = A([0, 5, 7, 11, 13, 17]) array_almost_equal(l, rl) array_almost_equal(u, ru) def test_interval_negative(self): actl = theano_var([-2, -1, -1, 0, 0, 1]) actu = theano_var([-1, 1, 0, 0, 1, 2]) doutl = theano_var([-3, -5, -7, -11, -13, -17]) doutu = theano_var([-2, -3, -5, -7, -11, -13]) iact = TheanoInterval(actl, actu) idout = TheanoInterval(doutl, doutu) idin = d_relu(idout, iact) l, u = idin.eval() rl = A([0, -5, -7, -11, -13, -17]) ru = A([0, 0, 0, 0, 0, -13]) array_almost_equal(l, rl) array_almost_equal(u, ru) if __name__ == '__main__': unittest.main(verbosity=2, catchbreak=True)
18,937
405
1,078
bfaf6e7cdef5ef47cf258822d993d21d3a5b5cdf
9,317
py
Python
pynuodb/cursor.py
madscientist/nuodb-python
93dc174afada40f56f3e2ddded6b9f473b7ae553
[ "BSD-3-Clause" ]
null
null
null
pynuodb/cursor.py
madscientist/nuodb-python
93dc174afada40f56f3e2ddded6b9f473b7ae553
[ "BSD-3-Clause" ]
null
null
null
pynuodb/cursor.py
madscientist/nuodb-python
93dc174afada40f56f3e2ddded6b9f473b7ae553
[ "BSD-3-Clause" ]
null
null
null
"""A module for housing the Cursor class. Exported Classes: Cursor -- Class for representing a database cursor. """ from collections import deque from .statement import Statement, PreparedStatement from .exception import Error, NotSupportedError, ProgrammingError class Cursor(object): """Class for representing a database cursor. Public Functions: close -- Closes the cursor into the database. callproc -- Currently not supported. execute -- Executes an SQL operation. executemany -- Executes the operation for each list of paramaters passed in. fetchone -- Fetches the first row of results generated by the previous execute. fetchmany -- Fetches the number of rows that are passed in. fetchall -- Fetches everything generated by the previous execute. nextset -- Currently not supported. setinputsizes -- Currently not supported. setoutputsize -- Currently not supported. Private Functions: __init__ -- Constructor for the Cursor class. _check_closed -- Checks if the cursor is closed. _reset -- Resets SQL transaction variables. _execute -- Handles operations without parameters. _executeprepared -- Handles operations with parameters. _get_next_results -- Gets the next set of results. """ def __init__(self, session, prepared_statement_cache_size): """ Constructor for the Cursor class. :type session EncodedSession """ self.session = session """ :type : EncodedSession """ self._statement_cache = StatementCache(session, prepared_statement_cache_size) """ :type : StatementCache """ self._result_set = None """ :type : result_set.ResultSet """ self.closed = False self.arraysize = 1 self.description = None self.rowcount = -1 self.colcount = -1 self.rownumber = 0 self.__query = None @property def query(self): """Return the most recent query""" return self.__query def close(self): """Closes the cursor into the database.""" self._check_closed() self._statement_cache.shutdown() self._close_result_set() self.closed = True def _check_closed(self): """Checks if the cursor is closed.""" if self.closed: raise Error("cursor is closed") if self.session.closed: raise Error("connection is closed") def _close_result_set(self): """Close current ResultSet on client and server side""" if self._result_set: self._result_set.close(self.session) self._result_set = None def _reset(self): """Resets Cursor to a default SQL transaction state""" self.description = None self.rowcount = -1 self.colcount = -1 self._close_result_set() def callproc(self, procname, parameters=None): """Currently not supported.""" if(procname is not None or parameters is not None): raise NotSupportedError("Currently unsupported") def execute(self, operation, parameters=None): """Executes an SQL operation. The SQL operations can be with or without parameters, if parameters are included then _executeprepared is invoked to prepare and execute the operation. Arguments: operation -- SQL operation to be performed. parameters -- Additional parameters for the operation may be supplied, but these are optional. Returns: None """ self._check_closed() self._reset() self.__query = operation if parameters is None: exec_result = self._execute(operation) else: exec_result = self._executeprepared(operation, parameters) self.rowcount = exec_result.row_count if exec_result.result > 0: self._result_set = self.session.fetch_result_set(exec_result.statement) self.description = self.session.fetch_result_set_description(self._result_set) # TODO: ??? if self.rowcount < 0: self.rowcount = -1 self.rownumber = 0 def executesqltest(self, test): """Executes an SQL test. Arguments: test -- xml string containing the SQL test to be performed. Returns: String containing the result in the form of xml """ self._check_closed() self._reset() self.__query = test return self._executesqltest(test) def _execute(self, operation): """Handles operations without parameters.""" # Use handle to query return self.session.execute_statement(self._statement_cache.get_statement(), operation) def _executeprepared(self, operation, parameters): """Handles operations with parameters.""" # Create a statement handle p_statement = self._statement_cache.get_prepared_statement(operation) if p_statement.parameter_count != len(parameters): raise ProgrammingError("Incorrect number of parameters specified, expected %d, got %d" % (p_statement.parameter_count, len(parameters))) # Use handle to query return self.session.execute_prepared_statement(p_statement, parameters) def executemany(self, operation, seq_of_parameters): """Executes the operation for each list of paramaters passed in.""" self._check_closed() p_statement = self._statement_cache.get_prepared_statement(operation) self.session.execute_batch_prepared_statement(p_statement, seq_of_parameters) def _executesqltest(self, operation): """Handles operations without parameters.""" # Use handle to query return self.session.execute_sql_test(self._statement_cache.get_statement(), operation) def fetchone(self): """Fetches the first row of results generated by the previous execute.""" self._check_closed() if self._result_set is None: raise Error("Previous execute did not produce any results or no call was issued yet") self.rownumber += 1 return self._result_set.fetchone(self.session) def fetchmany(self, size=None): """Fetches the number of rows that are passed in.""" self._check_closed() if size is None: size = self.arraysize fetched_rows = [] num_fetched_rows = 0 while num_fetched_rows < size: row = self.fetchone() if row is None: break else: fetched_rows.append(row) num_fetched_rows += 1 return fetched_rows def fetchall(self): """Fetches everything generated by the previous execute.""" self._check_closed() fetched_rows = [] while True: row = self.fetchone() if row is None: break else: fetched_rows.append(row) return fetched_rows def nextset(self): """Currently not supported.""" raise NotSupportedError("Currently unsupported") def setinputsizes(self, sizes): """Currently not supported.""" pass def setoutputsize(self, size, column=None): """Currently not supported.""" pass
32.127586
100
0.625631
"""A module for housing the Cursor class. Exported Classes: Cursor -- Class for representing a database cursor. """ from collections import deque from .statement import Statement, PreparedStatement from .exception import Error, NotSupportedError, ProgrammingError class Cursor(object): """Class for representing a database cursor. Public Functions: close -- Closes the cursor into the database. callproc -- Currently not supported. execute -- Executes an SQL operation. executemany -- Executes the operation for each list of paramaters passed in. fetchone -- Fetches the first row of results generated by the previous execute. fetchmany -- Fetches the number of rows that are passed in. fetchall -- Fetches everything generated by the previous execute. nextset -- Currently not supported. setinputsizes -- Currently not supported. setoutputsize -- Currently not supported. Private Functions: __init__ -- Constructor for the Cursor class. _check_closed -- Checks if the cursor is closed. _reset -- Resets SQL transaction variables. _execute -- Handles operations without parameters. _executeprepared -- Handles operations with parameters. _get_next_results -- Gets the next set of results. """ def __init__(self, session, prepared_statement_cache_size): """ Constructor for the Cursor class. :type session EncodedSession """ self.session = session """ :type : EncodedSession """ self._statement_cache = StatementCache(session, prepared_statement_cache_size) """ :type : StatementCache """ self._result_set = None """ :type : result_set.ResultSet """ self.closed = False self.arraysize = 1 self.description = None self.rowcount = -1 self.colcount = -1 self.rownumber = 0 self.__query = None @property def query(self): """Return the most recent query""" return self.__query def close(self): """Closes the cursor into the database.""" self._check_closed() self._statement_cache.shutdown() self._close_result_set() self.closed = True def _check_closed(self): """Checks if the cursor is closed.""" if self.closed: raise Error("cursor is closed") if self.session.closed: raise Error("connection is closed") def _close_result_set(self): """Close current ResultSet on client and server side""" if self._result_set: self._result_set.close(self.session) self._result_set = None def _reset(self): """Resets Cursor to a default SQL transaction state""" self.description = None self.rowcount = -1 self.colcount = -1 self._close_result_set() def callproc(self, procname, parameters=None): """Currently not supported.""" if(procname is not None or parameters is not None): raise NotSupportedError("Currently unsupported") def execute(self, operation, parameters=None): """Executes an SQL operation. The SQL operations can be with or without parameters, if parameters are included then _executeprepared is invoked to prepare and execute the operation. Arguments: operation -- SQL operation to be performed. parameters -- Additional parameters for the operation may be supplied, but these are optional. Returns: None """ self._check_closed() self._reset() self.__query = operation if parameters is None: exec_result = self._execute(operation) else: exec_result = self._executeprepared(operation, parameters) self.rowcount = exec_result.row_count if exec_result.result > 0: self._result_set = self.session.fetch_result_set(exec_result.statement) self.description = self.session.fetch_result_set_description(self._result_set) # TODO: ??? if self.rowcount < 0: self.rowcount = -1 self.rownumber = 0 def executesqltest(self, test): """Executes an SQL test. Arguments: test -- xml string containing the SQL test to be performed. Returns: String containing the result in the form of xml """ self._check_closed() self._reset() self.__query = test return self._executesqltest(test) def _execute(self, operation): """Handles operations without parameters.""" # Use handle to query return self.session.execute_statement(self._statement_cache.get_statement(), operation) def _executeprepared(self, operation, parameters): """Handles operations with parameters.""" # Create a statement handle p_statement = self._statement_cache.get_prepared_statement(operation) if p_statement.parameter_count != len(parameters): raise ProgrammingError("Incorrect number of parameters specified, expected %d, got %d" % (p_statement.parameter_count, len(parameters))) # Use handle to query return self.session.execute_prepared_statement(p_statement, parameters) def executemany(self, operation, seq_of_parameters): """Executes the operation for each list of paramaters passed in.""" self._check_closed() p_statement = self._statement_cache.get_prepared_statement(operation) self.session.execute_batch_prepared_statement(p_statement, seq_of_parameters) def _executesqltest(self, operation): """Handles operations without parameters.""" # Use handle to query return self.session.execute_sql_test(self._statement_cache.get_statement(), operation) def fetchone(self): """Fetches the first row of results generated by the previous execute.""" self._check_closed() if self._result_set is None: raise Error("Previous execute did not produce any results or no call was issued yet") self.rownumber += 1 return self._result_set.fetchone(self.session) def fetchmany(self, size=None): """Fetches the number of rows that are passed in.""" self._check_closed() if size is None: size = self.arraysize fetched_rows = [] num_fetched_rows = 0 while num_fetched_rows < size: row = self.fetchone() if row is None: break else: fetched_rows.append(row) num_fetched_rows += 1 return fetched_rows def fetchall(self): """Fetches everything generated by the previous execute.""" self._check_closed() fetched_rows = [] while True: row = self.fetchone() if row is None: break else: fetched_rows.append(row) return fetched_rows def nextset(self): """Currently not supported.""" raise NotSupportedError("Currently unsupported") def setinputsizes(self, sizes): """Currently not supported.""" pass def setoutputsize(self, size, column=None): """Currently not supported.""" pass class StatementCache(object): def __init__(self, session, prepared_statement_cache_size): self._session = session """ :type : EncodedSession """ self._statement = self._session.create_statement() """ :type : Statement """ self._ps_cache = dict() """ :type : dict[str,PreparedStatement] """ self._ps_key_queue = deque() """ :type : deque[str] """ self._ps_cache_size = prepared_statement_cache_size """ :type : int """ def get_statement(self): """ :rtype : Statement """ return self._statement def get_prepared_statement(self, query): """ :type query str :rtype : PreparedStatement """ statement = self._ps_cache.get(query) if statement is not None: self._ps_key_queue.remove(query) self._ps_key_queue.append(query) return statement statement = self._session.create_prepared_statement(query) while len(self._ps_cache) >= self._ps_cache_size: lru_statement_key = self._ps_key_queue.popleft() statement_to_remove = self._ps_cache[lru_statement_key] self._session.close_statement(statement_to_remove) del self._ps_cache[lru_statement_key] self._ps_key_queue.append(query) self._ps_cache[query] = statement return statement def shutdown(self): """ Close connection and clear the cursor cache""" self._session.close_statement(self._statement) for key in self._ps_cache: statement_to_remove = self._ps_cache[key] self._session.close_statement(statement_to_remove) self._ps_cache.clear() self._ps_key_queue.clear()
450
1,313
23
fe701f3001d6852bba8289651be46f88091b413c
115
py
Python
grapherty/properties/__init__.py
Mautriz/grapherty
5aae4fb13b0b0cb715911373e5cfb2d75bddc2c6
[ "MIT" ]
null
null
null
grapherty/properties/__init__.py
Mautriz/grapherty
5aae4fb13b0b0cb715911373e5cfb2d75bddc2c6
[ "MIT" ]
null
null
null
grapherty/properties/__init__.py
Mautriz/grapherty
5aae4fb13b0b0cb715911373e5cfb2d75bddc2c6
[ "MIT" ]
null
null
null
from .one import * from .two import * from .three import * properties = [PropertyOne, PropertyTwo, PropertyThree]
19.166667
54
0.747826
from .one import * from .two import * from .three import * properties = [PropertyOne, PropertyTwo, PropertyThree]
0
0
0
d20fe013cd627b92dda27ee894bcdae87d098d82
1,318
py
Python
src/modules/tests/testQnetwork.py
sankhaMukherjee/RLalgos
80d19a39af29947db2fc73b0443b9c3bb66d6fc0
[ "MIT" ]
null
null
null
src/modules/tests/testQnetwork.py
sankhaMukherjee/RLalgos
80d19a39af29947db2fc73b0443b9c3bb66d6fc0
[ "MIT" ]
25
2019-03-30T00:31:07.000Z
2022-03-11T23:38:34.000Z
src/modules/tests/testQnetwork.py
sankhaMukherjee/RLalgos
80d19a39af29947db2fc73b0443b9c3bb66d6fc0
[ "MIT" ]
null
null
null
from logs import logDecorator as lD import json import numpy as np import torch from torch.nn import functional as F from lib.agents import qNetwork as qN import torch config = json.load(open('../config/config.json')) logBase = config['logging']['logBase'] + '.modules.tests.testPolicy' @lD.log( logBase + '.testArgMax' ) @lD.log( logBase + '.allTests' )
24.407407
97
0.562974
from logs import logDecorator as lD import json import numpy as np import torch from torch.nn import functional as F from lib.agents import qNetwork as qN import torch config = json.load(open('../config/config.json')) logBase = config['logging']['logBase'] + '.modules.tests.testPolicy' @lD.log( logBase + '.testArgMax' ) def testQnetwork(logger): try: print('--------------------') qn = qN.qNetworkDiscrete( 2, 1, [64, 64], activations=[torch.tanh, torch.tanh], lr=0.001) X = np.random.rand(30, 2).astype( np.float32 ) y = (2*X[:,0] + 3*X[:,1]).reshape(-1, 1) yT = torch.as_tensor( y ) for i in range(1000): qn.step( qn( torch.as_tensor(X) ), yT ) if i % 100 == 0: yHat = qn( torch.as_tensor(X) ).cpu().detach().numpy() print(np.mean((yHat - y)**2)) yHat = qn( torch.as_tensor(X) ).cpu().detach().numpy() print(f'Final error: {np.mean((yHat - y)**2)}') except Exception as e: logger.error(f'Unable to do the test for argmax: {e}') return @lD.log( logBase + '.allTests' ) def allTests(logger): try: testQnetwork() except Exception as e: logger.error(f'Unable to finish Memory Buffer tests: {e}') return
910
0
44
f7a0c034abe6bcbd6d0f2ab7346d69d8e7c9cbde
7,321
py
Python
games/world_gen_output.py
wnormandin/resources
43be223b0c66e944985357a6d23891b551ac2937
[ "MIT" ]
null
null
null
games/world_gen_output.py
wnormandin/resources
43be223b0c66e944985357a6d23891b551ac2937
[ "MIT" ]
null
null
null
games/world_gen_output.py
wnormandin/resources
43be223b0c66e944985357a6d23891b551ac2937
[ "MIT" ]
null
null
null
map_template = ( ( (0,0,0,0,3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), (0,0,0,0,3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), (0,0,0,0,3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), (0,0,0,0,3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), (0,0,1,0,0,1,0,0,0,0,0,3,3,3,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0), (0,0,1,1,1,1,0,0,0,0,0,3,3,3,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0), (0,0,1,0,0,0,0,0,0,0,0,3,3,3,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), (0,0,1,0,0,0,0,0,0,0,0,0,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,3,3,3), (0,0,1,0,0,0,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,3,3,3), (0,0,1,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,3,3,3,1,0,0,0,0,0,0,0,0,0,0,0,3,3,3), (0,0,1,0,0,0,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,3,D,3,1,1,1,1,1,1,1,1,1,1,1,1,3,3,3), (0,1,1,0,0,0,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,0,1,0,0,0,0,0,1,0,0,0,0,3,3,3), (3,3,1,0,0,0,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,3,3,3,3,3,0,0,0,0,0,0,0,0,1,1), (S,3,1,0,0,0,0,0,0,0,3,3,3,1,1,0,0,0,0,0,0,0,0,0,0,3,3,3,1,1,3,3,3,3,3,0,0,0,0,0,0,0,0,1,1), (3,3,1,1,1,1,1,1,3,3,3,3,3,1,3,3,3,3,3,1,1,1,1,1,1,3,3,3,1,0,3,3,3,3,3,0,0,0,0,0,0,0,0,3,3), (0,0,1,1,1,0,0,0,3,3,3,3,3,1,3,3,3,3,3,1,1,1,1,1,1,3,3,3,1,1,3,3,3,3,3,0,0,0,0,0,0,0,0,3,3), (0,1,1,0,0,0,0,0,3,3,3,1,0,1,3,3,3,3,3,1,0,0,0,1,0,0,0,1,1,1,3,3,3,3,3,3,3,1,1,1,1,1,1,3,3), (0,1,0,0,0,0,0,0,0,1,0,1,1,3,3,3,3,3,3,0,0,0,0,0,0,0,0,3,3,3,1,1,1,1,3,3,3,0,0,0,0,0,0,0,0), (0,1,0,0,0,0,0,0,0,1,0,0,1,3,3,3,3,3,3,1,1,1,1,1,1,1,1,3,3,3,0,0,1,0,3,3,3,0,0,0,0,0,0,0,0), (0,0,0,0,0,3,3,3,0,1,1,1,1,3,3,3,3,3,1,0,0,0,0,0,0,0,0,3,3,3,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0), (0,0,0,0,0,3,3,3,0,0,0,0,0,3,3,3,3,3,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0), (0,0,0,0,0,3,3,3,0,0,0,0,1,3,3,3,3,3,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3), (0,0,0,0,0,0,1,0,0,0,3,3,3,3,3,0,0,0,0,0,0,0,0,0,1,0,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3), (0,0,0,0,0,0,1,1,1,1,3,3,3,3,3,1,1,1,1,1,1,1,1,1,1,0,3,3,3,1,1,1,1,1,1,1,1,1,1,1,1,3,3,3,3), (0,0,0,0,0,0,1,1,0,0,3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,3,3,3,0,0,0,0,1,0,0,0,0,1,0,0,3,3,3,3), ), ( (3,3,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,3), (D,3,1,1,1,1,1,1,1,1,1,1,1,3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,3), (3,3,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,3,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,3,3,3,0,0,0,0,3,3,3,3,3), (0,0,0,0,0,0,0,0,0,1,1,1,1,3,3,3,3,3,1,1,1,1,0,1,0,0,0,0,0,0,0,0,0,3,3,3,0,0,0,0,3,3,3,3,3), (0,0,0,0,0,0,0,0,0,1,0,0,0,3,3,3,3,3,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,3,3,3,0,0,0,0,3,3,3,3,3), (0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,3,3,3,3,3,0,0,0,0,0,0,0,1,0), (0,0,0,0,1,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,3,3,3,0,0,0,3,3,3,3,3,0,0,0,0,0,0,1,1,0), (0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,3,3,3,3,3,1,1,3,3,3,3,3,0,0,0,0,0,0,1,0,0), (3,3,3,3,3,0,1,1,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,1,3,3,3,3,3,3,3,3,3,3,3,3,1,0,0,0,0,0,1,1,0), (3,3,3,3,3,0,0,0,3,3,3,1,1,1,0,0,0,0,0,0,0,0,0,1,3,3,3,3,3,3,3,3,3,3,3,3,0,0,0,0,0,0,0,1,0), (3,3,3,3,3,0,0,0,3,3,3,0,1,1,0,0,0,0,0,0,0,0,0,1,3,3,3,3,U,3,3,3,0,0,1,0,1,1,1,0,0,0,0,1,0), (3,3,3,3,3,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,3,3,3,3,3,3,0,0,0,0,1,0,0,1,1,0,0,0,0,1,1), (3,3,3,3,3,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,1,0,1,0,1,0,0,0,0,1,0,0,0,1,0,0,0,0,0,1), (0,1,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,1,0,0,0,0,1,0,0,0,1,0,0,0,0,0,1), (0,1,1,0,0,0,0,0,0,0,0,3,3,3,3,3,0,0,0,0,0,0,0,0,0,1,1,0,0,1,0,0,0,0,1,0,0,0,1,1,0,0,0,1,1), (3,3,3,1,1,1,1,1,1,1,1,3,3,3,3,3,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,0,0,0,1,1,1,0,0,1,1), (3,3,3,1,1,1,1,1,1,1,1,3,3,3,3,3,1,1,1,1,1,1,1,3,3,3,1,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,0,0,1), (3,3,3,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,3,3,3,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0,1,0,1,1), (0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,3,3,3,1,0,0,0,0,0,1,1,0,0,0,0,0,0,0,1,0,1,1), (0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,3,3,3,3,3,0,0,0,1,0,0,0,0,0,0,0,0,1,0,1,0), (0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,1,3,3,3,3,3,0,0,0,1,0,0,0,0,0,0,0,0,1,1,0,0), (0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,3,3,3,3,3,0,0,0,1,0,0,0,0,0,0,0,3,3,3,3,3), (0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,0,0,0,1,1,1,3,3,3,3,3,0,3,3,3,3,3,0,0,0,0,0,3,3,3,3,3), (0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,3,3,3,3,3,0,3,3,3,3,3,0,0,0,0,0,3,3,3,3,3), (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,3,3,3,3,3,0,3,3,3,3,3,0,0,0,0,0,3,3,3,3,3), ), ( (3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), (U,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), (3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), (0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), (0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,3,0,0), (0,0,1,1,0,0,0,0,0,0,0,0,0,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,3,0,3,3,3,3,3,0,0), (0,0,0,1,0,0,0,0,0,0,0,0,0,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,3,1,3,3,3,3,3,0,0), (0,0,0,1,0,0,0,0,0,0,0,0,0,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,3,3,3,1,3,3,3,3,3,1,0), (0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,3,D,3,3,3,3,3,1,3,3,3,3,3,1,0), (0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,3,3,3,0,1,1,0,1,0,1,0), (0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,3,3,3,3), (0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,1,0,0,3,3,3,3), (0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,3,3,3,3), (0,3,3,3,3,3,3,3,3,3,3,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,3,3,3,3,3,3,3,3), (0,3,3,3,3,3,3,3,3,3,3,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,0,0,3,3,3,3,3,3,3,3), (0,3,3,3,3,3,3,3,3,3,3,3,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,3,3,3,3,3,3,3,3,3,3,0,0,0), (0,3,3,3,3,3,3,3,3,3,3,3,1,1,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,3,3,3,3,3,3,3,3,3,3,1,0,0), (0,3,3,3,3,3,3,3,3,3,3,3,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,1,3,3,3,3,3,3,3,3,3,3,3,3,0), (0,3,3,3,3,3,3,3,3,3,3,1,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,3,3,3,3,3,3,1,1,1,3,3,3,0), (0,3,3,3,3,3,3,3,3,3,3,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,3,3,3,3,3,3,0,1,1,3,3,3,0), (0,0,3,3,3,3,3,1,3,3,3,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,3,0,0,0,0,0,0,0), (0,0,3,3,3,3,3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,3,0,0,0,0,0,0,0), (0,0,0,0,0,0,3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,3,0,0,0,0,0,0,0), (0,0,0,0,0,0,3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), (0,0,0,0,0,0,3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), ), )
87.154762
96
0.462642
map_template = ( ( (0,0,0,0,3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), (0,0,0,0,3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), (0,0,0,0,3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), (0,0,0,0,3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), (0,0,1,0,0,1,0,0,0,0,0,3,3,3,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0), (0,0,1,1,1,1,0,0,0,0,0,3,3,3,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0), (0,0,1,0,0,0,0,0,0,0,0,3,3,3,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), (0,0,1,0,0,0,0,0,0,0,0,0,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,3,3,3), (0,0,1,0,0,0,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,3,3,3), (0,0,1,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,3,3,3,1,0,0,0,0,0,0,0,0,0,0,0,3,3,3), (0,0,1,0,0,0,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,3,D,3,1,1,1,1,1,1,1,1,1,1,1,1,3,3,3), (0,1,1,0,0,0,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,0,1,0,0,0,0,0,1,0,0,0,0,3,3,3), (3,3,1,0,0,0,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,3,3,3,3,3,0,0,0,0,0,0,0,0,1,1), (S,3,1,0,0,0,0,0,0,0,3,3,3,1,1,0,0,0,0,0,0,0,0,0,0,3,3,3,1,1,3,3,3,3,3,0,0,0,0,0,0,0,0,1,1), (3,3,1,1,1,1,1,1,3,3,3,3,3,1,3,3,3,3,3,1,1,1,1,1,1,3,3,3,1,0,3,3,3,3,3,0,0,0,0,0,0,0,0,3,3), (0,0,1,1,1,0,0,0,3,3,3,3,3,1,3,3,3,3,3,1,1,1,1,1,1,3,3,3,1,1,3,3,3,3,3,0,0,0,0,0,0,0,0,3,3), (0,1,1,0,0,0,0,0,3,3,3,1,0,1,3,3,3,3,3,1,0,0,0,1,0,0,0,1,1,1,3,3,3,3,3,3,3,1,1,1,1,1,1,3,3), (0,1,0,0,0,0,0,0,0,1,0,1,1,3,3,3,3,3,3,0,0,0,0,0,0,0,0,3,3,3,1,1,1,1,3,3,3,0,0,0,0,0,0,0,0), (0,1,0,0,0,0,0,0,0,1,0,0,1,3,3,3,3,3,3,1,1,1,1,1,1,1,1,3,3,3,0,0,1,0,3,3,3,0,0,0,0,0,0,0,0), (0,0,0,0,0,3,3,3,0,1,1,1,1,3,3,3,3,3,1,0,0,0,0,0,0,0,0,3,3,3,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0), (0,0,0,0,0,3,3,3,0,0,0,0,0,3,3,3,3,3,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0), (0,0,0,0,0,3,3,3,0,0,0,0,1,3,3,3,3,3,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3), (0,0,0,0,0,0,1,0,0,0,3,3,3,3,3,0,0,0,0,0,0,0,0,0,1,0,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3), (0,0,0,0,0,0,1,1,1,1,3,3,3,3,3,1,1,1,1,1,1,1,1,1,1,0,3,3,3,1,1,1,1,1,1,1,1,1,1,1,1,3,3,3,3), (0,0,0,0,0,0,1,1,0,0,3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,3,3,3,0,0,0,0,1,0,0,0,0,1,0,0,3,3,3,3), ), ( (3,3,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,3), (D,3,1,1,1,1,1,1,1,1,1,1,1,3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,3), (3,3,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,3,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,3,3,3,0,0,0,0,3,3,3,3,3), (0,0,0,0,0,0,0,0,0,1,1,1,1,3,3,3,3,3,1,1,1,1,0,1,0,0,0,0,0,0,0,0,0,3,3,3,0,0,0,0,3,3,3,3,3), (0,0,0,0,0,0,0,0,0,1,0,0,0,3,3,3,3,3,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,3,3,3,0,0,0,0,3,3,3,3,3), (0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,3,3,3,3,3,0,0,0,0,0,0,0,1,0), (0,0,0,0,1,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,3,3,3,0,0,0,3,3,3,3,3,0,0,0,0,0,0,1,1,0), (0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,3,3,3,3,3,1,1,3,3,3,3,3,0,0,0,0,0,0,1,0,0), (3,3,3,3,3,0,1,1,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,1,3,3,3,3,3,3,3,3,3,3,3,3,1,0,0,0,0,0,1,1,0), (3,3,3,3,3,0,0,0,3,3,3,1,1,1,0,0,0,0,0,0,0,0,0,1,3,3,3,3,3,3,3,3,3,3,3,3,0,0,0,0,0,0,0,1,0), (3,3,3,3,3,0,0,0,3,3,3,0,1,1,0,0,0,0,0,0,0,0,0,1,3,3,3,3,U,3,3,3,0,0,1,0,1,1,1,0,0,0,0,1,0), (3,3,3,3,3,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,3,3,3,3,3,3,0,0,0,0,1,0,0,1,1,0,0,0,0,1,1), (3,3,3,3,3,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,1,0,1,0,1,0,0,0,0,1,0,0,0,1,0,0,0,0,0,1), (0,1,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,1,0,0,0,0,1,0,0,0,1,0,0,0,0,0,1), (0,1,1,0,0,0,0,0,0,0,0,3,3,3,3,3,0,0,0,0,0,0,0,0,0,1,1,0,0,1,0,0,0,0,1,0,0,0,1,1,0,0,0,1,1), (3,3,3,1,1,1,1,1,1,1,1,3,3,3,3,3,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,0,0,0,1,1,1,0,0,1,1), (3,3,3,1,1,1,1,1,1,1,1,3,3,3,3,3,1,1,1,1,1,1,1,3,3,3,1,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,0,0,1), (3,3,3,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,3,3,3,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0,1,0,1,1), (0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,3,3,3,1,0,0,0,0,0,1,1,0,0,0,0,0,0,0,1,0,1,1), (0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,3,3,3,3,3,0,0,0,1,0,0,0,0,0,0,0,0,1,0,1,0), (0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,1,3,3,3,3,3,0,0,0,1,0,0,0,0,0,0,0,0,1,1,0,0), (0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,3,3,3,3,3,0,0,0,1,0,0,0,0,0,0,0,3,3,3,3,3), (0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,0,0,0,1,1,1,3,3,3,3,3,0,3,3,3,3,3,0,0,0,0,0,3,3,3,3,3), (0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,3,3,3,3,3,0,3,3,3,3,3,0,0,0,0,0,3,3,3,3,3), (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,3,3,3,3,3,0,3,3,3,3,3,0,0,0,0,0,3,3,3,3,3), ), ( (3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), (U,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), (3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), (0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), (0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,3,0,0), (0,0,1,1,0,0,0,0,0,0,0,0,0,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,3,0,3,3,3,3,3,0,0), (0,0,0,1,0,0,0,0,0,0,0,0,0,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,3,1,3,3,3,3,3,0,0), (0,0,0,1,0,0,0,0,0,0,0,0,0,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,3,3,3,1,3,3,3,3,3,1,0), (0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,3,D,3,3,3,3,3,1,3,3,3,3,3,1,0), (0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,3,3,3,0,1,1,0,1,0,1,0), (0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,3,3,3,3), (0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,1,0,0,3,3,3,3), (0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,3,3,3,3), (0,3,3,3,3,3,3,3,3,3,3,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,3,3,3,3,3,3,3,3), (0,3,3,3,3,3,3,3,3,3,3,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,0,0,3,3,3,3,3,3,3,3), (0,3,3,3,3,3,3,3,3,3,3,3,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,3,3,3,3,3,3,3,3,3,3,0,0,0), (0,3,3,3,3,3,3,3,3,3,3,3,1,1,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,3,3,3,3,3,3,3,3,3,3,1,0,0), (0,3,3,3,3,3,3,3,3,3,3,3,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,1,3,3,3,3,3,3,3,3,3,3,3,3,0), (0,3,3,3,3,3,3,3,3,3,3,1,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,3,3,3,3,3,3,1,1,1,3,3,3,0), (0,3,3,3,3,3,3,3,3,3,3,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,3,3,3,3,3,3,0,1,1,3,3,3,0), (0,0,3,3,3,3,3,1,3,3,3,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,3,0,0,0,0,0,0,0), (0,0,3,3,3,3,3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,3,0,0,0,0,0,0,0), (0,0,0,0,0,0,3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,3,0,0,0,0,0,0,0), (0,0,0,0,0,0,3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), (0,0,0,0,0,0,3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), ), )
0
0
0
4d67af64d56116da62993595b723329bee185928
42
py
Python
tensordata/paper/WACV/__init__.py
Hourout/tensordata
cbef6742ee0d3bfc4b886358fc01618bb5b63603
[ "Apache-2.0" ]
13
2019-01-08T10:22:39.000Z
2020-06-17T10:02:47.000Z
tensordata/paper/WACV/__init__.py
Hourout/tensordata
cbef6742ee0d3bfc4b886358fc01618bb5b63603
[ "Apache-2.0" ]
null
null
null
tensordata/paper/WACV/__init__.py
Hourout/tensordata
cbef6742ee0d3bfc4b886358fc01618bb5b63603
[ "Apache-2.0" ]
1
2020-06-17T10:02:49.000Z
2020-06-17T10:02:49.000Z
from tensordata.paper.WACV._wacv import *
21
41
0.809524
from tensordata.paper.WACV._wacv import *
0
0
0
a8700ebf98366f97e9d9a60d1fdc6859359b5397
124
py
Python
src/test1.py
danilecug/GitTestNew
c76e3a71fea296eddc5c4110b853a5089904ea7d
[ "MIT" ]
null
null
null
src/test1.py
danilecug/GitTestNew
c76e3a71fea296eddc5c4110b853a5089904ea7d
[ "MIT" ]
null
null
null
src/test1.py
danilecug/GitTestNew
c76e3a71fea296eddc5c4110b853a5089904ea7d
[ "MIT" ]
null
null
null
import numpu as np import scipy as sp import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import pdb
15.5
31
0.806452
import numpu as np import scipy as sp import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import pdb
0
0
0
d02428ca36b49bbfb13c2f3c47cecf62c9b9d042
211
py
Python
networkx/algorithms/connectivity/__init__.py
tempcyc/networkx
cae83ba501c242567cb2454f97f851898276f06e
[ "BSD-3-Clause" ]
1
2015-07-16T01:36:44.000Z
2015-07-16T01:36:44.000Z
networkx/algorithms/connectivity/__init__.py
tempcyc/networkx
cae83ba501c242567cb2454f97f851898276f06e
[ "BSD-3-Clause" ]
null
null
null
networkx/algorithms/connectivity/__init__.py
tempcyc/networkx
cae83ba501c242567cb2454f97f851898276f06e
[ "BSD-3-Clause" ]
null
null
null
"""Connectivity and cut algorithms """ from networkx.algorithms.connectivity.connectivity import * from networkx.algorithms.connectivity.cuts import * from networkx.algorithms.connectivity.stoer_wagner import *
35.166667
59
0.834123
"""Connectivity and cut algorithms """ from networkx.algorithms.connectivity.connectivity import * from networkx.algorithms.connectivity.cuts import * from networkx.algorithms.connectivity.stoer_wagner import *
0
0
0
92442f9bdf30bef30f81e6e93fec882d43e694a1
1,522
py
Python
DNN.py
idocal/statslearning
a72b492d4ec07de3c719727015ad74b045b66bd6
[ "MIT" ]
null
null
null
DNN.py
idocal/statslearning
a72b492d4ec07de3c719727015ad74b045b66bd6
[ "MIT" ]
null
null
null
DNN.py
idocal/statslearning
a72b492d4ec07de3c719727015ad74b045b66bd6
[ "MIT" ]
null
null
null
import torch from torch import nn import torch.nn.functional as F import pytorch_lightning as pl
31.061224
73
0.574901
import torch from torch import nn import torch.nn.functional as F import pytorch_lightning as pl class DNN(pl.LightningModule): def __init__(self, n_feats, layers=None): super().__init__() if layers is None: layers = [n_feats * 2] modules = [] if not len(layers): # perceptron modules = [nn.Linear(n_feats, 1)] else: modules += [nn.Linear(n_feats, layers[0]), nn.ReLU()] for i in range(1, len(layers)): modules += [nn.Linear(layers[i-1], layers[i]), nn.ReLU()] modules += [nn.Linear(layers[-1], 1)] self.net = nn.Sequential(*modules) def forward(self, x): return self.net(x) def training_step(self, batch, batch_idx): x, y = batch y = y.type(torch.FloatTensor) # necessary for MSE x = x.view(x.size(0), -1) y_hat = self.net(x) y_hat = torch.squeeze(y_hat) loss = F.mse_loss(y_hat, y) self.log("train_loss", loss, on_epoch=True) return loss def validation_step(self, val_batch, batch_idx): x, y = val_batch y = y.type(torch.FloatTensor) # necessary for MSE x = x.view(x.size(0), -1) y_hat = self.net(x) y_hat = torch.squeeze(y_hat) val_loss = F.mse_loss(y_hat, y) self.log("val_loss", val_loss) return val_loss def configure_optimizers(self): optimizer = torch.optim.Adam(self.parameters(), lr=1e-3) return optimizer
1,257
9
158
5f5c3304c166f2a61c8883dc9a55e972b6432a91
1,151
py
Python
src/io_gateway/pinata.py
nakata5321/feecc-io-gateway
a7a70c3b7239142e7ee1b846916d28961020b1a9
[ "Apache-2.0" ]
null
null
null
src/io_gateway/pinata.py
nakata5321/feecc-io-gateway
a7a70c3b7239142e7ee1b846916d28961020b1a9
[ "Apache-2.0" ]
2
2021-11-27T09:31:12.000Z
2022-03-23T13:15:57.000Z
src/io_gateway/pinata.py
nakata5321/feecc-io-gateway
a7a70c3b7239142e7ee1b846916d28961020b1a9
[ "Apache-2.0" ]
2
2021-12-09T13:50:51.000Z
2022-03-23T12:39:38.000Z
from __future__ import annotations import os import typing as tp from time import time import httpx from loguru import logger from ..shared.config import config PINATA_ENDPOINT: str = "https://api.pinata.cloud" PINATA_API: str = config.pinata.pinata_api PINATA_SECRET_API: str = config.pinata.pinata_secret_api AUTH_HEADERS = { "pinata_api_key": PINATA_API, "pinata_secret_api_key": PINATA_SECRET_API, } @logger.catch(reraise=True)
31.108108
97
0.724587
from __future__ import annotations import os import typing as tp from time import time import httpx from loguru import logger from ..shared.config import config PINATA_ENDPOINT: str = "https://api.pinata.cloud" PINATA_API: str = config.pinata.pinata_api PINATA_SECRET_API: str = config.pinata.pinata_secret_api AUTH_HEADERS = { "pinata_api_key": PINATA_API, "pinata_secret_api_key": PINATA_SECRET_API, } @logger.catch(reraise=True) async def pin_file(file: tp.Union[os.PathLike[tp.AnyStr], tp.IO[bytes]]) -> tp.Tuple[str, str]: logger.info("Pushing file to Pinata") t0 = time() files = {"file": open(file, "rb") if isinstance(file, os.PathLike) else file} async with httpx.AsyncClient(base_url=PINATA_ENDPOINT, timeout=600.0) as client: response = await client.post("/pinning/pinFileToIPFS", files=files, headers=AUTH_HEADERS) data = response.json() ipfs_hash: str = data["IpfsHash"] ipfs_link: str = config.ipfs.gateway_address + ipfs_hash logger.info("Published file to Pinata.") logger.debug(f"Push took {round(time() - t0, 3)} s.") logger.debug(data) return ipfs_hash, ipfs_link
683
0
22
e508928aef3dd5fedee7d857f487400676619dd7
3,270
py
Python
wikidataintegrator/ref_handlers/update_retrieved_if_new_multiple_refs.py
tentwentyfour/WikidataIntegrator
a035d585ade4b0aa7a2b6126f14f2c5a828f6c49
[ "MIT" ]
193
2017-01-16T14:19:40.000Z
2022-03-13T18:44:18.000Z
wikidataintegrator/ref_handlers/update_retrieved_if_new_multiple_refs.py
tentwentyfour/WikidataIntegrator
a035d585ade4b0aa7a2b6126f14f2c5a828f6c49
[ "MIT" ]
140
2017-01-17T20:20:29.000Z
2022-03-21T11:17:11.000Z
wikidataintegrator/ref_handlers/update_retrieved_if_new_multiple_refs.py
tentwentyfour/WikidataIntegrator
a035d585ade4b0aa7a2b6126f14f2c5a828f6c49
[ "MIT" ]
53
2016-12-30T11:24:20.000Z
2022-03-16T20:46:07.000Z
#### # custom ref handler # If the newref is the same as the oldref except the retrieved date is `days` newer, overwrite # the retrieved date is NOT `days` newer, keep the old ref # If the refs are different (in any other way), overwrite with new ref # #### from datetime import datetime def update_retrieved_if_new_multiple_refs(olditem, newitem, days=180, retrieved_pid='P813'): """ # modifies olditem in place # any ref that does not exactly match the new proposed reference (not including retrieved) is kept """ def is_equal_not_retrieved(oldref, newref): """ Return True if the oldref == newref, NOT including any "retrieved" statements :param oldref: :param newref: :return: """ if len(oldref) != len(newref): return False oldref_minus_retrieved = [x for x in oldref if x.get_prop_nr() != retrieved_pid] newref_minus_retrieved = [x for x in newref if x.get_prop_nr() != retrieved_pid] if not all(x in oldref_minus_retrieved for x in newref_minus_retrieved): return False oldref_retrieved = [x for x in oldref if x.get_prop_nr() == retrieved_pid] newref_retrieved = [x for x in newref if x.get_prop_nr() == retrieved_pid] if (len(newref_retrieved) != len(oldref_retrieved)): return False return True def ref_overwrite(oldref, newref, days): """ If the newref is the same as the oldref except the retrieved date is `days` newer, return True the retrieved date is NOT `days` newer, return False the refs are different, return True """ if len(oldref) != len(newref): return True oldref_minus_retrieved = [x for x in oldref if x.get_prop_nr() != retrieved_pid] newref_minus_retrieved = [x for x in newref if x.get_prop_nr() != retrieved_pid] if not all(x in oldref_minus_retrieved for x in newref_minus_retrieved): return True oldref_retrieved = [x for x in oldref if x.get_prop_nr() == retrieved_pid] newref_retrieved = [x for x in newref if x.get_prop_nr() == retrieved_pid] if (len(newref_retrieved) != len(oldref_retrieved)) or not ( len(newref_retrieved) == len(oldref_retrieved) == 1): return True datefmt = '+%Y-%m-%dT%H:%M:%SZ' retold = list([datetime.strptime(r.get_value()[0], datefmt) for r in oldref if r.get_prop_nr() == retrieved_pid])[0] retnew = list([datetime.strptime(r.get_value()[0], datefmt) for r in newref if r.get_prop_nr() == retrieved_pid])[0] return (retnew - retold).days >= days newrefs = newitem.references oldrefs = olditem.references found_mate = [False] * len(newrefs) for new_n, newref in enumerate(newrefs): for old_n, oldref in enumerate(oldrefs): if is_equal_not_retrieved(oldref, newref): found_mate[new_n] = True if ref_overwrite(oldref, newref, days): oldrefs[old_n] = newref for f_idx, f in enumerate(found_mate): if not f: oldrefs.append(newrefs[f_idx])
45.416667
124
0.622018
#### # custom ref handler # If the newref is the same as the oldref except the retrieved date is `days` newer, overwrite # the retrieved date is NOT `days` newer, keep the old ref # If the refs are different (in any other way), overwrite with new ref # #### from datetime import datetime def update_retrieved_if_new_multiple_refs(olditem, newitem, days=180, retrieved_pid='P813'): """ # modifies olditem in place # any ref that does not exactly match the new proposed reference (not including retrieved) is kept """ def is_equal_not_retrieved(oldref, newref): """ Return True if the oldref == newref, NOT including any "retrieved" statements :param oldref: :param newref: :return: """ if len(oldref) != len(newref): return False oldref_minus_retrieved = [x for x in oldref if x.get_prop_nr() != retrieved_pid] newref_minus_retrieved = [x for x in newref if x.get_prop_nr() != retrieved_pid] if not all(x in oldref_minus_retrieved for x in newref_minus_retrieved): return False oldref_retrieved = [x for x in oldref if x.get_prop_nr() == retrieved_pid] newref_retrieved = [x for x in newref if x.get_prop_nr() == retrieved_pid] if (len(newref_retrieved) != len(oldref_retrieved)): return False return True def ref_overwrite(oldref, newref, days): """ If the newref is the same as the oldref except the retrieved date is `days` newer, return True the retrieved date is NOT `days` newer, return False the refs are different, return True """ if len(oldref) != len(newref): return True oldref_minus_retrieved = [x for x in oldref if x.get_prop_nr() != retrieved_pid] newref_minus_retrieved = [x for x in newref if x.get_prop_nr() != retrieved_pid] if not all(x in oldref_minus_retrieved for x in newref_minus_retrieved): return True oldref_retrieved = [x for x in oldref if x.get_prop_nr() == retrieved_pid] newref_retrieved = [x for x in newref if x.get_prop_nr() == retrieved_pid] if (len(newref_retrieved) != len(oldref_retrieved)) or not ( len(newref_retrieved) == len(oldref_retrieved) == 1): return True datefmt = '+%Y-%m-%dT%H:%M:%SZ' retold = list([datetime.strptime(r.get_value()[0], datefmt) for r in oldref if r.get_prop_nr() == retrieved_pid])[0] retnew = list([datetime.strptime(r.get_value()[0], datefmt) for r in newref if r.get_prop_nr() == retrieved_pid])[0] return (retnew - retold).days >= days newrefs = newitem.references oldrefs = olditem.references found_mate = [False] * len(newrefs) for new_n, newref in enumerate(newrefs): for old_n, oldref in enumerate(oldrefs): if is_equal_not_retrieved(oldref, newref): found_mate[new_n] = True if ref_overwrite(oldref, newref, days): oldrefs[old_n] = newref for f_idx, f in enumerate(found_mate): if not f: oldrefs.append(newrefs[f_idx])
0
0
0
b1ad856ad595461a20d1c8a1de08459807527696
14,130
py
Python
maad/util/wav2dBSPL.py
jflatorreg/scikit-maad
f7c4ac1370dcf416b7014f94784d71549623593f
[ "BSD-3-Clause" ]
3
2021-04-17T21:13:57.000Z
2021-04-25T00:55:18.000Z
maad/util/wav2dBSPL.py
jflatorreg/scikit-maad
f7c4ac1370dcf416b7014f94784d71549623593f
[ "BSD-3-Clause" ]
null
null
null
maad/util/wav2dBSPL.py
jflatorreg/scikit-maad
f7c4ac1370dcf416b7014f94784d71549623593f
[ "BSD-3-Clause" ]
null
null
null
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ SPL conversion functions for scikit-maad Collection of miscelaneous functions that help to convert wav and volt data to Sound Pressure Level (SPL in Pascal) and Leq (Continuous Equivalent SPL) """ # # Authors: Juan Sebastian ULLOA <lisofomia@gmail.com> # Sylvain HAUPERT <sylvain.haupert@mnhn.fr> # # License: New BSD License """**************************************************************************** # ------------------- Load modules --------------------------- ****************************************************************************""" # Import external modules import numpy as np from numpy import sum, log, log10, min, max, abs, mean, median, sqrt, diff """**************************************************************************** # ------------------- Functions --------------------------- ****************************************************************************""" ##### wav2volt def wav2volt (wave, bit=16, Vadc = sqrt(2)): """ convert in Volt Parameters ---------- wave : 1d ndarray of integers (directly from the wav file) Vector containing the raw sound waveform bit : int, optional, default is 16 Number of bits of the analog to digital converter (ADC) Vadc : scalar, optional, default is 1Vrms = 1*sqrt(2) Maximal voltage converted by the analog to digital convertor ADC Returns ------- volt : 1d ndarray of floats Vector containing the sound waveform in volt """ # be sure they are ndarray wave = np.asarray(wave) volt = (wave/(2**(bit-1))) * Vadc return volt ##### volt2SPL def volt2SPL(volt, gain, sensitivity=-35, dBref=94): """ convert volt amplitude to instantaneous sound pressure level SPL Parameters ---------- volt : 1d ndarray of integers floats Vector containing the sound waveform in volt gain : integer Total gain applied to the sound (preamplifer + amplifier) sensitivity : float, optional, default is -35 (dB/V) Sensitivity of the microphone dBref : integer, optional, default is 94 (dBSPL) Pressure sound level used for the calibration of the microphone (usually 94dB, sometimes 114dB) Returns ------- wave_SPL : 1d ndarray of floats Vector containing the sound waveform in SPL (Sound Pressure level : Pa) """ # be sure they are ndarray volt = np.asarray(volt) # wav to instantaneous sound pressure level (SPL) # coefficient to convert Volt into pressure (Pa) Volt2Pa = 1/10**(sensitivity/20) wave_SPL = volt * Volt2Pa / 10**(gain/20) return (wave_SPL) ##### wav2SPL def wav2SPL (wave, gain, bit=16, Vadc = sqrt(2), sensitivity=-35, dBref=94): """ convert wave to instantaneous sound pressure level SPL Parameters ---------- wave : 1d ndarray of integers (directly from the wav file) Vector containing the raw sound waveform gain : integer Total gain applied to the sound (preamplifer + amplifier) bit : int, optional, default is 16 Number of bits of the analog to digital converter (ADC) Vadc : scalar, optional, default is 1Vrms = 1*sqrt(2) Maximal voltage converted by the analog to digital convertor ADC sensitivity : float, optional, default is -35 (dB/V) Sensitivity of the microphone dBref : integer, optional, default is 94 (dBSPL) Pressure sound level used for the calibration of the microphone (usually 94dB, sometimes 114dB) ReturnsdBSP ------- wave_SPL : 1d ndarray of floats Vector containing the sound waveform in SPL (Sound Pressure level : Pa) """ wave_SPL = volt2SPL(wav2volt(wave, bit, Vadc), sensitivity, gain, dBref) return (wave_SPL) ##### SPL2dBSPL def SPL2dBSPL (waveSPL, pRef=20e-6): """ convert instantaneous sound pressure level SPL to instantaneous sound pressure level SPL in dB Parameters ---------- wave : 1d ndarray of integers or scalar Vector or scalar containing the SPL value (!! amplitude not energy !!) pRef : Sound pressure reference in the medium (air : 20e-6, water : ?) Returns ------- wave_dBSPL : 1d ndarray of floats Vector containing the sound waveform in dB SPL (Sound Pressure level in dB) """ wave_dBSPL = energy2dBSPL(waveSPL**2, pRef) return (wave_dBSPL) ##### wav2dBSPL def wav2dBSPL (wave, gain, Vadc = sqrt(2), bit=16, sensitivity=-35, dBref=94, pRef=20e-6): """ convert wave to instantaneous sound pressure level SPL in dB Parameters ---------- wave : 1d ndarray of integers (directly from the wav file) Vector containing the raw sound waveform gain : integer Total gain applied to the sound (preamplifer + amplifier) bit : int, optional, default is 16 Number of bits of the analog to digital converter (ADC) Vadc : scalar, optional, default is 1Vrms = 1*sqrt(2) Maximal voltage converted by the analog to digital convertor ADC sensitivity : float, optional, default is -35 (dB/V) Sensitivity of the microphone dBref : integer, optional, default is 94 (dBSPL) Pressure sound level used for the calibration of the microphone (usually 94dB, sometimes 114dB) pRef : Sound pressure reference in the medium (air : 20e-6, water : ?) Returns ------- wave_dBSPL : 1d ndarray of floats Vector containing the sound waveform in dB SPL (Sound Pressure level in dB) """ wave_SPL = wav2SPL(wave, bit, Vadc, sensitivity, gain, dBref) wave_dBSPL = energy2dBSPL(wave_SPL**2, pRef) return (wave_dBSPL) # wav2Leq def wav2Leq (wave, f, gain, Vadc=sqrt(2), bit=16, dt=1, sensitivity=-35, dBref = 94): """ convert wave to Equivalent Continuous Sound level (Leq) Parameters ---------- wave : 1d ndarray of integers (directly from the wav file) Vector containing the raw sound waveform f : integer Sampling frequency in Hz gain : integer Total gain applied to the sound (preamplifer + amplifier) Vadc : scalar, optional, default is 1Vrms = 1*sqrt(2) Maximal voltage converted by the analog to digital convertor ADC bit : int, optional, default is 16 Number of bits of the analog to digital converter (ADC) dt : float, optional, default is 1 (second) Integration step to compute the Leq (Equivalent Continuous Sound level) sensitivity : float, optional, default is -35 (dB/V) Sensitivity of the microphone dBref : integer, optional, default is 94 (dBSPL) Pressure sound level used for the calibration of the microphone (usually 94dB, sometimes 114dB) Returns ------- sig_Leq : float Equivalent Continuous Sound level (Leq) """ # convert in Volt volt = wav2volt(wave, bit, Vadc) ##### volt amplitude to Leq # wav to RMS dN = int(np.floor(dt*f)) # RMS period in number of points N_RMS = int(np.floor(len(volt)/dN)) # number of RMS periods # reduction of volt vector length volt_1D = volt[0:dN*N_RMS] # reshape into 2D (the duration of each row is dt) volt_2D = volt_1D.reshape(N_RMS,dN) # RMS volt_RMS = sqrt(mean(volt_2D**2,axis=1)) # RMS to Leq (Equivalent Continuous Sound level) sig_Leq = 20*log10(volt_RMS) - sensitivity + dBref - gain return(sig_Leq) ##### wavSPL2Leq def wavSPL2Leq (wave_SPL, f, dt=1, pRef = 20e-6): """ convert wave SPL to Equivalent Continuous Sound level (Leq) Parameters ---------- wave : 1d ndarray of floats Vector containing the sound waveform in SPL (Sound Pressure level : Pa) f : integer Sampling frequency in Hz bit : int, optional, default is 16 Number of bits of the analog to digital converter (ADC) dt : float, optional, default is 1 (second) Integration step to compute the Leq (Equivalent Continuous Sound level) pRef : Sound pressure reference in the medium (air : 20e-6, water : ?) Returns ------- sig_Leq : float Equivalent Continuous Sound level (Leq) """ # be sure they are ndarray wave_SPL = np.asarray(wave_SPL) ##### wav SPLto Leq # wav to RMS dN = int(np.floor(dt*f)) # RMS period in number of points N_RMS = int(np.floor(len(wave_SPL)/dN)) # number of RMS periods # reduction of volt vector length wave_SPL_1D = wave_SPL[0:dN*N_RMS] # reshape into 2D (the duration of each row is dt) wave_SPL_2D = wave_SPL_1D.reshape(N_RMS,dN) # RMS wave_SPL_RMS = sqrt(mean(wave_SPL_2D**2,axis=1))# Test the current operating system # RMS to Leq (Equivalent Continuous Sound level) sig_Leq = 20*log10(wave_SPL_RMS/pRef) return (sig_Leq) ##### energy2dBSPL def energy2dBSPL(energy_SPL, pRef = 20e-6): """ convert energy signal (e.g. Power spectral density (PSD) or wav²) already in SPL² into dB SPL Parameters ---------- energy_SPL : 1d ndarray of floats Vector containing the energy signal in SPL² pRef : Sound pressure reference in the medium (air : 20e-6, water : ?) Returns ------- PSD_dBSPL : 1d ndarray of floats Vector containing the energy signal in dB SPL """ # be sure they are ndarray energy_SPL = np.asarray(energy_SPL) # Take the log of the ratio ENERGY/pRef energy_dBSPL = 10*log10(energy_SPL/pRef**2) return (energy_dBSPL) ##### dBSPL2energy def dBSPL2energy (energy_dBSPL, pRef = 20e-6): """ convert energy in dB SPL (e.g. PSD) into energy in SPL² Parameters ---------- PSD_dBSPL : 1d ndarray of floats Vector containing the energy in dB SPL pRef : Sound pressure reference in the medium (air : 20e-6, water : ?) Returns ------- PSD_SPL : 1d ndarray of floats Vector containing the energy in SPL² """ # be sure they are ndarray energy_dBSPL = np.asarray(energy_dBSPL) # SPL to energy (pressure^2) (=> Leq (Equivalent Continuous Sound level) energy_SPL = 10**(energy_dBSPL/10)*pRef**2 return(energy_SPL) def PSD2Leq (PSD_SPL, pRef = 20e-6): """ convert Power spectral density (PSD) in SPL² into Equivalent Continuous Sound level (Leq) Parameters ---------- PSD_SPL : 1d ndarray of floats Vector containing the Power spectral density (PSD) already in SPL² pRef : Sound pressure reference in the medium (air : 20e-6, water : ?) Returns ------- PSD_Leq : float Equivalent Continuous Sound level (Leq) """ # be sure they are ndarray PSD_SPL = np.asarray(PSD_SPL) # Energy (pressure^2) to Leq (=> Leq (Equivalent Continuous Sound level) # if the sum is performed on the whole PSD) PSD_Leq = 10*log10(sum(PSD_SPL)/pRef**2) return(PSD_Leq) ########### TEST ## Test the current operating system if __name__ == "__main__": # ############## Import MAAD module from pathlib import Path # in order to be wind/linux/MacOS compatible import os # change the path to the current path where the script is located # Get the current dir of the current file dir_path = os.path.dirname(os.path.realpath('__file__')) os.chdir(dir_path) maad_path = Path(dir_path).parents[0] os.sys.path.append(maad_path.as_posix()) import maad # Sensbility microphone (for SM4 it is -35dBV) S = -35 #dBV # Amplification gain G = 42 # total amplification gain : preamplifier gain = 26dB and gain = 16dB # Reference pressure (in the air : 20µPa) P_REF = 20e-6 # Leq integration time dt in s deltaT = 1 # NFFT = 512 # bit = 16 # Vadc = sqrt(2) # root directory of the files base_path = Path(__file__).parent datadir = (base_path / "../../data/").resolve() filename = datadir/"jura_cold_forest_jour.wav" volt,fs = maad.sound.load(filename=filename, channel='right', detrend=False, verbose=False) # convert sounds (wave) into SPL and subtract DC offset volt = volt - mean(volt) # wav -> SPL -> Leq wav_SPL = volt2SPL(volt, sensitivity=S, gain=G, dBref=94) wav_Leq = wavSPL2Leq(wav_SPL, f=fs, dt=deltaT) print('Leq from volt', maad.util.linear2dB(mean(maad.util.dB2linear(wav_Leq, mode="power")),mode="power")) # wav -> Leq wav = volt*2**(bit-1)/Vadc wav_Leq2 = wav2Leq(wav, f=fs, dt=deltaT, sensitivity=S, gain=G, dBref = 94) print('Leq from wav', maad.util.linear2dB(mean(maad.util.dB2linear(wav_Leq2, mode="power")),mode="power")) # Power Density Spetrum : PSDxx from numpy import fft PSD = abs(fft.fft(wav_SPL)/len(wav_SPL))**2 # average Leq from PSD PSD_Leq3 = PSD2Leq(PSD) print('Leq from PSD',PSD_Leq3 ) # Power Density Spetrum : PSDxx PSDxx,tn,fn,_ = maad.sound.spectrogramPSD (wav_SPL, fs=fs, window='boxcar', noverlap=0, nfft=NFFT, fcrop=None, tcrop=None, verbose=False, display=False, savefig = None) PSD_mean = mean(PSDxx,axis=1) # average Leq from PSD PSD_Leq4 = PSD2Leq(PSD_mean) print('Leq from PSDxx spectrogram',PSD_Leq4 ) print('The difference with previous Leq is due to the average of the PSDxx along the time axis which reduces the noise contribution into the total energy ')
33.169014
160
0.601628
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ SPL conversion functions for scikit-maad Collection of miscelaneous functions that help to convert wav and volt data to Sound Pressure Level (SPL in Pascal) and Leq (Continuous Equivalent SPL) """ # # Authors: Juan Sebastian ULLOA <lisofomia@gmail.com> # Sylvain HAUPERT <sylvain.haupert@mnhn.fr> # # License: New BSD License """**************************************************************************** # ------------------- Load modules --------------------------- ****************************************************************************""" # Import external modules import numpy as np from numpy import sum, log, log10, min, max, abs, mean, median, sqrt, diff """**************************************************************************** # ------------------- Functions --------------------------- ****************************************************************************""" ##### wav2volt def wav2volt (wave, bit=16, Vadc = sqrt(2)): """ convert in Volt Parameters ---------- wave : 1d ndarray of integers (directly from the wav file) Vector containing the raw sound waveform bit : int, optional, default is 16 Number of bits of the analog to digital converter (ADC) Vadc : scalar, optional, default is 1Vrms = 1*sqrt(2) Maximal voltage converted by the analog to digital convertor ADC Returns ------- volt : 1d ndarray of floats Vector containing the sound waveform in volt """ # be sure they are ndarray wave = np.asarray(wave) volt = (wave/(2**(bit-1))) * Vadc return volt ##### volt2SPL def volt2SPL(volt, gain, sensitivity=-35, dBref=94): """ convert volt amplitude to instantaneous sound pressure level SPL Parameters ---------- volt : 1d ndarray of integers floats Vector containing the sound waveform in volt gain : integer Total gain applied to the sound (preamplifer + amplifier) sensitivity : float, optional, default is -35 (dB/V) Sensitivity of the microphone dBref : integer, optional, default is 94 (dBSPL) Pressure sound level used for the calibration of the microphone (usually 94dB, sometimes 114dB) Returns ------- wave_SPL : 1d ndarray of floats Vector containing the sound waveform in SPL (Sound Pressure level : Pa) """ # be sure they are ndarray volt = np.asarray(volt) # wav to instantaneous sound pressure level (SPL) # coefficient to convert Volt into pressure (Pa) Volt2Pa = 1/10**(sensitivity/20) wave_SPL = volt * Volt2Pa / 10**(gain/20) return (wave_SPL) ##### wav2SPL def wav2SPL (wave, gain, bit=16, Vadc = sqrt(2), sensitivity=-35, dBref=94): """ convert wave to instantaneous sound pressure level SPL Parameters ---------- wave : 1d ndarray of integers (directly from the wav file) Vector containing the raw sound waveform gain : integer Total gain applied to the sound (preamplifer + amplifier) bit : int, optional, default is 16 Number of bits of the analog to digital converter (ADC) Vadc : scalar, optional, default is 1Vrms = 1*sqrt(2) Maximal voltage converted by the analog to digital convertor ADC sensitivity : float, optional, default is -35 (dB/V) Sensitivity of the microphone dBref : integer, optional, default is 94 (dBSPL) Pressure sound level used for the calibration of the microphone (usually 94dB, sometimes 114dB) ReturnsdBSP ------- wave_SPL : 1d ndarray of floats Vector containing the sound waveform in SPL (Sound Pressure level : Pa) """ wave_SPL = volt2SPL(wav2volt(wave, bit, Vadc), sensitivity, gain, dBref) return (wave_SPL) ##### SPL2dBSPL def SPL2dBSPL (waveSPL, pRef=20e-6): """ convert instantaneous sound pressure level SPL to instantaneous sound pressure level SPL in dB Parameters ---------- wave : 1d ndarray of integers or scalar Vector or scalar containing the SPL value (!! amplitude not energy !!) pRef : Sound pressure reference in the medium (air : 20e-6, water : ?) Returns ------- wave_dBSPL : 1d ndarray of floats Vector containing the sound waveform in dB SPL (Sound Pressure level in dB) """ wave_dBSPL = energy2dBSPL(waveSPL**2, pRef) return (wave_dBSPL) ##### wav2dBSPL def wav2dBSPL (wave, gain, Vadc = sqrt(2), bit=16, sensitivity=-35, dBref=94, pRef=20e-6): """ convert wave to instantaneous sound pressure level SPL in dB Parameters ---------- wave : 1d ndarray of integers (directly from the wav file) Vector containing the raw sound waveform gain : integer Total gain applied to the sound (preamplifer + amplifier) bit : int, optional, default is 16 Number of bits of the analog to digital converter (ADC) Vadc : scalar, optional, default is 1Vrms = 1*sqrt(2) Maximal voltage converted by the analog to digital convertor ADC sensitivity : float, optional, default is -35 (dB/V) Sensitivity of the microphone dBref : integer, optional, default is 94 (dBSPL) Pressure sound level used for the calibration of the microphone (usually 94dB, sometimes 114dB) pRef : Sound pressure reference in the medium (air : 20e-6, water : ?) Returns ------- wave_dBSPL : 1d ndarray of floats Vector containing the sound waveform in dB SPL (Sound Pressure level in dB) """ wave_SPL = wav2SPL(wave, bit, Vadc, sensitivity, gain, dBref) wave_dBSPL = energy2dBSPL(wave_SPL**2, pRef) return (wave_dBSPL) # wav2Leq def wav2Leq (wave, f, gain, Vadc=sqrt(2), bit=16, dt=1, sensitivity=-35, dBref = 94): """ convert wave to Equivalent Continuous Sound level (Leq) Parameters ---------- wave : 1d ndarray of integers (directly from the wav file) Vector containing the raw sound waveform f : integer Sampling frequency in Hz gain : integer Total gain applied to the sound (preamplifer + amplifier) Vadc : scalar, optional, default is 1Vrms = 1*sqrt(2) Maximal voltage converted by the analog to digital convertor ADC bit : int, optional, default is 16 Number of bits of the analog to digital converter (ADC) dt : float, optional, default is 1 (second) Integration step to compute the Leq (Equivalent Continuous Sound level) sensitivity : float, optional, default is -35 (dB/V) Sensitivity of the microphone dBref : integer, optional, default is 94 (dBSPL) Pressure sound level used for the calibration of the microphone (usually 94dB, sometimes 114dB) Returns ------- sig_Leq : float Equivalent Continuous Sound level (Leq) """ # convert in Volt volt = wav2volt(wave, bit, Vadc) ##### volt amplitude to Leq # wav to RMS dN = int(np.floor(dt*f)) # RMS period in number of points N_RMS = int(np.floor(len(volt)/dN)) # number of RMS periods # reduction of volt vector length volt_1D = volt[0:dN*N_RMS] # reshape into 2D (the duration of each row is dt) volt_2D = volt_1D.reshape(N_RMS,dN) # RMS volt_RMS = sqrt(mean(volt_2D**2,axis=1)) # RMS to Leq (Equivalent Continuous Sound level) sig_Leq = 20*log10(volt_RMS) - sensitivity + dBref - gain return(sig_Leq) ##### wavSPL2Leq def wavSPL2Leq (wave_SPL, f, dt=1, pRef = 20e-6): """ convert wave SPL to Equivalent Continuous Sound level (Leq) Parameters ---------- wave : 1d ndarray of floats Vector containing the sound waveform in SPL (Sound Pressure level : Pa) f : integer Sampling frequency in Hz bit : int, optional, default is 16 Number of bits of the analog to digital converter (ADC) dt : float, optional, default is 1 (second) Integration step to compute the Leq (Equivalent Continuous Sound level) pRef : Sound pressure reference in the medium (air : 20e-6, water : ?) Returns ------- sig_Leq : float Equivalent Continuous Sound level (Leq) """ # be sure they are ndarray wave_SPL = np.asarray(wave_SPL) ##### wav SPLto Leq # wav to RMS dN = int(np.floor(dt*f)) # RMS period in number of points N_RMS = int(np.floor(len(wave_SPL)/dN)) # number of RMS periods # reduction of volt vector length wave_SPL_1D = wave_SPL[0:dN*N_RMS] # reshape into 2D (the duration of each row is dt) wave_SPL_2D = wave_SPL_1D.reshape(N_RMS,dN) # RMS wave_SPL_RMS = sqrt(mean(wave_SPL_2D**2,axis=1))# Test the current operating system # RMS to Leq (Equivalent Continuous Sound level) sig_Leq = 20*log10(wave_SPL_RMS/pRef) return (sig_Leq) ##### energy2dBSPL def energy2dBSPL(energy_SPL, pRef = 20e-6): """ convert energy signal (e.g. Power spectral density (PSD) or wav²) already in SPL² into dB SPL Parameters ---------- energy_SPL : 1d ndarray of floats Vector containing the energy signal in SPL² pRef : Sound pressure reference in the medium (air : 20e-6, water : ?) Returns ------- PSD_dBSPL : 1d ndarray of floats Vector containing the energy signal in dB SPL """ # be sure they are ndarray energy_SPL = np.asarray(energy_SPL) # Take the log of the ratio ENERGY/pRef energy_dBSPL = 10*log10(energy_SPL/pRef**2) return (energy_dBSPL) ##### dBSPL2energy def dBSPL2energy (energy_dBSPL, pRef = 20e-6): """ convert energy in dB SPL (e.g. PSD) into energy in SPL² Parameters ---------- PSD_dBSPL : 1d ndarray of floats Vector containing the energy in dB SPL pRef : Sound pressure reference in the medium (air : 20e-6, water : ?) Returns ------- PSD_SPL : 1d ndarray of floats Vector containing the energy in SPL² """ # be sure they are ndarray energy_dBSPL = np.asarray(energy_dBSPL) # SPL to energy (pressure^2) (=> Leq (Equivalent Continuous Sound level) energy_SPL = 10**(energy_dBSPL/10)*pRef**2 return(energy_SPL) def PSD2Leq (PSD_SPL, pRef = 20e-6): """ convert Power spectral density (PSD) in SPL² into Equivalent Continuous Sound level (Leq) Parameters ---------- PSD_SPL : 1d ndarray of floats Vector containing the Power spectral density (PSD) already in SPL² pRef : Sound pressure reference in the medium (air : 20e-6, water : ?) Returns ------- PSD_Leq : float Equivalent Continuous Sound level (Leq) """ # be sure they are ndarray PSD_SPL = np.asarray(PSD_SPL) # Energy (pressure^2) to Leq (=> Leq (Equivalent Continuous Sound level) # if the sum is performed on the whole PSD) PSD_Leq = 10*log10(sum(PSD_SPL)/pRef**2) return(PSD_Leq) ########### TEST ## Test the current operating system if __name__ == "__main__": # ############## Import MAAD module from pathlib import Path # in order to be wind/linux/MacOS compatible import os # change the path to the current path where the script is located # Get the current dir of the current file dir_path = os.path.dirname(os.path.realpath('__file__')) os.chdir(dir_path) maad_path = Path(dir_path).parents[0] os.sys.path.append(maad_path.as_posix()) import maad # Sensbility microphone (for SM4 it is -35dBV) S = -35 #dBV # Amplification gain G = 42 # total amplification gain : preamplifier gain = 26dB and gain = 16dB # Reference pressure (in the air : 20µPa) P_REF = 20e-6 # Leq integration time dt in s deltaT = 1 # NFFT = 512 # bit = 16 # Vadc = sqrt(2) # root directory of the files base_path = Path(__file__).parent datadir = (base_path / "../../data/").resolve() filename = datadir/"jura_cold_forest_jour.wav" volt,fs = maad.sound.load(filename=filename, channel='right', detrend=False, verbose=False) # convert sounds (wave) into SPL and subtract DC offset volt = volt - mean(volt) # wav -> SPL -> Leq wav_SPL = volt2SPL(volt, sensitivity=S, gain=G, dBref=94) wav_Leq = wavSPL2Leq(wav_SPL, f=fs, dt=deltaT) print('Leq from volt', maad.util.linear2dB(mean(maad.util.dB2linear(wav_Leq, mode="power")),mode="power")) # wav -> Leq wav = volt*2**(bit-1)/Vadc wav_Leq2 = wav2Leq(wav, f=fs, dt=deltaT, sensitivity=S, gain=G, dBref = 94) print('Leq from wav', maad.util.linear2dB(mean(maad.util.dB2linear(wav_Leq2, mode="power")),mode="power")) # Power Density Spetrum : PSDxx from numpy import fft PSD = abs(fft.fft(wav_SPL)/len(wav_SPL))**2 # average Leq from PSD PSD_Leq3 = PSD2Leq(PSD) print('Leq from PSD',PSD_Leq3 ) # Power Density Spetrum : PSDxx PSDxx,tn,fn,_ = maad.sound.spectrogramPSD (wav_SPL, fs=fs, window='boxcar', noverlap=0, nfft=NFFT, fcrop=None, tcrop=None, verbose=False, display=False, savefig = None) PSD_mean = mean(PSDxx,axis=1) # average Leq from PSD PSD_Leq4 = PSD2Leq(PSD_mean) print('Leq from PSDxx spectrogram',PSD_Leq4 ) print('The difference with previous Leq is due to the average of the PSDxx along the time axis which reduces the noise contribution into the total energy ')
0
0
0
f63afc086bb45acbfb6e4ac6ff5932c650741902
313
py
Python
test/unit/api/test_total_time.py
redmic-project/device-oag-buoy-modem
e905c53a5705695670512ff8f72bcc44c44421b1
[ "MIT" ]
2
2019-07-02T14:34:52.000Z
2021-04-15T12:48:20.000Z
test/unit/api/test_total_time.py
alzeih/python-vodem-vodafone-K4607-Z
d3b1f35d510b71b79ba9203993b5228006d9d8ee
[ "MIT" ]
null
null
null
test/unit/api/test_total_time.py
alzeih/python-vodem-vodafone-K4607-Z
d3b1f35d510b71b79ba9203993b5228006d9d8ee
[ "MIT" ]
null
null
null
import unittest from vodem.api import total_time
18.411765
51
0.632588
import unittest from vodem.api import total_time class TestTotalTime(unittest.TestCase): @classmethod def setUpClass(cls): cls.valid_response = { 'total_time': '0', } def test_call(self): resp = total_time() self.assertEqual(self.valid_response, resp)
150
89
23
146af929aa57220a406988b72ce3550451e498fb
2,924
py
Python
pyobiee/classes.py
hgokduman/pyobiee
f673f8d0474c7f151e2d74daa576ccf07933500f
[ "MIT-0" ]
1
2019-09-09T12:51:40.000Z
2019-09-09T12:51:40.000Z
pyobiee/classes.py
hgokduman/pyobiee
f673f8d0474c7f151e2d74daa576ccf07933500f
[ "MIT-0" ]
null
null
null
pyobiee/classes.py
hgokduman/pyobiee
f673f8d0474c7f151e2d74daa576ccf07933500f
[ "MIT-0" ]
null
null
null
from zeep import Client, Settings from zeep.transports import Transport from requests import Session
38.986667
142
0.683311
from zeep import Client, Settings from zeep.transports import Transport from requests import Session class SAWSessionService(): def __init__(self, wsdl): session = Session() transport = Transport(session=session) settings = Settings(xml_huge_tree=True) self.client = Client(wsdl=wsdl, transport=transport, settings=settings) self.service = self.client.service def logon(self, username, password): session_id = self.service.logon(name=username, password=password) return session_id def logoff(self, session_id): self.service.logoff(session_id) def get_current_user(self, session_id): return self.service.getCurUser(session_id) def get_session_environment(self, session_id): return self.service.getSessionEnvironment(session_id) def get_session_variable(self, names, session_id): return self.service.getSessionVariable(names, session_id) def impersonate(self, name, password, impersonate_id): session_id = self.service.getSessionVariable(name, password, impersonate_id) return session_id def keep_alive(self, session_id): self.service.keepAlive(session_id) def bind(self, service_name, port_name=None): return self.client.bind(service_name, port_name) class XMLViewService(): def __init__(self, session_service, session_id): self.service = session_service.client.bind('XmlViewService') self.session_id = session_id self.execution_options = {"async" : True, "maxRowsPerPage" : 10000, "refresh" : True, "presentationInfo" : True} def execute_sql_query(self, sql, output_format): query_results = self.service.executeSQLQuery(sql=sql, outputFormat=output_format, executionOptions=self.execution_options, sessionID=self.session_id) return query_results def execute_xml_query(self, report_ref, output_format): query_results = self.service.executeXMLQuery(report=report_ref, outputFormat=output_format, executionOptions=self.execution_options, sessionID=self.session_id) return query_results def fetch_next(self, query_id): query_results = self.service.fetchNext(queryID=query_id, sessionID=self.session_id) return query_results def cancel_query(self, query_id, session_id): self.service.cancelQuery(query_id, session_id) def get_prompted_filters(self, report_ref, session_id): return self.service.getPromptedFilters(report_ref, session_id) def get_available_services(wsdl): client = Client(wsdl=wsdl) service_names = [] for service in client.wsdl.services.values(): service_names.append(service.name) return service_names
2,283
7
524
87a9aef30724ffb204884ea7b3f846805e2a937f
27,197
py
Python
pysnmp-with-texts/UMSAOL-MIB.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
8
2019-05-09T17:04:00.000Z
2021-06-09T06:50:51.000Z
pysnmp-with-texts/UMSAOL-MIB.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
4
2019-05-31T16:42:59.000Z
2020-01-31T21:57:17.000Z
pysnmp-with-texts/UMSAOL-MIB.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
10
2019-04-30T05:51:36.000Z
2022-02-16T03:33:41.000Z
# # PySNMP MIB module UMSAOL-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/UMSAOL-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:28:38 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueSizeConstraint, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueSizeConstraint", "ValueRangeConstraint") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") ModuleIdentity, TimeTicks, MibIdentifier, Unsigned32, Counter32, IpAddress, Gauge32, NotificationType, Integer32, Counter64, MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType, Bits, iso, ObjectIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "ModuleIdentity", "TimeTicks", "MibIdentifier", "Unsigned32", "Counter32", "IpAddress", "Gauge32", "NotificationType", "Integer32", "Counter64", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType", "Bits", "iso", "ObjectIdentity") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") Real64, Sint32, Sint8, String, Uint32, ibmpsgAlertOnLAN, Uint64, Datetime, Real32, Sint64, Sint16, Boolean, Uint16, Uint8 = mibBuilder.importSymbols("UMS-MIB", "Real64", "Sint32", "Sint8", "String", "Uint32", "ibmpsgAlertOnLAN", "Uint64", "Datetime", "Real32", "Sint64", "Sint16", "Boolean", "Uint16", "Uint8") iBMPSGWatchdogTable = MibTable((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 1), ) if mibBuilder.loadTexts: iBMPSGWatchdogTable.setReference('IBMPSG_Watchdog') if mibBuilder.loadTexts: iBMPSGWatchdogTable.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGWatchdogTable.setDescription('') iBMPSGWatchdogEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 1, 1), ).setIndexNames((0, "UMSAOL-MIB", "iBMPSGWatchdogKeyIndex")) if mibBuilder.loadTexts: iBMPSGWatchdogEntry.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGWatchdogEntry.setDescription('') iBMPSGWatchdogKeyIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 1, 1, 1), String()).setMaxAccess("readonly") if mibBuilder.loadTexts: iBMPSGWatchdogKeyIndex.setReference('IBMPSG_Watchdog.KeyIndex') if mibBuilder.loadTexts: iBMPSGWatchdogKeyIndex.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGWatchdogKeyIndex.setDescription('') iBMPSGWatchdogMonitoredDeviceId = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 1, 1, 2), String()).setMaxAccess("readonly") if mibBuilder.loadTexts: iBMPSGWatchdogMonitoredDeviceId.setReference('IBMPSG_Watchdog.DeviceId') if mibBuilder.loadTexts: iBMPSGWatchdogMonitoredDeviceId.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGWatchdogMonitoredDeviceId.setDescription('') iBMPSGWatchdogMonitoredEntity = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 1, 1, 3), Uint16()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGWatchdogMonitoredEntity.setReference('IBMPSG_Watchdog.MonitoredEntity') if mibBuilder.loadTexts: iBMPSGWatchdogMonitoredEntity.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGWatchdogMonitoredEntity.setDescription('') iBMPSGWatchdogMonitoredEntityDescription = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 1, 1, 4), String()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGWatchdogMonitoredEntityDescription.setReference('IBMPSG_Watchdog.MonitoredEntityDescription') if mibBuilder.loadTexts: iBMPSGWatchdogMonitoredEntityDescription.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGWatchdogMonitoredEntityDescription.setDescription('') iBMPSGWatchdogTimeoutInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 1, 1, 5), Uint32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGWatchdogTimeoutInterval.setReference('IBMPSG_Watchdog.TimeoutInterval') if mibBuilder.loadTexts: iBMPSGWatchdogTimeoutInterval.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGWatchdogTimeoutInterval.setDescription('') iBMPSGWatchdogTimerResolution = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 1, 1, 6), Uint32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGWatchdogTimerResolution.setReference('IBMPSG_Watchdog.TimerResolution') if mibBuilder.loadTexts: iBMPSGWatchdogTimerResolution.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGWatchdogTimerResolution.setDescription('') iBMPSGWatchdogTimeOfLastExpiration = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 1, 1, 7), Datetime()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGWatchdogTimeOfLastExpiration.setReference('IBMPSG_Watchdog.TimeOfLastExpiration') if mibBuilder.loadTexts: iBMPSGWatchdogTimeOfLastExpiration.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGWatchdogTimeOfLastExpiration.setDescription('') iBMPSGWatchdogMonitoredEntityOnLastExpiration = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 1, 1, 8), Uint16()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGWatchdogMonitoredEntityOnLastExpiration.setReference('IBMPSG_Watchdog.MonitoredEntityOnLastExpiration') if mibBuilder.loadTexts: iBMPSGWatchdogMonitoredEntityOnLastExpiration.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGWatchdogMonitoredEntityOnLastExpiration.setDescription('') iBMPSGWatchdogActionOnExpiration = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 1, 1, 9), Uint16()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGWatchdogActionOnExpiration.setReference('IBMPSG_Watchdog.ActionOnExpiration') if mibBuilder.loadTexts: iBMPSGWatchdogActionOnExpiration.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGWatchdogActionOnExpiration.setDescription('') iBMPSGWatchdogMaximumTimeoutInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 1, 1, 10), Uint32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGWatchdogMaximumTimeoutInterval.setReference('IBMPSG_Watchdog.MaximumTimeoutInterval') if mibBuilder.loadTexts: iBMPSGWatchdogMaximumTimeoutInterval.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGWatchdogMaximumTimeoutInterval.setDescription('') iBMPSGWatchdogMinimumTimeoutInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 1, 1, 11), Uint32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGWatchdogMinimumTimeoutInterval.setReference('IBMPSG_Watchdog.MinimumTimeoutInterval') if mibBuilder.loadTexts: iBMPSGWatchdogMinimumTimeoutInterval.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGWatchdogMinimumTimeoutInterval.setDescription('') iBMPSGWatchdogEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 1, 1, 12), Boolean()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGWatchdogEnabled.setReference('IBMPSG_Watchdog.Enabled') if mibBuilder.loadTexts: iBMPSGWatchdogEnabled.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGWatchdogEnabled.setDescription('') iBMPSGWatchdogStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 1, 1, 13), String()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGWatchdogStatus.setReference('IBMPSG_Watchdog.Status') if mibBuilder.loadTexts: iBMPSGWatchdogStatus.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGWatchdogStatus.setDescription('The Status property is a string indicating the current status of the object. Various operational and non-operational statuses can be defined. Operational statuses are OK, Degraded and Pred Fail. Pred Fail indicates that an element may be functioning properly but predicting a failure in the near future. An example is a SMART-enabled hard drive. Non-operational statuses can also be specified. These are Error, Starting, Stopping and Service. The latter, Service, could apply during mirror-resilvering of a disk, reload of a user permissions list, or other administrative work. Not all such work is on-line, yet the managed element is neither OK nor in one of the other states.') iBMPSGAlertOnLANTable = MibTable((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 2), ) if mibBuilder.loadTexts: iBMPSGAlertOnLANTable.setReference('IBMPSG_AlertOnLAN') if mibBuilder.loadTexts: iBMPSGAlertOnLANTable.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAlertOnLANTable.setDescription('') iBMPSGAlertOnLANEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 2, 1), ).setIndexNames((0, "UMSAOL-MIB", "iBMPSGAlertOnLANKeyIndex")) if mibBuilder.loadTexts: iBMPSGAlertOnLANEntry.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAlertOnLANEntry.setDescription('') iBMPSGAlertOnLANKeyIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 2, 1, 1), String()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAlertOnLANKeyIndex.setReference('IBMPSG_AlertOnLAN.KeyIndex') if mibBuilder.loadTexts: iBMPSGAlertOnLANKeyIndex.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAlertOnLANKeyIndex.setDescription('') iBMPSGAlertOnLANDestinationType = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 2, 1, 2), Uint16()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAlertOnLANDestinationType.setReference('IBMPSG_AlertOnLAN.DestinationType') if mibBuilder.loadTexts: iBMPSGAlertOnLANDestinationType.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAlertOnLANDestinationType.setDescription('') iBMPSGAlertOnLANOtherDestinationTypeDescription = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 2, 1, 3), String()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAlertOnLANOtherDestinationTypeDescription.setReference('IBMPSG_AlertOnLAN.OtherDestinationTypeDescription') if mibBuilder.loadTexts: iBMPSGAlertOnLANOtherDestinationTypeDescription.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAlertOnLANOtherDestinationTypeDescription.setDescription('') iBMPSGAlertOnLANAlertDestinationAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 2, 1, 4), String()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAlertOnLANAlertDestinationAddress.setReference('IBMPSG_AlertOnLAN.AlertDestinationAddress') if mibBuilder.loadTexts: iBMPSGAlertOnLANAlertDestinationAddress.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAlertOnLANAlertDestinationAddress.setDescription('') iBMPSGAlertOnLANMessageFormat = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 2, 1, 5), Uint16()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAlertOnLANMessageFormat.setReference('IBMPSG_AlertOnLAN.MessageFormat') if mibBuilder.loadTexts: iBMPSGAlertOnLANMessageFormat.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAlertOnLANMessageFormat.setDescription('') iBMPSGAlertOnLANOtherMessageFormatDescription = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 2, 1, 6), String()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAlertOnLANOtherMessageFormatDescription.setReference('IBMPSG_AlertOnLAN.OtherMessageFormatDescription') if mibBuilder.loadTexts: iBMPSGAlertOnLANOtherMessageFormatDescription.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAlertOnLANOtherMessageFormatDescription.setDescription('') iBMPSGAlertOnLANOnlySendsFixedMessage = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 2, 1, 7), Boolean()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAlertOnLANOnlySendsFixedMessage.setReference('IBMPSG_AlertOnLAN.OnlySendsFixedMessage') if mibBuilder.loadTexts: iBMPSGAlertOnLANOnlySendsFixedMessage.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAlertOnLANOnlySendsFixedMessage.setDescription('') iBMPSGAlertOnLANFixedPartOfMessage = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 2, 1, 8), String()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAlertOnLANFixedPartOfMessage.setReference('IBMPSG_AlertOnLAN.FixedPartOfMessage') if mibBuilder.loadTexts: iBMPSGAlertOnLANFixedPartOfMessage.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAlertOnLANFixedPartOfMessage.setDescription('') iBMPSGAlertOnLANDestinationIsAckCapable = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 2, 1, 9), Boolean()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAlertOnLANDestinationIsAckCapable.setReference('IBMPSG_AlertOnLAN.DestinationIsAckCapable') if mibBuilder.loadTexts: iBMPSGAlertOnLANDestinationIsAckCapable.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAlertOnLANDestinationIsAckCapable.setDescription('') iBMPSGAlertOnLANRetryCount = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 2, 1, 10), Uint16()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAlertOnLANRetryCount.setReference('IBMPSG_AlertOnLAN.RetryCount') if mibBuilder.loadTexts: iBMPSGAlertOnLANRetryCount.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAlertOnLANRetryCount.setDescription('') iBMPSGAlertOnLANEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 2, 1, 11), Boolean()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAlertOnLANEnabled.setReference('IBMPSG_AlertOnLAN.Enabled') if mibBuilder.loadTexts: iBMPSGAlertOnLANEnabled.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAlertOnLANEnabled.setDescription('') iBMPSGAlertOnLANVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 2, 1, 12), String()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAlertOnLANVersion.setReference('IBMPSG_AlertOnLAN.Version') if mibBuilder.loadTexts: iBMPSGAlertOnLANVersion.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAlertOnLANVersion.setDescription('Hardware version.') iBMPSGAlertOnLANEventAutoClearEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 2, 1, 13), Boolean()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAlertOnLANEventAutoClearEnabled.setReference('IBMPSG_AlertOnLAN.EventAutoClearEnabled') if mibBuilder.loadTexts: iBMPSGAlertOnLANEventAutoClearEnabled.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAlertOnLANEventAutoClearEnabled.setDescription('') iBMPSGAlertOnLANMaximumEventPollInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 2, 1, 14), Uint32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAlertOnLANMaximumEventPollInterval.setReference('IBMPSG_AlertOnLAN.MaximumEventPollInterval') if mibBuilder.loadTexts: iBMPSGAlertOnLANMaximumEventPollInterval.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAlertOnLANMaximumEventPollInterval.setDescription('') iBMPSGAlertOnLANMinimumEventPollInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 2, 1, 15), Uint32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAlertOnLANMinimumEventPollInterval.setReference('IBMPSG_AlertOnLAN.MinimumEventPollInterval') if mibBuilder.loadTexts: iBMPSGAlertOnLANMinimumEventPollInterval.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAlertOnLANMinimumEventPollInterval.setDescription('') iBMPSGAlertOnLANEventPollInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 2, 1, 16), Uint32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAlertOnLANEventPollInterval.setReference('IBMPSG_AlertOnLAN.EventPollInterval') if mibBuilder.loadTexts: iBMPSGAlertOnLANEventPollInterval.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAlertOnLANEventPollInterval.setDescription('') iBMPSGAlertOnLANHeartbeatEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 2, 1, 17), Boolean()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAlertOnLANHeartbeatEnabled.setReference('IBMPSG_AlertOnLAN.HeartbeatEnabled') if mibBuilder.loadTexts: iBMPSGAlertOnLANHeartbeatEnabled.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAlertOnLANHeartbeatEnabled.setDescription('') iBMPSGAlertOnLANMaximumHeartbeatInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 2, 1, 18), Uint32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAlertOnLANMaximumHeartbeatInterval.setReference('IBMPSG_AlertOnLAN.MaximumHeartbeatInterval') if mibBuilder.loadTexts: iBMPSGAlertOnLANMaximumHeartbeatInterval.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAlertOnLANMaximumHeartbeatInterval.setDescription('') iBMPSGAlertOnLANMinimumHeartbeatInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 2, 1, 19), Uint32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAlertOnLANMinimumHeartbeatInterval.setReference('IBMPSG_AlertOnLAN.MinimumHeartbeatInterval') if mibBuilder.loadTexts: iBMPSGAlertOnLANMinimumHeartbeatInterval.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAlertOnLANMinimumHeartbeatInterval.setDescription('') iBMPSGAlertOnLANHeartbeatInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 2, 1, 20), Uint32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAlertOnLANHeartbeatInterval.setReference('IBMPSG_AlertOnLAN.HeartbeatInterval') if mibBuilder.loadTexts: iBMPSGAlertOnLANHeartbeatInterval.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAlertOnLANHeartbeatInterval.setDescription('') iBMPSGAlertOnLANStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 2, 1, 21), String()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAlertOnLANStatus.setReference('IBMPSG_AlertOnLAN.Status') if mibBuilder.loadTexts: iBMPSGAlertOnLANStatus.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAlertOnLANStatus.setDescription('The Status property is a string indicating the current status of the object. Various operational and non-operational statuses can be defined. Operational statuses are OK, Degraded and Pred Fail. Pred Fail indicates that an element may be functioning properly but predicting a failure in the near future. An example is a SMART-enabled hard drive. Non-operational statuses can also be specified. These are Error, Starting, Stopping and Service. The latter, Service, could apply during mirror-resilvering of a disk, reload of a user permissions list, or other administrative work. Not all such work is on-line, yet the managed element is neither OK nor in one of the other states.') iBMPSGAOLEventConfigurationTable = MibTable((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 3), ) if mibBuilder.loadTexts: iBMPSGAOLEventConfigurationTable.setReference('IBMPSG_AOLEventConfiguration') if mibBuilder.loadTexts: iBMPSGAOLEventConfigurationTable.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAOLEventConfigurationTable.setDescription('') iBMPSGAOLEventConfigurationEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 3, 1), ).setIndexNames((0, "UMSAOL-MIB", "iBMPSGAOLEventConfigurationKeyIndex")) if mibBuilder.loadTexts: iBMPSGAOLEventConfigurationEntry.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAOLEventConfigurationEntry.setDescription('') iBMPSGAOLEventConfigurationKeyIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 3, 1, 1), String()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAOLEventConfigurationKeyIndex.setReference('IBMPSG_AOLEventConfiguration.KeyIndex') if mibBuilder.loadTexts: iBMPSGAOLEventConfigurationKeyIndex.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAOLEventConfigurationKeyIndex.setDescription('') iBMPSGAOLEventConfigurationName = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 3, 1, 2), String()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAOLEventConfigurationName.setReference('IBMPSG_AOLEventConfiguration.Name') if mibBuilder.loadTexts: iBMPSGAOLEventConfigurationName.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAOLEventConfigurationName.setDescription('') iBMPSGAOLEventConfigurationIdentifier = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 3, 1, 3), Uint32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAOLEventConfigurationIdentifier.setReference('IBMPSG_AOLEventConfiguration.Identifier') if mibBuilder.loadTexts: iBMPSGAOLEventConfigurationIdentifier.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAOLEventConfigurationIdentifier.setDescription('') iBMPSGAOLEventConfigurationEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 3, 1, 4), Boolean()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAOLEventConfigurationEnabled.setReference('IBMPSG_AOLEventConfiguration.Enabled') if mibBuilder.loadTexts: iBMPSGAOLEventConfigurationEnabled.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAOLEventConfigurationEnabled.setDescription('') iBMPSGAOLEventConfigurationActivated = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 3, 1, 5), Boolean()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAOLEventConfigurationActivated.setReference('IBMPSG_AOLEventConfiguration.Activated') if mibBuilder.loadTexts: iBMPSGAOLEventConfigurationActivated.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAOLEventConfigurationActivated.setDescription('') iBMPSGAOLControlFunctionConfigurationTable = MibTable((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 4), ) if mibBuilder.loadTexts: iBMPSGAOLControlFunctionConfigurationTable.setReference('IBMPSG_AOLControlFunctionConfiguration') if mibBuilder.loadTexts: iBMPSGAOLControlFunctionConfigurationTable.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAOLControlFunctionConfigurationTable.setDescription('') iBMPSGAOLControlFunctionConfigurationEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 4, 1), ).setIndexNames((0, "UMSAOL-MIB", "iBMPSGAOLControlFunctionConfigurationKeyIndex")) if mibBuilder.loadTexts: iBMPSGAOLControlFunctionConfigurationEntry.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAOLControlFunctionConfigurationEntry.setDescription('') iBMPSGAOLControlFunctionConfigurationKeyIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 4, 1, 1), String()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAOLControlFunctionConfigurationKeyIndex.setReference('IBMPSG_AOLControlFunctionConfiguration.KeyIndex') if mibBuilder.loadTexts: iBMPSGAOLControlFunctionConfigurationKeyIndex.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAOLControlFunctionConfigurationKeyIndex.setDescription('') iBMPSGAOLControlFunctionConfigurationName = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 4, 1, 2), String()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAOLControlFunctionConfigurationName.setReference('IBMPSG_AOLControlFunctionConfiguration.Name') if mibBuilder.loadTexts: iBMPSGAOLControlFunctionConfigurationName.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAOLControlFunctionConfigurationName.setDescription('') iBMPSGAOLControlFunctionConfigurationIdentifier = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 4, 1, 3), Uint32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAOLControlFunctionConfigurationIdentifier.setReference('IBMPSG_AOLControlFunctionConfiguration.Identifier') if mibBuilder.loadTexts: iBMPSGAOLControlFunctionConfigurationIdentifier.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAOLControlFunctionConfigurationIdentifier.setDescription('') iBMPSGAOLControlFunctionConfigurationEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 4, 1, 4), Boolean()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAOLControlFunctionConfigurationEnabled.setReference('IBMPSG_AOLControlFunctionConfiguration.Enabled') if mibBuilder.loadTexts: iBMPSGAOLControlFunctionConfigurationEnabled.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAOLControlFunctionConfigurationEnabled.setDescription('') mibBuilder.exportSymbols("UMSAOL-MIB", iBMPSGAOLEventConfigurationEnabled=iBMPSGAOLEventConfigurationEnabled, iBMPSGAlertOnLANDestinationType=iBMPSGAlertOnLANDestinationType, iBMPSGWatchdogMonitoredEntity=iBMPSGWatchdogMonitoredEntity, iBMPSGAlertOnLANEventPollInterval=iBMPSGAlertOnLANEventPollInterval, iBMPSGAOLControlFunctionConfigurationName=iBMPSGAOLControlFunctionConfigurationName, iBMPSGWatchdogMaximumTimeoutInterval=iBMPSGWatchdogMaximumTimeoutInterval, iBMPSGAlertOnLANMaximumHeartbeatInterval=iBMPSGAlertOnLANMaximumHeartbeatInterval, iBMPSGWatchdogTimeoutInterval=iBMPSGWatchdogTimeoutInterval, iBMPSGAlertOnLANMinimumEventPollInterval=iBMPSGAlertOnLANMinimumEventPollInterval, iBMPSGAOLEventConfigurationActivated=iBMPSGAOLEventConfigurationActivated, iBMPSGWatchdogKeyIndex=iBMPSGWatchdogKeyIndex, iBMPSGAlertOnLANOnlySendsFixedMessage=iBMPSGAlertOnLANOnlySendsFixedMessage, iBMPSGAlertOnLANAlertDestinationAddress=iBMPSGAlertOnLANAlertDestinationAddress, iBMPSGAOLEventConfigurationEntry=iBMPSGAOLEventConfigurationEntry, iBMPSGAOLControlFunctionConfigurationKeyIndex=iBMPSGAOLControlFunctionConfigurationKeyIndex, iBMPSGAlertOnLANMinimumHeartbeatInterval=iBMPSGAlertOnLANMinimumHeartbeatInterval, iBMPSGWatchdogTimerResolution=iBMPSGWatchdogTimerResolution, iBMPSGAlertOnLANOtherDestinationTypeDescription=iBMPSGAlertOnLANOtherDestinationTypeDescription, iBMPSGAlertOnLANHeartbeatInterval=iBMPSGAlertOnLANHeartbeatInterval, iBMPSGAOLEventConfigurationName=iBMPSGAOLEventConfigurationName, iBMPSGWatchdogEnabled=iBMPSGWatchdogEnabled, iBMPSGAOLControlFunctionConfigurationIdentifier=iBMPSGAOLControlFunctionConfigurationIdentifier, iBMPSGWatchdogTimeOfLastExpiration=iBMPSGWatchdogTimeOfLastExpiration, iBMPSGAOLEventConfigurationTable=iBMPSGAOLEventConfigurationTable, iBMPSGAlertOnLANEntry=iBMPSGAlertOnLANEntry, iBMPSGWatchdogMonitoredDeviceId=iBMPSGWatchdogMonitoredDeviceId, iBMPSGAlertOnLANFixedPartOfMessage=iBMPSGAlertOnLANFixedPartOfMessage, iBMPSGAlertOnLANEnabled=iBMPSGAlertOnLANEnabled, iBMPSGAlertOnLANDestinationIsAckCapable=iBMPSGAlertOnLANDestinationIsAckCapable, iBMPSGWatchdogMonitoredEntityOnLastExpiration=iBMPSGWatchdogMonitoredEntityOnLastExpiration, iBMPSGAlertOnLANStatus=iBMPSGAlertOnLANStatus, iBMPSGWatchdogMinimumTimeoutInterval=iBMPSGWatchdogMinimumTimeoutInterval, iBMPSGAOLControlFunctionConfigurationEntry=iBMPSGAOLControlFunctionConfigurationEntry, iBMPSGAlertOnLANMessageFormat=iBMPSGAlertOnLANMessageFormat, iBMPSGAlertOnLANMaximumEventPollInterval=iBMPSGAlertOnLANMaximumEventPollInterval, iBMPSGAlertOnLANRetryCount=iBMPSGAlertOnLANRetryCount, iBMPSGAOLEventConfigurationKeyIndex=iBMPSGAOLEventConfigurationKeyIndex, iBMPSGAOLEventConfigurationIdentifier=iBMPSGAOLEventConfigurationIdentifier, iBMPSGAOLControlFunctionConfigurationTable=iBMPSGAOLControlFunctionConfigurationTable, iBMPSGAOLControlFunctionConfigurationEnabled=iBMPSGAOLControlFunctionConfigurationEnabled, iBMPSGAlertOnLANHeartbeatEnabled=iBMPSGAlertOnLANHeartbeatEnabled, iBMPSGWatchdogMonitoredEntityDescription=iBMPSGWatchdogMonitoredEntityDescription, iBMPSGAlertOnLANKeyIndex=iBMPSGAlertOnLANKeyIndex, iBMPSGAlertOnLANOtherMessageFormatDescription=iBMPSGAlertOnLANOtherMessageFormatDescription, iBMPSGAlertOnLANTable=iBMPSGAlertOnLANTable, iBMPSGWatchdogEntry=iBMPSGWatchdogEntry, iBMPSGWatchdogActionOnExpiration=iBMPSGWatchdogActionOnExpiration, iBMPSGWatchdogStatus=iBMPSGWatchdogStatus, iBMPSGWatchdogTable=iBMPSGWatchdogTable, iBMPSGAlertOnLANVersion=iBMPSGAlertOnLANVersion, iBMPSGAlertOnLANEventAutoClearEnabled=iBMPSGAlertOnLANEventAutoClearEnabled)
125.912037
3,583
0.829466
# # PySNMP MIB module UMSAOL-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/UMSAOL-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:28:38 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueSizeConstraint, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueSizeConstraint", "ValueRangeConstraint") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") ModuleIdentity, TimeTicks, MibIdentifier, Unsigned32, Counter32, IpAddress, Gauge32, NotificationType, Integer32, Counter64, MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType, Bits, iso, ObjectIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "ModuleIdentity", "TimeTicks", "MibIdentifier", "Unsigned32", "Counter32", "IpAddress", "Gauge32", "NotificationType", "Integer32", "Counter64", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType", "Bits", "iso", "ObjectIdentity") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") Real64, Sint32, Sint8, String, Uint32, ibmpsgAlertOnLAN, Uint64, Datetime, Real32, Sint64, Sint16, Boolean, Uint16, Uint8 = mibBuilder.importSymbols("UMS-MIB", "Real64", "Sint32", "Sint8", "String", "Uint32", "ibmpsgAlertOnLAN", "Uint64", "Datetime", "Real32", "Sint64", "Sint16", "Boolean", "Uint16", "Uint8") iBMPSGWatchdogTable = MibTable((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 1), ) if mibBuilder.loadTexts: iBMPSGWatchdogTable.setReference('IBMPSG_Watchdog') if mibBuilder.loadTexts: iBMPSGWatchdogTable.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGWatchdogTable.setDescription('') iBMPSGWatchdogEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 1, 1), ).setIndexNames((0, "UMSAOL-MIB", "iBMPSGWatchdogKeyIndex")) if mibBuilder.loadTexts: iBMPSGWatchdogEntry.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGWatchdogEntry.setDescription('') iBMPSGWatchdogKeyIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 1, 1, 1), String()).setMaxAccess("readonly") if mibBuilder.loadTexts: iBMPSGWatchdogKeyIndex.setReference('IBMPSG_Watchdog.KeyIndex') if mibBuilder.loadTexts: iBMPSGWatchdogKeyIndex.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGWatchdogKeyIndex.setDescription('') iBMPSGWatchdogMonitoredDeviceId = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 1, 1, 2), String()).setMaxAccess("readonly") if mibBuilder.loadTexts: iBMPSGWatchdogMonitoredDeviceId.setReference('IBMPSG_Watchdog.DeviceId') if mibBuilder.loadTexts: iBMPSGWatchdogMonitoredDeviceId.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGWatchdogMonitoredDeviceId.setDescription('') iBMPSGWatchdogMonitoredEntity = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 1, 1, 3), Uint16()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGWatchdogMonitoredEntity.setReference('IBMPSG_Watchdog.MonitoredEntity') if mibBuilder.loadTexts: iBMPSGWatchdogMonitoredEntity.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGWatchdogMonitoredEntity.setDescription('') iBMPSGWatchdogMonitoredEntityDescription = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 1, 1, 4), String()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGWatchdogMonitoredEntityDescription.setReference('IBMPSG_Watchdog.MonitoredEntityDescription') if mibBuilder.loadTexts: iBMPSGWatchdogMonitoredEntityDescription.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGWatchdogMonitoredEntityDescription.setDescription('') iBMPSGWatchdogTimeoutInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 1, 1, 5), Uint32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGWatchdogTimeoutInterval.setReference('IBMPSG_Watchdog.TimeoutInterval') if mibBuilder.loadTexts: iBMPSGWatchdogTimeoutInterval.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGWatchdogTimeoutInterval.setDescription('') iBMPSGWatchdogTimerResolution = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 1, 1, 6), Uint32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGWatchdogTimerResolution.setReference('IBMPSG_Watchdog.TimerResolution') if mibBuilder.loadTexts: iBMPSGWatchdogTimerResolution.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGWatchdogTimerResolution.setDescription('') iBMPSGWatchdogTimeOfLastExpiration = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 1, 1, 7), Datetime()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGWatchdogTimeOfLastExpiration.setReference('IBMPSG_Watchdog.TimeOfLastExpiration') if mibBuilder.loadTexts: iBMPSGWatchdogTimeOfLastExpiration.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGWatchdogTimeOfLastExpiration.setDescription('') iBMPSGWatchdogMonitoredEntityOnLastExpiration = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 1, 1, 8), Uint16()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGWatchdogMonitoredEntityOnLastExpiration.setReference('IBMPSG_Watchdog.MonitoredEntityOnLastExpiration') if mibBuilder.loadTexts: iBMPSGWatchdogMonitoredEntityOnLastExpiration.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGWatchdogMonitoredEntityOnLastExpiration.setDescription('') iBMPSGWatchdogActionOnExpiration = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 1, 1, 9), Uint16()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGWatchdogActionOnExpiration.setReference('IBMPSG_Watchdog.ActionOnExpiration') if mibBuilder.loadTexts: iBMPSGWatchdogActionOnExpiration.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGWatchdogActionOnExpiration.setDescription('') iBMPSGWatchdogMaximumTimeoutInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 1, 1, 10), Uint32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGWatchdogMaximumTimeoutInterval.setReference('IBMPSG_Watchdog.MaximumTimeoutInterval') if mibBuilder.loadTexts: iBMPSGWatchdogMaximumTimeoutInterval.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGWatchdogMaximumTimeoutInterval.setDescription('') iBMPSGWatchdogMinimumTimeoutInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 1, 1, 11), Uint32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGWatchdogMinimumTimeoutInterval.setReference('IBMPSG_Watchdog.MinimumTimeoutInterval') if mibBuilder.loadTexts: iBMPSGWatchdogMinimumTimeoutInterval.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGWatchdogMinimumTimeoutInterval.setDescription('') iBMPSGWatchdogEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 1, 1, 12), Boolean()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGWatchdogEnabled.setReference('IBMPSG_Watchdog.Enabled') if mibBuilder.loadTexts: iBMPSGWatchdogEnabled.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGWatchdogEnabled.setDescription('') iBMPSGWatchdogStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 1, 1, 13), String()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGWatchdogStatus.setReference('IBMPSG_Watchdog.Status') if mibBuilder.loadTexts: iBMPSGWatchdogStatus.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGWatchdogStatus.setDescription('The Status property is a string indicating the current status of the object. Various operational and non-operational statuses can be defined. Operational statuses are OK, Degraded and Pred Fail. Pred Fail indicates that an element may be functioning properly but predicting a failure in the near future. An example is a SMART-enabled hard drive. Non-operational statuses can also be specified. These are Error, Starting, Stopping and Service. The latter, Service, could apply during mirror-resilvering of a disk, reload of a user permissions list, or other administrative work. Not all such work is on-line, yet the managed element is neither OK nor in one of the other states.') iBMPSGAlertOnLANTable = MibTable((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 2), ) if mibBuilder.loadTexts: iBMPSGAlertOnLANTable.setReference('IBMPSG_AlertOnLAN') if mibBuilder.loadTexts: iBMPSGAlertOnLANTable.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAlertOnLANTable.setDescription('') iBMPSGAlertOnLANEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 2, 1), ).setIndexNames((0, "UMSAOL-MIB", "iBMPSGAlertOnLANKeyIndex")) if mibBuilder.loadTexts: iBMPSGAlertOnLANEntry.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAlertOnLANEntry.setDescription('') iBMPSGAlertOnLANKeyIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 2, 1, 1), String()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAlertOnLANKeyIndex.setReference('IBMPSG_AlertOnLAN.KeyIndex') if mibBuilder.loadTexts: iBMPSGAlertOnLANKeyIndex.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAlertOnLANKeyIndex.setDescription('') iBMPSGAlertOnLANDestinationType = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 2, 1, 2), Uint16()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAlertOnLANDestinationType.setReference('IBMPSG_AlertOnLAN.DestinationType') if mibBuilder.loadTexts: iBMPSGAlertOnLANDestinationType.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAlertOnLANDestinationType.setDescription('') iBMPSGAlertOnLANOtherDestinationTypeDescription = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 2, 1, 3), String()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAlertOnLANOtherDestinationTypeDescription.setReference('IBMPSG_AlertOnLAN.OtherDestinationTypeDescription') if mibBuilder.loadTexts: iBMPSGAlertOnLANOtherDestinationTypeDescription.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAlertOnLANOtherDestinationTypeDescription.setDescription('') iBMPSGAlertOnLANAlertDestinationAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 2, 1, 4), String()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAlertOnLANAlertDestinationAddress.setReference('IBMPSG_AlertOnLAN.AlertDestinationAddress') if mibBuilder.loadTexts: iBMPSGAlertOnLANAlertDestinationAddress.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAlertOnLANAlertDestinationAddress.setDescription('') iBMPSGAlertOnLANMessageFormat = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 2, 1, 5), Uint16()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAlertOnLANMessageFormat.setReference('IBMPSG_AlertOnLAN.MessageFormat') if mibBuilder.loadTexts: iBMPSGAlertOnLANMessageFormat.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAlertOnLANMessageFormat.setDescription('') iBMPSGAlertOnLANOtherMessageFormatDescription = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 2, 1, 6), String()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAlertOnLANOtherMessageFormatDescription.setReference('IBMPSG_AlertOnLAN.OtherMessageFormatDescription') if mibBuilder.loadTexts: iBMPSGAlertOnLANOtherMessageFormatDescription.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAlertOnLANOtherMessageFormatDescription.setDescription('') iBMPSGAlertOnLANOnlySendsFixedMessage = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 2, 1, 7), Boolean()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAlertOnLANOnlySendsFixedMessage.setReference('IBMPSG_AlertOnLAN.OnlySendsFixedMessage') if mibBuilder.loadTexts: iBMPSGAlertOnLANOnlySendsFixedMessage.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAlertOnLANOnlySendsFixedMessage.setDescription('') iBMPSGAlertOnLANFixedPartOfMessage = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 2, 1, 8), String()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAlertOnLANFixedPartOfMessage.setReference('IBMPSG_AlertOnLAN.FixedPartOfMessage') if mibBuilder.loadTexts: iBMPSGAlertOnLANFixedPartOfMessage.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAlertOnLANFixedPartOfMessage.setDescription('') iBMPSGAlertOnLANDestinationIsAckCapable = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 2, 1, 9), Boolean()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAlertOnLANDestinationIsAckCapable.setReference('IBMPSG_AlertOnLAN.DestinationIsAckCapable') if mibBuilder.loadTexts: iBMPSGAlertOnLANDestinationIsAckCapable.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAlertOnLANDestinationIsAckCapable.setDescription('') iBMPSGAlertOnLANRetryCount = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 2, 1, 10), Uint16()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAlertOnLANRetryCount.setReference('IBMPSG_AlertOnLAN.RetryCount') if mibBuilder.loadTexts: iBMPSGAlertOnLANRetryCount.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAlertOnLANRetryCount.setDescription('') iBMPSGAlertOnLANEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 2, 1, 11), Boolean()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAlertOnLANEnabled.setReference('IBMPSG_AlertOnLAN.Enabled') if mibBuilder.loadTexts: iBMPSGAlertOnLANEnabled.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAlertOnLANEnabled.setDescription('') iBMPSGAlertOnLANVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 2, 1, 12), String()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAlertOnLANVersion.setReference('IBMPSG_AlertOnLAN.Version') if mibBuilder.loadTexts: iBMPSGAlertOnLANVersion.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAlertOnLANVersion.setDescription('Hardware version.') iBMPSGAlertOnLANEventAutoClearEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 2, 1, 13), Boolean()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAlertOnLANEventAutoClearEnabled.setReference('IBMPSG_AlertOnLAN.EventAutoClearEnabled') if mibBuilder.loadTexts: iBMPSGAlertOnLANEventAutoClearEnabled.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAlertOnLANEventAutoClearEnabled.setDescription('') iBMPSGAlertOnLANMaximumEventPollInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 2, 1, 14), Uint32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAlertOnLANMaximumEventPollInterval.setReference('IBMPSG_AlertOnLAN.MaximumEventPollInterval') if mibBuilder.loadTexts: iBMPSGAlertOnLANMaximumEventPollInterval.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAlertOnLANMaximumEventPollInterval.setDescription('') iBMPSGAlertOnLANMinimumEventPollInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 2, 1, 15), Uint32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAlertOnLANMinimumEventPollInterval.setReference('IBMPSG_AlertOnLAN.MinimumEventPollInterval') if mibBuilder.loadTexts: iBMPSGAlertOnLANMinimumEventPollInterval.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAlertOnLANMinimumEventPollInterval.setDescription('') iBMPSGAlertOnLANEventPollInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 2, 1, 16), Uint32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAlertOnLANEventPollInterval.setReference('IBMPSG_AlertOnLAN.EventPollInterval') if mibBuilder.loadTexts: iBMPSGAlertOnLANEventPollInterval.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAlertOnLANEventPollInterval.setDescription('') iBMPSGAlertOnLANHeartbeatEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 2, 1, 17), Boolean()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAlertOnLANHeartbeatEnabled.setReference('IBMPSG_AlertOnLAN.HeartbeatEnabled') if mibBuilder.loadTexts: iBMPSGAlertOnLANHeartbeatEnabled.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAlertOnLANHeartbeatEnabled.setDescription('') iBMPSGAlertOnLANMaximumHeartbeatInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 2, 1, 18), Uint32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAlertOnLANMaximumHeartbeatInterval.setReference('IBMPSG_AlertOnLAN.MaximumHeartbeatInterval') if mibBuilder.loadTexts: iBMPSGAlertOnLANMaximumHeartbeatInterval.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAlertOnLANMaximumHeartbeatInterval.setDescription('') iBMPSGAlertOnLANMinimumHeartbeatInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 2, 1, 19), Uint32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAlertOnLANMinimumHeartbeatInterval.setReference('IBMPSG_AlertOnLAN.MinimumHeartbeatInterval') if mibBuilder.loadTexts: iBMPSGAlertOnLANMinimumHeartbeatInterval.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAlertOnLANMinimumHeartbeatInterval.setDescription('') iBMPSGAlertOnLANHeartbeatInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 2, 1, 20), Uint32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAlertOnLANHeartbeatInterval.setReference('IBMPSG_AlertOnLAN.HeartbeatInterval') if mibBuilder.loadTexts: iBMPSGAlertOnLANHeartbeatInterval.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAlertOnLANHeartbeatInterval.setDescription('') iBMPSGAlertOnLANStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 2, 1, 21), String()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAlertOnLANStatus.setReference('IBMPSG_AlertOnLAN.Status') if mibBuilder.loadTexts: iBMPSGAlertOnLANStatus.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAlertOnLANStatus.setDescription('The Status property is a string indicating the current status of the object. Various operational and non-operational statuses can be defined. Operational statuses are OK, Degraded and Pred Fail. Pred Fail indicates that an element may be functioning properly but predicting a failure in the near future. An example is a SMART-enabled hard drive. Non-operational statuses can also be specified. These are Error, Starting, Stopping and Service. The latter, Service, could apply during mirror-resilvering of a disk, reload of a user permissions list, or other administrative work. Not all such work is on-line, yet the managed element is neither OK nor in one of the other states.') iBMPSGAOLEventConfigurationTable = MibTable((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 3), ) if mibBuilder.loadTexts: iBMPSGAOLEventConfigurationTable.setReference('IBMPSG_AOLEventConfiguration') if mibBuilder.loadTexts: iBMPSGAOLEventConfigurationTable.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAOLEventConfigurationTable.setDescription('') iBMPSGAOLEventConfigurationEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 3, 1), ).setIndexNames((0, "UMSAOL-MIB", "iBMPSGAOLEventConfigurationKeyIndex")) if mibBuilder.loadTexts: iBMPSGAOLEventConfigurationEntry.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAOLEventConfigurationEntry.setDescription('') iBMPSGAOLEventConfigurationKeyIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 3, 1, 1), String()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAOLEventConfigurationKeyIndex.setReference('IBMPSG_AOLEventConfiguration.KeyIndex') if mibBuilder.loadTexts: iBMPSGAOLEventConfigurationKeyIndex.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAOLEventConfigurationKeyIndex.setDescription('') iBMPSGAOLEventConfigurationName = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 3, 1, 2), String()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAOLEventConfigurationName.setReference('IBMPSG_AOLEventConfiguration.Name') if mibBuilder.loadTexts: iBMPSGAOLEventConfigurationName.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAOLEventConfigurationName.setDescription('') iBMPSGAOLEventConfigurationIdentifier = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 3, 1, 3), Uint32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAOLEventConfigurationIdentifier.setReference('IBMPSG_AOLEventConfiguration.Identifier') if mibBuilder.loadTexts: iBMPSGAOLEventConfigurationIdentifier.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAOLEventConfigurationIdentifier.setDescription('') iBMPSGAOLEventConfigurationEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 3, 1, 4), Boolean()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAOLEventConfigurationEnabled.setReference('IBMPSG_AOLEventConfiguration.Enabled') if mibBuilder.loadTexts: iBMPSGAOLEventConfigurationEnabled.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAOLEventConfigurationEnabled.setDescription('') iBMPSGAOLEventConfigurationActivated = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 3, 1, 5), Boolean()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAOLEventConfigurationActivated.setReference('IBMPSG_AOLEventConfiguration.Activated') if mibBuilder.loadTexts: iBMPSGAOLEventConfigurationActivated.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAOLEventConfigurationActivated.setDescription('') iBMPSGAOLControlFunctionConfigurationTable = MibTable((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 4), ) if mibBuilder.loadTexts: iBMPSGAOLControlFunctionConfigurationTable.setReference('IBMPSG_AOLControlFunctionConfiguration') if mibBuilder.loadTexts: iBMPSGAOLControlFunctionConfigurationTable.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAOLControlFunctionConfigurationTable.setDescription('') iBMPSGAOLControlFunctionConfigurationEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 4, 1), ).setIndexNames((0, "UMSAOL-MIB", "iBMPSGAOLControlFunctionConfigurationKeyIndex")) if mibBuilder.loadTexts: iBMPSGAOLControlFunctionConfigurationEntry.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAOLControlFunctionConfigurationEntry.setDescription('') iBMPSGAOLControlFunctionConfigurationKeyIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 4, 1, 1), String()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAOLControlFunctionConfigurationKeyIndex.setReference('IBMPSG_AOLControlFunctionConfiguration.KeyIndex') if mibBuilder.loadTexts: iBMPSGAOLControlFunctionConfigurationKeyIndex.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAOLControlFunctionConfigurationKeyIndex.setDescription('') iBMPSGAOLControlFunctionConfigurationName = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 4, 1, 2), String()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAOLControlFunctionConfigurationName.setReference('IBMPSG_AOLControlFunctionConfiguration.Name') if mibBuilder.loadTexts: iBMPSGAOLControlFunctionConfigurationName.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAOLControlFunctionConfigurationName.setDescription('') iBMPSGAOLControlFunctionConfigurationIdentifier = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 4, 1, 3), Uint32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAOLControlFunctionConfigurationIdentifier.setReference('IBMPSG_AOLControlFunctionConfiguration.Identifier') if mibBuilder.loadTexts: iBMPSGAOLControlFunctionConfigurationIdentifier.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAOLControlFunctionConfigurationIdentifier.setDescription('') iBMPSGAOLControlFunctionConfigurationEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 2, 6, 159, 1, 1, 70, 4, 1, 4), Boolean()).setMaxAccess("readwrite") if mibBuilder.loadTexts: iBMPSGAOLControlFunctionConfigurationEnabled.setReference('IBMPSG_AOLControlFunctionConfiguration.Enabled') if mibBuilder.loadTexts: iBMPSGAOLControlFunctionConfigurationEnabled.setStatus('mandatory') if mibBuilder.loadTexts: iBMPSGAOLControlFunctionConfigurationEnabled.setDescription('') mibBuilder.exportSymbols("UMSAOL-MIB", iBMPSGAOLEventConfigurationEnabled=iBMPSGAOLEventConfigurationEnabled, iBMPSGAlertOnLANDestinationType=iBMPSGAlertOnLANDestinationType, iBMPSGWatchdogMonitoredEntity=iBMPSGWatchdogMonitoredEntity, iBMPSGAlertOnLANEventPollInterval=iBMPSGAlertOnLANEventPollInterval, iBMPSGAOLControlFunctionConfigurationName=iBMPSGAOLControlFunctionConfigurationName, iBMPSGWatchdogMaximumTimeoutInterval=iBMPSGWatchdogMaximumTimeoutInterval, iBMPSGAlertOnLANMaximumHeartbeatInterval=iBMPSGAlertOnLANMaximumHeartbeatInterval, iBMPSGWatchdogTimeoutInterval=iBMPSGWatchdogTimeoutInterval, iBMPSGAlertOnLANMinimumEventPollInterval=iBMPSGAlertOnLANMinimumEventPollInterval, iBMPSGAOLEventConfigurationActivated=iBMPSGAOLEventConfigurationActivated, iBMPSGWatchdogKeyIndex=iBMPSGWatchdogKeyIndex, iBMPSGAlertOnLANOnlySendsFixedMessage=iBMPSGAlertOnLANOnlySendsFixedMessage, iBMPSGAlertOnLANAlertDestinationAddress=iBMPSGAlertOnLANAlertDestinationAddress, iBMPSGAOLEventConfigurationEntry=iBMPSGAOLEventConfigurationEntry, iBMPSGAOLControlFunctionConfigurationKeyIndex=iBMPSGAOLControlFunctionConfigurationKeyIndex, iBMPSGAlertOnLANMinimumHeartbeatInterval=iBMPSGAlertOnLANMinimumHeartbeatInterval, iBMPSGWatchdogTimerResolution=iBMPSGWatchdogTimerResolution, iBMPSGAlertOnLANOtherDestinationTypeDescription=iBMPSGAlertOnLANOtherDestinationTypeDescription, iBMPSGAlertOnLANHeartbeatInterval=iBMPSGAlertOnLANHeartbeatInterval, iBMPSGAOLEventConfigurationName=iBMPSGAOLEventConfigurationName, iBMPSGWatchdogEnabled=iBMPSGWatchdogEnabled, iBMPSGAOLControlFunctionConfigurationIdentifier=iBMPSGAOLControlFunctionConfigurationIdentifier, iBMPSGWatchdogTimeOfLastExpiration=iBMPSGWatchdogTimeOfLastExpiration, iBMPSGAOLEventConfigurationTable=iBMPSGAOLEventConfigurationTable, iBMPSGAlertOnLANEntry=iBMPSGAlertOnLANEntry, iBMPSGWatchdogMonitoredDeviceId=iBMPSGWatchdogMonitoredDeviceId, iBMPSGAlertOnLANFixedPartOfMessage=iBMPSGAlertOnLANFixedPartOfMessage, iBMPSGAlertOnLANEnabled=iBMPSGAlertOnLANEnabled, iBMPSGAlertOnLANDestinationIsAckCapable=iBMPSGAlertOnLANDestinationIsAckCapable, iBMPSGWatchdogMonitoredEntityOnLastExpiration=iBMPSGWatchdogMonitoredEntityOnLastExpiration, iBMPSGAlertOnLANStatus=iBMPSGAlertOnLANStatus, iBMPSGWatchdogMinimumTimeoutInterval=iBMPSGWatchdogMinimumTimeoutInterval, iBMPSGAOLControlFunctionConfigurationEntry=iBMPSGAOLControlFunctionConfigurationEntry, iBMPSGAlertOnLANMessageFormat=iBMPSGAlertOnLANMessageFormat, iBMPSGAlertOnLANMaximumEventPollInterval=iBMPSGAlertOnLANMaximumEventPollInterval, iBMPSGAlertOnLANRetryCount=iBMPSGAlertOnLANRetryCount, iBMPSGAOLEventConfigurationKeyIndex=iBMPSGAOLEventConfigurationKeyIndex, iBMPSGAOLEventConfigurationIdentifier=iBMPSGAOLEventConfigurationIdentifier, iBMPSGAOLControlFunctionConfigurationTable=iBMPSGAOLControlFunctionConfigurationTable, iBMPSGAOLControlFunctionConfigurationEnabled=iBMPSGAOLControlFunctionConfigurationEnabled, iBMPSGAlertOnLANHeartbeatEnabled=iBMPSGAlertOnLANHeartbeatEnabled, iBMPSGWatchdogMonitoredEntityDescription=iBMPSGWatchdogMonitoredEntityDescription, iBMPSGAlertOnLANKeyIndex=iBMPSGAlertOnLANKeyIndex, iBMPSGAlertOnLANOtherMessageFormatDescription=iBMPSGAlertOnLANOtherMessageFormatDescription, iBMPSGAlertOnLANTable=iBMPSGAlertOnLANTable, iBMPSGWatchdogEntry=iBMPSGWatchdogEntry, iBMPSGWatchdogActionOnExpiration=iBMPSGWatchdogActionOnExpiration, iBMPSGWatchdogStatus=iBMPSGWatchdogStatus, iBMPSGWatchdogTable=iBMPSGWatchdogTable, iBMPSGAlertOnLANVersion=iBMPSGAlertOnLANVersion, iBMPSGAlertOnLANEventAutoClearEnabled=iBMPSGAlertOnLANEventAutoClearEnabled)
0
0
0
f41f2662e4f40fdad1c2ec61ff8cf3d68cf63e8c
2,945
py
Python
tensorflow/python/client/pywrap_tf_session.py
yage99/tensorflow
c7fa71b32a3635eb25596ae80d007b41007769c4
[ "Apache-2.0" ]
78
2020-08-04T12:36:25.000Z
2022-03-25T04:23:40.000Z
tensorflow/python/client/pywrap_tf_session.py
sseung0703/tensorflow
be084bd7a4dd241eb781fc704f57bcacc5c9b6dd
[ "Apache-2.0" ]
1,056
2019-12-15T01:20:31.000Z
2022-02-10T02:06:28.000Z
tensorflow/python/client/pywrap_tf_session.py
sseung0703/tensorflow
be084bd7a4dd241eb781fc704f57bcacc5c9b6dd
[ "Apache-2.0" ]
66
2020-05-15T10:05:12.000Z
2022-02-14T07:28:18.000Z
# Copyright 2019 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. # ============================================================================== """Python module for Session ops, vars, and functions exported by pybind11.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=invalid-import-order,g-bad-import-order, wildcard-import, unused-import from tensorflow.python import pywrap_tensorflow from tensorflow.python._pywrap_tf_session import * from tensorflow.python._pywrap_tf_session import _TF_SetTarget from tensorflow.python._pywrap_tf_session import _TF_SetConfig from tensorflow.python._pywrap_tf_session import _TF_NewSessionOptions # Convert versions to strings for Python2 and keep api_compatibility_test green. # We can remove this hack once we remove Python2 presubmits. pybind11 can only # return unicode for Python2 even with py::str. # https://pybind11.readthedocs.io/en/stable/advanced/cast/strings.html#returning-c-strings-to-python # pylint: disable=undefined-variable __version__ = str(get_version()) __git_version__ = str(get_git_version()) __compiler_version__ = str(get_compiler_version()) __cxx11_abi_flag__ = get_cxx11_abi_flag() __monolithic_build__ = get_monolithic_build() # User getters to hold attributes rather than pybind11's m.attr due to # b/145559202. GRAPH_DEF_VERSION = get_graph_def_version() GRAPH_DEF_VERSION_MIN_CONSUMER = get_graph_def_version_min_consumer() GRAPH_DEF_VERSION_MIN_PRODUCER = get_graph_def_version_min_producer() TENSOR_HANDLE_KEY = get_tensor_handle_key() # pylint: enable=undefined-variable # Disable pylint invalid name warnings for legacy functions. # pylint: disable=invalid-name # Disable pylind undefined-variable as the variable is exported in the shared # object via pybind11. # pylint: disable=undefined-variable
41.478873
100
0.782683
# Copyright 2019 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. # ============================================================================== """Python module for Session ops, vars, and functions exported by pybind11.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=invalid-import-order,g-bad-import-order, wildcard-import, unused-import from tensorflow.python import pywrap_tensorflow from tensorflow.python._pywrap_tf_session import * from tensorflow.python._pywrap_tf_session import _TF_SetTarget from tensorflow.python._pywrap_tf_session import _TF_SetConfig from tensorflow.python._pywrap_tf_session import _TF_NewSessionOptions # Convert versions to strings for Python2 and keep api_compatibility_test green. # We can remove this hack once we remove Python2 presubmits. pybind11 can only # return unicode for Python2 even with py::str. # https://pybind11.readthedocs.io/en/stable/advanced/cast/strings.html#returning-c-strings-to-python # pylint: disable=undefined-variable __version__ = str(get_version()) __git_version__ = str(get_git_version()) __compiler_version__ = str(get_compiler_version()) __cxx11_abi_flag__ = get_cxx11_abi_flag() __monolithic_build__ = get_monolithic_build() # User getters to hold attributes rather than pybind11's m.attr due to # b/145559202. GRAPH_DEF_VERSION = get_graph_def_version() GRAPH_DEF_VERSION_MIN_CONSUMER = get_graph_def_version_min_consumer() GRAPH_DEF_VERSION_MIN_PRODUCER = get_graph_def_version_min_producer() TENSOR_HANDLE_KEY = get_tensor_handle_key() # pylint: enable=undefined-variable # Disable pylint invalid name warnings for legacy functions. # pylint: disable=invalid-name def TF_NewSessionOptions(target=None, config=None): # NOTE: target and config are validated in the session constructor. opts = _TF_NewSessionOptions() if target is not None: _TF_SetTarget(opts, target) if config is not None: config_str = config.SerializeToString() _TF_SetConfig(opts, config_str) return opts # Disable pylind undefined-variable as the variable is exported in the shared # object via pybind11. # pylint: disable=undefined-variable def TF_Reset(target, containers=None, config=None): opts = TF_NewSessionOptions(target=target, config=config) try: TF_Reset_wrapper(opts, containers) finally: TF_DeleteSessionOptions(opts)
490
0
44
959b3db8a6a7d05b7f3378dbae164f774574b9f1
1,956
py
Python
monarch.py
michaelduong/monarch-apt-scraper
2bf36af7ab4c26b661d96cfedb0c49239e601ddc
[ "MIT" ]
null
null
null
monarch.py
michaelduong/monarch-apt-scraper
2bf36af7ab4c26b661d96cfedb0c49239e601ddc
[ "MIT" ]
null
null
null
monarch.py
michaelduong/monarch-apt-scraper
2bf36af7ab4c26b661d96cfedb0c49239e601ddc
[ "MIT" ]
null
null
null
# Monarch Apartment Price Scraper # Monarch.py # Checks Monarch apartment webpages every hour to see if the prices have changed import bs4 import requests import smtplib import time # time between checks in seconds sleeptime = 3600 # generic network request function that returns an array of prices last_A4_Prices = None last_A1D_Prices = None currentA4Prices = getPrices("a4") currentA1DPrices = getPrices("a1d") if last_A4_Prices is None: last_A4_Prices = currentA4Prices if last_A1D_Prices is None: last_A1D_Prices = currentA1DPrices while True: if last_A1D_Prices == currentA1DPrices or last_A4_Prices == currentA4Prices: print("No price change") if last_A1D_Prices != currentA1DPrices: print("Price has changed!") sendEmail("a1d") if last_A4_Prices != currentA4Prices: print("Price has changed!") sendEmail("a4") time.sleep(sleeptime)
33.152542
152
0.699898
# Monarch Apartment Price Scraper # Monarch.py # Checks Monarch apartment webpages every hour to see if the prices have changed import bs4 import requests import smtplib import time # time between checks in seconds sleeptime = 3600 # generic network request function that returns an array of prices def getPrices(floorplan: str) -> [str]: url = "https://www.themonarchbywindsor.com/floorplans/" + floorplan headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} response = requests.get(url, headers=headers) response.raise_for_status() web_page = bs4.BeautifulSoup(response.content, 'html.parser') price = web_page.find_all(class_="td-card-rent") results = [r.text.split(' ')[0].strip() for r in price] results = [result.replace("Rent:", "") for result in results] return results def sendEmail(floorplan: str): msg = "Subject: Monarch's " + floorplan.capitalize() + " price has changed!" fromaddr = '[GMAIL EMAIL ADDRESS HERE]' toaddr = ['[EMAIL ADDRESS TO SEND TO]'] server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login("[GMAIL EMAIL ADDRESS HERE]", "[GMAIL EMAIL PASSWORD HERE]") server.sendmail(fromaddr, toaddr, msg) server.quit() last_A4_Prices = None last_A1D_Prices = None currentA4Prices = getPrices("a4") currentA1DPrices = getPrices("a1d") if last_A4_Prices is None: last_A4_Prices = currentA4Prices if last_A1D_Prices is None: last_A1D_Prices = currentA1DPrices while True: if last_A1D_Prices == currentA1DPrices or last_A4_Prices == currentA4Prices: print("No price change") if last_A1D_Prices != currentA1DPrices: print("Price has changed!") sendEmail("a1d") if last_A4_Prices != currentA4Prices: print("Price has changed!") sendEmail("a4") time.sleep(sleeptime)
980
0
45
7277ad1fe405a54a5b713d131f90a8d72b4b88f3
135
py
Python
gameServer/mapCode/__init__.py
hydrogen602/settlersPy
5a1df6162d35b6ae9eeefd11c9a0a9ba7a19019c
[ "MIT" ]
null
null
null
gameServer/mapCode/__init__.py
hydrogen602/settlersPy
5a1df6162d35b6ae9eeefd11c9a0a9ba7a19019c
[ "MIT" ]
null
null
null
gameServer/mapCode/__init__.py
hydrogen602/settlersPy
5a1df6162d35b6ae9eeefd11c9a0a9ba7a19019c
[ "MIT" ]
null
null
null
from .gameMap import GameMap from .lineMapFeatures import Road from .pointMapFeatures import Settlement, City from .tiles import Tile
22.5
46
0.82963
from .gameMap import GameMap from .lineMapFeatures import Road from .pointMapFeatures import Settlement, City from .tiles import Tile
0
0
0
573d32a608f13f8d64effc820ea56127067e7930
1,559
py
Python
esmvalcore/cmor/_fixes/cmip5/ccsm4.py
jvegreg/ESMValCore
03eb1c942bf1dc3be98cb30c3592b42e82a94f16
[ "Apache-2.0" ]
26
2019-06-07T07:50:07.000Z
2022-03-22T21:04:01.000Z
esmvalcore/cmor/_fixes/cmip5/ccsm4.py
jvegreg/ESMValCore
03eb1c942bf1dc3be98cb30c3592b42e82a94f16
[ "Apache-2.0" ]
1,370
2019-06-06T09:03:07.000Z
2022-03-31T04:37:20.000Z
esmvalcore/cmor/_fixes/cmip5/ccsm4.py
valeriupredoi/ESMValCore
b46b948c47d8579d997b28501f8588f5531aa354
[ "Apache-2.0" ]
26
2019-07-03T13:08:48.000Z
2022-03-02T16:08:47.000Z
"""Fixes for CCSM4 model.""" import dask.array as da from ..fix import Fix from ..shared import round_coordinates from .bnu_esm import Cl as BaseCl Cl = BaseCl class Csoil(Fix): """Fixes for Csoil.""" def fix_data(self, cube): """Fix data. The data is not properly masked. This fixes the mask. Parameters ---------- cube : iris.cube.Cube Input cube. Returns ------- iris.cube.Cube """ cube.data = da.ma.masked_equal(cube.core_data(), 1.e33) return cube Cveg = Csoil Gpp = Csoil class AllVars(Fix): """Fixes for all variables.""" def fix_metadata(self, cubes): """Fix data. Some coordinate points vary for different files of this dataset (for different time range). This fix removes these inaccuracies by rounding the coordinates. Parameters ---------- cubes : iris.cube.CubeList Input cubes. Returns ------- iris.cube.CubeList """ return round_coordinates(cubes, decimals=3, coord_names=['latitude']) class So(Fix): """Fixes for so.""" def fix_metadata(self, cubes): """Fix data. Fixes discrepancy between declared units and real units Parameters ---------- cubes : iris.cube.CubeList Input cubes. Returns ------- iris.cube.CubeList """ self.get_cube_from_list(cubes).units = '1e3' return cubes
19.4875
78
0.552919
"""Fixes for CCSM4 model.""" import dask.array as da from ..fix import Fix from ..shared import round_coordinates from .bnu_esm import Cl as BaseCl Cl = BaseCl class Csoil(Fix): """Fixes for Csoil.""" def fix_data(self, cube): """Fix data. The data is not properly masked. This fixes the mask. Parameters ---------- cube : iris.cube.Cube Input cube. Returns ------- iris.cube.Cube """ cube.data = da.ma.masked_equal(cube.core_data(), 1.e33) return cube Cveg = Csoil Gpp = Csoil class AllVars(Fix): """Fixes for all variables.""" def fix_metadata(self, cubes): """Fix data. Some coordinate points vary for different files of this dataset (for different time range). This fix removes these inaccuracies by rounding the coordinates. Parameters ---------- cubes : iris.cube.CubeList Input cubes. Returns ------- iris.cube.CubeList """ return round_coordinates(cubes, decimals=3, coord_names=['latitude']) class So(Fix): """Fixes for so.""" def fix_metadata(self, cubes): """Fix data. Fixes discrepancy between declared units and real units Parameters ---------- cubes : iris.cube.CubeList Input cubes. Returns ------- iris.cube.CubeList """ self.get_cube_from_list(cubes).units = '1e3' return cubes
0
0
0
f7f7b1147798ce46ece79acebd6afb2506af7e3b
4,106
py
Python
snakescale/formatters.py
clintval/snakeskin
0d282ae8331756ca5b93ffe7146af1ba6491d579
[ "MIT" ]
6
2018-01-24T04:40:45.000Z
2018-08-10T18:03:35.000Z
snakescale/formatters.py
clintval/snakeskin
0d282ae8331756ca5b93ffe7146af1ba6491d579
[ "MIT" ]
9
2018-12-27T18:13:15.000Z
2019-01-01T23:06:22.000Z
snakescale/formatters.py
clintval/snakeskin
0d282ae8331756ca5b93ffe7146af1ba6491d579
[ "MIT" ]
null
null
null
from types import GeneratorType from typing import List, Mapping, Union __all__ = [ 'clean_picard_style_value', 'snakecase_to_kebab_case', 'clean_picard_style_key', 'format_bedtools_params', 'format_bwa_params', 'format_dwgsim_params', 'format_fgbio_params', 'format_kraken_params', 'format_picard_params', ] def clean_picard_style_value(value: Union[List[str], str]) -> Union[List[str], str]: """Clean a dictionary of Picard key-value pairs.""" if isinstance(value, (list, tuple, GeneratorType)): return list(map(clean_picard_style_value, value)) # type: ignore elif value is None: return 'null' elif value is True: return 'true' elif value is False: return 'false' else: return value def format_bed_key(key: str) -> str: """Clean a bedtools parameter key.""" return '-' + key.replace('_', '') def snakecase_to_kebab_case(key: str) -> str: """Convert snake_case to kebab-case.""" return f'--{key.lower().replace("_", "-")}' def clean_picard_style_key(key: str) -> str: """Clean a Picard parameter key.""" return key.upper() def format_bedtools_params(params: Mapping) -> str: """Clean a dictionary of bedtools key-value pairs.""" formatted_params = '' for key, value in params.items(): if key == 'extra': continue key = format_bed_key(key) if value is True: formatted_params += f' {key}' elif value is False: continue else: formatted_params += f' {key} {value}' return formatted_params def format_bwa_params(params: Mapping) -> str: """Clean a dictionary of bwa key-value pairs.""" formatted_params = '' for key, value in params.items(): if key == 'extra': continue elif value is True: formatted_params += f' -{key}' elif value is False: continue else: formatted_params += f' -{key} {value}' return formatted_params def format_dwgsim_params(params: Mapping) -> str: """Clean a dictionary of dwgsim key-value pairs.""" formatted_params = '' for key, value in params.items(): if key in ('extra', 'output_prefix'): continue key = '1' if key == 'r1' else key key = '2' if key == 'r2' else key if value is True: formatted_params += f' -{key}' elif value is False: continue else: formatted_params += f' -{key} {value}' return formatted_params def format_fgbio_params(params: Mapping) -> str: """Clean a dictionary of fgbio key-value pairs.""" formatted_params = '' for key, value in params.items(): key = snakecase_to_kebab_case(key) value = clean_picard_style_value(value) if key == 'extra': continue elif isinstance(value, list): formatted_params += ''.join(f' --{key}={v}' for v in value) else: formatted_params += f' --{key}={value}' return formatted_params def format_kraken_params(params: Mapping) -> str: """Clean a dictionary of kraken key-value pairs.""" formatted_params = '' for key, value in params.items(): key = snakecase_to_kebab_case(key) if key == 'extra': continue elif value is True: formatted_params += f' --{key}' elif value is False: continue else: formatted_params += f' --{key} {value}' return formatted_params def format_picard_params(params: Mapping) -> str: """Clean a dictionary of picard key-value pairs.""" formatted_params = '' for key, value in params.items(): key = clean_picard_style_key(key) value = clean_picard_style_value(value) if key == 'extra': continue elif isinstance(value, list): formatted_params += ''.join(f' {key}={v}' for v in value) else: formatted_params += f' {key}={value}' return formatted_params
27.013158
84
0.595226
from types import GeneratorType from typing import List, Mapping, Union __all__ = [ 'clean_picard_style_value', 'snakecase_to_kebab_case', 'clean_picard_style_key', 'format_bedtools_params', 'format_bwa_params', 'format_dwgsim_params', 'format_fgbio_params', 'format_kraken_params', 'format_picard_params', ] def clean_picard_style_value(value: Union[List[str], str]) -> Union[List[str], str]: """Clean a dictionary of Picard key-value pairs.""" if isinstance(value, (list, tuple, GeneratorType)): return list(map(clean_picard_style_value, value)) # type: ignore elif value is None: return 'null' elif value is True: return 'true' elif value is False: return 'false' else: return value def format_bed_key(key: str) -> str: """Clean a bedtools parameter key.""" return '-' + key.replace('_', '') def snakecase_to_kebab_case(key: str) -> str: """Convert snake_case to kebab-case.""" return f'--{key.lower().replace("_", "-")}' def clean_picard_style_key(key: str) -> str: """Clean a Picard parameter key.""" return key.upper() def format_bedtools_params(params: Mapping) -> str: """Clean a dictionary of bedtools key-value pairs.""" formatted_params = '' for key, value in params.items(): if key == 'extra': continue key = format_bed_key(key) if value is True: formatted_params += f' {key}' elif value is False: continue else: formatted_params += f' {key} {value}' return formatted_params def format_bwa_params(params: Mapping) -> str: """Clean a dictionary of bwa key-value pairs.""" formatted_params = '' for key, value in params.items(): if key == 'extra': continue elif value is True: formatted_params += f' -{key}' elif value is False: continue else: formatted_params += f' -{key} {value}' return formatted_params def format_dwgsim_params(params: Mapping) -> str: """Clean a dictionary of dwgsim key-value pairs.""" formatted_params = '' for key, value in params.items(): if key in ('extra', 'output_prefix'): continue key = '1' if key == 'r1' else key key = '2' if key == 'r2' else key if value is True: formatted_params += f' -{key}' elif value is False: continue else: formatted_params += f' -{key} {value}' return formatted_params def format_fgbio_params(params: Mapping) -> str: """Clean a dictionary of fgbio key-value pairs.""" formatted_params = '' for key, value in params.items(): key = snakecase_to_kebab_case(key) value = clean_picard_style_value(value) if key == 'extra': continue elif isinstance(value, list): formatted_params += ''.join(f' --{key}={v}' for v in value) else: formatted_params += f' --{key}={value}' return formatted_params def format_kraken_params(params: Mapping) -> str: """Clean a dictionary of kraken key-value pairs.""" formatted_params = '' for key, value in params.items(): key = snakecase_to_kebab_case(key) if key == 'extra': continue elif value is True: formatted_params += f' --{key}' elif value is False: continue else: formatted_params += f' --{key} {value}' return formatted_params def format_picard_params(params: Mapping) -> str: """Clean a dictionary of picard key-value pairs.""" formatted_params = '' for key, value in params.items(): key = clean_picard_style_key(key) value = clean_picard_style_value(value) if key == 'extra': continue elif isinstance(value, list): formatted_params += ''.join(f' {key}={v}' for v in value) else: formatted_params += f' {key}={value}' return formatted_params
0
0
0
49336efae7ad8ab0ed8d9f0b0ab614569ef39185
3,883
py
Python
dot_weechat/python/unhighlight.py
benmezger/new-dotfiles
5aa41015bd017d0e4cc39edf374ca73e8c25b8cb
[ "MIT" ]
68
2016-09-28T12:51:20.000Z
2022-02-25T15:33:16.000Z
dot_weechat/python/unhighlight.py
benmezger/new-dotfiles
5aa41015bd017d0e4cc39edf374ca73e8c25b8cb
[ "MIT" ]
null
null
null
dot_weechat/python/unhighlight.py
benmezger/new-dotfiles
5aa41015bd017d0e4cc39edf374ca73e8c25b8cb
[ "MIT" ]
2
2016-09-28T12:51:28.000Z
2022-01-11T10:26:44.000Z
# # Copyright (C) 2016 Andrew Rodgers-Schatz <me@andrew.rs> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from __future__ import print_function try: import weechat except Exception: print('This script must be run under WeeChat.') print('Get WeeChat now at: https://weechat.org/') import_ok = False import time import re SCRIPT_NAME = 'unhighlight' SCRIPT_AUTHOR = 'xiagu' SCRIPT_VERSION = '0.1.3' SCRIPT_LICENSE = 'GPL3' SCRIPT_DESC = 'Allows per-buffer specification of a regex that prevents highlights.' def unhighlight_cb(data, modifier, modifier_data, message): """Check if the line matches the unhighlight regular expression, and if it does, clear the message and reprint it with the no_highlight tag added.""" if modifier_data.startswith('0x'): # WeeChat >= 2.9 buffer, tags = modifier_data.split(';', 1) else: # WeeChat <= 2.8 plugin, buffer_name, tags = modifier_data.split(';', 2) buffer = weechat.buffer_search(plugin, buffer_name) if 'no_highlight' in tags or 'notify_none' in tags: return message unhighlight_regex = weechat.buffer_get_string(buffer, 'localvar_unhighlight_regex') if not matches_unhighlight_strings(message, unhighlight_regex): return message # inspired by https://weechat.org/scripts/source/mass_hl_blocker.pl.html/ # this is terrible and gross but afaik there is no way to change the # highlight message once it's set and no way to interact with a message's # tags before highlights are checked. weechat.prnt_date_tags(buffer, 0, "%s,no_highlight" % tags, message) return '' if weechat.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION, SCRIPT_LICENSE, SCRIPT_DESC, '', ''): main()
35.3
153
0.733969
# # Copyright (C) 2016 Andrew Rodgers-Schatz <me@andrew.rs> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from __future__ import print_function try: import weechat except Exception: print('This script must be run under WeeChat.') print('Get WeeChat now at: https://weechat.org/') import_ok = False import time import re SCRIPT_NAME = 'unhighlight' SCRIPT_AUTHOR = 'xiagu' SCRIPT_VERSION = '0.1.3' SCRIPT_LICENSE = 'GPL3' SCRIPT_DESC = 'Allows per-buffer specification of a regex that prevents highlights.' def matches_unhighlight_strings(msg, regex): return weechat.string_has_highlight_regex(msg, regex) def unhighlight_cb(data, modifier, modifier_data, message): """Check if the line matches the unhighlight regular expression, and if it does, clear the message and reprint it with the no_highlight tag added.""" if modifier_data.startswith('0x'): # WeeChat >= 2.9 buffer, tags = modifier_data.split(';', 1) else: # WeeChat <= 2.8 plugin, buffer_name, tags = modifier_data.split(';', 2) buffer = weechat.buffer_search(plugin, buffer_name) if 'no_highlight' in tags or 'notify_none' in tags: return message unhighlight_regex = weechat.buffer_get_string(buffer, 'localvar_unhighlight_regex') if not matches_unhighlight_strings(message, unhighlight_regex): return message # inspired by https://weechat.org/scripts/source/mass_hl_blocker.pl.html/ # this is terrible and gross but afaik there is no way to change the # highlight message once it's set and no way to interact with a message's # tags before highlights are checked. weechat.prnt_date_tags(buffer, 0, "%s,no_highlight" % tags, message) return '' def command_cb(data, buffer, args): args = args.strip().lower().split(' ') if args[0] == 'list': weechat.command('', '/set *.localvar_set_unhighlight_regex') else: weechat.command('', '/help %s' % SCRIPT_NAME) return weechat.WEECHAT_RC_OK def main(): hook = weechat.hook_modifier('weechat_print', 'unhighlight_cb', '') description = """ {script_name} lets you set up a regex for things to never highlight. To use this, set the localvar 'unhighlight_regex' on a buffer. Lines in that buffer which match will never be highlighted, even if they have your nick or match highlight_words or highlight_regex. You will need the script 'buffer_autoset.py' installed to make local variables persistent; see the examples below. Examples: Temporarily block highlights in the current buffer for lines matching 'banana': /buffer set localvar_set_unhighlight_regex banana Unhighlight SASL authentication messages for double logins: /buffer weechat /buffer set localvar_set_unhighlight_regex SaslServ /buffer_autoset add core.weechat localvar_set_unhighlight_regex SaslServ List buffers with autoset unhighlights: /{script_name} list Show this help: /{script_name} Display local variables for current buffer: /buffer localvar """.format(script_name = SCRIPT_NAME) weechat.hook_command(SCRIPT_NAME, SCRIPT_DESC, 'list', description, 'list %-', 'command_cb', '') if weechat.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION, SCRIPT_LICENSE, SCRIPT_DESC, '', ''): main()
1,459
0
69
5dbc29abd552c7f1afbb42cf9ea7e8338b005f16
9,759
py
Python
src/utils/myutils.py
haxhimitsu/dl_classification
0de59faedb18dd944f341af4fd37028639831d54
[ "MIT" ]
null
null
null
src/utils/myutils.py
haxhimitsu/dl_classification
0de59faedb18dd944f341af4fd37028639831d54
[ "MIT" ]
null
null
null
src/utils/myutils.py
haxhimitsu/dl_classification
0de59faedb18dd944f341af4fd37028639831d54
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # coding: UTF-8 #--------------------------------------------------------------- # author:"Haxhimitsu" # date :"2021/01/06" # cite : # sample:python3 imgtrim_gui_ver.2.0.py --input_dir ../assets/original_img/cbn_test_01/ --output_dir ../assets/sample_output/ --trim_width 32 --trim_height 64 #--------------------------------------------------------------- import keras from keras.utils import np_utils from keras.layers.convolutional import Conv2D, MaxPooling2D from keras.models import Sequential from keras.layers.core import Dense, Dropout, Activation, Flatten from keras.preprocessing.image import array_to_img, img_to_array, load_img import keras.callbacks from keras.models import Sequential, model_from_json import numpy as np #import pandas as pd #from sklearn.model_selection import train_test_split #import matplotlib.pyplot as plt import os class myutil: """ # function : careate directory # input arg : directory path # output : none # func detail : if not already exist argument directory path,this function create directory. """ """ # function : create network # input arg : category number # output : network model # func detail : please following comments """ """ # function : create dataset # input arg : train data path,validation data path # output : train img,train label,validation img,validation label # func detail : please following comments """ """ # function : check acc # input arg : test image path,log directory # output : test image predict label, score # func detail : # test image path example test/class1/01.png # /02.png # /03.png # test/class2/01.png # /02.png # /03.png # test/class3/01.png # /02.png # /03.png """ """ # function : acc2 # input arg : network model, test img data path, log save directory # output : none # func detail : テスト画像のディレクトリを読み込み,学習したネットワークで分類をする # 各々の正解ラベルに対する正答率を算出する # testdata_architecture :test_img_path->test/class1/ """ if __name__ == '__main__': test = myutil() test.sayStr("Hello") # Hello
38.121094
160
0.565119
#!/usr/bin/env python3 # coding: UTF-8 #--------------------------------------------------------------- # author:"Haxhimitsu" # date :"2021/01/06" # cite : # sample:python3 imgtrim_gui_ver.2.0.py --input_dir ../assets/original_img/cbn_test_01/ --output_dir ../assets/sample_output/ --trim_width 32 --trim_height 64 #--------------------------------------------------------------- import keras from keras.utils import np_utils from keras.layers.convolutional import Conv2D, MaxPooling2D from keras.models import Sequential from keras.layers.core import Dense, Dropout, Activation, Flatten from keras.preprocessing.image import array_to_img, img_to_array, load_img import keras.callbacks from keras.models import Sequential, model_from_json import numpy as np #import pandas as pd #from sklearn.model_selection import train_test_split #import matplotlib.pyplot as plt import os class myutil: """ # function : careate directory # input arg : directory path # output : none # func detail : if not already exist argument directory path,this function create directory. """ def create_directory(self,directory_path): if not os.path.exists(directory_path): os.makedirs(directory_path) else: print("already exists"+directory_path) """ # function : create network # input arg : category number # output : network model # func detail : please following comments """ def create_network(self,category_num): model = Sequential() #Conv2D #input shape(width,height,channel) #filter (3,3) 16channel model.add(Conv2D(32, (3, 3), padding='same',input_shape=(64,64,3))) #Downsamples the input representation by taking the maximum by pool_size model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Activation('relu')) #randomly sets input units to 0, which helps prevent overfitting. model.add(Dropout(0.5)) model.add(Conv2D(64, (3, 3), padding='same')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Conv2D(128, (3, 3), padding='same')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Flatten()) model.add(Dense(400)) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(category_num)) #分類数を決めている model.add(Activation('softmax')) model.summary() return model """ # function : create dataset # input arg : train data path,validation data path # output : train img,train label,validation img,validation label # func detail : please following comments """ def create_dataset(self,train_path,val_path): TrainIMG = [] TrainLABEL = [] ValIMG = [] ValLABEL = [] TestIMG = [] TestLABEL = [] label =0 """ #trainディレクトリ内のディレクトリをリストで取得 train--class1 --class2 --class3 ->[class1,class2,class3] """ img_dirs=os.listdir(train_path) print("img_dirs",img_dirs) for i, d in enumerate(img_dirs):#classごとに画像を読み込んでいく files0 = os.listdir(train_path+ d) files1 = os.listdir(val_path+ d) print(train_path+d)#print->train/class1 print(val_path+d)#print->val/class1 for f0 in files0:#class内の画像を順番に読み込む #load_img->train/class1/picturename.png img1 = img_to_array(load_img(train_path + d + '/' + f0,target_size=(64,64,3))) #train imgのlistに追加 TrainIMG.append(img1) #train labelのlistに追加 TrainLABEL.append(label) for f1 in files1: img2 = img_to_array(load_img(val_path + d + '/' + f1,target_size=(64,64,3))) ValIMG.append(img2) ValLABEL.append(label) #1class読み込みが終わったらlabelをインクリメント #次は,train/class2 を読み込んでいく label = label + 1 print("now:" + img_dirs[i]) #tensor flowの入力に合わせるためにデータを整える TrainIMG = np.asarray(TrainIMG)#np.asarrayに変換 TrainLABEL = np.asarray(TrainLABEL) TrainIMG = TrainIMG.astype('float32')#float32に変換 TrainIMG = TrainIMG / 255.0#0~255に正規化 #ラベルを数値ではなく,0or1を要素に持つベクトルで表現 #ラベルが 1の場合[0, 1, 0] TrainLABEL = np_utils.to_categorical(TrainLABEL, label) ValIMG = np.asarray(ValIMG) ValLABEL = np.asarray(ValLABEL) ValIMG = ValIMG.astype('float32') ValIMG = ValIMG / 255.0 ValLABEL = np_utils.to_categorical(ValLABEL, label) TestIMG = np.asarray(TestIMG) TestLABEL = np.asarray(TestLABEL) TestIMG = TestIMG.astype('float32') TestIMG = TestIMG / 255.0 TestLABEL = np_utils.to_categorical(TestLABEL, label) label=0 print("completed loading the data set") return TrainIMG,TrainLABEL,ValIMG,ValLABEL """ # function : check acc # input arg : test image path,log directory # output : test image predict label, score # func detail : # test image path example test/class1/01.png # /02.png # /03.png # test/class2/01.png # /02.png # /03.png # test/class3/01.png # /02.png # /03.png """ def check_acc(self,model,test_img_path,log_dir): result_count = [] all_count = 0 img_dirs=os.listdir(test_img_path) #test_img_path->test/ #img_dirs->[class1,class2,class3] for i,name in enumerate(img_dirs): result_count.append(0)#classの個数だけresult_contのlistに0を追加 print("\t",end =" ") for j, name in enumerate(img_dirs):#j->countclass,name->[class1,class2,class3] print(img_dirs[j] + "\t",end = "") print("") for i, d in enumerate(img_dirs): files2 = os.listdir(test_img_path + d)#files2->test/class1/ for f2 in files2: test_img = np.array(load_img(test_img_path + d + '/' + f2).resize((64, 64)))#load img->test/class1/01.png result = model.predict_classes(np.array([test_img / 255.]))#normalize and predict all_count = all_count + 1#全カウントをインクリメント for j, name in enumerate(img_dirs):#enumerate(img_dirs)->count of img dirs list->[class1,class2,class3]->0-2までの3(int) if result == j:#result->model predicted class, j->current class label result_count[j] = result_count[j] + 1#予測ラベルと正解ラベルが同じラベルの場合インクリメント #print(result) print(d + "\t",end="") for j, name in enumerate(img_dirs): print("{0:.2f}\t".format(result_count[j]/all_count*100),end="")#正答率を表示 print("") all_count = 0#カウントをリセット  for j, name in enumerate(img_dirs): result_count[j] = 0#カウントをリセット #next->#files2->test/class2/ ##csv形式で各画像の予測ラベルを保存#### f = open(log_dir+'test_img_result.txt', 'w')#open file ->logdir/test_img_result.txt for i, d in enumerate(img_dirs): files2 = os.listdir(test_img_path + d)#test_img_path->test/class1/ for f2 in files2:#f2->[01.png,02.pmg,...] test_img = np.array(load_img(test_img_path + d + '/' + f2).resize((64, 64))) #test_img_path + d + '/' + f2->test/class1/01.png y1 = model.predict(np.array([test_img / 255.])) #判別精度(確率)の表示 y2 = model.predict_classes(np.array([test_img / 255.])) #判別精度(ラベル)の表示 f.write(f2 + "\t" + str(y1) + "\t" + str(y2) +"\n")#write file ->img.name,[判別精度(確率)],#判別精度(ラベル) #print(y) f.close() print("check_accc") """ # function : acc2 # input arg : network model, test img data path, log save directory # output : none # func detail : テスト画像のディレクトリを読み込み,学習したネットワークで分類をする # 各々の正解ラベルに対する正答率を算出する # testdata_architecture :test_img_path->test/class1/ """ def acc2(self,model,test_img_path,log_dir): score=[] test_img_path=test_img_path print(test_img_path) img_dirs=os.listdir(test_img_path)#->[test/class1/00.png,test/class1/01.png,.....] print(img_dirs) for f2 in range(len(img_dirs)): #print(test_img_path+f2) test_img = np.array(load_img(test_img_path + img_dirs[f2]).resize((64, 64))) result = model.predict_classes(np.array([test_img / 255.]))#predict class score.append(result) label0 = [i for i in score if i == 0]#resultのうち0だった場合の個数をカウント label1 = [i for i in score if i == 1] label2 = [i for i in score if i == 2] label3 = [i for i in score if i == 3] print("label0",(len(label0)/len(score))*100)#labelが0/ラベルの総数の割合を表示 print("label1",(len(label1)/len(score))*100) print("label2",(len(label2)/len(score))*100) print("label3",(len(label3)/len(score))*100) #print(score) return def sayStr(self, str): print (str) if __name__ == '__main__': test = myutil() test.sayStr("Hello") # Hello
7,664
0
157
fc29640972c3d6c009959460f4b241cb149acfc7
2,735
py
Python
src/ndn/bin/sec/cmd_new_item.py
tianyuan129/python-ndn
f390b3122d2a233a9a22a1ee9468b1241c46ef86
[ "Apache-2.0" ]
5
2019-10-03T01:26:43.000Z
2020-07-07T15:21:52.000Z
src/ndn/bin/sec/cmd_new_item.py
tianyuan129/python-ndn
f390b3122d2a233a9a22a1ee9468b1241c46ef86
[ "Apache-2.0" ]
12
2019-10-28T03:17:16.000Z
2020-08-26T22:10:52.000Z
src/ndn/bin/sec/cmd_new_item.py
tianyuan129/python-ndn
f390b3122d2a233a9a22a1ee9468b1241c46ef86
[ "Apache-2.0" ]
10
2019-10-18T21:16:43.000Z
2021-06-24T07:26:22.000Z
# ----------------------------------------------------------------------------- # Copyright (C) 2019-2021 The python-ndn authors # # This file is part of python-ndn. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ----------------------------------------------------------------------------- import argparse from ...encoding import Name from .utils import resolve_keychain, infer_obj_name
40.820896
99
0.595978
# ----------------------------------------------------------------------------- # Copyright (C) 2019-2021 The python-ndn authors # # This file is part of python-ndn. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ----------------------------------------------------------------------------- import argparse from ...encoding import Name from .utils import resolve_keychain, infer_obj_name def add_parser(subparsers): parser = subparsers.add_parser('New-Item', aliases=['key-gen', 'ni', 'new-item']) parser.add_argument('-t', '--type', metavar='TYPE', default='e', choices=['e', 'r'], help="key type: 'r' for RSA, 'e' for ECDSA (default: e)") parser.add_argument('-k', '--keyid-type', metavar='KEYIDTYPE', default='r', choices=['h', 'r'], help="key id type: 'h' for the SHA-256 of the public key, " "'r' for a 64-bit random number (the default unless " "a key name is specified for OBJECT)") parser.add_argument('obj', metavar='OBJECT', help='identity/key name') parser.set_defaults(executor=execute) def execute(args: argparse.Namespace): kc = resolve_keychain(args) obj_name = Name.from_str(args.obj) _, id_name, key_name, cert_name = infer_obj_name(obj_name) # New identity try: iden = kc[id_name] except KeyError: iden = kc.new_identity(id_name) print(f'Created new identity: {Name.to_str(id_name)}') # New key if key_name: try: _ = iden[key_name] print(f'Specified key already exists: {Name.to_str(key_name)}') return -2 except KeyError: key = None else: key = None if key is None: key_type = 'ec' if args.type == 'e' else 'rsa' if key_name: key = kc.new_key(id_name, key_type, key_id=key_name[-1]) else: key_id_type = 'sha256' if args.keyid_type == 'h' else 'random' key = kc.new_key(id_name, key_type, key_id_type=key_id_type) key_name = key.name print(f'Created new key: {Name.to_str(key_name)}') print(f'With self-signed certificate: {Name.to_str(key.default_cert().name)}')
1,798
0
46
4b1b7c995699f7c87327dc61ab60c9ce63683dd7
748
py
Python
tests/settings.py
vincenz-e/django-paydirekt
eda3b23c27f0a5a78d5a2a91e4083dab75f2f01f
[ "MIT" ]
4
2017-04-19T15:01:24.000Z
2021-08-23T07:26:18.000Z
tests/settings.py
vincenz-e/django-paydirekt
eda3b23c27f0a5a78d5a2a91e4083dab75f2f01f
[ "MIT" ]
2
2019-04-03T13:44:51.000Z
2019-07-22T10:19:06.000Z
tests/settings.py
vincenz-e/django-paydirekt
eda3b23c27f0a5a78d5a2a91e4083dab75f2f01f
[ "MIT" ]
2
2019-04-03T08:08:28.000Z
2019-07-22T00:32:05.000Z
# Django settings for testproject project. from django.conf import settings settings.configure( ALLOWED_HOSTS=['*'], DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:' } }, ROOT_URLCONF='tests.test_urls', INSTALLED_APPS=( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.staticfiles', 'django_paydirekt', 'tests', ), PAYDIREKT=True, PAYDIREKT_ROOT_URL='http://example.com', PAYDIREKT_API_KEY="e81d298b-60dd-4f46-9ec9-1dbc72f5b5df", PAYDIREKT_API_SECRET="GJlN718sQxN1unxbLWHVlcf0FgXw2kMyfRwD0mgTRME=", )
24.933333
72
0.629679
# Django settings for testproject project. from django.conf import settings settings.configure( ALLOWED_HOSTS=['*'], DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:' } }, ROOT_URLCONF='tests.test_urls', INSTALLED_APPS=( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.staticfiles', 'django_paydirekt', 'tests', ), PAYDIREKT=True, PAYDIREKT_ROOT_URL='http://example.com', PAYDIREKT_API_KEY="e81d298b-60dd-4f46-9ec9-1dbc72f5b5df", PAYDIREKT_API_SECRET="GJlN718sQxN1unxbLWHVlcf0FgXw2kMyfRwD0mgTRME=", )
0
0
0
d77ccb5ed65ceadf95c5aa7f2d4204c73111466c
749
py
Python
eye_video.py
Berkeley-BORIS/BORIS_FileBrowser
5742a7686b0aa7b3dccad71ecd39bc640346a1df
[ "MIT" ]
null
null
null
eye_video.py
Berkeley-BORIS/BORIS_FileBrowser
5742a7686b0aa7b3dccad71ecd39bc640346a1df
[ "MIT" ]
null
null
null
eye_video.py
Berkeley-BORIS/BORIS_FileBrowser
5742a7686b0aa7b3dccad71ecd39bc640346a1df
[ "MIT" ]
null
null
null
import subprocess import os from glob import glob import cv2 # def printnow(s): # sys. tempdir= './temp_for_video' if os.path.exists(tempdir): print "Removing temp_for_video directory" subprocess.call('rm -rf {0}'.format(tempdir), shell=True) print "Creating temp_for_video directory" os.mkdir(tempdir) ims = glob('*.png') ims.sort() for i, imname in enumerate(ims): im = cv2.imread(imname, cv2.CV_LOAD_IMAGE_GRAYSCALE) cv2.imwrite('{0}/img{1:0>5}.png'.format(tempdir, i+1), im) if (i+1) % 100 == 0: print "Image", i+1 cmd = r"ffmpeg -f image2 -r 30 -q:v 2 -i ./temp_for_video/img%05d.png -y ./eye_video.mp4" print cmd subprocess.call(cmd, shell=True) subprocess.call('rm -rf {0}'.format(tempdir), shell=True)
24.16129
89
0.682243
import subprocess import os from glob import glob import cv2 # def printnow(s): # sys. tempdir= './temp_for_video' if os.path.exists(tempdir): print "Removing temp_for_video directory" subprocess.call('rm -rf {0}'.format(tempdir), shell=True) print "Creating temp_for_video directory" os.mkdir(tempdir) ims = glob('*.png') ims.sort() for i, imname in enumerate(ims): im = cv2.imread(imname, cv2.CV_LOAD_IMAGE_GRAYSCALE) cv2.imwrite('{0}/img{1:0>5}.png'.format(tempdir, i+1), im) if (i+1) % 100 == 0: print "Image", i+1 cmd = r"ffmpeg -f image2 -r 30 -q:v 2 -i ./temp_for_video/img%05d.png -y ./eye_video.mp4" print cmd subprocess.call(cmd, shell=True) subprocess.call('rm -rf {0}'.format(tempdir), shell=True)
0
0
0
98225817872599faceaca882fac6b82b284be004
17,867
py
Python
fowt_force_gen/moortune.py
SoftwareDevEngResearch/fowt-force-gen
abfda75edf31ee7018ceec0e48b2b24e7ee350eb
[ "MIT" ]
null
null
null
fowt_force_gen/moortune.py
SoftwareDevEngResearch/fowt-force-gen
abfda75edf31ee7018ceec0e48b2b24e7ee350eb
[ "MIT" ]
null
null
null
fowt_force_gen/moortune.py
SoftwareDevEngResearch/fowt-force-gen
abfda75edf31ee7018ceec0e48b2b24e7ee350eb
[ "MIT" ]
null
null
null
from fowt_force_gen import run_fast from fowt_force_gen import filegen from fowt_force_gen import parse import math import numpy as np import os import argparse def tune(water_depth, platform, output_moordyn_filename): """ Using metocean and platform information, generates MoorDyn .dat files with a properly tuned and positioned mooring system so rigid body modes and frequencies match those specified in the NREL platform definition. Contains subfunctions to: 1) Identify proper anchor coordinate (get_positions) 2) Approximate the necessary mooring line length needed in a catenary mooring system to prevent vertical force acting on the anchor (tune_rough) 3) Fine tune the mooring line length so the free decay response of the platform matches that of the NREL platform definition (tune_fine) Parameters: water_depth is an integer or float specifying the depth of the particular location of the floating platform platform is a string specifying which platform definition to use. Currently, the two options for this are 'OC3', which selects the OC3-Hywind spar buoy platform, or 'OC4', which selects the OC4-DeepCwind semisubmersible platform. output_moordyn_filename is a string specifying the desired name of the generated MoorDyn DAT file. """ mooring = Mooring(water_depth, platform) initial_line_length = mooring.tune_rough() mooring.tune_fine(initial_line_length, output_moordyn_filename) if __name__ == '__main__': main()
52.705015
130
0.643477
from fowt_force_gen import run_fast from fowt_force_gen import filegen from fowt_force_gen import parse import math import numpy as np import os import argparse def tune(water_depth, platform, output_moordyn_filename): """ Using metocean and platform information, generates MoorDyn .dat files with a properly tuned and positioned mooring system so rigid body modes and frequencies match those specified in the NREL platform definition. Contains subfunctions to: 1) Identify proper anchor coordinate (get_positions) 2) Approximate the necessary mooring line length needed in a catenary mooring system to prevent vertical force acting on the anchor (tune_rough) 3) Fine tune the mooring line length so the free decay response of the platform matches that of the NREL platform definition (tune_fine) Parameters: water_depth is an integer or float specifying the depth of the particular location of the floating platform platform is a string specifying which platform definition to use. Currently, the two options for this are 'OC3', which selects the OC3-Hywind spar buoy platform, or 'OC4', which selects the OC4-DeepCwind semisubmersible platform. output_moordyn_filename is a string specifying the desired name of the generated MoorDyn DAT file. """ mooring = Mooring(water_depth, platform) initial_line_length = mooring.tune_rough() mooring.tune_fine(initial_line_length, output_moordyn_filename) class Mooring: def __init__(self, water_depth, platform): self.water_depth = water_depth if platform.lower() == 'oc3': self.line_massden = .0777066 self.line_diameter = 90 self.template_rough_moordyn_file = 'template_files/OC3Hywind_MoorDyn_rough_template.dat' self.template_fine_moordyn_file = 'template_files/OC3Hywind_MoorDyn_fine_template.dat' self.template_hydro_file = 'template_files/OC3Hywind_HydroDyn_template.dat' self.template_rough_elasto_file = 'tuning_files/OC3Hywind_tuning_rough_ElastoDyn.dat' self.template_fine_elasto_file = 'tuning_files/OC3Hywind_tuning_fine_ElastoDyn.dat' self.template_rough_fst_file = 'tuning_files/OC3Hywind_tuning_rough.fst' self.template_fine_fst_file = 'tuning_files/OC3Hywind_tuning_fine.fst' self.baseline_outb_file = 'tuning_files/OC3Hywind_tuning_baseline.outb' self.line_angles = np.array([0., 120., 240.]) self.fairlead_x = np.array([5.2, -2.6, -2.6]) self.fairlead_y = np.array([0., 4.5, -4.5]) self.fairlead_z = -70 elif platform.lower() == 'oc4': self.line_massden = .11335 self.line_diameter = 76.6 self.template_rough_moordyn_file = 'template_files/OC4Semi_MoorDyn_rough_template.dat' self.template_fine_moordyn_file = 'template_files/OC4Semi_MoorDyn_fine_template.dat' self.template_hydro_file = 'template_files/OC4Semi_HydroDyn_template.dat' self.template_rough_elasto_file = 'tuning_files/OC4Semi_tuning_rough_ElastoDyn.dat' self.template_fine_elasto_file = 'tuning_files/OC4Semi_tuning_fine_ElastoDyn.dat' self.template_rough_fst_file = 'tuning_files/OC4Semi_tuning_rough.fst' self.template_fine_fst_file = 'tuning_files/OC4Semi_tuning_fine.fst' self.baseline_outb_file = 'tuning_files/OC4Semi_tuning_baseline.outb' self.line_angles= np.array([60., 180., 300.]) self.fairlead_x = np.array([20.434, -40.868, 20.434]) self.fairlead_y = np.array([35.393, 0., -35.393]) self.fairlead_z = -14 else: raise ValueError("Platform type not recognized. Please specify either 'OC3' or 'OC4'.") self.anchor_x, self.anchor_y = self.get_positions() def tune_fine(self, initial_line_length, output_moordyn_filename): """ Determines the exact starting point for UnstrLen parameter in MoorDyn by iteratively increasing the length until the platform decay frequency matches that of the NREL platform baseline """ baseline_time, baseline_surge = self.get_decay_data(self.baseline_outb_file) line_length = initial_line_length # Run OpenFAST and see if surge decay frequency is identical to baseline. If not, alter line length and repeat. tuned = False prev_max_errors = [] # TODO: figure out why the second iteration (and ONLY the second iteration) of tuning always makes it worse while not tuned: self.update_tuning_inputs(line_length, test='fine', md_filename=output_moordyn_filename) run_fast.run_fast('fine_temp.fst') test_time, test_surge = self.get_decay_data('fine_temp.outb') freq_error = self.compare_zero_crossings(baseline_time, test_time, baseline_surge, test_surge) tuned, line_adjust = self.check_fine_tuning(freq_error, prev_max_errors) line_length = round(line_length + line_adjust, 3) freq_error_magnitude = [round(abs(errors), 3) for errors in freq_error] prev_max_errors.append(round(freq_error[freq_error_magnitude.index(max(freq_error_magnitude))], 3)) print(line_length) # If system is properly tuned, remove all the temporary OpenFAST files print('Mooring system tuned. Unstretched mooring line length is ' + str(line_length)) os.remove('fine_temp.fst') os.remove('fine_temp.outb') os.remove('fine_temp.MD.out') os.remove('fine_temp.MD.Line1.out') os.remove('fine_temp.MD.Line2.out') os.remove('fine_temp.MD.Line3.out') os.remove('hydrodyn_fine_temp.dat') def tune_rough(self): """ Determines the rough starting point for UnstrLen parameter in MoorDyn by iteratively increasing the length until there is no uplift force next to the anchor point. The procedure used in this is based on research by Kim et al. in 'Design of Mooring Lines of Floating Offshore Wind Turbine in Jeju Offshore Area', 2014. The MoorDyn file used should be outputting 'L1N1PZ', 'L2N1PZ', and 'L3N1PZ' parameters. """ initial_line_length = self.get_initial_line_length() # Run OpenFAST and see if uplift force on all anchors is zero. If not, increase line length and repeat. no_uplift = False while not no_uplift: # Update MoorDyn and .fst file self.update_tuning_inputs(initial_line_length, test='rough') # Run OpenFAST run_fast.run_fast('rough_temp.fst') # Check uplift forces on all anchors and increase line length if needed. If all nodes on all lines are on # the seabed, stop looping. if self.check_rough_tuning('rough_temp.outb'): os.remove('moordyn_temp.dat') os.remove('hydrodyn_rough_temp.dat') os.remove('rough_temp.fst') os.remove('rough_temp.outb') os.remove('rough_temp.MD.out') no_uplift = True else: initial_line_length = initial_line_length + 5 print('Rough mooring tuning complete.') return initial_line_length def get_positions(self): """ Places the anchor points in the correct location to make it proportional to the baseline setup, even if the water depth has changed. The procedure used in this is based on research by Kim et al. in 'Design of Mooring Lines of Floating Offshore Wind Turbine in Jeju Offshore Area', 2014 """ # Proof load of mooring line (assumes chain) t_max = 0.0156 * self.line_diameter ** 2. * (44. - 0.08 * self.line_diameter) # Vertical distance from fairlead to anchor TODO integrate this with unit testing # vert_line_distance = self.water_depth - self.fairlead_z # Horizontal distance between fairlead and anchor hor_anchor_distance = ((t_max - self.line_massden*self.water_depth)/self.line_massden) *\ math.acosh(1+self.water_depth*(self.line_massden/(t_max-self.line_massden*self.water_depth))) anchor_x = np.zeros(len(self.line_angles)) anchor_y = np.zeros(len(self.line_angles)) for idx in np.arange(len(self.line_angles)): anchor_x[idx] = self.fairlead_x[idx] + hor_anchor_distance * math.cos(math.radians(self.line_angles[idx])) anchor_x[idx] = round(anchor_x[idx], 3) anchor_y[idx] = self.fairlead_y[idx] + hor_anchor_distance * math.sin(math.radians(self.line_angles[idx])) anchor_y[idx] = round(anchor_y[idx], 3) print('Anchor positions identified.') return anchor_x, anchor_y def get_initial_line_length(self): # Proof load of mooring line (assumes chain) t_max = 0.0156 * self.line_diameter ** 2. * (44. - 0.08 * self.line_diameter) # Vertical distance from fairlead to anchor TODO integrate this with unit testing # vert_line_distance = self.water_depth - self.fairlead_z # Initial line length estimate used in Kim et al. initial_line_length = self.water_depth * math.sqrt(2. * (t_max / (self.line_massden * self.water_depth)) - 1.) initial_line_length = round(initial_line_length, 3) return initial_line_length def update_tuning_inputs(self, line_length, test='rough', md_filename=None): """ Updates necessary input files for a tuning test. ARGUMENTS line_length: the unstretched mooring line length to be used for the input files. test: specified as either 'rough' or 'fine' to denote whether to create the tuning input files in the format needed for tune_rough or tune_fine, as these differ somewhat. It is set to 'rough' by default. md_filename: name of the MoorDyn input file to be created. Unused if test='rough'. """ if test.lower() == 'rough': filegen.moordyn_filegen(self.template_rough_moordyn_file, 'moordyn_temp.dat', UnstrLen={'1': str(line_length), '2': str(line_length), '3': str(line_length)}, X={'1': str(self.anchor_x[0]), '2': str(self.anchor_x[1]), '3': str(self.anchor_x[2])}, Y={'1': str(self.anchor_y[0]), '2': str(self.anchor_y[1]), '3': str(self.anchor_y[2])}, Z={'1': str(-self.water_depth), '2': str(-self.water_depth), '3': str(-self.water_depth)}) filegen.filegen(self.template_hydro_file, 'hydrodyn_rough_temp.dat', WtrDpth=str(self.water_depth), WaveMod='0') filegen.filegen(str(self.template_rough_fst_file), 'rough_temp.fst', EDFile='"'+str(self.template_rough_elasto_file)+'"', HydroFile='"hydrodyn_rough_temp.dat"', MooringFile='"moordyn_temp.dat"') elif test.lower() == 'fine': if not md_filename or not isinstance(md_filename, str): raise AttributeError('To use update_tuning_inputs for fine tuning, output_moordyn_filename' 'must be specified as a string with a .dat file extension') else: filegen.moordyn_filegen(self.template_fine_moordyn_file, md_filename, UnstrLen={'1': str(line_length), '2': str(line_length), '3': str(line_length)}, X={'1': str(self.anchor_x[0]), '2': str(self.anchor_x[1]), '3': str(self.anchor_x[2])}, Y={'1': str(self.anchor_y[0]), '2': str(self.anchor_y[1]), '3': str(self.anchor_y[2])}, Z={'1': str(-self.water_depth), '2': str(-self.water_depth), '3': str(-self.water_depth)}) filegen.filegen(self.template_hydro_file, 'hydrodyn_fine_temp.dat', WtrDpth=str(self.water_depth), WaveMod='0') filegen.filegen(str(self.template_fine_fst_file), 'fine_temp.fst', EDFile='"'+str(self.template_fine_elasto_file)+'"', HydroFile='"hydrodyn_fine_temp.dat"', MooringFile='"'+str(md_filename)+'"') else: raise ValueError("Value of test not recognized. Specify either 'rough' or 'fine'") def check_rough_tuning(self, outb_file): line_data = parse.get_param_data(outb_file, ['L1N1PZ', 'L2N1PZ', 'L3N1PZ']) tuned = ((line_data[:, 1:3] <= -self.water_depth).sum() == line_data[:, 1:3].size).astype(np.float) if tuned: return True else: return False def get_decay_data(self, outb_file): output_data = parse.get_param_data(outb_file, ['Time', 'PtfmSurge']) time = output_data[:, 0] surge = output_data[:, 1] return time, surge def compare_zero_crossings(self, baseline_time, test_time, baseline_surge, test_surge): """ Implicitly determines the difference in free decay frequency (in surge) of a tested platform with its baseline values determined in the platform definition. Returns a list containing the time errors between each zero crossing between the test platform and the baseline platform. """ baseline_crossings = np.where(np.diff(np.signbit(baseline_surge)))[0] test_crossings = np.where(np.diff(np.signbit(test_surge)))[0] if len(baseline_crossings) <= len(test_crossings): num_checks = len(baseline_crossings) else: num_checks = len(test_crossings) freq_error = np.zeros(num_checks) for idx in np.arange(num_checks): freq_error[idx] = baseline_time[baseline_crossings[idx]] - test_time[test_crossings[idx]] return freq_error def check_fine_tuning(self, freq_error, prev_max_errors): """ Determines if a given error between the baseline and tested free decay frequency is within acceptable bounds, and determines the necessary line adjustment if not. The change in mooring line length is inversely proportional to change in platform decay frequency. If the current frequency is too low, decrease line length, and vice versa. The higher the frequency error, the greater the adjustment. ARGUMENTS freq_error: list of floats containing the time errors between the zero crossing points between the test platform and the baseline platform. prev_max_errors: list of floats containing the maximum time errors between the two platforms from previous tests. This is used to identify if the tuning is stuck 'flip-flopping' back and forth between two values and correct it. If this is the first test, use an empty list instead. """ print(freq_error) print(prev_max_errors) freq_error_magnitude = [round(abs(errors), 3) for errors in freq_error] if round(freq_error[freq_error_magnitude.index(max(freq_error_magnitude))], 3) in prev_max_errors: flipflop_error = True else: flipflop_error = False if max(freq_error_magnitude) <= .5: line_adjust = 0 tuned = True elif .5 < max(freq_error_magnitude) <= 3: tuned = False if flipflop_error is True: line_adjust = .125 else: line_adjust = round(max(freq_error_magnitude)/8, 3) elif 3 < max(freq_error_magnitude) <= 5: tuned = False if flipflop_error is True: line_adjust = .25 else: line_adjust = round(max(freq_error_magnitude)/10, 3) elif 5 < max(freq_error_magnitude) <= 8: tuned = False if flipflop_error is True: line_adjust = 1 else: line_adjust = round(max(freq_error_magnitude)/12, 3) elif 8 < max(freq_error_magnitude) <= 50: tuned = False if flipflop_error is True: line_adjust = 2 else: line_adjust = round(max(freq_error_magnitude)/14, 3) elif 50 < max(freq_error_magnitude) <= 100: tuned = False if flipflop_error is True: line_adjust = 3 else: line_adjust = round(max(freq_error_magnitude)/16, 3) elif max(freq_error_magnitude) > 100: tuned = False if flipflop_error is True: line_adjust = 4 else: line_adjust = 8 if freq_error[freq_error_magnitude.index(max(freq_error_magnitude))] < 0: line_adjust = -line_adjust print(line_adjust) return tuned, line_adjust def main(): parser = argparse.ArgumentParser(description='Generates MoorDyn file with proper line length and anchor placement' 'for the specified platform type and water depth') parser.add_argument('-d', '--depth', type=float, required=True, help='Water depth at desired platform site') parser.add_argument('-pf', '--platform', type=str, required=True, help='Platform type; either OC3 or OC4 (i.e. Hywind or DeepCwind)') parser.add_argument('-fn', '--filename', type=str, required=True, help='Desired filename of output MoorDyn file') args = parser.parse_args() tune(args.depth, args.platform, args.filename) if __name__ == '__main__': main()
4,092
12,162
46
bff8917d6740c51bfa4e08081e7c2fe235de40e8
1,697
py
Python
helpers.py
mikeehun/mattermost-bitbucket-bridge
d231cbd4cf1e73c107ce6e1b07c2a7dea190b262
[ "MIT" ]
null
null
null
helpers.py
mikeehun/mattermost-bitbucket-bridge
d231cbd4cf1e73c107ce6e1b07c2a7dea190b262
[ "MIT" ]
null
null
null
helpers.py
mikeehun/mattermost-bitbucket-bridge
d231cbd4cf1e73c107ce6e1b07c2a7dea190b262
[ "MIT" ]
1
2019-04-18T15:12:25.000Z
2019-04-18T15:12:25.000Z
""" Dictionary of supported Bitbucket events and output friendly format """ bitbucket_server_event_names = { "pr:comment:added": "Pull Request: Comment Added", "pr:comment:deleted": "Pull Request: Comment Deleted", "pr:comment:edited": "Pull Request: Comment Edited", "pr:opened": "Pull Request: Opened", "pr:declined": "Pull Request: Declined", "pr:deleted": "Pull Request: Deleted", "pr:merged": "Pull Request: Merged", "pr:modified": "Pull Request: Modified", "pr:approved": "Pull Request: Approved", "pr:unapproved": "Pull Request: Unapproved", "repo:refs_changed": "Repository: Updated", "repo:comment:added": "Repository: Commit Comment Added", "repo:comment:edited": "Repository: Commit Comment Edited", "repo:comment:deleted": "Repository: Commit Comment Deleted", "repo:commit_comment_created": "Repository: Commit Comment Added", "repo:forked": "Repository: Forked" } bitbucket_cloud_event_actions = { "pullrequest:created": "{} created pull request {}", "pullrequest:updated": "{} updated pull request {}", "pullrequest:approved": ":thumbsup: {} approved pull request {}", "pullrequest:unapproved": "{} unapproved pull request {}", "pullrequest:merged": ":tada: {} merged pull request {}", "pullrequest:declined": "{} declined pull request {}", "pullrequest:deleted": "{} deleted pull request {}", "pullrequest:comment_created": "{} added a comment to pull request {}", "pullrequest:comment_updated": "{} updated a comment to pull request {}", "pullrequest:comment_deleted": "{} deleted a comment to pull request {}", "repo:push": "{} Repository: Code changes pushed by: {}" }
47.138889
77
0.677666
""" Dictionary of supported Bitbucket events and output friendly format """ bitbucket_server_event_names = { "pr:comment:added": "Pull Request: Comment Added", "pr:comment:deleted": "Pull Request: Comment Deleted", "pr:comment:edited": "Pull Request: Comment Edited", "pr:opened": "Pull Request: Opened", "pr:declined": "Pull Request: Declined", "pr:deleted": "Pull Request: Deleted", "pr:merged": "Pull Request: Merged", "pr:modified": "Pull Request: Modified", "pr:approved": "Pull Request: Approved", "pr:unapproved": "Pull Request: Unapproved", "repo:refs_changed": "Repository: Updated", "repo:comment:added": "Repository: Commit Comment Added", "repo:comment:edited": "Repository: Commit Comment Edited", "repo:comment:deleted": "Repository: Commit Comment Deleted", "repo:commit_comment_created": "Repository: Commit Comment Added", "repo:forked": "Repository: Forked" } bitbucket_cloud_event_actions = { "pullrequest:created": "{} created pull request {}", "pullrequest:updated": "{} updated pull request {}", "pullrequest:approved": ":thumbsup: {} approved pull request {}", "pullrequest:unapproved": "{} unapproved pull request {}", "pullrequest:merged": ":tada: {} merged pull request {}", "pullrequest:declined": "{} declined pull request {}", "pullrequest:deleted": "{} deleted pull request {}", "pullrequest:comment_created": "{} added a comment to pull request {}", "pullrequest:comment_updated": "{} updated a comment to pull request {}", "pullrequest:comment_deleted": "{} deleted a comment to pull request {}", "repo:push": "{} Repository: Code changes pushed by: {}" }
0
0
0
108c8e8ba849b9944dfb5dfed567e85d38231b86
249
py
Python
tests/box_test.py
drichmond/IPICO-Open-Source
bbb7b7f800edd524caba1f89394236f32e05e02e
[ "Apache-2.0" ]
3
2018-02-13T17:54:58.000Z
2020-12-30T04:07:48.000Z
tests/box_test.py
drichmond/IPICO-Open-Source
bbb7b7f800edd524caba1f89394236f32e05e02e
[ "Apache-2.0" ]
null
null
null
tests/box_test.py
drichmond/IPICO-Open-Source
bbb7b7f800edd524caba1f89394236f32e05e02e
[ "Apache-2.0" ]
null
null
null
#!/usr/local/bin/python3.6 from ipico.reader import BoxReader if __name__ == '__main__': main()
14.647059
45
0.590361
#!/usr/local/bin/python3.6 from ipico.reader import BoxReader def main(): # read a data packet data = None seq = 0 rdr = BoxReader('Finish', '192.168.2.34') for s in rdr: print(s) if __name__ == '__main__': main()
125
0
22
d22419bb2ffe084bb952a6ac2539d7f55fc18699
450
py
Python
leetcode-life/linkedlist/NO_141_linked_list_cycle_easy.py
sunrong1990/PythonLife
ce288e4fcccc76cd647c80f47f83bf16117269ba
[ "MIT" ]
null
null
null
leetcode-life/linkedlist/NO_141_linked_list_cycle_easy.py
sunrong1990/PythonLife
ce288e4fcccc76cd647c80f47f83bf16117269ba
[ "MIT" ]
null
null
null
leetcode-life/linkedlist/NO_141_linked_list_cycle_easy.py
sunrong1990/PythonLife
ce288e4fcccc76cd647c80f47f83bf16117269ba
[ "MIT" ]
null
null
null
from myLinkedList import *
21.428571
47
0.482222
from myLinkedList import * class Solution: def hasCycle(self, head: ListNode) -> bool: """ 方法1,快慢指针 链表中环的判断 :param head: :return: """ if not head: return False slow, fast = head, head while fast and fast.next: slow = slow.next fast = fast.next.next if slow and slow == fast: return True return False
0
427
23
8714de68982283bcaeff5e6a0b71251d452dbab8
1,873
py
Python
tests/x7/lib/test_shell_tools.py
gribbg/x7-lib
1ec5807d2c85d522a9f678f995d0f2fe42735d18
[ "BSD-2-Clause" ]
null
null
null
tests/x7/lib/test_shell_tools.py
gribbg/x7-lib
1ec5807d2c85d522a9f678f995d0f2fe42735d18
[ "BSD-2-Clause" ]
null
null
null
tests/x7/lib/test_shell_tools.py
gribbg/x7-lib
1ec5807d2c85d522a9f678f995d0f2fe42735d18
[ "BSD-2-Clause" ]
null
null
null
# Originally auto-generated on 2021-02-15-12:14:36 -0500 EST # By '--verbose --verbose x7.lib.shell_tools' from unittest import TestCase from x7.lib.annotations import tests from x7.testing.support import Capture from x7.lib import shell_tools from x7.lib.shell_tools_load import ShellTool @tests(shell_tools) class TestModShellTools(TestCase): """Tests for stand-alone functions in x7.lib.shell_tools module""" @tests(shell_tools.Dir) @tests(shell_tools.help) @tests(shell_tools.help) @tests(shell_tools.tools)
36.019231
74
0.662573
# Originally auto-generated on 2021-02-15-12:14:36 -0500 EST # By '--verbose --verbose x7.lib.shell_tools' from unittest import TestCase from x7.lib.annotations import tests from x7.testing.support import Capture from x7.lib import shell_tools from x7.lib.shell_tools_load import ShellTool @tests(shell_tools) class TestModShellTools(TestCase): """Tests for stand-alone functions in x7.lib.shell_tools module""" @tests(shell_tools.Dir) def test_dir(self): self.assertIn('__init__', dir(self)) self.assertNotIn('__init__', shell_tools.Dir(self)) self.assertIn('test_dir', shell_tools.Dir(self)) @tests(shell_tools.help) def test_help(self): with Capture() as orig: help(shell_tools.Dir) with Capture() as modified: shell_tools.help(shell_tools.Dir) self.assertEqual(orig.stdout(), modified.stdout()) self.assertIn('Like dir(v), but only non __ names', orig.stdout()) st_dir = ShellTool('Dir', shell_tools.Dir) with Capture() as as_shell_tool: shell_tools.help(st_dir) self.assertEqual(orig.stdout(), as_shell_tool.stdout()) self.assertNotIn('__init__', as_shell_tool.stdout()) with Capture() as orig_as_shell_tool: help(st_dir) self.assertIn('__init__', orig_as_shell_tool.stdout()) @tests(shell_tools.help) def test_help_on_help(self): with Capture() as orig: help(help) with Capture() as modified: shell_tools.help(ShellTool('help', shell_tools.help)) self.assertEqual(orig.stdout(), modified.stdout()) @tests(shell_tools.tools) def test_tools(self): with Capture() as out: shell_tools.tools() self.assertIn('Help for tools', out.stdout()) self.assertGreaterEqual(out.stdout().count('\n'), 5)
1,230
0
104
1619fbea4d2721b8f99f0b77fee06159cd5d23ad
1,560
py
Python
challenges/graph/graph/tests/test_graph.py
nsinner1/data-structures-and-algorithms-python
6c15d3805ba052d6b884c8ddae1c926d81b97118
[ "MIT" ]
null
null
null
challenges/graph/graph/tests/test_graph.py
nsinner1/data-structures-and-algorithms-python
6c15d3805ba052d6b884c8ddae1c926d81b97118
[ "MIT" ]
null
null
null
challenges/graph/graph/tests/test_graph.py
nsinner1/data-structures-and-algorithms-python
6c15d3805ba052d6b884c8ddae1c926d81b97118
[ "MIT" ]
null
null
null
import pytest from graph.graph import Graph, Vertex, Edge, Queue
22.285714
50
0.665385
import pytest from graph.graph import Graph, Vertex, Edge, Queue def test_add_graph(): graph = Graph() assert graph def test_add_vertex(): graph = Graph() vertex = graph.add_vertex('spam') assert vertex.value == 'spam' def test_add_edge(): graph = Graph() spam = graph.add_vertex('spam') egg = graph.add_vertex('eggs') graph.add_edge(spam, egg) assert True def test_add_edge_test_size_pass(): graph = Graph() spam = graph.add_vertex('spam') egg = graph.add_vertex('eggs') graph.add_edge(spam, egg) assert len(graph.adjacency_list) == 2 def test_add_edge_test_size_fail(): graph = Graph() spam = graph.add_vertex('spam') egg = graph.add_vertex('eggs') graph.add_edge(spam, egg) assert len(graph.adjacency_list) != 3 def test_edge_start_node_not_in_graph(): graph = Graph() start = Vertex('start') end = graph.add_vertex('end') with pytest.raises(KeyError): graph.add_edge(start, end) def test_edge_end_node_not_in_graph(): graph = Graph() end = Vertex('end') start = graph.add_vertex('start') with pytest.raises(KeyError): graph.add_edge(start, end) def test_get_neighbors_no_neighbors(): graph = Graph() spam = graph.add_vertex('spam') neighbors = graph.get_neighbors(spam) assert len(neighbors) == 0 assert neighbors == [] def test_breadth_first_empty_graph(): graph = Graph() spam = Vertex("spam") with pytest.raises(ValueError): vertices_lst = graph.breadth_first(spam)
1,278
0
207
2620b6b9400f88f53b3ed2fe084239f6a699e5d3
432
py
Python
semantic_querying.py
Haoyu-R/How-to-Manage-TinyML-at-Scale
da05a79f3abdaf476b73a4b7c689468c951bb364
[ "MIT" ]
1
2022-02-22T01:32:50.000Z
2022-02-22T01:32:50.000Z
semantic_querying.py
Haoyu-R/How-to-Manage-TinyML-at-Scale
da05a79f3abdaf476b73a4b7c689468c951bb364
[ "MIT" ]
null
null
null
semantic_querying.py
Haoyu-R/How-to-Manage-TinyML-at-Scale
da05a79f3abdaf476b73a4b7c689468c951bb364
[ "MIT" ]
null
null
null
from SPARQLWrapper import SPARQLWrapper, JSON from sparql_queries import * import json # Put the repository URL from Graph DB here sparql = SPARQLWrapper(r"http://192.168.1.106:7200/repositories/tinyml2022_v2") # Put the query here sparql.setQuery(query_1) sparql.setReturnFormat(JSON) results = sparql.query().convert() # Print out the result for result in results["results"]["bindings"]: print(json.dumps(result, indent=4))
28.8
79
0.773148
from SPARQLWrapper import SPARQLWrapper, JSON from sparql_queries import * import json # Put the repository URL from Graph DB here sparql = SPARQLWrapper(r"http://192.168.1.106:7200/repositories/tinyml2022_v2") # Put the query here sparql.setQuery(query_1) sparql.setReturnFormat(JSON) results = sparql.query().convert() # Print out the result for result in results["results"]["bindings"]: print(json.dumps(result, indent=4))
0
0
0
f5a48c2673e686fc065e294695731a83dc05584c
4,015
py
Python
lnk/googl/command.py
goldsborough/lnk
1487d272a70329571c77c0ec17c394dc6a1d088f
[ "MIT" ]
3
2017-06-16T18:51:54.000Z
2018-04-08T19:36:12.000Z
lnk/googl/command.py
goldsborough/lnk
1487d272a70329571c77c0ec17c394dc6a1d088f
[ "MIT" ]
2
2021-02-08T20:17:54.000Z
2021-04-30T20:35:44.000Z
lnk/googl/command.py
goldsborough/lnk
1487d272a70329571c77c0ec17c394dc6a1d088f
[ "MIT" ]
1
2019-11-06T19:05:30.000Z
2019-11-06T19:05:30.000Z
#!/usr/bin/env python #! -*- coding: utf-8 -*- """Contains the base-class for all goo.gl commands.""" import apiclient.discovery import googleapiclient.errors import httplib2 import oauth2client.file import os import lnk.config import lnk.errors from lnk.abstract import AbstractCommand class Command(AbstractCommand): """ Base-class for all goo.gl commands. Configures the AbstractCommand base class for all commands in the entire application, which needs information about the service being used. Moreover fetches the oauth2 credentials for any HTTP request. Attributes: credentials (oauth2client.file.Storage): An object from Google's API-library used to interact with the oauth2 credentials file. """ def __init__(self, which, credentials_path=None): """ Constructs a new Command. Arguments: which (str): The name of the command (e.g. link). credentials_path (str): Optionally, the full path to a credentials file. The one at lnk/config/credentials will be chosen by default. """ super(Command, self).__init__('googl', which) if credentials_path: self.credentials_path = credentials_path else: self.credentials_path = os.path.join(lnk.config.CONFIG_PATH, '.credentials') self.credentials = oauth2client.file.Storage(self.credentials_path) def get_api(self): """ Returns an API-object used to perform any request. Returns: An API object from Google API-library, used to perform any HTTP request for the url-shortening API. """ http = self.authorize() api = apiclient.discovery.build('urlshortener', 'v1', http=http) return api.url() def get(self, url, projection=None, what=None): """ Base method to perform an HTTP request with the GET method. Arguments: url (str): The short goo.gl URL for which to perform a data-request. projection (str|None): Controls the amount of data returned for the url (values should be either None, such as for url-expansion, or 'FULL' to get statistics or information about a link). what (str): A human-readable string representing what the request was for, such that if there is an error in the response, an errors.HTTPError is raised with the message 'Could not <what>.' (NOT: 'even'). Return: The requested data. """ api = self.get_api() request = api.get(shortUrl=url, projection=projection) response = self.execute(request, what) return response def authorize(self): """ Handles the authorization and re-authorization procedure. Normally, this method will return an HTTP object from Google's httplib2 library, authorized to fetch user-specifc data by using the credentials that were configured for the user. There are two other cases: The oauth2 access-token used to make oauth2 requests expires around-about every hour, so if that is the case this method will first refresh the token; if there are no credentials at all (i.e. the user did not run the 'key' command yet), this method throws an exception. Returns: If all goes well, an oauth2-authorized httplib2.HTTP object. Raises: errors.AuthorizationError: If there are no credentials for this user yet (the initial authorization-procedure was not yet performed). """ credentials = self.credentials.get() if not credentials: raise lnk.errors.AuthorizationError('goo.gl') http = httplib2.Http() if credentials.access_token_expired: credentials.refresh(http) self.credentials.put(credentials) credentials.authorize(http) return http @staticmethod def execute(request, what=None): """ Execute an HTTP request. The main point of this method is to catch HTTP errors raised by Google's API-library and re-raise them as lnk.errorrs.HTTPErrors. """ try: response = request.execute() except googleapiclient.errors.HttpError: raise lnk.errors.HTTPError('Could not {0}.'.format(what)) return response
30.648855
74
0.718306
#!/usr/bin/env python #! -*- coding: utf-8 -*- """Contains the base-class for all goo.gl commands.""" import apiclient.discovery import googleapiclient.errors import httplib2 import oauth2client.file import os import lnk.config import lnk.errors from lnk.abstract import AbstractCommand class Command(AbstractCommand): """ Base-class for all goo.gl commands. Configures the AbstractCommand base class for all commands in the entire application, which needs information about the service being used. Moreover fetches the oauth2 credentials for any HTTP request. Attributes: credentials (oauth2client.file.Storage): An object from Google's API-library used to interact with the oauth2 credentials file. """ def __init__(self, which, credentials_path=None): """ Constructs a new Command. Arguments: which (str): The name of the command (e.g. link). credentials_path (str): Optionally, the full path to a credentials file. The one at lnk/config/credentials will be chosen by default. """ super(Command, self).__init__('googl', which) if credentials_path: self.credentials_path = credentials_path else: self.credentials_path = os.path.join(lnk.config.CONFIG_PATH, '.credentials') self.credentials = oauth2client.file.Storage(self.credentials_path) def get_api(self): """ Returns an API-object used to perform any request. Returns: An API object from Google API-library, used to perform any HTTP request for the url-shortening API. """ http = self.authorize() api = apiclient.discovery.build('urlshortener', 'v1', http=http) return api.url() def get(self, url, projection=None, what=None): """ Base method to perform an HTTP request with the GET method. Arguments: url (str): The short goo.gl URL for which to perform a data-request. projection (str|None): Controls the amount of data returned for the url (values should be either None, such as for url-expansion, or 'FULL' to get statistics or information about a link). what (str): A human-readable string representing what the request was for, such that if there is an error in the response, an errors.HTTPError is raised with the message 'Could not <what>.' (NOT: 'even'). Return: The requested data. """ api = self.get_api() request = api.get(shortUrl=url, projection=projection) response = self.execute(request, what) return response def authorize(self): """ Handles the authorization and re-authorization procedure. Normally, this method will return an HTTP object from Google's httplib2 library, authorized to fetch user-specifc data by using the credentials that were configured for the user. There are two other cases: The oauth2 access-token used to make oauth2 requests expires around-about every hour, so if that is the case this method will first refresh the token; if there are no credentials at all (i.e. the user did not run the 'key' command yet), this method throws an exception. Returns: If all goes well, an oauth2-authorized httplib2.HTTP object. Raises: errors.AuthorizationError: If there are no credentials for this user yet (the initial authorization-procedure was not yet performed). """ credentials = self.credentials.get() if not credentials: raise lnk.errors.AuthorizationError('goo.gl') http = httplib2.Http() if credentials.access_token_expired: credentials.refresh(http) self.credentials.put(credentials) credentials.authorize(http) return http @staticmethod def execute(request, what=None): """ Execute an HTTP request. The main point of this method is to catch HTTP errors raised by Google's API-library and re-raise them as lnk.errorrs.HTTPErrors. """ try: response = request.execute() except googleapiclient.errors.HttpError: raise lnk.errors.HTTPError('Could not {0}.'.format(what)) return response
0
0
0
d9de5c2b3e8c00f404ff312ce3e36c2caeb75133
771
py
Python
var/spack/repos/builtin/packages/nvtop/package.py
player1537-forks/spack
822b7632222ec5a91dc7b7cda5fc0e08715bd47c
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
3
2021-09-29T02:14:40.000Z
2022-01-27T20:50:36.000Z
var/spack/repos/builtin/packages/nvtop/package.py
player1537-forks/spack
822b7632222ec5a91dc7b7cda5fc0e08715bd47c
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
8
2022-02-28T11:30:18.000Z
2022-03-23T19:34:56.000Z
var/spack/repos/builtin/packages/nvtop/package.py
player1537-forks/spack
822b7632222ec5a91dc7b7cda5fc0e08715bd47c
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
null
null
null
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Nvtop(CMakePackage, CudaPackage): """Nvtop stands for NVidia TOP, a (h)top like task monitor for NVIDIA GPUs. It can handle multiple GPUs and print information about them in a htop familiar way.""" homepage = "https://github.com/Syllo/nvtop" url = "https://github.com/Syllo/nvtop/archive/1.1.0.tar.gz" version('1.1.0', sha256='00470cde8fc48d5a5ed7c96402607e474414d94b562b21189bdde1dbe6b1d1f3') depends_on('ncurses')
33.521739
95
0.728923
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Nvtop(CMakePackage, CudaPackage): """Nvtop stands for NVidia TOP, a (h)top like task monitor for NVIDIA GPUs. It can handle multiple GPUs and print information about them in a htop familiar way.""" homepage = "https://github.com/Syllo/nvtop" url = "https://github.com/Syllo/nvtop/archive/1.1.0.tar.gz" version('1.1.0', sha256='00470cde8fc48d5a5ed7c96402607e474414d94b562b21189bdde1dbe6b1d1f3') depends_on('ncurses') def cmake_args(self): return [self.define('NVML_RETRIEVE_HEADER_ONLINE', True)]
66
0
27
1a9d033864d3ed4ca4ff2d1c25a865a9ebe5bb68
599
py
Python
website/extensions/intro_text.py
acaciawater/wfn
74c5b6bb0b2065cfcf6e968daef6e7354ff971c2
[ "MIT" ]
null
null
null
website/extensions/intro_text.py
acaciawater/wfn
74c5b6bb0b2065cfcf6e968daef6e7354ff971c2
[ "MIT" ]
null
null
null
website/extensions/intro_text.py
acaciawater/wfn
74c5b6bb0b2065cfcf6e968daef6e7354ff971c2
[ "MIT" ]
null
null
null
from django.db import models from django.utils.translation import ugettext_lazy as _ from feincms.module.medialibrary.models import MediaFile from feincms import extensions
31.526316
75
0.701169
from django.db import models from django.utils.translation import ugettext_lazy as _ from feincms.module.medialibrary.models import MediaFile from feincms import extensions class Extension(extensions.Extension): def handle_model(self): self.model.add_to_class('intro_text', models.TextField( verbose_name=_('introduction'), default='', blank=True, null=True, help_text=_('The introduction will be shown below the title'))) def handle_modeladmin(self, modeladmin): modeladmin.add_extension_options('intro_text')
331
17
76
45b35d71aa5c89c4cc5bf4f44e16d910cbdcac65
10,551
py
Python
codes/data/data_process.py
RyanXingQL/MW-GAN
562199344e322919a108048acd55b0dd8820df55
[ "MIT" ]
2
2021-11-05T09:21:54.000Z
2021-11-14T06:03:16.000Z
codes/data/data_process.py
RyanXingQL/MW-GAN
562199344e322919a108048acd55b0dd8820df55
[ "MIT" ]
2
2021-06-05T02:53:30.000Z
2021-06-06T03:05:44.000Z
codes/data/data_process.py
RyanXingQL/MW-GAN
562199344e322919a108048acd55b0dd8820df55
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- import cv2 import os, sys sys.path.append('./') import numpy as np import glob import math """ Created on Thu Jan 10 10:48:00 2013 @author: Chen Ming """ def read_YUV420(image_path, rows, cols, numfrm): """ 读取YUV文件,解析为Y, U, V图像 :param image_path: YUV图像路径 :param rows: 给定高 :param cols: 给定宽 :return: 列表,[Y, U, V] """ # create Y gray = np.zeros((rows, cols), np.uint8) # print(type(gray)) # print(gray.shape) # create U,V img_U = np.zeros((int(rows / 2), int(cols / 2)), np.uint8) # print(type(img_U)) # print(img_U.shape) img_V = np.zeros((int(rows / 2), int(cols / 2)), np.uint8) # print(type(img_V)) # print(img_V.shape) Y = [] U = [] V = [] reader=open(image_path,'rb') # with open(image_path, 'rb') as reader: for num in range(numfrm-1): Y_buf = reader.read(cols * rows) gray = np.reshape(np.frombuffer(Y_buf, dtype=np.uint8), [rows, cols]) U_buf = reader.read(cols//2 * rows//2) img_U = np.reshape(np.frombuffer(U_buf, dtype=np.uint8), [rows//2, cols//2]) V_buf = reader.read(cols//2 * rows//2) img_V = np.reshape(np.frombuffer(V_buf, dtype=np.uint8), [rows//2, cols//2]) Y = Y+[gray] U = U+[img_U] V = V+[img_V] return [Y, U, V] if __name__ == '__main__': fixerror = False qp_value = 37 frame_maxnum = 100 info_mode = 'x265' crop_size = 64 channal_num = 3 # add_name='_qp37_rec' add_name='' if info_mode == 'train': readPath_GT = '/media/iceclear/yangren/train_108/raw/' readPath_RAnof = '/media/iceclear/yangren/train_108/HM16.5_LDP/QP'+str(qp_value)+'/' if channal_num==3: savePath_GT = '/media/iceclear/iceking/YUV_GT_img_crop_rgb/' # readPath_RAnof = '/media/iceclear/yuhang/RA_Rec/' savePath_RAnof = '/media/iceclear/iceking/YUV_f_img_crop_'+str(qp_value)+'_rgb/' elif channal_num==1: savePath_GT = '/media/iceclear/iceking/YUV_GT_img_crop_yuv/' # readPath_RAnof = '/media/iceclear/yuhang/RA_Rec/' savePath_RAnof = '/media/iceclear/iceking/YUV_f_img_crop_'+str(qp_value)+'_yuv/' elif info_mode == 'test': readPath_GT = '/media/iceclear/yangren/test_18/raw/' readPath_RAnof = '/media/iceclear/yangren/test_18/HM16.5_LDP/QP'+str(qp_value)+'/' if channal_num==3: savePath_GT = '/media/iceclear/iceking/YUV_GT_img_crop_test_rgb/' # readPath_RAnof = '/media/iceclear/yuhang/RA_Rec/' savePath_RAnof = '/media/iceclear/iceking/YUV_f_img_crop_'+str(qp_value)+'_test_rgb/' elif channal_num==1: savePath_GT = '/media/iceclear/iceking/YUV_GT_img_crop_test_yuv/' # readPath_RAnof = '/media/iceclear/yuhang/RA_Rec/' savePath_RAnof = '/media/iceclear/iceking/YUV_f_img_crop_'+str(qp_value)+'_test_yuv/' elif info_mode == 'mos': readPath_GT = '/media/iceclear/yangren/train_108/raw/' readPath_RAnof = '/media/iceclear/yangren/train_108/HM16.5_LDP/QP'+str(qp_value)+'/' if channal_num==3: savePath_GT = '/media/iceclear/iceking/YUV_GT_img_crop_rgb/' # readPath_RAnof = '/media/iceclear/yuhang/RA_Rec/' savePath_RAnof = '/media/iceclear/iceking/YUV_f_img_crop_'+str(qp_value)+'_rgb/' elif info_mode == 'jm': readPath_GT = '/media/iceclear/yangren/test_18/raw/' readPath_RAnof = '/media/iceclear/yangren/test_18/JM_qp'+str(qp_value)+'/' if channal_num==3: savePath_GT = '/media/iceclear/iceking/YUV_GT_img_crop_rgb_JM/' # readPath_RAnof = '/media/iceclear/yuhang/RA_Rec/' savePath_RAnof = '/media/iceclear/iceking/YUV_JM_img_crop_'+str(qp_value)+'_rgb/' elif info_mode == 'vidyo': readPath_GT = '/media/iceclear/yangren/test_18/vidyo/' readPath_RAnof = '/media/iceclear/yangren/test_18/vidyo_JM'+str(qp_value)+'/' if channal_num==3: savePath_GT = '/media/iceclear/iceking/YUV_GT_img_vidyo_rgb_265/' # readPath_RAnof = '/media/iceclear/yuhang/RA_Rec/' savePath_RAnof = '/media/iceclear/iceking/YUV_265_img_vidyo_'+str(qp_value)+'_rgb/' elif info_mode == 'x265': readPath_GT = '/home/x/data/pycharm/MW-GAN/data/mfqe/raw/' readPath_RAnof = '/home/x/data/pycharm/MW-GAN/data/mfqe/qp'+str(qp_value)+'/' if channal_num==3: savePath_GT = '/home/x/data/pycharm/MW-GAN/data/YUV_GT_img_x265_rgb/' savePath_RAnof = '/home/x/data/pycharm/MW-GAN/data/YUV_img_x265_'+str(qp_value)+'_rgb/' errorfile = [] errorwith = [] errorheight = [] errorframe = [] video_list = glob.glob(readPath_GT+"*.yuv") # video_list = ['/media/iceclear/yangren/test_18/raw/KristenAndSara_1280x720_600.yuv'] for c in video_list: c_array = os.path.basename(c).split('_') filename = c_array[0]+c_array[1] height_x_width = c_array[1] print('>>>>>>>>>>>>>> '+filename+' is starting') psnr_list = [] oripsnr_list = [] frame_per_second = 30 frame_total_name = int(c_array[2][:-4]) frame_total = int(c_array[2][:-4]) vid_width = int(height_x_width[0:len(height_x_width)//2]) vid_height = int(height_x_width[len(height_x_width)//2+1:]) # if vid_width != 1920: # continue width_crop = 0 height_crop = 0 if info_mode != 'train': if vid_width%crop_size != 0 or vid_height%crop_size != 0: if vid_width%crop_size != 0: width_crop = int(vid_width%crop_size/2) if vid_height%crop_size != 0: height_crop = int(vid_height%crop_size/2) createpath(savePath_GT+filename+'/') createpath(savePath_RAnof+filename+'/') try: [y_gt,u_gt,v_gt] = read_YUV420(c,vid_height,vid_width,frame_total) # [y_lq,u_lq,v_lq] = read_YUV420(readPath_RAnof + 'rec_RA_' + filename + '_qp'+str(qp_value)+'_nf'+ str(frame_total) +'.yuv', # vid_height,vid_width,frame_total) gt_name = os.path.basename(c).split('.')[0] [y_lq,u_lq,v_lq] = read_YUV420(readPath_RAnof + gt_name + add_name + '.yuv',vid_height,vid_width,frame_total) if frame_total>frame_maxnum and info_mode!='test': frame_total = frame_maxnum+1 # [Y,U,V] = read_YUV420(readPath + filename+'_resi.yuv',vid_height,vid_width,frame_total) # print((Y[0]==Y[5]).all()) # subprocess.call(["./360tools_conv", "-i", '/media/s/YuhangSong_1/env/ff/vr_new/'+dataset[i]+'.yuv', "-w",str(W), "-h", str(H), "-x", str(1), "-o", '/media/s/Iceclear/CMP/'+dataset[i]+'.yuv', "-l", str(3840), "-m", str(2880), "-y", str(1), "-f", str(3)]) for index in range(frame_total-1): # psnr_frame = computePSNR(y_gt[index],y_lq[index]) # psnr_list.append(psnr_frame) rgb_lq = yuv2rgb(y_lq[index],u_lq[index],v_lq[index]) rgb_gt = yuv2rgb(y_gt[index],u_gt[index],v_gt[index]) if height_crop>0: temp_y_lq = y_lq[index][height_crop:-height_crop, :] temp_y_gt = y_gt[index][height_crop:-height_crop, :] rgb_lq = rgb_lq[height_crop:-height_crop, :, :] rgb_gt = rgb_gt[height_crop:-height_crop, :, :] else: temp_y_lq = y_lq[index] temp_y_gt = y_gt[index] rgb_lq = rgb_lq rgb_gt = rgb_gt if width_crop>0: temp_y_lq = temp_y_lq[:, width_crop:-width_crop] temp_y_gt = temp_y_gt[:, width_crop:-width_crop] rgb_lq = rgb_lq[:, width_crop:-width_crop, :] rgb_gt = rgb_gt[:, width_crop:-width_crop, :] psnr_frame = computePSNR(rgb_gt,rgb_lq) print(psnr_frame) if not os.path.exists(savePath_GT+filename+'/'+filename+'_'+str(index)+'.png'): if channal_num==3: cv2.imwrite(savePath_GT+filename+'/'+filename+'_'+str(index)+'.png',rgb_gt) # np.save(savePath_GT+filename+'/'+filename+'_'+str(index)+'.npy',rgb_gt) elif channal_num==1: cv2.imwrite(savePath_GT+filename+'/'+filename+'_'+str(index)+'.png',temp_y_gt) if not os.path.exists(savePath_RAnof+filename+'/'+filename+'_'+str(index)+'.png'): if channal_num==3: cv2.imwrite(savePath_RAnof+filename+'/'+filename+'_'+str(index)+'.png',rgb_lq) # np.save(savePath_RAnof+filename+'/'+filename+'_'+str(index)+'.npy',rgb_lq) elif channal_num==1: cv2.imwrite(savePath_RAnof+filename+'/'+filename+'_'+str(index)+'.png',temp_y_lq) # psnr_list = np.array(psnr_list) print('>>>>>>>>>>>>>> '+filename+' is finished') # print('Average PSNR is: '+str(np.mean(psnr_list))) except Exception as e: errorfile.append(filename) errorwith.append(vid_width) errorheight.append(vid_height) errorframe.append(frame_total_name) print('ERROR: '+filename) print('All finish, error list is: ') print(errorfile)
40.425287
268
0.572647
# -*- coding: utf-8 -*- import cv2 import os, sys sys.path.append('./') import numpy as np import glob import math """ Created on Thu Jan 10 10:48:00 2013 @author: Chen Ming """ def read_YUV420(image_path, rows, cols, numfrm): """ 读取YUV文件,解析为Y, U, V图像 :param image_path: YUV图像路径 :param rows: 给定高 :param cols: 给定宽 :return: 列表,[Y, U, V] """ # create Y gray = np.zeros((rows, cols), np.uint8) # print(type(gray)) # print(gray.shape) # create U,V img_U = np.zeros((int(rows / 2), int(cols / 2)), np.uint8) # print(type(img_U)) # print(img_U.shape) img_V = np.zeros((int(rows / 2), int(cols / 2)), np.uint8) # print(type(img_V)) # print(img_V.shape) Y = [] U = [] V = [] reader=open(image_path,'rb') # with open(image_path, 'rb') as reader: for num in range(numfrm-1): Y_buf = reader.read(cols * rows) gray = np.reshape(np.frombuffer(Y_buf, dtype=np.uint8), [rows, cols]) U_buf = reader.read(cols//2 * rows//2) img_U = np.reshape(np.frombuffer(U_buf, dtype=np.uint8), [rows//2, cols//2]) V_buf = reader.read(cols//2 * rows//2) img_V = np.reshape(np.frombuffer(V_buf, dtype=np.uint8), [rows//2, cols//2]) Y = Y+[gray] U = U+[img_U] V = V+[img_V] return [Y, U, V] def nomalize(input): temp = np.maximum(0, input) temp = np.minimum(255, temp) return temp def yuv2rgb(Y,U,V): enlarge_U = cv2.resize(U, (0, 0), fx=2.0, fy=2.0) enlarge_V = cv2.resize(V, (0, 0), fx=2.0, fy=2.0) # 合并YUV3通道 img_YUV = cv2.merge([Y, enlarge_U, enlarge_V]) dst = cv2.cvtColor(img_YUV, cv2.COLOR_YUV2BGR) return dst def computePSNR(origin,pred): origin = np.array(origin) origin = origin.astype(np.float32) pred = np.array(pred) pred = pred.astype(np.float32) mse = np.mean((origin/1.0 - pred/1.0) ** 2 ) if mse < 1.0e-10: return 100 return 10 * math.log10(255.0**2/mse) def createpath(path): while not os.path.exists(path): os.makedirs(path) if __name__ == '__main__': fixerror = False qp_value = 37 frame_maxnum = 100 info_mode = 'x265' crop_size = 64 channal_num = 3 # add_name='_qp37_rec' add_name='' if info_mode == 'train': readPath_GT = '/media/iceclear/yangren/train_108/raw/' readPath_RAnof = '/media/iceclear/yangren/train_108/HM16.5_LDP/QP'+str(qp_value)+'/' if channal_num==3: savePath_GT = '/media/iceclear/iceking/YUV_GT_img_crop_rgb/' # readPath_RAnof = '/media/iceclear/yuhang/RA_Rec/' savePath_RAnof = '/media/iceclear/iceking/YUV_f_img_crop_'+str(qp_value)+'_rgb/' elif channal_num==1: savePath_GT = '/media/iceclear/iceking/YUV_GT_img_crop_yuv/' # readPath_RAnof = '/media/iceclear/yuhang/RA_Rec/' savePath_RAnof = '/media/iceclear/iceking/YUV_f_img_crop_'+str(qp_value)+'_yuv/' elif info_mode == 'test': readPath_GT = '/media/iceclear/yangren/test_18/raw/' readPath_RAnof = '/media/iceclear/yangren/test_18/HM16.5_LDP/QP'+str(qp_value)+'/' if channal_num==3: savePath_GT = '/media/iceclear/iceking/YUV_GT_img_crop_test_rgb/' # readPath_RAnof = '/media/iceclear/yuhang/RA_Rec/' savePath_RAnof = '/media/iceclear/iceking/YUV_f_img_crop_'+str(qp_value)+'_test_rgb/' elif channal_num==1: savePath_GT = '/media/iceclear/iceking/YUV_GT_img_crop_test_yuv/' # readPath_RAnof = '/media/iceclear/yuhang/RA_Rec/' savePath_RAnof = '/media/iceclear/iceking/YUV_f_img_crop_'+str(qp_value)+'_test_yuv/' elif info_mode == 'mos': readPath_GT = '/media/iceclear/yangren/train_108/raw/' readPath_RAnof = '/media/iceclear/yangren/train_108/HM16.5_LDP/QP'+str(qp_value)+'/' if channal_num==3: savePath_GT = '/media/iceclear/iceking/YUV_GT_img_crop_rgb/' # readPath_RAnof = '/media/iceclear/yuhang/RA_Rec/' savePath_RAnof = '/media/iceclear/iceking/YUV_f_img_crop_'+str(qp_value)+'_rgb/' elif info_mode == 'jm': readPath_GT = '/media/iceclear/yangren/test_18/raw/' readPath_RAnof = '/media/iceclear/yangren/test_18/JM_qp'+str(qp_value)+'/' if channal_num==3: savePath_GT = '/media/iceclear/iceking/YUV_GT_img_crop_rgb_JM/' # readPath_RAnof = '/media/iceclear/yuhang/RA_Rec/' savePath_RAnof = '/media/iceclear/iceking/YUV_JM_img_crop_'+str(qp_value)+'_rgb/' elif info_mode == 'vidyo': readPath_GT = '/media/iceclear/yangren/test_18/vidyo/' readPath_RAnof = '/media/iceclear/yangren/test_18/vidyo_JM'+str(qp_value)+'/' if channal_num==3: savePath_GT = '/media/iceclear/iceking/YUV_GT_img_vidyo_rgb_265/' # readPath_RAnof = '/media/iceclear/yuhang/RA_Rec/' savePath_RAnof = '/media/iceclear/iceking/YUV_265_img_vidyo_'+str(qp_value)+'_rgb/' elif info_mode == 'x265': readPath_GT = '/home/x/data/pycharm/MW-GAN/data/mfqe/raw/' readPath_RAnof = '/home/x/data/pycharm/MW-GAN/data/mfqe/qp'+str(qp_value)+'/' if channal_num==3: savePath_GT = '/home/x/data/pycharm/MW-GAN/data/YUV_GT_img_x265_rgb/' savePath_RAnof = '/home/x/data/pycharm/MW-GAN/data/YUV_img_x265_'+str(qp_value)+'_rgb/' errorfile = [] errorwith = [] errorheight = [] errorframe = [] video_list = glob.glob(readPath_GT+"*.yuv") # video_list = ['/media/iceclear/yangren/test_18/raw/KristenAndSara_1280x720_600.yuv'] for c in video_list: c_array = os.path.basename(c).split('_') filename = c_array[0]+c_array[1] height_x_width = c_array[1] print('>>>>>>>>>>>>>> '+filename+' is starting') psnr_list = [] oripsnr_list = [] frame_per_second = 30 frame_total_name = int(c_array[2][:-4]) frame_total = int(c_array[2][:-4]) vid_width = int(height_x_width[0:len(height_x_width)//2]) vid_height = int(height_x_width[len(height_x_width)//2+1:]) # if vid_width != 1920: # continue width_crop = 0 height_crop = 0 if info_mode != 'train': if vid_width%crop_size != 0 or vid_height%crop_size != 0: if vid_width%crop_size != 0: width_crop = int(vid_width%crop_size/2) if vid_height%crop_size != 0: height_crop = int(vid_height%crop_size/2) createpath(savePath_GT+filename+'/') createpath(savePath_RAnof+filename+'/') try: [y_gt,u_gt,v_gt] = read_YUV420(c,vid_height,vid_width,frame_total) # [y_lq,u_lq,v_lq] = read_YUV420(readPath_RAnof + 'rec_RA_' + filename + '_qp'+str(qp_value)+'_nf'+ str(frame_total) +'.yuv', # vid_height,vid_width,frame_total) gt_name = os.path.basename(c).split('.')[0] [y_lq,u_lq,v_lq] = read_YUV420(readPath_RAnof + gt_name + add_name + '.yuv',vid_height,vid_width,frame_total) if frame_total>frame_maxnum and info_mode!='test': frame_total = frame_maxnum+1 # [Y,U,V] = read_YUV420(readPath + filename+'_resi.yuv',vid_height,vid_width,frame_total) # print((Y[0]==Y[5]).all()) # subprocess.call(["./360tools_conv", "-i", '/media/s/YuhangSong_1/env/ff/vr_new/'+dataset[i]+'.yuv', "-w",str(W), "-h", str(H), "-x", str(1), "-o", '/media/s/Iceclear/CMP/'+dataset[i]+'.yuv', "-l", str(3840), "-m", str(2880), "-y", str(1), "-f", str(3)]) for index in range(frame_total-1): # psnr_frame = computePSNR(y_gt[index],y_lq[index]) # psnr_list.append(psnr_frame) rgb_lq = yuv2rgb(y_lq[index],u_lq[index],v_lq[index]) rgb_gt = yuv2rgb(y_gt[index],u_gt[index],v_gt[index]) if height_crop>0: temp_y_lq = y_lq[index][height_crop:-height_crop, :] temp_y_gt = y_gt[index][height_crop:-height_crop, :] rgb_lq = rgb_lq[height_crop:-height_crop, :, :] rgb_gt = rgb_gt[height_crop:-height_crop, :, :] else: temp_y_lq = y_lq[index] temp_y_gt = y_gt[index] rgb_lq = rgb_lq rgb_gt = rgb_gt if width_crop>0: temp_y_lq = temp_y_lq[:, width_crop:-width_crop] temp_y_gt = temp_y_gt[:, width_crop:-width_crop] rgb_lq = rgb_lq[:, width_crop:-width_crop, :] rgb_gt = rgb_gt[:, width_crop:-width_crop, :] psnr_frame = computePSNR(rgb_gt,rgb_lq) print(psnr_frame) if not os.path.exists(savePath_GT+filename+'/'+filename+'_'+str(index)+'.png'): if channal_num==3: cv2.imwrite(savePath_GT+filename+'/'+filename+'_'+str(index)+'.png',rgb_gt) # np.save(savePath_GT+filename+'/'+filename+'_'+str(index)+'.npy',rgb_gt) elif channal_num==1: cv2.imwrite(savePath_GT+filename+'/'+filename+'_'+str(index)+'.png',temp_y_gt) if not os.path.exists(savePath_RAnof+filename+'/'+filename+'_'+str(index)+'.png'): if channal_num==3: cv2.imwrite(savePath_RAnof+filename+'/'+filename+'_'+str(index)+'.png',rgb_lq) # np.save(savePath_RAnof+filename+'/'+filename+'_'+str(index)+'.npy',rgb_lq) elif channal_num==1: cv2.imwrite(savePath_RAnof+filename+'/'+filename+'_'+str(index)+'.png',temp_y_lq) # psnr_list = np.array(psnr_list) print('>>>>>>>>>>>>>> '+filename+' is finished') # print('Average PSNR is: '+str(np.mean(psnr_list))) except Exception as e: errorfile.append(filename) errorwith.append(vid_width) errorheight.append(vid_height) errorframe.append(frame_total_name) print('ERROR: '+filename) print('All finish, error list is: ') print(errorfile)
680
0
100
1fc81586f7ee334a7c58811a00bc04f65d79aa81
5,752
py
Python
Bot_Training.py
TianyuWu1990/ChatterBot
171fd25a14fd0c4dccaaa54e1a5d0ec6c40221dd
[ "BSD-3-Clause" ]
null
null
null
Bot_Training.py
TianyuWu1990/ChatterBot
171fd25a14fd0c4dccaaa54e1a5d0ec6c40221dd
[ "BSD-3-Clause" ]
null
null
null
Bot_Training.py
TianyuWu1990/ChatterBot
171fd25a14fd0c4dccaaa54e1a5d0ec6c40221dd
[ "BSD-3-Clause" ]
null
null
null
""" AI Neural Network Training For Captain Pi Created By: Vicky Bao """ import tensorflow as tf from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences from tensorflow.keras.layers import Embedding, LSTM, Dense, Bidirectional, GRU from tensorflow.keras.models import Sequential from tensorflow.keras.optimizers import Adam import numpy as np import nltk from nltk.stem.lancaster import LancasterStemmer # Query tags related data from mysql import sqlalchemy engine = sqlalchemy.create_engine( 'mysql+mysqlconnector://root:root@localhost:8889/test', echo=True) connection = engine.connect() trans = connection.begin() query = 'SELECT * FROM training_bot' connection = engine.connect() results = connection.execute(query) # Input data initialization input_corpus, label_corpus = [], [] from collections import defaultdict response_dict = defaultdict(set) for row in results: # pre-process tag and pattern to make it all lower cases and stemmed to its root word tag, pattern, response = row[1].lower(), row[2].lower(), row[3] input_corpus.append(pattern) label_corpus.append(tag) response_dict[tag].add(response) print(f"input_corpose:{input_corpus} \nlabel_corpose: {label_corpus}") connection.close() # Tokenization on texts oov_tok = "<OOV>" tokenizer = Tokenizer(num_words=150, oov_token=oov_tok) tokenizer.fit_on_texts(input_corpus) print(f"input word index: {tokenizer.word_index}") tokenizer.fit_on_texts(label_corpus) total_words = len(tokenizer.word_index) + 1 print(f"total words: {tokenizer.word_index}" f"total word index: {tokenizer.word_index}") # Sequence all texts input_sequences = tokenizer.texts_to_sequences(input_corpus) # input_sequences = [] # Input # for line in input_corpus: # token_list = tokenizer.texts_to_sequences([line])[0] # input_sequences.append(token_list) # max sequence length of the input max_sequence_len = max(len(x) for x in input_sequences) print(f"input_sequences:{input_sequences}\nmax_sequence_len: {max_sequence_len}") label_sequences = tokenizer.texts_to_sequences(label_corpus) # label_sequences = [] # Label # for line in label_corpus: # if line == '': # continue # token_list = tokenizer.texts_to_sequences([line])[0] # label_sequences.append(token_list) label_max_sequence_len = max([len(x) for x in label_sequences]) print(f"label_sequences:{label_sequences}\nlabel_max_sequence_len: {label_max_sequence_len}") # Padded sequences input_sequences = np.array(pad_sequences(input_sequences, maxlen=max_sequence_len, padding='post')) label_sequences = np.array(pad_sequences(label_sequences, maxlen=label_max_sequence_len, padding='post')) # x and y set up xs = input_sequences print(f"xs: \n{input_sequences}\nlabels: \n{label_sequences}") # Categorize y before training the model ys = tf.keras.utils.to_categorical(label_sequences, num_classes=total_words) print(f"ys: \n{ys }") model = Sequential() model.add(Embedding(total_words, 64, input_length=max_sequence_len)) # model.add(Bidirectional(LSTM(20))) # LSTM(150) # GRU(32) # model.add(Dense(total_words, activation='relu')) model.add(LSTM(total_words )) model.add(Dense(total_words, activation='softmax')) adam = Adam(lr=0.01) # learning rate model.compile(loss='categorical_crossentropy', optimizer=adam, metrics=['accuracy']) history = model.fit(xs, ys, epochs=500, verbose=1) model.summary() # Plot Accuracy and loss import matplotlib.pyplot as plt plot_graphs(history, 'accuracy') dict = dict([(value, key) for (key, value) in tokenizer.word_index.items()]) # prediction predict_test("I want to download DUDL Data") predict_test("Show me dudl data") predict_test("I want DUDL reports") predict_test("definition of DUDL") predict_test("Hi Captain") # Load into Tensorflow model for visualization e = model.layers[0] weights = e.get_weights()[0] print(weights.shape) # shape: (vocab_size, embedding_dim) (vocab_size, embedding_dim) = weights.shape import io out_v = io.open('vecs.tsv', 'w', encoding='utf-8') out_m = io.open('meta.tsv', 'w', encoding='utf-8') for word_num in range(1, vocab_size): word = dict[word_num] embeddings = weights[word_num] out_m.write(word + "\n") out_v.write('\t'.join([str(x) for x in embeddings]) + '\n') out_v.close() out_m.close() try: from google.colab import files except ImportError: pass else: files.download('vecs.tsv') files.download('meta.tsv') pass # # Save the model # model.SAVE("model.h5") # # # # # Load the model # # model = keras.models.load_model("model.h5")
31.26087
105
0.727399
""" AI Neural Network Training For Captain Pi Created By: Vicky Bao """ import tensorflow as tf from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences from tensorflow.keras.layers import Embedding, LSTM, Dense, Bidirectional, GRU from tensorflow.keras.models import Sequential from tensorflow.keras.optimizers import Adam import numpy as np import nltk from nltk.stem.lancaster import LancasterStemmer # Query tags related data from mysql import sqlalchemy engine = sqlalchemy.create_engine( 'mysql+mysqlconnector://root:root@localhost:8889/test', echo=True) connection = engine.connect() trans = connection.begin() query = 'SELECT * FROM training_bot' connection = engine.connect() results = connection.execute(query) # Input data initialization input_corpus, label_corpus = [], [] from collections import defaultdict response_dict = defaultdict(set) for row in results: # pre-process tag and pattern to make it all lower cases and stemmed to its root word tag, pattern, response = row[1].lower(), row[2].lower(), row[3] input_corpus.append(pattern) label_corpus.append(tag) response_dict[tag].add(response) print(f"input_corpose:{input_corpus} \nlabel_corpose: {label_corpus}") connection.close() # Tokenization on texts oov_tok = "<OOV>" tokenizer = Tokenizer(num_words=150, oov_token=oov_tok) tokenizer.fit_on_texts(input_corpus) print(f"input word index: {tokenizer.word_index}") tokenizer.fit_on_texts(label_corpus) total_words = len(tokenizer.word_index) + 1 print(f"total words: {tokenizer.word_index}" f"total word index: {tokenizer.word_index}") # Sequence all texts input_sequences = tokenizer.texts_to_sequences(input_corpus) # input_sequences = [] # Input # for line in input_corpus: # token_list = tokenizer.texts_to_sequences([line])[0] # input_sequences.append(token_list) # max sequence length of the input max_sequence_len = max(len(x) for x in input_sequences) print(f"input_sequences:{input_sequences}\nmax_sequence_len: {max_sequence_len}") label_sequences = tokenizer.texts_to_sequences(label_corpus) # label_sequences = [] # Label # for line in label_corpus: # if line == '': # continue # token_list = tokenizer.texts_to_sequences([line])[0] # label_sequences.append(token_list) label_max_sequence_len = max([len(x) for x in label_sequences]) print(f"label_sequences:{label_sequences}\nlabel_max_sequence_len: {label_max_sequence_len}") # Padded sequences input_sequences = np.array(pad_sequences(input_sequences, maxlen=max_sequence_len, padding='post')) label_sequences = np.array(pad_sequences(label_sequences, maxlen=label_max_sequence_len, padding='post')) # x and y set up xs = input_sequences print(f"xs: \n{input_sequences}\nlabels: \n{label_sequences}") # Categorize y before training the model ys = tf.keras.utils.to_categorical(label_sequences, num_classes=total_words) print(f"ys: \n{ys }") model = Sequential() model.add(Embedding(total_words, 64, input_length=max_sequence_len)) # model.add(Bidirectional(LSTM(20))) # LSTM(150) # GRU(32) # model.add(Dense(total_words, activation='relu')) model.add(LSTM(total_words )) model.add(Dense(total_words, activation='softmax')) adam = Adam(lr=0.01) # learning rate model.compile(loss='categorical_crossentropy', optimizer=adam, metrics=['accuracy']) history = model.fit(xs, ys, epochs=500, verbose=1) model.summary() # Plot Accuracy and loss import matplotlib.pyplot as plt def plot_graphs(history, string): plt.plot(history.history[string]) plt.plot(history.history['loss']) plt.xlabel('Epochs') plt.ylabel(string) plt.legend([string, 'loss']) plt.show() plot_graphs(history, 'accuracy') dict = dict([(value, key) for (key, value) in tokenizer.word_index.items()]) # prediction def predict_test(seed_text): token_list = tokenizer.texts_to_sequences([seed_text])[0] token_list = pad_sequences([token_list], maxlen=max_sequence_len, padding='post') predicted = model.predict_classes(token_list, verbose=0) prob = model.predict_proba(token_list) print(f"predicted: {predicted}") print(f"prob: {prob}") max_index = np.argmax(prob) top_3_index = (-prob).argsort()[0][:3] #[-3:][::-1] print(f"max index of prob is {np.argmax(prob)}") print(f"top 3 index of prob is {top_3_index}") for i in top_3_index: print(f"top3 index is {i} -> {prob[0][i] * 100}%") max_prob = prob[0][max_index] * 100 print(f"word index: \n{tokenizer.word_index}") tag = dict[predicted[0]] print(f"tag: {tag}") print(f"max prob for tag {tag}: {max_prob}%") responses = response_dict[tag] print(f"responses: {responses}") predict_test("I want to download DUDL Data") predict_test("Show me dudl data") predict_test("I want DUDL reports") predict_test("definition of DUDL") predict_test("Hi Captain") # Load into Tensorflow model for visualization e = model.layers[0] weights = e.get_weights()[0] print(weights.shape) # shape: (vocab_size, embedding_dim) (vocab_size, embedding_dim) = weights.shape import io out_v = io.open('vecs.tsv', 'w', encoding='utf-8') out_m = io.open('meta.tsv', 'w', encoding='utf-8') for word_num in range(1, vocab_size): word = dict[word_num] embeddings = weights[word_num] out_m.write(word + "\n") out_v.write('\t'.join([str(x) for x in embeddings]) + '\n') out_v.close() out_m.close() try: from google.colab import files except ImportError: pass else: files.download('vecs.tsv') files.download('meta.tsv') pass # # Save the model # model.SAVE("model.h5") # # # # # Load the model # # model = keras.models.load_model("model.h5")
1,052
0
45
0cbff20b100b33389282e1285b151fa26b89e5b3
2,251
py
Python
lamby/models/user.py
lamby-ml/lamby-web
4e3a1f0c9a12118bb8d6d084d07256475d48256c
[ "MIT" ]
null
null
null
lamby/models/user.py
lamby-ml/lamby-web
4e3a1f0c9a12118bb8d6d084d07256475d48256c
[ "MIT" ]
16
2019-01-31T21:48:41.000Z
2019-04-25T21:32:38.000Z
lamby/models/user.py
lamby-ml/lamby-web
4e3a1f0c9a12118bb8d6d084d07256475d48256c
[ "MIT" ]
null
null
null
import secrets from flask_login import UserMixin from werkzeug.security import check_password_hash, generate_password_hash from lamby.database import db from lamby.models.projects import projects
31.704225
79
0.501555
import secrets from flask_login import UserMixin from werkzeug.security import check_password_hash, generate_password_hash from lamby.database import db from lamby.models.projects import projects class User(UserMixin, db.Model): # ------------------------------------------------------------------------- # Meta # ------------------------------------------------------------------------- __tablename__ = 'user' # ------------------------------------------------------------------------- # Fields # ------------------------------------------------------------------------- # ID -- (PrimaryKey) id = db.Column(db.Integer, primary_key=True, autoincrement=True) # EMAIL -- Unique email of the user email = db.Column(db.String(120), unique=True, nullable=False) # PASSWORD -- Encrypted password of the user password = db.Column(db.String(120), nullable=False) # API_KEY -- Token that gives the user access to push and pull from the cli api_key = db.Column(db.String(120)) # ------------------------------------------------------------------------- # Relationships # ------------------------------------------------------------------------- # OWNED_PROJECTS (USER one-to-many PROJECT) # ----------------------------------------- # Represents the projects that the user owns/created owned_projects = db.relationship( 'Project', backref='owner', lazy=True, cascade='all,delete-orphan' ) # PROJECTS (User many-to-many Project) # ------------------------------------ # Represents the projects where the user is a member projects = db.relationship( 'Project', secondary=projects, lazy='subquery', backref=db.backref('members', lazy=True), cascade='all,delete' ) def get_id(self): return str(self.id) def set_password(self, password): self.password = generate_password_hash(password) def check_password(self, password): return check_password_hash(self.password, password) def generate_new_api_key(self): self.api_key = secrets.token_urlsafe(32) def __str__(self): return f'<User email={self.email} />'
269
1,760
23
73d4a4be4d531fdb1cabdd6b5596c2c010a561cc
948
py
Python
imlib/image/masking.py
noisysky/imlib
625193be4a586d9040a48df9d51dbdd3a17c7d06
[ "MIT" ]
null
null
null
imlib/image/masking.py
noisysky/imlib
625193be4a586d9040a48df9d51dbdd3a17c7d06
[ "MIT" ]
6
2020-04-17T12:02:56.000Z
2020-05-12T15:20:18.000Z
imlib/image/masking.py
noisysky/imlib
625193be4a586d9040a48df9d51dbdd3a17c7d06
[ "MIT" ]
4
2020-02-05T18:53:30.000Z
2022-02-21T18:50:14.000Z
import numpy as np def mask_image_threshold(image, masking_image, threshold=0): """ Mask one image, based on the values in another image that are above a threshold :param image: Input image :param masking_image: Image to base the mask on (same shape as image) :param threshold: Threshold to base the mask on :return: Masked image """ masking_image = make_mask(masking_image, threshold=threshold) return image * masking_image def make_mask(masking_image, threshold=0): """ Given an image, and an optional threshold, returns a binary image that can be used as a mask :param masking_image: nD image :param threshold: Optional threshold, default 0. Values above this are included in the mask. Values below this are not. :return: Binary mask """ mask = np.copy(masking_image) mask[masking_image <= threshold] = 0 mask[masking_image > threshold] = 1 return mask
31.6
78
0.703586
import numpy as np def mask_image_threshold(image, masking_image, threshold=0): """ Mask one image, based on the values in another image that are above a threshold :param image: Input image :param masking_image: Image to base the mask on (same shape as image) :param threshold: Threshold to base the mask on :return: Masked image """ masking_image = make_mask(masking_image, threshold=threshold) return image * masking_image def make_mask(masking_image, threshold=0): """ Given an image, and an optional threshold, returns a binary image that can be used as a mask :param masking_image: nD image :param threshold: Optional threshold, default 0. Values above this are included in the mask. Values below this are not. :return: Binary mask """ mask = np.copy(masking_image) mask[masking_image <= threshold] = 0 mask[masking_image > threshold] = 1 return mask
0
0
0
fabd427094c1ac44bdebcf5e81a06aed67bcb985
1,425
py
Python
percept/point.py
joshleeb/PerceptronVis
2d0e2f1969e11498533f190f5598c174b7584513
[ "MIT" ]
null
null
null
percept/point.py
joshleeb/PerceptronVis
2d0e2f1969e11498533f190f5598c174b7584513
[ "MIT" ]
null
null
null
percept/point.py
joshleeb/PerceptronVis
2d0e2f1969e11498533f190f5598c174b7584513
[ "MIT" ]
null
null
null
import random def generate_points(n, bounds): ''' Generates a list of n points with random coordinates. ''' return [Point.create_random(bounds) for i in range(n)] def generate_class_fn(bounds): ''' Generates a function used to classify the generated points. The function returned is the equation of the class boundary points specified. ''' x0, y0, x1, y1 = bounds[0][0], bounds[0][1], bounds[1][0], bounds[1][1] gradient = (y0 - y1) / (x0 - x1) return fn
27.941176
76
0.61193
import random class Point: def __init__(self, x, y, classification=None): self.x = x self.y = y self.classification = None def __repr__(self): return '({}, {}, {})'.format(self.x, self.y, self.classification) def __str__(self): return self.__repr__() def apply_classification(self, class_boundary): ''' Applies the classification rule to the point. ''' class_fn = generate_class_fn(class_boundary) self.classification = self.y >= class_fn(self.x) @classmethod def create_random(cls, bounds): ''' Creates a point with random coordinates within the specified bounds. ''' rand_x = round(random.uniform(bounds[0][0], bounds[0][1]), 3) rand_y = round(random.uniform(bounds[1][0], bounds[1][1]), 3) return Point(rand_x, rand_y) def generate_points(n, bounds): ''' Generates a list of n points with random coordinates. ''' return [Point.create_random(bounds) for i in range(n)] def generate_class_fn(bounds): ''' Generates a function used to classify the generated points. The function returned is the equation of the class boundary points specified. ''' x0, y0, x1, y1 = bounds[0][0], bounds[0][1], bounds[1][0], bounds[1][1] gradient = (y0 - y1) / (x0 - x1) def fn(x): return gradient * (x - x0) + y0 return fn
227
644
50
4d3dcdd573097f329abfa171c72eeb7e953e4944
74
py
Python
src/lib/robotparser.py
timmartin/skulpt
2e3a3fbbaccc12baa29094a717ceec491a8a6750
[ "MIT" ]
10
2015-11-13T17:02:40.000Z
2021-02-09T23:21:05.000Z
src/lib/robotparser.py
timmartin/skulpt
2e3a3fbbaccc12baa29094a717ceec491a8a6750
[ "MIT" ]
43
2015-06-03T17:59:23.000Z
2021-09-17T10:45:21.000Z
src/lib/robotparser.py
timmartin/skulpt
2e3a3fbbaccc12baa29094a717ceec491a8a6750
[ "MIT" ]
13
2017-07-02T03:16:46.000Z
2021-07-05T14:53:56.000Z
raise NotImplementedError("robotparser is not yet implemented in Skulpt")
37
73
0.837838
raise NotImplementedError("robotparser is not yet implemented in Skulpt")
0
0
0
681ce907021c18a1a31bb281a18230934f7340fc
1,761
py
Python
rl_games/algos_tf14/model_builder.py
cremebrule/rl_games
fc996a0d00438f6747fef86959c8d31ecd7880f9
[ "MIT" ]
193
2019-05-28T01:48:56.000Z
2022-03-31T07:56:37.000Z
rl_games/algos_tf14/model_builder.py
cremebrule/rl_games
fc996a0d00438f6747fef86959c8d31ecd7880f9
[ "MIT" ]
35
2020-01-28T22:15:51.000Z
2022-03-28T22:10:54.000Z
rl_games/algos_tf14/model_builder.py
cremebrule/rl_games
fc996a0d00438f6747fef86959c8d31ecd7880f9
[ "MIT" ]
37
2019-06-28T01:09:53.000Z
2022-03-26T09:14:06.000Z
from rl_games.common import object_factory import rl_games.algos_tf14 from rl_games.algos_tf14 import network_builder from rl_games.algos_tf14 import models
50.314286
146
0.752413
from rl_games.common import object_factory import rl_games.algos_tf14 from rl_games.algos_tf14 import network_builder from rl_games.algos_tf14 import models class ModelBuilder: def __init__(self): self.model_factory = object_factory.ObjectFactory() self.model_factory.register_builder('discrete_a2c', lambda network, **kwargs : models.ModelA2C(network)) self.model_factory.register_builder('discrete_a2c_lstm', lambda network, **kwargs : models.LSTMModelA2C(network)) self.model_factory.register_builder('continuous_a2c', lambda network, **kwargs : models.ModelA2CContinuous(network)) self.model_factory.register_builder('continuous_a2c_logstd', lambda network, **kwargs : models.ModelA2CContinuousLogStd(network)) self.model_factory.register_builder('continuous_a2c_lstm', lambda network, **kwargs : models.LSTMModelA2CContinuous(network)) self.model_factory.register_builder('continuous_a2c_lstm_logstd', lambda network, **kwargs : models.LSTMModelA2CContinuousLogStd(network)) self.model_factory.register_builder('dqn', lambda network, **kwargs : models.AtariDQN(network)) self.network_factory = object_factory.ObjectFactory() self.network_factory.register_builder('actor_critic', lambda **kwargs : network_builder.A2CBuilder()) self.network_factory.register_builder('dqn', lambda **kwargs : network_builder.DQNBuilder()) def load(self, params): self.model_name = params['model']['name'] self.network_name = params['network']['name'] network = self.network_factory.create(self.network_name) network.load(params['network']) model = self.model_factory.create(self.model_name, network=network) return model
1,527
-2
76
bab9e9cc214af5590dbda085405554100fa3778a
544
py
Python
examples/parameterized_test.py
Likangkang08/SeleniumBases
0fdd3ea44fafff976d349c2ccc2b4e7fef21084e
[ "MIT" ]
1
2019-06-14T09:23:51.000Z
2019-06-14T09:23:51.000Z
examples/parameterized_test.py
Likangkang08/SeleniumBases
0fdd3ea44fafff976d349c2ccc2b4e7fef21084e
[ "MIT" ]
1
2021-06-01T23:51:27.000Z
2021-06-01T23:51:27.000Z
examples/parameterized_test.py
Likangkang08/SeleniumBases
0fdd3ea44fafff976d349c2ccc2b4e7fef21084e
[ "MIT" ]
null
null
null
from seleniumbase import BaseCase from parameterized import parameterized
34
74
0.676471
from seleniumbase import BaseCase from parameterized import parameterized class GoogleTestClass(BaseCase): @parameterized.expand([ ["pypi", "https://pypi.org"], ["wikipedia", "https://www.wikipedia.org"], ["seleniumbase", "https://github.com/seleniumbase/SeleniumBase"], ]) def test_parameterized_google_search(self, search_term, expected_url): self.open('https://google.com') self.update_text('input[title="Search"]', search_term + '\n') self.assert_text(expected_url, '#search')
209
237
23
6ad90e1b8027ebf5b6784838d7b1bf86701cb99c
7,110
py
Python
calamari_ocr/scripts/predict.py
timothydereuse/calamari
eba8e9c35d2c301319cc9cb15d25124460aee2db
[ "Apache-2.0" ]
null
null
null
calamari_ocr/scripts/predict.py
timothydereuse/calamari
eba8e9c35d2c301319cc9cb15d25124460aee2db
[ "Apache-2.0" ]
null
null
null
calamari_ocr/scripts/predict.py
timothydereuse/calamari
eba8e9c35d2c301319cc9cb15d25124460aee2db
[ "Apache-2.0" ]
null
null
null
import os import zlib from dataclasses import dataclass, field from typing import TYPE_CHECKING, List, Optional import tfaip.util.logging from bidi.algorithm import get_base_level from paiargparse import PAIArgumentParser, pai_meta, pai_dataclass from calamari_ocr import __version__ from calamari_ocr.ocr.dataset.datareader.base import CalamariDataGeneratorParams from calamari_ocr.ocr.dataset.datareader.file import FileDataParams from calamari_ocr.ocr.dataset.params import DATA_GENERATOR_CHOICES from calamari_ocr.ocr.model.ctcdecoder.ctc_decoder import ( CTCDecoderParams, CTCDecoderType, ) from calamari_ocr.ocr.predict.params import Predictions, PredictorParams from calamari_ocr.ocr.voting import VoterParams from calamari_ocr.utils.glob import glob_all if TYPE_CHECKING: from calamari_ocr.ocr.dataset.pipeline import CalamariPipeline logger = tfaip.util.logging.logger(__name__) @pai_dataclass @dataclass if __name__ == "__main__": main()
36.839378
120
0.669198
import os import zlib from dataclasses import dataclass, field from typing import TYPE_CHECKING, List, Optional import tfaip.util.logging from bidi.algorithm import get_base_level from paiargparse import PAIArgumentParser, pai_meta, pai_dataclass from calamari_ocr import __version__ from calamari_ocr.ocr.dataset.datareader.base import CalamariDataGeneratorParams from calamari_ocr.ocr.dataset.datareader.file import FileDataParams from calamari_ocr.ocr.dataset.params import DATA_GENERATOR_CHOICES from calamari_ocr.ocr.model.ctcdecoder.ctc_decoder import ( CTCDecoderParams, CTCDecoderType, ) from calamari_ocr.ocr.predict.params import Predictions, PredictorParams from calamari_ocr.ocr.voting import VoterParams from calamari_ocr.utils.glob import glob_all if TYPE_CHECKING: from calamari_ocr.ocr.dataset.pipeline import CalamariPipeline logger = tfaip.util.logging.logger(__name__) @pai_dataclass @dataclass class PredictArgs: checkpoint: List[str] = field(metadata=pai_meta(mode="flat", help="Path to the checkpoint without file extension")) data: CalamariDataGeneratorParams = field( default_factory=FileDataParams, metadata=pai_meta(mode="flat", choices=DATA_GENERATOR_CHOICES), ) verbose: bool = field( default=True, metadata=pai_meta( mode="flat", help="Print the prediction result to the log", ), ) extended_prediction_data: bool = field( default=False, metadata=pai_meta( mode="flat", help="Write: Predicted string, labels; position, probabilities and alternatives of chars to a .pred file", ), ) extended_prediction_data_format: str = field( default="json", metadata=pai_meta( mode="flat", help="Extension format: Either pred or json. Note that json will not print logits.", ), ) ctc_decoder: CTCDecoderParams = field(default_factory=CTCDecoderParams, metadata=pai_meta(mode="ignore")) voter: VoterParams = field(default_factory=VoterParams) output_dir: Optional[str] = field( default=None, metadata=pai_meta( mode="flat", help="By default the prediction files will be written to the same directory as the given files. " "You can use this argument to specify a specific output dir for the prediction files.", ), ) predictor: PredictorParams = field( default_factory=PredictorParams, metadata=pai_meta( fix_dc=True, mode="flat", ), ) def prepare_ctc_decoder_params(ctc_decoder: CTCDecoderParams): if ctc_decoder.dictionary: dictionary = set() logger.info("Creating dictionary") for path in glob_all(ctc_decoder.dictionary): with open(path, "r") as f: dictionary = dictionary.union({word for word in f.read().split()}) ctc_decoder.dictionary = dictionary logger.info("Dictionary with {} unique words successfully created.".format(len(dictionary))) if ctc_decoder.dictionary: logger.warning("USING A LANGUAGE MODEL IS CURRENTLY EXPERIMENTAL ONLY. NOTE: THE PREDICTION IS VERY SLOW!") ctc_decoder.type = CTCDecoderType.WordBeamSearch def run(args: PredictArgs): # check if loading a json file # TODO: support running from JSON # if len(args.files) == 1 and args.files[0].endswith("json"): # import json # with open(args.files[0], 'r') as f: # json_args = json.load(f) # for key, value in json_args.items(): # setattr(args, key, value) # checks if args.extended_prediction_data_format not in ["pred", "json"]: raise Exception("Only 'pred' and 'json' are allowed extended prediction data formats") # add json as extension, resolve wildcard, expand user, ... and remove .json again args.checkpoint = [(cp if cp.endswith(".json") else cp + ".json") for cp in args.checkpoint] args.checkpoint = glob_all(args.checkpoint) args.checkpoint = [cp[:-5] for cp in args.checkpoint] # create ctc decoder prepare_ctc_decoder_params(args.ctc_decoder) # predict for all models from calamari_ocr.ocr.predict.predictor import MultiPredictor predictor = MultiPredictor.from_paths( checkpoints=args.checkpoint, voter_params=args.voter, predictor_params=args.predictor, ) do_prediction = predictor.predict(args.data) pipeline: CalamariPipeline = predictor.data.get_or_create_pipeline(predictor.params.pipeline, args.data) reader = pipeline.reader() if len(reader) == 0: raise Exception("Empty dataset provided. Check your command line arguments or if the provided files are empty.") avg_sentence_confidence = 0 n_predictions = 0 reader.prepare_store() # output the voted results to the appropriate files for s in do_prediction: inputs, (result, prediction), meta = s.inputs, s.outputs, s.meta sample = reader.sample_by_id(meta["id"]) n_predictions += 1 sentence = prediction.sentence avg_sentence_confidence += prediction.avg_char_probability if args.verbose: lr = "\u202A\u202B" logger.info("{}: '{}{}{}'".format(meta["id"], lr[get_base_level(sentence)], sentence, "\u202C")) output_dir = args.output_dir if args.output_dir else os.path.dirname(prediction.line_path) reader.store_text_prediction(sentence, meta["id"], output_dir=output_dir) if args.extended_prediction_data: ps = Predictions() ps.line_path = sample["image_path"] if "image_path" in sample else sample["id"] ps.predictions.extend([prediction] + [r.prediction for r in result]) output_dir = output_dir if output_dir else os.path.dirname(ps.line_path) if not os.path.exists(output_dir): os.mkdir(output_dir) if args.extended_prediction_data_format == "pred": data = zlib.compress(ps.to_json(indent=2, ensure_ascii=False).encode("utf-8")) elif args.extended_prediction_data_format == "json": # remove logits for p in ps.predictions: p.logits = None data = ps.to_json(indent=2) else: raise Exception("Unknown prediction format.") reader.store_extended_prediction( data, sample, output_dir=output_dir, extension=args.extended_prediction_data_format, ) logger.info("Average sentence confidence: {:.2%}".format(avg_sentence_confidence / n_predictions)) reader.store() logger.info("All prediction files written") def main(): parser = PAIArgumentParser() parser.add_argument("--version", action="version", version="%(prog)s v" + __version__) parser.add_root_argument("root", PredictArgs, flat=True) args = parser.parse_args() run(args.root) if __name__ == "__main__": main()
4,405
1,639
91
c1e3aaef01cfa4a5cc14f7225f454aa2d7e4a3f1
13,767
py
Python
detect_wrapper.py
jobpasin/tensorflow-yolov4
52ffe2e21ee715bfcaa72058a4c32a3942fc594e
[ "MIT" ]
null
null
null
detect_wrapper.py
jobpasin/tensorflow-yolov4
52ffe2e21ee715bfcaa72058a4c32a3942fc594e
[ "MIT" ]
null
null
null
detect_wrapper.py
jobpasin/tensorflow-yolov4
52ffe2e21ee715bfcaa72058a4c32a3942fc594e
[ "MIT" ]
null
null
null
import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1' import sys import cv2 import numpy as np import tensorflow as tf from tensorflow.compat.v1 import ConfigProto from tensorflow.compat.v1 import InteractiveSession from tensorflow.python.saved_model import tag_constants import tensorflow_yolov4.core.utils as utils from absl import logging import time from queue import Queue, Empty, Full from threading import Event from typing import Union, List from core.utils import TimeTracker # from tensorflow_yolov4.core.yolov4 import filter_boxes sys.stdout.flush() def draw_bbox(frame, pred_bbox, boundary=None, classes=None): """ Draw bounding box on yolov4 output @param frame: @param pred_bbox: Direct output from yolov4 @param boundary: WarpMatrix class. Show only bbox in boundary. Give None to show all bbox in the image @param classes: List of full class name @return: """ return utils.draw_bbox(frame, pred_bbox, classes=classes, show_label=True, boundary=boundary)
48.819149
118
0.575507
import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1' import sys import cv2 import numpy as np import tensorflow as tf from tensorflow.compat.v1 import ConfigProto from tensorflow.compat.v1 import InteractiveSession from tensorflow.python.saved_model import tag_constants import tensorflow_yolov4.core.utils as utils from absl import logging import time from queue import Queue, Empty, Full from threading import Event from typing import Union, List from core.utils import TimeTracker # from tensorflow_yolov4.core.yolov4 import filter_boxes sys.stdout.flush() class YoloV4: def __init__(self, FLAGS, interested_class: Union[dict, List] = None): logging.set_verbosity(logging.WARNING) # config = ConfigProto() # config.gpu_options.allow_growth = True # session = tf.compat.v1.Session(config=config) # tf.debugging.set_log_device_placement(True) gpus = tf.config.experimental.list_physical_devices('GPU') logging.debug(f"Number of GPU: {gpus}") try: # Currently, memory growth needs to be the same across GPUs assert FLAGS.gpu < len(gpus), "--gpu is higher than number of gpu available. " \ "(Choose integer less than or equal to {} or use -1)".format(len(gpus) - 1) if FLAGS.gpu != -1: tf.config.experimental.set_visible_devices(gpus[FLAGS.gpu], 'GPU') for gpu in gpus: tf.config.experimental.set_memory_growth(gpu, True) logical_gpus = tf.config.experimental.list_logical_devices('GPU') logging.debug("{} Physical GPUS, {} Logical GPUS".format(len(gpus), len(logical_gpus))) except RuntimeError as e: # Memory growth must be set before GPUs have been initialized print(e) self.tt_total = utils.TimeTracker(FLAGS.time_report_freq * 15, "YOLOV4 Total") self.tt_infer = utils.TimeTracker(FLAGS.time_report_freq * 15, "Yolo Inference") self.tt_suppress = utils.TimeTracker(FLAGS.time_report_freq * 15, "Yolo Suppress") self.tt_filter = utils.TimeTracker(FLAGS.time_report_freq * 15, "Yolo Filter") self.frame_id = 0 if len(gpus) == 0: logging.warning('No GPU found') self.strategy = tf.distribute.MirroredStrategy() self.FLAGS = FLAGS if type(interested_class) is list: self.interested_class = {} for i in interested_class: self.interested_class[i] = i else: self.interested_class = interested_class self.interpreter = None with self.strategy.scope(): self.saved_model_loaded = None self.infer = None if FLAGS.framework == 'tflite': self.interpreter = tf.lite.Interpreter(model_path=FLAGS.weights) self.interpreter.allocate_tensors() self.input_details = self.interpreter.get_input_details() self.output_details = self.interpreter.get_output_details() print("input details: ", self.input_details) print("output details: ", self.output_details) else: self.saved_model_loaded = tf.saved_model.load(FLAGS.weights, tags=[tag_constants.SERVING]) self.infer = self.saved_model_loaded.signatures['serving_default'] if FLAGS.debug: logging.set_verbosity(logging.DEBUG) else: logging.set_verbosity(logging.INFO) temp_image = np.random.randint(0, 255, (608, 608, 3)) temp_queue, temp_queue2 = Queue(), Queue() temp_queue.put([temp_image, 0]) temp_queue.put([None, None]) self.predict_wrapper(temp_queue, temp_queue2, 1, Event()) def predict_wrapper(self, in_queue: Queue, out_queue: Queue, batch_size: int, stop_event: Event): if self.FLAGS.framework == 'tflite': raise ValueError("") image_buffer, frame_id_buffer, image_copy_buffer = [], [], [] STRIDES, ANCHORS, NUM_CLASS, XYSCALE = utils.load_config(self.FLAGS) input_size = self.FLAGS.size stop_flag = False while not stop_flag: if stop_event.isSet(): # Clear data in queue if receiving stop signal with in_queue.mutex: in_queue.queue.clear() break # if in_queue.qsize() == 0: # continue # Fetching data wait_start_time = time.time() try: frame, frame_id = in_queue.get(timeout=20) except Empty: logging.error("Yolo thread timeout. No image found for a certain time") break start_time = time.time() # Add data into the list until the list has [batch_size] images if frame is None: stop_flag = True else: # self.wait_time_tracker.add(start_time - wait_start_time, frame_id) frame_size = frame.shape[:2] image_copy_buffer.append(frame.copy()) image_data = cv2.resize(frame, (input_size, input_size)) image_data = image_data / 255. # image_data = image_data[np.newaxis, ...].astype(np.float32) image_buffer.append(image_data) frame_id_buffer.append(frame_id) # Run detection when we have [batch_size] images, or has stop_flag (finish program) if len(image_buffer) == batch_size or stop_flag: if len(image_buffer) > 0: image_data = np.stack(image_buffer).astype(np.float32) batch_data = tf.constant(image_data) infer_start = time.time() pred_bbox = self.infer(batch_data) infer_end = time.time() for key, value in pred_bbox.items(): boxes = value[:, :, 0:4] pred_conf = value[:, :, 4:] boxes, scores, classes, valid_detections = tf.image.combined_non_max_suppression( boxes=tf.reshape(boxes, (tf.shape(boxes)[0], -1, 1, 4)), scores=tf.reshape( pred_conf, (tf.shape(pred_conf)[0], -1, tf.shape(pred_conf)[-1])), max_output_size_per_class=50, max_total_size=50, iou_threshold=self.FLAGS.iou, score_threshold=self.FLAGS.score ) pred_bboxes = [boxes.numpy(), scores.numpy(), classes.numpy(), valid_detections.numpy()] non_max = time.time() if self.interested_class is not None: # Filter only prediction of interested class pred_bboxes = self.filter_class(pred_bboxes) filter = time.time() # Send prediction one by one for i in range(np.shape(pred_bboxes[3])[0]): pred_bbox = [pred_bboxes[0][i:i + 1, :, :], pred_bboxes[1][i:i + 1, :], pred_bboxes[2][i:i + 1, :], pred_bboxes[3][i:i + 1]] if not stop_event.isSet(): try: out_queue.put([pred_bbox, frame_id_buffer[i], image_copy_buffer[i]], timeout=25) except Full: logging.error("bbox_queue: Read vid timeout. Post-processing might take too long") break end_time = time.time() # self.tt_total.add(end_time - start_time, frame_id) # self.tt_infer.add(infer_end - infer_start, frame_id) # self.tt_suppress.add(non_max - infer_end, frame_id) # self.tt_filter.add(filter - non_max, frame_id) # Reset buffer after predictions image_buffer, frame_id_buffer, image_copy_buffer = [], [], [] if stop_flag: try: out_queue.put([None, None, None], timeout=25) except Full: pass logging.debug("Yolo thread complete") def predict(self, frame): """ Predict with yolo @param frame: ndarray(608,608,3) or list of ndarray of images @return: list[4] of output : bboxes, scores, classes, num_rect or the list of list[4] """ STRIDES, ANCHORS, NUM_CLASS, XYSCALE = utils.load_config(self.FLAGS) input_size = self.FLAGS.size video_path = self.FLAGS.video # frame_id = 0 # start_time = time.time() if type(frame) is not list: frame = [frame] image_data = [] for index in range(len(frame)): image = frame[index] frame_size = image.shape[:2] image = cv2.resize(image, (input_size, input_size)) image = image / 255. # image = image[np.newaxis, ...].astype(np.float32) image_data.append(image) image_data = np.stack(image_data).astype(np.float32) if self.FLAGS.framework == 'tflite': self.interpreter.set_tensor(self.input_details[0]['index'], image_data) self.interpreter.invoke() pred = [self.interpreter.get_tensor(self.output_details[i]['index']) for i in range(len(self.output_details))] if self.FLAGS.model == 'yolov3' and self.FLAGS.tiny == True: boxes, pred_conf = filter_boxes(pred[1], pred[0], score_threshold=0.25, input_shape=tf.constant([input_size, input_size])) else: boxes, pred_conf = filter_boxes(pred[0], pred[1], score_threshold=0.25, input_shape=tf.constant([input_size, input_size])) else: batch_data = tf.constant(image_data, name='batch_data') pred_bbox = self.infer(batch_data) for key, value in pred_bbox.items(): boxes = value[:, :, 0:4] pred_conf = value[:, :, 4:] boxes, scores, classes, valid_detections = tf.image.combined_non_max_suppression( boxes=tf.reshape(boxes, (tf.shape(boxes)[0], -1, 1, 4)), scores=tf.reshape( pred_conf, (tf.shape(pred_conf)[0], -1, tf.shape(pred_conf)[-1])), max_output_size_per_class=50, max_total_size=50, iou_threshold=self.FLAGS.iou, score_threshold=self.FLAGS.score ) pred_bboxes = [boxes.numpy(), scores.numpy(), classes.numpy(), valid_detections.numpy()] if self.interested_class is not None: pred_bboxes = self.filter_class(pred_bboxes) # Send prediction one by one out_pred_bbox = [] for i in range(np.shape(pred_bboxes[3])[0]): pred_bbox = [pred_bboxes[0][i:i + 1, :, :], pred_bboxes[1][i:i + 1, :], pred_bboxes[2][i:i + 1, :], pred_bboxes[3][i:i + 1]] out_pred_bbox.append(pred_bbox) self.frame_id += 1 # end_time = time.time() # self.time_tracker.add(end_time - start_time, self.frame_id) if len(out_pred_bbox) == 1: return out_pred_bbox[0] return out_pred_bbox def filter_class(self, pred_bbox): boxes_new, scores_new, classes_new, valid_detection_new = [], [], [], [] num_detection = np.shape(pred_bbox[2])[1] num_batch = np.shape(pred_bbox[3])[0] for batch in range(num_batch): boxes_temp, scores_temp, classes_temp = [], [], [] current_detections = 0 for i in range(pred_bbox[3][batch]): if int(pred_bbox[2][batch, i]) in self.interested_class: boxes_temp.append(pred_bbox[0][batch, i, :]) scores_temp.append(pred_bbox[1][batch, i]) classes_temp.append(pred_bbox[2][batch, i]) current_detections += 1 for _ in range(num_detection - current_detections): boxes_temp.append(np.zeros([4])) scores_temp.append(0.0) classes_temp.append(0.0) # if current_detections == 0: # boxes_new.append(np.zeros([1,4])) # scores_new.append(np.zeros([1])) # classes_new.append(np.zeros([0])) # valid_detection_new.append(current_detections) # # return ([np.zeros([1, 0, 4]), np.zeros([1, 0]), np.zeros([1, 0]), np.array([current_detections])]) # else: boxes_new.append(np.stack(boxes_temp)) scores_new.append(np.stack(scores_temp)) classes_new.append(np.stack(classes_temp)) valid_detection_new.append(current_detections) # return [np.expand_dims(np.stack(boxes_temp), axis=0), np.expand_dims(np.stack(scores_temp), axis=0), # np.expand_dims(np.stack(classes_temp), axis=0), np.array([current_detections])] return [np.stack(boxes_new), np.stack(scores_new), np.stack(classes_new), np.array(valid_detection_new)] def draw_bbox(frame, pred_bbox, boundary=None, classes=None): """ Draw bounding box on yolov4 output @param frame: @param pred_bbox: Direct output from yolov4 @param boundary: WarpMatrix class. Show only bbox in boundary. Give None to show all bbox in the image @param classes: List of full class name @return: """ return utils.draw_bbox(frame, pred_bbox, classes=classes, show_label=True, boundary=boundary)
9,505
3,230
23
abbbd08479e35cd1f8448cdae81203f7b33d7947
5,991
py
Python
src/cogs/buttonrole.py
Infernum1/Spacebot
1a393334ff03ea9d6015498e96adb2ad6a8481b4
[ "MIT" ]
48
2021-12-03T19:19:35.000Z
2022-03-28T08:41:15.000Z
src/cogs/buttonrole.py
27Saumya/Spacebot
9736ae2543de5d59114eb9a027b9f8787c172057
[ "MIT" ]
30
2021-12-06T10:22:35.000Z
2022-01-23T10:50:02.000Z
src/cogs/buttonrole.py
27Saumya/Spacebot
9736ae2543de5d59114eb9a027b9f8787c172057
[ "MIT" ]
14
2021-12-08T18:20:36.000Z
2022-03-06T18:01:30.000Z
import discord import aiosqlite from discord.commands import slash_command from discord.ext import commands # Courtesy of Pycord examples """ Let users assign themselves roles by clicking on Buttons. The view made is persistent, so it will work even when the bot restarts. See this example for more information about persistent views https://github.com/Pycord-Development/pycord/blob/master/examples/views/persistent.py Make sure to load this cog when your bot starts! """ class ButtonRoleCog(commands.Cog): """A cog with a slash command for posting the message with buttons and to initialize the view again when the bot is restarted """ # make sure to set the guild ID here to whatever server you want the buttons in @slash_command(name="reactionrole") async def reactionrole( self, ctx, channel: discord.TextChannel, title: str, description: str, role1: discord.Role, role2: discord.Role = None, role3: discord.Role = None, ): """Slash command to post a new view with a button for each role""" if not ctx.author.guild_permissions.manage_roles == True: return await ctx.respond("You dont have the permission to manage roles -_-") # timeout is None because we want this view to be persistent view = discord.ui.View(timeout=None) role_ids = [role1.id] if role2 is not None: role_ids.append(role2.id) if role3 is not None: role_ids.append(role3.id) # loop through the list of roles and add a new button to the view for each role for role_id in role_ids: # get the role the guild by ID try: await self.bot.db.execute( "INSERT INTO Roles(id , guild_id) VALUES (? ,?)", (role_id, ctx.guild.id), ) except aiosqlite.IntegrityError: return await ctx.respond( "A Button role with the same thing already exists.\n In order to cancel that role, just use the command /reactionrole_remove <roleid>" ) self.bot.db.commit() role = ctx.guild.get_role(role_id) view.add_item(RoleButton(role)) await ctx.respond("success", ephemeral=True) await channel.send( embed=discord.Embed( title=title, description=description, colour=discord.Colour.random() ), view=view, ) @slash_command(name="rr_remove") async def reactionrole_remove(self, ctx, role: discord.Role): """Slash command to remove a role button""" if not ctx.author.guild_permissions.manage_roles == True: return await ctx.respond("You dont have the permission to manage roles -_-") try: self.bot.db.execute("DELETE FROM Roles WHERE id = ?", (role.id,)) self.bot.db.commit() await ctx.respond("Successfully removed the role button") except aiosqlite.IntegrityError: await ctx.respond( "A Button role with the same thing already exists.\n In order to cancel that role, just use the command /reactionrole_remove <roleid>" ) @commands.Cog.listener() async def on_ready(self): """This function is called every time the bot restarts. If a view was already created before (with the same custom IDs for buttons) it will be loaded and the bot will start watching for button clicks again. """ # we recreate the view as we did in the /post command view = discord.ui.View(timeout=None) role = self.bot.db.execute("SELECT * FROM Roles") # make a list of guilds and roles of that guild for row in role: role = self.bot.get_guild(row[1]).get_role(row[0]) view.add_item(RoleButton(role)) # add the view to the bot so it will watch for button interactions self.bot.add_view(view)
38.651613
155
0.602737
import discord import aiosqlite from discord.commands import slash_command from discord.ext import commands # Courtesy of Pycord examples """ Let users assign themselves roles by clicking on Buttons. The view made is persistent, so it will work even when the bot restarts. See this example for more information about persistent views https://github.com/Pycord-Development/pycord/blob/master/examples/views/persistent.py Make sure to load this cog when your bot starts! """ class RoleButton(discord.ui.Button): def __init__(self, role: discord.Role): """ A button for one role. `custom_id` is needed for persistent views. """ super().__init__( label=role.name, style=discord.enums.ButtonStyle.primary, custom_id=str(role.id), ) async def callback(self, interaction: discord.Interaction): """This function will be called any time a user clicks on this button Parameters ---------- interaction : discord.Interaction The interaction object that was created when the user clicked on the button """ # figure out who clicked the button user = interaction.user # get the role this button is for (stored in the custom ID) role = interaction.guild.get_role(int(self.custom_id)) if role is None: # if this role doesn't exist, ignore # you can do some error handling here return # passed all checks # add the role and send a response to the uesr ephemerally (hidden to other users) if role not in user.roles: # give the user the role if they don't already have it await user.add_roles(role) await interaction.response.send_message( f"🎉 You have been given the role {role.mention}", ephemeral=True ) else: # else, take the role from the user await user.remove_roles(role) await interaction.response.send_message( f"❌ The {role.mention} role has been taken from you", ephemeral=True ) class ButtonRoleCog(commands.Cog): """A cog with a slash command for posting the message with buttons and to initialize the view again when the bot is restarted """ def __init__(self, bot): self.bot = bot # make sure to set the guild ID here to whatever server you want the buttons in @slash_command(name="reactionrole") async def reactionrole( self, ctx, channel: discord.TextChannel, title: str, description: str, role1: discord.Role, role2: discord.Role = None, role3: discord.Role = None, ): """Slash command to post a new view with a button for each role""" if not ctx.author.guild_permissions.manage_roles == True: return await ctx.respond("You dont have the permission to manage roles -_-") # timeout is None because we want this view to be persistent view = discord.ui.View(timeout=None) role_ids = [role1.id] if role2 is not None: role_ids.append(role2.id) if role3 is not None: role_ids.append(role3.id) # loop through the list of roles and add a new button to the view for each role for role_id in role_ids: # get the role the guild by ID try: await self.bot.db.execute( "INSERT INTO Roles(id , guild_id) VALUES (? ,?)", (role_id, ctx.guild.id), ) except aiosqlite.IntegrityError: return await ctx.respond( "A Button role with the same thing already exists.\n In order to cancel that role, just use the command /reactionrole_remove <roleid>" ) self.bot.db.commit() role = ctx.guild.get_role(role_id) view.add_item(RoleButton(role)) await ctx.respond("success", ephemeral=True) await channel.send( embed=discord.Embed( title=title, description=description, colour=discord.Colour.random() ), view=view, ) @slash_command(name="rr_remove") async def reactionrole_remove(self, ctx, role: discord.Role): """Slash command to remove a role button""" if not ctx.author.guild_permissions.manage_roles == True: return await ctx.respond("You dont have the permission to manage roles -_-") try: self.bot.db.execute("DELETE FROM Roles WHERE id = ?", (role.id,)) self.bot.db.commit() await ctx.respond("Successfully removed the role button") except aiosqlite.IntegrityError: await ctx.respond( "A Button role with the same thing already exists.\n In order to cancel that role, just use the command /reactionrole_remove <roleid>" ) @commands.Cog.listener() async def on_ready(self): """This function is called every time the bot restarts. If a view was already created before (with the same custom IDs for buttons) it will be loaded and the bot will start watching for button clicks again. """ # we recreate the view as we did in the /post command view = discord.ui.View(timeout=None) role = self.bot.db.execute("SELECT * FROM Roles") # make a list of guilds and roles of that guild for row in role: role = self.bot.get_guild(row[1]).get_role(row[0]) view.add_item(RoleButton(role)) # add the view to the bot so it will watch for button interactions self.bot.add_view(view) def setup(bot): # load the cog bot.add_cog(ButtonRoleCog(bot))
78
1,699
79
eea26823d632d9aada73bba8a8562d67323244cd
729
py
Python
tests/paradrop/backend/test_token_manager.py
lhartung/paradrop-test
22a491bf3198bf61bcabaedfaecde5b9be97e76f
[ "Apache-2.0" ]
76
2015-08-24T18:15:20.000Z
2021-12-06T20:03:19.000Z
tests/paradrop/backend/test_token_manager.py
leilei1881/Paradrop
546464e075f8a226b9eb4fe444390dc5c8527ad9
[ "Apache-2.0" ]
35
2015-07-07T22:27:49.000Z
2022-03-01T17:13:40.000Z
tests/paradrop/backend/test_token_manager.py
lhartung/paradrop-test
22a491bf3198bf61bcabaedfaecde5b9be97e76f
[ "Apache-2.0" ]
27
2016-02-03T22:00:09.000Z
2021-09-26T16:59:38.000Z
import time from mock import patch, MagicMock from paradrop.backend import token_manager @patch("paradrop.backend.token_manager.nexus")
27
49
0.717421
import time from mock import patch, MagicMock from paradrop.backend import token_manager def test_generate_jwt_secret(): secret = token_manager.generate_jwt_secret() assert isinstance(secret, basestring) assert len(secret) >= 32 @patch("paradrop.backend.token_manager.nexus") def test_TokenManager_issue(nexus): nexus.core.info.pdid = 'halo42' nexus.core.getKey.return_value = None manager = token_manager.TokenManager() token = manager.issue('test') assert isinstance(token, basestring) decoded = manager.decode(token) assert decoded['exp'] > time.time() assert decoded['iat'] < time.time() assert decoded['iss'] == nexus.core.info.pdid assert decoded['sub'] == 'test'
544
0
45
154a33fc57b757260cefdc34b640f03d0463f7c5
10,613
py
Python
TeMail.py
k8scat/TeMail
32591ebf0d9774c8d9ce7aee90946e2502f81263
[ "MIT" ]
null
null
null
TeMail.py
k8scat/TeMail
32591ebf0d9774c8d9ce7aee90946e2502f81263
[ "MIT" ]
null
null
null
TeMail.py
k8scat/TeMail
32591ebf0d9774c8d9ce7aee90946e2502f81263
[ "MIT" ]
1
2019-10-20T14:29:03.000Z
2019-10-20T14:29:03.000Z
# -*- coding: utf-8 -*- """ @author: hsowan <hsowan.me@gmail.com> @date: 2019/10/19 """ import os from tkinter import * from tkinter import simpledialog, messagebox, filedialog, dialog from tkinter import ttk import yaml import smtplib from email.mime.text import MIMEText from email.header import Header from smtplib import SMTP_SSL, SMTP from email.utils import parseaddr, formataddr from email.mime.multipart import MIMEMultipart import time import webbrowser settings_file = 'settings.yaml' def compute_x_y(master, width, height): """计算组件的居中坐标 :param master: :param width: :param height: :return: """ ws = master.winfo_screenwidth() hs = master.winfo_screenheight() x = int((ws / 2) - (width / 2)) y = int((hs / 2) - (height / 2)) return f'{width}x{height}+{x}+{y}' class SettingsDialog(Toplevel): """设置对话框""" # 定义构造方法 # 通过该方法来创建自定义对话框的内容 # 通过该方法来创建对话框下方的按钮框 def validate(self): """检验配置""" pass def save(self): """保存配置""" pass class Application(Frame): """主窗口""" def import_mails(self): """导入邮箱列表""" file = filedialog.askopenfile(title='导入邮箱列表', filetypes=[('文本文件', '*.txt'), ('CSV文件', '*.csv'), ('xlsx文件', '*.xlsx')]) self.mail_recipients = file.read().split('\n') print(self.mail_recipients) def open_settings(self): """打开设置""" d = SettingsDialog(self.master, title='模式对话框') # 默认是模式对话框 def send_mails(self, preview=False): """发送邮件""" # 获取用户配置 with open(settings_file, 'r') as f: settings = yaml.load(f, Loader=yaml.FullLoader) host_port = (settings['host'], settings['port']) smtp = SMTP_SSL(*host_port) if settings['ssh'] else SMTP(*host_port) try: # smtp.set_debuglevel(1) smtp.login(settings['user'], settings['pass']) except smtplib.SMTPException as e: self.open_simpledialog('SMTP设置有误', str(e)) subject = self.mail_subject.get() content = self.mail_content.get(1.0, END) root_msg = MIMEMultipart() # 发件人 root_msg['From'] = self._format_addr(f'{settings["name"]} <{settings["user"]}>') # 邮件主题 root_msg['Subject'] = Header(subject, 'utf-8').encode() # 邮件内容 html_message = MIMEText(content, 'html', 'utf-8') root_msg.attach(html_message) # 附件 if self.mail_attach_in.get(): try: for attachment_path in self.mail_attach_in.get().split(';'): att = MIMEText(open(attachment_path, 'rb').read(), 'base64', 'utf-8') att['Content-Type'] = 'application/octet-stream' att['Content-Disposition'] = f'attachment;filename="{attachment_path.split(os.path.sep).pop()}"' root_msg.attach(att) except FileNotFoundError as e: self.open_simpledialog('邮件推送', str(e)) if preview: root_msg['To'] = Header(settings['user'], 'utf-8').encode() try: # 发送邮件 smtp.sendmail(settings['user'], settings['user'], root_msg.as_string()) self.open_simpledialog('预览', '发送成功') except smtplib.SMTPException as e: self.open_simpledialog('预览', '发送失败: ' + str(e)) else: # Todo: 显示推送成功与失败的列表 success_mails = [] failed_mails = [] recipients_count = len(self.mail_recipients) # 设置进度条的最大值 self.push_progress['maximum'] = recipients_count # 显示进度条 self.push_progress.place(x=70, y=350) self.push_progress.update() if not self.mail_recipients: self.open_simpledialog('邮件推送', '没有导入收件人列表') return for i, recipient in enumerate(self.mail_recipients): root_msg['To'] = Header(recipient, 'utf-8').encode() try: # 发送邮件 smtp.sendmail(settings['user'], [recipient], root_msg.as_string()) success_mails.append(recipient) # 发送延时 if i != recipients_count - 1: time.sleep(settings['delay']) except smtplib.SMTPException as e: failed_mails.append(dict(to=recipient, error=str(e))) finally: # 更新进度条 self.push_progress['value'] += 1 self.push_progress.update() self.open_simpledialog('邮件推送', f'推送成功: {len(success_mails)} 封\n推送失败: {len(failed_mails)} 封') # 删除进度条 self.push_progress.place_forget() # 重置进度条 self.push_progress['value'] = 0 smtp.quit() @staticmethod def _format_addr(s): """格式化发件人 Refer: https://www.liaoxuefeng.com/wiki/1016959663602400/1017790702398272 """ name, addr = parseaddr(s) return formataddr((Header(name, 'utf-8').encode(), addr)) def open_simpledialog(self, title, msg): """显示对话框 Refer: http://c.biancheng.net/view/2523.html :param title: 对话框标题 :param msg: 对话框内容 :return: """ d = simpledialog.SimpleDialog(self.master, title=title, text=msg, cancel=3, default=0) d.root.geometry(compute_x_y(self.master, 240, 100)) d.root.grab_set() d.root.wm_resizable(width=False, height=False) d.go() if __name__ == '__main__': # 创建Tk对象, Tk代表窗口 root = Tk() # 设置窗口标题 root.title('特邮') # 禁止改变窗口大小 root.resizable(width=False, height=False) root.geometry(compute_x_y(root, 600, 400)) app = Application(master=root) # 启动主窗口的消息循环 app.mainloop()
31.306785
116
0.576274
# -*- coding: utf-8 -*- """ @author: hsowan <hsowan.me@gmail.com> @date: 2019/10/19 """ import os from tkinter import * from tkinter import simpledialog, messagebox, filedialog, dialog from tkinter import ttk import yaml import smtplib from email.mime.text import MIMEText from email.header import Header from smtplib import SMTP_SSL, SMTP from email.utils import parseaddr, formataddr from email.mime.multipart import MIMEMultipart import time import webbrowser settings_file = 'settings.yaml' def compute_x_y(master, width, height): """计算组件的居中坐标 :param master: :param width: :param height: :return: """ ws = master.winfo_screenwidth() hs = master.winfo_screenheight() x = int((ws / 2) - (width / 2)) y = int((hs / 2) - (height / 2)) return f'{width}x{height}+{x}+{y}' class SettingsDialog(Toplevel): """设置对话框""" # 定义构造方法 def __init__(self, parent, title=None): Toplevel.__init__(self, parent) self.transient(parent) # 设置标题 if title: self.title(title) self.parent = parent # 创建对话框的主体内容 frame = Frame(self) frame.pack(padx=5, pady=5) # 调用init_buttons方法初始化对话框下方的按钮 self.init_buttons() # 设置为模式对话框 self.grab_set() # 为"WM_DELETE_WINDOW"协议使用self.cancel_click事件处理方法 self.protocol("WM_DELETE_WINDOW", self.cancel_click) # 根据父窗口来设置对话框的位置 self.geometry(f'+{parent.winfo_rootx() + 50}+{parent.winfo_rooty() + 50}') # 调用init_widgets方法来初始化对话框界面 self.init_widgets(frame) # 让对话框获取焦点 self.focus_set() self.wait_window(self) # 通过该方法来创建自定义对话框的内容 def init_widgets(self, master): # 创建并添加Label Label(master, text='用户名', font=12, width=10).grid(row=1, column=0) # 创建并添加Entry,用于接受用户输入的用户名 self.name_entry = Entry(master, font=16) self.name_entry.grid(row=1, column=1) # 创建并添加Label Label(master, text='密 码', font=12, width=10).grid(row=2, column=0) # 创建并添加Entry,用于接受用户输入的密码 self.pass_entry = Entry(master, font=16) self.pass_entry.grid(row=2, column=1) # 通过该方法来创建对话框下方的按钮框 def init_buttons(self): f = Frame(self) # 创建"确定"按钮,位置绑定self.ok_click处理方法 w = Button(f, text="确定", width=10, command=self.ok_click, default=ACTIVE) w.pack(side=LEFT, padx=5, pady=5) # 创建"确定"按钮,位置绑定self.cancel_click处理方法 w = Button(f, text="取消", width=10, command=self.cancel_click) w.pack(side=LEFT, padx=5, pady=5) self.bind("<Return>", self.ok_click) self.bind("<Escape>", self.cancel_click) f.pack() def validate(self): """检验配置""" pass def save(self): """保存配置""" pass def ok_click(self, event=None): print('确定') # 如果不能通过校验,让用户重新输入 if not self.validate(): self.focus_set() return self.withdraw() self.update_idletasks() # 获取用户输入数据 self.save() # 将焦点返回给父窗口 self.parent.focus_set() # 销毁自己 self.destroy() def cancel_click(self, event=None): print('取消') # 将焦点返回给父窗口 self.parent.focus_set() # 销毁自己 self.destroy() class Application(Frame): """主窗口""" def __init__(self, master=None): Frame.__init__(self, master) self.pack() self.init_widgets() self.mail_recipients = None def init_widgets(self): # 创建menubar,它被放入self.master中 menubar = Menu(self.master) # 添加菜单条 self.master['menu'] = menubar settings_menu = Menu(menubar, tearoff=0) # 使用add_cascade方法添加 menubar.add_cascade(label='设置', menu=settings_menu) settings_menu.add_command(label="SMTP", command=self.open_settings) mail_lbs = ['邮件主题', '附件', '邮件内容(HTML)'] for i, mail_lb in enumerate(mail_lbs): # 邮件主题标签 lb = Label(self.master, text=mail_lb) lb.place(x=65, y=18 + i * 30) # 邮件主题的输入框 self.mail_subject = ttk.Entry(self.master, width=40) self.mail_subject.place(x=150, y=17) # 附件的输入框 self.mail_attach_in = StringVar() ttk.Entry(self.master, width=30, textvariable=self.mail_attach_in).place(x=150, y=47) # 浏览文件按钮 ttk.Button(self.master, text='浏览', command=self.choose_attachments).place(x=433, y=47) # 添加编辑器链接 editor_link = Label(self.master, text='点击编辑HTML', fg='blue') editor_link.place(x=422, y=78) editor_link.bind('<Button-1>', self.open_editor) self.mail_content = Text(self.master, width=63, height=15) self.mail_content.config(highlightbackground='#D3D3D3') self.mail_content.place(x=70, y=105) # 预览按钮 ttk.Button(self.master, text='预览', command=self.preview).place(x=70, y=315) # 导入收件人列表按钮 ttk.Button(self.master, text='导入收件人列表', command=self.import_mails).place(x=180, y=315) # 推送按钮 ttk.Button(self.master, text='开始推送', command=self.send_mails).place(x=330, y=315) # 推送进度条 self.push_progress = ttk.Progressbar(self.master, orient="horizontal", length=448, mode="determinate") self.push_progress['value'] = 0 def open_editor(self, event): editor_url = 'https://wysiwyg.ncucoder.com' webbrowser.open(editor_url) def import_mails(self): """导入邮箱列表""" file = filedialog.askopenfile(title='导入邮箱列表', filetypes=[('文本文件', '*.txt'), ('CSV文件', '*.csv'), ('xlsx文件', '*.xlsx')]) self.mail_recipients = file.read().split('\n') print(self.mail_recipients) def choose_attachments(self): self.attachments = filedialog.askopenfiles(title='添加邮件附件') files = '' for i, attachment in enumerate(self.attachments): files += attachment.name if i != len(self.attachments) - 1: files += ';' self.mail_attach_in.set(files) def open_settings(self): """打开设置""" d = SettingsDialog(self.master, title='模式对话框') # 默认是模式对话框 def preview(self): self.send_mails(preview=True) def send_mails(self, preview=False): """发送邮件""" # 获取用户配置 with open(settings_file, 'r') as f: settings = yaml.load(f, Loader=yaml.FullLoader) host_port = (settings['host'], settings['port']) smtp = SMTP_SSL(*host_port) if settings['ssh'] else SMTP(*host_port) try: # smtp.set_debuglevel(1) smtp.login(settings['user'], settings['pass']) except smtplib.SMTPException as e: self.open_simpledialog('SMTP设置有误', str(e)) subject = self.mail_subject.get() content = self.mail_content.get(1.0, END) root_msg = MIMEMultipart() # 发件人 root_msg['From'] = self._format_addr(f'{settings["name"]} <{settings["user"]}>') # 邮件主题 root_msg['Subject'] = Header(subject, 'utf-8').encode() # 邮件内容 html_message = MIMEText(content, 'html', 'utf-8') root_msg.attach(html_message) # 附件 if self.mail_attach_in.get(): try: for attachment_path in self.mail_attach_in.get().split(';'): att = MIMEText(open(attachment_path, 'rb').read(), 'base64', 'utf-8') att['Content-Type'] = 'application/octet-stream' att['Content-Disposition'] = f'attachment;filename="{attachment_path.split(os.path.sep).pop()}"' root_msg.attach(att) except FileNotFoundError as e: self.open_simpledialog('邮件推送', str(e)) if preview: root_msg['To'] = Header(settings['user'], 'utf-8').encode() try: # 发送邮件 smtp.sendmail(settings['user'], settings['user'], root_msg.as_string()) self.open_simpledialog('预览', '发送成功') except smtplib.SMTPException as e: self.open_simpledialog('预览', '发送失败: ' + str(e)) else: # Todo: 显示推送成功与失败的列表 success_mails = [] failed_mails = [] recipients_count = len(self.mail_recipients) # 设置进度条的最大值 self.push_progress['maximum'] = recipients_count # 显示进度条 self.push_progress.place(x=70, y=350) self.push_progress.update() if not self.mail_recipients: self.open_simpledialog('邮件推送', '没有导入收件人列表') return for i, recipient in enumerate(self.mail_recipients): root_msg['To'] = Header(recipient, 'utf-8').encode() try: # 发送邮件 smtp.sendmail(settings['user'], [recipient], root_msg.as_string()) success_mails.append(recipient) # 发送延时 if i != recipients_count - 1: time.sleep(settings['delay']) except smtplib.SMTPException as e: failed_mails.append(dict(to=recipient, error=str(e))) finally: # 更新进度条 self.push_progress['value'] += 1 self.push_progress.update() self.open_simpledialog('邮件推送', f'推送成功: {len(success_mails)} 封\n推送失败: {len(failed_mails)} 封') # 删除进度条 self.push_progress.place_forget() # 重置进度条 self.push_progress['value'] = 0 smtp.quit() @staticmethod def _format_addr(s): """格式化发件人 Refer: https://www.liaoxuefeng.com/wiki/1016959663602400/1017790702398272 """ name, addr = parseaddr(s) return formataddr((Header(name, 'utf-8').encode(), addr)) def open_simpledialog(self, title, msg): """显示对话框 Refer: http://c.biancheng.net/view/2523.html :param title: 对话框标题 :param msg: 对话框内容 :return: """ d = simpledialog.SimpleDialog(self.master, title=title, text=msg, cancel=3, default=0) d.root.geometry(compute_x_y(self.master, 240, 100)) d.root.grab_set() d.root.wm_resizable(width=False, height=False) d.go() if __name__ == '__main__': # 创建Tk对象, Tk代表窗口 root = Tk() # 设置窗口标题 root.title('特邮') # 禁止改变窗口大小 root.resizable(width=False, height=False) root.geometry(compute_x_y(root, 600, 400)) app = Application(master=root) # 启动主窗口的消息循环 app.mainloop()
5,128
0
267
0c4b4d51a705eb165b6b3aefbcd194e6b68b539a
3,106
py
Python
irc_harvest.py
pauldardeau/irc-wheat
94ecc407497c2b6c9c22d566315c12cb3015e558
[ "BSD-3-Clause" ]
null
null
null
irc_harvest.py
pauldardeau/irc-wheat
94ecc407497c2b6c9c22d566315c12cb3015e558
[ "BSD-3-Clause" ]
null
null
null
irc_harvest.py
pauldardeau/irc-wheat
94ecc407497c2b6c9c22d566315c12cb3015e558
[ "BSD-3-Clause" ]
null
null
null
import irc_wheat import sys def parse_date(d): """Parse date string to (yyyy, MM, dd) :param d: the date string to parse :returns: parsed date as tuple or None on error """ date_fields = d.split('-') if date_fields and len(date_fields) == 3: return (int(date_fields[0]), int(date_fields[1]), int(date_fields[2])) else: return None def harvest_channel(channel, start_date, end_date, exclude_nicks=None, exclude_posts=None): """Pull all matching irc posts :param channel: the irc channel to search :param start_date: the starting date of irc entries :param end_date: the ending date of irc entries :param exclude_nicks: the irc nicknames whose posts are to be ignored :param exclude_posts: the substrings to cause posts to be ignored """ start_fields = parse_date(start_date) end_fields = parse_date(end_date) if not start_fields or not end_fields: return start_year = start_fields[0] start_month = start_fields[1] start_day = start_fields[2] end_year = end_fields[0] end_month = end_fields[1] end_day = end_fields[2] days_in_month = {} days_in_month['1'] = 31 days_in_month['2'] = 28 days_in_month['3'] = 31 days_in_month['4'] = 30 days_in_month['5'] = 31 days_in_month['6'] = 30 days_in_month['7'] = 31 days_in_month['8'] = 31 days_in_month['9'] = 30 days_in_month['10'] = 31 days_in_month['11'] = 30 days_in_month['12'] = 31 pulling_data = True current_year = start_year current_month = start_month current_day = start_day while pulling_data: current_date = '%d-%02d-%02d' % (current_year, current_month, current_day) log_entries = irc_wheat.get_channel_entries(channel, current_date, exclude_nicks, exclude_posts) if log_entries: irc_wheat.print_irc_entries(log_entries) if current_year == end_year and \ current_month == end_month and \ current_day == end_day: pulling_data = False else: if current_day < days_in_month[str(current_month)]: current_day += 1 else: current_month += 1 current_day = 1 if current_month > 12: current_month = 1 current_year += 1 if __name__ == '__main__': if len(sys.argv) < 4: print('usage: python %s channel start_date end_date' % sys.argv[0]) sys.exit(1) exclude_nicks = ['openstack', 'openstackgerrit'] exclude_posts = [' has joined ', ' has quit IRC'] harvest_channel(sys.argv[1], sys.argv[2], sys.argv[3], exclude_nicks, exclude_posts)
30.752475
78
0.554733
import irc_wheat import sys def parse_date(d): """Parse date string to (yyyy, MM, dd) :param d: the date string to parse :returns: parsed date as tuple or None on error """ date_fields = d.split('-') if date_fields and len(date_fields) == 3: return (int(date_fields[0]), int(date_fields[1]), int(date_fields[2])) else: return None def harvest_channel(channel, start_date, end_date, exclude_nicks=None, exclude_posts=None): """Pull all matching irc posts :param channel: the irc channel to search :param start_date: the starting date of irc entries :param end_date: the ending date of irc entries :param exclude_nicks: the irc nicknames whose posts are to be ignored :param exclude_posts: the substrings to cause posts to be ignored """ start_fields = parse_date(start_date) end_fields = parse_date(end_date) if not start_fields or not end_fields: return start_year = start_fields[0] start_month = start_fields[1] start_day = start_fields[2] end_year = end_fields[0] end_month = end_fields[1] end_day = end_fields[2] days_in_month = {} days_in_month['1'] = 31 days_in_month['2'] = 28 days_in_month['3'] = 31 days_in_month['4'] = 30 days_in_month['5'] = 31 days_in_month['6'] = 30 days_in_month['7'] = 31 days_in_month['8'] = 31 days_in_month['9'] = 30 days_in_month['10'] = 31 days_in_month['11'] = 30 days_in_month['12'] = 31 pulling_data = True current_year = start_year current_month = start_month current_day = start_day while pulling_data: current_date = '%d-%02d-%02d' % (current_year, current_month, current_day) log_entries = irc_wheat.get_channel_entries(channel, current_date, exclude_nicks, exclude_posts) if log_entries: irc_wheat.print_irc_entries(log_entries) if current_year == end_year and \ current_month == end_month and \ current_day == end_day: pulling_data = False else: if current_day < days_in_month[str(current_month)]: current_day += 1 else: current_month += 1 current_day = 1 if current_month > 12: current_month = 1 current_year += 1 if __name__ == '__main__': if len(sys.argv) < 4: print('usage: python %s channel start_date end_date' % sys.argv[0]) sys.exit(1) exclude_nicks = ['openstack', 'openstackgerrit'] exclude_posts = [' has joined ', ' has quit IRC'] harvest_channel(sys.argv[1], sys.argv[2], sys.argv[3], exclude_nicks, exclude_posts)
0
0
0
7c37cc3d1996a097af34d7a0ff2aa60225add307
1,154
py
Python
benzole/core/response.py
kritibytes/benzole
6f8f246ab55a3ca29c52c650e400c69317773622
[ "MIT" ]
null
null
null
benzole/core/response.py
kritibytes/benzole
6f8f246ab55a3ca29c52c650e400c69317773622
[ "MIT" ]
null
null
null
benzole/core/response.py
kritibytes/benzole
6f8f246ab55a3ca29c52c650e400c69317773622
[ "MIT" ]
null
null
null
from typing import Any, Union, List from ..utils.types import Header, HeaderList import json
25.644444
75
0.613518
from typing import Any, Union, List from ..utils.types import Header, HeaderList import json class Response: status_code: str = "200" _headers: Header body: Any def __init__(self, type: str, body: Any) -> None: self._headers = { "Content-Type": type, } self.body = body def add_header(self, header: Header) -> None: self._headers = { **self._headers, **header } def get_headers(self) -> HeaderList: return list(self._headers.items()) def set_headers(self, header_obj: Header) -> None: self._headers = header_obj def status(self, status_code: Union[str, int]) -> 'Response': self.status_code = str(status_code) return self headers = property(get_headers, set_headers) # Response generator methods @classmethod def json(cls, data: Union[dict, list]) -> 'Response': rendered_data = json.dumps(data) return cls("application/json", rendered_data) @classmethod def render(cls, template_name: str, template_data: dict) -> 'Response': return cls('text/html', "")
672
365
23