code
stringlengths
22
1.05M
apis
listlengths
1
3.31k
extract_api
stringlengths
75
3.25M
import logging from cliff.lister import Lister from cliff.show import ShowOne from atmosphere.api import AtmosphereAPI class GroupList(Lister): """ List groups for a user. """ log = logging.getLogger(__name__) def take_action(self, parsed_args): column_headers = ('uuid', 'name') api = AtmosphereAPI(self.app_args.auth_token, base_url=self.app_args.base_url, timeout=self.app_args.api_server_timeout, verify=self.app_args.verify_cert) data = api.get_groups() groups = [] if data.ok: for group in data.message['results']: groups.append(( group['uuid'], group['name'] )) return (column_headers, tuple(groups)) class GroupShow(ShowOne): """ Show details for a group. """ log = logging.getLogger(__name__) def get_parser(self, prog_name): parser = super(GroupShow, self).get_parser(prog_name) parser.add_argument('id', help='the group uuid') return parser def take_action(self, parsed_args): column_headers = ('uuid', 'name', 'users', 'leaders') api = AtmosphereAPI(self.app_args.auth_token, base_url=self.app_args.base_url, timeout=self.app_args.api_server_timeout, verify=self.app_args.verify_cert) data = api.get_group(parsed_args.id) group = () if data.ok: message = data.message group = ( message['uuid'], message['name'], '\n'.join([value['username'] for value in message['users']]), '\n'.join([value['username'] for value in message['leaders']]) ) return (column_headers, group)
[ "logging.getLogger", "atmosphere.api.AtmosphereAPI" ]
[((202, 229), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (219, 229), False, 'import logging\n'), ((851, 878), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (868, 878), False, 'import logging\n'), ((327, 479), 'atmosphere.api.AtmosphereAPI', 'AtmosphereAPI', (['self.app_args.auth_token'], {'base_url': 'self.app_args.base_url', 'timeout': 'self.app_args.api_server_timeout', 'verify': 'self.app_args.verify_cert'}), '(self.app_args.auth_token, base_url=self.app_args.base_url,\n timeout=self.app_args.api_server_timeout, verify=self.app_args.verify_cert)\n', (340, 479), False, 'from atmosphere.api import AtmosphereAPI\n'), ((1253, 1405), 'atmosphere.api.AtmosphereAPI', 'AtmosphereAPI', (['self.app_args.auth_token'], {'base_url': 'self.app_args.base_url', 'timeout': 'self.app_args.api_server_timeout', 'verify': 'self.app_args.verify_cert'}), '(self.app_args.auth_token, base_url=self.app_args.base_url,\n timeout=self.app_args.api_server_timeout, verify=self.app_args.verify_cert)\n', (1266, 1405), False, 'from atmosphere.api import AtmosphereAPI\n')]
import numpy as np from sklearn.cluster import KMeans from splearn.cluster import SparkKMeans from splearn.utils.testing import SplearnTestCase, assert_array_almost_equal class TestKMeans(SplearnTestCase): def test_same_centroids(self): X, y, X_rdd = self.make_blobs(centers=4, n_samples=200000) local = KMeans(n_clusters=4, init='k-means++', random_state=42) dist = SparkKMeans(n_clusters=4, init='k-means++', random_state=42) local.fit(X) dist.fit(X_rdd) local_centers = np.sort(local.cluster_centers_, axis=0) dist_centers = np.sort(dist.cluster_centers_, axis=0) assert_array_almost_equal(local_centers, dist_centers, decimal=4)
[ "sklearn.cluster.KMeans", "numpy.sort", "splearn.cluster.SparkKMeans", "splearn.utils.testing.assert_array_almost_equal" ]
[((328, 383), 'sklearn.cluster.KMeans', 'KMeans', ([], {'n_clusters': '(4)', 'init': '"""k-means++"""', 'random_state': '(42)'}), "(n_clusters=4, init='k-means++', random_state=42)\n", (334, 383), False, 'from sklearn.cluster import KMeans\n'), ((399, 459), 'splearn.cluster.SparkKMeans', 'SparkKMeans', ([], {'n_clusters': '(4)', 'init': '"""k-means++"""', 'random_state': '(42)'}), "(n_clusters=4, init='k-means++', random_state=42)\n", (410, 459), False, 'from splearn.cluster import SparkKMeans\n'), ((531, 570), 'numpy.sort', 'np.sort', (['local.cluster_centers_'], {'axis': '(0)'}), '(local.cluster_centers_, axis=0)\n', (538, 570), True, 'import numpy as np\n'), ((594, 632), 'numpy.sort', 'np.sort', (['dist.cluster_centers_'], {'axis': '(0)'}), '(dist.cluster_centers_, axis=0)\n', (601, 632), True, 'import numpy as np\n'), ((642, 707), 'splearn.utils.testing.assert_array_almost_equal', 'assert_array_almost_equal', (['local_centers', 'dist_centers'], {'decimal': '(4)'}), '(local_centers, dist_centers, decimal=4)\n', (667, 707), False, 'from splearn.utils.testing import SplearnTestCase, assert_array_almost_equal\n')]
""" Tests for worker """ import sys import _pytest import act.api import pytest from act.api.base import ValidationError from act.api.helpers import handle_fact from act.api.libs import cli from act.types.format import object_format from act.types.types import object_validates from act.workers.libs import worker def test_args_origin_name(monkeypatch: _pytest.monkeypatch.MonkeyPatch) -> None: """test argument origin-name""" origin_name = "test-origin" monkeypatch.setattr(sys, "argv", ["./test-worker.py", "--origin-name", origin_name]) args = cli.handle_args(worker.parseargs("Test worker")) actapi = worker.init_act(args) assert actapi.config.origin_name == origin_name fact = ( actapi.fact("mentions").source("report", "xyz").destination("fqdn", "test.com") ) assert fact.origin.name == origin_name def test_args_origin_id(monkeypatch: _pytest.monkeypatch.MonkeyPatch) -> None: """test argument origin-id""" origin_id = "00000000-0000-0000-0000-000000000001" monkeypatch.setattr(sys, "argv", ["./test-worker.py", "--origin-id", origin_id]) args = cli.handle_args(worker.parseargs("Test worker")) actapi = worker.init_act(args) assert actapi.config.origin_id == origin_id fact = ( actapi.fact("mentions").source("report", "xyz").destination("fqdn", "test.com") ) assert fact.origin.id == origin_id def test_validator_no_strict(caplog) -> None: api = act.api.Act( "", None, object_formatter=object_format, object_validator=object_validates, ) # Should return None if fact does not validate fact = handle_fact( api.fact("mentions") .source("report", "xyz") .destination("uri", "X7f://cve-2014-0224") ) assert fact is None assert "Destination object does not validate:" in caplog.text def test_validate_same_object() -> None: api = act.api.Act( "", None, strict_validator=True, object_formatter=object_format, object_validator=object_validates, ) act.api.helpers.handle_fact.cache_clear() with pytest.raises(ValidationError, match=r"Source object can not be equal to.*"): handle_fact( api.fact("mentions").source("report", "xyz").destination("report", "xyz") ) def test_validator_no_validator(caplog) -> None: api = act.api.Act("", None) act.api.helpers.handle_fact.cache_clear() # Should return None if fact does not validate fact = handle_fact( api.fact("mentions") .source("report", "xyz") .destination("uri", "X7f://cve-2014-0224") ) # No validator is specified so the above should return a fact assert fact is not None # Should not log errors assert caplog.text == "" def test_validator_strict() -> None: api = act.api.Act( "", None, strict_validator=True, object_formatter=object_format, object_validator=object_validates, ) act.api.helpers.handle_fact.cache_clear() with pytest.raises( ValidationError, match=r"Destination object does not validate.*" ): handle_fact( api.fact("mentions") .source("report", "xyz") .destination("uri", ".X7f://cve-2014-0224") ) def test_format() -> None: api = act.api.Act( "", None, object_formatter=object_format, object_validator=object_validates, ) act.api.helpers.handle_fact.cache_clear() ta_alias = handle_fact( api.fact("alias") .source("threatActor", "APT29") .destination("threatActor", "Cozy Bear") ) assert ta_alias.source_object.value == "apt29" assert ta_alias.destination_object.value == "cozy bear"
[ "act.workers.libs.worker.parseargs", "pytest.raises", "act.workers.libs.worker.init_act" ]
[((632, 653), 'act.workers.libs.worker.init_act', 'worker.init_act', (['args'], {}), '(args)\n', (647, 653), False, 'from act.workers.libs import worker\n'), ((1190, 1211), 'act.workers.libs.worker.init_act', 'worker.init_act', (['args'], {}), '(args)\n', (1205, 1211), False, 'from act.workers.libs import worker\n'), ((586, 617), 'act.workers.libs.worker.parseargs', 'worker.parseargs', (['"""Test worker"""'], {}), "('Test worker')\n", (602, 617), False, 'from act.workers.libs import worker\n'), ((1144, 1175), 'act.workers.libs.worker.parseargs', 'worker.parseargs', (['"""Test worker"""'], {}), "('Test worker')\n", (1160, 1175), False, 'from act.workers.libs import worker\n'), ((2151, 2226), 'pytest.raises', 'pytest.raises', (['ValidationError'], {'match': '"""Source object can not be equal to.*"""'}), "(ValidationError, match='Source object can not be equal to.*')\n", (2164, 2226), False, 'import pytest\n'), ((3087, 3165), 'pytest.raises', 'pytest.raises', (['ValidationError'], {'match': '"""Destination object does not validate.*"""'}), "(ValidationError, match='Destination object does not validate.*')\n", (3100, 3165), False, 'import pytest\n')]
from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='darch', # Versions should comply with PEP440. For a discussion on single-sourcing # the version across setup.py and the project code, see # https://packaging.python.org/en/latest/single_source_version.html version='0.1.0', description='Deep Architect', long_description=long_description, # The project's main homepage. url='https://github.com/negrinho/deep_architect', # Author details author='The Python Packaging Authority', author_email='<EMAIL>', # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ # How mature is this project? Common values are # 3 - Alpha # 4 - Beta # 5 - Production/Stable 'Development Status :: 3 - Alpha', # Indicate who your project is intended for 'Intended Audience :: Developers', # Specify the Python versions you support here. In particular, ensure # that you indicate whether you support Python 2, Python 3 or both. 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], # What does your project relate to? keywords='deep architect', # You can just specify the packages manually here if your project is # simple. Or you can use find_packages(). packages=['darch'], # List run-time dependencies here. These will be installed by pip when # your project is installed. For an analysis of "install_requires" vs pip's # requirements files see: # https://packaging.python.org/en/latest/requirements.html install_requires=[ 'numpy', 'scipy', 'sklearn' ] )
[ "os.path.join", "os.path.dirname", "setuptools.setup" ]
[((279, 963), 'setuptools.setup', 'setup', ([], {'name': '"""darch"""', 'version': '"""0.1.0"""', 'description': '"""Deep Architect"""', 'long_description': 'long_description', 'url': '"""https://github.com/negrinho/deep_architect"""', 'author': '"""The Python Packaging Authority"""', 'author_email': '"""<EMAIL>"""', 'classifiers': "['Development Status :: 3 - Alpha', 'Intended Audience :: Developers',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5']", 'keywords': '"""deep architect"""', 'packages': "['darch']", 'install_requires': "['numpy', 'scipy', 'sklearn']"}), "(name='darch', version='0.1.0', description='Deep Architect',\n long_description=long_description, url=\n 'https://github.com/negrinho/deep_architect', author=\n 'The Python Packaging Authority', author_email='<EMAIL>', classifiers=[\n 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5'], keywords='deep architect',\n packages=['darch'], install_requires=['numpy', 'scipy', 'sklearn'])\n", (284, 963), False, 'from setuptools import setup, find_packages\n'), ((109, 131), 'os.path.dirname', 'path.dirname', (['__file__'], {}), '(__file__)\n', (121, 131), False, 'from os import path\n'), ((192, 220), 'os.path.join', 'path.join', (['here', '"""README.md"""'], {}), "(here, 'README.md')\n", (201, 220), False, 'from os import path\n')]
import curses from .game import Game def go(stdscr): Game(stdscr).run() # Start game def main(): # Curses convinient wrapper curses.wrapper(go) if __name__ == '__main__': main()
[ "curses.wrapper" ]
[((142, 160), 'curses.wrapper', 'curses.wrapper', (['go'], {}), '(go)\n', (156, 160), False, 'import curses\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright(c) 2019 Nippon Telegraph and Telephone Corporation # Filename: NVRDriverCLIProtocol.py import traceback import re import GlobalModule from EmCommonLog import decorater_log from CgwshDriverCLIProtocol import CgwshDriverCLIProtocol class NVRDriverCLIProtocol(CgwshDriverCLIProtocol): ''' Class for processing NVR driver protocol(CLI) ''' @decorater_log def __init__(self, error_recv_message=[], connected_recv_message="~"): super(NVRDriverCLIProtocol, self).__init__(error_recv_message, connected_recv_message) @decorater_log def _exit_configuration_mode(self): ''' Release of configuration mode is forced. ''' re_txt_save_conf = "Save new configuration \? \(Y/N\)" send_message = [("quit", "{0}|{1}".format(">", re_txt_save_conf))] GlobalModule.EM_LOGGER.debug( "start exit command :\n%s" % (send_message,)) try: output = self._exec_interactive(send_message, self.error_recv_message) if re.search(re_txt_save_conf, output): self._send_command_no_save() except Exception as ex: GlobalModule.EM_LOGGER.debug("Error exit command:%s", ex) GlobalModule.EM_LOGGER.debug("Traceback:%s", traceback.format_exc()) else: GlobalModule.EM_LOGGER.debug("Success configuration exit") self._is_mode_configuration = False @decorater_log def _send_command_no_save(self): ''' Save new configuration ? n is set as reponse to question(Y/N). Return value: Received message ''' GlobalModule.EM_LOGGER.debug( "Send n for 'Save new configuration ? (Y/N)'") shell_obj = self._ssh_shell send_message = "n" receive_keyword = ">" shell_obj.send(send_message) return self._recv_message(shell_obj, receive_keyword)
[ "GlobalModule.EM_LOGGER.debug", "traceback.format_exc", "re.search" ]
[((970, 1047), 'GlobalModule.EM_LOGGER.debug', 'GlobalModule.EM_LOGGER.debug', (['("""start exit command :\n%s""" % (send_message,))'], {}), '("""start exit command :\n%s""" % (send_message,))\n', (998, 1047), False, 'import GlobalModule\n'), ((1885, 1960), 'GlobalModule.EM_LOGGER.debug', 'GlobalModule.EM_LOGGER.debug', (['"""Send n for \'Save new configuration ? (Y/N)\'"""'], {}), '("Send n for \'Save new configuration ? (Y/N)\'")\n', (1913, 1960), False, 'import GlobalModule\n'), ((1218, 1253), 're.search', 're.search', (['re_txt_save_conf', 'output'], {}), '(re_txt_save_conf, output)\n', (1227, 1253), False, 'import re\n'), ((1557, 1615), 'GlobalModule.EM_LOGGER.debug', 'GlobalModule.EM_LOGGER.debug', (['"""Success configuration exit"""'], {}), "('Success configuration exit')\n", (1585, 1615), False, 'import GlobalModule\n'), ((1347, 1404), 'GlobalModule.EM_LOGGER.debug', 'GlobalModule.EM_LOGGER.debug', (['"""Error exit command:%s"""', 'ex'], {}), "('Error exit command:%s', ex)\n", (1375, 1404), False, 'import GlobalModule\n'), ((1505, 1527), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (1525, 1527), False, 'import traceback\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2015 <NAME> (davvid -at- gmail.com) # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. import os try: import setuptools as setup_mod except ImportError: import distutils.core as setup_mod here = os.path.dirname(__file__) version = os.path.join(here, 'skeletor', 'core', 'version.py') scope = {} exec(open(version).read(), scope) SETUP_ARGS = dict( name='skeletor', version=scope['VERSION'], description='minimalist application skeleton', long_description='skeletor is a reusable application skeleton', author='<NAME>', author_email='<EMAIL>', url='https://github.com/davvid/skeletor', license='BSD', platforms=['POSIX'], keywords=['skeletor', 'skeleton', 'application', 'utilities'], classifiers=[ 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Topic :: Software Development :: Libraries :: Python Modules', 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Programming Language :: Python', ], options={'clean': {'all': 1}}, packages=['skeletor', 'skeletor.core', 'skeletor.cli', 'skeletor.db', 'skeletor.util'], ) if __name__ == '__main__': setup_mod.setup(**SETUP_ARGS)
[ "os.path.dirname", "os.path.join", "distutils.core.setup" ]
[((368, 393), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (383, 393), False, 'import os\n'), ((404, 456), 'os.path.join', 'os.path.join', (['here', '"""skeletor"""', '"""core"""', '"""version.py"""'], {}), "(here, 'skeletor', 'core', 'version.py')\n", (416, 456), False, 'import os\n'), ((1595, 1624), 'distutils.core.setup', 'setup_mod.setup', ([], {}), '(**SETUP_ARGS)\n', (1610, 1624), True, 'import distutils.core as setup_mod\n')]
# coding=utf-8 # Copyright 2020 HuggingFace Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 import os import datasets logger = datasets.logging.get_logger(__name__) _URL = "" _TRAINING_FILE = "train.txt" _DEV_FILE = "dev.txt" _TEST_FILE = "test.txt" class PunctuationConfig(datasets.BuilderConfig): def __init__(self, **kwargs): super(PunctuationConfig, self).__init__(**kwargs) class Punctuation(datasets.GeneratorBasedBuilder): BUILDER_CONFIGS = [ PunctuationConfig(name="punctuation", version=datasets.Version("1.0.0"), description="Punctuation dataset"), ] def _info(self): return datasets.DatasetInfo( features=datasets.Features( { "id": datasets.Value("string"), "tokens": datasets.Sequence(datasets.Value("string")), "seg_tags": datasets.Sequence( datasets.features.ClassLabel( names=[ 'O', 'B', ] ) ), "punc_tags": datasets.Sequence( datasets.features.ClassLabel( names=[ "O", 'B-,', 'B-.', 'B-?', 'B-!', 'B-\\', 'B-:', 'B-;', ] ) ), "quote_tags": datasets.Sequence( datasets.features.ClassLabel( names=[ 'O', 'B', 'I', ] ) ), "book_tags": datasets.Sequence( datasets.features.ClassLabel( names=[ 'O', 'B', 'I', ] ) ), "has_quote": datasets.Value("bool"), "has_book": datasets.Value("bool"), } ), supervised_keys=None, ) def _split_generators(self, dl_manager): """Returns SplitGenerators.""" urls_to_download = { "train": f"{_URL}{_TRAINING_FILE}", "dev": f"{_URL}{_DEV_FILE}", "test": f"{_URL}{_TEST_FILE}", } downloaded_files = dl_manager.download_and_extract(urls_to_download) return [ datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"filepath": downloaded_files["train"]}), datasets.SplitGenerator(name=datasets.Split.VALIDATION, gen_kwargs={"filepath": downloaded_files["dev"]}), datasets.SplitGenerator(name=datasets.Split.TEST, gen_kwargs={"filepath": downloaded_files["test"]}), ] def _generate_examples(self, filepath): logger.info("⏳ Generating examples from = %s", filepath) with open(filepath, encoding="utf-8") as f: guid = 0 tokens = [] seg_tags = [] punc_tags = [] quote_tags = [] book_tags = [] has_quote = False has_book = False for line in f: if line.startswith("-DOCSTART-") or line == "" or line == "\n": if line.startswith("-DOCSTART-"): has_quote = '-QUOTE-' in line has_book = '-BOOK-' in line if tokens: yield guid, { "id": str(guid), "tokens": tokens, "seg_tags": seg_tags, "punc_tags": punc_tags, "quote_tags": quote_tags, "book_tags": book_tags, "has_quote": has_quote, "has_book": has_book, } guid += 1 tokens = [] seg_tags = [] punc_tags = [] quote_tags = [] book_tags = [] else: # conll2003 tokens are space separated splits = line.split(" ") tokens.append(splits[0]) seg_tags.append(splits[1]) punc_tags.append(splits[2]) quote_tags.append(splits[3]) book_tags.append(splits[4]) # last example yield guid, { "id": str(guid), "tokens": tokens, "seg_tags": seg_tags, "punc_tags": punc_tags, "quote_tags": quote_tags, "book_tags": book_tags, "has_quote": has_quote, "has_book": has_book, }
[ "datasets.SplitGenerator", "datasets.features.ClassLabel", "datasets.Version", "datasets.logging.get_logger", "datasets.Value" ]
[((665, 702), 'datasets.logging.get_logger', 'datasets.logging.get_logger', (['__name__'], {}), '(__name__)\n', (692, 702), False, 'import datasets\n'), ((3421, 3527), 'datasets.SplitGenerator', 'datasets.SplitGenerator', ([], {'name': 'datasets.Split.TRAIN', 'gen_kwargs': "{'filepath': downloaded_files['train']}"}), "(name=datasets.Split.TRAIN, gen_kwargs={'filepath':\n downloaded_files['train']})\n", (3444, 3527), False, 'import datasets\n'), ((3537, 3647), 'datasets.SplitGenerator', 'datasets.SplitGenerator', ([], {'name': 'datasets.Split.VALIDATION', 'gen_kwargs': "{'filepath': downloaded_files['dev']}"}), "(name=datasets.Split.VALIDATION, gen_kwargs={\n 'filepath': downloaded_files['dev']})\n", (3560, 3647), False, 'import datasets\n'), ((3656, 3760), 'datasets.SplitGenerator', 'datasets.SplitGenerator', ([], {'name': 'datasets.Split.TEST', 'gen_kwargs': "{'filepath': downloaded_files['test']}"}), "(name=datasets.Split.TEST, gen_kwargs={'filepath':\n downloaded_files['test']})\n", (3679, 3760), False, 'import datasets\n'), ((1064, 1089), 'datasets.Version', 'datasets.Version', (['"""1.0.0"""'], {}), "('1.0.0')\n", (1080, 1089), False, 'import datasets\n'), ((1276, 1300), 'datasets.Value', 'datasets.Value', (['"""string"""'], {}), "('string')\n", (1290, 1300), False, 'import datasets\n'), ((2901, 2923), 'datasets.Value', 'datasets.Value', (['"""bool"""'], {}), "('bool')\n", (2915, 2923), False, 'import datasets\n'), ((2957, 2979), 'datasets.Value', 'datasets.Value', (['"""bool"""'], {}), "('bool')\n", (2971, 2979), False, 'import datasets\n'), ((1350, 1374), 'datasets.Value', 'datasets.Value', (['"""string"""'], {}), "('string')\n", (1364, 1374), False, 'import datasets\n'), ((1452, 1498), 'datasets.features.ClassLabel', 'datasets.features.ClassLabel', ([], {'names': "['O', 'B']"}), "(names=['O', 'B'])\n", (1480, 1498), False, 'import datasets\n'), ((1747, 1842), 'datasets.features.ClassLabel', 'datasets.features.ClassLabel', ([], {'names': "['O', 'B-,', 'B-.', 'B-?', 'B-!', 'B-\\\\', 'B-:', 'B-;']"}), "(names=['O', 'B-,', 'B-.', 'B-?', 'B-!', 'B-\\\\',\n 'B-:', 'B-;'])\n", (1775, 1842), False, 'import datasets\n'), ((2280, 2331), 'datasets.features.ClassLabel', 'datasets.features.ClassLabel', ([], {'names': "['O', 'B', 'I']"}), "(names=['O', 'B', 'I'])\n", (2308, 2331), False, 'import datasets\n'), ((2612, 2663), 'datasets.features.ClassLabel', 'datasets.features.ClassLabel', ([], {'names': "['O', 'B', 'I']"}), "(names=['O', 'B', 'I'])\n", (2640, 2663), False, 'import datasets\n')]
import click import vk.config as config import vk.utils as utils from vk.commands.query import show_layer_state def _add_layers(layer_str, current_layers, set_layers_func): """Append layers to current_layers and set to device props. Args: layer_str: A string in <layer1:layer2:layerN> format. current_layers: A list of current layers. set_layers_func: A function takes layer list to updates system properties. """ for layer in layer_str.split(':'): if layer not in current_layers: current_layers.append(layer) set_layers_func(current_layers) def _remove_layers(layer_str, current_layers, set_layers_func): """Remove layers from current_layers and update to device props. Args: layer_str: A string in <layer1:layer2:layerN> format. current_layers: A list of current layers. set_layers_func: A function takes layer list to updates system properties. """ new_layers = [] remove_layers = layer_str.split(':') for layer in current_layers: if layer not in remove_layers: new_layers.append(layer) set_layers_func(new_layers) @click.command() @click.option('--app', 'app_name', type=str, metavar='<app_name>', help='Modify per-app layer configuration.') @click.option('--add', 'add_layer_str', type=str, metavar='<layer_names>', help='Add layers <layer1:layer2:layerN>.') @click.option('--remove', 'remove_layer_str', metavar='<layer_names>', type=str, help='Remove layers <layer1:layer2:layerN>.') @click.option('--clear', is_flag=True, help='Clear active layer settings.') def layer(app_name, add_layer_str, remove_layer_str, clear): """Configure active layer settings. \b >> Example 1: Add VK_LAYER_foo:VK_LAYER_bar globally. $ vk layer --add VK_LAYER_foo:VK_LAYER_bar \b >> Example 2: Add VK_LAYER_foo to <app_name>. $ vk layer --app <app_name> --add VK_LAYER_foo \b >> Example 3: Add VK_LAYER_foo to selected app. $ vk layer --app ? --add VK_LAYER_foo \f https://developer.android.com/ndk/guides/graphics/validation-layer#enable-layers-outside-app """ if add_layer_str and clear: raise click.UsageError('--add can not be used with --clear') if clear: utils.enable_gpu_debug_layers(False) utils.set_gpu_debug_app('') utils.set_gpu_debug_layers(None) utils.set_debug_vulkan_layers(None) click.echo('Clear all relevant layer settings.') return if app_name: try: app_name = utils.get_valid_app_name(app_name) except click.BadParameter as e: e.show() return # Set per-app layer configuration. utils.enable_gpu_debug_layers(True) utils.set_gpu_debug_app(app_name) current_layers = utils.get_gpu_debug_layers() set_layer_func = utils.set_gpu_debug_layers else: current_layers = utils.get_debug_vulkan_layers() set_layer_func = utils.set_debug_vulkan_layers if add_layer_str: _add_layers(add_layer_str, current_layers, set_layer_func) if remove_layer_str == '*': set_layer_func(None) # Remove all layers elif remove_layer_str: _remove_layers(remove_layer_str, current_layers, set_layer_func) click.echo('\nSuccessfully update active layers:') show_layer_state(False) def _save_layer_preset(preset_name): settings = config.Settings() if settings.has_layer_preset(preset_name) and \ not click.confirm(f'Override existent preset {preset_name}?'): return app_layers_value = utils.get_gpu_debug_layers_value() global_layers_value = utils.get_debug_vulkan_layers_value() app_name = utils.get_gpu_debug_app() settings.set_layer_preset(preset_name, global_layers_value, app_name, app_layers_value) click.echo(f'Save preset \'{preset_name}\' successfully.') show_layer_state(False) def _load_layer_preset(preset_name): settings = config.Settings() preset_name_list = settings.get_layer_preset_names() if preset_name == '?': settings.show_layers(show_indices=True) click.echo('') preset_count = len(preset_name_list) selected_idx = -1 while not (0 < selected_idx < preset_count): selected_idx = click.prompt('Please choose preset (ctrl+c to abort)', type=int) if not (0 < selected_idx < preset_count): click.echo(f'Error: selected index {selected_idx} is out-of-range!') preset_name = preset_name_list[selected_idx] elif preset_name not in preset_name_list: raise click.BadParameter(f'Can not find preset named \'{preset_name}\'') global_layers_value, app_name, app_layers_value = settings.get_layer_preset(preset_name) utils.set_debug_vulkan_layers(global_layers_value.split(':')) utils.set_gpu_debug_app(app_name) utils.set_gpu_debug_layers(app_layers_value.split(':')) click.echo(f'Load preset \'{preset_name}\' successfully.') show_layer_state(False) @click.command() @click.argument('preset_name', type=str) @click.option('--save', 'action', flag_value='save', help='Save settings to preset.') @click.option('--load', 'action', flag_value='load', help='Load settings from preset.') @click.option('--delete', 'action', flag_value='delete', help='Delete preset.') def layerset(action, preset_name): """Customize layer presets. PRESET_NAME is the name of preset entry. \b >> Example 1: Save current layer settings to PRESET_NAME. $ vk layerset --save PRESET_NAME. \b >> Example 2: Load PRESET_NAME to overwrite current layer settings. $ vk layerset --load PRESET_NAME. """ if action == 'save': _save_layer_preset(preset_name) elif action == 'load': _load_layer_preset(preset_name) elif action == 'delete': settings = config.Settings() settings.delete_layer_preset(preset_name)
[ "click.echo", "vk.utils.get_valid_app_name", "click.BadParameter", "vk.utils.enable_gpu_debug_layers", "click.UsageError", "click.option", "click.command", "vk.commands.query.show_layer_state", "vk.utils.get_gpu_debug_layers", "click.argument", "click.confirm", "click.prompt", "vk.config.Set...
[((1164, 1179), 'click.command', 'click.command', ([], {}), '()\n', (1177, 1179), False, 'import click\n'), ((1181, 1295), 'click.option', 'click.option', (['"""--app"""', '"""app_name"""'], {'type': 'str', 'metavar': '"""<app_name>"""', 'help': '"""Modify per-app layer configuration."""'}), "('--app', 'app_name', type=str, metavar='<app_name>', help=\n 'Modify per-app layer configuration.')\n", (1193, 1295), False, 'import click\n'), ((1306, 1426), 'click.option', 'click.option', (['"""--add"""', '"""add_layer_str"""'], {'type': 'str', 'metavar': '"""<layer_names>"""', 'help': '"""Add layers <layer1:layer2:layerN>."""'}), "('--add', 'add_layer_str', type=str, metavar='<layer_names>',\n help='Add layers <layer1:layer2:layerN>.')\n", (1318, 1426), False, 'import click\n'), ((1438, 1568), 'click.option', 'click.option', (['"""--remove"""', '"""remove_layer_str"""'], {'metavar': '"""<layer_names>"""', 'type': 'str', 'help': '"""Remove layers <layer1:layer2:layerN>."""'}), "('--remove', 'remove_layer_str', metavar='<layer_names>', type=\n str, help='Remove layers <layer1:layer2:layerN>.')\n", (1450, 1568), False, 'import click\n'), ((1579, 1653), 'click.option', 'click.option', (['"""--clear"""'], {'is_flag': '(True)', 'help': '"""Clear active layer settings."""'}), "('--clear', is_flag=True, help='Clear active layer settings.')\n", (1591, 1653), False, 'import click\n'), ((5111, 5126), 'click.command', 'click.command', ([], {}), '()\n', (5124, 5126), False, 'import click\n'), ((5128, 5167), 'click.argument', 'click.argument', (['"""preset_name"""'], {'type': 'str'}), "('preset_name', type=str)\n", (5142, 5167), False, 'import click\n'), ((5169, 5258), 'click.option', 'click.option', (['"""--save"""', '"""action"""'], {'flag_value': '"""save"""', 'help': '"""Save settings to preset."""'}), "('--save', 'action', flag_value='save', help=\n 'Save settings to preset.')\n", (5181, 5258), False, 'import click\n'), ((5255, 5346), 'click.option', 'click.option', (['"""--load"""', '"""action"""'], {'flag_value': '"""load"""', 'help': '"""Load settings from preset."""'}), "('--load', 'action', flag_value='load', help=\n 'Load settings from preset.')\n", (5267, 5346), False, 'import click\n'), ((5343, 5421), 'click.option', 'click.option', (['"""--delete"""', '"""action"""'], {'flag_value': '"""delete"""', 'help': '"""Delete preset."""'}), "('--delete', 'action', flag_value='delete', help='Delete preset.')\n", (5355, 5421), False, 'import click\n'), ((3356, 3409), 'click.echo', 'click.echo', (['"""\nSuccessfully update active layers:"""'], {}), '("""\nSuccessfully update active layers:""")\n', (3366, 3409), False, 'import click\n'), ((3411, 3434), 'vk.commands.query.show_layer_state', 'show_layer_state', (['(False)'], {}), '(False)\n', (3427, 3434), False, 'from vk.commands.query import show_layer_state\n'), ((3489, 3506), 'vk.config.Settings', 'config.Settings', ([], {}), '()\n', (3504, 3506), True, 'import vk.config as config\n'), ((3669, 3703), 'vk.utils.get_gpu_debug_layers_value', 'utils.get_gpu_debug_layers_value', ([], {}), '()\n', (3701, 3703), True, 'import vk.utils as utils\n'), ((3730, 3767), 'vk.utils.get_debug_vulkan_layers_value', 'utils.get_debug_vulkan_layers_value', ([], {}), '()\n', (3765, 3767), True, 'import vk.utils as utils\n'), ((3783, 3808), 'vk.utils.get_gpu_debug_app', 'utils.get_gpu_debug_app', ([], {}), '()\n', (3806, 3808), True, 'import vk.utils as utils\n'), ((3906, 3962), 'click.echo', 'click.echo', (['f"""Save preset \'{preset_name}\' successfully."""'], {}), '(f"Save preset \'{preset_name}\' successfully.")\n', (3916, 3962), False, 'import click\n'), ((3969, 3992), 'vk.commands.query.show_layer_state', 'show_layer_state', (['(False)'], {}), '(False)\n', (3985, 3992), False, 'from vk.commands.query import show_layer_state\n'), ((4047, 4064), 'vk.config.Settings', 'config.Settings', ([], {}), '()\n', (4062, 4064), True, 'import vk.config as config\n'), ((4923, 4956), 'vk.utils.set_gpu_debug_app', 'utils.set_gpu_debug_app', (['app_name'], {}), '(app_name)\n', (4946, 4956), True, 'import vk.utils as utils\n'), ((5021, 5077), 'click.echo', 'click.echo', (['f"""Load preset \'{preset_name}\' successfully."""'], {}), '(f"Load preset \'{preset_name}\' successfully.")\n', (5031, 5077), False, 'import click\n'), ((5084, 5107), 'vk.commands.query.show_layer_state', 'show_layer_state', (['(False)'], {}), '(False)\n', (5100, 5107), False, 'from vk.commands.query import show_layer_state\n'), ((2239, 2293), 'click.UsageError', 'click.UsageError', (['"""--add can not be used with --clear"""'], {}), "('--add can not be used with --clear')\n", (2255, 2293), False, 'import click\n'), ((2317, 2353), 'vk.utils.enable_gpu_debug_layers', 'utils.enable_gpu_debug_layers', (['(False)'], {}), '(False)\n', (2346, 2353), True, 'import vk.utils as utils\n'), ((2362, 2389), 'vk.utils.set_gpu_debug_app', 'utils.set_gpu_debug_app', (['""""""'], {}), "('')\n", (2385, 2389), True, 'import vk.utils as utils\n'), ((2398, 2430), 'vk.utils.set_gpu_debug_layers', 'utils.set_gpu_debug_layers', (['None'], {}), '(None)\n', (2424, 2430), True, 'import vk.utils as utils\n'), ((2439, 2474), 'vk.utils.set_debug_vulkan_layers', 'utils.set_debug_vulkan_layers', (['None'], {}), '(None)\n', (2468, 2474), True, 'import vk.utils as utils\n'), ((2483, 2531), 'click.echo', 'click.echo', (['"""Clear all relevant layer settings."""'], {}), "('Clear all relevant layer settings.')\n", (2493, 2531), False, 'import click\n'), ((2768, 2803), 'vk.utils.enable_gpu_debug_layers', 'utils.enable_gpu_debug_layers', (['(True)'], {}), '(True)\n', (2797, 2803), True, 'import vk.utils as utils\n'), ((2812, 2845), 'vk.utils.set_gpu_debug_app', 'utils.set_gpu_debug_app', (['app_name'], {}), '(app_name)\n', (2835, 2845), True, 'import vk.utils as utils\n'), ((2872, 2900), 'vk.utils.get_gpu_debug_layers', 'utils.get_gpu_debug_layers', ([], {}), '()\n', (2898, 2900), True, 'import vk.utils as utils\n'), ((2988, 3019), 'vk.utils.get_debug_vulkan_layers', 'utils.get_debug_vulkan_layers', ([], {}), '()\n', (3017, 3019), True, 'import vk.utils as utils\n'), ((4207, 4221), 'click.echo', 'click.echo', (['""""""'], {}), "('')\n", (4217, 4221), False, 'import click\n'), ((2601, 2635), 'vk.utils.get_valid_app_name', 'utils.get_valid_app_name', (['app_name'], {}), '(app_name)\n', (2625, 2635), True, 'import vk.utils as utils\n'), ((3571, 3628), 'click.confirm', 'click.confirm', (['f"""Override existent preset {preset_name}?"""'], {}), "(f'Override existent preset {preset_name}?')\n", (3584, 3628), False, 'import click\n'), ((4373, 4437), 'click.prompt', 'click.prompt', (['"""Please choose preset (ctrl+c to abort)"""'], {'type': 'int'}), "('Please choose preset (ctrl+c to abort)', type=int)\n", (4385, 4437), False, 'import click\n'), ((4691, 4755), 'click.BadParameter', 'click.BadParameter', (['f"""Can not find preset named \'{preset_name}\'"""'], {}), '(f"Can not find preset named \'{preset_name}\'")\n', (4709, 4755), False, 'import click\n'), ((4508, 4576), 'click.echo', 'click.echo', (['f"""Error: selected index {selected_idx} is out-of-range!"""'], {}), "(f'Error: selected index {selected_idx} is out-of-range!')\n", (4518, 4576), False, 'import click\n'), ((5950, 5967), 'vk.config.Settings', 'config.Settings', ([], {}), '()\n', (5965, 5967), True, 'import vk.config as config\n')]
#!/usr/bin/env python2 # -*- coding: utf-8 -*- import rospy import message_filters from std_msgs.msg import Int32, Float32 from pololu_drv8835_rpi import motors rospy.init_node('message_sync', anonymous=False) speed_desired = 0.5 # desired wheel speed in rpm angle_desired = 0.0 # desired angle - 0 k_p_angle = 4*480.0/90.0 # propotional gain for angle control k_i_angle = k_p_angle/4. # integral gain for angle control k_d_angle = 1 # derivatibe gain for angle control k_p_speed = 15 # proportional gain for speed control (60) k_i_speed = 35 # integral gain for speed control(30) def drive_motor(speed): # send speed command to motor max_speed = 380 if speed > max_speed: drive_speed = max_speed elif speed < -max_speed: drive_speed = -max_speed else: drive_speed = round(speed) motors.motor1.setSpeed(int(drive_speed)) return drive_speed def PID_control(IMU_message,Encoder_message): global current_wheel_speed global current_imu_angle global speed_error_cum global angle_error_cum global time_current current_wheel_speed = Encoder_message.data angle_prev = current_imu_angle current_imu_angle = IMU_message.data #### time update time_old = time_current # set previous time reading time_current = rospy.get_rostime() # set current time reading dt = time_current - time_old # time step # P speed_error = speed_desired - current_wheel_speed # I speed_error_cum += speed_error * dt # Effort # not sure what speed_direction_comp is used for angle_desired = 1 * (k_p_speed * speed_error + k_i_speed * speed_error_cum) if current_imu_angle <= 90 and current_imu_angle >= -90: # P angle_error = angle_desired - current_imu_angle # I angle_error_cum += angle_error*dt # D angle_diff = (angle_prev - current_imu_angle)/dt # Effort motor_output = -1*(k_p_angle*angle_error + k_i_angle*angle_error_cum + k_d_angle*angle_diff) drive_motor(motor_output) def message_sync(): global speed_error_cum global angle_error_cum global time_current speed_error_cum = 0.0 angle_error_cum = 0.0 time_current = rospy.get_rostime() IMU_message = message_filters.Subscriber('/IMU_angle', Float32) Encoder_message = message_filters.Subscriber('/Encoder_data', Float32) sync = message_filters.ApproximateTimeSynchronizer([IMU_message,Encoder_message],queue_size = 1,slop = 0.05) #what happens if queue size is not one and what should the slop be sync.registerCallback(PID_control) rospy.spin() if __name__ == "__main__": try: message_sync() except rospy.ROSInterruptException: pass
[ "rospy.init_node", "rospy.get_rostime", "rospy.spin", "message_filters.Subscriber", "message_filters.ApproximateTimeSynchronizer" ]
[((164, 212), 'rospy.init_node', 'rospy.init_node', (['"""message_sync"""'], {'anonymous': '(False)'}), "('message_sync', anonymous=False)\n", (179, 212), False, 'import rospy\n'), ((1319, 1338), 'rospy.get_rostime', 'rospy.get_rostime', ([], {}), '()\n', (1336, 1338), False, 'import rospy\n'), ((2284, 2303), 'rospy.get_rostime', 'rospy.get_rostime', ([], {}), '()\n', (2301, 2303), False, 'import rospy\n'), ((2327, 2376), 'message_filters.Subscriber', 'message_filters.Subscriber', (['"""/IMU_angle"""', 'Float32'], {}), "('/IMU_angle', Float32)\n", (2353, 2376), False, 'import message_filters\n'), ((2399, 2451), 'message_filters.Subscriber', 'message_filters.Subscriber', (['"""/Encoder_data"""', 'Float32'], {}), "('/Encoder_data', Float32)\n", (2425, 2451), False, 'import message_filters\n'), ((2468, 2572), 'message_filters.ApproximateTimeSynchronizer', 'message_filters.ApproximateTimeSynchronizer', (['[IMU_message, Encoder_message]'], {'queue_size': '(1)', 'slop': '(0.05)'}), '([IMU_message, Encoder_message],\n queue_size=1, slop=0.05)\n', (2511, 2572), False, 'import message_filters\n'), ((2685, 2697), 'rospy.spin', 'rospy.spin', ([], {}), '()\n', (2695, 2697), False, 'import rospy\n')]
# -*- coding: utf-8 -*- # Copyright (c) 2016, KOL # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the <organization> nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from urlparse import urlparse from updater import Updater PREFIX = '/video/torrserver' ART = 'art-default.jpg' ICON = 'icon-default.png' TITLE = 'TorrServer' SERVER_RE = Regex('^https?://[^/:]+(:[0-9]{1,5})?$') def Start(): HTTP.CacheTime = 0 def ValidatePrefs(): if (ValidateServer()): return MessageContainer( header=u'%s' % L('Success'), message=u'%s' % L('Preferences was changed') ) else: return MessageContainer( header=u'%s' % L('Error'), message=u'%s' % L('Bad server address') ) def ValidateServer(): return Prefs['server'] and SERVER_RE.match(Prefs['server']) def GetLink(file): if 'Play' in file: return file['Play'] return file['Link'] @handler(PREFIX, TITLE, thumb=ICON) def MainMenu(): oc = ObjectContainer(title2=TITLE, no_cache=True) Updater(PREFIX+'/update', oc) if not ValidateServer(): return MessageContainer( header=u'%s' % L('Error'), message=u'%s' % L('Please specify server address in plugin preferences') ) items = GetItems() if not items: return NoContents() server = GetServerUrl() for item in items: if len(item['Files']) > 1: oc.add(DirectoryObject( key=Callback( List, hash=item['Hash'] ), title=u'%s' % item['Name'] )) else: file = item['Files'][0] oc.add(GetVideoObject(server+GetLink(file), file['Name'])) return oc @route(PREFIX + '/list') def List(hash): found = False items = GetItems() if not items: return NoContents() for item in items: if item['Hash'] == hash: found = True break if not found: return NoContents() oc = ObjectContainer( title2=u'%s' % item['Name'], replace_parent=False, ) server = GetServerUrl() for file in item['Files']: oc.add(GetVideoObject(server+GetLink(file), file['Name'])) if not len(oc): return NoContents() return oc @route(PREFIX + '/play') def VideoPlay(uri, title, **kwargs): return ObjectContainer( objects=[GetVideoObject(uri, title)], content=ContainerContent.GenericVideos ) def GetVideoObject(uri, title): uri = u'%s' % uri title = u'%s' % title return VideoClipObject( key=Callback( VideoPlay, uri=uri, title=title ), rating_key=uri, title=title, source_title=TITLE, items=[ MediaObject( parts=[PartObject(key=uri)], container=Container.MP4, video_codec=VideoCodec.H264, audio_codec=AudioCodec.AAC, optimized_for_streaming=True ) ] ) def GetItems(): try: res = JSON.ObjectFromURL(GetServerUrl()+'/torrent/list', method='POST') except Exception as e: Log.Error(u'%s' % e) return None if not len(res): return None return res def GetServerUrl(): url = Prefs['server'] if url[-1] == '/': return url[0:-1] return url def NoContents(): return ObjectContainer( header=u'%s' % L('Error'), message=u'%s' % L('No entries found') )
[ "updater.Updater" ]
[((2445, 2476), 'updater.Updater', 'Updater', (["(PREFIX + '/update')", 'oc'], {}), "(PREFIX + '/update', oc)\n", (2452, 2476), False, 'from updater import Updater\n')]
# !/usr/bin/env python # coding:utf-8 # Author:XuPengTao # Date: 2020/3/14 from ssd.layers import L2Norm import torch.nn.functional as F import torch.nn as nn import torch from ssd.modeling import registry import os import quantization.WqAq.dorefa.models.util_wqaq as dorefa import quantization.WqAq.IAO.models.util_wqaq as IAO import quantization.WbWtAb.models.util_wt_bab as BWN def fuse_conv_and_bn(conv, bn): # https://tehnokv.com/posts/fusing-batchnorm-and-conv/ with torch.no_grad(): # init fusedconv = torch.nn.Conv2d(conv.in_channels, conv.out_channels, kernel_size=conv.kernel_size, stride=conv.stride, padding=conv.padding, dilation=conv.dilation, groups=conv.groups, bias=True) # prepare filters w_conv = conv.weight.clone().view(conv.out_channels, -1) w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var))) fusedconv.weight.copy_(torch.mm(w_bn, w_conv).view(fusedconv.weight.size())) # prepare spatial bias if conv.bias is not None: b_conv = conv.bias else: b_conv = torch.zeros(conv.weight.size(0)).cuda() b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps)) fusedconv.bias.copy_(bn.weight.mul(b_conv).div(torch.sqrt(bn.running_var + bn.eps))+ b_bn) return fusedconv class Swish(nn.Module): def __init__(self): super(Swish, self).__init__() def forward(self, x): return x * torch.sigmoid(x) class relu6(nn.Module): def __init__(self): super(relu6, self).__init__() def forward(self, x): return F.relu6(x, inplace=True) class h_swish(nn.Module): def __init__(self): super(h_swish, self).__init__() def forward(self, x): return x * (F.relu6(x + 3.0, inplace=True) / 6.0) class h_sigmoid(nn.Module): def __init__(self): super(h_sigmoid, self).__init__() def forward(self, x): out = F.relu6(x + 3.0, inplace=True) / 6.0 return out class SE(nn.Module): def __init__(self, channel, reduction=4): super(SE, self).__init__() self.avg_pool = nn.AdaptiveAvgPool2d(1) self.fc = nn.Sequential( nn.Linear(channel, channel // reduction, bias=False), nn.ReLU(inplace=True), nn.Linear(channel // reduction, channel, bias=False), h_sigmoid() # nn.Sigmoid() ) def forward(self, x): b, c, _, _ = x.size() y = self.avg_pool(x).view(b, c) y = self.fc(y).view(b, c, 1, 1) return x * y.expand_as(x) class Backbone(nn.Module): def __init__(self, cfg): super().__init__() self.quan_type = cfg.QUANTIZATION.TYPE if self.quan_type == 'dorefa': self.quan_conv = dorefa.Conv2d_Q self.wbits = cfg.QUANTIZATION.WBITS self.abits = cfg.QUANTIZATION.ABITS elif self.quan_type == 'IAO': self.quan_conv_bn = IAO.BNFold_Conv2d_Q # BN融合训练 self.quan_conv = IAO.Conv2d_Q self.wbits = cfg.QUANTIZATION.WBITS self.abits = cfg.QUANTIZATION.ABITS elif self.quan_type =='BWN': self.quan_conv = BWN.Conv2d_Q self.wbits = cfg.QUANTIZATION.WBITS self.abits = cfg.QUANTIZATION.ABITS if self.abits!=2: #这里2不表示2位,表示二值 print('激活未量化') if self.wbits!=2 and self.wbits!=3: print('权重未量化') self.module_defs = self.parse_model_cfg(cfg.MODEL.BACKBONE.CFG) self.module_list, self.l2_norm_index,self.features,self.l2_norm,self.routs= self.create_backbone(cfg,self.module_defs) self.reset_parameters() def parse_model_cfg(self,path): # Parses the ssd layer configuration file and returns module definitions # print(os.getcwd())#绝对路径 # print(os.path.abspath(os.path.join(os.getcwd(), "../../.."))) #获取上上上级目录 # file = open(os.path.join(os.path.abspath(os.path.join(os.getcwd(), "../../..")),path), 'r') #测试本文件时使用 file=open(path,'r') lines = file.read().split('\n') lines = [x for x in lines if x and not x.startswith('#')] lines = [x.rstrip().lstrip() for x in lines] # get rid of fringe whitespaces mdefs = [] # module definitions for line in lines: if line.startswith('['): # This marks the start of a new block mdefs.append({}) mdefs[-1]['type'] = line[1:-1].rstrip() if mdefs[-1]['type'] == 'convolutional' or mdefs[-1]['type'] == 'depthwise': mdefs[-1]['batch_normalize'] = '0' # pre-populate with zeros (may be overwritten later) mdefs[-1]['feature'] = 'no' mdefs[-1]['dilation'] = '1' mdefs[-1]['bias'] = '1' mdefs[-1]['quantization'] = '0' else: mdefs[-1]['feature'] = 'no' else: key, val = line.split("=") key = key.rstrip() mdefs[-1][key] = val.strip() return mdefs def create_backbone(self,cfg, module_defs): # Constructs module list of layer blocks from module configuration in module_defs output_filters = [int(cfg.INPUT.CHANNELS)] module_list = nn.ModuleList() features = [] # list of layers which rout to detection layes routs = [] # list of layers which rout to deeper layes l2_norm_index = 0 l2_norm = 0 for i, mdef in enumerate(module_defs): modules = nn.Sequential() # print(mdef) if mdef['type'] == 'convolutional': bn = int(mdef['batch_normalize']) quantization = int(mdef['quantization']) filters = int(mdef['filters']) kernel_size = int(mdef['size']) pad = int(mdef['pad']) if mdef['bias']=='1': bias=True else: bias=False if quantization == 0: modules.add_module('Conv2d', nn.Conv2d(in_channels=output_filters[-1], out_channels=filters, kernel_size=kernel_size, stride=int(mdef['stride']), padding=pad, dilation=int(mdef['dilation']),bias=bias)) if bn: modules.add_module('BatchNorm2d', nn.BatchNorm2d(filters, momentum=0.1)) elif self.quan_type=='dorefa': # print('Q') modules.add_module('Conv2d', self.quan_conv(in_channels=output_filters[-1], out_channels=filters, kernel_size=kernel_size, stride=int(mdef['stride']), padding=pad, dilation=int(mdef['dilation']), a_bits=self.abits, w_bits=self.wbits,bias=bias)) if bn: modules.add_module('BatchNorm2d', nn.BatchNorm2d(filters, momentum=0.1)) elif self.quan_type=='IAO': if bn: modules.add_module('Conv2d', self.quan_conv_bn(in_channels=output_filters[-1], out_channels=filters, kernel_size=kernel_size, stride=int(mdef['stride']), padding=pad, dilation=int(mdef['dilation']), a_bits=self.abits, w_bits=self.wbits,bias=False))##BN_fold这一版默认没有bias #默认对称量化 量化零点为0 else: modules.add_module('Conv2d', self.quan_conv(in_channels=output_filters[-1], out_channels=filters, kernel_size=kernel_size, stride=int(mdef['stride']), padding=pad, dilation=int(mdef['dilation']), a_bits=self.abits, w_bits=self.wbits,bias=bias)) elif self.quan_type=='BWN': modules.add_module('Conv2d', self.quan_conv(in_channels=output_filters[-1], out_channels=filters, kernel_size=kernel_size, stride=int(mdef['stride']), padding=pad, dilation=int(mdef['dilation']), A=self.abits, W=self.wbits, bias=bias)) if bn: modules.add_module('BatchNorm2d', nn.BatchNorm2d(filters, momentum=0.1)) if mdef['activation'] == 'leaky': modules.add_module('activation', nn.LeakyReLU(0.1, inplace=True)) elif mdef['activation'] == 'relu': modules.add_module('activation', nn.ReLU(inplace=True)) elif mdef['activation'] == 'relu6': modules.add_module('activation', relu6()) elif mdef['activation'] == 'h_swish': modules.add_module('activation', h_swish()) elif mdef['type'] == 'depthwise': bn = int(mdef['batch_normalize']) filters = int(mdef['filters']) kernel_size = int(mdef['size']) pad = int(mdef['pad']) quantization = int(mdef['quantization']) if mdef['bias'] == '1': bias = True else: bias = False if quantization == 0: modules.add_module('DepthWise2d', nn.Conv2d(in_channels=output_filters[-1], out_channels=filters, kernel_size=kernel_size, stride=int(mdef['stride']), padding=pad, groups=output_filters[-1], dilation=int(mdef['dilation']), bias=bias)) if bn: modules.add_module('BatchNorm2d', nn.BatchNorm2d(filters, momentum=0.1)) elif self.quan_type=='dorefa': # print('Q') modules.add_module('DepthWise2d', self.quan_conv(in_channels=output_filters[-1], out_channels=filters, kernel_size=kernel_size, stride=int(mdef['stride']), padding=pad, dilation=int(mdef['dilation']), groups=output_filters[-1], a_bits=self.abits, w_bits=self.wbits,bias=bias)) if bn: modules.add_module('BatchNorm2d', nn.BatchNorm2d(filters, momentum=0.1)) elif self.quan_type=='IAO': if bn: modules.add_module('Conv2d', self.quan_conv_bn(in_channels=output_filters[-1], out_channels=filters, kernel_size=kernel_size, stride=int(mdef['stride']), padding=pad, dilation=int(mdef['dilation']), groups=output_filters[-1], a_bits=self.abits, w_bits=self.wbits,bias=False))##BN_fold这一版默认没有bias #默认对称量化 量化零点为0 else: modules.add_module('Conv2d', self.quan_conv(in_channels=output_filters[-1], out_channels=filters, kernel_size=kernel_size, stride=int(mdef['stride']), padding=pad, groups=output_filters[-1], dilation=int(mdef['dilation']), a_bits=self.abits, w_bits=self.wbits,bias=bias)) elif self.quan_type=='BWN': modules.add_module('Conv2d', self.quan_conv(in_channels=output_filters[-1], out_channels=filters, kernel_size=kernel_size, stride=int(mdef['stride']), padding=pad, dilation=int(mdef['dilation']), groups=output_filters[-1], A=self.abits, W=self.wbits, bias=bias)) if bn: modules.add_module('BatchNorm2d', nn.BatchNorm2d(filters, momentum=0.1)) if mdef['activation'] == 'leaky': modules.add_module('activation', nn.LeakyReLU(0.1, inplace=True)) elif mdef['activation'] == 'relu': modules.add_module('activation', nn.ReLU(inplace=True)) elif mdef['activation'] == 'relu6': modules.add_module('activation', relu6()) elif mdef['activation'] == 'h_swish': modules.add_module('activation', h_swish()) #不能加else 会影响linear不激活 elif mdef['type'] == 'shortcut': # nn.Sequential() placeholder for 'shortcut' layer layer = int(mdef['from']) filters = output_filters[layer] routs.extend([i + layer if layer < 0 else layer]) elif mdef['type'] == 'maxpool': kernel_size = int(mdef['size']) stride = int(mdef['stride']) ceil_mode = True if int(mdef['ceil_mode']) else False maxpool = nn.MaxPool2d(kernel_size=kernel_size, stride=stride, padding=int(mdef['pad']), ceil_mode=ceil_mode)#https://www.cnblogs.com/xxxxxxxxx/p/11529343.html ceilmode modules = maxpool else: print("Error type!") raise Exception if mdef['feature'] == 'linear': # 传入预测层 features.append(i) elif mdef['feature'] == 'l2_norm': features.append(i) l2_norm_index = i l2_norm = L2Norm(filters) # Register module list and number of output filters module_list.append(modules) output_filters.append(filters) return module_list, l2_norm_index, features, l2_norm,routs def reset_parameters(self): for m in self.module_list.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_uniform_(m.weight) if m.bias is not None: nn.init.zeros_(m.bias) def forward(self, x): layer_outputs = [] features=[] for i, (mdef, module) in enumerate(zip(self.module_defs, self.module_list)): mtype = mdef['type'] if mtype in ['convolutional', 'depthwise', 'se', 'upsample', 'maxpool']: x = module(x)#过卷积、激活 # #打印中间输出 # import numpy as np # import sys # np.set_printoptions(threshold=sys.maxsize) # 全部输出,无省略号 # np.set_printoptions(suppress=True) # 不用指数e # print(x.shape) # # print(x.cpu().numpy()) # np.savetxt(f'fpga/{i}_{x.shape}.txt', x.flatten().cpu().numpy()) # # #模拟fpga量化特征值 # # 给你一个weight.txt和bias.txt的float型数据 # # 跑你现在的ssd网络,针对每一层的输出特征,进行量化(找到这一层的最大值(因为是relu,所以最小值可以不管)之后最大值如果是56,可以用2 ^ 6 # # 表示,那么这一层的数同时乘以再除以2 ^ 9(此处用short型或者int16型,之后传到下一层)) # max=torch.max(x) # # print(max) # for bit in range(15):#16bit量化 符号位占一位 # if max<pow(2,bit): # zhengshu=bit#整数部分用几位 # break # xiaoshu=15-zhengshu # # print(xiaoshu) # # print((x*torch.tensor([pow(2,xiaoshu)]).cuda()).int().float()) # x=(x*torch.tensor([pow(2,xiaoshu)]).cuda()).int().float()/torch.tensor([pow(2,xiaoshu)]).cuda() # # print(x_copy-x) # # print('max:') # print(torch.max(x)) ######### elif mtype == 'shortcut': x = x + layer_outputs[int(mdef['from'])] layer_outputs.append(x if i in self.routs else []) if i in self.features: if i!=self.l2_norm_index: features.append(x) else:#l2_norm feature=self.l2_norm(x) features.append(feature) return tuple(features) def bn_fuse(self): #dilation应该不影响bn融合 # Fuse Conv2d + BatchNorm2d layers throughout model BN融合 fused_list = nn.ModuleList() # print(list(self.children())[0])#module_list for a in list(self.children())[0]: # print(a) if isinstance(a, nn.Sequential): for i, b in enumerate(a): if isinstance(b, nn.modules.batchnorm.BatchNorm2d): # print(1) # # fuse this bn layer with the previous conv2d layer # print(a[i-1]) # print(b) # print(*list(a.children())[i + 1:]) conv = a[i - 1] fused = fuse_conv_and_bn(conv, b) a = nn.Sequential(fused, *list(a.children())[i + 1:]) break fused_list.append(a) self.module_list = fused_list @registry.BACKBONES.register('cfg_backbone') def cfg_backbone(cfg, pretrained=True): model = Backbone(cfg) if pretrained: # print('Load pretrained model from {}'.format(cfg.MODEL.BACKBONE.WEIGHTS)) state = torch.load(cfg.MODEL.BACKBONE.WEIGHTS) if cfg.MODEL.BACKBONE.WEIGHTS.find('ssd') >= 0: #在检测数据集(voc\coco)上的预训练模型,加载全部backbone if 'model' in state.keys(): state = state['model'] name_list = list(state.keys()) num = 0 for i, (mdef, module) in enumerate(zip(model.module_defs, model.module_list)): if mdef['type'] == 'convolutional' or mdef['type'] == 'depthwise': conv_layer = module[0] conv_layer.weight.data.copy_(state[name_list[num]]) num = num + 1 if conv_layer.bias is not None: conv_layer.bias.data.copy_(state[name_list[num]]) ##可能之前的全精度权重有bias,IAO没有 if mdef['bias']=='1': num=num+1 if mdef['batch_normalize'] == '1': if isinstance(conv_layer, IAO.BNFold_Conv2d_Q): # iIAO bn conv_layer.gamma.data.copy_(state[name_list[num]]) num = num + 1 conv_layer.beta.data.copy_(state[name_list[num]]) num = num + 1 conv_layer.running_mean.data.copy_(state[name_list[num]]) num = num + 1 conv_layer.running_var.data.copy_(state[name_list[num]]) num = num + 2 # 跳过num_batches_tracked else: # Load BN bias, weights, running mean and running variance bn_layer = module[1] bn_layer.weight.data.copy_(state[name_list[num]]) num = num + 1 bn_layer.bias.data.copy_(state[name_list[num]]) num = num + 1 bn_layer.running_mean.data.copy_(state[name_list[num]]) num = num + 1 bn_layer.running_var.data.copy_(state[name_list[num]]) num = num + 2 # 跳过num_batches_tracked else:#加载在分类数据集(imagenet)上的权重,只加载reduce_fc的部分 name_list = list(state.keys()) num = 0 for i, (mdef, module) in enumerate(zip(model.module_defs, model.module_list)): if mdef['type'] == 'convolutional' or mdef['type'] == 'depthwise': conv_layer = module[0] conv_layer.weight.data.copy_(state[name_list[num]]) num = num + 1 if conv_layer.bias is not None: conv_layer.bias.data.copy_(state[name_list[num]]) num = num + 1 if mdef['batch_normalize'] == '1': # Load BN bias, weights, running mean and running variance bn_layer = module[1] bn_layer.weight.data.copy_(state[name_list[num]]) num = num + 1 bn_layer.bias.data.copy_(state[name_list[num]]) num = num + 1 bn_layer.running_mean.data.copy_(state[name_list[num]]) num = num + 1 bn_layer.running_var.data.copy_(state[name_list[num]]) num = num + 2 # 跳过num_batches_tracked if 'backbone' in mdef.keys():#加载在分类数据集(imagenet)上的权重,只加载reduce_fc的部分,之后不加载 break return model if __name__=='__main__': from ssd.config import cfg model = Backbone(cfg) print(model)
[ "torch.nn.ReLU", "ssd.layers.L2Norm", "torch.nn.Sequential", "torch.sqrt", "torch.nn.BatchNorm2d", "torch.nn.ModuleList", "torch.nn.init.zeros_", "torch.nn.functional.relu6", "torch.nn.AdaptiveAvgPool2d", "torch.nn.LeakyReLU", "ssd.modeling.registry.BACKBONES.register", "torch.nn.init.kaiming_...
[((20852, 20895), 'ssd.modeling.registry.BACKBONES.register', 'registry.BACKBONES.register', (['"""cfg_backbone"""'], {}), "('cfg_backbone')\n", (20879, 20895), False, 'from ssd.modeling import registry\n'), ((481, 496), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (494, 496), False, 'import torch\n'), ((533, 722), 'torch.nn.Conv2d', 'torch.nn.Conv2d', (['conv.in_channels', 'conv.out_channels'], {'kernel_size': 'conv.kernel_size', 'stride': 'conv.stride', 'padding': 'conv.padding', 'dilation': 'conv.dilation', 'groups': 'conv.groups', 'bias': '(True)'}), '(conv.in_channels, conv.out_channels, kernel_size=conv.\n kernel_size, stride=conv.stride, padding=conv.padding, dilation=conv.\n dilation, groups=conv.groups, bias=True)\n', (548, 722), False, 'import torch\n'), ((1894, 1918), 'torch.nn.functional.relu6', 'F.relu6', (['x'], {'inplace': '(True)'}), '(x, inplace=True)\n', (1901, 1918), True, 'import torch.nn.functional as F\n'), ((2417, 2440), 'torch.nn.AdaptiveAvgPool2d', 'nn.AdaptiveAvgPool2d', (['(1)'], {}), '(1)\n', (2437, 2440), True, 'import torch.nn as nn\n'), ((5624, 5639), 'torch.nn.ModuleList', 'nn.ModuleList', ([], {}), '()\n', (5637, 5639), True, 'import torch.nn as nn\n'), ((20030, 20045), 'torch.nn.ModuleList', 'nn.ModuleList', ([], {}), '()\n', (20043, 20045), True, 'import torch.nn as nn\n'), ((21081, 21119), 'torch.load', 'torch.load', (['cfg.MODEL.BACKBONE.WEIGHTS'], {}), '(cfg.MODEL.BACKBONE.WEIGHTS)\n', (21091, 21119), False, 'import torch\n'), ((1747, 1763), 'torch.sigmoid', 'torch.sigmoid', (['x'], {}), '(x)\n', (1760, 1763), False, 'import torch\n'), ((2233, 2263), 'torch.nn.functional.relu6', 'F.relu6', (['(x + 3.0)'], {'inplace': '(True)'}), '(x + 3.0, inplace=True)\n', (2240, 2263), True, 'import torch.nn.functional as F\n'), ((2486, 2538), 'torch.nn.Linear', 'nn.Linear', (['channel', '(channel // reduction)'], {'bias': '(False)'}), '(channel, channel // reduction, bias=False)\n', (2495, 2538), True, 'import torch.nn as nn\n'), ((2552, 2573), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (2559, 2573), True, 'import torch.nn as nn\n'), ((2587, 2639), 'torch.nn.Linear', 'nn.Linear', (['(channel // reduction)', 'channel'], {'bias': '(False)'}), '(channel // reduction, channel, bias=False)\n', (2596, 2639), True, 'import torch.nn as nn\n'), ((5889, 5904), 'torch.nn.Sequential', 'nn.Sequential', ([], {}), '()\n', (5902, 5904), True, 'import torch.nn as nn\n'), ((21131, 21169), 'ssd.config.cfg.MODEL.BACKBONE.WEIGHTS.find', 'cfg.MODEL.BACKBONE.WEIGHTS.find', (['"""ssd"""'], {}), "('ssd')\n", (21162, 21169), False, 'from ssd.config import cfg\n'), ((1097, 1132), 'torch.sqrt', 'torch.sqrt', (['(bn.eps + bn.running_var)'], {}), '(bn.eps + bn.running_var)\n', (1107, 1132), False, 'import torch\n'), ((1452, 1487), 'torch.sqrt', 'torch.sqrt', (['(bn.running_var + bn.eps)'], {}), '(bn.running_var + bn.eps)\n', (1462, 1487), False, 'import torch\n'), ((2058, 2088), 'torch.nn.functional.relu6', 'F.relu6', (['(x + 3.0)'], {'inplace': '(True)'}), '(x + 3.0, inplace=True)\n', (2065, 2088), True, 'import torch.nn.functional as F\n'), ((17715, 17749), 'torch.nn.init.kaiming_uniform_', 'nn.init.kaiming_uniform_', (['m.weight'], {}), '(m.weight)\n', (17739, 17749), True, 'import torch.nn as nn\n'), ((1166, 1188), 'torch.mm', 'torch.mm', (['w_bn', 'w_conv'], {}), '(w_bn, w_conv)\n', (1174, 1188), False, 'import torch\n'), ((1544, 1579), 'torch.sqrt', 'torch.sqrt', (['(bn.running_var + bn.eps)'], {}), '(bn.running_var + bn.eps)\n', (1554, 1579), False, 'import torch\n'), ((17350, 17365), 'ssd.layers.L2Norm', 'L2Norm', (['filters'], {}), '(filters)\n', (17356, 17365), False, 'from ssd.layers import L2Norm\n'), ((17809, 17831), 'torch.nn.init.zeros_', 'nn.init.zeros_', (['m.bias'], {}), '(m.bias)\n', (17823, 17831), True, 'import torch.nn as nn\n'), ((10464, 10495), 'torch.nn.LeakyReLU', 'nn.LeakyReLU', (['(0.1)'], {'inplace': '(True)'}), '(0.1, inplace=True)\n', (10476, 10495), True, 'import torch.nn as nn\n'), ((6981, 7018), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['filters'], {'momentum': '(0.1)'}), '(filters, momentum=0.1)\n', (6995, 7018), True, 'import torch.nn as nn\n'), ((10601, 10622), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (10608, 10622), True, 'import torch.nn as nn\n'), ((15882, 15913), 'torch.nn.LeakyReLU', 'nn.LeakyReLU', (['(0.1)'], {'inplace': '(True)'}), '(0.1, inplace=True)\n', (15894, 15913), True, 'import torch.nn as nn\n'), ((7863, 7900), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['filters'], {'momentum': '(0.1)'}), '(filters, momentum=0.1)\n', (7877, 7900), True, 'import torch.nn as nn\n'), ((12032, 12069), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['filters'], {'momentum': '(0.1)'}), '(filters, momentum=0.1)\n', (12046, 12069), True, 'import torch.nn as nn\n'), ((16019, 16040), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (16026, 16040), True, 'import torch.nn as nn\n'), ((13005, 13042), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['filters'], {'momentum': '(0.1)'}), '(filters, momentum=0.1)\n', (13019, 13042), True, 'import torch.nn as nn\n'), ((10321, 10358), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['filters'], {'momentum': '(0.1)'}), '(filters, momentum=0.1)\n', (10335, 10358), True, 'import torch.nn as nn\n'), ((15738, 15775), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['filters'], {'momentum': '(0.1)'}), '(filters, momentum=0.1)\n', (15752, 15775), True, 'import torch.nn as nn\n')]
import os import shutil def build_env(config, config_name, path): t_path = os.path.join(path, config_name) if config != t_path: os.makedirs(path, exist_ok=True) shutil.copyfile(config, os.path.join(path, config_name))
[ "os.path.join", "os.makedirs" ]
[((80, 111), 'os.path.join', 'os.path.join', (['path', 'config_name'], {}), '(path, config_name)\n', (92, 111), False, 'import os\n'), ((145, 177), 'os.makedirs', 'os.makedirs', (['path'], {'exist_ok': '(True)'}), '(path, exist_ok=True)\n', (156, 177), False, 'import os\n'), ((210, 241), 'os.path.join', 'os.path.join', (['path', 'config_name'], {}), '(path, config_name)\n', (222, 241), False, 'import os\n')]
""" Python 3.9 программа самостоятельной игры агентов текущего и предыдущего покаления программа на Python по изучению обучения с подкреплением - Reinforcement Learning Название файла actor.py Version: 0.1 Author: <NAME> Date: 2021-12-23 """ import numpy as np import parl import os from alphazero_agent import create_agent from MCTS import MCTS from Arena import Arena from utils import win_loss_draw @parl.remote_class(wait=False) class Actor(object): def __init__(self, game, args, seed): # инициализация класса np.random.seed(seed) os.environ['OMP_NUM_THREADS'] = "1" self.game = game # экземпляр (объект) класса доски и игры между двумя игроками self.args = args # принимает все аргументы из главной программы # 'master_address': 'localhost:8010', # главный адрес кластера xparl # 'actors_num': 1, # количество удаленных участников # 'numIters': 1, # общее количество итераций # 'numEps': 1, # Количество полных игр с самостоятельной игрой для моделирования во время новой итерации. # 'arenaCompare': 50, # Количество игр, которые нужно сыграть во время игры на арене (питтинг) # 'numMCTSSims': 800, # Количество игровых ходов для моделирования MCTS. # 'updateThreshold': 0.8, # пороговое или большее количество игр # 'cpuct': 4, # CPUCT parameter # 'dirichletAlpha': 1.0, # альфа-параметр шума дирихле # 'numItersForTrainExamplesHistory': 20, # история примеров из последних итераций # 'checkpoint': './saved_model/', # папка для сохранения моделей и обучающих примеров # neural network of previous generation # нейронная сеть предыдущего поколения self.previous_agent = create_agent(self.game, cuda=False) # neural network of current generation # нейронная сеть текущего поколения self.current_agent = create_agent(self.game, cuda=False) # MCTS of previous generation # MCTS предыдущего поколения self.previous_mcts = MCTS( self.game, self.previous_agent, self.args, dirichlet_noise=True) # MCTS of current generation # MCTS текущего поколения self.current_mcts = MCTS( self.game, self.current_agent, self.args, dirichlet_noise=True) def self_play(self, current_weights, game_num): """ Сбор данных о тренировках путем самостоятельной игры. Аргументы: current_weights (numpy.array): последние веса нейронной сети game_num (int): номер игры для самостоятельной игры Возврат: train_examples (список): примеры формы (canonicalBoard, currPlayer, pi, v) """ print('Самостоятельная игра одного из созданных агентов (использует одно ядро)') # update weights of current neural network with latest weights # обновить веса текущей нейронной сети с последними весами self.current_agent.set_weights(current_weights) train_examples = [] # создаем пустую таблицу (список) тренировки for _ in range(game_num): print('Начинается игра №', _) # reset node state of MCTS print('сбросить состояние узла MCTS') self.current_mcts = MCTS(self.game, self.current_agent, self.args, dirichlet_noise=True) print('тренировка узла MCTS') train_examples.extend(self._executeEpisode()) # _executeEpisode() - функция одной игры return train_examples def pitting(self, previous_weights, current_weights, games_num): """Борьба между агентом предыдущего поколения и агентом текущего поколения Аргументы: previous_weights (numpy.array): веса нейронной сети предыдущего поколения current_weights (numpy.array): веса нейронной сети текущего поколения game_num (int): количество боев в игре Возврат: кортеж из (номер игры, в которой выиграл предыдущий агент, номер игры, в которой выиграл текущий агент, номер игры, в которой был проведен розыгрыш) """ print('Борьба') # update weights of previous and current neural network # обновить веса предыдущей и текущей нейронной сети self.previous_agent.set_weights(previous_weights) self.current_agent.set_weights(current_weights) # reset node state of MCTS # сбросить состояние узла MCTS print('сбросить состояние узла MCTS перед ареной') self.previous_mcts = MCTS(self.game, self.previous_agent, self.args) self.current_mcts = MCTS(self.game, self.current_agent, self.args) arena = Arena( lambda x: np.argmax(self.previous_mcts.getActionProb(x, temp=0)), lambda x: np.argmax(self.current_mcts.getActionProb(x, temp=0)), self.game) previous_wins, current_wins, draws = arena.playGames(games_num) return (previous_wins, current_wins, draws) # возвращает количество предудущих побед, текущих побед и ничьих def evaluate_test_dataset(self, current_weights, test_dataset): """ Оценить эффективность новейших нейронных сетей Аргументы: current_weights (numpy.array): последние веса нейронной сети test_dataset (список): номер игры для самостоятельной игры Возврат: кортеж из (количество совершенных ходов, количество хороших ходов) """ print('Эволюция') # update weights of current neural network with latest weights # обновить веса текущей нейронной сети с последними весами self.current_agent.set_weights(current_weights) # определяем качество проведенной игры perfect_move_count, good_move_count = 0, 0 for data in test_dataset: self.current_mcts = MCTS(self.game, self.current_agent, self.args) # обращаемся к дереву MCTS x = self.game.getCanonicalForm(data['board'], data['player']) agent_move = int(np.argmax(self.current_mcts.getActionProb(x, temp=0))) # количество ходов moves = data["move_score"] # список очков perfect_score = max(moves) # определяем максимальное значение в списке очков perfect_moves = [i for i in range(7) if moves[i] == perfect_score] # выбираем 7 лучших if agent_move in perfect_moves: perfect_move_count += 1 # подсчет идеальных ходов print('perfect_move_count', perfect_move_count) print('Определяем победа\пройгрыш\ничья - ', win_loss_draw(moves[agent_move])) if win_loss_draw(moves[agent_move]) == win_loss_draw(perfect_score): good_move_count += 1 # подсчет хороших ходов print('good_move_count', good_move_count) return (perfect_move_count, good_move_count) def _executeEpisode(self): # функция одной игры """ Эта функция выполняет один эпизод самостоятельной игры, начиная с игрока 1. По ходу игры каждый ход добавляется в качестве обучающего примера к trainExamples. Игра длится до конца. После игры заканчивается, результат игры используется для присвоения значений каждому примеру в поезде Примеры. Он использует temp = 1, если episodeStep <tempThresholdStep, и после этого использует temp = 0. Возврат: trainExamples: список примеров формы (canonicalBoard, currPlayer, pi, v) pi - вектор политики, проинформированный MCTS, v - +1, если игрок в конце концов выиграл игру, иначе -1. """ print('Эпизод одной игры') trainExamples = [] board = self.game.getInitBoard() self.curPlayer = 1 episodeStep = 0 while True: episodeStep += 1 print('Самостоятельная игра агентов текущего поколения и предыдущего, ход = ', episodeStep) canonicalBoard = self.game.getCanonicalForm(board, self.curPlayer) temp = int(episodeStep < self.args.tempThresholdStep) pi = self.current_mcts.getActionProb(canonicalBoard, temp=temp) sym = self.game.getSymmetries(canonicalBoard, pi) for b, p in sym: # board, pi trainExamples.append([b, self.curPlayer, p, None]) action = np.random.choice(len(pi), p=pi) board, self.curPlayer = self.game.getNextState( board, self.curPlayer, action) r = self.game.getGameEnded(board, self.curPlayer) if r != 0: return [(x[0], x[2], r * ((-1)**(x[1] != self.curPlayer))) for x in trainExamples]
[ "MCTS.MCTS", "utils.win_loss_draw", "parl.remote_class", "alphazero_agent.create_agent", "numpy.random.seed" ]
[((406, 435), 'parl.remote_class', 'parl.remote_class', ([], {'wait': '(False)'}), '(wait=False)\n', (423, 435), False, 'import parl\n'), ((531, 551), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (545, 551), True, 'import numpy as np\n'), ((1788, 1823), 'alphazero_agent.create_agent', 'create_agent', (['self.game'], {'cuda': '(False)'}), '(self.game, cuda=False)\n', (1800, 1823), False, 'from alphazero_agent import create_agent\n'), ((1944, 1979), 'alphazero_agent.create_agent', 'create_agent', (['self.game'], {'cuda': '(False)'}), '(self.game, cuda=False)\n', (1956, 1979), False, 'from alphazero_agent import create_agent\n'), ((2085, 2154), 'MCTS.MCTS', 'MCTS', (['self.game', 'self.previous_agent', 'self.args'], {'dirichlet_noise': '(True)'}), '(self.game, self.previous_agent, self.args, dirichlet_noise=True)\n', (2089, 2154), False, 'from MCTS import MCTS\n'), ((2267, 2335), 'MCTS.MCTS', 'MCTS', (['self.game', 'self.current_agent', 'self.args'], {'dirichlet_noise': '(True)'}), '(self.game, self.current_agent, self.args, dirichlet_noise=True)\n', (2271, 2335), False, 'from MCTS import MCTS\n'), ((4591, 4638), 'MCTS.MCTS', 'MCTS', (['self.game', 'self.previous_agent', 'self.args'], {}), '(self.game, self.previous_agent, self.args)\n', (4595, 4638), False, 'from MCTS import MCTS\n'), ((4667, 4713), 'MCTS.MCTS', 'MCTS', (['self.game', 'self.current_agent', 'self.args'], {}), '(self.game, self.current_agent, self.args)\n', (4671, 4713), False, 'from MCTS import MCTS\n'), ((3314, 3382), 'MCTS.MCTS', 'MCTS', (['self.game', 'self.current_agent', 'self.args'], {'dirichlet_noise': '(True)'}), '(self.game, self.current_agent, self.args, dirichlet_noise=True)\n', (3318, 3382), False, 'from MCTS import MCTS\n'), ((5904, 5950), 'MCTS.MCTS', 'MCTS', (['self.game', 'self.current_agent', 'self.args'], {}), '(self.game, self.current_agent, self.args)\n', (5908, 5950), False, 'from MCTS import MCTS\n'), ((6667, 6699), 'utils.win_loss_draw', 'win_loss_draw', (['moves[agent_move]'], {}), '(moves[agent_move])\n', (6680, 6699), False, 'from utils import win_loss_draw\n'), ((6687, 6719), 'utils.win_loss_draw', 'win_loss_draw', (['moves[agent_move]'], {}), '(moves[agent_move])\n', (6700, 6719), False, 'from utils import win_loss_draw\n'), ((6723, 6751), 'utils.win_loss_draw', 'win_loss_draw', (['perfect_score'], {}), '(perfect_score)\n', (6736, 6751), False, 'from utils import win_loss_draw\n')]
from ptkcmd import PtkCmd, Completion, complete_files class MyPtkCmd(PtkCmd): prompt='MyPtkCmd$ ' def __init__(self,stdin=None,stdout=None,intro=None,interactive=True,do_complete_cmd=True,default_shell=False,**psession_kwargs): super().__init__(stdin,stdout,intro,interactive,do_complete_cmd,default_shell,**psession_kwargs) def do_mycmd(self,*args): """ This command is documented. """ self.stdout.write('Args were %s\n' % repr(args)) def do_myundoc(self,*args): self.stdout.write('Args were %s\n' % repr(args)) def help_mytopic(self): self.stdout.write('You called help for mytopic\n') def complete_mycmd(self,prev_args,curr_arg,document,complete_event): yield from complete_files(curr_arg) def test_ptkcmd(): MyPtkCmd().cmdloop()
[ "ptkcmd.complete_files" ]
[((759, 783), 'ptkcmd.complete_files', 'complete_files', (['curr_arg'], {}), '(curr_arg)\n', (773, 783), False, 'from ptkcmd import PtkCmd, Completion, complete_files\n')]
from schema.models import Member from django.shortcuts import render def save_userdata(backend, user, response, *args, **kwargs): if backend.name == 'facebook': try: profile = Member.objects.get(user_id=user.id) except Member.DoesNotExist: profile = Member(user_id=user.id) profile.uuid = response.get('id') profile.name = response.get('name') profile.save() def index(request): return render(request, 'index.html') def login(request): return render(request, 'index.html')
[ "django.shortcuts.render", "schema.models.Member", "schema.models.Member.objects.get" ]
[((462, 491), 'django.shortcuts.render', 'render', (['request', '"""index.html"""'], {}), "(request, 'index.html')\n", (468, 491), False, 'from django.shortcuts import render\n'), ((525, 554), 'django.shortcuts.render', 'render', (['request', '"""index.html"""'], {}), "(request, 'index.html')\n", (531, 554), False, 'from django.shortcuts import render\n'), ((202, 237), 'schema.models.Member.objects.get', 'Member.objects.get', ([], {'user_id': 'user.id'}), '(user_id=user.id)\n', (220, 237), False, 'from schema.models import Member\n'), ((296, 319), 'schema.models.Member', 'Member', ([], {'user_id': 'user.id'}), '(user_id=user.id)\n', (302, 319), False, 'from schema.models import Member\n')]
from django.http import HttpResponseRedirect, HttpResponse from django.shortcuts import get_object_or_404, render, redirect from django.urls import reverse from django.views import generic from django.views.generic import View from .pdf import * from .models import Campus, Usuario, Inventario, Libros,Issue,Resp,Cd from .forms import UsuarioForm, LibrosForm, IssueForm, CdForm, RespForm,InventarioForm def index(request): inventarios = Inventario.objects.all() return render(request, 'inventario/index.html', {'inventarios': inventarios}) def update_inventario(request, idinventario): inventario = Inventario.objects.get(idinventario=idinventario) form = InventarioForm(request.POST or None, instance=inventario) if form.is_valid(): form.save() return redirect('index') return render(request, 'inventario/inventario-form.html', {'form': form, 'inventario': inventario}) def create_libros(request): form = LibrosForm(request.POST or None) if form.is_valid(): form.save() return redirect('create_issue') return render(request, 'inventario/libros-form.html', {'form': form}) def create_issue(request): form = IssueForm(request.POST or None) if form.is_valid(): form.save() return redirect('create_resp') return render(request, 'inventario/issue-form.html', {'form': form}) def create_resp(request): form = RespForm(request.POST or None) if form.is_valid(): form.save() return redirect('create_cd') return render(request, 'inventario/resp-form.html', {'form': form}) def create_cd(request): form = CdForm(request.POST or None) if form.is_valid(): form.save() return redirect('create_inventario') return render(request, 'inventario/cd-form.html', {'form': form}) def create_inventario(request): form = InventarioForm(request.POST or None) if form.is_valid(): form.save() return redirect('index') return render(request, 'inventario/inventario-form.html', {'form': form}) def generar_pdf(request,idinventario): inventario = Inventario.objects.get(idinventario=idinventario) libros = Libros.objects.get(idinventario_libros=idinventario) issue = Issue.objects.get(idinventario_issue=idinventario) cd = Cd.objects.get(idinventario_cd=idinventario) resp = Resp.objects.get(idinventario_resp=idinventario) pdf=crearPdf(request,inventario,libros,issue,cd,resp) response = HttpResponse(content_type='application/pdf') response['Content-Disposition']='filename="InventarioAnual.pdf"' response.write(pdf) return response def libro_edit(request, idinventario): libros = Libros.objects.get(idinventario_libros=idinventario) form = LibrosForm(request.POST or None, instance=libros) if form.is_valid(): form.save() return redirect('index') return render(request, 'inventario/libros-edit.html', {'form': form, 'libros': libros}) def issue_edit(request,idinventario): issue = Issue.objects.get(idinventario_issue=idinventario) form = IssueForm(request.POST or None, instance=issue) if form.is_valid(): form.save() return redirect('index') return render(request, 'inventario/issue-edit.html', {'form': form, 'issue': issue}) def resp_edit(request, idinventario): resp = Resp.objects.get(idinventario_resp=idinventario) form = RespForm(request.POST or None, instance=resp) if form.is_valid(): form.save() return redirect('index') return render(request, 'inventario/resp-edit.html', {'form': form, 'resp': resp}) def cd_edit(request, idinventario): cd = Cd.objects.get(idinventario_cd=idinventario) form = CdForm(request.POST or None, instance=cd) if form.is_valid(): form.save() return redirect('index') return render(request, 'inventario/cd-edit.html', {'form': form, 'cd': cd}) def inventario_edit(request, idinventario): inventario = Inventario.objects.get(idinventario=idinventario) form = InventarioForm(request.POST or None, instance=inventario) if form.is_valid(): form.save() return redirect('index') return render(request, 'inventario/inventario-edit.html', {'form': form, 'inventario': inventario})
[ "django.shortcuts.render", "django.http.HttpResponse", "django.shortcuts.redirect" ]
[((479, 549), 'django.shortcuts.render', 'render', (['request', '"""inventario/index.html"""', "{'inventarios': inventarios}"], {}), "(request, 'inventario/index.html', {'inventarios': inventarios})\n", (485, 549), False, 'from django.shortcuts import get_object_or_404, render, redirect\n'), ((823, 919), 'django.shortcuts.render', 'render', (['request', '"""inventario/inventario-form.html"""', "{'form': form, 'inventario': inventario}"], {}), "(request, 'inventario/inventario-form.html', {'form': form,\n 'inventario': inventario})\n", (829, 919), False, 'from django.shortcuts import get_object_or_404, render, redirect\n'), ((1086, 1148), 'django.shortcuts.render', 'render', (['request', '"""inventario/libros-form.html"""', "{'form': form}"], {}), "(request, 'inventario/libros-form.html', {'form': form})\n", (1092, 1148), False, 'from django.shortcuts import get_object_or_404, render, redirect\n'), ((1316, 1377), 'django.shortcuts.render', 'render', (['request', '"""inventario/issue-form.html"""', "{'form': form}"], {}), "(request, 'inventario/issue-form.html', {'form': form})\n", (1322, 1377), False, 'from django.shortcuts import get_object_or_404, render, redirect\n'), ((1541, 1601), 'django.shortcuts.render', 'render', (['request', '"""inventario/resp-form.html"""', "{'form': form}"], {}), "(request, 'inventario/resp-form.html', {'form': form})\n", (1547, 1601), False, 'from django.shortcuts import get_object_or_404, render, redirect\n'), ((1769, 1827), 'django.shortcuts.render', 'render', (['request', '"""inventario/cd-form.html"""', "{'form': form}"], {}), "(request, 'inventario/cd-form.html', {'form': form})\n", (1775, 1827), False, 'from django.shortcuts import get_object_or_404, render, redirect\n'), ((1999, 2065), 'django.shortcuts.render', 'render', (['request', '"""inventario/inventario-form.html"""', "{'form': form}"], {}), "(request, 'inventario/inventario-form.html', {'form': form})\n", (2005, 2065), False, 'from django.shortcuts import get_object_or_404, render, redirect\n'), ((2490, 2534), 'django.http.HttpResponse', 'HttpResponse', ([], {'content_type': '"""application/pdf"""'}), "(content_type='application/pdf')\n", (2502, 2534), False, 'from django.http import HttpResponseRedirect, HttpResponse\n'), ((2905, 2990), 'django.shortcuts.render', 'render', (['request', '"""inventario/libros-edit.html"""', "{'form': form, 'libros': libros}"], {}), "(request, 'inventario/libros-edit.html', {'form': form, 'libros': libros}\n )\n", (2911, 2990), False, 'from django.shortcuts import get_object_or_404, render, redirect\n'), ((3237, 3314), 'django.shortcuts.render', 'render', (['request', '"""inventario/issue-edit.html"""', "{'form': form, 'issue': issue}"], {}), "(request, 'inventario/issue-edit.html', {'form': form, 'issue': issue})\n", (3243, 3314), False, 'from django.shortcuts import get_object_or_404, render, redirect\n'), ((3561, 3635), 'django.shortcuts.render', 'render', (['request', '"""inventario/resp-edit.html"""', "{'form': form, 'resp': resp}"], {}), "(request, 'inventario/resp-edit.html', {'form': form, 'resp': resp})\n", (3567, 3635), False, 'from django.shortcuts import get_object_or_404, render, redirect\n'), ((3870, 3938), 'django.shortcuts.render', 'render', (['request', '"""inventario/cd-edit.html"""', "{'form': form, 'cd': cd}"], {}), "(request, 'inventario/cd-edit.html', {'form': form, 'cd': cd})\n", (3876, 3938), False, 'from django.shortcuts import get_object_or_404, render, redirect\n'), ((4210, 4306), 'django.shortcuts.render', 'render', (['request', '"""inventario/inventario-edit.html"""', "{'form': form, 'inventario': inventario}"], {}), "(request, 'inventario/inventario-edit.html', {'form': form,\n 'inventario': inventario})\n", (4216, 4306), False, 'from django.shortcuts import get_object_or_404, render, redirect\n'), ((793, 810), 'django.shortcuts.redirect', 'redirect', (['"""index"""'], {}), "('index')\n", (801, 810), False, 'from django.shortcuts import get_object_or_404, render, redirect\n'), ((1049, 1073), 'django.shortcuts.redirect', 'redirect', (['"""create_issue"""'], {}), "('create_issue')\n", (1057, 1073), False, 'from django.shortcuts import get_object_or_404, render, redirect\n'), ((1280, 1303), 'django.shortcuts.redirect', 'redirect', (['"""create_resp"""'], {}), "('create_resp')\n", (1288, 1303), False, 'from django.shortcuts import get_object_or_404, render, redirect\n'), ((1507, 1528), 'django.shortcuts.redirect', 'redirect', (['"""create_cd"""'], {}), "('create_cd')\n", (1515, 1528), False, 'from django.shortcuts import get_object_or_404, render, redirect\n'), ((1727, 1756), 'django.shortcuts.redirect', 'redirect', (['"""create_inventario"""'], {}), "('create_inventario')\n", (1735, 1756), False, 'from django.shortcuts import get_object_or_404, render, redirect\n'), ((1969, 1986), 'django.shortcuts.redirect', 'redirect', (['"""index"""'], {}), "('index')\n", (1977, 1986), False, 'from django.shortcuts import get_object_or_404, render, redirect\n'), ((2875, 2892), 'django.shortcuts.redirect', 'redirect', (['"""index"""'], {}), "('index')\n", (2883, 2892), False, 'from django.shortcuts import get_object_or_404, render, redirect\n'), ((3207, 3224), 'django.shortcuts.redirect', 'redirect', (['"""index"""'], {}), "('index')\n", (3215, 3224), False, 'from django.shortcuts import get_object_or_404, render, redirect\n'), ((3531, 3548), 'django.shortcuts.redirect', 'redirect', (['"""index"""'], {}), "('index')\n", (3539, 3548), False, 'from django.shortcuts import get_object_or_404, render, redirect\n'), ((3840, 3857), 'django.shortcuts.redirect', 'redirect', (['"""index"""'], {}), "('index')\n", (3848, 3857), False, 'from django.shortcuts import get_object_or_404, render, redirect\n'), ((4180, 4197), 'django.shortcuts.redirect', 'redirect', (['"""index"""'], {}), "('index')\n", (4188, 4197), False, 'from django.shortcuts import get_object_or_404, render, redirect\n')]
import math a = int(input('digite um numero:')) print('O dobro do valor digitado é: {}\nO triplo é: {}\nA Raiz quadrada é: {}'.format((a*2),(a*3),(math.sqrt(a))))
[ "math.sqrt" ]
[((150, 162), 'math.sqrt', 'math.sqrt', (['a'], {}), '(a)\n', (159, 162), False, 'import math\n')]
#!/usr/bin/python import os, csv import tensorflow as tf import numpy as np import pandas as pd import helpers # fix random seed for reproducibility np.random.seed(7) #-------------------------- Constants --------------------------# FLAGS = tf.flags.FLAGS tf.flags.DEFINE_string( "input_dir", os.path.abspath("../data/real_logs"), "Input directory containing original JSON data files (default = '../data')" ) tf.flags.DEFINE_string( "output_dir", os.path.abspath("../data"), "Output directory for TFrEcord files (default = '../data')") tf.flags.DEFINE_integer("max_vector_len", 16, "Maximum vector length") #----------------------------------------------------------------# TRAIN_PATH = os.path.join(FLAGS.input_dir, "20170618_Belma.log") TEST_PATH = os.path.join(FLAGS.input_dir, "user1_unauthorized.log") CURRENT_PATH = TEST_PATH OUTPUT_FILE = "user1_test_C.csv" #----------------------------------------------------------------# ### START VOCABULARY FUNCTIONS ### def tokenizer_fn(iterator): return (x.split(" ") for x in iterator) def create_vocabulary(train_path, test_path): print("Creating vocabulary...") iter_generator = helpers.create_iter_generator(train_path) input_iter = [] for x in iter_generator: input = get_features(x) input = " ".join(input) input_iter.append(input) if (test_path): iter_generator = helpers.create_iter_generator(test_path) for x in iter_generator: input = get_features(x) for x in input: input_iter.append(x) vocab_processor = tf.contrib.learn.preprocessing.VocabularyProcessor( FLAGS.max_vector_len, tokenizer_fn=tokenizer_fn) vocab_processor.fit(input_iter) print("Done creating vocabulary.") return vocab_processor def write_vocabulary(vocabulary_processor, outfile): with open(outfile, "w") as vocabfile: for id in range(len(vocabulary_processor.vocabulary_)): word = vocabulary_processor.vocabulary_._reverse_mapping[id] vocabfile.write(word + "\n") print("Saved vocabulary to {}".format(outfile)) def create_and_save_vocabulary(train, test="", vocabularyfile="vocabulary.txt", processorfile="vocab_processor.bin"): vocabulary = create_vocabulary(train, test) # Create vocabulary.txt file write_vocabulary(vocabulary, os.path.join(FLAGS.output_dir, vocabularyfile)) # Save vocab processor vocabulary.save(os.path.join(tf.flags.FLAGS.output_dir, processorfile)) return vocabulary def restore_vocabulary(filename = os.path.join(tf.flags.FLAGS.output_dir, "vocab_processor.bin")): return tf.contrib.learn.preprocessing.VocabularyProcessor.restore(filename) ### END VOCABULARY FUNCTIONS ### def transform_sentence(sequence, vocab_processor): # Maps a single vector input into the integer vocabulary. if (type(sequence) is not list): sequence = [sequence] sequence = [" ".join(sequence)] vector = next(vocab_processor.transform(sequence)).tolist() vector_len = len(next(vocab_processor._tokenizer(sequence))) vector = vector[:vector_len] return vector def get_features(line): structure = ["added_or_removed", "hour", "usb_devices", "kernel_modules", "open_sockets", "open_sockets", "processes", "open_files", "logged_in_users", "logged_in_users", "shell_history", "listening_ports", "arp_cache", "arp_cache", "syslog", "syslog"] # First feature added_or_removed = "2" # added if (line["action"] == "removed"): added_or_removed = "1" # Second feature time = helpers.extract_hour(line["unixTime"]) # Other osquery features columns = line["columns"].values() # Compatibility with old shell_history query #if (line["name"] == "pack_external_pack_shell_history"): #columns = str(helpers._parse_shell_history(columns)) initial_vector = [added_or_removed, time] + ["0"] * (len(structure) - 2) # Put action columns in the right place of vector according to structure index = structure.index(line["name"].replace('pack_external_pack_', '')) for i in range(len(columns)): if (columns[i] == ""): initial_vector[index + i] = "0" else: initial_vector[index + i] = columns[i] return initial_vector """ Takes logline in json format and vocabulary object. Prepare to extract features from logline. Return dictionary containing features vector in key name action """ def action_to_vector(line, vocabulary): features_vector = get_features(line) action = transform_sentence(features_vector, vocabulary) return action def create_csv_file(input_filename, output_filename, vocabulary): print("Creating CSV file at {}...".format(output_filename)) actions = [] for i, row in enumerate(helpers.create_iter_generator(input_filename)): action_transformed = action_to_vector(row, vocabulary) actions.append(action_transformed) output = pd.DataFrame(data={'action': actions}) output.to_csv(output_filename, index=False, sep=";", quoting=csv.QUOTE_NONE, quotechar='') print("Wrote to {}".format(output_filename)) if __name__ == "__main__": if (CURRENT_PATH == TRAIN_PATH): vocabulary = create_and_save_vocabulary(TRAIN_PATH, TEST_PATH) else: vocabulary = restore_vocabulary() create_csv_file( input_filename=CURRENT_PATH, output_filename=os.path.join(tf.flags.FLAGS.output_dir, OUTPUT_FILE), vocabulary=vocabulary)
[ "helpers.extract_hour", "pandas.DataFrame", "os.path.join", "tensorflow.contrib.learn.preprocessing.VocabularyProcessor", "helpers.create_iter_generator", "numpy.random.seed", "tensorflow.flags.DEFINE_integer", "os.path.abspath", "tensorflow.contrib.learn.preprocessing.VocabularyProcessor.restore" ]
[((151, 168), 'numpy.random.seed', 'np.random.seed', (['(7)'], {}), '(7)\n', (165, 168), True, 'import numpy as np\n'), ((549, 619), 'tensorflow.flags.DEFINE_integer', 'tf.flags.DEFINE_integer', (['"""max_vector_len"""', '(16)', '"""Maximum vector length"""'], {}), "('max_vector_len', 16, 'Maximum vector length')\n", (572, 619), True, 'import tensorflow as tf\n'), ((701, 752), 'os.path.join', 'os.path.join', (['FLAGS.input_dir', '"""20170618_Belma.log"""'], {}), "(FLAGS.input_dir, '20170618_Belma.log')\n", (713, 752), False, 'import os, csv\n'), ((765, 820), 'os.path.join', 'os.path.join', (['FLAGS.input_dir', '"""user1_unauthorized.log"""'], {}), "(FLAGS.input_dir, 'user1_unauthorized.log')\n", (777, 820), False, 'import os, csv\n'), ((299, 335), 'os.path.abspath', 'os.path.abspath', (['"""../data/real_logs"""'], {}), "('../data/real_logs')\n", (314, 335), False, 'import os, csv\n'), ((457, 483), 'os.path.abspath', 'os.path.abspath', (['"""../data"""'], {}), "('../data')\n", (472, 483), False, 'import os, csv\n'), ((1159, 1200), 'helpers.create_iter_generator', 'helpers.create_iter_generator', (['train_path'], {}), '(train_path)\n', (1188, 1200), False, 'import helpers\n'), ((1591, 1694), 'tensorflow.contrib.learn.preprocessing.VocabularyProcessor', 'tf.contrib.learn.preprocessing.VocabularyProcessor', (['FLAGS.max_vector_len'], {'tokenizer_fn': 'tokenizer_fn'}), '(FLAGS.max_vector_len,\n tokenizer_fn=tokenizer_fn)\n', (1641, 1694), True, 'import tensorflow as tf\n'), ((2564, 2626), 'os.path.join', 'os.path.join', (['tf.flags.FLAGS.output_dir', '"""vocab_processor.bin"""'], {}), "(tf.flags.FLAGS.output_dir, 'vocab_processor.bin')\n", (2576, 2626), False, 'import os, csv\n'), ((2640, 2708), 'tensorflow.contrib.learn.preprocessing.VocabularyProcessor.restore', 'tf.contrib.learn.preprocessing.VocabularyProcessor.restore', (['filename'], {}), '(filename)\n', (2698, 2708), True, 'import tensorflow as tf\n'), ((3618, 3656), 'helpers.extract_hour', 'helpers.extract_hour', (["line['unixTime']"], {}), "(line['unixTime'])\n", (3638, 3656), False, 'import helpers\n'), ((5023, 5061), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': "{'action': actions}"}), "(data={'action': actions})\n", (5035, 5061), True, 'import pandas as pd\n'), ((1393, 1433), 'helpers.create_iter_generator', 'helpers.create_iter_generator', (['test_path'], {}), '(test_path)\n', (1422, 1433), False, 'import helpers\n'), ((2354, 2400), 'os.path.join', 'os.path.join', (['FLAGS.output_dir', 'vocabularyfile'], {}), '(FLAGS.output_dir, vocabularyfile)\n', (2366, 2400), False, 'import os, csv\n'), ((2449, 2503), 'os.path.join', 'os.path.join', (['tf.flags.FLAGS.output_dir', 'processorfile'], {}), '(tf.flags.FLAGS.output_dir, processorfile)\n', (2461, 2503), False, 'import os, csv\n'), ((4855, 4900), 'helpers.create_iter_generator', 'helpers.create_iter_generator', (['input_filename'], {}), '(input_filename)\n', (4884, 4900), False, 'import helpers\n'), ((5479, 5531), 'os.path.join', 'os.path.join', (['tf.flags.FLAGS.output_dir', 'OUTPUT_FILE'], {}), '(tf.flags.FLAGS.output_dir, OUTPUT_FILE)\n', (5491, 5531), False, 'import os, csv\n')]
from django.contrib import admin from django.urls import path # from django.contrib.auth.decorators import login_required # from rest_framework.urlpatterns import format_suffix_patterns from . views import * urlpatterns = [ # path('admin/', admin.site.urls), path('', main_view, name='main_view'), ]
[ "django.urls.path" ]
[((267, 304), 'django.urls.path', 'path', (['""""""', 'main_view'], {'name': '"""main_view"""'}), "('', main_view, name='main_view')\n", (271, 304), False, 'from django.urls import path\n')]
#!/usr/bin/env python # Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import unittest from app_yaml_helper import AppYamlHelper from extensions_paths import SERVER2 from host_file_system_provider import HostFileSystemProvider from mock_file_system import MockFileSystem from object_store_creator import ObjectStoreCreator from test_file_system import MoveTo, TestFileSystem from test_util import DisableLogging _ExtractVersion, _IsGreater, _GenerateAppYaml = ( AppYamlHelper.ExtractVersion, AppYamlHelper.IsGreater, AppYamlHelper.GenerateAppYaml) class AppYamlHelperTest(unittest.TestCase): def testExtractVersion(self): def run_test(version): self.assertEqual(version, _ExtractVersion(_GenerateAppYaml(version))) run_test('0') run_test('0-0') run_test('0-0-0') run_test('1') run_test('1-0') run_test('1-0-0') run_test('1-0-1') run_test('1-1-0') run_test('1-1-1') run_test('2-0-9') run_test('2-0-12') run_test('2-1') run_test('2-1-0') run_test('2-11-0') run_test('3-1-0') run_test('3-1-3') run_test('3-12-0') def testIsGreater(self): def assert_is_greater(lhs, rhs): self.assertTrue(_IsGreater(lhs, rhs), '%s is not > %s' % (lhs, rhs)) self.assertFalse(_IsGreater(rhs, lhs), '%s should not be > %s' % (rhs, lhs)) assert_is_greater('0-0', '0') assert_is_greater('0-0-0', '0') assert_is_greater('0-0-0', '0-0') assert_is_greater('1', '0') assert_is_greater('1', '0-0') assert_is_greater('1', '0-0-0') assert_is_greater('1-0', '0-0') assert_is_greater('1-0-0-0', '0-0-0') assert_is_greater('2-0-12', '2-0-9') assert_is_greater('2-0-12', '2-0-9-0') assert_is_greater('2-0-12-0', '2-0-9') assert_is_greater('2-0-12-0', '2-0-9-0') assert_is_greater('2-1', '2-0-9') assert_is_greater('2-1', '2-0-12') assert_is_greater('2-1-0', '2-0-9') assert_is_greater('2-1-0', '2-0-12') assert_is_greater('3-1-0', '2-1') assert_is_greater('3-1-0', '2-1-0') assert_is_greater('3-1-0', '2-11-0') assert_is_greater('3-1-3', '3-1-0') assert_is_greater('3-12-0', '3-1-0') assert_is_greater('3-12-0', '3-1-3') assert_is_greater('3-12-0', '3-1-3-0') @DisableLogging('warning') def testInstanceMethods(self): test_data = { 'app.yaml': _GenerateAppYaml('1-0'), 'app_yaml_helper.py': 'Copyright notice etc' } updates = [] # Pass a specific file system at head to the HostFileSystemProvider so that # we know it's always going to be backed by a MockFileSystem. The Provider # may decide to wrap it in caching etc. file_system_at_head = MockFileSystem( TestFileSystem(test_data, relative_to=SERVER2)) def apply_update(update): update = MoveTo(SERVER2, update) file_system_at_head.Update(update) updates.append(update) def host_file_system_constructor(branch, revision=None): self.assertEqual('trunk', branch) self.assertTrue(revision is not None) return MockFileSystem.Create( TestFileSystem(test_data, relative_to=SERVER2), updates[:revision]) object_store_creator = ObjectStoreCreator.ForTest() host_file_system_provider = HostFileSystemProvider( object_store_creator, default_trunk_instance=file_system_at_head, constructor_for_test=host_file_system_constructor) helper = AppYamlHelper(object_store_creator, host_file_system_provider) def assert_is_up_to_date(version): self.assertTrue(helper.IsUpToDate(version), '%s is not up to date' % version) self.assertRaises(ValueError, helper.GetFirstRevisionGreaterThan, version) self.assertEqual(0, helper.GetFirstRevisionGreaterThan('0-5-0')) assert_is_up_to_date('1-0-0') assert_is_up_to_date('1-5-0') # Revision 1. apply_update({ 'app.yaml': _GenerateAppYaml('1-5-0') }) self.assertEqual(0, helper.GetFirstRevisionGreaterThan('0-5-0')) self.assertEqual(1, helper.GetFirstRevisionGreaterThan('1-0-0')) assert_is_up_to_date('1-5-0') assert_is_up_to_date('2-5-0') # Revision 2. apply_update({ 'app_yaml_helper.py': 'fixed a bug' }) self.assertEqual(0, helper.GetFirstRevisionGreaterThan('0-5-0')) self.assertEqual(1, helper.GetFirstRevisionGreaterThan('1-0-0')) assert_is_up_to_date('1-5-0') assert_is_up_to_date('2-5-0') # Revision 3. apply_update({ 'app.yaml': _GenerateAppYaml('1-6-0') }) self.assertEqual(0, helper.GetFirstRevisionGreaterThan('0-5-0')) self.assertEqual(1, helper.GetFirstRevisionGreaterThan('1-0-0')) self.assertEqual(3, helper.GetFirstRevisionGreaterThan('1-5-0')) assert_is_up_to_date('2-5-0') # Revision 4. apply_update({ 'app.yaml': _GenerateAppYaml('1-8-0') }) # Revision 5. apply_update({ 'app.yaml': _GenerateAppYaml('2-0-0') }) # Revision 6. apply_update({ 'app.yaml': _GenerateAppYaml('2-2-0') }) # Revision 7. apply_update({ 'app.yaml': _GenerateAppYaml('2-4-0') }) # Revision 8. apply_update({ 'app.yaml': _GenerateAppYaml('2-6-0') }) self.assertEqual(0, helper.GetFirstRevisionGreaterThan('0-5-0')) self.assertEqual(1, helper.GetFirstRevisionGreaterThan('1-0-0')) self.assertEqual(3, helper.GetFirstRevisionGreaterThan('1-5-0')) self.assertEqual(5, helper.GetFirstRevisionGreaterThan('1-8-0')) self.assertEqual(6, helper.GetFirstRevisionGreaterThan('2-0-0')) self.assertEqual(6, helper.GetFirstRevisionGreaterThan('2-1-0')) self.assertEqual(7, helper.GetFirstRevisionGreaterThan('2-2-0')) self.assertEqual(7, helper.GetFirstRevisionGreaterThan('2-3-0')) self.assertEqual(8, helper.GetFirstRevisionGreaterThan('2-4-0')) self.assertEqual(8, helper.GetFirstRevisionGreaterThan('2-5-0')) assert_is_up_to_date('2-6-0') assert_is_up_to_date('2-7-0') if __name__ == '__main__': unittest.main()
[ "test_file_system.MoveTo", "test_file_system.TestFileSystem", "unittest.main", "object_store_creator.ObjectStoreCreator.ForTest", "app_yaml_helper.AppYamlHelper", "host_file_system_provider.HostFileSystemProvider", "test_util.DisableLogging" ]
[((2371, 2396), 'test_util.DisableLogging', 'DisableLogging', (['"""warning"""'], {}), "('warning')\n", (2385, 2396), False, 'from test_util import DisableLogging\n'), ((6137, 6152), 'unittest.main', 'unittest.main', ([], {}), '()\n', (6150, 6152), False, 'import unittest\n'), ((3295, 3323), 'object_store_creator.ObjectStoreCreator.ForTest', 'ObjectStoreCreator.ForTest', ([], {}), '()\n', (3321, 3323), False, 'from object_store_creator import ObjectStoreCreator\n'), ((3356, 3500), 'host_file_system_provider.HostFileSystemProvider', 'HostFileSystemProvider', (['object_store_creator'], {'default_trunk_instance': 'file_system_at_head', 'constructor_for_test': 'host_file_system_constructor'}), '(object_store_creator, default_trunk_instance=\n file_system_at_head, constructor_for_test=host_file_system_constructor)\n', (3378, 3500), False, 'from host_file_system_provider import HostFileSystemProvider\n'), ((3534, 3596), 'app_yaml_helper.AppYamlHelper', 'AppYamlHelper', (['object_store_creator', 'host_file_system_provider'], {}), '(object_store_creator, host_file_system_provider)\n', (3547, 3596), False, 'from app_yaml_helper import AppYamlHelper\n'), ((2819, 2865), 'test_file_system.TestFileSystem', 'TestFileSystem', (['test_data'], {'relative_to': 'SERVER2'}), '(test_data, relative_to=SERVER2)\n', (2833, 2865), False, 'from test_file_system import MoveTo, TestFileSystem\n'), ((2913, 2936), 'test_file_system.MoveTo', 'MoveTo', (['SERVER2', 'update'], {}), '(SERVER2, update)\n', (2919, 2936), False, 'from test_file_system import MoveTo, TestFileSystem\n'), ((3199, 3245), 'test_file_system.TestFileSystem', 'TestFileSystem', (['test_data'], {'relative_to': 'SERVER2'}), '(test_data, relative_to=SERVER2)\n', (3213, 3245), False, 'from test_file_system import MoveTo, TestFileSystem\n')]
import numpy as np import tensorflow as tf from tensorstream.finance.supertrend import Supertrend from tensorstream.tests import TestCase class SupertrendSpec(TestCase): def setUp(self): self.sheets = self.read_ods( self.from_test_res('supertrend.ods', __file__)) def test_supertrend(self): sheet = self.sheets['supertrend'] supertrend = Supertrend(10, 3) close_prices = tf.placeholder(tf.float32) low_prices = tf.placeholder(tf.float32) high_prices = tf.placeholder(tf.float32) supertrend_ts, _, _ = supertrend( inputs=(close_prices, low_prices, high_prices) ) with tf.Session() as sess: output = sess.run(supertrend_ts, { close_prices: sheet['close'], low_prices: sheet['low'], high_prices: sheet['high'], }) np.testing.assert_almost_equal(output, sheet['Supertrend'].values, decimal=3)
[ "numpy.testing.assert_almost_equal", "tensorflow.placeholder", "tensorstream.finance.supertrend.Supertrend", "tensorflow.Session" ]
[((364, 381), 'tensorstream.finance.supertrend.Supertrend', 'Supertrend', (['(10)', '(3)'], {}), '(10, 3)\n', (374, 381), False, 'from tensorstream.finance.supertrend import Supertrend\n'), ((401, 427), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {}), '(tf.float32)\n', (415, 427), True, 'import tensorflow as tf\n'), ((445, 471), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {}), '(tf.float32)\n', (459, 471), True, 'import tensorflow as tf\n'), ((490, 516), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {}), '(tf.float32)\n', (504, 516), True, 'import tensorflow as tf\n'), ((810, 887), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['output', "sheet['Supertrend'].values"], {'decimal': '(3)'}), "(output, sheet['Supertrend'].values, decimal=3)\n", (840, 887), True, 'import numpy as np\n'), ((625, 637), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (635, 637), True, 'import tensorflow as tf\n')]
import sys import math sys.setrecursionlimit(999000) def fac(x): if x < 2: return 1 return x * fac(x - 1) print(math.log10( fac(int(sys.argv[1])) ))
[ "sys.setrecursionlimit" ]
[((23, 52), 'sys.setrecursionlimit', 'sys.setrecursionlimit', (['(999000)'], {}), '(999000)\n', (44, 52), False, 'import sys\n')]
#!/usr/bin/python from Tkinter import * from notifier import Notifier from configurationReader import Configuration class PomodoroTimer(Frame): def __start(self): """ Start to work, this function is executed only the first time """ self.__button.config(text = "Stop", background = '#e21212', activebackground = '#f21515', command = self.quit) self.__status.config(text='Work!') self.__pomodorolabel.config(text=('Number of pomodoros done: ' + str(self.__npomodoro)) ) self.__working = True self.__notifier.notify('start') self.after(1000,self.__update) def __update(self): """ Keep updating the timer and change the session if ended """ self.__secs -= 1 if self.__secs < 0: self.__mins -= 1 self.__secs = 59 if self.__mins == 0 and self.__secs ==0: if self.__working: self.__break() self.__working = False elif not self.__working: self.__restart() self.__working = True self.__timeformat = '{:02d}:{:02d}'.format(self.__mins, self.__secs) self.__clock.config(text = self.__timeformat) self.__clock.after(1000,self.__update) def __break(self): """ Start a short break or a long break every four session """ self.__secs = 0 self.__npomodoro += 1 self.__pomodorolabel.config(text=('Number of pomodoros done: ' + str(self.__npomodoro)) ) self.__status.config(text='Break') if divmod(self.__npomodoro, self.__sprintsessions)[1] == 0: self.__notifier.notify('long break') self.__mins = self.__longbreaktime else: self.__notifier.notify('short break') self.__mins = self.__shortbreaktime def __restart(self): """ Restart the working session after a break """ self.__mins, self.__secs = self.__pomodorotime, 0 self.__status.config(text='Work!') self.__notifier.notify('start') def __createWidgets(self): """ Create all the widgets needed """ self.__buttons = Frame(self, bd = 0, bg = 'white') self.__button = Button(self, width=15, height=2, text = "Start", background = '#0ece10', activebackground = '#16e519', command = self.__start) #initialize minute and second for the timer self.__mins, self.__secs = self.__pomodorotime , 0 self.__timeformat = '{:02d}:{:02d}'.format(self.__mins, self.__secs) self.__clock = Label(self, font=('times', 50, 'bold'), background = 'white') self.__clock.config(text=self.__timeformat) #display the number of session done self.__pomodorolabel = Label(self, font=(21), background = 'white') #display a description of the session self.__status = Label(self, font=('times', 18, 'bold'), background = 'white') self.__buttons.pack(side = BOTTOM, fill = X) self.__button.pack(in_ = self.__buttons) self.__clock.pack( fill = BOTH, expand = 1) self.__status.pack(fill = BOTH, expand = 1) self.__pomodorolabel.pack(fill = BOTH, expand = 1) def __init__(self, master = Tk()): Frame.__init__(self, master) configuration = Configuration().get_values() self.__pomodorotime = configuration['pomodoro'] #minute of work self.__shortbreaktime = configuration['shortbreak'] #minute of short break self.__longbreaktime = configuration['longbreak'] #minute of long break #number of session before a long break self.__sprintsessions = configuration['beforelongbreak'] alarm = configuration['alarm'] self.__npomodoro = 0 # number of session done self.__notifier = Notifier(alarm) self.__working = False self.master.title("Pomodoro Timer") self.master.minsize(230, 220) self.master.maxsize(400, 300) self.master.configure(background = 'white') self.master.tk.call('wm', 'iconphoto', self.master._w, PhotoImage(file='./res/icon.png')) self.pack() self.__createWidgets()
[ "notifier.Notifier", "configurationReader.Configuration" ]
[((3474, 3489), 'notifier.Notifier', 'Notifier', (['alarm'], {}), '(alarm)\n', (3482, 3489), False, 'from notifier import Notifier\n'), ((3024, 3039), 'configurationReader.Configuration', 'Configuration', ([], {}), '()\n', (3037, 3039), False, 'from configurationReader import Configuration\n')]
""" """ import unittest import arcpy from numpy import pi from gsfarc.test import config class TestDatatypeDouble(unittest.TestCase): """Tests the double task datatype""" @classmethod def setUpClass(cls): """Class setup creates a toolbox file wrapper to GSF.""" config.setup_idl_toolbox('test_datatype_double', 'qa_idltaskengine_datatype_double') @classmethod def tearDownClass(cls): pass def test_datatype_double_positive(self): """Tests the double datatype with a positive value.""" input = pi result = arcpy.QA_IDLTaskEngine_DataType_Double_GSF(input) self.assertAlmostEqual(float(result.getOutput(0)), input, places=14) def test_datatype_double_negative(self): """Tests the double datatype with a negative value.""" input = -pi result = arcpy.QA_IDLTaskEngine_DataType_Double_GSF(input) self.assertAlmostEqual(float(result.getOutput(0)), input, places=14) if __name__ == '__main__': unittest.main()
[ "unittest.main", "gsfarc.test.config.setup_idl_toolbox", "arcpy.QA_IDLTaskEngine_DataType_Double_GSF" ]
[((1017, 1032), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1030, 1032), False, 'import unittest\n'), ((293, 381), 'gsfarc.test.config.setup_idl_toolbox', 'config.setup_idl_toolbox', (['"""test_datatype_double"""', '"""qa_idltaskengine_datatype_double"""'], {}), "('test_datatype_double',\n 'qa_idltaskengine_datatype_double')\n", (317, 381), False, 'from gsfarc.test import config\n'), ((582, 631), 'arcpy.QA_IDLTaskEngine_DataType_Double_GSF', 'arcpy.QA_IDLTaskEngine_DataType_Double_GSF', (['input'], {}), '(input)\n', (624, 631), False, 'import arcpy\n'), ((856, 905), 'arcpy.QA_IDLTaskEngine_DataType_Double_GSF', 'arcpy.QA_IDLTaskEngine_DataType_Double_GSF', (['input'], {}), '(input)\n', (898, 905), False, 'import arcpy\n')]
import psutil import os import time def get_function_memory_usage(function, iterations=100, max_time=None, max_mem_usage=90, verbose=False, display_period=0.2): ''' Cette fonction execute <iterations> fois <function> et renvoit la difference de mémoire virtuelle utilisée par le processus python entre la fin des iterations et le début. Une mesure de sécurité s'assure qu'une proportion <max_mem_usage> (en %, entre 0 et 100, defaut 90) de la RAM totale n'est pas dépassée au cours du bench afin de ne pas bloquer l'ordinateur. ''' this_process = psutil.Process(os.getpid()) i = 0 t0 = time.time() last_display_time = t0 last_display_iteration = i initial_process_mem = this_process.memory_info().vms while True: # execution de la fonction a bencher function() i += 1 # recuperation l'heure et de la mémoire utilisée process_mem = this_process.memory_info().vms total_mem = psutil.virtual_memory() t2 = time.time() # Affichage if verbose and display_period > 0 and (t2 - last_display_time) > display_period: function_mem = process_mem - initial_process_mem total_test_time = t2 - t0 average_iteration_duration = ( t2 - last_display_time) / (i - last_display_iteration) time_display = f'{total_test_time:.1f}s [{average_iteration_duration*1000:.1f}ms/it]' function_mem_display = f'function: {function_mem/2**20:.0f}MB' total_mem_display=f'total: {total_mem.used/2**20:.0f}MB ({total_mem.percent:.0f}%)' print(i, time_display, function_mem_display, total_mem_display, end = '\r') last_display_time=t2 last_display_iteration=i if i >= iterations: if verbose: print(f'\nReached maximum iteration number {iterations}') break # Check les critere d'arret if total_mem.percent >= max_mem_usage: if verbose: print(f'\nReached maximum memory usage ({max_mem_usage}%) after {i} iterations') break if max_time is not None and t2 - t0 >= max_time: if verbose: print(f'\nReached maximum duration {max_time} after {i} iterations') break # Preparation de la sortie return (process_mem - initial_process_mem), i
[ "psutil.virtual_memory", "time.time", "os.getpid" ]
[((660, 671), 'time.time', 'time.time', ([], {}), '()\n', (669, 671), False, 'import time\n'), ((628, 639), 'os.getpid', 'os.getpid', ([], {}), '()\n', (637, 639), False, 'import os\n'), ((1014, 1037), 'psutil.virtual_memory', 'psutil.virtual_memory', ([], {}), '()\n', (1035, 1037), False, 'import psutil\n'), ((1051, 1062), 'time.time', 'time.time', ([], {}), '()\n', (1060, 1062), False, 'import time\n')]
"""__main__ file invoked with `python -m tiatoolbox` command""" from tiatoolbox.cli import main main()
[ "tiatoolbox.cli.main" ]
[((98, 104), 'tiatoolbox.cli.main', 'main', ([], {}), '()\n', (102, 104), False, 'from tiatoolbox.cli import main\n')]
# Copyright 2020, Battelle Energy Alliance, LLC # ALL RIGHTS RESERVED import numpy as np import math import random from scipy.integrate import quad def timeDepLambda(t,a,b): return a+t*b def pdfFailure(t,a,b): first = timeDepLambda(t,a,b) second = math.exp(-quad(timeDepLambda, 0, t, args=(a,b))[0]) return first*second def run(self,Input): # lambda(t) = a + t*b # intput: a_V1, b_V1, T (max time) # output: t_V1, p_V1 self.p_V1 = np.zeros(Input['time'].size) for index,value in np.ndenumerate(Input['time']): #self.p_V1[index[0]] = quad(pdfFailure, 0, value, args=(Input['a_V1'],Input['b_V1']))[0] self.p_V1[index[0]] = 1. - math.exp(-quad(timeDepLambda, 0, value, args=(Input['a_V1'],Input['b_V1']))[0])
[ "scipy.integrate.quad", "numpy.zeros", "numpy.ndenumerate" ]
[((452, 480), 'numpy.zeros', 'np.zeros', (["Input['time'].size"], {}), "(Input['time'].size)\n", (460, 480), True, 'import numpy as np\n'), ((503, 532), 'numpy.ndenumerate', 'np.ndenumerate', (["Input['time']"], {}), "(Input['time'])\n", (517, 532), True, 'import numpy as np\n'), ((267, 305), 'scipy.integrate.quad', 'quad', (['timeDepLambda', '(0)', 't'], {'args': '(a, b)'}), '(timeDepLambda, 0, t, args=(a, b))\n', (271, 305), False, 'from scipy.integrate import quad\n'), ((668, 734), 'scipy.integrate.quad', 'quad', (['timeDepLambda', '(0)', 'value'], {'args': "(Input['a_V1'], Input['b_V1'])"}), "(timeDepLambda, 0, value, args=(Input['a_V1'], Input['b_V1']))\n", (672, 734), False, 'from scipy.integrate import quad\n')]
from collections import defaultdict from minpair import arpabet from minpair.corpus import require as corpus_require from nltk.corpus import brown from nltk.corpus import cmudict from nltk.corpus import words import re class Generator(object): """Class to generate minimal pairs. """ def __init__(self, download_corpus: bool = True, pos: list = []): """Init. Keyword Arguments: download_corpus {bool} -- Flag to download corpus data if missing (default: {True}) pos {list} -- Part-of-speech tags to filter words (default: {[]}) """ self.pos(pos) self.__download_corpus = download_corpus def pos(self, pos: list = []): """Set the part-of-speech tags to filter words. If pos is empty, default to ['ADJ', 'NOUN', 'VERB'] Keyword Arguments: pos {list} -- Part-of-speech tags to filter words (default: {[]}) Returns: Generator -- Self """ self.__pos = pos or ['ADJ', 'NOUN', 'VERB'] return self def _corpus_require(self, corpora: list = []): """Check corpus data requirements. If configured to download corpus and the corpus data is missing, download the respective corpus data. Keyword Arguments: corpora {list} -- The identifier or name of corpus (default: {[]}) """ if self.__download_corpus: corpus_require(corpora) def vowel_minpair(self, vowels: list): """Return list of :class:`MinimalSet <MinimalSet>`, that differ in only one vowel phonological element. For example, ['bad', 'bed', 'bid'] are one of the vowel minimal sets for ['AE', 'EH', 'IH'] vowels. Arguments: vowels {list} -- The vowel arpabets. For example, ['AE', 'EH']. Raises: Exception: If less than two unique vowel arpabets is given. Exception: If non-vowel arpabet is given. Returns: list -- The list of :class:`MinimalSet <MinimalSet>`. """ vowels = {arpabet.destress(vowel.upper()) for vowel in vowels} if len(vowels) < 2: raise Exception('At least a pair of unique vowels required.') if any(not arpabet.is_vowel(vowel) for vowel in vowels): raise Exception('Only vowels are accepted.') self._corpus_require(['brown', 'cmudict', 'universal_tagset', 'words']) possible_pairs = defaultdict(lambda: {}) vowels_regex = re.compile(r'^(?:%s)' % '|'.join(vowels)) tagged_words = {word for word, tag in brown.tagged_words(tagset='universal') if tag in self.__pos} english_words = set(words.words()).intersection(tagged_words) cmudict_entries = [(word, phones) for word, phones in cmudict.entries() if word in english_words if self.syllable_count(phones) == 1] for word, phones in cmudict_entries: matches = [vowels_regex.search(phone) for phone in phones] indices = [(i, match.group(0)) for i, match in enumerate(matches) if match != None] for index, matched_vowel in indices: key = tuple(phone if i != index else '.' for i, phone in enumerate(phones)) possible_pairs[key][matched_vowel] = word return [MinimalSet(matched_vowel) for (k, matched_vowel) in possible_pairs.items() if set(matched_vowel) == vowels] def syllable_count(self, phones: list): """Return the number of syllables for the given list of phones. For example, given phones for the word 'minimal': ['M', 'IH1', 'N', 'AH0', 'M', 'AH0', 'L'], should return 3 syllables. Arguments: phones {list} -- The given phones. For example, ['M', 'IH1', 'N', 'AH0', 'M', 'AH0', 'L']. Returns: int -- The number of syllables. """ return sum(arpabet.has_stress(phone) for phone in phones) class MinimalSet(dict): """Dictionary of words that differ in only one phonological element. Each key-value pair maps the differing phonological element to its associated word. A minimal pair is a minimal set with only 2 entries. """
[ "minpair.arpabet.is_vowel", "minpair.corpus.require", "minpair.arpabet.has_stress", "nltk.corpus.brown.tagged_words", "nltk.corpus.cmudict.entries", "collections.defaultdict", "nltk.corpus.words.words" ]
[((2496, 2520), 'collections.defaultdict', 'defaultdict', (['(lambda : {})'], {}), '(lambda : {})\n', (2507, 2520), False, 'from collections import defaultdict\n'), ((1455, 1478), 'minpair.corpus.require', 'corpus_require', (['corpora'], {}), '(corpora)\n', (1469, 1478), True, 'from minpair.corpus import require as corpus_require\n'), ((2655, 2693), 'nltk.corpus.brown.tagged_words', 'brown.tagged_words', ([], {'tagset': '"""universal"""'}), "(tagset='universal')\n", (2673, 2693), False, 'from nltk.corpus import brown\n'), ((2899, 2916), 'nltk.corpus.cmudict.entries', 'cmudict.entries', ([], {}), '()\n', (2914, 2916), False, 'from nltk.corpus import cmudict\n'), ((4138, 4163), 'minpair.arpabet.has_stress', 'arpabet.has_stress', (['phone'], {}), '(phone)\n', (4156, 4163), False, 'from minpair import arpabet\n'), ((2288, 2311), 'minpair.arpabet.is_vowel', 'arpabet.is_vowel', (['vowel'], {}), '(vowel)\n', (2304, 2311), False, 'from minpair import arpabet\n'), ((2768, 2781), 'nltk.corpus.words.words', 'words.words', ([], {}), '()\n', (2779, 2781), False, 'from nltk.corpus import words\n')]
import asyncio import glob import os import random import subprocess import sys import wave from collections import defaultdict from contextlib import suppress from datetime import datetime from functools import partial from itertools import count, islice from pathlib import Path from typing import DefaultDict, Dict, List, Optional, Tuple, Union from urllib.parse import urlparse import discord import gtts import youtube_dl from aiofile import AIOFile from async_timeout import timeout from discord.ext import commands from discord.opus import load_opus from pathvalidate import sanitize_filename from youtube_dl import YoutubeDL from ..config import (DOWNLOADS_DIR, FFMPEG_LOGLEVEL, SOUND_DIR, SOUND_SUB_DIRS, SOUNDLIST_FILE_LIMIT, TTS_DIR, YTDL_DIR) from ..utils.checks import admins_only, trusted from ..utils.converters import SoundURLConverter, URLConverter from ..utils.exceptions import (CommandError, InvalidVoiceChannel, VoiceConnectionError) from ..utils.filetypes import check_file_audio from ..utils.messaging import ask_user_yes_no from ..utils.parsing import split_text_numbers from ..utils.sound import convert, join_wavs from ..utils.spotify import get_spotify_song_info from ..utils.youtube import youtube_get_top_result from .base_cog import BaseCog ytdlopts = { "format": "bestaudio/best", "outtmpl": f"{YTDL_DIR}/%(title)s.%(ext)s", "noplaylist": True, "nocheckcertificate": True, "ignoreerrors": False, "logtostderr": True, "quiet": False, "no_warnings": False, "default_search": "auto", "source_address": "0.0.0.0" # ipv6 addresses cause issues sometimes } ffmpegopts = { "before_options": "-nostdin -reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5 -strict experimental", "options": f"-vn -loglevel {FFMPEG_LOGLEVEL}" } ytdl = YoutubeDL(ytdlopts) VALID_FILE_TYPES = [".mp3", ".mp4", ".webm", ".wav"] # this is probably useless FILETYPES = {".mp3", ".wav", ".m4a", ".webm", ".mp4"} def get_file_path(directory: str, filename: str) -> Path: """Resolves a filename and directory, returns a Path.""" try: path = list(Path(directory).glob(glob.escape(filename)+".*"))[0] except IndexError: raise ValueError("File does not exist!") return path class YTDLSource(discord.PCMVolumeTransformer): def __init__(self, source, *, data, requester): super().__init__(source) self.requester = requester self.title = data.get("title") self.web_url = data.get("webpage_url") def __getitem__(self, item: str): """Allows us to access attributes similar to a dict. This is only useful when you are NOT downloading. """ return self.__getattribute__(item) @classmethod async def create_source(cls, ctx: commands.Context, search: str, *, loop: asyncio.AbstractEventLoop, download=False): loop = loop or asyncio.get_event_loop() to_run = partial(ytdl.extract_info, url=search, download=download) data = await loop.run_in_executor(None, to_run) if "entries" in data: # take first item from a playlist data = data["entries"][0] await ctx.send(f"```\nAdded {data['title']} to the Queue.\n```", delete_after=10) if download: source = ytdl.prepare_filename(data) else: return {"webpage_url": data["webpage_url"], "requester": ctx.author, "title": data["title"]} return cls(discord.FFmpegPCMAudio(source), data=data, requester=ctx.author) @classmethod async def create_local_source(cls, ctx: commands.Context, subdir: str, filename: str): path = get_file_path(subdir, filename) # Send add-to-queue confirmation await ctx.send(f"```\nAdded {filename} to the Queue.\n```", delete_after=10) return cls(discord.FFmpegPCMAudio(str(path)), data={"title":filename}, requester=ctx.author) @classmethod async def regather_stream(cls, data, *, loop): """Used for preparing a stream, instead of downloading. Since Youtube Streaming links expire.""" loop = loop or asyncio.get_event_loop() requester = data["requester"] to_run = partial(ytdl.extract_info, url=data["webpage_url"], download=False) data = await loop.run_in_executor(None, to_run) return cls(discord.FFmpegPCMAudio(data["url"], **ffmpegopts), data=data, requester=requester) class AudioPlayer: def __init__(self, ctx): self.bot = ctx.bot self.guild = ctx.guild self.channel = ctx.channel if not ctx.cog or ctx.cog.qualified_name != "SoundCog": self.cog = self.bot.get_cog("SoundCog") else: self.cog = ctx.cog self.created_at = datetime.now() self.queue = asyncio.Queue() self.next = asyncio.Event() self.np = None self.volume = 1 self.current = None self.timeout_duration = 60.0 ctx.bot.loop.create_task(self.player_loop()) async def player_loop(self): await self.bot.wait_until_ready() while not self.bot.is_closed(): self.next.clear() try: async with timeout(self.timeout_duration): source = await self.queue.get() except asyncio.TimeoutError: if not self.guild.voice_client or self.queue.empty() and not self.guild.voice_client.is_playing(): return self.destroy(self.guild) else: continue if not isinstance(source, YTDLSource): try: source = await YTDLSource.regather_stream(source, loop=self.bot.loop) except: await self.channel.send("There was an error processing your song") continue # Exit loop if AudioPlayer is destroyed while playing audio if not self.guild.voice_client: break source.volume = self.volume self.current = source self.guild.voice_client.play(source, after=lambda _: self.bot.loop.call_soon_threadsafe(self.next.set)) self.np = await self.channel.send(f"```\nNow playing: {source.title}```") await self.next.wait() source.cleanup() self.current = None try: await self.np.delete() except discord.HTTPException: pass def destroy(self, guild): """Disconnect and cleanup the player.""" return self.bot.loop.create_task(self.cog.cleanup(guild)) class SoundDirectory: """ Represents a subdirectory of the base sound directory defined in `config.py`. """ def __init__(self, directory: str, header: str, aliases: list, path: str, color: Optional[Union[str, int]]=None) -> None: self.directory = directory self.header = header # This attribute is honestly pretty terrible self.aliases = aliases self.path = path self.color = color self.cached_at = 0.0 self._sound_list = {} @property def modified_at(self) -> float: return Path(self.path).stat().st_mtime @property def sound_list(self) -> list: if not self._sound_list or self.cached_at != self.modified_at: self.cached_at = self.modified_at self._sound_list = {file_.stem: self.path for file_ in Path(self.path).iterdir() if file_.suffix in VALID_FILE_TYPES} return self._sound_list class SoundCog(BaseCog): """Soundboard commands""" EMOJI = ":speaker:" DIRS = [d.path for d in SOUND_SUB_DIRS] YTDL_MAXSIZE = 10000000 # 10 MB def __init__(self, bot: commands.Bot) -> None: super().__init__(bot) if sys.platform == "linux": load_opus("libopus.so.0") # Create SoundDirectory instance for each subdirectory self.sub_dirs = [ SoundDirectory( directory=subdir.directory, header=subdir.directory.upper(), aliases=subdir.aliases, path=subdir.path, color=self.generate_hex_color_code(subdir.directory)) for subdir in SOUND_SUB_DIRS ] # Per-guild audio players. Key: Guild ID self.players: Dict[int, AudioPlayer] = {} # Number of sounds played by guilds in the current session self.played_count: DefaultDict[int, int] = defaultdict(int) # Key: Guild ID. Value: n times played @property def sound_list(self) -> dict: """ Dict of K: Sound file name, V: file directory NOTE ---- Raises Exception if no sound files are found. """ # This is a mess now sound_list = {} for sd in self.sub_dirs: sl = sd.sound_list for k in list(sl.keys()): if k in sound_list: new_name = self.get_unique_filename(k, ext_sound_list={**sound_list, **sl}) self._do_rename_file(sd.path, k, new_name) sound_list[new_name] = sl.pop(k) print(f"{sd.path}/{k} has been renamed to {sd.path}/{new_name}") sound_list.update(sl) if not sound_list: raise ValueError("No local sound files exist!") return sound_list def _sound_list_init(self) -> None: pass async def cleanup(self, guild: discord.Guild) -> None: try: await guild.voice_client.disconnect() except AttributeError: pass try: del self.players[guild.id] except KeyError: pass def get_player(self, ctx: commands.Context) -> AudioPlayer: """Retrieve the guild player, or generate one.""" try: player = self.players[ctx.guild.id] except KeyError: player = AudioPlayer(ctx) self.players[ctx.guild.id] = player return player @commands.command(name="players") @admins_only() async def show_players(self, ctx: commands.Context) -> None: """Show active Audio Players.""" players = "\n".join( [f"{str(self.bot.get_guild(gid))}" for gid in self.players] ) if players: await ctx.send(players) else: await ctx.send("No active audio players.") @commands.command(name="played") @admins_only() async def times_played_session(self, ctx: commands.Context) -> None: """ Display sound played count for current guild. """ out = "\n".join([f"{self.bot.get_guild(k)}: {v}" for k, v in self.played_count.items()]) await self.send_text_message(out, ctx) @commands.command(name="connect", aliases=["join"]) async def connect(self, ctx, *, channel: discord.VoiceChannel=None): """Connect to voice. Parameters ------------ channel: discord.VoiceChannel [Optional] The channel to connect to. If a channel is not specified, an attempt to join the voice channel you are in will be made. This command also handles moving the bot to different channels. """ if not channel: try: channel = ctx.author.voice.channel except AttributeError: raise InvalidVoiceChannel("No channel to join. Please either specify a valid channel or join one.") vc = ctx.voice_client # If bot is restarted while connected to a voice channel, # it can sometimes get "stuck" in a channel in a state where # any attempts to play sound is unsuccessful if not vc and any(self.bot.user.id == user.id for user in channel.members): #if not vc and self.bot.user.id in [user.id for user in channel.members]: await channel.connect() # Try to connect await ctx.invoke(self.stop) # Immediately issue !stop command, removing bot user from channel if vc: if vc.channel.id == channel.id: return try: await vc.move_to(channel) except asyncio.TimeoutError: raise VoiceConnectionError(f"Moving to channel: <{channel}> timed out.") else: try: await channel.connect() except asyncio.TimeoutError: raise VoiceConnectionError(f"Connecting to channel: <{channel}> timed out.") # Keep ffmpeg hot (seems to fix delayed sound output on initial sound file) subprocess.call("ffmpeg", stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) async def play_local_source(self, ctx: commands.Context, player: AudioPlayer, sound_name: str) -> None: """Creates audio source from local file and adds it to player queue.""" try: if sound_name: subdir = self.sound_list[sound_name] else: # Select random sound if no argument sound_name = random.choice(list(self.sound_list)) subdir = self.sound_list[sound_name] # Attempt to suggest sound files with similar names if no results except KeyError: embeds = await self._do_search(sound_name, ctx) if embeds and len(embeds) <= len(self.sub_dirs): dym = "Did you mean:" else: dym = "" await ctx.send(f"No sound with name **`{sound_name}`**. {dym}") if dym: for embed in embeds: await ctx.send(embed=embed) return else: source = await YTDLSource.create_local_source(ctx, subdir, sound_name) await player.queue.put(source) async def play_ytdl_source(self, ctx: commands.Context, player: AudioPlayer, url: str) -> None: """Creates audio source from online source and adds it to player queue.""" # Check if downloading is allowed if ctx.invoked_with == "ytdl": await self.check_downloads_permissions(add_msg= "Use **`!play`** or **`!yt`** instead.") download = True else: download = False source = await YTDLSource.create_source(ctx, url, loop=self.bot.loop, download=download) await player.queue.put(source) async def _play(self, ctx: commands.Context, arg: str, voice_channel: commands.VoiceChannelConverter=None) -> None: """Play sound in message author's voice channel Parameters ---------- ctx : commands.Context Command invocation context arg : `str` Name of local sound file or HTTP(S) URL voice_channel : `commands.VoiceChannelConverter`, optional Specific voice channel to play sound in, by default uses `ctx.message.author.voice.channel` """ vc = ctx.voice_client if not vc: await ctx.invoke(self.connect, channel=voice_channel) player = self.get_player(ctx) # Play audio from online source if urlparse(arg).scheme in ["http", "https"]: await self.play_ytdl_source(ctx, player, arg) else: await self.play_local_source(ctx, player, arg) # Increment played count for guild self.played_count[ctx.guild.id] += 1 @commands.command(name="play", usage="<filename>") async def play(self, ctx: commands.Context, *args): """Play local sound files. Use `!search` to list available sounds.""" arg = " ".join(args) await self._play(ctx, arg) @commands.command(name="yt", aliases=["ytdl", "spotify"], usage="<url>, <search query> or <Spotify URI>") async def yt(self, ctx: commands.Context, *args): """Play YouTube or Spotify content.""" arg = " ".join(args) if "spotify" in arg: await ctx.send("Attempting to find song on YouTube...", delete_after=5.0) artist, song, album = await self.bot.loop.run_in_executor(None, get_spotify_song_info, arg) arg = await self.bot.loop.run_in_executor(None, youtube_get_top_result, f"{artist} {song}") elif urlparse(arg).scheme not in ["http", "https"]: await ctx.send(f"Searching YouTube for `{arg}`...", delete_after=5.0) arg = await self.bot.loop.run_in_executor(None, youtube_get_top_result, arg) await self._play(ctx, arg) @commands.command(name="rplay", usage="<channel_id>") async def remoteplay(self, ctx: commands.Context, channel: commands.VoiceChannelConverter, *args) -> None: """`!play` in a specific channel.""" await ctx.invoke(self.play, *args, voice_channel=channel) @commands.command(name="stop", aliases=["s"]) async def stop(self, ctx: commands.Context) -> None: player = self.get_player(ctx) vc = ctx.voice_client if vc and vc.is_connected() and not player.queue.empty(): await ctx.invoke(self.skip) else: await self.cleanup(ctx.guild) @commands.command(name="skip") async def skip(self, ctx): """Skip the song.""" vc = ctx.voice_client if not vc or not vc.is_connected(): return await ctx.send("I am not currently playing anything!", delete_after=5) if vc.is_paused(): pass elif not vc.is_playing(): return vc.stop() await ctx.send(f"**`{ctx.author}`**: Skipped the song!") @commands.command(name="volume", aliases=["vol"]) @admins_only() async def change_volume(self, ctx, *, vol: int): """Set player volume (1-100)""" vc = ctx.voice_client if not vc or not vc.is_connected(): return await ctx.send("I am not currently connected to voice!", delete_after=5) if not 0 < vol < 101: return await ctx.send("Please enter a value between 1 and 100.") player = self.get_player(ctx) if vc.source: vc.source.volume = vol / 100 player.volume = vol / 100 await ctx.send(f"**`{ctx.author}`**: Set the volume to **{vol}%**") @commands.command(name="now_playing", aliases=["np"]) async def now_playing(self, ctx) -> None: vc = ctx.voice_client if not vc or not vc.is_connected(): return await ctx.send("I am not currently connected to voice!", delete_after=5) player = self.get_player(ctx) if not player.current: return await ctx.send("I am not currently playing anything!") try: await player.np.delete() except discord.HTTPException: pass player.np = await ctx.send(f"**Now Playing:** `{vc.source.title}` " f"requested by `{vc.source.requester}`") @commands.command(name="destroy", aliases=["quit"]) @admins_only() async def destroy_player(self, ctx) -> None: vc = ctx.voice_client if not vc or not vc.is_connected(): return await ctx.send("I am not currently playing anything!", delete_after=20) await self.cleanup(ctx.guild) @commands.command(name="soundlist", aliases=["sounds"], description="Prints a list of all sounds on the soundboard.") @commands.cooldown(rate=1, per=10, type=commands.BucketType.user) async def soundlist(self, ctx: commands.Context, category: Optional[str]=None) -> None: """List soundboard files. Parameters ---------- ctx : commands.Context Discord Context category : `str`, optional Sound category. See SoundCog.sub_dirs for available categories. Raises ------ discord.DiscordException Raised if attempting to display all sound files at once. """ # Formatted string of sound categories categories = "\n".join( [f"**`{sd.directory}`**" for sd in self.sub_dirs if sd.sound_list] ) # Raise exception if all sound directories are empty if not categories: raise CommandError("Soundboard has no sound files!") # Prompt user to specify category if message lacks category argument if not category: await self.send_embed_message(ctx, title="Categories", description=categories) await ctx.send(f"\nType **`!{ctx.invoked_with}`** + **`<category>`**") self.reset_command_cooldown(ctx) return # Directory names are all lowercase category = category.lower() # Find subdirectory matching `category` argument for sub_dir in self.sub_dirs: if category in sub_dir.aliases: break # Raise exception if no sound directory matches category else: raise CommandError(f"No such category **`{category}`**.\n" f"Categories: {categories}") # Compile list of sounds _out = [sound for sound in sub_dir.sound_list] # Send large directory sound lists as DM if len(_out) > SOUNDLIST_FILE_LIMIT: msg = ( f"The **`{category}`** category contains {len(_out)} sound files. " f"It is recommended to try using the **`{self.bot.command_prefix}search`** command first.\n" f"Are you sure you want to show all sounds in this category?" ) if not await ask_user_yes_no(ctx, msg): return await ctx.send("Aborting.") await ctx.send("Soundlist will be sent as DM.") channel = await ctx.message.author.create_dm() else: channel = None out = "\n".join(_out) if not out: return await ctx.send( f"Category **`{category}`** is empty!" ) return await self.send_embed_message( ctx, sub_dir.header, out, color=sub_dir.color, channel=channel) @commands.command(name="search", usage="<query>") async def search(self, ctx: commands.Context, *query: str, rtn: bool=False) -> Optional[List[discord.Embed]]: """Search for Soundboard files.""" # Join args into space-separated search query string query = " ".join(query) if not query or query.isspace(): raise CommandError("Search query cannot be an empty string.") embeds = await self._do_search(query, ctx) # Require searches to be specific in order to avoid spamming a channel if len(embeds) > len(self.sub_dirs): n_results = sum([len(e.description.splitlines()) for e in embeds]) raise CommandError(f"Search returned {n_results} results. A more specific search query is required.") # Post search results to ctx.channel if embeds: for embed in embeds: await ctx.send(embed=embed) else: await ctx.send("No results") async def _do_search(self, query: str, ctx: commands.Context=None) -> List[discord.Embed]: """Performs Soundboard file search. Returns list of Discord Embeds""" if not ctx: ctx = await self.get_command_invocation_ctx() embeds = [] for sf in self.sub_dirs: _out = [sound for sound in sf.sound_list if query.lower() in sound.lower()] if _out: _out_str = "\n".join(_out) _rtn_embeds = await self.send_embed_message(ctx, sf.header, _out_str, color=sf.color, return_embeds=True) embeds.extend(_rtn_embeds) return embeds @commands.group(name="queue", usage="[subcommand]") async def queue(self, ctx: commands.Context) -> None: """Display soundboard queue.""" vc = ctx.voice_client if not vc or not vc.is_connected(): return await ctx.send("I am not currently connected to a voice channel!", delete_after=5) player = self.get_player(ctx) if player.queue.empty(): return await ctx.send("Queue is empty!") # Invoke subcommands if ctx.invoked_subcommand: return upcoming = list(islice(player.queue._queue, 0, 5)) out_msg = "\n".join(f"{idx}. **`{up['title']}`**" for idx, up in enumerate(upcoming, 1)) await self.send_embed_message(ctx, "Queue", out_msg, color="red") @queue.command(name="clear") async def clear_queue(self, ctx: commands.Context) -> None: """Clear soundboard queue.""" player = self.get_player(ctx) if not player: return n = player.queue.qsize() player.destroy(ctx.guild) # Grammar if n == 1: s = "" werewas = "was" else: s = "s" werewas = "were" await ctx.send(f"Cleared queue! {n} sound{s} {werewas} cleared.") @commands.command(name="tts", aliases=["texttospeech", "text-to-speech"]) async def texttospeech(self, ctx: commands.Context, text: str, language: str="en", filename: Optional[str]=None) -> None: """Create text-to-speech sound files. """ # gTTS exception handling. # The language list has a tendency to break, which requires gTTS to be updated try: valid_langs = gtts.lang.tts_langs() except: await self.send_log(f"**URGENT**: Update gTTS. {self.AUTHOR_MENTION}") raise CommandError("Text-to-speech module is unavailable. Try again later.") # User error and help arguments if not text: return await self.send_error_msg(ctx, "Text for TTS is a required argument.") elif text in ["languages", "lang", "options"]: _langs = [ f"`{lang_short}`{self.EMBED_FILL_CHAR*(8-len(lang_short))}" f"{lang_long}" for lang_short, lang_long in valid_langs.items() ] langs = "\n".join(_langs) return await self.send_embed_message(ctx, "Code\tLanguage", langs) await ctx.trigger_typing() # Use first word of text if no filename if not filename: filename = text.split(" ")[0] filename = await self._do_create_tts_file(text, language, filename) await ctx.send(f"TTS audio file created: **`{filename}`**") # Try to play created sound file in author"s voice channel afterwards #with suppress(AttributeError): if ctx.message.author.voice: cmd = self.bot.get_command("play") await ctx.invoke(cmd, filename) async def _do_create_tts_file(self, text: str, language: str, filename: str, *, directory: str=TTS_DIR, overwrite: bool=False) -> None: # Get tts object tts = gtts.gTTS(text=text, lang=language) filename = sanitize_filename(filename) if not overwrite: # Check filename uniqueness filename = self.get_unique_filename(filename) # Save mp3 file to_run = partial(tts.save, f"{directory}/{filename}.mp3") await self.bot.loop.run_in_executor(None, to_run) return filename @commands.command(name="add_sound", usage="<url> or <file attachment>") async def add_sound(self, ctx: commands.Context, url: str=None, filename: str=None) -> None: """Download sound file to soundboard. Sound file URL is passed in as argument `url` or as a message attachment. Parameters ---------- ctx : `commands.Context` Discord Context object url : `str` HTTP(s) URL of file. """ # Check if downloading is allowed await self.check_downloads_permissions() # Raise exception if message has no attachment and no URL was passed in if not ctx.message.attachments and not url: return await self.send_error_msg(ctx, "A file attachment or file URL is required!") # Use attachment URL if message has attachment if ctx.message.attachments: attachment = ctx.message.attachments[0] filename, url = url, attachment.url # Download and save sound file try: filename = await self._do_download_sound(ctx, url, filename=filename) except AttributeError: raise CommandError( "Invalid URL. Must be a direct link to a file. " "Example: http://example.com/file.mp3" ) except ValueError: raise CommandError( f"Invalid file type. Must be one of: **{FILETYPES}**" ) else: await ctx.send(f"Saved file **`{filename}`**") # Play downloaded sound if command invoker is in a voice channel if ctx.author.voice: await ctx.invoke(self.play, filename) async def _do_download_sound(self, ctx: commands.Context, url: str, *, filename: str=None) -> str: """Attempts to download sound file from URL. Fails if file already exists or file is not a recognized filetype. Parameters ---------- ctx : `commands.Context` Discord context url : `str` HTTP(s) URL of target file """ # Get filename and extension fname, ext = await self.get_filename_extension_from_url(url) if not filename: filename = fname filename = sanitize_filename(filename) # Check if file extension is recognized if ext not in FILETYPES: raise CommandError("Downloaded file is of an invalid filetype.") # Attempt to download file sound_file = await self.download_from_url(ctx, url) # Check if downloaded file is actually an audio file if not check_file_audio(sound_file) and ext != ".mp3": # mp3 files can't always be identified by MIME type raise CommandError("Downloaded file does not appear to be an audio file!") filename = self.get_unique_filename(filename) filepath = f"{DOWNLOADS_DIR}/{filename}{ext}" async with AIOFile(filepath, "wb") as f: await f.write(sound_file.getvalue()) await self.log_file_download(ctx, url=url, filename=f"{filename}{ext}") return filename def get_unique_filename(self, filename: str, *, ext_sound_list: dict=None) -> str: # Increment i until a unique filename is found sl = ext_sound_list if ext_sound_list else self.sound_list # Check if filename has a trailing number that can be incremented head, tail = split_text_numbers(filename) if tail.isnumeric(): filename = head start = int(tail) else: start = 0 for i in count(start=start): # we don't need a number if first attempted filename is unique i = "" if i==0 else i fname = f"{filename}{i}" if fname not in sl: return fname @commands.command(name="rename") @admins_only() async def rename_sound(self, ctx: commands.Context, original: str, new: str) -> None: """Renames a soundboard file.""" directory = self.sound_list.get(original) if new in self.sound_list: # NOTE: ask user to overwrite? raise CommandError(f"**`{new}`** already exists!") elif original == new: raise CommandError("New filename cannot be identical to the original filename.") elif not directory: raise CommandError(f"Cannot find **`{original}`**!") self._do_rename_file(directory, original, new) await ctx.send(f"Successfully renamed **`{original}`** to **`{new}`**") def _do_rename_file(self, directory: str, filename: str, new: str) -> None: path = get_file_path(directory, filename) # Remove invalid characters new = sanitize_filename(new) try: path.rename(f"{path.parent}/{new}{path.suffix}") except: raise CommandError("Unable to rename file!") @commands.command(name="dl") async def dl(self, ctx: commands.Context, url: URLConverter=None) -> None: """Lazy download sound command. Depending on arguments received, calls either `!ytdl` or `!add_sound` Parameters ---------- ctx : `commands.Context` Discord Context object url : `str`, optional Optional HTTP(s) URL to sound file. Can not be None if message has no attachment. """ if ctx.message.attachments or url and any( url.path.lower().endswith(filetype) for filetype in VALID_FILE_TYPES): cmd = self.bot.get_command("add_sound") await ctx.invoke(cmd, url) elif url: cmd = self.bot.get_command("ytdl") await ctx.invoke(cmd, url) else: raise CommandError("A URL or attached file is required!") @commands.command(name="combine") @admins_only() async def join_sound_files(self, ctx: commands.Context, file_1: str, file_2: str) -> None: """Combine two sound files. Parameters ---------- ctx : commands.Context Discord context file_1 : str Filename of first sound (DON'T INCLUDE EXTENSION) file_2 : str Filename of second sound Raises ------ AttributeError Raised if args to either file_1 or file_2 does not match a sound currently added to the soundboard. FileNotFoundError Raised if a converted .wav file cannot be found FileExistsError Raised if attempting to combine two files that have already been combined previously. """ # NOTE: ugly files: List[Path] = [] for f in [file_1, file_2]: for p in Path(f"{SOUND_DIR}").glob(f"*/*{f}*"): if p.stem == f: # NOTE: necessary? files.append(p) break else: raise FileNotFoundError(f"Unable to find soundfile '{f}'") # Make sure all files are .wav. Convert to .wav if necessary tempfiles = [] # Files that are temporarily converted to .wav for fp in list(files): # NOTE: use enumerate() instead? if fp.suffix == ".mp3": wavname = await self.bot.loop.run_in_executor(None, convert, fp, True) files[files.index(fp)] = wavname tempfiles.append(wavname) # Combine .wavs try: joined = join_wavs(*files) except (FileNotFoundError, FileExistsError) as e: raise CommandError(e) except Exception: await ctx.send("ERROR: Something went wrong when attempting to join files.") raise finally: # Delete temporary files (if any) for tf in tempfiles: os.remove(tf) # Convert joined file to mp3 (why?) await self.bot.loop.run_in_executor(None, convert, joined, False) await ctx.send(f"Combined **{file_1}** & **{file_2}**! New sound: **{joined.stem}**") # Delete wav version of joined file if Path(joined).exists(): os.remove(joined)
[ "discord.FFmpegPCMAudio", "youtube_dl.YoutubeDL", "discord.ext.commands.group", "pathvalidate.sanitize_filename", "discord.ext.commands.cooldown", "discord.ext.commands.command", "os.remove", "pathlib.Path", "asyncio.Queue", "subprocess.call", "discord.opus.load_opus", "asyncio.get_event_loop"...
[((1927, 1946), 'youtube_dl.YoutubeDL', 'YoutubeDL', (['ytdlopts'], {}), '(ytdlopts)\n', (1936, 1946), False, 'from youtube_dl import YoutubeDL\n'), ((10776, 10808), 'discord.ext.commands.command', 'commands.command', ([], {'name': '"""players"""'}), "(name='players')\n", (10792, 10808), False, 'from discord.ext import commands\n'), ((11188, 11219), 'discord.ext.commands.command', 'commands.command', ([], {'name': '"""played"""'}), "(name='played')\n", (11204, 11219), False, 'from discord.ext import commands\n'), ((11549, 11599), 'discord.ext.commands.command', 'commands.command', ([], {'name': '"""connect"""', 'aliases': "['join']"}), "(name='connect', aliases=['join'])\n", (11565, 11599), False, 'from discord.ext import commands\n'), ((16360, 16409), 'discord.ext.commands.command', 'commands.command', ([], {'name': '"""play"""', 'usage': '"""<filename>"""'}), "(name='play', usage='<filename>')\n", (16376, 16409), False, 'from discord.ext import commands\n'), ((16629, 16738), 'discord.ext.commands.command', 'commands.command', ([], {'name': '"""yt"""', 'aliases': "['ytdl', 'spotify']", 'usage': '"""<url>, <search query> or <Spotify URI>"""'}), "(name='yt', aliases=['ytdl', 'spotify'], usage=\n '<url>, <search query> or <Spotify URI>')\n", (16645, 16738), False, 'from discord.ext import commands\n'), ((17494, 17546), 'discord.ext.commands.command', 'commands.command', ([], {'name': '"""rplay"""', 'usage': '"""<channel_id>"""'}), "(name='rplay', usage='<channel_id>')\n", (17510, 17546), False, 'from discord.ext import commands\n'), ((17780, 17824), 'discord.ext.commands.command', 'commands.command', ([], {'name': '"""stop"""', 'aliases': "['s']"}), "(name='stop', aliases=['s'])\n", (17796, 17824), False, 'from discord.ext import commands\n'), ((18129, 18158), 'discord.ext.commands.command', 'commands.command', ([], {'name': '"""skip"""'}), "(name='skip')\n", (18145, 18158), False, 'from discord.ext import commands\n'), ((18588, 18636), 'discord.ext.commands.command', 'commands.command', ([], {'name': '"""volume"""', 'aliases': "['vol']"}), "(name='volume', aliases=['vol'])\n", (18604, 18636), False, 'from discord.ext import commands\n'), ((19264, 19316), 'discord.ext.commands.command', 'commands.command', ([], {'name': '"""now_playing"""', 'aliases': "['np']"}), "(name='now_playing', aliases=['np'])\n", (19280, 19316), False, 'from discord.ext import commands\n'), ((19958, 20008), 'discord.ext.commands.command', 'commands.command', ([], {'name': '"""destroy"""', 'aliases': "['quit']"}), "(name='destroy', aliases=['quit'])\n", (19974, 20008), False, 'from discord.ext import commands\n'), ((20298, 20419), 'discord.ext.commands.command', 'commands.command', ([], {'name': '"""soundlist"""', 'aliases': "['sounds']", 'description': '"""Prints a list of all sounds on the soundboard."""'}), "(name='soundlist', aliases=['sounds'], description=\n 'Prints a list of all sounds on the soundboard.')\n", (20314, 20419), False, 'from discord.ext import commands\n'), ((20444, 20508), 'discord.ext.commands.cooldown', 'commands.cooldown', ([], {'rate': '(1)', 'per': '(10)', 'type': 'commands.BucketType.user'}), '(rate=1, per=10, type=commands.BucketType.user)\n', (20461, 20508), False, 'from discord.ext import commands\n'), ((23378, 23426), 'discord.ext.commands.command', 'commands.command', ([], {'name': '"""search"""', 'usage': '"""<query>"""'}), "(name='search', usage='<query>')\n", (23394, 23426), False, 'from discord.ext import commands\n'), ((25166, 25216), 'discord.ext.commands.group', 'commands.group', ([], {'name': '"""queue"""', 'usage': '"""[subcommand]"""'}), "(name='queue', usage='[subcommand]')\n", (25180, 25216), False, 'from discord.ext import commands\n'), ((26523, 26595), 'discord.ext.commands.command', 'commands.command', ([], {'name': '"""tts"""', 'aliases': "['texttospeech', 'text-to-speech']"}), "(name='tts', aliases=['texttospeech', 'text-to-speech'])\n", (26539, 26595), False, 'from discord.ext import commands\n'), ((28923, 28993), 'discord.ext.commands.command', 'commands.command', ([], {'name': '"""add_sound"""', 'usage': '"""<url> or <file attachment>"""'}), "(name='add_sound', usage='<url> or <file attachment>')\n", (28939, 28993), False, 'from discord.ext import commands\n'), ((33061, 33092), 'discord.ext.commands.command', 'commands.command', ([], {'name': '"""rename"""'}), "(name='rename')\n", (33077, 33092), False, 'from discord.ext import commands\n'), ((34220, 34247), 'discord.ext.commands.command', 'commands.command', ([], {'name': '"""dl"""'}), "(name='dl')\n", (34236, 34247), False, 'from discord.ext import commands\n'), ((35210, 35242), 'discord.ext.commands.command', 'commands.command', ([], {'name': '"""combine"""'}), "(name='combine')\n", (35226, 35242), False, 'from discord.ext import commands\n'), ((3086, 3143), 'functools.partial', 'partial', (['ytdl.extract_info'], {'url': 'search', 'download': 'download'}), '(ytdl.extract_info, url=search, download=download)\n', (3093, 3143), False, 'from functools import partial\n'), ((4394, 4461), 'functools.partial', 'partial', (['ytdl.extract_info'], {'url': "data['webpage_url']", 'download': '(False)'}), "(ytdl.extract_info, url=data['webpage_url'], download=False)\n", (4401, 4461), False, 'from functools import partial\n'), ((4986, 5000), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (4998, 5000), False, 'from datetime import datetime\n'), ((5025, 5040), 'asyncio.Queue', 'asyncio.Queue', ([], {}), '()\n', (5038, 5040), False, 'import asyncio\n'), ((5062, 5077), 'asyncio.Event', 'asyncio.Event', ([], {}), '()\n', (5075, 5077), False, 'import asyncio\n'), ((9173, 9189), 'collections.defaultdict', 'defaultdict', (['int'], {}), '(int)\n', (9184, 9189), False, 'from collections import defaultdict\n'), ((13430, 13509), 'subprocess.call', 'subprocess.call', (['"""ffmpeg"""'], {'stdout': 'subprocess.DEVNULL', 'stderr': 'subprocess.DEVNULL'}), "('ffmpeg', stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n", (13445, 13509), False, 'import subprocess\n'), ((28490, 28525), 'gtts.gTTS', 'gtts.gTTS', ([], {'text': 'text', 'lang': 'language'}), '(text=text, lang=language)\n', (28499, 28525), False, 'import gtts\n'), ((28556, 28583), 'pathvalidate.sanitize_filename', 'sanitize_filename', (['filename'], {}), '(filename)\n', (28573, 28583), False, 'from pathvalidate import sanitize_filename\n'), ((28768, 28816), 'functools.partial', 'partial', (['tts.save', 'f"""{directory}/{filename}.mp3"""'], {}), "(tts.save, f'{directory}/{filename}.mp3')\n", (28775, 28816), False, 'from functools import partial\n'), ((31374, 31401), 'pathvalidate.sanitize_filename', 'sanitize_filename', (['filename'], {}), '(filename)\n', (31391, 31401), False, 'from pathvalidate import sanitize_filename\n'), ((32821, 32839), 'itertools.count', 'count', ([], {'start': 'start'}), '(start=start)\n', (32826, 32839), False, 'from itertools import count, islice\n'), ((34016, 34038), 'pathvalidate.sanitize_filename', 'sanitize_filename', (['new'], {}), '(new)\n', (34033, 34038), False, 'from pathvalidate import sanitize_filename\n'), ((3041, 3065), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (3063, 3065), False, 'import asyncio\n'), ((3638, 3668), 'discord.FFmpegPCMAudio', 'discord.FFmpegPCMAudio', (['source'], {}), '(source)\n', (3660, 3668), False, 'import discord\n'), ((4310, 4334), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (4332, 4334), False, 'import asyncio\n'), ((4549, 4598), 'discord.FFmpegPCMAudio', 'discord.FFmpegPCMAudio', (["data['url']"], {}), "(data['url'], **ffmpegopts)\n", (4571, 4598), False, 'import discord\n'), ((8401, 8426), 'discord.opus.load_opus', 'load_opus', (['"""libopus.so.0"""'], {}), "('libopus.so.0')\n", (8410, 8426), False, 'from discord.opus import load_opus\n'), ((25750, 25783), 'itertools.islice', 'islice', (['player.queue._queue', '(0)', '(5)'], {}), '(player.queue._queue, 0, 5)\n', (25756, 25783), False, 'from itertools import count, islice\n'), ((26973, 26994), 'gtts.lang.tts_langs', 'gtts.lang.tts_langs', ([], {}), '()\n', (26992, 26994), False, 'import gtts\n'), ((32103, 32126), 'aiofile.AIOFile', 'AIOFile', (['filepath', '"""wb"""'], {}), "(filepath, 'wb')\n", (32110, 32126), False, 'from aiofile import AIOFile\n'), ((37637, 37654), 'os.remove', 'os.remove', (['joined'], {}), '(joined)\n', (37646, 37654), False, 'import os\n'), ((16071, 16084), 'urllib.parse.urlparse', 'urlparse', (['arg'], {}), '(arg)\n', (16079, 16084), False, 'from urllib.parse import urlparse\n'), ((37311, 37324), 'os.remove', 'os.remove', (['tf'], {}), '(tf)\n', (37320, 37324), False, 'import os\n'), ((37601, 37613), 'pathlib.Path', 'Path', (['joined'], {}), '(joined)\n', (37605, 37613), False, 'from pathlib import Path\n'), ((5455, 5485), 'async_timeout.timeout', 'timeout', (['self.timeout_duration'], {}), '(self.timeout_duration)\n', (5462, 5485), False, 'from async_timeout import timeout\n'), ((7630, 7645), 'pathlib.Path', 'Path', (['self.path'], {}), '(self.path)\n', (7634, 7645), False, 'from pathlib import Path\n'), ((17228, 17241), 'urllib.parse.urlparse', 'urlparse', (['arg'], {}), '(arg)\n', (17236, 17241), False, 'from urllib.parse import urlparse\n'), ((36207, 36227), 'pathlib.Path', 'Path', (['f"""{SOUND_DIR}"""'], {}), "(f'{SOUND_DIR}')\n", (36211, 36227), False, 'from pathlib import Path\n'), ((2241, 2256), 'pathlib.Path', 'Path', (['directory'], {}), '(directory)\n', (2245, 2256), False, 'from pathlib import Path\n'), ((2262, 2283), 'glob.escape', 'glob.escape', (['filename'], {}), '(filename)\n', (2273, 2283), False, 'import glob\n'), ((7952, 7967), 'pathlib.Path', 'Path', (['self.path'], {}), '(self.path)\n', (7956, 7967), False, 'from pathlib import Path\n')]
# -*- encoding: utf-8 -*- """ _core/queries_db/query_stats.py """ import re import random import pandas as pd import numpy as np from pandas.io.json import json_normalize from log_config import log, pformat log.debug("... _core.queries_db.query_stats.py ..." ) from bson.objectid import ObjectId from flask_restplus import marshal from . import db_dict_by_type, Marshaller from solidata_api._choices._choices_docs import doc_type_dict import operator from .query_utils import * ### + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ### ### GLOBAL FUNCTION TO QUERY ONE DOC FROM DB ### + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ### ### cf : response codes : https://restfulapi.net/http-status-codes/ def Query_db_stats ( ns, document_type, claims, query_args, doc_id = None, is_one_stat = False, roles_for_complete = ["admin"], payload = {} ): ### DEBUGGING print() print("-+- "*40) log.debug( "... Query_db_stats / document_type : %s", document_type ) # log.debug( "... Query_db_stats / db_dict_by_type : \n%s", pformat(db_dict_by_type) ) # log.debug( "... Query_db_stats / doc_type_dict : \n%s", pformat(doc_type_dict) ) ### prepare marshaller # marshaller = Marshaller(ns, models) ### default values # not_filtered = True db_collection = db_dict_by_type[document_type] document_type_full = doc_type_dict[document_type] user_id = user_oid = None user_role = "anonymous" document_out = None message = "testing stats endpoint for the whole app" dft_open_level_show = ["open_data"] response_code = 200 can_access_complete = True if claims or claims!={} : user_role = claims["auth"]["role"] user_id = claims["_id"] ### get the oid as str if user_role and user_role != "anonymous" : user_oid = ObjectId(user_id) log.debug("user_oid : %s", user_oid ) dft_open_level_show += ["commons"] ### sum up all query arguments query_resume = { "document_type" : document_type, "doc_id" : doc_id, "user_id" : user_id, "user_role" : user_role, "query_args" : query_args, "payload" : payload, "is_member_of_team" : False, "is_creator" : False, } ### get query arguments log.debug('query_args : \n%s', pformat(query_args) ) # stats_type_ds = ['dso', 'dsi'] # stats_type_ds_doc = ['dso_doc', 'dsi_doc'] # stats_type_coll = ['usr', 'dmt', 'dmf', 'prj', 'tag'] ### get query arguments search_for = query_args.get('search_for', None ) # search_in = query_args.get('search_in', None ) search_filters = query_args.get('search_filters', None ) as_series = query_args.get('as_series', False ) descending = query_args.get('descending', False ) ### prepare sorting order if descending : sort_order = -1 else : sort_order = 1 ### get payload log.debug('payload : \n%s', pformat(payload) ) is_payload = False if payload and payload != {} and len(payload) > 0 : is_payload = True ### starting dict for matching parrt of aggregation q_match = { "$match" : {} } ### build basic info for db query if is_one_stat and doc_id and ObjectId.is_valid(doc_id) : doc_oid = ObjectId(doc_id) document = db_collection.find_one( {"_id": doc_oid }) db_collection = db_dict_by_type[ document_type + "_doc" ] match_field = "oid_" + document_type q_match["$match"][match_field] = ObjectId(doc_id) elif is_one_stat == False : document = db_collection.find({}) else : response_code = 400 document = None ### start if document and is_payload : ### check doc's specs : public_auth, team... doc_open_level_show = document["public_auth"]["open_level_show"] log.debug( "doc_open_level_show : %s", doc_open_level_show ) ### get doc's owner infos created_by_oid = document["log"]["created_by"] log.debug( "created_by_oid : %s", str(created_by_oid) ) ### get doc's team infos if "team" in document : team_oids = [ t["oid_usr"] for t in document["team"] ] log.debug( "team_oids : \n%s", pformat(team_oids) ) ### AGGREGATION ### ### - - - - - - ### ### build query pipelines for stats # $ aggregation q_aggregate = [] # $ matching log.debug( "q_match : \n%s", pformat(q_match) ) # if search_for != None and search_for != [] and search_for != [''] and search_for != '' : # search_words = [ "\""+word+"\"" for word in search_for ] ### "\"<word>\"" means AND operrator on text search # q_match["$match"]["$text"] = { # "$search" : u" ".join(search_words) # } q_match["$match"] = append_search_for_to_query( q_match["$match"], search_for) q_match["$match"] = append_filters_to_query( q_match["$match"], search_filters) log.debug( "q_match : \n%s", pformat(q_match) ) q_aggregate.append(q_match) # $ grouping x payload # payload_sorted = sorted(payload, key=lambda i:i["agg_level_group"]) q_complex_stat = len(payload) > 1 q_sorting = [] # $ unwind - loop payload looking for unwindders q_unwindders = [] for p in payload : field = p["agg_field"] needs_unwind = p["agg_needs_unwind"] unwind_separator = p["agg_unwind_separator"] if needs_unwind : q_unwindders = [ { "$addFields": { field : { "$filter" : { "input": { "$split": [ "${}".format(field), unwind_separator ] }, "as": "str", "cond": { "$ne" : [ "$$str", "" ] } } } }}, { "$unwind" : "${}".format(field) } ] ### $ unwind - append unwindders to aggregation pipelinne log.debug( "unwindders : \n%s", pformat(q_unwindders) ) if len(q_unwindders) > 0 : q_aggregate += q_unwindders # $ grouping simple if q_complex_stat == False : q_group_block = { "$group" : { "_id" : "${}".format( payload[0]["agg_field"] ), "count" : { "$sum": 1 } } } q_sort = { "$sort" : { "count" : sort_order } } q_aggregate.append(q_group_block) q_sorting.append(q_sort) # $ grouping complex else : field_0 = payload[0]["agg_field"] field_1 = payload[1]["agg_field"] # basic complex aggregation q_group_block = [ { "$group": { "_id": { field_0: "${}".format(field_0), field_1: "${}".format(field_1) }, "count": { "$sum": 1 } } }] q_group_block_1 = [ { "$group": { "_id": "$_id.{}".format(field_0), "subcounts": { "$addToSet": { "tag_name" : "$_id.{}".format(field_1), "tag_code" : field_1, "count": "$count" }, } } }] q_group_block += q_group_block_1 ### append groupers to aggregation pipelinne q_aggregate += q_group_block q_sorting = [ { "$sort" : { "count" : sort_order } }, { "$sort" : { "subcount.count" : sort_order } } ] ### add sorters to pipeline for sorter in q_sorting : q_aggregate.append(sorter) ### check and run pipeline log.debug( "q_aggregate : \n%s", pformat(q_aggregate) ) results = db_collection.aggregate(q_aggregate) message = "stats required for this {}".format(document_type_full) document_out = list(results) ### transform list of results as series (e.g. for apexChart format) # if as_series : # log.debug( "as_series : %s", as_series ) # serie_format = query_args.get('serie_format', "apexCharts" ) # log.debug( "serie_format : %s", serie_format ) # ### TO DO ... elif is_payload == False : message = "your payload is empty, ouuups..." response_code = 401 else : message = "this {} doesn't exist".format(document_type_full) response_code = 401 log.debug('query_resume : \n%s', pformat(query_resume)) ### return response return { "msg" : message, "data" : document_out, "query" : query_resume, }, response_code """ ### examples pipeline aggregation stats ### LOCALLY ### ### - - - - ### db.getCollection('datasets_outputs_docs').aggregate([ { $match: { "oid_dso" : ObjectId("5c8942a48626a059decaa34a") } }, { $group: { _id: "$source", count: { $sum: 1 }, } }, { $sort : { "count" : 1 } } ]) db.getCollection('datasets_inputs_docs').aggregate([ { $match: { "oid_dsi" : ObjectId("5c891b3c8626a023e4fd61b3") } }, { $group: { _id: "$Label", count: { $sum: 1 } }}, { $sort : { "count" : -1 } } ]) ### IN SOLIDATA PROD ### ### - - - - - - - - ### ### SIMPLE COUNT db.getCollection('datasets_outputs_docs').aggregate([ { $match: { "oid_dso" : ObjectId("5c89636d328ed70609be03ab") } }, { $group: { _id: "$source", total: { $sum: 1 } } }, { $sort : { "count" : 1 } }, ]) ### COMPLEX COUNT / UNIQUES db.getCollection('datasets_outputs_docs').aggregate([ { $match: { "oid_dso": ObjectId("5c89636d328ed70609be03ab") } }, { $group: { _id: { "source": "$source", "ville structure": "$ville structure" } , count: { $sum: 1 } } }, { $group: { _id: "$_id.source", subcounts: { $addToSet: { "ville structure": "$_id.ville structure", count: "$count" } }, count: { $sum: 1 } } }, { $sort : { "count" : -1 } }, { $sort : { "subcounts.count" : -1 } }, ]) ### COMPLEX COUNT / COUNT AND UNWIND TAGS db.getCollection('datasets_outputs_docs').aggregate([ { $match: { "oid_dso": ObjectId("5c89636d328ed70609be03ab") } }, { $addFields: { "coding services" : { $filter: { input: { $split: ["$coding services", "-"] }, as: "str", cond: { $ne : [ "$$str", "" ] } } } }}, { $unwind : "$coding services" }, { $group: { _id: { "source" : "$source", "coding services": "$coding services" }, "coding services": { "$push": "$coding services" } , count: { $sum: 1 } } }, { $group: { "_id": "$_id.source", "subcounts": { $addToSet: { "coding services": "$_id.coding services", "count" : "$count" } }, } }, { $sort : { "count" : -1 } }, { $sort : { "subcounts.count" : -1 } }, ]) db.getCollection('datasets_inputs_docs').aggregate([ { $match: { "oid_dsi": ObjectId("5d1932db8626a086eb308e68"), "$text" : { "$search": "château" } }}, { $addFields: { "coding-services" : { $filter: { input: { $split: ["$coding-services", "-"] }, as: "str", cond: { $ne : [ "$$str", "" ] } } } }}, { $unwind : "$coding-services" }, { $group: { _id: { "sourceur" : "$sourceur", "coding-services": "$coding-services" }, "coding-services": { $push: "$coding-services" }, count: { $sum: 1 } }}, { $group: { _id: "$_id.sourceur", subcounts: { $addToSet: { "tag_name": "$_id.coding-services", "tag_code": "coding-services", count : "$count" }}, }}, { $sort : { "subcounts.count" : -1 } } ]) db.getCollection('datasets_outputs_docs').aggregate([ { $match: { "oid_dso": ObjectId("5c89636d328ed70609be03ab") } }, { $addFields: { "coding services" : { $filter: { input: { $split: ["$coding services", "-"] }, as: "str", cond: { $ne : [ "$$str", "" ] } } } }}, { $unwind : "$coding services" }, { $group: { _id: { "source" : "$source", "coding services": "$coding services" }, "coding services": { $push: "$coding services" } , count: { $sum: 1 } } }, { $group: { _id: "$_id.source", subcounts: { $addToSet: { "tag_name": "$_id.coding services", "tag_code": "coding services", count : "$count" } }, } } }, { $sort : { "subcounts.count" : -1 } }, ]) db.getCollection('datasets_inputs_docs').aggregate([ { $match: { "oid_dsi": ObjectId("5d1932db8626a086eb308e68"), "$text" : { "$search": "château" }, '$and': [ {'$or': [ {'coding-services': {'$options': '-i','$regex': '.*ACC.*' }} ]} ], }}, { $addFields: { "coding-services" : { $filter: { input: { $split: ["$coding-services", "-"] }, as: "str", cond: { $ne : [ "$$str", "" ] } } } }}, { $unwind : "$coding-services" }, { $group: { _id: { "sourceur" : "$sourceur", "coding-services": "$coding-services" }, "coding-services": { $push: "$coding-services" }, count: { $sum: 1 } }}, { $group: { _id: "$_id.sourceur", subcounts: { $addToSet: { "tag_name": "$_id.coding-services", "tag_code": "coding-services", count : "$count" }}, }}, { $sort : { "subcounts.count" : -1 } } ]) """ # ### marshal out results given user's claims / doc's public_auth / doc's team ... # # for admin or members of the team --> complete infos model # if user_role in roles_for_complete or user_oid in team_oids or user_oid == created_by_oid : # log.debug( "... user_role in roles_for_complete or user_oid in team_oids or user_oid == created_by_oid " ) # # flag as member of doc's team # if user_oid == created_by_oid : # query_resume["is_creator"] = True # # flag as member of doc's team # if user_oid in team_oids : # query_resume["is_member_of_team"] = True # document_out = {} # message = "dear user, there is the complete {} you requested ".format(document_type_full) # # for other users # else : # log.debug( "... user_role NOT in roles_for_complete or user_oid in team_oids or user_oid == created_by_oid " ) # if doc_open_level_show in ["commons", "open_data"] : # ### for anonymous users --> minimum infos model # if user_id == None or user_role == "anonymous" : # document_out = {} # ### for registred users (guests) --> guest infos model # else : # document_out = {} # message = "dear user, there is the {} you requested given your credentials".format(document_type_full) # else : # response_code = 401 # ### unvalid credentials / empty response # message = "dear user, you don't have the credentials to access/see this {} with this oid : {}".format(document_type_full, doc_id) # else : # ### no document / empty response # response_code = 404 # message = "dear user, there is no {} with this oid : {}".format(document_type_full, doc_id) # document_out = None
[ "bson.objectid.ObjectId", "log_config.pformat", "log_config.log.debug", "bson.objectid.ObjectId.is_valid" ]
[((213, 265), 'log_config.log.debug', 'log.debug', (['"""... _core.queries_db.query_stats.py ..."""'], {}), "('... _core.queries_db.query_stats.py ...')\n", (222, 265), False, 'from log_config import log, pformat\n'), ((1034, 1101), 'log_config.log.debug', 'log.debug', (['"""... Query_db_stats / document_type : %s"""', 'document_type'], {}), "('... Query_db_stats / document_type : %s', document_type)\n", (1043, 1101), False, 'from log_config import log, pformat\n'), ((2383, 2402), 'log_config.pformat', 'pformat', (['query_args'], {}), '(query_args)\n', (2390, 2402), False, 'from log_config import log, pformat\n'), ((2986, 3002), 'log_config.pformat', 'pformat', (['payload'], {}), '(payload)\n', (2993, 3002), False, 'from log_config import log, pformat\n'), ((3257, 3282), 'bson.objectid.ObjectId.is_valid', 'ObjectId.is_valid', (['doc_id'], {}), '(doc_id)\n', (3274, 3282), False, 'from bson.objectid import ObjectId\n'), ((3302, 3318), 'bson.objectid.ObjectId', 'ObjectId', (['doc_id'], {}), '(doc_id)\n', (3310, 3318), False, 'from bson.objectid import ObjectId\n'), ((3518, 3534), 'bson.objectid.ObjectId', 'ObjectId', (['doc_id'], {}), '(doc_id)\n', (3526, 3534), False, 'from bson.objectid import ObjectId\n'), ((3829, 3887), 'log_config.log.debug', 'log.debug', (['"""doc_open_level_show : %s"""', 'doc_open_level_show'], {}), "('doc_open_level_show : %s', doc_open_level_show)\n", (3838, 3887), False, 'from log_config import log, pformat\n'), ((8270, 8291), 'log_config.pformat', 'pformat', (['query_resume'], {}), '(query_resume)\n', (8277, 8291), False, 'from log_config import log, pformat\n'), ((1903, 1920), 'bson.objectid.ObjectId', 'ObjectId', (['user_id'], {}), '(user_id)\n', (1911, 1920), False, 'from bson.objectid import ObjectId\n'), ((1927, 1963), 'log_config.log.debug', 'log.debug', (['"""user_oid : %s"""', 'user_oid'], {}), "('user_oid : %s', user_oid)\n", (1936, 1963), False, 'from log_config import log, pformat\n'), ((4400, 4416), 'log_config.pformat', 'pformat', (['q_match'], {}), '(q_match)\n', (4407, 4416), False, 'from log_config import log, pformat\n'), ((4928, 4944), 'log_config.pformat', 'pformat', (['q_match'], {}), '(q_match)\n', (4935, 4944), False, 'from log_config import log, pformat\n'), ((5980, 6001), 'log_config.pformat', 'pformat', (['q_unwindders'], {}), '(q_unwindders)\n', (5987, 6001), False, 'from log_config import log, pformat\n'), ((7553, 7573), 'log_config.pformat', 'pformat', (['q_aggregate'], {}), '(q_aggregate)\n', (7560, 7573), False, 'from log_config import log, pformat\n'), ((4189, 4207), 'log_config.pformat', 'pformat', (['team_oids'], {}), '(team_oids)\n', (4196, 4207), False, 'from log_config import log, pformat\n')]
# This is the file that implements a flask server to do inferences. import os import json import flask import pandas as pd from io import StringIO, BytesIO import mindsdb # Define the path prefix = '/opt/ml/' model_path = os.path.join(prefix, 'model') def parse_data(content_type, data): ''' Get the request content type and return data as DataFrame object ''' excel_mime = ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'] if content_type == 'application/json': req = data.json when_data = pd.DataFrame(req) elif content_type == 'text/csv': req = data.data.decode('utf-8') s = StringIO(req) when_data = pd.read_csv(s, header=0) elif content_type in excel_mime: req = data.data s = BytesIO(req) when_data = pd.read_excel(s, header=0) else: raise ValueError return when_data # The flask app for serving predictions app = flask.Flask(__name__) @app.route('/ping', methods=['GET']) def ping(): # Check if the predictor was loaded correctly, if not throw error try: if not os.path.exists(model_path + '/mdbp_heavy_model_metadata.pickle'): raise IOError response = "Success" status = 200 except Exception as e: response = str(e) status = 404 return flask.Response(response=response, status=status, mimetype='application/json') @app.route('/invocations', methods=['POST']) def transformation(): # Avoid mindsdb storage path write access mindsdb.CONFIG.SAGEMAKER = 'True' mindsdb.CONFIG.MINDSDB_STORAGE_PATH = model_path try: when_data = parse_data(flask.request.content_type, flask.request) except ValueError: return flask.Response(response='This predictor supports JSON,CSV and Excel data', status=415, mimetype='text/plain') print('Invoked with {} records'.format(when_data)) result = mindsdb.Predictor(name='mdbp').predict(when_data=when_data) cconfidence = [x['Class_confidence'] for x in result] response = { 'prediction': str(result[0]), 'class_confidence': cconfidence[-1] } print('Response prediction: {}'.format(response['prediction'])) return flask.Response(response=json.dumps(response), status=200, mimetype='application/json')
[ "os.path.exists", "mindsdb.Predictor", "pandas.read_csv", "flask.Flask", "json.dumps", "os.path.join", "io.BytesIO", "flask.Response", "pandas.read_excel", "pandas.DataFrame", "io.StringIO" ]
[((223, 252), 'os.path.join', 'os.path.join', (['prefix', '"""model"""'], {}), "(prefix, 'model')\n", (235, 252), False, 'import os\n'), ((1000, 1021), 'flask.Flask', 'flask.Flask', (['__name__'], {}), '(__name__)\n', (1011, 1021), False, 'import flask\n'), ((1392, 1469), 'flask.Response', 'flask.Response', ([], {'response': 'response', 'status': 'status', 'mimetype': '"""application/json"""'}), "(response=response, status=status, mimetype='application/json')\n", (1406, 1469), False, 'import flask\n'), ((597, 614), 'pandas.DataFrame', 'pd.DataFrame', (['req'], {}), '(req)\n', (609, 614), True, 'import pandas as pd\n'), ((704, 717), 'io.StringIO', 'StringIO', (['req'], {}), '(req)\n', (712, 717), False, 'from io import StringIO, BytesIO\n'), ((738, 762), 'pandas.read_csv', 'pd.read_csv', (['s'], {'header': '(0)'}), '(s, header=0)\n', (749, 762), True, 'import pandas as pd\n'), ((1165, 1229), 'os.path.exists', 'os.path.exists', (["(model_path + '/mdbp_heavy_model_metadata.pickle')"], {}), "(model_path + '/mdbp_heavy_model_metadata.pickle')\n", (1179, 1229), False, 'import os\n'), ((1825, 1938), 'flask.Response', 'flask.Response', ([], {'response': '"""This predictor supports JSON,CSV and Excel data"""', 'status': '(415)', 'mimetype': '"""text/plain"""'}), "(response='This predictor supports JSON,CSV and Excel data',\n status=415, mimetype='text/plain')\n", (1839, 1938), False, 'import flask\n'), ((2034, 2064), 'mindsdb.Predictor', 'mindsdb.Predictor', ([], {'name': '"""mdbp"""'}), "(name='mdbp')\n", (2051, 2064), False, 'import mindsdb\n'), ((2362, 2382), 'json.dumps', 'json.dumps', (['response'], {}), '(response)\n', (2372, 2382), False, 'import json\n'), ((836, 848), 'io.BytesIO', 'BytesIO', (['req'], {}), '(req)\n', (843, 848), False, 'from io import StringIO, BytesIO\n'), ((869, 895), 'pandas.read_excel', 'pd.read_excel', (['s'], {'header': '(0)'}), '(s, header=0)\n', (882, 895), True, 'import pandas as pd\n')]
from math import floor n = int(input()) result = 0 game_over = False path = [] directions = { "up": (-1, 0), "down": (1, 0), "left": (0, -1), "right": (0, 1) } matrix = [] for row in range(n): matrix.append(input().split()) def movement_is_valid(movement): if movement == "up" or movement == "down" or movement == "right" or movement == "left": return True return False def check_if_new_position_is_valid(matrix, new_row, new_col): if not 0 <= new_row < n or not 0 <= new_col < n: return False if matrix[new_row][new_col] == "X": return False return True def finding_the_player(matrix): for row in range(n): for col in range(n): current_el = matrix[row][col] if current_el == "P": return row, col while not game_over: movement = input() if movement_is_valid(movement): pass else: continue current_player_position = finding_the_player(matrix) new_row, new_col = directions[movement] old_row, old_col = current_player_position new_row += old_row new_col += old_col if check_if_new_position_is_valid(matrix, new_row, new_col): if movement == "up": result += int(matrix[new_row][new_col]) path.append([new_row, new_col]) matrix[new_row][new_col] = "P" matrix[old_row][old_col] = "-" if movement == "down": result += int(matrix[new_row][new_col]) path.append([new_row, new_col]) matrix[new_row][new_col] = "P" matrix[old_row][old_col] = "-" if movement == "right": result += int(matrix[new_row][new_col]) path.append([new_row, new_col]) matrix[new_row][new_col] = "P" matrix[old_row][old_col] = "-" if movement == "left": result += int(matrix[new_row][new_col]) path.append([new_row, new_col]) matrix[new_row][new_col] = "P" matrix[old_row][old_col] = "-" else: game_over = True result /= 2 print(f"Game over! You've collected {floor(result)} coins.") print("Your path:") [print(el) for el in path] break if result >= 100: print(f"You won! You've collected {result} coins.") print("Your path:") [print(el) for el in path] break
[ "math.floor" ]
[((2158, 2171), 'math.floor', 'floor', (['result'], {}), '(result)\n', (2163, 2171), False, 'from math import floor\n')]
import os import torch import torchvision.datasets as datasets from .imagenet import ImageNetSubsample, ImageNetSubsampleValClasses import numpy as np CLASS_SUBLIST = [ 1, 2, 4, 6, 8, 9, 11, 13, 22, 23, 26, 29, 31, 39, 47, 63, 71, 76, 79, 84, 90, 94, 96, 97, 99, 100, 105, 107, 113, 122, 125, 130, 132, 144, 145, 147, 148, 150, 151, 155, 160, 161, 162, 163, 171, 172, 178, 187, 195, 199, 203, 207, 208, 219, 231, 232, 234, 235, 242, 245, 247, 250, 251, 254, 259, 260, 263, 265, 267, 269, 276, 277, 281, 288, 289, 291, 292, 293, 296, 299, 301, 308, 309, 310, 311, 314, 315, 319, 323, 327, 330, 334, 335, 337, 338, 340, 341, 344, 347, 353, 355, 361, 362, 365, 366, 367, 368, 372, 388, 390, 393, 397, 401, 407, 413, 414, 425, 428, 430, 435, 437, 441, 447, 448, 457, 462, 463, 469, 470, 471, 472, 476, 483, 487, 515, 546, 555, 558, 570, 579, 583, 587, 593, 594, 596, 609, 613, 617, 621, 629, 637, 657, 658, 701, 717, 724, 763, 768, 774, 776, 779, 780, 787, 805, 812, 815, 820, 824, 833, 847, 852, 866, 875, 883, 889, 895, 907, 928, 931, 932, 933, 934, 936, 937, 943, 945, 947, 948, 949, 951, 953, 954, 957, 963, 965, 967, 980, 981, 983, 988] CLASS_SUBLIST_MASK = [(i in CLASS_SUBLIST) for i in range(1000)] class ImageNetRValClasses(ImageNetSubsampleValClasses): def get_class_sublist_and_mask(self): return CLASS_SUBLIST, CLASS_SUBLIST_MASK class ImageNetR(ImageNetSubsample): def get_class_sublist_and_mask(self): return CLASS_SUBLIST, CLASS_SUBLIST_MASK def get_test_path(self): return os.path.join(self.location, 'imagenet-r')
[ "os.path.join" ]
[((1596, 1637), 'os.path.join', 'os.path.join', (['self.location', '"""imagenet-r"""'], {}), "(self.location, 'imagenet-r')\n", (1608, 1637), False, 'import os\n')]
#!/usr/bin/python # -*- coding: utf-8 -*- """ This bot retreives a list of long term IP blocks on the wiki and tries to identify if any of them are proxies. If so, it extends the block for another year. """ # # (C) User:<NAME>, 2019 # (C) User:Huji, 2019 # # Distributed under the terms of the CC-BY-SA license. # from __future__ import absolute_import # import pywikibot import MySQLdb as mysqldb from ipwhois import IPWhois import config import json import requests import re from cidr_trie import PatriciaTrie class FindProxyBot(): def __init__(self): self.site = pywikibot.Site() self.target = 'ویکی‌پدیا:گزارش دیتابیس/تمدید بستن پروکسی' self.summary = 'روزآمدسازی نتایج (وظیفه ۲۳)' self.blocksummary = '{{پروکسی باز}}' self.IPQSkey = config.findproxy['IPQSkey'] self.PCkey = config.findproxy['PCkey'] self.GIIemail = config.findproxy['GIIemail'] self.IPv4cache = PatriciaTrie() self.IPv6cache = PatriciaTrie() def get_ip_list(self): """ Gathers a list of IPs with a long-term block that is about to expire. """ conn = mysqldb.connect( host='fawiki.web.db.svc.wikimedia.cloud', db='fawiki_p', read_default_file='~/replica.my.cnf' ) cursor = conn.cursor() query = """ SELECT ipb_address, STR_TO_DATE(LEFT(ipb_expiry, 8), '%Y%m%d') AS start_date, STR_TO_DATE(LEFT(ipb_timestamp, 8), '%Y%m%d') AS expiry, 0 - DATEDIFF(NOW(), STR_TO_DATE(LEFT(ipb_expiry, 8), '%Y%m%d')) AS days_left, DATEDIFF(NOW(), STR_TO_DATE(LEFT(ipb_timestamp, 8), '%Y%m%d')) AS block_age FROM ipblocks WHERE ipb_user = 0 AND ipb_expiry NOT IN ( 'infinity', 'indefinite' ) AND DATEDIFF(NOW(), STR_TO_DATE(LEFT(ipb_expiry, 8), '%Y%m%d')) > -30 AND DATEDIFF(NOW(), STR_TO_DATE(LEFT(ipb_timestamp, 8), '%Y%m%d')) > 300 AND ipb_range_start = ipb_range_end -- exclude CIDRs """ cursor.execute(query) results = cursor.fetchall() return results def get_cache(self, ip): pat = r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}' if re.match(pat, ip) is None: """ Temporary fix for https://github.com/Figglewatts/cidr-trie/issues/2 """ if self.IPv6cache.size == 0: return [] return self.IPv6cache.find_all(ip) else: return self.IPv4cache.find_all(ip) def set_cache(self, ip, cidr, country): pat = r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}' if re.match(pat, ip) is None: self.IPv6cache.insert(cidr, country) else: self.IPv4cache.insert(cidr, country) def get_ip_info(self, ip): """ Retrieves pertinent fields from IP WHOIS information """ cached_info = self.get_cache(ip) if len(cached_info) == 0: try: request = IPWhois(ip) result = request.lookup_rdap(depth=1) cidr = result['asn_cidr'] country = result['asn_country_code'] self.set_cache(ip, cidr, country) except Exception: cidr = '' country = '' else: cidr = cached_info[0][0] country = cached_info[0][1] return { 'cidr': cidr, 'country_code': country } def query_IPQualityScore(self, ip): """ Queries the IPQualityScore API to check if an IP is a proxy """ url = 'https://www.ipqualityscore.com/api/json/ip/%s/%s' request = requests.get(url % (self.IPQSkey, ip)) result = request.json() if 'proxy' in result.keys(): return 1 if result['proxy'] is True else 0 else: return False def query_proxycheck(self, ip): """ Queries the proxycheck.io API to check if an IP is a proxy """ url = 'http://proxycheck.io/v2/%s?key=%s&vpn=1' request = requests.get(url % (ip, self.PCkey)) result = request.json() if ip in result.keys() and 'proxy' in result[ip]: return 1 if result[ip]['proxy'] == 'yes' else 0 else: return False def query_GetIPIntel(self, ip): """ Queries the GetIPIntel API to check if an IP is a proxy """ url = 'http://check.getipintel.net/check.php' + \ '?ip=%s&contact=%s&format=json&flags=m' request = requests.get(url % (ip, self.GIIemail)) result = request.json() if 'result' in result.keys(): return 1 if result['result'] == '1' else 0 else: return False def query_teoh_io(self, ip): """ Queries the teoh.io API to check if an IP is a proxy """ url = 'https://ip.teoh.io/api/vpn/%s' request = requests.get(url % ip) """ Sadly, teoh.io sometimes generates PHP notices before the JSON output. Therefore, we will have to find the actual JSON output and parse it. """ result = request.text if result[0] != '{': result = result[result.find('{'):] result = json.loads(result) if 'vpn_or_proxy' in result.keys(): return 1 if result['vpn_or_proxy'] == 'yes' else 0 else: return False def run_queries(self, ip): return [ self.query_IPQualityScore(ip), self.query_proxycheck(ip), self.query_GetIPIntel(ip) ] def format_result(self, res): if res == 1: return '{{yes}}' elif res == 0: return '{{no}}' else: return '{{yes-no|}}' def find_proxies(self): out = '{| class="wikitable sortable"\n' out += '! آی‌پی !! بازه !! کد کشور !! ' +\ 'IPQualityScore !! proxycheck !! GetIPIntel !! ' +\ 'بسته شد' iplist = self.get_ip_list() rowtemplate = '\n|-\n| %s || %s || %s || %s || %s || %s || %s' for ipdata in iplist: ip = ipdata[0].decode('ASCII') print(ip) pywikibot.output('Checking %s' % ip) ipinfo = self.get_ip_info(ip) if ipinfo['country_code'] == 'IR': """ IPs from Iran are almost never proxies, skip the checks """ pass else: IPQS, PC, GII = self.run_queries(ip) if IPQS + PC + GII == 3: target = pywikibot.User(self.site, ip) pywikibot.output('Blocking %s' % ip) self.site.blockuser( target, '1 year', self.blocksummary, anononly=False, reblock=True, allowusertalk=True) blocked = 1 else: blocked = 0 row = rowtemplate % ( ip, ipinfo['cidr'], ipinfo['country_code'], self.format_result(IPQS), self.format_result(PC), self.format_result(GII), self.format_result(blocked) ) out += row out += '\n|}' page = pywikibot.Page(self.site, self.target) page.text = out page.save(self.summary) page = pywikibot.Page(self.site, self.target + '/امضا') page.text = '~~~~~' page.save(self.summary) robot = FindProxyBot() robot.find_proxies()
[ "json.loads", "cidr_trie.PatriciaTrie", "pywikibot.Site", "pywikibot.User", "re.match", "requests.get", "ipwhois.IPWhois", "pywikibot.Page", "MySQLdb.connect", "pywikibot.output" ]
[((583, 599), 'pywikibot.Site', 'pywikibot.Site', ([], {}), '()\n', (597, 599), False, 'import pywikibot\n'), ((940, 954), 'cidr_trie.PatriciaTrie', 'PatriciaTrie', ([], {}), '()\n', (952, 954), False, 'from cidr_trie import PatriciaTrie\n'), ((980, 994), 'cidr_trie.PatriciaTrie', 'PatriciaTrie', ([], {}), '()\n', (992, 994), False, 'from cidr_trie import PatriciaTrie\n'), ((1140, 1254), 'MySQLdb.connect', 'mysqldb.connect', ([], {'host': '"""fawiki.web.db.svc.wikimedia.cloud"""', 'db': '"""fawiki_p"""', 'read_default_file': '"""~/replica.my.cnf"""'}), "(host='fawiki.web.db.svc.wikimedia.cloud', db='fawiki_p',\n read_default_file='~/replica.my.cnf')\n", (1155, 1254), True, 'import MySQLdb as mysqldb\n'), ((3623, 3661), 'requests.get', 'requests.get', (['(url % (self.IPQSkey, ip))'], {}), '(url % (self.IPQSkey, ip))\n', (3635, 3661), False, 'import requests\n'), ((4027, 4063), 'requests.get', 'requests.get', (['(url % (ip, self.PCkey))'], {}), '(url % (ip, self.PCkey))\n', (4039, 4063), False, 'import requests\n'), ((4508, 4547), 'requests.get', 'requests.get', (['(url % (ip, self.GIIemail))'], {}), '(url % (ip, self.GIIemail))\n', (4520, 4547), False, 'import requests\n'), ((4895, 4917), 'requests.get', 'requests.get', (['(url % ip)'], {}), '(url % ip)\n', (4907, 4917), False, 'import requests\n'), ((5221, 5239), 'json.loads', 'json.loads', (['result'], {}), '(result)\n', (5231, 5239), False, 'import json\n'), ((7343, 7381), 'pywikibot.Page', 'pywikibot.Page', (['self.site', 'self.target'], {}), '(self.site, self.target)\n', (7357, 7381), False, 'import pywikibot\n'), ((7454, 7502), 'pywikibot.Page', 'pywikibot.Page', (['self.site', "(self.target + '/امضا')"], {}), "(self.site, self.target + '/امضا')\n", (7468, 7502), False, 'import pywikibot\n'), ((2133, 2150), 're.match', 're.match', (['pat', 'ip'], {}), '(pat, ip)\n', (2141, 2150), False, 'import re\n'), ((2555, 2572), 're.match', 're.match', (['pat', 'ip'], {}), '(pat, ip)\n', (2563, 2572), False, 'import re\n'), ((6185, 6221), 'pywikibot.output', 'pywikibot.output', (["('Checking %s' % ip)"], {}), "('Checking %s' % ip)\n", (6201, 6221), False, 'import pywikibot\n'), ((2930, 2941), 'ipwhois.IPWhois', 'IPWhois', (['ip'], {}), '(ip)\n', (2937, 2941), False, 'from ipwhois import IPWhois\n'), ((6585, 6614), 'pywikibot.User', 'pywikibot.User', (['self.site', 'ip'], {}), '(self.site, ip)\n', (6599, 6614), False, 'import pywikibot\n'), ((6635, 6671), 'pywikibot.output', 'pywikibot.output', (["('Blocking %s' % ip)"], {}), "('Blocking %s' % ip)\n", (6651, 6671), False, 'import pywikibot\n')]
from backend.create_app import create_app application = create_app()
[ "backend.create_app.create_app" ]
[((58, 70), 'backend.create_app.create_app', 'create_app', ([], {}), '()\n', (68, 70), False, 'from backend.create_app import create_app\n')]
# encoding: utf-8 from unittest.mock import Mock, patch from src.client.models import utils from src.exceptions import WalletError from tests.unit.logging import LoggingMixin class ClientUtilsTest(LoggingMixin): def setUp(self): self.data = {'test_data_key': 'test_data_value'} def test_get_utcnow_timestamp(self): timestamp = utils.get_utcnow_timestamp() self.assertIsInstance(timestamp, int) def test_utils_serialize(self): serialized = utils.serialize(self.data) self.assertIsInstance(self.data, dict) self.assertIsInstance(serialized, str) @patch('src.client.models.utils.json.dumps') def test_utils_serialize_error(self, mock_json_dumps): err_message = 'Could not encode data' mock_json_dumps.side_effect = Mock(side_effect=WalletError(err_message)) with self.assertRaises(WalletError) as err: utils.serialize(self.data) self.assertTrue(mock_json_dumps.called) self.assertIsInstance(err, WalletError) self.assertIn(err_message, err.message)
[ "src.client.models.utils.serialize", "unittest.mock.patch", "src.client.models.utils.get_utcnow_timestamp", "src.exceptions.WalletError" ]
[((617, 660), 'unittest.mock.patch', 'patch', (['"""src.client.models.utils.json.dumps"""'], {}), "('src.client.models.utils.json.dumps')\n", (622, 660), False, 'from unittest.mock import Mock, patch\n'), ((357, 385), 'src.client.models.utils.get_utcnow_timestamp', 'utils.get_utcnow_timestamp', ([], {}), '()\n', (383, 385), False, 'from src.client.models import utils\n'), ((490, 516), 'src.client.models.utils.serialize', 'utils.serialize', (['self.data'], {}), '(self.data)\n', (505, 516), False, 'from src.client.models import utils\n'), ((911, 937), 'src.client.models.utils.serialize', 'utils.serialize', (['self.data'], {}), '(self.data)\n', (926, 937), False, 'from src.client.models import utils\n'), ((821, 845), 'src.exceptions.WalletError', 'WalletError', (['err_message'], {}), '(err_message)\n', (832, 845), False, 'from src.exceptions import WalletError\n')]
from flask import request from assemblyline.common.concurrency import execute_concurrently from assemblyline.common.importing import module_attribute_by_name from al_ui.api_base import api_login, make_api_response from al_ui.apiv3 import core from al_ui.config import LOGGER, config from assemblyline.al.datasource.common import hash_type SUB_API = 'hash_search' hash_search_api = core.make_subapi_blueprint(SUB_API) hash_search_api._doc = "Search hashes through multiple data sources" class SkipDatasource(Exception): pass def create_query_datasource(ds): def query_datasource(h, u): return { 'error': None, 'items': ds.parse(ds.query(h, **u), **u) } return query_datasource sources = {} # noinspection PyBroadException try: for name, settings in config.datasources.iteritems(): name = name.lower() classpath = 'unknown' # noinspection PyBroadException try: classpath = settings['classpath'] cfg = settings['config'] if isinstance(cfg, basestring): path = cfg cfg = config for point in path.split('.'): if 'enabled' in cfg: if not cfg['enabled']: raise SkipDatasource() cfg = cfg.get(point) cls = module_attribute_by_name(classpath) obj = cls(LOGGER, **cfg) sources[name] = create_query_datasource(obj) except SkipDatasource: continue except: # pylint: disable=W0702 LOGGER.exception( "Problem creating %s datasource (%s)", name, classpath ) except: # pylint: disable=W0702 LOGGER.exception("No datasources") # noinspection PyUnusedLocal @hash_search_api.route("/<file_hash>/", methods=["GET"]) @api_login(required_priv=['R']) def search_hash(file_hash, *args, **kwargs): """ Search for a hash in multiple data sources as configured in the seed. Variables: value => Hash to search in the multiple data sources [MD5, SHA1 or SHA256] Arguments:(optional) db => | separated list of data sources show_timers => Display time it took to query each sources max_timeout => Maximum execution time for the call in seconds Data Block: None API call examples: /api/v3/hash_search/ /api/v3/hash_search/123456...654321/?db=nsrl|al&show_timers=true Result example: { # Dictionary of: "al": { # Data source queried "error": null, # Error message returned by data source "items": [ # List of items found in the data source {"confirmed": true, # Is the maliciousness attribution confirmed or not "data": # Raw data from the data source "description": "", # Description of the findings "malicious": false}, # Is the file found malicious or not ... ] }, ... } """ user = kwargs['user'] if hash_type(file_hash) == "invalid": return make_api_response("", "Invalid hash. This API only supports MD5, SHA1 and SHA256.", 400) db_list = [] invalid_sources = [] db = request.args.get('db', None) if db: db_list = db.split("|") invalid_sources = [] for x in db_list: if x not in sources: invalid_sources.append(x) for x in invalid_sources: db_list.remove(x) show_timers = request.args.get('show_timers', False) if show_timers: show_timers = show_timers.lower() == 'true' max_timeout = request.args.get('max_timeout', "2") # noinspection PyBroadException try: max_timeout = float(max_timeout) except: # pylint: disable=W0702 max_timeout = 2.0 if len(db_list) == 0 and len(invalid_sources) == 0: db_list = sources.keys() plan = [(sources[x], (file_hash.lower(), user), x) for x in db_list] res = execute_concurrently(plan, calculate_timers=show_timers, max_timeout=max_timeout) data = {} for x in db_list: if x not in res: if x in res["_timeout_"]: data[x] = {"items": [], "error": "Service reached the maximum execution time. [%s seconds]" % max_timeout} elif x in res["_exception_"]: exception = res["_exception_"][x] e = "%s: %s" % (exception.__class__.__name__, str(exception)) data[x] = {"items": [], "error": "Exception occured while querying datasource. [%s]" % e} else: data[x] = {"items": [], "error": "Service is currently not available."} else: data[x] = res[x] if show_timers: data['_timers_'] = res.get("_timers_", {}) return make_api_response(data) # noinspection PyUnusedLocal @hash_search_api.route("/list_data_sources/", methods=["GET"]) @api_login(audit=False, required_priv=['R']) def list_data_sources(*args, **kwargs): """ List all available data sources to use the hash_search API Variables: None Arguments: None Data Block: None Result example: [ <list of sources> ] """ return make_api_response(sorted(sources.keys()))
[ "flask.request.args.get", "al_ui.api_base.make_api_response", "assemblyline.common.concurrency.execute_concurrently", "assemblyline.common.importing.module_attribute_by_name", "al_ui.config.LOGGER.exception", "al_ui.config.config.datasources.iteritems", "al_ui.apiv3.core.make_subapi_blueprint", "assem...
[((384, 419), 'al_ui.apiv3.core.make_subapi_blueprint', 'core.make_subapi_blueprint', (['SUB_API'], {}), '(SUB_API)\n', (410, 419), False, 'from al_ui.apiv3 import core\n'), ((1881, 1911), 'al_ui.api_base.api_login', 'api_login', ([], {'required_priv': "['R']"}), "(required_priv=['R'])\n", (1890, 1911), False, 'from al_ui.api_base import api_login, make_api_response\n'), ((5136, 5179), 'al_ui.api_base.api_login', 'api_login', ([], {'audit': '(False)', 'required_priv': "['R']"}), "(audit=False, required_priv=['R'])\n", (5145, 5179), False, 'from al_ui.api_base import api_login, make_api_response\n'), ((812, 842), 'al_ui.config.config.datasources.iteritems', 'config.datasources.iteritems', ([], {}), '()\n', (840, 842), False, 'from al_ui.config import LOGGER, config\n'), ((3379, 3407), 'flask.request.args.get', 'request.args.get', (['"""db"""', 'None'], {}), "('db', None)\n", (3395, 3407), False, 'from flask import request\n'), ((3665, 3703), 'flask.request.args.get', 'request.args.get', (['"""show_timers"""', '(False)'], {}), "('show_timers', False)\n", (3681, 3703), False, 'from flask import request\n'), ((3795, 3831), 'flask.request.args.get', 'request.args.get', (['"""max_timeout"""', '"""2"""'], {}), "('max_timeout', '2')\n", (3811, 3831), False, 'from flask import request\n'), ((4155, 4241), 'assemblyline.common.concurrency.execute_concurrently', 'execute_concurrently', (['plan'], {'calculate_timers': 'show_timers', 'max_timeout': 'max_timeout'}), '(plan, calculate_timers=show_timers, max_timeout=\n max_timeout)\n', (4175, 4241), False, 'from assemblyline.common.concurrency import execute_concurrently\n'), ((5017, 5040), 'al_ui.api_base.make_api_response', 'make_api_response', (['data'], {}), '(data)\n', (5034, 5040), False, 'from al_ui.api_base import api_login, make_api_response\n'), ((1757, 1791), 'al_ui.config.LOGGER.exception', 'LOGGER.exception', (['"""No datasources"""'], {}), "('No datasources')\n", (1773, 1791), False, 'from al_ui.config import LOGGER, config\n'), ((3188, 3208), 'assemblyline.al.datasource.common.hash_type', 'hash_type', (['file_hash'], {}), '(file_hash)\n', (3197, 3208), False, 'from assemblyline.al.datasource.common import hash_type\n'), ((3238, 3330), 'al_ui.api_base.make_api_response', 'make_api_response', (['""""""', '"""Invalid hash. This API only supports MD5, SHA1 and SHA256."""', '(400)'], {}), "('',\n 'Invalid hash. This API only supports MD5, SHA1 and SHA256.', 400)\n", (3255, 3330), False, 'from al_ui.api_base import api_login, make_api_response\n'), ((1382, 1417), 'assemblyline.common.importing.module_attribute_by_name', 'module_attribute_by_name', (['classpath'], {}), '(classpath)\n', (1406, 1417), False, 'from assemblyline.common.importing import module_attribute_by_name\n'), ((1617, 1689), 'al_ui.config.LOGGER.exception', 'LOGGER.exception', (['"""Problem creating %s datasource (%s)"""', 'name', 'classpath'], {}), "('Problem creating %s datasource (%s)', name, classpath)\n", (1633, 1689), False, 'from al_ui.config import LOGGER, config\n')]
#!/usr/bin/env python r""" This file contains functions useful for validating variables in robot. """ import gen_robot_print as grp import gen_valid as gv from robot.libraries.BuiltIn import BuiltIn from robot.api import logger def rvalid_value(var_name, invalid_values=[], valid_values=[]): r""" Validate a robot value. This function is the robot wrapper for gen_robot_print.svalid_value. Description of arguments: var_name The name of the variable whose value is to be validated. invalid_values A list of invalid values. If var_value is equal to any of these, it is invalid. Note that if you specify anything for invalid_values (below), the valid_values list is not even processed. valid_values A list of invalid values. var_value must be equal to one of these values to be considered valid. Examples of robot calls and corresponding output: Robot code... rvalid_value MY_PARM Output... #(CDT) 2016/11/02 10:04:20 - **ERROR** Variable "MY_PARM" not found (i.e. #it's undefined). or if it is defined but blank: Output... #(CDT) 2016/11/02 10:14:24 - **ERROR** The following variable has an #invalid value: MY_PARM: It must NOT be one of the following values: invalid_values: invalid_values[0]: <blank> Robot code... ${invalid_values}= Create List one two three ${MY_PARM}= Set Variable one rvalid_value MY_PARM invalid_values=${invalid_values} Output... #(CDT) 2016/11/02 10:20:05 - **ERROR** The following variable has an #invalid value: MY_PARM: one It must NOT be one of the following values: invalid_values: invalid_values[0]: one invalid_values[1]: two invalid_values[2]: three """ # Note: get_variable_value() seems to have no trouble with local variables. var_value = BuiltIn().get_variable_value("${" + var_name + "}") if var_value is None: var_value = "" error_message = "Variable \"" + var_name +\ "\" not found (i.e. it's undefined).\n" else: error_message = gv.svalid_value(var_value, invalid_values, valid_values, var_name) if not error_message == "": error_message = grp.sprint_error_report(error_message) BuiltIn().fail(error_message) def rvalid_integer(var_name): r""" Validate a robot integer. This function is the robot wrapper for gen_robot_print.svalid_integer. Description of arguments: var_name The name of the variable whose value is to be validated. Examples of robot calls and corresponding output: Robot code... Rvalid Integer MY_PARM Output... #(CDT) 2016/11/02 10:44:43 - **ERROR** Variable "MY_PARM" not found (i.e. #it's undefined). or if it is defined but blank: Output... #(CDT) 2016/11/02 10:45:37 - **ERROR** Invalid integer value: MY_PARM: <blank> Robot code... ${MY_PARM}= Set Variable HELLO Rvalid Integer MY_PARM Output... #(CDT) 2016/11/02 10:46:18 - **ERROR** Invalid integer value: MY_PARM: HELLO """ # Note: get_variable_value() seems to have no trouble with local variables. var_value = BuiltIn().get_variable_value("${" + var_name + "}") if var_value is None: var_value = "" error_message = "Variable \"" + var_name +\ "\" not found (i.e. it's undefined).\n" else: error_message = gv.svalid_integer(var_value, var_name) if not error_message == "": error_message = grp.sprint_error_report(error_message) BuiltIn().fail(error_message) def rvalid_range(var_name, range): r""" Validate that a robot integer is within the given range. This function is the robot wrapper for gen_robot_print.svalid_range. Description of arguments: var_name The name of the variable whose value is to be validated. range A list comprised of one or two elements which are the lower and upper ends of a range. These values must be integers except where noted. Valid specifications may be of the following forms: [lower, upper], [lower] or [None, upper]. The caller may also specify this value as a string which will then be converted to a list in the aforementioned format: lower..upper, lower.. or ..upper. Examples of robot calls and corresponding output: Robot code... Rvalid Range MY_PARM 5..9 Output... #(CDT) 2018/05/09 11:45:00.166344 - 0.004252 - **ERROR** The following # variable is not within the expected range: MY_PARM: 4 valid_range: 5..9 """ var_value = BuiltIn().get_variable_value("${" + var_name + "}") if var_value is None: var_value = "" error_message = "Variable \"" + var_name +\ "\" not found (i.e. it's undefined).\n" else: if isinstance(range, unicode): range = range.split("..") if range[0] == "": range[0] = None range = [x for x in range if x] error_message = gv.svalid_range(var_value, range, var_name) if not error_message == "": error_message = grp.sprint_error_report(error_message) BuiltIn().fail(error_message)
[ "gen_robot_print.sprint_error_report", "robot.libraries.BuiltIn.BuiltIn", "gen_valid.svalid_range", "gen_valid.svalid_integer", "gen_valid.svalid_value" ]
[((2546, 2612), 'gen_valid.svalid_value', 'gv.svalid_value', (['var_value', 'invalid_values', 'valid_values', 'var_name'], {}), '(var_value, invalid_values, valid_values, var_name)\n', (2561, 2612), True, 'import gen_valid as gv\n'), ((2709, 2747), 'gen_robot_print.sprint_error_report', 'grp.sprint_error_report', (['error_message'], {}), '(error_message)\n', (2732, 2747), True, 'import gen_robot_print as grp\n'), ((4030, 4068), 'gen_valid.svalid_integer', 'gv.svalid_integer', (['var_value', 'var_name'], {}), '(var_value, var_name)\n', (4047, 4068), True, 'import gen_valid as gv\n'), ((4125, 4163), 'gen_robot_print.sprint_error_report', 'grp.sprint_error_report', (['error_message'], {}), '(error_message)\n', (4148, 4163), True, 'import gen_robot_print as grp\n'), ((6120, 6163), 'gen_valid.svalid_range', 'gv.svalid_range', (['var_value', 'range', 'var_name'], {}), '(var_value, range, var_name)\n', (6135, 6163), True, 'import gen_valid as gv\n'), ((6220, 6258), 'gen_robot_print.sprint_error_report', 'grp.sprint_error_report', (['error_message'], {}), '(error_message)\n', (6243, 6258), True, 'import gen_robot_print as grp\n'), ((2294, 2303), 'robot.libraries.BuiltIn.BuiltIn', 'BuiltIn', ([], {}), '()\n', (2301, 2303), False, 'from robot.libraries.BuiltIn import BuiltIn\n'), ((3778, 3787), 'robot.libraries.BuiltIn.BuiltIn', 'BuiltIn', ([], {}), '()\n', (3785, 3787), False, 'from robot.libraries.BuiltIn import BuiltIn\n'), ((5696, 5705), 'robot.libraries.BuiltIn.BuiltIn', 'BuiltIn', ([], {}), '()\n', (5703, 5705), False, 'from robot.libraries.BuiltIn import BuiltIn\n'), ((2756, 2765), 'robot.libraries.BuiltIn.BuiltIn', 'BuiltIn', ([], {}), '()\n', (2763, 2765), False, 'from robot.libraries.BuiltIn import BuiltIn\n'), ((4172, 4181), 'robot.libraries.BuiltIn.BuiltIn', 'BuiltIn', ([], {}), '()\n', (4179, 4181), False, 'from robot.libraries.BuiltIn import BuiltIn\n'), ((6267, 6276), 'robot.libraries.BuiltIn.BuiltIn', 'BuiltIn', ([], {}), '()\n', (6274, 6276), False, 'from robot.libraries.BuiltIn import BuiltIn\n')]
import cherrypy import os hostIp = "127.0.0.1" portNumber = 1337 class ImpulseServer(object): def get_path(self, data_path): return os.path.dirname(os.path.realpath(__file__)) + os.sep + data_path @cherrypy.expose def index(self): main_path = self.get_path('main.html') with open(main_path, "r") as f: return f.read() conf = { 'global': { 'server.socket_host': hostIp, 'server.socket_port': portNumber, }, '/': { 'tools.sessions.on': True, 'tools.staticdir.root': os.path.abspath(os.getcwd()), 'tools.staticdir.on': True, 'tools.staticdir.dir': ".", } } if __name__ == '__main__': cherrypy.quickstart(ImpulseServer(), '/', conf)
[ "os.path.realpath", "os.getcwd" ]
[((509, 520), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (518, 520), False, 'import os\n'), ((153, 179), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (169, 179), False, 'import os\n')]
# -*- coding: utf-8 -*- import sys import numpy as np import time from utils import print_bracketing, check_dir import argparse import torch import os.path import re import matplotlib import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec class Saver(): """ Handles the saving of checkpoints and collection of data to do so. Generates the savename and directory for each Agent session. PARAMS: prefix - usually the name of the framework of the agent being trained, but could be manually provided if desired. agent - agent to either load or save data to/from. save_dir - this will usually come from a cmdline parser load_file - filename of saved weights to load into the current agent. file_ext - extension to append to saved weights files. Can be any arbitrary string the user desires. """ def __init__(self, prefix, agent, save_dir = 'saves', load_file = None, file_ext = ".agent" ): """ Initialize a Saver object. """ self.file_ext = file_ext self.save_dir, self.filename = self.generate_savename(prefix, save_dir) if load_file: self._load_agent(load_file, agent) else: statement = "Saving to base filename: {}".format(self.filename) print_bracketing(statement) def generate_savename(self, prefix, save_dir): """ Generates an automatic savename for training files, will version-up as needed. """ check_dir(save_dir) timestamp = time.strftime("%Y%m%d", time.localtime()) base_name = "{}_{}_v".format(prefix, timestamp) files = [f for f in os.listdir(save_dir)] files = [f for f in files if base_name in f] if len(files)>0: ver = [int(re.search("_v(\d+)", file).group(1)) for file in files] ver = max(ver) + 1 else: ver = 1 filename = "{}{:03d}".format(base_name, ver) save_dir = os.path.join(save_dir, filename) return save_dir, filename def save_checkpoint(self, agent, save_every): """ Preps a checkpoint save file at intervals controlled by SAVE_EVERY. """ if not agent.episode % save_every == 0: return mssg = "Saving Agent checkpoint to: " save_name = "{}_eps{:04d}_ckpt".format(self.filename, agent.episode) self._save(agent, save_name, mssg) def save_final(self, agent): """ Preps a final savefile after training has finished. """ mssg = "Saved final Agent weights to: " save_name = "{}_eps{:04d}_FINAL".format(self.filename, agent.episode-1) self._save(agent, save_name, mssg) def _save(self, agent, save_name, mssg): """ Does the actual saving bit. """ full_name = os.path.join(self.save_dir, save_name).replace('\\','/') full_name += self.file_ext statement = mssg + full_name print("{0}\n{1}\n{0}".format("#"*len(statement), statement)) check_dir(self.save_dir) torch.save(self._get_save_dict(agent), full_name) def _get_save_dict(self, agent): """ Prep a dictionary of data from the current Agent. """ checkpoint = {'state_size': agent.state_size, 'action_size': agent.action_size, 'actor_dict': agent.actor.state_dict(), 'critic_dict': agent.critic.state_dict() } return checkpoint def _load_agent(self, load_file, agent): """ Loads a checkpoint from an earlier trained agent. """ checkpoint = torch.load(load_file, map_location=lambda storage, loc: storage) agent.actor.load_state_dict(checkpoint['actor_dict']) agent.critic.load_state_dict(checkpoint['critic_dict']) agent._hard_update(agent.actor, agent.actor_target) agent._hard_update(agent.critic, agent.critic_target) statement = "Successfully loaded file: {}".format(load_file) print_bracketing(statement) class Logger: """ Handles logging training data and printing to log files. Creates a graph at the end of training to compare data in a nice format. Log files are stored so the data can also be used elsewhere as needed. Initializing a blank Logger object allows to manually provide a log directory from which to parse data and construct a graph. This is very useful if training is still running but one wants to utilize a Jupyter Notebook to monitor current results. PARAMS: agent - Logger collects the params of both ARGS and AGENT in order to log the training session details. args - Logger collects the params of both ARGS and AGENT in order to log the training session details. save_dir - directory where current session saves are being stored. Logger will create a /logs/ directory here for storing data. log_every - how many timesteps between each logging of losses. Scores are logged every episode. """ def __init__(self, agent=None, args=None, save_dir = '.'): """ Initialize a Logger object. """ if agent==None or args==None: print("Blank init for Logger object.") return self.eval = args.eval self.framework = agent.framework self.max_eps = args.num_episodes self.quietmode = args.quiet self.log_every = args.log_every self.print_every = args.print_every self.agent_count = agent.agent_count self.save_dir = save_dir self.log_dir = os.path.join(self.save_dir, 'logs').replace('\\','/') self.filename = os.path.basename(self.save_dir) self.start_time = self.prev_timestamp = time.time() self.scores = [] self._reset_rewards() if not self.eval: timestamp = time.strftime("%H:%M:%S", time.localtime()) statement = "Starting training at: {}".format(timestamp) print_bracketing(statement) check_dir(self.log_dir) self._init_logs(self._collect_params(args, agent)) @property def latest_score(self): return self.scores[-1] def log(self, rewards, agent): """ After each timestep, keep track of loss and reward data. """ self.rewards += rewards if self.eval: return self.actor_loss = agent.actor_loss self.critic_loss = agent.critic_loss # Writes the loss data to an on-disk logfile every LOG_EVERY timesteps if agent.t_step % self.log_every == 0: self._write_losses() def step(self, eps_num=None, agent=None): """ After each episode, report data on runtime and score. If not in QUIETMODE, then also report the most recent losses. """ self._update_score() self._reset_rewards() if self.eval: print("Score: {}".format(self.latest_score)) return self._write_scores() if eps_num % self.print_every == 0: self._print_status(eps_num, agent) def _print_status(self, eps_num, agent): """ Print status info to the command line. """ leader = "..." # TIME INFORMATION eps_time, total_time, remaining = self._runtime(eps_num) timestamp = time.strftime("%H:%M:%S", time.localtime()) print("\nEp: {}/{} - {} steps - @{}".format(eps_num, self.max_eps, agent.t_step, timestamp)) print("Batch: {}, Total: {}, Est.Remain: {}".format(eps_time, total_time, remaining)) # LOSS INFORMATION if not self.quietmode: print("{}Actor Loss: {:.4f}, Critic Loss: {:.4f}\ ".format(leader, agent.actor_loss, agent.critic_loss)) # SCORE DATA prev_scores = self.scores[-self.print_every:] print("Avg RETURN over previous {} episodes: {:.4f}\n".format( self.print_every, np.array(prev_scores).mean())) def load_logs(self): """ Loads data from on-disk log files, for later manipulation and plotting. """ with open(self.scoresfile, 'r') as f: self.slines = np.array([float(i) for i in f.read().splitlines()]) with open(self.alossfile, 'r') as f: self.alines = np.array([float(i) for i in f.read().splitlines()]) with open(self.clossfile, 'r') as f: self.clines = np.array([float(i) for i in f.read().splitlines()]) with open(self.paramfile, 'r') as f: loglines = f.read().splitlines() # List of the desired params to print on the graph for later review params_to_print = ['max_steps', 'num_episodes', 'c', 'num_atoms', 'vmin', 'vmax', 'e', 'e_decay', 'e_min', 'gamma', 'actor_learn_rate', 'critic_learn_rate', 'buffer_size', 'batch_size', 'pretrain'] sess_params = '' counter = 0 for line in loglines: if line.split(':')[0].lower() in params_to_print: line += ' ' counter += len(line) if counter > 80: sess_params += '\n' counter = 0 sess_params += line self.sess_params = sess_params def _moving_avg(self, data, avg_across): """ Averages a curve, interpolates at boundaries. """ avg_across = int(avg_across) window = np.ones(avg_across)/avg_across data = np.pad(data, avg_across, mode="mean", stat_length=5) return np.convolve(data, window, 'same')[avg_across:-avg_across] def plot_logs(self, save_to_disk=True): """ Plots data in a matplotlib graph for review and comparison. """ score_x = np.linspace(1, len(self.slines), len(self.slines)) actor_x = np.linspace(1, len(self.alines), len(self.alines)) critic_x = np.linspace(1, len(self.clines), len(self.clines)) dtop = 0.85 xcount = 5 bg_color = 0.925 ma100_color = (1, .2, .3) ma200_color = (.38,1,.55) xstep = int(len(self.slines)/xcount) xticks = np.linspace(0, len(self.slines), xcount, dtype=int) a_yticks = np.linspace(min(self.alines), max(self.alines), 5) c_yticks = np.linspace(min(self.clines), max(self.clines), 5) score_window = min(100, len(self.slines)) alines_ratio = len(self.alines)/len(self.slines) clines_ratio = len(self.clines)/len(self.slines) annotate_props = dict(facecolor=(0.1,0.3,0.5), alpha=0.85, edgecolor=(0.2,0.3,0.6), linewidth=2) score_mean = self.slines[-score_window:].mean() score_std = self.slines[-score_window:].std() score_report = "{0}eps MA score: {1:.2f}\n{0}eps STD: {2:.3f}".format( score_window, score_mean, score_std) a_mean = self.alines[-int(score_window*alines_ratio):].mean() a_std = self.alines[-int(score_window*alines_ratio):].std() a_report = "{0}eps MA actor loss: {1:.2f}\n{0}eps STD: {2:.3f}".format( score_window, a_mean, a_std) c_mean = self.clines[-int(score_window*clines_ratio):].mean() c_std = self.clines[-int(score_window*clines_ratio):].std() c_report = "{0}eps MA critic loss: {1:.2f}\n{0}eps STD: {2:.3f}".format( score_window, c_mean, c_std) fig = plt.figure(figsize=(20,10)) gs = GridSpec(2, 2, hspace=.5, wspace=.2, top=dtop-0.08) ax1 = fig.add_subplot(gs[:,0]) ax2 = fig.add_subplot(gs[0,1]) ax3 = fig.add_subplot(gs[1,1]) gs2 = GridSpec(1,1, bottom=dtop-0.01, top=dtop) dummyax = fig.add_subplot(gs2[0,0]) # Plot unfiltered scores ax1.plot(score_x, self.slines) # Plot 200MA line ax1.plot(score_x, self._moving_avg(self.slines, score_window*2), color=ma200_color, lw=3, label="{}eps MA".format(score_window*2)) # Plot 100MA line ax1.plot(score_x, self._moving_avg(self.slines, score_window), color=ma100_color, lw=2, label="{}eps MA".format(score_window)) ax1.set_title("Scores") ax1.set_xlabel("Episode") ax1.set_ylabel("Score") ax1.set_facecolor((bg_color, bg_color, bg_color)) ax1.grid() ax1.legend(loc="upper left", markerscale=2.5, fontsize=15) ax1.axvspan(score_x[-score_window], score_x[-1], color=(0.1,0.4,0.1), alpha=0.25) ax1.annotate(score_report, xy=(1,1), xycoords="figure points", xytext=(0.925,0.05), textcoords="axes fraction", horizontalalignment="right", size=20, color='white', bbox = annotate_props) # Plot unfiltered actor loss data ax2.plot(actor_x, self.alines) # Plot 200MA line ax2.plot(actor_x, self._moving_avg(self.alines, score_window*2*alines_ratio), color=ma200_color, lw=3, label="{}eps MA".format(score_window*2)) # Plot 100MA line ax2.plot(actor_x, self._moving_avg(self.alines, score_window*alines_ratio), color=ma100_color, lw=2, label="{}eps MA".format(score_window)) ax2.set_xticks(np.linspace(0, len(self.alines), xcount)) ax2.set_xticklabels(xticks) ax2.set_yticks(a_yticks) ax2.set_title("Actor Loss") ax2.set_ylabel("Loss", labelpad=10) ax2.set_facecolor((bg_color, bg_color, bg_color)) ax2.grid() ax2.legend(loc="upper left", markerscale=1.5, fontsize=12) ax2.axvspan(actor_x[-int(score_window*alines_ratio)], actor_x[-1], color=(0.1,0.4,0.1), alpha=0.25) ax2.annotate(a_report, xy=(0,0), xycoords="figure points", xytext=(.935,.79), textcoords="axes fraction", horizontalalignment="right", size=14, color='white', bbox = annotate_props) # Plot unfiltered critic loss data ax3.plot(critic_x, self.clines) # Plot 200MA line ax3.plot(critic_x, self._moving_avg(self.clines, score_window*2*clines_ratio), color=ma200_color, lw=3, label="{}eps MA".format(score_window*2)) # Plot 100MA line ax3.plot(critic_x, self._moving_avg(self.clines, score_window*clines_ratio), color=ma100_color, lw=2, label="{}eps MA".format(score_window)) ax3.set_xticks(np.linspace(0, len(self.alines), xcount)) ax3.set_xticklabels(xticks) ax3.set_yticks(c_yticks) ax3.set_title("Critic Loss") ax3.set_ylabel("Loss", labelpad=20) ax3.set_facecolor((bg_color, bg_color, bg_color)) ax3.grid() ax3.legend(loc="upper left", markerscale=1.5, fontsize=12) ax3.axvspan(critic_x[-int(score_window*clines_ratio)], critic_x[-1], color=(0.1,0.4,0.1), alpha=0.25) ax3.annotate(c_report, xy=(0,0), xycoords="figure points", xytext=(0.935,0.79), textcoords="axes fraction", horizontalalignment="right", size=14, color='white', bbox = annotate_props) dummyax.set_title(self.sess_params, size=13) dummyax.axis("off") fig.suptitle("{} Training Run".format(self.framework), size=40) if save_to_disk: save_file = os.path.join(self.save_dir, self.filename+"_graph.png") fig.savefig(save_file) statement = "Saved graph data to: {}".format(save_file).replace("\\", "/") print("{0}\n{1}\n{0}".format("#"*len(statement), statement)) else: fig.show() def graph(self, logdir=None, save_to_disk=True): """ Preps filepaths and then loads data from on-disk logs. Then graphs them for review. If SAVE_TO_DISK is False, then a graph will be popped up but not saved. Default is to save to disk and not do a pop-up. """ if logdir != None: self.log_dir = logdir self.filename = os.path.basename(logdir) for f in os.listdir(self.log_dir): f = os.path.join(self.log_dir,f) if f.endswith("_LOG.txt"): self.paramfile = f if f.endswith("_actorloss.txt"): self.alossfile = f if f.endswith("_criticloss.txt"): self.clossfile = f if f.endswith("_scores.txt"): self.scoresfile = f self.load_logs() self.plot_logs(save_to_disk) def _init_logs(self, params): """ Outputs an initial log of all parameters provided as a list. """ basename = os.path.join(self.log_dir, self.filename) self.paramfile = basename + "_LOG.txt" self.alossfile = basename + "_actorloss.txt" self.clossfile = basename + "_criticloss.txt" self.scoresfile = basename + "_scores.txt" # Create the log files. Params is filled on creation, the others are # initialized blank and filled as training proceeds. files = [self.paramfile, self.alossfile, self.clossfile, self.scoresfile] log_statement = ["Logfiles saved to: {}".format(self.log_dir)] for filename in files: with open(filename, 'w') as f: if filename.endswith("_LOG.txt"): for line in params: f.write(line + '\n') else: pass log_statement.append("...{}".format(os.path.basename(filename))) print_bracketing(log_statement) def _collect_params(self, args, agent): """ Creates a list of all the Params used to run this training instance, prints this list to the command line if QUIET is not flagged, and stores it for later saving to the params log in the /logs/ directory. """ param_dict = {key:getattr(args, key) for key in vars(args)} for key in vars(agent): param_dict[key.lstrip('_')] = getattr(agent, key) param_dict.pop('nographics', None) param_dict.pop('save_every', None) param_dict.pop('print_every', None) param_dict.pop('verbose', None) param_dict.pop('quiet', None) param_dict.pop('latest', None) param_dict.pop('save_every', None) param_dict.pop('avg_score', None) param_dict.pop('episode', None) param_dict.pop('t_step', None) if param_dict['update_type'] == 'soft': param_dict.pop('C', None) else: param_dict.pop('tau', None) param_list = ["{}: {}".format(key, value) for (key, value) in param_dict.items()] print_bracketing(param_list) return param_list def _format_param(self, arg, args): """ Formats into PARAM: VALUE for reporting. Strips leading underscores for placeholder params where @properties are used for the real value. """ return "{}: {}".format(arg.upper().lstrip("_"), getattr(args, arg)) def _runtime(self, eps_num): """ Return the time since the previous episode, as well as total time for the training session. """ current_time = time.time() projected_end = (self.max_eps / eps_num) * (current_time - self.start_time) + self.start_time eps_time = self._format_time(current_time, self.prev_timestamp) total_time = self._format_time(current_time, self.start_time) remaining = self._format_time(projected_end, current_time) self.prev_timestamp = current_time return eps_time, total_time, remaining def _format_time(self, current, previous): """ Formats time difference into Hours, Minutes, Seconds. """ m, s = divmod(current - previous, 60) h, m = divmod(m, 60) time = "" if h != 0: time += "{}h".format(int(h)) if m != 0: time += "{}m".format(int(m)) time += "{}s".format(int(s)) return time def _update_score(self): """ Calculates the average reward for the previous episode, prints to the cmdline, and then saves to the logfile. """ score = self.rewards.mean() self.scores.append(score) # print("{}Return: {}".format("."*10, score)) # if not self.eval: # self._write_scores(score) # if self.quietmode: # return # print("A LOSS: ", self.actor_loss) # print("C LOSS: ", self.critic_loss) def _write_losses(self): """ Writes actor/critic loss data to file. """ with open(self.alossfile, 'a') as f: f.write(str(self.actor_loss) + '\n') with open(self.clossfile, 'a') as f: f.write(str(self.critic_loss) + '\n') def _write_scores(self): """ Writes score data to file. """ with open(self.scoresfile, 'a') as f: f.write(str(self.latest_score) + '\n') def _reset_rewards(self): """ Resets the REWARDS matrix to zero for starting an episode. """ self.rewards = np.zeros(self.agent_count) def gather_args(manual_args=None): """ Generate arguments passed from the command line. """ parser = argparse.ArgumentParser(description="Continuous control environment for \ Udacity DeepRL course.", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("-alr", "--actor_learn_rate", help="Actor Learning Rate.", type=float, default=0.0005) parser.add_argument("-clr", "--critic_learn_rate", help="Critic Learning Rate.", type=float, default=0.001) parser.add_argument("-bs", "--batch_size", help="Size of each batch between learning updates", type=int, default=128) parser.add_argument("-buffer", "--buffer_size", help="How many past timesteps to keep in memory.", type=int, default=300000) parser.add_argument("-C", "--C", help="How many timesteps between hard network updates.", type=int, default=350) parser.add_argument("-layers", "--layer_sizes", help="The size of the hidden layers for the networks (Actor/Critic \ currently use the same network sizes).", nargs="+", type=int, default=[400,300]) parser.add_argument("-cpu", "--cpu", help="Run training on the CPU instead of the default (GPU).", action="store_true") parser.add_argument("-e", "--e", help="Noisey exploration rate.", type=float, default=0.3) parser.add_argument("-vmin", "--vmin", help="Min value of reward projection.", type=float, default=0.0) parser.add_argument("-vmax", "--vmax", help="Max value of reward projection.", type=float, default=0.3) parser.add_argument("-atoms", "--num_atoms", help="Number of atoms to project categorically.", type=int, default=100) parser.add_argument("-eval", "--eval", help="Run in evalutation mode. Otherwise, will utilize \ training mode. In default EVAL mode, NUM_EPISODES is set \ to 1 and MAX_STEPS to 1000.", action="store_true") parser.add_argument("-feval", "--force_eval", help="Force evaluation mode to run with specified NUM_EPISODES \ and MAX_STEPS param.", action="store_true") parser.add_argument("-gamma", help="Gamma (Discount rate).", type=float, default=0.99) parser.add_argument("-max", "--max_steps", help="How many timesteps to explore each episode, if a \ Terminal state is not reached first", type=int, default=1000) parser.add_argument("-ng", "--nographics", help="Run Unity environment without graphics displayed.", action="store_true") parser.add_argument("-num", "--num_episodes", help="How many episodes to train?", type=int, default=225) parser.add_argument("-pre", "--pretrain", help="How many trajectories to randomly sample into the \ ReplayBuffer before training begins.", type=int, default=5000) parser.add_argument("--quiet", help="Print less while running the agent.", action="store_true") parser.add_argument("--resume", help="Resume training from a checkpoint.", action="store_true") parser.add_argument("-roll", "--rollout", help="How many experiences to use in N-Step returns", type=int, default=5) parser.add_argument("-se", "--save_every", help="How many episodes between saves.", type=int, default=10) parser.add_argument("-le", "--log_every", help="How many timesteps between writing a log step.", type=int, default=50) parser.add_argument("-pe", "--print_every", help="How many episodes between status printouts.", type=int, default=3) parser.add_argument("-t", "--tau", help="Soft network update weighting.", type=float, default=0.0005) parser.add_argument("--latest", help="Use this flag to automatically use the latest save file \ to run in DEMO mode (instead of choosing from a prompt).", action="store_true") parser.add_argument("-file", "--filename", help="Path agent weights file to load. ", type=str, default=None) parser.add_argument("-savedir", "--save_dir", help="Directory to find saved agent weights.", type=str, default="saves") args = parser.parse_args(manual_args) ############################################################################ # PROCESS ARGS AFTER COMMAND LINE GATHERING # # Pretrain length can't be less than batch_size assert args.pretrain >= args.batch_size, "PRETRAIN less than BATCHSIZE." # Use GPU (if available) unless user specifically asks to use CPU if not args.cpu and torch.cuda.is_available(): args.device = torch.device("cuda:0") else: args.device = torch.device("cpu") # Limit the length of evaluation runs unless user forces cmdline args if args.eval and not args.force_eval: args.num_episodes = 1 args.max_steps = 1000 # To avoid redundant code checks elsewhere, EVAL should be set to True if # FORCE_EVAL is flagged if args.force_eval: args.eval = True # Determine whether to load a file, and if so, set the filename args.load_file = _get_agent_file(args) return args def _get_agent_file(args): """ Checks to see what sort of loading, if any, to do. Returns one of: -FILENAME... if flagged with a specific filename on the cmdline -LASTEST FILE... if flagged to load the most recently saved weights -USER FILE... a user selected file from a list prompt -FALSE... if no loading is needed, return false and skip loading """ invalid_filename = "Requested filename is invalid." no_files_found = "Could not find any files in: {}".format(args.save_dir) if args.resume or args.eval: if args.filename is not None: assert os.path.isfile(args.filename), invalid_filename return args.filename files = _get_files(args.save_dir) assert len(files) > 0, no_files_found if args.latest: return files[-1] else: return _get_filepath(files) else: return False def _get_files(save_dir): """ Returns a list of files in a given directory, sorted by last-modified. """ file_list = [] for root, _, files in os.walk(save_dir): for file in files: if file.endswith(".agent"): file_list.append(os.path.join(root, file)) return sorted(file_list, key=lambda x: os.path.getmtime(x)) def _get_filepath(files): """ Prompts the user about what save to load, or uses the last modified save. """ load_file_prompt = " (LATEST)\n\nPlease choose a saved Agent training file (or: q/quit): " user_quit_message = "User quit process before loading a file." message = ["{}. {}".format(len(files)-i, file) for i, file in enumerate(files)] message = '\n'.join(message).replace('\\', '/') message = message + load_file_prompt save_file = input(message) if save_file.lower() in ("q", "quit"): raise KeyboardInterrupt(user_quit_message) try: file_index = len(files) - int(save_file) assert file_index >= 0 return files[file_index] except: print_bracketing('Input "{}" is INVALID...'.format(save_file)) return _get_filepath(files)
[ "time.localtime", "re.search", "numpy.convolve", "numpy.ones", "argparse.ArgumentParser", "torch.load", "numpy.array", "matplotlib.pyplot.figure", "matplotlib.gridspec.GridSpec", "numpy.zeros", "torch.cuda.is_available", "time.time", "numpy.pad", "utils.check_dir", "utils.print_bracketin...
[((21619, 21792), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Continuous control environment for Udacity DeepRL course."""', 'formatter_class': 'argparse.ArgumentDefaultsHelpFormatter'}), "(description=\n 'Continuous control environment for Udacity DeepRL course.',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n", (21642, 21792), False, 'import argparse\n'), ((1635, 1654), 'utils.check_dir', 'check_dir', (['save_dir'], {}), '(save_dir)\n', (1644, 1654), False, 'from utils import print_bracketing, check_dir\n'), ((3193, 3217), 'utils.check_dir', 'check_dir', (['self.save_dir'], {}), '(self.save_dir)\n', (3202, 3217), False, 'from utils import print_bracketing, check_dir\n'), ((3832, 3896), 'torch.load', 'torch.load', (['load_file'], {'map_location': '(lambda storage, loc: storage)'}), '(load_file, map_location=lambda storage, loc: storage)\n', (3842, 3896), False, 'import torch\n'), ((4222, 4249), 'utils.print_bracketing', 'print_bracketing', (['statement'], {}), '(statement)\n', (4238, 4249), False, 'from utils import print_bracketing, check_dir\n'), ((6021, 6032), 'time.time', 'time.time', ([], {}), '()\n', (6030, 6032), False, 'import time\n'), ((9813, 9865), 'numpy.pad', 'np.pad', (['data', 'avg_across'], {'mode': '"""mean"""', 'stat_length': '(5)'}), "(data, avg_across, mode='mean', stat_length=5)\n", (9819, 9865), True, 'import numpy as np\n'), ((11728, 11756), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(20, 10)'}), '(figsize=(20, 10))\n', (11738, 11756), True, 'import matplotlib.pyplot as plt\n'), ((11769, 11824), 'matplotlib.gridspec.GridSpec', 'GridSpec', (['(2)', '(2)'], {'hspace': '(0.5)', 'wspace': '(0.2)', 'top': '(dtop - 0.08)'}), '(2, 2, hspace=0.5, wspace=0.2, top=dtop - 0.08)\n', (11777, 11824), False, 'from matplotlib.gridspec import GridSpec\n'), ((11952, 11996), 'matplotlib.gridspec.GridSpec', 'GridSpec', (['(1)', '(1)'], {'bottom': '(dtop - 0.01)', 'top': 'dtop'}), '(1, 1, bottom=dtop - 0.01, top=dtop)\n', (11960, 11996), False, 'from matplotlib.gridspec import GridSpec\n'), ((17814, 17845), 'utils.print_bracketing', 'print_bracketing', (['log_statement'], {}), '(log_statement)\n', (17830, 17845), False, 'from utils import print_bracketing, check_dir\n'), ((18957, 18985), 'utils.print_bracketing', 'print_bracketing', (['param_list'], {}), '(param_list)\n', (18973, 18985), False, 'from utils import print_bracketing, check_dir\n'), ((19499, 19510), 'time.time', 'time.time', ([], {}), '()\n', (19508, 19510), False, 'import time\n'), ((21472, 21498), 'numpy.zeros', 'np.zeros', (['self.agent_count'], {}), '(self.agent_count)\n', (21480, 21498), True, 'import numpy as np\n'), ((26860, 26885), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (26883, 26885), False, 'import torch\n'), ((26909, 26931), 'torch.device', 'torch.device', (['"""cuda:0"""'], {}), "('cuda:0')\n", (26921, 26931), False, 'import torch\n'), ((26964, 26983), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (26976, 26983), False, 'import torch\n'), ((1419, 1446), 'utils.print_bracketing', 'print_bracketing', (['statement'], {}), '(statement)\n', (1435, 1446), False, 'from utils import print_bracketing, check_dir\n'), ((1699, 1715), 'time.localtime', 'time.localtime', ([], {}), '()\n', (1713, 1715), False, 'import time\n'), ((6265, 6292), 'utils.print_bracketing', 'print_bracketing', (['statement'], {}), '(statement)\n', (6281, 6292), False, 'from utils import print_bracketing, check_dir\n'), ((6306, 6329), 'utils.check_dir', 'check_dir', (['self.log_dir'], {}), '(self.log_dir)\n', (6315, 6329), False, 'from utils import print_bracketing, check_dir\n'), ((7676, 7692), 'time.localtime', 'time.localtime', ([], {}), '()\n', (7690, 7692), False, 'import time\n'), ((9767, 9786), 'numpy.ones', 'np.ones', (['avg_across'], {}), '(avg_across)\n', (9774, 9786), True, 'import numpy as np\n'), ((9881, 9914), 'numpy.convolve', 'np.convolve', (['data', 'window', '"""same"""'], {}), "(data, window, 'same')\n", (9892, 9914), True, 'import numpy as np\n'), ((6166, 6182), 'time.localtime', 'time.localtime', ([], {}), '()\n', (6180, 6182), False, 'import time\n'), ((8262, 8283), 'numpy.array', 'np.array', (['prev_scores'], {}), '(prev_scores)\n', (8270, 8283), True, 'import numpy as np\n'), ((1924, 1951), 're.search', 're.search', (['"""_v(\\\\d+)"""', 'file'], {}), "('_v(\\\\d+)', file)\n", (1933, 1951), False, 'import re\n')]
import json from unittest.mock import ANY, MagicMock, call, patch from pinga.events.consumer import Consumer @patch("pinga.events.consumer.get_db_conn") @patch("pinga.events.consumer.save_event") @patch("pinga.events.consumer.get_logger") @patch( "pinga.events.consumer.KafkaConsumer", return_value=[ MagicMock(value=b"hello"), MagicMock(value=b"world"), MagicMock(value=b"") ] ) def test_consumer_consume_invalid_events(mock_kafka, mock_logger, mock_save, mock_db_conn): consumer = Consumer() consumer.consume() mock_logger().error.assert_has_calls([ call("Received invalid message: 'hello', skipping"), call("Received invalid message: 'world', skipping"), call("Received invalid message: '', skipping") ]) mock_save.assert_not_called() @patch("pinga.events.consumer.get_db_conn") @patch("pinga.events.consumer.save_event") @patch("pinga.events.consumer.KafkaConsumer") def test_consumer_consume_happy_path(mock_kafka, mock_save, mock_db_conn): event_1 = { "url": "http://example.org/404", "status": "down", "httpStatus": 404, "responseTimeSeconds": 0.160735 } event_2 = { "url": "a.a", "status": "error", "errorMessage": "some error" } mock_kafka.return_value = [ MagicMock(value=json.dumps(event_1).encode("utf-8")), MagicMock(value=json.dumps(event_2).encode("utf-8")) ] consumer = Consumer() consumer.consume() mock_save.assert_has_calls([call(ANY, event_1), call(ANY, event_2)]) @patch("pinga.events.consumer.get_db_conn") @patch("pinga.events.consumer.create_events_table") @patch("pinga.events.consumer.KafkaConsumer") def test_consumer_table_created(mock_kafka, mock_create_table, mock_db_conn): _ = Consumer() mock_create_table.assert_called_once_with(mock_db_conn())
[ "pinga.events.consumer.Consumer", "unittest.mock.MagicMock", "unittest.mock.call", "json.dumps", "unittest.mock.patch" ]
[((113, 155), 'unittest.mock.patch', 'patch', (['"""pinga.events.consumer.get_db_conn"""'], {}), "('pinga.events.consumer.get_db_conn')\n", (118, 155), False, 'from unittest.mock import ANY, MagicMock, call, patch\n'), ((157, 198), 'unittest.mock.patch', 'patch', (['"""pinga.events.consumer.save_event"""'], {}), "('pinga.events.consumer.save_event')\n", (162, 198), False, 'from unittest.mock import ANY, MagicMock, call, patch\n'), ((200, 241), 'unittest.mock.patch', 'patch', (['"""pinga.events.consumer.get_logger"""'], {}), "('pinga.events.consumer.get_logger')\n", (205, 241), False, 'from unittest.mock import ANY, MagicMock, call, patch\n'), ((825, 867), 'unittest.mock.patch', 'patch', (['"""pinga.events.consumer.get_db_conn"""'], {}), "('pinga.events.consumer.get_db_conn')\n", (830, 867), False, 'from unittest.mock import ANY, MagicMock, call, patch\n'), ((869, 910), 'unittest.mock.patch', 'patch', (['"""pinga.events.consumer.save_event"""'], {}), "('pinga.events.consumer.save_event')\n", (874, 910), False, 'from unittest.mock import ANY, MagicMock, call, patch\n'), ((912, 956), 'unittest.mock.patch', 'patch', (['"""pinga.events.consumer.KafkaConsumer"""'], {}), "('pinga.events.consumer.KafkaConsumer')\n", (917, 956), False, 'from unittest.mock import ANY, MagicMock, call, patch\n'), ((1584, 1626), 'unittest.mock.patch', 'patch', (['"""pinga.events.consumer.get_db_conn"""'], {}), "('pinga.events.consumer.get_db_conn')\n", (1589, 1626), False, 'from unittest.mock import ANY, MagicMock, call, patch\n'), ((1628, 1678), 'unittest.mock.patch', 'patch', (['"""pinga.events.consumer.create_events_table"""'], {}), "('pinga.events.consumer.create_events_table')\n", (1633, 1678), False, 'from unittest.mock import ANY, MagicMock, call, patch\n'), ((1680, 1724), 'unittest.mock.patch', 'patch', (['"""pinga.events.consumer.KafkaConsumer"""'], {}), "('pinga.events.consumer.KafkaConsumer')\n", (1685, 1724), False, 'from unittest.mock import ANY, MagicMock, call, patch\n'), ((526, 536), 'pinga.events.consumer.Consumer', 'Consumer', ([], {}), '()\n', (534, 536), False, 'from pinga.events.consumer import Consumer\n'), ((1473, 1483), 'pinga.events.consumer.Consumer', 'Consumer', ([], {}), '()\n', (1481, 1483), False, 'from pinga.events.consumer import Consumer\n'), ((1811, 1821), 'pinga.events.consumer.Consumer', 'Consumer', ([], {}), '()\n', (1819, 1821), False, 'from pinga.events.consumer import Consumer\n'), ((612, 663), 'unittest.mock.call', 'call', (['"""Received invalid message: \'hello\', skipping"""'], {}), '("Received invalid message: \'hello\', skipping")\n', (616, 663), False, 'from unittest.mock import ANY, MagicMock, call, patch\n'), ((673, 724), 'unittest.mock.call', 'call', (['"""Received invalid message: \'world\', skipping"""'], {}), '("Received invalid message: \'world\', skipping")\n', (677, 724), False, 'from unittest.mock import ANY, MagicMock, call, patch\n'), ((734, 780), 'unittest.mock.call', 'call', (['"""Received invalid message: \'\', skipping"""'], {}), '("Received invalid message: \'\', skipping")\n', (738, 780), False, 'from unittest.mock import ANY, MagicMock, call, patch\n'), ((320, 345), 'unittest.mock.MagicMock', 'MagicMock', ([], {'value': "b'hello'"}), "(value=b'hello')\n", (329, 345), False, 'from unittest.mock import ANY, MagicMock, call, patch\n'), ((355, 380), 'unittest.mock.MagicMock', 'MagicMock', ([], {'value': "b'world'"}), "(value=b'world')\n", (364, 380), False, 'from unittest.mock import ANY, MagicMock, call, patch\n'), ((390, 410), 'unittest.mock.MagicMock', 'MagicMock', ([], {'value': "b''"}), "(value=b'')\n", (399, 410), False, 'from unittest.mock import ANY, MagicMock, call, patch\n'), ((1540, 1558), 'unittest.mock.call', 'call', (['ANY', 'event_1'], {}), '(ANY, event_1)\n', (1544, 1558), False, 'from unittest.mock import ANY, MagicMock, call, patch\n'), ((1560, 1578), 'unittest.mock.call', 'call', (['ANY', 'event_2'], {}), '(ANY, event_2)\n', (1564, 1578), False, 'from unittest.mock import ANY, MagicMock, call, patch\n'), ((1352, 1371), 'json.dumps', 'json.dumps', (['event_1'], {}), '(event_1)\n', (1362, 1371), False, 'import json\n'), ((1414, 1433), 'json.dumps', 'json.dumps', (['event_2'], {}), '(event_2)\n', (1424, 1433), False, 'import json\n')]
from PySide6.QtCore import Qt, QThread, Signal, QPoint, QRect, QLocale, QTranslator, QCoreApplication, QThreadPool, \ QObject, QRunnable from PySide6.QtGui import QCursor, QPixmap, QIcon, QFont from PySide6.QtWidgets import QApplication, QMessageBox from gui_about import Ui_AboutWindow from gui_main import Ui_MainWindow from os.path import getsize, join from packaging import version import webbrowser import subprocess import requests import img_res # skipcq: PYL-W0611 import json import sys import os __version__ = "1.11.0" def resource_path(relative_path): """Determine resource path if app is built or run natively.""" if hasattr(sys, 'frozen'): return os.path.join(sys._MEIPASS, relative_path) # skipcq: PYL-W0212 return os.path.join(os.path.abspath('.'), relative_path) def get_dir_size(dir_path): """Get directory size of installed apps.""" dir_size = 0 for root, _, files in os.walk(dir_path): dir_size += sum([getsize(join(root, name)) for name in files]) return dir_size class Logic(): def __init__(self): about.label_version.setText(QCoreApplication.translate("Label", "Version") + f" {__version__}") self.total_size = 0 self.is_link_menu = False self.main_title = QCoreApplication.translate("Label", "Select the default Windows 10 apps to uninstall:\n(Hover over app names to view description)") self.store_title = QCoreApplication.translate("Label", "Click on an app name to view it in Microsoft Store.") self.refresh_title = QCoreApplication.translate("Label", "Refreshing list of installed apps...") self.size_text = QCoreApplication.translate("Label", "MB") self.github_dialog = QCoreApplication.translate("MessageBox", "Visit the PyDebloatX GitHub page?") self.quit_dialog = QCoreApplication.translate("MessageBox", "Quit PyDebloatX?") self.dialog_yes = QCoreApplication.translate("Button", "Yes") self.dialog_no = QCoreApplication.translate("Button", "No") self.dialog_ok = QCoreApplication.translate("Button", "OK") self.success_text = QCoreApplication.translate("MessageBox", "All selected apps were successfully uninstalled.") self.main_widgets = (ui.refresh_btn, ui.refresh_bind, ui.store_btn, ui.store_bind, ui.button_select_all, ui.button_deselect_all, ui.button_uninstall) self.apps_dict = ui.apps_dict ui.progressbar.setValue(0) ui.progressbar.setMaximum(len(self.apps_dict)) ui.progressbar.setFont(ui.font) ui.layout_widget_labels.adjustSize() for layout in (ui.layout_checkboxes, ui.layout_checkboxes_2, ui.layout_checkboxes_3): layout.addStretch() layout.setSpacing(14) for layout_widget in (ui.layout_widget_checkboxes, ui.layout_widget_checkboxes_2, ui.layout_widget_checkboxes_3): layout_widget.adjustSize() ui.button_uninstall.clicked.connect(self.uninstall) ui.button_select_all.clicked.connect(self.select_all) ui.button_deselect_all.clicked.connect(self.deselect_all) ui.refresh_btn.clicked.connect(self.app_refresh) ui.refresh_bind.activated.connect(self.app_refresh) ui.store_btn.clicked.connect(self.store_menu) ui.store_bind.activated.connect(self.store_menu) ui.homepage_btn.clicked.connect(self.app_homepage) ui.homepage_bind.activated.connect(self.app_homepage) ui.about_btn.clicked.connect(self.app_about) ui.about_bind.activated.connect(self.app_about) ui.quit_btn.clicked.connect(self.app_quit) ui.quit_bind.activated.connect(self.app_quit) about.button_quit_about.clicked.connect(about.close) for checkbox in ui.checkbox_list: checkbox.clicked.connect(self.enable_buttons) self.app_refresh() self.check_updates() def store_menu(self): """Toggle between Main view and Store view.""" widgets = (ui.layout_widget_buttons, ui.label_space, ui.label_size) if self.is_link_menu: self.is_link_menu = False ui.label_info.setText(self.main_title) ui.store_btn.setIcon(QIcon(':/icon/store_icon.png')) for i in self.apps_dict: i.setEnabled(False) i.setChecked(False) for i in self.installed_apps: i.setEnabled(True) for i in self.selected_apps: i.setChecked(True) self.enable_buttons() for widget in widgets: widget.show() else: self.is_link_menu = True ui.label_info.setText(self.store_title) ui.store_btn.setIcon(QIcon(':/icon/back_icon.png')) for i in self.apps_dict: i.setEnabled(True) i.setChecked(True) for widget in widgets: widget.hide() def check_updates(self): """Check for updates.""" self.check_updates_thread = CheckUpdates() self.check_updates_thread.version_signal.connect(self.show_updates) self.check_updates_thread.start() def show_updates(self, latest_version): """Show updates.""" if version.parse(latest_version) > version.parse(__version__): msg_update = QCoreApplication.translate("MessageBox", "PyDebloatX {0} is available.\n\nVisit download page?").format(latest_version) if self.message_box(msg_update, 2) == QMessageBox.Yes: webbrowser.open_new('https://github.com/Teraskull/PyDebloatX/releases') def app_refresh(self): """Create threads to refresh list of installed apps.""" if self.is_link_menu: self.store_menu() self.installed_apps = [] self.progress = 0 for i in self.apps_dict: i.setEnabled(False) i.setChecked(False) ui.label_refresh.show() ui.label_info.hide() ui.progressbar.show() for widget in self.main_widgets: widget.setEnabled(False) QApplication.setOverrideCursor(QCursor(Qt.BusyCursor)) ui.label_refresh.setText(self.refresh_title) self.check_thread = CheckApps(self.apps_dict) self.check_thread.app_signal.connect(self.enable_installed) self.check_thread.progress_signal.connect(self.update_progress) self.check_thread.start() def thread_finished(self): """Set up Main view after finishing a task.""" ui.progressbar.hide() ui.label_refresh.hide() ui.label_info.show() ui.progressbar.setValue(0) QApplication.setOverrideCursor(QCursor()) ui.label_info.setText(self.main_title) for widget in (ui.refresh_btn, ui.refresh_bind, ui.store_btn, ui.store_bind): widget.setEnabled(True) self.enable_buttons() def enable_installed(self, i): """Enable checkboxes while refreshing list of installed apps.""" i.setEnabled(True) self.installed_apps.append(i) self.enable_buttons() def update_progress(self): """Update progress bar while refreshing list of installed apps.""" self.progress += 1 ui.progressbar.setValue(self.progress) if self.progress >= len(self.apps_dict): self.thread_finished() def uninstall_progress(self, i): """Update progress bar and label while uninstalling selected apps.""" self.progress += 1 ui.progressbar.setValue(self.progress) self.installed_apps.remove(i) app_name = i.text().replace(' && ', ' & ') apps_left = len(self.selected_apps) - self.progress + 1 ui.label_refresh.setText(QCoreApplication.translate("Label", "Uninstalling {0}, %n app(s) left...", "", apps_left).format(app_name)) ui.label_refresh.show() if self.progress >= len(self.selected_apps): self.thread_finished() self.message_box(self.success_text) def enable_buttons(self): """Enable buttons or open Microsoft Store when clicking checkboxes.""" if not self.is_link_menu: self.total_size = 0 self.selected_apps = [] for i in self.installed_apps: if i.isChecked(): self.selected_apps.append(i) self.total_size += self.apps_dict[i]["size"] ui.label_size.setText(f'{self.total_size:.2f} {self.size_text}') ui.layout_widget_labels.adjustSize() if any(i.isChecked() for i in self.installed_apps): ui.button_uninstall.setDisabled(False) ui.button_deselect_all.setDisabled(False) else: ui.button_uninstall.setDisabled(True) ui.button_deselect_all.setDisabled(True) ui.label_size.setText(f'{self.total_size} {self.size_text}') if all(i.isChecked() for i in self.installed_apps): ui.button_select_all.setDisabled(True) else: ui.button_select_all.setDisabled(False) else: for i in self.apps_dict: if not i.isChecked(): i.setChecked(True) webbrowser.open_new(f'ms-windows-store://pdp{self.apps_dict[i]["link"]}') def message_box(self, message: str, buttons: int = 1) -> int: ''' Message box with "Yes/No" or "OK" buttons. Defaults to "OK".\n Parameters:\n message (str): Message shown inside the message box. buttons (int): Amount of buttons, 1 - "OK" button, 2 - "Yes/No" buttons. Returns:\n choice (int): ID of the clicked button. ''' pixmap = QPixmap(resource_path('icon.ico')).scaledToWidth(35, Qt.SmoothTransformation) msg_box = QMessageBox() msg_box.setFont(ui.font) msg_box.setText(message) if buttons == 2: msg_yes = msg_box.addButton(QMessageBox.Yes) msg_no = msg_box.addButton(QMessageBox.No) msg_yes.setText(self.dialog_yes) msg_no.setText(self.dialog_no) msg_yes.setProperty('class', 'button_yes') msg_no.setProperty('class', 'button_no') msg_box.setWindowFlags(Qt.Dialog | Qt.CustomizeWindowHint) msg_box.setIconPixmap(pixmap) with open(resource_path('style.css'), 'r') as file: msg_box.setStyleSheet(file.read()) msg_box.move(ui.frameGeometry().center() - QRect(QPoint(), msg_box.sizeHint()).center()) choice = msg_box.exec_() return choice def app_homepage(self): """Open GitHub app homepage after confirmation.""" if self.message_box(self.github_dialog, 2) == QMessageBox.Yes: webbrowser.open_new('https://github.com/Teraskull/PyDebloatX') @staticmethod def app_about(): """Show 'About' window.""" about.setWindowModality(Qt.ApplicationModal) about.move(ui.geometry().center() - about.rect().center()) about.show() def app_quit(self): """Quit app after confirmation.""" if self.message_box(self.quit_dialog, 2) == QMessageBox.Yes: app.quit() def select_all(self): """Select all checkboxes for installed apps.""" for i in self.installed_apps: if not i.isChecked(): i.setChecked(True) self.enable_buttons() def deselect_all(self): """Deselect all checkboxes for installed apps.""" for i in self.installed_apps: if i.isChecked(): i.setChecked(False) self.enable_buttons() def uninstall(self): """Create threads to uninstall selected apps after confirmation.""" apps = len(self.selected_apps) confirm_uninstall = QCoreApplication.translate("MessageBox", "Uninstall %n app(s)?", "", apps) space_freed_text = QCoreApplication.translate("MessageBox", "MB of space will be freed.") msg_uninstall = f"{confirm_uninstall}\n\n{self.total_size:.2f} {space_freed_text}" if self.message_box(msg_uninstall, 2) == QMessageBox.Yes: for widget in self.main_widgets: widget.setEnabled(False) ui.label_info.hide() self.progress = 0 ui.progressbar.setMaximum(apps) ui.progressbar.show() self.new_thread_list = [] for item, i in enumerate(self.selected_apps): i.setEnabled(False) i.setChecked(False) self.new_thread_list.append(UninstallApps(self.apps_dict, i)) self.new_thread_list[item].signals.progress_signal.connect(self.uninstall_progress) self.newPoolThread = RunThreadPool(self.new_thread_list) self.newPoolThread.start() class CheckUpdates(QThread): """Check for updates and get the latest version number.""" version_signal = Signal(str) def run(self): try: api_url = 'https://api.github.com/repos/Teraskull/PyDebloatX/releases/latest' api_data = requests.get(api_url, timeout=(5, 0.7)).json() # API rate limit exceeded (https://docs.github.com/rest/overview/resources-in-the-rest-api#rate-limiting) if 'tag_name' in api_data: latest_version = api_data['tag_name'] self.version_signal.emit(latest_version) except requests.exceptions.RequestException: pass class CheckApps(QThread): """Refresh list of installed apps.""" progress_signal = Signal() app_signal = Signal(object) def __init__(self, apps_dict): super().__init__() self.apps_dict = apps_dict def run(self): si = subprocess.STARTUPINFO() si.dwFlags |= subprocess.STARTF_USESHOWWINDOW x = subprocess.Popen(["powershell", "Get-AppxPackage -PackageTypeFilter Main | Select Name, InstallLocation | ConvertTo-JSON"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=False, startupinfo=si, text=True) names_str = x.communicate()[0] names_list = json.loads(names_str) for i in self.apps_dict: temp_name = self.apps_dict[i]["name"].strip("*") self.apps_dict[i]["size"] = 0 flag = False if temp_name != "Xbox": for item in names_list: name = item["Name"] if name.find(temp_name, 0, len(name)) != -1: flag = True self.apps_dict[i]["size"] += get_dir_size(item["InstallLocation"]) / 1024 / 1024 break else: for item in names_list: name = item["Name"] if name.find(temp_name, 0, len(name)) != -1 and name.find("XboxGameCallableUI", 0, len(name)) == -1: flag = True self.apps_dict[i]["size"] += get_dir_size(item["InstallLocation"]) / 1024 / 1024 if flag: self.app_signal.emit(i) self.progress_signal.emit() class RunThreadPool(QThread): """Run thread pool for uninstalling selected apps.""" def __init__(self, new_thread_list): super().__init__() self.new_thread_list = new_thread_list def run(self): pool = QThreadPool() for new_thread in self.new_thread_list: pool.start(new_thread) pool.waitForDone() class UninstallSignals(QObject): """PyQt signal emitting class for uninstalling apps.""" progress_signal = Signal(object) class UninstallApps(QRunnable): """Uninstall selected apps.""" def __init__(self, apps_dict, i): super().__init__() self.signals = UninstallSignals() self.apps_dict = apps_dict self.i = i def run(self): package_name = self.apps_dict[self.i]["name"] if "Xbox" in package_name: package_name = "*Xbox* | Where-Object {$_.name -notmatch 'XboxGameCallableUI'}" si = subprocess.STARTUPINFO() si.dwFlags |= subprocess.STARTF_USESHOWWINDOW x = subprocess.Popen( ["powershell", f'try {{Get-AppxPackage {package_name} -OutVariable app | Remove-AppPackage -ea stop;[bool]$app}} catch {{$false}}'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=False, startupinfo=si ) x.communicate()[0] self.signals.progress_signal.emit(self.i) if __name__ == '__main__': QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True) QApplication.setHighDpiScaleFactorRoundingPolicy(Qt.HighDpiScaleFactorRoundingPolicy.PassThrough) app = QApplication(sys.argv) app.setFont(QFont("Tahoma")) locale = QLocale() trans = QTranslator() if trans.load(locale, "", "", resource_path("Language"), ".qm"): app.installTranslator(trans) about = Ui_AboutWindow() about.setupUi() ui = Ui_MainWindow() ui.setupUi() ui.show() logic = Logic() sys.exit(app.exec_())
[ "PySide6.QtCore.QLocale", "webbrowser.open_new", "subprocess.STARTUPINFO", "PySide6.QtWidgets.QMessageBox", "os.walk", "PySide6.QtCore.QPoint", "PySide6.QtCore.QThreadPool", "subprocess.Popen", "PySide6.QtWidgets.QApplication.setHighDpiScaleFactorRoundingPolicy", "PySide6.QtGui.QCursor", "packag...
[((930, 947), 'os.walk', 'os.walk', (['dir_path'], {}), '(dir_path)\n', (937, 947), False, 'import os\n'), ((13008, 13019), 'PySide6.QtCore.Signal', 'Signal', (['str'], {}), '(str)\n', (13014, 13019), False, 'from PySide6.QtCore import Qt, QThread, Signal, QPoint, QRect, QLocale, QTranslator, QCoreApplication, QThreadPool, QObject, QRunnable\n'), ((13643, 13651), 'PySide6.QtCore.Signal', 'Signal', ([], {}), '()\n', (13649, 13651), False, 'from PySide6.QtCore import Qt, QThread, Signal, QPoint, QRect, QLocale, QTranslator, QCoreApplication, QThreadPool, QObject, QRunnable\n'), ((13669, 13683), 'PySide6.QtCore.Signal', 'Signal', (['object'], {}), '(object)\n', (13675, 13683), False, 'from PySide6.QtCore import Qt, QThread, Signal, QPoint, QRect, QLocale, QTranslator, QCoreApplication, QThreadPool, QObject, QRunnable\n'), ((15712, 15726), 'PySide6.QtCore.Signal', 'Signal', (['object'], {}), '(object)\n', (15718, 15726), False, 'from PySide6.QtCore import Qt, QThread, Signal, QPoint, QRect, QLocale, QTranslator, QCoreApplication, QThreadPool, QObject, QRunnable\n'), ((16658, 16717), 'PySide6.QtWidgets.QApplication.setAttribute', 'QApplication.setAttribute', (['Qt.AA_EnableHighDpiScaling', '(True)'], {}), '(Qt.AA_EnableHighDpiScaling, True)\n', (16683, 16717), False, 'from PySide6.QtWidgets import QApplication, QMessageBox\n'), ((16722, 16824), 'PySide6.QtWidgets.QApplication.setHighDpiScaleFactorRoundingPolicy', 'QApplication.setHighDpiScaleFactorRoundingPolicy', (['Qt.HighDpiScaleFactorRoundingPolicy.PassThrough'], {}), '(Qt.\n HighDpiScaleFactorRoundingPolicy.PassThrough)\n', (16770, 16824), False, 'from PySide6.QtWidgets import QApplication, QMessageBox\n'), ((16830, 16852), 'PySide6.QtWidgets.QApplication', 'QApplication', (['sys.argv'], {}), '(sys.argv)\n', (16842, 16852), False, 'from PySide6.QtWidgets import QApplication, QMessageBox\n'), ((16899, 16908), 'PySide6.QtCore.QLocale', 'QLocale', ([], {}), '()\n', (16906, 16908), False, 'from PySide6.QtCore import Qt, QThread, Signal, QPoint, QRect, QLocale, QTranslator, QCoreApplication, QThreadPool, QObject, QRunnable\n'), ((16921, 16934), 'PySide6.QtCore.QTranslator', 'QTranslator', ([], {}), '()\n', (16932, 16934), False, 'from PySide6.QtCore import Qt, QThread, Signal, QPoint, QRect, QLocale, QTranslator, QCoreApplication, QThreadPool, QObject, QRunnable\n'), ((17053, 17069), 'gui_about.Ui_AboutWindow', 'Ui_AboutWindow', ([], {}), '()\n', (17067, 17069), False, 'from gui_about import Ui_AboutWindow\n'), ((17099, 17114), 'gui_main.Ui_MainWindow', 'Ui_MainWindow', ([], {}), '()\n', (17112, 17114), False, 'from gui_main import Ui_MainWindow\n'), ((685, 726), 'os.path.join', 'os.path.join', (['sys._MEIPASS', 'relative_path'], {}), '(sys._MEIPASS, relative_path)\n', (697, 726), False, 'import os\n'), ((772, 792), 'os.path.abspath', 'os.path.abspath', (['"""."""'], {}), "('.')\n", (787, 792), False, 'import os\n'), ((1273, 1416), 'PySide6.QtCore.QCoreApplication.translate', 'QCoreApplication.translate', (['"""Label"""', '"""Select the default Windows 10 apps to uninstall:\n(Hover over app names to view description)"""'], {}), '(\'Label\',\n """Select the default Windows 10 apps to uninstall:\n(Hover over app names to view description)"""\n )\n', (1299, 1416), False, 'from PySide6.QtCore import Qt, QThread, Signal, QPoint, QRect, QLocale, QTranslator, QCoreApplication, QThreadPool, QObject, QRunnable\n'), ((1432, 1526), 'PySide6.QtCore.QCoreApplication.translate', 'QCoreApplication.translate', (['"""Label"""', '"""Click on an app name to view it in Microsoft Store."""'], {}), "('Label',\n 'Click on an app name to view it in Microsoft Store.')\n", (1458, 1526), False, 'from PySide6.QtCore import Qt, QThread, Signal, QPoint, QRect, QLocale, QTranslator, QCoreApplication, QThreadPool, QObject, QRunnable\n'), ((1552, 1627), 'PySide6.QtCore.QCoreApplication.translate', 'QCoreApplication.translate', (['"""Label"""', '"""Refreshing list of installed apps..."""'], {}), "('Label', 'Refreshing list of installed apps...')\n", (1578, 1627), False, 'from PySide6.QtCore import Qt, QThread, Signal, QPoint, QRect, QLocale, QTranslator, QCoreApplication, QThreadPool, QObject, QRunnable\n'), ((1653, 1694), 'PySide6.QtCore.QCoreApplication.translate', 'QCoreApplication.translate', (['"""Label"""', '"""MB"""'], {}), "('Label', 'MB')\n", (1679, 1694), False, 'from PySide6.QtCore import Qt, QThread, Signal, QPoint, QRect, QLocale, QTranslator, QCoreApplication, QThreadPool, QObject, QRunnable\n'), ((1724, 1801), 'PySide6.QtCore.QCoreApplication.translate', 'QCoreApplication.translate', (['"""MessageBox"""', '"""Visit the PyDebloatX GitHub page?"""'], {}), "('MessageBox', 'Visit the PyDebloatX GitHub page?')\n", (1750, 1801), False, 'from PySide6.QtCore import Qt, QThread, Signal, QPoint, QRect, QLocale, QTranslator, QCoreApplication, QThreadPool, QObject, QRunnable\n'), ((1829, 1889), 'PySide6.QtCore.QCoreApplication.translate', 'QCoreApplication.translate', (['"""MessageBox"""', '"""Quit PyDebloatX?"""'], {}), "('MessageBox', 'Quit PyDebloatX?')\n", (1855, 1889), False, 'from PySide6.QtCore import Qt, QThread, Signal, QPoint, QRect, QLocale, QTranslator, QCoreApplication, QThreadPool, QObject, QRunnable\n'), ((1916, 1959), 'PySide6.QtCore.QCoreApplication.translate', 'QCoreApplication.translate', (['"""Button"""', '"""Yes"""'], {}), "('Button', 'Yes')\n", (1942, 1959), False, 'from PySide6.QtCore import Qt, QThread, Signal, QPoint, QRect, QLocale, QTranslator, QCoreApplication, QThreadPool, QObject, QRunnable\n'), ((1985, 2027), 'PySide6.QtCore.QCoreApplication.translate', 'QCoreApplication.translate', (['"""Button"""', '"""No"""'], {}), "('Button', 'No')\n", (2011, 2027), False, 'from PySide6.QtCore import Qt, QThread, Signal, QPoint, QRect, QLocale, QTranslator, QCoreApplication, QThreadPool, QObject, QRunnable\n'), ((2053, 2095), 'PySide6.QtCore.QCoreApplication.translate', 'QCoreApplication.translate', (['"""Button"""', '"""OK"""'], {}), "('Button', 'OK')\n", (2079, 2095), False, 'from PySide6.QtCore import Qt, QThread, Signal, QPoint, QRect, QLocale, QTranslator, QCoreApplication, QThreadPool, QObject, QRunnable\n'), ((2124, 2220), 'PySide6.QtCore.QCoreApplication.translate', 'QCoreApplication.translate', (['"""MessageBox"""', '"""All selected apps were successfully uninstalled."""'], {}), "('MessageBox',\n 'All selected apps were successfully uninstalled.')\n", (2150, 2220), False, 'from PySide6.QtCore import Qt, QThread, Signal, QPoint, QRect, QLocale, QTranslator, QCoreApplication, QThreadPool, QObject, QRunnable\n'), ((9883, 9896), 'PySide6.QtWidgets.QMessageBox', 'QMessageBox', ([], {}), '()\n', (9894, 9896), False, 'from PySide6.QtWidgets import QApplication, QMessageBox\n'), ((11880, 11954), 'PySide6.QtCore.QCoreApplication.translate', 'QCoreApplication.translate', (['"""MessageBox"""', '"""Uninstall %n app(s)?"""', '""""""', 'apps'], {}), "('MessageBox', 'Uninstall %n app(s)?', '', apps)\n", (11906, 11954), False, 'from PySide6.QtCore import Qt, QThread, Signal, QPoint, QRect, QLocale, QTranslator, QCoreApplication, QThreadPool, QObject, QRunnable\n'), ((11982, 12052), 'PySide6.QtCore.QCoreApplication.translate', 'QCoreApplication.translate', (['"""MessageBox"""', '"""MB of space will be freed."""'], {}), "('MessageBox', 'MB of space will be freed.')\n", (12008, 12052), False, 'from PySide6.QtCore import Qt, QThread, Signal, QPoint, QRect, QLocale, QTranslator, QCoreApplication, QThreadPool, QObject, QRunnable\n'), ((13815, 13839), 'subprocess.STARTUPINFO', 'subprocess.STARTUPINFO', ([], {}), '()\n', (13837, 13839), False, 'import subprocess\n'), ((13906, 14156), 'subprocess.Popen', 'subprocess.Popen', (["['powershell',\n 'Get-AppxPackage -PackageTypeFilter Main | Select Name, InstallLocation | ConvertTo-JSON'\n ]"], {'stdin': 'subprocess.PIPE', 'stdout': 'subprocess.PIPE', 'stderr': 'subprocess.STDOUT', 'shell': '(False)', 'startupinfo': 'si', 'text': '(True)'}), "(['powershell',\n 'Get-AppxPackage -PackageTypeFilter Main | Select Name, InstallLocation | ConvertTo-JSON'\n ], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.\n STDOUT, shell=False, startupinfo=si, text=True)\n", (13922, 14156), False, 'import subprocess\n'), ((14232, 14253), 'json.loads', 'json.loads', (['names_str'], {}), '(names_str)\n', (14242, 14253), False, 'import json\n'), ((15471, 15484), 'PySide6.QtCore.QThreadPool', 'QThreadPool', ([], {}), '()\n', (15482, 15484), False, 'from PySide6.QtCore import Qt, QThread, Signal, QPoint, QRect, QLocale, QTranslator, QCoreApplication, QThreadPool, QObject, QRunnable\n'), ((16171, 16195), 'subprocess.STARTUPINFO', 'subprocess.STARTUPINFO', ([], {}), '()\n', (16193, 16195), False, 'import subprocess\n'), ((16262, 16527), 'subprocess.Popen', 'subprocess.Popen', (["['powershell',\n f'try {{Get-AppxPackage {package_name} -OutVariable app | Remove-AppPackage -ea stop;[bool]$app}} catch {{$false}}'\n ]"], {'stdin': 'subprocess.PIPE', 'stdout': 'subprocess.PIPE', 'stderr': 'subprocess.STDOUT', 'shell': '(False)', 'startupinfo': 'si'}), "(['powershell',\n f'try {{Get-AppxPackage {package_name} -OutVariable app | Remove-AppPackage -ea stop;[bool]$app}} catch {{$false}}'\n ], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.\n STDOUT, shell=False, startupinfo=si)\n", (16278, 16527), False, 'import subprocess\n'), ((16869, 16884), 'PySide6.QtGui.QFont', 'QFont', (['"""Tahoma"""'], {}), "('Tahoma')\n", (16874, 16884), False, 'from PySide6.QtGui import QCursor, QPixmap, QIcon, QFont\n'), ((5237, 5266), 'packaging.version.parse', 'version.parse', (['latest_version'], {}), '(latest_version)\n', (5250, 5266), False, 'from packaging import version\n'), ((5269, 5295), 'packaging.version.parse', 'version.parse', (['__version__'], {}), '(__version__)\n', (5282, 5295), False, 'from packaging import version\n'), ((6113, 6135), 'PySide6.QtGui.QCursor', 'QCursor', (['Qt.BusyCursor'], {}), '(Qt.BusyCursor)\n', (6120, 6135), False, 'from PySide6.QtGui import QCursor, QPixmap, QIcon, QFont\n'), ((6671, 6680), 'PySide6.QtGui.QCursor', 'QCursor', ([], {}), '()\n', (6678, 6680), False, 'from PySide6.QtGui import QCursor, QPixmap, QIcon, QFont\n'), ((10831, 10893), 'webbrowser.open_new', 'webbrowser.open_new', (['"""https://github.com/Teraskull/PyDebloatX"""'], {}), "('https://github.com/Teraskull/PyDebloatX')\n", (10850, 10893), False, 'import webbrowser\n'), ((1117, 1163), 'PySide6.QtCore.QCoreApplication.translate', 'QCoreApplication.translate', (['"""Label"""', '"""Version"""'], {}), "('Label', 'Version')\n", (1143, 1163), False, 'from PySide6.QtCore import Qt, QThread, Signal, QPoint, QRect, QLocale, QTranslator, QCoreApplication, QThreadPool, QObject, QRunnable\n'), ((4189, 4219), 'PySide6.QtGui.QIcon', 'QIcon', (['""":/icon/store_icon.png"""'], {}), "(':/icon/store_icon.png')\n", (4194, 4219), False, 'from PySide6.QtGui import QCursor, QPixmap, QIcon, QFont\n'), ((4718, 4747), 'PySide6.QtGui.QIcon', 'QIcon', (['""":/icon/back_icon.png"""'], {}), "(':/icon/back_icon.png')\n", (4723, 4747), False, 'from PySide6.QtGui import QCursor, QPixmap, QIcon, QFont\n'), ((5525, 5596), 'webbrowser.open_new', 'webbrowser.open_new', (['"""https://github.com/Teraskull/PyDebloatX/releases"""'], {}), "('https://github.com/Teraskull/PyDebloatX/releases')\n", (5544, 5596), False, 'import webbrowser\n'), ((982, 998), 'os.path.join', 'join', (['root', 'name'], {}), '(root, name)\n', (986, 998), False, 'from os.path import getsize, join\n'), ((5322, 5424), 'PySide6.QtCore.QCoreApplication.translate', 'QCoreApplication.translate', (['"""MessageBox"""', '"""PyDebloatX {0} is available.\n\nVisit download page?"""'], {}), '(\'MessageBox\',\n """PyDebloatX {0} is available.\n\nVisit download page?""")\n', (5348, 5424), False, 'from PySide6.QtCore import Qt, QThread, Signal, QPoint, QRect, QLocale, QTranslator, QCoreApplication, QThreadPool, QObject, QRunnable\n'), ((7726, 7819), 'PySide6.QtCore.QCoreApplication.translate', 'QCoreApplication.translate', (['"""Label"""', '"""Uninstalling {0}, %n app(s) left..."""', '""""""', 'apps_left'], {}), "('Label', 'Uninstalling {0}, %n app(s) left...',\n '', apps_left)\n", (7752, 7819), False, 'from PySide6.QtCore import Qt, QThread, Signal, QPoint, QRect, QLocale, QTranslator, QCoreApplication, QThreadPool, QObject, QRunnable\n'), ((9271, 9344), 'webbrowser.open_new', 'webbrowser.open_new', (['f"""ms-windows-store://pdp{self.apps_dict[i][\'link\']}"""'], {}), '(f"ms-windows-store://pdp{self.apps_dict[i][\'link\']}")\n', (9290, 9344), False, 'import webbrowser\n'), ((13166, 13205), 'requests.get', 'requests.get', (['api_url'], {'timeout': '(5, 0.7)'}), '(api_url, timeout=(5, 0.7))\n', (13178, 13205), False, 'import requests\n'), ((10565, 10573), 'PySide6.QtCore.QPoint', 'QPoint', ([], {}), '()\n', (10571, 10573), False, 'from PySide6.QtCore import Qt, QThread, Signal, QPoint, QRect, QLocale, QTranslator, QCoreApplication, QThreadPool, QObject, QRunnable\n')]
import json_and_dictionary_constructor class Channel: def __init__(self, user, channel_id): self.channel_id = channel_id self.user = user async def send(self, message): http_template = dictionary_templates.http_load message_template = dictionary_templates.new_message message_template["content"] = message message_template["tts"] = False http_template["request_type"] = "POST" http_template["end_point"] = "/channels/" + self.channel_id + "/messages" http_template["headers/data"] = message_template return await self.user.aiohttp_client_session.http_request(http_template) async def get_channel_data(self): http_template = await json_and_dictionary_constructor.create_http_request("GET", "/channels/" + self.channel_id, {"Authorization": "Bot " + self.user.bot_data["token"]}) return await self.user.aiohttp_client_session.http_request(http_template)
[ "json_and_dictionary_constructor.create_http_request" ]
[((737, 888), 'json_and_dictionary_constructor.create_http_request', 'json_and_dictionary_constructor.create_http_request', (['"""GET"""', "('/channels/' + self.channel_id)", "{'Authorization': 'Bot ' + self.user.bot_data['token']}"], {}), "('GET', '/channels/' +\n self.channel_id, {'Authorization': 'Bot ' + self.user.bot_data['token']})\n", (788, 888), False, 'import json_and_dictionary_constructor\n')]
# This file is just a basic example of the server comunication structure to a client program. # The server is run on the embedded computer and passes data to a client on your local pc # over a direct wifi connection. This can be used to display telemetry. import time import json import socket def current_time(start_time): current_time = time.time() - start_time day = current_time // (24 * 3600) current_time = current_time % (24 * 3600) hour = current_time // 3600 current_time %= 3600 minutes = current_time // 60 current_time %= 60 seconds = round(current_time,3) return hour, minutes, seconds def log(*args): t = current_time(start_time) print("%02d:%02d:%02.3f -" % (t[0],t[1],t[2]),' '.join(map(str, args))) ip = "0.0.0.0" # 0.0.0.0 will make the server accessable on all network interfaces port = 2442 # Port to run server on start_time = time.time() # Record start time for logging socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Setup UDP Communication socket.bind((ip, port)) print("Bound to IP: ",ip,"\n\t Port:",port) print("\nServer running!") while 1: data = { "a": 1, "b": 2, "c": 3 } ###################################### # UPDATE DATA HERE # Example: # data["batt_v"] = analog_read(battery) ###################################### try: request, ip = socket.recvfrom(1024) # Wait until data is received request = json.loads(request.decode('utf-8')) # Converts data back from bytes to string log("Received Request from", ip[0], "for:", request) # Log to console packet = [] # Create empty list to construct packet for item in request: # Iterate through requested items and # assemble packet in order requested if item in data: # Check requested item exists in data dictionary packet.append(data[item]) # If items exists append to end of packet elif item not in data: # If item doesnt exist in data dictionary log("Item \"",item,"\"", "does not exist!") # Log to console packet.append(None) # append 'None' for better error handling packet = json.dumps(packet) # Convert message to bytes socket.sendto(packet.encode('utf-8'), ip) # Send back to device that requested log("Sent response", packet,"to",ip[0]) # Log to console except Exception as e: # If there is an error print(e) # Print error exit() # Exit code. Replace with "pass" for code to move on after error
[ "socket.socket", "json.dumps", "socket.bind", "time.time", "socket.recvfrom" ]
[((911, 922), 'time.time', 'time.time', ([], {}), '()\n', (920, 922), False, 'import time\n'), ((968, 1016), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_DGRAM'], {}), '(socket.AF_INET, socket.SOCK_DGRAM)\n', (981, 1016), False, 'import socket\n'), ((1045, 1068), 'socket.bind', 'socket.bind', (['(ip, port)'], {}), '((ip, port))\n', (1056, 1068), False, 'import socket\n'), ((346, 357), 'time.time', 'time.time', ([], {}), '()\n', (355, 357), False, 'import time\n'), ((1410, 1431), 'socket.recvfrom', 'socket.recvfrom', (['(1024)'], {}), '(1024)\n', (1425, 1431), False, 'import socket\n'), ((2429, 2447), 'json.dumps', 'json.dumps', (['packet'], {}), '(packet)\n', (2439, 2447), False, 'import json\n')]
from django.db import models from mayan.apps.testing.tests.base import BaseTestCase from ..classes import QuerysetParametersSerializer class QuerysetParametersSerializerTestCase(BaseTestCase): def setUp(self): super().setUp() self.TestModelParent = self._create_test_model( model_name='TestModelParent' ) self.TestModelChild = self._create_test_model( fields={ 'parent': models.ForeignKey( on_delete=models.CASCADE, related_name='children', to='TestModelParent' ) }, model_name='TestModelChild' ) self._test_object_parent = self.TestModelParent.objects.create() self.TestModelChild.objects.create(parent_id=self._test_object_parent.pk) def _assertQuerysetEqual(self): rebuilt_items = list(map(repr, self.queryset_rebuilt)) self.assertQuerysetEqual( qs=self.queryset_original, values=rebuilt_items ) def test_without_kwargs(self): self.queryset_original = self.TestModelParent.objects.all() decomposed_queryset = QuerysetParametersSerializer.decompose( _model=self.TestModelParent, _method_name='all' ) self.queryset_rebuilt = QuerysetParametersSerializer.rebuild( decomposed_queryset=decomposed_queryset ) self._assertQuerysetEqual() def test_foreign_key_model(self): self.queryset_original = self.TestModelChild.objects.all() decomposed_queryset = QuerysetParametersSerializer.decompose( _model=self.TestModelChild, _method_name='filter', parent=self._test_object_parent ) self.queryset_rebuilt = QuerysetParametersSerializer.rebuild( decomposed_queryset=decomposed_queryset ) self._assertQuerysetEqual() def test_foreign_key_model_id_query(self): self.queryset_original = self.TestModelChild.objects.all() decomposed_queryset = QuerysetParametersSerializer.decompose( _model=self.TestModelChild, _method_name='filter', parent_id=self._test_object_parent.pk ) self.queryset_rebuilt = QuerysetParametersSerializer.rebuild( decomposed_queryset=decomposed_queryset ) self._assertQuerysetEqual()
[ "django.db.models.ForeignKey" ]
[((451, 546), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'on_delete': 'models.CASCADE', 'related_name': '"""children"""', 'to': '"""TestModelParent"""'}), "(on_delete=models.CASCADE, related_name='children', to=\n 'TestModelParent')\n", (468, 546), False, 'from django.db import models\n')]
import matplotlib.pyplot as plt import numpy as np def autolabel(rects): for rect in rects: height = rect.get_height() plt.text(rect.get_x()+rect.get_width()/2., 1.03*height, "%s" % float(height)) text = ["10.65x", "57.62x", "54.44x"] def autolabel_user(rects): for i, rect in enumerate(rects): height = text[i] plt.text(rect.get_x()+rect.get_width()/2, rect.get_height()*1.01, "%s" % height, fontsize=12, ha='center') size = 3 x = np.arange(size) total_width = 0.8 n = 3 width = total_width / n x = x - (total_width - width) / 2 mingwen = [0.000124, 0.000151, 0.000154] # 6摄像头明文运算一帧的速度 miwen = [0.00132, 0.0087, 0.0084] # 6摄像头密文运算一帧的速度 error = [0.00001, ] * 3 # 生成一个包含有n个值,均为0.2的list,表示允许的误差范围[-0.002,0.002] plt.xlabel('Operation', fontsize=18.5) plt.ylabel('Average Time Cost (ms)', fontsize=18.5) rect = plt.bar(x, miwen, color="#800000", width=0.75 * width, label='Ciphertext', yerr=error) plt.xticks(x, ("Mul", "Add", "Sub"), fontsize=16) plt.yticks(fontsize=18) plt.legend(loc='upper left', fontsize=12) autolabel_user(rect) plt.show()
[ "matplotlib.pyplot.xticks", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.legend", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.bar", "matplotlib.pyplot.yticks", "numpy.arange", "matplotlib.pyplot.show" ]
[((478, 493), 'numpy.arange', 'np.arange', (['size'], {}), '(size)\n', (487, 493), True, 'import numpy as np\n'), ((760, 798), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Operation"""'], {'fontsize': '(18.5)'}), "('Operation', fontsize=18.5)\n", (770, 798), True, 'import matplotlib.pyplot as plt\n'), ((799, 850), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Average Time Cost (ms)"""'], {'fontsize': '(18.5)'}), "('Average Time Cost (ms)', fontsize=18.5)\n", (809, 850), True, 'import matplotlib.pyplot as plt\n'), ((858, 948), 'matplotlib.pyplot.bar', 'plt.bar', (['x', 'miwen'], {'color': '"""#800000"""', 'width': '(0.75 * width)', 'label': '"""Ciphertext"""', 'yerr': 'error'}), "(x, miwen, color='#800000', width=0.75 * width, label='Ciphertext',\n yerr=error)\n", (865, 948), True, 'import matplotlib.pyplot as plt\n'), ((945, 994), 'matplotlib.pyplot.xticks', 'plt.xticks', (['x', "('Mul', 'Add', 'Sub')"], {'fontsize': '(16)'}), "(x, ('Mul', 'Add', 'Sub'), fontsize=16)\n", (955, 994), True, 'import matplotlib.pyplot as plt\n'), ((995, 1018), 'matplotlib.pyplot.yticks', 'plt.yticks', ([], {'fontsize': '(18)'}), '(fontsize=18)\n', (1005, 1018), True, 'import matplotlib.pyplot as plt\n'), ((1019, 1060), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper left"""', 'fontsize': '(12)'}), "(loc='upper left', fontsize=12)\n", (1029, 1060), True, 'import matplotlib.pyplot as plt\n'), ((1083, 1093), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1091, 1093), True, 'import matplotlib.pyplot as plt\n')]
from django_tables2 import TemplateColumn from service_catalog.models import GlobalHook from Squest.utils.squest_table import SquestTable class GlobalHookTable(SquestTable): state = TemplateColumn(template_name='custom_columns/global_hook_state.html') actions = TemplateColumn(template_name='custom_columns/global_hook_actions.html', orderable=False) class Meta: model = GlobalHook attrs = {"id": "global_hook_table", "class": "table squest-pagination-tables"} fields = ("name", "model", "state", "job_template", "actions")
[ "django_tables2.TemplateColumn" ]
[((189, 258), 'django_tables2.TemplateColumn', 'TemplateColumn', ([], {'template_name': '"""custom_columns/global_hook_state.html"""'}), "(template_name='custom_columns/global_hook_state.html')\n", (203, 258), False, 'from django_tables2 import TemplateColumn\n'), ((273, 365), 'django_tables2.TemplateColumn', 'TemplateColumn', ([], {'template_name': '"""custom_columns/global_hook_actions.html"""', 'orderable': '(False)'}), "(template_name='custom_columns/global_hook_actions.html',\n orderable=False)\n", (287, 365), False, 'from django_tables2 import TemplateColumn\n')]
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Keras upsampling layer for 1D inputs.""" import tensorflow.compat.v2 as tf from keras import backend from keras.engine.base_layer import Layer from keras.engine.input_spec import InputSpec # isort: off from tensorflow.python.util.tf_export import keras_export @keras_export("keras.layers.UpSampling1D") class UpSampling1D(Layer): """Upsampling layer for 1D inputs. Repeats each temporal step `size` times along the time axis. Examples: >>> input_shape = (2, 2, 3) >>> x = np.arange(np.prod(input_shape)).reshape(input_shape) >>> print(x) [[[ 0 1 2] [ 3 4 5]] [[ 6 7 8] [ 9 10 11]]] >>> y = tf.keras.layers.UpSampling1D(size=2)(x) >>> print(y) tf.Tensor( [[[ 0 1 2] [ 0 1 2] [ 3 4 5] [ 3 4 5]] [[ 6 7 8] [ 6 7 8] [ 9 10 11] [ 9 10 11]]], shape=(2, 4, 3), dtype=int64) Args: size: Integer. Upsampling factor. Input shape: 3D tensor with shape: `(batch_size, steps, features)`. Output shape: 3D tensor with shape: `(batch_size, upsampled_steps, features)`. """ def __init__(self, size=2, **kwargs): super().__init__(**kwargs) self.size = int(size) self.input_spec = InputSpec(ndim=3) def compute_output_shape(self, input_shape): input_shape = tf.TensorShape(input_shape).as_list() size = ( self.size * input_shape[1] if input_shape[1] is not None else None ) return tf.TensorShape([input_shape[0], size, input_shape[2]]) def call(self, inputs): output = backend.repeat_elements(inputs, self.size, axis=1) return output def get_config(self): config = {"size": self.size} base_config = super().get_config() return dict(list(base_config.items()) + list(config.items()))
[ "tensorflow.compat.v2.TensorShape", "keras.engine.input_spec.InputSpec", "tensorflow.python.util.tf_export.keras_export", "keras.backend.repeat_elements" ]
[((959, 1000), 'tensorflow.python.util.tf_export.keras_export', 'keras_export', (['"""keras.layers.UpSampling1D"""'], {}), "('keras.layers.UpSampling1D')\n", (971, 1000), False, 'from tensorflow.python.util.tf_export import keras_export\n'), ((1966, 1983), 'keras.engine.input_spec.InputSpec', 'InputSpec', ([], {'ndim': '(3)'}), '(ndim=3)\n', (1975, 1983), False, 'from keras.engine.input_spec import InputSpec\n'), ((2215, 2269), 'tensorflow.compat.v2.TensorShape', 'tf.TensorShape', (['[input_shape[0], size, input_shape[2]]'], {}), '([input_shape[0], size, input_shape[2]])\n', (2229, 2269), True, 'import tensorflow.compat.v2 as tf\n'), ((2316, 2366), 'keras.backend.repeat_elements', 'backend.repeat_elements', (['inputs', 'self.size'], {'axis': '(1)'}), '(inputs, self.size, axis=1)\n', (2339, 2366), False, 'from keras import backend\n'), ((2056, 2083), 'tensorflow.compat.v2.TensorShape', 'tf.TensorShape', (['input_shape'], {}), '(input_shape)\n', (2070, 2083), True, 'import tensorflow.compat.v2 as tf\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Main script for Empty My Fridge project. Provides a CLI for the Spoonacular API. """ import requests from rich.console import Console import config def get_missing_ingredients(available_ingredients, amount_recipes): """ :param available_ingredients: comma separated list of ingredients the user has :type available_ingredients: str :param amount_recipes: number of recipes that the user wants :type amount_recipes: int :return: None """ # explanation of API parameters: https://spoonacular.com/food-api/docs#Search-Recipes-by-Ingredients # ingredients (string): A comma-separated list of ingredients that the recipes should contain. # number (number): The maximum number of recipes to return (between 1 and 100). Defaults to 10. # limitLicense (bool): Whether the recipes should have an open license that allows display with proper attribution. # ranking (number): Whether to maximize used ingredients (1) or minimize missing ingredients (2) first. # ignorePantry (bool): Whether to ignore typical pantry items, such as water, salt, flour, etc. parameters = { 'apiKey': config.API_KEY, 'ingredients': available_ingredients, 'number': amount_recipes, 'ranking': 2, 'ignorePantry': True } r = requests.get('https://api.spoonacular.com/recipes/findByIngredients/', params=parameters) data = r.json() recipes = [] missing_ingredients = [] links = [] for recipe in data: # get recipe information param = { 'apiKey': config.API_KEY, 'includeNutrition': False } a = requests.get('https://api.spoonacular.com/recipes/' + str(recipe['id']) + '/information', params=param) d = a.json() recipes.append(recipe['title']) list_of_missing = recipe['missedIngredients'] missing = [] for item in list_of_missing: missing.append(item['name']) missing_ingredients.append(', '.join(map(str, missing))) links.append(d['sourceUrl']) return recipes, missing_ingredients, links def main(): # initialize the rich environment for command line formatting console = Console() # get user inputs ingredients = console.input("Enter the ingredients you have (each separated by a comma and a space): ") amount_recipes = int(console.input("How many recipes do you want to see? ")) while amount_recipes < 1: amount_recipes = int(console.input("Please enter 1 or higher: ")) # call method to get results recipes, missing, links = get_missing_ingredients(ingredients, amount_recipes) # format output # unpack results and format into table from rich.table import Table # initialize table table = Table(title='Recipes you can make with ' + ingredients) table.add_column("Recipe Name", style="cyan") table.add_column("Missing Ingredients", style="magenta") table.add_column("Recipe Link", style="green") # load data for recipe, missing_ingredients, link in zip(recipes, missing, links): table.add_row(recipe, missing_ingredients, link) # FIXME: make full links and ingredient list show up in smaller windows console.print(table) if __name__ == "__main__": main()
[ "rich.console.Console", "requests.get", "rich.table.Table" ]
[((1353, 1446), 'requests.get', 'requests.get', (['"""https://api.spoonacular.com/recipes/findByIngredients/"""'], {'params': 'parameters'}), "('https://api.spoonacular.com/recipes/findByIngredients/',\n params=parameters)\n", (1365, 1446), False, 'import requests\n'), ((2262, 2271), 'rich.console.Console', 'Console', ([], {}), '()\n', (2269, 2271), False, 'from rich.console import Console\n'), ((2838, 2893), 'rich.table.Table', 'Table', ([], {'title': "('Recipes you can make with ' + ingredients)"}), "(title='Recipes you can make with ' + ingredients)\n", (2843, 2893), False, 'from rich.table import Table\n')]
import json from flask import Blueprint from metrics import availability as avail from metrics import utils as ut from elasticsearch.exceptions import ConnectionError avail_page = Blueprint('availability', __name__) QUERY_CONTENT = '*' @avail_page.route('/') def hello(): return ut.json_response_formatter({'msg': "I'm the availability file!"}) @avail_page.route('/time/<int:minutes>') def all_avail_of_minutes(minutes): # Time window with dummy data #computation_timestamp, time_window = '2016-06-20T22:28:46', '[2018-06-20T22:28:46 TO 2020-06-20T22:36:41]' computation_timestamp, time_window = ut.get_timestamp_timewindow(minutes) try: avail_dictionaries = avail.get_availability_per_bp_and_method(computation_timestamp=computation_timestamp, time_window=time_window) except ConnectionError: avail_dictionaries = [] return ut.json_response_formatter(avail_dictionaries) @avail_page.route('/<string:method>/time/<int:minutes>') def service_avail_of_minutes(method, minutes): # Time window with dummy data #computation_timestamp, time_window = '2016-06-20T22:28:46', '[2018-06-20T22:28:46 TO 2020-06-20T22:36:41]' computation_timestamp, time_window = ut.get_timestamp_timewindow(minutes) try: avail_dictionaries = avail.get_availability_per_bp_and_method(computation_timestamp=computation_timestamp, time_window=time_window, method=method)[0] except (ConnectionError,IndexError): avail_dictionaries = { 'method': method, 'BluePrint-ID': '', 'value': 0, 'metric': 'availability', 'unit': 'percentage', '@timestamp': '', 'delta': 0, 'delta_unit': '', 'hits': 0 } return ut.json_response_formatter(avail_dictionaries) @avail_page.route('/test') def test(): dicti = { "_source": ["request.id"], "sort": [ {"_index": {"order": "desc"}} ] } es_resp = ut.es_rest(body=dicti) return ut.json_response_formatter(es_resp)
[ "metrics.utils.es_rest", "metrics.utils.json_response_formatter", "metrics.availability.get_availability_per_bp_and_method", "flask.Blueprint", "metrics.utils.get_timestamp_timewindow" ]
[((181, 216), 'flask.Blueprint', 'Blueprint', (['"""availability"""', '__name__'], {}), "('availability', __name__)\n", (190, 216), False, 'from flask import Blueprint\n'), ((287, 352), 'metrics.utils.json_response_formatter', 'ut.json_response_formatter', (['{\'msg\': "I\'m the availability file!"}'], {}), '({\'msg\': "I\'m the availability file!"})\n', (313, 352), True, 'from metrics import utils as ut\n'), ((618, 654), 'metrics.utils.get_timestamp_timewindow', 'ut.get_timestamp_timewindow', (['minutes'], {}), '(minutes)\n', (645, 654), True, 'from metrics import utils as ut\n'), ((942, 988), 'metrics.utils.json_response_formatter', 'ut.json_response_formatter', (['avail_dictionaries'], {}), '(avail_dictionaries)\n', (968, 988), True, 'from metrics import utils as ut\n'), ((1283, 1319), 'metrics.utils.get_timestamp_timewindow', 'ut.get_timestamp_timewindow', (['minutes'], {}), '(minutes)\n', (1310, 1319), True, 'from metrics import utils as ut\n'), ((1990, 2036), 'metrics.utils.json_response_formatter', 'ut.json_response_formatter', (['avail_dictionaries'], {}), '(avail_dictionaries)\n', (2016, 2036), True, 'from metrics import utils as ut\n'), ((2218, 2240), 'metrics.utils.es_rest', 'ut.es_rest', ([], {'body': 'dicti'}), '(body=dicti)\n', (2228, 2240), True, 'from metrics import utils as ut\n'), ((2252, 2287), 'metrics.utils.json_response_formatter', 'ut.json_response_formatter', (['es_resp'], {}), '(es_resp)\n', (2278, 2287), True, 'from metrics import utils as ut\n'), ((693, 808), 'metrics.availability.get_availability_per_bp_and_method', 'avail.get_availability_per_bp_and_method', ([], {'computation_timestamp': 'computation_timestamp', 'time_window': 'time_window'}), '(computation_timestamp=\n computation_timestamp, time_window=time_window)\n', (733, 808), True, 'from metrics import availability as avail\n'), ((1358, 1488), 'metrics.availability.get_availability_per_bp_and_method', 'avail.get_availability_per_bp_and_method', ([], {'computation_timestamp': 'computation_timestamp', 'time_window': 'time_window', 'method': 'method'}), '(computation_timestamp=\n computation_timestamp, time_window=time_window, method=method)\n', (1398, 1488), True, 'from metrics import availability as avail\n')]
#!/usr/bin/env python from nlputil import * import fileinput import re switch_thresh_and_grid = True errdists = dictdict() for line in fileinput.input(): line = line.strip() m = re.match(r'.*thresh: ([0-9.]*), grid: ([0-9.]*),.*true error distance.*\(([0-9.]*) km.*', line) if not m: errprint("Can't parse line: %s", line) else: thresh = float(m.group(1)) grid = float(m.group(2)) dist = float(m.group(3)) if switch_thresh_and_grid: errdists[grid][thresh] = dist else: errdists[thresh][grid] = dist first = True for (thresh, dic) in key_sorted_items(errdists): if first: first = False errprint(r" & %s \\" % ( ' & '.join(["%g" % grid for grid in sorted(dic.keys())]))) errprint(r"\hline") errprint(r"%g & %s \\" % (thresh, ' & '.join(["%g" % dist for (grid, dist) in key_sorted_items(dic)])))
[ "re.match", "fileinput.input" ]
[((139, 156), 'fileinput.input', 'fileinput.input', ([], {}), '()\n', (154, 156), False, 'import fileinput\n'), ((186, 291), 're.match', 're.match', (['""".*thresh: ([0-9.]*), grid: ([0-9.]*),.*true error distance.*\\\\(([0-9.]*) km.*"""', 'line'], {}), "(\n '.*thresh: ([0-9.]*), grid: ([0-9.]*),.*true error distance.*\\\\(([0-9.]*) km.*'\n , line)\n", (194, 291), False, 'import re\n')]
import sys import os import re import json import base64 REFERENCE_BRANCH_NAME = 'master' GRADLE_FILE_PATH = './build.gradle' GET_GRADLE_COMMAND = f'git show {REFERENCE_BRANCH_NAME} HEAD:{GRADLE_FILE_PATH}' class Version: def __init__(self, version_string: str): parts = version_string.split('.') if len(parts) > 3: raise Exception('Invalid version format') else: self._major = int(parts[0]) self._minor = int(parts[1]) self._patch = int(parts[2]) def major(self): self._major += 1 def minor(self): self._minor += 1 def patch(self): self._patch += 1 def __eq__(self, other): return (self.to_number() == other.to_number()) def __ne__(self, other): return (self.to_number() != other.to_number()) def __lt__(self, other): return (self.to_number() < other.to_number()) def __le__(self, other): return (self.to_number() <= other.to_number()) def __gt__(self, other): return (self.to_number() > other.to_number()) def __ge__(self, other): return (self.to_number() >= other.to_number()) def to_number(self): return (self._major * 100) + (self._minor * 10) + self._patch def __str__(self): return f'{self._major}.{self._minor}.{self._patch}' def get_build_gradle_from_branch(branch_name: str) -> str: return os.popen(GET_GRADLE_COMMAND).read() def get_version_from_gradle(build_gradle_content: str) -> Version: matches = re.findall(r"-*\+*version\s*=*\s*'\S+'\n", build_gradle_content) print(matches) max_version = None for match in matches: version_line = match version_string = version_line.split("'")[1::2][0] version = Version(version_string) if max_version is None or version > max_version: max_version = version return max_version if __name__ == "__main__": build_gradle_file = open(GRADLE_FILE_PATH, "r") my_build_gradle_content = build_gradle_file.read() their_build_gradle_content = get_build_gradle_from_branch(REFERENCE_BRANCH_NAME) my_version = get_version_from_gradle(my_build_gradle_content) their_version = get_version_from_gradle(their_build_gradle_content) if my_version <= their_version: print(f'Local version ({str(my_version)}) lower or equal than their version ({str(their_version)}).') exit(1) exit(0)
[ "re.findall", "os.popen" ]
[((1443, 1511), 're.findall', 're.findall', (['"""-*\\\\+*version\\\\s*=*\\\\s*\'\\\\S+\'\\\\n"""', 'build_gradle_content'], {}), '("-*\\\\+*version\\\\s*=*\\\\s*\'\\\\S+\'\\\\n", build_gradle_content)\n', (1453, 1511), False, 'import re\n'), ((1327, 1355), 'os.popen', 'os.popen', (['GET_GRADLE_COMMAND'], {}), '(GET_GRADLE_COMMAND)\n', (1335, 1355), False, 'import os\n')]
from sklearn.metrics.pairwise import cosine_similarity import pandas as pd import numpy as np cs = cosine_similarity df=pd.read_csv("df_final.csv") def get_recommender(user_input): """ This function produces the 5 top recommendations depending on user_input. The user_input is the age group and skills selected from the webpage. It calculates the similarity of each row in the dataframe and the user_input. """ all_scores = [] for i, row in df.iterrows(): row = row[5:].to_numpy().reshape(1, -1) all_scores.append((cs(row,user_input)).flatten()) all_scores = pd.Series(np.array(all_scores).flatten(), index=df.index) top_5 = all_scores.sort_values(ascending=False).head().index print (type(top_5)) result=[] for t in top_5: print(t) toy = df.loc[df.index == t] link = toy["link"].values image = toy["main_image_link"].values price = toy["price_value"].values title = toy["title"].values entry ={"title":title, "link":link, "image":image, "price":price} result.append(entry) return result
[ "numpy.array", "pandas.read_csv" ]
[((121, 148), 'pandas.read_csv', 'pd.read_csv', (['"""df_final.csv"""'], {}), "('df_final.csv')\n", (132, 148), True, 'import pandas as pd\n'), ((619, 639), 'numpy.array', 'np.array', (['all_scores'], {}), '(all_scores)\n', (627, 639), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- #config import configparser #sys & os import sys import os.path #set logging import logging logging.basicConfig(filename=os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), 'umr.log'),level=logging.DEBUG) #Set locale #FIXME : force French, should be in conf ? import locale locale.setlocale(locale.LC_TIME, 'fr_FR') #Initialisation to None gconfig = None #config helpers def localpath(): """Path of launcher, supposed to be the root of the tree""" return(os.path.dirname(os.path.abspath(sys.argv[0]))) def get_config(cname = 'umr.ini'): """Load config as a dict""" #Configuration global gconfig if gconfig == None : logging.info("Load config") gconfig = configparser.ConfigParser() gconfig.readfp(open(os.path.join(localpath(), cname))) #logging.info("Config loaded, user %s" % gconfig.get('User', 'login')) return gconfig def get_path(pathname_config, filename_config = None): """Helper to get pathname from config, and create if necessary""" #check path conf_path = os.path.join(localpath(), gconfig.get('Path', pathname_config)) if not os.path.exists(conf_path) : logging.debug("Creating %s", conf_path) os.mkdir(conf_path) if filename_config is not None: filename = gconfig.get("Files", filename_config) conf_path = os.path.join(conf_path, filename) return(conf_path) gconfig = get_config()
[ "configparser.ConfigParser", "logging.info", "locale.setlocale", "logging.debug" ]
[((310, 351), 'locale.setlocale', 'locale.setlocale', (['locale.LC_TIME', '"""fr_FR"""'], {}), "(locale.LC_TIME, 'fr_FR')\n", (326, 351), False, 'import locale\n'), ((687, 714), 'logging.info', 'logging.info', (['"""Load config"""'], {}), "('Load config')\n", (699, 714), False, 'import logging\n'), ((733, 760), 'configparser.ConfigParser', 'configparser.ConfigParser', ([], {}), '()\n', (758, 760), False, 'import configparser\n'), ((1191, 1230), 'logging.debug', 'logging.debug', (['"""Creating %s"""', 'conf_path'], {}), "('Creating %s', conf_path)\n", (1204, 1230), False, 'import logging\n')]
from django.db import models from django.conf import settings from django.urls import reverse # Create your models here. class Room(models.Model): ROOM_CATEGORIES = ( ('BZS', 'BUSINESS SUITE'), ('TNS', 'TWIN SUITE'), ('EXS', 'EXECUTIVE SUITE'), ('SGB', 'SINGLE BED'), ) room_number = models.IntegerField(null=True, blank=True) category = models.CharField(choices=ROOM_CATEGORIES, max_length=3) beds = models.IntegerField(null=True, blank=True) capacity = models.IntegerField(null=True, blank=True) price = models.FloatField(null=True, blank=True) image_url = models.CharField(max_length=1000, null=True,blank=True) def __str__(self): return f'{self.room_number}.{self.category} with {self.beds} bed(s) for {self.capacity} person(s) @ KSH. {self.price}' class Booking(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) room = models.ForeignKey(Room, on_delete=models.CASCADE) check_in = models.DateTimeField() check_out = models.DateTimeField() def __str__(self): return f'{self.user} has booked {self.room} from {self.check_in} to {self.check_out}' def get_category(self): categories = dict(self.room.ROOM_CATEGORIES) category = categories.get(self.room.category) return category def cancel_booking(self): return reverse('booking:CancelBookingView', args=[self.pk, ])
[ "django.db.models.FloatField", "django.db.models.ForeignKey", "django.db.models.IntegerField", "django.urls.reverse", "django.db.models.DateTimeField", "django.db.models.CharField" ]
[((329, 371), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'null': '(True)', 'blank': '(True)'}), '(null=True, blank=True)\n', (348, 371), False, 'from django.db import models\n'), ((387, 442), 'django.db.models.CharField', 'models.CharField', ([], {'choices': 'ROOM_CATEGORIES', 'max_length': '(3)'}), '(choices=ROOM_CATEGORIES, max_length=3)\n', (403, 442), False, 'from django.db import models\n'), ((454, 496), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'null': '(True)', 'blank': '(True)'}), '(null=True, blank=True)\n', (473, 496), False, 'from django.db import models\n'), ((512, 554), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'null': '(True)', 'blank': '(True)'}), '(null=True, blank=True)\n', (531, 554), False, 'from django.db import models\n'), ((567, 607), 'django.db.models.FloatField', 'models.FloatField', ([], {'null': '(True)', 'blank': '(True)'}), '(null=True, blank=True)\n', (584, 607), False, 'from django.db import models\n'), ((624, 680), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(1000)', 'null': '(True)', 'blank': '(True)'}), '(max_length=1000, null=True, blank=True)\n', (640, 680), False, 'from django.db import models\n'), ((877, 946), 'django.db.models.ForeignKey', 'models.ForeignKey', (['settings.AUTH_USER_MODEL'], {'on_delete': 'models.CASCADE'}), '(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)\n', (894, 946), False, 'from django.db import models\n'), ((958, 1007), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Room'], {'on_delete': 'models.CASCADE'}), '(Room, on_delete=models.CASCADE)\n', (975, 1007), False, 'from django.db import models\n'), ((1023, 1045), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {}), '()\n', (1043, 1045), False, 'from django.db import models\n'), ((1062, 1084), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {}), '()\n', (1082, 1084), False, 'from django.db import models\n'), ((1409, 1461), 'django.urls.reverse', 'reverse', (['"""booking:CancelBookingView"""'], {'args': '[self.pk]'}), "('booking:CancelBookingView', args=[self.pk])\n", (1416, 1461), False, 'from django.urls import reverse\n')]
from HABApp.openhab.connection_handler import http_connection from ._plugin import on_connect, on_disconnect, setup_plugins log = http_connection.log def setup(): from HABApp.runtime import shutdown # initialize callbacks http_connection.ON_CONNECTED = on_connect http_connection.ON_DISCONNECTED = on_disconnect # shutdown handler for connection shutdown.register_func(http_connection.stop_connection, msg='Stopping openHAB connection') # shutdown handler for plugins shutdown.register_func(on_disconnect, msg='Stopping openHAB plugins') # initialize all plugins setup_plugins() return None async def start(): await http_connection.start_connection()
[ "HABApp.runtime.shutdown.register_func", "HABApp.openhab.connection_handler.http_connection.start_connection" ]
[((375, 470), 'HABApp.runtime.shutdown.register_func', 'shutdown.register_func', (['http_connection.stop_connection'], {'msg': '"""Stopping openHAB connection"""'}), "(http_connection.stop_connection, msg=\n 'Stopping openHAB connection')\n", (397, 470), False, 'from HABApp.runtime import shutdown\n'), ((506, 575), 'HABApp.runtime.shutdown.register_func', 'shutdown.register_func', (['on_disconnect'], {'msg': '"""Stopping openHAB plugins"""'}), "(on_disconnect, msg='Stopping openHAB plugins')\n", (528, 575), False, 'from HABApp.runtime import shutdown\n'), ((673, 707), 'HABApp.openhab.connection_handler.http_connection.start_connection', 'http_connection.start_connection', ([], {}), '()\n', (705, 707), False, 'from HABApp.openhab.connection_handler import http_connection\n')]
#Imported to DeOXy from userbot import bot, BOTLOG_CHATID, ALIVE_NAME, CMD_LIST import asyncio from telethon import events from telethon.tl.functions.channels import EditBannedRequest from telethon.tl.types import (PeerChat, PeerChannel,ChannelParticipantsAdmins, ChatAdminRights,ChatBannedRights, MessageEntityMentionName,MessageMediaPhoto, ChannelParticipantsBots) from telethon.tl.types import Channel from telethon.tl.functions.contacts import BlockRequest, UnblockRequest client = telebot = bot from telethon.tl.functions.messages import GetCommonChatsRequest ALIVE_NAME = str(ALIVE_NAME) from telethon.events import ChatAction # Imported from @javes05 # Kangers keep the credits -_- @command(outgoing=True, pattern="^.gban(?: |$)(.*)") async def startgban(tb): oof = tb ; sender = await oof.get_sender() ; me = await oof.client.get_me() if not sender.id == me.id: tele = await oof.reply("`Processing...`") else: tele = await oof.edit("`Processing...`") me = await tb.client.get_me() ; await tele.edit(f"`{ALIVE_NAME}:` **Globally Banning user!**") ; my_mention = "[{}](tg://user?id={})".format(me.first_name, me.id) ; my_username = f"@{me.username}" if me.username else my_mention ; chat = await tb.get_chat() ; a = b = 0 if tb.is_private: user = tb.chat ; reason = tb.pattern_match.group(1) ; chat_title = 'PM' else: chat_title = tb.chat.title try: user, reason = await get_user_from_event(tb) except: pass try: if not reason: reason = 'Private' except: return await tele.edit(f"`{ALIVE_NAME}:`**User not found.**") if user: if user.id == 767014786: return await tele.edit(f"`{ALIVE_NAME}:`**DeOXy MASTER: Denied.**") try: from userbot.modules.sql_helper.gmute_sql import gmute except: pass try: await tb.client(BlockRequest(user)) block = 'True' except: pass testtb = [d.entity.id for d in await tb.client.get_dialogs() if (d.is_group or d.is_channel) ] for i in testtb: try: await tb.client.edit_permissions(i, user, view_messages=False) a += 1 await tele.edit(f"`{ALIVE_NAME}:` **Global Banning User!\nGbanned {a} chats.....**") except: b += 1 else: await tele.edit(f"`{ALIVE_NAME}:` **Reply to a user !! **") try: if gmute(user.id) is False: return await tele.edit(f"`{ALIVE_NAME}:`**DeOXy MATER: User already Gbanned**") except: pass return await tele.edit(f"`{ALIVE_NAME}:` **Gbanned [{user.first_name}](tg://user?id={user.id}) in {a} chat(s) **") @command(outgoing=True, pattern="^;ungban(?: |$)(.*)") async def regressgban(tb): oof = tb ; sender = await oof.get_sender() ; me = await oof.client.get_me() if not sender.id == me.id: tele = await oof.reply("`Processing...`") else: tele = await oof.edit("`processing...`") me = await tb.client.get_me() ; await tele.edit(f"`{ALIVE_NAME}:` **Requesting to UnGban user!**") ; my_mention = "[{}](tg://user?id={})".format(me.first_name, me.id) ; my_username = f"@{me.username}" if me.username else my_mention ; chat = await tb.get_chat() ; a = b = 0 if tb.is_private: user = tb.chat ; reason = tb.pattern_match.group(1) ; chat_title = 'PM' else: chat_title = tb.chat.title try: user, reason = await get_user_from_event(tb) except: pass try: if not reason: reason = 'Private' except: return await tele.edit(f"`{ALIVE_NAME}:`**DeOXy MASTER: User not found. Invalid argument**") if user: if user.id == 767014786: return await tele.edit(f"`{ALIVE_NAME}:`**DeOXy MASTER: Denied.**") try: from userbot.modules.sql_helper.gmute_sql import ungmute except: pass try: await tb.client(UnblockRequest(user)) block = 'True' except: pass testtb = [d.entity.id for d in await tb.client.get_dialogs() if (d.is_group or d.is_channel) ] for i in testtb: try: await tb.client.edit_permissions(i, user, send_messages=True) a += 1 await tele.edit(f"`{ALIVE_NAME}:` **Requesting to ungban user!\nunGbanned {a} chats.....**") except: b += 1 else: await tele.edit(f"`{ALIVE_NAME}:` **DeOXy MASTER: User not found, Reply to a user**") try: if ungmute(user.id) is False: return await tele.edit(f"`{ALIVE_NAME}:`**DeOXy MASTER: Invalid argument, Already Gbanned**") except: pass return await tele.edit(f"`{ALIVE_NAME}:` **UnGbanned [{user.first_name}](tg://user?id={user.id}) in {a} chat(s) **")
[ "telethon.tl.functions.contacts.BlockRequest", "userbot.modules.sql_helper.gmute_sql.gmute", "telethon.tl.functions.contacts.UnblockRequest", "userbot.modules.sql_helper.gmute_sql.ungmute" ]
[((2568, 2582), 'userbot.modules.sql_helper.gmute_sql.gmute', 'gmute', (['user.id'], {}), '(user.id)\n', (2573, 2582), False, 'from userbot.modules.sql_helper.gmute_sql import gmute\n'), ((4763, 4779), 'userbot.modules.sql_helper.gmute_sql.ungmute', 'ungmute', (['user.id'], {}), '(user.id)\n', (4770, 4779), False, 'from userbot.modules.sql_helper.gmute_sql import ungmute\n'), ((1933, 1951), 'telethon.tl.functions.contacts.BlockRequest', 'BlockRequest', (['user'], {}), '(user)\n', (1945, 1951), False, 'from telethon.tl.functions.contacts import BlockRequest, UnblockRequest\n'), ((4092, 4112), 'telethon.tl.functions.contacts.UnblockRequest', 'UnblockRequest', (['user'], {}), '(user)\n', (4106, 4112), False, 'from telethon.tl.functions.contacts import BlockRequest, UnblockRequest\n')]
import bluetooth import time import RPi.GPIO as GPIO from bt_rssi import BluetoothRSSI search_time = 10 GPIO.setmode(GPIO.BCM) GPIO.setup(17, GPIO.OUT) THRESHOLD = (-13, 38) # You can hardcode the desired device ID here as a string to skip the discovery stage addr = "F4:AF:E7:72:CB:19" b = BluetoothRSSI(addr=addr) print("Welcome to the Bluetooth Detection Demo! \nMake sure your desired Bluetooth-capable device is turned on and " "discoverable.") try: if addr is None: try: input("When you are ready to begin, press the Enter key to continue...") except SyntaxError: pass print("Searching for devices...") nearby_devices = bluetooth.discover_devices(duration=search_time, flush_cache=True, lookup_names=True) if len(nearby_devices) > 0: print("Found %d devices!" % len(nearby_devices)) else: print("No devices found! Please check your Bluetooth device and restart the demo!") exit(0) i = 0 # Just an incrementer for labeling the list entries # Print out a list of all the discovered Bluetooth Devices for addr, name in nearby_devices: print("%s. %s - %s" % (i, addr, name)) i = + 1 device_num = input("Please specify the number of the device you want to track: ") # extract out the useful info on the desired device for use later addr, name = nearby_devices[device_num][0], nearby_devices[device_num][1] print("The script will now scan for the device %s." % addr) print("Feel free to move near and far away from the BeagleBone to see the state change on " "the LED.\nUse Ctrl+c to exit...") while True: # Try to gather information from the desired device. # We're using two different metrics (readable name and data services) # to reduce false negatives. rssi = b.get_rssi() state = bluetooth.lookup_name(addr, timeout=20) services = bluetooth.find_service(address=addr) # Flip the LED pin on or off depending on whether the device is nearby if THRESHOLD[0] < rssi < THRESHOLD[1]: GPIO.output(17, 1) else: GPIO.output(17, 0) # Arbitrary wait time time.sleep(1) except: print("Exited...") finally: GPIO.cleanup()
[ "RPi.GPIO.cleanup", "bt_rssi.BluetoothRSSI", "bluetooth.discover_devices", "RPi.GPIO.setup", "RPi.GPIO.output", "time.sleep", "bluetooth.find_service", "RPi.GPIO.setmode", "bluetooth.lookup_name" ]
[((105, 127), 'RPi.GPIO.setmode', 'GPIO.setmode', (['GPIO.BCM'], {}), '(GPIO.BCM)\n', (117, 127), True, 'import RPi.GPIO as GPIO\n'), ((128, 152), 'RPi.GPIO.setup', 'GPIO.setup', (['(17)', 'GPIO.OUT'], {}), '(17, GPIO.OUT)\n', (138, 152), True, 'import RPi.GPIO as GPIO\n'), ((292, 316), 'bt_rssi.BluetoothRSSI', 'BluetoothRSSI', ([], {'addr': 'addr'}), '(addr=addr)\n', (305, 316), False, 'from bt_rssi import BluetoothRSSI\n'), ((2340, 2354), 'RPi.GPIO.cleanup', 'GPIO.cleanup', ([], {}), '()\n', (2352, 2354), True, 'import RPi.GPIO as GPIO\n'), ((697, 786), 'bluetooth.discover_devices', 'bluetooth.discover_devices', ([], {'duration': 'search_time', 'flush_cache': '(True)', 'lookup_names': '(True)'}), '(duration=search_time, flush_cache=True,\n lookup_names=True)\n', (723, 786), False, 'import bluetooth\n'), ((1946, 1985), 'bluetooth.lookup_name', 'bluetooth.lookup_name', (['addr'], {'timeout': '(20)'}), '(addr, timeout=20)\n', (1967, 1985), False, 'import bluetooth\n'), ((2005, 2041), 'bluetooth.find_service', 'bluetooth.find_service', ([], {'address': 'addr'}), '(address=addr)\n', (2027, 2041), False, 'import bluetooth\n'), ((2282, 2295), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (2292, 2295), False, 'import time\n'), ((2180, 2198), 'RPi.GPIO.output', 'GPIO.output', (['(17)', '(1)'], {}), '(17, 1)\n', (2191, 2198), True, 'import RPi.GPIO as GPIO\n'), ((2225, 2243), 'RPi.GPIO.output', 'GPIO.output', (['(17)', '(0)'], {}), '(17, 0)\n', (2236, 2243), True, 'import RPi.GPIO as GPIO\n')]
import clockngpn.totp as totp from clockngpn.proc_worker import Event, Broker, ProcWorkerEvent from clockngpn.ttp import TocTocPorts, TocTocPortsWorker from queue import Queue import time import os import logging from clockngpn.bidi import OTPBidi import signal import argparse log = logging.getLogger(__name__) def check_environment(): if not os.geteuid() == 0: raise Exception("This program needs root for managing IPTABLES!") try: import iptc except Exception as _: if 'XTABLES_LIBDIR' not in os.environ: os.environ['XTABLES_LIBDIR'] = '/usr/lib/x86_64-linux-gnu/xtables' else: raise Exception("Error, la variable XTABLES_LIBDIR está mal configurada") # TODO Sacar a una clase y hacer el main con arg_parser def main_server(secret, slot, address, ports, opened): try: check_environment() except Exception as e: log.error(e) exit(-1) log.debug("Secret: %s" % secret) from clockngpn.port_manager import PortManagerWorker, PortManager from clockngpn.firewall_manager import FirewallManager, FirewallManagerWorker oq = Queue() bq = Queue() b = Broker(bq, oq) fwmq = Queue() b.add_client(fwmq) fwm = FirewallManager() fwmw = FirewallManagerWorker(fwmq, bq, fwm=fwm) for port in opened: fwm.open(port) pmq = Queue() b.add_client(pmq) pm = PortManager(address, unmanaged_ports=opened) pmw = PortManagerWorker(pmq, bq, pm=pm) ttpq = Queue() b.add_client(ttpq) ttp = TocTocPorts(secret, destination=ports) ttpw = TocTocPortsWorker(ttpq, bq, ttp) fwmw.start() pmw.start() ttpw.start() b.start() # TODO Refactor de este método def end(signum, *args): log.warning('Signal handler called with signal %s' % signum) bq.put(Event(ProcWorkerEvent.END, None)) retry = 0 while retry <= 3: if not fwmw.is_alive() and not pmw.is_alive() and not ttpw.is_alive() and not b.is_alive(): break time.sleep(retry * 1) if fwmw.is_alive(): log.warning("Bad killing thread fwmw") if pmw.is_alive(): log.warning("Bad killing thread pmw") if ttpw.is_alive(): log.warning("Bad killing thread ttpw") if b.is_alive(): log.warning("Bad killing thread broker") if fwmw.is_alive() or pmw.is_alive() or ttpw.is_alive() or b.is_alive(): exit(0) signal.signal(signal.SIGINT, end) signal.signal(signal.SIGSEGV, end) signal.signal(signal.SIGFPE, end) signal.signal(signal.SIGABRT, end) signal.signal(signal.SIGBUS, end) signal.signal(signal.SIGILL, end) # TODO Clase orquestador def main(): log_levels = { 'DEBUG': logging.DEBUG, 'INFO': logging.INFO, 'WARNING': logging.WARNING, 'ERROR': logging.ERROR, 'CRITICAL': logging.CRITICAL, 'QUIET': logging.NOTSET } parser = argparse.ArgumentParser(description='Launch TOTP based port knocking protection') parser.add_argument('-ts', '--time-slot', dest='slot', default=30, type=int, help='Time slot for TOTP') parser.add_argument('-a', '--address', default='0.0.0.0', help="Address to protect") parser.add_argument('-s', '--secret', help="Secret part of TOTP") parser.add_argument('-p', '--protected-ports', type=int, default=[], action='append', help="Port which has to be protected") parser.add_argument('-o', '--opened-ports', type=int, default=[], action='append', help="Port which should be opened") parser.add_argument('--gen-secret', help="Generate random secret", action='store_true') parser.add_argument('--clean-firewall', help="Clean firewall configuration (e.g., after a bad close)", action='store_true') parser.add_argument('--log-level', default="DEBUG", help="Log level") # parser.add_argument('--config-file') args = parser.parse_args() log_level = args.log_level level = log_levels.get(log_level, logging.DEBUG) logging.basicConfig( level=level, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) if args.clean_firewall: try: check_environment() except Exception as e: log.error(e) exit(-1) from clockng.firewall_manager import FirewallManager FirewallManager().clean_firewall() elif args.gen_secret: i_secret = totp.gen_secret() otp_bidi = OTPBidi(i_secret) print("TOTP generated secret: %s" % i_secret) print(otp_bidi.generate()) elif args.secret: i_secret = args.secret try: secret = totp.web_secret_2_bytes(i_secret) except Exception as e: log.error("Bad secret: Remember secret must be b32") return slot = args.slot address = args.address ports = args.protected_ports if args.protected_ports else [] opened = args.opened_ports main_server(secret, slot, address, ports, opened) else: log.error("A secret is required to start") parser.print_help() return if __name__ == '__main__': main()
[ "logging.getLogger", "logging.basicConfig", "signal.signal", "argparse.ArgumentParser", "clockngpn.port_manager.PortManager", "clockngpn.ttp.TocTocPorts", "clockngpn.proc_worker.Broker", "clockngpn.totp.web_secret_2_bytes", "clockngpn.totp.gen_secret", "clockng.firewall_manager.FirewallManager", ...
[((287, 314), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (304, 314), False, 'import logging\n'), ((1148, 1155), 'queue.Queue', 'Queue', ([], {}), '()\n', (1153, 1155), False, 'from queue import Queue\n'), ((1165, 1172), 'queue.Queue', 'Queue', ([], {}), '()\n', (1170, 1172), False, 'from queue import Queue\n'), ((1182, 1196), 'clockngpn.proc_worker.Broker', 'Broker', (['bq', 'oq'], {}), '(bq, oq)\n', (1188, 1196), False, 'from clockngpn.proc_worker import Event, Broker, ProcWorkerEvent\n'), ((1209, 1216), 'queue.Queue', 'Queue', ([], {}), '()\n', (1214, 1216), False, 'from queue import Queue\n'), ((1250, 1267), 'clockng.firewall_manager.FirewallManager', 'FirewallManager', ([], {}), '()\n', (1265, 1267), False, 'from clockng.firewall_manager import FirewallManager\n'), ((1279, 1319), 'clockngpn.firewall_manager.FirewallManagerWorker', 'FirewallManagerWorker', (['fwmq', 'bq'], {'fwm': 'fwm'}), '(fwmq, bq, fwm=fwm)\n', (1300, 1319), False, 'from clockngpn.firewall_manager import FirewallManager, FirewallManagerWorker\n'), ((1379, 1386), 'queue.Queue', 'Queue', ([], {}), '()\n', (1384, 1386), False, 'from queue import Queue\n'), ((1418, 1462), 'clockngpn.port_manager.PortManager', 'PortManager', (['address'], {'unmanaged_ports': 'opened'}), '(address, unmanaged_ports=opened)\n', (1429, 1462), False, 'from clockngpn.port_manager import PortManagerWorker, PortManager\n'), ((1473, 1506), 'clockngpn.port_manager.PortManagerWorker', 'PortManagerWorker', (['pmq', 'bq'], {'pm': 'pm'}), '(pmq, bq, pm=pm)\n', (1490, 1506), False, 'from clockngpn.port_manager import PortManagerWorker, PortManager\n'), ((1519, 1526), 'queue.Queue', 'Queue', ([], {}), '()\n', (1524, 1526), False, 'from queue import Queue\n'), ((1560, 1598), 'clockngpn.ttp.TocTocPorts', 'TocTocPorts', (['secret'], {'destination': 'ports'}), '(secret, destination=ports)\n', (1571, 1598), False, 'from clockngpn.ttp import TocTocPorts, TocTocPortsWorker\n'), ((1610, 1642), 'clockngpn.ttp.TocTocPortsWorker', 'TocTocPortsWorker', (['ttpq', 'bq', 'ttp'], {}), '(ttpq, bq, ttp)\n', (1627, 1642), False, 'from clockngpn.ttp import TocTocPorts, TocTocPortsWorker\n'), ((2515, 2548), 'signal.signal', 'signal.signal', (['signal.SIGINT', 'end'], {}), '(signal.SIGINT, end)\n', (2528, 2548), False, 'import signal\n'), ((2553, 2587), 'signal.signal', 'signal.signal', (['signal.SIGSEGV', 'end'], {}), '(signal.SIGSEGV, end)\n', (2566, 2587), False, 'import signal\n'), ((2592, 2625), 'signal.signal', 'signal.signal', (['signal.SIGFPE', 'end'], {}), '(signal.SIGFPE, end)\n', (2605, 2625), False, 'import signal\n'), ((2630, 2664), 'signal.signal', 'signal.signal', (['signal.SIGABRT', 'end'], {}), '(signal.SIGABRT, end)\n', (2643, 2664), False, 'import signal\n'), ((2669, 2702), 'signal.signal', 'signal.signal', (['signal.SIGBUS', 'end'], {}), '(signal.SIGBUS, end)\n', (2682, 2702), False, 'import signal\n'), ((2707, 2740), 'signal.signal', 'signal.signal', (['signal.SIGILL', 'end'], {}), '(signal.SIGILL, end)\n', (2720, 2740), False, 'import signal\n'), ((3024, 3110), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Launch TOTP based port knocking protection"""'}), "(description=\n 'Launch TOTP based port knocking protection')\n", (3047, 3110), False, 'import argparse\n'), ((4085, 4185), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'level', 'format': '"""%(asctime)s - %(name)s - %(levelname)s - %(message)s"""'}), "(level=level, format=\n '%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n", (4104, 4185), False, 'import logging\n'), ((354, 366), 'os.geteuid', 'os.geteuid', ([], {}), '()\n', (364, 366), False, 'import os\n'), ((1856, 1888), 'clockngpn.proc_worker.Event', 'Event', (['ProcWorkerEvent.END', 'None'], {}), '(ProcWorkerEvent.END, None)\n', (1861, 1888), False, 'from clockngpn.proc_worker import Event, Broker, ProcWorkerEvent\n'), ((2072, 2093), 'time.sleep', 'time.sleep', (['(retry * 1)'], {}), '(retry * 1)\n', (2082, 2093), False, 'import time\n'), ((4508, 4525), 'clockngpn.totp.gen_secret', 'totp.gen_secret', ([], {}), '()\n', (4523, 4525), True, 'import clockngpn.totp as totp\n'), ((4546, 4563), 'clockngpn.bidi.OTPBidi', 'OTPBidi', (['i_secret'], {}), '(i_secret)\n', (4553, 4563), False, 'from clockngpn.bidi import OTPBidi\n'), ((4426, 4443), 'clockng.firewall_manager.FirewallManager', 'FirewallManager', ([], {}), '()\n', (4441, 4443), False, 'from clockng.firewall_manager import FirewallManager\n'), ((4743, 4776), 'clockngpn.totp.web_secret_2_bytes', 'totp.web_secret_2_bytes', (['i_secret'], {}), '(i_secret)\n', (4766, 4776), True, 'import clockngpn.totp as totp\n')]
""" CLI for azureml module. """ import json import click from mlflow.google.aiplatform import register_model as do_register_model from mlflow.utils import cli_args from mlflow.utils.annotations import experimental @click.group("google") def commands(): """ Serve models on Google Cloud AI Platform. **These commands require that MLflow be installed with Python 3.** To serve a model associated with a run on a tracking server, set the MLFLOW_TRACKING_URI environment variable to the URL of the desired server. """ pass @commands.command( short_help=( "Build a container and register an MLflow model with" " Cloud AI Platform for deployment." ) ) @cli_args.MODEL_URI @click.option( "--display-name", "-n", required=True, help="Name of the model when it's registered on Cloud AI Platform", ) @click.option( "--model-options", "-o", default=None, help="JSON string of other attributes of the Cloud AI Platform Model object, like labels and schema", ) @click.option( "--project", "-p", default=None, help="The Google Cloud Platform project in which to build image and register the model," " as a string. Uses the default project from gcloud config set <PROJECT_ID> if not set" ) @click.option( "--destination-image-uri", "-t", default=None, help="The name of the container image that will be built with your model inside of it." " Should be of the format ``gcr.io/<REPO>/<IMAGE>:<TAG>``. Defaults to" " gcr.io/<DEFAULT PROJECT>/<MODEL NAME>/<LATEST>" ) @click.option( "--location", "-l", default="us-central1", help="The GCP region that your model will be created in. Defaults to us-central1" ) @click.option( "--wait-timeout", "-w", default=1800, help="How long to wait for model deployment to complete. Defaults to 30 minutes." ) @click.option( "--mlflow-source-dir", default=None, help="Optionally, specify a dir to install MLFlow from instead of PyPI" ) @experimental def register_model( model_uri: str, display_name: str, destination_image_uri: str, mlflow_source_dir: str, model_options: dict, project: str, location: str, wait_timeout: int ): """ Build a container image included your model that's ready to serve on Google Cloud AI Platform. Push the container image and register a model. After you run this step, you should use gcloud to create an endpoint and deploy the model behind it. See https://cloud.google.com/ai-platform-unified/docs/predictions/deploy-model-api """ model_cfg = None if model_options is not None: model_cfg = json.loads(model_options) do_register_model( model_uri=model_uri, display_name=display_name, destination_image_uri=destination_image_uri, mlflow_source_dir=mlflow_source_dir, model_options=model_cfg, project=project, location=location, synchronous=True, wait_timeout=wait_timeout )
[ "click.group", "click.option", "json.loads", "mlflow.google.aiplatform.register_model" ]
[((219, 240), 'click.group', 'click.group', (['"""google"""'], {}), "('google')\n", (230, 240), False, 'import click\n'), ((722, 846), 'click.option', 'click.option', (['"""--display-name"""', '"""-n"""'], {'required': '(True)', 'help': '"""Name of the model when it\'s registered on Cloud AI Platform"""'}), '(\'--display-name\', \'-n\', required=True, help=\n "Name of the model when it\'s registered on Cloud AI Platform")\n', (734, 846), False, 'import click\n'), ((862, 1025), 'click.option', 'click.option', (['"""--model-options"""', '"""-o"""'], {'default': 'None', 'help': '"""JSON string of other attributes of the Cloud AI Platform Model object, like labels and schema"""'}), "('--model-options', '-o', default=None, help=\n 'JSON string of other attributes of the Cloud AI Platform Model object, like labels and schema'\n )\n", (874, 1025), False, 'import click\n'), ((1036, 1266), 'click.option', 'click.option', (['"""--project"""', '"""-p"""'], {'default': 'None', 'help': '"""The Google Cloud Platform project in which to build image and register the model, as a string. Uses the default project from gcloud config set <PROJECT_ID> if not set"""'}), "('--project', '-p', default=None, help=\n 'The Google Cloud Platform project in which to build image and register the model, as a string. Uses the default project from gcloud config set <PROJECT_ID> if not set'\n )\n", (1048, 1266), False, 'import click\n'), ((1288, 1562), 'click.option', 'click.option', (['"""--destination-image-uri"""', '"""-t"""'], {'default': 'None', 'help': '"""The name of the container image that will be built with your model inside of it. Should be of the format ``gcr.io/<REPO>/<IMAGE>:<TAG>``. Defaults to gcr.io/<DEFAULT PROJECT>/<MODEL NAME>/<LATEST>"""'}), "('--destination-image-uri', '-t', default=None, help=\n 'The name of the container image that will be built with your model inside of it. Should be of the format ``gcr.io/<REPO>/<IMAGE>:<TAG>``. Defaults to gcr.io/<DEFAULT PROJECT>/<MODEL NAME>/<LATEST>'\n )\n", (1300, 1562), False, 'import click\n'), ((1596, 1744), 'click.option', 'click.option', (['"""--location"""', '"""-l"""'], {'default': '"""us-central1"""', 'help': '"""The GCP region that your model will be created in. Defaults to us-central1"""'}), "('--location', '-l', default='us-central1', help=\n 'The GCP region that your model will be created in. Defaults to us-central1'\n )\n", (1608, 1744), False, 'import click\n'), ((1754, 1897), 'click.option', 'click.option', (['"""--wait-timeout"""', '"""-w"""'], {'default': '(1800)', 'help': '"""How long to wait for model deployment to complete. Defaults to 30 minutes."""'}), "('--wait-timeout', '-w', default=1800, help=\n 'How long to wait for model deployment to complete. Defaults to 30 minutes.'\n )\n", (1766, 1897), False, 'import click\n'), ((1907, 2034), 'click.option', 'click.option', (['"""--mlflow-source-dir"""'], {'default': 'None', 'help': '"""Optionally, specify a dir to install MLFlow from instead of PyPI"""'}), "('--mlflow-source-dir', default=None, help=\n 'Optionally, specify a dir to install MLFlow from instead of PyPI')\n", (1919, 2034), False, 'import click\n'), ((2738, 3005), 'mlflow.google.aiplatform.register_model', 'do_register_model', ([], {'model_uri': 'model_uri', 'display_name': 'display_name', 'destination_image_uri': 'destination_image_uri', 'mlflow_source_dir': 'mlflow_source_dir', 'model_options': 'model_cfg', 'project': 'project', 'location': 'location', 'synchronous': '(True)', 'wait_timeout': 'wait_timeout'}), '(model_uri=model_uri, display_name=display_name,\n destination_image_uri=destination_image_uri, mlflow_source_dir=\n mlflow_source_dir, model_options=model_cfg, project=project, location=\n location, synchronous=True, wait_timeout=wait_timeout)\n', (2755, 3005), True, 'from mlflow.google.aiplatform import register_model as do_register_model\n'), ((2708, 2733), 'json.loads', 'json.loads', (['model_options'], {}), '(model_options)\n', (2718, 2733), False, 'import json\n')]
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 import numpy as np from music21 import midi import pypianoroll from pypianoroll import Multitrack from texttable import Texttable import os from pprint import pprint def play_midi(input_midi): '''Takes path to an input and plays the midi file in the notebook cell :param input_midi: Path to midi file :return: ''' midi_object = midi.MidiFile() midi_object.open(input_midi) midi_object.read() midi_object.close() show_midi = midi.translate.midiFileToStream(midi_object) show_midi.show('midi') def find_files_by_extensions(root, exts=[]): def _has_ext(name): if not exts: return True name = name.lower() for ext in exts: if name.endswith(ext): return True return False for path, _, files in os.walk(root): for name in files: if _has_ext(name): yield os.path.join(path, name) def print_sample_array(split, parent_dir="data/jsb_chorales_numpy"): """ Prints a randomly sampled numpy array from the parent_dir """ midi_files = [ os.path.join(parent_dir, split, midi) for midi in os.listdir(os.path.join(parent_dir, split)) ] selection = np.random.choice(midi_files) pprint(np.load(selection))
[ "numpy.random.choice", "os.path.join", "music21.midi.MidiFile", "music21.midi.translate.midiFileToStream", "numpy.load", "os.walk" ]
[((457, 472), 'music21.midi.MidiFile', 'midi.MidiFile', ([], {}), '()\n', (470, 472), False, 'from music21 import midi\n'), ((569, 613), 'music21.midi.translate.midiFileToStream', 'midi.translate.midiFileToStream', (['midi_object'], {}), '(midi_object)\n', (600, 613), False, 'from music21 import midi\n'), ((920, 933), 'os.walk', 'os.walk', (['root'], {}), '(root)\n', (927, 933), False, 'import os\n'), ((1356, 1384), 'numpy.random.choice', 'np.random.choice', (['midi_files'], {}), '(midi_files)\n', (1372, 1384), True, 'import numpy as np\n'), ((1232, 1269), 'os.path.join', 'os.path.join', (['parent_dir', 'split', 'midi'], {}), '(parent_dir, split, midi)\n', (1244, 1269), False, 'import os\n'), ((1396, 1414), 'numpy.load', 'np.load', (['selection'], {}), '(selection)\n', (1403, 1414), True, 'import numpy as np\n'), ((1301, 1332), 'os.path.join', 'os.path.join', (['parent_dir', 'split'], {}), '(parent_dir, split)\n', (1313, 1332), False, 'import os\n'), ((1015, 1039), 'os.path.join', 'os.path.join', (['path', 'name'], {}), '(path, name)\n', (1027, 1039), False, 'import os\n')]
# ***************************************************************** # Copyright 2013 MIT Lincoln Laboratory # Project: SPAR # Authors: SY # Description: Section class # # # Modifications: # Date Name Modification # ---- ---- ------------ # 19 Sep 2013 SY Original version # ***************************************************************** # SPAR imports: import spar_python.report_generation.ta1.ta1_section as section import spar_python.report_generation.common.regression as regression import spar_python.report_generation.common.latex_classes as latex_classes import spar_python.report_generation.ta1.ta1_schema as t1s import spar_python.report_generation.ta1.ta1_analysis_percentiles as percentiles import spar_python.report_generation.ta1.ta1_analysis_input as t1ai class Ta1PercentilesSection(section.Ta1Section): """The percentiles section of the TA1 report""" def _store_query_percentiles_table(self): """Stores the LaTeX string representing the query percentiles table on the output object.""" constraint_list = self._config.get_constraint_list( require_correct=True) categories = self._config.results_db.get_unique_query_values( simple_fields=[(t1s.DBF_TABLENAME, t1s.DBF_NUMRECORDS), (t1s.DBF_TABLENAME, t1s.DBF_RECORDSIZE), (t1s.DBP_TABLENAME, t1s.DBP_SELECTIONCOLS), (t1s.DBF_TABLENAME, t1s.DBF_CAT)], constraint_list=constraint_list) # create the percentiles table: caption = "Number of Percentiles passing the $%s+%sx$ requirement" % ( str(self._config.a_req), str(self._config.b_req)) percentiles_table = latex_classes.LatexTable( caption, "perc_main", ["DBNR", "DBRS", "Select", "Query Type", "Num Passing $\%$iles"]) # compute number of percentiles met for every query category: for (dbnr, dbrs, selection_cols, query_cat) in categories: inp = t1ai.Input() inp[t1s.DBF_CAT] = query_cat inp[t1s.DBF_NUMRECORDS] = dbnr inp[t1s.DBF_RECORDSIZE] = dbrs inp[t1s.DBP_SELECTIONCOLS] = selection_cols performer_constraint_list = self._config.get_constraint_list( usebaseline=False) + inp.get_constraint_list() baseline_constraint_list = self._config.get_constraint_list( usebaseline=True) + inp.get_constraint_list() percentile_getter = percentiles.Ta1PercentileGetter( self._config.results_db, performer_constraint_list, baseline_constraint_list) if percentile_getter.has_values(): all_met = percentile_getter.get_all_met( self._config.a_req, self._config.b_req) percentiles_table.add_content([ inp.test_db.get_db_num_records_str(), inp.test_db.get_db_record_size_str(), selection_cols, query_cat, len(all_met)]) self._outp["query_percentiles_table"] = percentiles_table.get_string() def _populate_output(self): """Populates the output object which is passed to the Jinja tempalte in get_string.""" self._store_query_percentiles_table()
[ "spar_python.report_generation.common.latex_classes.LatexTable", "spar_python.report_generation.ta1.ta1_analysis_input.Input", "spar_python.report_generation.ta1.ta1_analysis_percentiles.Ta1PercentileGetter" ]
[((1833, 1950), 'spar_python.report_generation.common.latex_classes.LatexTable', 'latex_classes.LatexTable', (['caption', '"""perc_main"""', "['DBNR', 'DBRS', 'Select', 'Query Type', 'Num Passing $\\\\%$iles']"], {}), "(caption, 'perc_main', ['DBNR', 'DBRS', 'Select',\n 'Query Type', 'Num Passing $\\\\%$iles'])\n", (1857, 1950), True, 'import spar_python.report_generation.common.latex_classes as latex_classes\n'), ((2126, 2138), 'spar_python.report_generation.ta1.ta1_analysis_input.Input', 't1ai.Input', ([], {}), '()\n', (2136, 2138), True, 'import spar_python.report_generation.ta1.ta1_analysis_input as t1ai\n'), ((2626, 2739), 'spar_python.report_generation.ta1.ta1_analysis_percentiles.Ta1PercentileGetter', 'percentiles.Ta1PercentileGetter', (['self._config.results_db', 'performer_constraint_list', 'baseline_constraint_list'], {}), '(self._config.results_db,\n performer_constraint_list, baseline_constraint_list)\n', (2657, 2739), True, 'import spar_python.report_generation.ta1.ta1_analysis_percentiles as percentiles\n')]
#-*- encoding: utf-8 -*- """ About : Code to run as a linux daemon service, interface with it via REST POST """ __author__ = "<NAME>" __email__ = "<EMAIL>" __company__ = "" __copyright__ = "Copyright (C) 2020 {a}".format(a=__author__) __credits__ = "" __license__ = "MIT" __version__ = 0.03 __lastdate__ = "2020-04-13" # ---------------------------------------------------------------------------------------------------------------------- # # Supporting libraries # import json import os import sqlite3 import time import threading import uuid from http.server import HTTPServer, BaseHTTPRequestHandler from io import BytesIO from queue import Queue from pprint import pprint # ---------------------------------------------------------------------------------------------------------------------- # # Support Classes # class LocalData(object): records = Queue() @staticmethod def put(data): LocalData.records.put(data) @staticmethod def get(): return LocalData.records.get() @staticmethod def empty(): return LocalData.records.empty() @staticmethod def qsize(): return LocalData.records.qsize() class WebServerConfig(object): config = {} @staticmethod def set_static_directory(directory): WebServerConfig.config['Static Files Root'] = directory class WebServerRoutes(object): @staticmethod def index(): """ <!DOCTYPE html> <html> <head> <title>SLM Process</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> </head> <body> <div class="w3-container"> <h2>Rounded Images</h2> <p>The w3-round classes add rounded corners to an image:</p> <p>w3-round-small:</p> <img src="/images/img_lights.jpg" class="w3-round-small" alt="Norway" style="width:30%"> </div> </body> </html> """ page = ''' <!DOCTYPE html> <html lang="en"> <head> <meta charset='utf-8'> <meta name='viewport' content='width=device-width,initial-scale=1'> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <title>SLM Process App</title> <link rel='icon' type='image/png' href='/images/favicon.png'> <link rel='stylesheet' href='/css/global.css'> <link rel='stylesheet' href='/app/build/bundle.css'> <script defer src='/app/build/bundle.js'></script> </head> <body></body> </html>''' return page class SimpleHTTPRequestHandler(BaseHTTPRequestHandler): def file_check(self, path): allowed_file_types = WebServerConfig.config['Allowed File Types'] file_found = None for aft in allowed_file_types: if path.find(aft) != -1: # print('found {ff} file !'.format(ff=aft)) file_found = path break return file_found def get_file(self, file_found): sfr = WebServerConfig.config['Static Files Root'] full_file_path = '{r}{f}'.format(r=sfr, f=file_found) file_bytes = False try: with open(full_file_path, "rb") as f: file_bytes = f.read() except IOError as error: #print(error) pass finally: return file_bytes def do_GET(self): file_found = self.file_check(self.path) if file_found: file_bytes = self.get_file(file_found) if file_bytes is False: self.handle_404() else: self.send_response(200) self.end_headers() self.wfile.write(file_bytes) else: url_list = WebServerConfig.config['URL List'] if self.path in url_list: if 'GET' in url_list[self.path]: self.send_response(200) self.end_headers() page = WebServerRoutes.index() self.wfile.write(page.encode('utf-8')) else: self.handle_405() else: self.handle_404() def do_POST(self): content_length = int(self.headers['Content-Length']) body = self.rfile.read(content_length) url_list = WebServerConfig.config['URL List'] if self.path in url_list: if 'POST' in url_list[self.path]: if self.headers['Content-Type'] == 'application/json': raw_json = body.decode('utf-8') # Uncomment for testing only # print(raw_json) data_dict = json.loads(raw_json) if 'API Key' in data_dict: received_key = data_dict['API Key'] if received_key == WebServerConfig.config['API Key']: record_id = str(uuid.uuid4()) data_dict['API Key'] = 'Pass' LocalData.put( {'Timestamp': time.time(), 'Record ID': record_id, 'Data': data_dict}) self.send_response(200) self.end_headers() response = BytesIO() response.write(b'Your POST request was received, thank you !') # response.write(b'Received: ') # response.write(body) self.wfile.write(response.getvalue()) else: self.handle_405() else: self.handle_404() def handle_404(self): self.send_response(404) self.end_headers() response = BytesIO() response.write(b'Page Not Found') self.wfile.write(response.getvalue()) def handle_405(self): self.send_response(405) self.end_headers() response = BytesIO() response.write(b'Invalid Method') self.wfile.write(response.getvalue()) # ---------------------------------------------------------------------------------------------------------------------- # # Main Class # class SLM_Process(object): def __init__(self, config, verbose=False): self.verbose = verbose if 'Service Run' in config: self.service_run = config['Service Run'] else: self.service_run = True self.service_state = 'Running' self.service_pause_time = 0 if 'Process Delay' in config: self.process_delay = config['Process Delay'] else: # Default is 5 seconds on main loop delay self.process_delay = 5 self.httpd = None if 'Agent Port' in config: self.agent_port = config['Agent Port'] else: self.agent_port = 12080 self.start_time = time.time() if self.agent_run() is True: self.run() def set_state(self, state, pause_time=0): if state == 'Pause': self.service_state = 'Paused' self.service_pause_time = pause_time elif state == 'Stop': self.service_state = 'Stopped' elif state == 'Kill': self.service_state = 'Stopped' self.service_run = False elif state == 'Resume': self.service_state = 'Running' if self.verbose is True: print('Service just entered a "{s}" state '.format(s=state)) # ------------------------------------------------------------------------------------------------------------------ def agent(self): self.httpd = HTTPServer(('localhost', self.agent_port), SimpleHTTPRequestHandler) self.httpd.serve_forever() def agent_run(self): try: t = threading.Thread(name="Service_Interface", target=self.agent) t.start() except Exception as error: print(error) return False else: return True # ------------------------------------------------------------------------------------------------------------------ # # Application Methods # def api_cmd(self, request): # Uncomment for testing only #print(request) if 'Data' in request: request_data = request['Data'] operation = request_data['Operation'] if operation == 'Set State': if 'Pause Time' in request_data: self.set_state(request_data['State'], request_data['Pause Time']) else: self.set_state(request_data['State']) else: pass # ------------------------------------------------------------------------------------------------------------------ def run(self): while self.service_run is True: if self.service_state == 'Running': while not LocalData.empty(): self.api_cmd(LocalData.get()) elif self.service_state == 'Paused': time.sleep(self.service_pause_time) time.sleep(self.process_delay) # ---------------------------------------------------------------------------------------------------------------------- # # Main Declaration # def main(): api_key = str(uuid.uuid5(uuid.NAMESPACE_URL, 'Top Secret')) # Uncomment for testing only. #print(api_key) # ------------------------------------------------------------------------------------------------------------------ # # Set the Web Server configuration # WebServerConfig.config['API Key'] = api_key url_list = { '/': ['GET'], '/api': ['GET', 'POST'] } WebServerConfig.config['URL List'] = url_list allowed_file_types = [ '.css', '.gif', '.ico', '.jpeg', '.jpg', '.js', '.json', '.jsp', '.map', '.png', '.webp', '.woff2', ] WebServerConfig.config['Allowed File Types'] = allowed_file_types WebServerConfig.set_static_directory('/home/eddief/PycharmProjects/signals_test_code/static') # ------------------------------------------------------------------------------------------------------------------ config = { 'Service Run': True, 'Process Delay': 5, 'Agent Port': 12080, 'API Key': api_key } x = SLM_Process(config, verbose=True) # ---------------------------------------------------------------------------------------------------------------------- # # Supporting libraries # if __name__ == '__main__': main()
[ "json.loads", "uuid.uuid5", "io.BytesIO", "time.sleep", "uuid.uuid4", "http.server.HTTPServer", "threading.Thread", "queue.Queue", "time.time" ]
[((868, 875), 'queue.Queue', 'Queue', ([], {}), '()\n', (873, 875), False, 'from queue import Queue\n'), ((5733, 5742), 'io.BytesIO', 'BytesIO', ([], {}), '()\n', (5740, 5742), False, 'from io import BytesIO\n'), ((5941, 5950), 'io.BytesIO', 'BytesIO', ([], {}), '()\n', (5948, 5950), False, 'from io import BytesIO\n'), ((6897, 6908), 'time.time', 'time.time', ([], {}), '()\n', (6906, 6908), False, 'import time\n'), ((7672, 7740), 'http.server.HTTPServer', 'HTTPServer', (["('localhost', self.agent_port)", 'SimpleHTTPRequestHandler'], {}), "(('localhost', self.agent_port), SimpleHTTPRequestHandler)\n", (7682, 7740), False, 'from http.server import HTTPServer, BaseHTTPRequestHandler\n'), ((9373, 9417), 'uuid.uuid5', 'uuid.uuid5', (['uuid.NAMESPACE_URL', '"""Top Secret"""'], {}), "(uuid.NAMESPACE_URL, 'Top Secret')\n", (9383, 9417), False, 'import uuid\n'), ((7834, 7895), 'threading.Thread', 'threading.Thread', ([], {'name': '"""Service_Interface"""', 'target': 'self.agent'}), "(name='Service_Interface', target=self.agent)\n", (7850, 7895), False, 'import threading\n'), ((9164, 9194), 'time.sleep', 'time.sleep', (['self.process_delay'], {}), '(self.process_delay)\n', (9174, 9194), False, 'import time\n'), ((5293, 5302), 'io.BytesIO', 'BytesIO', ([], {}), '()\n', (5300, 5302), False, 'from io import BytesIO\n'), ((4649, 4669), 'json.loads', 'json.loads', (['raw_json'], {}), '(raw_json)\n', (4659, 4669), False, 'import json\n'), ((9115, 9150), 'time.sleep', 'time.sleep', (['self.service_pause_time'], {}), '(self.service_pause_time)\n', (9125, 9150), False, 'import time\n'), ((4902, 4914), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (4912, 4914), False, 'import uuid\n'), ((5065, 5076), 'time.time', 'time.time', ([], {}), '()\n', (5074, 5076), False, 'import time\n')]
# Generated by Django 2.1.2 on 2018-11-08 12:48 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('Game', '0004_auto_20181106_1255'), ] operations = [ migrations.CreateModel( name='Loan', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('loaned', models.FloatField(default=-1)), ('due_date', models.DateField()), ('borrower', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='Game.Wallet')), ], ), migrations.CreateModel( name='LoanOffer', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('loaned', models.FloatField(default=-1)), ('interest_rate', models.FloatField(default=-1)), ('days', models.IntegerField(default=-1)), ('lender', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='Game.Wallet')), ], ), migrations.AddField( model_name='loan', name='offer', field=models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='Game.LoanOffer'), ), ]
[ "django.db.models.DateField", "django.db.models.FloatField", "django.db.models.IntegerField", "django.db.models.ForeignKey", "django.db.models.AutoField" ]
[((1325, 1416), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'on_delete': 'django.db.models.deletion.DO_NOTHING', 'to': '"""Game.LoanOffer"""'}), "(on_delete=django.db.models.deletion.DO_NOTHING, to=\n 'Game.LoanOffer')\n", (1342, 1416), False, 'from django.db import migrations, models\n'), ((358, 451), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (374, 451), False, 'from django.db import migrations, models\n'), ((477, 506), 'django.db.models.FloatField', 'models.FloatField', ([], {'default': '(-1)'}), '(default=-1)\n', (494, 506), False, 'from django.db import migrations, models\n'), ((538, 556), 'django.db.models.DateField', 'models.DateField', ([], {}), '()\n', (554, 556), False, 'from django.db import migrations, models\n'), ((588, 676), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'on_delete': 'django.db.models.deletion.DO_NOTHING', 'to': '"""Game.Wallet"""'}), "(on_delete=django.db.models.deletion.DO_NOTHING, to=\n 'Game.Wallet')\n", (605, 676), False, 'from django.db import migrations, models\n'), ((806, 899), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (822, 899), False, 'from django.db import migrations, models\n'), ((925, 954), 'django.db.models.FloatField', 'models.FloatField', ([], {'default': '(-1)'}), '(default=-1)\n', (942, 954), False, 'from django.db import migrations, models\n'), ((991, 1020), 'django.db.models.FloatField', 'models.FloatField', ([], {'default': '(-1)'}), '(default=-1)\n', (1008, 1020), False, 'from django.db import migrations, models\n'), ((1048, 1079), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'default': '(-1)'}), '(default=-1)\n', (1067, 1079), False, 'from django.db import migrations, models\n'), ((1109, 1197), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'on_delete': 'django.db.models.deletion.DO_NOTHING', 'to': '"""Game.Wallet"""'}), "(on_delete=django.db.models.deletion.DO_NOTHING, to=\n 'Game.Wallet')\n", (1126, 1197), False, 'from django.db import migrations, models\n')]
#!/usr/bin/env python from __future__ import division import rospy from std_msgs.msg import String from hopper_msgs.msg import ServoTelemetry, HexapodTelemetry from sensor_msgs.msg import BatteryState def mean(numbers): return sum(numbers) / max(len(numbers), 1) SERVO_COUNT = 18 MAX_VOLTAGE = 12.5 MIN_VOLTAGE = 10.5 class BatteryStatusMonitor(object): critical_voltage_warning_period = rospy.Duration.from_sec(15) def __init__(self): super(BatteryStatusMonitor, self).__init__() rospy.init_node("hopper_battery_monitor", anonymous=True) self.lowest_recorded_voltage = 24.0 self.voltages = {} self.first_check = True self.speech_publisher = rospy.Publisher('hopper_play_sound', String, queue_size=5) self.battery_publisher = rospy.Publisher("hopper/battery_status", BatteryState, queue_size=5) self.face_color_publisher = rospy.Publisher("hopper/face/mode", String, queue_size=3) self.telemetry_sub = rospy.Subscriber("hopper_telemetry", HexapodTelemetry, self.on_new_telemetry, queue_size=1) self.last_critical_voltage_warning = rospy.Time.now() + self.critical_voltage_warning_period rospy.spin() def on_new_telemetry(self, message): for servo in message.servos: self.voltages[servo.id] = servo.voltage if len(self.voltages) == SERVO_COUNT: voltages = self.voltages.values() self.voltages.clear() voltage = max(voltages) battery_state = BatteryState() battery_state.header.stamp = rospy.Time.now() battery_state.voltage = voltage battery_state.current = float("nan") battery_state.charge = float("nan") battery_state.capacity = float("nan") battery_state.design_capacity = float("nan") battery_state.percentage = 100 - (MAX_VOLTAGE - voltage) / (MAX_VOLTAGE - MIN_VOLTAGE) * 100 battery_state.power_supply_status = BatteryState.POWER_SUPPLY_STATUS_DISCHARGING battery_state.power_supply_health = BatteryState.POWER_SUPPLY_HEALTH_UNKNOWN battery_state.power_supply_technology = BatteryState.POWER_SUPPLY_TECHNOLOGY_LIPO battery_state.present = True battery_state.cell_voltage = [float("nan")] * 3 battery_state.location = "Primary batter bay" battery_state.serial_number = "N/A" self.battery_publisher.publish(battery_state) # skip the first check so that you don't get a warning if battery is already bellow some value if self.first_check: self.first_check = False self.lowest_recorded_voltage = voltage return if voltage < 10.2: if self.last_critical_voltage_warning + self.critical_voltage_warning_period < rospy.Time.now(): self.speech_publisher.publish("battery_critical") self.face_color_publisher.publish("flash:red") self.last_critical_voltage_warning = rospy.Time.now() elif voltage < 11 and self.lowest_recorded_voltage >= 11: self.speech_publisher.publish("battery_below_11") elif voltage < 12 and self.lowest_recorded_voltage >= 12: self.speech_publisher.publish("battery_below_12") if voltage < self.lowest_recorded_voltage: self.lowest_recorded_voltage = voltage if __name__ == '__main__': BatteryStatusMonitor()
[ "rospy.Subscriber", "rospy.init_node", "sensor_msgs.msg.BatteryState", "rospy.Duration.from_sec", "rospy.Time.now", "rospy.spin", "rospy.Publisher" ]
[((403, 430), 'rospy.Duration.from_sec', 'rospy.Duration.from_sec', (['(15)'], {}), '(15)\n', (426, 430), False, 'import rospy\n'), ((517, 574), 'rospy.init_node', 'rospy.init_node', (['"""hopper_battery_monitor"""'], {'anonymous': '(True)'}), "('hopper_battery_monitor', anonymous=True)\n", (532, 574), False, 'import rospy\n'), ((710, 768), 'rospy.Publisher', 'rospy.Publisher', (['"""hopper_play_sound"""', 'String'], {'queue_size': '(5)'}), "('hopper_play_sound', String, queue_size=5)\n", (725, 768), False, 'import rospy\n'), ((802, 870), 'rospy.Publisher', 'rospy.Publisher', (['"""hopper/battery_status"""', 'BatteryState'], {'queue_size': '(5)'}), "('hopper/battery_status', BatteryState, queue_size=5)\n", (817, 870), False, 'import rospy\n'), ((907, 964), 'rospy.Publisher', 'rospy.Publisher', (['"""hopper/face/mode"""', 'String'], {'queue_size': '(3)'}), "('hopper/face/mode', String, queue_size=3)\n", (922, 964), False, 'import rospy\n'), ((994, 1090), 'rospy.Subscriber', 'rospy.Subscriber', (['"""hopper_telemetry"""', 'HexapodTelemetry', 'self.on_new_telemetry'], {'queue_size': '(1)'}), "('hopper_telemetry', HexapodTelemetry, self.\n on_new_telemetry, queue_size=1)\n", (1010, 1090), False, 'import rospy\n'), ((1195, 1207), 'rospy.spin', 'rospy.spin', ([], {}), '()\n', (1205, 1207), False, 'import rospy\n'), ((1131, 1147), 'rospy.Time.now', 'rospy.Time.now', ([], {}), '()\n', (1145, 1147), False, 'import rospy\n'), ((1529, 1543), 'sensor_msgs.msg.BatteryState', 'BatteryState', ([], {}), '()\n', (1541, 1543), False, 'from sensor_msgs.msg import BatteryState\n'), ((1585, 1601), 'rospy.Time.now', 'rospy.Time.now', ([], {}), '()\n', (1599, 1601), False, 'import rospy\n'), ((2881, 2897), 'rospy.Time.now', 'rospy.Time.now', ([], {}), '()\n', (2895, 2897), False, 'import rospy\n'), ((3093, 3109), 'rospy.Time.now', 'rospy.Time.now', ([], {}), '()\n', (3107, 3109), False, 'import rospy\n')]
import pytest from datacube.utils.geometry import box from datacube_ows.cube_pool import cube from datacube_ows.ogc_utils import local_solar_date_range from datacube_ows.ows_configuration import get_config from datacube_ows.mv_index import MVSelectOpts, mv_search_datasets def test_full_layer(): cfg = get_config() lyr = list(cfg.product_index.values())[0] with cube() as dc: sel = mv_search_datasets(dc.index, MVSelectOpts.COUNT, layer=lyr) assert sel > 0 class MockGeobox: def __init__(self, geom): if geom.crs != "EPSG:4326": geom = geom.to_crs("EPSG:4326") self.geographic_extent = geom def test_time_search(): cfg = get_config() lyr = list(cfg.product_index.values())[0] time = lyr.ranges["times"][-1] geom = box( lyr.bboxes["EPSG:4326"]["left"], lyr.bboxes["EPSG:4326"]["bottom"], lyr.bboxes["EPSG:4326"]["right"], lyr.bboxes["EPSG:4326"]["top"], "EPSG:4326", ) time_rng = local_solar_date_range(MockGeobox(geom), time) with cube() as dc: sel = mv_search_datasets( dc.index, MVSelectOpts.COUNT, times=[time_rng], layer=lyr ) assert sel > 0 def test_count(): cfg = get_config() lyr = list(cfg.product_index.values())[0] with cube() as dc: count = mv_search_datasets(dc.index, MVSelectOpts.COUNT, layer=lyr) ids = mv_search_datasets(dc.index, MVSelectOpts.IDS, layer=lyr) assert len(ids) == count def test_datasets(): cfg = get_config() lyr = list(cfg.product_index.values())[0] with cube() as dc: dss = mv_search_datasets(dc.index, MVSelectOpts.DATASETS, layer=lyr) ids = mv_search_datasets(dc.index, MVSelectOpts.IDS, layer=lyr) assert len(ids) == len(dss) for ds in dss: assert str(ds.id) in ids def test_extent_and_spatial(): cfg = get_config() lyr = list(cfg.product_index.values())[0] layer_ext_bbx = ( lyr.bboxes["EPSG:4326"]["left"], lyr.bboxes["EPSG:4326"]["bottom"], lyr.bboxes["EPSG:4326"]["right"], lyr.bboxes["EPSG:4326"]["top"], ) small_bbox = pytest.helpers.enclosed_bbox(layer_ext_bbx) layer_ext_geom = box( layer_ext_bbx[0], layer_ext_bbx[1], layer_ext_bbx[2], layer_ext_bbx[3], "EPSG:4326", ) small_geom = box( small_bbox[0], small_bbox[1], small_bbox[2], small_bbox[3], "EPSG:4326" ) with cube() as dc: all_ext = mv_search_datasets( dc.index, MVSelectOpts.EXTENT, geom=layer_ext_geom, layer=lyr ) small_ext = mv_search_datasets( dc.index, MVSelectOpts.EXTENT, geom=small_geom, layer=lyr ) assert layer_ext_geom.contains(all_ext) assert small_geom.contains(small_ext) assert all_ext.contains(small_ext) assert small_ext.area < all_ext.area all_count = mv_search_datasets( dc.index, MVSelectOpts.COUNT, geom=layer_ext_geom, layer=lyr ) small_count = mv_search_datasets( dc.index, MVSelectOpts.COUNT, geom=small_geom, layer=lyr ) assert small_count <= all_count
[ "pytest.helpers.enclosed_bbox", "datacube_ows.mv_index.mv_search_datasets", "datacube.utils.geometry.box", "datacube_ows.ows_configuration.get_config", "datacube_ows.cube_pool.cube" ]
[((310, 322), 'datacube_ows.ows_configuration.get_config', 'get_config', ([], {}), '()\n', (320, 322), False, 'from datacube_ows.ows_configuration import get_config\n'), ((693, 705), 'datacube_ows.ows_configuration.get_config', 'get_config', ([], {}), '()\n', (703, 705), False, 'from datacube_ows.ows_configuration import get_config\n'), ((798, 953), 'datacube.utils.geometry.box', 'box', (["lyr.bboxes['EPSG:4326']['left']", "lyr.bboxes['EPSG:4326']['bottom']", "lyr.bboxes['EPSG:4326']['right']", "lyr.bboxes['EPSG:4326']['top']", '"""EPSG:4326"""'], {}), "(lyr.bboxes['EPSG:4326']['left'], lyr.bboxes['EPSG:4326']['bottom'], lyr\n .bboxes['EPSG:4326']['right'], lyr.bboxes['EPSG:4326']['top'], 'EPSG:4326')\n", (801, 953), False, 'from datacube.utils.geometry import box\n'), ((1249, 1261), 'datacube_ows.ows_configuration.get_config', 'get_config', ([], {}), '()\n', (1259, 1261), False, 'from datacube_ows.ows_configuration import get_config\n'), ((1545, 1557), 'datacube_ows.ows_configuration.get_config', 'get_config', ([], {}), '()\n', (1555, 1557), False, 'from datacube_ows.ows_configuration import get_config\n'), ((1915, 1927), 'datacube_ows.ows_configuration.get_config', 'get_config', ([], {}), '()\n', (1925, 1927), False, 'from datacube_ows.ows_configuration import get_config\n'), ((2185, 2228), 'pytest.helpers.enclosed_bbox', 'pytest.helpers.enclosed_bbox', (['layer_ext_bbx'], {}), '(layer_ext_bbx)\n', (2213, 2228), False, 'import pytest\n'), ((2250, 2342), 'datacube.utils.geometry.box', 'box', (['layer_ext_bbx[0]', 'layer_ext_bbx[1]', 'layer_ext_bbx[2]', 'layer_ext_bbx[3]', '"""EPSG:4326"""'], {}), "(layer_ext_bbx[0], layer_ext_bbx[1], layer_ext_bbx[2], layer_ext_bbx[3],\n 'EPSG:4326')\n", (2253, 2342), False, 'from datacube.utils.geometry import box\n'), ((2403, 2479), 'datacube.utils.geometry.box', 'box', (['small_bbox[0]', 'small_bbox[1]', 'small_bbox[2]', 'small_bbox[3]', '"""EPSG:4326"""'], {}), "(small_bbox[0], small_bbox[1], small_bbox[2], small_bbox[3], 'EPSG:4326')\n", (2406, 2479), False, 'from datacube.utils.geometry import box\n'), ((378, 384), 'datacube_ows.cube_pool.cube', 'cube', ([], {}), '()\n', (382, 384), False, 'from datacube_ows.cube_pool import cube\n'), ((406, 465), 'datacube_ows.mv_index.mv_search_datasets', 'mv_search_datasets', (['dc.index', 'MVSelectOpts.COUNT'], {'layer': 'lyr'}), '(dc.index, MVSelectOpts.COUNT, layer=lyr)\n', (424, 465), False, 'from datacube_ows.mv_index import MVSelectOpts, mv_search_datasets\n'), ((1068, 1074), 'datacube_ows.cube_pool.cube', 'cube', ([], {}), '()\n', (1072, 1074), False, 'from datacube_ows.cube_pool import cube\n'), ((1096, 1173), 'datacube_ows.mv_index.mv_search_datasets', 'mv_search_datasets', (['dc.index', 'MVSelectOpts.COUNT'], {'times': '[time_rng]', 'layer': 'lyr'}), '(dc.index, MVSelectOpts.COUNT, times=[time_rng], layer=lyr)\n', (1114, 1173), False, 'from datacube_ows.mv_index import MVSelectOpts, mv_search_datasets\n'), ((1317, 1323), 'datacube_ows.cube_pool.cube', 'cube', ([], {}), '()\n', (1321, 1323), False, 'from datacube_ows.cube_pool import cube\n'), ((1347, 1406), 'datacube_ows.mv_index.mv_search_datasets', 'mv_search_datasets', (['dc.index', 'MVSelectOpts.COUNT'], {'layer': 'lyr'}), '(dc.index, MVSelectOpts.COUNT, layer=lyr)\n', (1365, 1406), False, 'from datacube_ows.mv_index import MVSelectOpts, mv_search_datasets\n'), ((1421, 1478), 'datacube_ows.mv_index.mv_search_datasets', 'mv_search_datasets', (['dc.index', 'MVSelectOpts.IDS'], {'layer': 'lyr'}), '(dc.index, MVSelectOpts.IDS, layer=lyr)\n', (1439, 1478), False, 'from datacube_ows.mv_index import MVSelectOpts, mv_search_datasets\n'), ((1613, 1619), 'datacube_ows.cube_pool.cube', 'cube', ([], {}), '()\n', (1617, 1619), False, 'from datacube_ows.cube_pool import cube\n'), ((1641, 1703), 'datacube_ows.mv_index.mv_search_datasets', 'mv_search_datasets', (['dc.index', 'MVSelectOpts.DATASETS'], {'layer': 'lyr'}), '(dc.index, MVSelectOpts.DATASETS, layer=lyr)\n', (1659, 1703), False, 'from datacube_ows.mv_index import MVSelectOpts, mv_search_datasets\n'), ((1718, 1775), 'datacube_ows.mv_index.mv_search_datasets', 'mv_search_datasets', (['dc.index', 'MVSelectOpts.IDS'], {'layer': 'lyr'}), '(dc.index, MVSelectOpts.IDS, layer=lyr)\n', (1736, 1775), False, 'from datacube_ows.mv_index import MVSelectOpts, mv_search_datasets\n'), ((2503, 2509), 'datacube_ows.cube_pool.cube', 'cube', ([], {}), '()\n', (2507, 2509), False, 'from datacube_ows.cube_pool import cube\n'), ((2535, 2620), 'datacube_ows.mv_index.mv_search_datasets', 'mv_search_datasets', (['dc.index', 'MVSelectOpts.EXTENT'], {'geom': 'layer_ext_geom', 'layer': 'lyr'}), '(dc.index, MVSelectOpts.EXTENT, geom=layer_ext_geom,\n layer=lyr)\n', (2553, 2620), False, 'from datacube_ows.mv_index import MVSelectOpts, mv_search_datasets\n'), ((2659, 2736), 'datacube_ows.mv_index.mv_search_datasets', 'mv_search_datasets', (['dc.index', 'MVSelectOpts.EXTENT'], {'geom': 'small_geom', 'layer': 'lyr'}), '(dc.index, MVSelectOpts.EXTENT, geom=small_geom, layer=lyr)\n', (2677, 2736), False, 'from datacube_ows.mv_index import MVSelectOpts, mv_search_datasets\n'), ((2962, 3047), 'datacube_ows.mv_index.mv_search_datasets', 'mv_search_datasets', (['dc.index', 'MVSelectOpts.COUNT'], {'geom': 'layer_ext_geom', 'layer': 'lyr'}), '(dc.index, MVSelectOpts.COUNT, geom=layer_ext_geom, layer=lyr\n )\n', (2980, 3047), False, 'from datacube_ows.mv_index import MVSelectOpts, mv_search_datasets\n'), ((3087, 3163), 'datacube_ows.mv_index.mv_search_datasets', 'mv_search_datasets', (['dc.index', 'MVSelectOpts.COUNT'], {'geom': 'small_geom', 'layer': 'lyr'}), '(dc.index, MVSelectOpts.COUNT, geom=small_geom, layer=lyr)\n', (3105, 3163), False, 'from datacube_ows.mv_index import MVSelectOpts, mv_search_datasets\n')]
# coding:utf-8 # @Time : 2019-01-14 15:22 # @Author : 小贰 # @FileName: ansible_sync_hosts.py # @function: ansible for python 3.x import json from collections import namedtuple from ansible.parsing.dataloader import DataLoader from ansible.vars.manager import VariableManager from ansible.inventory.manager import InventoryManager from ansible.playbook.play import Play from ansible.executor.task_queue_manager import TaskQueueManager from ansible.plugins.callback import CallbackBase class ResultsCollector(CallbackBase): """重构执行结果""" def __init__(self, *args, **kwargs): super(ResultsCollector, self).__init__(*args, **kwargs) self.host_ok = {} self.host_unreachable = {} self.host_failed = {} self.host_skipped = {} def v2_runner_on_unreachable(self, result, *args, **kwargs): """不可达""" self.host_unreachable[result._host.get_name()] = result def v2_runner_on_ok(self, result, *args, **kwargs): """执行成功""" self.host_ok[result._host.get_name()] = result def v2_runner_on_failed(self, result, *args, **kwargs): """执行失败""" self.host_failed[result._host.get_name()] = result def v2_runner_on_skipped(self, result, *args, **kwargs): """跳过不执行""" self.host_skipped[result._host.get_name()] = result def run_ansible(module_name,module_args,host_list,ansible_user): """ansible api""" # 负责查找和读取yaml、json和ini文件 loader = DataLoader() # 初始化需要的对象 Options = namedtuple('Options', ['connection', 'module_path', 'forks', 'become', 'become_method', 'private_key_file','become_user', 'remote_user', 'check', 'diff'] ) options = Options(connection='ssh', module_path=None, forks=5, become=True, become_method='sudo',private_key_file="/root/.ssh/id_rsa", become_user='root', remote_user=ansible_user, check=False, diff=False ) passwords = dict(vault_pass='<PASSWORD>') # 实例化ResultCallback来处理结果 callback = ResultsCollector() # 创建库存(inventory)并传递给VariableManager inventory = InventoryManager(loader=loader, sources=['/etc/ansible/hosts']) # 管理变量的类,包括主机,组,扩展等变量 variable_manager = VariableManager(loader=loader, inventory=inventory) # 创建任务 host = ",".join(host_list) play_source = dict( name="Ansible Play", hosts=host, gather_facts='no', tasks=[ dict(action=dict(module=module_name, args=module_args), register='shell_out'), ] ) play = Play().load(play_source, variable_manager=variable_manager, loader=loader) # 开始执行 tqm = None tqm = TaskQueueManager( inventory=inventory, variable_manager=variable_manager, loader=loader, options=options, passwords=passwords, stdout_callback=callback, ) result = tqm.run(play) result_raw = {'success': {}, 'failed': {}, 'unreachable': {}} for host, result in callback.host_ok.items(): result_raw['success'][host] = result._result for host, result in callback.host_failed.items(): result_raw['failed'][host] = result._result for host, result in callback.host_unreachable.items(): result_raw['unreachable'][host] = result._result for host, result in callback.host_skipped.items(): result_raw['skipped'][host] = result._result return json.dumps(result_raw, indent=4,ensure_ascii=False) if __name__ == "__main__": ansible_user="opadmin" module_name = 'shell' module_args = "ls /root" host_list = ['192.168.1.191','192.168.1.190'] ret = run_ansible(module_name,module_args,host_list,ansible_user) print(ret)
[ "collections.namedtuple", "ansible.vars.manager.VariableManager", "ansible.playbook.play.Play", "json.dumps", "ansible.inventory.manager.InventoryManager", "ansible.parsing.dataloader.DataLoader", "ansible.executor.task_queue_manager.TaskQueueManager" ]
[((1464, 1476), 'ansible.parsing.dataloader.DataLoader', 'DataLoader', ([], {}), '()\n', (1474, 1476), False, 'from ansible.parsing.dataloader import DataLoader\n'), ((1507, 1670), 'collections.namedtuple', 'namedtuple', (['"""Options"""', "['connection', 'module_path', 'forks', 'become', 'become_method',\n 'private_key_file', 'become_user', 'remote_user', 'check', 'diff']"], {}), "('Options', ['connection', 'module_path', 'forks', 'become',\n 'become_method', 'private_key_file', 'become_user', 'remote_user',\n 'check', 'diff'])\n", (1517, 1670), False, 'from collections import namedtuple\n'), ((2211, 2274), 'ansible.inventory.manager.InventoryManager', 'InventoryManager', ([], {'loader': 'loader', 'sources': "['/etc/ansible/hosts']"}), "(loader=loader, sources=['/etc/ansible/hosts'])\n", (2227, 2274), False, 'from ansible.inventory.manager import InventoryManager\n'), ((2325, 2376), 'ansible.vars.manager.VariableManager', 'VariableManager', ([], {'loader': 'loader', 'inventory': 'inventory'}), '(loader=loader, inventory=inventory)\n', (2340, 2376), False, 'from ansible.vars.manager import VariableManager\n'), ((2769, 2929), 'ansible.executor.task_queue_manager.TaskQueueManager', 'TaskQueueManager', ([], {'inventory': 'inventory', 'variable_manager': 'variable_manager', 'loader': 'loader', 'options': 'options', 'passwords': 'passwords', 'stdout_callback': 'callback'}), '(inventory=inventory, variable_manager=variable_manager,\n loader=loader, options=options, passwords=passwords, stdout_callback=\n callback)\n', (2785, 2929), False, 'from ansible.executor.task_queue_manager import TaskQueueManager\n'), ((3519, 3571), 'json.dumps', 'json.dumps', (['result_raw'], {'indent': '(4)', 'ensure_ascii': '(False)'}), '(result_raw, indent=4, ensure_ascii=False)\n', (3529, 3571), False, 'import json\n'), ((2656, 2662), 'ansible.playbook.play.Play', 'Play', ([], {}), '()\n', (2660, 2662), False, 'from ansible.playbook.play import Play\n')]
# -*- coding:utf-8 -*- from django.db import models from alipay import conf from alipay.models import AliPayBaseModel from alipay.create_direct_pay_by_user.dpn.signals import alipay_dpn_flagged, alipay_dpn_successful class AliPayDPN(AliPayBaseModel): """ AliPay DPN """ gmt_close = models.DateTimeField(blank=True, null=True) extra_common_param = models.CharField(blank=True, null=True, max_length=256) out_channel_type = models.CharField(blank=True, null=True, max_length=256) out_channel_amount = models.CharField(blank=True, null=True, max_length=256) out_channel_inst = models.CharField(blank=True, null=True, max_length=256) class Meta: db_table = 'alipay_dpn' verbose_name = 'AliPay DPN' def send_signals(self): if self.notify_type != 'trade_status_sync': return if self.is_transaction(): if self.flag: alipay_dpn_flagged.send(sender=self) else: alipay_dpn_successful.send(sender=self)
[ "django.db.models.DateTimeField", "django.db.models.CharField", "alipay.create_direct_pay_by_user.dpn.signals.alipay_dpn_successful.send", "alipay.create_direct_pay_by_user.dpn.signals.alipay_dpn_flagged.send" ]
[((301, 344), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'blank': '(True)', 'null': '(True)'}), '(blank=True, null=True)\n', (321, 344), False, 'from django.db import models\n'), ((370, 425), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'null': '(True)', 'max_length': '(256)'}), '(blank=True, null=True, max_length=256)\n', (386, 425), False, 'from django.db import models\n'), ((449, 504), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'null': '(True)', 'max_length': '(256)'}), '(blank=True, null=True, max_length=256)\n', (465, 504), False, 'from django.db import models\n'), ((530, 585), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'null': '(True)', 'max_length': '(256)'}), '(blank=True, null=True, max_length=256)\n', (546, 585), False, 'from django.db import models\n'), ((609, 664), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'null': '(True)', 'max_length': '(256)'}), '(blank=True, null=True, max_length=256)\n', (625, 664), False, 'from django.db import models\n'), ((926, 962), 'alipay.create_direct_pay_by_user.dpn.signals.alipay_dpn_flagged.send', 'alipay_dpn_flagged.send', ([], {'sender': 'self'}), '(sender=self)\n', (949, 962), False, 'from alipay.create_direct_pay_by_user.dpn.signals import alipay_dpn_flagged, alipay_dpn_successful\n'), ((997, 1036), 'alipay.create_direct_pay_by_user.dpn.signals.alipay_dpn_successful.send', 'alipay_dpn_successful.send', ([], {'sender': 'self'}), '(sender=self)\n', (1023, 1036), False, 'from alipay.create_direct_pay_by_user.dpn.signals import alipay_dpn_flagged, alipay_dpn_successful\n')]
import numpy as np import pandas as pd import time mnist = pd.read_csv("../input/train.csv") mnist.head() y_train = mnist.label.values x_train = mnist.drop('label',axis=1) x_train = (x_train / 255.0).values x_train = np.reshape(x_train,(42000,1,28,28)) x_train.shape from keras.models import Sequential from keras.layers.core import Dense, Dropout, Activation, Flatten from keras.layers.convolutional import Conv2D from keras.layers.pooling import MaxPooling2D from keras.optimizers import SGD from keras import backend as K K.set_image_data_format('channels_first') IMG_SIZE = 28 NUM_CLASSES = 10 def cnn_model(): model = Sequential() model.add(Conv2D(32, (3, 3), padding='same', input_shape=(1, IMG_SIZE, IMG_SIZE), activation='relu')) model.add(Conv2D(32, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.2)) model.add(Conv2D(64, (3, 3), padding='same', activation='relu')) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.2)) model.add(Conv2D(128, (3, 3), padding='same', activation='relu')) model.add(Conv2D(128, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.2)) model.add(Flatten()) model.add(Dense(512, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(NUM_CLASSES, activation='softmax')) return model model = cnn_model() model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) model.fit(x_train, y_train, epochs=3) test = pd.read_csv("../input/test.csv") test.describe() x_test = (test / 255.0).values x_test = np.reshape(x_test,(28000,1,28,28)) x_test.shape predictions = model.predict(x_test) import matplotlib.pyplot as plt plt.figure(figsize=(10,10)) for i in range(25): plt.subplot(5,5,i+1) plt.xticks([]) plt.yticks([]) plt.grid('off') plt.imshow(np.reshape(x_test[i],(28,28)), cmap=plt.cm.binary) predicted_label = np.argmax(predictions[i]) #true_label = y_test[i] #if predicted_label == true_label: # color = 'green' #else: # color = 'red' plt.xlabel("{} ".format(predicted_label), color='green') model_name = "digit_clf_model_"+ time.strftime("%Y-%m-%d-%H%M") +".h5" model.save_weights("models/"+model_name) # f=open("submissions.csv","w") # # Write headers # f.write("ImageId,Label\n") # for key,p in enumerate(predictions): # i = key+1 # line = str(i)+","+str(np.argmax(p))+"\n" # f.write(line) # f.close() # sub = pd.read_csv("submissions.csv") # sub.head()
[ "keras.backend.set_image_data_format", "keras.layers.core.Flatten", "matplotlib.pyplot.grid", "numpy.reshape", "pandas.read_csv", "matplotlib.pyplot.xticks", "keras.layers.pooling.MaxPooling2D", "time.strftime", "numpy.argmax", "keras.models.Sequential", "matplotlib.pyplot.figure", "keras.laye...
[((60, 93), 'pandas.read_csv', 'pd.read_csv', (['"""../input/train.csv"""'], {}), "('../input/train.csv')\n", (71, 93), True, 'import pandas as pd\n'), ((221, 260), 'numpy.reshape', 'np.reshape', (['x_train', '(42000, 1, 28, 28)'], {}), '(x_train, (42000, 1, 28, 28))\n', (231, 260), True, 'import numpy as np\n'), ((531, 572), 'keras.backend.set_image_data_format', 'K.set_image_data_format', (['"""channels_first"""'], {}), "('channels_first')\n", (554, 572), True, 'from keras import backend as K\n'), ((1723, 1755), 'pandas.read_csv', 'pd.read_csv', (['"""../input/test.csv"""'], {}), "('../input/test.csv')\n", (1734, 1755), True, 'import pandas as pd\n'), ((1813, 1851), 'numpy.reshape', 'np.reshape', (['x_test', '(28000, 1, 28, 28)'], {}), '(x_test, (28000, 1, 28, 28))\n', (1823, 1851), True, 'import numpy as np\n'), ((1932, 1960), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 10)'}), '(figsize=(10, 10))\n', (1942, 1960), True, 'import matplotlib.pyplot as plt\n'), ((634, 646), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (644, 646), False, 'from keras.models import Sequential\n'), ((1984, 2008), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(5)', '(5)', '(i + 1)'], {}), '(5, 5, i + 1)\n', (1995, 2008), True, 'import matplotlib.pyplot as plt\n'), ((2009, 2023), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (2019, 2023), True, 'import matplotlib.pyplot as plt\n'), ((2028, 2042), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (2038, 2042), True, 'import matplotlib.pyplot as plt\n'), ((2047, 2062), 'matplotlib.pyplot.grid', 'plt.grid', (['"""off"""'], {}), "('off')\n", (2055, 2062), True, 'import matplotlib.pyplot as plt\n'), ((2151, 2176), 'numpy.argmax', 'np.argmax', (['predictions[i]'], {}), '(predictions[i])\n', (2160, 2176), True, 'import numpy as np\n'), ((662, 756), 'keras.layers.convolutional.Conv2D', 'Conv2D', (['(32)', '(3, 3)'], {'padding': '"""same"""', 'input_shape': '(1, IMG_SIZE, IMG_SIZE)', 'activation': '"""relu"""'}), "(32, (3, 3), padding='same', input_shape=(1, IMG_SIZE, IMG_SIZE),\n activation='relu')\n", (668, 756), False, 'from keras.layers.convolutional import Conv2D\n'), ((810, 847), 'keras.layers.convolutional.Conv2D', 'Conv2D', (['(32)', '(3, 3)'], {'activation': '"""relu"""'}), "(32, (3, 3), activation='relu')\n", (816, 847), False, 'from keras.layers.convolutional import Conv2D\n'), ((863, 893), 'keras.layers.pooling.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': '(2, 2)'}), '(pool_size=(2, 2))\n', (875, 893), False, 'from keras.layers.pooling import MaxPooling2D\n'), ((909, 921), 'keras.layers.core.Dropout', 'Dropout', (['(0.2)'], {}), '(0.2)\n', (916, 921), False, 'from keras.layers.core import Dense, Dropout, Activation, Flatten\n'), ((938, 991), 'keras.layers.convolutional.Conv2D', 'Conv2D', (['(64)', '(3, 3)'], {'padding': '"""same"""', 'activation': '"""relu"""'}), "(64, (3, 3), padding='same', activation='relu')\n", (944, 991), False, 'from keras.layers.convolutional import Conv2D\n'), ((1028, 1065), 'keras.layers.convolutional.Conv2D', 'Conv2D', (['(64)', '(3, 3)'], {'activation': '"""relu"""'}), "(64, (3, 3), activation='relu')\n", (1034, 1065), False, 'from keras.layers.convolutional import Conv2D\n'), ((1081, 1111), 'keras.layers.pooling.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': '(2, 2)'}), '(pool_size=(2, 2))\n', (1093, 1111), False, 'from keras.layers.pooling import MaxPooling2D\n'), ((1127, 1139), 'keras.layers.core.Dropout', 'Dropout', (['(0.2)'], {}), '(0.2)\n', (1134, 1139), False, 'from keras.layers.core import Dense, Dropout, Activation, Flatten\n'), ((1156, 1210), 'keras.layers.convolutional.Conv2D', 'Conv2D', (['(128)', '(3, 3)'], {'padding': '"""same"""', 'activation': '"""relu"""'}), "(128, (3, 3), padding='same', activation='relu')\n", (1162, 1210), False, 'from keras.layers.convolutional import Conv2D\n'), ((1247, 1285), 'keras.layers.convolutional.Conv2D', 'Conv2D', (['(128)', '(3, 3)'], {'activation': '"""relu"""'}), "(128, (3, 3), activation='relu')\n", (1253, 1285), False, 'from keras.layers.convolutional import Conv2D\n'), ((1301, 1331), 'keras.layers.pooling.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': '(2, 2)'}), '(pool_size=(2, 2))\n', (1313, 1331), False, 'from keras.layers.pooling import MaxPooling2D\n'), ((1347, 1359), 'keras.layers.core.Dropout', 'Dropout', (['(0.2)'], {}), '(0.2)\n', (1354, 1359), False, 'from keras.layers.core import Dense, Dropout, Activation, Flatten\n'), ((1376, 1385), 'keras.layers.core.Flatten', 'Flatten', ([], {}), '()\n', (1383, 1385), False, 'from keras.layers.core import Dense, Dropout, Activation, Flatten\n'), ((1401, 1430), 'keras.layers.core.Dense', 'Dense', (['(512)'], {'activation': '"""relu"""'}), "(512, activation='relu')\n", (1406, 1430), False, 'from keras.layers.core import Dense, Dropout, Activation, Flatten\n'), ((1446, 1458), 'keras.layers.core.Dropout', 'Dropout', (['(0.5)'], {}), '(0.5)\n', (1453, 1458), False, 'from keras.layers.core import Dense, Dropout, Activation, Flatten\n'), ((1474, 1514), 'keras.layers.core.Dense', 'Dense', (['NUM_CLASSES'], {'activation': '"""softmax"""'}), "(NUM_CLASSES, activation='softmax')\n", (1479, 1514), False, 'from keras.layers.core import Dense, Dropout, Activation, Flatten\n'), ((2078, 2109), 'numpy.reshape', 'np.reshape', (['x_test[i]', '(28, 28)'], {}), '(x_test[i], (28, 28))\n', (2088, 2109), True, 'import numpy as np\n'), ((2428, 2458), 'time.strftime', 'time.strftime', (['"""%Y-%m-%d-%H%M"""'], {}), "('%Y-%m-%d-%H%M')\n", (2441, 2458), False, 'import time\n')]
import subprocess import time from os import listdir from os.path import isfile, join COMMAND = ["python3", "onnx_sender.py",] DIR = "working" def get_file_list_from_dir(mypath): onlyfiles = [join(mypath, f) for f in listdir(mypath) if isfile(join(mypath, f))] return onlyfiles file_list = get_file_list_from_dir(DIR) for file_name in file_list: driving_video = file_name out_kp_file = file_name+".kp" out_img_file = file_name+".jpeg" current_command = COMMAND + ["--driving_video", driving_video, '--out_kp_file', out_kp_file, '--out_img_file', out_img_file] print(current_command) subprocess.run(current_command)
[ "os.listdir", "subprocess.run", "os.path.join" ]
[((621, 652), 'subprocess.run', 'subprocess.run', (['current_command'], {}), '(current_command)\n', (635, 652), False, 'import subprocess\n'), ((199, 214), 'os.path.join', 'join', (['mypath', 'f'], {}), '(mypath, f)\n', (203, 214), False, 'from os.path import isfile, join\n'), ((224, 239), 'os.listdir', 'listdir', (['mypath'], {}), '(mypath)\n', (231, 239), False, 'from os import listdir\n'), ((250, 265), 'os.path.join', 'join', (['mypath', 'f'], {}), '(mypath, f)\n', (254, 265), False, 'from os.path import isfile, join\n')]
import paho.mqtt.client as mqtt # 當地端程式連線伺服器得到回應時,要做的動作 def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) # 將訂閱主題寫在on_connet中 # 如果我們失去連線或重新連線時 # 地端程式將會重新訂閱 client.subscribe("Try/MQTT") # 當接收到從伺服器發送的訊息時要進行的動作 def on_message(client, userdata, msg): # 轉換編碼utf-8才看得懂中文 print(msg.topic+" "+ msg.payload.decode('utf-8')) # 連線設定 # 初始化地端程式 client = mqtt.Client() # 設定連線的動作 client.on_connect = on_connect # 設定接收訊息的動作 client.on_message = on_message # 設定登入帳號密碼 client.username_pw_set("try","xxxx") # 設定連線資訊(IP, Port, 連線時間) client.connect("54.xxx.xxx.xxx", 1883, 60) # 開始連線,執行設定的動作和處理重新連線問題 # 也可以手動使用其他loop函式來進行連接 client.loop_forever()
[ "paho.mqtt.client.Client" ]
[((414, 427), 'paho.mqtt.client.Client', 'mqtt.Client', ([], {}), '()\n', (425, 427), True, 'import paho.mqtt.client as mqtt\n')]
import copy import pprint import inspect from collections import OrderedDict import six from neupy.exceptions import LayerConnectionError __all__ = ('LayerGraph',) def filter_list(iterable, include_values): """ Create new list that contains only values specified in the ``include_values`` attribute. Parameters ---------- iterable : list List that needs to be filtered. include_values : list, tuple List of values that needs to be included in the filtered list. Other values that hasn't been defined in the list will be excluded from the list specified by ``iterable`` attribute. Returns ------- list Filtered list. """ filtered_list = [] for value in iterable: if value in include_values: filtered_list.append(value) return filtered_list def filter_dict(dictionary, include_keys): """ Create new list that contains only values specified in the ``include_keys`` attribute. Parameters ---------- dictionary : dict Original dictionary include_keys : list or tuple Keys that will copied from original dictionary into a new one. Returns ------- dict """ filtered_dict = OrderedDict() for key, value in dictionary.items(): if key in include_keys: filtered_dict[key] = filter_list(value, include_keys) return filtered_dict def merge_dicts_with_list(first_dict, second_dict): """ Create new dict that contains all elements from the first one and from the second one. Function assumes that all value elements are lists. In case if one key appears in both dicts function will merge these lists into one. Parameters ---------- first_dict : dict second_dict : dict Returns ------- dict """ common_dict = OrderedDict() for key, value in first_dict.items(): # To make sure that we copied lists inside of the # dictionary, but didn't copied values inside of the list common_dict[key] = copy.copy(value) for key, values in second_dict.items(): if key in common_dict: for value in values: if value not in common_dict[key]: common_dict[key].append(value) else: common_dict[key] = copy.copy(values) return common_dict def is_cyclic(graph): """ Check if graph has cycles. Parameters ---------- graph : dict must be represented as a dictionary mapping vertices to iterables of neighbouring vertices. Returns ------- bool Return ``True`` if the directed graph has a cycle. Examples -------- >>> is_cyclic({1: (2,), 2: (3,), 3: (1,)}) True >>> is_cyclic({1: (2,), 2: (3,), 3: (4,)}) False """ path = set() visited = set() def visit(vertex): if vertex in visited: return False visited.add(vertex) path.add(vertex) for neighbour in graph.get(vertex, ()): if neighbour in path or visit(neighbour): return True path.remove(vertex) return False return any(visit(vertex) for vertex in graph) def does_layer_expect_one_input(layer): """ Check whether layer can except only one input layer. Parameters ---------- layer : layer or connection Raises ------ ValueError In case if argument is not a layer. Retruns ------- bool Returns ``True`` if layer can accept onl one input layer, ``False`` otherwise. """ if not hasattr(layer, 'output'): raise ValueError("Layer `{}` doesn't have " "output method".format(layer)) if not inspect.ismethod(layer.output): raise ValueError("Layer has an `output` property, " "but it not a method") arginfo = inspect.getargspec(layer.output) if arginfo.varargs is not None: return False # In case if layer expects fixed number of input layers n_args = len(arginfo.args) - 1 # Ignore `self` argument return n_args == 1 class LayerGraph(object): """ Direct Acyclic Graph (DAG) for layer connections. Parameters ---------- forward_graph : None or dict backward_graph : None or dict Raises ------ LayerConnectionError If graph cannot connect layers. """ def __init__(self, forward_graph=None, backward_graph=None): if forward_graph is None: forward_graph = OrderedDict() if backward_graph is None: backward_graph = OrderedDict() self.forward_graph = forward_graph self.backward_graph = backward_graph @classmethod def merge(cls, left_graph, right_graph): """ Combine two separated graphs into one. Parameters ---------- left_graph : LayerGraph instance right_graph : LayerGraph instance Returns ------- LayerGraph instance New graph that contains layers and connections from input graphs. """ forward_graph = merge_dicts_with_list( left_graph.forward_graph, right_graph.forward_graph ) backward_graph = merge_dicts_with_list( left_graph.backward_graph, right_graph.backward_graph ) return cls(forward_graph, backward_graph) def add_layer(self, layer): """ Add new layer into the graph. Parameters ---------- layer : layer Returns ------- bool Returns ``False`` if layer has beed already added into graph and there is no need to add it again, and ``True`` - if layer is a new and was added successfully. """ if layer in self.forward_graph: return False for existed_layer in self.forward_graph: if existed_layer.name == layer.name: raise LayerConnectionError( "Cannot connect {} layer. Layer with name {!r} has been " "already defined in the graph.".format(layer, layer.name)) self.forward_graph[layer] = [] self.backward_graph[layer] = [] return True def add_connection(self, from_layer, to_layer): """ Add new directional connection between two layers. Parameters ---------- from_layer : layer to_layer : layer Raises ------ LayerConnectionError Raises if it's impossible to connect two layers or new connection creates cycles in graph. Returns ------- bool Returns ``False`` if connection has already been added into the graph, and ``True`` if connection was added successfully. """ if from_layer is to_layer: raise LayerConnectionError("Cannot connect layer `{}` " "to itself".format(from_layer)) self.add_layer(from_layer) self.add_layer(to_layer) forward_connections = self.forward_graph[from_layer] backward_connections = self.backward_graph[to_layer] if to_layer in forward_connections: # Layers have been already connected return False forward_connections.append(to_layer) backward_connections.append(from_layer) if is_cyclic(self.forward_graph): raise LayerConnectionError( "Cannot connect layer `{}` to `{}`, because this " "connection creates cycle in the graph." "".format(from_layer, to_layer)) return True def connect_layers(self, from_layers, to_layers): """ Connect two layers together and update other layers in the graph. Parameters ---------- from_layer : layer or list of layers to_layer : layer or list of layers Raises ------ LayerConnectionError Raises if cannot graph cannot connect two layers. Returns ------- bool Returns ``False`` if connection has already been added into the graph, and ``True`` if connection was added successfully. """ if not isinstance(from_layers, (list, tuple)): from_layers = [from_layers] if not isinstance(to_layers, (list, tuple)): to_layers = [to_layers] connections_added = [] do_not_have_shapes = True for from_layer in from_layers: if from_layer.input_shape or from_layer.output_shape: do_not_have_shapes = False for to_layer in to_layers: connection_added = self.add_connection(from_layer, to_layer) connections_added.append(connection_added) if not any(connections_added): return False if do_not_have_shapes: return True # Layer has an input shape which means that we can # propagate this information through the graph and # set up input shape for layers that don't have it. layers = copy.copy(from_layers) forward_graph = self.forward_graph # We need to know whether all input layers # have defined input shape all_inputs_has_shape = all( layer.input_shape for layer in self.input_layers) while layers: current_layer = layers.pop() next_layers = forward_graph[current_layer] for next_layer in next_layers: next_inp_shape = next_layer.input_shape current_out_shape = current_layer.output_shape expect_one_input = does_layer_expect_one_input(next_layer) if not next_inp_shape and expect_one_input: next_layer.input_shape = current_out_shape next_layer.initialize() elif not expect_one_input and all_inputs_has_shape: input_shapes = [] for incoming_layer in self.backward_graph[next_layer]: input_shapes.append(incoming_layer.output_shape) if None not in input_shapes: next_layer.input_shape = input_shapes next_layer.initialize() else: # Some of the previous layers still don't # have input shape. We can put layer at the # end of the stack and check it again at the end layers.insert(0, current_layer) elif expect_one_input and next_inp_shape != current_out_shape: raise LayerConnectionError( "Cannot connect `{}` to the `{}`. Output shape " "from one layer is equal to {} and input shape " "to the next one is equal to {}".format( current_layer, next_layer, current_out_shape, next_inp_shape, )) layers.extend(next_layers) return True def reverse(self): """ Returns graph with reversed connections. """ return LayerGraph(self.backward_graph, self.forward_graph) def subgraph_for_output(self, output_layers): """ Extract subgraph with specified set of output layers. Parameters ---------- layers : layer, list of layers Returns ------- LayerGraph instance """ if not isinstance(output_layers, (list, tuple)): output_layers = [output_layers] if all(layer not in self.forward_graph for layer in output_layers): return LayerGraph() observed_layers = [] layers = copy.copy(output_layers) while layers: current_layer = layers.pop() next_layers = self.backward_graph[current_layer] for next_layer in next_layers: if next_layer not in observed_layers: layers.append(next_layer) observed_layers.append(current_layer) forward_subgraph = filter_dict(self.forward_graph, observed_layers) backward_subgraph = filter_dict(self.backward_graph, observed_layers) # Remove old relations to the other layers. # Output layer cannot point to some other layers. for layer in output_layers: forward_subgraph[layer] = [] return LayerGraph(forward_subgraph, backward_subgraph) def subgraph_for_input(self, input_layers): """ Extract subgraph with specified set of input layers. Parameters ---------- layers : layer, list of layers Returns ------- LayerGraph instance """ # Output layers for the reversed graph are # input layers for normal graph graph_reversed = self.reverse() subgraph_reversed = graph_reversed.subgraph_for_output(input_layers) # Reverse it to make normal graph return subgraph_reversed.reverse() def subgraph(self, input_layers, output_layers): """ Create subgraph that contains only layers that has relations between specified input and output layers. Parameters ---------- input_layers : layer, list of layers output_layers : layer, list of layers Returns ------- LayerGraph """ subgraph = self.subgraph_for_input(input_layers) return subgraph.subgraph_for_output(output_layers) @property def input_layers(self): """ List of input layers. Raises ------ LayerConnectionError If graph doesn't have input layers. Returns ------- list List of input layers. """ input_layers = [] for layer, next_layers in self.backward_graph.items(): if not next_layers: input_layers.append(layer) return input_layers @property def output_layers(self): """ List of output layers. Raises ------ LayerConnectionError If graph doesn't have output layers. Returns ------- list List of output layers. """ output_layers = [] for layer, next_layers in self.forward_graph.items(): if not next_layers: output_layers.append(layer) return output_layers def find_layer_by_name(self, layer_name): """ Find layer instance in the graph based on the specified layer name. Parameters ---------- layer_name : str Name of the layer that presented in this graph. Raises ------ NameError In case if there is no layer with specified name in the graph. Returns ------- layer """ for layer in self.forward_graph: if layer.name == layer_name: return layer raise NameError("Cannot find layer with name {!r}".format(layer_name)) def propagate_forward(self, input_value): """ Propagates input variable through the directed acyclic graph and returns output from the final layers. Parameters ---------- input_value : array-like, Theano variable or dict - If input is an array or Theano variable than it will be used as a direct input to the input layer/layers. - The dict type input should has a specific structure. Each key of the dict is a layer and each value array or Theano variable. Dict defines input values for specific layers. In the dict input layer is not necessary should be an instance of the ``layers.Input`` class. It can be any layer from the graph. Returns ------- object Output from the final layer/layers. """ outputs = {} if isinstance(input_value, dict): for layer, input_variable in input_value.items(): if isinstance(layer, six.string_types): layer = self.find_layer_by_name(layer) if layer not in self.forward_graph: raise ValueError("The `{}` layer doesn't appear " "in the graph".format(layer)) outputs[layer] = layer.output(input_variable) else: for input_layer in self.input_layers: outputs[input_layer] = input_layer.output(input_value) def output_from_layer(layer): if layer in outputs: return outputs[layer] input_layers = self.backward_graph[layer] inputs = [] for input_layer in input_layers: if input_layer in outputs: res = outputs[input_layer] else: res = output_from_layer(input_layer) outputs[input_layer] = res inputs.append(res) return layer.output(*inputs) results = [] for output_layer in self.output_layers: results.append(output_from_layer(output_layer)) if len(results) == 1: results = results[0] return results def layer_names_only(self): """ Replaces in the graph layers with their names. Parameters ---------- graph : LayerGraph Returns ------- OrderedDict """ prepared_graph = OrderedDict() for from_layer, to_layers in self.forward_graph.items(): prepared_graph[from_layer.name] = [l.name for l in to_layers] return list(prepared_graph.items()) def __len__(self): return len(self.forward_graph) def __repr__(self): graph = list(self.forward_graph.items()) return pprint.pformat(graph)
[ "collections.OrderedDict", "inspect.ismethod", "pprint.pformat", "inspect.getargspec", "copy.copy" ]
[((1278, 1291), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (1289, 1291), False, 'from collections import OrderedDict\n'), ((1895, 1908), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (1906, 1908), False, 'from collections import OrderedDict\n'), ((3980, 4012), 'inspect.getargspec', 'inspect.getargspec', (['layer.output'], {}), '(layer.output)\n', (3998, 4012), False, 'import inspect\n'), ((2103, 2119), 'copy.copy', 'copy.copy', (['value'], {}), '(value)\n', (2112, 2119), False, 'import copy\n'), ((3825, 3855), 'inspect.ismethod', 'inspect.ismethod', (['layer.output'], {}), '(layer.output)\n', (3841, 3855), False, 'import inspect\n'), ((9344, 9366), 'copy.copy', 'copy.copy', (['from_layers'], {}), '(from_layers)\n', (9353, 9366), False, 'import copy\n'), ((12075, 12099), 'copy.copy', 'copy.copy', (['output_layers'], {}), '(output_layers)\n', (12084, 12099), False, 'import copy\n'), ((18138, 18151), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (18149, 18151), False, 'from collections import OrderedDict\n'), ((18489, 18510), 'pprint.pformat', 'pprint.pformat', (['graph'], {}), '(graph)\n', (18503, 18510), False, 'import pprint\n'), ((2375, 2392), 'copy.copy', 'copy.copy', (['values'], {}), '(values)\n', (2384, 2392), False, 'import copy\n'), ((4627, 4640), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (4638, 4640), False, 'from collections import OrderedDict\n'), ((4706, 4719), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (4717, 4719), False, 'from collections import OrderedDict\n')]
# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch from kaolin.nnsearch import nnsearch import kaolin.cuda.sided_distance as sd from scipy.spatial import cKDTree as Tree import numpy as np class SidedDistanceFunction(torch.autograd.Function): @staticmethod def forward(ctx, S1, S2): batchsize, n, _ = S1.size() S1 = S1.contiguous() S2 = S2.contiguous() dist1 = torch.zeros(batchsize, n) idx1 = torch.zeros(batchsize, n, dtype=torch.int) dist1 = dist1.cuda() idx1 = idx1.cuda() try: sd.forward(S1, S2, dist1, idx1) except BaseException: sd.forward_cuda(S1, S2, dist1, idx1) return idx1.long() class SidedDistance(torch.nn.Module): r"""For every point in set1 find the indecies of the closest point in set2 Args: set1 (torch.cuda.Tensor) : set of pointclouds of shape B x N x 3 set2 (torch.cuda.Tensor) : set of pointclouds of shape B x M x 3 Returns: torch.cuda.Tensor: indecies of the closest points in set2 Example: >>> A = torch.rand(2,300,3) >>> B = torch.rand(2,200,3) >>> sided_minimum_dist = SidedDistance() >>> indices = sided_minimum_dist(A,B) >>> indices.shape torch.Size([2, 300]) """ def forward(self, S1: torch.Tensor, S2: torch.Tensor): assert len(S1.shape) == 3 assert len(S2.shape) == 3 return SidedDistanceFunction.apply(S1, S2).detach() def chamfer_distance(S1: torch.Tensor, S2: torch.Tensor, w1: float = 1., w2: float = 1.): r"""Computes the chamfer distance between two point clouds Args: S1 (torch.Tensor): point cloud S2 (torch.Tensor): point cloud w1: (float): weighting of forward direction w2: (float): weighting of backward direction Returns: torch.Tensor: chamfer distance between two point clouds S1 and S2 Example: >>> A = torch.rand(300,3) >>> B = torch.rand(200,3) >>> >>> chamfer_distance(A,B) tensor(0.1868) """ assert (S1.dim() == S2.dim()), 'S1 and S2 must have the same dimesionality' assert (S1.dim() == 2), 'the dimensions of the input must be 2 ' dist_to_S2 = directed_distance(S1, S2) dist_to_S1 = directed_distance(S2, S1) distance = w1 * dist_to_S2 + w2 * dist_to_S1 return distance def directed_distance(S1: torch.Tensor, S2: torch.Tensor, mean: bool = True): r"""Computes the average distance from point cloud S1 to point cloud S2 Args: S1 (torch.Tensor): point cloud S2 (torch.Tensor): point cloud mean (bool): if the distances should be reduced to the average Returns: torch.Tensor: ditance from point cloud S1 to point cloud S2 Args: Example: >>> A = torch.rand(300,3) >>> B = torch.rand(200,3) >>> >>> directed_distance(A,B) tensor(0.1868) """ if S1.is_cuda and S2.is_cuda: sided_minimum_dist = SidedDistance() closest_index_in_S2 = sided_minimum_dist( S1.unsqueeze(0), S2.unsqueeze(0))[0] closest_S2 = torch.index_select(S2, 0, closest_index_in_S2) else: from time import time closest_index_in_S2 = nnsearch(S1, S2) closest_S2 = S2[closest_index_in_S2] dist_to_S2 = (((S1 - closest_S2)**2).sum(dim=-1)) if mean: dist_to_S2 = dist_to_S2.mean() return dist_to_S2 def iou(points1: torch.Tensor, points2: torch.Tensor, thresh=.5): r""" Computes the intersection over union values for two sets of points Args: points1 (torch.Tensor): first points points2 (torch.Tensor): second points Returns: iou (torch.Tensor) : IoU scores for the two sets of points Examples: >>> points1 = torch.rand( 1000) >>> points2 = torch.rand( 1000) >>> loss = iou(points1, points2) tensor(0.3400) """ points1[points1 <= thresh] = 0 points1[points1 > thresh] = 1 points2[points2 <= thresh] = 0 points2[points2 > thresh] = 1 points1 = points1.view(-1).byte() points2 = points2.view(-1).byte() assert points1.shape == points2.shape, 'points1 and points2 must have the same shape' iou = torch.sum(torch.mul(points1, points2).float()) / \ torch.sum((points1 + points2).clamp(min=0, max=1).float()) return iou def f_score(gt_points: torch.Tensor, pred_points: torch.Tensor, radius: float = 0.01, extend=False): r""" Computes the f-score of two sets of points, with a hit defined by two point existing withing a defined radius of each other Args: gt_points (torch.Tensor): ground truth points pred_points (torch.Tensor): predicted points points radius (float): radisu from a point to define a hit extend (bool): if the alternate f-score definition should be applied Returns: (float): computed f-score Example: >>> points1 = torch.rand(1000) >>> points2 = torch.rand(1000) >>> loss = f_score(points1, points2) >>> loss tensor(0.0070) """ pred_distances = torch.sqrt(directed_distance( gt_points, pred_points, mean=False)) gt_distances = torch.sqrt(directed_distance( pred_points, gt_points, mean=False)) if extend: fp = (gt_distances > radius).float().sum() tp = (gt_distances <= radius).float().sum() precision = tp / (tp + fp) tp = (pred_distances <= radius).float().sum() fn = (pred_distances > radius).float().sum() recall = tp / (tp + fn) else: fn = torch.sum(pred_distances > radius) fp = torch.sum(gt_distances > radius).float() tp = torch.sum(gt_distances <= radius).float() precision = tp / (tp + fp) recall = tp / (tp + fn) f_score = 2 * (precision * recall) / (precision + recall + 1e-8) return f_score
[ "torch.index_select", "kaolin.nnsearch.nnsearch", "torch.mul", "kaolin.cuda.sided_distance.forward_cuda", "torch.sum", "kaolin.cuda.sided_distance.forward", "torch.zeros" ]
[((976, 1001), 'torch.zeros', 'torch.zeros', (['batchsize', 'n'], {}), '(batchsize, n)\n', (987, 1001), False, 'import torch\n'), ((1017, 1059), 'torch.zeros', 'torch.zeros', (['batchsize', 'n'], {'dtype': 'torch.int'}), '(batchsize, n, dtype=torch.int)\n', (1028, 1059), False, 'import torch\n'), ((3854, 3900), 'torch.index_select', 'torch.index_select', (['S2', '(0)', 'closest_index_in_S2'], {}), '(S2, 0, closest_index_in_S2)\n', (3872, 3900), False, 'import torch\n'), ((3972, 3988), 'kaolin.nnsearch.nnsearch', 'nnsearch', (['S1', 'S2'], {}), '(S1, S2)\n', (3980, 3988), False, 'from kaolin.nnsearch import nnsearch\n'), ((6430, 6464), 'torch.sum', 'torch.sum', (['(pred_distances > radius)'], {}), '(pred_distances > radius)\n', (6439, 6464), False, 'import torch\n'), ((1141, 1172), 'kaolin.cuda.sided_distance.forward', 'sd.forward', (['S1', 'S2', 'dist1', 'idx1'], {}), '(S1, S2, dist1, idx1)\n', (1151, 1172), True, 'import kaolin.cuda.sided_distance as sd\n'), ((1215, 1251), 'kaolin.cuda.sided_distance.forward_cuda', 'sd.forward_cuda', (['S1', 'S2', 'dist1', 'idx1'], {}), '(S1, S2, dist1, idx1)\n', (1230, 1251), True, 'import kaolin.cuda.sided_distance as sd\n'), ((6478, 6510), 'torch.sum', 'torch.sum', (['(gt_distances > radius)'], {}), '(gt_distances > radius)\n', (6487, 6510), False, 'import torch\n'), ((6532, 6565), 'torch.sum', 'torch.sum', (['(gt_distances <= radius)'], {}), '(gt_distances <= radius)\n', (6541, 6565), False, 'import torch\n'), ((5014, 5041), 'torch.mul', 'torch.mul', (['points1', 'points2'], {}), '(points1, points2)\n', (5023, 5041), False, 'import torch\n')]
import argparse import sys import torch from inferno.trainers.basic import Trainer from inferno.trainers.callbacks.logging.tensorboard import TensorboardLogger from torch import nn from torch.autograd import Variable from torch.utils.data.dataloader import DataLoader from torch.utils.data.dataset import Dataset from torchvision import datasets from torchvision import transforms from mnist_gan import Reshape, format_images from mnist_gan import generate_video from mnist_gan import save_args, GANModel, GenerateDataCallback, GeneratorTrainingCallback from mnist_wgangp import WGANDiscriminatorLoss, WGANGeneratorLoss class MNISTWrapper(Dataset): def __init__(self): super(MNISTWrapper, self).__init__() self.dataset = datasets.MNIST('./data/mnist', train=True, download=True, transform=transforms.ToTensor()) def __len__(self): return len(self.dataset) def __getitem__(self, item): x, y = self.dataset[item] return x, y, y def mnist_cgan_data_loader(args): # Create DataLoader for MNIST kwargs = {'num_workers': 2, 'pin_memory': True} if args.cuda else {} train_loader = DataLoader( MNISTWrapper(), batch_size=args.batch_size, shuffle=True, **kwargs) return train_loader class CGeneratorNetwork(nn.Module): # Network for generation # Input is (N, latent_dim) def __init__(self, args): super(CGeneratorNetwork, self).__init__() self.embedding = nn.Embedding(10, args.embedding_dim) self.trunk = nn.Sequential(*[m for m in [ nn.Linear(args.latent_dim + args.embedding_dim, 1024), nn.BatchNorm1d(1024) if args.generator_batchnorm else None, nn.LeakyReLU(), nn.Linear(1024, 7 * 7 * 128), Reshape(-1, 128, 7, 7), # N, 128,7,7 nn.BatchNorm2d(128) if args.generator_batchnorm else None, nn.LeakyReLU(), nn.ConvTranspose2d(128, 64, kernel_size=4, stride=2, padding=1), # N, 64,14,14 nn.BatchNorm2d(64) if args.generator_batchnorm else None, nn.LeakyReLU(), nn.ConvTranspose2d(64, 32, kernel_size=4, stride=2, padding=1), # N, 32,28,28 nn.BatchNorm2d(32) if args.generator_batchnorm else None, nn.LeakyReLU(), nn.Conv2d(32, 1, kernel_size=3, stride=1, padding=1), # N, 1,28,28 nn.Sigmoid()] if m is not None]) def forward(self, latent, y): embedded = self.embedding(y) h = torch.cat((latent, embedded), dim=1) h = self.trunk(h) return h class CDiscriminatorNetwork(nn.Module): # Network for discrimination # Input is (N, 1, 28, 28) def __init__(self, args): super(CDiscriminatorNetwork, self).__init__() self.embedding = nn.Embedding(10, args.embedding_dim) self.trunk = nn.Sequential(*[m for m in [ nn.Conv2d(1 + args.embedding_dim, 64, kernel_size=4, stride=2, padding=1), # N, 64, 14, 14 nn.BatchNorm2d(64) if args.discriminator_batchnorm else None, nn.LeakyReLU(), nn.Conv2d(64, 128, kernel_size=4, stride=2, padding=1), # N, 128, 7, 7 nn.BatchNorm2d(128) if args.discriminator_batchnorm else None, nn.LeakyReLU(), Reshape(-1, 128 * 7 * 7), # N, 128*7*7 nn.Linear(128 * 7 * 7, 1024), # N, 1024 nn.BatchNorm1d(1024) if args.discriminator_batchnorm else None, nn.LeakyReLU(), nn.Linear(1024, 1), # N, 1 Reshape(-1)] if m is not None]) # N def forward(self, x, y): embedded = self.embedding(y) # (N, dim) embedded = embedded.unsqueeze(2).unsqueeze(3).expand(-1, -1, x.size(2), x.size(3)) h = torch.cat((x, embedded), dim=1) h = self.trunk(h) return h class CGANModel(GANModel): # GAN containing generator and discriminator def __init__(self, args, discriminator, generator): super(CGANModel, self).__init__( args=args, discriminator=discriminator, generator=generator) def generate(self, latent, y): # Generate fake images from latent inputs xfake = self.generator(latent, y) # Save images for later self._state_hooks['xfake'] = xfake self._state_hooks['y'] = y self._state_hooks['generated_images'] = format_images(xfake) # log the generated images return xfake def discriminate(self, x, y): # Run discriminator on an input return self.discriminator(x, y) def y_fake(self, latent, y): # Run discriminator on generated images yfake = self.discriminate(self.generate(latent, y), y) return yfake def y_real(self, xreal, y): # Run discriminator on real images yreal = self.discriminate(xreal, y) # Save images for later self._state_hooks['xreal'] = xreal self._state_hooks['real_images'] = format_images(xreal) return yreal def latent_sample(self, xreal): # Generate latent samples of same shape as real data latent = xreal.data.new(xreal.size(0), self.latent_dim) torch.randn(*latent.size(), out=latent) latent = Variable(latent) return latent def forward(self, xreal, y): # Calculate and return y_real and y_fake return self.y_real(xreal, y), self.y_fake(self.latent_sample(xreal), y) class CWGANDiscriminatorLoss(WGANDiscriminatorLoss): def discriminate(self, xmix): y = self.model._state_hooks['y'] return self.model.discriminate(xmix, y) class CGenerateDataCallback(GenerateDataCallback): # Callback saves generated images to a folder def __init__(self, args): super(CGenerateDataCallback, self).__init__(args, gridsize=10) self.y = torch.arange(0, 10).unsqueeze(1).expand(-1, 10).contiguous().view(-1).contiguous().long() def end_of_training_iteration(self, **_): # Check if it is time to generate images self.count += 1 if self.count > self.frequency: self.save_images() self.count = 0 def generate(self, latent): # Set eval, generate, then set back to train self.trainer.model.eval() y = Variable(self.y) if self.trainer.is_cuda(): y = y.cuda() generated = self.trainer.model.generate(Variable(latent), y) self.trainer.model.train() return generated class CGeneratorTrainingCallback(GeneratorTrainingCallback): # Callback periodically trains the generator def __init__(self, args, parameters, criterion): super(CGeneratorTrainingCallback, self).__init__(args, parameters, criterion) def train_generator(self): # Train the generator # Generate latent samples if self.trainer.is_cuda(): latent = torch.cuda.FloatTensor(self.batch_size, self.latent_dim) else: latent = torch.FloatTensor(self.batch_size, self.latent_dim) torch.randn(*latent.size(), out=latent) latent = Variable(latent) # Calculate yfake y = Variable(torch.rand(latent.size(0), out=latent.data.new()) * 10).long() yfake = self.trainer.model.y_fake(latent, y) # Calculate loss loss = self.criterion(yfake) # Perform update self.opt.zero_grad() loss.backward() self.opt.step() def run(args): save_args(args) # save command line to a file for reference train_loader = mnist_cgan_data_loader(args) # get the data model = CGANModel( args, discriminator=CDiscriminatorNetwork(args), generator=CGeneratorNetwork(args)) # Build trainer trainer = Trainer(model) trainer.build_criterion(CWGANDiscriminatorLoss(penalty_weight=args.penalty_weight, model=model)) trainer.build_optimizer('Adam', model.discriminator.parameters(), lr=args.discriminator_lr) trainer.save_every((1, 'epochs')) trainer.save_to_directory(args.save_directory) trainer.set_max_num_epochs(args.epochs) trainer.register_callback(CGenerateDataCallback(args)) trainer.register_callback(CGeneratorTrainingCallback( args, parameters=model.generator.parameters(), criterion=WGANGeneratorLoss())) trainer.bind_loader('train', train_loader, num_inputs=2) # Custom logging configuration so it knows to log our images logger = TensorboardLogger( log_scalars_every=(1, 'iteration'), log_images_every=(args.log_image_frequency, 'iteration')) trainer.build_logger(logger, log_directory=args.save_directory) logger.observe_state('generated_images') logger.observe_state('real_images') logger._trainer_states_being_observed_while_training.remove('training_inputs') if args.cuda: trainer.cuda() # Go! trainer.fit() # Generate video from saved images if not args.no_ffmpeg: generate_video(args.save_directory) def main(argv): # Training settings parser = argparse.ArgumentParser(description='PyTorch GAN Example') # Output directory parser.add_argument('--save-directory', type=str, default='output/mnist_cwgangp/v1', help='output directory') # Configuration parser.add_argument('--batch-size', type=int, default=128, metavar='N', help='batch size') parser.add_argument('--epochs', type=int, default=50, metavar='N', help='number of epochs') parser.add_argument('--image-frequency', type=int, default=10, metavar='N', help='frequency to write images') parser.add_argument('--log-image-frequency', type=int, default=100, metavar='N', help='frequency to log images') parser.add_argument('--generator-frequency', type=int, default=10, metavar='N', help='frequency to train generator') # Hyperparameters parser.add_argument('--latent-dim', type=int, default=100, metavar='N', help='latent dimension') parser.add_argument('--embedding-dim', type=int, default=32, metavar='N', help='latent dimension') parser.add_argument('--discriminator-lr', type=float, default=3e-4, metavar='N', help='discriminator learning rate') parser.add_argument('--generator-lr', type=float, default=3e-4, metavar='N', help='generator learning rate') parser.add_argument('--penalty-weight', type=float, default=20., metavar='N', help='gradient penalty weight') parser.add_argument('--discriminator-batchnorm', type=bool, default=False, metavar='N', help='enable BN') parser.add_argument('--generator-batchnorm', type=bool, default=True, metavar='N', help='enable BN') # Flags parser.add_argument('--no-cuda', action='store_true', default=False, help='disables CUDA training') parser.add_argument('--no-ffmpeg', action='store_true', default=False, help='disables video generation') args = parser.parse_args(argv) args.cuda = not args.no_cuda and torch.cuda.is_available() run(args) if __name__ == '__main__': main(sys.argv[1:])
[ "mnist_wgangp.WGANGeneratorLoss", "torch.nn.BatchNorm1d", "torch.cuda.is_available", "mnist_gan.Reshape", "mnist_gan.format_images", "torch.arange", "mnist_gan.generate_video", "torch.nn.Sigmoid", "torch.nn.BatchNorm2d", "argparse.ArgumentParser", "torchvision.transforms.ToTensor", "torch.auto...
[((7509, 7524), 'mnist_gan.save_args', 'save_args', (['args'], {}), '(args)\n', (7518, 7524), False, 'from mnist_gan import save_args, GANModel, GenerateDataCallback, GeneratorTrainingCallback\n'), ((7800, 7814), 'inferno.trainers.basic.Trainer', 'Trainer', (['model'], {}), '(model)\n', (7807, 7814), False, 'from inferno.trainers.basic import Trainer\n'), ((8504, 8620), 'inferno.trainers.callbacks.logging.tensorboard.TensorboardLogger', 'TensorboardLogger', ([], {'log_scalars_every': "(1, 'iteration')", 'log_images_every': "(args.log_image_frequency, 'iteration')"}), "(log_scalars_every=(1, 'iteration'), log_images_every=(\n args.log_image_frequency, 'iteration'))\n", (8521, 8620), False, 'from inferno.trainers.callbacks.logging.tensorboard import TensorboardLogger\n'), ((9106, 9164), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""PyTorch GAN Example"""'}), "(description='PyTorch GAN Example')\n", (9129, 9164), False, 'import argparse\n'), ((1507, 1543), 'torch.nn.Embedding', 'nn.Embedding', (['(10)', 'args.embedding_dim'], {}), '(10, args.embedding_dim)\n', (1519, 1543), False, 'from torch import nn\n'), ((2540, 2576), 'torch.cat', 'torch.cat', (['(latent, embedded)'], {'dim': '(1)'}), '((latent, embedded), dim=1)\n', (2549, 2576), False, 'import torch\n'), ((2834, 2870), 'torch.nn.Embedding', 'nn.Embedding', (['(10)', 'args.embedding_dim'], {}), '(10, args.embedding_dim)\n', (2846, 2870), False, 'from torch import nn\n'), ((3794, 3825), 'torch.cat', 'torch.cat', (['(x, embedded)'], {'dim': '(1)'}), '((x, embedded), dim=1)\n', (3803, 3825), False, 'import torch\n'), ((4427, 4447), 'mnist_gan.format_images', 'format_images', (['xfake'], {}), '(xfake)\n', (4440, 4447), False, 'from mnist_gan import Reshape, format_images\n'), ((5016, 5036), 'mnist_gan.format_images', 'format_images', (['xreal'], {}), '(xreal)\n', (5029, 5036), False, 'from mnist_gan import Reshape, format_images\n'), ((5285, 5301), 'torch.autograd.Variable', 'Variable', (['latent'], {}), '(latent)\n', (5293, 5301), False, 'from torch.autograd import Variable\n'), ((6326, 6342), 'torch.autograd.Variable', 'Variable', (['self.y'], {}), '(self.y)\n', (6334, 6342), False, 'from torch.autograd import Variable\n'), ((7144, 7160), 'torch.autograd.Variable', 'Variable', (['latent'], {}), '(latent)\n', (7152, 7160), False, 'from torch.autograd import Variable\n'), ((9015, 9050), 'mnist_gan.generate_video', 'generate_video', (['args.save_directory'], {}), '(args.save_directory)\n', (9029, 9050), False, 'from mnist_gan import generate_video\n'), ((10956, 10981), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (10979, 10981), False, 'import torch\n'), ((6451, 6467), 'torch.autograd.Variable', 'Variable', (['latent'], {}), '(latent)\n', (6459, 6467), False, 'from torch.autograd import Variable\n'), ((6935, 6991), 'torch.cuda.FloatTensor', 'torch.cuda.FloatTensor', (['self.batch_size', 'self.latent_dim'], {}), '(self.batch_size, self.latent_dim)\n', (6957, 6991), False, 'import torch\n'), ((7027, 7078), 'torch.FloatTensor', 'torch.FloatTensor', (['self.batch_size', 'self.latent_dim'], {}), '(self.batch_size, self.latent_dim)\n', (7044, 7078), False, 'import torch\n'), ((851, 872), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (870, 872), False, 'from torchvision import transforms\n'), ((8343, 8362), 'mnist_wgangp.WGANGeneratorLoss', 'WGANGeneratorLoss', ([], {}), '()\n', (8360, 8362), False, 'from mnist_wgangp import WGANDiscriminatorLoss, WGANGeneratorLoss\n'), ((1606, 1659), 'torch.nn.Linear', 'nn.Linear', (['(args.latent_dim + args.embedding_dim)', '(1024)'], {}), '(args.latent_dim + args.embedding_dim, 1024)\n', (1615, 1659), False, 'from torch import nn\n'), ((1745, 1759), 'torch.nn.LeakyReLU', 'nn.LeakyReLU', ([], {}), '()\n', (1757, 1759), False, 'from torch import nn\n'), ((1773, 1801), 'torch.nn.Linear', 'nn.Linear', (['(1024)', '(7 * 7 * 128)'], {}), '(1024, 7 * 7 * 128)\n', (1782, 1801), False, 'from torch import nn\n'), ((1815, 1837), 'mnist_gan.Reshape', 'Reshape', (['(-1)', '(128)', '(7)', '(7)'], {}), '(-1, 128, 7, 7)\n', (1822, 1837), False, 'from mnist_gan import Reshape, format_images\n'), ((1936, 1950), 'torch.nn.LeakyReLU', 'nn.LeakyReLU', ([], {}), '()\n', (1948, 1950), False, 'from torch import nn\n'), ((1964, 2027), 'torch.nn.ConvTranspose2d', 'nn.ConvTranspose2d', (['(128)', '(64)'], {'kernel_size': '(4)', 'stride': '(2)', 'padding': '(1)'}), '(128, 64, kernel_size=4, stride=2, padding=1)\n', (1982, 2027), False, 'from torch import nn\n'), ((2126, 2140), 'torch.nn.LeakyReLU', 'nn.LeakyReLU', ([], {}), '()\n', (2138, 2140), False, 'from torch import nn\n'), ((2154, 2216), 'torch.nn.ConvTranspose2d', 'nn.ConvTranspose2d', (['(64)', '(32)'], {'kernel_size': '(4)', 'stride': '(2)', 'padding': '(1)'}), '(64, 32, kernel_size=4, stride=2, padding=1)\n', (2172, 2216), False, 'from torch import nn\n'), ((2315, 2329), 'torch.nn.LeakyReLU', 'nn.LeakyReLU', ([], {}), '()\n', (2327, 2329), False, 'from torch import nn\n'), ((2343, 2395), 'torch.nn.Conv2d', 'nn.Conv2d', (['(32)', '(1)'], {'kernel_size': '(3)', 'stride': '(1)', 'padding': '(1)'}), '(32, 1, kernel_size=3, stride=1, padding=1)\n', (2352, 2395), False, 'from torch import nn\n'), ((2423, 2435), 'torch.nn.Sigmoid', 'nn.Sigmoid', ([], {}), '()\n', (2433, 2435), False, 'from torch import nn\n'), ((2933, 3006), 'torch.nn.Conv2d', 'nn.Conv2d', (['(1 + args.embedding_dim)', '(64)'], {'kernel_size': '(4)', 'stride': '(2)', 'padding': '(1)'}), '(1 + args.embedding_dim, 64, kernel_size=4, stride=2, padding=1)\n', (2942, 3006), False, 'from torch import nn\n'), ((3111, 3125), 'torch.nn.LeakyReLU', 'nn.LeakyReLU', ([], {}), '()\n', (3123, 3125), False, 'from torch import nn\n'), ((3139, 3193), 'torch.nn.Conv2d', 'nn.Conv2d', (['(64)', '(128)'], {'kernel_size': '(4)', 'stride': '(2)', 'padding': '(1)'}), '(64, 128, kernel_size=4, stride=2, padding=1)\n', (3148, 3193), False, 'from torch import nn\n'), ((3298, 3312), 'torch.nn.LeakyReLU', 'nn.LeakyReLU', ([], {}), '()\n', (3310, 3312), False, 'from torch import nn\n'), ((3326, 3350), 'mnist_gan.Reshape', 'Reshape', (['(-1)', '(128 * 7 * 7)'], {}), '(-1, 128 * 7 * 7)\n', (3333, 3350), False, 'from mnist_gan import Reshape, format_images\n'), ((3378, 3406), 'torch.nn.Linear', 'nn.Linear', (['(128 * 7 * 7)', '(1024)'], {}), '(128 * 7 * 7, 1024)\n', (3387, 3406), False, 'from torch import nn\n'), ((3507, 3521), 'torch.nn.LeakyReLU', 'nn.LeakyReLU', ([], {}), '()\n', (3519, 3521), False, 'from torch import nn\n'), ((3535, 3553), 'torch.nn.Linear', 'nn.Linear', (['(1024)', '(1)'], {}), '(1024, 1)\n', (3544, 3553), False, 'from torch import nn\n'), ((3575, 3586), 'mnist_gan.Reshape', 'Reshape', (['(-1)'], {}), '(-1)\n', (3582, 3586), False, 'from mnist_gan import Reshape, format_images\n'), ((1673, 1693), 'torch.nn.BatchNorm1d', 'nn.BatchNorm1d', (['(1024)'], {}), '(1024)\n', (1687, 1693), False, 'from torch import nn\n'), ((1865, 1884), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['(128)'], {}), '(128)\n', (1879, 1884), False, 'from torch import nn\n'), ((2056, 2074), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['(64)'], {}), '(64)\n', (2070, 2074), False, 'from torch import nn\n'), ((2245, 2263), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['(32)'], {}), '(32)\n', (2259, 2263), False, 'from torch import nn\n'), ((3037, 3055), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['(64)'], {}), '(64)\n', (3051, 3055), False, 'from torch import nn\n'), ((3223, 3242), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['(128)'], {}), '(128)\n', (3237, 3242), False, 'from torch import nn\n'), ((3431, 3451), 'torch.nn.BatchNorm1d', 'nn.BatchNorm1d', (['(1024)'], {}), '(1024)\n', (3445, 3451), False, 'from torch import nn\n'), ((5886, 5905), 'torch.arange', 'torch.arange', (['(0)', '(10)'], {}), '(0, 10)\n', (5898, 5905), False, 'import torch\n')]
#!/usr/bin/env python # coding:utf8 # Copyright (c) 2018, Tencent. All rights reserved # This file contain DataProcessor class which can # 1. Generate dict from train text data: # Text format: label\t[(token )+]\t[(char )+]\t[(custom_feature )+]. # Label could be flattened or hierarchical which is separated by "--". # 2. Convert data to tfrecord according to dict and config. # 3. Provide input_fn for estimator train and serving. import codecs import json import os import sys from collections import Counter import tensorflow as tf import util from config import Config class DataProcessor(object): VOCAB_UNKNOWN = "_UNK" VOCAB_PADDING = "_PAD" # Text format: label\t[(token )+]\t[(char )+]\t[(custom_feature )+]. LINE_SPLIT_NUMBER = 4 # Index of line, also index in dict list LABEL_INDEX = 0 TOKEN_INDEX = 1 CHAR_INDEX = 2 CUSTOM_FEATURE_INDEX = 3 USE_SPECIAL_LABEL = False SPECIAL_LABEL_LIST = ["社会", "时政", "国际", "军事"] SPECIAL_LABEL = "|".join(SPECIAL_LABEL_LIST) # TODO(marvinmu): check config def __init__(self, config, logger=None): self.config = config if logger: self.logger = logger else: self.logger = util.Logger(config) self.dict_names = ["label", "token", "char", "custom_feature", "token_ngram", "char_ngram", "char_in_token"] self.dict_files = [] for dict_name in self.dict_names: self.dict_files.append( self.config.data.dict_dir + "/" + dict_name + ".dict") self.label_dict_file = self.dict_files[0] # Should keep all labels self.min_count = [0, self.config.feature_common.min_token_count, self.config.feature_common.min_char_count, self.config.var_len_feature.min_custom_feature_count, self.config.var_len_feature.min_token_ngram_count, self.config.var_len_feature.min_char_ngram_count, self.config.feature_common.min_char_count_in_token] # Should keep all labels self.max_dict_size = \ [1000 * 1000, self.config.feature_common.max_token_dict_size, self.config.feature_common.max_char_dict_size, self.config.var_len_feature.max_custom_feature_dict_size, self.config.var_len_feature.max_token_ngram_dict_size, self.config.var_len_feature.max_char_ngram_dict_size, self.config.feature_common.max_char_in_token_dict_size] # Label and custom feature has no max_sequence_length. self.max_sequence_length = \ [0, self.config.fixed_len_feature.max_token_sequence_length, self.config.fixed_len_feature.max_char_sequence_length, 0] # Label and custom feature has no ngram. self.ngram_list = [0, self.config.var_len_feature.token_ngram, self.config.var_len_feature.char_ngram, 0] self.label_map = dict() self.token_map = dict() self.char_map = dict() self.custom_feature_map = dict() self.token_gram_map = dict() self.char_gram_map = dict() self.char_in_token_map = dict() self.dict_list = [self.label_map, self.token_map, self.char_map, self.custom_feature_map, self.token_gram_map, self.char_gram_map, self.char_in_token_map] self.id_to_label_map = dict() self.id_to_token_map = dict() self.id_to_char_map = dict() self.id_to_custom_feature_map = dict() self.id_to_token_gram_map = dict() self.id_to_char_gram_map = dict() self.id_to_char_in_token_map = dict() self.id_to_vocab_dict_list = [ self.id_to_label_map, self.id_to_token_map, self.id_to_char_map, self.id_to_custom_feature_map, self.id_to_token_gram_map, self.id_to_char_gram_map, self.id_to_char_in_token_map] self.train_text_file, self.validate_text_file, self.test_text_file = \ self.config.data.train_text_file, \ self.config.data.validate_text_file, \ self.config.data.test_text_file self.tfrecord_files = [ self.config.data.tfrecord_dir + "/" + os.path.basename( self.train_text_file) + ".tfrecord", self.config.data.tfrecord_dir + "/" + os.path.basename( self.validate_text_file) + ".tfrecord", self.config.data.tfrecord_dir + "/" + os.path.basename( self.test_text_file) + ".tfrecord"] self.train_file, self.validate_file, self.test_file = \ self.tfrecord_files self.feature_files = [ self.config.data.tfrecord_dir + "/" + os.path.basename( self.train_text_file) + ".feature", self.config.data.tfrecord_dir + "/" + os.path.basename( self.validate_text_file) + ".feature", self.config.data.tfrecord_dir + "/" + os.path.basename( self.test_text_file) + ".feature"] (self.train_feature_file, self.validate_feature_file, self.test_feature_file) = self.feature_files self.pretrained_embedding_files = [ "", config.feature_common.token_pretrained_embedding_file, config.feature_common.char_pretrained_embedding_file, config.var_len_feature.custom_feature_pretrained_embedding_file, ] self.int_list_column = ["fixed_len_token", "var_len_token", "char_in_token", "char_in_token_real_len", "fixed_len_char", "var_len_char", "var_len_token_ngram", "var_len_char_ngram", "var_len_custom_feature"] self.int_column = ["token_fixed_real_len", "char_fixed_real_len"] self.float_column = ["token_var_real_len", "char_var_real_len", "token_ngram_var_real_len", "char_ngram_var_real_len", "custom_feature_var_real_len"] def _save_dict(self, dict_file, counter, name): """Save all vocab to file. Args: dict_file: File to save to. counter: Vocab counts. name: Dict name. """ dict_list = counter.most_common() dict_file = codecs.open(dict_file, "w", encoding=util.CHARSET) # Save _UNK for vocab not in dict and _PAD for padding count = 1000 * 1000 # Must bigger than min count if name != "label": dict_list = [(self.VOCAB_PADDING, count), (self.VOCAB_UNKNOWN, count)] + dict_list for vocab in dict_list: dict_file.write("%s\t%d\n" % (vocab[0], vocab[1])) dict_file.close() self.logger.info("Total count of %s: %d" % (name, len(dict_list))) def _load_dict(self, dict_map, id_to_vocab_dict_map, dict_file, min_count, max_dict_size, name): """Load dict according to params. Args: dict_map: Vocab dict map. id_to_vocab_dict_map: Id to vocab dict map. dict_file: File to load. min_count: Vocab whose count is equal or greater than min_count will be loaded. max_dict_size: Load top max_dict_size vocabs sorted by count. name: Dict name. Returns: dict. """ if not os.path.exists(dict_file): self.logger.warn("Not exists %s for %s" % (dict_file, name)) else: for line in codecs.open(dict_file, "r", encoding=util.CHARSET): vocab = line.strip("\n").split("\t") try: temp = vocab[1] except IndexError: continue if int(temp) >= min_count: index = len(dict_map) dict_map[vocab[0]] = index id_to_vocab_dict_map[index] = vocab[0] if len(dict_map) >= max_dict_size: self.logger.warn( "Reach the max size(%d) of %s, ignore the rest" % ( max_dict_size, name)) break self.logger.info("Load %d vocab of %s" % (len(dict_map), name)) def load_all_dict(self): """Load all dict. """ for i, dict_name in enumerate(self.dict_names): self._load_dict(self.dict_list[i], self.id_to_vocab_dict_list[i], self.dict_files[i], self.min_count[i], self.max_dict_size[i], dict_name) def _generate_dict(self, text_file_list): """Generate dict and label dict given train text file. Save all vocab to files and load dicts. Text format: label\t[(token )+]\t[(char )+]\t[(feature )+]. Label could be flattened or hierarchical which is separated by "--". Args: text_file_list: Text file list, usually only contain train text file. """ sample_size = 0 label_counter = Counter() token_counter = Counter() char_in_token_counter = Counter() token_ngram_counter = Counter() char_counter = Counter() char_ngram_counter = Counter() custom_feature_counter = Counter() counters = [label_counter, token_counter, char_counter, custom_feature_counter, token_ngram_counter, char_ngram_counter, char_in_token_counter] for text_file in text_file_list: self.logger.info("Generate dict using text file %s" % text_file) for line in codecs.open(text_file, "r", encoding='utf8'): content = line.strip("\n").split('\t') if len(content) != self.LINE_SPLIT_NUMBER: self.logger.error("Wrong line: %s" % line) continue sample_size += 1 for i, _ in enumerate(content): vocabs = content[i].strip().split(" ") counters[i].update(vocabs) if i == self.LABEL_INDEX: # 增加特殊类处理 if vocabs[0] in self.SPECIAL_LABEL_LIST and self.USE_SPECIAL_LABEL: vocabs = [self.SPECIAL_LABEL] counters[i].update(vocabs) # If vocab is token, extract char info of each token if i == self.TOKEN_INDEX: char_in_token = [] for vocab in vocabs: char_in_token.extend(vocab) char_in_token_counter.update(char_in_token) if self.ngram_list[i] > 1: ngram_list = [] for j in range(2, self.ngram_list[i] + 1): ngram_list.extend(["".join(vocabs[k:k + j]) for k in range(len(vocabs) - j + 1)]) counters[i + 3].update(ngram_list) for counter in counters: if "" in counter.keys(): counter.pop("") self.logger.info("sample size: %d" % sample_size) for i, dict_name in enumerate(self.dict_names): self._save_dict(self.dict_files[i], counters[i], self.dict_names[i]) def _get_vocab_id_list(self, dict_map, vocabs, ngram, sequence_length, max_var_length, ngram_dict_map=None, char_in_token_map=None, max_char_sequence_length_per_token=-1): """Convert vocab string list to vocab id list. Args: dict_map: Dict used to map string to id. vocabs: Vocab string list. ngram: Ngram to use (if bigger than 1). sequence_length: List length for fixed length vocab id list. max_var_length: List length for var length vocab id list. ngram_dict_map: Ngram dict map. max_char_sequence_length_per_token: Useful when using char to get token embedding. Returns: fixed length vocab id list, real length of fixed vocab id list, var length vocab id list, ngram string list. """ if len(dict_map) == 0 or len(vocabs) == 0: return [], 0, [], [], [], [] vocabs_iter = [x for x in vocabs if x in dict_map] var_len_vocabs = [dict_map[x] for x in vocabs_iter] if len(var_len_vocabs) > max_var_length: var_len_vocabs = var_len_vocabs[0:max_var_length] if not var_len_vocabs: var_len_vocabs.append(dict_map[self.VOCAB_UNKNOWN]) if len(vocabs) > sequence_length: vocabs = vocabs[0:sequence_length] fixed_len_vocabs = [] fixed_len_vocabs.extend( [dict_map[x] if x in dict_map else dict_map[self.VOCAB_UNKNOWN] for x in vocabs]) fixed_real_len = len(fixed_len_vocabs) if fixed_real_len < sequence_length: fixed_len_vocabs.extend([dict_map[self.VOCAB_PADDING]] * ( sequence_length - len(fixed_len_vocabs))) ngram_list = [] if ngram > 1: ngram_list_str = [] for i in range(2, ngram + 1): ngram_list_str.extend(["".join(vocabs[j:j + i]) for j in range(len(vocabs) - i + 1)]) ngram_iter = [x for x in ngram_list_str if x in ngram_dict_map] ngram_list = [ngram_dict_map[x] for x in ngram_iter] if not ngram_list: ngram_list.append(ngram_dict_map[self.VOCAB_UNKNOWN]) char_in_token = [] char_in_token_real_len = [] if max_char_sequence_length_per_token > 0: length = 0 for vocab in vocabs: length += 1 chars = [] chars.extend( [char_in_token_map[x] if x in char_in_token_map else char_in_token_map[self.VOCAB_UNKNOWN] for x in vocab]) if len(chars) > max_char_sequence_length_per_token: chars = chars[0:max_char_sequence_length_per_token] char_in_token_real_len.append(len(chars)) if len(chars) < max_char_sequence_length_per_token: chars.extend([char_in_token_map[self.VOCAB_PADDING]] * ( max_char_sequence_length_per_token - len(chars))) char_in_token.extend(chars) while length < sequence_length: length += 1 char_in_token.extend( [char_in_token_map[self.VOCAB_PADDING]] * max_char_sequence_length_per_token) char_in_token_real_len.append(0) return (fixed_len_vocabs, fixed_real_len, var_len_vocabs, ngram_list, char_in_token, char_in_token_real_len) def _get_features_from_text(self, text, has_label=True): """Parse text to features that model can use. Args: text: Input text has_label: If true, result will contain label. Returns: Features that model can use. """ content = text.split('\t') if len(content) != self.LINE_SPLIT_NUMBER: self.logger.error("Wrong format line: %s" % text) return None label_string = content[self.LABEL_INDEX] if has_label and label_string not in self.label_map: self.logger.error("Wrong label of line: %s" % text) return None token = content[self.TOKEN_INDEX].strip().split(" ") (fixed_len_token, token_fixed_real_len, var_len_token, var_len_token_ngram, char_in_token, char_in_token_real_len) = \ self._get_vocab_id_list( self.token_map, token, self.config.var_len_feature.token_ngram, self.config.fixed_len_feature.max_token_sequence_length, self.config.var_len_feature.max_var_token_length, self.token_gram_map, self.char_in_token_map, self.config.fixed_len_feature.max_char_length_per_token) chars = content[self.CHAR_INDEX].strip().split(" ") (fixed_len_char, char_fixed_real_len, var_len_char, var_len_char_ngram, _, _) = self._get_vocab_id_list( self.char_map, chars, self.config.var_len_feature.char_ngram, self.config.fixed_len_feature.max_char_sequence_length, self.config.var_len_feature.max_var_char_length, self.char_gram_map) custom_features = content[self.CUSTOM_FEATURE_INDEX].strip().split( " ") _, _, var_len_custom_feature, _, _, _ = self._get_vocab_id_list( self.custom_feature_map, custom_features, 0, 0, 0, self.config.var_len_feature.max_var_custom_feature_length, None) feature_sample = dict({ "fixed_len_token": fixed_len_token, "token_fixed_real_len": token_fixed_real_len, "var_len_token": var_len_token, "token_var_real_len": len(var_len_token), "char_in_token": char_in_token, "char_in_token_real_len": char_in_token_real_len, "var_len_token_ngram": var_len_token_ngram, "token_ngram_var_real_len": len(var_len_token_ngram), "fixed_len_char": fixed_len_char, "char_fixed_real_len": char_fixed_real_len, "var_len_char": var_len_char, "char_var_real_len": len(var_len_char), "var_len_char_ngram": var_len_char_ngram, "char_ngram_var_real_len": len(var_len_char_ngram), "var_len_custom_feature": var_len_custom_feature, "custom_feature_var_real_len": len(var_len_custom_feature) }) if has_label: label = self.label_map[content[0]] if content[self.LABEL_INDEX] in self.SPECIAL_LABEL_LIST and self.USE_SPECIAL_LABEL: label = self.label_map[self.SPECIAL_LABEL] feature_sample["label"] = label return feature_sample def _convert_features_to_tfexample(self, feature_sample, has_label=True): """Convert feature sample to tf.example Args: feature_sample: Feature sample. has_label: If true, result will contain label Returns: tf.example """ if not feature_sample: return None tfexample = tf.train.Example() for name in self.int_list_column: tfexample.features.feature[name].int64_list.value.extend( feature_sample[name]) for name in self.int_column: tfexample.features.feature[name].int64_list.value.append( feature_sample[name]) for name in self.float_column: tfexample.features.feature[name].float_list.value.append( feature_sample[name]) if has_label: tfexample.features.feature["label"].int64_list.value.append( feature_sample["label"]) return tfexample def get_tfexample_from_text(self, text, has_label=True): feature_sample = self._get_features_from_text(text, has_label) tfexample = self._convert_features_to_tfexample(feature_sample, has_label) return tfexample, feature_sample def _get_tfrecord_from_text_file(self, text_file, tfrecord_file, feature_file): """Get tfrecord from text file. Text format: label\t[(token )+]\t[(char )+]\t[(feature )+]. Label could be flattened or hierarchical which is separated by "--". Args: text_file: Text file. tfrecord_file: Tfrecord file to write. feature_file: Feature file, will save feature sample for debug. For validate and test evaluation """ self.logger.info("Get tfrecord from text file %s" % text_file) writer = tf.python_io.TFRecordWriter(tfrecord_file) sample_size = 0 with codecs.open(feature_file, "w", encoding=util.CHARSET) as label_file: for line in codecs.open(text_file, "r", encoding='utf8'): tfexample, feature_sample = self.get_tfexample_from_text(line) if tfexample is not None: feature_str = json.dumps(feature_sample, ensure_ascii=False) label_file.write( self.id_to_label_map[feature_sample["label"]] + "\t" + feature_str + "\n") writer.write(tfexample.SerializeToString()) sample_size += 1 writer.close() self.logger.info( "Text file %s has sample %d" % (text_file, sample_size)) def process_from_text_file(self, use_exists_dict=False): """Process text data to tfrecord for training and generate dicts. """ if not os.path.exists(self.config.data.tfrecord_dir): os.makedirs(self.config.data.tfrecord_dir) if not os.path.exists(self.config.data.dict_dir): os.makedirs(self.config.data.dict_dir) if use_exists_dict: self.load_all_dict() else: self._generate_dict([self.config.data.train_text_file]) # If using pretrained embedding, dict can be generated by all text file. # when repeating the result in the paper of textcnn, the following code # should be used. # self._generate_dict([self.config.data.train_text_file, # self.config.data.validate_text_file, # self.config.data.test_text_file]) self.load_all_dict() text_files = [self.config.data.train_text_file, self.config.data.validate_text_file, self.config.data.test_text_file] for i, text_file in enumerate(text_files): self._get_tfrecord_from_text_file(text_file, self.tfrecord_files[i], self.feature_files[i]) @staticmethod def _get_feature_spec(has_label): """Feature map to parse tf.example Args: has_label: If true, feature map include label Return: feature map """ feature_spec = dict({ "fixed_len_token": tf.VarLenFeature(dtype=tf.int64), "token_fixed_real_len": tf.FixedLenFeature(shape=(1,), dtype=tf.int64), "var_len_token": tf.VarLenFeature(dtype=tf.int64), "token_var_real_len": tf.FixedLenFeature(shape=(1,), dtype=tf.float32), "char_in_token": tf.VarLenFeature(dtype=tf.int64), "char_in_token_real_len": tf.VarLenFeature(dtype=tf.int64), "var_len_token_ngram": tf.VarLenFeature(dtype=tf.int64), "token_ngram_var_real_len": tf.FixedLenFeature(shape=(1,), dtype=tf.float32), "fixed_len_char": tf.VarLenFeature(dtype=tf.int64), "char_fixed_real_len": tf.FixedLenFeature(shape=(1,), dtype=tf.int64), "var_len_char": tf.VarLenFeature(dtype=tf.int64), "char_var_real_len": tf.FixedLenFeature(shape=(1,), dtype=tf.float32), "var_len_char_ngram": tf.VarLenFeature(dtype=tf.int64), "char_ngram_var_real_len": tf.FixedLenFeature(shape=(1,), dtype=tf.float32), "var_len_custom_feature": tf.VarLenFeature(dtype=tf.int64), "custom_feature_var_real_len": tf.FixedLenFeature(shape=(1,), dtype=tf.float32), }) if has_label: feature_spec["label"] = tf.FixedLenFeature(shape=(1,), dtype=tf.int64) return feature_spec def check_tfrecord(self, file_names, field_name, dtype=tf.int32): """Check one field of tfrecord Args: file_names: List of file names. field_name: Field to check. dtype: Field data type. """ filename_queue = tf.train.string_input_producer(file_names, shuffle=False) reader = tf.TFRecordReader() _, serialized_example = reader.read(filename_queue) features = tf.parse_single_example(serialized_example, self._get_feature_spec(True)) feature = tf.cast(features[field_name], dtype) check_file = codecs.open("tf_check.txt", "w", encoding=util.CHARSET) with tf.Session(config=tf.ConfigProto( device_count={"CPU":12}, inter_op_parallelism_threads=1, intra_op_parallelism_threads=1, gpu_options=gpu_options, )) as sess: #with tf.Session() as sess: init_op = tf.global_variables_initializer() sess.run(init_op) coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) check_file.write(feature.eval()) coord.request_stop() coord.join(threads) check_file.close() def _parse_tfexample(self, example, mode=tf.estimator.ModeKeys.TRAIN): """Parse input example. Args: example: Tf.example. mode: Estimator mode. Return: parsed feature and label. """ parsed = tf.parse_single_example(example, self._get_feature_spec(True)) parsed = self._sparse_to_dense(parsed) label = None if mode != tf.estimator.ModeKeys.PREDICT: label = parsed.pop("label") return parsed, label def _sparse_to_dense(self, parsed_example): for key in self.int_list_column: if "var" not in key: parsed_example[key] = tf.sparse_tensor_to_dense( parsed_example[key]) return parsed_example def dataset_input_fn(self, mode, input_file, batch_size, num_epochs=1): """Input function using tf.dataset for estimator Args: mode: input mode of tf.estimator.ModeKeys.{TRAIN, EVAL, PREDICT}. input_file: Input tfrecord file. batch_size: Batch size for model. num_epochs: Number epoch. Returns: tf.dataset """ dataset = tf.data.TFRecordDataset(input_file) dataset = dataset.map(self._parse_tfexample) if mode != tf.estimator.ModeKeys.PREDICT: dataset = dataset.shuffle( buffer_size=self.config.data.shuffle_buffer) dataset = dataset.repeat(num_epochs) dataset = dataset.batch(batch_size) return dataset def serving_input_receiver_fn(self): """Input function for session server Returns: input_receiver_fn for session server """ serialized_tf_example = tf.placeholder( dtype=tf.string, name='input_example_tensor') receiver_tensors = {'examples': serialized_tf_example} parsed_example = tf.parse_example(serialized_tf_example, self._get_feature_spec(False)) parsed_example = self._sparse_to_dense(parsed_example) return tf.estimator.export.ServingInputReceiver(parsed_example, receiver_tensors) def main(_): config = Config(config_file=sys.argv[1]) data_processor = DataProcessor(config) data_processor.process_from_text_file() if __name__ == '__main__': tf.app.run()
[ "config.Config", "util.Logger", "tensorflow.TFRecordReader", "tensorflow.cast", "tensorflow.app.run", "os.path.exists", "tensorflow.train.Example", "tensorflow.train.Coordinator", "tensorflow.placeholder", "json.dumps", "tensorflow.estimator.export.ServingInputReceiver", "tensorflow.python_io....
[((28196, 28227), 'config.Config', 'Config', ([], {'config_file': 'sys.argv[1]'}), '(config_file=sys.argv[1])\n', (28202, 28227), False, 'from config import Config\n'), ((28348, 28360), 'tensorflow.app.run', 'tf.app.run', ([], {}), '()\n', (28358, 28360), True, 'import tensorflow as tf\n'), ((6482, 6532), 'codecs.open', 'codecs.open', (['dict_file', '"""w"""'], {'encoding': 'util.CHARSET'}), "(dict_file, 'w', encoding=util.CHARSET)\n", (6493, 6532), False, 'import codecs\n'), ((9264, 9273), 'collections.Counter', 'Counter', ([], {}), '()\n', (9271, 9273), False, 'from collections import Counter\n'), ((9298, 9307), 'collections.Counter', 'Counter', ([], {}), '()\n', (9305, 9307), False, 'from collections import Counter\n'), ((9340, 9349), 'collections.Counter', 'Counter', ([], {}), '()\n', (9347, 9349), False, 'from collections import Counter\n'), ((9380, 9389), 'collections.Counter', 'Counter', ([], {}), '()\n', (9387, 9389), False, 'from collections import Counter\n'), ((9413, 9422), 'collections.Counter', 'Counter', ([], {}), '()\n', (9420, 9422), False, 'from collections import Counter\n'), ((9452, 9461), 'collections.Counter', 'Counter', ([], {}), '()\n', (9459, 9461), False, 'from collections import Counter\n'), ((9495, 9504), 'collections.Counter', 'Counter', ([], {}), '()\n', (9502, 9504), False, 'from collections import Counter\n'), ((18804, 18822), 'tensorflow.train.Example', 'tf.train.Example', ([], {}), '()\n', (18820, 18822), True, 'import tensorflow as tf\n'), ((20380, 20422), 'tensorflow.python_io.TFRecordWriter', 'tf.python_io.TFRecordWriter', (['tfrecord_file'], {}), '(tfrecord_file)\n', (20407, 20422), True, 'import tensorflow as tf\n'), ((24872, 24929), 'tensorflow.train.string_input_producer', 'tf.train.string_input_producer', (['file_names'], {'shuffle': '(False)'}), '(file_names, shuffle=False)\n', (24902, 24929), True, 'import tensorflow as tf\n'), ((25003, 25022), 'tensorflow.TFRecordReader', 'tf.TFRecordReader', ([], {}), '()\n', (25020, 25022), True, 'import tensorflow as tf\n'), ((25237, 25273), 'tensorflow.cast', 'tf.cast', (['features[field_name]', 'dtype'], {}), '(features[field_name], dtype)\n', (25244, 25273), True, 'import tensorflow as tf\n'), ((25295, 25350), 'codecs.open', 'codecs.open', (['"""tf_check.txt"""', '"""w"""'], {'encoding': 'util.CHARSET'}), "('tf_check.txt', 'w', encoding=util.CHARSET)\n", (25306, 25350), False, 'import codecs\n'), ((27136, 27171), 'tensorflow.data.TFRecordDataset', 'tf.data.TFRecordDataset', (['input_file'], {}), '(input_file)\n', (27159, 27171), True, 'import tensorflow as tf\n'), ((27684, 27744), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.string', 'name': '"""input_example_tensor"""'}), "(dtype=tf.string, name='input_example_tensor')\n", (27698, 27744), True, 'import tensorflow as tf\n'), ((28037, 28111), 'tensorflow.estimator.export.ServingInputReceiver', 'tf.estimator.export.ServingInputReceiver', (['parsed_example', 'receiver_tensors'], {}), '(parsed_example, receiver_tensors)\n', (28077, 28111), True, 'import tensorflow as tf\n'), ((1241, 1260), 'util.Logger', 'util.Logger', (['config'], {}), '(config)\n', (1252, 1260), False, 'import util\n'), ((7586, 7611), 'os.path.exists', 'os.path.exists', (['dict_file'], {}), '(dict_file)\n', (7600, 7611), False, 'import os\n'), ((7724, 7774), 'codecs.open', 'codecs.open', (['dict_file', '"""r"""'], {'encoding': 'util.CHARSET'}), "(dict_file, 'r', encoding=util.CHARSET)\n", (7735, 7774), False, 'import codecs\n'), ((9839, 9883), 'codecs.open', 'codecs.open', (['text_file', '"""r"""'], {'encoding': '"""utf8"""'}), "(text_file, 'r', encoding='utf8')\n", (9850, 9883), False, 'import codecs\n'), ((20461, 20514), 'codecs.open', 'codecs.open', (['feature_file', '"""w"""'], {'encoding': 'util.CHARSET'}), "(feature_file, 'w', encoding=util.CHARSET)\n", (20472, 20514), False, 'import codecs\n'), ((20579, 20623), 'codecs.open', 'codecs.open', (['text_file', '"""r"""'], {'encoding': '"""utf8"""'}), "(text_file, 'r', encoding='utf8')\n", (20590, 20623), False, 'import codecs\n'), ((21370, 21415), 'os.path.exists', 'os.path.exists', (['self.config.data.tfrecord_dir'], {}), '(self.config.data.tfrecord_dir)\n', (21384, 21415), False, 'import os\n'), ((21429, 21471), 'os.makedirs', 'os.makedirs', (['self.config.data.tfrecord_dir'], {}), '(self.config.data.tfrecord_dir)\n', (21440, 21471), False, 'import os\n'), ((21487, 21528), 'os.path.exists', 'os.path.exists', (['self.config.data.dict_dir'], {}), '(self.config.data.dict_dir)\n', (21501, 21528), False, 'import os\n'), ((21542, 21580), 'os.makedirs', 'os.makedirs', (['self.config.data.dict_dir'], {}), '(self.config.data.dict_dir)\n', (21553, 21580), False, 'import os\n'), ((24461, 24507), 'tensorflow.FixedLenFeature', 'tf.FixedLenFeature', ([], {'shape': '(1,)', 'dtype': 'tf.int64'}), '(shape=(1,), dtype=tf.int64)\n', (24479, 24507), True, 'import tensorflow as tf\n'), ((25622, 25655), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (25653, 25655), True, 'import tensorflow as tf\n'), ((25706, 25728), 'tensorflow.train.Coordinator', 'tf.train.Coordinator', ([], {}), '()\n', (25726, 25728), True, 'import tensorflow as tf\n'), ((25751, 25792), 'tensorflow.train.start_queue_runners', 'tf.train.start_queue_runners', ([], {'coord': 'coord'}), '(coord=coord)\n', (25779, 25792), True, 'import tensorflow as tf\n'), ((22823, 22855), 'tensorflow.VarLenFeature', 'tf.VarLenFeature', ([], {'dtype': 'tf.int64'}), '(dtype=tf.int64)\n', (22839, 22855), True, 'import tensorflow as tf\n'), ((22893, 22939), 'tensorflow.FixedLenFeature', 'tf.FixedLenFeature', ([], {'shape': '(1,)', 'dtype': 'tf.int64'}), '(shape=(1,), dtype=tf.int64)\n', (22911, 22939), True, 'import tensorflow as tf\n'), ((23025, 23057), 'tensorflow.VarLenFeature', 'tf.VarLenFeature', ([], {'dtype': 'tf.int64'}), '(dtype=tf.int64)\n', (23041, 23057), True, 'import tensorflow as tf\n'), ((23093, 23141), 'tensorflow.FixedLenFeature', 'tf.FixedLenFeature', ([], {'shape': '(1,)', 'dtype': 'tf.float32'}), '(shape=(1,), dtype=tf.float32)\n', (23111, 23141), True, 'import tensorflow as tf\n'), ((23225, 23257), 'tensorflow.VarLenFeature', 'tf.VarLenFeature', ([], {'dtype': 'tf.int64'}), '(dtype=tf.int64)\n', (23241, 23257), True, 'import tensorflow as tf\n'), ((23297, 23329), 'tensorflow.VarLenFeature', 'tf.VarLenFeature', ([], {'dtype': 'tf.int64'}), '(dtype=tf.int64)\n', (23313, 23329), True, 'import tensorflow as tf\n'), ((23366, 23398), 'tensorflow.VarLenFeature', 'tf.VarLenFeature', ([], {'dtype': 'tf.int64'}), '(dtype=tf.int64)\n', (23382, 23398), True, 'import tensorflow as tf\n'), ((23440, 23488), 'tensorflow.FixedLenFeature', 'tf.FixedLenFeature', ([], {'shape': '(1,)', 'dtype': 'tf.float32'}), '(shape=(1,), dtype=tf.float32)\n', (23458, 23488), True, 'import tensorflow as tf\n'), ((23580, 23612), 'tensorflow.VarLenFeature', 'tf.VarLenFeature', ([], {'dtype': 'tf.int64'}), '(dtype=tf.int64)\n', (23596, 23612), True, 'import tensorflow as tf\n'), ((23649, 23695), 'tensorflow.FixedLenFeature', 'tf.FixedLenFeature', ([], {'shape': '(1,)', 'dtype': 'tf.int64'}), '(shape=(1,), dtype=tf.int64)\n', (23667, 23695), True, 'import tensorflow as tf\n'), ((23779, 23811), 'tensorflow.VarLenFeature', 'tf.VarLenFeature', ([], {'dtype': 'tf.int64'}), '(dtype=tf.int64)\n', (23795, 23811), True, 'import tensorflow as tf\n'), ((23846, 23894), 'tensorflow.FixedLenFeature', 'tf.FixedLenFeature', ([], {'shape': '(1,)', 'dtype': 'tf.float32'}), '(shape=(1,), dtype=tf.float32)\n', (23864, 23894), True, 'import tensorflow as tf\n'), ((23982, 24014), 'tensorflow.VarLenFeature', 'tf.VarLenFeature', ([], {'dtype': 'tf.int64'}), '(dtype=tf.int64)\n', (23998, 24014), True, 'import tensorflow as tf\n'), ((24055, 24103), 'tensorflow.FixedLenFeature', 'tf.FixedLenFeature', ([], {'shape': '(1,)', 'dtype': 'tf.float32'}), '(shape=(1,), dtype=tf.float32)\n', (24073, 24103), True, 'import tensorflow as tf\n'), ((24202, 24234), 'tensorflow.VarLenFeature', 'tf.VarLenFeature', ([], {'dtype': 'tf.int64'}), '(dtype=tf.int64)\n', (24218, 24234), True, 'import tensorflow as tf\n'), ((24279, 24327), 'tensorflow.FixedLenFeature', 'tf.FixedLenFeature', ([], {'shape': '(1,)', 'dtype': 'tf.float32'}), '(shape=(1,), dtype=tf.float32)\n', (24297, 24327), True, 'import tensorflow as tf\n'), ((26613, 26659), 'tensorflow.sparse_tensor_to_dense', 'tf.sparse_tensor_to_dense', (['parsed_example[key]'], {}), '(parsed_example[key])\n', (26638, 26659), True, 'import tensorflow as tf\n'), ((4356, 4394), 'os.path.basename', 'os.path.basename', (['self.train_text_file'], {}), '(self.train_text_file)\n', (4372, 4394), False, 'import os\n'), ((4477, 4518), 'os.path.basename', 'os.path.basename', (['self.validate_text_file'], {}), '(self.validate_text_file)\n', (4493, 4518), False, 'import os\n'), ((4601, 4638), 'os.path.basename', 'os.path.basename', (['self.test_text_file'], {}), '(self.test_text_file)\n', (4617, 4638), False, 'import os\n'), ((4849, 4887), 'os.path.basename', 'os.path.basename', (['self.train_text_file'], {}), '(self.train_text_file)\n', (4865, 4887), False, 'import os\n'), ((4969, 5010), 'os.path.basename', 'os.path.basename', (['self.validate_text_file'], {}), '(self.validate_text_file)\n', (4985, 5010), False, 'import os\n'), ((5092, 5129), 'os.path.basename', 'os.path.basename', (['self.test_text_file'], {}), '(self.test_text_file)\n', (5108, 5129), False, 'import os\n'), ((20780, 20826), 'json.dumps', 'json.dumps', (['feature_sample'], {'ensure_ascii': '(False)'}), '(feature_sample, ensure_ascii=False)\n', (20790, 20826), False, 'import json\n'), ((25382, 25515), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'device_count': "{'CPU': 12}", 'inter_op_parallelism_threads': '(1)', 'intra_op_parallelism_threads': '(1)', 'gpu_options': 'gpu_options'}), "(device_count={'CPU': 12}, inter_op_parallelism_threads=1,\n intra_op_parallelism_threads=1, gpu_options=gpu_options)\n", (25396, 25515), True, 'import tensorflow as tf\n')]
from nltk.corpus import stopwords from nltk.tokenize import word_tokenize text = "This is an example sentence for showing stop words filteration." stop_words = set(stopwords.words("english")) # all the stop words of englist language defined in nltk # print(stop_words) words = word_tokenize(text) filtered_sentence = [] # long process:- #for w in words: # if w not in stop_words: # filtered_sentence.append(w) # # short process:- filtered_sentence = [w for w in words if not w in stop_words] print(filtered_sentence)
[ "nltk.corpus.stopwords.words", "nltk.tokenize.word_tokenize" ]
[((281, 300), 'nltk.tokenize.word_tokenize', 'word_tokenize', (['text'], {}), '(text)\n', (294, 300), False, 'from nltk.tokenize import word_tokenize\n'), ((166, 192), 'nltk.corpus.stopwords.words', 'stopwords.words', (['"""english"""'], {}), "('english')\n", (181, 192), False, 'from nltk.corpus import stopwords\n')]
import sys import subprocess ex = sys.executable print(subprocess.run([ex, sys.argv[1], *sys.argv[2:]], capture_output=True).stdout.decode("UTF-8"))
[ "subprocess.run" ]
[((57, 126), 'subprocess.run', 'subprocess.run', (['[ex, sys.argv[1], *sys.argv[2:]]'], {'capture_output': '(True)'}), '([ex, sys.argv[1], *sys.argv[2:]], capture_output=True)\n', (71, 126), False, 'import subprocess\n')]
# -*- coding: utf-8 -*- """ # 3D Image Data Synthesis. # Copyright (C) 2021 <NAME>, <NAME>, <NAME>, <NAME>, <NAME> # # 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 Liceense 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. # # Please refer to the documentation for more information about the software # as well as for installation instructions. # """ import os import pyshtools import itertools import numpy as np from skimage import io, filters, morphology, measure from scipy.stats import multivariate_normal from scipy.ndimage import convolve, distance_transform_edt, gaussian_filter from pyquaternion import Quaternion from utils.utils import print_timestamp from utils.harmonics import harmonics2sampling, sampling2instance from utils.h5_converter import h5_writer def generate_data(synthesizer, save_path, experiment_name='dummy_nuclei', num_imgs=50, img_shape=(140,140,1000), max_radius=40, min_radius=20, std_radius=10, psf=None,\ sh_order=20, num_cells=200, num_cells_std=50, circularity=5, smooth_std=0.5, noise_std=0.1, noise_mean=-0.1, position_std=3,\ cell_elongation=1.5, irregularity_extend=50, generate_images=False, theta_phi_sampling_file=r'utils/theta_phi_sampling_5000points_10000iter.npy'): # Set up the synthesizer synthesizer = synthesizer(img_shape=img_shape, max_radius=max_radius, min_radius=min_radius,\ smooth_std=smooth_std, noise_std=noise_std, noise_mean=noise_mean,\ sh_order=sh_order, circularity=circularity, num_cells=num_cells, psf=psf,\ position_std=position_std, theta_phi_sampling=theta_phi_sampling,\ cell_elongation=cell_elongation, irregularity_extend=irregularity_extend, generate_images=generate_images) # Set up the save directories if generate_images: os.makedirs(os.path.join(save_path, 'images'), exist_ok=True) os.makedirs(os.path.join(save_path, 'masks'), exist_ok=True) for num_data in range(num_imgs): current_radius = np.random.randint(min_radius, max_radius) synthesizer.max_radius = current_radius + std_radius synthesizer.min_radius = current_radius - std_radius cell_count = np.random.randint(num_cells-num_cells_std, num_cells+num_cells_std) synthesizer.num_cells = cell_count print_timestamp('_'*20) print_timestamp('Generating image {0}/{1} with {2} cells of size {3}-{4}', [num_data+1, num_imgs, cell_count, current_radius-std_radius, current_radius+std_radius]) # Get the image and the corresponding mask processed_img, instance_mask = synthesizer.generate_data() ## Save the image for num_img,img in enumerate(processed_img): if not img is None: save_name_img = 'psf{0}_img_'.format(num_img)+experiment_name+'_{0}'.format(num_data) # TIF io.imsave(os.path.join(save_path, 'images', save_name_img+'.tif'), 255*img.astype(np.uint8)) # H5 img = img.astype(np.float32) perc01, perc99 = np.percentile(img, [1,99]) if not perc99-perc01 <= 0: img -= perc01 img /= (perc99-perc01) else: img /= img.max() img = np.clip(img, 0, 1) h5_writer([img], save_name_img+'.h5', group_root='data', group_names=['image']) ## Save the mask save_name_mask = 'mask_'+experiment_name+'_{0}'.format(num_data) # TIF io.imsave(os.path.join(save_path, 'masks', save_name_mask+'.tif'), instance_mask.astype(np.uint16)) # H5 h5_writer([instance_mask, synthesizer.dist_map], os.path.join(save_path, 'masks', save_name_mask+'.h5'), group_root='data', group_names=['nuclei', 'distance']) def generate_data_from_masks(synthesizer_class, save_path, filelist, min_radius=8, max_radius=9, std_radius=1, psf=None,\ sh_order=20, circularity=5, smooth_std=0.5, noise_std=0.1, noise_mean=-0.1, position_std=3, bg_label=0,\ cell_elongation=1.5, irregularity_extend=50, generate_images=False, theta_phi_sampling_file=r'utils/theta_phi_sampling_5000points_10000iter.npy'): # Set up the synthesizer synthesizer = synthesizer_class(img_shape=(100,100,100), max_radius=max_radius, min_radius=min_radius,\ smooth_std=smooth_std, noise_std=noise_std, noise_mean=noise_mean,\ sh_order=sh_order, circularity=circularity, num_cells=0, psf=psf,\ position_std=position_std, theta_phi_sampling_file=theta_phi_sampling_file,\ cell_elongation=cell_elongation, irregularity_extend=irregularity_extend, generate_images=generate_images) # Set up the save directories if generate_images: os.makedirs(os.path.join(save_path, 'images_h5'), exist_ok=True) os.makedirs(os.path.join(save_path, 'segmentation'), exist_ok=True) os.makedirs(os.path.join(save_path, 'segmentation_h5'), exist_ok=True) for num_file, file in enumerate(filelist): print_timestamp('_'*20) print_timestamp('Extracting statistics from image {0}/{1}', [num_file+1, len(filelist)]) template = io.imread(file) synthesizer.img_shape = template.shape positions = [] for props in measure.regionprops(template): positions.append([int(p) for p in props.centroid]) synthesizer.num_cells = len(positions) current_radius = np.random.randint(min_radius, max_radius) synthesizer.max_radius = current_radius + std_radius synthesizer.min_radius = current_radius - std_radius print_timestamp('Generating image with {0} cells of size {1}-{2}', [len(positions), current_radius-std_radius, current_radius+std_radius]) # Get the image and the corresponding mask processed_img, instance_mask = synthesizer.generate_data(foreground=template!=bg_label, positions=positions) ## Save the image for num_img,img in enumerate(processed_img): if not img is None: save_name_img = 'psf{0}_img_'.format(num_img)+os.path.split(file)[-1][:-4] # TIF io.imsave(os.path.join(save_path, 'images_h5', save_name_img+'.tif'), 255*img.astype(np.uint8)) # H5 img = img.astype(np.float32) perc01, perc99 = np.percentile(img, [1,99]) if not perc99-perc01 <= 0: img -= perc01 img /= (perc99-perc01) else: img /= img.max() img = np.clip(img, 0, 1) h5_writer([img], save_name_img+'.h5', group_root='data', group_names=['image']) ## Save the mask save_name_mask = 'SimMask_'+os.path.split(file)[-1][:-4] # TIF io.imsave(os.path.join(save_path, 'segmentation', save_name_mask+'.tif'), instance_mask.astype(np.uint16)) # H5 h5_writer([instance_mask, synthesizer.dist_map], os.path.join(save_path, 'segmentation_h5', save_name_mask+'.h5'), group_root='data', group_names=['nuclei', 'distance']) class SyntheticNuclei: def __init__(self, img_shape=(200,400,400), max_radius=50, min_radius=20, psf=None, sh_order=20, smooth_std=1,\ noise_std=0.1, noise_mean=0, num_cells=10, circularity=5, generate_images=False,\ theta_phi_sampling_file=r'utils/theta_phi_sampling_5000points_10000iter.npy', **kwargs): self.img_shape = img_shape self.max_radius = max_radius self.min_radius = min_radius self.sh_order = sh_order self.num_coefficients = (sh_order+1)**2 self.smooth_std = smooth_std self.noise_std = noise_std self.noise_mean = noise_mean self.circularity = circularity self.num_cells = num_cells self.generate_images = generate_images self.theta_phi_sampling_file = theta_phi_sampling_file if not isinstance(psf, (tuple, list)): psf = [psf] self.psf = [] for p in psf: if isinstance(p, str): if psf.endswith(('.tif', '.TIF', 'png')): self.psf.append(io.imread(psf)) elif psf.endswith(('.npz', '.npy')): self.psf.append(np.load(p)) else: raise TypeError('Unknown PSF file format.') else: self.psf.append(p) self.fg_map = None self.instance_mask = None self.processed_img = [None] self._preparations() def _preparations(self): # Setting up the converter print_timestamp('Loading sampling angles...') self.theta_phi_sampling = np.load(self.theta_phi_sampling_file) print_timestamp('Setting up harmonic converter...') self.h2s = harmonics2sampling(self.sh_order, self.theta_phi_sampling) def generate_data(self, foreground=None, positions=None): if foreground is None: print_timestamp('Generating foreground...') self._generate_foreground() else: self.fg_map = foreground>0 self._generate_distmap() if positions is None: print_timestamp('Determining cell positions...') self.positions = self._generate_positions() else: self.positions = positions print_timestamp('Starting cell generation...') self._generate_instances() if self.generate_images: print_timestamp('Starting synthesis process...') self._generate_image() print_timestamp('Finished...') return self.processed_img, self.instance_mask def _generate_foreground(self): self.fg_map = np.zeros(self.img_shape, dtype=np.bool) def _generate_distmap(self): # generate foreground distance map fg_map = self.fg_map[::4,::4,::4] dist_map = distance_transform_edt(fg_map>=1) dist_map = dist_map - distance_transform_edt(fg_map<1) dist_map = dist_map.astype(np.float32) # rescale to original size dist_map = np.repeat(dist_map, 4, axis=0) dist_map = np.repeat(dist_map, 4, axis=1) dist_map = np.repeat(dist_map, 4, axis=2) dim_missmatch = np.array(self.fg_map.shape)-np.array(dist_map.shape) if dim_missmatch[0]<0: dist_map = dist_map[:dim_missmatch[0],...] if dim_missmatch[1]<0: dist_map = dist_map[:,:dim_missmatch[1],:] if dim_missmatch[2]<0: dist_map = dist_map[...,:dim_missmatch[2]] dist_map = dist_map.astype(np.float32) self.dist_map = dist_map def _generate_positions(self): positions = np.zeros((self.num_cells, 3), dtype=np.uint16) # Get map of possible cell locations location_map = self.fg_map.copy() cell_size_est = (self.min_radius + self.max_radius) // 2 slicing = tuple(map(slice, [cell_size_est,]*len(self.img_shape), [s-cell_size_est for s in self.img_shape])) location_map[slicing] = True for cell_count in range(self.num_cells): # Get random centroid location = np.array(np.nonzero(location_map)) location = location[:,np.random.randint(0, location.shape[1])] positions[cell_count,:] = location # Exclude region of current cell from possible future locations slicing = tuple(map(slice, list(np.maximum(location-cell_size_est, 0)), list(location+cell_size_est))) location_map[slicing] = False return positions def _generate_instances(self): assert self.circularity>=0, 'Circularity needs to be positive.' # Get the power per harmonic order power_per_order = np.arange(self.sh_order+1, dtype=np.float32) power_per_order[0] = np.inf power_per_order = power_per_order**-self.circularity coeff_list = np.zeros((len(self.positions), self.num_coefficients), dtype=np.float32) for cell_count in range(len(self.positions)): # Get harmonic coefficients clm = pyshtools.SHCoeffs.from_random(power_per_order) coeffs = clm.coeffs coeffs[0,0,0] = 1 # Get radius radius = np.random.randint(self.min_radius, self.max_radius) # Scale coefficients respectively coeffs *= radius coeffs = np.concatenate((np.fliplr(coeffs[0,...]), coeffs[1,...]), axis=1) coeffs = coeffs[np.nonzero(coeffs)] assert len(coeffs) == self.num_coefficients, 'Number of coefficients did not match the expected value.' coeff_list[cell_count,:] = coeffs # Reconstruct the sampling from the coefficients r_sampling = self.h2s.convert(coeff_list) # Reconstruct the intance mask instance_mask = sampling2instance(self.positions, r_sampling, self.theta_phi_sampling, self.img_shape, verbose=True) self.instance_mask = instance_mask def _generate_image(self): assert not self.instance_mask is None, 'There needs to be an instance mask.' # Generate image img_raw = np.zeros_like(self.instance_mask, dtype=np.float32) for label in np.unique(self.instance_mask): if label == 0: continue # exclude background img_raw[self.instance_mask == label] = np.random.uniform(0.5, 0.9) self.processed_img = [] for num_psf,psf in enumerate(self.psf): print_timestamp('Applying PSF {0}/{1}...', [num_psf+1, len(self.psf)]) img = img_raw.copy() # Perform PSF smoothing if not psf is None: img = convolve(img, psf) # Add final additive noise noise = np.random.normal(self.noise_mean, self.noise_std, size=self.img_shape) img = img+noise img = img.clip(0, 1) # Final smoothing touch img = filters.gaussian(img, self.smooth_std) self.processed_img.append(img.astype(np.float32)) class SyntheticCElegansWorm(SyntheticNuclei): def __init__(self, img_shape=(140,140,1000), max_radius=20, min_radius=10, num_cells=400,\ psf=None, sh_order=20, smooth_std=0.5, noise_std=0.1, noise_mean=-0.1, circularity=5,\ theta_phi_sampling_file=r'utils/theta_phi_sampling_5000points_10000iter.npy', **kwargs): super().__init__(img_shape=img_shape, max_radius=max_radius, min_radius=min_radius, num_cells=num_cells,\ psf=psf, sh_order=sh_order, smooth_std=smooth_std, noise_mean=noise_mean,\ noise_std=noise_std, circularity=circularity, theta_phi_sampling_file=theta_phi_sampling_file) def _generate_foreground(self): # within ellipsoid equation: (x/a)^2 + (y/b)^2 + /z/c)^2 < 1 a,b,c = [int(i*0.45) for i in self.img_shape] x,y,z = np.indices(self.img_shape) ellipsoid = ((x-self.img_shape[0]//2)/a)**2 + ((y-self.img_shape[1]//2)/b)**2 + ((z-self.img_shape[2]//2)/c)**2 self.fg_map = ellipsoid<=1 def _generate_positions(self): positions = np.zeros((self.num_cells, 3), dtype=np.uint16) # Get map of possible cell locations location_map = self.fg_map.copy() for cell_count in range(self.num_cells): print_timestamp('Placing cell {0}/{1}...', [cell_count+1, self.num_cells]) # Get random centroid location = np.array(np.nonzero(location_map)) if location.shape[1] == 0: print_timestamp('The maximum number of cells ({0}) was reached...', [cell_count+1]) positions = positions[:cell_count-1,:] break location = location[:,np.random.randint(0, location.shape[1])] positions[cell_count,:] = location # Exclude region of current cell from possible future locations slicing = tuple(map(slice, list(np.maximum(location-self.min_radius, 0)), list(location+self.min_radius))) location_map[slicing] = False return positions class SyntheticTRIF(SyntheticNuclei): def __init__(self, img_shape=(900,1800,900), min_radius=13, max_radius=18, cell_elongation=2, num_cells=3500, psf=None,\ smooth_std=0.5, noise_std=0.1, noise_mean=-0.1, position_std=3, irregularity_extend=200, **kwargs): super().__init__(img_shape=img_shape, max_radius=max_radius, min_radius=min_radius, num_cells=num_cells,\ psf=psf, smooth_std=smooth_std, noise_mean=noise_mean,\ noise_std=noise_std) self.position_std = position_std self.cell_elongation = cell_elongation self.irregularity_extend = irregularity_extend def _preparations(self): pass def _generate_foreground(self): # determine ellipsoid parameters (adjusted to the image size) a,b,c = [int(i*0.4) for i in self.img_shape] x,y,z = np.indices(self.img_shape, dtype=np.float16) # distort the coordinates with random gaussian distributions to simulate random shape irregularities # coords = coords +/- extend * exp(-x_norm**2/sigma_x - y_norm**2/sigma_y**2 - z_norm**2/sigma_z**2) extend_x = (-1)**np.random.randint(0,2) * np.random.randint(self.irregularity_extend/2,np.maximum(self.irregularity_extend,1)) extend_y = (-1)**np.random.randint(0,2) * np.random.randint(self.irregularity_extend/2,np.maximum(self.irregularity_extend,1)) extend_z = (-1)**np.random.randint(0,2) * np.random.randint(self.irregularity_extend/2,np.maximum(self.irregularity_extend,1)) distortion_x = np.exp(- np.divide(x-np.random.randint(0,2*a),np.random.randint(a/2,a),dtype=np.float16)**2 - np.divide(y-np.random.randint(0,2*b),np.random.randint(b/2,b),dtype=np.float16)**2 - np.divide(z-np.random.randint(0,2*c),np.random.randint(c/2,c),dtype=np.float16)**2, dtype=np.float16) distortion_y = np.exp(- np.divide(x-np.random.randint(0,2*a),np.random.randint(a/2,a),dtype=np.float16)**2 - np.divide(y-np.random.randint(0,2*b),np.random.randint(b/2,b),dtype=np.float16)**2 - np.divide(z-np.random.randint(0,2*c),np.random.randint(c/2,c),dtype=np.float16)**2, dtype=np.float16) distortion_z = np.exp(- np.divide(x-np.random.randint(0,2*a),np.random.randint(a/2,a),dtype=np.float16)**2 - np.divide(y-np.random.randint(0,2*b),np.random.randint(b/2,b),dtype=np.float16)**2 - np.divide(z-np.random.randint(0,2*c),np.random.randint(c/2,c),dtype=np.float16)**2, dtype=np.float16) x = x + extend_x * distortion_x y = y + extend_y * distortion_y z = z + extend_z * distortion_z # within ellipsoid equation: (x/a)^2 + (y/b)^2 + /z/c)^2 < 1 ellipsoid = ((x-self.img_shape[0]//2)/a)**2 + ((y-self.img_shape[1]//2)/b)**2 + ((z-self.img_shape[2]//2)/c)**2 self.fg_map = ellipsoid<=1 self._generate_distmap() def _generate_positions(self): positions = np.zeros((self.num_cells, 3), dtype=np.uint16) # Get map of possible cell locations (outer ring) location_map = np.logical_xor(self.fg_map, morphology.binary_erosion(self.fg_map, selem=morphology.ball(self.position_std*2))) locations = np.array(np.nonzero(location_map)) # Get cell parameters (*2 since we are looking for centroids) cell_shape = 2*np.array([self.max_radius, self.max_radius/self.cell_elongation, self.max_radius/self.cell_elongation]) for cell_count in range(self.num_cells): print_timestamp('Placing cell {0}/{1}...', [cell_count+1, self.num_cells]) # Get random centroid if locations.shape[1] == 0: print_timestamp('The maximum number of cells ({0}) was reached...', [cell_count+1]) positions = positions[:cell_count-1,:] break location = locations[:,np.random.randint(0, locations.shape[1])] positions[cell_count,:] = location # Exclude region of current cell from possible future locations distances = locations - location[:,np.newaxis] distances = distances / cell_shape[:,np.newaxis] distances = np.sum(distances**2, axis=0) locations = locations[:,distances>1] return positions def _generate_instances(self): # calculate the gradient direction at each position (used to orient each cell) grad_map_x, grad_map_y, grad_map_z = np.gradient(self.dist_map, 5) grad_map_x = gaussian_filter(grad_map_x, 5) grad_map_y = gaussian_filter(grad_map_y, 5) grad_map_z = gaussian_filter(grad_map_z, 5) # normalize the gradient vectors to unit length grad_norm = np.sqrt(grad_map_x**2 + grad_map_y**2 + grad_map_z**2) grad_map_x = grad_map_x/grad_norm grad_map_y = grad_map_y/grad_norm grad_map_z = grad_map_z/grad_norm # create local coordinates cell_mask_shape = (self.max_radius*3,)*3 coords_default = np.indices(cell_mask_shape) coords_default = np.reshape(coords_default, (3,-1)) coords_default = np.subtract(coords_default, coords_default.max(axis=1, keepdims=True)//2) coords_default = coords_default.astype(np.float16) # place a cell at each position instance_mask = np.zeros(self.dist_map.shape, dtype=np.uint16) for num_cell, pos in enumerate(self.positions): print_timestamp('Generating cell {0}/{1}...', [num_cell+1, len(self.positions)]) cell_size = np.random.randint(self.min_radius,self.max_radius) a,b,c = [cell_size,cell_size/self.cell_elongation,cell_size/self.cell_elongation] coords = coords_default.copy() # rotation axis is perpendicular to gradient direction and the major axis of the cell grad_vec = [grad_map_x[tuple(pos)], grad_map_y[tuple(pos)], grad_map_z[tuple(pos)]] cell_vec = [0,]*3 cell_vec[np.argmax([a,b,c])] = 1 rot_axis = np.cross(grad_vec, cell_vec) axis_norm = np.sqrt(np.sum(rot_axis**2)) if not axis_norm==0: # normalize the rotation axis rot_axis = rot_axis / axis_norm # calculate the angle from: a*b = ||a||*||b||*cos(angle) rot_angle = np.arccos(np.dot(grad_vec, cell_vec)/1) # rotate using the quaternion cell_quant = Quaternion(axis=rot_axis, angle=rot_angle) coords = np.matmul(cell_quant.rotation_matrix, coords) coords = coords.reshape((3,)+cell_mask_shape) x_new = coords[0,...] y_new = coords[1,...] z_new = coords[2,...] ellipsoid = ((x_new/a)**2 + (y_new/b)**2 + (z_new/c)**2) <= 1 slice_start = [np.minimum(np.maximum(0,p-c//2),i-c) for p,c,i in zip(pos,cell_mask_shape,self.img_shape)] slice_end = [s+c for s,c in zip(slice_start,cell_mask_shape)] slicing = tuple(map(slice, slice_start, slice_end)) instance_mask[slicing] = np.maximum(instance_mask[slicing], (num_cell+1)*ellipsoid.astype(np.uint16)) self.instance_mask = instance_mask.astype(np.uint16) class SyntheticDRO(SyntheticNuclei): def __init__(self, img_shape=(300,600,1200), min_radius=13, max_radius=18, cell_elongation=3, num_cells=1000, psf=None,\ smooth_std=0.5, noise_std=0.1, noise_mean=-0.1, position_std=3, irregularity_extend=200, **kwargs): super().__init__(img_shape=img_shape, max_radius=max_radius, min_radius=min_radius, num_cells=num_cells,\ psf=psf, smooth_std=smooth_std, noise_mean=noise_mean,\ noise_std=noise_std) self.position_std = position_std self.cell_elongation = cell_elongation self.irregularity_extend = irregularity_extend def _preparations(self): pass def _generate_foreground(self): # Determine positions coords = np.indices(self.img_shape, dtype=np.float16) coords[0,...] -= self.img_shape[0]//2 coords[1,...] -= self.img_shape[1]//2 coords[2,...] -= self.img_shape[2]//2 # Rotate workspace around x- and y-axis between 0 and 10 degree coords = coords.reshape((3,-1)) alpha_x = -np.radians(np.random.randint(5,10)) alpha_y = -np.radians(np.random.randint(5,10)) Rx = np.array([[1,0,0],[0,np.cos(alpha_x),-np.sin(alpha_x)],[0,np.sin(alpha_x),np.cos(alpha_x)]]) Ry = np.array([[np.cos(alpha_y),0,np.sin(alpha_y)],[0,1,0],[-np.sin(alpha_y),0,np.cos(alpha_y)]]) coords = np.matmul(Rx,coords) coords = np.matmul(Ry,coords) coords = coords.reshape((3,)+self.img_shape) # determine ellipsoid parameters (adjusted to the image size) a,b,c = [int(i*0.4) for i in self.img_shape] # distort the coordinates with large random gaussian distributions to simulate shape irregularities # coords = coords +/- extend * exp(-x_norm**2/sigma_x - y_norm**2/sigma_y**2 - z_norm**2/sigma_z**2) extend_x = (-1)**np.random.randint(0,2) * np.random.randint(self.irregularity_extend/2,np.maximum(self.irregularity_extend,1)) extend_y = (-1)**np.random.randint(0,2) * np.random.randint(self.irregularity_extend/2,np.maximum(self.irregularity_extend,1)) extend_z = (-1)**np.random.randint(0,2) * np.random.randint(self.irregularity_extend/2,np.maximum(self.irregularity_extend,1)) distortion_x = np.exp(- np.divide(coords[0,...]-np.random.randint(0,2*a),np.random.randint(a/2,a),dtype=np.float16)**2\ - np.divide(coords[1,...]-np.random.randint(0,2*b),np.random.randint(b/2,b),dtype=np.float16)**2\ - np.divide(coords[2,...]-np.random.randint(0,2*c),np.random.randint(c/2,c),dtype=np.float16)**2, dtype=np.float16) distortion_y = np.exp(- np.divide(coords[0,...]-np.random.randint(0,2*a),np.random.randint(a/2,a),dtype=np.float16)**2\ - np.divide(coords[1,...]-np.random.randint(0,2*b),np.random.randint(b/2,b),dtype=np.float16)**2\ - np.divide(coords[2,...]-np.random.randint(0,2*c),np.random.randint(c/2,c),dtype=np.float16)**2, dtype=np.float16) distortion_z = np.exp(- np.divide(coords[0,...]-np.random.randint(0,2*a),np.random.randint(a/2,a),dtype=np.float16)**2\ - np.divide(coords[1,...]-np.random.randint(0,2*b),np.random.randint(b/2,b),dtype=np.float16)**2\ - np.divide(coords[2,...]-np.random.randint(0,2*c),np.random.randint(c/2,c),dtype=np.float16)**2, dtype=np.float16) coords[0,...] = coords[0,...] + extend_x * distortion_x coords[1,...] = coords[1,...] + extend_y * distortion_y coords[2,...] = coords[2,...] + extend_z * distortion_z # distort the coordinates with small gaussian distributions to simulate identations for i in range(np.random.randint(0,5)): extend_x = np.random.randint(a,a*2) extend_y = np.random.randint(b,b*2) extend_z = np.random.randint(c,c*2) distortion_x = np.exp(- np.divide(coords[0,...]-np.random.randint(a/2,a),np.random.randint(a/2,a),dtype=np.float16)**2\ - np.divide(coords[1,...]-np.random.randint(b/2,b),np.random.randint(b/2,b),dtype=np.float16)**2\ - np.divide(coords[2,...]-np.random.randint(c/2,c),np.random.randint(c/20,c/10),dtype=np.float16)**2, dtype=np.float16) distortion_y = np.exp(- np.divide(coords[0,...]-np.random.randint(a/2,a),np.random.randint(a/2,a),dtype=np.float16)**2\ - np.divide(coords[1,...]-np.random.randint(b/2,b),np.random.randint(b/2,b),dtype=np.float16)**2\ - np.divide(coords[2,...]-np.random.randint(c/2,c),np.random.randint(c/20,c/10),dtype=np.float16)**2, dtype=np.float16) distortion_z = np.exp(- np.divide(coords[0,...]-np.random.randint(a/2,a),np.random.randint(a/2,a),dtype=np.float16)**2\ - np.divide(coords[1,...]-np.random.randint(b/2,b),np.random.randint(b/2,b),dtype=np.float16)**2\ - np.divide(coords[2,...]-np.random.randint(c/2,c),np.random.randint(c/20,c/10),dtype=np.float16)**2, dtype=np.float16) coords[0,...] = coords[0,...] + np.sign(coords[0,...]) * extend_x * distortion_x coords[1,...] = coords[1,...] + np.sign(coords[1,...]) * extend_y * distortion_y coords[2,...] = coords[2,...] + np.sign(coords[2,...]) * extend_z * distortion_z # within ellipsoid equation: (x/a)^2 + (y/b)^2 + /z/c)^2 < 1 ellipsoid = (coords[0,...]/a)**2 + (coords[1,...]/b)**2 + (coords[2,...]/c)**2 self.fg_map = ellipsoid<=1 self._generate_distmap() def _generate_positions(self): positions = np.zeros((self.num_cells, 3), dtype=np.uint16) # Get map of possible cell locations (outer ring) location_map = np.logical_xor(self.fg_map, morphology.binary_erosion(self.fg_map, selem=morphology.ball(self.position_std*2))) locations = np.array(np.nonzero(location_map)) # Get cell parameters (*2 since we are looking for centroids) cell_shape = 2*np.array([self.max_radius, self.max_radius/self.cell_elongation, self.max_radius/self.cell_elongation]) for cell_count in range(self.num_cells): print_timestamp('Placing cell {0}/{1}...', [cell_count+1, self.num_cells]) # Get random centroid if locations.shape[1] == 0: print_timestamp('The maximum number of cells ({0}) was reached...', [cell_count+1]) positions = positions[:cell_count-1,:] break location = locations[:,np.random.randint(0, locations.shape[1])] positions[cell_count,:] = location # Exclude region of current cell from possible future locations distances = locations - location[:,np.newaxis] distances = distances / cell_shape[:,np.newaxis] distances = np.sum(distances**2, axis=0) locations = locations[:,distances>1] return positions def _generate_instances(self): # calculate the gradient direction at each position (used to orient each cell) grad_map_x, grad_map_y, grad_map_z = np.gradient(self.dist_map, 5) grad_map_x = gaussian_filter(grad_map_x, 5) grad_map_y = gaussian_filter(grad_map_y, 5) grad_map_z = gaussian_filter(grad_map_z, 5) # normalize the gradient vectors to unit length grad_norm = np.sqrt(grad_map_x**2 + grad_map_y**2 + grad_map_z**2) grad_map_x = grad_map_x/grad_norm grad_map_y = grad_map_y/grad_norm grad_map_z = grad_map_z/grad_norm # create local coordinates cell_mask_shape = (self.max_radius*3,)*3 coords_default = np.indices(cell_mask_shape) coords_default = np.reshape(coords_default, (3,-1)) coords_default = np.subtract(coords_default, coords_default.max(axis=1, keepdims=True)//2) coords_default = coords_default.astype(np.float16) # place a cell at each position instance_mask = np.zeros(self.dist_map.shape, dtype=np.uint16) for num_cell, pos in enumerate(self.positions): print_timestamp('Generating cell {0}/{1}...', [num_cell+1, len(self.positions)]) cell_size = np.random.randint(self.min_radius,self.max_radius) a,b,c = [cell_size,cell_size/self.cell_elongation,cell_size/self.cell_elongation] coords = coords_default.copy() # rotation axis is perpendicular to gradient direction and the major axis of the cell grad_vec = [grad_map_x[tuple(pos)], grad_map_y[tuple(pos)], grad_map_z[tuple(pos)]] cell_vec = [0,]*3 cell_vec[np.argmax([a,b,c])] = 1 rot_axis = np.cross(grad_vec, cell_vec) axis_norm = np.sqrt(np.sum(rot_axis**2)) if not axis_norm==0: # normalize the rotation axis rot_axis = rot_axis / axis_norm # calculate the angle from: a*b = ||a||*||b||*cos(angle) rot_angle = np.arccos(np.dot(grad_vec, cell_vec)/1) # rotate using the quaternion cell_quant = Quaternion(axis=rot_axis, angle=rot_angle) coords = np.matmul(cell_quant.rotation_matrix, coords) coords = coords.reshape((3,)+cell_mask_shape) x_new = coords[0,...] y_new = coords[1,...] z_new = coords[2,...] ellipsoid = ((x_new/a)**2 + (y_new/b)**2 + (z_new/c)**2) <= 1 slice_start = [np.minimum(np.maximum(0,p-c//2),i-c) for p,c,i in zip(pos,cell_mask_shape,self.img_shape)] slice_end = [s+c for s,c in zip(slice_start,cell_mask_shape)] slicing = tuple(map(slice, slice_start, slice_end)) instance_mask[slicing] = np.maximum(instance_mask[slicing], (num_cell+1)*ellipsoid.astype(np.uint16)) self.instance_mask = instance_mask.astype(np.uint16)
[ "numpy.clip", "numpy.sqrt", "numpy.array", "scipy.ndimage.gaussian_filter", "numpy.sin", "numpy.gradient", "numpy.arange", "numpy.repeat", "numpy.reshape", "numpy.cross", "os.path.split", "numpy.dot", "numpy.matmul", "skimage.morphology.ball", "numpy.maximum", "pyshtools.SHCoeffs.from_...
[((2455, 2487), 'os.path.join', 'os.path.join', (['save_path', '"""masks"""'], {}), "(save_path, 'masks')\n", (2467, 2487), False, 'import os\n'), ((2580, 2621), 'numpy.random.randint', 'np.random.randint', (['min_radius', 'max_radius'], {}), '(min_radius, max_radius)\n', (2597, 2621), True, 'import numpy as np\n'), ((2774, 2845), 'numpy.random.randint', 'np.random.randint', (['(num_cells - num_cells_std)', '(num_cells + num_cells_std)'], {}), '(num_cells - num_cells_std, num_cells + num_cells_std)\n', (2791, 2845), True, 'import numpy as np\n'), ((2902, 2927), 'utils.utils.print_timestamp', 'print_timestamp', (["('_' * 20)"], {}), "('_' * 20)\n", (2917, 2927), False, 'from utils.utils import print_timestamp\n'), ((2934, 3113), 'utils.utils.print_timestamp', 'print_timestamp', (['"""Generating image {0}/{1} with {2} cells of size {3}-{4}"""', '[num_data + 1, num_imgs, cell_count, current_radius - std_radius, \n current_radius + std_radius]'], {}), "('Generating image {0}/{1} with {2} cells of size {3}-{4}',\n [num_data + 1, num_imgs, cell_count, current_radius - std_radius, \n current_radius + std_radius])\n", (2949, 3113), False, 'from utils.utils import print_timestamp\n'), ((5771, 5810), 'os.path.join', 'os.path.join', (['save_path', '"""segmentation"""'], {}), "(save_path, 'segmentation')\n", (5783, 5810), False, 'import os\n'), ((5843, 5885), 'os.path.join', 'os.path.join', (['save_path', '"""segmentation_h5"""'], {}), "(save_path, 'segmentation_h5')\n", (5855, 5885), False, 'import os\n'), ((5971, 5996), 'utils.utils.print_timestamp', 'print_timestamp', (["('_' * 20)"], {}), "('_' * 20)\n", (5986, 5996), False, 'from utils.utils import print_timestamp\n'), ((6129, 6144), 'skimage.io.imread', 'io.imread', (['file'], {}), '(file)\n', (6138, 6144), False, 'from skimage import io, filters, morphology, measure\n'), ((6236, 6265), 'skimage.measure.regionprops', 'measure.regionprops', (['template'], {}), '(template)\n', (6255, 6265), False, 'from skimage import io, filters, morphology, measure\n'), ((6424, 6465), 'numpy.random.randint', 'np.random.randint', (['min_radius', 'max_radius'], {}), '(min_radius, max_radius)\n', (6441, 6465), True, 'import numpy as np\n'), ((9806, 9851), 'utils.utils.print_timestamp', 'print_timestamp', (['"""Loading sampling angles..."""'], {}), "('Loading sampling angles...')\n", (9821, 9851), False, 'from utils.utils import print_timestamp\n'), ((9886, 9923), 'numpy.load', 'np.load', (['self.theta_phi_sampling_file'], {}), '(self.theta_phi_sampling_file)\n', (9893, 9923), True, 'import numpy as np\n'), ((9932, 9983), 'utils.utils.print_timestamp', 'print_timestamp', (['"""Setting up harmonic converter..."""'], {}), "('Setting up harmonic converter...')\n", (9947, 9983), False, 'from utils.utils import print_timestamp\n'), ((10003, 10061), 'utils.harmonics.harmonics2sampling', 'harmonics2sampling', (['self.sh_order', 'self.theta_phi_sampling'], {}), '(self.sh_order, self.theta_phi_sampling)\n', (10021, 10061), False, 'from utils.harmonics import harmonics2sampling, sampling2instance\n'), ((10607, 10653), 'utils.utils.print_timestamp', 'print_timestamp', (['"""Starting cell generation..."""'], {}), "('Starting cell generation...')\n", (10622, 10653), False, 'from utils.utils import print_timestamp\n'), ((10850, 10880), 'utils.utils.print_timestamp', 'print_timestamp', (['"""Finished..."""'], {}), "('Finished...')\n", (10865, 10880), False, 'from utils.utils import print_timestamp\n'), ((11021, 11060), 'numpy.zeros', 'np.zeros', (['self.img_shape'], {'dtype': 'np.bool'}), '(self.img_shape, dtype=np.bool)\n', (11029, 11060), True, 'import numpy as np\n'), ((11225, 11260), 'scipy.ndimage.distance_transform_edt', 'distance_transform_edt', (['(fg_map >= 1)'], {}), '(fg_map >= 1)\n', (11247, 11260), False, 'from scipy.ndimage import convolve, distance_transform_edt, gaussian_filter\n'), ((11440, 11470), 'numpy.repeat', 'np.repeat', (['dist_map', '(4)'], {'axis': '(0)'}), '(dist_map, 4, axis=0)\n', (11449, 11470), True, 'import numpy as np\n'), ((11490, 11520), 'numpy.repeat', 'np.repeat', (['dist_map', '(4)'], {'axis': '(1)'}), '(dist_map, 4, axis=1)\n', (11499, 11520), True, 'import numpy as np\n'), ((11540, 11570), 'numpy.repeat', 'np.repeat', (['dist_map', '(4)'], {'axis': '(2)'}), '(dist_map, 4, axis=2)\n', (11549, 11570), True, 'import numpy as np\n'), ((12025, 12071), 'numpy.zeros', 'np.zeros', (['(self.num_cells, 3)'], {'dtype': 'np.uint16'}), '((self.num_cells, 3), dtype=np.uint16)\n', (12033, 12071), True, 'import numpy as np\n'), ((13182, 13228), 'numpy.arange', 'np.arange', (['(self.sh_order + 1)'], {'dtype': 'np.float32'}), '(self.sh_order + 1, dtype=np.float32)\n', (13191, 13228), True, 'import numpy as np\n'), ((14409, 14514), 'utils.harmonics.sampling2instance', 'sampling2instance', (['self.positions', 'r_sampling', 'self.theta_phi_sampling', 'self.img_shape'], {'verbose': '(True)'}), '(self.positions, r_sampling, self.theta_phi_sampling, self\n .img_shape, verbose=True)\n', (14426, 14514), False, 'from utils.harmonics import harmonics2sampling, sampling2instance\n'), ((14770, 14821), 'numpy.zeros_like', 'np.zeros_like', (['self.instance_mask'], {'dtype': 'np.float32'}), '(self.instance_mask, dtype=np.float32)\n', (14783, 14821), True, 'import numpy as np\n'), ((14843, 14872), 'numpy.unique', 'np.unique', (['self.instance_mask'], {}), '(self.instance_mask)\n', (14852, 14872), True, 'import numpy as np\n'), ((16726, 16752), 'numpy.indices', 'np.indices', (['self.img_shape'], {}), '(self.img_shape)\n', (16736, 16752), True, 'import numpy as np\n'), ((17007, 17053), 'numpy.zeros', 'np.zeros', (['(self.num_cells, 3)'], {'dtype': 'np.uint16'}), '((self.num_cells, 3), dtype=np.uint16)\n', (17015, 17053), True, 'import numpy as np\n'), ((19010, 19054), 'numpy.indices', 'np.indices', (['self.img_shape'], {'dtype': 'np.float16'}), '(self.img_shape, dtype=np.float16)\n', (19020, 19054), True, 'import numpy as np\n'), ((21103, 21149), 'numpy.zeros', 'np.zeros', (['(self.num_cells, 3)'], {'dtype': 'np.uint16'}), '((self.num_cells, 3), dtype=np.uint16)\n', (21111, 21149), True, 'import numpy as np\n'), ((22736, 22765), 'numpy.gradient', 'np.gradient', (['self.dist_map', '(5)'], {}), '(self.dist_map, 5)\n', (22747, 22765), True, 'import numpy as np\n'), ((22787, 22817), 'scipy.ndimage.gaussian_filter', 'gaussian_filter', (['grad_map_x', '(5)'], {}), '(grad_map_x, 5)\n', (22802, 22817), False, 'from scipy.ndimage import convolve, distance_transform_edt, gaussian_filter\n'), ((22839, 22869), 'scipy.ndimage.gaussian_filter', 'gaussian_filter', (['grad_map_y', '(5)'], {}), '(grad_map_y, 5)\n', (22854, 22869), False, 'from scipy.ndimage import convolve, distance_transform_edt, gaussian_filter\n'), ((22891, 22921), 'scipy.ndimage.gaussian_filter', 'gaussian_filter', (['grad_map_z', '(5)'], {}), '(grad_map_z, 5)\n', (22906, 22921), False, 'from scipy.ndimage import convolve, distance_transform_edt, gaussian_filter\n'), ((23007, 23067), 'numpy.sqrt', 'np.sqrt', (['(grad_map_x ** 2 + grad_map_y ** 2 + grad_map_z ** 2)'], {}), '(grad_map_x ** 2 + grad_map_y ** 2 + grad_map_z ** 2)\n', (23014, 23067), True, 'import numpy as np\n'), ((23314, 23341), 'numpy.indices', 'np.indices', (['cell_mask_shape'], {}), '(cell_mask_shape)\n', (23324, 23341), True, 'import numpy as np\n'), ((23367, 23402), 'numpy.reshape', 'np.reshape', (['coords_default', '(3, -1)'], {}), '(coords_default, (3, -1))\n', (23377, 23402), True, 'import numpy as np\n'), ((23642, 23688), 'numpy.zeros', 'np.zeros', (['self.dist_map.shape'], {'dtype': 'np.uint16'}), '(self.dist_map.shape, dtype=np.uint16)\n', (23650, 23688), True, 'import numpy as np\n'), ((26594, 26638), 'numpy.indices', 'np.indices', (['self.img_shape'], {'dtype': 'np.float16'}), '(self.img_shape, dtype=np.float16)\n', (26604, 26638), True, 'import numpy as np\n'), ((27272, 27293), 'numpy.matmul', 'np.matmul', (['Rx', 'coords'], {}), '(Rx, coords)\n', (27281, 27293), True, 'import numpy as np\n'), ((27310, 27331), 'numpy.matmul', 'np.matmul', (['Ry', 'coords'], {}), '(Ry, coords)\n', (27319, 27331), True, 'import numpy as np\n'), ((31779, 31825), 'numpy.zeros', 'np.zeros', (['(self.num_cells, 3)'], {'dtype': 'np.uint16'}), '((self.num_cells, 3), dtype=np.uint16)\n', (31787, 31825), True, 'import numpy as np\n'), ((33412, 33441), 'numpy.gradient', 'np.gradient', (['self.dist_map', '(5)'], {}), '(self.dist_map, 5)\n', (33423, 33441), True, 'import numpy as np\n'), ((33463, 33493), 'scipy.ndimage.gaussian_filter', 'gaussian_filter', (['grad_map_x', '(5)'], {}), '(grad_map_x, 5)\n', (33478, 33493), False, 'from scipy.ndimage import convolve, distance_transform_edt, gaussian_filter\n'), ((33515, 33545), 'scipy.ndimage.gaussian_filter', 'gaussian_filter', (['grad_map_y', '(5)'], {}), '(grad_map_y, 5)\n', (33530, 33545), False, 'from scipy.ndimage import convolve, distance_transform_edt, gaussian_filter\n'), ((33567, 33597), 'scipy.ndimage.gaussian_filter', 'gaussian_filter', (['grad_map_z', '(5)'], {}), '(grad_map_z, 5)\n', (33582, 33597), False, 'from scipy.ndimage import convolve, distance_transform_edt, gaussian_filter\n'), ((33683, 33743), 'numpy.sqrt', 'np.sqrt', (['(grad_map_x ** 2 + grad_map_y ** 2 + grad_map_z ** 2)'], {}), '(grad_map_x ** 2 + grad_map_y ** 2 + grad_map_z ** 2)\n', (33690, 33743), True, 'import numpy as np\n'), ((33990, 34017), 'numpy.indices', 'np.indices', (['cell_mask_shape'], {}), '(cell_mask_shape)\n', (34000, 34017), True, 'import numpy as np\n'), ((34043, 34078), 'numpy.reshape', 'np.reshape', (['coords_default', '(3, -1)'], {}), '(coords_default, (3, -1))\n', (34053, 34078), True, 'import numpy as np\n'), ((34318, 34364), 'numpy.zeros', 'np.zeros', (['self.dist_map.shape'], {'dtype': 'np.uint16'}), '(self.dist_map.shape, dtype=np.uint16)\n', (34326, 34364), True, 'import numpy as np\n'), ((2389, 2422), 'os.path.join', 'os.path.join', (['save_path', '"""images"""'], {}), "(save_path, 'images')\n", (2401, 2422), False, 'import os\n'), ((4222, 4279), 'os.path.join', 'os.path.join', (['save_path', '"""masks"""', "(save_name_mask + '.tif')"], {}), "(save_path, 'masks', save_name_mask + '.tif')\n", (4234, 4279), False, 'import os\n'), ((4387, 4443), 'os.path.join', 'os.path.join', (['save_path', '"""masks"""', "(save_name_mask + '.h5')"], {}), "(save_path, 'masks', save_name_mask + '.h5')\n", (4399, 4443), False, 'import os\n'), ((5702, 5738), 'os.path.join', 'os.path.join', (['save_path', '"""images_h5"""'], {}), "(save_path, 'images_h5')\n", (5714, 5738), False, 'import os\n'), ((7899, 7963), 'os.path.join', 'os.path.join', (['save_path', '"""segmentation"""', "(save_name_mask + '.tif')"], {}), "(save_path, 'segmentation', save_name_mask + '.tif')\n", (7911, 7963), False, 'import os\n'), ((8071, 8137), 'os.path.join', 'os.path.join', (['save_path', '"""segmentation_h5"""', "(save_name_mask + '.h5')"], {}), "(save_path, 'segmentation_h5', save_name_mask + '.h5')\n", (8083, 8137), False, 'import os\n'), ((10194, 10237), 'utils.utils.print_timestamp', 'print_timestamp', (['"""Generating foreground..."""'], {}), "('Generating foreground...')\n", (10209, 10237), False, 'from utils.utils import print_timestamp\n'), ((10428, 10476), 'utils.utils.print_timestamp', 'print_timestamp', (['"""Determining cell positions..."""'], {}), "('Determining cell positions...')\n", (10443, 10476), False, 'from utils.utils import print_timestamp\n'), ((10743, 10791), 'utils.utils.print_timestamp', 'print_timestamp', (['"""Starting synthesis process..."""'], {}), "('Starting synthesis process...')\n", (10758, 10791), False, 'from utils.utils import print_timestamp\n'), ((11297, 11331), 'scipy.ndimage.distance_transform_edt', 'distance_transform_edt', (['(fg_map < 1)'], {}), '(fg_map < 1)\n', (11319, 11331), False, 'from scipy.ndimage import convolve, distance_transform_edt, gaussian_filter\n'), ((11595, 11622), 'numpy.array', 'np.array', (['self.fg_map.shape'], {}), '(self.fg_map.shape)\n', (11603, 11622), True, 'import numpy as np\n'), ((11623, 11647), 'numpy.array', 'np.array', (['dist_map.shape'], {}), '(dist_map.shape)\n', (11631, 11647), True, 'import numpy as np\n'), ((13573, 13620), 'pyshtools.SHCoeffs.from_random', 'pyshtools.SHCoeffs.from_random', (['power_per_order'], {}), '(power_per_order)\n', (13603, 13620), False, 'import pyshtools\n'), ((13742, 13793), 'numpy.random.randint', 'np.random.randint', (['self.min_radius', 'self.max_radius'], {}), '(self.min_radius, self.max_radius)\n', (13759, 13793), True, 'import numpy as np\n'), ((14982, 15009), 'numpy.random.uniform', 'np.random.uniform', (['(0.5)', '(0.9)'], {}), '(0.5, 0.9)\n', (14999, 15009), True, 'import numpy as np\n'), ((15664, 15702), 'skimage.filters.gaussian', 'filters.gaussian', (['img', 'self.smooth_std'], {}), '(img, self.smooth_std)\n', (15680, 15702), False, 'from skimage import io, filters, morphology, measure\n'), ((17233, 17309), 'utils.utils.print_timestamp', 'print_timestamp', (['"""Placing cell {0}/{1}..."""', '[cell_count + 1, self.num_cells]'], {}), "('Placing cell {0}/{1}...', [cell_count + 1, self.num_cells])\n", (17248, 17309), False, 'from utils.utils import print_timestamp\n'), ((21381, 21405), 'numpy.nonzero', 'np.nonzero', (['location_map'], {}), '(location_map)\n', (21391, 21405), True, 'import numpy as np\n'), ((21509, 21621), 'numpy.array', 'np.array', (['[self.max_radius, self.max_radius / self.cell_elongation, self.max_radius /\n self.cell_elongation]'], {}), '([self.max_radius, self.max_radius / self.cell_elongation, self.\n max_radius / self.cell_elongation])\n', (21517, 21621), True, 'import numpy as np\n'), ((21696, 21772), 'utils.utils.print_timestamp', 'print_timestamp', (['"""Placing cell {0}/{1}..."""', '[cell_count + 1, self.num_cells]'], {}), "('Placing cell {0}/{1}...', [cell_count + 1, self.num_cells])\n", (21711, 21772), False, 'from utils.utils import print_timestamp\n'), ((22417, 22447), 'numpy.sum', 'np.sum', (['(distances ** 2)'], {'axis': '(0)'}), '(distances ** 2, axis=0)\n', (22423, 22447), True, 'import numpy as np\n'), ((23888, 23939), 'numpy.random.randint', 'np.random.randint', (['self.min_radius', 'self.max_radius'], {}), '(self.min_radius, self.max_radius)\n', (23905, 23939), True, 'import numpy as np\n'), ((24383, 24411), 'numpy.cross', 'np.cross', (['grad_vec', 'cell_vec'], {}), '(grad_vec, cell_vec)\n', (24391, 24411), True, 'import numpy as np\n'), ((29705, 29728), 'numpy.random.randint', 'np.random.randint', (['(0)', '(5)'], {}), '(0, 5)\n', (29722, 29728), True, 'import numpy as np\n'), ((29753, 29780), 'numpy.random.randint', 'np.random.randint', (['a', '(a * 2)'], {}), '(a, a * 2)\n', (29770, 29780), True, 'import numpy as np\n'), ((29801, 29828), 'numpy.random.randint', 'np.random.randint', (['b', '(b * 2)'], {}), '(b, b * 2)\n', (29818, 29828), True, 'import numpy as np\n'), ((29849, 29876), 'numpy.random.randint', 'np.random.randint', (['c', '(c * 2)'], {}), '(c, c * 2)\n', (29866, 29876), True, 'import numpy as np\n'), ((32057, 32081), 'numpy.nonzero', 'np.nonzero', (['location_map'], {}), '(location_map)\n', (32067, 32081), True, 'import numpy as np\n'), ((32185, 32297), 'numpy.array', 'np.array', (['[self.max_radius, self.max_radius / self.cell_elongation, self.max_radius /\n self.cell_elongation]'], {}), '([self.max_radius, self.max_radius / self.cell_elongation, self.\n max_radius / self.cell_elongation])\n', (32193, 32297), True, 'import numpy as np\n'), ((32372, 32448), 'utils.utils.print_timestamp', 'print_timestamp', (['"""Placing cell {0}/{1}..."""', '[cell_count + 1, self.num_cells]'], {}), "('Placing cell {0}/{1}...', [cell_count + 1, self.num_cells])\n", (32387, 32448), False, 'from utils.utils import print_timestamp\n'), ((33093, 33123), 'numpy.sum', 'np.sum', (['(distances ** 2)'], {'axis': '(0)'}), '(distances ** 2, axis=0)\n', (33099, 33123), True, 'import numpy as np\n'), ((34564, 34615), 'numpy.random.randint', 'np.random.randint', (['self.min_radius', 'self.max_radius'], {}), '(self.min_radius, self.max_radius)\n', (34581, 34615), True, 'import numpy as np\n'), ((35059, 35087), 'numpy.cross', 'np.cross', (['grad_vec', 'cell_vec'], {}), '(grad_vec, cell_vec)\n', (35067, 35087), True, 'import numpy as np\n'), ((3723, 3750), 'numpy.percentile', 'np.percentile', (['img', '[1, 99]'], {}), '(img, [1, 99])\n', (3736, 3750), True, 'import numpy as np\n'), ((3951, 3969), 'numpy.clip', 'np.clip', (['img', '(0)', '(1)'], {}), '(img, 0, 1)\n', (3958, 3969), True, 'import numpy as np\n'), ((3986, 4072), 'utils.h5_converter.h5_writer', 'h5_writer', (['[img]', "(save_name_img + '.h5')"], {'group_root': '"""data"""', 'group_names': "['image']"}), "([img], save_name_img + '.h5', group_root='data', group_names=[\n 'image'])\n", (3995, 4072), False, 'from utils.h5_converter import h5_writer\n'), ((7408, 7435), 'numpy.percentile', 'np.percentile', (['img', '[1, 99]'], {}), '(img, [1, 99])\n', (7421, 7435), True, 'import numpy as np\n'), ((7636, 7654), 'numpy.clip', 'np.clip', (['img', '(0)', '(1)'], {}), '(img, 0, 1)\n', (7643, 7654), True, 'import numpy as np\n'), ((7671, 7757), 'utils.h5_converter.h5_writer', 'h5_writer', (['[img]', "(save_name_img + '.h5')"], {'group_root': '"""data"""', 'group_names': "['image']"}), "([img], save_name_img + '.h5', group_root='data', group_names=[\n 'image'])\n", (7680, 7757), False, 'from utils.h5_converter import h5_writer\n'), ((12524, 12548), 'numpy.nonzero', 'np.nonzero', (['location_map'], {}), '(location_map)\n', (12534, 12548), True, 'import numpy as np\n'), ((13997, 14015), 'numpy.nonzero', 'np.nonzero', (['coeffs'], {}), '(coeffs)\n', (14007, 14015), True, 'import numpy as np\n'), ((15358, 15376), 'scipy.ndimage.convolve', 'convolve', (['img', 'psf'], {}), '(img, psf)\n', (15366, 15376), False, 'from scipy.ndimage import convolve, distance_transform_edt, gaussian_filter\n'), ((15457, 15527), 'numpy.random.normal', 'np.random.normal', (['self.noise_mean', 'self.noise_std'], {'size': 'self.img_shape'}), '(self.noise_mean, self.noise_std, size=self.img_shape)\n', (15473, 15527), True, 'import numpy as np\n'), ((17387, 17411), 'numpy.nonzero', 'np.nonzero', (['location_map'], {}), '(location_map)\n', (17397, 17411), True, 'import numpy as np\n'), ((17468, 17558), 'utils.utils.print_timestamp', 'print_timestamp', (['"""The maximum number of cells ({0}) was reached..."""', '[cell_count + 1]'], {}), "('The maximum number of cells ({0}) was reached...', [\n cell_count + 1])\n", (17483, 17558), False, 'from utils.utils import print_timestamp\n'), ((19307, 19330), 'numpy.random.randint', 'np.random.randint', (['(0)', '(2)'], {}), '(0, 2)\n', (19324, 19330), True, 'import numpy as np\n'), ((19377, 19416), 'numpy.maximum', 'np.maximum', (['self.irregularity_extend', '(1)'], {}), '(self.irregularity_extend, 1)\n', (19387, 19416), True, 'import numpy as np\n'), ((19442, 19465), 'numpy.random.randint', 'np.random.randint', (['(0)', '(2)'], {}), '(0, 2)\n', (19459, 19465), True, 'import numpy as np\n'), ((19512, 19551), 'numpy.maximum', 'np.maximum', (['self.irregularity_extend', '(1)'], {}), '(self.irregularity_extend, 1)\n', (19522, 19551), True, 'import numpy as np\n'), ((19577, 19600), 'numpy.random.randint', 'np.random.randint', (['(0)', '(2)'], {}), '(0, 2)\n', (19594, 19600), True, 'import numpy as np\n'), ((19647, 19686), 'numpy.maximum', 'np.maximum', (['self.irregularity_extend', '(1)'], {}), '(self.irregularity_extend, 1)\n', (19657, 19686), True, 'import numpy as np\n'), ((21874, 21964), 'utils.utils.print_timestamp', 'print_timestamp', (['"""The maximum number of cells ({0}) was reached..."""', '[cell_count + 1]'], {}), "('The maximum number of cells ({0}) was reached...', [\n cell_count + 1])\n", (21889, 21964), False, 'from utils.utils import print_timestamp\n'), ((24336, 24356), 'numpy.argmax', 'np.argmax', (['[a, b, c]'], {}), '([a, b, c])\n', (24345, 24356), True, 'import numpy as np\n'), ((24444, 24465), 'numpy.sum', 'np.sum', (['(rot_axis ** 2)'], {}), '(rot_axis ** 2)\n', (24450, 24465), True, 'import numpy as np\n'), ((24864, 24906), 'pyquaternion.Quaternion', 'Quaternion', ([], {'axis': 'rot_axis', 'angle': 'rot_angle'}), '(axis=rot_axis, angle=rot_angle)\n', (24874, 24906), False, 'from pyquaternion import Quaternion\n'), ((24932, 24977), 'numpy.matmul', 'np.matmul', (['cell_quant.rotation_matrix', 'coords'], {}), '(cell_quant.rotation_matrix, coords)\n', (24941, 24977), True, 'import numpy as np\n'), ((26945, 26969), 'numpy.random.randint', 'np.random.randint', (['(5)', '(10)'], {}), '(5, 10)\n', (26962, 26969), True, 'import numpy as np\n'), ((27000, 27024), 'numpy.random.randint', 'np.random.randint', (['(5)', '(10)'], {}), '(5, 10)\n', (27017, 27024), True, 'import numpy as np\n'), ((27776, 27799), 'numpy.random.randint', 'np.random.randint', (['(0)', '(2)'], {}), '(0, 2)\n', (27793, 27799), True, 'import numpy as np\n'), ((27846, 27885), 'numpy.maximum', 'np.maximum', (['self.irregularity_extend', '(1)'], {}), '(self.irregularity_extend, 1)\n', (27856, 27885), True, 'import numpy as np\n'), ((27911, 27934), 'numpy.random.randint', 'np.random.randint', (['(0)', '(2)'], {}), '(0, 2)\n', (27928, 27934), True, 'import numpy as np\n'), ((27981, 28020), 'numpy.maximum', 'np.maximum', (['self.irregularity_extend', '(1)'], {}), '(self.irregularity_extend, 1)\n', (27991, 28020), True, 'import numpy as np\n'), ((28046, 28069), 'numpy.random.randint', 'np.random.randint', (['(0)', '(2)'], {}), '(0, 2)\n', (28063, 28069), True, 'import numpy as np\n'), ((28116, 28155), 'numpy.maximum', 'np.maximum', (['self.irregularity_extend', '(1)'], {}), '(self.irregularity_extend, 1)\n', (28126, 28155), True, 'import numpy as np\n'), ((32550, 32640), 'utils.utils.print_timestamp', 'print_timestamp', (['"""The maximum number of cells ({0}) was reached..."""', '[cell_count + 1]'], {}), "('The maximum number of cells ({0}) was reached...', [\n cell_count + 1])\n", (32565, 32640), False, 'from utils.utils import print_timestamp\n'), ((35012, 35032), 'numpy.argmax', 'np.argmax', (['[a, b, c]'], {}), '([a, b, c])\n', (35021, 35032), True, 'import numpy as np\n'), ((35120, 35141), 'numpy.sum', 'np.sum', (['(rot_axis ** 2)'], {}), '(rot_axis ** 2)\n', (35126, 35141), True, 'import numpy as np\n'), ((35540, 35582), 'pyquaternion.Quaternion', 'Quaternion', ([], {'axis': 'rot_axis', 'angle': 'rot_angle'}), '(axis=rot_axis, angle=rot_angle)\n', (35550, 35582), False, 'from pyquaternion import Quaternion\n'), ((35608, 35653), 'numpy.matmul', 'np.matmul', (['cell_quant.rotation_matrix', 'coords'], {}), '(cell_quant.rotation_matrix, coords)\n', (35617, 35653), True, 'import numpy as np\n'), ((3524, 3581), 'os.path.join', 'os.path.join', (['save_path', '"""images"""', "(save_name_img + '.tif')"], {}), "(save_path, 'images', save_name_img + '.tif')\n", (3536, 3581), False, 'import os\n'), ((7206, 7266), 'os.path.join', 'os.path.join', (['save_path', '"""images_h5"""', "(save_name_img + '.tif')"], {}), "(save_path, 'images_h5', save_name_img + '.tif')\n", (7218, 7266), False, 'import os\n'), ((7829, 7848), 'os.path.split', 'os.path.split', (['file'], {}), '(file)\n', (7842, 7848), False, 'import os\n'), ((12584, 12623), 'numpy.random.randint', 'np.random.randint', (['(0)', 'location.shape[1]'], {}), '(0, location.shape[1])\n', (12601, 12623), True, 'import numpy as np\n'), ((13919, 13944), 'numpy.fliplr', 'np.fliplr', (['coeffs[0, ...]'], {}), '(coeffs[0, ...])\n', (13928, 13944), True, 'import numpy as np\n'), ((17663, 17702), 'numpy.random.randint', 'np.random.randint', (['(0)', 'location.shape[1]'], {}), '(0, location.shape[1])\n', (17680, 17702), True, 'import numpy as np\n'), ((21313, 21351), 'skimage.morphology.ball', 'morphology.ball', (['(self.position_std * 2)'], {}), '(self.position_std * 2)\n', (21328, 21351), False, 'from skimage import io, filters, morphology, measure\n'), ((22095, 22135), 'numpy.random.randint', 'np.random.randint', (['(0)', 'locations.shape[1]'], {}), '(0, locations.shape[1])\n', (22112, 22135), True, 'import numpy as np\n'), ((25309, 25334), 'numpy.maximum', 'np.maximum', (['(0)', '(p - c // 2)'], {}), '(0, p - c // 2)\n', (25319, 25334), True, 'import numpy as np\n'), ((27068, 27083), 'numpy.cos', 'np.cos', (['alpha_x'], {}), '(alpha_x)\n', (27074, 27083), True, 'import numpy as np\n'), ((27105, 27120), 'numpy.sin', 'np.sin', (['alpha_x'], {}), '(alpha_x)\n', (27111, 27120), True, 'import numpy as np\n'), ((27121, 27136), 'numpy.cos', 'np.cos', (['alpha_x'], {}), '(alpha_x)\n', (27127, 27136), True, 'import numpy as np\n'), ((27164, 27179), 'numpy.cos', 'np.cos', (['alpha_y'], {}), '(alpha_y)\n', (27170, 27179), True, 'import numpy as np\n'), ((27182, 27197), 'numpy.sin', 'np.sin', (['alpha_y'], {}), '(alpha_y)\n', (27188, 27197), True, 'import numpy as np\n'), ((27227, 27242), 'numpy.cos', 'np.cos', (['alpha_y'], {}), '(alpha_y)\n', (27233, 27242), True, 'import numpy as np\n'), ((31989, 32027), 'skimage.morphology.ball', 'morphology.ball', (['(self.position_std * 2)'], {}), '(self.position_std * 2)\n', (32004, 32027), False, 'from skimage import io, filters, morphology, measure\n'), ((32771, 32811), 'numpy.random.randint', 'np.random.randint', (['(0)', 'locations.shape[1]'], {}), '(0, locations.shape[1])\n', (32788, 32811), True, 'import numpy as np\n'), ((35985, 36010), 'numpy.maximum', 'np.maximum', (['(0)', '(p - c // 2)'], {}), '(0, p - c // 2)\n', (35995, 36010), True, 'import numpy as np\n'), ((9315, 9329), 'skimage.io.imread', 'io.imread', (['psf'], {}), '(psf)\n', (9324, 9329), False, 'from skimage import io, filters, morphology, measure\n'), ((12801, 12840), 'numpy.maximum', 'np.maximum', (['(location - cell_size_est)', '(0)'], {}), '(location - cell_size_est, 0)\n', (12811, 12840), True, 'import numpy as np\n'), ((17884, 17925), 'numpy.maximum', 'np.maximum', (['(location - self.min_radius)', '(0)'], {}), '(location - self.min_radius, 0)\n', (17894, 17925), True, 'import numpy as np\n'), ((19935, 19962), 'numpy.random.randint', 'np.random.randint', (['(c / 2)', 'c'], {}), '(c / 2, c)\n', (19952, 19962), True, 'import numpy as np\n'), ((20239, 20266), 'numpy.random.randint', 'np.random.randint', (['(c / 2)', 'c'], {}), '(c / 2, c)\n', (20256, 20266), True, 'import numpy as np\n'), ((20543, 20570), 'numpy.random.randint', 'np.random.randint', (['(c / 2)', 'c'], {}), '(c / 2, c)\n', (20560, 20570), True, 'import numpy as np\n'), ((24746, 24772), 'numpy.dot', 'np.dot', (['grad_vec', 'cell_vec'], {}), '(grad_vec, cell_vec)\n', (24752, 24772), True, 'import numpy as np\n'), ((27085, 27100), 'numpy.sin', 'np.sin', (['alpha_x'], {}), '(alpha_x)\n', (27091, 27100), True, 'import numpy as np\n'), ((27209, 27224), 'numpy.sin', 'np.sin', (['alpha_y'], {}), '(alpha_y)\n', (27215, 27224), True, 'import numpy as np\n'), ((28502, 28529), 'numpy.random.randint', 'np.random.randint', (['(c / 2)', 'c'], {}), '(c / 2, c)\n', (28519, 28529), True, 'import numpy as np\n'), ((28904, 28931), 'numpy.random.randint', 'np.random.randint', (['(c / 2)', 'c'], {}), '(c / 2, c)\n', (28921, 28931), True, 'import numpy as np\n'), ((29306, 29333), 'numpy.random.randint', 'np.random.randint', (['(c / 2)', 'c'], {}), '(c / 2, c)\n', (29323, 29333), True, 'import numpy as np\n'), ((31198, 31221), 'numpy.sign', 'np.sign', (['coords[0, ...]'], {}), '(coords[0, ...])\n', (31205, 31221), True, 'import numpy as np\n'), ((31291, 31314), 'numpy.sign', 'np.sign', (['coords[1, ...]'], {}), '(coords[1, ...])\n', (31298, 31314), True, 'import numpy as np\n'), ((31384, 31407), 'numpy.sign', 'np.sign', (['coords[2, ...]'], {}), '(coords[2, ...])\n', (31391, 31407), True, 'import numpy as np\n'), ((35422, 35448), 'numpy.dot', 'np.dot', (['grad_vec', 'cell_vec'], {}), '(grad_vec, cell_vec)\n', (35428, 35448), True, 'import numpy as np\n'), ((7114, 7133), 'os.path.split', 'os.path.split', (['file'], {}), '(file)\n', (7127, 7133), False, 'import os\n'), ((9420, 9430), 'numpy.load', 'np.load', (['p'], {}), '(p)\n', (9427, 9430), True, 'import numpy as np\n'), ((19850, 19877), 'numpy.random.randint', 'np.random.randint', (['(b / 2)', 'b'], {}), '(b / 2, b)\n', (19867, 19877), True, 'import numpy as np\n'), ((19910, 19937), 'numpy.random.randint', 'np.random.randint', (['(0)', '(2 * c)'], {}), '(0, 2 * c)\n', (19927, 19937), True, 'import numpy as np\n'), ((20154, 20181), 'numpy.random.randint', 'np.random.randint', (['(b / 2)', 'b'], {}), '(b / 2, b)\n', (20171, 20181), True, 'import numpy as np\n'), ((20214, 20241), 'numpy.random.randint', 'np.random.randint', (['(0)', '(2 * c)'], {}), '(0, 2 * c)\n', (20231, 20241), True, 'import numpy as np\n'), ((20458, 20485), 'numpy.random.randint', 'np.random.randint', (['(b / 2)', 'b'], {}), '(b / 2, b)\n', (20475, 20485), True, 'import numpy as np\n'), ((20518, 20545), 'numpy.random.randint', 'np.random.randint', (['(0)', '(2 * c)'], {}), '(0, 2 * c)\n', (20535, 20545), True, 'import numpy as np\n'), ((28374, 28401), 'numpy.random.randint', 'np.random.randint', (['(b / 2)', 'b'], {}), '(b / 2, b)\n', (28391, 28401), True, 'import numpy as np\n'), ((28477, 28504), 'numpy.random.randint', 'np.random.randint', (['(0)', '(2 * c)'], {}), '(0, 2 * c)\n', (28494, 28504), True, 'import numpy as np\n'), ((28776, 28803), 'numpy.random.randint', 'np.random.randint', (['(b / 2)', 'b'], {}), '(b / 2, b)\n', (28793, 28803), True, 'import numpy as np\n'), ((28879, 28906), 'numpy.random.randint', 'np.random.randint', (['(0)', '(2 * c)'], {}), '(0, 2 * c)\n', (28896, 28906), True, 'import numpy as np\n'), ((29178, 29205), 'numpy.random.randint', 'np.random.randint', (['(b / 2)', 'b'], {}), '(b / 2, b)\n', (29195, 29205), True, 'import numpy as np\n'), ((29281, 29308), 'numpy.random.randint', 'np.random.randint', (['(0)', '(2 * c)'], {}), '(0, 2 * c)\n', (29298, 29308), True, 'import numpy as np\n'), ((30236, 30269), 'numpy.random.randint', 'np.random.randint', (['(c / 20)', '(c / 10)'], {}), '(c / 20, c / 10)\n', (30253, 30269), True, 'import numpy as np\n'), ((30654, 30687), 'numpy.random.randint', 'np.random.randint', (['(c / 20)', '(c / 10)'], {}), '(c / 20, c / 10)\n', (30671, 30687), True, 'import numpy as np\n'), ((31072, 31105), 'numpy.random.randint', 'np.random.randint', (['(c / 20)', '(c / 10)'], {}), '(c / 20, c / 10)\n', (31089, 31105), True, 'import numpy as np\n'), ((19765, 19792), 'numpy.random.randint', 'np.random.randint', (['(a / 2)', 'a'], {}), '(a / 2, a)\n', (19782, 19792), True, 'import numpy as np\n'), ((19825, 19852), 'numpy.random.randint', 'np.random.randint', (['(0)', '(2 * b)'], {}), '(0, 2 * b)\n', (19842, 19852), True, 'import numpy as np\n'), ((20069, 20096), 'numpy.random.randint', 'np.random.randint', (['(a / 2)', 'a'], {}), '(a / 2, a)\n', (20086, 20096), True, 'import numpy as np\n'), ((20129, 20156), 'numpy.random.randint', 'np.random.randint', (['(0)', '(2 * b)'], {}), '(0, 2 * b)\n', (20146, 20156), True, 'import numpy as np\n'), ((20373, 20400), 'numpy.random.randint', 'np.random.randint', (['(a / 2)', 'a'], {}), '(a / 2, a)\n', (20390, 20400), True, 'import numpy as np\n'), ((20433, 20460), 'numpy.random.randint', 'np.random.randint', (['(0)', '(2 * b)'], {}), '(0, 2 * b)\n', (20450, 20460), True, 'import numpy as np\n'), ((28246, 28273), 'numpy.random.randint', 'np.random.randint', (['(a / 2)', 'a'], {}), '(a / 2, a)\n', (28263, 28273), True, 'import numpy as np\n'), ((28349, 28376), 'numpy.random.randint', 'np.random.randint', (['(0)', '(2 * b)'], {}), '(0, 2 * b)\n', (28366, 28376), True, 'import numpy as np\n'), ((28648, 28675), 'numpy.random.randint', 'np.random.randint', (['(a / 2)', 'a'], {}), '(a / 2, a)\n', (28665, 28675), True, 'import numpy as np\n'), ((28751, 28778), 'numpy.random.randint', 'np.random.randint', (['(0)', '(2 * b)'], {}), '(0, 2 * b)\n', (28768, 28778), True, 'import numpy as np\n'), ((29050, 29077), 'numpy.random.randint', 'np.random.randint', (['(a / 2)', 'a'], {}), '(a / 2, a)\n', (29067, 29077), True, 'import numpy as np\n'), ((29153, 29180), 'numpy.random.randint', 'np.random.randint', (['(0)', '(2 * b)'], {}), '(0, 2 * b)\n', (29170, 29180), True, 'import numpy as np\n'), ((30104, 30131), 'numpy.random.randint', 'np.random.randint', (['(b / 2)', 'b'], {}), '(b / 2, b)\n', (30121, 30131), True, 'import numpy as np\n'), ((30211, 30238), 'numpy.random.randint', 'np.random.randint', (['(c / 2)', 'c'], {}), '(c / 2, c)\n', (30228, 30238), True, 'import numpy as np\n'), ((30522, 30549), 'numpy.random.randint', 'np.random.randint', (['(b / 2)', 'b'], {}), '(b / 2, b)\n', (30539, 30549), True, 'import numpy as np\n'), ((30629, 30656), 'numpy.random.randint', 'np.random.randint', (['(c / 2)', 'c'], {}), '(c / 2, c)\n', (30646, 30656), True, 'import numpy as np\n'), ((30940, 30967), 'numpy.random.randint', 'np.random.randint', (['(b / 2)', 'b'], {}), '(b / 2, b)\n', (30957, 30967), True, 'import numpy as np\n'), ((31047, 31074), 'numpy.random.randint', 'np.random.randint', (['(c / 2)', 'c'], {}), '(c / 2, c)\n', (31064, 31074), True, 'import numpy as np\n'), ((19740, 19767), 'numpy.random.randint', 'np.random.randint', (['(0)', '(2 * a)'], {}), '(0, 2 * a)\n', (19757, 19767), True, 'import numpy as np\n'), ((20044, 20071), 'numpy.random.randint', 'np.random.randint', (['(0)', '(2 * a)'], {}), '(0, 2 * a)\n', (20061, 20071), True, 'import numpy as np\n'), ((20348, 20375), 'numpy.random.randint', 'np.random.randint', (['(0)', '(2 * a)'], {}), '(0, 2 * a)\n', (20365, 20375), True, 'import numpy as np\n'), ((28221, 28248), 'numpy.random.randint', 'np.random.randint', (['(0)', '(2 * a)'], {}), '(0, 2 * a)\n', (28238, 28248), True, 'import numpy as np\n'), ((28623, 28650), 'numpy.random.randint', 'np.random.randint', (['(0)', '(2 * a)'], {}), '(0, 2 * a)\n', (28640, 28650), True, 'import numpy as np\n'), ((29025, 29052), 'numpy.random.randint', 'np.random.randint', (['(0)', '(2 * a)'], {}), '(0, 2 * a)\n', (29042, 29052), True, 'import numpy as np\n'), ((29972, 29999), 'numpy.random.randint', 'np.random.randint', (['(a / 2)', 'a'], {}), '(a / 2, a)\n', (29989, 29999), True, 'import numpy as np\n'), ((30079, 30106), 'numpy.random.randint', 'np.random.randint', (['(b / 2)', 'b'], {}), '(b / 2, b)\n', (30096, 30106), True, 'import numpy as np\n'), ((30390, 30417), 'numpy.random.randint', 'np.random.randint', (['(a / 2)', 'a'], {}), '(a / 2, a)\n', (30407, 30417), True, 'import numpy as np\n'), ((30497, 30524), 'numpy.random.randint', 'np.random.randint', (['(b / 2)', 'b'], {}), '(b / 2, b)\n', (30514, 30524), True, 'import numpy as np\n'), ((30808, 30835), 'numpy.random.randint', 'np.random.randint', (['(a / 2)', 'a'], {}), '(a / 2, a)\n', (30825, 30835), True, 'import numpy as np\n'), ((30915, 30942), 'numpy.random.randint', 'np.random.randint', (['(b / 2)', 'b'], {}), '(b / 2, b)\n', (30932, 30942), True, 'import numpy as np\n'), ((29947, 29974), 'numpy.random.randint', 'np.random.randint', (['(a / 2)', 'a'], {}), '(a / 2, a)\n', (29964, 29974), True, 'import numpy as np\n'), ((30365, 30392), 'numpy.random.randint', 'np.random.randint', (['(a / 2)', 'a'], {}), '(a / 2, a)\n', (30382, 30392), True, 'import numpy as np\n'), ((30783, 30810), 'numpy.random.randint', 'np.random.randint', (['(a / 2)', 'a'], {}), '(a / 2, a)\n', (30800, 30810), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- from __future__ import division, print_function __all__ = ["GP"] try: from itertools import izip except ImportError: izip = zip import numpy as np import scipy.optimize as op from scipy.linalg import cho_factor, cho_solve, LinAlgError from .utils import multivariate_gaussian_samples, nd_sort_samples # MAGIC: tiny epsilon to add on the diagonal of the matrices in the absence # of observational uncertainties. Needed for computational stability. TINY = 1.25e-12 class GP(object): """ The basic Gaussian Process object. :param kernel: An instance of a subclass of :class:`kernels.Kernel`. :param mean: (optional) A description of the mean function; can be a callable or a scalar. If scalar, the mean is assumed constant. Otherwise, the function will be called with the array of independent coordinates as the only argument. (default: ``0.0``) """ def __init__(self, kernel, mean=None): self.kernel = kernel self._computed = False if mean is None: self.mean = _default_mean(0.) else: try: val = float(mean) except TypeError: self.mean = mean else: self.mean = _default_mean(val) @property def computed(self): """ Has the processes been computed since the last update of the kernel? """ return self._computed and not self.kernel.dirty @computed.setter def computed(self, v): self._computed = v if v: self.kernel.dirty = False def parse_samples(self, t, sort=False): """ Parse a list of samples to make sure that it has the correct dimensions and optionally sort it. In one dimension, the samples will be sorted in the logical order. In higher dimensions, a kd-tree is built and the samples are sorted in increasing distance from the *first* sample. :param t: ``(nsamples,)`` or ``(nsamples, ndim)`` The list of samples. If 1-D, this is assumed to be a list of one-dimensional samples otherwise, the size of the second dimension is assumed to be the dimension of the input space. :param sort: A boolean flag indicating whether or not the samples should be sorted. Returns a tuple ``(samples, inds)`` where * **samples** is an array with shape ``(nsamples, ndim)`` and if ``sort`` was ``True``, it will also be sorted, and * **inds** is an ``(nsamples,)`` list of integer permutations used to sort the list of samples. Raises a ``RuntimeError`` if the input dimension doesn't match the dimension of the kernel. """ t = np.atleast_1d(t) if len(t.shape) == 1: # Deal with one-dimensional data. if sort: inds = np.argsort(t) else: inds = np.arange(len(t), dtype=int) t = np.atleast_2d(t).T elif sort: # Sort the data using a KD-tree. inds = nd_sort_samples(t) else: # Otherwise, assume that the samples are sorted. inds = np.arange(t.shape[0], dtype=int) # Double check the dimensions against the kernel. if len(t.shape) != 2 or t.shape[1] != self.kernel.ndim: raise ValueError("Dimension mismatch") return t[inds], inds def _check_dimensions(self, y): n, ndim = self._x.shape y = np.atleast_1d(y) if len(y.shape) > 1: raise ValueError("The predicted dimension must be 1-D") if len(y) != n: raise ValueError("Dimension mismatch") return y def compute(self, x, yerr=TINY, sort=True, **kwargs): """ Pre-compute the covariance matrix and factorize it for a set of times and uncertainties. :param x: ``(nsamples,)`` or ``(nsamples, ndim)`` The independent coordinates of the data points. :param yerr: (optional) ``(nsamples,)`` or scalar The Gaussian uncertainties on the data points at coordinates ``x``. These values will be added in quadrature to the diagonal of the covariance matrix. :param sort: (optional) Should the samples be sorted before computing the covariance matrix? This can lead to more numerically stable results and with some linear algebra libraries this can more computationally efficient. Either way, this flag is passed directly to :func:`parse_samples`. (default: ``True``) """ # Parse the input coordinates. self._x, self.inds = self.parse_samples(x, sort) try: self._yerr = float(yerr) * np.ones(len(x)) except TypeError: self._yerr = self._check_dimensions(yerr)[self.inds] self._do_compute(**kwargs) def _do_compute(self, _scale=0.5*np.log(2*np.pi)): # Compute the kernel matrix. K = self.kernel(self._x[:, None], self._x[None, :]) K[np.diag_indices_from(K)] += self._yerr ** 2 # Factor the matrix and compute the log-determinant. factor, _ = self._factor = cho_factor(K, overwrite_a=True) self._const = -(np.sum(np.log(np.diag(factor))) + _scale*len(self._x)) # Save the computed state. self.computed = True def recompute(self, sort=False, **kwargs): """ Re-compute a previously computed model. You might want to do this if the kernel parameters change and the kernel is labeled as ``dirty``. :params sort: (optional) Should the samples be sorted before computing the covariance matrix? (default: ``False``) """ if not (hasattr(self, "_x") and hasattr(self, "_yerr")): raise RuntimeError("You need to compute the model first") return self.compute(self._x, self._yerr, sort=sort, **kwargs) def _compute_lnlike(self, r): return self._const - 0.5*np.dot(r.T, cho_solve(self._factor, r)) def lnlikelihood(self, y, quiet=False): """ Compute the ln-likelihood of a set of observations under the Gaussian process model. You must call ``compute`` before this function. :param y: ``(nsamples, )`` The observations at the coordinates provided in the ``compute`` step. :param quiet: If ``True`` return negative infinity instead of raising an exception when there is an invalid kernel or linear algebra failure. (default: ``False``) """ if not self.computed: try: self.recompute() except (ValueError, LinAlgError): if quiet: return -np.inf raise r = self._check_dimensions(y)[self.inds] - self.mean(self._x) ll = self._compute_lnlike(r) return ll if np.isfinite(ll) else -np.inf def grad_lnlikelihood(self, y, dims=None, quiet=False): """ Compute the gradient of the ln-likelihood function as a function of the kernel parameters. :param y: ``(nsamples,)`` The list of observations at coordinates ``x`` provided to the :func:`compute` function. :param dims: (optional) If you only want to compute the gradient in some dimensions, list them here. :param quiet: If ``True`` return a gradient of zero instead of raising an exception when there is an invalid kernel or linear algebra failure. (default: ``False``) """ # By default, compute the gradient in all dimensions. if dims is None: dims = np.ones(len(self.kernel), dtype=bool) # Make sure that the model is computed and try to recompute it if it's # dirty. if not self.computed: try: self.recompute() except (ValueError, LinAlgError): if quiet: return np.zeros_like(dims, dtype=float) raise # Parse the input sample list. r = self._check_dimensions(y)[self.inds] - self.mean(self._x) # Pre-compute some factors. alpha = cho_solve(self._factor, r) Kg = self.kernel.grad(self._x[:, None], self._x[None, :])[dims] # Loop over dimensions and compute the gradient in each one. g = np.empty(len(Kg)) for i, k in enumerate(Kg): d = sum(map(lambda r: np.dot(alpha, r), alpha[:, None] * k)) d -= np.sum(np.diag(cho_solve(self._factor, k))) g[i] = 0.5 * d return g def predict(self, y, t): """ Compute the conditional predictive distribution of the model. :param y: ``(nsamples,)`` The observations to condition the model on. :param t: ``(ntest,)`` or ``(ntest, ndim)`` The coordinates where the predictive distribution should be computed. Returns a tuple ``(mu, cov)`` where * **mu** ``(ntest,)`` is the mean of the predictive distribution, and * **cov** ``(ntest, ntest)`` is the predictive covariance. """ if not self.computed: self.recompute() r = self._check_dimensions(y)[self.inds] - self.mean(self._x) xs, i = self.parse_samples(t, False) alpha = cho_solve(self._factor, r) # Compute the predictive mean. Kxs = self.kernel(self._x[None, :], xs[:, None]) mu = np.dot(Kxs, alpha) + self.mean(xs) # Compute the predictive covariance. cov = self.kernel(xs[:, None], xs[None, :]) cov -= np.dot(Kxs, cho_solve(self._factor, Kxs.T)) return mu, cov def sample_conditional(self, y, t, size=1): """ Draw samples from the predictive conditional distribution. :param y: ``(nsamples, )`` The observations to condition the model on. :param t: ``(ntest, )`` or ``(ntest, ndim)`` The coordinates where the predictive distribution should be computed. :param size: (optional) The number of samples to draw. (default: ``1``) Returns **samples** ``(N, ntest)``, a list of predictions at coordinates given by ``t``. """ mu, cov = self.predict(y, t) return multivariate_gaussian_samples(cov, size, mean=mu) def sample(self, t, size=1): """ Draw samples from the prior distribution. :param t: ``(ntest, )`` or ``(ntest, ndim)`` The coordinates where the model should be sampled. :param size: (optional) The number of samples to draw. (default: ``1``) Returns **samples** ``(N, ntest)``, a list of predictions at coordinates given by ``t``. """ x, _ = self.parse_samples(t, False) cov = self.get_matrix(x) return multivariate_gaussian_samples(cov, size, mean=self.mean(x)) def get_matrix(self, t): """ Get the covariance matrix at a given set of independent coordinates. :param t: ``(nsamples,)`` or ``(nsamples, ndim)`` The list of samples. """ r, _ = self.parse_samples(t, False) return self.kernel(r[:, None], r[None, :]) def optimize(self, x, y, yerr=TINY, sort=True, dims=None, in_log=True, verbose=True, **kwargs): """ A simple and not terribly robust non-linear optimization algorithm for the kernel hyperpararmeters. :param x: ``(nsamples,)`` or ``(nsamples, ndim)`` The independent coordinates of the data points. :param y: ``(nsamples, )`` The observations at the coordinates ``x``. :param yerr: (optional) ``(nsamples,)`` or scalar The Gaussian uncertainties on the data points at coordinates ``x``. These values will be added in quadrature to the diagonal of the covariance matrix. :param sort: (optional) Should the samples be sorted before computing the covariance matrix? :param dims: (optional) If you only want to optimize over some parameters, list their indices here. :param in_log: (optional) ``(len(kernel),)``, ``(len(dims),)`` or bool If you want to fit the parameters in the log (this can be useful for parameters that shouldn't go negative) specify that here. This can be a single boolean---in which case it is assumed to apply to every dimension---or it can be an array of booleans, one for each dimension. :param verbose: (optional) Display the results of the call to :func:`scipy.optimize.minimize`? (default: ``True``) Returns ``(pars, results)`` where ``pars`` is the list of optimized parameters and ``results`` is the results object returned by :func:`scipy.optimize.minimize`. """ self.compute(x, yerr, sort=sort) # By default, optimize all the hyperparameters. if dims is None: dims = np.ones(len(self.kernel), dtype=bool) dims = np.arange(len(self.kernel))[dims] # Deal with conversion functions. try: len(in_log) except TypeError: in_log = in_log * np.ones_like(dims, dtype=bool) else: if len(in_log) != len(dims): raise RuntimeError("Dimension list and log mask mismatch") # Build the conversion functions. conv = np.array([lambda x: x for i in range(len(dims))]) iconv = np.array([lambda x: x for i in range(len(dims))]) conv[in_log] = np.exp iconv[in_log] = np.log # Define the objective function and gradient. def nll(pars): for i, f, p in izip(dims, conv, pars): self.kernel[i] = f(p) ll = self.lnlikelihood(y, quiet=True) if not np.isfinite(ll): return 1e25 # The optimizers can't deal with infinities. return -ll def grad_nll(pars): for i, f, p in izip(dims, conv, pars): self.kernel[i] = f(p) return -self.grad_lnlikelihood(y, dims=dims, quiet=True) # Run the optimization. p0 = [f(p) for f, p in izip(iconv, self.kernel.pars[dims])] results = op.minimize(nll, p0, jac=grad_nll, **kwargs) if verbose: print(results.message) # Update the kernel. for i, f, p in izip(dims, conv, results.x): self.kernel[i] = f(p) return self.kernel.pars[dims], results class _default_mean(object): def __init__(self, value): self.value = value def __call__(self, t): return self.value + np.zeros(len(t), dtype=float)
[ "numpy.diag_indices_from", "scipy.linalg.cho_solve", "numpy.atleast_2d", "numpy.ones_like", "scipy.linalg.cho_factor", "scipy.optimize.minimize", "numpy.log", "numpy.diag", "numpy.argsort", "numpy.dot", "numpy.isfinite", "itertools.izip", "numpy.zeros_like", "numpy.arange", "numpy.atleas...
[((2842, 2858), 'numpy.atleast_1d', 'np.atleast_1d', (['t'], {}), '(t)\n', (2855, 2858), True, 'import numpy as np\n'), ((3612, 3628), 'numpy.atleast_1d', 'np.atleast_1d', (['y'], {}), '(y)\n', (3625, 3628), True, 'import numpy as np\n'), ((5344, 5375), 'scipy.linalg.cho_factor', 'cho_factor', (['K'], {'overwrite_a': '(True)'}), '(K, overwrite_a=True)\n', (5354, 5375), False, 'from scipy.linalg import cho_factor, cho_solve, LinAlgError\n'), ((8452, 8478), 'scipy.linalg.cho_solve', 'cho_solve', (['self._factor', 'r'], {}), '(self._factor, r)\n', (8461, 8478), False, 'from scipy.linalg import cho_factor, cho_solve, LinAlgError\n'), ((9610, 9636), 'scipy.linalg.cho_solve', 'cho_solve', (['self._factor', 'r'], {}), '(self._factor, r)\n', (9619, 9636), False, 'from scipy.linalg import cho_factor, cho_solve, LinAlgError\n'), ((14683, 14727), 'scipy.optimize.minimize', 'op.minimize', (['nll', 'p0'], {'jac': 'grad_nll'}), '(nll, p0, jac=grad_nll, **kwargs)\n', (14694, 14727), True, 'import scipy.optimize as op\n'), ((14837, 14864), 'itertools.izip', 'izip', (['dims', 'conv', 'results.x'], {}), '(dims, conv, results.x)\n', (14841, 14864), False, 'from itertools import izip\n'), ((5078, 5095), 'numpy.log', 'np.log', (['(2 * np.pi)'], {}), '(2 * np.pi)\n', (5084, 5095), True, 'import numpy as np\n'), ((5203, 5226), 'numpy.diag_indices_from', 'np.diag_indices_from', (['K'], {}), '(K)\n', (5223, 5226), True, 'import numpy as np\n'), ((7102, 7117), 'numpy.isfinite', 'np.isfinite', (['ll'], {}), '(ll)\n', (7113, 7117), True, 'import numpy as np\n'), ((9747, 9765), 'numpy.dot', 'np.dot', (['Kxs', 'alpha'], {}), '(Kxs, alpha)\n', (9753, 9765), True, 'import numpy as np\n'), ((9907, 9937), 'scipy.linalg.cho_solve', 'cho_solve', (['self._factor', 'Kxs.T'], {}), '(self._factor, Kxs.T)\n', (9916, 9937), False, 'from scipy.linalg import cho_factor, cho_solve, LinAlgError\n'), ((14131, 14153), 'itertools.izip', 'izip', (['dims', 'conv', 'pars'], {}), '(dims, conv, pars)\n', (14135, 14153), False, 'from itertools import izip\n'), ((14433, 14455), 'itertools.izip', 'izip', (['dims', 'conv', 'pars'], {}), '(dims, conv, pars)\n', (14437, 14455), False, 'from itertools import izip\n'), ((2979, 2992), 'numpy.argsort', 'np.argsort', (['t'], {}), '(t)\n', (2989, 2992), True, 'import numpy as np\n'), ((3079, 3095), 'numpy.atleast_2d', 'np.atleast_2d', (['t'], {}), '(t)\n', (3092, 3095), True, 'import numpy as np\n'), ((3294, 3326), 'numpy.arange', 'np.arange', (['t.shape[0]'], {'dtype': 'int'}), '(t.shape[0], dtype=int)\n', (3303, 3326), True, 'import numpy as np\n'), ((14263, 14278), 'numpy.isfinite', 'np.isfinite', (['ll'], {}), '(ll)\n', (14274, 14278), True, 'import numpy as np\n'), ((14628, 14663), 'itertools.izip', 'izip', (['iconv', 'self.kernel.pars[dims]'], {}), '(iconv, self.kernel.pars[dims])\n', (14632, 14663), False, 'from itertools import izip\n'), ((6180, 6206), 'scipy.linalg.cho_solve', 'cho_solve', (['self._factor', 'r'], {}), '(self._factor, r)\n', (6189, 6206), False, 'from scipy.linalg import cho_factor, cho_solve, LinAlgError\n'), ((8791, 8817), 'scipy.linalg.cho_solve', 'cho_solve', (['self._factor', 'k'], {}), '(self._factor, k)\n', (8800, 8817), False, 'from scipy.linalg import cho_factor, cho_solve, LinAlgError\n'), ((13630, 13660), 'numpy.ones_like', 'np.ones_like', (['dims'], {'dtype': 'bool'}), '(dims, dtype=bool)\n', (13642, 13660), True, 'import numpy as np\n'), ((5414, 5429), 'numpy.diag', 'np.diag', (['factor'], {}), '(factor)\n', (5421, 5429), True, 'import numpy as np\n'), ((8234, 8266), 'numpy.zeros_like', 'np.zeros_like', (['dims'], {'dtype': 'float'}), '(dims, dtype=float)\n', (8247, 8266), True, 'import numpy as np\n'), ((8720, 8736), 'numpy.dot', 'np.dot', (['alpha', 'r'], {}), '(alpha, r)\n', (8726, 8736), True, 'import numpy as np\n')]
from surprise.model_selection import train_test_split from surprise.model_selection import LeaveOneOut from surprise import KNNBaseline from surprise import Dataset, KNNBasic from surprise import Reader import heapq from movies_analyzer.Movies import Movies, RATINGS, LINKS, MOVIES from movies_recommender.utils import get_popularity_ranking import pandas as pd from operator import itemgetter from surprise.similarities import cosine class RecommendationDataSet: def __init__(self, movies: Movies): # train_test_split(dataset, test_size=test_size, random_state=1) self.movies = movies self.dataset_df = pd.read_csv(movies.movielens_path / RATINGS) reader = Reader(line_format='user item rating timestamp', sep=',', skip_lines=1) """ line_format - list of columns sep - separator for csv file skip_lines - start from the second line """ self.dataset = Dataset.load_from_file(self.movies.movielens_path / RATINGS, reader=reader) self.full_dataset = self.dataset.build_full_trainset() # ranking self.ratings, self.rankings = get_popularity_ranking(self.full_dataset) # TRAINING self.train_set, self.test_set = None, None self.anti_test_set = None self.leave_one_out_train_set = None self.leave_one_out_test_set = None self.leave_one_out_anti_test_set = None self.similarity_algorithm = None def clear_training(self): self.train_set, self.test_set = None, None self.anti_test_set = None self.leave_one_out_train_set = None self.leave_one_out_test_set = None self.leave_one_out_anti_test_set = None self.similarity_algorithm = None def get_dataset_with_extended_user(self, watched): """ Create new dataset with new user, based only on the score of current movies. :param """ df = pd.DataFrame.from_dict(watched, orient='index', columns=['rating']) df.reset_index(inplace=True) df.rename(columns={'index': 'movieId'},inplace=True) new_user_id = max(self.dataset_df['userId']) + 1 df['userId'] = new_user_id rating_df = self.dataset_df[['userId', 'movieId', 'rating']].append( df[['userId', 'movieId', 'rating']], ignore_index=True, sort=False) rating_df['movieId'] = rating_df['movieId'].astype(str) reader = Reader(rating_scale=(1, 5)) dataset = Dataset.load_from_df(rating_df[['userId', 'movieId', 'rating']], reader) full_dataset = dataset.build_full_trainset() return new_user_id, full_dataset def build_train_test(self, test_size=.25): # Train Set, Test Set to test results self.train_set, self.test_set = train_test_split(self.dataset, test_size=test_size, random_state=1) # https://surprise.readthedocs.io/en/stable/trainset.html#surprise.Trainset.build_anti_testset # Situation when the user u is known, the item is known, but the rating is not in the trainset self.anti_test_set = self.full_dataset.build_anti_testset() # Cross-validation iterator where each user has exactly one rating in the testset. leave_one_out_set = LeaveOneOut(n_splits=1, random_state=1) loo_train_set, loo_test_set = list(leave_one_out_set.split(self.dataset))[0] self.leave_one_out_train_set = loo_train_set self.leave_one_out_test_set = loo_test_set self.leave_one_out_anti_test_set = loo_train_set.build_anti_testset() # Compute similarity matrix between items so we can measure diversity sim_options = {'name': 'cosine', 'user_based': False} self.similarity_algorithm = KNNBaseline(sim_options=sim_options) self.similarity_algorithm.fit(self.full_dataset)
[ "surprise.KNNBaseline", "pandas.read_csv", "surprise.model_selection.LeaveOneOut", "surprise.Dataset.load_from_file", "surprise.Dataset.load_from_df", "surprise.model_selection.train_test_split", "pandas.DataFrame.from_dict", "movies_recommender.utils.get_popularity_ranking", "surprise.Reader" ]
[((635, 679), 'pandas.read_csv', 'pd.read_csv', (['(movies.movielens_path / RATINGS)'], {}), '(movies.movielens_path / RATINGS)\n', (646, 679), True, 'import pandas as pd\n'), ((698, 769), 'surprise.Reader', 'Reader', ([], {'line_format': '"""user item rating timestamp"""', 'sep': '""","""', 'skip_lines': '(1)'}), "(line_format='user item rating timestamp', sep=',', skip_lines=1)\n", (704, 769), False, 'from surprise import Reader\n'), ((940, 1015), 'surprise.Dataset.load_from_file', 'Dataset.load_from_file', (['(self.movies.movielens_path / RATINGS)'], {'reader': 'reader'}), '(self.movies.movielens_path / RATINGS, reader=reader)\n', (962, 1015), False, 'from surprise import Dataset, KNNBasic\n'), ((1136, 1177), 'movies_recommender.utils.get_popularity_ranking', 'get_popularity_ranking', (['self.full_dataset'], {}), '(self.full_dataset)\n', (1158, 1177), False, 'from movies_recommender.utils import get_popularity_ranking\n'), ((1956, 2023), 'pandas.DataFrame.from_dict', 'pd.DataFrame.from_dict', (['watched'], {'orient': '"""index"""', 'columns': "['rating']"}), "(watched, orient='index', columns=['rating'])\n", (1978, 2023), True, 'import pandas as pd\n'), ((2501, 2528), 'surprise.Reader', 'Reader', ([], {'rating_scale': '(1, 5)'}), '(rating_scale=(1, 5))\n', (2507, 2528), False, 'from surprise import Reader\n'), ((2547, 2619), 'surprise.Dataset.load_from_df', 'Dataset.load_from_df', (["rating_df[['userId', 'movieId', 'rating']]", 'reader'], {}), "(rating_df[['userId', 'movieId', 'rating']], reader)\n", (2567, 2619), False, 'from surprise import Dataset, KNNBasic\n'), ((2849, 2916), 'surprise.model_selection.train_test_split', 'train_test_split', (['self.dataset'], {'test_size': 'test_size', 'random_state': '(1)'}), '(self.dataset, test_size=test_size, random_state=1)\n', (2865, 2916), False, 'from surprise.model_selection import train_test_split\n'), ((3312, 3351), 'surprise.model_selection.LeaveOneOut', 'LeaveOneOut', ([], {'n_splits': '(1)', 'random_state': '(1)'}), '(n_splits=1, random_state=1)\n', (3323, 3351), False, 'from surprise.model_selection import LeaveOneOut\n'), ((3797, 3833), 'surprise.KNNBaseline', 'KNNBaseline', ([], {'sim_options': 'sim_options'}), '(sim_options=sim_options)\n', (3808, 3833), False, 'from surprise import KNNBaseline\n')]
# MIT License # # Copyright (c) 2018-2019 Red Hat, Inc. # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from typing import Union from celery import Celery from flexmock import flexmock from ogr.abstract import GitProject, GitService, CommitStatus from packit.api import PackitAPI from packit.config import PackageConfig, JobConfig, JobType, JobConfigTriggerType from packit.exceptions import FailedCreateSRPM from packit_service import sentry_integration from packit_service.config import ServiceConfig from packit_service.models import CoprBuild, SRPMBuild from packit_service.service.events import ( PullRequestEvent, PullRequestCommentEvent, CoprBuildEvent, PushGitHubEvent, ReleaseEvent, ) from packit_service.service.models import CoprBuild as RedisCoprBuild from packit_service.worker.build.copr_build import CoprBuildJobHelper from packit_service.worker.reporting import StatusReporter class FakeCoprBuildModel: build_id = 0 def save(self): pass def add_build(self): pass def build_helper( event: Union[ PullRequestEvent, PullRequestCommentEvent, CoprBuildEvent, PushGitHubEvent, ReleaseEvent, ], metadata=None, trigger=None, jobs=None, ): if not metadata: metadata = { "owner": "nobody", "targets": [ "fedora-29-x86_64", "fedora-30-x86_64", "fedora-31-x86_64", "fedora-rawhide-x86_64", ], } jobs = jobs or [] jobs.append( JobConfig( type=JobType.copr_build, trigger=trigger or JobConfigTriggerType.pull_request, metadata=metadata, ) ) pkg_conf = PackageConfig(jobs=jobs, downstream_package_name="dummy") handler = CoprBuildJobHelper( config=ServiceConfig(), package_config=pkg_conf, project=GitProject("", GitService(), ""), event=event, ) handler._api = PackitAPI(ServiceConfig(), pkg_conf) return handler def test_copr_build_check_names(pull_request_event): helper = build_helper( event=pull_request_event, metadata={"owner": "nobody", "targets": ["bright-future-x86_64"]}, ) flexmock(StatusReporter).should_receive("set_status").with_args( state=CommitStatus.pending, description="Building SRPM ...", check_name="packit-stg/rpm-build-bright-future-x86_64", url="", ).and_return() flexmock(StatusReporter).should_receive("set_status").with_args( state=CommitStatus.pending, description="Building RPM ...", check_name="packit-stg/rpm-build-bright-future-x86_64", url="https://localhost:5000/copr-build/1/logs", ).and_return() flexmock(GitProject).should_receive("set_commit_status").and_return().never() flexmock(RedisCoprBuild).should_receive("create").and_return(FakeCoprBuildModel()) flexmock(SRPMBuild).should_receive("create").and_return(SRPMBuild()) flexmock(CoprBuild).should_receive("get_or_create").and_return(CoprBuild(id=1)) flexmock(PackitAPI).should_receive("run_copr_build").and_return(1, None) flexmock(Celery).should_receive("send_task").once() assert helper.run_copr_build()["success"] def test_copr_build_success_set_test_check(pull_request_event): # status is set for each build-target (4x): # - Building SRPM ... # - Building RPM ... # status is set for each test-target (4x): # - Building SRPM ... # - Building RPM ... test_job = JobConfig( type=JobType.tests, trigger=JobConfigTriggerType.pull_request, metadata={} ) helper = build_helper(jobs=[test_job], event=pull_request_event) flexmock(GitProject).should_receive("set_commit_status").and_return().times(16) flexmock(RedisCoprBuild).should_receive("create").and_return(FakeCoprBuildModel()) flexmock(SRPMBuild).should_receive("create").and_return(SRPMBuild()) flexmock(CoprBuild).should_receive("get_or_create").and_return(CoprBuild(id=1)) flexmock(PackitAPI).should_receive("run_copr_build").and_return(1, None).once() flexmock(Celery).should_receive("send_task").once() assert helper.run_copr_build()["success"] def test_copr_build_for_branch(branch_push_event): # status is set for each build-target (4x): # - Building SRPM ... # - Building RPM ... branch_build_job = JobConfig( type=JobType.build, trigger=JobConfigTriggerType.commit, metadata={ "branch": "build-branch", "owner": "nobody", "targets": [ "fedora-29-x86_64", "fedora-30-x86_64", "fedora-31-x86_64", "fedora-rawhide-x86_64", ], }, ) helper = build_helper(jobs=[branch_build_job], event=branch_push_event) flexmock(GitProject).should_receive("set_commit_status").and_return().times(8) flexmock(RedisCoprBuild).should_receive("create").and_return(FakeCoprBuildModel()) flexmock(SRPMBuild).should_receive("create").and_return(SRPMBuild()) flexmock(CoprBuild).should_receive("get_or_create").and_return(CoprBuild(id=1)) flexmock(PackitAPI).should_receive("run_copr_build").and_return(1, None).once() flexmock(Celery).should_receive("send_task").once() assert helper.run_copr_build()["success"] def test_copr_build_for_release(release_event): # status is set for each build-target (4x): # - Building SRPM ... # - Building RPM ... branch_build_job = JobConfig( type=JobType.build, trigger=JobConfigTriggerType.release, metadata={ "branch": "build-branch", "owner": "nobody", "targets": [ "fedora-29-x86_64", "fedora-30-x86_64", "fedora-31-x86_64", "fedora-rawhide-x86_64", ], }, ) helper = build_helper(jobs=[branch_build_job], event=release_event) flexmock(GitProject).should_receive("set_commit_status").and_return().times(8) flexmock(RedisCoprBuild).should_receive("create").and_return(FakeCoprBuildModel()) flexmock(SRPMBuild).should_receive("create").and_return(SRPMBuild()) flexmock(CoprBuild).should_receive("get_or_create").and_return(CoprBuild(id=1)) flexmock(PackitAPI).should_receive("run_copr_build").and_return(1, None).once() flexmock(Celery).should_receive("send_task").once() assert helper.run_copr_build()["success"] def test_copr_build_success(pull_request_event): # status is set for each build-target (4x): # - Building SRPM ... # - Building RPM ... helper = build_helper(event=pull_request_event) flexmock(GitProject).should_receive("set_commit_status").and_return().times(8) flexmock(RedisCoprBuild).should_receive("create").and_return(FakeCoprBuildModel()) flexmock(SRPMBuild).should_receive("create").and_return(SRPMBuild()) flexmock(CoprBuild).should_receive("get_or_create").and_return(CoprBuild(id=1)) flexmock(PackitAPI).should_receive("run_copr_build").and_return(1, None).once() flexmock(Celery).should_receive("send_task").once() assert helper.run_copr_build()["success"] def test_copr_build_fails_in_packit(pull_request_event): # status is set for each build-target (4x): # - Building SRPM ... # - Build failed, check latest comment for details. helper = build_helper(event=pull_request_event) templ = "packit-stg/rpm-build-fedora-{ver}-x86_64" for v in ["29", "30", "31", "rawhide"]: flexmock(GitProject).should_receive("set_commit_status").with_args( "528b803be6f93e19ca4130bf4976f2800a3004c4", CommitStatus.pending, "", "Building SRPM ...", templ.format(ver=v), trim=True, ).and_return().once() for v in ["29", "30", "31", "rawhide"]: flexmock(GitProject).should_receive("set_commit_status").with_args( "528b803be6f93e19ca4130bf4976f2800a3004c4", CommitStatus.failure, "https://localhost:5000/srpm-build/2/logs", "SRPM build failed, check the logs for details.", templ.format(ver=v), trim=True, ).and_return().once() flexmock(RedisCoprBuild).should_receive("create").and_return(FakeCoprBuildModel()) flexmock(SRPMBuild).should_receive("create").and_return(SRPMBuild(id=2)) flexmock(CoprBuild).should_receive("get_or_create").and_return(CoprBuild(id=1)) flexmock(sentry_integration).should_receive("send_to_sentry").and_return().once() flexmock(PackitAPI).should_receive("run_copr_build").and_raise( FailedCreateSRPM, "some error" ) assert not helper.run_copr_build()["success"] def test_copr_build_no_targets(pull_request_event): # status is set for each build-target (fedora-stable => 2x): # - Building SRPM ... # - Building RPM ... helper = build_helper(event=pull_request_event, metadata={"owner": "nobody"}) flexmock(GitProject).should_receive("set_commit_status").and_return().times(4) flexmock(RedisCoprBuild).should_receive("create").and_return(FakeCoprBuildModel()) flexmock(SRPMBuild).should_receive("create").and_return(SRPMBuild()) flexmock(CoprBuild).should_receive("get_or_create").and_return(CoprBuild(id=1)) flexmock(PackitAPI).should_receive("run_copr_build").and_return(1, None).once() flexmock(Celery).should_receive("send_task").once() assert helper.run_copr_build()["success"]
[ "packit_service.models.CoprBuild", "packit.config.JobConfig", "packit_service.config.ServiceConfig", "packit.config.PackageConfig", "ogr.abstract.GitService", "packit_service.models.SRPMBuild", "flexmock.flexmock" ]
[((2766, 2823), 'packit.config.PackageConfig', 'PackageConfig', ([], {'jobs': 'jobs', 'downstream_package_name': '"""dummy"""'}), "(jobs=jobs, downstream_package_name='dummy')\n", (2779, 2823), False, 'from packit.config import PackageConfig, JobConfig, JobType, JobConfigTriggerType\n'), ((4589, 4678), 'packit.config.JobConfig', 'JobConfig', ([], {'type': 'JobType.tests', 'trigger': 'JobConfigTriggerType.pull_request', 'metadata': '{}'}), '(type=JobType.tests, trigger=JobConfigTriggerType.pull_request,\n metadata={})\n', (4598, 4678), False, 'from packit.config import PackageConfig, JobConfig, JobType, JobConfigTriggerType\n'), ((5449, 5683), 'packit.config.JobConfig', 'JobConfig', ([], {'type': 'JobType.build', 'trigger': 'JobConfigTriggerType.commit', 'metadata': "{'branch': 'build-branch', 'owner': 'nobody', 'targets': [\n 'fedora-29-x86_64', 'fedora-30-x86_64', 'fedora-31-x86_64',\n 'fedora-rawhide-x86_64']}"}), "(type=JobType.build, trigger=JobConfigTriggerType.commit, metadata\n ={'branch': 'build-branch', 'owner': 'nobody', 'targets': [\n 'fedora-29-x86_64', 'fedora-30-x86_64', 'fedora-31-x86_64',\n 'fedora-rawhide-x86_64']})\n", (5458, 5683), False, 'from packit.config import PackageConfig, JobConfig, JobType, JobConfigTriggerType\n'), ((6590, 6824), 'packit.config.JobConfig', 'JobConfig', ([], {'type': 'JobType.build', 'trigger': 'JobConfigTriggerType.release', 'metadata': "{'branch': 'build-branch', 'owner': 'nobody', 'targets': [\n 'fedora-29-x86_64', 'fedora-30-x86_64', 'fedora-31-x86_64',\n 'fedora-rawhide-x86_64']}"}), "(type=JobType.build, trigger=JobConfigTriggerType.release,\n metadata={'branch': 'build-branch', 'owner': 'nobody', 'targets': [\n 'fedora-29-x86_64', 'fedora-30-x86_64', 'fedora-31-x86_64',\n 'fedora-rawhide-x86_64']})\n", (6599, 6824), False, 'from packit.config import PackageConfig, JobConfig, JobType, JobConfigTriggerType\n'), ((2590, 2702), 'packit.config.JobConfig', 'JobConfig', ([], {'type': 'JobType.copr_build', 'trigger': '(trigger or JobConfigTriggerType.pull_request)', 'metadata': 'metadata'}), '(type=JobType.copr_build, trigger=trigger or JobConfigTriggerType.\n pull_request, metadata=metadata)\n', (2599, 2702), False, 'from packit.config import PackageConfig, JobConfig, JobType, JobConfigTriggerType\n'), ((3029, 3044), 'packit_service.config.ServiceConfig', 'ServiceConfig', ([], {}), '()\n', (3042, 3044), False, 'from packit_service.config import ServiceConfig\n'), ((4031, 4042), 'packit_service.models.SRPMBuild', 'SRPMBuild', ([], {}), '()\n', (4040, 4042), False, 'from packit_service.models import CoprBuild, SRPMBuild\n'), ((4111, 4126), 'packit_service.models.CoprBuild', 'CoprBuild', ([], {'id': '(1)'}), '(id=1)\n', (4120, 4126), False, 'from packit_service.models import CoprBuild, SRPMBuild\n'), ((4989, 5000), 'packit_service.models.SRPMBuild', 'SRPMBuild', ([], {}), '()\n', (4998, 5000), False, 'from packit_service.models import CoprBuild, SRPMBuild\n'), ((5069, 5084), 'packit_service.models.CoprBuild', 'CoprBuild', ([], {'id': '(1)'}), '(id=1)\n', (5078, 5084), False, 'from packit_service.models import CoprBuild, SRPMBuild\n'), ((6133, 6144), 'packit_service.models.SRPMBuild', 'SRPMBuild', ([], {}), '()\n', (6142, 6144), False, 'from packit_service.models import CoprBuild, SRPMBuild\n'), ((6213, 6228), 'packit_service.models.CoprBuild', 'CoprBuild', ([], {'id': '(1)'}), '(id=1)\n', (6222, 6228), False, 'from packit_service.models import CoprBuild, SRPMBuild\n'), ((7271, 7282), 'packit_service.models.SRPMBuild', 'SRPMBuild', ([], {}), '()\n', (7280, 7282), False, 'from packit_service.models import CoprBuild, SRPMBuild\n'), ((7351, 7366), 'packit_service.models.CoprBuild', 'CoprBuild', ([], {'id': '(1)'}), '(id=1)\n', (7360, 7366), False, 'from packit_service.models import CoprBuild, SRPMBuild\n'), ((7988, 7999), 'packit_service.models.SRPMBuild', 'SRPMBuild', ([], {}), '()\n', (7997, 7999), False, 'from packit_service.models import CoprBuild, SRPMBuild\n'), ((8068, 8083), 'packit_service.models.CoprBuild', 'CoprBuild', ([], {'id': '(1)'}), '(id=1)\n', (8077, 8083), False, 'from packit_service.models import CoprBuild, SRPMBuild\n'), ((9475, 9490), 'packit_service.models.SRPMBuild', 'SRPMBuild', ([], {'id': '(2)'}), '(id=2)\n', (9484, 9490), False, 'from packit_service.models import CoprBuild, SRPMBuild\n'), ((9559, 9574), 'packit_service.models.CoprBuild', 'CoprBuild', ([], {'id': '(1)'}), '(id=1)\n', (9568, 9574), False, 'from packit_service.models import CoprBuild, SRPMBuild\n'), ((10309, 10320), 'packit_service.models.SRPMBuild', 'SRPMBuild', ([], {}), '()\n', (10318, 10320), False, 'from packit_service.models import CoprBuild, SRPMBuild\n'), ((10389, 10404), 'packit_service.models.CoprBuild', 'CoprBuild', ([], {'id': '(1)'}), '(id=1)\n', (10398, 10404), False, 'from packit_service.models import CoprBuild, SRPMBuild\n'), ((2873, 2888), 'packit_service.config.ServiceConfig', 'ServiceConfig', ([], {}), '()\n', (2886, 2888), False, 'from packit_service.config import ServiceConfig\n'), ((2954, 2966), 'ogr.abstract.GitService', 'GitService', ([], {}), '()\n', (2964, 2966), False, 'from ogr.abstract import GitProject, GitService, CommitStatus\n'), ((3888, 3912), 'flexmock.flexmock', 'flexmock', (['RedisCoprBuild'], {}), '(RedisCoprBuild)\n', (3896, 3912), False, 'from flexmock import flexmock\n'), ((3975, 3994), 'flexmock.flexmock', 'flexmock', (['SRPMBuild'], {}), '(SRPMBuild)\n', (3983, 3994), False, 'from flexmock import flexmock\n'), ((4048, 4067), 'flexmock.flexmock', 'flexmock', (['CoprBuild'], {}), '(CoprBuild)\n', (4056, 4067), False, 'from flexmock import flexmock\n'), ((4132, 4151), 'flexmock.flexmock', 'flexmock', (['PackitAPI'], {}), '(PackitAPI)\n', (4140, 4151), False, 'from flexmock import flexmock\n'), ((4209, 4225), 'flexmock.flexmock', 'flexmock', (['Celery'], {}), '(Celery)\n', (4217, 4225), False, 'from flexmock import flexmock\n'), ((4846, 4870), 'flexmock.flexmock', 'flexmock', (['RedisCoprBuild'], {}), '(RedisCoprBuild)\n', (4854, 4870), False, 'from flexmock import flexmock\n'), ((4933, 4952), 'flexmock.flexmock', 'flexmock', (['SRPMBuild'], {}), '(SRPMBuild)\n', (4941, 4952), False, 'from flexmock import flexmock\n'), ((5006, 5025), 'flexmock.flexmock', 'flexmock', (['CoprBuild'], {}), '(CoprBuild)\n', (5014, 5025), False, 'from flexmock import flexmock\n'), ((5174, 5190), 'flexmock.flexmock', 'flexmock', (['Celery'], {}), '(Celery)\n', (5182, 5190), False, 'from flexmock import flexmock\n'), ((5990, 6014), 'flexmock.flexmock', 'flexmock', (['RedisCoprBuild'], {}), '(RedisCoprBuild)\n', (5998, 6014), False, 'from flexmock import flexmock\n'), ((6077, 6096), 'flexmock.flexmock', 'flexmock', (['SRPMBuild'], {}), '(SRPMBuild)\n', (6085, 6096), False, 'from flexmock import flexmock\n'), ((6150, 6169), 'flexmock.flexmock', 'flexmock', (['CoprBuild'], {}), '(CoprBuild)\n', (6158, 6169), False, 'from flexmock import flexmock\n'), ((6318, 6334), 'flexmock.flexmock', 'flexmock', (['Celery'], {}), '(Celery)\n', (6326, 6334), False, 'from flexmock import flexmock\n'), ((7128, 7152), 'flexmock.flexmock', 'flexmock', (['RedisCoprBuild'], {}), '(RedisCoprBuild)\n', (7136, 7152), False, 'from flexmock import flexmock\n'), ((7215, 7234), 'flexmock.flexmock', 'flexmock', (['SRPMBuild'], {}), '(SRPMBuild)\n', (7223, 7234), False, 'from flexmock import flexmock\n'), ((7288, 7307), 'flexmock.flexmock', 'flexmock', (['CoprBuild'], {}), '(CoprBuild)\n', (7296, 7307), False, 'from flexmock import flexmock\n'), ((7456, 7472), 'flexmock.flexmock', 'flexmock', (['Celery'], {}), '(Celery)\n', (7464, 7472), False, 'from flexmock import flexmock\n'), ((7845, 7869), 'flexmock.flexmock', 'flexmock', (['RedisCoprBuild'], {}), '(RedisCoprBuild)\n', (7853, 7869), False, 'from flexmock import flexmock\n'), ((7932, 7951), 'flexmock.flexmock', 'flexmock', (['SRPMBuild'], {}), '(SRPMBuild)\n', (7940, 7951), False, 'from flexmock import flexmock\n'), ((8005, 8024), 'flexmock.flexmock', 'flexmock', (['CoprBuild'], {}), '(CoprBuild)\n', (8013, 8024), False, 'from flexmock import flexmock\n'), ((8173, 8189), 'flexmock.flexmock', 'flexmock', (['Celery'], {}), '(Celery)\n', (8181, 8189), False, 'from flexmock import flexmock\n'), ((9332, 9356), 'flexmock.flexmock', 'flexmock', (['RedisCoprBuild'], {}), '(RedisCoprBuild)\n', (9340, 9356), False, 'from flexmock import flexmock\n'), ((9419, 9438), 'flexmock.flexmock', 'flexmock', (['SRPMBuild'], {}), '(SRPMBuild)\n', (9427, 9438), False, 'from flexmock import flexmock\n'), ((9496, 9515), 'flexmock.flexmock', 'flexmock', (['CoprBuild'], {}), '(CoprBuild)\n', (9504, 9515), False, 'from flexmock import flexmock\n'), ((9666, 9685), 'flexmock.flexmock', 'flexmock', (['PackitAPI'], {}), '(PackitAPI)\n', (9674, 9685), False, 'from flexmock import flexmock\n'), ((10166, 10190), 'flexmock.flexmock', 'flexmock', (['RedisCoprBuild'], {}), '(RedisCoprBuild)\n', (10174, 10190), False, 'from flexmock import flexmock\n'), ((10253, 10272), 'flexmock.flexmock', 'flexmock', (['SRPMBuild'], {}), '(SRPMBuild)\n', (10261, 10272), False, 'from flexmock import flexmock\n'), ((10326, 10345), 'flexmock.flexmock', 'flexmock', (['CoprBuild'], {}), '(CoprBuild)\n', (10334, 10345), False, 'from flexmock import flexmock\n'), ((10494, 10510), 'flexmock.flexmock', 'flexmock', (['Celery'], {}), '(Celery)\n', (10502, 10510), False, 'from flexmock import flexmock\n'), ((3276, 3300), 'flexmock.flexmock', 'flexmock', (['StatusReporter'], {}), '(StatusReporter)\n', (3284, 3300), False, 'from flexmock import flexmock\n'), ((3521, 3545), 'flexmock.flexmock', 'flexmock', (['StatusReporter'], {}), '(StatusReporter)\n', (3529, 3545), False, 'from flexmock import flexmock\n'), ((3806, 3826), 'flexmock.flexmock', 'flexmock', (['GitProject'], {}), '(GitProject)\n', (3814, 3826), False, 'from flexmock import flexmock\n'), ((4762, 4782), 'flexmock.flexmock', 'flexmock', (['GitProject'], {}), '(GitProject)\n', (4770, 4782), False, 'from flexmock import flexmock\n'), ((5090, 5109), 'flexmock.flexmock', 'flexmock', (['PackitAPI'], {}), '(PackitAPI)\n', (5098, 5109), False, 'from flexmock import flexmock\n'), ((5907, 5927), 'flexmock.flexmock', 'flexmock', (['GitProject'], {}), '(GitProject)\n', (5915, 5927), False, 'from flexmock import flexmock\n'), ((6234, 6253), 'flexmock.flexmock', 'flexmock', (['PackitAPI'], {}), '(PackitAPI)\n', (6242, 6253), False, 'from flexmock import flexmock\n'), ((7045, 7065), 'flexmock.flexmock', 'flexmock', (['GitProject'], {}), '(GitProject)\n', (7053, 7065), False, 'from flexmock import flexmock\n'), ((7372, 7391), 'flexmock.flexmock', 'flexmock', (['PackitAPI'], {}), '(PackitAPI)\n', (7380, 7391), False, 'from flexmock import flexmock\n'), ((7762, 7782), 'flexmock.flexmock', 'flexmock', (['GitProject'], {}), '(GitProject)\n', (7770, 7782), False, 'from flexmock import flexmock\n'), ((8089, 8108), 'flexmock.flexmock', 'flexmock', (['PackitAPI'], {}), '(PackitAPI)\n', (8097, 8108), False, 'from flexmock import flexmock\n'), ((9580, 9608), 'flexmock.flexmock', 'flexmock', (['sentry_integration'], {}), '(sentry_integration)\n', (9588, 9608), False, 'from flexmock import flexmock\n'), ((10083, 10103), 'flexmock.flexmock', 'flexmock', (['GitProject'], {}), '(GitProject)\n', (10091, 10103), False, 'from flexmock import flexmock\n'), ((10410, 10429), 'flexmock.flexmock', 'flexmock', (['PackitAPI'], {}), '(PackitAPI)\n', (10418, 10429), False, 'from flexmock import flexmock\n'), ((8621, 8641), 'flexmock.flexmock', 'flexmock', (['GitProject'], {}), '(GitProject)\n', (8629, 8641), False, 'from flexmock import flexmock\n'), ((8966, 8986), 'flexmock.flexmock', 'flexmock', (['GitProject'], {}), '(GitProject)\n', (8974, 8986), False, 'from flexmock import flexmock\n')]
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # import os import sys from sphinx.application import Sphinx sys.path.append(os.path.join(os.getcwd(), "..")) # -- Project information ----------------------------------------------------- project = "GHAS Compliance" copyright = "2021, GeekMasher" author = "GeekMasher" # The full version, including alpha/beta/rc tags release = "v1.5" # -- General configuration --------------------------------------------------- extensions = [ "myst_parser", "sphinx.ext.autodoc", "sphinx.ext.doctest", "sphinx.ext.todo", "sphinx.ext.coverage", "sphinx.ext.githubpages", "sphinx.ext.napoleon", "sphinx.ext.autosectionlabel", ] master_doc = "index" templates_path = ["_templates"] exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] source_suffix = { ".rst": "restructuredtext", ".txt": "markdown", ".md": "markdown", } pygments_style = "sphinx" # -- Options for HTML output ------------------------------------------------- html_theme = "alabaster" html_static_path = ["_static"] html_logo = "_static/SecurityPolicy.png" htmlhelp_basename = "GHASComplianceDoc" # -- Options for Napoleon output ------------------------------------------------ napoleon_google_docstring = True napoleon_numpy_docstring = False napoleon_include_init_with_doc = True napoleon_include_private_with_doc = False napoleon_include_special_with_doc = True napoleon_use_admonition_for_examples = True napoleon_use_admonition_for_notes = False napoleon_use_admonition_for_references = False napoleon_use_ivar = False napoleon_use_param = True napoleon_use_rtype = True # -- Options for manual page output ------------------------------------------ man_pages = [ (master_doc, "ghascompliance", "GHASCompliance Documentation", [author], 1) ] # -- Options for Texinfo output ---------------------------------------------- texinfo_documents = [ ( master_doc, "GHASCompliance", "GHASCompliance Documentation", author, "GHASCompliance", "One line description of project.", "Miscellaneous", ), ] # unwrap decorators def unwrap_decorators(): import sphinx.util.inspect as inspect import functools old_getargspec = inspect.getargspec def getargspec(x): return old_getargspec(getattr(x, "_original_function", x)) inspect.getargspec = getargspec old_update_wrapper = functools.update_wrapper def update_wrapper(wrapper, wrapped, *a, **kw): rv = old_update_wrapper(wrapper, wrapped, *a, **kw) rv._original_function = wrapped return rv functools.update_wrapper = update_wrapper unwrap_decorators() del unwrap_decorators def setup(app: Sphinx): def cut_module_meta(app, what, name, obj, options, lines): """Remove metadata from autodoc output.""" if what != "module": return lines[:] = [ line for line in lines if not line.startswith((":copyright:", ":license:")) ] app.connect("autodoc-process-docstring", cut_module_meta)
[ "os.getcwd" ]
[((642, 653), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (651, 653), False, 'import os\n')]
import unittest from collections import defaultdict import numpy as np import enstat.mean class Test_mean(unittest.TestCase): """ tests """ def test_scalar(self): """ Basic test of "mean" and "std" using a random sample. """ average = enstat.scalar() average.add_sample(np.array(1.0)) self.assertFalse(np.isnan(average.mean())) self.assertTrue(np.isnan(average.std())) average.add_sample(np.array(1.0)) self.assertFalse(np.isnan(average.mean())) self.assertFalse(np.isnan(average.std())) def test_scalar_division(self): """ Check for zero division. """ average = enstat.scalar() a = np.random.random(50 * 20).reshape(50, 20) for i in range(a.shape[0]): average.add_sample(a[i, :]) self.assertTrue(np.isclose(average.mean(), np.mean(a))) self.assertTrue(np.isclose(average.std(), np.std(a), rtol=1e-3)) def test_static(self): """ Basic test of "mean" and "std" using a random sample. """ average = enstat.static() a = np.random.random(35 * 50 * 20).reshape(35, 50, 20) for i in range(a.shape[0]): average.add_sample(a[i, :, :]) self.assertTrue(np.allclose(average.mean(), np.mean(a, axis=0))) self.assertTrue(np.allclose(average.std(), np.std(a, axis=0), rtol=5e-1, atol=1e-3)) self.assertTrue(average.shape() == a.shape[1:]) self.assertTrue(average.size() == np.prod(a.shape[1:])) def test_static_ravel(self): """ Like :py:func:`test_static` but with a test of `ravel`. """ arraylike = enstat.static() scalar = enstat.scalar() a = np.random.random(35 * 50 * 20).reshape(35, 50, 20) for i in range(a.shape[0]): arraylike.add_sample(a[i, :, :]) scalar.add_sample(a[i, :, :]) flat = arraylike.ravel() self.assertTrue(np.allclose(flat.mean(), np.mean(a))) self.assertTrue(np.allclose(flat.std(), np.std(a), rtol=5e-1, atol=1e-3)) self.assertTrue(np.allclose(flat.mean(), scalar.mean())) self.assertTrue(np.allclose(flat.std(), scalar.std(), rtol=5e-1, atol=1e-3)) def test_static_division(self): """ Check for zero division. """ average = enstat.static() average.add_sample(np.array([1.0])) self.assertFalse(np.isnan(average.mean())) self.assertTrue(np.isnan(average.std())) average.add_sample(np.array([1.0])) self.assertFalse(np.isnan(average.mean())) self.assertFalse(np.isnan(average.std())) def test_static_mask(self): average = enstat.static() a = np.random.random(35 * 50 * 20).reshape(35, 50, 20) m = np.random.random(35 * 50 * 20).reshape(35, 50, 20) > 0.8 for i in range(a.shape[0]): average.add_sample(a[i, :, :], m[i, :, :]) self.assertTrue( np.isclose( np.sum(average.first()) / np.sum(average.norm()), np.mean(a[np.logical_not(m)]), ) ) self.assertTrue( np.isclose( np.sum(average.first()) / np.sum(average.norm()), np.mean(a[np.logical_not(m)]), ) ) self.assertTrue(np.all(np.equal(average.norm(), np.sum(np.logical_not(m), axis=0)))) def test_dynamic1d(self): average = enstat.dynamic1d() average.add_sample(np.array([1, 2, 3])) average.add_sample(np.array([1, 2, 3])) average.add_sample(np.array([1, 2])) average.add_sample(np.array([1])) self.assertTrue(np.allclose(average.mean(), np.array([1, 2, 3]))) self.assertTrue(np.allclose(average.std(), np.array([0, 0, 0]))) self.assertEqual(average.shape(), (3,)) self.assertEqual(average.size(), 3) class Test_defaultdict(unittest.TestCase): """ functionality """ def test_scalar(self): average = defaultdict(enstat.scalar) a = np.random.random(50 * 20).reshape(50, 20) b = np.random.random(52 * 21).reshape(52, 21) for i in range(a.shape[0]): average["a"].add_sample(a[i, :]) for i in range(b.shape[0]): average["b"].add_sample(b[i, :]) self.assertTrue(np.isclose(average["a"].mean(), np.mean(a))) self.assertTrue(np.isclose(average["b"].mean(), np.mean(b))) def test_static(self): average = defaultdict(enstat.static) a = np.random.random(35 * 50 * 20).reshape(35, 50, 20) b = np.random.random(37 * 52 * 21).reshape(37, 52, 21) for i in range(a.shape[0]): average["a"].add_sample(a[i, :, :]) for i in range(b.shape[0]): average["b"].add_sample(b[i, :, :]) self.assertTrue(np.allclose(average["a"].mean(), np.mean(a, axis=0))) self.assertTrue(np.allclose(average["b"].mean(), np.mean(b, axis=0))) self.assertTrue(average["a"].shape() == a.shape[1:]) self.assertTrue(average["b"].shape() == b.shape[1:]) if __name__ == "__main__": unittest.main()
[ "numpy.mean", "numpy.prod", "numpy.random.random", "numpy.logical_not", "numpy.array", "collections.defaultdict", "numpy.std", "unittest.main" ]
[((5207, 5222), 'unittest.main', 'unittest.main', ([], {}), '()\n', (5220, 5222), False, 'import unittest\n'), ((4084, 4110), 'collections.defaultdict', 'defaultdict', (['enstat.scalar'], {}), '(enstat.scalar)\n', (4095, 4110), False, 'from collections import defaultdict\n'), ((4570, 4596), 'collections.defaultdict', 'defaultdict', (['enstat.static'], {}), '(enstat.static)\n', (4581, 4596), False, 'from collections import defaultdict\n'), ((333, 346), 'numpy.array', 'np.array', (['(1.0)'], {}), '(1.0)\n', (341, 346), True, 'import numpy as np\n'), ((477, 490), 'numpy.array', 'np.array', (['(1.0)'], {}), '(1.0)\n', (485, 490), True, 'import numpy as np\n'), ((2439, 2454), 'numpy.array', 'np.array', (['[1.0]'], {}), '([1.0])\n', (2447, 2454), True, 'import numpy as np\n'), ((2585, 2600), 'numpy.array', 'np.array', (['[1.0]'], {}), '([1.0])\n', (2593, 2600), True, 'import numpy as np\n'), ((3562, 3581), 'numpy.array', 'np.array', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (3570, 3581), True, 'import numpy as np\n'), ((3610, 3629), 'numpy.array', 'np.array', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (3618, 3629), True, 'import numpy as np\n'), ((3658, 3674), 'numpy.array', 'np.array', (['[1, 2]'], {}), '([1, 2])\n', (3666, 3674), True, 'import numpy as np\n'), ((3703, 3716), 'numpy.array', 'np.array', (['[1]'], {}), '([1])\n', (3711, 3716), True, 'import numpy as np\n'), ((736, 761), 'numpy.random.random', 'np.random.random', (['(50 * 20)'], {}), '(50 * 20)\n', (752, 761), True, 'import numpy as np\n'), ((907, 917), 'numpy.mean', 'np.mean', (['a'], {}), '(a)\n', (914, 917), True, 'import numpy as np\n'), ((970, 979), 'numpy.std', 'np.std', (['a'], {}), '(a)\n', (976, 979), True, 'import numpy as np\n'), ((1155, 1185), 'numpy.random.random', 'np.random.random', (['(35 * 50 * 20)'], {}), '(35 * 50 * 20)\n', (1171, 1185), True, 'import numpy as np\n'), ((1339, 1357), 'numpy.mean', 'np.mean', (['a'], {'axis': '(0)'}), '(a, axis=0)\n', (1346, 1357), True, 'import numpy as np\n'), ((1411, 1428), 'numpy.std', 'np.std', (['a'], {'axis': '(0)'}), '(a, axis=0)\n', (1417, 1428), True, 'import numpy as np\n'), ((1551, 1571), 'numpy.prod', 'np.prod', (['a.shape[1:]'], {}), '(a.shape[1:])\n', (1558, 1571), True, 'import numpy as np\n'), ((1778, 1808), 'numpy.random.random', 'np.random.random', (['(35 * 50 * 20)'], {}), '(35 * 50 * 20)\n', (1794, 1808), True, 'import numpy as np\n'), ((2037, 2047), 'numpy.mean', 'np.mean', (['a'], {}), '(a)\n', (2044, 2047), True, 'import numpy as np\n'), ((2098, 2107), 'numpy.std', 'np.std', (['a'], {}), '(a)\n', (2104, 2107), True, 'import numpy as np\n'), ((2785, 2815), 'numpy.random.random', 'np.random.random', (['(35 * 50 * 20)'], {}), '(35 * 50 * 20)\n', (2801, 2815), True, 'import numpy as np\n'), ((3771, 3790), 'numpy.array', 'np.array', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (3779, 3790), True, 'import numpy as np\n'), ((3844, 3863), 'numpy.array', 'np.array', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (3852, 3863), True, 'import numpy as np\n'), ((4124, 4149), 'numpy.random.random', 'np.random.random', (['(50 * 20)'], {}), '(50 * 20)\n', (4140, 4149), True, 'import numpy as np\n'), ((4178, 4203), 'numpy.random.random', 'np.random.random', (['(52 * 21)'], {}), '(52 * 21)\n', (4194, 4203), True, 'import numpy as np\n'), ((4441, 4451), 'numpy.mean', 'np.mean', (['a'], {}), '(a)\n', (4448, 4451), True, 'import numpy as np\n'), ((4510, 4520), 'numpy.mean', 'np.mean', (['b'], {}), '(b)\n', (4517, 4520), True, 'import numpy as np\n'), ((4610, 4640), 'numpy.random.random', 'np.random.random', (['(35 * 50 * 20)'], {}), '(35 * 50 * 20)\n', (4626, 4640), True, 'import numpy as np\n'), ((4673, 4703), 'numpy.random.random', 'np.random.random', (['(37 * 52 * 21)'], {}), '(37 * 52 * 21)\n', (4689, 4703), True, 'import numpy as np\n'), ((4952, 4970), 'numpy.mean', 'np.mean', (['a'], {'axis': '(0)'}), '(a, axis=0)\n', (4959, 4970), True, 'import numpy as np\n'), ((5030, 5048), 'numpy.mean', 'np.mean', (['b'], {'axis': '(0)'}), '(b, axis=0)\n', (5037, 5048), True, 'import numpy as np\n'), ((2848, 2878), 'numpy.random.random', 'np.random.random', (['(35 * 50 * 20)'], {}), '(35 * 50 * 20)\n', (2864, 2878), True, 'import numpy as np\n'), ((3139, 3156), 'numpy.logical_not', 'np.logical_not', (['m'], {}), '(m)\n', (3153, 3156), True, 'import numpy as np\n'), ((3326, 3343), 'numpy.logical_not', 'np.logical_not', (['m'], {}), '(m)\n', (3340, 3343), True, 'import numpy as np\n'), ((3435, 3452), 'numpy.logical_not', 'np.logical_not', (['m'], {}), '(m)\n', (3449, 3452), True, 'import numpy as np\n')]
"""Script for testing selfies against large datasets. """ import argparse import pathlib import pandas as pd from rdkit import Chem from tqdm import tqdm import selfies as sf parser = argparse.ArgumentParser() parser.add_argument("--data_path", type=str, default="version.smi.gz") parser.add_argument("--col_name", type=str, default="isosmiles") parser.add_argument("--sep", type=str, default=r"\s+") parser.add_argument("--start_from", type=int, default=0) args = parser.parse_args() TEST_DIR = pathlib.Path(__file__).parent TEST_SET_PATH = TEST_DIR / "test_sets" / args.data_path ERROR_LOG_DIR = TEST_DIR / "error_logs" ERROR_LOG_DIR.mkdir(exist_ok=True, parents=True) def make_reader(): return pd.read_csv(TEST_SET_PATH, sep=args.sep, chunksize=10000) def roundtrip_translation(): sf.set_semantic_constraints("hypervalent") n_entries = 0 for chunk in make_reader(): n_entries += len(chunk) pbar = tqdm(total=n_entries) reader = make_reader() error_log = open(ERROR_LOG_DIR / f"{TEST_SET_PATH.stem}.txt", "a+") curr_idx = 0 for chunk_idx, chunk in enumerate(reader): for in_smiles in chunk[args.col_name]: pbar.update(1) curr_idx += 1 if curr_idx < args.start_from: continue in_smiles = in_smiles.strip() mol = Chem.MolFromSmiles(in_smiles, sanitize=True) if (mol is None) or ("*" in in_smiles): continue try: selfies = sf.encoder(in_smiles, strict=True) out_smiles = sf.decoder(selfies) except (sf.EncoderError, sf.DecoderError): error_log.write(in_smiles + "\n") tqdm.write(in_smiles) continue if not is_same_mol(in_smiles, out_smiles): error_log.write(in_smiles + "\n") tqdm.write(in_smiles) error_log.close() def is_same_mol(smiles1, smiles2): try: can_smiles1 = Chem.CanonSmiles(smiles1) can_smiles2 = Chem.CanonSmiles(smiles2) return can_smiles1 == can_smiles2 except Exception: return False if __name__ == "__main__": roundtrip_translation()
[ "pandas.read_csv", "argparse.ArgumentParser", "pathlib.Path", "tqdm.tqdm.write", "tqdm.tqdm", "rdkit.Chem.MolFromSmiles", "rdkit.Chem.CanonSmiles", "selfies.decoder", "selfies.set_semantic_constraints", "selfies.encoder" ]
[((188, 213), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (211, 213), False, 'import argparse\n'), ((501, 523), 'pathlib.Path', 'pathlib.Path', (['__file__'], {}), '(__file__)\n', (513, 523), False, 'import pathlib\n'), ((708, 765), 'pandas.read_csv', 'pd.read_csv', (['TEST_SET_PATH'], {'sep': 'args.sep', 'chunksize': '(10000)'}), '(TEST_SET_PATH, sep=args.sep, chunksize=10000)\n', (719, 765), True, 'import pandas as pd\n'), ((801, 843), 'selfies.set_semantic_constraints', 'sf.set_semantic_constraints', (['"""hypervalent"""'], {}), "('hypervalent')\n", (828, 843), True, 'import selfies as sf\n'), ((938, 959), 'tqdm.tqdm', 'tqdm', ([], {'total': 'n_entries'}), '(total=n_entries)\n', (942, 959), False, 'from tqdm import tqdm\n'), ((2008, 2033), 'rdkit.Chem.CanonSmiles', 'Chem.CanonSmiles', (['smiles1'], {}), '(smiles1)\n', (2024, 2033), False, 'from rdkit import Chem\n'), ((2056, 2081), 'rdkit.Chem.CanonSmiles', 'Chem.CanonSmiles', (['smiles2'], {}), '(smiles2)\n', (2072, 2081), False, 'from rdkit import Chem\n'), ((1355, 1399), 'rdkit.Chem.MolFromSmiles', 'Chem.MolFromSmiles', (['in_smiles'], {'sanitize': '(True)'}), '(in_smiles, sanitize=True)\n', (1373, 1399), False, 'from rdkit import Chem\n'), ((1521, 1555), 'selfies.encoder', 'sf.encoder', (['in_smiles'], {'strict': '(True)'}), '(in_smiles, strict=True)\n', (1531, 1555), True, 'import selfies as sf\n'), ((1585, 1604), 'selfies.decoder', 'sf.decoder', (['selfies'], {}), '(selfies)\n', (1595, 1604), True, 'import selfies as sf\n'), ((1895, 1916), 'tqdm.tqdm.write', 'tqdm.write', (['in_smiles'], {}), '(in_smiles)\n', (1905, 1916), False, 'from tqdm import tqdm\n'), ((1726, 1747), 'tqdm.tqdm.write', 'tqdm.write', (['in_smiles'], {}), '(in_smiles)\n', (1736, 1747), False, 'from tqdm import tqdm\n')]
from typing import List, Optional # NOQA import chainer from chainer import cuda from chainer import functions from chainer import links import numpy # NOQA class Set2Set(chainer.Chain): r"""MPNN subsubmodule for readout part. See: <NAME>+, \ Order Matters: Sequence to sequence for sets. November 2015. `arXiv:1511.06391 <https://arxiv.org/abs/1511.06391>` Args: in_channels (int): dimension of input feature vector n_layers (int): number of LSTM layers Returns (chainer.Variable): Output feature vector: (minibatch, in_channels * 2) """ def __init__(self, in_channels, n_layers=1): # type: (int, int) -> None super(Set2Set, self).__init__() with self.init_scope(): self.lstm_layer = links.NStepLSTM( n_layers=n_layers, in_size=in_channels * 2, out_size=in_channels, dropout=0) self.in_channels = in_channels self.n_layers = n_layers self.hx = None # type: Optional[chainer.Variable] self.cx = None # type: Optional[chainer.Variable] self.q_star = None # type: Optional[List] def __call__(self, h): # type: (chainer.Variable) -> chainer.Variable xp = cuda.get_array_module(h) mb, node, ch = h.shape # type: int, int, int if self.q_star is None: self.q_star = [ xp.zeros((1, self.in_channels * 2)).astype('f') for _ in range(mb) ] self.hx, self.cx, q = self.lstm_layer(self.hx, self.cx, self.q_star) # self.hx: (mb, mb, ch) # self.cx: (mb, mb, ch) # q: List[(1, ch) * mb] q = functions.stack(q) # q: (mb, 1, ch) q_ = functions.transpose(q, axes=(0, 2, 1)) # q_: (mb, ch, 1) e = functions.matmul(h, q_) # e: (mb, node, 1) a = functions.softmax(e) # a: (mb, node, 1) a = functions.broadcast_to(a, h.shape) # a: (mb, node, ch) r = functions.sum((a * h), axis=1, keepdims=True) # r: (mb, 1, ch) q_star_ = functions.concat((q, r), axis=2) # q_star_: (mb, 1, ch*2) self.q_star = functions.separate(q_star_) return functions.reshape(q_star_, (mb, ch * 2)) def reset_state(self): # type: () -> None self.hx = None self.cx = None self.q_star = None
[ "chainer.functions.transpose", "chainer.functions.stack", "chainer.cuda.get_array_module", "chainer.functions.sum", "chainer.functions.concat", "chainer.functions.reshape", "chainer.functions.softmax", "chainer.functions.matmul", "chainer.links.NStepLSTM", "chainer.functions.separate", "chainer....
[((1290, 1314), 'chainer.cuda.get_array_module', 'cuda.get_array_module', (['h'], {}), '(h)\n', (1311, 1314), False, 'from chainer import cuda\n'), ((1727, 1745), 'chainer.functions.stack', 'functions.stack', (['q'], {}), '(q)\n', (1742, 1745), False, 'from chainer import functions\n'), ((1777, 1815), 'chainer.functions.transpose', 'functions.transpose', (['q'], {'axes': '(0, 2, 1)'}), '(q, axes=(0, 2, 1))\n', (1796, 1815), False, 'from chainer import functions\n'), ((1847, 1870), 'chainer.functions.matmul', 'functions.matmul', (['h', 'q_'], {}), '(h, q_)\n', (1863, 1870), False, 'from chainer import functions\n'), ((1903, 1923), 'chainer.functions.softmax', 'functions.softmax', (['e'], {}), '(e)\n', (1920, 1923), False, 'from chainer import functions\n'), ((1956, 1990), 'chainer.functions.broadcast_to', 'functions.broadcast_to', (['a', 'h.shape'], {}), '(a, h.shape)\n', (1978, 1990), False, 'from chainer import functions\n'), ((2024, 2067), 'chainer.functions.sum', 'functions.sum', (['(a * h)'], {'axis': '(1)', 'keepdims': '(True)'}), '(a * h, axis=1, keepdims=True)\n', (2037, 2067), False, 'from chainer import functions\n'), ((2106, 2138), 'chainer.functions.concat', 'functions.concat', (['(q, r)'], {'axis': '(2)'}), '((q, r), axis=2)\n', (2122, 2138), False, 'from chainer import functions\n'), ((2187, 2214), 'chainer.functions.separate', 'functions.separate', (['q_star_'], {}), '(q_star_)\n', (2205, 2214), False, 'from chainer import functions\n'), ((2230, 2270), 'chainer.functions.reshape', 'functions.reshape', (['q_star_', '(mb, ch * 2)'], {}), '(q_star_, (mb, ch * 2))\n', (2247, 2270), False, 'from chainer import functions\n'), ((795, 892), 'chainer.links.NStepLSTM', 'links.NStepLSTM', ([], {'n_layers': 'n_layers', 'in_size': '(in_channels * 2)', 'out_size': 'in_channels', 'dropout': '(0)'}), '(n_layers=n_layers, in_size=in_channels * 2, out_size=\n in_channels, dropout=0)\n', (810, 892), False, 'from chainer import links\n')]
"""Console script for kanbanflow_prj_selector.""" import sys import click from .kanbanflow_prj_selector import start @click.command() @click.option('-f', '--board-token-path', help='Input file with board tokens to fetch', required=True) def main(board_token_path): """Console script for kanbanflow_prj_selector.""" start(board_token_path) return 0 if __name__ == "__main__": sys.exit(main()) # pragma: no cover
[ "click.option", "click.command" ]
[((121, 136), 'click.command', 'click.command', ([], {}), '()\n', (134, 136), False, 'import click\n'), ((138, 244), 'click.option', 'click.option', (['"""-f"""', '"""--board-token-path"""'], {'help': '"""Input file with board tokens to fetch"""', 'required': '(True)'}), "('-f', '--board-token-path', help=\n 'Input file with board tokens to fetch', required=True)\n", (150, 244), False, 'import click\n')]
# # Copyright (C) 2014-2015 # <NAME> (<EMAIL>) # # 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 2, 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 XBMC; see the file COPYING. If not, write to # the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. # http://www.gnu.org/copyleft/gpl.html # import xbmcgui import xbmcaddon class Viewer(xbmcgui.WindowXMLDialog): ACTION_EXIT = (9, 10, 247, 275, 61467, 216, 257, 61448) def __init__(self, *args, **kwargs): pass def onInit(self): self.getControl(1000).setImage(self.fanart) self.getControl(1100).setImage(self.thumb) self.setFocus(self.getControl(2000)) def onClick(self, controlId): self.close() pass def onFocus(self, controlId): pass def onAction(self, action): actionId = action.getId() buttonId = action.getButtonCode() if buttonId in self.ACTION_EXIT or actionId in self.ACTION_EXIT: self.close() if actionId != 107: self.close() def show(fanart, thumb, addon=None): try: if addon: path = xbmcaddon.Addon(addon).getAddonInfo('path') else: path = xbmcaddon.Addon().getAddonInfo('path') v = Viewer('viewer.xml', path, 'Default') v.fanart = fanart v.thumb = thumb v.doModal() del v except: pass
[ "xbmcaddon.Addon" ]
[((1630, 1652), 'xbmcaddon.Addon', 'xbmcaddon.Addon', (['addon'], {}), '(addon)\n', (1645, 1652), False, 'import xbmcaddon\n'), ((1707, 1724), 'xbmcaddon.Addon', 'xbmcaddon.Addon', ([], {}), '()\n', (1722, 1724), False, 'import xbmcaddon\n')]
import csv import os from os import mkdir from os.path import isdir from datetime import datetime import ast from configuration import Config conf = Config() traj_j = [] policy_per_plot = [] plot_policy = [] traj_j_ID = [] CSV_DIRECTORY_NAME = "Flights_trajectories" BP_DIRECTORY_NAME = 'Best_policy/' myfile = "./Best_policy/trajectory.csv" myfile_plot = "./Best_policy/policy_per_plot_.csv" if not isdir(CSV_DIRECTORY_NAME): mkdir(CSV_DIRECTORY_NAME) if not isdir(BP_DIRECTORY_NAME): mkdir(BP_DIRECTORY_NAME) if os.path.isfile(myfile): with open('./Best_policy/trajectory.csv', 'r', newline='') as file: myreader = csv.reader(file, delimiter='-') traj_csv = [] for rows in myreader: traj_csv.append([int(x) for x in rows]) #print(traj_csv) else: traj_csv = [] # DIRECTORIES: MAP_DATA_DIR = "./map_data/" MAP_STATUS_DIR = "./map_status/" INITIAL_USERS_DIR = "./initial_users/" AGENTS_DIR = "./scenario_agents" # FILES: OBS_POINTS_LIST = "obs_points.npy" POINTS_MATRIX = "points_matrix.npy" CS_POINTS = "cs_points.npy" ENODEB_POINT = "eNB_point.npy" HOSP_POINTS = "hosp_points.npy" PRIORITIES_POINTS = "priorities_points.npy" CELLS_MATRIX = "cells_matrix.npy" OBS_CELLS = "obs_cells.npy" CS_CELLS = "cs_cells.npy" ENB_CELLS = "enb_cells.npy" HOSP_CELLS = "hosp_cells.npy" PRIORITIES_CELLS = "priorities_cells.npy" POINTS_STATUS_MATRIX = "points_status_matrix.npy" CELLS_STATUS_MATRIX = "cells_status_matrix.npy" PERCEIVED_STATUS_MATRIX = "perceived_status_matrix.npy" INITIAL_USERS = "initial_users.npy" INITIAL_CENTROIDS = "initial_centroids.npy" INITIAL_CLUSTERS_RADIUSES = "initial_clusters_radiuses.npy" INITIAL_CLUSTERER = "initial_clusterer.npy" INITIAL_USERS_CLUSTERS = "initial_users_clusters.npy" AGENTS = "agents.npy" #CSV-------------------------------------------------------------------------------------------------------------------- dir_mission = "/Mission_"+str(datetime.now().strftime('%Y-%m-%d %H:%M:%S')) def generate_single_trajectory(csv_filename, csv_dir, data): out = open('./' + csv_dir + '/' + csv_filename, 'a') #print(data, "data") for row in data: for column in row: out.write('%d, ' % column) out.write('\n') out.close() num_trajectories = 1 def generate_trajectories(name, data): csv_dir = str(CSV_DIRECTORY_NAME+"/MissionStart"+ '_' +str(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))\ .replace("-", "_")\ .replace(":", "_")\ .replace(".", "")\ .replace(" ", "--").strip() ) mkdir(csv_dir) for i in range(0,num_trajectories): csv_filename=csv_dir+"/"+"flight_"+str(i+1) generate_single_trajectory(name, csv_dir, data) return None def CSV_writer(csv_filename, data): with open('./' + BP_DIRECTORY_NAME + csv_filename, 'a', newline='') as file: mywriter = csv.writer(file, delimiter='-') mywriter.writerows(data) def policy_per_plot_(): with open('Best_policy/policy_per_plot_.csv', 'r', newline='') as file: myreader = csv.reader(file, delimiter=',') buffer = [] policy_plot = [] for rows in myreader: # ok.append([int(x) for x in rows]) for i in range(len(rows)): #print(rows[i]) buffer.append(ast.literal_eval(rows[i])) policy_plot.append(list(buffer)) buffer = [] #print(policy_plot, "policy_plot") '''if policy_plot == []: pass else: print(policy_plot) del policy_plot[-1]''' return policy_plot if os.path.isfile(myfile_plot): agents_paths = policy_per_plot_() print("agents_paths", agents_paths) else: pass
[ "configuration.Config", "csv.writer", "os.path.isfile", "datetime.datetime.now", "ast.literal_eval", "os.path.isdir", "os.mkdir", "csv.reader" ]
[((150, 158), 'configuration.Config', 'Config', ([], {}), '()\n', (156, 158), False, 'from configuration import Config\n'), ((520, 542), 'os.path.isfile', 'os.path.isfile', (['myfile'], {}), '(myfile)\n', (534, 542), False, 'import os\n'), ((3616, 3643), 'os.path.isfile', 'os.path.isfile', (['myfile_plot'], {}), '(myfile_plot)\n', (3630, 3643), False, 'import os\n'), ((405, 430), 'os.path.isdir', 'isdir', (['CSV_DIRECTORY_NAME'], {}), '(CSV_DIRECTORY_NAME)\n', (410, 430), False, 'from os.path import isdir\n'), ((432, 457), 'os.mkdir', 'mkdir', (['CSV_DIRECTORY_NAME'], {}), '(CSV_DIRECTORY_NAME)\n', (437, 457), False, 'from os import mkdir\n'), ((465, 489), 'os.path.isdir', 'isdir', (['BP_DIRECTORY_NAME'], {}), '(BP_DIRECTORY_NAME)\n', (470, 489), False, 'from os.path import isdir\n'), ((491, 515), 'os.mkdir', 'mkdir', (['BP_DIRECTORY_NAME'], {}), '(BP_DIRECTORY_NAME)\n', (496, 515), False, 'from os import mkdir\n'), ((2563, 2577), 'os.mkdir', 'mkdir', (['csv_dir'], {}), '(csv_dir)\n', (2568, 2577), False, 'from os import mkdir\n'), ((635, 666), 'csv.reader', 'csv.reader', (['file'], {'delimiter': '"""-"""'}), "(file, delimiter='-')\n", (645, 666), False, 'import csv\n'), ((2879, 2910), 'csv.writer', 'csv.writer', (['file'], {'delimiter': '"""-"""'}), "(file, delimiter='-')\n", (2889, 2910), False, 'import csv\n'), ((3064, 3095), 'csv.reader', 'csv.reader', (['file'], {'delimiter': '""","""'}), "(file, delimiter=',')\n", (3074, 3095), False, 'import csv\n'), ((1940, 1954), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (1952, 1954), False, 'from datetime import datetime\n'), ((3320, 3345), 'ast.literal_eval', 'ast.literal_eval', (['rows[i]'], {}), '(rows[i])\n', (3336, 3345), False, 'import ast\n'), ((2382, 2396), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (2394, 2396), False, 'from datetime import datetime\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- from client import Sample_Client import time import random # Create client client = Sample_Client('sample.cfg') time.sleep(5) # Simple exemple while(True): print('Sending updates') client.publish('Sensor1', 'L1_Volts', random.uniform(207,253)) client.publish('Sensor1', 'L2_Volts', random.uniform(207,253)) client.publish('Sensor1', 'L3_Volts', random.uniform(207,253)) client.publish('Sensor1', 'L1_Amps', random.uniform(1,2)) client.publish('Sensor1', 'L2_Amps', random.uniform(1,2)) client.publish('Sensor1', 'L3_Amps', random.uniform(1,2)) client.publish('Sensor2', 'L1_Volts', random.uniform(207,253)) client.publish('Sensor2', 'L2_Volts', random.uniform(207,253)) client.publish('Sensor2', 'L3_Volts', random.uniform(207,253)) client.publish('Sensor2', 'L1_Amps', random.uniform(1,2)/2) client.publish('Sensor2', 'L2_Amps', random.uniform(1,2)/2) client.publish('Sensor2', 'L3_Amps', random.uniform(1,2)/2) time.sleep(60)
[ "random.uniform", "client.Sample_Client", "time.sleep" ]
[((133, 160), 'client.Sample_Client', 'Sample_Client', (['"""sample.cfg"""'], {}), "('sample.cfg')\n", (146, 160), False, 'from client import Sample_Client\n'), ((161, 174), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (171, 174), False, 'import time\n'), ((1021, 1035), 'time.sleep', 'time.sleep', (['(60)'], {}), '(60)\n', (1031, 1035), False, 'import time\n'), ((277, 301), 'random.uniform', 'random.uniform', (['(207)', '(253)'], {}), '(207, 253)\n', (291, 301), False, 'import random\n'), ((344, 368), 'random.uniform', 'random.uniform', (['(207)', '(253)'], {}), '(207, 253)\n', (358, 368), False, 'import random\n'), ((411, 435), 'random.uniform', 'random.uniform', (['(207)', '(253)'], {}), '(207, 253)\n', (425, 435), False, 'import random\n'), ((477, 497), 'random.uniform', 'random.uniform', (['(1)', '(2)'], {}), '(1, 2)\n', (491, 497), False, 'import random\n'), ((539, 559), 'random.uniform', 'random.uniform', (['(1)', '(2)'], {}), '(1, 2)\n', (553, 559), False, 'import random\n'), ((601, 621), 'random.uniform', 'random.uniform', (['(1)', '(2)'], {}), '(1, 2)\n', (615, 621), False, 'import random\n'), ((665, 689), 'random.uniform', 'random.uniform', (['(207)', '(253)'], {}), '(207, 253)\n', (679, 689), False, 'import random\n'), ((732, 756), 'random.uniform', 'random.uniform', (['(207)', '(253)'], {}), '(207, 253)\n', (746, 756), False, 'import random\n'), ((799, 823), 'random.uniform', 'random.uniform', (['(207)', '(253)'], {}), '(207, 253)\n', (813, 823), False, 'import random\n'), ((865, 885), 'random.uniform', 'random.uniform', (['(1)', '(2)'], {}), '(1, 2)\n', (879, 885), False, 'import random\n'), ((929, 949), 'random.uniform', 'random.uniform', (['(1)', '(2)'], {}), '(1, 2)\n', (943, 949), False, 'import random\n'), ((993, 1013), 'random.uniform', 'random.uniform', (['(1)', '(2)'], {}), '(1, 2)\n', (1007, 1013), False, 'import random\n')]
# -*- coding:utf-8 -*- """ 外键关联相关的选项: - model: 关联的资产Model - field:关联的字段,这个字段必须是unique,默认可选择id - on_delete: 当关联的外键删除的时候的操作:cascade | set_null | disable - on_update: 当关联的外键修改的时候: cascade | disable 这些功能/约束,都是用代码逻辑来实现的,其实尽量不要使用外键: 少用的话,其实可以把约束放到业务代码中 """ from cmdb.types.base import BaseType # 注意别循环引用了 from cmdb.models import Model, Field, Instance, Value class ForeignKey(BaseType): """ 外键类型 """ def stringify(self, value): return str(self.validate(data=value)) def destringify(self, value): return self.validate(data=value) def validate(self, data): """ 验证数据 :param data: :return: """ # 如果是唯一的那么就需要加锁(因为校验一般是插入/更新的时候才校验) # 1. 先校验Model model_code = self.option.get('model', None) if not model_code: raise ValueError('ForeinKey需要关联Model') model = Model.objects.filter(code=model_code).first() if not model: raise ValueError("没有{}类型的Model".format(model_code)) # 2. 校验Field field_code = self.option.get('field', None) if not field_code: raise ValueError('ForeinKey需要设置关联的field') if field_code == 'id': value = Instance.objects.filter(model=model, id=int(data), deleted=False).first() if not value: raise ValueError("对象({})不存在".format(data)) else: return data else: # 获取ID field = Field.objects.filter(model=model, code=field_code).first() if not field: raise ValueError('{}不存在字段{}'.format(model_code, field_code)) # 3. 开始校验值 value = Value.objects.filter(model=model, field=field, value=str(data)).first() if not value: raise ValueError('值为{}的{}不存在'.format(data, model_code)) else: return data
[ "cmdb.models.Field.objects.filter", "cmdb.models.Model.objects.filter" ]
[((885, 922), 'cmdb.models.Model.objects.filter', 'Model.objects.filter', ([], {'code': 'model_code'}), '(code=model_code)\n', (905, 922), False, 'from cmdb.models import Model, Field, Instance, Value\n'), ((1481, 1531), 'cmdb.models.Field.objects.filter', 'Field.objects.filter', ([], {'model': 'model', 'code': 'field_code'}), '(model=model, code=field_code)\n', (1501, 1531), False, 'from cmdb.models import Model, Field, Instance, Value\n')]
# !/usr/bin/env python # -*- coding: utf-8 -*- import threading import time import urllib2 # SELECT "bmember" as type, COUNT(*) AS bmember FROM bmember WHERE isDownPics=0 # UNION ALL SELECT "memberby " as type, COUNT(*) AS memberby FROM memberby # UNION ALL SELECT "membercontact" as type, COUNT(*) AS membercontact FROM membercontact # UNION ALL SELECT "memberlevel" as type, COUNT(*) AS memberlevel FROM memberlevel # UNION ALL SELECT "member " as type, COUNT(*) AS member FROM member # cd ~/tt # nohup python a.py> output10.html 2>&1 & def getHtml(url): header = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:48.0) Gecko/20100101 Firefox/48.0"} request = urllib2.Request(url=url, headers=header) # 模拟浏览器进行访问 response = urllib2.urlopen(request) text = response.read() return text def spider(): while True: html = getHtml("http://travelling.chinesecompanion.com/index.php/index/spby/pics?isShowPic=no&limit=1") print(html) time.sleep(1) if __name__ == '__main__': t = [] for index in range(10): t.append(threading.Thread(target=spider)) for index in range(len(t)): t[index].start() for index in range(len(t)): t[index].join()
[ "urllib2.Request", "threading.Thread", "urllib2.urlopen", "time.sleep" ]
[((729, 769), 'urllib2.Request', 'urllib2.Request', ([], {'url': 'url', 'headers': 'header'}), '(url=url, headers=header)\n', (744, 769), False, 'import urllib2\n'), ((798, 822), 'urllib2.urlopen', 'urllib2.urlopen', (['request'], {}), '(request)\n', (813, 822), False, 'import urllib2\n'), ((1038, 1051), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (1048, 1051), False, 'import time\n'), ((1137, 1168), 'threading.Thread', 'threading.Thread', ([], {'target': 'spider'}), '(target=spider)\n', (1153, 1168), False, 'import threading\n')]
import sys, psycopg2, psycopg2.extras def generate(user_id, db): try: with db.cursor(cursor_factory = psycopg2.extras.DictCursor) as cursor: cursor.execute(""" INSERT INTO minicloud_auths (user_id) VALUES (%s) RETURNING token """, [int(user_id)]) data = cursor.fetchone() db.commit() return data['token'] except Exception as e: db.rollback() sys.stderr('%s\n' % 'No token generated!') return None def revoke(user_id, db): try: with db.cursor(cursor_factory = psycopg2.extras.DictCursor) as cursor: cursor.execute(""" DELETE FROM minicloud_auths WHERE user_id = %s """, [user_id]) db.commit() sys.stderr.write('X-Auth-Token revoked\n') return True except Exception as e: db.rollback() sys.stderr.write('Revoke X-Auth-Token failed: %s\n' % str(e)) return False
[ "sys.stderr.write", "sys.stderr" ]
[((449, 491), 'sys.stderr', 'sys.stderr', (["('%s\\n' % 'No token generated!')"], {}), "('%s\\n' % 'No token generated!')\n", (459, 491), False, 'import sys, psycopg2, psycopg2.extras\n'), ((778, 820), 'sys.stderr.write', 'sys.stderr.write', (['"""X-Auth-Token revoked\n"""'], {}), "('X-Auth-Token revoked\\n')\n", (794, 820), False, 'import sys, psycopg2, psycopg2.extras\n')]
import graphene from app.models import User class RegisterMutation(graphene.Mutation): class Arguments(object): email = graphene.String() username = graphene.String() password = graphene.String() is_success = graphene.Boolean() message = graphene.String() @staticmethod def mutate(root, info, **kwargs): try: new_user = User(**kwargs) new_user.save() except Exception as e: print(str(e)) return RegisterMutation(is_success=False, message="Registration Failure") return RegisterMutation(is_success=True, message="Successfully registered")
[ "graphene.String", "app.models.User", "graphene.Boolean" ]
[((247, 265), 'graphene.Boolean', 'graphene.Boolean', ([], {}), '()\n', (263, 265), False, 'import graphene\n'), ((280, 297), 'graphene.String', 'graphene.String', ([], {}), '()\n', (295, 297), False, 'import graphene\n'), ((137, 154), 'graphene.String', 'graphene.String', ([], {}), '()\n', (152, 154), False, 'import graphene\n'), ((174, 191), 'graphene.String', 'graphene.String', ([], {}), '()\n', (189, 191), False, 'import graphene\n'), ((211, 228), 'graphene.String', 'graphene.String', ([], {}), '()\n', (226, 228), False, 'import graphene\n'), ((391, 405), 'app.models.User', 'User', ([], {}), '(**kwargs)\n', (395, 405), False, 'from app.models import User\n')]
from init_repo import init_repo def find_commit(repo, local_repo, version, branch='master'): """ Find commit with specified version in the DESCRIPTION file in the xcms repo This function checkout to specified version :param repo: git.repo.base.Repo - repository object :param local_repo: str - path to the local repository :param version: str - necessary version :param branch: str - in which branch to search :return: str - necessary commit sha """ # Description file path description_path = local_repo / 'DESCRIPTION' # Find commit with desired version in DESCRIPTION file for commit in repo.iter_commits(branch): # Checkout previous version repo.git.checkout(commit) # Inspect DESCRIPTION in the previous commit with open(description_path) as description: description.readline() description = description.readline().strip() description = description.split(': ')[1] print(description) # Stop if we found commit with desired version if description == version: sha = commit.hexsha print(f'version {version} was found in the {sha} commit') print('try to build it in the correspondent image') return sha raise ValueError(f'{version} was not found') if __name__ == '__main__': version = '3.0.0' path = '~/skoltech/aspire/server/different_xcms' # Load from github repo_clone_url = 'https://github.com/sneumann/xcms.git' repo, local_repo = init_repo(repo_clone_url=repo_clone_url, path=path, version=version) find_commit(repo=repo, local_repo=local_repo, version=version, branch='master')
[ "init_repo.init_repo" ]
[((1601, 1669), 'init_repo.init_repo', 'init_repo', ([], {'repo_clone_url': 'repo_clone_url', 'path': 'path', 'version': 'version'}), '(repo_clone_url=repo_clone_url, path=path, version=version)\n', (1610, 1669), False, 'from init_repo import init_repo\n')]
"""Author: <NAME>, Copyright 2019""" import numpy as np import mineral as ml from mineral.core.samplers.sampler import Sampler class PathSampler(Sampler): def __init__( self, env, policies, buffers, time_skips=(1,), **kwargs ): Sampler.__init__(self, **kwargs) self.env = env.clone() self.master_policies = policies if isinstance(policies, list) else [policies] self.worker_policies = [p.clone() for p in self.master_policies] self.buffers = buffers if isinstance(buffers, list) else [buffers] self.num_levels = len(self.worker_policies) self.time_skips = tuple(time_skips) + tuple( 1 for _i in range(self.num_levels - len(time_skips))) self.push_through_hierarchy([[-1, {}, None, 0.0] for _level in range(self.num_levels)], 0, self.env.reset(), random=True) def push_through_hierarchy( self, hierarchy_samples, time_step, observation, random=False, ): for level in reversed(range(self.num_levels)): if time_step % np.prod(self.time_skips[:level + 1]) == 0: observation_for_this_level = {**observation} if level < self.num_levels - 1: observation_for_this_level["achieved_goal"] = observation_for_this_level observation_for_this_level["goal"] = hierarchy_samples[level + 1][2] policy_inputs = self.selector( level, observation_for_this_level)[np.newaxis, ...] if random: current_action = self.worker_policies[level].sample( policy_inputs)[0, ...].numpy() else: current_action = self.worker_policies[level].get_expected_value( policy_inputs)[0, ...].numpy() hierarchy_samples[level][0] += 1 hierarchy_samples[level][1] = observation_for_this_level hierarchy_samples[level][2] = current_action hierarchy_samples[level][3] = 0.0 if level > 0: hierarchy_samples[level][1]["induced_actions"] = [] hierarchy_samples[level][1]["induced_observations"] = [] if level < self.num_levels - 1: hierarchy_samples[level + 1][1]["induced_actions"].append(current_action) hierarchy_samples[level + 1][1]["induced_observations"].append(observation_for_this_level) def collect( self, num_samples_to_collect, random=False, save_paths=False, render=False, **render_kwargs ): all_rewards = [] for master_p, worker_p in zip(self.master_policies, self.worker_policies): master_p.copy_to(worker_p) for i in range(num_samples_to_collect): hierarchy_samples = [[-1, {}, None, 0.0] for _level in range(self.num_levels)] heads = [self.buffers[level].request_head() for level in range(self.num_levels)] observation = self.env.reset() for time_step in range(self.max_path_length): self.push_through_hierarchy(hierarchy_samples, time_step, observation, random=random) next_observation, reward, done, info = self.env.step(hierarchy_samples[0][2]) observation = next_observation all_rewards.append(reward) for level in range(self.num_levels): hierarchy_samples[level][3] += reward sample = hierarchy_samples[level][1] if (save_paths and ( "induced_actions" not in sample or len(sample["induced_actions"]) == self.time_skips[level])): self.buffers[level].insert_sample(heads[level], *hierarchy_samples[level]) relative_step = time_step // np.prod(self.time_skips[:level]) if level > 0: def relabel_achieved_goal(x, y): x[heads[level], ( relative_step - self.time_skips[level]):relative_step, ...] = y[np.newaxis, ...] ml.nested_apply( relabel_achieved_goal, self.buffers[level - 1].observations["achieved_goal"], hierarchy_samples[level - 1][1]) if render: self.env.render(**render_kwargs) if save_paths: self.increment() if done: break return all_rewards
[ "numpy.prod", "mineral.core.samplers.sampler.Sampler.__init__", "mineral.nested_apply" ]
[((315, 347), 'mineral.core.samplers.sampler.Sampler.__init__', 'Sampler.__init__', (['self'], {}), '(self, **kwargs)\n', (331, 347), False, 'from mineral.core.samplers.sampler import Sampler\n'), ((1194, 1230), 'numpy.prod', 'np.prod', (['self.time_skips[:level + 1]'], {}), '(self.time_skips[:level + 1])\n', (1201, 1230), True, 'import numpy as np\n'), ((4123, 4155), 'numpy.prod', 'np.prod', (['self.time_skips[:level]'], {}), '(self.time_skips[:level])\n', (4130, 4155), True, 'import numpy as np\n'), ((4492, 4623), 'mineral.nested_apply', 'ml.nested_apply', (['relabel_achieved_goal', "self.buffers[level - 1].observations['achieved_goal']", 'hierarchy_samples[level - 1][1]'], {}), "(relabel_achieved_goal, self.buffers[level - 1].observations\n ['achieved_goal'], hierarchy_samples[level - 1][1])\n", (4507, 4623), True, 'import mineral as ml\n')]
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2017-03-19 18:41 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('references', '0054_auto_20170308_2100'), ] operations = [ migrations.CreateModel( name='ObjectClass', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('major_object_class', models.CharField(db_index=True, max_length=2)), ('major_object_class_name', models.CharField(max_length=100)), ('object_class', models.CharField(db_index=True, max_length=3)), ('object_class_name', models.CharField(max_length=60)), ('direct_reimbursable', models.CharField(blank=True, db_index=True, max_length=1, null=True)), ('direct_reimbursable_name', models.CharField(blank=True, max_length=50, null=True)), ('create_date', models.DateTimeField(auto_now_add=True, null=True)), ('update_date', models.DateTimeField(auto_now=True, null=True)), ], options={ 'db_table': 'object_class', 'managed': True, }, ), migrations.AlterUniqueTogether( name='objectclass', unique_together=set([('object_class', 'direct_reimbursable')]), ), ]
[ "django.db.models.DateTimeField", "django.db.models.AutoField", "django.db.models.CharField" ]
[((403, 496), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (419, 496), False, 'from django.db import migrations, models\n'), ((534, 579), 'django.db.models.CharField', 'models.CharField', ([], {'db_index': '(True)', 'max_length': '(2)'}), '(db_index=True, max_length=2)\n', (550, 579), False, 'from django.db import migrations, models\n'), ((626, 658), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(100)'}), '(max_length=100)\n', (642, 658), False, 'from django.db import migrations, models\n'), ((694, 739), 'django.db.models.CharField', 'models.CharField', ([], {'db_index': '(True)', 'max_length': '(3)'}), '(db_index=True, max_length=3)\n', (710, 739), False, 'from django.db import migrations, models\n'), ((780, 811), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(60)'}), '(max_length=60)\n', (796, 811), False, 'from django.db import migrations, models\n'), ((854, 922), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'db_index': '(True)', 'max_length': '(1)', 'null': '(True)'}), '(blank=True, db_index=True, max_length=1, null=True)\n', (870, 922), False, 'from django.db import migrations, models\n'), ((970, 1024), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(50)', 'null': '(True)'}), '(blank=True, max_length=50, null=True)\n', (986, 1024), False, 'from django.db import migrations, models\n'), ((1059, 1109), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now_add': '(True)', 'null': '(True)'}), '(auto_now_add=True, null=True)\n', (1079, 1109), False, 'from django.db import migrations, models\n'), ((1144, 1190), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now': '(True)', 'null': '(True)'}), '(auto_now=True, null=True)\n', (1164, 1190), False, 'from django.db import migrations, models\n')]
from importlib import import_module from django.db import models from django.db.models.signals import post_save from django.utils.translation import gettext_lazy as _ from django.utils.module_loading import import_string from django.conf import settings from django_otp import devices_for_user from .services import UsernameService, EmailService, PhoneService from .decorators import ( is_authenticated, is_admin, # is_custom_user, # EXAMPLE ) SERVICES = tuple(import_string(d) for d in tuple(getattr(settings, 'MULTAUTH_SERVICES', [ 'multauth.services.UsernameService', 'multauth.services.EmailService', 'multauth.services.PhoneService', ]))); mixin_classes = tuple( getattr(import_module(d.__module__), d.USER_MIXIN) for d in SERVICES ) if not mixin_classes: msg = _('At least one Service should be added (see MULTAUTH_SERVICES settings)') raise ValueError(msg) mixin_identifiers = tuple( c.IDENTIFIER_FIELD for c in SERVICES if getattr(c, 'IDENTIFIER_FIELD', None) ) if not mixin_identifiers: msg = _('At least one identifier should be declared (see Service.IDENTIFIER_FIELD attribute)') raise ValueError(msg) mixin_classes_username_fields = tuple( c.USERNAME_FIELD for c in mixin_classes if getattr(c, 'USERNAME_FIELD', None) ) mixin_username_field = ( mixin_classes_username_fields[0] if mixin_classes_username_fields else mixin_identifiers[0] ) mixin_meta_options = { 'abstract': True, 'unique_together': (mixin_identifiers,) # reserved # 'index_together': ...all possible combinations of two/three identifiers # reserved # 'constraints': ... probably } @classmethod def mixin_get_service_classes(cls): return list(SERVICES) @classmethod def mixin_get_service_class_by_identifier(cls, identifier): if identifier not in mixin_identifiers: return None return SERVICES[mixin_identifiers.index(identifier)] # todo: refactor, should be called for "updated" identifiers only @classmethod def mixin_post_save(cls, sender, instance, *args, **kwargs): """ Create or update services with identifiers """ user = instance identifiers = [x for x in instance.IDENTIFIERS if getattr(instance, x, None)] for identifier in identifiers: service_class = instance.get_service_class_by_identifier(identifier) if service_class._meta.abstract: continue values = {'user': user, identifier: getattr(user, identifier)} try: d = service_class.objects.get(**values) except service_class.DoesNotExist: d = None if not d: service_class.objects.create(**values) @classmethod def mixin_post_create(cls, sender, instance, created, *args, **kwargs): """ Create or update services without indetifiers """ if not created: return user = instance service_classes = tuple( c for c in SERVICES if not getattr(c, 'IDENTIFIER_FIELD', None) ) for service_class in service_classes: values = {'user': user} try: d = service_class.objects.get(**values) except service_class.DoesNotExist: d = None if not d: service_class.objects.create(**values) def mixin_get_services(self, confirmed=None): # to think: can be sorted by order in the settings return devices_for_user(self, confirmed) UserServicesMixin = type( 'UserServicesMixin', mixin_classes, { '__module__': 'multauth', 'Meta': type('Meta', (object,), mixin_meta_options), 'USERNAME_FIELD': mixin_username_field, 'IDENTIFIERS': tuple(set(list(mixin_identifiers) + [mixin_username_field])), # drop duplicates '_post_save': mixin_post_save, '_post_create': mixin_post_create, 'get_service_classes': mixin_get_service_classes, 'get_service_class_by_identifier': mixin_get_service_class_by_identifier, 'get_services': mixin_get_services, } ) post_save.connect(UserServicesMixin._post_save, sender=settings.AUTH_USER_MODEL) post_save.connect(UserServicesMixin._post_create, sender=settings.AUTH_USER_MODEL) class IsAuthenticatedMixin(object): @classmethod def as_view(cls, **initkwargs): view = super(IsAuthenticatedMixin, cls).as_view(**initkwargs) return is_authenticated(view) class IsAdminMixin(object): @classmethod def as_view(cls, **initkwargs): view = super(IsAdminMixin, cls).as_view(**initkwargs) return is_admin(view) # EXAMPLE # class IsCustomUserMixin(object): # @classmethod # def as_view(cls, **initkwargs): # view = super(IsCustomUserMixin, cls).as_view(**initkwargs) # return is_custom_user(view)
[ "importlib.import_module", "django_otp.devices_for_user", "django.db.models.signals.post_save.connect", "django.utils.translation.gettext_lazy", "django.utils.module_loading.import_string" ]
[((4009, 4094), 'django.db.models.signals.post_save.connect', 'post_save.connect', (['UserServicesMixin._post_save'], {'sender': 'settings.AUTH_USER_MODEL'}), '(UserServicesMixin._post_save, sender=settings.AUTH_USER_MODEL\n )\n', (4026, 4094), False, 'from django.db.models.signals import post_save\n'), ((4090, 4177), 'django.db.models.signals.post_save.connect', 'post_save.connect', (['UserServicesMixin._post_create'], {'sender': 'settings.AUTH_USER_MODEL'}), '(UserServicesMixin._post_create, sender=settings.\n AUTH_USER_MODEL)\n', (4107, 4177), False, 'from django.db.models.signals import post_save\n'), ((805, 879), 'django.utils.translation.gettext_lazy', '_', (['"""At least one Service should be added (see MULTAUTH_SERVICES settings)"""'], {}), "('At least one Service should be added (see MULTAUTH_SERVICES settings)')\n", (806, 879), True, 'from django.utils.translation import gettext_lazy as _\n'), ((1054, 1147), 'django.utils.translation.gettext_lazy', '_', (['"""At least one identifier should be declared (see Service.IDENTIFIER_FIELD attribute)"""'], {}), "('At least one identifier should be declared (see Service.IDENTIFIER_FIELD attribute)'\n )\n", (1055, 1147), True, 'from django.utils.translation import gettext_lazy as _\n'), ((3374, 3407), 'django_otp.devices_for_user', 'devices_for_user', (['self', 'confirmed'], {}), '(self, confirmed)\n', (3390, 3407), False, 'from django_otp import devices_for_user\n'), ((477, 493), 'django.utils.module_loading.import_string', 'import_string', (['d'], {}), '(d)\n', (490, 493), False, 'from django.utils.module_loading import import_string\n'), ((709, 736), 'importlib.import_module', 'import_module', (['d.__module__'], {}), '(d.__module__)\n', (722, 736), False, 'from importlib import import_module\n')]
from __future__ import unicode_literals import unittest from mock import Mock from mopidy.models import Ref from mopidy_oe1.library import OE1LibraryProvider, OE1LibraryUri, OE1UriType class OE1LibraryUriTest(unittest.TestCase): def test_parse_root_uri(self): uri = 'oe1:directory' result = OE1LibraryUri.parse(uri) self.assertEqual(result.uri_type, OE1UriType.ROOT) def test_parse_live_uri(self): uri = 'oe1:live' result = OE1LibraryUri.parse(uri) self.assertEqual(result.uri_type, OE1UriType.LIVE) def test_parse_campus_uri(self): uri = 'oe1:campus' result = OE1LibraryUri.parse(uri) self.assertEqual(result.uri_type, OE1UriType.CAMPUS) def test_parse_archive_uri(self): uri = 'oe1:archive' result = OE1LibraryUri.parse(uri) self.assertEqual(result.uri_type, OE1UriType.ARCHIVE) def test_parse_day_uri(self): uri = 'oe1:archive:20140914' result = OE1LibraryUri.parse(uri) self.assertEqual(result.uri_type, OE1UriType.ARCHIVE_DAY) self.assertEqual(result.day_id, '20140914') def test_parse_invalid_uri(self): uri = 'foo:bar' self.assertRaises(TypeError, OE1LibraryUri.parse, uri) def test_parse_item_uri(self): uri = 'oe1:archive:20140914:382176' result = OE1LibraryUri.parse(uri) self.assertEqual(result.uri_type, OE1UriType.ARCHIVE_ITEM) self.assertEqual(result.day_id, '20140914') self.assertEqual(result.item_id, '382176') def test_create_root_uri(self): parsed_uri = OE1LibraryUri(OE1UriType.ROOT) self.assertEqual(str(parsed_uri), 'oe1:directory') def test_create_live_uri(self): parsed_uri = OE1LibraryUri(OE1UriType.LIVE) self.assertEqual(str(parsed_uri), 'oe1:live') def test_create_campus_uri(self): parsed_uri = OE1LibraryUri(OE1UriType.CAMPUS) self.assertEqual(str(parsed_uri), 'oe1:campus') def test_create_archive_uri(self): parsed_uri = OE1LibraryUri(OE1UriType.ARCHIVE) self.assertEqual(str(parsed_uri), 'oe1:archive') def test_create_day_uri(self): parsed_uri = OE1LibraryUri(OE1UriType.ARCHIVE_DAY, '20140914') self.assertEqual(str(parsed_uri), 'oe1:archive:20140914') def test_create_item_uri(self): parsed_uri = OE1LibraryUri(OE1UriType.ARCHIVE_ITEM, '20140914', '382176') self.assertEqual(str(parsed_uri), 'oe1:archive:20140914:382176') class OE1LibraryProviderTest(unittest.TestCase): def setUp(self): self.client_mock = Mock() self.client_mock.get_days = Mock( return_value=[ {'id': '1', 'label': 'Day1'}, {'id': '2', 'label': 'Day2'} ] ) self.client_mock.get_day = Mock( return_value={ 'items': [ {'id': '1', 'time': '01:00', 'title': 'Item1'}, {'id': '2', 'time': '02:00', 'title': 'Item2'}, {'id': '3', 'time': '03:00', 'title': 'Item3'} ] } ) self.client_mock.get_item = Mock( return_value={'id': '1', 'time': '01:00', 'title': 'Item1'} ) self.library = OE1LibraryProvider(None, client=self.client_mock) def test_browse_invalid_uri(self): uri = 'foo:bar' result = self.library.browse(uri) self.assertEqual(result, []) def test_browse_unbrowsable_uri(self): uri = str(OE1LibraryUri(OE1UriType.LIVE)) result = self.library.browse(uri) self.assertEqual(result, []) def test_browse_root(self): uri = str(OE1LibraryUri(OE1UriType.ROOT)) result = self.library.browse(uri) self.assertEqual(len(result), 3) def test_browse_archive(self): uri = str(OE1LibraryUri(OE1UriType.ARCHIVE)) result = self.library.browse(uri) self.assertEqual(len(result), 2) self.assertEqual(result[0].type, Ref.DIRECTORY) self.assertEqual(result[0].uri, 'oe1:archive:1') self.assertEqual(result[0].name, 'Day1') def test_browse_archive_day(self): uri = str(OE1LibraryUri(OE1UriType.ARCHIVE_DAY, '20140914')) result = self.library.browse(uri) self.client_mock.get_day.assert_called_once_with('20140914') self.assertEqual(len(result), 3) self.assertEqual(result[0].type, Ref.TRACK) self.assertEqual(result[0].uri, 'oe1:archive:20140914:1') self.assertEqual(result[0].name, '01:00: Item1') def test_lookup_invalid_uri(self): uri = 'foo:bar' result = self.library.lookup(uri) self.assertEqual(result, []) def test_browse_unlookable_uri(self): uri = str(OE1LibraryUri(OE1UriType.ROOT)) result = self.library.lookup(uri) self.assertEqual(result, []) def test_lookup_live(self): uri = str(OE1LibraryUri(OE1UriType.LIVE)) result = self.library.lookup(uri) self.assertEqual(len(result), 1) self.assertEqual(result[0].uri, uri) self.assertEqual(result[0].name, 'Live') def test_lookup_campus(self): uri = str(OE1LibraryUri(OE1UriType.CAMPUS)) result = self.library.lookup(uri) self.assertEqual(len(result), 1) self.assertEqual(result[0].uri, uri) self.assertEqual(result[0].name, 'Campus') def test_lookup_archive_day(self): uri = str(OE1LibraryUri(OE1UriType.ARCHIVE_DAY, '20140914')) result = self.library.lookup(uri) self.client_mock.get_day.assert_called_once_with('20140914') self.assertEqual(len(result), 3) self.assertEqual(result[0].type, Ref.TRACK) self.assertEqual(result[0].uri, 'oe1:archive:20140914:1') self.assertEqual(result[0].name, '01:00: Item1') def test_lookup_archive_item(self): uri = str(OE1LibraryUri(OE1UriType.ARCHIVE_ITEM, '20140914', '1234567')) result = self.library.lookup(uri) self.client_mock.get_item.assert_called_once_with( '20140914', '1234567') self.assertEqual(len(result), 1) self.assertEqual(result[0].uri, 'oe1:archive:20140914:1') self.assertEqual(result[0].name, '01:00: Item1')
[ "mock.Mock", "mopidy_oe1.library.OE1LibraryUri", "mopidy_oe1.library.OE1LibraryProvider", "mopidy_oe1.library.OE1LibraryUri.parse" ]
[((317, 341), 'mopidy_oe1.library.OE1LibraryUri.parse', 'OE1LibraryUri.parse', (['uri'], {}), '(uri)\n', (336, 341), False, 'from mopidy_oe1.library import OE1LibraryProvider, OE1LibraryUri, OE1UriType\n'), ((479, 503), 'mopidy_oe1.library.OE1LibraryUri.parse', 'OE1LibraryUri.parse', (['uri'], {}), '(uri)\n', (498, 503), False, 'from mopidy_oe1.library import OE1LibraryProvider, OE1LibraryUri, OE1UriType\n'), ((645, 669), 'mopidy_oe1.library.OE1LibraryUri.parse', 'OE1LibraryUri.parse', (['uri'], {}), '(uri)\n', (664, 669), False, 'from mopidy_oe1.library import OE1LibraryProvider, OE1LibraryUri, OE1UriType\n'), ((815, 839), 'mopidy_oe1.library.OE1LibraryUri.parse', 'OE1LibraryUri.parse', (['uri'], {}), '(uri)\n', (834, 839), False, 'from mopidy_oe1.library import OE1LibraryProvider, OE1LibraryUri, OE1UriType\n'), ((991, 1015), 'mopidy_oe1.library.OE1LibraryUri.parse', 'OE1LibraryUri.parse', (['uri'], {}), '(uri)\n', (1010, 1015), False, 'from mopidy_oe1.library import OE1LibraryProvider, OE1LibraryUri, OE1UriType\n'), ((1357, 1381), 'mopidy_oe1.library.OE1LibraryUri.parse', 'OE1LibraryUri.parse', (['uri'], {}), '(uri)\n', (1376, 1381), False, 'from mopidy_oe1.library import OE1LibraryProvider, OE1LibraryUri, OE1UriType\n'), ((1610, 1640), 'mopidy_oe1.library.OE1LibraryUri', 'OE1LibraryUri', (['OE1UriType.ROOT'], {}), '(OE1UriType.ROOT)\n', (1623, 1640), False, 'from mopidy_oe1.library import OE1LibraryProvider, OE1LibraryUri, OE1UriType\n'), ((1758, 1788), 'mopidy_oe1.library.OE1LibraryUri', 'OE1LibraryUri', (['OE1UriType.LIVE'], {}), '(OE1UriType.LIVE)\n', (1771, 1788), False, 'from mopidy_oe1.library import OE1LibraryProvider, OE1LibraryUri, OE1UriType\n'), ((1903, 1935), 'mopidy_oe1.library.OE1LibraryUri', 'OE1LibraryUri', (['OE1UriType.CAMPUS'], {}), '(OE1UriType.CAMPUS)\n', (1916, 1935), False, 'from mopidy_oe1.library import OE1LibraryProvider, OE1LibraryUri, OE1UriType\n'), ((2053, 2086), 'mopidy_oe1.library.OE1LibraryUri', 'OE1LibraryUri', (['OE1UriType.ARCHIVE'], {}), '(OE1UriType.ARCHIVE)\n', (2066, 2086), False, 'from mopidy_oe1.library import OE1LibraryProvider, OE1LibraryUri, OE1UriType\n'), ((2201, 2250), 'mopidy_oe1.library.OE1LibraryUri', 'OE1LibraryUri', (['OE1UriType.ARCHIVE_DAY', '"""20140914"""'], {}), "(OE1UriType.ARCHIVE_DAY, '20140914')\n", (2214, 2250), False, 'from mopidy_oe1.library import OE1LibraryProvider, OE1LibraryUri, OE1UriType\n'), ((2375, 2435), 'mopidy_oe1.library.OE1LibraryUri', 'OE1LibraryUri', (['OE1UriType.ARCHIVE_ITEM', '"""20140914"""', '"""382176"""'], {}), "(OE1UriType.ARCHIVE_ITEM, '20140914', '382176')\n", (2388, 2435), False, 'from mopidy_oe1.library import OE1LibraryProvider, OE1LibraryUri, OE1UriType\n'), ((2643, 2649), 'mock.Mock', 'Mock', ([], {}), '()\n', (2647, 2649), False, 'from mock import Mock\n'), ((2686, 2765), 'mock.Mock', 'Mock', ([], {'return_value': "[{'id': '1', 'label': 'Day1'}, {'id': '2', 'label': 'Day2'}]"}), "(return_value=[{'id': '1', 'label': 'Day1'}, {'id': '2', 'label': 'Day2'}])\n", (2690, 2765), False, 'from mock import Mock\n'), ((2869, 3051), 'mock.Mock', 'Mock', ([], {'return_value': "{'items': [{'id': '1', 'time': '01:00', 'title': 'Item1'}, {'id': '2',\n 'time': '02:00', 'title': 'Item2'}, {'id': '3', 'time': '03:00',\n 'title': 'Item3'}]}"}), "(return_value={'items': [{'id': '1', 'time': '01:00', 'title': 'Item1'},\n {'id': '2', 'time': '02:00', 'title': 'Item2'}, {'id': '3', 'time':\n '03:00', 'title': 'Item3'}]})\n", (2873, 3051), False, 'from mock import Mock\n'), ((3210, 3275), 'mock.Mock', 'Mock', ([], {'return_value': "{'id': '1', 'time': '01:00', 'title': 'Item1'}"}), "(return_value={'id': '1', 'time': '01:00', 'title': 'Item1'})\n", (3214, 3275), False, 'from mock import Mock\n'), ((3322, 3371), 'mopidy_oe1.library.OE1LibraryProvider', 'OE1LibraryProvider', (['None'], {'client': 'self.client_mock'}), '(None, client=self.client_mock)\n', (3340, 3371), False, 'from mopidy_oe1.library import OE1LibraryProvider, OE1LibraryUri, OE1UriType\n'), ((3577, 3607), 'mopidy_oe1.library.OE1LibraryUri', 'OE1LibraryUri', (['OE1UriType.LIVE'], {}), '(OE1UriType.LIVE)\n', (3590, 3607), False, 'from mopidy_oe1.library import OE1LibraryProvider, OE1LibraryUri, OE1UriType\n'), ((3739, 3769), 'mopidy_oe1.library.OE1LibraryUri', 'OE1LibraryUri', (['OE1UriType.ROOT'], {}), '(OE1UriType.ROOT)\n', (3752, 3769), False, 'from mopidy_oe1.library import OE1LibraryProvider, OE1LibraryUri, OE1UriType\n'), ((3908, 3941), 'mopidy_oe1.library.OE1LibraryUri', 'OE1LibraryUri', (['OE1UriType.ARCHIVE'], {}), '(OE1UriType.ARCHIVE)\n', (3921, 3941), False, 'from mopidy_oe1.library import OE1LibraryProvider, OE1LibraryUri, OE1UriType\n'), ((4246, 4295), 'mopidy_oe1.library.OE1LibraryUri', 'OE1LibraryUri', (['OE1UriType.ARCHIVE_DAY', '"""20140914"""'], {}), "(OE1UriType.ARCHIVE_DAY, '20140914')\n", (4259, 4295), False, 'from mopidy_oe1.library import OE1LibraryProvider, OE1LibraryUri, OE1UriType\n'), ((4828, 4858), 'mopidy_oe1.library.OE1LibraryUri', 'OE1LibraryUri', (['OE1UriType.ROOT'], {}), '(OE1UriType.ROOT)\n', (4841, 4858), False, 'from mopidy_oe1.library import OE1LibraryProvider, OE1LibraryUri, OE1UriType\n'), ((4990, 5020), 'mopidy_oe1.library.OE1LibraryUri', 'OE1LibraryUri', (['OE1UriType.LIVE'], {}), '(OE1UriType.LIVE)\n', (5003, 5020), False, 'from mopidy_oe1.library import OE1LibraryProvider, OE1LibraryUri, OE1UriType\n'), ((5252, 5284), 'mopidy_oe1.library.OE1LibraryUri', 'OE1LibraryUri', (['OE1UriType.CAMPUS'], {}), '(OE1UriType.CAMPUS)\n', (5265, 5284), False, 'from mopidy_oe1.library import OE1LibraryProvider, OE1LibraryUri, OE1UriType\n'), ((5523, 5572), 'mopidy_oe1.library.OE1LibraryUri', 'OE1LibraryUri', (['OE1UriType.ARCHIVE_DAY', '"""20140914"""'], {}), "(OE1UriType.ARCHIVE_DAY, '20140914')\n", (5536, 5572), False, 'from mopidy_oe1.library import OE1LibraryProvider, OE1LibraryUri, OE1UriType\n'), ((5960, 6021), 'mopidy_oe1.library.OE1LibraryUri', 'OE1LibraryUri', (['OE1UriType.ARCHIVE_ITEM', '"""20140914"""', '"""1234567"""'], {}), "(OE1UriType.ARCHIVE_ITEM, '20140914', '1234567')\n", (5973, 6021), False, 'from mopidy_oe1.library import OE1LibraryProvider, OE1LibraryUri, OE1UriType\n')]
#! /usr/bin/env python # -*- coding: utf-8 -*- """Integrate two files known as 'packages.xml'. Usage: python combine_packages_xml.py FPATH_1 FPATH_2 >result.xml Description: The script reads FPATH_1 and updates the data with FPATH_2. Entries are sorted by 'version+language'. The file timestamp is set to 'now'. The result is printed to stdout. """ from __future__ import print_function from __future__ import absolute_import import codecs import datetime import re import sys import time if not __name__ == "__main__": print('Please run as main.') sys.exit(1) def usage(exitcode=0): print(__doc__) sys.exit(exitcode) def usage1(exitcode=1): lines = __doc__.split('\n') print('\n'.join(lines[2:4] + [' Try --help'])) sys.exit(exitcode) if len(sys.argv) == 1 or '--help' in sys.argv: usage() if len(sys.argv) != 3: usage1() fpath1 = sys.argv[1] fpath2 = sys.argv[2] unixtime = int(time.time()) dt = datetime.datetime.fromtimestamp(unixtime) datetimestr = dt.strftime('%Y-%m-%d %H:%M:%S') example_data = """ <?xml version="1.0" standalone="yes" ?> <documentationPackIndex> <meta> <timestamp>1493982096</timestamp> <date>2017-05-05 13:01:36</date> </meta> <languagePackIndex> <languagepack version="0.4.0" language="default"> <md5>7c5890efa98d8184f2004a5d219bb57b</md5> </languagepack> <languagepack version="0.5.0" language="default"> <md5>cad89b3359498d070e75247b9e974eb2</md5> </languagepack> <languagepack version="0.6.0" language="default"> <md5>fd8f805fef1bdf748de32e430ccd08d6</md5> </languagepack> <languagepack version="1.0.0" language="default"> <md5>c98885a6a82329c48d35ba1be06c62c2</md5> </languagepack> <languagepack version="1.1.0" language="default"> <md5>8a20f8337c2dd3cadeeab46544826177</md5> </languagepack> <languagepack version="1.1.0" language="fr_FR"> <md5>2725397412083343c57bad8a706257cf</md5> </languagepack> <languagepack version="1.1.1" language="default"> <md5>567f4fa8883766acf58ad529bd28f165</md5> </languagepack> <languagepack version="1.1.1" language="fr_FR"> <md5>20fd95af62d5bee7bab4b20e20752923</md5> </languagepack> <languagepack version="1.2.0" language="default"> <md5>d82077b4e25ebd4d3ff2d6568006310c</md5> </languagepack> <languagepack version="1.2.0" language="fr_FR"> <md5>a2fecd2e4a43e7103dca6a7800990519</md5> </languagepack> <languagepack version="1.2.1" language="default"> <md5>9c0d59e8ca0224417f4cc50d1137b989</md5> </languagepack> <languagepack version="1.2.1" language="fr_FR"> <md5>7b64db2f3632f15639c5c1b0b6853962</md5> </languagepack> <languagepack version="1.2.2" language="default"> <md5>5b269fc51aab30596267e40f65494ab3</md5> </languagepack> <languagepack version="1.2.2" language="fr_FR"> <md5>12cc312274ccc74836218a4a1c4fe367</md5> </languagepack> <languagepack version="1.3.0" language="default"> <md5>1b9ff0511b50f89220efa4dae402d7f2</md5> </languagepack> <languagepack version="1.3.0" language="fr_FR"> <md5>6ce32d8a414aaeabfa706483e7799b46</md5> </languagepack> <languagepack version="1.3.1" language="default"> <md5>13079fb01792655184bf71650938b308</md5> </languagepack> <languagepack version="1.3.1" language="fr_FR"> <md5>4edf4b024b394135152bd204bfaff2f5</md5> </languagepack> <languagepack version="1.3.2" language="default"> <md5>c6338fb4fc2e5178184cf6ad65eefcfe</md5> </languagepack> <languagepack version="1.3.2" language="fr_FR"> <md5>6a8ed5d22a808487a8217844f5b0c500</md5> </languagepack> <languagepack version="2.0.0" language="default"> <md5>1d079e747c8b2f4c0b589712c13427be</md5> </languagepack> <languagepack version="2.0.0" language="fr_FR"> <md5>c3cf49cfdc8a0e29d10832a4344e91e7</md5> </languagepack> <languagepack version="2.0.1" language="default"> <md5>76abdd02fa068e8074815b36d8e460d3</md5> </languagepack> <languagepack version="2.0.1" language="fr_FR"> <md5>4bf4dcda2a6e74d34479503543137ad5</md5> </languagepack> <languagepack version="2.1.0" language="default"> <md5>f08a233da48eacb10c47922805afd249</md5> </languagepack> <languagepack version="2.1.0" language="fr_FR"> <md5>6584398fcc9e7f5a546722da5a103d26</md5> </languagepack> <languagepack version="2.2.0" language="default"> <md5>b982d16982626a60d0afd175a42b8938</md5> </languagepack> <languagepack version="2.2.0" language="fr_FR"> <md5>7333f623ee0452401d653818c1e5a8de</md5> </languagepack> <languagepack version="2.2.1" language="default"> <md5>15c025915b4106418dabdb19ef67d24b</md5> </languagepack> <languagepack version="2.2.1" language="fr_FR"> <md5>d4160de05bde35f2217558b57adba429</md5> </languagepack> <languagepack version="2.2.2" language="default"> <md5>9af5abd5ebf7278bcc456ccc1cc23b63</md5> </languagepack> <languagepack version="2.2.2" language="fr_FR"> <md5>3609e8f2052ff03d27eabfd52991b9f8</md5> </languagepack> <languagepack version="2.2.3" language="default"> <md5>fe6d78a9e3deed8ff43f9424dd3272f7</md5> </languagepack> <languagepack version="2.2.3" language="fr_FR"> <md5>f39b898bf9efedfbbf8b670e7ce7bb88</md5> </languagepack> <languagepack version="2.3.0" language="default"> <md5>d4f85ecaf4f6a0c83cfcf5e68dcd7a0f</md5> </languagepack> <languagepack version="2.3.0" language="fr_FR"> <md5>37428948f560597acf8ed45fdfb3da98</md5> </languagepack> <languagepack version="2.3.1" language="default"> <md5>152b3e2f0645fd2e8c9c08fcc2e8862b</md5> </languagepack> <languagepack version="2.3.1" language="fr_FR"> <md5>c36846d36aea5225e54260892eccc24b</md5> </languagepack> <languagepack version="2.4.0" language="default"> <md5>e7db74af568ddc646ee6e7388dbbe110</md5> </languagepack> <languagepack version="2.4.0" language="fr_FR"> <md5>55dab560775a957acb32f3edb23d439a</md5> </languagepack> <languagepack version="2.5.0" language="default"> <md5>2d8aedc81bca14a3077a474299b64af6</md5> </languagepack> <languagepack version="2.5.0" language="fr_FR"> <md5>ebdcb836634fb3c0cb57d8b4d1c745da</md5> </languagepack> <languagepack version="2.5.1" language="default"> <md5>26ae6128e32b5e5567b4fb52f8b5a2d2</md5> </languagepack> <languagepack version="2.5.1" language="fr_FR"> <md5>c371f7323107d00de9c9172e5a51f05a</md5> </languagepack> </languagePackIndex> </documentationPackIndex> """ prolog_template = """\ <?xml version="1.0" standalone="yes" ?> <documentationPackIndex> <meta> <timestamp>%(unixtime)s</timestamp> <date>%(datetimestr)s</date> </meta> <languagePackIndex>""" languagepack = """\ <languagepack version="%(version)s" language="%(language)s"> <md5>%(md5)s</md5> </languagepack>""" epilog = """\ </languagePackIndex> </documentationPackIndex>""" re_obj = re.compile(''' <languagepack \\s+ version="(?P<version>\d+\.\d+\.\d+)" \\s+ language="(?P<language>[a-zA-Z-_]*)"\\s*. \\s*<md5>(?P<md5>[a-f0-9]*)</md5> ''', re.VERBOSE + re.DOTALL) def version_tuple(v): return tuple([int(part) for part in v.split('.') if part.isdigit()]) def version_cmp(a, b): return cmp(version_tuple(a), version_tuple(b)) def getversions(fpath): result = {} with codecs.open(fpath, 'r', 'utf-8') as f1: data = f1.read() for m in re_obj.finditer(data): k = '%s,%s' % (m.group('version'), m.group('language')) result[k] = { 'version': m.group('version'), 'language': m.group('language'), 'md5': m.group('md5') } return result def version_cmp(a, b): result = cmp(version_tuple(a[1]['version']), version_tuple(b[1]['version'])) if result == 0: result = cmp(a[1]['language'], b[1]['language']) return result versions1 = getversions(fpath1) versions2 = getversions(fpath2) versions3 = versions1.copy() versions3.update(versions2) print(prolog_template % {'unixtime': unixtime, 'datetimestr': datetimestr}) for k, v in sorted(list(versions3.items()), cmp=version_cmp): print(languagepack % v) print(epilog)
[ "datetime.datetime.fromtimestamp", "re.compile", "sys.exit", "codecs.open", "time.time" ]
[((964, 1005), 'datetime.datetime.fromtimestamp', 'datetime.datetime.fromtimestamp', (['unixtime'], {}), '(unixtime)\n', (995, 1005), False, 'import datetime\n'), ((6808, 7021), 're.compile', 're.compile', (['"""\n <languagepack\n \\\\s+\n version="(?P<version>\\\\d+\\\\.\\\\d+\\\\.\\\\d+)"\n \\\\s+\n language="(?P<language>[a-zA-Z-_]*)"\\\\s*.\n \\\\s*<md5>(?P<md5>[a-f0-9]*)</md5>\n"""', '(re.VERBOSE + re.DOTALL)'], {}), '(\n """\n <languagepack\n \\\\s+\n version="(?P<version>\\\\d+\\\\.\\\\d+\\\\.\\\\d+)"\n \\\\s+\n language="(?P<language>[a-zA-Z-_]*)"\\\\s*.\n \\\\s*<md5>(?P<md5>[a-f0-9]*)</md5>\n"""\n , re.VERBOSE + re.DOTALL)\n', (6818, 7021), False, 'import re\n'), ((578, 589), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (586, 589), False, 'import sys\n'), ((637, 655), 'sys.exit', 'sys.exit', (['exitcode'], {}), '(exitcode)\n', (645, 655), False, 'import sys\n'), ((771, 789), 'sys.exit', 'sys.exit', (['exitcode'], {}), '(exitcode)\n', (779, 789), False, 'import sys\n'), ((946, 957), 'time.time', 'time.time', ([], {}), '()\n', (955, 957), False, 'import time\n'), ((7229, 7261), 'codecs.open', 'codecs.open', (['fpath', '"""r"""', '"""utf-8"""'], {}), "(fpath, 'r', 'utf-8')\n", (7240, 7261), False, 'import codecs\n')]