text
stringlengths
0
1.05M
meta
dict
# Always prefer setuptools over distutils from setuptools import setup, find_packages import os import shutil with open('README.rst', encoding='utf-8') as fobj: LONG_DESCRIPTION = fobj.read() this_dir = os.getcwd() root_dir = os.path.dirname(this_dir) src_dir = os.path.join(root_dir, "www", "src") data_dir = os.path.join(this_dir, "data") # copy files from /www/src for fname in ["brython.js", "brython_stdlib.js", "unicode.txt"]: shutil.copyfile(os.path.join(src_dir, fname), os.path.join(data_dir, fname)) # copy demo.html with open(os.path.join(root_dir, 'www', 'demo.html'), encoding="utf-8") as f: demo = f.read() start_tag = "<!-- start copy -->" end_tag = "<!-- end copy -->" start = demo.find(start_tag) if start == -1: raise Exception("No tag <!-- start copy --> in demo.html") end = demo.find(end_tag) if end == -1: raise Exception("No tag <!-- end copy --> in demo.html") body = demo[start + len(start_tag) : end].strip() with open(os.path.join(data_dir, "demo.tmpl"), encoding="utf-8") as f: template = f.read() demo = template.replace("{{body}}", body) with open(os.path.join(data_dir, "demo.html"), "w", encoding="utf-8") as out: out.write(demo) setup( name='brython', version='3.5.2', description='Brython is an implementation of Python 3 running in the browser', long_description = LONG_DESCRIPTION, # The project's main homepage. url='http://brython.info', # Author details author='Pierre Quentel', author_email='quentel.pierre@orange.fr', packages = ['data', 'data.tools'], # Choose your license license='BSD', # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ # Indicate who your project is intended for 'Intended Audience :: Developers', 'Topic :: Software Development :: Interpreters', 'Operating System :: OS Independent', # Pick your license as you wish (should match "license" above) 'License :: OSI Approved :: BSD License', # 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 :: 3', ], # What does your project relate to? keywords='Python browser', py_modules=["brython", "list_modules", "server"], package_data={ 'data': [ 'README.txt', 'demo.html', 'brython.js', 'brython_stdlib.js', 'unicode.txt' ] } )
{ "repo_name": "jonathanverner/brython", "path": "setup/setup.py", "copies": "1", "size": "2571", "license": "bsd-3-clause", "hash": 993681513990764300, "line_mean": 26.0736842105, "line_max": 82, "alpha_frac": 0.6196032672, "autogenerated": false, "ratio": 3.479025710419486, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4598628977619486, "avg_score": null, "num_lines": null }
# Always prefer setuptools over distutils from setuptools import setup, find_packages setup( name='neoapi', # 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='2.0.1', description='A package for serializing json api compliant responses from neomodel StructuredNodes', # The project's main homepage. url='https://github.com/buckmaxwell/neoapi', # Author details author='Max Buck', author_email='maxbuckdeveloper@gmail.com', # Choose your license license='MIT', # 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', 'Topic :: Software Development :: Build Tools', # Pick your license as you wish (should match "license" above) 'License :: OSI Approved :: MIT License', # 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.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], # What does your project relate to? keywords='json api specification neomodel neo4j', # You can just specify the packages manually here if your project is # simple. Or you can use find_packages(). packages=find_packages(exclude=['contrib', 'docs', 'tests*']), # 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=['neomodel', 'py2neo', 'flask'], # If there are data files included in your packages that need to be # installed, specify them here. If using Python 2.6 or less, then these # have to be included in MANIFEST.in as well. include_package_data=True )
{ "repo_name": "buckmaxwell/neoapi", "path": "setup.py", "copies": "1", "size": "2529", "license": "mit", "hash": -5274118811599405000, "line_mean": 35.6666666667, "line_max": 103, "alpha_frac": 0.6599446422, "autogenerated": false, "ratio": 4.222036727879799, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5381981370079799, "avg_score": null, "num_lines": null }
# Always prefer setuptools over distutils from setuptools import setup, find_packages setup( name='pyjection', # 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='1.0.0', description='Pyjection is a lightweight python dependency injection library', # The project's main homepage. url='https://github.com/Darkheir/pyjection', # Author details author='Raphael Cohen', author_email='raphael.cohen.utt@gmail.com', # Choose your license license='MIT', # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 4 - Beta', 'Operating System :: OS Independent', 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries :: Python Modules', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Natural Language :: English', ], # What does your project relate to? keywords='dependency injection dependency-injection development', # You can just specify the packages manually here if your project is # simple. Or you can use find_packages(). packages=find_packages(exclude=['contrib', 'docs', 'tests*']), # List additional groups of dependencies here (e.g. development # dependencies). You can install these using the following syntax, # for example: # $ pip install -e .[dev,test] extras_require={ 'test': ['coverage'], }, )
{ "repo_name": "Darkheir/pyjection", "path": "setup.py", "copies": "1", "size": "1744", "license": "mit", "hash": 553665499728181250, "line_mean": 31.9056603774, "line_max": 81, "alpha_frac": 0.6599770642, "autogenerated": false, "ratio": 4.2227602905569, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.53827373547569, "avg_score": null, "num_lines": null }
# Always prefer setuptools over distutils from setuptools import setup, find_packages # Read in long_description from README.rst. By using a separate file, instead # of translating README.md, we can use different content on PyPI than on # GitHub. with open('README.rst') as readme_file: long_description = readme_file.read() # As PyPI only accepts PEP 440 non-local version strings, we need to strip # down the version generated for non-tagged commits. def version_config(): import os from setuptools_scm.version import postrelease_version if os.environ.get('TRAVIS_TAG'): return {'version_scheme': postrelease_version} # Use a version like 1.1.0.54 for commit with distance 54 from v1.1.0 tag def version_scheme(version): return postrelease_version(version).replace('post', '') def local_scheme(version): return '' return {'version_scheme': version_scheme, 'local_scheme': local_scheme} setup( # Name of project, see PEP 426 name='XD-Docker', # Short and long descriptions, will be displayed on PyPI. description='Python library for accessing Docker Remote API', long_description=long_description, url='https://github.com/XD-embedded/xd-docker', author='Esben Haabendal', author_email='esben@haabendal.dk', license='MIT', # Version number, see PEP 440 use_scm_version=version_config, 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', 'Topic :: Software Development :: Libraries :: Python Modules', # Pick your license as you wish (should match "license" above) 'License :: OSI Approved :: MIT License', # 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', 'Programming Language :: Python :: 3 :: Only', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], keywords='docker', packages=find_packages(exclude=['contrib', 'docs', 'tests']), # Run-time dependencies install_requires=['requests', 'requests-unixsocket', 'typing'], # Dependencies needed for setup.py to run setup_requires=['setuptools_scm'], )
{ "repo_name": "XD-embedded/xd-docker", "path": "setup.py", "copies": "2", "size": "2512", "license": "mit", "hash": 8508460761858989000, "line_mean": 35.4057971014, "line_max": 78, "alpha_frac": 0.6652070064, "autogenerated": false, "ratio": 4.158940397350993, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5824147403750993, "avg_score": null, "num_lines": null }
# Always prefer setuptools over distutils from setuptools import setup, find_packages scripts = [ 'scripts/upho_weights', 'scripts/upho_sf', 'scripts/upho_qpoints', 'scripts/upho_fit', ] setup( # This is the name of your project. The first time you publish this # package, this name will be registered for you. It will determine how # users can install this project, e.g.: # # $ pip install sampleproject # # And where it will live on PyPI: https://pypi.org/project/sampleproject/ # # There are some restrictions on what makes a valid project name # specification here: # https://packaging.python.org/specifications/core-metadata/#name name='upho', # Required # Versions should comply with PEP 440: # https://www.python.org/dev/peps/pep-0440/ # # 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.6.1', # Required # This should be a valid link to your project's main homepage. # # This field corresponds to the "Home-Page" metadata field: # https://packaging.python.org/specifications/core-metadata/#home-page-optional url='https://github.com/yuzie007/upho', # Optional # This should be your name or the name of the organization which owns the # project. author='Yuji Ikeda', # Optional # This should be a valid email address corresponding to the author listed # above. author_email='yuji.ikeda.ac.jp@gmail.com', # Optional # You can just specify package directories manually here if your project is # simple. Or you can use find_packages(). # # Alternatively, if you just want to distribute a single Python file, use # the `py_modules` argument instead as follows, which will expect a file # called `my_module.py` to exist: # # py_modules=["my_module"], # packages=find_packages(), # Required # This field lists other packages that your project depends on to run. # Any package you put here will be installed by pip when your project is # installed, so they must be valid existing projects. # # For an analysis of "install_requires" vs pip's requirements files see: # https://packaging.python.org/en/latest/requirements.html install_requires=['phonopy>=2.3.2'], # Optional scripts=scripts)
{ "repo_name": "yuzie007/ph_unfolder", "path": "setup.py", "copies": "1", "size": "2437", "license": "mit", "hash": -7936882558794953000, "line_mean": 36.4923076923, "line_max": 83, "alpha_frac": 0.6860894542, "autogenerated": false, "ratio": 3.8805732484076434, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5066662702607643, "avg_score": null, "num_lines": null }
# Always prefer setuptools over distutils from setuptools import setup, find_packages setup( name='drone-bci', # 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.0.1', description='Brain controlled drone', # The project's main homepage. url='https://github.com/Frijol/Drone-BCI', # Choose your license license='Apache 2.0', # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ # 3 - Alpha # 4 - Beta # 5 - Production/Stable 'Development Status :: 3 - Alpha', # Indicate who your project is intended for 'Intended Audience :: Developers', 'Topic :: Software Development :: Build Tools', # Pick your license as you wish (should match "license" above) 'License :: OSI Approved :: Apache 2.0 License', 'Programming Language :: Python :: 2.7', ], # What does your project relate to? keywords='dronedirect, bci', # You can just specify the packages manually here if your project is # simple. Or you can use find_packages(). packages=find_packages(), # 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=['dronekit'], )
{ "repo_name": "Frijol/Drone-BCI", "path": "setup.py", "copies": "1", "size": "1583", "license": "apache-2.0", "hash": 2413394663587194400, "line_mean": 30.66, "line_max": 79, "alpha_frac": 0.6582438408, "autogenerated": false, "ratio": 4.069408740359897, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 50 }
# Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path import re here = path.abspath(path.dirname(__file__)) def get_version(): return re.search("__version__ = \"([\d\.]+)\"", open("gdvfs.py").read()).groups()[0] # Get the long description from the relevant file with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='gdvfs', version=get_version(), description='A FUSE file system for Google Drive videos', long_description=long_description, url='https://github.com/wnielson/gdvfs', author='Weston Nielson', author_email='wnielson@github', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', ], keywords='Google Drive FUSE file system', py_modules=["gdvfs"], install_requires=[ 'fusepy', 'google-api-python-client'], package_data={ 'sample': ['gdvfs.conf'], }, entry_points={ 'console_scripts': [ 'gdvfs=gdvfs:main', ], }, )
{ "repo_name": "wnielson/gdvfs", "path": "setup.py", "copies": "1", "size": "1370", "license": "mit", "hash": -1747037791063200000, "line_mean": 27.5416666667, "line_max": 86, "alpha_frac": 0.6153284672, "autogenerated": false, "ratio": 3.816155988857939, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.49314844560579385, "avg_score": null, "num_lines": null }
# Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path here = path.abspath(path.dirname(__file__)) exec(open(path.join(here, 'esper_tool/version.py')).read()) def readme(): with open('README.rst') as f: return f.read() setup( name='esper-tool', # 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=__version__, description='Command line tool for accessing ESPER', long_description=readme(), # The project's main homepage. url='https://github.com/bryerton/esper-tool', # Author details author='Bryerton Shaw', author_email='bryerton@triumf.ca', # Choose your license license='MIT', # 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 :: 5 - Production/Stable', # Indicate who your project is intended for 'Intended Audience :: Science/Research', 'Environment :: Console', 'Topic :: System :: Networking', # Pick your license as you wish (should match "license" above) 'License :: OSI Approved :: MIT License', # 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='esper monitoring control experiments', # You can just specify the packages manually here if your project is # simple. Or you can use find_packages(). packages=['esper_tool'], # Alternatively, if you want to distribute just a my_module.py, uncomment # this: # py_modules=["my_module"], # 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=['requests', 'argparse', 'future'], # List additional groups of dependencies here (e.g. development # dependencies). You can install these using the following syntax, # for example: # $ pip install -e .[dev,test] # extras_require={ # 'dev': ['check-manifest'], # 'test': ['coverage'], # }, # If there are data files included in your packages that need to be # installed, specify them here. If using Python 2.6 or less, then these # have to be included in MANIFEST.in as well. package_data={ 'esper_tool': [], }, # Although 'package_data' is the preferred approach, in some case you may # need to place data files outside of your packages. See: # http://docs.python.org/3.4/distutils/setupscript.html#installing-additional-files # noqa # In this case, 'data_file' will be installed into '<sys.prefix>/my_data' # data_files=[('my_data', ['data/data_file'])], # To provide executable scripts, use entry points in preference to the # "scripts" keyword. Entry points provide cross-platform support and allow # pip to create the appropriate form of executable for the target platform. entry_points={ 'console_scripts': [ 'esper-tool = esper_tool.__main__:main' ] } )
{ "repo_name": "bryerton/esper-tool", "path": "setup.py", "copies": "1", "size": "3884", "license": "mit", "hash": -1073234486347852800, "line_mean": 33.6785714286, "line_max": 94, "alpha_frac": 0.6503604531, "autogenerated": false, "ratio": 4.054279749478079, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 112 }
# Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding from codecs import open as opn from os import path here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with opn(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup(name='lebot-cerebro', version='0.1.0dev8', description='Core engine for LeBot', long_description=long_description, classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', 'Topic :: Scientific/Engineering :: Artificial Intelligence', ], keywords=['Chat Bot, AI'], url='https://github.com/Le-Bot/cerebro', author='LeBot', author_email='sanket.upadhyay@infoud.co.in', license='MIT', packages=['cerebro']+find_packages(), package_data={'': ['*.csv'], 'cerebro.data': ['datasets/*.csv']}, install_requires=[ 'scikit-learn', 'scipy', 'numpy', 'pandas', ], test_suite='nose.collector', tests_require=['nose'], include_package_data=True, zip_safe=False)
{ "repo_name": "Le-Bot/cerebro", "path": "setup.py", "copies": "1", "size": "1272", "license": "mit", "hash": 2795401668090283500, "line_mean": 30.8, "line_max": 71, "alpha_frac": 0.6139937107, "autogenerated": false, "ratio": 3.7633136094674557, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.48773073201674555, "avg_score": null, "num_lines": null }
# Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path import fnmatch import os here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() # recursively find **.c under pydpi/src dpi_srcs = [] for root, dirnames, filenames in os.walk('pydpi/src'): for filename in fnmatch.filter(filenames, '*.c'): dpi_srcs.append(os.path.join(root, filename).replace('pydpi/','')) setup( name='python-svlog', # 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.1', description='Verilog development framework with DPI-python verification utils', long_description=long_description, # The project's main homepage. url='https://github.com/hchsiao/python-svlog', # Author details author='Hsiang-Chih Hsiao', author_email='hchsiao@vlsilab.ee.ncku.edu.tw', # Choose your license license='MIT', # 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 :: 2 - Pre-Alpha', # Indicate who your project is intended for 'Intended Audience :: Developers', 'Topic :: Software Development :: Code Generators', # Pick your license as you wish (should match "license" above) 'License :: OSI Approved :: MIT License', # 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', ], # What does your project relate to? keywords='sample setuptools development', # You can just specify the packages manually here if your project is # simple. Or you can use find_packages(). packages=find_packages(exclude=['contrib', 'docs', 'tests']), # Alternatively, if you want to distribute just a my_module.py, uncomment # this: # py_modules=["my_module"], # 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=['ruamel.yaml', 'anyconfig'], # If there are data files included in your packages that need to be # installed, specify them here. If using Python 2.6 or less, then these # have to be included in MANIFEST.in as well. package_data={ 'pydpi': ['templates/*'] + dpi_srcs, }, data_files=[ ('.', ['LICENSE']), ], # To provide executable scripts, use entry points in preference to the # "scripts" keyword. Entry points provide cross-platform support and allow # pip to create the appropriate form of executable for the target platform. entry_points={ 'console_scripts': [ 'pydpi-gen = pydpi.utils:run_gen', 'pydpi-gen-mod = pydpi.utils:run_gen_mod', 'pydpi-gen-param = pydpi.utils:run_gen_param', 'pydpi-build = pydpi.utils:run_build_bridge', 'pydpi-run = pydpi.utils:run_run', ], }, )
{ "repo_name": "hchsiao/python-svlog", "path": "setup.py", "copies": "1", "size": "3448", "license": "mit", "hash": 5882951908140390000, "line_mean": 32.8039215686, "line_max": 81, "alpha_frac": 0.6931554524, "autogenerated": false, "ratio": 3.7115177610333694, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4904673213433369, "avg_score": null, "num_lines": null }
# Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path import re here = path.abspath(path.dirname(__file__)) def get_version(filename): with open(filename) as fh: metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", fh.read())) return metadata['version'] # Get the long description from the README file with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='Transilien-Domoticz', # 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=get_version('Transilen_Domoticz/__init__.py'), description='A Python script for use transilien.com API with Domoticz.', long_description=long_description, # The project's main homepage. url='https://github.com/matleses/Transilien-Domoticz', # Author details author='Treussart Matthieu', author_email='matthieu@treussart.com', # Choose your license license='MIT', # 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 :: 5 - Production/Stable', # 'Environment :: Console', # Indicate who your project is intended for 'Intended Audience :: Developers', 'Topic :: Home Automation', # Pick your license as you wish (should match "license" above) 'License :: OSI Approved :: MIT License', # 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 :: 3', ], # What does your project relate to? keywords='Domoticz Transilien SNCF', # You can just specify the packages manually here if your project is # simple. Or you can use find_packages(). # packages=find_packages(exclude=['docs', 'tests', '.venv', '.idea', 'htmlcov']), # packages=['TransilienDomoticz'], packages=find_packages(), # Alternatively, if you want to distribute just a my_module.py, uncomment # this: # py_modules=["transilien"], # 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=['peppercorn'], include_package_data=True, # List additional groups of dependencies here (e.g. development # dependencies). You can install these using the following syntax, # for example: # $ pip install -e .[dev,test] # extras_require={ # 'dev': ['check-manifest'], # 'test': ['coverage'], # }, # If there are data files included in your packages that need to be # installed, specify them here. If using Python 2.6 or less, then these # have to be included in MANIFEST.in as well. # package_data={ # 'sample': ['package_data.dat'], # }, # Although 'package_data' is the preferred approach, in some case you may # need to place data files outside of your packages. See: # http://docs.python.org/3.4/distutils/setupscript.html#installing-additional-files # noqa # In this case, 'data_file' will be installed into '<sys.prefix>/my_data' # data_files=[('my_data', ['data/data_file'])], # To provide executable scripts, use entry points in preference to the # "scripts" keyword. Entry points provide cross-platform support and allow # pip to create the appropriate form of executable for the target platform. entry_points={ 'console_scripts': [ 'transilien = Transilien_Domoticz.transilien:transilien', ], }, )
{ "repo_name": "matleses/Transilien-Domoticz", "path": "setup.py", "copies": "1", "size": "4080", "license": "mit", "hash": -2763012461098788000, "line_mean": 34.7894736842, "line_max": 94, "alpha_frac": 0.6605392157, "autogenerated": false, "ratio": 3.870967741935484, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00010199918400652795, "num_lines": 114 }
# Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path import sys if sys.version_info < (3,5,0): sys.exit('It requires Python version 3.5.0 or higher.') here = path.abspath(path.dirname(__file__)) setup( name='logger', # 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='A simple logger with attachable handlers', long_description='', url='https://github.com/lablup/logger', author='Lablup Inc.', author_email='joongi@lablup.com', license='Apache 2.0', packages=find_packages(exclude=['contrib', 'docs', 'tests*']), # TODO: add aiobotocore if it becomes available in pip install_requires=['simplejson', 'toml', 'umsgpack', 'pyzmq', 'aiozmq', 'aiohttp'], extras_require={ 'dev': [], 'test': [], }, data_files=[], entry_points={ 'console_scripts': ['run-logger=logger:main'], }, )
{ "repo_name": "lablup/logger", "path": "setup.py", "copies": "1", "size": "1173", "license": "apache-2.0", "hash": 4337000819698303000, "line_mean": 28.325, "line_max": 86, "alpha_frac": 0.6589940324, "autogenerated": false, "ratio": 3.576219512195122, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.47352135445951216, "avg_score": null, "num_lines": null }
# Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path here = path.abspath(path.dirname(__file__)) # configure plugin name here PLUGIN_NAME = "son-mano-example-plugin-1" # generate a name without dashes PLUGIN_NAME_CLEAR = "son_mano_exampleplugin" # 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=PLUGIN_NAME_CLEAR, # 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.0.1', description='SONATA example plugin 1', long_description=long_description, # The project's main homepage. url='https://github.com/sonata-nfv/son-mano-framework/', # Author details author='SONATA', author_email='info@sonata-nfv.eu', # Choose your license license='Apache 2.0', packages=find_packages(), install_requires=['pika', 'pytest'], setup_requires=['pytest-runner'], # To provide executable scripts, use entry points in preference to the # "scripts" keyword. Entry points provide cross-platform support and allow # pip to create the appropriate form of executable for the target platform. entry_points={ 'console_scripts': [ '%s=%s.__main__:main' % (PLUGIN_NAME, PLUGIN_NAME_CLEAR), ], }, )
{ "repo_name": "sonata-nfv/son-tests", "path": "int-slm-infrabstractV1/test-trigger/setup/setup.py", "copies": "4", "size": "1568", "license": "apache-2.0", "hash": -5376673813529458000, "line_mean": 29.1730769231, "line_max": 79, "alpha_frac": 0.6926020408, "autogenerated": false, "ratio": 3.769230769230769, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.019230769230769232, "num_lines": 52 }
# Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding 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.rst'), encoding='utf-8') as f: # long_description = f.read() setup( name='extrom', # 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.2', description='ROM Extraction tool from archived ROM set file', # long_description=long_description, # The project's main homepage. url='https://github.com/masushin/extrom', # Author details author='masushin', author_email='shinsuke.masuda@gmail.com', # Choose your license license='MIT', # 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 :: Other Audience', 'Topic :: Games/Entertainment', # Pick your license as you wish (should match "license" above) 'License :: OSI Approved :: MIT License', # 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 :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], # What does your project relate to? keywords='rom extract tool', # You can just specify the packages manually here if your project is # simple. Or you can use find_packages(). packages=find_packages(), # Alternatively, if you want to distribute just a my_module.py, uncomment # this: # py_modules=["my_module"], # 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=['npyscreen'], # List additional groups of dependencies here (e.g. development # dependencies). You can install these using the following syntax, # for example: # $ pip install -e .[dev,test] # extras_require={ # 'dev': ['check-manifest'], # 'test': ['coverage'], # }, # If there are data files included in your packages that need to be # installed, specify them here. If using Python 2.6 or less, then these # have to be included in MANIFEST.in as well. # package_data={ # 'sample': ['package_data.dat'], # }, # Although 'package_data' is the preferred approach, in some case you may # need to place data files outside of your packages. See: # http://docs.python.org/3.4/distutils/setupscript.html#installing-additional-files # noqa # In this case, 'data_file' will be installed into '<sys.prefix>/my_data' # data_files=[('my_data', ['data/data_file'])], # To provide executable scripts, use entry points in preference to the # "scripts" keyword. Entry points provide cross-platform support and allow # pip to create the appropriate form of executable for the target platform. entry_points={ 'console_scripts': [ 'extrom=extrom.extrom:main', ], }, )
{ "repo_name": "masushin/extrom", "path": "setup.py", "copies": "1", "size": "3788", "license": "mit", "hash": 2764636454554167000, "line_mean": 35.0761904762, "line_max": 94, "alpha_frac": 0.653907075, "autogenerated": false, "ratio": 4.029787234042553, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5183694309042554, "avg_score": null, "num_lines": null }
# Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding 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.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='FacebookWebBot', version='1.1.0', description='A python library to automatize facebook without the official API', long_description=long_description, # The project's main homepage. url='https://github.com/hikaruAi/FacebookBot', # Author details author='Juan José Mendoza', author_email='contacto.juanmendoza@gmail.com', # Choose your license license='Apache License 2.0', # 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 :: 4 - Beta', # Indicate who your project is intended for 'Intended Audience :: Developers', 'Topic :: Home Automation', # Pick your license as you wish (should match "license" above) 'License :: OSI Approved :: Apache Software License', # 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 :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], # What does your project relate to? keywords='Automation, web, social network', # You can just specify the packages manually here if your project is # simple. Or you can use find_packages(). #packages=find_packages(exclude=['contrib', 'docs', 'tests']), # Alternatively, if you want to distribute just a my_module.py, uncomment # this: py_modules=["FacebookWebBot"], # 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=['selenium'], # List additional groups of dependencies here (e.g. development # dependencies). You can install these using the following syntax, # for example: # $ pip install -e .[dev,test] #extras_require={ # 'dev': ['check-manifest'], # 'test': ['coverage'], #}, # If there are data files included in your packages that need to be # installed, specify them here. If using Python 2.6 or less, then these # have to be included in MANIFEST.in as well. #package_data={ # 'sample': ['package_data.dat'], #}, # Although 'package_data' is the preferred approach, in some case you may # need to place data files outside of your packages. See: # http://docs.python.org/3.4/distutils/setupscript.html#installing-additional-files # noqa # In this case, 'data_file' will be installed into '<sys.prefix>/my_data' #data_files=[('my_data', ['data/data_file'])], # To provide executable scripts, use entry points in preference to the # "scripts" keyword. Entry points provide cross-platform support and allow # pip to create the appropriate form of executable for the target platform. #entry_points={ # 'console_scripts': [ # 'sample=sample:main', # ], #}, )
{ "repo_name": "hikaruAi/FacebookBot", "path": "setup.py", "copies": "1", "size": "3574", "license": "apache-2.0", "hash": -8821103810973147000, "line_mean": 34.73, "line_max": 94, "alpha_frac": 0.6593898685, "autogenerated": false, "ratio": 4.032731376975169, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.519212124547517, "avg_score": null, "num_lines": null }
# Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding #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.rst'), encoding='utf-8') as f: # long_description = f.read() setup( name='humanid', # 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='1.0', description='human readable unique-ish identifiers', long_description="", # The project's main homepage. url='https://github.com/balihoo/humanid', # Author details author='Balihoo', author_email='devall@balihoo.com', # Choose your license license='MIT License', # 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', 'Topic :: Software Development :: Build Tools', # Pick your license as you wish (should match "license" above) 'License :: OSI Approved :: MIT License', # 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.7', ], # What does your project relate to? keywords='', # You can just specify the packages manually here if your project is # simple. Or you can use find_packages(). # packages=find_packages(exclude=['contrib', 'docs', 'tests']), packages=['data'], # Alternatively, if you want to distribute just a my_module.py, uncomment # this: py_modules=["humanid"], # 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=[], # List additional groups of dependencies here (e.g. development # dependencies). You can install these using the following syntax, # for example: # $ pip install -e .[dev,test] extras_require={ 'dev': ['check-manifest'], 'test': ['coverage'], }, # If there are data files included in your packages that need to be # installed, specify them here. If using Python 2.6 or less, then these # have to be included in MANIFEST.in as well. package_data={ 'data': ['adjectives', 'ance', 'ence', 'ity', 'ment', 'ncy', 'ness', 'nouns', 'tent'] }, # Although 'package_data' is the preferred approach, in some case you may # need to place data files outside of your packages. See: # http://docs.python.org/3.4/distutils/setupscript.html#installing-additional-files # noqa # In this case, 'data_file' will be installed into '<sys.prefix>/my_data' data_files=[],#('my_data', ['data/data_file'])], # To provide executable scripts, use entry points in preference to the # "scripts" keyword. Entry points provide cross-platform support and allow # pip to create the appropriate form of executable for the target platform. entry_points={ # 'console_scripts': [ # 'sample=sample:main', # ], }, )
{ "repo_name": "balihoo/humanid", "path": "setup.py", "copies": "1", "size": "3698", "license": "mit", "hash": -8262746004217430000, "line_mean": 35.2549019608, "line_max": 97, "alpha_frac": 0.6454840454, "autogenerated": false, "ratio": 4.108888888888889, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5254372934288889, "avg_score": null, "num_lines": null }
# Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding 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.rst'), encoding='utf-8') as f: # long_description = f.read() setup( name='PenPen', # 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.1b1', description='Audio podcasting suite.', long_description=open('README.txt').read(), # The project's main homepage. url='https://github.com/ryanmeasel/PenPen', # Author details author='Ryan Measel', author_email='ryanmeasel@gmail.com', # Choose your license license='MIT', # You can just specify the packages manually here if your project is # simple. Or you can use find_packages(). # packages=find_packages(exclude=['contrib', 'docs', 'tests']), packages=find_packages(), # 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=['mutagen==1.33.2'], # To provide executable scripts, use entry points in preference to the # "scripts" keyword. Entry points provide cross-platform support and allow # pip to create the appropriate form of executable for the target platform. entry_points={ 'console_scripts': [ 'penpen=penpen:main', ] }, classifiers=[ # How mature is this project? Common values are # 3 - Alpha # 4 - Beta # 5 - Production/Stable 'Development Status :: 4 - Beta', # Indicate who your project is intended for 'Intended Audience :: Information Technology', 'Topic :: Utilities', # Pick your license as you wish (should match "license" above) 'License :: OSI Approved :: MIT License', # 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.6', 'Programming Language :: Python :: 2.7' ] )
{ "repo_name": "ryanmeasel/PenPen", "path": "setup.py", "copies": "1", "size": "2535", "license": "mit", "hash": -9014105094449220000, "line_mean": 33.2567567568, "line_max": 79, "alpha_frac": 0.659566075, "autogenerated": false, "ratio": 4.128664495114006, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5288230570114006, "avg_score": null, "num_lines": null }
# Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path # https://packaging.python.org/distributing/ # to deploy: # rm -r dist # python setup.py sdist # python setup.py bdist_wheel # twine upload dist/* here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='function-pipe', version='1.0.3', description='Tools for extended function composition and pipelines', long_description=long_description, url='https://github.com/InvestmentSystems/function-pipe', author='Christopher Ariza', license='MIT', # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Topic :: Software Development', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], keywords='functionnode pipenode composition pipeline pipe', py_modules=['function_pipe'], # no .py! )
{ "repo_name": "InvestmentSystems/function-pipe", "path": "setup.py", "copies": "1", "size": "1228", "license": "mit", "hash": -3733816882065328000, "line_mean": 28.2380952381, "line_max": 72, "alpha_frac": 0.6758957655, "autogenerated": false, "ratio": 3.8984126984126983, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5074308463912698, "avg_score": null, "num_lines": null }
# Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path import agentserver here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='agentserver', # 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=agentserver.__version__, description='A server for managing monitoring agents', long_description=long_description, # The project's main homepage. url='https://github.com/silverfernsys/agentserver', # Author details author='Silver Fern Systems', author_email='dev@silverfern.io', # Choose your license license='BSD', # 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', 'Topic :: Software Development :: Build Tools', # Pick your license as you wish (should match "license" above) 'License :: OSI Approved :: BSD License', # 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.7', ], # What does your project relate to? keywords='monitoring development', # You can just specify the packages manually here if your project is # simple. Or you can use find_packages(). packages=find_packages(), # 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=[ 'Cerberus==0.9.2', 'configutil', 'iso8601utils', 'passlib', 'pyfiglet', 'setproctitle', 'sqlalchemy', 'tabulate', 'termcolor', 'tornado', ], dependency_links=['https://github.com/silverfernsys/pydruid.git=pydruid-0.4.0beta'], # List additional groups of dependencies here (e.g. development # dependencies). You can install these using the following syntax, # for example: # $ pip install -e .[dev,test] extras_require={ 'postgres': ['psycopg2'], 'mysql': ['PyMySQL'], 'druid': ['pydruid', 'kafka-python'], 'test': ['coverage', 'codecov', 'pytest', 'mock'], }, include_package_data=True, # # To provide executable scripts, use entry points in preference to the # # "scripts" keyword. Entry points provide cross-platform support and allow # # pip to create the appropriate form of executable for the target platform. entry_points={ 'console_scripts': [ 'agentserver=agentserver.server:main', 'agentserveradmin=agentserver.admin:main', 'agentserverecho=agentserver.echo:main' ], }, )
{ "repo_name": "silverfernsys/agentserver", "path": "setup.py", "copies": "1", "size": "3442", "license": "bsd-3-clause", "hash": -6075785901645630000, "line_mean": 31.780952381, "line_max": 88, "alpha_frac": 0.6481696688, "autogenerated": false, "ratio": 4.122155688622755, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.002245492914473762, "num_lines": 105 }
# Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path here = path.abspath(path.dirname(__file__)) # Get the long description from the relevant file with open(path.join(here, 'DESCRIPTION.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='django-render-as-template', version='1.0.0', description='A template tag for Django that takes a string and renders as it if it was a template.', long_description=long_description, url='https://github.com/daniboy/django-render-as-template', author='Daniel Rozenberg', author_email='me@danielrozenberg.com', license='ISC', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Framework :: Django', 'Framework :: Django :: 1.8', 'Intended Audience :: Developers', 'Intended Audience :: End Users/Desktop', 'License :: OSI Approved :: ISC License (ISCL)', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], keywords='template templates template-engine flatpages', packages=['render_as_template', 'render_as_template.templatetags'], install_requires=['django'], )
{ "repo_name": "daniboy/django-render-as-template", "path": "setup.py", "copies": "1", "size": "1534", "license": "isc", "hash": 5979723805815791000, "line_mean": 36.4146341463, "line_max": 104, "alpha_frac": 0.6531942634, "autogenerated": false, "ratio": 4.112600536193029, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5265794799593029, "avg_score": null, "num_lines": null }
# Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path setup( name='nnClassify', # 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.0.27', description='A command line tool for classifying images using transfer learning', long_description="A transfer learning classifier", # The project's main homepage. url='https://github.com/PatrickgHayes/nnClassify', # Author details author='Patrick Hayes and Aaron Graham', author_email='patrickghayes@gmail.com', # Choose your license license='MIT', # 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', # Pick your license as you wish (should match "license" above) 'License :: OSI Approved :: MIT License', # 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 :: 3', ], # What does your project relate to? keywords='image classification transfer learning', # You can just specify the packages manually here if your project is # simple. Or you can use find_packages(). packages=['src',], entry_points={'console_scripts':[ 'create_model = src.scripts:create_model', 'test_individual = src.scripts:test_individual', 'test_wells = src.scripts:test_wells', 'train = src.scripts:train', 'crop = src.scripts:crop', 'predict = src.scripts:predict', ]}, # Alternatively, if you want to distribute just a my_module.py, uncomment # this: # py_modules=["my_module"], # 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=['peppercorn'], # List additional groups of dependencies here (e.g. development # dependencies). You can install these using the following syntax, # for example: # $ pip install -e .[dev,test] #extras_require={ # 'dev': ['check-manifest'], # 'test': ['coverage'], #}, # If there are data files included in your packages that need to be # installed, specify them here. If using Python 2.6 or less, then these # have to be included in MANIFEST.in as well. #package_data={ # 'sample': ['package_data.dat'], #}, # Although 'package_data' is the preferred approach, in some case you may # need to place data files outside of your packages. See: # http://docs.python.org/3.4/distutils/setupscript.html#installing-additional-files # noqa # In this case, 'data_file' will be installed into '<sys.prefix>/my_data' #data_files=[('my_data', ['data/data_file'])], # To provide executable scripts, use entry points in preference to the # "scripts" keyword. Entry points provide cross-platform support and allow # pip to create the appropriate form of executable for the target platform. #entry_points={ # 'console_scripts': [ # 'sample=sample:main', # ], #}, )
{ "repo_name": "PatrickgHayes/nnClassify", "path": "setup.py", "copies": "1", "size": "3809", "license": "mit", "hash": -6471363577573850000, "line_mean": 37.4747474747, "line_max": 94, "alpha_frac": 0.6308742452, "autogenerated": false, "ratio": 4.1949339207048455, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00669271883581273, "num_lines": 99 }
# Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding from codecs import open import os import sys # file read helper def read_from_file(path): if os.path.exists(path): with open(path,"rb","utf-8") as input: return input.read() setup( name='k4cglicht', # 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.0.2", description='Controls Philips Hue light in the k4cg room', # The project's main homepage. url='https://github.com/C0rby/k4cglicht', # Author details author='K4CG', author_email='info@k4cg.org', # Choose your license license='MIT', # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 4 - Beta', 'Topic :: Utilities', 'Topic :: Terminals', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', ], keywords='hue philips light', packages=find_packages(), zip_safe=True, install_requires=["beautifulhue", "docopt"], #entry_points={ # 'console_scripts': [ # 'k4cglicht=k4cglicht:main', # ], #}, )
{ "repo_name": "k4cg/k4cglicht", "path": "setup.py", "copies": "1", "size": "1387", "license": "mit", "hash": 8948515488006077000, "line_mean": 24.6851851852, "line_max": 78, "alpha_frac": 0.6344628695, "autogenerated": false, "ratio": 3.5655526992287916, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.47000155687287914, "avg_score": null, "num_lines": null }
# Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding from codecs import open import os here = os.path.abspath(os.path.dirname(__file__)) # I really prefer Markdown to reStructuredText. PyPi does not. This allows me # to have things how I'd like, but not throw complaints when people are trying # to install the package and they don't have pypandoc or the README in the # right place. ''' try: import pypandoc long_description = pypandoc.convert(path.join(here, 'README.md'), 'rst') except (IOError, ImportError): long_description = '' ''' # Get the long description from the relevant file with open(os.path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() __version__ = '1.0.0' setup( name='python-lorem-pixel', version=__version__, description='Grab any number of images from Lorem Pixel easily.', long_description=long_description, url='https://bitbucket.org/tsantor/python-lorem-pixel', download_url='https://bitbucket.org/tsantor/python-lorem-pixel/get/%s.tar.gz' % __version__, author='Tim Santor', author_email='tsantor@xstudios.agency', license='MIT', # 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 :: 5 - Production/Stable', "Environment :: Console", # Indicate who your project is intended for 'Intended Audience :: Developers', # Pick your license as you wish (should match "license" above) 'License :: OSI Approved :: MIT License', # 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.7', 'Programming Language :: Python :: 3.4', ], keywords='lorem pixel', # You can just specify the packages manually here if your project is # simple. Or you can use find_packages(). packages=find_packages(exclude=['contrib', 'docs', 'tests*']), # 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=['python-bash-utils', 'progressbar33', 'requests'], # To provide executable scripts, use entry points in preference to the # "scripts" keyword. Entry points provide cross-platform support and allow # pip to create the appropriate form of executable for the target platform. entry_points={ 'console_scripts': [ 'lorem-pixel = lorempixel.lorem_pixel:run', ], }, test_suite="tests", )
{ "repo_name": "tsantor/python-lorem-pixel", "path": "setup.py", "copies": "1", "size": "2922", "license": "mit", "hash": -4827068054326789000, "line_mean": 33.7857142857, "line_max": 96, "alpha_frac": 0.6718001369, "autogenerated": false, "ratio": 3.9327052489905787, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5104505385890579, "avg_score": null, "num_lines": null }
# Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding from codecs import open def readme(): with open('README.rst') as f: return f.read() # Get the long description from the relevant file setup( name='finist', # 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.2', description='Redis based Finite State Machine.', long_description=readme(), # The project's main homepage. url='https://github.com/sumanau7/finist', # Author details author='Sumanau Sareen', author_email='finist-python@googlegroups.com', # Choose your license license='APACHE', # What does your project relate to? keywords='redis state machine python', # You can just specify the packages manually here if your project is # simple. Or you can use find_packages(). packages=['finist'], # 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=['redis'], # include_package_data=True, # zip_safe=False )
{ "repo_name": "sumanau7/finist", "path": "setup.py", "copies": "1", "size": "1410", "license": "mit", "hash": -2754534214494015000, "line_mean": 29, "line_max": 79, "alpha_frac": 0.6971631206, "autogenerated": false, "ratio": 3.983050847457627, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.022796352583586626, "num_lines": 47 }
# Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding import os, codecs HERE = os.path.abspath(os.path.dirname(__file__)) def read(*parts): """ Build an absolute path from *parts* and and return the contents of the resulting file. Assume UTF-8 encoding. """ with codecs.open(os.path.join(HERE, *parts), "rb", "utf-8") as f: return f.read() import modularity_maximization VERSION = modularity_maximization.__version__ setup( name='python-modularity-maximization', # You can just specify the packages manually here if your project is # simple. Or you can use find_packages(). packages=['modularity_maximization'], exclude_package_data={'': ['data*']}, # 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=VERSION, description='Community detection using Newman spectral methods to maximize modularity', long_description=read("README.rst"), # The project's main homepage. url='http://zhiyzuo.github.io/python-modularity-maximization/', download_url='https://github.com/zhiyzuo/python-modularity-maximization/tarball/' + VERSION, # Author details author='Zhiya Zuo', author_email='zhiyazuo@gmail.com', # Choose your license license='MIT', # 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 :: Education', 'Intended Audience :: Science/Research', 'Intended Audience :: Information Technology', 'Topic :: Scientific/Engineering :: Information Analysis', # Pick your license as you wish (should match "license" above) 'License :: OSI Approved :: MIT License', # 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 :: 3', ], keywords='modularity newman community-detection network-analysis clustering', install_requires=[ "scipy", "numpy", "networkx", ] )
{ "repo_name": "zhiyzuo/python-modularity-maximization", "path": "setup.py", "copies": "1", "size": "2540", "license": "mit", "hash": 6785861369839281000, "line_mean": 32.4210526316, "line_max": 96, "alpha_frac": 0.6653543307, "autogenerated": false, "ratio": 4.116693679092383, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5282048009792383, "avg_score": null, "num_lines": null }
# Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding import os from codecs import open here = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(here, 'requirements.txt')) as f: dependencies = [dep.strip() for dep in f.readlines()] setup( name='python-quran-odoa', py_modules=['odoa'], install_requires=dependencies, # 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='2.0.0', description='Library to get random ayah within quran including the translation.', long_description='Library to get random ayah within quran including the translation.', # The project's main homepage. url='https://github.com/Keda87/python-quran-odoa', # Author details author='Keda87', author_email='adiyatmubarak@gmail.com', # Choose your license license='MIT', # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ # How mature is this project? Common values are # 5 - Production/Stable 'Development Status :: 5 - Production/Stable', # Indicate who your project is intended for 'Intended Audience :: Developers', 'Topic :: Internet', 'Topic :: Software Development', 'Topic :: Software Development :: Libraries', # Pick your license as you wish (should match "license" above) 'License :: OSI Approved :: MIT License', # 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 :: 3', ], # What does your project relate to? keywords='development quran', # You can just specify the packages manually here if your project is # simple. Or you can use find_packages(). packages=find_packages(exclude=['contrib', 'docs', 'tests*']), )
{ "repo_name": "Keda87/python-quran-odoa", "path": "setup.py", "copies": "1", "size": "2096", "license": "mit", "hash": -1893078951657442000, "line_mean": 32.8064516129, "line_max": 90, "alpha_frac": 0.6750954198, "autogenerated": false, "ratio": 4.069902912621359, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5244998332421359, "avg_score": null, "num_lines": null }
# Always prefer setuptools over distutils from setuptools import setup from os import path from swg_python import __version__ as VERSION here = path.abspath(path.dirname(__file__)) long_description = "For more information see https://github.com/Furkanzmc/swg-python" setup( name='swg_python', # 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=VERSION, description='Framework agnostic Swagger parsing library in Python', long_description=long_description, # The project's main homepage. url='https://github.com/Furkanzmc/swg-python', # Author details author='Furkan Uzumcu', author_email='furkanuzumcu@gmail.com', # Choose your license license='Public Domain', # 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 :: 4 - Beta', # Indicate who your project is intended for 'Intended Audience :: Developers', 'Topic :: Software Development :: Build Tools', # Pick your license as you wish (should match "license" above) 'License :: Public Domain', # 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.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='python swagger python-library python-script', # You can just specify the packages manually here if your project is # simple. Or you can use find_packages(). packages=['swg_python'], # Alternatively, if you want to distribute just a my_module.py, uncomment # this: # py_modules=["my_module"], # 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=['pyyaml==5.1.2'], # List additional groups of dependencies here (e.g. development # dependencies). You can install these using the following syntax, # for example: # $ pip install -e .[dev,test] extras_require={ }, # If there are data files included in your packages that need to be # installed, specify them here. If using Python 2.6 or less, then these # have to be included in MANIFEST.in as well. package_data={ '': ['swg_python/static *', 'swg_python/templates *'], }, include_package_data=True, # To provide executable scripts, use entry points in preference to the # "scripts" keyword. Entry points provide cross-platform support and allow # pip to create the appropriate form of executable for the target platform. entry_points={ 'console_scripts': [ 'swg_python = swg_python.parser:command_line_compile', ], }, )
{ "repo_name": "Furkanzmc/swg-python", "path": "setup.py", "copies": "1", "size": "3382", "license": "unlicense", "hash": 7511045476678401000, "line_mean": 34.9787234043, "line_max": 85, "alpha_frac": 0.6638083974, "autogenerated": false, "ratio": 4.119366626065774, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00012370113805047005, "num_lines": 94 }
# Always prefer setuptools over distutils from setuptools import setup # To use a consistent encoding from codecs import open from os import path import meta 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='codeviz', version=meta.__version__, description=meta.__description__, long_description=long_description, url=meta.__url__, author=meta.__author__, author_email=meta.__email__, license='MIT', py_modules=['codeviz', 'meta'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', ], entry_points={ 'console_scripts': [ 'codeviz=codeviz:main', ], }, )
{ "repo_name": "jmarkowski/codeviz", "path": "setup.py", "copies": "1", "size": "1162", "license": "mit", "hash": -3441716293013922300, "line_mean": 27.3414634146, "line_max": 63, "alpha_frac": 0.6084337349, "autogenerated": false, "ratio": 4.120567375886525, "config_test": false, "has_no_keywords": true, "few_assignments": false, "quality_score": 0.5229001110786524, "avg_score": null, "num_lines": null }
# Always prefer setuptools over distutils from setuptools import setup # To use a consistent encoding from codecs import open from os import path import unittest here = path.abspath(path.dirname(__file__)) # Get the long description from the relevant file with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='football-data-api', version='1.0.0', description='A wrapper for the http://api.football-data.org/', url='https://github.com/buluba89/football-data-api', author='John Buluba', license='MIT', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: Utilities', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], keywords='wrapper football-data api development', py_modules=['football_data_api'], install_requires=['tortilla'], test_suite="tests", tests_require=['httmock'], )
{ "repo_name": "buluba89/football-data-api", "path": "setup.py", "copies": "2", "size": "1166", "license": "mit", "hash": -3688850069875862500, "line_mean": 21.4423076923, "line_max": 66, "alpha_frac": 0.6380789022, "autogenerated": false, "ratio": 3.993150684931507, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.019230769230769232, "num_lines": 52 }
# Always prefer setuptools over distutils from setuptools import setup # To use a consistent encoding 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='wrapit', version='0.3.1', description='A task loader for doit that supports argparse console scripts', long_description=long_description, url='https://github.com/rbeagrie/wrapit', author='Rob Beagrie', author_email='rob@beagrie.com', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Software Development :: Build Tools', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', ], keywords='doit development console_scripts build_tools', packages=['wrapit'], install_requires=['doit'], )
{ "repo_name": "rbeagrie/wrapit", "path": "setup.py", "copies": "1", "size": "1117", "license": "mit", "hash": -8557699232787390000, "line_mean": 27.641025641, "line_max": 80, "alpha_frac": 0.6553267681, "autogenerated": false, "ratio": 4.076642335766423, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5231969103866423, "avg_score": null, "num_lines": null }
# Always prefer setuptools over distutils import os # To use a consistent encoding from codecs import open from os import path from pathlib import Path from setuptools import setup, find_packages 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() def read_requirements(path: str): res = [] path = Path(path) with path.open(encoding='UTF-8') as f: for line in f.readlines(): if line.startswith('-r'): file = line[len('-r'):].strip() res += read_requirements(Path(file)) else: res.append(line.strip()) return res install_requires = read_requirements('requirements.txt') test_requires = read_requirements('test-requirements.txt') setup( name='freenom dns updater', # 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=os.environ.get('SETUP_VERSION_OVERWRITE', '1.1.1'), description="A tool to update freenom's dns records", long_description=long_description, long_description_content_type="text/markdown", # The project's main homepage. url='https://github.com/maxisoft/Freenom-dns-updater', # Author details author='maxisoft', author_email='maxisoft@maxisoft.ga', # Choose your license license='MIT', # 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 :: 4 - Beta', # Indicate who your project is intended for 'Intended Audience :: Developers', 'Topic :: Software Development :: Build Tools', # Pick your license as you wish (should match "license" above) 'License :: OSI Approved :: MIT License', # 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 :: 3', 'Programming Language :: Python :: 3.8', ], # What does your project relate to? keywords='freenom dns', # You can just specify the packages manually here if your project is # simple. Or you can use find_packages(). packages=find_packages(exclude=['freenom_dns_updater.test.*']), python_requires='~=3.6', # Alternatively, if you want to distribute just a my_module.py, uncomment # this: # py_modules=["my_module"], # 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=install_requires, # List additional groups of dependencies here (e.g. development # dependencies). You can install these using the following syntax, # for example: # $ pip install -e .[dev,test] extras_require={ 'dev': ['check-manifest'], 'test': test_requires, }, # If there are data files included in your packages that need to be # installed, specify them here. If using Python 2.6 or less, then these # have to be included in MANIFEST.in as well. package_data={ 'freenom_dns_updater': ["data/*"], }, # Although 'package_data' is the preferred approach, in some case you may # need to place data files outside of your packages. See: # http://docs.python.org/3.4/distutils/setupscript.html#installing-additional-files # noqa # In this case, 'data_file' will be installed into '<sys.prefix>/my_data' data_files=[], # To provide executable scripts, use entry points in preference to the # "scripts" keyword. Entry points provide cross-platform support and allow # pip to create the appropriate form of executable for the target platform. entry_points=''' [console_scripts] fdu=freenom_dns_updater.scripts.fdu:cli ''', )
{ "repo_name": "maxisoft/Freenom-dns-updater", "path": "setup.py", "copies": "1", "size": "4284", "license": "mit", "hash": -3073776578736529400, "line_mean": 33.272, "line_max": 94, "alpha_frac": 0.660130719, "autogenerated": false, "ratio": 4.007483629560337, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 125 }
""" Copyright (c) 2015 Michael Bright and Bamboo HR LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import ssl import sys from setuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path ssl._create_default_https_context = ssl._create_unverified_context here = path.abspath(path.dirname(__file__)) # Get the long description from the relevant file with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() try: execfile('./rapid/lib/version.py') except NameError: exec(open('./rapid/lib/version.py').read()) requirements = [ 'flask', 'requests==2.25.1', 'futures', 'jsonpickle', 'simplejson==3.10.0', 'simpleeval' ] if sys.version_info[0] == 2: requirements.append('enum34==1.0.4') setup( name='rapid-framework', version=__version__, description='Rapid Framework', long_description=long_description, # The project's main homepage. url='https://github.com/BambooHR/rapid', # Author details author='Michael Bright', author_email='mbright@bamboohr.com', # 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 :: 4 - Beta', # Indicate who your project is intended for 'Topic :: Software Development :: Build Tools', # 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.7' ], # What does your project relate to? keywords='internal ci jenkinskiller', # You can just specify the packages manually here if your project is # simple. Or you can use find_packages(). packages=find_packages(exclude=['contrib', 'docs', 'tests*']), # 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=requirements, # List additional groups of dependencies here (e.g. development # dependencies). You can install these using the following syntax, # for example: # $ pip install -e .[dev,test] extras_require={ 'test': ['coverage', 'nose', 'ddt', 'mock', 'MagicMock'], 'master': ['alembic', 'SQLAlchemy>=1.0.6', 'Flask-SQLAlchemy>=2.3.0', 'mysqlclient', 'pygithub', 'simpleeval'], 'windows-client': ['waitress==1.4.4'], 'client': [] }, # To provide executable scripts, use entry points in preference to the # "scripts" keyword. Entry points provide cross-platform support and allow # pip to create the appropriate form of executable for the target platform. entry_points={ 'console_scripts': [ 'rapid=rapid.__main__:main', ], }, )
{ "repo_name": "BambooHR/rapid", "path": "setup.py", "copies": "1", "size": "3813", "license": "apache-2.0", "hash": 336355787799194200, "line_mean": 33.3513513514, "line_max": 123, "alpha_frac": 0.6378179911, "autogenerated": false, "ratio": 4.171772428884026, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5309590419984026, "avg_score": null, "num_lines": null }
# Always prefer setuptools over distutils import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(here, 'VERSION')) as f: __version__ = f.read().strip() with open(os.path.join(here, 'requirements.txt')) as f: required = f.read().splitlines() with open(os.path.join(here, 'README.rst')) as f: long_description = f.read() extra_files = [] extra_files.append(os.path.join(here, 'LICENSE')) extra_files.append(os.path.join(here, 'requirements.txt')) extra_files.append(os.path.join(here, 'VERSION')) setup( name='osfclient', # update `osfclient/__init__.py` as well version=__version__, description='An OSF command-line library', long_description=long_description, # The project's main homepage. url='https://github.com/dib-lab/osf-cli', # Author details author='The OSF-cli authors', # Choose your license license='BSD3', # 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', 'Environment :: Console', # Indicate who your project is intended for 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'License :: OSI Approved :: BSD License', 'Topic :: Utilities' ], # You can just specify the packages manually here if your project is # simple. Or you can use find_packages(). packages=find_packages(), incude_package_data=True, package_data={'': extra_files}, # 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=required, # To provide executable scripts, use entry points in preference to the # "scripts" keyword. Entry points provide cross-platform support and allow # pip to create the appropriate form of executable for the target platform. entry_points={ 'console_scripts': [ 'osf=osfclient.__main__:main', ], }, )
{ "repo_name": "betatim/osf-cli", "path": "setup.py", "copies": "1", "size": "2524", "license": "bsd-3-clause", "hash": -288202240842566850, "line_mean": 29.4096385542, "line_max": 79, "alpha_frac": 0.6442155309, "autogenerated": false, "ratio": 3.931464174454829, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5075679705354829, "avg_score": null, "num_lines": null }
# Always prefer setuptools over distutils # To use a consistent encoding from codecs import open from os import path from setuptools import find_packages, setup here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() exec(open('toskeriser/__init__.py').read()) setup( name='TosKeriser', # 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=__version__, description='A tool to complete TosKer application description with' 'suitable Docker Images', long_description=long_description, # The project's main homepage. url='https://github.com/di-unipi-socc/TosKeriser', # Author details author='lucarin91', author_email='to@lucar.in', # Choose your license license='MIT', python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*', # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Intended Audience :: Developers', 'Topic :: System :: Installation/Setup', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX :: Linux', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], keywords='Docker match matcher TOSCA deployment complete development', # You can just specify the packages manually here if your project is # simple. Or you can use find_packages(). # packages=find_packages(exclude=['test']), packages=find_packages(exclude=['tests']), # 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=['cmd2<=0.8.6', # BUGFIX: Added to avoide conflict in the # version of cmd2 inside tosca_parser. 'tosca-parser', 'six', 'requests', 'ruamel.yaml'], # List additional groups of dependencies here (e.g. development # dependencies). You can install these using the following syntax, # for example: # $ pip install -e .[dev,test] extras_require={ 'dev': ['check-manifest', 'isort', 'flake8', 'tox', 'coverage'], 'test': ['requests_mock'], }, test_suite="tests", # If there are data files included in your packages that need to be # installed, specify them here. If using Python 2.6 or less, then these # have to be included in MANIFEST.in as well. include_package_data=True, # package_data={ # 'tosker': ['*.yaml'], # }, # Although 'package_data' is the preferred approach, in some case you may # need to place data files outside of your packages. See: # http://docs.python.org/3.4/distutils/setupscript.html#installing-additional-files # noqa # In this case, 'data_file' will be installed into '<sys.prefix>/my_data' data_files=[ ('/usr/share/toskeriser', ['data/tosker-types.yaml']), ('/usr/share/toskeriser/examples', ['data/examples/thinking-app/thinking.csar']) ], # To provide executable scripts, use entry points in preference to the # "scripts" keyword. Entry points provide cross-platform support and allow # pip to create the appropriate form of executable for the target platform. entry_points={ 'console_scripts': [ 'toskerise=toskeriser.ui:run', ], }, )
{ "repo_name": "di-unipi-socc/TosKeriser", "path": "setup.py", "copies": "1", "size": "4019", "license": "mit", "hash": 6266797282398120000, "line_mean": 35.2072072072, "line_max": 94, "alpha_frac": 0.6412042797, "autogenerated": false, "ratio": 3.9209756097560975, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5062179889456098, "avg_score": null, "num_lines": null }
# Always prefer setuptools over distutils # To use a consistent encoding from codecs import open from os import path from setuptools import setup, find_packages here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='bioc', python_requires='>=3.6', # 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='1.3.6', description='BioC data structures and encoder/decoder for Python', long_description=long_description, long_description_content_type='text/x-rst', # The project's main homepage. url='https://github.com/yfpeng/bioc', # Author details author='Yifan Peng', author_email='yip4002@med.cornell.edu', license='BSD 3-Clause License', # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 5 - Production/Stable', # Indicate who your project is intended for 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', # Pick your license as you wish (should match "license" above) 'License :: OSI Approved :: BSD License', 'Operating System :: MacOS', 'Operating System :: POSIX', 'Operating System :: POSIX :: Linux', 'Operating System :: Microsoft :: Windows', # Specify the Python versions you support here. 'Programming Language :: Python', 'Topic :: Text Processing :: Markup :: XML', 'Topic :: Software Development', 'Topic :: Software Development :: Libraries :: Application Frameworks', ], keywords='bioc', packages=find_packages(exclude=["tests.*", "tests"]), install_requires=[ 'docutils==0.15.2', 'lxml==4.4.1', 'jsonlines==1.2.0'], )
{ "repo_name": "yfpeng/pengyifan-pybioc", "path": "setup.py", "copies": "2", "size": "2050", "license": "bsd-3-clause", "hash": 1284863610772812300, "line_mean": 30.5384615385, "line_max": 79, "alpha_frac": 0.6497560976, "autogenerated": false, "ratio": 4.011741682974559, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 65 }
# Always prefer setuptools over distutils # To use a consistent encoding from codecs import open from os import path from setuptools import setup HERE = path.abspath(path.dirname(__file__)) # Get version info ABOUT = {} with open(path.join(HERE, "datadog_checks", "network", "__about__.py")) as f: exec(f.read(), ABOUT) # Get the long description from the README file with open(path.join(HERE, 'README.md'), encoding='utf-8') as f: long_description = f.read() def get_dependencies(): dep_file = path.join(HERE, 'requirements.in') if not path.isfile(dep_file): return [] with open(dep_file, encoding='utf-8') as f: return f.readlines() CHECKS_BASE_REQ = 'datadog-checks-base>=13.1.0' setup( name='datadog-network', version=ABOUT["__version__"], description='The Network check', long_description=long_description, long_description_content_type='text/markdown', keywords='datadog agent network check', # The project's main homepage. url='https://github.com/DataDog/integrations-core', # Author details author='Datadog', author_email='packages@datadoghq.com', # License license='MIT', # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Topic :: System :: Monitoring', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', ], # The package we're going to ship packages=['datadog_checks.network'], # Run-time dependencies install_requires=[CHECKS_BASE_REQ], extras_require={'deps': get_dependencies()}, # Extra files to ship with the wheel package include_package_data=True, )
{ "repo_name": "DataDog/integrations-core", "path": "network/setup.py", "copies": "1", "size": "1887", "license": "bsd-3-clause", "hash": 4173498260335015400, "line_mean": 29.435483871, "line_max": 77, "alpha_frac": 0.6592474828, "autogenerated": false, "ratio": 3.781563126252505, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9940810609052505, "avg_score": 0, "num_lines": 62 }
# Always prefer setuptools over distutils # To use a consistent encoding from codecs import open from os import path from setuptools import setup here = path.abspath(path.dirname(__file__)) HERE = path.dirname(path.abspath(__file__)) # Get version info ABOUT = {} with open(path.join(HERE, 'datadog_checks', 'active_directory', '__about__.py')) as f: exec(f.read(), ABOUT) # Get the long description from the README file with open(path.join(HERE, 'README.md'), encoding='utf-8') as f: long_description = f.read() def get_dependencies(): dep_file = path.join(HERE, 'requirements.in') if not path.isfile(dep_file): return [] with open(dep_file, encoding='utf-8') as f: return f.readlines() CHECKS_BASE_REQ = 'datadog-checks-base>=15.7.0' setup( name='datadog-active_directory', version=ABOUT["__version__"], description='The Active Directory check', long_description=long_description, long_description_content_type='text/markdown', keywords='datadog agent active directory check', # The project's main homepage. url='https://github.com/DataDog/integrations-core', # Author details author='Datadog', author_email='packages@datadoghq.com', # License license='BSD', # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Topic :: System :: Monitoring', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', ], # The package we're going to ship packages=['datadog_checks.active_directory'], # Run-time dependencies install_requires=[CHECKS_BASE_REQ], extras_require={'deps': get_dependencies()}, # Extra files to ship with the wheel package include_package_data=True, )
{ "repo_name": "DataDog/integrations-core", "path": "active_directory/setup.py", "copies": "1", "size": "1977", "license": "bsd-3-clause", "hash": 7033551444175229000, "line_mean": 29.890625, "line_max": 86, "alpha_frac": 0.6646433991, "autogenerated": false, "ratio": 3.7946257197696736, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.49592691188696736, "avg_score": null, "num_lines": null }
# Always prefer setuptools over distutils # To use a consistent encoding from codecs import open from os import path from setuptools import setup 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() # Get version info ABOUT = {} with open(path.join(HERE, "datadog_checks", "powerdns_recursor", "__about__.py")) as f: exec(f.read(), ABOUT) def get_dependencies(): dep_file = path.join(HERE, 'requirements.in') if not path.isfile(dep_file): return [] with open(dep_file, encoding='utf-8') as f: return f.readlines() CHECKS_BASE_REQ = 'datadog-checks-base>=11.8.0' setup( name='datadog-powerdns_recursor', version=ABOUT["__version__"], description='The PowerDNS check', long_description=long_description, long_description_content_type='text/markdown', keywords='datadog agent powerdns_recursor check', # The project's main homepage. url='https://github.com/DataDog/integrations-core', # Author details author='Datadog', author_email='packages@datadoghq.com', # License license='BSD', # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Topic :: System :: Monitoring', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', ], # The package we're going to ship packages=['datadog_checks.powerdns_recursor'], # Run-time dependencies install_requires=[CHECKS_BASE_REQ], extras_require={'deps': get_dependencies()}, # Extra files to ship with the wheel package include_package_data=True, )
{ "repo_name": "DataDog/integrations-core", "path": "powerdns_recursor/setup.py", "copies": "1", "size": "1930", "license": "bsd-3-clause", "hash": -4905890024011347000, "line_mean": 29.15625, "line_max": 87, "alpha_frac": 0.6637305699, "autogenerated": false, "ratio": 3.74031007751938, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.490404064741938, "avg_score": null, "num_lines": null }
# Always prefer setuptools over distutils # To use a consistent encoding from os import path from setuptools import find_packages, setup here = path.abspath(path.dirname(__file__)) setup( name='sushi-bargain', version='0.1', description='Extract your OS X Photos images', long_description='', url='https://github.com/nlindblad/sushi-bargain', # Author details author='Niklas Lindblad', author_email='niklas@lindblad.info', # Choose your license license='MIT', # 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', 'Topic :: Utilities', # Pick your license as you wish (should match "license" above) 'License :: OSI Approved :: MIT License', # 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.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], # What does your project relate to? keywords='sushi', # You can just specify the packages manually here if your project is # simple. Or you can use find_packages(). packages=find_packages(exclude=['contrib', 'docs', 'tests']), # Alternatively, if you want to distribute just a my_module.py, uncomment # this: # py_modules=["my_module"], # 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=[], # List additional groups of dependencies here (e.g. development # dependencies). You can install these using the following syntax, # for example: # $ pip install -e .[dev,test] extras_require={ 'dev': ['check-manifest'], 'test': ['coverage'], }, package_data={}, data_files=[], # To provide executable scripts, use entry points in preference to the # "scripts" keyword. Entry points provide cross-platform support and allow # pip to create the appropriate form of executable for the target platform. entry_points={ 'console_scripts': [ 'sushi-bargain=sushi_bargain:main', ], }, )
{ "repo_name": "nlindblad/sushi-bargain", "path": "setup.py", "copies": "1", "size": "2896", "license": "mit", "hash": 7376780679470149000, "line_mean": 30.8241758242, "line_max": 79, "alpha_frac": 0.6339779006, "autogenerated": false, "ratio": 4.178932178932179, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5312910079532178, "avg_score": null, "num_lines": null }
# Always prefer setuptools over distutils from setuptools import setup, find_packages from setuptools.dist import Distribution # To use a consistent encoding from codecs import open import os from os import path import platform import subprocess # Trick setuptools in order to get correct binary wheel tag name # We are forced to do this as we don't compile the extension modules through setuptools # but rather with CMake. class BinaryDistribution(Distribution): def is_pure(self): return False def has_ext_modules(self): return True setup( name='manylinux-cmake-test', # 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', description='', long_description='', # The project's main homepage. url='https://github.com/anlambert/python_manylinux_cmake_test_project', # Author details author='Antoine Lambert', author_email='antoine.lambert33@gmail.com', # Choose your license license='MIT', # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[], # What does your project relate to? keywords='', # You can just specify the packages manually here if your project is # simple. Or you can use find_packages(). packages=['zliblinkage', 'pnglinkage'], # 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=[], # List additional groups of dependencies here (e.g. development # dependencies). You can install these using the following syntax, # for example: # $ pip install -e .[dev,test] extras_require={}, # If there are data files included in your packages that need to be # installed, specify them here. If using Python 2.6 or less, then these # have to be included in MANIFEST.in as well. package_data={ 'zliblinkage': ['*.so', '../*.so'], 'pnglinkage': ['*.so'], }, # Although 'package_data' is the preferred approach, in some case you may # need to place data files outside of your packages. See: # http://docs.python.org/3.4/distutils/setupscript.html#installing-additional-files # noqa # In this case, 'data_file' will be installed into '<sys.prefix>/my_data' data_files=[], # To provide executable scripts, use entry points in preference to the # "scripts" keyword. Entry points provide cross-platform support and allow # pip to create the appropriate form of executable for the target platform. entry_points={}, include_package_data=True, distclass=BinaryDistribution )
{ "repo_name": "anlambert/python_manylinux_cmake_test_project", "path": "setup.py", "copies": "1", "size": "2981", "license": "mit", "hash": -6316462861965750000, "line_mean": 33.0705882353, "line_max": 94, "alpha_frac": 0.6803086213, "autogenerated": false, "ratio": 4.186797752808989, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5367106374108989, "avg_score": null, "num_lines": null }
# Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding 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='urbackup-server-web-api-wrapper', # 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.11', description='Python wrapper to access and control an UrBackup server', long_description=long_description, long_description_content_type="text/markdown", # The project's main homepage. url='https://github.com/uroni/urbackup-server-python-web-api-wrapper', # Author details author='Martin Raiber', author_email='martin@urbackup.org', # Choose your license license='Apache License 2.0', # 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', # Pick your license as you wish (should match "license" above) 'License :: OSI Approved :: Apache Software License', # 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 :: 3.4', 'Programming Language :: Python :: 3.5', ], # What does your project relate to? keywords='urbackup web api client', # You can just specify the packages manually here if your project is # simple. Or you can use find_packages(). packages=find_packages(exclude=['contrib', 'docs', 'tests']), # Alternatively, if you want to distribute just a my_module.py, uncomment # this: # py_modules=["my_module"], # 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=[], # List additional groups of dependencies here (e.g. development # dependencies). You can install these using the following syntax, # for example: # $ pip install -e .[dev,test] extras_require={ 'dev': [], 'test': [], } )
{ "repo_name": "uroni/urbackup-server-python-web-api-wrapper", "path": "setup.py", "copies": "1", "size": "2821", "license": "apache-2.0", "hash": 5076168998352716000, "line_mean": 33.2875, "line_max": 79, "alpha_frac": 0.6497695853, "autogenerated": false, "ratio": 4.185459940652819, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5335229525952818, "avg_score": null, "num_lines": null }
# Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path VERSION = '0.2' here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='clapperboard', # 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=VERSION, description='A command-line clapperboard', long_description=long_description, # The project's main homepage. url='https://github.com/sdeleon28/clapperboard', download_url='https://github.com/sdeleon28/clapperboard/tarball/{}'.format(VERSION), # Author details author='Santiago de Leon', author_email='sdeleon28@gmail.com', # Choose your license license='MIT', # 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', # Pick your license as you wish (should match "license" above) 'License :: OSI Approved :: MIT License', # 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='movie clip video clapperboard editing', # You can just specify the packages manually here if your project is # simple. Or you can use find_packages(). packages=['clapperboard'], # 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=['moviepy'], # To provide executable scripts, use entry points in preference to the # "scripts" keyword. Entry points provide cross-platform support and allow # pip to create the appropriate form of executable for the target platform. entry_points={ 'console_scripts': [ 'clapsync=clapperboard.sync:main', 'clapcrop=clapperboard.crop:main', ], }, )
{ "repo_name": "sdeleon28/clapperboard", "path": "setup.py", "copies": "1", "size": "2980", "license": "mit", "hash": -6116750041912340000, "line_mean": 33.5, "line_max": 88, "alpha_frac": 0.6476510067, "autogenerated": false, "ratio": 4.203102961918194, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.012037037037037037, "num_lines": 84 }
always_safe = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' '0123456789' '_.-') _safemaps = {} def quote(s, safe = '/'): """quote('abc def') -> 'abc%20def' Each part of a URL, e.g. the path info, the query, etc., has a different set of reserved characters that must be quoted. RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists the following reserved characters. reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | "," Each of these characters is reserved in some component of a URL, but not necessarily in all of them. By default, the quote function is intended for quoting the path section of a URL. Thus, it will not encode '/'. This character is reserved, but in typical usage the quote function is being called on a path where the existing slash characters are used as reserved characters. """ cachekey = (safe, always_safe) try: safe_map = _safemaps[cachekey] except KeyError: safe += always_safe safe_map = {} for i in range(256): c = chr(i) safe_map[c] = (c in safe) and c or ('%%%02X' % i) _safemaps[cachekey] = safe_map res = map(safe_map.__getitem__, s) return ''.join(res) _hextochr = dict(('%02x' % i, chr(i)) for i in range(256)) _hextochr.update(('%02X' % i, chr(i)) for i in range(256)) def unquote(s): """unquote('abc%20def') -> 'abc def'.""" res = s.split('%') for i in xrange(1, len(res)): item = res[i] try: res[i] = _hextochr[item[:2]] + item[2:] except KeyError: res[i] = '%' + item except UnicodeDecodeError: res[i] = unichr(int(item[:2], 16)) + item[2:] return "".join(res) _hostprog = None def splithost(url): """splithost('//host[:port]/path') --> 'host[:port]', '/path'.""" global _hostprog if _hostprog is None: import re _hostprog = re.compile('^//([^/?]*)(.*)$') match = _hostprog.match(url) if match: return match.group(1, 2) return None, url _typeprog = None def splittype(url): """splittype('type:opaquestring') --> 'type', 'opaquestring'.""" global _typeprog if _typeprog is None: import re _typeprog = re.compile('^([^/:]+):') match = _typeprog.match(url) if match: scheme = match.group(1) return scheme.lower(), url[len(scheme) + 1:] return None, url
{ "repo_name": "gagoel/freebase-python", "path": "appengine_stubs/urllib_stub.py", "copies": "5", "size": "2514", "license": "bsd-2-clause", "hash": 5208830030131932000, "line_mean": 30.037037037, "line_max": 69, "alpha_frac": 0.5600636436, "autogenerated": false, "ratio": 3.5609065155807365, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.004682695345429365, "num_lines": 81 }
#Alwin Mao's Iterator for grtrans as of June 23, 2015 #Added Secant method to the iterator, no longer producing 3 per iteration #Factor of 4 speedup from before #When using, look at the power law dependence of the flux on mdot or whatever, and use appropriately. #note iterator can be turned off by finding 33 + tries and replacing with -1 + tries import sys import os from local import putdir #this line is if you have a file local.py with directory information. only putdir is needed, to tell the iterator where to save files. import grtrans_batch as gr from pgrtrans import pgrtrans import numpy as n x = gr.grtrans() mecc = 5.92989e9 mastervalue = 3.4 #the value you are trying to match #edit this function to define what constitutes a good enough fit def isgoodenough(errors): three = len(n.where(errors < .01)[0]) > 3 two = len(n.where(errors < .001)[0]) > 2 one = len(n.where(errors < .0001)[0]) > 1 return (three or two or one) #least squares polynomial fit, avoids importing scipy... def jgpoly(x,y,degree): array = n.zeros([len(x),degree]) for no in n.arange(degree): array[:,no] = x**no matrix = n.mat(array) pseudo = (((matrix.T).dot(matrix)).I).dot((matrix.T).dot((n.mat(y)).T)) wooodo = n.array(pseudo.reshape(degree))[0][::-1] return wooodo #checks the new guess (newcenter) given the array of tested parameters (marr) and fluxes (farr), and the argument of the best run (best) def checkguess(newcenter,marr,farr,best): bestflux = farr[best] bestmdot = marr[best] quality = True if True: if (bestflux < mastervalue) & (newcenter < bestmdot ): #Guess is shit. Flux is too small, we need bigger mdot quality = False elif (bestflux > mastervalue) & (newcenter > bestmdot): #Guess is shit. Flux is too big, we need a small mdot quality = False else: quality = True #Sign check. Should use 0.0 but usually mdot shouldn't become so small. if newcenter < 1.0: quality = False #make sure the new mass is actually new if (marr == newcenter).sum() > 0: quality = False #don't jump more than 3 orders of magnitude at a time in case something funky happens #but if you need to, allow jumping by 1 order of magnitude #edit these if you want more/less flexibility if n.abs(n.log10(newcenter/bestmdot)) > 3: quality = False #but please jump more than a part in a thousand... if n.abs(newcenter/bestmdot - 1.0) < 5e-3: quality = False return quality #given the list of mdots and resulting fluxes, try many strategies to determine the next mdot to try. #general strategy: try a safe method, check that it works and is a new guess, #if it doesn't lead to a better fit, checkguess prevents repeats, which forces finder() to try a riskier guess def finder(mdots,fluxs,tries=0,wander=2.0): sarr = n.argsort(mdots) marr = n.array(mdots)[sarr] farr = n.array(fluxs)[sarr] darr = ((farr - mastervalue)/mastervalue)**2. poss = n.where(farr > 0) best = n.where(darr == n.min(((farr[poss] - mastervalue)/mastervalue)**2.))[0][0] #only search through positive fluxs for the best # best = n.argmin(darr) quality = False #add data when there is not enough data or when run is just beginning if quality == False: if (len(darr) < (3 + tries)): newcenter = marr[best] * wander quality = checkguess(newcenter,marr,farr,best) if quality == False: if (len(darr) < (3 + tries)): newcenter = marr[best] / wander quality = checkguess(newcenter,marr,farr,best) if quality == False: #if the mastervalue is in between 2 other guesses, use reliable midpoint methods upperbounds = (n.where(farr[poss] > mastervalue)[0]) if len(upperbounds) > 0: lowerbounds = (n.where(farr[poss] < mastervalue)[0]) if len(lowerbounds) > 0: #newcenter = n.sqrt(marr[upperbounds[0]]*marr[lowerbounds[-1]]) newcenter = 0.5*(marr[poss][upperbounds[0]] + marr[poss][lowerbounds[-1]]) quality = checkguess(newcenter,marr,farr,best) print('Testing Newcenter' + str(newcenter) + str(quality)) if quality == False: newcenter = n.sqrt(marr[upperbounds[0]]*marr[lowerbounds[-1]]) quality = checkguess(newcenter,marr,farr,best) else: quality = False else: quality = False #forced jump every 4 unless already done # if (marr == newcenter).sum() > 0: if quality == False: if (len(darr)%6 == 1): newcenter = marr[best] * wander quality = ((marr == newcenter).sum() == 0) if quality == False: if (len(darr)%6 == 2): newcenter = marr[best] / wander quality = ((marr == newcenter).sum() == 0) if quality == False: #secant method if len(darr[poss]) > 1: sbestdarr = n.sort(darr[poss])[1] sbest = n.where(darr == sbestdarr)[0][0] newcenter = marr[best] - (farr[best] - mastervalue) * (marr[best] - marr[sbest])/(farr[best] - farr[sbest]) quality = checkguess(newcenter,marr,farr,best) #relies on I propto M**1/2. if quality == False: newcenter = marr[best] * (mastervalue/farr[best])**2. quality = checkguess(newcenter,marr,farr,best) #clauses work with the order-of-magnitude limit imposed by checkguess if quality == False: newcenter = marr[best] * 10. quality = checkguess(newcenter,marr,farr,best) if quality == False: newcenter = marr[best] * 0.1 quality = checkguess(newcenter,marr,farr,best) #relies on I propto M**2. if quality == False: newcenter = marr[best] / n.sqrt(farr[best]/mastervalue) quality = checkguess(newcenter,marr,farr,best) if quality == False: newcenter = marr[best] * 10. quality = checkguess(newcenter,marr,farr,best) if quality == False: newcenter = marr[best] * 0.1 quality = checkguess(newcenter,marr,farr,best) #general power law if quality == False: if len(darr) > 1: sbest = n.argsort(darr)[1] newcenter = marr[best] * (mastervalue/farr[best])**(n.log(marr[best]/marr[sbest])/n.log(farr[best]/farr[sbest])) quality = checkguess(newcenter,marr,farr,best) if quality == False: newcenter = marr[best] * 10. quality = checkguess(newcenter,marr,farr,best) if quality == False: newcenter = marr[best] * 0.1 quality = checkguess(newcenter,marr,farr,best) if quality == False: if len(marr[poss]) > 2: fit = jgpoly(n.array(marr[poss]),n.array(darr[poss]),3) newcenter = -.5 * fit[1]/fit[0] quality = checkguess(newcenter,marr,farr,best) if quality == False: if len(marr[poss]) > 2: a,b,c = jgpoly(marr[poss],farr[poss],3) newcenter = (-b + n.sqrt(b**2. - 4.0 * a * (c-mastervalue)))/(2.0*a) quality = checkguess(newcenter,marr,farr,best) #desperately try to find good data when there is not enough good data if quality == False: if len(poss) < 3: newcenter = marr[best] * 2.0 quality = checkguess(newcenter,marr,farr,best) if quality == False: if len(poss) < 3: newcenter = marr[best] * 0.5 quality = checkguess(newcenter,marr,farr,best) if quality == False: #Give up print('I give up. Try a more reasonable initial guess.') return newcenter,newcenter,True newwidth = n.sqrt(1.0+n.min(n.abs((n.array(mdots) - newcenter)/newcenter))) if len(marr) > 33 + tries: #This has gone on long enough print('I give up. Try a more reasonable guess.') return newwidth,newcenter,True #old comments regarding newwidth #zooms in, makes width smaller, if center is inside. #zooms as needed if center is outside goodenough = isgoodenough(darr) #number of points within 10% return newwidth,newcenter,goodenough #startiter #inputs for SARIAF and MAXJUTT class inputs: def __init__(self): self.standard=1 self.fname='SARIAF' self.ename='MAXJUTT' self.nmu=1 self.mumin=0.7#0.996194698092 self.mumax=0.7#0.996194698092 self.nfreq=1 self.fmin=2.3e11 self.fmax=2.3e11 self.phi0=-0.5 self.mbh=4.0e6 self.spin=0.9375 self.uout=0.005 self.uin=1.0 self.nvals=1 self.gridvals=[-60.,60.,-60.,60.] self.nn=[150,150,400] self.muval=0.25 self.stype='const' self.ntscl=10*mecc self.snscl=3e7 self.snnthscl=8e4 self.snnthp=2.9 self.sbeta=10. self.sbl06=0 self.delta=2.0 self.coefs=[0.10714295,0.4459917,1.34219997,2.17450422,1.36515333,0.52892829] self.epotherargs = [self.delta] + self.coefs self.epcoefindx = [1,1,1,1,1,1,1] def submit(alinputs): epotherargs = [float(alinputs.delta)] + alinputs.coefs x.run_pgrtrans(standard=alinputs.standard,fname=alinputs.fname,ename=alinputs.ename,nmu=alinputs.nmu,mumin=alinputs.mumin,mumax=alinputs.mumax,nfreq=alinputs.nfreq,fmin=alinputs.fmin,fmax=alinputs.fmax,phi0=alinputs.phi0,mbh=alinputs.mbh,spin=alinputs.spin,uout=alinputs.uout,uin=alinputs.uin,nvals=alinputs.nvals,gridvals=alinputs.gridvals,nn=alinputs.nn,muval=alinputs.muval,stype=alinputs.stype,ntscl=alinputs.ntscl,snscl=alinputs.snscl,snnthscl=alinputs.snnthscl,snnthp=alinputs.snnthp,sbeta=alinputs.sbeta,sbl06=alinputs.sbl06,epotherargs=alinputs.epotherargs,epcoefindx=alinputs.epcoefindx) x.calc_spec_pgrtrans(0) return (x.spec)*3.41e13 def makealinputs(): alinputs=inputs() mu = float(sys.argv[1]) spin = float(sys.argv[2]) te = float(sys.argv[3]) delta = float(sys.argv[4]) muval = float(sys.argv[5]) #delta = 2.0 #te = 10.0 #spin = 0.0 #mu = 0.7 #muval = 0.25 alinputs.delta = delta alinputs.epotherargs[0] = delta alinputs.ntscl = te * mecc #theta_e * m_e c^2/ k_b in kelvin alinputs.spin = spin alinputs.mumin = mu alinputs.mumax = mu alinputs.muval = muval alinputs.delta = delta filename = putdir+'d'+ '{:0.3f}'.format(float(alinputs.delta))+'te'+'{:0.3f}'.format(te)+'a'+'{:0.3f}'.format(alinputs.spin)+'i'+'{:0.3f}'.format(alinputs.mumin)+'mvl'+'{:0.3f}'.format(alinputs.muval)+'sarjutt.txt' return alinputs,filename #for SARIAF mdot is just n instead. Here we are. def runiterator(alinputs,filename): iteragoodenough = False iteramdots = [] iterafluxs = [] iterarange = 2.0 iteracenter = alinputs.snscl #mdot is now the scale n number density param = 0 #Load previous data iteratries = 0 if os.path.isfile(filename): print('Loading ' + filename) data = n.loadtxt(filename) if len(data.shape) > 1: filtre = (data[:,2] == 2.3e11) & (data[:,3] > 0) & (data[:,1] > 0) iteramdots = list(data[filtre][:,1]) iterafluxs = list(data[filtre][:,3]) iteratries = len(iteramdots) iterarange,iteracenter,iteragoodenough = finder(iteramdots,iterafluxs,tries=iteratries) while iteragoodenough == False: #computation step param += 1 alinputs.snscl = iteracenter outflux = float(submit(alinputs)) #submit runs it in pgrtrans print(outflux) outstring=str(param)+'\t'+str(alinputs.snscl)+'\t'+str(alinputs.fmin)+'\t' outstring+=str(outflux)+'\n' if param > -1: with open(filename,'a') as tfile: tfile.write(outstring) # pgrtrans.del_pgrtrans_data() iteramdots.append(alinputs.snscl) iterafluxs.append(outflux) #Iteration step iterarange,iteracenter,iteragoodenough = finder(iteramdots,iterafluxs,tries=iteratries) if isgoodenough((n.array(iterafluxs)/mastervalue - 1.0)**2.): summaryvalue = 'good' else: summaryvalue = 'bad' return iteramdots,iterafluxs,summaryvalue ######################################### def makesariafspectra(filename,alinputs,summaryvalue): specfile = filename[:-4]+'.spec' if ((summaryvalue == 'good')): outspecnu = [] outspecflux = [] if os.path.isfile(specfile): oldspec = n.loadtxt(specfile) oldspec = oldspec.reshape(oldspec.size/2,2) else: oldspec = n.array([[0,0],[0,0]]) flist = [1.5e10,2.7e10,4.868e10,8.77e10,1.58e11,2.0e11,6.0e11,2.0e12,3.0e12,3.0e13,2.5e11,1.5e12,4.0e12,1.6e13,9.0e13,2.3e11,1.0e10,3.1e9,1.0e9,3.0e14] for i in range(len(flist)): if (oldspec[:,0] == flist[i]).sum() == 0: if flist[i] <= 1.0e10: camsize = 500 elif flist[i] > 1.58e11: camsize = 60 else: camsize = 100 alinputs.fmin = flist[i] alinputs.fmax = flist[i] alinputs.nfreq = 1 alinputs.gridvals=[-camsize,camsize,-camsize,camsize] print('Running ' + str(flist[i]) + '\t' + specfile) fluxs = submit(alinputs)[0] nus = x.nu for j in range(len(nus)): specstring=str(nus[j])+'\t'+str(fluxs[j])+'\n' with open(specfile,'a') as pfile: pfile.write(specstring) #alinputs,filename = makealinputs() #iteramdots,iterafluxs,summaryvalue = runiterator(alinputs,filename) #alinputs.snscl = iteramdots[n.argmin(n.abs(n.array(iterafluxs) - mastervalue))] #summaryname = putdir + 'pgrsummary.txt' #summarytext = filename + '\t' + summaryvalue + '\n' #with open(summaryname,'a') as tfile: # tfile.write(summarytext) #makesariafspectra(filename,alinputs,summaryvalue)
{ "repo_name": "jadexter/grtrans", "path": "pgriter.py", "copies": "1", "size": "14240", "license": "mit", "hash": -7619757921282133000, "line_mean": 36.180156658, "line_max": 600, "alpha_frac": 0.6063904494, "autogenerated": false, "ratio": 3.103072564828939, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.42094630142289385, "avg_score": null, "num_lines": null }
"""ama_app URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from ama_app.exercise.apis import QuestionsView, QuestionView from ama_app.exercise.views import home, publish question_patterns = [ url(r'^questions/(?P<id>[^/]*)/?$', QuestionView.as_view(), name='v1_question'), url(r'^questions/?$', QuestionsView.as_view(), name='v1_questions'), ] urlpatterns = [ url(r'^api/v1/', include(question_patterns)), url(r'^$', home, name='home'), url(r'^publish$', publish, name='publish'), ]
{ "repo_name": "ifkite/ama", "path": "src/ama_app/exercise/urls.py", "copies": "1", "size": "1128", "license": "mit", "hash": 7377562084411762000, "line_mean": 37.8965517241, "line_max": 84, "alpha_frac": 0.6835106383, "autogenerated": false, "ratio": 3.337278106508876, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.45207887448088757, "avg_score": null, "num_lines": null }
# amachine.py # a tiny stack machine for our new language A, nothing special. import math, os, re, operator, sys end=[] def run(l): stack=[[]] for i in l: if i is end: f=stack.pop() i=f[0](*f[1:]) if callable(i): stack.append([i]) else: stack[-1].append(i) # end of amachine.py # atest.py (written in our new language A) # encoding: acodec sys.stdout.write "Hello!\n"; sys.stdout.write "4 * sin(pi/4) + 3 = "; sys.stdout.write str operator.add operator.mul 4 math.sin math.pi/4;; 3;;; sys.stdout.write "\n"; # End of atest.py # Looks like atest.py can be executed by our tiny stack machine. # After all, it is written in Language A. # But certainly it can not be executed by the python interpreter directly. # Obviously, atest.py is not written in Python. # Or is it? # After load the following module, it is Python enough for the python interpreter. # acodec.py import encodings, codecs, re, sys # a mini tokenizer _qs=r"'(?:[^'\\\n]|\\.|\\\n)*?'(?!')|'''(?:[^\\]|\\.)*?'''" String = r"[uU]?[rR]?(?:%s|%s)"%(_qs, _qs.replace("'",'"')) Comment=r'\#.*' Name= r"[^#\"'\s\n;]+" tok_re=re.compile(r"%s|%s|%s|(?P<e>[;\.])"%(Name, String , Comment)) # Our StreamReader class aStreamReader(codecs.StreamReader): def readline(self, size=None, keepends=True): def repl(m): r=m.group() return "end," if m.group("e") else r+"," if getattr(self, "pysrc", None)==None: r=self.stream.read().decode("utf8") r="from amachine import *;run([%s])" % tok_re.sub(repl,r) self.pysrc=r.splitlines() return u'%s\n'%self.pysrc.pop(0) if self.pysrc else u'' def search_function(s): if s!="acodec": return None u8=encodings.search_function("utf8") return codecs.CodecInfo( name='acodec', encode=u8.encode, decode=u8.decode, incrementalencoder=u8.incrementalencoder, incrementaldecoder=u8.incrementaldecoder, streamreader=aStreamReader, # acodec StreamReader streamwriter=u8.streamwriter) codecs.register(search_function) # register our new codec search function # End of acodec.py # to test # import acodec # execfile("atest.py") # Executed like python # import atest.py # Imported like python # You can also use site.py or .pth file to load acodec.py automaticly. # then you can simply: # python atest.py
{ "repo_name": "ActiveState/code", "path": "recipes/Python/546539_Use_PEP_263_for_metaprogramming/recipe-546539.py", "copies": "1", "size": "2459", "license": "mit", "hash": 150918235732482, "line_mean": 31.7866666667, "line_max": 82, "alpha_frac": 0.612444083, "autogenerated": false, "ratio": 3.1647361647361647, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4277180247736165, "avg_score": null, "num_lines": null }
# A magic index in an array A[0...n-1] is defined to be an indexe such that # A[i] = i. Given a sorted array of distinct integers, write a method to find a # magic index, if one exists, in array A. # Assumes distinct def find(sorted_array): i = 0 while i < len(sorted_array): difference = sorted_array[i] - i if difference > 0: return None elif difference == 0: return i else: i += -difference return None def findr(sorted_array): def h(a, l, r): if l > r or a[l] > l or a[r] < r: return None m = (l + r) // 2 difference = a[m] - m if difference == 0: return m elif difference > 0: return h(sorted_array, l, m - 1) else: return h(sorted_array, m - difference, r) return h(sorted_array, 0, len(sorted_array) - 1) print(find([-1, 0, 1, 2, 4, 5])) print(findr([-1, 0, 1, 2, 4, 5])) print(findr([3, 3, 3, 3, 3])) # should give "None" # for duplicates, i don't really see a good way to salvage the recursive # solution... here's an iterative one, which is O(n) average and worst case, # but might work nicely for some inputs def find_with_dups(sorted_array): i = 0 while i < len(sorted_array): difference = sorted_array[i] - i if difference > 0: i += difference elif difference == 0: return i else: i += 1 return None print(find_with_dups([3, 3, 3, 3, 3]))
{ "repo_name": "jdf3/CtCI", "path": "python/8-recursion-and-dynamic-programming/magicindex.py", "copies": "1", "size": "1393", "license": "apache-2.0", "hash": -7985987812029290000, "line_mean": 25.2830188679, "line_max": 79, "alpha_frac": 0.5994256999, "autogenerated": false, "ratio": 3.0615384615384613, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4160964161438461, "avg_score": null, "num_lines": null }
"""A Mailman newsletter subscription interface. To use this plugin, enable the newsletter module and set the newsletter module and name settings in the admin settings page. """ from django.utils.translation import ugettext as _ from Mailman import MailList, Errors from models import Subscription from livesettings import config_value import logging import sys log = logging.getLogger('newsletter.mailman') class UserDesc: pass def is_subscribed(contact): return Subscription.email_is_subscribed(contact.email) def update_contact(contact, subscribe, attributes={}): email = contact.email current = Subscription.email_is_subscribed(email) attributesChanged = False sub = None if attributes: sub, created = Subscription.objects.get_or_create(email=email) if created: attributesChanged = True else: oldAttr = [(a.name,a.value) for a in sub.attributes.all()] oldAttr.sort() sub.update_attributes(attributes) newAttr = [(a.name,a.value) for a in sub.attributes.all()] newAttr.sort() if not created: attributesChanged = oldAttr != newAttr if current == subscribe: if subscribe: if attributesChanged: result = _("Updated subscription for %(email)s.") else: result = _("Already subscribed %(email)s.") else: result = _("Already removed %(email)s.") else: if not sub: sub, created = Subscription.objects.get_or_create(email=email) sub.subscribed = subscribe sub.save() if subscribe: mailman_add(contact) result = _("Subscribed: %(email)s") else: mailman_remove(contact) result = _("Unsubscribed: %(email)s") return result % { 'email' : email } def mailman_add(contact, listname=None, send_welcome_msg=None, admin_notify=None): """Add a Satchmo contact to a mailman mailing list. Parameters: - `Contact`: A Satchmo Contact - `listname`: the Mailman listname, defaulting to whatever you have set in settings.NEWSLETTER_NAME - `send_welcome_msg`: True or False, defaulting to the list default - `admin_notify`: True of False, defaulting to the list default """ mm, listname = _get_maillist(listname) print >> sys.stderr, 'mailman adding %s to %s' % (contact.email, listname) if send_welcome_msg is None: send_welcome_msg = mm.send_welcome_msg userdesc = UserDesc() userdesc.fullname = contact.full_name userdesc.address = contact.email userdesc.digest = False if mm.isMember(contact.email): print >> sys.stderr, _('Already Subscribed: %s' % contact.email) else: try: try: mm.Lock() mm.ApprovedAddMember(userdesc, send_welcome_msg, admin_notify) mm.Save() print >> sys.stderr, _('Subscribed: %(email)s') % { 'email' : contact.email } except Errors.MMAlreadyAMember: print >> sys.stderr, _('Already a member: %(email)s') % { 'email' : contact.email } except Errors.MMBadEmailError: if userdesc.address == '': print >> sys.stderr, _('Bad/Invalid email address: blank line') else: print >> sys.stderr, _('Bad/Invalid email address: %(email)s') % { 'email' : contact.email } except Errors.MMHostileAddress: print >> sys.stderr, _('Hostile address (illegal characters): %(email)s') % { 'email' : contact.email } finally: mm.Unlock() def mailman_remove(contact, listname=None, userack=None, admin_notify=None): """Remove a Satchmo contact from a Mailman mailing list Parameters: - `contact`: A Satchmo contact - `listname`: the Mailman listname, defaulting to whatever you have set in settings.NEWSLETTER_NAME - `userack`: True or False, whether to notify the user, defaulting to the list default - `admin_notify`: True or False, defaulting to the list default """ mm, listname = _get_maillist(listname) print >> sys.stderr, 'mailman removing %s from %s' % (contact.email, listname) if mm.isMember(contact.email): try: mm.Lock() mm.ApprovedDeleteMember(contact.email, 'satchmo_ext.newsletter', admin_notify, userack) mm.Save() finally: mm.Unlock() def _get_maillist(listname): try: if not listname: listname = config_value('NEWSLETTER', 'NEWSLETTER_NAME') if listname == "": log.warn("NEWSLETTER_NAME not set in store settings") raise NameError('No NEWSLETTER_NAME in settings') return MailList.MailList(listname, lock=0), listname except Errors.MMUnknownListError: print >> sys.stderr, "Can't find the MailMan newsletter: %s" % listname raise NameError('No such newsletter, "%s"' % listname)
{ "repo_name": "thoreg/satchmo", "path": "satchmo/apps/satchmo_ext/newsletter/mailman.py", "copies": "12", "size": "5119", "license": "bsd-3-clause", "hash": -7601279049806313000, "line_mean": 33.8231292517, "line_max": 119, "alpha_frac": 0.6098847431, "autogenerated": false, "ratio": 4.030708661417322, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.007227880261132423, "num_lines": 147 }
"""A mail sender that just stores mail to make testing easier.""" # ============================================================================= # CONTENTS # ----------------------------------------------------------------------------- # phlmail_mocksender # # Public Classes: # MailSender # .send # .mailboxes # .mails # .is_empty # # Public Assignments: # Mail # # ----------------------------------------------------------------------------- # (this contents block is generated, edits will be lost) # ============================================================================= from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import types Mail = collections.namedtuple( 'phlmail_mocksender__Mail', ['subject', 'message', 'to_addresses', 'cc_addresses']) class MailSender(object): """A mail sender that just stores mail to make testing easier.""" def __init__(self): """Setup to store sent email.""" self._mailboxes = collections.defaultdict(list) self._mails = [] def send(self, subject, message, to_addresses, cc_addresses=None): assert not isinstance(to_addresses, types.StringTypes) assert not isinstance(cc_addresses, types.StringTypes) mail = Mail(subject, message, to_addresses, cc_addresses) for address in to_addresses: self._mailboxes[address].append(mail) if cc_addresses is not None: for address in cc_addresses: self._mailboxes[address].append(mail) self._mails.append(mail) @property def mailboxes(self): return self._mailboxes @property def mails(self): return self._mails def is_empty(self): return not self._mails # ----------------------------------------------------------------------------- # Copyright (C) 2013-2014 Bloomberg Finance L.P. # # 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. # ------------------------------ END-OF-FILE ----------------------------------
{ "repo_name": "kjedruczyk/phabricator-tools", "path": "py/phl/phlmail_mocksender.py", "copies": "4", "size": "2574", "license": "apache-2.0", "hash": -3689176662564958700, "line_mean": 32, "line_max": 79, "alpha_frac": 0.5563325563, "autogenerated": false, "ratio": 4.5638297872340425, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.7120162343534043, "avg_score": null, "num_lines": null }
"""A mail sender that sends mail via a configured sendmail.""" # ============================================================================= # CONTENTS # ----------------------------------------------------------------------------- # phlmail_sender # # Public Classes: # MailSender # .send # # ----------------------------------------------------------------------------- # (this contents block is generated, edits will be lost) # ============================================================================= from __future__ import absolute_import from __future__ import division from __future__ import print_function import phlmail_format class MailSender(object): """A mail sender that sends mail via a configured sendmail.""" def __init__(self, sendmail, from_email): """Setup to send mail with 'sendmail' from 'from_email'. :sendmail: the sendmail instance to send with, e.g. a phlsys_sendmail :from_email: the address to send from """ self._sendmail = sendmail self._from_email = from_email def send(self, subject, message, to_addresses, cc_addresses=None): mime = phlmail_format.text( subject, message, self._from_email, to_addresses, cc_addresses) self._sendmail.send(mime) # ----------------------------------------------------------------------------- # Copyright (C) 2013-2014 Bloomberg Finance L.P. # # 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. # ------------------------------ END-OF-FILE ----------------------------------
{ "repo_name": "cs-shadow/phabricator-tools", "path": "py/phl/phlmail_sender.py", "copies": "4", "size": "2042", "license": "apache-2.0", "hash": 7042024307359520000, "line_mean": 35.4642857143, "line_max": 79, "alpha_frac": 0.5391772772, "autogenerated": false, "ratio": 4.662100456621005, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 56 }
"""Amalgamate Arbiter library sources into a single source and header file. Works with python2.6+ and python3.4+. A near carbon copy of: https://github.com/open-source-parsers/jsoncpp/blob/master/amalgamate.py Example of invocation (must be invoked from top directory): python amalgamate.py """ import os import os.path import sys class AmalgamationFile: def __init__(self, top_dir): self.top_dir = top_dir self.blocks = [] def add_text(self, text): if not text.endswith("\n"): text += "\n" self.blocks.append(text) def add_file(self, relative_input_path, wrap_in_comment=False): def add_marker(prefix): self.add_text("") self.add_text("// " + "/"*70) self.add_text("// %s of content of file: %s" % (prefix, relative_input_path.replace("\\","/"))) self.add_text("// " + "/"*70) self.add_text("") add_marker("Beginning") f = open(os.path.join(self.top_dir, relative_input_path), "rt") content = f.read() if wrap_in_comment: content = "/*\n" + content + "\n*/" self.add_text(content) f.close() add_marker("End") self.add_text("\n\n\n\n") def get_value(self): return "".join(self.blocks).replace("\r\n","\n") def write_to(self, output_path): output_dir = os.path.dirname(output_path) if output_dir and not os.path.isdir(output_dir): os.makedirs(output_dir) f = open(output_path, "wb") f.write(str.encode(self.get_value(), 'UTF-8')) f.close() def amalgamate_source(source_top_dir=None, target_source_path=None, header_include_path=None, include_xml=True, custom_namespace=None, define_curl=True, bundle_json=False): """Produces amalgamated source. Parameters: source_top_dir: top-directory target_source_path: output .cpp path header_include_path: generated header path relative to target_source_path. """ gitsha = None try: f = open(".git/refs/heads/master") gitsha = f.read().rstrip() f.close() except: print("This script must be run from the top level") if include_xml: print("Bundling RapidXML with amalgamation") else: print("NOT bundling RapidXML with amalgamation") print("Amalgamating header...") header = AmalgamationFile(source_top_dir) header.add_text("/// Arbiter amalgamated header (https://github.com/connormanning/arbiter).") header.add_text('/// It is intended to be used with #include "%s"' % header_include_path) header.add_text('\n// Git SHA: ' + gitsha) header.add_file("LICENSE", wrap_in_comment=True) header.add_text("#pragma once") header.add_text("/// If defined, indicates that the source file is amalgamated") header.add_text("/// to prevent private header inclusion.") header.add_text("#define ARBITER_IS_AMALGAMATION") if custom_namespace: print("Using custom namespace: " + custom_namespace) header.add_text("#define ARBITER_CUSTOM_NAMESPACE " + custom_namespace) if not include_xml: print("NOT bundling XML") header.add_text("#define ARBITER_EXTERNAL_XML") if include_xml: header.add_file("arbiter/third/xml/rapidxml.hpp") header.add_file("arbiter/third/xml/xml.hpp") if define_curl: header.add_text("\n#pragma once") header.add_text("#define ARBITER_CURL") else: print("NOT #defining ARBITER_CURL") if bundle_json: header.add_file("arbiter/third/json/json.hpp") else: header.add_text("\n#include <nlohmann/json.hpp>\n\n") header.add_file("arbiter/util/exports.hpp") header.add_file("arbiter/util/types.hpp") header.add_file("arbiter/util/json.hpp") header.add_file("arbiter/util/curl.hpp") header.add_file("arbiter/util/http.hpp") header.add_file("arbiter/util/ini.hpp") header.add_file("arbiter/util/time.hpp") header.add_file("arbiter/util/macros.hpp") header.add_file("arbiter/util/md5.hpp") header.add_file("arbiter/util/sha256.hpp") header.add_file("arbiter/util/transforms.hpp") header.add_file("arbiter/util/util.hpp") header.add_file("arbiter/driver.hpp") header.add_file("arbiter/drivers/fs.hpp") header.add_file("arbiter/drivers/http.hpp") header.add_file("arbiter/drivers/s3.hpp") header.add_file("arbiter/drivers/az.hpp") header.add_file("arbiter/drivers/google.hpp") header.add_file("arbiter/drivers/dropbox.hpp") header.add_file("arbiter/drivers/test.hpp") header.add_file("arbiter/endpoint.hpp") header.add_file("arbiter/arbiter.hpp") target_header_path = os.path.join(os.path.dirname(target_source_path), header_include_path) print("Writing amalgamated header to %r" % target_header_path) header.write_to(target_header_path) print("Amalgamating source...") source = AmalgamationFile(source_top_dir) source.add_text("/// Arbiter amalgamated source (https://github.com/connormanning/arbiter).") source.add_text('/// It is intended to be used with #include "%s"' % header_include_path) source.add_file("LICENSE", wrap_in_comment=True) source.add_text("") source.add_text('#include "%s"' % header_include_path) source.add_text(""" #ifndef ARBITER_IS_AMALGAMATION #error "Compile with -I PATH_TO_ARBITER_DIRECTORY" #endif """) source.add_text("") source.add_file("arbiter/arbiter.cpp") source.add_file("arbiter/driver.cpp") source.add_file("arbiter/endpoint.cpp") source.add_file("arbiter/drivers/fs.cpp") source.add_file("arbiter/drivers/http.cpp") source.add_file("arbiter/drivers/s3.cpp") source.add_file("arbiter/drivers/az.cpp") source.add_file("arbiter/drivers/google.cpp") source.add_file("arbiter/drivers/dropbox.cpp") source.add_file("arbiter/util/curl.cpp") source.add_file("arbiter/util/http.cpp") source.add_file("arbiter/util/ini.cpp") source.add_file("arbiter/util/md5.cpp") source.add_file("arbiter/util/sha256.cpp") source.add_file("arbiter/util/transforms.cpp") source.add_file("arbiter/util/time.cpp") source.add_file("arbiter/util/util.cpp") print("Writing amalgamated source to %r" % target_source_path) source.write_to(target_source_path) def main(): usage = """%prog [options] Generate a single amalgamated source and header file from the sources. """ from optparse import OptionParser parser = OptionParser(usage=usage) parser.allow_interspersed_args = False parser.add_option( "-s", "--source", dest="target_source_path", action="store", default="dist/arbiter.cpp", help="""Output .cpp source path. [Default: %default]""") parser.add_option( "-i", "--include", dest="header_include_path", action="store", default="arbiter.hpp", help="""Header include path. Used to include the header from the amalgamated source file. [Default: %default]""") parser.add_option( "-t", "--top-dir", dest="top_dir", action="store", default=os.getcwd(), help="""Source top-directory. [Default: %default]""") parser.add_option( "-x", "--no-include-xml", dest="include_xml", action="store_false", default=True) parser.add_option( "-d", "--define-curl", dest="define_curl", action="store_true", default=False) parser.add_option( "-j", "--bundle-json", dest="bundle_json", action="store_true", default=False) parser.add_option( "-c", "--custom-namespace", dest="custom_namespace", action="store", default=None) parser.enable_interspersed_args() options, args = parser.parse_args() msg = amalgamate_source(source_top_dir=options.top_dir, target_source_path=options.target_source_path, header_include_path=options.header_include_path, include_xml=options.include_xml, custom_namespace=options.custom_namespace, define_curl=options.define_curl, bundle_json=options.bundle_json) if msg: sys.stderr.write(msg + "\n") sys.exit(1) else: print("Source successfully amalgamated") if __name__ == "__main__": main()
{ "repo_name": "connormanning/arbiter", "path": "amalgamate.py", "copies": "1", "size": "8811", "license": "mit", "hash": -7022648606222290000, "line_mean": 34.244, "line_max": 125, "alpha_frac": 0.6054931336, "autogenerated": false, "ratio": 3.4607227022780833, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.45662158358780836, "avg_score": null, "num_lines": null }
"""Amalgamate json-cpp library sources into a single source and header file. Works with python2.6+ and python3.4+. Example of invocation (must be invoked from json-cpp top directory): python amalgamate.py """ import os import os.path import sys class AmalgamationFile: def __init__(self, top_dir): self.top_dir = top_dir self.blocks = [] def add_text(self, text): if not text.endswith("\n"): text += "\n" self.blocks.append(text) def add_file(self, relative_input_path, wrap_in_comment=False): def add_marker(prefix): self.add_text("") self.add_text("// " + "/"*70) self.add_text("// %s of content of file: %s" % (prefix, relative_input_path.replace("\\","/"))) self.add_text("// " + "/"*70) self.add_text("") add_marker("Beginning") f = open(os.path.join(self.top_dir, relative_input_path), "rt") content = f.read() if wrap_in_comment: content = "/*\n" + content + "\n*/" self.add_text(content) f.close() add_marker("End") self.add_text("\n\n\n\n") def get_value(self): return "".join(self.blocks).replace("\r\n","\n") def write_to(self, output_path): output_dir = os.path.dirname(output_path) if output_dir and not os.path.isdir(output_dir): os.makedirs(output_dir) f = open(output_path, "wb") f.write(str.encode(self.get_value(), 'UTF-8')) f.close() def amalgamate_source(source_top_dir=None, target_source_path=None, header_include_path=None): """Produces amalgamated source. Parameters: source_top_dir: top-directory target_source_path: output .cpp path header_include_path: generated header path relative to target_source_path. """ print("Amalgamating header...") header = AmalgamationFile(source_top_dir) header.add_text("/// Json-cpp amalgamated header (http://jsoncpp.sourceforge.net/).") header.add_text('/// It is intended to be used with #include "%s"' % header_include_path) header.add_file("LICENSE", wrap_in_comment=True) header.add_text("#ifndef JSON_AMALGAMATED_H_INCLUDED") header.add_text("# define JSON_AMALGAMATED_H_INCLUDED") header.add_text("/// If defined, indicates that the source file is amalgamated") header.add_text("/// to prevent private header inclusion.") header.add_text("#define JSON_IS_AMALGAMATION") header.add_file("include/json/version.h") header.add_file("include/json/allocator.h") header.add_file("include/json/config.h") header.add_file("include/json/forwards.h") header.add_file("include/json/features.h") header.add_file("include/json/value.h") header.add_file("include/json/reader.h") header.add_file("include/json/writer.h") header.add_file("include/json/assertions.h") header.add_text("#endif //ifndef JSON_AMALGAMATED_H_INCLUDED") target_header_path = os.path.join(os.path.dirname(target_source_path), header_include_path) print("Writing amalgamated header to %r" % target_header_path) header.write_to(target_header_path) base, ext = os.path.splitext(header_include_path) forward_header_include_path = base + "-forwards" + ext print("Amalgamating forward header...") header = AmalgamationFile(source_top_dir) header.add_text("/// Json-cpp amalgamated forward header (http://jsoncpp.sourceforge.net/).") header.add_text('/// It is intended to be used with #include "%s"' % forward_header_include_path) header.add_text("/// This header provides forward declaration for all JsonCpp types.") header.add_file("LICENSE", wrap_in_comment=True) header.add_text("#ifndef JSON_FORWARD_AMALGAMATED_H_INCLUDED") header.add_text("# define JSON_FORWARD_AMALGAMATED_H_INCLUDED") header.add_text("/// If defined, indicates that the source file is amalgamated") header.add_text("/// to prevent private header inclusion.") header.add_text("#define JSON_IS_AMALGAMATION") header.add_file("include/json/config.h") header.add_file("include/json/forwards.h") header.add_text("#endif //ifndef JSON_FORWARD_AMALGAMATED_H_INCLUDED") target_forward_header_path = os.path.join(os.path.dirname(target_source_path), forward_header_include_path) print("Writing amalgamated forward header to %r" % target_forward_header_path) header.write_to(target_forward_header_path) print("Amalgamating source...") source = AmalgamationFile(source_top_dir) source.add_text("/// Json-cpp amalgamated source (http://jsoncpp.sourceforge.net/).") source.add_text('/// It is intended to be used with #include "%s"' % header_include_path) source.add_file("LICENSE", wrap_in_comment=True) source.add_text("") source.add_text('#include "%s"' % header_include_path) source.add_text(""" #ifndef JSON_IS_AMALGAMATION #error "Compile with -I PATH_TO_JSON_DIRECTORY" #endif """) source.add_text("") lib_json = "src/lib_json" source.add_file(os.path.join(lib_json, "json_tool.h")) source.add_file(os.path.join(lib_json, "json_reader.cpp")) source.add_file(os.path.join(lib_json, "json_valueiterator.inl")) source.add_file(os.path.join(lib_json, "json_value.cpp")) source.add_file(os.path.join(lib_json, "json_writer.cpp")) print("Writing amalgamated source to %r" % target_source_path) source.write_to(target_source_path) def main(): usage = """%prog [options] Generate a single amalgamated source and header file from the sources. """ from optparse import OptionParser parser = OptionParser(usage=usage) parser.allow_interspersed_args = False parser.add_option("-s", "--source", dest="target_source_path", action="store", default="dist/jsoncpp.cpp", help="""Output .cpp source path. [Default: %default]""") parser.add_option("-i", "--include", dest="header_include_path", action="store", default="json/json.h", help="""Header include path. Used to include the header from the amalgamated source file. [Default: %default]""") parser.add_option("-t", "--top-dir", dest="top_dir", action="store", default=os.getcwd(), help="""Source top-directory. [Default: %default]""") parser.enable_interspersed_args() options, args = parser.parse_args() msg = amalgamate_source(source_top_dir=options.top_dir, target_source_path=options.target_source_path, header_include_path=options.header_include_path) if msg: sys.stderr.write(msg + "\n") sys.exit(1) else: print("Source successfully amalgamated") if __name__ == "__main__": main()
{ "repo_name": "endlessm/chromium-browser", "path": "third_party/jsoncpp/source/amalgamate.py", "copies": "5", "size": "6832", "license": "bsd-3-clause", "hash": 621245006358010100, "line_mean": 43.0774193548, "line_max": 121, "alpha_frac": 0.6451990632, "autogenerated": false, "ratio": 3.3922542204568025, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.003369707898705913, "num_lines": 155 }
"""Amalgate cppunit library sources into a single source file (headers are not amalgated for backward compatibility). Requires Python 2.6 Example of invocation (must be invoked from cppunit top directory): python amalgate.py This will generate file ${CPPUNIT_ROOT}/dist/amalgated-src/cppunit_lib.cpp that contains all sources (.cpp/.h) from src/cppcunit. """ from glob import glob import os import os.path import sys class AmalgamationFile: def __init__( self, top_dir ): self.top_dir = top_dir self.blocks = [] def add_text( self, text ): if not text.endswith( '\n' ): text += '\n' self.blocks.append( text ) def add_file( self, relative_input_path, wrap_in_comment=False, comment_out_local_include=False ): def add_marker( prefix ): self.add_text( '' ) self.add_text( '// ' + '/'*70 ) self.add_text( '// %s of content of file: %s' % (prefix, relative_input_path.replace('\\','/')) ) self.add_text( '// ' + '/'*70 ) self.add_text( '' ) add_marker( 'Beginning' ) f = open( os.path.join( self.top_dir, relative_input_path ), 'rt' ) content = f.read() if wrap_in_comment: content = '/*\n' + content + '\n*/' if comment_out_local_include: content = content.replace( '#include "', '// header was amalgamated #include "' ) self.add_text( content ) f.close() add_marker( 'End' ) self.add_text( '\n\n\n\n' ) def get_value( self ): return ''.join( self.blocks ).replace('\r\n','\n') def write_to( self, output_path ): output_dir = os.path.dirname( output_path ) if output_dir and not os.path.isdir( output_dir ): os.makedirs( output_dir ) f = open( output_path, 'wb' ) f.write( self.get_value() ) f.close() def amalgamate_source( source_top_dir=None, target_source_path=None ): """Produces amalgated source. Parameters: source_top_dir: top-directory target_source_path: output .cpp path header_include_path: generated header path relative to target_source_path. """ print 'Amalgating source...' source = AmalgamationFile( source_top_dir ) source.add_text( '/// CppUnit amalgated source (http://cppunit.sourceforge.net/).' ) source.add_file( 'COPYING', wrap_in_comment=True ) source.add_text( '' ) source.add_text( '' ) lib_cppunit = 'src/cppunit' lib_cppunit_h = glob( os.path.join( lib_cppunit, '*.h' ) ) lib_cppunit_h.sort() lib_cppunit_cpp = glob( os.path.join( lib_cppunit, '*.cpp' ) ) lib_cppunit_cpp.sort() for src_relative_path in lib_cppunit_h + lib_cppunit_cpp: source.add_file( src_relative_path, comment_out_local_include=True ) print 'Writing amalgated source to %r' % target_source_path source.write_to( target_source_path ) def main(): usage = """%prog [options] Generate a single amalgated source and header file from the sources. """ from optparse import OptionParser parser = OptionParser(usage=usage) parser.allow_interspersed_args = False parser.add_option('-s', '--source', dest="target_source_path", action='store', default='dist/amalgated-src/cppunit_lib.cpp', help="""Output .cpp source path. [Default: %default]""") parser.add_option('-t', '--top-dir', dest="top_dir", action='store', default=os.getcwd(), help="""Source top-directory. [Default: %default]""") parser.enable_interspersed_args() options, args = parser.parse_args() msg = amalgamate_source( source_top_dir=options.top_dir, target_source_path=options.target_source_path ) if msg: sys.stderr.write( msg + '\n' ) sys.exit( 1 ) else: print 'Source succesfully amalagated' if __name__ == '__main__': main()
{ "repo_name": "wojwal/msiext", "path": "externals/cppunit/amalgamate.py", "copies": "5", "size": "3939", "license": "epl-1.0", "hash": -1573388011841632000, "line_mean": 36.5142857143, "line_max": 128, "alpha_frac": 0.603960396, "autogenerated": false, "ratio": 3.404494382022472, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6508454778022471, "avg_score": null, "num_lines": null }
"""Amalgate json-cpp library sources into a single source and header file. Requires Python 2.6 Example of invocation (must be invoked from json-cpp top directory): python amalgate.py """ import os import os.path import sys class AmalgamationFile: def __init__( self, top_dir ): self.top_dir = top_dir self.blocks = [] def add_text( self, text ): if not text.endswith( '\n' ): text += '\n' self.blocks.append( text ) def add_file( self, relative_input_path, wrap_in_comment=False ): def add_marker( prefix ): self.add_text( '' ) self.add_text( '// ' + '/'*70 ) self.add_text( '// %s of content of file: %s' % (prefix, relative_input_path.replace('\\','/')) ) self.add_text( '// ' + '/'*70 ) self.add_text( '' ) add_marker( 'Beginning' ) f = open( os.path.join( self.top_dir, relative_input_path ), 'rt' ) content = f.read() if wrap_in_comment: content = '/*\n' + content + '\n*/' self.add_text( content ) f.close() add_marker( 'End' ) self.add_text( '\n\n\n\n' ) def get_value( self ): return ''.join( self.blocks ).replace('\r\n','\n') def write_to( self, output_path ): output_dir = os.path.dirname( output_path ) if output_dir and not os.path.isdir( output_dir ): os.makedirs( output_dir ) f = open( output_path, 'wb' ) f.write( self.get_value() ) f.close() def amalgamate_source( source_top_dir=None, target_source_path=None, header_include_path=None ): """Produces amalgated source. Parameters: source_top_dir: top-directory target_source_path: output .cpp path header_include_path: generated header path relative to target_source_path. """ print 'Amalgating header...' header = AmalgamationFile( source_top_dir ) header.add_text( '/// Json-cpp amalgated header (http://jsoncpp.sourceforge.net/).' ) header.add_text( '/// It is intented to be used with #include <%s>' % header_include_path ) header.add_file( 'LICENSE', wrap_in_comment=True ) header.add_text( '#ifndef JSON_AMALGATED_H_INCLUDED' ) header.add_text( '# define JSON_AMALGATED_H_INCLUDED' ) header.add_text( '/// If defined, indicates that the source file is amalgated' ) header.add_text( '/// to prevent private header inclusion.' ) header.add_text( '#define JSON_IS_AMALGAMATION' ) header.add_file( 'include/json/config.h' ) header.add_file( 'include/json/forwards.h' ) header.add_file( 'include/json/features.h' ) header.add_file( 'include/json/value.h' ) header.add_file( 'include/json/reader.h' ) header.add_file( 'include/json/writer.h' ) header.add_text( '#endif //ifndef JSON_AMALGATED_H_INCLUDED' ) target_header_path = os.path.join( os.path.dirname(target_source_path), header_include_path ) print 'Writing amalgated header to %r' % target_header_path header.write_to( target_header_path ) base, ext = os.path.splitext( header_include_path ) forward_header_include_path = base + '-forwards' + ext print 'Amalgating forward header...' header = AmalgamationFile( source_top_dir ) header.add_text( '/// Json-cpp amalgated forward header (http://jsoncpp.sourceforge.net/).' ) header.add_text( '/// It is intented to be used with #include <%s>' % forward_header_include_path ) header.add_text( '/// This header provides forward declaration for all JsonCpp types.' ) header.add_file( 'LICENSE', wrap_in_comment=True ) header.add_text( '#ifndef JSON_FORWARD_AMALGATED_H_INCLUDED' ) header.add_text( '# define JSON_FORWARD_AMALGATED_H_INCLUDED' ) header.add_text( '/// If defined, indicates that the source file is amalgated' ) header.add_text( '/// to prevent private header inclusion.' ) header.add_text( '#define JSON_IS_AMALGAMATION' ) header.add_file( 'include/json/config.h' ) header.add_file( 'include/json/forwards.h' ) header.add_text( '#endif //ifndef JSON_FORWARD_AMALGATED_H_INCLUDED' ) target_forward_header_path = os.path.join( os.path.dirname(target_source_path), forward_header_include_path ) print 'Writing amalgated forward header to %r' % target_forward_header_path header.write_to( target_forward_header_path ) print 'Amalgating source...' source = AmalgamationFile( source_top_dir ) source.add_text( '/// Json-cpp amalgated source (http://jsoncpp.sourceforge.net/).' ) source.add_text( '/// It is intented to be used with #include <%s>' % header_include_path ) source.add_file( 'LICENSE', wrap_in_comment=True ) source.add_text( '' ) source.add_text( '#include <%s>' % header_include_path ) source.add_text( '' ) lib_json = 'src/lib_json' source.add_file( os.path.join(lib_json, 'json_tool.h') ) source.add_file( os.path.join(lib_json, 'json_reader.cpp') ) source.add_file( os.path.join(lib_json, 'json_batchallocator.h') ) source.add_file( os.path.join(lib_json, 'json_valueiterator.inl') ) source.add_file( os.path.join(lib_json, 'json_value.cpp') ) source.add_file( os.path.join(lib_json, 'json_writer.cpp') ) print 'Writing amalgated source to %r' % target_source_path source.write_to( target_source_path ) def main(): usage = """%prog [options] Generate a single amalgated source and header file from the sources. """ from optparse import OptionParser parser = OptionParser(usage=usage) parser.allow_interspersed_args = False parser.add_option('-s', '--source', dest="target_source_path", action='store', default='dist/jsoncpp.cpp', help="""Output .cpp source path. [Default: %default]""") parser.add_option('-i', '--include', dest="header_include_path", action='store', default='json/json.h', help="""Header include path. Used to include the header from the amalgated source file. [Default: %default]""") parser.add_option('-t', '--top-dir', dest="top_dir", action='store', default=os.getcwd(), help="""Source top-directory. [Default: %default]""") parser.enable_interspersed_args() options, args = parser.parse_args() msg = amalgamate_source( source_top_dir=options.top_dir, target_source_path=options.target_source_path, header_include_path=options.header_include_path ) if msg: sys.stderr.write( msg + '\n' ) sys.exit( 1 ) else: print 'Source succesfully amalagated' if __name__ == '__main__': main()
{ "repo_name": "zhongzw/skia-sdl", "path": "third_party/externals/jsoncpp/amalgamate.py", "copies": "13", "size": "6708", "license": "bsd-3-clause", "hash": 8797351350017247000, "line_mean": 44.3243243243, "line_max": 119, "alpha_frac": 0.6271615981, "autogenerated": false, "ratio": 3.325731284085275, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.027368106474731865, "num_lines": 148 }
"""Amalgate json-cpp library sources into a single source and header file. Works with python2.6+ and python3.4+. Example of invocation (must be invoked from json-cpp top directory): python amalgate.py """ import os import os.path import sys class AmalgamationFile: def __init__(self, top_dir): self.top_dir = top_dir self.blocks = [] def add_text(self, text): if not text.endswith("\n"): text += "\n" self.blocks.append(text) def add_file(self, relative_input_path, wrap_in_comment=False): def add_marker(prefix): self.add_text("") self.add_text("// " + "/"*70) self.add_text("// %s of content of file: %s" % (prefix, relative_input_path.replace("\\","/"))) self.add_text("// " + "/"*70) self.add_text("") add_marker("Beginning") f = open(os.path.join(self.top_dir, relative_input_path), "rt") content = f.read() if wrap_in_comment: content = "/*\n" + content + "\n*/" self.add_text(content) f.close() add_marker("End") self.add_text("\n\n\n\n") def get_value(self): return "".join(self.blocks).replace("\r\n","\n") def write_to(self, output_path): output_dir = os.path.dirname(output_path) if output_dir and not os.path.isdir(output_dir): os.makedirs(output_dir) f = open(output_path, "wb") f.write(str.encode(self.get_value(), 'UTF-8')) f.close() def amalgamate_source(source_top_dir=None, target_source_path=None, header_include_path=None): """Produces amalgated source. Parameters: source_top_dir: top-directory target_source_path: output .cpp path header_include_path: generated header path relative to target_source_path. """ print("Amalgating header...") header = AmalgamationFile(source_top_dir) header.add_text("/// Json-cpp amalgated header (http://jsoncpp.sourceforge.net/).") header.add_text('/// It is intended to be used with #include "%s"' % header_include_path) header.add_file("LICENSE", wrap_in_comment=True) header.add_text("#ifndef JSON_AMALGATED_H_INCLUDED") header.add_text("# define JSON_AMALGATED_H_INCLUDED") header.add_text("/// If defined, indicates that the source file is amalgated") header.add_text("/// to prevent private header inclusion.") header.add_text("#define JSON_IS_AMALGAMATION") header.add_file("include/json/version.h") header.add_file("include/json/config.h") header.add_file("include/json/forwards.h") header.add_file("include/json/features.h") header.add_file("include/json/value.h") header.add_file("include/json/reader.h") header.add_file("include/json/writer.h") header.add_file("include/json/assertions.h") header.add_text("#endif //ifndef JSON_AMALGATED_H_INCLUDED") target_header_path = os.path.join(os.path.dirname(target_source_path), header_include_path) print("Writing amalgated header to %r" % target_header_path) header.write_to(target_header_path) base, ext = os.path.splitext(header_include_path) forward_header_include_path = base + "-forwards" + ext print("Amalgating forward header...") header = AmalgamationFile(source_top_dir) header.add_text("/// Json-cpp amalgated forward header (http://jsoncpp.sourceforge.net/).") header.add_text('/// It is intended to be used with #include "%s"' % forward_header_include_path) header.add_text("/// This header provides forward declaration for all JsonCpp types.") header.add_file("LICENSE", wrap_in_comment=True) header.add_text("#ifndef JSON_FORWARD_AMALGATED_H_INCLUDED") header.add_text("# define JSON_FORWARD_AMALGATED_H_INCLUDED") header.add_text("/// If defined, indicates that the source file is amalgated") header.add_text("/// to prevent private header inclusion.") header.add_text("#define JSON_IS_AMALGAMATION") header.add_file("include/json/config.h") header.add_file("include/json/forwards.h") header.add_text("#endif //ifndef JSON_FORWARD_AMALGATED_H_INCLUDED") target_forward_header_path = os.path.join(os.path.dirname(target_source_path), forward_header_include_path) print("Writing amalgated forward header to %r" % target_forward_header_path) header.write_to(target_forward_header_path) print("Amalgating source...") source = AmalgamationFile(source_top_dir) source.add_text("/// Json-cpp amalgated source (http://jsoncpp.sourceforge.net/).") source.add_text('/// It is intended to be used with #include "%s"' % header_include_path) source.add_file("LICENSE", wrap_in_comment=True) source.add_text("") source.add_text('#include "%s"' % header_include_path) source.add_text(""" #ifndef JSON_IS_AMALGAMATION #error "Compile with -I PATH_TO_JSON_DIRECTORY" #endif """) source.add_text("") lib_json = "src/lib_json" source.add_file(os.path.join(lib_json, "json_tool.h")) source.add_file(os.path.join(lib_json, "json_reader.cpp")) source.add_file(os.path.join(lib_json, "json_valueiterator.inl")) source.add_file(os.path.join(lib_json, "json_value.cpp")) source.add_file(os.path.join(lib_json, "json_writer.cpp")) print("Writing amalgated source to %r" % target_source_path) source.write_to(target_source_path) def main(): usage = """%prog [options] Generate a single amalgated source and header file from the sources. """ from optparse import OptionParser parser = OptionParser(usage=usage) parser.allow_interspersed_args = False parser.add_option("-s", "--source", dest="target_source_path", action="store", default="dist/jsoncpp.cpp", help="""Output .cpp source path. [Default: %default]""") parser.add_option("-i", "--include", dest="header_include_path", action="store", default="json/json.h", help="""Header include path. Used to include the header from the amalgated source file. [Default: %default]""") parser.add_option("-t", "--top-dir", dest="top_dir", action="store", default=os.getcwd(), help="""Source top-directory. [Default: %default]""") parser.enable_interspersed_args() options, args = parser.parse_args() msg = amalgamate_source(source_top_dir=options.top_dir, target_source_path=options.target_source_path, header_include_path=options.header_include_path) if msg: sys.stderr.write(msg + "\n") sys.exit(1) else: print("Source succesfully amalagated") if __name__ == "__main__": main()
{ "repo_name": "herocodemaster/opencvr", "path": "3rdparty/jsoncpp/amalgamate.py", "copies": "14", "size": "6738", "license": "mit", "hash": -1304566166640478700, "line_mean": 42.7532467532, "line_max": 119, "alpha_frac": 0.6423271, "autogenerated": false, "ratio": 3.3825301204819276, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": null, "num_lines": null }
"""A management command to apply mailbox operations.""" from __future__ import unicode_literals, print_function import logging import os import shutil from django.core.management.base import BaseCommand from modoboa.parameters import tools as param_tools from modoboa.lib.sysutils import exec_cmd from modoboa.lib.exceptions import InternalError from ...app_settings import load_admin_settings from ...models import MailboxOperation class OperationError(Exception): """Custom exception.""" pass class Command(BaseCommand): """Command definition""" help = "Handles rename and delete operations on mailboxes" def __init__(self, *args, **kwargs): super(Command, self).__init__(*args, **kwargs) self.logger = logging.getLogger("modoboa.admin") def add_arguments(self, parser): """Add extra arguments to command line.""" parser.add_argument( "--pidfile", default="/tmp/handle_mailbox_operations.pid", help="Path to the file that will contain the PID of this process" ) def rename_mailbox(self, operation): if not os.path.exists(operation.argument): return new_mail_home = operation.mailbox.mail_home dirname = os.path.dirname(new_mail_home) if not os.path.exists(dirname): try: os.makedirs(dirname) except os.error as e: raise OperationError(str(e)) code, output = exec_cmd( "mv %s %s" % (operation.argument, new_mail_home) ) if code: raise OperationError(output) def delete_mailbox(self, operation): """Try to delete a mailbox tree on filesystem.""" if not os.path.exists(operation.argument): return def onerror(function, path, excinfo): """Handle errors.""" self.logger.critical( "delete failed (reason: {})".format(excinfo)) shutil.rmtree(operation.argument, False, onerror) def check_pidfile(self, path): """Check if this command is already running :param str path: path to the file containing the PID :return: a boolean, True means we can go further """ if os.path.exists(path): with open(path) as fp: pid = fp.read().strip() code, output = exec_cmd( "grep handle_mailbox_operations /proc/%s/cmdline" % pid ) if not code: return False with open(path, 'w') as fp: print(os.getpid(), file=fp) return True def handle(self, *args, **options): """Command entry point.""" load_admin_settings() if not param_tools.get_global_parameter("handle_mailboxes"): return if not self.check_pidfile(options["pidfile"]): return for ope in MailboxOperation.objects.all(): try: f = getattr(self, "%s_mailbox" % ope.type) except AttributeError: continue try: f(ope) except (OperationError, InternalError) as e: self.logger.critical( "%s failed (reason: %s)", ope, str(e).decode("utf-8")) else: self.logger.info("%s succeed", ope) ope.delete() os.unlink(options["pidfile"])
{ "repo_name": "bearstech/modoboa", "path": "modoboa/admin/management/commands/handle_mailbox_operations.py", "copies": "1", "size": "3420", "license": "isc", "hash": -2555186251974463000, "line_mean": 30.9626168224, "line_max": 77, "alpha_frac": 0.5798245614, "autogenerated": false, "ratio": 4.334600760456274, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5414425321856274, "avg_score": null, "num_lines": null }
"""A management command to apply mailbox operations.""" import logging from optparse import make_option import os from django.core.management.base import BaseCommand from param_tools import tools as param_tools from modoboa.lib.sysutils import exec_cmd from modoboa.lib.exceptions import InternalError from ...app_settings import load_admin_settings from ...models import MailboxOperation class OperationError(Exception): """Custom exception.""" pass class Command(BaseCommand): """Command definition""" help = "Handles rename and delete operations on mailboxes" option_list = BaseCommand.option_list + ( make_option( "--pidfile", default="/tmp/handle_mailbox_operations.pid", help="Path to the file that will contain the PID of this process" ), ) def __init__(self, *args, **kwargs): super(Command, self).__init__(*args, **kwargs) self.logger = logging.getLogger("modoboa.admin") def rename_mailbox(self, operation): if not os.path.exists(operation.argument): return new_mail_home = operation.mailbox.mail_home dirname = os.path.dirname(new_mail_home) if not os.path.exists(dirname): try: os.makedirs(dirname) except os.error as e: raise OperationError(str(e)) code, output = exec_cmd( "mv %s %s" % (operation.argument, new_mail_home) ) if code: raise OperationError(output) def delete_mailbox(self, operation): if not os.path.exists(operation.argument): return code, output = exec_cmd( "rm -r %s" % operation.argument ) if code: raise OperationError(output) def check_pidfile(self, path): """Check if this command is already running :param str path: path to the file containing the PID :return: a boolean, True means we can go further """ if os.path.exists(path): with open(path) as fp: pid = fp.read().strip() code, output = exec_cmd( "grep handle_mailbox_operations /proc/%s/cmdline" % pid ) if not code: return False with open(path, 'w') as fp: print >> fp, os.getpid() return True def handle(self, *args, **options): """Command entry point.""" load_admin_settings() if not param_tools.get_global_parameter("handle_mailboxes"): return if not self.check_pidfile(options["pidfile"]): return for ope in MailboxOperation.objects.all(): try: f = getattr(self, "%s_mailbox" % ope.type) except AttributeError: continue try: f(ope) except (OperationError, InternalError) as e: self.logger.critical("%s failed (reason: %s)", ope, str(e).encode("utf-8")) else: self.logger.info("%s succeed", ope) ope.delete() os.unlink(options["pidfile"])
{ "repo_name": "carragom/modoboa", "path": "modoboa/admin/management/commands/handle_mailbox_operations.py", "copies": "1", "size": "3197", "license": "isc", "hash": -5050249760159960000, "line_mean": 30.3431372549, "line_max": 77, "alpha_frac": 0.5680325305, "autogenerated": false, "ratio": 4.314439946018894, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5382472476518894, "avg_score": null, "num_lines": null }
"""A management command to apply mailbox operations.""" import logging import os import shutil from django.core.management.base import BaseCommand from modoboa.lib.exceptions import InternalError from modoboa.lib.sysutils import exec_cmd from modoboa.parameters import tools as param_tools from ...app_settings import load_admin_settings from ...models import MailboxOperation class OperationError(Exception): """Custom exception.""" pass class Command(BaseCommand): """Command definition""" help = "Handles rename and delete operations on mailboxes" # NOQA:A003 def __init__(self, *args, **kwargs): super(Command, self).__init__(*args, **kwargs) self.logger = logging.getLogger("modoboa.admin") def add_arguments(self, parser): """Add extra arguments to command line.""" parser.add_argument( "--pidfile", default="/tmp/handle_mailbox_operations.pid", help="Path to the file that will contain the PID of this process" ) def rename_mailbox(self, operation): if not os.path.exists(operation.argument): return new_mail_home = operation.mailbox.mail_home dirname = os.path.dirname(new_mail_home) if not os.path.exists(dirname): try: os.makedirs(dirname) except os.error as e: raise OperationError(str(e)) code, output = exec_cmd( "mv %s %s" % (operation.argument, new_mail_home) ) if code: raise OperationError(output) def delete_mailbox(self, operation): """Try to delete a mailbox tree on filesystem.""" if not os.path.exists(operation.argument): return def onerror(function, path, excinfo): """Handle errors.""" self.logger.critical( "delete failed (reason: {})".format(excinfo)) shutil.rmtree(operation.argument, False, onerror) def check_pidfile(self, path): """Check if this command is already running :param str path: path to the file containing the PID :return: a boolean, True means we can go further """ if os.path.exists(path): with open(path) as fp: pid = fp.read().strip() code, output = exec_cmd( "grep handle_mailbox_operations /proc/%s/cmdline" % pid ) if not code: return False with open(path, "w") as fp: print(os.getpid(), file=fp) return True def handle(self, *args, **options): """Command entry point.""" load_admin_settings() if not param_tools.get_global_parameter("handle_mailboxes"): return if not self.check_pidfile(options["pidfile"]): return for ope in MailboxOperation.objects.all(): try: f = getattr(self, "%s_mailbox" % ope.type) except AttributeError: continue try: f(ope) except (OperationError, InternalError) as e: self.logger.critical( "%s failed (reason: %s)", ope, str(e).decode("utf-8")) else: self.logger.info("%s succeed", ope) ope.delete() os.unlink(options["pidfile"])
{ "repo_name": "modoboa/modoboa", "path": "modoboa/admin/management/commands/handle_mailbox_operations.py", "copies": "1", "size": "3375", "license": "isc", "hash": -5150002537135292000, "line_mean": 31.4519230769, "line_max": 77, "alpha_frac": 0.5768888889, "autogenerated": false, "ratio": 4.326923076923077, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5403811965823077, "avg_score": null, "num_lines": null }
"""A management command to load Modoboa initial data: * Create a default super admin if none exists * Create groups and permissions """ from django.contrib.auth.models import Group from django.core.management.base import BaseCommand from modoboa.core import load_core_settings, PERMISSIONS from modoboa.core.extensions import exts_pool from modoboa.core.models import User, ObjectAccess from modoboa.lib import events from modoboa.lib.permissions import add_permissions_to_group from . import CloseConnectionMixin class Command(BaseCommand, CloseConnectionMixin): """Command defintion.""" help = "Load Modoboa initial data" def handle(self, *args, **options): """Command entry point.""" load_core_settings() if not User.objects.filter(is_superuser=True).count(): admin = User(username="admin", is_superuser=True) admin.set_password("password") admin.save() ObjectAccess.objects.create( user=admin, content_object=admin, is_owner=True) exts_pool.load_all() superadmin = User.objects.filter(is_superuser=True).first() groups = PERMISSIONS.keys() + [ role[0] for role in events.raiseQueryEvent("GetExtraRoles", superadmin, None) ] for groupname in groups: group, created = Group.objects.get_or_create(name=groupname) permissions = ( PERMISSIONS.get(groupname, []) + events.raiseQueryEvent("GetExtraRolePermissions", groupname) ) if not permissions: continue add_permissions_to_group(group, permissions) for extname in exts_pool.extensions.keys(): extension = exts_pool.get_extension(extname) extension.load_initial_data() events.raiseEvent("InitialDataLoaded", extname)
{ "repo_name": "RavenB/modoboa", "path": "modoboa/core/management/commands/load_initial_data.py", "copies": "2", "size": "1896", "license": "isc", "hash": -1339274210248851500, "line_mean": 32.8571428571, "line_max": 76, "alpha_frac": 0.6524261603, "autogenerated": false, "ratio": 4.1487964989059085, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5801222659205909, "avg_score": null, "num_lines": null }
"""A management command to load Modoboa initial data: * Create a default super admin if none exists * Create groups and permissions """ from functools import reduce from django.contrib.auth.models import Group from django.core.management.base import BaseCommand from modoboa.lib.permissions import add_permissions_to_group from ... import constants, extensions, models, signals class Command(BaseCommand): """Command definition.""" help = "Load Modoboa initial data" # NOQA:A003 def add_arguments(self, parser): """Add extra arguments to command.""" parser.add_argument( "--admin-username", default="admin", help="Username of the initial super administrator." ) parser.add_argument( "--extra-fixtures", action="store_true", default=False, help="Also load some fixtures from the admin application." ) def handle(self, *args, **options): """Command entry point.""" extensions.exts_pool.load_all() if not models.User.objects.filter(is_superuser=True).count(): admin = models.User( username=options["admin_username"], is_superuser=True) admin.set_password("password") admin.save() models.ObjectAccess.objects.create( user=admin, content_object=admin, is_owner=True) groups = list(constants.PERMISSIONS.keys()) for groupname in groups: group, created = Group.objects.get_or_create(name=groupname) results = signals.extra_role_permissions.send( sender=self.__class__, role=groupname) permissions = constants.PERMISSIONS.get(groupname, []) if results: permissions += reduce( lambda a, b: a + b, [result[1] for result in results]) if not permissions: continue add_permissions_to_group(group, permissions) for extname in list(extensions.exts_pool.extensions.keys()): extension = extensions.exts_pool.get_extension(extname) try: extension.load_initial_data() except Exception as e: self.stderr.write( "Unable to load initial data for '{}' ({}).".format( extname, str(e) ) ) else: signals.initial_data_loaded.send( sender=self.__class__, extname=extname ) if options["extra_fixtures"]: from modoboa.admin import factories factories.populate_database()
{ "repo_name": "modoboa/modoboa", "path": "modoboa/core/management/commands/load_initial_data.py", "copies": "1", "size": "2672", "license": "isc", "hash": 4869360091223776000, "line_mean": 34.6266666667, "line_max": 74, "alpha_frac": 0.5845808383, "autogenerated": false, "ratio": 4.583190394511149, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 75 }
"""A management command to load Modoboa initial data: * Create a default super admin if none exists * Create groups and permissions """ from __future__ import unicode_literals from functools import reduce from django.contrib.auth.models import Group from django.core.management.base import BaseCommand from modoboa.lib.cryptutils import random_key from modoboa.lib.permissions import add_permissions_to_group import modoboa.relaydomains.models as relay_models from ... import constants from ... import extensions from ... import models from ... import signals class Command(BaseCommand): """Command definition.""" help = "Load Modoboa initial data" def add_arguments(self, parser): """Add extra arguments to command.""" parser.add_argument( "--admin-username", default="admin", help="Username of the initial super administrator." ) parser.add_argument( "--extra-fixtures", action="store_true", default=False, help="Also load some fixtures from the admin application." ) def handle(self, *args, **options): """Command entry point.""" if not models.User.objects.filter(is_superuser=True).count(): admin = models.User( username=options["admin_username"], is_superuser=True) admin.set_password("password") admin.save() models.ObjectAccess.objects.create( user=admin, content_object=admin, is_owner=True) lc = models.LocalConfig.objects.first() condition = ( "core" not in lc._parameters or "secret_key" not in lc._parameters["core"]) if condition: lc.parameters.set_value("secret_key", random_key()) lc.save() for service_name in ["relay", "smtp"]: relay_models.Service.objects.get_or_create(name=service_name) extensions.exts_pool.load_all() groups = list(constants.PERMISSIONS.keys()) for groupname in groups: group, created = Group.objects.get_or_create(name=groupname) results = signals.extra_role_permissions.send( sender=self.__class__, role=groupname) permissions = ( constants.PERMISSIONS.get(groupname, []) + reduce(lambda a, b: a + b, [result[1] for result in results]) ) if not permissions: continue add_permissions_to_group(group, permissions) for extname in list(extensions.exts_pool.extensions.keys()): extension = extensions.exts_pool.get_extension(extname) extension.load_initial_data() signals.initial_data_loaded.send( sender=self.__class__, extname=extname) if options["extra_fixtures"]: from modoboa.admin import factories factories.populate_database()
{ "repo_name": "bearstech/modoboa", "path": "modoboa/core/management/commands/load_initial_data.py", "copies": "1", "size": "2931", "license": "isc", "hash": -568213284367465200, "line_mean": 33.4823529412, "line_max": 77, "alpha_frac": 0.6206073013, "autogenerated": false, "ratio": 4.329394387001477, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5450001688301477, "avg_score": null, "num_lines": null }
# A manager for files - this will record temporary and output files from # xia2, which can be used for composing a dump of "useful" files at the end # if processing. # # This will also be responsible for migrating the data - that is, when # the .xinfo file is parsed the directories referred to therein may be # migrated to a local disk. import contextlib import logging import os import shutil logger = logging.getLogger("xia2.Handlers.Files") class _FileHandler: """A singleton class to manage files.""" def __init__(self): self._temporary_files = [] self._html_files = {} self._log_files = {} self._xml_files = {} # for putting the reflection files somewhere nice... self._data_files = [] # same mechanism as log files - I want to rename files copied to the # DataFiles directory self._more_data_files = {} def cleanup(self, base_path): for f in self._temporary_files: try: os.remove(f) logger.debug("Deleted: %s", f) except Exception as e: logger.debug("Failed to delete: %s (%s)", f, str(e), exc_info=True) # copy the log files log_directory = base_path.joinpath("LogFiles") log_directory.mkdir(parents=True, exist_ok=True) for tag, source in self._log_files.items(): filename = log_directory.joinpath("%s.log" % tag.replace(" ", "_")) shutil.copyfile(source, filename) logger.debug(f"Copied log file {source} to {filename}") for tag, source in self._xml_files.items(): filename = log_directory.joinpath("%s.xml" % tag.replace(" ", "_")) shutil.copyfile(source, filename) logger.debug(f"Copied xml file {source} to {filename}") for tag, source in self._html_files.items(): filename = log_directory.joinpath("%s.html" % tag.replace(" ", "_")) shutil.copyfile(source, filename) logger.debug(f"Copied html file {source} to {filename}") # copy the data files data_directory = base_path.joinpath("DataFiles") data_directory.mkdir(parents=True, exist_ok=True) for f in self._data_files: filename = data_directory.joinpath(os.path.split(f)[-1]) shutil.copyfile(f, filename) logger.debug(f"Copied data file {f} to {filename}") for tag, ext in self._more_data_files: filename_out = data_directory.joinpath( "{}.{}".format(tag.replace(" ", "_"), ext) ) filename_in = self._more_data_files[(tag, ext)] shutil.copyfile(filename_in, filename_out) logger.debug(f"Copied extra data file {filename_in} to {filename_out}") def record_log_file(self, tag, filename): """Record a log file.""" self._log_files[tag] = filename def record_xml_file(self, tag, filename): """Record an xml file.""" self._xml_files[tag] = filename def record_html_file(self, tag, filename): """Record an html file.""" self._html_files[tag] = filename def record_data_file(self, filename): """Record a data file.""" if filename not in self._data_files: assert os.path.isfile(filename), "Required file %s not found" % filename self._data_files.append(filename) def record_more_data_file(self, tag, filename): """Record an extra data file.""" ext = os.path.splitext(filename)[1][1:] key = (tag, ext) self._more_data_files[key] = filename def get_data_file(self, base_path, filename): """Return the point where this data file will end up!""" if filename not in self._data_files: return filename data_directory = base_path.joinpath("DataFiles") data_directory.mkdir(parents=True, exist_ok=True) return str(data_directory.joinpath(os.path.split(filename)[-1])) def record_temporary_file(self, filename): # allow for file overwrites etc. if filename not in self._temporary_files: self._temporary_files.append(filename) FileHandler = _FileHandler() @contextlib.contextmanager def cleanup(base_path): try: yield finally: FileHandler.cleanup(base_path)
{ "repo_name": "xia2/xia2", "path": "src/xia2/Handlers/Files.py", "copies": "1", "size": "4358", "license": "bsd-3-clause", "hash": 2896722256271531000, "line_mean": 33.5873015873, "line_max": 84, "alpha_frac": 0.6023405232, "autogenerated": false, "ratio": 3.9332129963898916, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5035553519589892, "avg_score": null, "num_lines": null }
# A managing class (like database) for color and style of lines of all the G(r) and thus S(q) that are loaded and/or # calculated. from __future__ import (absolute_import, division, print_function) LineColorBase = ['black', 'red', 'blue', 'green', 'brown', 'orange'] LineStyleBase = ['-', '--', '-.'] LineMarkerBase = [None, 'o', '.', 'D', 's'] Q_MIN = 10. Q_MAX = 50. class PDFPlotManager(object): """ class to manage the color and line styles of G(r) and S(Q) """ def __init__(self): """ initialization """ self._currLineColorIndex = 0 self._currStandaloneGofRColorIndex = 0 self._sofqInfoDict = dict() # key: SofQ workspace name, value (tuple): color index, style-marker index self._gofrInfoDict = dict() # key: GofR workspace name self._maxLineStyleMarkerIndex = len(LineStyleBase) * len(LineMarkerBase) return def add_sofq(self, sq_ws_name): """ Add a S(Q) workspace to plot :param sq_ws_name: :return: """ if sq_ws_name not in self._sofqInfoDict: # new workspace self._sofqInfoDict[sq_ws_name] = self._currLineColorIndex, 0 self._currLineColorIndex += 1 if self._currLineColorIndex >= len(LineColorBase): self._currLineColorIndex = 0 # existing workspace color = LineColorBase[self._sofqInfoDict[sq_ws_name][0]] return color @staticmethod def retrieve_line_style_marker(style_marker_index): """ convert the combo-index of line style and marker index to line style and marker in string Parameters ---------- style_marker_index Returns ------- """ marker_index = style_marker_index // len(LineStyleBase) style_index = style_marker_index % len(LineStyleBase) return LineStyleBase[style_index], LineMarkerBase[marker_index] def add_gofr(self, sq_ws_name, gr_ws_name, curr_q_max): """add a G(r) line :param sq_ws_name: S(Q) workspace that is associated :param gr_ws_name: :param curr_q_max: :return: """ if sq_ws_name is None: # standalone G(r) which might come from a GofR data file color = LineColorBase[self._currStandaloneGofRColorIndex] line_style = ':' alpha = 1. line_marker = None self._currStandaloneGofRColorIndex %= len(LineColorBase) elif sq_ws_name not in self._sofqInfoDict: # it is possible that a S(Q) never been plotted??? raise RuntimeError('S(Q) workspace {0} has not been added. It is not allowed!'.format(sq_ws_name)) else: # G(r) from parent assert isinstance(curr_q_max, float), 'Current Q Max {0} must be a float but not a {1}' \ ''.format(curr_q_max, type(curr_q_max)) # get current information color_index, style_marker_index = self._sofqInfoDict[sq_ws_name] color = LineColorBase[color_index] line_style, line_marker = self.retrieve_line_style_marker(style_marker_index) # increase index counter for next style_marker_index += 1 if style_marker_index == self._maxLineStyleMarkerIndex: style_marker_index = 0 self._sofqInfoDict[sq_ws_name] = color_index, style_marker_index alpha = ((curr_q_max - Q_MIN) / (Q_MAX - Q_MIN) + 1.) * 0.5 # END-IF-ELSE self._gofrInfoDict[gr_ws_name] = color, line_style, alpha return color, line_style, line_marker, alpha def get_gr_line(self, gr_ws_name): """ get color, style and alpha for a G(r) line :param gr_ws_name: :return: """ return self._gofrInfoDict[gr_ws_name]
{ "repo_name": "neutrons/FastGR", "path": "addie/calculate_gr/pdf_lines_manager.py", "copies": "1", "size": "3913", "license": "mit", "hash": 6837063794193675000, "line_mean": 33.0260869565, "line_max": 116, "alpha_frac": 0.5770508561, "autogenerated": false, "ratio": 3.6638576779026217, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.47409085340026214, "avg_score": null, "num_lines": null }
# A mapping between model field internal datatypes and sensible # client-friendly datatypes. In virtually all cases, client programs # only need to differentiate between high-level types like number, string, # and boolean. More granular separation be may desired to alter the # allowed operators or may infer a different client-side representation SIMPLE_TYPES = { 'auto': 'key', 'foreignkey': 'key', 'biginteger': 'number', 'decimal': 'number', 'float': 'number', 'integer': 'number', 'positiveinteger': 'number', 'positivesmallinteger': 'number', 'smallinteger': 'number', 'nullboolean': 'boolean', 'char': 'string', 'email': 'string', 'file': 'string', 'filepath': 'string', 'image': 'string', 'ipaddress': 'string', 'slug': 'string', 'text': 'string', 'url': 'string', } # A mapping between the client-friendly datatypes and sensible operators # that will be used to validate a query condition. In many cases, these types # support more operators than what are defined, but are not include because # they are not commonly used. OPERATORS = { 'key': ('exact', '-exact', 'in', '-in'), 'boolean': ('exact', '-exact', 'in', '-in'), 'date': ('exact', '-exact', 'in', '-in', 'lt', 'lte', 'gt', 'gte', 'range', '-range'), 'number': ('exact', '-exact', 'in', '-in', 'lt', 'lte', 'gt', 'gte', 'range', '-range'), 'string': ('exact', '-exact', 'iexact', '-iexact', 'in', '-in', 'icontains', '-icontains', 'iregex', '-iregex'), 'datetime': ('exact', '-exact', 'in', '-in', 'lt', 'lte', 'gt', 'gte', 'range', '-range'), 'time': ('exact', '-exact', 'in', '-in', 'lt', 'lte', 'gt', 'gte', 'range', '-range'), } # A general mapping of formfield overrides for all subclasses. the mapping is # similar to the SIMPLE_TYPE_MAP, but the values reference internal # formfield classes, that is integer -> IntegerField. in many cases, the # validation performed may need to be a bit less restrictive than what the # is actually necessary INTERNAL_DATATYPE_FORMFIELDS = { 'integer': 'FloatField', 'positiveinteger': 'FloatField', 'positivesmallinteger': 'FloatField', 'smallinteger': 'FloatField', 'biginteger': 'FloatField', } # The minimum number of distinct values required when determining to set the # `searchable` flag on `DataField` instances during the `init` process. This # will only be applied to fields with a Avocado datatype of 'string' ENUMERABLE_MAXIMUM = 30 # Flag for enabling the history API HISTORY_ENABLED = True # The maximum size of a user's history. If the value is an integer, this # is the maximum number of allowed items in the user's history. Set to # `None` (or 0) to enable unlimited history. Note, in order to enforce this # limit, the `avocado history --prune` command must be executed to remove # the oldest history from each user based on this value. HISTORY_MAX_SIZE = None # App that the metadata migrations will be created for. This is typically the # project itself. METADATA_MIGRATION_APP = None # Directory for the migration backup fixtures. If None, this will default to # the fixtures dir in the app defined by `METADATA_MIGRATION_APP` METADATA_FIXTURE_DIR = None METADATA_FIXTURE_SUFFIX = 'avocado_metadata' METADATA_MIGRATION_SUFFIX = 'avocado_metadata_migration' # Query processors QUERY_PROCESSORS = { 'default': 'avocado.query.pipeline.QueryProcessor', } # Custom validation error and warnings messages VALIDATION_ERRORS = {} VALIDATION_WARNINGS = {} # Toggle whether DataField instances should cache the underlying data # for their most common data access methods. DATA_CACHE_ENABLED = True # These settings affect how queries can be shared between users. # A user is able to enter either a username or an email of another user # they wish to share the query with. To limit to only one type of sharing # set the appropriate setting to True and all others to false. SHARE_BY_USERNAME = True SHARE_BY_EMAIL = True SHARE_BY_USERNAME_CASE_SENSITIVE = True # Toggle whether the permissions system should be enabled. # If django-guardian is installed and this value is None or True, permissions # will be applied. If the value is True and django-guardian is not installed # it is an error. If set to False the permissions will not be applied. PERMISSIONS_ENABLED = None # Caches are used to improve performance across various APIs. The two primary # ones are data and query. Data cache is used for individual data field # caching such as counts, values, and aggregations. Query cache is used for # the ad-hoc queries built from a context and view. DATA_CACHE = 'default' QUERY_CACHE = 'default' # Name of the queue to use for scheduling and working on async jobs. ASYNC_QUEUE = 'avocado'
{ "repo_name": "murphyke/avocado", "path": "avocado/conf/global_settings.py", "copies": "3", "size": "4830", "license": "bsd-2-clause", "hash": -5710483870511314000, "line_mean": 37.64, "line_max": 77, "alpha_frac": 0.6937888199, "autogenerated": false, "ratio": 3.806146572104019, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 125 }
#: A mapping of group names to import paths to renderer instances RENDERERS = { "js": "require_media.renderers.javascript_requirement_renderer", "css": "require_media.renderers.css_requirement_renderer" } #: The list of all recognized groups GROUPS = ["css", "js"] #: The name of the requirement attribute on the request object REQUEST_ATTR_NAME = "_require_media_manager" #: The name of the requirements manager in template context CONTEXT_VAR_NAME = "requirements_manager" #: The default template for external JavaScript requirements JAVASCRIPT_EXTERNAL_TEMPLATE = '<script src="%s"></script>' #: The default template for inline JavaScript requirements JAVASCRIPT_INLINE_TEMPLATE = '<script>%s</script>' #: The default template for external CSS requirements CSS_EXTERNAL_TEMPLATE = '<link rel="stylesheet" type="text/css" href="%s">' #: The default template for inline CSS requirements CSS_INLINE_TEMPLATE = '<style>%s</style>' #: A mapping of requirement names to replacement names REQUIREMENT_ALIASES = {} #: A mapping of requirement group names to replacement names REQUIREMENT_GROUP_ALIASES = {}
{ "repo_name": "jeffkistler/django-require-media", "path": "src/require_media/defaults.py", "copies": "1", "size": "1120", "license": "bsd-3-clause", "hash": -3088532816050489000, "line_mean": 34, "line_max": 75, "alpha_frac": 0.7517857143, "autogenerated": false, "ratio": 3.98576512455516, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0005040322580645161, "num_lines": 32 }
""" Utilities for managing data inputs for Amara Copyright 2008-2015 Uche Ogbuji """ import zipfile import functools from enum import Enum from io import StringIO, BytesIO from amara3 import iri from urllib.request import urlopen class inputsourcetype(Enum): unknown = 0 stream = 1 string = 2 iri = 3 filename = 4 zipfilestream = 5 def factory(obj, defaultsourcetype=inputsourcetype.unknown, encoding=None, streamopenmode='rb', zipcheck=False): ''' Helper function to create an iterable of inputsources from compound sources such as a zip file Returns an iterable of input sources obj - object, possibly list or tuple of items to be converted into one or more inputsource ''' if isinstance(obj, inputsource): return obj _inputsource = functools.partial(inputsource, encoding=encoding, streamopenmode=streamopenmode) if isinstance(obj, tuple) or isinstance(obj, list): inputsources = [ _inputsource(o, sourcetype=defaultsourcetype) for o in obj ] #if isinstance(objs, str) or isinstance(objs, bytes) or isinstance(objs, bytearray): #Don't do a zipcheck unless we know we can rewind the obj #Because zipfile.is_zipfile fast forwards to EOF elif zipcheck and hasattr(obj, 'seek'): inputsources = [] if zipfile.is_zipfile(obj): def zipfilegen(): zf = zipfile.ZipFile(obj, 'r') #Mode must be r, w or a for info in zf.infolist(): #From the doc: Note If the ZipFile was created by passing in a file-like object as the first argument to the constructor, then the object returned by open() shares the ZipFile’s file pointer. Under these circumstances, the object returned by open() should not be used after any additional operations are performed on the ZipFile object. yield(_inputsource(zf.open(info, mode='r'))) inputsources = zipfilegen() else: #Because zipfile.is_zipfile fast forwards to EOF obj.seek(0, 0) else: inputsources = [_inputsource(obj)] return inputsources class inputsource(object): ''' A flexible class for managing input sources for e.g. XML processing Loosely based on Amara's old inputsource <https://github.com/zepheira/amara/blob/master/lib/lib/_inputsource.py> ''' def __init__(self, obj, siri=None, encoding=None, streamopenmode='rb', sourcetype=inputsourcetype.unknown): ''' obj - byte string, proper string (only if you really know what you're doing), file-like object (stream), file path or URI. uri - optional override URI. Base URI for the input source will be set to this value >>> from amara3 import inputsource >>> inp = inputsource('abc') >>> inp.stream <_io.StringIO object at 0x1056fbf78> >>> inp.iri >>> print(inp.iri) None >>> inp = inputsource(['abc', 'def']) #Now multiple streams in one source >>> inp.stream <_io.StringIO object at 0x1011aff78> >>> print(inp.iri) None >>> inp = next(inp) >>> inp.stream <_io.StringIO object at 0x1011af5e8> >>> print(inp.iri) None >>> ''' # from amara3 import inputsource; inp = inputsource('foo.zip') # from amara3 import inputsource; inp = inputsource('test/resource/std-examples.zip') # s = inp.stream.read(100) # s # b'<?xml version="1.0" encoding="UTF-8"?>\r\n<!-- edited with XML Spy v4.3 U (http://www.xmlspy.com) by M' # s # b'<?xml version="1.0" encoding="UTF-8"?>\r\n<collection xmlns="http://www.loc.gov/MARC21/slim">\r\n <reco' self.stream = None self.iri = siri self.sourcetype = sourcetype if obj in ('', b''): raise ValueError("Cannot parse an empty string as XML") if hasattr(obj, 'read'): #Create dummy Uri to use as base #uri = uri or uuid4().urn self.stream = obj #elif sourcetype == inputsourcetype.xmlstring: #See this article about XML detection heuristics #http://www.xml.com/pub/a/2007/02/28/what-does-xml-smell-like.html #uri = uri or uuid4().urn elif self.sourcetype == inputsourcetype.iri or (siri and iri.matches_uri_syntax(obj)): self.iri = siri or obj self.stream = urlopen(iri) elif self.sourcetype == inputsourcetype.filename or (siri and iri.is_absolute(obj) and not os.path.isfile(obj)): #FIXME: convert path to URI self.iri = siri or iri.os_path_to_uri(obj) self.stream = open(obj, streamopenmode) elif self.sourcetype == inputsourcetype.string or isinstance(obj, str) or isinstance(obj, bytes): self.stream = StringIO(obj) #If obj is beyond a certain length, don't even try it as a URI #if len(obj) < MAX_URI_LENGTH_FOR_HEURISTIC: # self.iri = iri.os_path_to_uri(obj) # self.stream = urlopen(siri) else: raise ValueError("Unable to recognize as an inputsource") return @staticmethod def text(obj, siri=None, encoding=None): ''' Set up an input source from text, according to the markup convention of the term (i.e. in Python terms a string with XML, HTML, fragments thereof, or tag soup) Helps with processing content sources that are not unambiguously XML or HTML strings (e.g. could be mistaken for filenames or IRIs) ''' return inputsource(obj, siri, encoding, sourcetype=inputsourcetype.string)
{ "repo_name": "uogbuji/amara3-iri", "path": "pylib/inputsource.py", "copies": "1", "size": "5762", "license": "apache-2.0", "hash": -942931378717529700, "line_mean": 40.4388489209, "line_max": 356, "alpha_frac": 0.6274305556, "autogenerated": false, "ratio": 3.891891891891892, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5019322447491892, "avg_score": null, "num_lines": null }
""" Some utilities for general use in Amara Copyright 2008-2015 Uche Ogbuji """ def coroutine(func): ''' Decorator: Eliminate the need to call next() to kick-start a co-routine From David Beazley: http://www.dabeaz.com/generators/index.html ''' def start(*args,**kwargs): coro = func(*args,**kwargs) next(coro) return coro return start def parse_requirement(r): ''' Parse out package & version from requirements.txt format For example, might use in setup.py as follows (for requires=REQUIREMENTS, in the setup function): with open(REQ_FILENAME) as infp: #See https://pip.pypa.io/en/stable/reference/pip_install/#requirements-file-format reqs = [r.split('#', 1)[0].strip() for r in infp.read().split('\n') if r.split('#', 1)[0].strip() ] REQUIREMENTS = [parse_requirement(r) for r in reqs] >>> from amara3.util import parse_requirement >>> reqtxt = """amara3-iri==3.0.0b3 ... pymarc ... rdflib ... mmh3 ... pytest ... versa>=0.3.3 ... ... #From Versa pyreqs.txt ... amara3-xml==3.0.0a6 ... """ >>> for line in reqtxt.splitlines(): ... parse_requirement(line) ... 'amara3 (==3.0.0b3)' 'pymarc' 'rdflib' 'mmh3' 'pytest' 'versa (>=0.3.3)' '' '#From Versa pyreqs.txt' 'amara3 (==3.0.0a6)' ''' import re #Defying PEP 8 for perf of other routines m = re.search('[<>=][=]', r) if m: package = r[:m.start()] version = r[m.start():] if '-' in package: package = package.split('-')[0] return '{} ({})'.format(package, version) else: return r
{ "repo_name": "uogbuji/amara3-iri", "path": "pylib/util.py", "copies": "1", "size": "1724", "license": "apache-2.0", "hash": 4384398852093323300, "line_mean": 25.1212121212, "line_max": 107, "alpha_frac": 0.5609048724, "autogenerated": false, "ratio": 3.2284644194756553, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4289369291875655, "avg_score": null, "num_lines": null }
# amara3.uxml.treeutil ''' Various utilities related to amara3's lightweight tree implementation, includes some operations widely associated with DOM, but in the form of utility functions rather than methods. ''' import itertools from amara3.uxml.tree import * __all__ = ['descendants', 'select_elements', 'select_name', 'select_name_pattern', 'select_value', 'select_attribute', 'following_siblings', 'select_pattern', 'make_pretty'] def descendants(elem): ''' Yields all the elements descendant of elem in document order ''' for child in elem.xml_children: if isinstance(child, element): yield child yield from descendants(child) def select_elements(source): ''' Yields all the elements from the source source - if an element, yields all child elements in order; if any other iterator yields the elements from that iterator ''' if isinstance(source, element): source = source.xml_children return filter(lambda x: isinstance(x, element), source) def select_name(source, name): ''' Yields all the elements with the given name source - if an element, starts with all child elements in order; can also be any other iterator name - will yield only elements with this name ''' return filter(lambda x: x.xml_name == name, select_elements(source)) def select_name_pattern(source, pat): ''' Yields elements from the source whose name matches the given regular expression pattern source - if an element, starts with all child elements in order; can also be any other iterator pat - re.pattern object ''' return filter(lambda x: pat.match(x.xml_name) is not None, select_elements(source)) def select_value(source, val): ''' Yields elements from the source with the given value (accumulated child text) source - if an element, starts with all child elements in order; can also be any other iterator val - string value to match ''' if isinstance(source, element): source = source.xml_children return filter(lambda x: x.xml_value == val, source) def select_attribute(source, name, val=None): ''' Yields elements from the source having the given attrivute, optionally with the given attribute value source - if an element, starts with all child elements in order; can also be any other iterator name - attribute name to check val - if None check only for the existence of the attribute, otherwise compare the given value as well ''' def check(x): if val is None: return name in x.xml_attributes else: return name in x.xml_attributes and x.xml_attributes[name] == val return filter(check, select_elements(source)) def following_siblings(elem): ''' Yields elements and text which have the same parent as elem, but come afterward in document order ''' it = itertools.dropwhile(lambda x: x != elem, elem.xml_parent.xml_children) next(it, None) #Skip the element itself, if any return it # MATCHED_STATE = object() def attr_test(next, name): def _attr_test(node): if isinstance(node, element) and name in node.xml_attributes: return next return _attr_test def name_test(next, name): def _name_test(node): if isinstance(node, element) and node.xml_name == name: return next return _name_test def elem_test(next): def _elem_test(node): if isinstance(node, element): return next return _elem_test def any_until(next): def _any_until(node): if isinstance(node, element): next_next = next(node) if next_next is not None: return next_next return _any_until #Return this same state until we can match the next return _any_until def any_(next, funcs): def _any(node): if any( (func(node) for func in funcs) ): return next return _any def _prep_pattern(pattern): next_state = MATCHED_STATE #Work from the end of the pattern back to the beginning for i in range(len(pattern)): stage = pattern[-i-1] #reverse indexing if isinstance(stage, str): if stage == '*': next_state = elem_test(next_state) elif stage == '**': next_state = any_until(next_state) else: next_state = name_test(next_state, stage) elif isinstance(stage, tuple): new_tuple = tuple(( name_test(substage) if isinstance(substage, str) else substage for substage in stage )) next_state = any_(next_state, new_tuple) else: raise ValueError('Cannot interpret pattern component {0}'.format(repr(stage))) return next_state def select_pattern(node, pattern, state=None): ''' Yield descendant nodes matching the given pattern specification pattern - tuple of steps, each of which matches an element by name, with "*" acting like a wildcard, descending the tree in tuple order sort of like a subset of XPath in Python tuple form state - for internal use only pattern examples: ("a", "b", "c") - all c elements whose parent is a b element whose parent is an a element whose parent is node ("*", "*") - any "grandchild" of node ("*", "*", "*") - any "great grandchild" of node ("**", "a") - any a descendant of node >>> from amara3.uxml import tree >>> from amara3.uxml.treeutil import * >>> >>> tb = tree.treebuilder() >>> DOC = '<a xmlns="urn:namespaces:suck"><b><x>1</x></b><c><x>2</x><d><x>3</x></d></c><x>4</x><y>5</y></a>' >>> root = tb.parse(DOC) >>> results = [ e.xml_value for e in select_pattern(root, ('**', 'x')) ] >>> results ['1', '2', '3', '4'] ''' if state is None: state = _prep_pattern(pattern) #for child in select_elements(elem): if isinstance(node, element): for child in node.xml_children: new_state = state(child) if new_state == MATCHED_STATE: yield child elif new_state is not None: yield from select_pattern(child, None, state=new_state) return def make_pretty(elem, depth=0, indent=' '): ''' Add text nodes as possible to all descendants of an element for spacing & indentation to make the MicroXML as printed easier for people to read. Will not modify the value of any text node which is not already entirely whitespace. Warning: even though this operaton avoids molesting text nodes which already have whitespace, it still makes changes which alter the text. Not all whitespace in XML is ignorable. In XML cues from the DTD indicate which whitespace can be ignored. No such cues are available for MicroXML, so use this function with care. That said, in many real world applications of XML and MicroXML, this function causes no problems. elem - target element whose descendant nodes are to be modified. returns - the same element, which has been updated in place >>> from amara3.uxml import tree >>> from amara3.uxml.treeutil import * >>> DOC = '<a><b><x>1</x></b><c><x>2</x><d><x>3</x></d></c><x>4</x><y>5</y></a>' >>> tb = tree.treebuilder() >>> root = tb.parse(DOC) >>> len(root.xml_children) 4 >>> make_pretty(root) <uxml.element (8763373718343) "a" with 9 children> >>> len(root.xml_children) 9 >>> root.xml_encode() '<a>\n <b>\n <x>1</x>\n </b>\n <c>\n <x>2</x>\n <d>\n <x>3</x>\n </d>\n </c>\n <x>4</x>\n <y>5</y>\n</a>' ''' depth += 1 updated_child_list = [] updated_child_ix = 0 for child in elem.xml_children: if isinstance(child, element): if updated_child_ix % 2: updated_child_list.append(child) updated_child_ix += 1 else: #It's the turn for text, but we have an element new_text = text('\n' + indent*depth, elem) updated_child_list.append(new_text) updated_child_list.append(child) updated_child_ix += 2 make_pretty(child, depth) else: if child.xml_value.strip(): #More to it than whitespace, so leave alone #Note: if only whitespace entities are used, will still be left alone updated_child_list.append(child) updated_child_ix += 1 else: #Only whitespace, so replace with proper indentation new_text = text('\n' + indent*depth, elem) updated_child_list.append(new_text) updated_child_ix += 1 #Trailing indentation might be needed if not(updated_child_ix % 2): new_text = text('\n' + indent*(depth-1), elem) updated_child_list.append(new_text) #updated_child_ix += 1 #About to be done, so not really needed elem.xml_children = updated_child_list return elem
{ "repo_name": "uogbuji/amara3-xml", "path": "pylib/uxml/treeutil.py", "copies": "1", "size": "9050", "license": "apache-2.0", "hash": -692721633668344600, "line_mean": 37.025210084, "line_max": 173, "alpha_frac": 0.6232044199, "autogenerated": false, "ratio": 3.859275053304904, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4982479473204904, "avg_score": null, "num_lines": null }
# amara3.uxml.uxpath.functions '''Built-in functions for MicroXPath ''' __all__ = [ 'BUILTIN_FUNCTIONS', ] #import operator from functools import wraps from amara3.uxml.tree import node, element, strval from .ast import root_node, attribute_node, index_docorder, to_string, to_number, to_boolean def boolean_arg(ctx, obj): ''' Handles LiteralObjects as well as computable arguments ''' if hasattr(obj, 'compute'): obj = next(obj.compute(ctx), False) return to_boolean(obj) def number_arg(ctx, obj): ''' Handles LiteralObjects as well as computable arguments ''' if hasattr(obj, 'compute'): obj = next(obj.compute(ctx), False) return to_number(obj) def string_arg(ctx, obj): ''' Handles LiteralObjects as well as computable arguments ''' if hasattr(obj, 'compute'): obj = next(obj.compute(ctx), False) return to_string(obj) BUILTIN_FUNCTIONS = {} def microxpath_function(name): def _microxpath_function(f): BUILTIN_FUNCTIONS[name] = f #global BUILTIN_FUNCTIONS @wraps(f) def wrapper(*args, **kwargs): return f(*args, **kwargs) return wrapper return _microxpath_function @microxpath_function('name') def name(ctx, obj=None): ''' Yields one string a node name or the empty string, operating on the first item in the provided obj, or the current item if obj is omitted If this item is a node, yield its node name (generic identifier), otherwise yield '' If obj is provided, but empty, yield '' ''' if obj is None: item = ctx.item elif hasattr(obj, 'compute'): item = next(obj.compute(ctx), None) else: item = obj if isinstance(item, node): yield item.xml_name else: yield '' @microxpath_function('last') def last(ctx): ''' ''' #FIXME: Implement yield -1 @microxpath_function('count') def count(ctx, obj): ''' Yields one number, count of items in the argument sequence ''' yield len(list(obj.compute(ctx))) @microxpath_function('string') def string_(ctx, seq=None): ''' Yields one string, derived from the argument literal (or the first item in the argument sequence, unless empty in which case yield '') as follows: * If a node, yield its string-value * If NaN, yield 'NaN' * If +0 or -0, yield '0' * If positive infinity, yield 'Infinity' * If negative infinity, yield '-Infinity' * If an integer, no decimal point and no leading zeros * If a non-integer number, at least one digit before the decimal point and at least one digit after * If boolean, either 'true' or 'false' ''' if seq is None: item = ctx.item elif hasattr(seq, 'compute'): item = next(seq.compute(ctx), '') else: item = seq yield next(to_string(item), '') def flatten(iterables): return (elem for it in iterables for elem in ([it] if isinstance(it, str) else it)) @microxpath_function('concat') def concat(ctx, *strings): ''' Yields one string, concatenation of argument strings ''' strings = flatten([ (s.compute(ctx) if callable(s) else s) for s in strings ]) strings = (next(string_arg(ctx, s), '') for s in strings) #assert(all(map(lambda x: isinstance(x, str), strings))) #FIXME: Check arg types yield ''.join(strings) @microxpath_function('starts-with') def starts_with(ctx, full, part): ''' Yields one boolean, whether the first string starts with the second ''' full = next(string_arg(ctx, full), '') part = next(string_arg(ctx, part), '') yield full.startswith(part) @microxpath_function('contains') def contains(ctx, full, part): ''' Yields one boolean, whether the first string contains the second ''' full = next(string_arg(ctx, full), '') part = next(string_arg(ctx, part), '') yield part in full @microxpath_function('substring-before') def substring_before(ctx, full, part): ''' Yields one string ''' full = next(string_arg(ctx, full), '') part = next(string_arg(ctx, part), '') yield full.partition(part)[0] @microxpath_function('substring-after') def substring_after(ctx, full, part): ''' Yields one string ''' full = next(string_arg(ctx, full), '') part = next(string_arg(ctx, part), '') yield full.partition(part)[-1] @microxpath_function('substring') def substring(ctx, full, start, length): ''' Yields one string ''' full = next(string_arg(ctx, full), '') start = int(next(to_number(start))) length = int(next(to_number(length))) yield full[start-1:start-1+length] @microxpath_function('string-length') def string_length(ctx, s=None): ''' Yields one number ''' if s is None: s = ctx.node elif callable(s): s = next(s.compute(ctx), '') yield len(s) @microxpath_function('normalize-space') def normalize_space(ctx, s): ''' Yields one string ''' #FIXME: Implement raise NotImplementedError yield s @microxpath_function('translate') def translate(ctx, s, subst): ''' Yields one string ''' #FIXME: Implement raise NotImplementedError yield s @microxpath_function('same-lang') def same_lang(ctx, seq, lang): ''' Yields one boolean ''' #FIXME: Implement raise NotImplementedError yield s @microxpath_function('boolean') def boolean(ctx, seq): ''' Yields one boolean, false if the argument sequence is empty, otherwise * false if the first item is a boolean and false * false if the first item is a number and positive or negative zero or NaN * false if the first item is a string and '' * true in all other cases ''' if hasattr(seq, 'compute'): obj = next(seq.compute(ctx), '') else: obj = seq yield next(to_boolean(obj), '') @microxpath_function('not') def _not(ctx, obj): ''' Yields one boolean ''' yield not next(boolean_arg(ctx, obj), False) @microxpath_function('true') def _true(ctx): ''' Yields one boolean, true ''' yield True @microxpath_function('false') def _false(ctx): ''' Yields one boolean, false ''' yield False @microxpath_function('number') def number(ctx, seq=None): ''' Yields one float, derived from the first item in the argument sequence (unless empty in which case yield NaN) as follows: * If string with optional whitespace followed by an optional minus sign followed by a Number followed by whitespace, converte to the IEEE 754 number that is nearest (according to the IEEE 754 round-to-nearest rule) to the mathematical value represented by the string; in case of any other string yield NaN * If boolean true yield 1; if boolean false yield 0 * If a node convert to string as if by a call to string(); yield the same value as if passed that string argument to number() ''' if hasattr(seq, 'compute'): obj = next(seq.compute(ctx), '') else: obj = seq yield next(to_number(obj), '') @microxpath_function('for-each') def foreach_(ctx, seq, expr): ''' Yields the result of applying an expression to each item in the input sequence. * seq: input sequence * expr: expression to be converted to string, then dynamically evaluated for each item on the sequence to produce the result ''' from . import context, parse as uxpathparse if hasattr(seq, 'compute'): seq = seq.compute(ctx) expr = next(string_arg(ctx, expr), '') pexpr = uxpathparse(expr) for item in seq: innerctx = ctx.copy(item=item) yield from pexpr.compute(innerctx) @microxpath_function('lookup') def lookup_(ctx, tableid, key): ''' Yields a sequence of a single value, the result of looking up a value from the tables provided in the context, or an empty sequence if lookup is unsuccessful * tableid: id of the lookup table to use * expr: expression to be converted to string, then dynamically evaluated for each item on the sequence to produce the result ''' tableid = next(string_arg(ctx, tableid), '') key = next(string_arg(ctx, key), '') #value = ctx. for item in seq: innerctx = ctx.copy(item=item) yield from pexpr.compute(innerctx) @microxpath_function('sum') def _sum(ctx, seq): ''' Yields one number, the sum, for each item in the argument sequence, of the result of converting as if by a call to number() ''' #FIXME: Implement raise NotImplementedError yield seq @microxpath_function('floor') def _floor(ctx, num): ''' Yields one number, the largest (closest to positive infinity) number that is not greater than the argument and that is an integer. ''' #FIXME: Implement raise NotImplementedError yield num @microxpath_function('ceiling') def _ceiling(ctx, num): ''' Yields one number, the smallest (closest to negative infinity) number that is not less than the argument and that is an integer. ''' #FIXME: Implement raise NotImplementedError yield num @microxpath_function('round') def _round(ctx, num): ''' Yields one number, that which is closest to the argument and that is an integer. If there are two such numbers, then the one that is closest to positive infinity is returned. If the argument is NaN, then NaN is returned. If the argument is positive infinity, then positive infinity is returned. If the argument is negative infinity, then negative infinity is returned. If the argument is positive zero, then positive zero is returned. If the argument is negative zero, then negative zero is returned. If the argument is less than zero, but greater than or equal to -0.5, then negative zero is returned. ''' #FIXME: Implement raise NotImplementedError yield num
{ "repo_name": "uogbuji/amara3-xml", "path": "pylib/uxml/uxpath/functions.py", "copies": "1", "size": "9907", "license": "apache-2.0", "hash": 1780393990239518200, "line_mean": 26.8286516854, "line_max": 606, "alpha_frac": 0.654688604, "autogenerated": false, "ratio": 3.829532276768458, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4984220880768458, "avg_score": null, "num_lines": null }
# amara3.uxml.uxpath.lexrules ''' Heavy debt to: https://github.com/emory-libraries/eulxml/blob/master/eulxml/xpath/lexrules.py ''' import re from ply.lex import TOKEN OPERATOR_NAMES = { 'or': 'OR_OP', 'and': 'AND_OP', 'div': 'DIV_OP', 'mod': 'MOD_OP', } tokens = [ 'PATH_SEP', 'ABBREV_PATH_SEP', 'ABBREV_STEP_SELF', 'ABBREV_STEP_PARENT', 'AXIS_SEP', 'ABBREV_AXIS_AT', 'OPEN_PAREN', 'CLOSE_PAREN', 'OPEN_BRACKET', 'CLOSE_BRACKET', 'UNION_OP', 'EQUAL_OP', 'REL_OP', 'PLUS_OP', 'MINUS_OP', 'MULT_OP', 'STAR_OP', 'COMMA', 'LITERAL', 'FLOAT', 'INTEGER', 'NODETEXTTEST', 'NAME', 'DOLLAR', ] + list(OPERATOR_NAMES.values()) t_PATH_SEP = r'/' t_ABBREV_PATH_SEP = r'//' t_ABBREV_STEP_SELF = r'\.' t_ABBREV_STEP_PARENT = r'\.\.' t_AXIS_SEP = r'::' t_ABBREV_AXIS_AT = r'@' t_OPEN_PAREN = r'\(' t_CLOSE_PAREN = r'\)' t_OPEN_BRACKET = r'\[' t_CLOSE_BRACKET = r'\]' t_UNION_OP = r'\|' t_EQUAL_OP = r'!?=' t_REL_OP = r'[<>]=?' t_PLUS_OP = r'\+' t_MINUS_OP = r'-' t_COMMA = r',' t_DOLLAR = r'\$' t_STAR_OP = r'\*' t_ignore = ' \t\r\n' NameStartChar = r'(' + r'[A-Z]|_|[a-z]|\xc0-\xd6]|[\xd8-\xf6]|[\xf8-\u02ff]|' + \ r'[\u0370-\u037d]|[\u037f-\u1fff]|[\u200c-\u200d]|[\u2070-\u218f]|' + \ r'[\u2c00-\u2fef]|[\u3001-\uD7FF]|[\uF900-\uFDCF]|[\uFDF0-\uFFFD]' + \ r'|[\U00010000-\U000EFFFF]' + r')' # additional characters allowed in NCNames after the first character NameChar_extras = r'[-.0-9\xb7\u0300-\u036f\u203f-\u2040]' NAME_REGEX = r'(' + NameStartChar + r')(' + \ NameStartChar + r'|' + NameChar_extras + r')*' NODE_TYPES = set(['text', 'node']) @TOKEN(NAME_REGEX) def t_NAME(t): # Check for operators t.type = OPERATOR_NAMES.get(t.value, 'NAME') return t def t_LITERAL(t): r""""[^"]*"|'[^']*'""" t.value = t.value[1:-1] return t def t_FLOAT(t): r'\d+\.\d*|\.\d+' t.value = float(t.value) return t def t_INTEGER(t): r'\d+' t.value = int(t.value) return t def t_NODETEXTTEST(t): r'text\(\)|node\(\)' return t def t_error(t): raise TypeError("Unknown text '{}'".format(t.value))
{ "repo_name": "uogbuji/amara3-xml", "path": "pylib/uxml/uxpath/lexrules.py", "copies": "1", "size": "2289", "license": "apache-2.0", "hash": -145919353355869820, "line_mean": 20.5943396226, "line_max": 93, "alpha_frac": 0.5181301879, "autogenerated": false, "ratio": 2.4612903225806453, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3479420510480645, "avg_score": null, "num_lines": null }
# amara3.uxml.uxpath ''' from amara3.uxml.uxpath import qquery results = qquery(b'<a>1<b>2</b>3</a>', 'a/text()')) next(results).xml_value next(results).xml_value from amara3.uxml import tree DOC = '<a><b><x>1</x></b><c><x>2</x><d><x>3</x></d></c><x>4</x><y>5</y></a>' tb = tree.treebuilder() root = tb.parse(DOC) from amara3.uxml.uxpath import context, parse as uxpathparse ctx = context(root) parsed_expr = uxpathparse('b/x') result = parsed_expr.compute(ctx) print(result) print(list(result)) ''' import os import re import tempfile from ply import lex, yacc #from amara3 import iri #from amara3.uxml import xml from amara3.uxml import tree from amara3.uxml.treeutil import * from amara3.uxml.tree import node as nodetype from amara3.util import coroutine from . import lexrules, parserules, ast from .functions import BUILTIN_FUNCTIONS __all__ = ['lexer', 'parser', 'parse', 'context']#, 'serialize'] lexer = None #BUILDuxpath.LEX=1; python -m amara3.uxml.uxpath if 'BUILDuxpath.LEX' in os.environ: # Build with cached lex table. Meant for developers to do and commit the updated file. Will fail without write access on the source directory. lexdir = os.path.dirname(lexrules.__file__) try: lexer = lex.lex(module=lexrules, optimize=1, outputdir=lexdir, reflags=re.UNICODE) except IOError as e: import errno if e.errno != errno.EACCES: raise if lexer is None: lexer = lex.lex(module=lexrules, reflags=re.UNICODE) # Generate parsetab.py parsedir = os.path.dirname(parserules.__file__) if (not os.access(parsedir, os.W_OK)): parsedir = tempfile.gettempdir() parser = yacc.yacc(module=parserules, outputdir=parsedir)#, debug=True) def parse(xpath): ''' Parse an xpath. >>> from amara3.uxml.uxpath import parse >>> xp = parse('a/text()') ''' # Explicitly specify the lexer created above, otherwise parser.parse will use the most-recently created lexer. (Ewww! Wha?!) return parser.parse(xpath, lexer=lexer)#, debug=True) class context(object): def __init__(self, item, pos=None, variables=None, functions=None, lookuptables=None, extras=None, parent=None, force_root=True): ''' Note: No explicit context size. Will be dynamically computed if needed ''' self.item = item if force_root and isinstance(item, nodetype): self.item = ast.root_node.get(item) self.pos = pos self.variables = variables or {} self.functions = functions or BUILTIN_FUNCTIONS self.extras = extras or {} #Needed for the case where the context node is a text node self.parent = parent or nodetype.xml_parent self.lookuptables = lookuptables or {} def copy(self, item=None, pos=None, variables=None, functions=None, lookuptables=None, extras=None, parent=None): item = item if item else self.item pos = pos if pos else self.pos variables = variables if variables else self.variables functions = functions if functions else self.functions lookuptables = lookuptables if lookuptables else self.lookuptables extras = extras if extras else self.extras parent = parent if parent else self.parent return context(item, pos=pos, variables=variables, functions=functions, lookuptables=lookuptables, extras=extras, parent=parent, force_root=False) def qquery(xml_thing, xpath_thing, vars=None, funcs=None, force_root=True): ''' Quick query. Convenience for using the MicroXPath engine. Give it some XML and an expression and it will yield the results. No fuss. xml_thing - bytes or string, or amara3.xml.tree node xpath_thing - string or parsed XPath expression vars - optional mapping of variables, name to value funcs - optional mapping of functions, name to function object >>> from amara3.uxml.uxpath import qquery >>> results = qquery(b'<a>1<b>2</b>3</a>', 'a/text()')) >>> next(results).xml_value '1' >>> next(results).xml_value '3' ''' root = None if isinstance(xml_thing, nodetype): root = xml_thing elif isinstance(xml_thing, str): tb = tree.treebuilder() root = tb.parse(xml_thing) elif isinstance(xml_thing, bytes): tb = tree.treebuilder() #Force UTF-8 root = tb.parse(xml_thing.decode('utf-8')) if not root: return if isinstance(xpath_thing, str): parsed_expr = parse(xpath_thing) ctx = context(root, variables=vars, functions=funcs, force_root=force_root) result = parsed_expr.compute(ctx) yield from result
{ "repo_name": "uogbuji/amara3-xml", "path": "pylib/uxml/uxpath/__init__.py", "copies": "1", "size": "4653", "license": "apache-2.0", "hash": 1192621488595666700, "line_mean": 33.2132352941, "line_max": 154, "alpha_frac": 0.6701053084, "autogenerated": false, "ratio": 3.4364844903988185, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.46065897987988186, "avg_score": null, "num_lines": null }
# amara3.uxml.writer ''' Raw XML writer ''' from enum import Enum #https://docs.python.org/3.4/library/enum.html from xml.sax.saxutils import escape, quoteattr from amara3.uxml import tree, xml class token(Enum): start_open = 1 start_close = 2 end_open = 3 end_close = 4 empty_close = 5 attr_quote = 6 between_attr = 7 pre_attr = 8 attr_equals = 9 TOKENS = { token.start_open: '<', token.start_close: '>', token.end_open: '</', token.end_close: '>', token.empty_close: '/>', # token.attr_quote: '"', # Let quoteattr handle this token.pre_attr: ' ', token.between_attr: ' ', token.attr_equals: '=', } class context(Enum): start_element = 1 end_element = 2 element_name = 3 attribute_name = 4 attribute_text = 5 text = 6 class raw(object): ''' >>> import io >>> from amara3.uxml import writer >>> fp = io.StringIO() #or is it better to use BytesIO? >>> w = writer.raw(fp) >>> w.start_element('spam') >>> w.text('eggs') >>> w.end_element('spam') >>> fp.getvalue() '<spam>eggs</spam>' ''' def __init__(self, fp=None, whandler=None, indent=None, depth=0): #FIXME: check that fp *or* whandler are not None self._fp = fp self._whandler = whandler(fp) if whandler else self self._indent = str(indent) if indent else None self._depth = depth self._awaiting_indent = False return def write(self, ctx, text): # Had to take out context.attribute_text to avoid double escaping # if ctx in (context.text, context.attribute_text): if ctx in (context.text,): text = escape(text) if isinstance(text, token): text = TOKENS[text] self._fp.write(text) return def start_element(self, name, attribs=None, empty=False): ''' attribs - mapping from MicroXML attribute name to value ''' if self._awaiting_indent and self._indent: self._whandler.write(context.text, '\n') self._whandler.write(context.text, self._indent*self._depth) self._awaiting_indent = False attribs = attribs or {} self._whandler.write(context.start_element, token.start_open) self._whandler.write(context.element_name, name) first_attribute = True for k, v in attribs.items(): if first_attribute: self._whandler.write(context.start_element, token.pre_attr) first_attribute = False else: self._whandler.write(context.start_element, token.between_attr) self._whandler.write(context.attribute_name, k) self._whandler.write(context.start_element, token.attr_equals) # Check whether we need to extract quoteattr(v) at [0] and [-1] and write these in start_element context self._whandler.write(context.attribute_text, quoteattr(v)) if empty: self._whandler.write(context.start_element, token.empty_close) if self._indent: self._whandler.write(context.text, '\n') self._whandler.write(context.text, self._indent*self._depth) else: self._whandler.write(context.start_element, token.start_close) self._depth += 1 self._awaiting_indent = True return def end_element(self, name): self._whandler.write(context.end_element, token.end_open) self._whandler.write(context.element_name, name) self._whandler.write(context.end_element, token.end_close) if self._indent: self._whandler.write(context.text, '\n') self._whandler.write(context.text, self._indent*self._depth) self._depth -= 1 self._awaiting_indent = False return def text(self, text): self._whandler.write(context.text, text) return class namespacer(raw): ''' Writer that adds namespace information to output mapping = {} >>> import io >>> from amara3.uxml import writer >>> fp = io.StringIO() >>> w = writer.raw(fp) >>> w.start_element('spam') >>> w.text('eggs') >>> w.end_element('spam') >>> fp.getvalue() '<spam>eggs</spam>' ''' def __init__(self, fp, whandler=None, prefixes=None, mapping=None): raw.__init__(self, fp=fp, whandler=whandler) self._mapping = mapping or {} self._prefixes = prefixes or {} self._first_element = True return def start_element(self, name, attribs=None): self._ns_handled = False raw.start_element(self, name, attribs=attribs) self._first_element = False def write(self, ctx, text): # Had to take out context.attribute_text to avoid double escaping # if ctx in (context.text, context.attribute_text): if ctx in (context.text,): text = escape(text) if ctx == context.start_element: if self._first_element and text in (token.pre_attr, token.start_close) and not self._ns_handled: #Namespace declarations here for k, v in self._prefixes.items(): self._fp.write(TOKENS[token.pre_attr]) self._fp.write('xmlns:' + k if k else 'xmlns') self._fp.write(TOKENS[token.attr_equals]) # Check whether we need to extract quoteattr(v) at [0] and [-1] and write these in start_element context self._fp.write(quoteattr(v)) #self._fp.write(TOKENS[token.pre_attr]) self._ns_handled = True if ctx == context.element_name: #Include prefix, if there's one prefix = self._mapping.get(text, ('', ''))[1] if prefix: self._fp.write(prefix + ':') if ctx == context.attribute_name: #Include prefix, if there's one prefix = self._mapping.get('@' + text, ('', ''))[1] if prefix: self._fp.write(prefix + ':') if isinstance(text, token): text = TOKENS[text] self._fp.write(text) return def write(elem, a_writer): ''' Write a MicroXML element node (yes, even one representign a whole document) elem - Amara MicroXML element node to be written out writer - instance of amara3.uxml.writer to implement the writing process ''' a_writer.start_element(elem.xml_name, attribs=elem.xml_attributes) for node in elem.xml_children: if isinstance(node, tree.element): write(node, a_writer) elif isinstance(node, tree.text): a_writer.text(node) a_writer.end_element(elem.xml_name) return
{ "repo_name": "uogbuji/amara3-xml", "path": "pylib/uxml/writer.py", "copies": "1", "size": "6770", "license": "apache-2.0", "hash": 8972212698489540000, "line_mean": 33.3654822335, "line_max": 124, "alpha_frac": 0.582127031, "autogenerated": false, "ratio": 3.7444690265486726, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9820349091493731, "avg_score": 0.001249393210988215, "num_lines": 197 }
#amara.lib._inputsource #Named with _ to avoid clash with amara.lib.inputsource class from __future__ import with_statement import os import urllib, urllib2 from cStringIO import StringIO from uuid import uuid4 from amara.lib import IriError from amara._expat import InputSource from amara.lib.xmlstring import isxml __all__ = [ '_inputsource', 'XMLSTRING', 'XMLURI', 'XMLFILE', ] MAX_URI_LENGTH_FOR_HEURISTIC = 1024 #Classifications of raw input sources XMLSTRING = 1 XMLURI = 2 XMLFILE = 3 class _inputsource(InputSource): """ The representation of a resource. Supports further, relative resolution of URIs, including resolution to absolute form of URI references. Standard object attributes: _supported_schemes is a list of URI schemes supported for dereferencing (representation retrieval). """ def __new__(cls, arg, uri=None, encoding=None, resolver=None, sourcetype=0): """ arg - a string, Unicode object (only if you really know what you're doing), file-like object (stream), file path or URI. You can also pass an InputSource object, in which case the return value is just the same object, possibly with the URI modified uri - optional override URI. The base URI for the IS will be set to this value Returns an input source which can be passed to Amara APIs. """ #do the imports within the function to avoid circular crap #from amara._xmlstring import IsXml as isxml #These importa are tucked in here because amara.lib.iri is an expensive import from amara.lib.iri import is_absolute, os_path_to_uri from amara.lib.irihelpers import DEFAULT_RESOLVER resolver = resolver or DEFAULT_RESOLVER if isinstance(arg, InputSource): return arg #if arg == (u'', ''): -> UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal if arg == '': #FIXME L10N raise ValueError("Cannot parse an empty string as XML") if isinstance(arg, urllib2.Request): uri = arg.get_full_url() #One of the rightly labeled "lame" helper methods in urllib2 ;) stream = resolver.resolve(arg) elif hasattr(arg, 'read'): #Create dummy Uri to use as base uri = uri or uuid4().urn stream = arg #XXX: Should we at this point refuse to proceed unless it's a basestring? elif sourcetype == XMLSTRING or isxml(arg): #See this article about XML detection heuristics #http://www.xml.com/pub/a/2007/02/28/what-does-xml-smell-like.html uri = uri or uuid4().urn stream = StringIO(arg) elif is_absolute(arg) and not os.path.isfile(arg): uri = arg stream = resolver.resolve(uri) #If the arg is beyond a certain length, don't even try it as a URI elif len(arg) < MAX_URI_LENGTH_FOR_HEURISTIC: uri = os_path_to_uri(arg) stream = resolver.resolve(uri) else: #FIXME L10N raise ValueError("Does not appear to be well-formed XML") #We might add the ability to load zips, gzips & bzip2s #http://docs.python.org/lib/module-zlib.html #http://docs.python.org/lib/module-gzip.html #http://docs.python.org/lib/module-bz2.html #http://docs.python.org/lib/zipfile-objects.html #import inspect; print inspect.stack() #InputSource.__new__ is in C: expat/input_source.c:inputsource_new return InputSource.__new__(cls, stream, uri, encoding) def __init__(self, arg, uri=None, encoding=None, resolver=None, sourcetype=0): #uri is set from amara.lib.irihelpers import DEFAULT_RESOLVER self.resolver = resolver or DEFAULT_RESOLVER @staticmethod def text(arg, uri=None, encoding=None, resolver=None): ''' Set up an input source from text, according to the markup convention of the term (i.e. in Python terms a string with XML, HTML, fragments thereof, or tag soup) Supports processing content sources that are not unambiguously XML or HTML strings ''' return _inputsource(arg, uri, encoding, resolver, sourcetype=XMLSTRING) def resolve(self, uriRef, baseUri=None): """ Takes a URI or a URI reference plus a base URI, produces an absolutized URI if a base URI was given, then attempts to obtain access to an entity representing the resource identified by the resulting URI, returning the entity as a stream (a file-like object). (this work is done in self.resolver) Raises a IriError if the URI scheme is unsupported or if a stream could not be obtained for any reason. """ if baseUri: uriRef = self.resolver.absolutize(uriRef, baseUri) return self.__class__(uriRef) def absolutize(self, uriRef, baseUri): """ Resolves a URI reference to absolute form, effecting the result of RFC 3986 section 5. The URI reference is considered to be relative to the given base URI. Also verifies that the resulting URI reference has a scheme that resolve() supports, raising a IriError if it doesn't. The default implementation does not perform any validation on the base URI beyond that performed by absolutize(). If leniency has been turned on (self.lenient=True), accepts a base URI beginning with '/', in which case the argument is assumed to be an absolute path component of 'file' URI with no authority component. """ return self.resolver.absolutize(uriRef, baseUri)
{ "repo_name": "zepheira/amara", "path": "lib/lib/_inputsource.py", "copies": "1", "size": "5849", "license": "apache-2.0", "hash": 9148567260729239000, "line_mean": 39.9020979021, "line_max": 154, "alpha_frac": 0.65156437, "autogenerated": false, "ratio": 4.119014084507042, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.014255256209082115, "num_lines": 143 }
#amara.lib __all__ = ['IriError', 'inputsource'] from amara import Error class IriError(Error): """ Exception related to URI/IRI processing """ RESOURCE_ERROR = 1 INVALID_BASE_URI = 100 #RELATIVE_DOCUMENT_URI = 110 RELATIVE_BASE_URI = 111 OPAQUE_BASE_URI = 112 NON_FILE_URI = 120 UNIX_REMOTE_HOST_FILE_URI = 121 RESOURCE_ERROR = 130 SCHEME_REQUIRED = 200 # for SchemeRegistryResolver UNSUPPORTED_SCHEME = 201 IDNA_UNSUPPORTED = 202 DENIED_BY_RULE = 300 INVALID_PUBLIC_ID_URN = 400 UNSUPPORTED_PLATFORM = 1000 @classmethod def _load_messages(cls): from gettext import gettext as _ # %r preferred for reporting URIs because the URI refs can be empty # strings or, if invalid, could contain characters unsafe for the # error # message stream. return { IriError.INVALID_BASE_URI: _( "Invalid base URI: %(base)r cannot be used to resolve " " reference %(ref)r"), IriError.RELATIVE_BASE_URI: _( "Invalid base URI: %(base)r cannot be used to resolve " "reference %(ref)r; the base URI must be absolute, not " "relative."), IriError.NON_FILE_URI: _( "Only a 'file' URI can be converted to an OS-specific path; " "URI given was %(uri)r"), IriError.UNIX_REMOTE_HOST_FILE_URI: _( "A URI containing a remote host name cannot be converted to a " " path on posix; URI given was %(uri)r"), IriError.RESOURCE_ERROR: _( "Error retrieving resource %(loc)r: %(msg)s"), IriError.UNSUPPORTED_PLATFORM: _( "Platform %(platform)r not supported by URI function " "%(function)s"), IriError.SCHEME_REQUIRED: _( "Scheme-based resolution requires a URI with a scheme; " "neither the base URI %(base)r nor the reference %(ref)r " "have one."), IriError.INVALID_PUBLIC_ID_URN: _( "A public ID cannot be derived from URN %(urn)r " "because it does not conform to RFC 3151."), IriError.UNSUPPORTED_SCHEME: _( "The URI scheme %(scheme)s is not supported by resolver "), IriError.IDNA_UNSUPPORTED: _( "The URI ref %(uri)r cannot be made urllib-safe on this " "version of Python (IDNA encoding unsupported)."), IriError.DENIED_BY_RULE: _( "Access to IRI %(uri)r was denied by action of an IRI restriction"), } from amara.lib._inputsource import _inputsource as inputsource # Alias amara.test to amara.lib.testsupport from amara.lib import importutil testsupport = importutil.proxy_module('amara.lib.testsupport', 'amara.test') from amara.lib.xmlstring import *
{ "repo_name": "zepheira/amara", "path": "lib/lib/__init__.py", "copies": "1", "size": "2942", "license": "apache-2.0", "hash": -8803132206975633000, "line_mean": 34.8780487805, "line_max": 84, "alpha_frac": 0.5819170632, "autogenerated": false, "ratio": 3.954301075268817, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9945602423048037, "avg_score": 0.01812314308415612, "num_lines": 82 }
"""amara.writers.node Internal module containing the logic for traversing an Amara tree in order to serialize it. """ from amara import tree from amara.namespaces import XML_NAMESPACE, XMLNS_NAMESPACE class _Visitor: """ Provides functions to recursively walk a DOM or Domlette object and generate SAX-like event calls for each node encountered. See the printer classes (XMLPrinter, HTMLPrinter, etc.) for the event handlers. """ def __init__(self, printer, ns_hints=None, added_attributes=None): """ Initializes an instance of the class. ns_hints, if given, is a dictionary of namespace mappings that help determine if namespace declarations need to be emitted when visiting the first Element node. """ self.printer = printer # Namespaces self._namespaces = [{'xml' : XML_NAMESPACE}] self._ns_hints = ns_hints self._added_attributes = added_attributes or {} _dispatch = {} def visit(self, node): """ Starts walking the tree at the given node. """ try: node_type = node.xml_type except AttributeError: raise ValueError('Not a valid Amara node %r' % node) try: visit = self._dispatch[node_type] except KeyError: # unknown node type, try and get a "pretty" name for the error #FIXME: Not ported for Amara 2 node_types = {} for name in dir(Node): if name.endswith('_NODE'): node_types[getattr(Node, name)] = name node_type = node_types.get(node.node_type, node.node_type) raise ValueError('Unknown node type %r' % node_type) else: visit(self, node) def visit_not_implemented(self, node): """ Called when an known but unsupported type of node is encountered, always raising a NotImplementedError exception. The unsupported node types are those that require DTD subset support: entity nodes, entity reference nodes, and notation nodes. """ raise NotImplementedError('Printing of %r' % node) def visit_document(self, node): """ Called when an Entity node is encountered (e.g. may or may not be a full XML document entity). Work on DTDecl details, if any, and then to the children. """ self.printer.start_document() if node.xml_system_id: for child in node.xml_children: if child.xml_type == tree.element.xml_type: self.printer.doctype(child.xml_qname, node.xml_public_id, node.xml_system_id) break for child in node.xml_children: self.visit(child) self.printer.end_document() return _dispatch[tree.entity.xml_type] = visit_document def visit_element(self, node): """ Called when an Element node is encountered. Generates for the printer a startElement event, events for the node's children (including attributes), and an endElement event. """ ##print "visit_element", node.xml_name current_nss = self._namespaces[-1].copy() # Gather the namespaces and attributes for writing namespaces = node.xml_namespaces.copy() del namespaces[u'xml'] if self._ns_hints: for prefix, namespaceUri in self._ns_hints.items(): # See if this namespace needs to be emitted if current_nss.get(prefix, 0) != namespaceUri: namespaces[prefix or u''] = namespaceUri self._ns_hints = None if self._added_attributes: attributes = self._added_attributes self._added_attributes = None else: attributes = {} for attr in node.xml_attributes.nodes(): # xmlns="uri" or xmlns:foo="uri" if attr.xml_namespace == XMLNS_NAMESPACE: if not attr.xml_prefix: # xmlns="uri" prefix = None else: # xmlns:foo="uri" prefix = attr.xml_local if current_nss.get(prefix, 0) != attr.xml_value: namespaces[prefix] = attr.xml_value else: attributes[attr.xml_qname] = attr.xml_value # The element's namespaceURI/prefix mapping takes precedence if node.xml_namespace or namespaces.get(None, 0): if namespaces.get(node.xml_prefix or None, 0) != node.xml_namespace: namespaces[node.xml_prefix or None] = node.xml_namespace or u"" #The kill_prefixes = [] for prefix in namespaces: if prefix in current_nss and current_nss[prefix] == namespaces[prefix]: kill_prefixes.append(prefix) for prefix in kill_prefixes: del namespaces[prefix] self.printer.start_element(node.xml_namespace, node.xml_qname, namespaces.iteritems(), attributes.iteritems()) # Update in scope namespaces with those we emitted current_nss.update(namespaces) self._namespaces.append(current_nss) # Write out this node's children for child in node.xml_children: self.visit(child) self.printer.end_element(node.xml_namespace, node.xml_qname) del self._namespaces[-1] _dispatch[tree.element.xml_type] = visit_element def visit_text(self, node): """ Called when a Text node is encountered. Generates a text event for the printer. """ self.printer.text(node.xml_value) _dispatch[tree.text.xml_type] = visit_text def visit_comment(self, node): """ Called when a Comment node is encountered. Generates a comment event for the printer. """ self.printer.comment(node.xml_value) return _dispatch[tree.comment.xml_type] = visit_comment def visit_processing_instruction(self, node): """ Called when a ProcessingInstruction node is encountered. Generates a processingInstruction event for the printer. """ self.printer.processing_instruction(node.xml_target, node.xml_data) return _dispatch[tree.processing_instruction.xml_type] = visit_processing_instruction
{ "repo_name": "zepheira/amara", "path": "lib/writers/node.py", "copies": "1", "size": "6501", "license": "apache-2.0", "hash": 152214737752704770, "line_mean": 35.3184357542, "line_max": 102, "alpha_frac": 0.5923704046, "autogenerated": false, "ratio": 4.4345156889495225, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00234848700026369, "num_lines": 179 }
# amara.xpath.compiler.assembler """ A flow graph representation for Python bytecode. Useful background at: http://eli.thegreenplace.net/2009/11/28/python-internals-working-with-python-asts/ """ import dis import new import array import itertools from compiler.consts import CO_OPTIMIZED, CO_NEWLOCALS class assembler: """A flow graph representation for Python bytecode as a function body""" postorder = None def __init__(self): self.entry = self.current = basicblock(0) self.blocks = [self.entry] def new_block(self): block = basicblock(len(self.blocks)) self.blocks.append(block) return block def next_block(self, block=None): if block is None: block = basicblock(len(self.blocks)) self.blocks.append(block) self.current.next = block self.current = block return block def emit(self, *instructions): hasarg = self.hasarg hasjump = self.hasjump add = self.current.append instructions = iter(instructions) for opname in instructions: instr = instruction(opname) if opname in hasarg: oparg = instructions.next() if opname in hasjump: assert isinstance(oparg, basicblock) instr.target = oparg else: instr.oparg = oparg instr.hasarg = True add(instr) return # -- PyFlowGraph -------------------------------------------------- def assemble(self, name, args, docstring, filename, firstlineno): """Get a Python code object""" self.next_block() self.emit('RETURN_VALUE') stacksize = self._compute_stack_size() blocks = self._get_blocks_in_order() consts, names, varnames = \ self._compute_lookups(blocks, args, docstring) bytecode = self._compute_jump_offsets(blocks) codestring = bytecode.tostring() return new.code(len(args), len(varnames), stacksize, CO_OPTIMIZED | CO_NEWLOCALS, codestring, consts, names, varnames, filename, name, firstlineno, '', (), ()) def _compute_stack_size(self): """Return the blocks in reverse dfs postorder""" stack_effect = { 'POP_TOP': -1, 'ROT_TWO': 0, 'ROT_THREE': 0, 'DUP_TOP': 1, 'ROT_FOUR': 0, 'UNARY_POSITIVE': 0, 'UNARY_NEGATIVE': 0, 'UNARY_NOT': 0, 'UNARY_CONVERT': 0, 'UNARY_INVERT': 0, 'LIST_APPEND': -2, 'BINARY_POWER': -1, 'BINARY_MULTIPLY': -1, 'BINARY_DIVIDE': -1, 'BINARY_MODULO': -1, 'BINARY_ADD': -1, 'BINARY_SUBTRACT': -1, 'BINARY_SUBSCR': -1, 'BINARY_FLOOR_DIVIDE': -1, 'BINARY_TRUE_DIVIDE': -1, 'INPLACE_FLOOR_DIVIDE': -1, 'INPLACE_TRUE_DIVIDE': -1, 'SLICE+0': 1, 'SLICE+1': 0, 'SLICE+2': 0, 'SLICE+3': -1, 'STORE_SLICE+0': -2, 'STORE_SLICE+1': -3, 'STORE_SLICE+2': -3, 'STORE_SLICE+3': -4, 'DELETE_SLICE+0': -1, 'DELETE_SLICE+1': -2, 'DELETE_SLICE+2': -2, 'DELETE_SLICE+3': -3, 'INPLACE_ADD': -1, 'INPLACE_SUBSTRACT': -1, 'INPLACE_MULTIPLY': -1, 'INPLACE_DIVIDE': -1, 'INPLACE_MODULO': -1, 'STORE_SUBSCR': -3, 'DELETE_SUBSCR': -2, 'BINARY_LSHIFT': -1, 'BINARY_RSHIFT': -1, 'BINARY_AND': -1, 'BINARY_XOR': -1, 'BINARY_OR': -1, 'INPLACE_POWER': -1, 'GET_ITER': 0, 'PRINT_EXPR': -1, 'PRINT_ITEM': -1, 'PRINT_NEWLINE': 0, 'PRINT_ITEM_TO': -2, 'PRINT_NEWLINE_TO': -1, 'INPLACE_LSHIFT': -1, 'INPLACE_RSHIFT': -1, 'INPLACE_AND': -1, 'INPLACE_XOR': -1, 'INPLACE_OR': -1, 'BREAK_LOOP': 0, 'RETURN_VALUE': -1, 'YIELD_VALUE': 0, 'STORE_NAME': -1, 'DELETE_NAME': 0, 'FOR_ITER': 1, 'STORE_ATTR': -2, 'DELETE_ATTR': -1, 'STORE_GLOBAL': -1, 'DELETE_GLOBAL': 0, 'LOAD_CONST': 1, 'LOAD_NAME': 1, 'BUILD_MAP': 1, 'LOAD_ATTR': 0, 'COMPARE_OP': -1, 'JUMP_FORWARD': 0, 'JUMP_IF_FALSE': 0, 'JUMP_IF_TRUE': 0, 'JUMP_ABSOLUTE': 0, 'LOAD_GLOBAL': 1, 'LOAD_FAST': 1, 'STORE_FAST': -1, 'DELETE_FAST': 0, } def walk(block, size, maxsize): block.seen = True instructions = iter(block) for instr in instructions: if instr in stack_effect: size += stack_effect[instr] elif instr == 'CALL_FUNCTION': size += -((instr.oparg % 256) + (2 * (instr.oparg / 256))) elif instr in ('BUILD_TUPLE', 'BUILD_LIST'): size += (1 - instr.oparg) elif instr == 'UNPACK_SEQUENCE': size += (instr.oparg - 1) elif instr == 'DUP_TOPX': size += instr.oparg else: raise RuntimeError("unhandled instruction: %r" % instr) if size > maxsize: maxsize = size if instr.target is not None and not instr.target.seen: assert instr in self.hasjump, instr maxsize = walk(instr.target, size, maxsize) if instr in ('JUMP_ABSOLUTE', 'JUMP_FORWARD'): # remaining code is dead break else: if block.next is not None and not block.next.seen: maxsize = walk(block.next, size, maxsize) block.seen = False return maxsize return walk(self.entry, 0, 0) def _get_blocks_in_order(self): """Return the blocks in reverse dfs postorder""" def walk(block, postorder): """Depth-first search of tree rooted at `block`""" block.seen = True if block.next is not None and not block.next.seen: walk(block.next, postorder) for instr in block: if instr.target is not None and not instr.target.seen: assert instr in self.hasjump, instr walk(instr.target, postorder) postorder.append(block) return postorder return tuple(reversed(walk(self.entry, []))) def _compute_lookups(self, blocks, args, docstring): """Convert lookup arguments from symbolic to concrete form""" haslookup = self.haslookup hascompare = self.hascompare hasconst = self.hasconst haslocal = self.haslocal hasname = self.hasname cmpop = self.cmpop consts = {(docstring, type(docstring)): 0} names = {} varnames = {} for i, arg in enumerate(args): varnames[arg] = i for block in blocks: for instr in block: if instr in haslookup: if instr in hasconst: key = (instr.oparg, type(instr.oparg)) try: oparg = consts[key] except KeyError: oparg = len(consts) consts[key] = oparg elif instr in haslocal: try: oparg = varnames[instr.oparg] except KeyError: oparg = len(varnames) varnames[instr.oparg] = oparg elif instr in hasname: try: oparg = names[instr.oparg] except KeyError: oparg = len(names) names[instr.oparg] = oparg elif instr in hascompare: oparg = cmpop[instr.oparg] else: raise RuntimeError("unhandled instruction: %r" % instr) instr.oparg = oparg if consts: L = ['']*len(consts) for key, pos in consts.iteritems(): L[pos] = key[0] consts = tuple(L) else: consts = () if names: L = ['']*len(names) for name, pos in names.iteritems(): L[pos] = name names = tuple(L) else: names = () if varnames: L = ['']*len(varnames) for name, pos in varnames.iteritems(): L[pos] = name varnames = tuple(L) else: varnames = () return consts, names, varnames def _compute_jump_offsets(self, blocks): """Compute the size of each block and fixup jump args""" hasjump = self.hasjump hasjrel = self.hasjrel hasjabs = self.hasjabs map = itertools.imap opmap = dis.opmap bytecode = array.array('B') append = bytecode.append extend = bytecode.extend while not bytecode: # Compute the size of each block offset = 0 for block in blocks: block.offset = offset offset += sum(map(len, block)) for block in blocks: for i, instr in enumerate(block): if instr.target is not None: assert instr in hasjump if instr in hasjrel: offset = len(bytecode) + len(instr) instr.oparg = instr.target.offset - offset elif instr in hasjabs: instr.oparg = instr.target.offset else: raise RuntimeError("unhandled instruction: %r" % instr) opcode = opmap[instr] if instr.hasarg: oparg = instr.oparg if oparg > 0xFFFF: instr.oparg &= 0xFFFF instr = Instruction('EXTENDED_ARG') instr.oparg = oparg >> 16 instr.hasarg = True block.insert(i, instr) break extend((opcode, oparg & 0xFF, oparg >> 8)) else: append(opcode) else: # process the next block of instructions continue # add an EXTENDED_ARG instruction assert instr == 'EXTENDED_ARG', instr # restart while loop to recompute offsets del bytecode[:] break return bytecode hasarg = set(dis.opname[dis.HAVE_ARGUMENT:]) hasjrel = set(dis.opname[op] for op in dis.hasjrel) hasjabs = set(dis.opname[op] for op in dis.hasjabs) hasjump = hasjrel | hasjabs hascompare = set(dis.opname[op] for op in dis.hascompare) hasconst = set(dis.opname[op] for op in dis.hasconst) haslocal = set(dis.opname[op] for op in dis.haslocal) hasname = set(dis.opname[op] for op in dis.hasname) haslookup = hascompare | hasconst | haslocal | hasname cmpop = dict(itertools.izip(dis.cmp_op, itertools.count())) class instruction(str): opname = property(str.__str__) oparg = None target = None hasarg = False def __len__(self): if self.hasarg: if self.oparg > 0xFFFF: return 6 return 3 return 1 def __repr__(self): ptr = id(self) if ptr < 0: ptr += 0x100000000L return '<instr at 0x%x: opname=%r, oparg=%r, target=%r>' % ( ptr, self.opname, self.oparg, self.target) def __str__(self): return '<instr %s, oparg=%r>' % (self.opname, self.oparg) class basicblock(list): __slots__ = ('id', 'label', 'next', 'seen', 'offset') def __init__(self, id, label=None): self.id = id self.label = label self.next = None self.seen = False self.offset = 0 emit = list.append __hash__ = object.__hash__ def __repr__(self): ptr = id(self) if ptr < 0: ptr += 0x100000000L if self.label: label = ', label=%s' % self.label else: label = '' return "<block at 0x%x: id=%d%s>" % (ptr, self.id, label) def __str__(self): if self.label: label = ' %r ' % self.label else: label = '' if self: instructions = ':\n ' + '\n '.join(map(str, self)) else: instructions = '' return "<block %s%d, offset %d%s>" % (label, self.id, self.offset, instructions)
{ "repo_name": "zepheira/amara", "path": "lib/xpath/compiler/assembler.py", "copies": "1", "size": "13567", "license": "apache-2.0", "hash": -6857354518096972000, "line_mean": 32.0097323601, "line_max": 104, "alpha_frac": 0.4636986806, "autogenerated": false, "ratio": 4.101269649334945, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5064968329934946, "avg_score": null, "num_lines": null }
'''A margin widget designed to augment the DynamicTableEditor This displays line numbers and has some bindings for selecting whole rows ''' import Tkinter as tk import sys class DteMargin(tk.Canvas): '''A widget to display line numbers and markers for a DynamicTableEditor widget''' def __init__(self, *args, **kwargs): tk.Canvas.__init__(self, *args, **kwargs) self.dte = None self.bind("<ButtonPress-1>", self._on_linenumber_click) self.bind("<Control-ButtonPress-1>", self._on_linenumber_control_click) self.bind("<Shift-ButtonPress-1>", self._on_linenumber_move) self.bind("<B1-Motion>", self._on_linenumber_move) def attach(self, dte): '''Attach to a dte widget''' self.dte = dte self.dte.margin = self padding = int(self.dte.cget("padx")) + int(self.cget("width")) self.dte.configure(padx=padding) self.place(x=-padding,y=0, relheight=1.0, in_=self.dte) self.dte.add_post_change_hook(lambda *args: self.refresh()) def refresh(self): '''Refresh line numbers and markers''' self.update_linenumbers() self.update_markers() def _get_linenumber(self, index): return int(self.dte.index(index).split(".")[0]) def update_markers(self, *args): '''This creates a marker which represents the current statement''' current_line = self.dte.index("insert").split(".")[0] start = self.dte.find_start_of_statement("insert") end = self.dte.find_end_of_statement("insert") self.set_marker(start, end) def set_marker(self, start, end): # start and end may be string indices, so we need to convert # them to integers start = int(float(start)) end=int(float(end)) bg = self.cget("background") self.itemconfigure("marker", outline=bg, fill=bg) for i in range(start, end+1): self.itemconfigure("marker-%s" %i, outline="blue", fill="blue") def update_linenumbers(self, *args): '''redraw line numbers for visible lines, and add invisible markers This may seem like a rather compute-intensive thing to do, but in practice it's pretty quick (on the order of 5-8ms when there are 50 lines displayed, last time I measured) ''' self.delete("all") window_height = self.winfo_height() window_width = self.winfo_width() first = int(self.dte.index("@0,0").split(".")[0]) last = int(self.dte.index("@0,%s"%window_height).split(".")[0]) self.create_line(0, 1, 0, window_height, fill="gray", tags=("border",)) self.create_line(window_width-1, 1, window_width-1, window_height, fill="gray", tags=("border",)) bg = self.dte.cget("background") markerx = window_width-3 for i in range(first, last+1): dline= self.dte.dlineinfo("%s.0" % i) if dline is None: break y = dline[1] last_id = self.create_text(window_width-8,y,anchor="ne", text=str(i)) self.create_rectangle(markerx, y, window_width-2, y+dline[3], outline=bg, fill=bg, tags=("marker", "marker-%s" % i)) self.create_line(0,y-1, window_width+3, y-1, fill="gray") self.lift("border") # if the line numbers don't fit, adjust the size and try # again. Danger Will Robinson! We only do this if the window # is visible, otherwise we get into a nasty loop at startup. if self.winfo_viewable(): bbox = self.bbox(last_id) required_width=bbox[2]-bbox[0] if bbox[0] < 0: self.configure(width=(window_width + abs(bbox[0]) + 4)) self.after(1, self.update_linenumbers, False) def mark_current_statement(self): start = self.find_start_of_statement("insert") end = self.find_end_of_statement("insert") self.tag_remove("w00t", 1.0, "end") self.tag_add("w00t", start, "%s lineend+1c" % end) def _on_linenumber_control_click(self, event): text_index = self.dte.index("@%s,%s" % (event.x, event.y)) self.dte.mark_set("click", "%s linestart" % text_index) self.dte.tag_add("sel", "%s linestart" % text_index, "%s lineend+1c" % text_index) self.dte.mark_set("insert", "%s linestart" % text_index) def _on_linenumber_click(self, event): try: text_index = self.dte.index("@%s,%s" % (event.x, event.y)) self.dte.mark_set("click", "%s linestart" % text_index) self.dte.tag_remove("sel", "1.0", "end") self.dte.tag_add("sel", "%s linestart" % text_index, "%s lineend+1c" % text_index) self.dte.mark_set("insert", "%s lineend" % text_index) except Exception, e: import sys; sys.stdout.flush() def _on_linenumber_move(self, event): try: text_index = self.dte.index("@%s,%s" % (event.x, event.y)) self.dte.tag_remove("sel", "1.0", "end") if self.dte.compare(text_index, ">", "click"): self.dte.tag_add("sel", "click", "%s lineend+1c" % text_index) else: self.dte.tag_add("sel", "%s linestart" % text_index, "click lineend+1c") self.dte.mark_set("insert", "%s lineend" % text_index) except Exception, e: pass
{ "repo_name": "boakley/robotframework-workbench", "path": "rwb/editor/dte_margin.py", "copies": "1", "size": "5461", "license": "apache-2.0", "hash": 1952703703674852600, "line_mean": 43.0403225806, "line_max": 105, "alpha_frac": 0.5795641824, "autogenerated": false, "ratio": 3.3647566235366604, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9373637288933356, "avg_score": 0.014136703400660621, "num_lines": 124 }
""" A *Marker* is a proxy class which wraps some schema. Immediately, the example is: ```python from good import Schema, Required Schema({ 'name': str, # required key Optional('age'): int, # optional key }, default_keys=Required) ``` This way, keys marked with `Required()` will report errors if no value if provided. Typically, a marker "decorates" a mapping key, but some of them can be "standalone": ```python from good import Schema, Extra Schema({ 'name': str, Extra: int # allow any keys, provided their values are integer }) ``` Each marker can have it's own unique behavior since nothing is hardcoded into the core [`Schema`](#schema). Keep on reading to learn how markers perform. """ from gettext import gettext as _ from .signals import RemoveValue from .errors import Invalid, MultipleInvalid from .util import const, get_type_name, get_literal_name class Marker: """ A Marker is a class that decorates a mapping key. Its compilation goes in 3 phases: 1. Marker.key is set by the user: `Required('name')` 2. Marker.key is compiled into a schema, and notified with `Marker.on_compiled(name, key_schema)` 3. Marker receives a value schema, through `Marker.on_compiled(value_schema=value_schema)` Note that if a marker is used as a mapping key, its `key_schema` is compiled as a matcher for performance. When CompiledSchema performs matching, it collects input values that match the marker (using `priority` to decide which of the markers will actually get the duck) and then calls execute() on the Marker so it can implement its logic. Note that `execute()` is always called, regardless of whether the marker has matched anything: this gives markers a chance to modify the input to its taste. This opens the possibilities of implementing custom markers which validate the whole schema! Finally, note that a marker does not necessarily decorate something: it can be used as a class: ```python Schema({ 'name': str, Extra: Reject }) ``` In this case, a Marker class is automatically instantiated with an identity function (which matches any value): `Extra(lambda x: x)`. """ #: Marker priority #: This defines matching order for mapping keys priority = 0 #: The default marker error message #: Stored here just for convenience error_message = None def __init__(self, key): #: The original key self.key = key #: Human-readable marker representation self.name = None #: CompiledSchema for the key self.key_schema = None #: CompiledSchema for value (if the Marker was used as a key in a mapping) self.value_schema = None #: Whether the marker is used as a mapping key self.as_mapping_key = False def on_compiled(self, name=None, key_schema=None, value_schema=None, as_mapping_key=None): """ When CompiledSchema compiles this marker, it sets informational values onto it. Note that arguments may be provided in two incomplete sets, e.g. (name, key_schema, None) and then (None, None, value_schema). Thus, all assignments must be handled individually. It is possible that a marker may have no `value_schema` at all: e.g. in the case of { Extra: Reject } -- `Reject` will have no value schema, but `Extra` will have compiled `Reject` as the value. :param key_schema: Compiled key schema :type key_schema: CompiledSchema|None :param value_schema: Compiled value schema :type value_schema: CompiledSchema|None :param name: Human-friendly marker name :type name: unicode|None :param as_mapping_key: Whether it's used as a mapping key? :type as_mapping_key: bool|None :rtype: Marker """ if self.name is None: self.name = name if self.key_schema is None: self.key_schema = key_schema if self.value_schema is None: self.value_schema = value_schema if as_mapping_key: self.as_mapping_key = True return self def __repr__(self): return '{cls}({0})'.format( self.name or self.key, cls=type(self).__name__) #region Marker is a Proxy def __hash__(self): return hash(self.key) def __eq__(self, other): # Marker equality comparison: # key == key | key == Marker.key | key is Marker return self.key == (other.key if isinstance(other, Marker) else other) or other is type(self) def __bytes__(self): return bytes(self.key) def __str__(self): return get_literal_name(self.key) #endregion def __call__(self, v): """ Validate a key using this Marker's schema """ return self.key_schema(v) def execute(self, d, matches): """ Execute the marker against the the matching values from the input. Note that `execute()` is called precisely once, and even if there are no matches for the marker. :param d: The original user input :type d: dict :param matches: List of (input-key, sanitized-input-key, input-value) triples that matched the given marker :type matches: list[tuple] :returns: The list of matches, potentially modified :rtype: list[tuple] :raises: Invalid|MultipleInvalid """ return matches # No-op by default class Required(Marker): """ `Required(key)` is used to decorate mapping keys and hence specify that these keys must always be present in the input mapping. When compiled, [`Schema`](#schema) uses `default_keys` as the default marker: ```python from good import Schema, Required schema = Schema({ 'name': str, 'age': int }, default_keys=Required) # wrap with Required() by default schema({'name': 'Mark'}) #-> Invalid: Required key not provided @ ['age']: expected age, got -none- ``` Remember that mapping keys are schemas as well, and `Require` will expect to always have a match: ```python schema = Schema({ Required(str): int, }) schema({}) # no `str` keys provided #-> Invalid: Required key not provided: expected String, got -none- ``` In addition, the `Required` marker has special behavior with [`Default`](#default) that allows to set the key to a default value if the key was not provided. More details in the docs for [`Default`](#default). """ priority = 0 error_message = _(u'Required key not provided') def execute(self, d, matches): # If a Required() key is present -- it expects to ALWAYS have one or more matches # When Required() has no matches... if not matches: # Last chance: value_schema supports Undefined, and the key is a literal if self.value_schema.supports_undefined: # Schema supports `Undefined`, then use it! v = self.value_schema(const.UNDEFINED) matches.append((self.key_schema.schema, self.key_schema.schema, v)) return matches else: # Invalid path = [self.key] if self.key_schema.compiled_type == const.COMPILED_TYPE.LITERAL else [] raise Invalid(self.error_message, self.name, _(u'-none-'), path) return matches class Optional(Marker): """ `Optional(key)` is controversial to [`Required(key)`](#required): specified that the mapping key is not required. This only has meaning when a [`Schema`](#schema) has `default_keys=Required`: then, it decorates all keys with `Required()`, unless a key is already decorated with some Marker. `Optional()` steps in: those keys are already decorated and hence are not wrapped with `Required()`. So, it's only used to prevent `Schema` from putting `Required()` on a key. In all other senses, it has absolutely no special behavior. As a result, optional key can be missing, but if it was provided -- its value must match the value schema. Example: use as `default_keys`: ```python schema = Schema({ 'name': str, 'age': int }, default_keys=Optional) # Make all keys optional by default schema({}) #-> {} -- okay schema({'name': None}) #-> Invalid: Wrong type @ ['name']: expected String, got None ``` Example: use to mark specific keys are not required: ```python schema = Schema({ 'name': str, Optional(str): int # key is optional }) schema({'name': 'Mark'}) # valid schema({'name': 'Mark', 'age': 10}) # valid schema({'name': 'Mark', 'age': 'X'}) #-> Invalid: Wrong type @ ['age']: expected Integer number, got Binary String ``` """ priority = 0 pass # no-op class Remove(Marker): """ `Remove(key)` marker is used to declare that the key, if encountered, should be removed, without validating the value. `Remove` has highest priority, so it operates before everything else in the schema. Example: ```python schema = Schema({ Remove('name'): str, # `str` does not mean anything since the key is removed anyway 'age': int }) schema({'name': 111, 'age': 18}) #-> {'age': 18} ``` However, it's more natural to use `Remove()` on values. Remember that in this case `'name'` will become [`Required()`](#required), if not decorated with [`Optional()`](#optional): ```python schema = Schema({ Optional('name'): Remove }) schema({'name': 111, 'age': 18}) #-> {'age': 18} ``` **Bonus**: `Remove()` can be used in iterables as well: ```python schema = Schema([str, Remove(int)]) schema(['a', 'b', 1, 2]) #-> ['a', 'b'] ``` """ priority = 1000 # We always want to remove keys prior to any other actions def execute(self, d, matches): # Remove all matching keys from the input for k, sanitized_k, v in matches: d.pop(k) # Clean the list of matches so further processing does not assign them again return [] def __call__(self, v): if not self.as_mapping_key: # When used on a value -- drop it raise RemoveValue() return super(Remove, self).__call__(v) class Reject(Marker): """ `Reject(key)` marker is used to report [`Invalid`](#invalid) errors every time is matches something in the input. It has lower priority than most of other schemas, so rejection will only happen if no other schemas has matched this value. Example: ```python schema = Schema({ Reject('name'): None, # Reject by key Optional('age'): Msg(Reject, u"Field is not supported anymore"), # alternative form }) schema({'name': 111}) #-> Invalid: Field is not supported anymore @ ['name']: expected -none-, got name ``` """ priority = -50 error_message = _(u'Value rejected') def __call__(self, v): if not self.as_mapping_key: # When used on a value -- complain raise Invalid(self.error_message, _(u'-none-'), get_literal_name(v), validator=self) return super(Reject, self).__call__(v) def execute(self, d, matches): # Complain on all values it gets if matches: errors = [] for k, sanitized_k, v in matches: errors.append(Invalid(self.error_message, _(u'-none-'), get_literal_name(k), [k])) raise MultipleInvalid.if_multiple(errors) return matches class Allow(Marker): """ `Allow(key)` is a no-op marker that never complains on anything. Designed to be used with [`Extra`](#extra). """ priority = 0 pass # no-op class Extra(Marker): """ `Extra` is a catch-all marker to define the behavior for mapping keys not defined in the schema. It has the lowest priority, and delegates its function to its value, which can be a schema, or another marker. Given without argument, it's compiled with an identity function `lambda x:x` which is a catch-all: it matches any value. Together with lowest priority, `Extra` will only catch values which did not match anything else. Every mapping has an `Extra` implicitly, and `extra_keys` argument controls the default behavior. Example with `Extra: <schema>`: ```python schema = Schema({ 'name': str, Extra: int # this will allow extra keys provided they're int }) schema({'name': 'Alex', 'age': 18'}) #-> ok schema({'name': 'Alex', 'age': 'X'}) #-> Invalid: Wrong type @ ['age']: expected Integer number, got Binary String ``` Example with `Extra: Reject`: reject all extra values: ```python schema = Schema({ 'name': str, Extra: Reject }) schema({'name': 'Alex', 'age': 'X'}) #-> Invalid: Extra keys not allowed @ ['age']: expected -none-, got age ``` Example with `Extra: Remove`: silently discard all extra values: ```python schema = Schema({'name': str}, extra_keys=Remove) schema({'name': 'Alex', 'age': 'X'}) #-> {'name': 'Alex'} ``` Example with `Extra: Allow`: allow any extra values: ```python schema = Schema({'name': str}, extra_keys=Allow) schema({'name': 'Alex', 'age': 'X'}) #-> {'name': 'Alex', 'age': 'X'} ``` """ priority = -1000 # Extra should match last error_message = _(u'Extra keys not allowed') def on_compiled(self, name=None, key_schema=None, value_schema=None, as_mapping_key=None): # Special case # When { Extra: Reject }, use a customized error message if value_schema and isinstance(value_schema.compiled, Reject): value_schema.compiled.error_message = self.error_message return super(Extra, self).on_compiled(name, key_schema, value_schema, as_mapping_key) def execute(self, d, matches): # Delegate the decision to the value. # If the value is a marker -- call execute() on it # This is for the cases when `Extra` is mapped to a marker if isinstance(self.value_schema.compiled, Marker): return self.value_schema.compiled.execute(d, matches) # Otherwise, it's a schema, which must be called on every value to validate it. # However, CompiledSchema does this anyway at the next step, so doing nothing here return matches class Entire(Optional): """ `Entire` is a convenience marker that validates the entire mapping using validators provided as a value. It has absolutely lowest priority, lower than `Extra`, hence it never matches any keys, but is still executed to validate the mapping itself. This opens the possibilities to define rules on multiple fields. This feature is leveraged by the [`Inclusive`](#inclusive) and [`Exclusive`](#exclusive) group validators. For example, let's require the mapping to have no more than 3 keys: ```python from good import Schema, Entire def maxkeys(n): # Return a validator function def validator(d): # `d` is the dictionary. # Validate it assert len(d) <= 3, 'Dict size should be <= 3' # Return the value since all callable schemas should do that return d return validator schema = Schema({ str: int, Entire: maxkeys(3) }) ``` In this example, `Entire` is executed for every input dictionary, and magically calls the schema it's mapped to. The `maxkeys(n)` schema is a validator that complains on the dictionary size if it's too huge. `Schema` catches the `AssertionError` thrown by it and converts it to [`Invalid`](#invalid). Note that the schema this marker is mapped to can't replace the mapping object, but it can mutate the given mapping. """ priority = -2000 # Should never match anything def execute(self, d, matches): # Ignore `matches`, since it's always empty. # Instead, pass the mapping `d` to the schema it's mapped to: `value_schema` try: self.value_schema(d) except Invalid as e: e.enrich( expected=self.value_schema.name, provided=get_type_name(type(d)), validator=self.value_schema.schema ) raise # Still return the same `matches` list return matches __all__ = ('Required', 'Optional', 'Remove', 'Reject', 'Allow', 'Extra', 'Entire')
{ "repo_name": "kolypto/py-good", "path": "good/schema/markers.py", "copies": "1", "size": "16658", "license": "bsd-2-clause", "hash": -7437623635556347000, "line_mean": 32.7890466531, "line_max": 122, "alpha_frac": 0.6260055229, "autogenerated": false, "ratio": 4.099926162933793, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0015043333285009004, "num_lines": 493 }
"""A Market is all the market streets that have been added to the board. A Market Street is a line of merchants that strech across the board giving adjacency bonuses to nearby buildings. Each merchant has a location so a market street is saved as a set of locations. Not two merchants can occupy the same location and merchants can only be added to the ends of the market street. When adding merchants, a merchant can only be played in a way in which it is only adjacent to at most one other merchant. In other words, A merchant can be played at the tail or head of the merchant street and can be played in a location that does not make a loop with the market street. It is possible for a market street to terminate due to a loop or dead ends. If this happens, a new market street is started as an extension of this street. The rules for placement still apply to the new market street and the new market street is also restricted by the old market street(s). """ from Location import * def clone_market(market): """Clones a market""" return [street[:] for street in market] def make_market(start): """This function will make a market which is the list of all the market streets of merchants there are in the game.""" market = []; market.append(make_market_street(start)); return market; def market_contains_location(market, loc): """Checks if a market contains a specific location in any of its streets.""" for street in market: if loc in street: return True return False def add_merchant_to_market(market, merchant): """Addsa a merchant to the active street or creates a new street if the merchant cannot be added to the active street""" poss = get_possible_addition(market) if merchant in poss: add_merchant(get_active_market_street(market), merchant) else: add_market_street(market, merchant) def get_num_streets(market): """Gets the number of streets in a market.""" return len(market) def add_market_street(market, start): """Adds a new market street to a market and sets it as the active street.""" market.append(make_market_street(start)) def get_active_market_street(market): """Gets the active street in a market.""" return market[-1] def make_market_street(start): """This function will make a market street which is a saved list of locations that represents merchants placed on the board.""" return [start] def get_street_length(street): """Gets the length of a market street.""" return len(street) def add_merchant(street, merchant): """Adds a merchant to a market street.""" street.append(merchant) def get_adjacent_to_street(street): """Gets all locations orthogonally adjacent to a street.""" adj = set() for loc in street: adj.update(get_orthogonal(loc)) adj.difference_update(street) return adj def is_valid_location(loc, market): """This checks if a location is a valid place to add a merchant for a given market. A place is considered valid if it is attached to a spot adjacent to the head or tail of the market street and only has 1 neighbor upon being placed.""" return loc in get_possible_addition(market) def get_possible_addition(market): """Gets the possible locations to add merchants to the market street. This must account for other streets as merchatns can only be played in a location where they would only have one other merchant adjacent to them; no loops allowed. This includes other streets. These locations branch from the head and tail of a market street.""" possible = set() for end in get_head_and_tail(get_active_market_street(market)): possible.update(get_orthogonal(end)) possible.difference_update(get_active_market_street(market)) for street in market: if street != get_active_market_street(market): possible.difference_update(get_adjacent_to_street(street)) else: street2 = list(set(street) - set(get_head_and_tail(street))) if(street2): possible.difference_update(set(get_adjacent_to_street(street2))) ends = get_head_and_tail(street) if len(ends) == 2: head = ends[0] tail = ends[1] share = set(get_orthogonal(head)).intersection(set(get_orthogonal(tail))) if share: #print(head, tail, share) possible.difference_update(share) return possible def get_head_and_tail(street): """Gets the head and tail of a street. The head and tail are locations on the street that can have merchants added to them. The head and the tail can be identified because the merchant at the head or tail of the street will only ever have one other merchant adjacent to them. This will return a list of only one location if the street is only one merchant long.""" def is_end(location): num_adj = 0 adj = get_orthogonal(location) for merchant in street: if merchant != location and merchant in adj: num_adj += 1 return num_adj <= 1 return [loc for loc in street if is_end(loc)]
{ "repo_name": "nicholas-maltbie/Medina", "path": "Market.py", "copies": "1", "size": "5376", "license": "mit", "hash": 5123091925725307000, "line_mean": 39.3538461538, "line_max": 89, "alpha_frac": 0.6705729167, "autogenerated": false, "ratio": 3.921225382932166, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5091798299632166, "avg_score": null, "num_lines": null }
"""A Martel format to parse the output from transfac. Formats: format Format for a whole file. """ import warnings warnings.warn("Bio.expressions was deprecated, as it does not work with recent versions of mxTextTools. If you want to continue to use this module, please get in contact with the Biopython developers at biopython-dev@biopython.org to avoid permanent removal of this module from Biopython", DeprecationWarning) import sys from Martel import * from Martel import RecordReader blank_line = Opt(Spaces()) + AnyEol() MATRIX_LINE = Str("Search for sites by WeightMatrix library:") + Spaces() + \ UntilEol("matrix_file") + AnyEol() SEQUENCE_LINE = Str("Sequence file:") + Spaces() + \ UntilEol("sequence_file") + AnyEol() PROFILE_LINE = Str("Site selection profile:") + Spaces() + \ UntilSep("profile_file", sep=" ") + Spaces() + \ UntilEol("profile_description") + AnyEol() TITLE_LINE = Str("Inspecting sequence ID") + Spaces() + \ UntilSep("entryname", sep=" ") + Spaces() + \ UntilSep("dataclass", sep=";") + Str(";") + Spaces() + \ UntilSep("molecule", sep=";") + Str(";") + Spaces() + \ UntilSep("division", sep=";") + Str(";") + Spaces() + \ UntilSep("sequencelength", sep=" ") + Spaces() + Str("BP") + \ UntilEol() + AnyEol() def SS(exp): # expression surrounded by optional spaces. return Opt(Spaces()) + exp + Opt(Spaces()) DATA_LINE = \ SS(UntilSep("matrix_identifier", sep=" |")) + \ Str("|") + \ SS(UntilSep("position", sep=" ")) + \ SS(Str("(") + Group("strand", Any("+-")) + Str(")")) + \ Str("|") + \ SS(Float("core_match")) + \ Str("|") + \ SS(Float("matrix_match")) + \ Str("|") + \ Opt(Spaces()) + UntilEol("sequence") + AnyEol() SEQUENCES_LENGTH_LINE = \ Spaces() + Str("Total sequences length=") + Integer("sequences_length") + \ AnyEol() FOUND_SITES_LINE = \ Spaces() + Str("Total number of found sites=") + Integer("found_sites") + \ AnyEol() SITE_FREQUENCY_LINE = \ Spaces() + Str("Frequency of sites per nucleotide=") + \ Float("sites_per_nucleotide") + AnyEol() format = MATRIX_LINE + \ SEQUENCE_LINE + \ PROFILE_LINE + \ blank_line + \ TITLE_LINE + \ blank_line + \ Rep(DATA_LINE) + \ blank_line + \ SEQUENCES_LENGTH_LINE + \ blank_line + \ FOUND_SITES_LINE + \ blank_line + \ SITE_FREQUENCY_LINE
{ "repo_name": "dbmi-pitt/DIKB-Micropublication", "path": "scripts/mp-scripts/Bio/expressions/transfac.py", "copies": "1", "size": "2579", "license": "apache-2.0", "hash": -943715152453956100, "line_mean": 33.3866666667, "line_max": 309, "alpha_frac": 0.5684373788, "autogenerated": false, "ratio": 3.366840731070496, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.44352781098704963, "avg_score": null, "num_lines": null }
# A. match_ends def match_ends(words): n=len (words) i=0 count=0 while i<n: if len(words[i])>=2 and words[i][0]==words[i][-1]: count = count+1 i = i+1 return count # B. front_x def front_x(words): s=[] s1=[] for i in words: if i.startswith('x'): s.append(i) else: s1.append(i) s.sort() s1.sort() return s+s1 # C. sort_last def last (a): return a[-1] def sort_last(tuples): return sorted(tuples, key=last) def test(got, expected): if got == expected: prefix = ' OK ' else: prefix = ' X ' print ('%s got: %s expected: %s' % (prefix, repr(got), repr(expected))) def main(): print ('match_ends') test(match_ends(['aba', 'xyz', 'aa', 'x', 'bbb']), 3) test(match_ends(['', 'x', 'xy', 'xyx', 'xx']), 2) test(match_ends(['aaa', 'be', 'abc', 'hello']), 1) print print ('front_x') test(front_x(['bbb', 'ccc', 'axx', 'xzz', 'xaa']), ['xaa', 'xzz', 'axx', 'bbb', 'ccc']) test(front_x(['ccc', 'bbb', 'aaa', 'xcc', 'xaa']), ['xaa', 'xcc', 'aaa', 'bbb', 'ccc']) test(front_x(['mix', 'xyz', 'apple', 'xanadu', 'aardvark']), ['xanadu', 'xyz', 'aardvark', 'apple', 'mix']) print print ('sort_last') test(sort_last([(1, 3), (3, 2), (2, 1)]), [(2, 1), (3, 2), (1, 3)]) test(sort_last([(2, 3), (1, 2), (3, 1)]), [(3, 1), (1, 2), (2, 3)]) test(sort_last([(1, 7), (1, 3), (3, 4, 5), (2, 2)]), [(2, 2), (1, 3), (3, 4, 5), (1, 7)]) if __name__ == '__main__': main()
{ "repo_name": "dimir2/hse12pi2-scripts", "path": "BaydakovaE/list1.py", "copies": "1", "size": "1565", "license": "mit", "hash": 2354050790572468700, "line_mean": 22.7121212121, "line_max": 73, "alpha_frac": 0.4587859425, "autogenerated": false, "ratio": 2.5953565505804312, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8383653960823605, "avg_score": 0.034097706451365326, "num_lines": 66 }
"""A matplotlib backend for publishing figures via display_data""" #----------------------------------------------------------------------------- # Copyright (C) 2011 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- from __future__ import print_function # Third-party imports import matplotlib from matplotlib.backends.backend_agg import new_figure_manager, FigureCanvasAgg # analysis: ignore from matplotlib._pylab_helpers import Gcf # Local imports from IPython.core.getipython import get_ipython from IPython.core.display import display from .config import InlineBackend #----------------------------------------------------------------------------- # Functions #----------------------------------------------------------------------------- def show(close=None): """Show all figures as SVG/PNG payloads sent to the IPython clients. Parameters ---------- close : bool, optional If true, a ``plt.close('all')`` call is automatically issued after sending all the figures. If this is set, the figures will entirely removed from the internal list of figures. """ if close is None: close = InlineBackend.instance().close_figures try: for figure_manager in Gcf.get_all_fig_managers(): display(figure_manager.canvas.figure) finally: show._to_draw = [] if close: matplotlib.pyplot.close('all') # This flag will be reset by draw_if_interactive when called show._draw_called = False # list of figures to draw when flush_figures is called show._to_draw = [] def draw_if_interactive(): """ Is called after every pylab drawing command """ # signal that the current active figure should be sent at the end of # execution. Also sets the _draw_called flag, signaling that there will be # something to send. At the end of the code execution, a separate call to # flush_figures() will act upon these values manager = Gcf.get_active() if manager is None: return fig = manager.canvas.figure # Hack: matplotlib FigureManager objects in interacive backends (at least # in some of them) monkeypatch the figure object and add a .show() method # to it. This applies the same monkeypatch in order to support user code # that might expect `.show()` to be part of the official API of figure # objects. # For further reference: # https://github.com/ipython/ipython/issues/1612 # https://github.com/matplotlib/matplotlib/issues/835 if not hasattr(fig, 'show'): # Queue up `fig` for display fig.show = lambda *a: display(fig) # If matplotlib was manually set to non-interactive mode, this function # should be a no-op (otherwise we'll generate duplicate plots, since a user # who set ioff() manually expects to make separate draw/show calls). if not matplotlib.is_interactive(): return # ensure current figure will be drawn, and each subsequent call # of draw_if_interactive() moves the active figure to ensure it is # drawn last try: show._to_draw.remove(fig) except ValueError: # ensure it only appears in the draw list once pass # Queue up the figure for drawing in next show() call show._to_draw.append(fig) show._draw_called = True def flush_figures(): """Send all figures that changed This is meant to be called automatically and will call show() if, during prior code execution, there had been any calls to draw_if_interactive. This function is meant to be used as a post_execute callback in IPython, so user-caused errors are handled with showtraceback() instead of being allowed to raise. If this function is not called from within IPython, then these exceptions will raise. """ if not show._draw_called: return if InlineBackend.instance().close_figures: # ignore the tracking, just draw and close all figures try: return show(True) except Exception as e: # safely show traceback if in IPython, else raise ip = get_ipython() if ip is None: raise e else: ip.showtraceback() return try: # exclude any figures that were closed: active = set([fm.canvas.figure for fm in Gcf.get_all_fig_managers()]) for fig in [ fig for fig in show._to_draw if fig in active ]: try: display(fig) except Exception as e: # safely show traceback if in IPython, else raise ip = get_ipython() if ip is None: raise e else: ip.showtraceback() return finally: # clear flags for next round show._to_draw = [] show._draw_called = False # Changes to matplotlib in version 1.2 requires a mpl backend to supply a default # figurecanvas. This is set here to a Agg canvas # See https://github.com/matplotlib/matplotlib/pull/1125 FigureCanvas = FigureCanvasAgg
{ "repo_name": "poojavade/Genomics_Docker", "path": "Dockerfiles/gedlab-khmer-filter-abund/pymodules/python2.7/lib/python/ipython-2.2.0-py2.7.egg/IPython/kernel/zmq/pylab/backend_inline.py", "copies": "8", "size": "5498", "license": "apache-2.0", "hash": -3073908146283557400, "line_mean": 35.4105960265, "line_max": 98, "alpha_frac": 0.5963986904, "autogenerated": false, "ratio": 4.691126279863481, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9287524970263481, "avg_score": null, "num_lines": null }
"""A matplotlib backend for publishing figures via display_data""" # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. from __future__ import print_function import matplotlib # analysis: ignore from matplotlib.backends.backend_agg import new_figure_manager, FigureCanvasAgg from matplotlib._pylab_helpers import Gcf from IPython.core.getipython import get_ipython from IPython.core.display import display from .config import InlineBackend def show(close=None): """Show all figures as SVG/PNG payloads sent to the IPython clients. Parameters ---------- close : bool, optional If true, a ``plt.close('all')`` call is automatically issued after sending all the figures. If this is set, the figures will entirely removed from the internal list of figures. """ if close is None: close = InlineBackend.instance().close_figures try: for figure_manager in Gcf.get_all_fig_managers(): display(figure_manager.canvas.figure) finally: show._to_draw = [] # only call close('all') if any to close # close triggers gc.collect, which can be slow if close and Gcf.get_all_fig_managers(): matplotlib.pyplot.close('all') # This flag will be reset by draw_if_interactive when called show._draw_called = False # list of figures to draw when flush_figures is called show._to_draw = [] def draw_if_interactive(): """ Is called after every pylab drawing command """ # signal that the current active figure should be sent at the end of # execution. Also sets the _draw_called flag, signaling that there will be # something to send. At the end of the code execution, a separate call to # flush_figures() will act upon these values manager = Gcf.get_active() if manager is None: return fig = manager.canvas.figure # Hack: matplotlib FigureManager objects in interacive backends (at least # in some of them) monkeypatch the figure object and add a .show() method # to it. This applies the same monkeypatch in order to support user code # that might expect `.show()` to be part of the official API of figure # objects. # For further reference: # https://github.com/ipython/ipython/issues/1612 # https://github.com/matplotlib/matplotlib/issues/835 if not hasattr(fig, 'show'): # Queue up `fig` for display fig.show = lambda *a: display(fig) # If matplotlib was manually set to non-interactive mode, this function # should be a no-op (otherwise we'll generate duplicate plots, since a user # who set ioff() manually expects to make separate draw/show calls). if not matplotlib.is_interactive(): return # ensure current figure will be drawn, and each subsequent call # of draw_if_interactive() moves the active figure to ensure it is # drawn last try: show._to_draw.remove(fig) except ValueError: # ensure it only appears in the draw list once pass # Queue up the figure for drawing in next show() call show._to_draw.append(fig) show._draw_called = True def flush_figures(): """Send all figures that changed This is meant to be called automatically and will call show() if, during prior code execution, there had been any calls to draw_if_interactive. This function is meant to be used as a post_execute callback in IPython, so user-caused errors are handled with showtraceback() instead of being allowed to raise. If this function is not called from within IPython, then these exceptions will raise. """ if not show._draw_called: return if InlineBackend.instance().close_figures: # ignore the tracking, just draw and close all figures try: return show(True) except Exception as e: # safely show traceback if in IPython, else raise ip = get_ipython() if ip is None: raise e else: ip.showtraceback() return try: # exclude any figures that were closed: active = set([fm.canvas.figure for fm in Gcf.get_all_fig_managers()]) for fig in [fig for fig in show._to_draw if fig in active]: try: display(fig) except Exception as e: # safely show traceback if in IPython, else raise ip = get_ipython() if ip is None: raise e else: ip.showtraceback() return finally: # clear flags for next round show._to_draw = [] show._draw_called = False # Changes to matplotlib in version 1.2 requires a mpl backend to supply a default # figurecanvas. This is set here to a Agg canvas # See https://github.com/matplotlib/matplotlib/pull/1125 FigureCanvas = FigureCanvasAgg
{ "repo_name": "mattvonrocketstein/smash", "path": "smashlib/ipy3x/kernel/zmq/pylab/backend_inline.py", "copies": "1", "size": "4994", "license": "mit", "hash": 509267559390923460, "line_mean": 34.1690140845, "line_max": 81, "alpha_frac": 0.6525830997, "autogenerated": false, "ratio": 4.320069204152249, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5472652303852249, "avg_score": null, "num_lines": null }
# a_matrix.py # Construct the parameters for the linear optimisation # # Import external packages import networkx as nx import numpy as np __all__ = ["a_matrix", "build_coupled_edges", "couple_node_sets", "reduce_to_coupled", "adjust_capacity_edges"] def a_matrix(g): # couple_matrix # Construct coupled graph matrix from graph structure # # # Inputs: g - current graph structure # # Outputs: a_coup - coupled incidence matrix # a_vertices - order of vertices in coupled matrix # # order of vertices in incidence matrix nodelist = g.nodes() a_vertices = [n for n in nodelist if 'M' not in n and 'S' not in n] # Incidence matrix a_sparse = nx.incidence_matrix(g, nodelist=nodelist, oriented=True) a_dense = a_sparse.todense() # Build new coupled edges edges_to_add = build_coupled_edges(g, nodelist) # Add edges to matrix try: a_extra = np.hstack((a_dense, edges_to_add)) except ValueError: print('No edges to couple in this frame') a_extra = a_dense # Remove split/merge vertices and previously associated edges a_reduce = reduce_to_coupled(a_extra, nodelist) # Adjust for higher capacity edges a_cap = adjust_capacity_edges(a_reduce, nodelist) a_coup = a_cap.copy() return a_coup, a_vertices def build_coupled_edges(g, nodelist): # new_coupled_edges # given a graph structure returns list of new coupled edges. # # Inputs: g - graph structure # nodelist - order of rows in incidence matrix # # Outputs: new_edges - list of edges to add # Initialise list of new edges new_edges = [] # Loop through nodes for node in nodelist: if 'M' in node or 'S' in node: # sets of neighbouring nodes is split/merge is in solution fixed_set, cycle_set = couple_node_sets(g, node) fixed_edge = [0] * len(nodelist) for f in fixed_set: fixed_edge[nodelist.index(f[0])] = f[1] for c in cycle_set: coupled_edge = list(fixed_edge) coupled_edge[nodelist.index(c[0])] = c[1] new_edges.append(coupled_edge) new_array = np.asarray(new_edges) new_array = np.transpose(new_array) return new_array def couple_node_sets(g, node): # couple_sets # Find the sets of coupling neighbour nodes. # # Inputs: g - graph structure # node - node in question # # Outputs: fixed_set - invariant neighbours when node is in solution # cycle_set - varying neighbours when node is in solution s = [(n, 1) for n in g.successors(node)] p = [(n, -1) for n in g.predecessors(node)] cycle_set = None fixed_set = None if 'M' in node: s.remove(('D', 1)) p.append(('D', 1)) cycle_set = s fixed_set = p elif 'S' in node: p.remove(('A', -1)) s.append(('A', -1)) cycle_set = p fixed_set = s return fixed_set, cycle_set def reduce_to_coupled(a_extra, nodelist): # reduce_to_coupled # Given a_matrix with new coupled edges appended. Remove the split/merge # vertices and their connected edges # # Inputs: a_extra - a matrix with coupled edges appended # nodelist - order of vertices in incidence matrix # # Outputs: a_reduced - Incidence matrix without redundant edges edges_to_remove = set() required_vertices = [] for row, node in enumerate(nodelist): required_vertices.append(row) if 'M' in node or 'S' in node: # remove from included vertices required_vertices.pop() # Find edges to remove row = a_extra[row, :].nonzero()[1] for e in row: edges_to_remove.add(e) # Therefore the included edges are the required_edges = list(set(range(a_extra.shape[1])) - edges_to_remove) # Reduce to only included vertices/edges a_reduced = a_extra[np.ix_(required_vertices, required_edges)] return a_reduced def adjust_capacity_edges(a_dense, nodelist): # adjust_capacity_edges # Account for the larger capacity edges in the graph by appending the # specific edges to the matrix the required amount of times. # # Inputs: a_dense - incidence matrix # nodelist - order of rows in matrix # # Outputs: a_cap - incidence matrix adjusted for edge capacity # a_cap = a_dense.copy() # Coupled nodes couple_vertices = [n for n in nodelist if 'M' not in n and 'S' not in n] # Total nodes l_nodes = sum(1 for x in couple_vertices if 'L' in x) # Edge indices connected to nodes a_e = np.nonzero(a_dense[couple_vertices.index('A'), :])[1] d_e = np.nonzero(a_dense[couple_vertices.index('D'), :])[1] # Edges a_d = set(a_e).intersection(d_e).pop() # Add Edges appropriate number of times for x in xrange(1, l_nodes): a_cap = np.hstack((a_cap, a_cap[:, a_d])) return a_cap
{ "repo_name": "alanaberdeen/coupled-minimum-cost-flow-track", "path": "cmcft/tools/params/a_matrix.py", "copies": "1", "size": "5231", "license": "mit", "hash": -2161424848631343000, "line_mean": 26.103626943, "line_max": 76, "alpha_frac": 0.5909004015, "autogenerated": false, "ratio": 3.573087431693989, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.966398783319399, "avg_score": 0, "num_lines": 193 }
"""Amavis related functions.""" import os import platform from .. import package from .. import utils from . import base from . import install class Amavis(base.Installer): """Amavis installer.""" appname = "amavis" packages = { "deb": [ "libdbi-perl", "amavisd-new", "arc", "arj", "cabextract", "liblz4-tool", "lrzip", "lzop", "p7zip-full", "rpm2cpio", "unrar-free", ], "rpm": [ "amavisd-new", "arj", "cabextract", "lz4", "lrzip", "lzop", "p7zip", "unar", "unzoo" ], } with_db = True @property def config_dir(self): """Return appropriate config dir.""" if package.backend.FORMAT == "rpm": return "/etc/amavisd" return "/etc/amavis" def get_daemon_name(self): """Return appropriate daemon name.""" if package.backend.FORMAT == "rpm": return "amavisd" return "amavis" def get_config_files(self): """Return appropriate config files.""" if package.backend.FORMAT == "deb": return [ "conf.d/05-node_id", "conf.d/15-content_filter_mode", "conf.d/50-user"] return ["amavisd.conf"] def get_packages(self): """Additional packages.""" packages = super(Amavis, self).get_packages() if package.backend.FORMAT == "deb": db_driver = "pg" if self.db_driver == "pgsql" else self.db_driver return packages + ["libdbd-{}-perl".format(db_driver)] if self.db_driver == "pgsql": db_driver = "Pg" elif self.db_driver == "mysql": db_driver = "MySQL" else: raise NotImplementedError("DB driver not supported") return packages + ["perl-DBD-{}".format(db_driver)] def get_sql_schema_path(self): """Return schema path.""" version = package.backend.get_installed_version("amavisd-new") if version is None: raise utils.FatalError("Amavis is not installed") path = self.get_file_path( "amavis_{}_{}.sql".format(self.dbengine, version)) if not os.path.exists(path): version = ".".join(version.split(".")[:-1]) + ".X" path = self.get_file_path( "amavis_{}_{}.sql".format(self.dbengine, version)) if not os.path.exists(path): raise utils.FatalError("Failed to find amavis database schema") return path def pre_run(self): """Tasks to run first.""" with open("/etc/mailname", "w") as fp: fp.write("{}\n".format(self.config.get("general", "hostname"))) def post_run(self): """Additional tasks.""" install("spamassassin", self.config, self.upgrade) install("clamav", self.config, self.upgrade)
{ "repo_name": "modoboa/modoboa-installer", "path": "modoboa_installer/scripts/amavis.py", "copies": "1", "size": "2863", "license": "mit", "hash": 3145732697487889400, "line_mean": 31.1685393258, "line_max": 78, "alpha_frac": 0.5452322738, "autogenerated": false, "ratio": 3.694193548387097, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.47394258221870966, "avg_score": null, "num_lines": null }
"""A max heap is a complete binary tree [CBT] (implemented using array) in which each node has a value larger than its sub-trees""" from math import ceil class MaxHeap: def __init__(self, arr=None): self.heap = [] self.heap_size = 0 if arr is not None: self.create_max_heap(arr) self.heap = arr self.heap_size = len(arr) def create_max_heap(self, arr): """ Converts a given array into a max heap :param arr: input array of numbers """ n = len(arr) # last n/2 elements will be leaf nodes (CBT property) hence already max heaps # loop from n/2 to 0 index and convert each index node into max heap for i in range(int(n / 2), -1, -1): self.max_heapify(i, arr, n) def max_heapify(self, indx, arr, size): """ Assuming sub trees are already max heaps, converts tree rooted at current indx into a max heap. :param indx: Index to check for max heap """ # Get index of left and right child of indx node left_child = indx * 2 + 1 right_child = indx * 2 + 2 largest = indx # check what is the largest value node in indx, left child and right child if left_child < size: if arr[left_child] > arr[largest]: largest = left_child if right_child < size: if arr[right_child] > arr[largest]: largest = right_child # if indx node is not the largest value, swap with the largest child # and recursively call min_heapify on the respective child swapped with if largest != indx: arr[indx], arr[largest] = arr[largest], arr[indx] self.max_heapify(largest, arr, size) def insert(self, value): """ Inserts an element in the max heap :param value: value to be inserted in the heap """ self.heap.append(value) self.heap_size += 1 indx = self.heap_size - 1 # Get parent index of the current node parent = int(ceil(indx / 2 - 1)) # Check if the parent value is smaller than the newly inserted value # if so, then replace the value with the parent value and check with the new parent while parent >= 0 and self.heap[indx] > self.heap[parent]: self.heap[indx], self.heap[parent] = self.heap[parent], self.heap[indx] indx = parent parent = int(ceil(indx / 2 - 1)) def delete(self, indx): """ Deletes the value on the specified index node :param indx: index whose node is to be removed :return: Value of the node deleted from the heap """ if self.heap_size == 0: print("Heap Underflow!!") return self.heap[-1], self.heap[indx] = self.heap[indx], self.heap[-1] self.heap_size -= 1 self.max_heapify(indx, self.heap, self.heap_size) return self.heap.pop() def extract_max(self): """ Extracts the maximum value from the heap :return: extracted max value """ return self.delete(0) def print(self): print(*self.heap) heap = MaxHeap([5, 10, 4, 8, 3, 0, 9, 11]) heap.insert(15) print(heap.delete(2)) print(heap.extract_max()) heap.print()
{ "repo_name": "anubhavshrimal/Data_Structures_Algorithms_In_Python", "path": "Heaps/MaxHeap.py", "copies": "1", "size": "3359", "license": "mit", "hash": -8156910757316596000, "line_mean": 30.6886792453, "line_max": 103, "alpha_frac": 0.5754688896, "autogenerated": false, "ratio": 3.847651775486827, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4923120665086827, "avg_score": null, "num_lines": null }
"""A MayaVi example of how to generate an unstructured grid dataset using numpy arrays. Also shown is a way to visualize this data with mayavi2. The script can be run like so: $ mayavi2 -x unstructured_grid.py Alternatively, it can be run as: $ python unstructured_grid.py Author: Prabhu Ramachandran <prabhu at aero dot iitb dot ac dot in> Copyright (c) 2007, Enthought, Inc. License: BSD style. """ from numpy import array, arange, random from tvtk.api import tvtk from mayavi.scripts import mayavi2 def single_type_ug(): """Simple example showing how to create an unstructured grid consisting of cells of a single type. """ points = array([[0,0,0], [1,0,0], [0,1,0], [0,0,1], # tets [1,0,0], [2,0,0], [1,1,0], [1,0,1], [2,0,0], [3,0,0], [2,1,0], [2,0,1], ], 'f') tets = array([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]) tet_type = tvtk.Tetra().cell_type ug = tvtk.UnstructuredGrid(points=points) ug.set_cells(tet_type, tets) return ug def mixed_type_ug(): """A slightly more complex example of how to generate an unstructured grid with different cell types. Returns a created unstructured grid. """ points = array([[0,0,0], [1,0,0], [0,1,0], [0,0,1], # tetra [2,0,0], [3,0,0], [3,1,0], [2,1,0], [2,0,1], [3,0,1], [3,1,1], [2,1,1], # Hex ], 'f') # shift the points so we can show both. points[:,1] += 2.0 # The cells cells = array([4, 0, 1, 2, 3, # tetra 8, 4, 5, 6, 7, 8, 9, 10, 11 # hex ]) # The offsets for the cells, i.e. the indices where the cells # start. offset = array([0, 5]) tetra_type = tvtk.Tetra().cell_type # VTK_TETRA == 10 hex_type = tvtk.Hexahedron().cell_type # VTK_HEXAHEDRON == 12 cell_types = array([tetra_type, hex_type]) # Create the array of cells unambiguously. cell_array = tvtk.CellArray() cell_array.set_cells(2, cells) # Now create the UG. ug = tvtk.UnstructuredGrid(points=points) # Now just set the cell types and reuse the ug locations and cells. ug.set_cells(cell_types, offset, cell_array) return ug def save_xml(ug, file_name): """Shows how you can save the unstructured grid dataset to a VTK XML file.""" w = tvtk.XMLUnstructuredGridWriter(input=ug, file_name=file_name) w.write() # ---------------------------------------------------------------------- # Create the unstructured grids and assign scalars and vectors. ug1 = single_type_ug() ug2 = mixed_type_ug() temperature = arange(0, 120, 10, 'd') velocity = random.randn(12, 3) for ug in ug1, ug2: ug.point_data.scalars = temperature ug.point_data.scalars.name = 'temperature' # Some vectors. ug.point_data.vectors = velocity ug.point_data.vectors.name = 'velocity' # Uncomment this to save the file to a VTK XML file. #save_xml(ug2, 'file.vtu') # Now view the data. @mayavi2.standalone def view(): from mayavi.sources.vtk_data_source import VTKDataSource from mayavi.modules.outline import Outline from mayavi.modules.surface import Surface from mayavi.modules.vectors import Vectors mayavi.new_scene() # The single type one src = VTKDataSource(data = ug1) mayavi.add_source(src) mayavi.add_module(Outline()) mayavi.add_module(Surface()) mayavi.add_module(Vectors()) # Mixed types. src = VTKDataSource(data = ug2) mayavi.add_source(src) mayavi.add_module(Outline()) mayavi.add_module(Surface()) mayavi.add_module(Vectors()) if __name__ == '__main__': view()
{ "repo_name": "liulion/mayavi", "path": "docs/source/mayavi/auto/unstructured_grid.py", "copies": "10", "size": "3670", "license": "bsd-3-clause", "hash": 1778426549892307500, "line_mean": 32.0630630631, "line_max": 72, "alpha_frac": 0.6079019074, "autogenerated": false, "ratio": 3.048172757475083, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8656074664875083, "avg_score": null, "num_lines": null }
""" Amazon Access Challenge Code for ensemble Marios Michaildis script for Amazon . Uses counts as features and 3way interactions and xgboost based on Paul Duan's Script. """ from __future__ import division import numpy as np from sklearn import preprocessing from sklearn.metrics import roc_auc_score import XGBoostClassifier as xg from sklearn.cross_validation import StratifiedKFold import pandas as pd SEED = 42 # always use a seed for randomized procedures def load_datacount3D(tr,te): #w ewill use pandas train = pd.read_csv(tr, sep=',',quotechar='"') test = pd.read_csv(te, sep=',',quotechar='"') label= np.array(train['ACTION']).astype(float) train.drop('ACTION', axis=1, inplace=True) test.drop('id', axis=1, inplace=True) test.drop('ROLE_CODE', axis=1, inplace=True) train.drop('ROLE_CODE', axis=1, inplace=True) train_s = train test_s = test headers=[f for f in train_s.columns] for t, col in enumerate(headers): for t1, col1 in enumerate(headers): if t1 <= t: continue print col + "_" + col1 train_s[col+"_"+col1] = train_s[[col, col1]].apply(lambda x: int(x[0]) + int(x[1]), axis=1) test_s[col+"_"+col1] = test_s[[col, col1]].apply(lambda x: int(x[0]) + int(x[1]), axis=1) for t, col in enumerate(headers): for t1, col1 in enumerate(headers): if t1 <= t: continue for t2, col2 in enumerate(headers): if t2 <= t1: continue print col + "_" + col1+ "_"+ col2 train_s[col+"_"+col1+"_"+col2] = train_s[[col, col1, col2]].apply(lambda x: int(x[0]) + int(x[1]) + int(x[2]), axis=1) test_s[col+"_"+col1+"_"+col2] = test_s[[col, col1, col2]].apply(lambda x: int(x[0]) + int(x[1]) + int(x[2]), axis=1) result = pd.concat([test_s,train_s]) headers=[f for f in result.columns] for i in range(train_s.shape[1]): print headers[i], len(np.unique(result[headers[i]])) cnt = result[headers[i]].value_counts().to_dict() #cnt = dict((k, -1) if v < 3 else (k,v) for k, v in cnt.items() ) # if u want to encode rare values as "special" train_s[headers[i]].replace(cnt, inplace=True) test_s[headers[i]].replace(cnt, inplace=True) train = np.array(train_s).astype(float) test = np.array(test_s).astype(float) print train.shape print test.shape return label, train,test def save_results(predictions, filename): """Given a vector of predictions, save results in CSV format.""" with open(filename, 'w') as f: f.write("id,ACTION\n") for i, pred in enumerate(predictions): f.write("%d,%f\n" % (i + 1, pred)) def bagged_set(X_t,y_c,model, seed, estimators, xt, update_seed=True): # create array object to hold predictions baggedpred=[ 0.0 for d in range(0, (xt.shape[0]))] #loop for as many times as we want bags for n in range (0, estimators): #shuff;e first, aids in increasing variance and forces different results #X_t,y_c=shuffle(Xs,ys, random_state=seed+n) if update_seed: # update seed if requested, to give a slightly different model model.set_params(random_state=seed + n) model.fit(X_t,y_c) # fit model0.0917411475506 preds=model.predict_proba(xt)[:,1] # predict probabilities # update bag's array for j in range (0, (xt.shape[0])): baggedpred[j]+=preds[j] # divide with number of bags to create an average estimate for j in range (0, len(baggedpred)): baggedpred[j]/=float(estimators) # return probabilities return np.array(baggedpred) # using numpy to print results def printfilcsve(X, filename): np.savetxt(filename,X) def main(): """ Fit models and make predictions. We'll use one-hot encoding to transform our categorical features into binary features. y and X will be numpy array objects. """ filename="main_xgboos_count_3D" # nam prefix #model = linear_model.LogisticRegression(C=3) # the classifier we'll use model=xg.XGBoostClassifier(num_round=1000 ,nthread=25, eta=0.012, gamma=0.1,max_depth=30, min_child_weight=0.1, subsample=0.9, colsample_bytree=0.08,objective='binary:logistic',seed=1) # === load data in memory === # print "loading data" y, X,X_test = load_datacount3D('train.csv','test.csv') # === one-hot encoding === # # we want to encode the category IDs encountered both in # the training and the test set, so we fit the encoder on both # if you want to create new features, you'll need to compute them # before the encoding, and append them to your dataset after #create arrays to hold cv an dtest predictions train_stacker=[ 0.0 for k in range (0,(X.shape[0])) ] # === training & metrics === # mean_auc = 0.0 bagging=20 # number of models trained with different seeds n = 5 # number of folds in strattified cv kfolder=StratifiedKFold(y, n_folds= n,shuffle=True, random_state=SEED) i=0 for train_index, test_index in kfolder: # for each train and test pair of indices in the kfolder object # creaning and validation sets X_train, X_cv = X[train_index], X[test_index] y_train, y_cv = np.array(y)[train_index], np.array(y)[test_index] #print (" train size: %d. test size: %d, cols: %d " % ((X_train.shape[0]) ,(X_cv.shape[0]) ,(X_train.shape[1]) )) # if you want to perform feature selection / hyperparameter # optimization, this is where you want to do it # train model and make predictions preds=bagged_set(X_train,y_train,model, SEED , bagging, X_cv, update_seed=True) # compute AUC metric for this CV fold roc_auc = roc_auc_score(y_cv, preds) print "AUC (fold %d/%d): %f" % (i + 1, n, roc_auc) mean_auc += roc_auc no=0 for real_index in test_index: train_stacker[real_index]=(preds[no]) no+=1 i+=1 mean_auc/=n print (" Average AUC: %f" % (mean_auc) ) print (" printing train datasets ") printfilcsve(np.array(train_stacker), filename + ".train.csv") # === Predictions === # # When making predictions, retrain the model on the whole training set preds=bagged_set(X, y,model, SEED, bagging, X_test, update_seed=True) #create submission file printfilcsve(np.array(preds), filename+ ".test.csv") #save_results(preds, filename+"_submission_" +str(mean_auc) + ".csv") if __name__ == '__main__': main()
{ "repo_name": "kaz-Anova/ensemble_amazon", "path": "amazon_main_xgboost_count_3D.py", "copies": "1", "size": "7087", "license": "apache-2.0", "hash": 5954560332607227000, "line_mean": 36.4973544974, "line_max": 142, "alpha_frac": 0.5809228164, "autogenerated": false, "ratio": 3.4121328839672604, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9295742274285561, "avg_score": 0.0394626852163398, "num_lines": 189 }
""" Amazon Access Challenge Code for ensemble Marios Michaildis script for Amazon . Uses counts as features and xgboost based on Paul Duan's Script. """ from __future__ import division import numpy as np from sklearn import preprocessing from sklearn.metrics import roc_auc_score import XGBoostClassifier as xg from sklearn.cross_validation import StratifiedKFold import pandas as pd SEED = 42 # always use a seed for randomized procedures def load_datacount(tr,te): #w ewill use pandas train = pd.read_csv(tr, sep=',',quotechar='"') test = pd.read_csv(te, sep=',',quotechar='"') label= np.array(train['ACTION']).astype(float) train.drop('ACTION', axis=1, inplace=True) test.drop('id', axis=1, inplace=True) test.drop('ROLE_CODE', axis=1, inplace=True) train.drop('ROLE_CODE', axis=1, inplace=True) train_s = train test_s = test result = pd.concat([test_s,train_s]) headers=[f for f in result.columns] for i in range(train_s.shape[1]): print headers[i], len(np.unique(result[headers[i]])) cnt = result[headers[i]].value_counts().to_dict() #cnt = dict((k, -1) if v < 3 else (k,v) for k, v in cnt.items() ) # if u want to encode rare values as "special" train_s[headers[i]].replace(cnt, inplace=True) test_s[headers[i]].replace(cnt, inplace=True) train = np.array(train_s).astype(float) test = np.array(test_s).astype(float) print train.shape print test.shape return label, train,test def save_results(predictions, filename): """Given a vector of predictions, save results in CSV format.""" with open(filename, 'w') as f: f.write("id,ACTION\n") for i, pred in enumerate(predictions): f.write("%d,%f\n" % (i + 1, pred)) def bagged_set(X_t,y_c,model, seed, estimators, xt, update_seed=True): # create array object to hold predictions baggedpred=[ 0.0 for d in range(0, (xt.shape[0]))] #loop for as many times as we want bags for n in range (0, estimators): #shuff;e first, aids in increasing variance and forces different results #X_t,y_c=shuffle(Xs,ys, random_state=seed+n) if update_seed: # update seed if requested, to give a slightly different model model.set_params(random_state=seed + n) model.fit(X_t,y_c) # fit model0.0917411475506 preds=model.predict_proba(xt)[:,1] # predict probabilities # update bag's array for j in range (0, (xt.shape[0])): baggedpred[j]+=preds[j] # divide with number of bags to create an average estimate for j in range (0, len(baggedpred)): baggedpred[j]/=float(estimators) # return probabilities return np.array(baggedpred) # using numpy to print results def printfilcsve(X, filename): np.savetxt(filename,X) def main(): """ Fit models and make predictions. We'll use one-hot encoding to transform our categorical features into binary features. y and X will be numpy array objects. """ filename="main_xgboos_count" # nam prefix #model = linear_model.LogisticRegression(C=3) # the classifier we'll use model=xg.XGBoostClassifier(num_round=1000 ,nthread=25, eta=0.02, gamma=1,max_depth=20, min_child_weight=0.1, subsample=0.9, colsample_bytree=0.5,objective='binary:logistic',seed=1) # === load data in memory === # print "loading data" y, X,X_test = load_datacount('train.csv','test.csv') # === one-hot encoding === # # we want to encode the category IDs encountered both in # the training and the test set, so we fit the encoder on both # if you want to create new features, you'll need to compute them # before the encoding, and append them to your dataset after #create arrays to hold cv an dtest predictions train_stacker=[ 0.0 for k in range (0,(X.shape[0])) ] # === training & metrics === # mean_auc = 0.0 bagging=20 # number of models trained with different seeds n = 5 # number of folds in strattified cv kfolder=StratifiedKFold(y, n_folds= n,shuffle=True, random_state=SEED) i=0 for train_index, test_index in kfolder: # for each train and test pair of indices in the kfolder object # creaning and validation sets X_train, X_cv = X[train_index], X[test_index] y_train, y_cv = np.array(y)[train_index], np.array(y)[test_index] #print (" train size: %d. test size: %d, cols: %d " % ((X_train.shape[0]) ,(X_cv.shape[0]) ,(X_train.shape[1]) )) # if you want to perform feature selection / hyperparameter # optimization, this is where you want to do it # train model and make predictions preds=bagged_set(X_train,y_train,model, SEED , bagging, X_cv, update_seed=True) # compute AUC metric for this CV fold roc_auc = roc_auc_score(y_cv, preds) print "AUC (fold %d/%d): %f" % (i + 1, n, roc_auc) mean_auc += roc_auc no=0 for real_index in test_index: train_stacker[real_index]=(preds[no]) no+=1 i+=1 mean_auc/=n print (" Average AUC: %f" % (mean_auc) ) print (" printing train datasets ") printfilcsve(np.array(train_stacker), filename + ".train.csv") # === Predictions === # # When making predictions, retrain the model on the whole training set preds=bagged_set(X, y,model, SEED, bagging, X_test, update_seed=True) #create submission file printfilcsve(np.array(preds), filename+ ".test.csv") #save_results(preds, filename+"_submission_" +str(mean_auc) + ".csv") if __name__ == '__main__': main()
{ "repo_name": "kaz-Anova/ensemble_amazon", "path": "amazon_main_xgboost_count.py", "copies": "1", "size": "5957", "license": "apache-2.0", "hash": 8938056276628725000, "line_mean": 33.8362573099, "line_max": 133, "alpha_frac": 0.6091992614, "autogenerated": false, "ratio": 3.429476108232585, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4538675369632585, "avg_score": null, "num_lines": null }
""" Amazon Access Challenge Code for ensemble Marios Michaildis script for Amazon . xgboost on input data based on Paul Duan's Script. """ from __future_ _ import division import numpy as np from sklearn import preprocessing from sklearn.metrics import roc_auc_score import XGBoostClassifier as xg from sklearn.cross_validation import StratifiedKFold SEED = 42 # always use a seed for randomized procedures def load_data(filename, use_labels=True): """ Load data from CSV files and return them as numpy arrays The use_labels parameter indicates whether one should read the first column (containing class labels). If false, return all 0s. """ # load column 1 to 8 (ignore last one) data = np.loadtxt(open( filename), delimiter=',', usecols=range(1, 9), skiprows=1) if use_labels: labels = np.loadtxt(open( filename), delimiter=',', usecols=[0], skiprows=1) else: labels = np.zeros(data.shape[0]) return labels, data def save_results(predictions, filename): """Given a vector of predictions, save results in CSV format.""" with open(filename, 'w') as f: f.write("id,ACTION\n") for i, pred in enumerate(predictions): f.write("%d,%f\n" % (i + 1, pred)) def bagged_set(X_t,y_c,model, seed, estimators, xt, update_seed=True): # create array object to hold predictions baggedpred=[ 0.0 for d in range(0, (xt.shape[0]))] #loop for as many times as we want bags for n in range (0, estimators): #shuff;e first, aids in increasing variance and forces different results #X_t,y_c=shuffle(Xs,ys, random_state=seed+n) if update_seed: # update seed if requested, to give a slightly different model model.set_params(random_state=seed + n) model.fit(X_t,y_c) # fit model0.0917411475506 preds=model.predict_proba(xt)[:,1] # predict probabilities # update bag's array for j in range (0, (xt.shape[0])): baggedpred[j]+=preds[j] # divide with number of bags to create an average estimate for j in range (0, len(baggedpred)): baggedpred[j]/=float(estimators) # return probabilities return np.array(baggedpred) # using numpy to print results def printfilcsve(X, filename): np.savetxt(filename,X) def main(): """ Fit models and make predictions. We'll use one-hot encoding to transform our categorical features into binary features. y and X will be numpy array objects. """ filename="main_xgboost" # nam prefix #model = linear_model.LogisticRegression(C=3) # the classifier we'll use model=xg.XGBoostClassifier(num_round=1000 ,nthread=25, eta=0.12, gamma=0.01,max_depth=12, min_child_weight=0.01, subsample=0.6, colsample_bytree=0.7,objective='binary:logistic',seed=1) # === load data in memory === # print "loading data" y, X = load_data('train.csv') y_test, X_test = load_data('test.csv', use_labels=False) # === one-hot encoding === # # we want to encode the category IDs encountered both in # the training and the test set, so we fit the encoder on both encoder = preprocessing.OneHotEncoder() encoder.fit(np.vstack((X, X_test))) X = encoder.transform(X) # Returns a sparse matrix (see numpy.sparse) X_test = encoder.transform(X_test) # if you want to create new features, you'll need to compute them # before the encoding, and append them to your dataset after #create arrays to hold cv an dtest predictions train_stacker=[ 0.0 for k in range (0,(X.shape[0])) ] # === training & metrics === # mean_auc = 0.0 bagging=20 # number of models trained with different seeds n = 5 # number of folds in strattified cv kfolder=StratifiedKFold(y, n_folds= n,shuffle=True, random_state=SEED) i=0 for train_index, test_index in kfolder: # for each train and test pair of indices in the kfolder object # creaning and validation sets X_train, X_cv = X[train_index], X[test_index] y_train, y_cv = np.array(y)[train_index], np.array(y)[test_index] #print (" train size: %d. test size: %d, cols: %d " % ((X_train.shape[0]) ,(X_cv.shape[0]) ,(X_train.shape[1]) )) # if you want to perform feature selection / hyperparameter # optimization, this is where you want to do it # train model and make predictions preds=bagged_set(X_train,y_train,model, SEED , bagging, X_cv, update_seed=True) # compute AUC metric for this CV fold roc_auc = roc_auc_score(y_cv, preds) print "AUC (fold %d/%d): %f" % (i + 1, n, roc_auc) mean_auc += roc_auc no=0 for real_index in test_index: train_stacker[real_index]=(preds[no]) no+=1 i+=1 mean_auc/=n print (" Average AUC: %f" % (mean_auc) ) print (" printing train datasets ") printfilcsve(np.array(train_stacker), filename + ".train.csv") # === Predictions === # # When making predictions, retrain the model on the whole training set preds=bagged_set(X, y,model, SEED, bagging, X_test, update_seed=True) #create submission file printfilcsve(np.array(preds), filename+ ".test.csv") #save_results(preds, filename+"_submission_" +str(mean_auc) + ".csv") if __name__ == '__main__': main()
{ "repo_name": "kaz-Anova/ensemble_amazon", "path": "amazon_main_xgboost.py", "copies": "1", "size": "5579", "license": "apache-2.0", "hash": 8209580502970843000, "line_mean": 34.7628205128, "line_max": 133, "alpha_frac": 0.6226922388, "autogenerated": false, "ratio": 3.493425172197871, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9473785477819435, "avg_score": 0.028466386635687124, "num_lines": 156 }
"""Amazon AWS Connection.""" from vine import promise, transform from kombu.asynchronous.aws.ext import AWSRequest, get_response from kombu.asynchronous.http import Headers, Request, get_client from email import message_from_bytes from email.mime.message import MIMEMessage def message_from_headers(hdr): # noqa bs = "\r\n".join("{}: {}".format(*h) for h in hdr) return message_from_bytes(bs.encode()) __all__ = ( 'AsyncHTTPSConnection', 'AsyncConnection', ) class AsyncHTTPResponse: """Async HTTP Response.""" def __init__(self, response): self.response = response self._msg = None self.version = 10 def read(self, *args, **kwargs): return self.response.body def getheader(self, name, default=None): return self.response.headers.get(name, default) def getheaders(self): return list(self.response.headers.items()) @property def msg(self): if self._msg is None: self._msg = MIMEMessage(message_from_headers(self.getheaders())) return self._msg @property def status(self): return self.response.code @property def reason(self): if self.response.error: return self.response.error.message return '' def __repr__(self): return repr(self.response) class AsyncHTTPSConnection: """Async HTTP Connection.""" Request = Request Response = AsyncHTTPResponse method = 'GET' path = '/' body = None default_ports = {'http': 80, 'https': 443} def __init__(self, strict=None, timeout=20.0, http_client=None): self.headers = [] self.timeout = timeout self.strict = strict self.http_client = http_client or get_client() def request(self, method, path, body=None, headers=None): self.path = path self.method = method if body is not None: try: read = body.read except AttributeError: self.body = body else: self.body = read() if headers is not None: self.headers.extend(list(headers.items())) def getrequest(self): headers = Headers(self.headers) return self.Request(self.path, method=self.method, headers=headers, body=self.body, connect_timeout=self.timeout, request_timeout=self.timeout, validate_cert=False) def getresponse(self, callback=None): request = self.getrequest() request.then(transform(self.Response, callback)) return self.http_client.add_request(request) def set_debuglevel(self, level): pass def connect(self): pass def close(self): pass def putrequest(self, method, path): self.method = method self.path = path def putheader(self, header, value): self.headers.append((header, value)) def endheaders(self): pass def send(self, data): if self.body: self.body += data else: self.body = data def __repr__(self): return f'<AsyncHTTPConnection: {self.getrequest()!r}>' class AsyncConnection: """Async AWS Connection.""" def __init__(self, sqs_connection, http_client=None, **kwargs): # noqa self.sqs_connection = sqs_connection self._httpclient = http_client or get_client() def get_http_connection(self): return AsyncHTTPSConnection(http_client=self._httpclient) def _mexe(self, request, sender=None, callback=None): callback = callback or promise() conn = self.get_http_connection() if callable(sender): sender(conn, request.method, request.path, request.body, request.headers, callback) else: conn.request(request.method, request.url, request.body, request.headers) conn.getresponse(callback=callback) return callback class AsyncAWSQueryConnection(AsyncConnection): """Async AWS Query Connection.""" STATUS_CODE_OK = 200 STATUS_CODE_REQUEST_TIMEOUT = 408 STATUS_CODE_NETWORK_CONNECT_TIMEOUT_ERROR = 599 STATUS_CODE_INTERNAL_ERROR = 500 STATUS_CODE_BAD_GATEWAY = 502 STATUS_CODE_SERVICE_UNAVAILABLE_ERROR = 503 STATUS_CODE_GATEWAY_TIMEOUT = 504 STATUS_CODES_SERVER_ERRORS = ( STATUS_CODE_INTERNAL_ERROR, STATUS_CODE_BAD_GATEWAY, STATUS_CODE_SERVICE_UNAVAILABLE_ERROR ) STATUS_CODES_TIMEOUT = ( STATUS_CODE_REQUEST_TIMEOUT, STATUS_CODE_NETWORK_CONNECT_TIMEOUT_ERROR, STATUS_CODE_GATEWAY_TIMEOUT ) def __init__(self, sqs_connection, http_client=None, http_client_params=None, **kwargs): if not http_client_params: http_client_params = {} AsyncConnection.__init__(self, sqs_connection, http_client, **http_client_params) def make_request(self, operation, params_, path, verb, callback=None): # noqa params = params_.copy() if operation: params['Action'] = operation signer = self.sqs_connection._request_signer # noqa # defaults for non-get signing_type = 'standard' param_payload = {'data': params} if verb.lower() == 'get': # query-based opts signing_type = 'presignurl' param_payload = {'params': params} request = AWSRequest(method=verb, url=path, **param_payload) signer.sign(operation, request, signing_type=signing_type) prepared_request = request.prepare() return self._mexe(prepared_request, callback=callback) def get_list(self, operation, params, markers, path='/', parent=None, verb='POST', callback=None): # noqa return self.make_request( operation, params, path, verb, callback=transform( self._on_list_ready, callback, parent or self, markers, operation ), ) def get_object(self, operation, params, path='/', parent=None, verb='GET', callback=None): # noqa return self.make_request( operation, params, path, verb, callback=transform( self._on_obj_ready, callback, parent or self, operation ), ) def get_status(self, operation, params, path='/', parent=None, verb='GET', callback=None): # noqa return self.make_request( operation, params, path, verb, callback=transform( self._on_status_ready, callback, parent or self, operation ), ) def _on_list_ready(self, parent, markers, operation, response): # noqa service_model = self.sqs_connection.meta.service_model if response.status == self.STATUS_CODE_OK: _, parsed = get_response( service_model.operation_model(operation), response.response ) return parsed elif ( response.status in self.STATUS_CODES_TIMEOUT or response.status in self.STATUS_CODES_SERVER_ERRORS ): # When the server returns a timeout or 50X server error, # the response is interpreted as an empty list. # This prevents hanging the Celery worker. return [] else: raise self._for_status(response, response.read()) def _on_obj_ready(self, parent, operation, response): # noqa service_model = self.sqs_connection.meta.service_model if response.status == self.STATUS_CODE_OK: _, parsed = get_response( service_model.operation_model(operation), response.response ) return parsed else: raise self._for_status(response, response.read()) def _on_status_ready(self, parent, operation, response): # noqa service_model = self.sqs_connection.meta.service_model if response.status == self.STATUS_CODE_OK: httpres, _ = get_response( service_model.operation_model(operation), response.response ) return httpres.code else: raise self._for_status(response, response.read()) def _for_status(self, response, body): context = 'Empty body' if not body else 'HTTP Error' return Exception("Request {} HTTP {} {} ({})".format( context, response.status, response.reason, body ))
{ "repo_name": "celery/kombu", "path": "kombu/asynchronous/aws/connection.py", "copies": "1", "size": "8572", "license": "bsd-3-clause", "hash": 2413738820337896000, "line_mean": 30.7481481481, "line_max": 110, "alpha_frac": 0.5965935604, "autogenerated": false, "ratio": 4.197845249755142, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5294438810155142, "avg_score": null, "num_lines": null }
"""Amazon AWS Connection.""" from vine import promise, transform from kombu.asynchronous.aws.ext import AWSRequest, get_response from kombu.asynchronous.http import Headers, Request, get_client import io try: # pragma: no cover from email import message_from_bytes from email.mime.message import MIMEMessage # py3 def message_from_headers(hdr): # noqa bs = "\r\n".join("{}: {}".format(*h) for h in hdr) return message_from_bytes(bs.encode()) except ImportError: # pragma: no cover from mimetools import Message as MIMEMessage # noqa # py2 def message_from_headers(hdr): # noqa return io.BytesIO(b'\r\n'.join( b'{}: {}'.format(*h) for h in hdr )) __all__ = ( 'AsyncHTTPSConnection', 'AsyncConnection', ) class AsyncHTTPResponse: """Async HTTP Response.""" def __init__(self, response): self.response = response self._msg = None self.version = 10 def read(self, *args, **kwargs): return self.response.body def getheader(self, name, default=None): return self.response.headers.get(name, default) def getheaders(self): return list(self.response.headers.items()) @property def msg(self): if self._msg is None: self._msg = MIMEMessage(message_from_headers(self.getheaders())) return self._msg @property def status(self): return self.response.code @property def reason(self): if self.response.error: return self.response.error.message return '' def __repr__(self): return repr(self.response) class AsyncHTTPSConnection: """Async HTTP Connection.""" Request = Request Response = AsyncHTTPResponse method = 'GET' path = '/' body = None default_ports = {'http': 80, 'https': 443} def __init__(self, strict=None, timeout=20.0, http_client=None): self.headers = [] self.timeout = timeout self.strict = strict self.http_client = http_client or get_client() def request(self, method, path, body=None, headers=None): self.path = path self.method = method if body is not None: try: read = body.read except AttributeError: self.body = body else: self.body = read() if headers is not None: self.headers.extend(list(headers.items())) def getrequest(self): headers = Headers(self.headers) return self.Request(self.path, method=self.method, headers=headers, body=self.body, connect_timeout=self.timeout, request_timeout=self.timeout, validate_cert=False) def getresponse(self, callback=None): request = self.getrequest() request.then(transform(self.Response, callback)) return self.http_client.add_request(request) def set_debuglevel(self, level): pass def connect(self): pass def close(self): pass def putrequest(self, method, path): self.method = method self.path = path def putheader(self, header, value): self.headers.append((header, value)) def endheaders(self): pass def send(self, data): if self.body: self.body += data else: self.body = data def __repr__(self): return f'<AsyncHTTPConnection: {self.getrequest()!r}>' class AsyncConnection: """Async AWS Connection.""" def __init__(self, sqs_connection, http_client=None, **kwargs): # noqa self.sqs_connection = sqs_connection self._httpclient = http_client or get_client() def get_http_connection(self): return AsyncHTTPSConnection(http_client=self._httpclient) def _mexe(self, request, sender=None, callback=None): callback = callback or promise() conn = self.get_http_connection() if callable(sender): sender(conn, request.method, request.path, request.body, request.headers, callback) else: conn.request(request.method, request.url, request.body, request.headers) conn.getresponse(callback=callback) return callback class AsyncAWSQueryConnection(AsyncConnection): """Async AWS Query Connection.""" STATUS_CODE_OK = 200 STATUS_CODE_REQUEST_TIMEOUT = 408 STATUS_CODE_NETWORK_CONNECT_TIMEOUT_ERROR = 599 STATUS_CODE_INTERNAL_ERROR = 500 STATUS_CODE_BAD_GATEWAY = 502 STATUS_CODE_SERVICE_UNAVAILABLE_ERROR = 503 STATUS_CODE_GATEWAY_TIMEOUT = 504 STATUS_CODES_SERVER_ERRORS = ( STATUS_CODE_INTERNAL_ERROR, STATUS_CODE_BAD_GATEWAY, STATUS_CODE_SERVICE_UNAVAILABLE_ERROR ) STATUS_CODES_TIMEOUT = ( STATUS_CODE_REQUEST_TIMEOUT, STATUS_CODE_NETWORK_CONNECT_TIMEOUT_ERROR, STATUS_CODE_GATEWAY_TIMEOUT ) def __init__(self, sqs_connection, http_client=None, http_client_params=None, **kwargs): if not http_client_params: http_client_params = {} AsyncConnection.__init__(self, sqs_connection, http_client, **http_client_params) def make_request(self, operation, params_, path, verb, callback=None): # noqa params = params_.copy() if operation: params['Action'] = operation signer = self.sqs_connection._request_signer # noqa # defaults for non-get signing_type = 'standard' param_payload = {'data': params} if verb.lower() == 'get': # query-based opts signing_type = 'presignurl' param_payload = {'params': params} request = AWSRequest(method=verb, url=path, **param_payload) signer.sign(operation, request, signing_type=signing_type) prepared_request = request.prepare() return self._mexe(prepared_request, callback=callback) def get_list(self, operation, params, markers, path='/', parent=None, verb='POST', callback=None): # noqa return self.make_request( operation, params, path, verb, callback=transform( self._on_list_ready, callback, parent or self, markers, operation ), ) def get_object(self, operation, params, path='/', parent=None, verb='GET', callback=None): # noqa return self.make_request( operation, params, path, verb, callback=transform( self._on_obj_ready, callback, parent or self, operation ), ) def get_status(self, operation, params, path='/', parent=None, verb='GET', callback=None): # noqa return self.make_request( operation, params, path, verb, callback=transform( self._on_status_ready, callback, parent or self, operation ), ) def _on_list_ready(self, parent, markers, operation, response): # noqa service_model = self.sqs_connection.meta.service_model if response.status == self.STATUS_CODE_OK: _, parsed = get_response( service_model.operation_model(operation), response.response ) return parsed elif ( response.status in self.STATUS_CODES_TIMEOUT or response.status in self.STATUS_CODES_SERVER_ERRORS ): # When the server returns a timeout or 50X server error, # the response is interpreted as an empty list. # This prevents hanging the Celery worker. return [] else: raise self._for_status(response, response.read()) def _on_obj_ready(self, parent, operation, response): # noqa service_model = self.sqs_connection.meta.service_model if response.status == self.STATUS_CODE_OK: _, parsed = get_response( service_model.operation_model(operation), response.response ) return parsed else: raise self._for_status(response, response.read()) def _on_status_ready(self, parent, operation, response): # noqa service_model = self.sqs_connection.meta.service_model if response.status == self.STATUS_CODE_OK: httpres, _ = get_response( service_model.operation_model(operation), response.response ) return httpres.code else: raise self._for_status(response, response.read()) def _for_status(self, response, body): context = 'Empty body' if not body else 'HTTP Error' return Exception("Request {} HTTP {} {} ({})".format( context, response.status, response.reason, body ))
{ "repo_name": "ZoranPavlovic/kombu", "path": "kombu/asynchronous/aws/connection.py", "copies": "1", "size": "8886", "license": "bsd-3-clause", "hash": -1419252259747600100, "line_mean": 30.5106382979, "line_max": 110, "alpha_frac": 0.5946432591, "autogenerated": false, "ratio": 4.1757518796992485, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 282 }
""" Amazon CD cover source. """ import collections import urllib.parse import lxml.cssselect import lxml.etree from sacad.cover import CoverImageFormat, CoverImageMetadata, CoverSourceQuality, CoverSourceResult from sacad.sources.amazonbase import AmazonBaseCoverSource class AmazonCdCoverSourceResult(CoverSourceResult): """ Amazon CD cover search result. """ def __init__(self, *args, **kwargs): super().__init__(*args, source_quality=CoverSourceQuality.NORMAL, **kwargs) class AmazonCdCoverSource(AmazonBaseCoverSource): """ Cover source returning Amazon.com audio CD images. """ TLDS = ("com", "ca", "cn", "fr", "de", "co.jp", "co.uk") RESULTS_SELECTORS = ( lxml.cssselect.CSSSelector("span.rush-component[data-component-type='s-product-image']"), lxml.cssselect.CSSSelector("#resultsCol li.s-result-item"), ) IMG_SELECTORS = (lxml.cssselect.CSSSelector("img.s-image"), lxml.cssselect.CSSSelector("img.s-access-image")) PRODUCT_LINK_SELECTORS = (lxml.cssselect.CSSSelector("a"), lxml.cssselect.CSSSelector("a.s-access-detail-page")) PRODUCT_PAGE_IMG_SELECTOR = lxml.cssselect.CSSSelector("img#landingImage") def __init__(self, *args, tld="com", **kwargs): assert tld in __class__.TLDS self.base_url = "https://www.amazon.%s/s" % (tld) super().__init__(*args, base_domain=urllib.parse.urlsplit(self.base_url).netloc, **kwargs) def getSearchUrl(self, album, artist): """ See CoverSource.getSearchUrl. """ params = collections.OrderedDict() params["i"] = "popular" params["rh"] = "p_32:%s,p_28:%s" % (artist, album) params["s"] = "relevancerank" return __class__.assembleUrl(self.base_url, params) async def parseResults(self, api_data): """ See CoverSource.parseResults. """ results = [] # parse page parser = lxml.etree.HTMLParser() html = lxml.etree.XML(api_data.decode("utf-8", "ignore"), parser) if self.isBlocked(html): self.logger.warning("Source is sending a captcha") return results for page_struct_version, result_selector in enumerate(__class__.RESULTS_SELECTORS): result_nodes = result_selector(html) if result_nodes: break for rank, result_node in enumerate(result_nodes, 1): try: img_node = __class__.IMG_SELECTORS[page_struct_version](result_node)[0] except IndexError: # no image for that product continue # get thumbnail & full image url thumbnail_url = img_node.get("src") url_parts = thumbnail_url.rsplit(".", 2) img_url = ".".join((url_parts[0], url_parts[2])) # assume size is fixed size = (500, 500) check_metadata = CoverImageMetadata.SIZE # try to get higher res image... if (self.target_size > size[0]) and ( # ...only if needed rank <= 3 ): # and only for first 3 results because this is time # consuming (1 more GET request per result) product_url = __class__.PRODUCT_LINK_SELECTORS[page_struct_version](result_node)[0].get("href") product_url_split = urllib.parse.urlsplit(product_url) if not product_url_split.scheme: # relative redirect url product_url_query = urllib.parse.parse_qsl(product_url_split.query) product_url_query = collections.OrderedDict(product_url_query) try: # needed if page_struct_version == 1 product_url = product_url_query["url"] except KeyError: # page_struct_version == 0, make url absolute product_url = urllib.parse.urljoin(self.base_url, product_url) product_url_split = urllib.parse.urlsplit(product_url) product_url_query = urllib.parse.parse_qsl(product_url_split.query) product_url_query = collections.OrderedDict(product_url_query) try: # remove timestamp from url to improve future cache hit rate del product_url_query["qid"] except KeyError: pass product_url_query = urllib.parse.urlencode(product_url_query) product_url_no_ts = urllib.parse.urlunsplit( product_url_split[:3] + (product_url_query,) + product_url_split[4:] ) store_in_cache_callback, product_page_data = await self.fetchResults(product_url_no_ts) product_page_html = lxml.etree.XML(product_page_data.decode("latin-1"), parser) try: img_node = __class__.PRODUCT_PAGE_IMG_SELECTOR(product_page_html)[0] except IndexError: # unable to get better image pass else: better_img_url = img_node.get("data-old-hires") # img_node.get("data-a-dynamic-image") contains json with image urls too, but they are not larger # than previous 500px image and are often covered by autorip badges (can be removed by cleaning url # though) if better_img_url: img_url = better_img_url size_url_hint = img_url.rsplit(".", 2)[1].strip("_").rsplit("_", 1)[-1] assert size_url_hint.startswith("SL") size_url_hint = int(size_url_hint[2:]) size = (size_url_hint, size_url_hint) check_metadata = CoverImageMetadata.NONE await store_in_cache_callback() # assume format is always jpg format = CoverImageFormat.JPEG # add result results.append( AmazonCdCoverSourceResult( img_url, size, format, thumbnail_url=thumbnail_url, source=self, rank=rank, check_metadata=check_metadata, ) ) return results
{ "repo_name": "desbma/sacad", "path": "sacad/sources/amazoncd.py", "copies": "1", "size": "6412", "license": "mpl-2.0", "hash": -8713921416673725000, "line_mean": 44.475177305, "line_max": 119, "alpha_frac": 0.5564566438, "autogenerated": false, "ratio": 4.185378590078329, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5241835233878329, "avg_score": null, "num_lines": null }
import sys import time import httplib import random from datetime import datetime from logging import debug, info, warning, error try: import xml.etree.ElementTree as ET except ImportError: import elementtree.ElementTree as ET from Config import Config from Exceptions import * from Utils import getTreeFromXml, appendXmlTextNode, getDictFromTree, dateS3toPython, sign_string, getBucketFromHostname, getHostnameFromBucket from S3Uri import S3Uri, S3UriS3 from FileLists import fetch_remote_list cloudfront_api_version = "2010-11-01" cloudfront_resource = "/%(api_ver)s/distribution" % { 'api_ver' : cloudfront_api_version } def output(message): sys.stdout.write(message + "\n") def pretty_output(label, message): #label = ("%s " % label).ljust(20, ".") label = ("%s:" % label).ljust(15) output("%s %s" % (label, message)) class DistributionSummary(object): ## Example: ## ## <DistributionSummary> ## <Id>1234567890ABC</Id> ## <Status>Deployed</Status> ## <LastModifiedTime>2009-01-16T11:49:02.189Z</LastModifiedTime> ## <DomainName>blahblahblah.cloudfront.net</DomainName> ## <S3Origin> ## <DNSName>example.bucket.s3.amazonaws.com</DNSName> ## </S3Origin> ## <CNAME>cdn.example.com</CNAME> ## <CNAME>img.example.com</CNAME> ## <Comment>What Ever</Comment> ## <Enabled>true</Enabled> ## </DistributionSummary> def __init__(self, tree): if tree.tag != "DistributionSummary": raise ValueError("Expected <DistributionSummary /> xml, got: <%s />" % tree.tag) self.parse(tree) def parse(self, tree): self.info = getDictFromTree(tree) self.info['Enabled'] = (self.info['Enabled'].lower() == "true") if self.info.has_key("CNAME") and type(self.info['CNAME']) != list: self.info['CNAME'] = [self.info['CNAME']] def uri(self): return S3Uri("cf://%s" % self.info['Id']) class DistributionList(object): ## Example: ## ## <DistributionList xmlns="http://cloudfront.amazonaws.com/doc/2010-07-15/"> ## <Marker /> ## <MaxItems>100</MaxItems> ## <IsTruncated>false</IsTruncated> ## <DistributionSummary> ## ... handled by DistributionSummary() class ... ## </DistributionSummary> ## </DistributionList> def __init__(self, xml): tree = getTreeFromXml(xml) if tree.tag != "DistributionList": raise ValueError("Expected <DistributionList /> xml, got: <%s />" % tree.tag) self.parse(tree) def parse(self, tree): self.info = getDictFromTree(tree) ## Normalise some items self.info['IsTruncated'] = (self.info['IsTruncated'].lower() == "true") self.dist_summs = [] for dist_summ in tree.findall(".//DistributionSummary"): self.dist_summs.append(DistributionSummary(dist_summ)) class Distribution(object): ## Example: ## ## <Distribution xmlns="http://cloudfront.amazonaws.com/doc/2010-07-15/"> ## <Id>1234567890ABC</Id> ## <Status>InProgress</Status> ## <LastModifiedTime>2009-01-16T13:07:11.319Z</LastModifiedTime> ## <DomainName>blahblahblah.cloudfront.net</DomainName> ## <DistributionConfig> ## ... handled by DistributionConfig() class ... ## </DistributionConfig> ## </Distribution> def __init__(self, xml): tree = getTreeFromXml(xml) if tree.tag != "Distribution": raise ValueError("Expected <Distribution /> xml, got: <%s />" % tree.tag) self.parse(tree) def parse(self, tree): self.info = getDictFromTree(tree) ## Normalise some items self.info['LastModifiedTime'] = dateS3toPython(self.info['LastModifiedTime']) self.info['DistributionConfig'] = DistributionConfig(tree = tree.find(".//DistributionConfig")) def uri(self): return S3Uri("cf://%s" % self.info['Id']) class DistributionConfig(object): ## Example: ## ## <DistributionConfig> ## <Origin>somebucket.s3.amazonaws.com</Origin> ## <CallerReference>s3://somebucket/</CallerReference> ## <Comment>http://somebucket.s3.amazonaws.com/</Comment> ## <Enabled>true</Enabled> ## <Logging> ## <Bucket>bu.ck.et</Bucket> ## <Prefix>/cf-somebucket/</Prefix> ## </Logging> ## </DistributionConfig> EMPTY_CONFIG = "<DistributionConfig><S3Origin><DNSName/></S3Origin><CallerReference/><Enabled>true</Enabled></DistributionConfig>" xmlns = "http://cloudfront.amazonaws.com/doc/%(api_ver)s/" % { 'api_ver' : cloudfront_api_version } def __init__(self, xml = None, tree = None): if xml is None: xml = DistributionConfig.EMPTY_CONFIG if tree is None: tree = getTreeFromXml(xml) if tree.tag != "DistributionConfig": raise ValueError("Expected <DistributionConfig /> xml, got: <%s />" % tree.tag) self.parse(tree) def parse(self, tree): self.info = getDictFromTree(tree) self.info['Enabled'] = (self.info['Enabled'].lower() == "true") if not self.info.has_key("CNAME"): self.info['CNAME'] = [] if type(self.info['CNAME']) != list: self.info['CNAME'] = [self.info['CNAME']] self.info['CNAME'] = [cname.lower() for cname in self.info['CNAME']] if not self.info.has_key("Comment"): self.info['Comment'] = "" if not self.info.has_key("DefaultRootObject"): self.info['DefaultRootObject'] = "" ## Figure out logging - complex node not parsed by getDictFromTree() logging_nodes = tree.findall(".//Logging") if logging_nodes: logging_dict = getDictFromTree(logging_nodes[0]) logging_dict['Bucket'], success = getBucketFromHostname(logging_dict['Bucket']) if not success: warning("Logging to unparsable bucket name: %s" % logging_dict['Bucket']) self.info['Logging'] = S3UriS3("s3://%(Bucket)s/%(Prefix)s" % logging_dict) else: self.info['Logging'] = None def __str__(self): tree = ET.Element("DistributionConfig") tree.attrib['xmlns'] = DistributionConfig.xmlns ## Retain the order of the following calls! s3org = appendXmlTextNode("S3Origin", '', tree) appendXmlTextNode("DNSName", self.info['S3Origin']['DNSName'], s3org) appendXmlTextNode("CallerReference", self.info['CallerReference'], tree) for cname in self.info['CNAME']: appendXmlTextNode("CNAME", cname.lower(), tree) if self.info['Comment']: appendXmlTextNode("Comment", self.info['Comment'], tree) appendXmlTextNode("Enabled", str(self.info['Enabled']).lower(), tree) # don't create a empty DefaultRootObject element as it would result in a MalformedXML error if str(self.info['DefaultRootObject']): appendXmlTextNode("DefaultRootObject", str(self.info['DefaultRootObject']), tree) if self.info['Logging']: logging_el = ET.Element("Logging") appendXmlTextNode("Bucket", getHostnameFromBucket(self.info['Logging'].bucket()), logging_el) appendXmlTextNode("Prefix", self.info['Logging'].object(), logging_el) tree.append(logging_el) return ET.tostring(tree) class Invalidation(object): ## Example: ## ## <Invalidation xmlns="http://cloudfront.amazonaws.com/doc/2010-11-01/"> ## <Id>id</Id> ## <Status>status</Status> ## <CreateTime>date</CreateTime> ## <InvalidationBatch> ## <Path>/image1.jpg</Path> ## <Path>/image2.jpg</Path> ## <Path>/videos/movie.flv</Path> ## <CallerReference>my-batch</CallerReference> ## </InvalidationBatch> ## </Invalidation> def __init__(self, xml): tree = getTreeFromXml(xml) if tree.tag != "Invalidation": raise ValueError("Expected <Invalidation /> xml, got: <%s />" % tree.tag) self.parse(tree) def parse(self, tree): self.info = getDictFromTree(tree) def __str__(self): return str(self.info) class InvalidationList(object): ## Example: ## ## <InvalidationList> ## <Marker/> ## <NextMarker>Invalidation ID</NextMarker> ## <MaxItems>2</MaxItems> ## <IsTruncated>true</IsTruncated> ## <InvalidationSummary> ## <Id>[Second Invalidation ID]</Id> ## <Status>Completed</Status> ## </InvalidationSummary> ## <InvalidationSummary> ## <Id>[First Invalidation ID]</Id> ## <Status>Completed</Status> ## </InvalidationSummary> ## </InvalidationList> def __init__(self, xml): tree = getTreeFromXml(xml) if tree.tag != "InvalidationList": raise ValueError("Expected <InvalidationList /> xml, got: <%s />" % tree.tag) self.parse(tree) def parse(self, tree): self.info = getDictFromTree(tree) def __str__(self): return str(self.info) class InvalidationBatch(object): ## Example: ## ## <InvalidationBatch> ## <Path>/image1.jpg</Path> ## <Path>/image2.jpg</Path> ## <Path>/videos/movie.flv</Path> ## <Path>/sound%20track.mp3</Path> ## <CallerReference>my-batch</CallerReference> ## </InvalidationBatch> def __init__(self, reference = None, distribution = None, paths = []): if reference: self.reference = reference else: if not distribution: distribution="0" self.reference = "%s.%s.%s" % (distribution, datetime.strftime(datetime.now(),"%Y%m%d%H%M%S"), random.randint(1000,9999)) self.paths = [] self.add_objects(paths) def add_objects(self, paths): self.paths.extend(paths) def get_reference(self): return self.reference def __str__(self): tree = ET.Element("InvalidationBatch") for path in self.paths: if len(path) < 1 or path[0] != "/": path = "/" + path appendXmlTextNode("Path", path, tree) appendXmlTextNode("CallerReference", self.reference, tree) return ET.tostring(tree) class CloudFront(object): operations = { "CreateDist" : { 'method' : "POST", 'resource' : "" }, "DeleteDist" : { 'method' : "DELETE", 'resource' : "/%(dist_id)s" }, "GetList" : { 'method' : "GET", 'resource' : "" }, "GetDistInfo" : { 'method' : "GET", 'resource' : "/%(dist_id)s" }, "GetDistConfig" : { 'method' : "GET", 'resource' : "/%(dist_id)s/config" }, "SetDistConfig" : { 'method' : "PUT", 'resource' : "/%(dist_id)s/config" }, "Invalidate" : { 'method' : "POST", 'resource' : "/%(dist_id)s/invalidation" }, "GetInvalList" : { 'method' : "GET", 'resource' : "/%(dist_id)s/invalidation" }, "GetInvalInfo" : { 'method' : "GET", 'resource' : "/%(dist_id)s/invalidation/%(request_id)s" }, } ## Maximum attempts of re-issuing failed requests _max_retries = 5 dist_list = None def __init__(self, config): self.config = config ## -------------------------------------------------- ## Methods implementing CloudFront API ## -------------------------------------------------- def GetList(self): response = self.send_request("GetList") response['dist_list'] = DistributionList(response['data']) if response['dist_list'].info['IsTruncated']: raise NotImplementedError("List is truncated. Ask s3cmd author to add support.") ## TODO: handle Truncated return response def CreateDistribution(self, uri, cnames_add = [], comment = None, logging = None, default_root_object = None): dist_config = DistributionConfig() dist_config.info['Enabled'] = True dist_config.info['S3Origin']['DNSName'] = uri.host_name() dist_config.info['CallerReference'] = str(uri) dist_config.info['DefaultRootObject'] = default_root_object if comment == None: dist_config.info['Comment'] = uri.public_url() else: dist_config.info['Comment'] = comment for cname in cnames_add: if dist_config.info['CNAME'].count(cname) == 0: dist_config.info['CNAME'].append(cname) if logging: dist_config.info['Logging'] = S3UriS3(logging) request_body = str(dist_config) debug("CreateDistribution(): request_body: %s" % request_body) response = self.send_request("CreateDist", body = request_body) response['distribution'] = Distribution(response['data']) return response def ModifyDistribution(self, cfuri, cnames_add = [], cnames_remove = [], comment = None, enabled = None, logging = None, default_root_object = None): if cfuri.type != "cf": raise ValueError("Expected CFUri instead of: %s" % cfuri) # Get current dist status (enabled/disabled) and Etag info("Checking current status of %s" % cfuri) response = self.GetDistConfig(cfuri) dc = response['dist_config'] if enabled != None: dc.info['Enabled'] = enabled if comment != None: dc.info['Comment'] = comment if default_root_object != None: dc.info['DefaultRootObject'] = default_root_object for cname in cnames_add: if dc.info['CNAME'].count(cname) == 0: dc.info['CNAME'].append(cname) for cname in cnames_remove: while dc.info['CNAME'].count(cname) > 0: dc.info['CNAME'].remove(cname) if logging != None: if logging == False: dc.info['Logging'] = False else: dc.info['Logging'] = S3UriS3(logging) response = self.SetDistConfig(cfuri, dc, response['headers']['etag']) return response def DeleteDistribution(self, cfuri): if cfuri.type != "cf": raise ValueError("Expected CFUri instead of: %s" % cfuri) # Get current dist status (enabled/disabled) and Etag info("Checking current status of %s" % cfuri) response = self.GetDistConfig(cfuri) if response['dist_config'].info['Enabled']: info("Distribution is ENABLED. Disabling first.") response['dist_config'].info['Enabled'] = False response = self.SetDistConfig(cfuri, response['dist_config'], response['headers']['etag']) warning("Waiting for Distribution to become disabled.") warning("This may take several minutes, please wait.") while True: response = self.GetDistInfo(cfuri) d = response['distribution'] if d.info['Status'] == "Deployed" and d.info['Enabled'] == False: info("Distribution is now disabled") break warning("Still waiting...") time.sleep(10) headers = {} headers['if-match'] = response['headers']['etag'] response = self.send_request("DeleteDist", dist_id = cfuri.dist_id(), headers = headers) return response def GetDistInfo(self, cfuri): if cfuri.type != "cf": raise ValueError("Expected CFUri instead of: %s" % cfuri) response = self.send_request("GetDistInfo", dist_id = cfuri.dist_id()) response['distribution'] = Distribution(response['data']) return response def GetDistConfig(self, cfuri): if cfuri.type != "cf": raise ValueError("Expected CFUri instead of: %s" % cfuri) response = self.send_request("GetDistConfig", dist_id = cfuri.dist_id()) response['dist_config'] = DistributionConfig(response['data']) return response def SetDistConfig(self, cfuri, dist_config, etag = None): if etag == None: debug("SetDistConfig(): Etag not set. Fetching it first.") etag = self.GetDistConfig(cfuri)['headers']['etag'] debug("SetDistConfig(): Etag = %s" % etag) request_body = str(dist_config) debug("SetDistConfig(): request_body: %s" % request_body) headers = {} headers['if-match'] = etag response = self.send_request("SetDistConfig", dist_id = cfuri.dist_id(), body = request_body, headers = headers) return response def InvalidateObjects(self, uri, paths, default_index_file, invalidate_default_index_on_cf, invalidate_default_index_root_on_cf): # joseprio: if the user doesn't want to invalidate the default index # path, or if the user wants to invalidate the root of the default # index, we need to process those paths if default_index_file is not None and (not invalidate_default_index_on_cf or invalidate_default_index_root_on_cf): new_paths = [] default_index_suffix = '/' + default_index_file for path in paths: if path.endswith(default_index_suffix) or path == default_index_file: if invalidate_default_index_on_cf: new_paths.append(path) if invalidate_default_index_root_on_cf: new_paths.append(path[:-len(default_index_file)]) else: new_paths.append(path) paths = new_paths # uri could be either cf:// or s3:// uri cfuri = self.get_dist_name_for_bucket(uri) if len(paths) > 999: try: tmp_filename = Utils.mktmpfile() f = open(tmp_filename, "w") f.write("\n".join(paths)+"\n") f.close() warning("Request to invalidate %d paths (max 999 supported)" % len(paths)) warning("All the paths are now saved in: %s" % tmp_filename) except: pass raise ParameterError("Too many paths to invalidate") invalbatch = InvalidationBatch(distribution = cfuri.dist_id(), paths = paths) debug("InvalidateObjects(): request_body: %s" % invalbatch) response = self.send_request("Invalidate", dist_id = cfuri.dist_id(), body = str(invalbatch)) response['dist_id'] = cfuri.dist_id() if response['status'] == 201: inval_info = Invalidation(response['data']).info response['request_id'] = inval_info['Id'] debug("InvalidateObjects(): response: %s" % response) return response def GetInvalList(self, cfuri): if cfuri.type != "cf": raise ValueError("Expected CFUri instead of: %s" % cfuri) response = self.send_request("GetInvalList", dist_id = cfuri.dist_id()) response['inval_list'] = InvalidationList(response['data']) return response def GetInvalInfo(self, cfuri): if cfuri.type != "cf": raise ValueError("Expected CFUri instead of: %s" % cfuri) if cfuri.request_id() is None: raise ValueError("Expected CFUri with Request ID") response = self.send_request("GetInvalInfo", dist_id = cfuri.dist_id(), request_id = cfuri.request_id()) response['inval_status'] = Invalidation(response['data']) return response ## -------------------------------------------------- ## Low-level methods for handling CloudFront requests ## -------------------------------------------------- def send_request(self, op_name, dist_id = None, request_id = None, body = None, headers = {}, retries = _max_retries): operation = self.operations[op_name] if body: headers['content-type'] = 'text/plain' request = self.create_request(operation, dist_id, request_id, headers) conn = self.get_connection() debug("send_request(): %s %s" % (request['method'], request['resource'])) conn.request(request['method'], request['resource'], body, request['headers']) http_response = conn.getresponse() response = {} response["status"] = http_response.status response["reason"] = http_response.reason response["headers"] = dict(http_response.getheaders()) response["data"] = http_response.read() conn.close() debug("CloudFront: response: %r" % response) if response["status"] >= 500: e = CloudFrontError(response) if retries: warning(u"Retrying failed request: %s" % op_name) warning(unicode(e)) warning("Waiting %d sec..." % self._fail_wait(retries)) time.sleep(self._fail_wait(retries)) return self.send_request(op_name, dist_id, body, retries = retries - 1) else: raise e if response["status"] < 200 or response["status"] > 299: raise CloudFrontError(response) return response def create_request(self, operation, dist_id = None, request_id = None, headers = None): resource = cloudfront_resource + ( operation['resource'] % { 'dist_id' : dist_id, 'request_id' : request_id }) if not headers: headers = {} if headers.has_key("date"): if not headers.has_key("x-amz-date"): headers["x-amz-date"] = headers["date"] del(headers["date"]) if not headers.has_key("x-amz-date"): headers["x-amz-date"] = time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime()) if len(self.config.security_token)>0: self.config.role_refresh() headers['x-amz-security-token']=self.config.security_token signature = self.sign_request(headers) headers["Authorization"] = "AWS "+self.config.access_key+":"+signature request = {} request['resource'] = resource request['headers'] = headers request['method'] = operation['method'] return request def sign_request(self, headers): string_to_sign = headers['x-amz-date'] signature = sign_string(string_to_sign) debug(u"CloudFront.sign_request('%s') = %s" % (string_to_sign, signature)) return signature def get_connection(self): if self.config.proxy_host != "": raise ParameterError("CloudFront commands don't work from behind a HTTP proxy") return httplib.HTTPSConnection(self.config.cloudfront_host) def _fail_wait(self, retries): # Wait a few seconds. The more it fails the more we wait. return (self._max_retries - retries + 1) * 3 def get_dist_name_for_bucket(self, uri): if (uri.type == "cf"): return uri if (uri.type != "s3"): raise ParameterError("CloudFront or S3 URI required instead of: %s" % uri) debug("_get_dist_name_for_bucket(%r)" % uri) if CloudFront.dist_list is None: response = self.GetList() CloudFront.dist_list = {} for d in response['dist_list'].dist_summs: if d.info.has_key("S3Origin"): CloudFront.dist_list[getBucketFromHostname(d.info['S3Origin']['DNSName'])[0]] = d.uri() elif d.info.has_key("CustomOrigin"): # Aral: This used to skip over distributions with CustomOrigin, however, we mustn't # do this since S3 buckets that are set up as websites use custom origins. # Thankfully, the custom origin URLs they use start with the URL of the # S3 bucket. Here, we make use this naming convention to support this use case. distListIndex = getBucketFromHostname(d.info['CustomOrigin']['DNSName'])[0]; distListIndex = distListIndex[:len(uri.bucket())] CloudFront.dist_list[distListIndex] = d.uri() else: # Aral: I'm not sure when this condition will be reached, but keeping it in there. continue debug("dist_list: %s" % CloudFront.dist_list) try: return CloudFront.dist_list[uri.bucket()] except Exception, e: debug(e) raise ParameterError("Unable to translate S3 URI to CloudFront distribution name: %s" % uri) class Cmd(object): """ Class that implements CloudFront commands """ class Options(object): cf_cnames_add = [] cf_cnames_remove = [] cf_comment = None cf_enable = None cf_logging = None cf_default_root_object = None def option_list(self): return [opt for opt in dir(self) if opt.startswith("cf_")] def update_option(self, option, value): setattr(Cmd.options, option, value) options = Options() @staticmethod def _parse_args(args): cf = CloudFront(Config()) cfuris = [] for arg in args: uri = cf.get_dist_name_for_bucket(S3Uri(arg)) cfuris.append(uri) return cfuris @staticmethod def info(args): cf = CloudFront(Config()) if not args: response = cf.GetList() for d in response['dist_list'].dist_summs: if d.info.has_key("S3Origin"): origin = S3UriS3.httpurl_to_s3uri(d.info['S3Origin']['DNSName']) elif d.info.has_key("CustomOrigin"): origin = "http://%s/" % d.info['CustomOrigin']['DNSName'] else: origin = "<unknown>" pretty_output("Origin", origin) pretty_output("DistId", d.uri()) pretty_output("DomainName", d.info['DomainName']) if d.info.has_key("CNAME"): pretty_output("CNAMEs", ", ".join(d.info['CNAME'])) pretty_output("Status", d.info['Status']) pretty_output("Enabled", d.info['Enabled']) output("") else: cfuris = Cmd._parse_args(args) for cfuri in cfuris: response = cf.GetDistInfo(cfuri) d = response['distribution'] dc = d.info['DistributionConfig'] if dc.info.has_key("S3Origin"): origin = S3UriS3.httpurl_to_s3uri(dc.info['S3Origin']['DNSName']) elif dc.info.has_key("CustomOrigin"): origin = "http://%s/" % dc.info['CustomOrigin']['DNSName'] else: origin = "<unknown>" pretty_output("Origin", origin) pretty_output("DistId", d.uri()) pretty_output("DomainName", d.info['DomainName']) if dc.info.has_key("CNAME"): pretty_output("CNAMEs", ", ".join(dc.info['CNAME'])) pretty_output("Status", d.info['Status']) pretty_output("Comment", dc.info['Comment']) pretty_output("Enabled", dc.info['Enabled']) pretty_output("DfltRootObject", dc.info['DefaultRootObject']) pretty_output("Logging", dc.info['Logging'] or "Disabled") pretty_output("Etag", response['headers']['etag']) @staticmethod def create(args): cf = CloudFront(Config()) buckets = [] for arg in args: uri = S3Uri(arg) if uri.type != "s3": raise ParameterError("Distribution can only be created from a s3:// URI instead of: %s" % arg) if uri.object(): raise ParameterError("Use s3:// URI with a bucket name only instead of: %s" % arg) if not uri.is_dns_compatible(): raise ParameterError("CloudFront can only handle lowercase-named buckets.") buckets.append(uri) if not buckets: raise ParameterError("No valid bucket names found") for uri in buckets: info("Creating distribution from: %s" % uri) response = cf.CreateDistribution(uri, cnames_add = Cmd.options.cf_cnames_add, comment = Cmd.options.cf_comment, logging = Cmd.options.cf_logging, default_root_object = Cmd.options.cf_default_root_object) d = response['distribution'] dc = d.info['DistributionConfig'] output("Distribution created:") pretty_output("Origin", S3UriS3.httpurl_to_s3uri(dc.info['S3Origin']['DNSName'])) pretty_output("DistId", d.uri()) pretty_output("DomainName", d.info['DomainName']) pretty_output("CNAMEs", ", ".join(dc.info['CNAME'])) pretty_output("Comment", dc.info['Comment']) pretty_output("Status", d.info['Status']) pretty_output("Enabled", dc.info['Enabled']) pretty_output("DefaultRootObject", dc.info['DefaultRootObject']) pretty_output("Etag", response['headers']['etag']) @staticmethod def delete(args): cf = CloudFront(Config()) cfuris = Cmd._parse_args(args) for cfuri in cfuris: response = cf.DeleteDistribution(cfuri) if response['status'] >= 400: error("Distribution %s could not be deleted: %s" % (cfuri, response['reason'])) output("Distribution %s deleted" % cfuri) @staticmethod def modify(args): cf = CloudFront(Config()) if len(args) > 1: raise ParameterError("Too many parameters. Modify one Distribution at a time.") try: cfuri = Cmd._parse_args(args)[0] except IndexError, e: raise ParameterError("No valid Distribution URI found.") response = cf.ModifyDistribution(cfuri, cnames_add = Cmd.options.cf_cnames_add, cnames_remove = Cmd.options.cf_cnames_remove, comment = Cmd.options.cf_comment, enabled = Cmd.options.cf_enable, logging = Cmd.options.cf_logging, default_root_object = Cmd.options.cf_default_root_object) if response['status'] >= 400: error("Distribution %s could not be modified: %s" % (cfuri, response['reason'])) output("Distribution modified: %s" % cfuri) response = cf.GetDistInfo(cfuri) d = response['distribution'] dc = d.info['DistributionConfig'] pretty_output("Origin", S3UriS3.httpurl_to_s3uri(dc.info['S3Origin']['DNSName'])) pretty_output("DistId", d.uri()) pretty_output("DomainName", d.info['DomainName']) pretty_output("Status", d.info['Status']) pretty_output("CNAMEs", ", ".join(dc.info['CNAME'])) pretty_output("Comment", dc.info['Comment']) pretty_output("Enabled", dc.info['Enabled']) pretty_output("DefaultRootObject", dc.info['DefaultRootObject']) pretty_output("Etag", response['headers']['etag']) @staticmethod def invalinfo(args): cf = CloudFront(Config()) cfuris = Cmd._parse_args(args) requests = [] for cfuri in cfuris: if cfuri.request_id(): requests.append(str(cfuri)) else: inval_list = cf.GetInvalList(cfuri) try: for i in inval_list['inval_list'].info['InvalidationSummary']: requests.append("/".join(["cf:/", cfuri.dist_id(), i["Id"]])) except: continue for req in requests: cfuri = S3Uri(req) inval_info = cf.GetInvalInfo(cfuri) st = inval_info['inval_status'].info pretty_output("URI", str(cfuri)) pretty_output("Status", st['Status']) pretty_output("Created", st['CreateTime']) pretty_output("Nr of paths", len(st['InvalidationBatch']['Path'])) pretty_output("Reference", st['InvalidationBatch']['CallerReference']) output("") # vim:et:ts=4:sts=4:ai
{ "repo_name": "sharethis-github/OpenSource", "path": "s3cmd/S3/CloudFront.py", "copies": "1", "size": "32703", "license": "apache-2.0", "hash": -5924886026421761000, "line_mean": 41.3065976714, "line_max": 143, "alpha_frac": 0.5661560102, "autogenerated": false, "ratio": 3.962078992003877, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5028235002203877, "avg_score": null, "num_lines": null }
""" Amazon digital cover source. """ import collections import operator import urllib.parse import lxml.cssselect import lxml.etree from sacad.cover import CoverImageFormat, CoverImageMetadata, CoverSourceQuality, CoverSourceResult from sacad.sources.amazonbase import AmazonBaseCoverSource AmazonDigitalImageFormat = collections.namedtuple("AmazonDigitalImageFormat", ("id", "slice_count", "total_res")) AMAZON_DIGITAL_IMAGE_FORMATS = [ AmazonDigitalImageFormat( 0, 1, 600 ), # http://z2-ec2.images-amazon.com/R/1/a=B00BJ93R7O+c=A17SFUTIVB227Z+d=_SCR(0,0,0)_=.jpg AmazonDigitalImageFormat( 1, 2, 700 ), # http://z2-ec2.images-amazon.com/R/1/a=B00BJ93R7O+c=A17SFUTIVB227Z+d=_SCR(1,1,1)_=.jpg AmazonDigitalImageFormat( 1, 4, 1280 ), # http://z2-ec2.images-amazon.com/R/1/a=B01NBTSVDN+c=A17SFUTIVB227Z+d=_SCR(1,3,3)_=.jpg AmazonDigitalImageFormat( 2, 3, 1025 ), # http://z2-ec2.images-amazon.com/R/1/a=B00BJ93R7O+c=A17SFUTIVB227Z+d=_SCR(2,2,2)_=.jpg AmazonDigitalImageFormat( 2, 5, 1920 ), # http://z2-ec2.images-amazon.com/R/1/a=B01NBTSVDN+c=A17SFUTIVB227Z+d=_SCR(2,4,4)_=.jpg AmazonDigitalImageFormat( 3, 4, 1500 ), # http://z2-ec2.images-amazon.com/R/1/a=B00BJ93R7O+c=A17SFUTIVB227Z+d=_SCR(3,3,3)_=.jpg AmazonDigitalImageFormat(3, 7, 2560), ] # http://z2-ec2.images-amazon.com/R/1/a=B01NBTSVDN+c=A17SFUTIVB227Z+d=_SCR(3,6,6)_=.jpg AMAZON_DIGITAL_IMAGE_FORMATS.sort(key=operator.attrgetter("total_res"), reverse=True) class AmazonDigitalCoverSourceResult(CoverSourceResult): """ Amazon digital cover search result. """ def __init__(self, *args, **kwargs): super().__init__(*args, source_quality=CoverSourceQuality.NORMAL, **kwargs) class AmazonDigitalCoverSource(AmazonBaseCoverSource): """ Cover source returning Amazon.com digital music images. """ BASE_URL = "https://www.amazon.com" DYNAPI_KEY = "A17SFUTIVB227Z" RESULTS_SELECTORS = ( lxml.cssselect.CSSSelector("span.rush-component[data-component-type='s-product-image']"), lxml.cssselect.CSSSelector("div#dm_mp3Player li.s-mp3-federated-bar-item"), ) IMG_SELECTORS = (lxml.cssselect.CSSSelector("img.s-image"), lxml.cssselect.CSSSelector("img.s-access-image")) LINK_SELECTOR = lxml.cssselect.CSSSelector("a") def __init__(self, *args, **kwargs): super().__init__(*args, base_domain=urllib.parse.urlsplit(__class__.BASE_URL).netloc, **kwargs) def getSearchUrl(self, album, artist): """ See CoverSource.getSearchUrl. """ url = "%s/s" % (__class__.BASE_URL) params = collections.OrderedDict() params["k"] = " ".join((artist, album)) params["i"] = "digital-music" params["s"] = "relevancerank" return __class__.assembleUrl(url, params) async def parseResults(self, api_data): """ See CoverSource.parseResults. """ results = [] # parse page parser = lxml.etree.HTMLParser() html = lxml.etree.XML(api_data.decode("utf-8"), parser) if self.isBlocked(html): self.logger.warning("Source is sending a captcha") return results for page_struct_version, result_selector in enumerate(__class__.RESULTS_SELECTORS): result_nodes = result_selector(html) if result_nodes: break for rank, result_node in enumerate(result_nodes, 1): # get thumbnail & full image url img_node = __class__.IMG_SELECTORS[page_struct_version](result_node)[0] thumbnail_url = img_node.get("src") thumbnail_url = thumbnail_url.replace("Stripe-Prime-Only", "") url_parts = thumbnail_url.rsplit(".", 2) img_url = ".".join((url_parts[0], url_parts[2])) # assume size is fixed size = (500, 500) # try to get higher res image... if self.target_size > size[0]: # ...but only if needed self.logger.debug("Looking for optimal subimages configuration...") product_url = __class__.LINK_SELECTOR(result_node)[0].get("href") product_url = urllib.parse.urlsplit(product_url) product_id = product_url.path.split("/")[3] # TODO don't pick up highest res image if user asked less? for amazon_img_format in AMAZON_DIGITAL_IMAGE_FORMATS: # TODO review this, it seem to always fail now self.logger.debug("Trying %u subimages..." % (amazon_img_format.slice_count ** 2)) urls = tuple( self.generateImgUrls( product_id, __class__.DYNAPI_KEY, amazon_img_format.id, amazon_img_format.slice_count ) ) url_ok = await self.probeUrl(urls[-1]) if not url_ok: # images at this size are not available continue # images at this size are available img_url = urls size = (amazon_img_format.total_res,) * 2 break # assume format is always jpg format = CoverImageFormat.JPEG # add result results.append( AmazonDigitalCoverSourceResult( img_url, size, format, thumbnail_url=thumbnail_url, source=self, rank=rank, check_metadata=CoverImageMetadata.SIZE, ) ) return results def generateImgUrls(self, product_id, dynapi_key, format_id, slice_count): """ Generate URLs for slice_count^2 subimages of a product. """ for x in range(slice_count): for y in range(slice_count): yield ( "http://z2-ec2.images-amazon.com/R/1/a=" + product_id + "+c=" + dynapi_key + "+d=_SCR%28" + str(format_id) + "," + str(x) + "," + str(y) + "%29_=.jpg" )
{ "repo_name": "desbma/sacad", "path": "sacad/sources/amazondigital.py", "copies": "1", "size": "6368", "license": "mpl-2.0", "hash": -8256985584239818000, "line_mean": 39.3037974684, "line_max": 113, "alpha_frac": 0.5643844221, "autogenerated": false, "ratio": 3.5735129068462403, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.463789732894624, "avg_score": null, "num_lines": null }
""" AmazonDriver for Network based on BaseDriver """ import boto3 from calplus.v1.network.drivers.base import BaseDriver, BaseQuota PROVIDER = "AMAZON" class AmazonDriver(BaseDriver): """docstring for AmazonDriver""" def __init__(self, cloud_config): super(AmazonDriver, self).__init__() self.aws_access_key_id = cloud_config['aws_access_key_id'] self.aws_secret_access_key = cloud_config['aws_secret_access_key'] self.endpoint_url = cloud_config['endpoint_url'] self.region_name = cloud_config.get('region_name', None) self.driver_name = \ cloud_config.get('driver_name', 'default') self.limit = cloud_config.get('limit', None) self._setup() def _setup(self): self.client = boto3.client( 'ec2', aws_access_key_id=self.aws_access_key_id, aws_secret_access_key=self.aws_secret_access_key, region_name=self.region_name, endpoint_url=self.endpoint_url ) self.quota = None def create(self, name, cidr, **kargs): # step1: create vpc vpc = self.client.create_vpc( CidrBlock=cidr, InstanceTenancy='default' ).get('Vpc') # step 2: create subnet subnet = self.client.create_subnet( VpcId=vpc.get('VpcId'), CidrBlock=cidr ).get('Subnet') result = {'name': subnet['SubnetId'], 'description': None, 'id': subnet['SubnetId'], 'cidr': subnet['CidrBlock'], 'cloud': PROVIDER, 'gateway_ip': None, 'security_group': None, 'allocation_pools': None, 'dns_nameservers': None } return result def show(self, subnet_id): subnet = self.client.describe_subnets( SubnetIds=[subnet_id]).get('Subnets')[0] result = {'name': subnet['SubnetId'], 'description': None, 'id': subnet['SubnetId'], 'cidr': subnet['CidrBlock'], 'cloud': PROVIDER, 'gateway_ip': None, 'security_group': None, 'allocation_pools': None, 'dns_nameservers': None } return result def list(self, **search_opts): subnets = self.client.describe_subnets(**search_opts).get('Subnets') result = [] for subnet in subnets: sub = {'name': subnet['SubnetId'], 'description': None, 'id': subnet['SubnetId'], 'cidr': subnet['CidrBlock'], 'cloud': PROVIDER, 'gateway_ip': None, 'security_group': None, 'allocation_pools': None, 'dns_nameservers': None } result.append(sub) return result def update(self, subnet_id, subnet): pass def delete(self, subnet_id): """ This is bad delete function because one vpc can have more than one subnet. It is Ok if user only use CAL for manage cloud resource We will update ASAP. """ # 1 : show subnet subnet = self.client.describe_subnets( SubnetIds=[subnet_id]).get('Subnets')[0] vpc_id = subnet.get('VpcId') # 2 : delete subnet self.client.delete_subnet(SubnetId=subnet_id) # 3 : delete vpc return self.client.delete_vpc(VpcId=vpc_id) def connect_external_net(self, network_id): pass def disconnect_external_net(self, network_id): pass def allocate_public_ip(self): self.client.allocate_address(Domain='vpc') return True def list_public_ip(self, **search_opts): """ :param search_opts: :return: list PublicIP """ result = self.client.describe_addresses(**search_opts) ips = result.get('Addresses') return_format = [] for ip in ips: return_format.append({ 'public_ip': ip.get('PublicIp'), 'id': ip.get('AllocationId') }) return return_format def release_public_ip(self, public_ip_id): self.client.release_address(AllocationId=public_ip_id) return True class AmazonQuota(BaseQuota): """docstring for AmazonQuota""" def __init__(self, client, limit=None): super(AmazonQuota, self).__init__() self.client = client self.limit = limit self._setup() def _setup(self): if self.limit is None: self.limit = None def get_networks(self): pass def get_security_groups(self): pass def get_floating_ips(self): pass def get_routers(self): pass def get_internet_gateways(self): pass
{ "repo_name": "cloudcomputinghust/CAL", "path": "calplus/v1/network/drivers/amazon.py", "copies": "1", "size": "5007", "license": "apache-2.0", "hash": 1859905737522317000, "line_mean": 27.2881355932, "line_max": 76, "alpha_frac": 0.527062113, "autogenerated": false, "ratio": 4.151741293532338, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5178803406532339, "avg_score": null, "num_lines": null }
"""amazon module is a jungle containing different plants and creatures, for instance the boa which is a reptile like the turtle, however it may not moved around freely and can be constricted, hence boa constrictor""" import turtle from random import shuffle, randrange from math import radians, cos, sin def even(number): """:param number: to be checked :return: Bool - True if number is even, False otherwise (return number % 2 == 0)""" return number % 2 == 0 def conv(value, fromLow=0, fromHigh=0, toLow=0, toHigh=0, func=None): """Re-maps a number from one range to another. That is, a value of fromLow would get mapped to toLow, a value of fromHigh to toHigh, values in-between to values in-between, etc. Does not constrain values to within the range, because out-of-range values are sometimes intended and useful. The constrain() function may be used either before or after this function, if limits to the ranges are desired. Note that the "lower bounds" of either range may be larger or smaller than the "upper bounds" so the conv() function may be used to reverse a range of numbers, for example y = conv(x, 1, 50, 50, 1) The function also handles negative numbers well, so that this example y = conv(x, 1, 50, 50, -100) is also valid and works well. :param value: the number to map :param fromLow: the lower bound of the value's current range :param fromHigh: the upper bound of the value's current range :param toLow: the lower bound of the value's target range :param toHigh: the upper bound of the value's target range :param func: function to be applied on result :return: The mapped value.""" result = (value - fromLow) * (toHigh - toLow) / (fromHigh - fromLow) + toLow if func is None: return result else: return func(result) def walltocord(wall, magnification=1, peakwidth=1): """creates a list of start and end coordinates for each line to be drawn from string representation of a maze wall :param wall: string representation of wall :param magnification: magnification applied to output coordinates :param peakwidth: A couple of weeks ago, cannot remember what I was thinking here... :return: list of [(startpos * magnification, end_pos * magnification)]""" """decodes a horizontal maze line and creates a list of start and end position for each line to be drawn""" out = [] rising_edge = False startpos = 0 for i, c in enumerate(wall): if c in '+-|': # value is above threshold if not rising_edge: rising_edge = True startpos = i else: if rising_edge: # this is falling edge rising_edge = False if startpos < i - peakwidth: # signal is wider than peak limit out += [(startpos * magnification, (i - peakwidth) * magnification)] # append to list # after loop check if complete signal is high, if so append if rising_edge and startpos <= i - peakwidth: out += [(startpos * magnification, i * magnification)] return out # def isVec2D(x): # iscorrectlist = False # if x is list and len(x) >= 2: # iscorrectlist = bool(type(x[0]) is float and type(x[1]) is float) # return x is turtle.Vec2D or iscorrectlist def samesideofline(pos, dest, line): """checks if pos and dest is on the same side of line :param pos: a pair/vector of numbers as a Vec2D (e.g. as returned by pos()) :param dest: a pair/vector of numbers as a Vec2D (e.g. as returned by pos()) :param line: a list of two pairs/vectors of numbers as two Vec2D :return: a number that can be used as bool 0 = pos and dest is on each side of line 1 = pos and dest is left of line 2 = pos and dest is over line 4 = pos and dest is right of line 8 = pos and dest is under line 16 = pos and dest is outside of line, should be considered as True as movement is allowed""" xli = min(line[0][0], line[1][0]) # min of x line cord xla = max(line[0][0], line[1][0]) # max of x line cord yli = min(line[0][1], line[1][1]) # min of y line cord yla = max(line[0][1], line[1][1]) # max of y line cord xpi = min(pos[0], dest[0]) # min of x pos and dest xpa = max(pos[0], dest[0]) # max of x pos and dest ypi = min(pos[1], dest[1]) # min of y pos and dest ypa = max(pos[1], dest[1]) # max of y pos and dest # if xli < xpi < xla or xli < xpa < xla: # result = ypa < yli or ypi > yla # elif yli < ypi < yla or yli > ypa > yla: # result = xpa < xli or xpi > xla # else: # result = True # return result if xli < xpi < xla or xli < xpa < xla: if ypa < yli: # pos and dest is under line result = 8 elif ypi > yla: # pos and dest is over line result = 2 else: result = 0 elif yli < ypi < yla or yli > ypa > yla: if xpa < xli: # pos and dest is left of line result = 1 elif xpi > xla: # pos and dest is right of line result = 4 else: result = 0 else: # pos and dest is outside of line result = 16 return result def getmazeheight(maze): """seriously? I am really not sure what to write here, is there anything unclear with the function name? Ok, fair enough :param maze: string representation of maze :return: the height of the maze given string representation (return (len(maze.split('&#92;n')) - 3) / 2)""" return (len(maze.split('\n')) - 3) / 2 def getmazewidth(maze): """Again?!? :param maze: string representation of maze :return: the width of the maze given string representation (return maze.split('&#92;n')[0].count('+') - 1)""" return maze.split('\n')[0].count('+') - 1 class Boa(turtle.Turtle): collidewithlines = True collisionautoturn = False collisionkill = False lines = list() maze = '' step = 5 def __init__(self, name=None, color=None): """Initialize self. See help(type(self)) for accurate signature. :param name: Set name str for this instance :param color: Set the pencolor and fillcolor. :return: None """ # super(Boa, self).__init__(self) turtle.Turtle.__init__(self) if type(name) is str: self.name = name if type(color) is str: self.color(color) self.penup() def getlines(self): "return self.lines" return self.lines def setmaze(self, maze): self.maze = maze def makemaze(self, w = 16, h = 8): """set self.maze to string representation of random generated maze :param w: int :param h: int :return: None """ vis = [[0] * w + [1] for _ in range(h)] + [[1] * (w + 1)] ver = [["| "] * w + ['|'] for _ in range(h)] + [[]] hor = [["+--"] * w + ['+'] for _ in range(h + 1)] def walk(x, y): vis[y][x] = 1 d = [(x - 1, y), (x, y + 1), (x + 1, y), (x, y - 1)] shuffle(d) for (xx, yy) in d: if vis[yy][xx]: continue if xx == x: hor[max(y, yy)][x] = "+ " if yy == y: ver[y][max(x, xx)] = " " walk(xx, yy) walk(randrange(w), randrange(h)) s = "" for (a, b) in zip(hor, ver): s += ''.join(a + ['\n'] + b + ['\n']) self.maze = s def appendline(self, xf, yf, xt=None, yt=None): """appends a line from one coordinate to another to the list self.lines :param xf: a number or a pair/vector of numbers :param yf: a number or a pair/vector of numbers :param xt: a number or None :param yt: a number or None If xt and yt is None, xf and yf must be a pair of coordinates or a Vec2D (e.g. as returned by pos()). :return: None """ if xt is None and yt is None: self.lines.append([xf,yf]) else: self.lines.append([[xf,yf],[xt,yt]]) def drawline(self, fromcord, tocord): """Draws a line from :param fromcord to :param tocord :param fromcord: a pair of coordinates or a Vec2D (e.g. as returned by pos()). :param tocord: a pair of coordinates or a Vec2D (e.g. as returned by pos()). :return: None""" self.penup() self.goto(fromcord) self.pendown() self.goto(tocord) def drawlines(self, drawcolor=None): " Draw all self.lines, tracer needs to be set to 1 after this" self._tracer(50) pencolor = self.pencolor() startpos = self.position() if type(drawcolor) is str: self.pencolor(drawcolor) else: self.pencolor('black') for line in self.lines: self.drawline(line[0], line[1]) self.penup() self.pencolor(pencolor) self.setpos(startpos) def onkeypress(self, fun, key=None): """redirect to turtle.onkeypress() In order to be able to register key-events, TurtleScreen must have focus. (See method listen.) :param fun: a function with no arguments :param key: a string: key (e.g. "a") or key-symbol (e.g. "space") :return: None """ turtle.onkeypress(fun, key) def collisionwith(self, radius, x, y=None): """Returns if self.pos() is within radius of x, y :param radius: a number (integer or float) :param x: a number or a pair/vector of numbers :param y: a number or None If y is None, x must be a pair of coordinates or a Vec2D (e.g. as returned by pos()). :return: Bool - True or False (return (cx - sx)**2 + (cy - sy)**2 < radius**2)""" if y is None: collider = x else: collider = [x,y] sx = self.pos()[0] # self pos x sy = self.pos()[1] # self pos y cx = collider[0] # collider x cy = collider[1] # collider y return (cx - sx)**2 + (cy - sy)**2 < radius**2 def loadmazeintolines(self, maze, zero): """ :param maze: string representation of the maze to be loaded into self.lines :param zero: dict containg 'left', 'right', 'top' and 'bottom' zero offest :return: None """ mazewidth = getmazewidth(maze) mazeheight = getmazeheight(maze) screenwidth = abs(zero['left'] - zero['right']) screenheight = abs(zero['top'] - zero['bottom']) y = 0 # handle vertical lines for i,wall in enumerate(maze.split('\n')): if even(i): ycord = conv(y, in_max=mazeheight, out_min=zero['top'], out_max=zero['bottom']) for line in walltocord(wall, screenwidth / mazewidth / 3): xfrom = line[0] + zero['left'] xdest = line[1] + zero['left'] self.appendline([xfrom, ycord], [xdest, ycord]) y += 1 # handle horizontal lines for x in range(0, mazewidth + 1): wall = '' for i,c in enumerate(maze[3 * x::50]): wall += c xcord = conv(x, in_max=mazewidth, out_min=zero['left'], out_max=zero['right']) for line in walltocord(wall, screenheight / mazeheight / 2): yfrom = zero['top'] - line[0] ydest = zero['top'] - line[1] self.appendline([xcord, yfrom], [xcord, ydest]) def advance(self, distance): """Move the boa forward() by the specified distance if allowed (not crossing any lines unless allowed to, hiding on collision and bouncing if set to) :param distance: a number (integer or float) :return: None""" self.movedir(distance) def reverse(self, distance): """Move the boa forward() by the specified distance if allowed (not crossing any lines unless allowed to, hiding on collision and bouncing if set to) :param distance: a number (integer or float) :return: None""" self.movedir(distance * -1) def movedir(self, distance): """moves a given distance if allowed similar to turtle.forward() and turtle.backward() positive number moves forward negative number moves backward :param distance: int :return: None """ dest = list(self.pos()) bearing = self.heading() angle = 90 - bearing dest =[dest[0] + (distance * cos(radians(bearing))), dest[1] + (distance * cos(radians(angle)))] self.gotoifallowed(dest) def gotoifallowed(self, x, y=None): """goto() if allowed (not crossing any lines unless allowed to, hiding on collision and bouncing if set to) :param x: a number or a pair/vector of numbers :param y: a number or None If y is None, x must be a pair of coordinates or a Vec2D (e.g. as returned by pos()). :return: None""" pos = self.pos() if y is None: dest = x else: dest = [x,y] premission = True for line in self.lines: premission = premission and samesideofline(pos, dest, line) if not premission: break if premission or not self.collidewithlines: self.goto(x, y) elif self.collisionkill: # on collision kill self instance class self.hideturtle() #del self elif self.collisionautoturn: sideofline = samesideofline(pos, pos, line) # left = 1, 2 = up, 4 = right, 8 = down newheading = randrange(180) if sideofline == 1: newheading += 90 elif sideofline == 4: newheading -= 90 elif sideofline == 8: newheading += 180 self.setheading(newheading) dest = list(self.pos()) bearing = self.heading() angle = 90 - bearing dest =[dest[0] + (self.step * cos(radians(bearing))), dest[1] + (self.step * cos(radians(angle)))] self.gotoifallowed(dest) def testmaze(): """:return: String representation of maze used for testing. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | | | | + +--+--+--+--+--+--+ + +--+--+--+--+--+ + + | | | | | | | | + +--+--+ + + +--+ +--+--+--+ +--+ +--+ + | | | | | | | | +--+--+--+--+ +--+ +--+--+--+ + +--+--+ + + | | | | | | | | +--+--+--+ +--+ +--+ + +--+--+--+ +--+ + + | | | | | | | + +--+--+ +--+--+ + +--+--+--+ +--+--+--+ + | | | | | | | | + + + +--+ +--+--+--+--+ +--+ +--+ +--+--+ | | | | | | | | | + +--+--+ + +--+ +--+ + + +--+ +--+--+ + | | | | | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ """ maze = \ """+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | | | | + +--+--+--+--+--+--+ + +--+--+--+--+--+ + + | | | | | | | | + +--+--+ + + +--+ +--+--+--+ +--+ +--+ + | | | | | | | | +--+--+--+--+ +--+ +--+--+--+ + +--+--+ + + | | | | | | | | +--+--+--+ +--+ +--+ + +--+--+--+ +--+ + + | | | | | | | + +--+--+ +--+--+ + +--+--+--+ +--+--+--+ + | | | | | | | | + + + +--+ +--+--+--+--+ +--+ +--+ +--+--+ | | | | | | | | | + +--+--+ + +--+ +--+ + + +--+ +--+--+ + | | | | | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ """ return maze
{ "repo_name": "wittrup/crap", "path": "TUMAGA/amazon.py", "copies": "1", "size": "16145", "license": "mit", "hash": 8032932315415495000, "line_mean": 38.8666666667, "line_max": 221, "alpha_frac": 0.5134097244, "autogenerated": false, "ratio": 3.5577346848832083, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4571144409283208, "avg_score": null, "num_lines": null }
"Amazon Payments Gateway" import urllib from datetime import datetime from decimal import Decimal from django.utils.safestring import mark_safe from hiicart.gateway.amazon import fps, ipn from hiicart.gateway.amazon.settings import SETTINGS as default_settings from hiicart.gateway.base import PaymentGatewayBase, SubmitResult, GatewayError LIVE_CBUI_URL = "https://authorize.payments.amazon.com/cobranded-ui/actions/start" TEST_CBUI_URL = "https://authorize.payments-sandbox.amazon.com/cobranded-ui/actions/start" class AmazonGateway(PaymentGatewayBase): "Payment Gateway for Amazon Payments." def __init__(self, cart): super(AmazonGateway, self).__init__("amazon", cart, default_settings) self._require_settings(["AWS_KEY", "AWS_SECRET"]) @property def _cbui_base_url(self): if self.settings["LIVE"]: url = mark_safe(LIVE_CBUI_URL) else: url = mark_safe(TEST_CBUI_URL) return url def _get_cbui_values(self, collect_address=False): "Get the key/values to be used in a co-branded UI request." values = {"callerKey" : self.settings["AWS_KEY"], "CallerReference" : self.cart.cart_uuid, "SignatureMethod" : "HmacSHA256", "SignatureVersion" : 2, "version" : "2009-01-09", "returnURL" : self.settings["CBUI_RETURN_URL"], "transactionAmount" : self.cart.total, "collectShippingAddress": str(collect_address)} if len(self.cart.recurring_lineitems) == 0: values["pipelineName"] = "SingleUse" else: if len(self.cart.recurring_lineitems) > 1: raise GatewayError("Only one recurring lineitem per cart.") recurring = self.cart.recurring_lineitems[0] values["pipelineName"] = "Recurring" values["recurringPeriod"] = "%s %s" % ( recurring.duration, recurring.duration_unit) if recurring.recurring_start and recurring.recurring_start > datetime.now(): values["validityStart"] = recurring.recurring_start.strftime('%s') # Optional Fields if self.settings["CBUI_WEBSITE_DESC"]: values["websiteDescription"] = unicode(self.settings["CBUI_WEBSITE_DESC"]).encode('utf-8') methods = self._get_payment_methods() if methods: values["paymentMethod"] = methods return values def _get_payment_methods(self): methods = [] if self.settings["ACCEPT_CC"]: methods.append("CC") if self.settings["ACCEPT_ACH"]: methods.append("ACH") if self.settings["ACCEPT_ABT"]: methods.append("ABT") return ",".join(methods) def _is_valid(self): "Return True if gateway is valid." #TODO: Query Amazon to validate credentials return True def cancel_recurring(self): "Cancel recurring lineitem." if len(self.cart.recurring_lineitems) == 0: return item = self.cart.recurring_lineitems[0] token = item.payment_token response = fps.do_fps("CancelToken", "GET", self.settings, TokenId=token) item.is_active = False item.save() self.cart.update_state() def charge_recurring(self, grace_period=None): """ Charge a cart's recurring item, if necessary. NOTE: Currently only one recurring item is supported per cart, so charge the first one found. """ if not grace_period: grace_period = self.settings.get("CHARGE_RECURRING_GRACE_PERIOD", None) recurring = [li for li in self.cart.recurring_lineitems if li.is_active] if not recurring or not recurring[0].is_expired(grace_period=grace_period): return item = recurring[0] payments = self.cart.payments \ .filter(state="PAID") \ .order_by("-created") payment_id= '%s-%i' % (self.cart.cart_uuid, len(payments)+1) result = ipn.AmazonIPN(self.cart).make_pay_request(item.payment_token, payment_id) if result != "TokenUsageError" and result != "Pending" and result != "Success": # TokenUsageError is if we tried to charge too soon item.recurring = False item.save() def sanitize_clone(self): "Nothing to do here..." return self.cart def submit(self, collect_address=False, cart_settings_kwargs=None): "Submit the cart to Amazon's Co-Branded UI (CBUI)" self._update_with_cart_settings(cart_settings_kwargs) values = self._get_cbui_values(collect_address) values["Signature"] = fps.generate_signature("GET", values, self._cbui_base_url, self.settings) url = "%s?%s" % (self._cbui_base_url, urllib.urlencode(values)) return SubmitResult("url", url)
{ "repo_name": "kbourgoin/hiicart", "path": "hiicart/gateway/amazon/gateway.py", "copies": "1", "size": "5059", "license": "mit", "hash": 3208039891129814500, "line_mean": 41.1583333333, "line_max": 102, "alpha_frac": 0.6015022732, "autogenerated": false, "ratio": 3.888547271329746, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.49900495445297466, "avg_score": null, "num_lines": null }
from Utils import getTreeFromXml try: import xml.etree.ElementTree as ET except ImportError: import elementtree.ElementTree as ET class Grantee(object): ALL_USERS_URI = "http://acs.amazonaws.com/groups/global/AllUsers" LOG_DELIVERY_URI = "http://acs.amazonaws.com/groups/s3/LogDelivery" def __init__(self): self.xsi_type = None self.tag = None self.name = None self.display_name = None self.permission = None def __repr__(self): return 'Grantee("%(tag)s", "%(name)s", "%(permission)s")' % { "tag" : self.tag, "name" : self.name, "permission" : self.permission } def isAllUsers(self): return self.tag == "URI" and self.name == Grantee.ALL_USERS_URI def isAnonRead(self): return self.isAllUsers() and (self.permission == "READ" or self.permission == "FULL_CONTROL") def getElement(self): el = ET.Element("Grant") grantee = ET.SubElement(el, "Grantee", { 'xmlns:xsi' : 'http://www.w3.org/2001/XMLSchema-instance', 'xsi:type' : self.xsi_type }) name = ET.SubElement(grantee, self.tag) name.text = self.name permission = ET.SubElement(el, "Permission") permission.text = self.permission return el class GranteeAnonRead(Grantee): def __init__(self): Grantee.__init__(self) self.xsi_type = "Group" self.tag = "URI" self.name = Grantee.ALL_USERS_URI self.permission = "READ" class GranteeLogDelivery(Grantee): def __init__(self, permission): """ permission must be either READ_ACP or WRITE """ Grantee.__init__(self) self.xsi_type = "Group" self.tag = "URI" self.name = Grantee.LOG_DELIVERY_URI self.permission = permission class ACL(object): EMPTY_ACL = "<AccessControlPolicy><Owner><ID></ID></Owner><AccessControlList></AccessControlList></AccessControlPolicy>" def __init__(self, xml = None): if not xml: xml = ACL.EMPTY_ACL self.grantees = [] self.owner_id = "" self.owner_nick = "" tree = getTreeFromXml(xml) self.parseOwner(tree) self.parseGrants(tree) def parseOwner(self, tree): self.owner_id = tree.findtext(".//Owner//ID") self.owner_nick = tree.findtext(".//Owner//DisplayName") def parseGrants(self, tree): for grant in tree.findall(".//Grant"): grantee = Grantee() g = grant.find(".//Grantee") grantee.xsi_type = g.attrib['{http://www.w3.org/2001/XMLSchema-instance}type'] grantee.permission = grant.find('Permission').text for el in g: if el.tag == "DisplayName": grantee.display_name = el.text else: grantee.tag = el.tag grantee.name = el.text self.grantees.append(grantee) def getGrantList(self): acl = [] for grantee in self.grantees: if grantee.display_name: user = grantee.display_name elif grantee.isAllUsers(): user = "*anon*" else: user = grantee.name acl.append({'grantee': user, 'permission': grantee.permission}) return acl def getOwner(self): return { 'id' : self.owner_id, 'nick' : self.owner_nick } def isAnonRead(self): for grantee in self.grantees: if grantee.isAnonRead(): return True return False def grantAnonRead(self): if not self.isAnonRead(): self.appendGrantee(GranteeAnonRead()) def revokeAnonRead(self): self.grantees = [g for g in self.grantees if not g.isAnonRead()] def appendGrantee(self, grantee): self.grantees.append(grantee) def hasGrant(self, name, permission): name = name.lower() permission = permission.upper() for grantee in self.grantees: if grantee.name.lower() == name: if grantee.permission == "FULL_CONTROL": return True elif grantee.permission.upper() == permission: return True return False; def grant(self, name, permission): if self.hasGrant(name, permission): return permission = permission.upper() if "ALL" == permission: permission = "FULL_CONTROL" if "FULL_CONTROL" == permission: self.revoke(name, "ALL") grantee = Grantee() grantee.name = name grantee.permission = permission if name.find('@') > -1: grantee.name = grantee.name.lower grantee.xsi_type = "AmazonCustomerByEmail" grantee.tag = "EmailAddress" elif name.find('http://acs.amazonaws.com/groups/') > -1: grantee.xsi_type = "Group" grantee.tag = "URI" else: grantee.name = grantee.name.lower grantee.xsi_type = "CanonicalUser" grantee.tag = "ID" self.appendGrantee(grantee) def revoke(self, name, permission): name = name.lower() permission = permission.upper() if "ALL" == permission: self.grantees = [g for g in self.grantees if not g.name.lower() == name] else: self.grantees = [g for g in self.grantees if not (g.name.lower() == name and g.permission.upper() == permission)] def __str__(self): tree = getTreeFromXml(ACL.EMPTY_ACL) tree.attrib['xmlns'] = "http://s3.amazonaws.com/doc/2006-03-01/" owner = tree.find(".//Owner//ID") owner.text = self.owner_id acl = tree.find(".//AccessControlList") for grantee in self.grantees: acl.append(grantee.getElement()) return ET.tostring(tree) if __name__ == "__main__": xml = """<?xml version="1.0" encoding="UTF-8"?> <AccessControlPolicy xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <Owner> <ID>12345678901234567890</ID> <DisplayName>owner-nickname</DisplayName> </Owner> <AccessControlList> <Grant> <Grantee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="CanonicalUser"> <ID>12345678901234567890</ID> <DisplayName>owner-nickname</DisplayName> </Grantee> <Permission>FULL_CONTROL</Permission> </Grant> <Grant> <Grantee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="Group"> <URI>http://acs.amazonaws.com/groups/global/AllUsers</URI> </Grantee> <Permission>READ</Permission> </Grant> </AccessControlList> </AccessControlPolicy> """ acl = ACL(xml) print "Grants:", acl.getGrantList() acl.revokeAnonRead() print "Grants:", acl.getGrantList() acl.grantAnonRead() print "Grants:", acl.getGrantList() print acl # vim:et:ts=4:sts=4:ai
{ "repo_name": "sharethis-github/OpenSource", "path": "s3cmd/S3/ACL.py", "copies": "2", "size": "7197", "license": "apache-2.0", "hash": 6612952104233416000, "line_mean": 30.5657894737, "line_max": 126, "alpha_frac": 0.5742670557, "autogenerated": false, "ratio": 3.5967016491754125, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.003363221418489991, "num_lines": 228 }
#Amazon S3 Bucket to Zendesk Import Process from __future__ import print_function import sys from zdesk import Zendesk from zdesk import get_id_from_url import boto3 import json import collections from time import sleep #Define S3 Bucket bucket = "<BUCKET_NAME>" #Define ZenDesk API Information config = { 'zdesk_email': '<ZENDESK_USER_EMAIL>', 'zdesk_password': '<ZENDESK_USER_PASSWORD_OR_TOKEN>', 'zdesk_url': '<ZENDESK_URL>', 'zdesk_token': <'TRUE OR FALSE'> } #Define telephone country code (if Active Directory numbers formatted without code) telephone_prefix = "1" #Connect to S3 with Boto3 s3 = boto3.client('s3') #Create ZenDesk Connection zendesk = Zendesk(**config) def lambda_handler(event, context): #List User users = zendesk.users_list().get('users', []) print("Listing Current ZenDesk Users") for user in users: name = user['name'] print(name) #Find Most Recently Modified Active Users File from S3 bucket_list = s3.list_objects(Bucket=bucket).get('Contents', []) print(bucket_list) for file in bucket_list: file_name = file['Key'] try: object = s3.get_object(Bucket=bucket,Key=file_name)['Body'] print(object) except Exception, e: print ("Error Encountered while downloading file.") print (e) exit() users = json.load(object) print(users) #Create and Update User print("Creating and Updating Users") for user in users: user_name = user['DisplayName'] user_email = user['EmailAddress'] user_phone = user['OfficePhone'] new_user = { 'user': { 'name': user_name, 'email': user_email, 'phone': "%s%s" % (telephone_prefix, user_phone), } } try: print(new_user) result = zendesk.user_create_or_update(data=new_user) sleep(0.03) #Print Generated User ID user_id = get_id_from_url(result) print(user_id) except Exception, e: print ("Error Encountered:") print (e) print("Deleting File") s3.delete_object(Bucket=bucket,Key=file_name)
{ "repo_name": "thigley986/Lambda-AD-Zendesk-Sync", "path": "Lambda/Lambda-2-Zendesk.py", "copies": "1", "size": "2392", "license": "apache-2.0", "hash": 585132563475042600, "line_mean": 25.5777777778, "line_max": 83, "alpha_frac": 0.5664715719, "autogenerated": false, "ratio": 3.839486356340289, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9860746795419133, "avg_score": 0.00904222656423118, "num_lines": 90 }