commit
stringlengths
40
40
old_file
stringlengths
4
264
new_file
stringlengths
4
264
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
624
message
stringlengths
15
4.7k
lang
stringclasses
3 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
cc4be37ef6d1ed2b8d89f14a051514d56f05b43b
setup.py
setup.py
#!/usr/bin/env python # coding=utf-8 __author__ = '[email protected]' from setuptools import setup setup(name="Power", version="1.0", description="Cross-platform system power status information.", author="Ilya Kulakov", author_email="[email protected]", url="https://github.com/Kentzo/Power", platforms=["Mac OS X 10.6+", "Windows XP+", "Linux 2.6+"], packages=['power'], classifiers=[ 'Operating System :: MacOS :: MacOS X', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX :: Linux', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Topic :: System :: Power (UPS)', 'Topic :: System :: Hardware', 'Topic :: System :: Monitoring' ], install_requires=['pyobjc-core == 2.3.2a0'] )
#!/usr/bin/env python # coding=utf-8 __author__ = '[email protected]' from setuptools import setup setup(name="Power", version="1.0", description="Cross-platform system power status information.", author="Ilya Kulakov", author_email="[email protected]", url="https://github.com/Kentzo/Power", platforms=["Mac OS X 10.6+", "Windows XP+", "Linux 2.6+"], packages=['power'], classifiers=[ 'Operating System :: MacOS :: MacOS X', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX :: Linux', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Topic :: System :: Power (UPS)', 'Topic :: System :: Hardware', 'Topic :: System :: Monitoring' ], install_requires=['pyobjc == 2.3'] )
Fix wrong install requirement name.
Fix wrong install requirement name.
Python
mit
Kentzo/Power
6fd24b15375f836c591c435ce1ded9dc96dc24f5
setup.py
setup.py
import os from setuptools import setup # Utility function to read the README file. def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name = "seqfile", version = "0.0.1", author = "Utkarsh Upadhyay", author_email = "[email protected]", description = ("Find the next file in a sequence of files in a thread-safe way."), license = "MIT", keywords = "file threadsafe sequence", url = "https://github.com/musically-ut/seqfile", packages = ['seqfile'], long_description = read('README.md'), classifiers = [ "License :: OSI Approved :: MIT License", "Intended Audience :: Developers", "Intended Audience :: Science/Research", "Development Status :: 3 - Alpha", "Operating System :: OS Independent", "Topic :: Utilities", "License :: OSI Approved :: MIT License", 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3' "Natural Language :: English", ], )
import os from setuptools import setup # Utility function to read the README file. def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name = "seqfile", version = "0.0.1", author = "Utkarsh Upadhyay", author_email = "[email protected]", description = ("Find the next file in a sequence of files in a thread-safe way."), license = "MIT", keywords = "file threadsafe sequence", url = "https://github.com/musically-ut/seqfile", packages = ['seqfile'], setup_requires = ['nose>=1.0', 'natsort>=3.5.6'], test_suite = 'nose.collector', long_description = read('README.md'), classifiers = [ "License :: OSI Approved :: MIT License", "Intended Audience :: Developers", "Intended Audience :: Science/Research", "Development Status :: 3 - Alpha", "Operating System :: OS Independent", "Topic :: Utilities", "License :: OSI Approved :: MIT License", 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3' "Natural Language :: English", ], )
Include natsort as a dependency for tests.
Include natsort as a dependency for tests.
Python
mit
musically-ut/seqfile
58433fad565aaf4889f0c5144fc3b4694a61b896
setup.py
setup.py
from setuptools import setup, find_packages setup( name = "sanitize", version = "0.33", description = "bringing sanitiy to world of messed-up data", author = "Aaron Swartz", author_email = "[email protected]", url='http://www.aaronsw.com/2002/sanitize/', license=open('LICENCE').read(), classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License (GPL)', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.3', 'Programming Language :: Python :: 2.4', 'Programming Language :: Python :: 2.5', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.0', 'Programming Language :: Python :: 3.1', 'Programming Language :: Python :: 3.2' ], license='BSD', packages=find_packages(), py_modules=['sanitize'], include_package_data=True, zip_safe=False, )
from setuptools import setup, find_packages setup( name = "sanitize", version = "0.33", description = "Bringing sanitiy to world of messed-up data", author = "Aaron Swartz", author_email = "[email protected]", url='http://www.aaronsw.com/2002/sanitize/', license=open('LICENCE').read(), classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License (GPL)', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.3', 'Programming Language :: Python :: 2.4', 'Programming Language :: Python :: 2.5', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.0', 'Programming Language :: Python :: 3.1', 'Programming Language :: Python :: 3.2' ], license='BSD', packages=find_packages(), py_modules=['sanitize'], include_package_data=True, zip_safe=False, )
Make the first word of the package description capital
Make the first word of the package description capital
Python
bsd-2-clause
Alir3z4/python-sanitize
6e0f2880c80150a71cc719ff652f1bfbde08a1fa
setup.py
setup.py
from setuptools import setup try: import ez_setup ez_setup.use_setuptools() except ImportError: pass setup( name = "django-tsearch2", version = "0.2", packages = ['tsearch2', 'tsearch2.management', 'tsearch2.management.commands'], author = "Henrique Carvalho Alves", author_email = "[email protected]", description = "TSearch2 support for Django", url = "http://github.com/hcarvalhoalves/django-tsearch2", )
from setuptools import setup setup( name = "django-tsearch2", version = "0.2", packages = ['tsearch2', 'tsearch2.management', 'tsearch2.management.commands'], zip_safe = False, author = "Henrique Carvalho Alves", author_email = "[email protected]", description = "TSearch2 support for Django", url = "http://github.com/hcarvalhoalves/django-tsearch2", )
Mark as zip_safe = False
Mark as zip_safe = False
Python
bsd-3-clause
hcarvalhoalves/django-tsearch2
600eef6ae431ad0b0e555832b3405be9d11ad8b6
setup.py
setup.py
#!/usr/bin/env python import sys from setuptools import setup, find_packages from exam import __version__ try: import multiprocessing except ImportError: pass install_requires = [] lint_requires = ['pep8', 'pyflakes'] tests_require = ['mock', 'nose', 'unittest2', 'describe==1.0.0beta1'] dependency_links = [ 'https://github.com/jeffh/describe/tarball/dev#egg=describe' ] setup_requires = [] if 'nosetests' in sys.argv[1:]: setup_requires.append('nose') setup( name='exam', version=__version__, author='Jeff Pollard', author_email='[email protected]', url='https://github.com/fluxx/exam', description='Helpers for better testing.', license='MIT', packages=find_packages(), install_requires=install_requires, tests_require=tests_require, setup_requires=setup_requires, extras_require={ 'test': tests_require, 'all': install_requires + tests_require, 'docs': ['sphinx'] + tests_require, 'lint': lint_requires }, zip_safe=False, test_suite='nose.collector', )
#!/usr/bin/env python import sys from setuptools import setup, find_packages from exam import __version__ try: import multiprocessing except ImportError: pass install_requires = ['mock'] lint_requires = ['pep8', 'pyflakes'] tests_require = ['nose', 'unittest2', 'describe==1.0.0beta1'] dependency_links = [ 'https://github.com/jeffh/describe/tarball/dev#egg=describe' ] setup_requires = [] if 'nosetests' in sys.argv[1:]: setup_requires.append('nose') setup( name='exam', version=__version__, author='Jeff Pollard', author_email='[email protected]', url='https://github.com/fluxx/exam', description='Helpers for better testing.', license='MIT', packages=find_packages(), install_requires=install_requires, tests_require=tests_require, setup_requires=setup_requires, extras_require={ 'test': tests_require, 'all': install_requires + tests_require, 'docs': ['sphinx'] + tests_require, 'lint': lint_requires }, zip_safe=False, test_suite='nose.collector', )
Declare mock as a requiement.
Declare mock as a requiement.
Python
mit
gterzian/exam,Fluxx/exam,Fluxx/exam,gterzian/exam
5acdff299ae3e65a0ab804d4d6ff3e058f6a3227
setup.py
setup.py
import sys from setuptools import setup, find_packages setup( name='chillin-server', version='1.4.0', description='Chillin AI Game Framework (Python Server)', long_description='', author='Koala', author_email='[email protected]', url='https://github.com/koala-team/Chillin-PyServer', keywords='ai game framework chillin', classifiers=[ 'Environment :: Console', 'License :: OSI Approved :: GNU Affero General Public License v3', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.5', 'Topic :: Software Development :: Libraries :: Application Frameworks' ], license='AGPL License, Version 3.0', install_requires=[ 'circuits==3.2', 'pydblite==3.0.4', 'koala-serializer==0.6.2', 'configparser==3.5.0', 'enum34==1.1.6' ], packages=find_packages(), package_data={ 'chillin_server': ['default_certs/*'] } )
import sys from setuptools import setup, find_packages setup( name='chillin-server', version='1.4.0', description='Chillin AI Game Framework (Python Server)', long_description='', author='Koala', author_email='[email protected]', url='https://github.com/koala-team/Chillin-PyServer', keywords='ai game framework chillin', classifiers=[ 'Environment :: Console', 'License :: OSI Approved :: GNU Affero General Public License v3', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.5', 'Topic :: Software Development :: Libraries :: Application Frameworks' ], license='AGPL License, Version 3.0', install_requires=[ 'circuits==3.2', 'pydblite==3.0.4', 'koala-serializer==0.6.3', 'configparser==3.5.0', 'enum34==1.1.6' ], packages=find_packages(), package_data={ 'chillin_server': ['default_certs/*'] } )
Change koala-serializer version to 0.6.3
Change koala-serializer version to 0.6.3
Python
agpl-3.0
koala-team/Chillin-PyServer
c451e87115bae4da01dd4c0ca3611433ee573220
setup.py
setup.py
from setuptools import setup setup( name = 'taskcat', packages = ['taskcat'], description = 'An OpenSource Cloudformation Deployment Framework', author = 'Tony Vattathil', author_email = '[email protected]', url = 'https://github.com/avattathil/taskcat.io', version = '0.1.3', download_url = 'https://github.com/avattathil/taskcat.io/archive/master.zip', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', ], keywords = ['aws', 'cloudformation', 'cloud', 'cloudformation testing', 'cloudformation deploy', 'taskcat'], #packages=find_packages(exclude=['contrib', 'docs', 'tests']), install_requires=['uuid', 'pyfiglet', 'argparse', 'boto3', 'pyyaml'], #data_files=[('config', ['ci/config.yml`'])], # 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', # ], #}, )
from setuptools import setup setup( name = 'taskcat', packages = ['taskcat'], description = 'An OpenSource Cloudformation Deployment Framework', author = 'Tony Vattathil', author_email = '[email protected]', url = 'https://aws-quickstart.github.io/taskcat/', version = '0.1.7', download_url = 'https://github.com/aws-quickstart/taskcat/tarball/master', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', ], keywords = ['aws', 'cloudformation', 'cloud', 'cloudformation testing', 'cloudformation deploy', 'taskcat'], #packages=find_packages(exclude=['contrib', 'docs', 'tests']), install_requires=['uuid', 'pyfiglet', 'argparse', 'boto3', 'pyyaml'], #data_files=[('config', ['ci/config.yml`'])], # 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', # ], #}, )
Update email in pip package
Update email in pip package
Python
apache-2.0
aws-quickstart/taskcat,aws-quickstart/taskcat,aws-quickstart/taskcat
5e38dda82bfc2f9f59fb591a9dde6ab52929d62e
setup.py
setup.py
#!/usr/bin/env python try: from setuptools import setup, find_packages except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages tests_require = [] setup( name='Mule', version='1.0', author='DISQUS', author_email='[email protected]', url='http://github.com/disqus/mule', description = 'Utilities for sharding test cases in BuildBot', packages=find_packages(), zip_safe=False, install_requires=[ 'unittest2', 'twisted', 'pyzmq', ], dependency_links=[], tests_require=tests_require, extras_require={'test': tests_require}, test_suite='mule.runtests.runtests', include_package_data=True, entry_points = { 'console_scripts': [ 'mule = mule.scripts.runner:main', ], }, classifiers=[ 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Operating System :: OS Independent', 'Topic :: Software Development' ], )
#!/usr/bin/env python try: from setuptools import setup, find_packages except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages import os.path tests_require = [] setup( name='Mule', version='1.0', author='DISQUS', author_email='[email protected]', url='http://github.com/disqus/mule', description = 'Utilities for sharding test cases in BuildBot', packages=find_packages(os.path.dirname(__file__)), zip_safe=False, install_requires=[ 'unittest2', 'twisted', 'pyzmq', ], dependency_links=[], tests_require=tests_require, extras_require={'test': tests_require}, test_suite='mule.runtests.runtests', include_package_data=True, entry_points = { 'console_scripts': [ 'mule = mule.scripts.runner:main', ], }, classifiers=[ 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Operating System :: OS Independent', 'Topic :: Software Development' ], )
Use absolute path on find packages
Use absolute path on find packages
Python
apache-2.0
disqus/mule
33691c04db2eb039a090bd85a811f3eaf80f315d
setup.py
setup.py
import os from setuptools import setup, find_packages setup( name = 'temps', version = '0.1', license = 'MIT', description = 'Context managers for creating and cleaning up temporary directories and files.', long_description = open(os.path.join(os.path.dirname(__file__), 'README.md')).read(), keywords = 'python temporary files directories context manager', url = 'https://github.com/todddeluca/temps', author = 'Todd Francis DeLuca', author_email = '[email protected]', classifiers = ['License :: OSI Approved :: MIT License', 'Development Status :: 3 - Alpha', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', ], py_modules = ['temps'], )
import os from setuptools import setup, find_packages setup( name = 'temps', version = '0.1.0', license = 'MIT', description = 'Context managers for creating and cleaning up temporary directories and files.', long_description = open(os.path.join(os.path.dirname(__file__), 'README.md')).read(), keywords = 'python temporary files directories context manager', url = 'https://github.com/todddeluca/temps', author = 'Todd Francis DeLuca', author_email = '[email protected]', classifiers = ['License :: OSI Approved :: MIT License', 'Development Status :: 3 - Alpha', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', ], py_modules = ['temps'], )
Use standard 3-part version number.
Use standard 3-part version number.
Python
mit
todddeluca/temps
67b8b26309f82130ab808ee6be5ede7260162b3b
setup.py
setup.py
import os from setuptools import setup version_file = open(os.path.join(os.path.dirname(__file__), 'VERSION')) version = version_file.read().strip() README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read() setup( name='canvas_python_sdk', version=version, description='A python sdk for the canvas LMS api', author='Harvard University', author_email='[email protected]', url='https://github.com/Harvard-University-iCommons/canvas_python_sdk', packages=['canvas_sdk'], long_description=README, classifiers=[ "License :: OSI Approved :: MIT License", 'Operating System :: OS Independent', "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Development Status :: 4 - Beta", "Intended Audience :: Developers", "Topic :: Software Development", ], keywords='canvas api sdk LMS', license='MIT', install_requires=[ 'requests>=2.3.0' ], test_suite='tests', tests_require=[ 'mock>=1.0.1', ], )
import os from setuptools import setup, find_packages version_file = open(os.path.join(os.path.dirname(__file__), 'VERSION')) version = version_file.read().strip() README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read() setup( name='canvas_python_sdk', version=version, description='A python sdk for the canvas LMS api', author='Harvard University', author_email='[email protected]', url='https://github.com/Harvard-University-iCommons/canvas_python_sdk', packages=find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"]), long_description=README, classifiers=[ "License :: OSI Approved :: MIT License", 'Operating System :: OS Independent', "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Development Status :: 4 - Beta", "Intended Audience :: Developers", "Topic :: Software Development", ], keywords='canvas api sdk LMS', license='MIT', install_requires=[ 'requests>=2.3.0', 'sphinx>=1.2.0', ], test_suite='tests', tests_require=[ 'mock>=1.0.1', ], )
Use find_packages helper to get everything except for tests. Add sphinx as an installation requirement.
Use find_packages helper to get everything except for tests. Add sphinx as an installation requirement.
Python
mit
penzance/canvas_python_sdk
2c3dbcaaa4eee9b2d48670fe0db5094044eb49af
setup.py
setup.py
#!/usr/bin/env python from setuptools import setup from glob import glob from dh_syncserver import version etcpath = "/etc" setup(name='dh_syncserver', version=version, description='DenyHosts Synchronisation Server', author='Jan-Pascal van Best', author_email='[email protected]', url='http://www.github.com/janpascal/denyhosts_sync_server', packages=['dh_syncserver'], install_requires=["Twisted", "twistar", "ipaddr", "jinja2", "pygal", "GeoIP"], scripts=['scripts/dh_syncserver'], data_files=[ ], license=""" Copyright (C) 2015 Jan-Pascal van Best <[email protected]> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ )
#!/usr/bin/env python from setuptools import setup from glob import glob from dh_syncserver import version etcpath = "/etc" setup(name='dh_syncserver', version=version, description='DenyHosts Synchronisation Server', author='Jan-Pascal van Best', author_email='[email protected]', url='http://www.github.com/janpascal/denyhosts_sync_server', packages=['dh_syncserver'], install_requires=["Twisted", "twistar", "ipaddr", "jinja2", "pygal", "GeoIP"], scripts=['scripts/dh_syncserver'], data_files=[ ('static/js', glob('static/js/*.js')), ('static/css', glob('static/css/*.css')), ('static/graph', glob('static/graph/README')), ('template', glob('template/*')), ('docs', glob('docs/*')), ], license=""" Copyright (C) 2015 Jan-Pascal van Best <[email protected]> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ )
Install static files, templates and docs
Install static files, templates and docs
Python
agpl-3.0
sergey-dryabzhinsky/denyhosts_sync,sergey-dryabzhinsky/denyhosts_sync,janpascal/denyhosts_sync,janpascal/denyhosts_sync,sergey-dryabzhinsky/denyhosts_sync,janpascal/denyhosts_sync
c25297735f38d1e2a6ddb6878f919d192f9faedd
GcodeParser.py
GcodeParser.py
#!/usr/bin/env python # coding=UTF-8 """Module containing Gcode parsing functions""" __author__ = "Dylan Armitage" __email__ = "[email protected]" ####---- Imports ----#### from pygcode import Line, GCodeLinearMove def bounding_box(gcode_file): """Take in file of gcode, return dict of max and min bounding values""" raise NotImplemented def box_gcode(min_xy, max_xy): """Take in min/max coordinate tuples, return G0 commands to bound it""" raise NotImplemented def mid_gcode(min_xy, max_xy): """Take in min/max coord tuples, return G0 to go to midpoint""" raise NotImplemented
#!/usr/bin/env python # coding=UTF-8 """Module containing Gcode parsing functions""" __author__ = "Dylan Armitage" __email__ = "[email protected]" ####---- Imports ----#### from pygcode import Line, GCodeLinearMove def bounding_box(gcode_file): """Take in file of gcode, return dict of max and min bounding values""" raise NotImplemented def box_gcode(min_xy, max_xy): """Take in min/max coordinate tuples, return G0 commands to bound it""" gcode = [] gcode.append(GCodeLinearMove(X=min_xy[0], Y=min_xy[1])) gcode.append(GCodeLinearMove(X=max_xy[0], Y=min_xy[1])) gcode.append(GCodeLinearMove(X=max_xy[0], Y=max_xy[1])) gcode.append(GCodeLinearMove(X=min_xy[0], Y=max_xy[1])) gcode.append(GCodeLinearMove(X=min_xy[0], Y=min_xy[1])) # Convert from GCodeLinearMove class to string gcode = [str(line) for line in gcode] return gcode def mid_gcode(min_xy, max_xy): """Take in min/max coord tuples, return G0 to go to midpoint""" raise NotImplemented
ADD function to return box gcode
ADD function to return box gcode
Python
mit
RootAccessHackerspace/k40-laser-scripts,RootAccessHackerspace/k40-laser-scripts
dce5c6f7f7cfd2b7384aba5d887700bb90ab2e39
app/timetables/admin.py
app/timetables/admin.py
from django.contrib import admin from . import models admin.site.register(models.Weekday) admin.site.register(models.Meal) admin.site.register(models.MealOption) admin.site.register(models.Course) admin.site.register(models.Timetable) admin.site.register(models.Dish) admin.site.register(models.Admin)
from django.contrib import admin from . import models admin.site.register(models.Weekday) admin.site.register(models.Meal) admin.site.register(models.MealOption) admin.site.register(models.Course) admin.site.register(models.Timetable) admin.site.register(models.Dish) admin.site.register(models.Admin)
Add extra space below ending of import
Add extra space below ending of import
Python
mit
teamtaverna/core
3bd2c8c48d81c22ca38b2c7a32ef9007eb8e2a8f
project/app/main.py
project/app/main.py
# -*- coding: utf-8 -*- """WSGI app setup.""" import os import sys if 'lib' not in sys.path: # Add lib as primary libraries directory, with fallback to lib/dist # and optionally to lib/dist.zip, loaded using zipimport. sys.path[0:0] = ['lib', 'lib/dist', 'lib/dist.zip'] from tipfy import Tipfy from config import config from urls import rules def enable_appstats(app): """Enables appstats middleware.""" if debug: return from google.appengine.ext.appstats.recording import appstats_wsgi_middleware app.wsgi_app = appstats_wsgi_middleware(app.wsgi_app) def enable_jinja2_debugging(): """Enables blacklisted modules that help Jinja2 debugging.""" if not debug: return # This enables better debugging info for errors in Jinja2 templates. from google.appengine.tools.dev_appserver import HardenedModulesHook HardenedModulesHook._WHITE_LIST_C_MODULES += ['_ctypes', 'gestalt'] # Is this the development server? debug = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev') # Instantiate the application. app = Tipfy(rules=rules, config=config, debug=debug) enable_appstats(app) enable_jinja2_debugging() def main(): # Run the app. app.run() if __name__ == '__main__': main()
# -*- coding: utf-8 -*- """WSGI app setup.""" import os import sys if 'lib' not in sys.path: # Add lib as primary libraries directory, with fallback to lib/dist # and optionally to lib/dist.zip, loaded using zipimport. sys.path[0:0] = ['lib', 'lib/dist', 'lib/dist.zip'] from tipfy import Tipfy from config import config from urls import rules def enable_appstats(app): """Enables appstats middleware.""" from google.appengine.ext.appstats.recording import \ appstats_wsgi_middleware app.wsgi_app = appstats_wsgi_middleware(app.wsgi_app) def enable_jinja2_debugging(): """Enables blacklisted modules that help Jinja2 debugging.""" if not debug: return # This enables better debugging info for errors in Jinja2 templates. from google.appengine.tools.dev_appserver import HardenedModulesHook HardenedModulesHook._WHITE_LIST_C_MODULES += ['_ctypes', 'gestalt'] # Is this the development server? debug = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev') # Instantiate the application. app = Tipfy(rules=rules, config=config, debug=debug) enable_appstats(app) enable_jinja2_debugging() def main(): # Run the app. app.run() if __name__ == '__main__': main()
Enable appstats by default in dev too.
Enable appstats by default in dev too.
Python
bsd-3-clause
pombreda/tipfy,adilhz/tipfy,google-code-export/tipfy,pombreda/tipfy,google-code-export/tipfy,google-code-export/tipfy,adilhz/tipfy,pombreda/tipfy
b3362c05032b66592b8592ccb94a3ec3f10f815f
project/urls.py
project/urls.py
# Django from django.conf.urls import ( include, url, ) from django.contrib import admin from django.http import HttpResponse urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/', include('apps.api.urls')), url(r'^api-auth/', include('rest_framework.urls')), url(r'^robots.txt$', lambda r: HttpResponse("User-agent: *\nDisallow: /", content_type="text/plain")), ]
# Django from django.conf.urls import ( include, url, ) from django.contrib import admin from django.http import HttpResponse from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/', include('apps.api.urls')), url(r'^api-auth/', include('rest_framework.urls')), url(r'^robots.txt$', lambda r: HttpResponse("User-agent: *\nDisallow: /", content_type="text/plain")), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Add media server to dev server
Add media server to dev server
Python
bsd-2-clause
dbinetti/barberscore-django,barberscore/barberscore-api,dbinetti/barberscore,dbinetti/barberscore,dbinetti/barberscore-django,barberscore/barberscore-api,barberscore/barberscore-api,barberscore/barberscore-api
d730eb0c0df2fb6784f7adcce479c4c9588764b9
spacy/ja/__init__.py
spacy/ja/__init__.py
# encoding: utf8 from __future__ import unicode_literals, print_function from os import path from ..language import Language from ..attrs import LANG from ..tokens import Doc from .language_data import * class Japanese(Language): lang = 'ja' def make_doc(self, text): from janome.tokenizer import Tokenizer words = [x.surface for x in Tokenizer().tokenize(text)] return Doc(self.vocab, words=words, spaces=[False]*len(words))
# encoding: utf8 from __future__ import unicode_literals, print_function from os import path from ..language import Language from ..attrs import LANG from ..tokens import Doc from .language_data import * class Japanese(Language): lang = 'ja' def make_doc(self, text): try: from janome.tokenizer import Tokenizer except ImportError: raise ImportError("The Japanese tokenizer requires the Janome library: https://github.com/mocobeta/janome") words = [x.surface for x in Tokenizer().tokenize(text)] return Doc(self.vocab, words=words, spaces=[False]*len(words))
Raise custom ImportError if importing janome fails
Raise custom ImportError if importing janome fails
Python
mit
raphael0202/spaCy,recognai/spaCy,explosion/spaCy,Gregory-Howard/spaCy,recognai/spaCy,spacy-io/spaCy,recognai/spaCy,aikramer2/spaCy,Gregory-Howard/spaCy,honnibal/spaCy,recognai/spaCy,raphael0202/spaCy,explosion/spaCy,Gregory-Howard/spaCy,raphael0202/spaCy,aikramer2/spaCy,spacy-io/spaCy,Gregory-Howard/spaCy,raphael0202/spaCy,aikramer2/spaCy,explosion/spaCy,honnibal/spaCy,honnibal/spaCy,Gregory-Howard/spaCy,explosion/spaCy,aikramer2/spaCy,explosion/spaCy,spacy-io/spaCy,recognai/spaCy,recognai/spaCy,raphael0202/spaCy,spacy-io/spaCy,explosion/spaCy,aikramer2/spaCy,honnibal/spaCy,aikramer2/spaCy,spacy-io/spaCy,spacy-io/spaCy,Gregory-Howard/spaCy,raphael0202/spaCy
f1dafecbafdb7dee7da5a5dea8a56b8b30e0fe1e
documents/urls.py
documents/urls.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf.urls import url import documents.views urlpatterns = [ url(r"^upload/(?P<slug>[^/]*)$", documents.views.upload_file, name="document_put"), url(r"^multiple_upload/(?P<slug>[^/]*)$", documents.views.upload_multiple_files, name="document_put_multiple"), url(r"^(?P<pk>[^/]*)/edit$", documents.views.document_edit, name="document_edit"), url(r"^(?P<pk>[^/]*)/reupload$", 'documents.views.document_reupload', name="document_reupload"), url(r"^(?P<pk>[^/]*)/download$", documents.views.document_download, name="document_download"), url(r"^(?P<pk>[^/]*)/original$", documents.views.document_download_original, name="document_download_original"), url(r"^(?P<pk>[^/]*)$", documents.views.document_show, name="document_show"), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf.urls import url import documents.views urlpatterns = [ url(r"^upload/(?P<slug>[^/]*)$", documents.views.upload_file, name="document_put"), url(r"^multiple_upload/(?P<slug>[^/]*)$", documents.views.upload_multiple_files, name="document_put_multiple"), url(r"^(?P<pk>[^/]*)/edit$", documents.views.document_edit, name="document_edit"), url(r"^(?P<pk>[^/]*)/reupload$", documents.views.document_reupload, name="document_reupload"), url(r"^(?P<pk>[^/]*)/download$", documents.views.document_download, name="document_download"), url(r"^(?P<pk>[^/]*)/original$", documents.views.document_download_original, name="document_download_original"), url(r"^(?P<pk>[^/]*)$", documents.views.document_show, name="document_show"), ]
Fix an url and use a callable instead of a string
Fix an url and use a callable instead of a string
Python
agpl-3.0
UrLab/DocHub,UrLab/DocHub,UrLab/beta402,UrLab/beta402,UrLab/beta402,UrLab/DocHub,UrLab/DocHub
223872a6f894b429b3784365fe50e139e649d233
chempy/electrochemistry/nernst.py
chempy/electrochemistry/nernst.py
# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function) import math def nernst_potential(ion_conc_out, ion_conc_in, charge, T, constants=None, units=None): """ Calculates the Nernst potential using the Nernst equation for a particular ion. Parameters ---------- ion_conc_out: float with unit Extracellular concentration of ion ion_conc_in: float with unit Intracellular concentration of ion charge: integer Charge of the ion T: float with unit Absolute temperature constants: object (optional, default: None) constant attributes accessed: F - Faraday constant R - Ideal Gas constant units: object (optional, default: None) unit attributes: coulomb, joule, kelvin, mol Returns ------- Membrane potential """ if constants is None: F = 96485.33289 R = 8.3144598 if units is not None: F *= units.coulomb / units.mol R *= units.joule / units.kelvin / units.mol else: F = constants.Faraday_constant R = constants.ideal_gas_constant return (R * T) / (charge * F) * math.log(ion_conc_out / ion_conc_in)
# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function) import math def nernst_potential(ion_conc_out, ion_conc_in, charge, T, constants=None, units=None, backend=math): """ Calculates the Nernst potential using the Nernst equation for a particular ion. Parameters ---------- ion_conc_out: float with unit Extracellular concentration of ion ion_conc_in: float with unit Intracellular concentration of ion charge: integer Charge of the ion T: float with unit Absolute temperature constants: object (optional, default: None) constant attributes accessed: F - Faraday constant R - Ideal Gas constant units: object (optional, default: None) unit attributes: coulomb, joule, kelvin, mol backend: module (optional, default: math) module used to calculate log using `log` method, can be substituted with sympy to get symbolic answers Returns ------- Membrane potential """ if constants is None: F = 96485.33289 R = 8.3144598 if units is not None: F *= units.coulomb / units.mol R *= units.joule / units.kelvin / units.mol else: F = constants.Faraday_constant R = constants.ideal_gas_constant return (R * T) / (charge * F) * backend.log(ion_conc_out / ion_conc_in)
Add keyword arg for backend for log
Add keyword arg for backend for log Can be used to switch out math module with other modules, ex. sympy for symbolic answers
Python
bsd-2-clause
bjodah/aqchem,bjodah/aqchem,bjodah/chempy,bjodah/chempy,bjodah/aqchem
5ea19da9fdd797963a7b7f1f2fd8f7163200b4bc
easy_maps/conf.py
easy_maps/conf.py
# -*- coding: utf-8 -*- import warnings from django.conf import settings # pylint: disable=W0611 from appconf import AppConf class EasyMapsSettings(AppConf): CENTER = (-41.3, 32) GEOCODE = 'easy_maps.geocode.google_v3' ZOOM = 16 # See https://developers.google.com/maps/documentation/javascript/tutorial#MapOptions for more information. LANGUAGE = 'en' # See https://developers.google.com/maps/faq#languagesupport for supported languages. GOOGLE_MAPS_API_KEY = None GOOGLE_KEY = None CACHE_LIFETIME = 600 # 10 minutes in seconds class Meta: prefix = 'easy_maps' holder = 'easy_maps.conf.settings' if hasattr(settings, 'EASY_MAPS_GOOGLE_MAPS_API_KEY'): warnings.warn("EASY_MAPS_GOOGLE_MAPS_API_KEY is deprecated, use EASY_MAPS_GOOGLE_KEY", DeprecationWarning)
# -*- coding: utf-8 -*- import warnings from django.conf import settings # pylint: disable=W0611 from appconf import AppConf class EasyMapsSettings(AppConf): CENTER = (-41.3, 32) GEOCODE = 'easy_maps.geocode.google_v3' ZOOM = 16 # See https://developers.google.com/maps/documentation/javascript/tutorial#MapOptions for more information. LANGUAGE = 'en' # See https://developers.google.com/maps/faq#languagesupport for supported languages. GOOGLE_MAPS_API_KEY = None GOOGLE_KEY = None CACHE_LIFETIME = 600 # 10 minutes in seconds class Meta: prefix = 'easy_maps' holder = 'easy_maps.conf.settings' if settings.EASY_MAPS_GOOGLE_MAPS_API_KEY is not None: warnings.warn("EASY_MAPS_GOOGLE_MAPS_API_KEY is deprecated, use EASY_MAPS_GOOGLE_KEY", DeprecationWarning)
Check is EASY_MAPS_GOOGLE_MAPS_API_KEY is not None before raising warning.
Check is EASY_MAPS_GOOGLE_MAPS_API_KEY is not None before raising warning.
Python
mit
kmike/django-easy-maps,kmike/django-easy-maps,bashu/django-easy-maps,bashu/django-easy-maps
2d74b55a0c110a836190af819b55673bce2300a0
gaphor/ui/macosshim.py
gaphor/ui/macosshim.py
try: import gi gi.require_version("GtkosxApplication", "1.0") except ValueError: macos_init = None else: from gi.repository import GtkosxApplication macos_app = GtkosxApplication.Application.get() def open_file(macos_app, path, application): if path == __file__: return False app_file_manager = application.get_service("app_file_manager") app_file_manager.load(path) return True def block_termination(macos_app, application): quit = application.quit() return not quit def macos_init(application): macos_app.connect("NSApplicationOpenFile", open_file, application) macos_app.connect( "NSApplicationBlockTermination", block_termination, application )
try: import gi from gi.repository import Gtk if Gtk.get_major_version() == 3: gi.require_version("GtkosxApplication", "1.0") else: raise ValueError() except ValueError: macos_init = None else: from gi.repository import GtkosxApplication macos_app = GtkosxApplication.Application.get() def open_file(macos_app, path, application): if path == __file__: return False app_file_manager = application.get_service("app_file_manager") app_file_manager.load(path) return True def block_termination(macos_app, application): quit = application.quit() return not quit def macos_init(application): macos_app.connect("NSApplicationOpenFile", open_file, application) macos_app.connect( "NSApplicationBlockTermination", block_termination, application )
Fix macos shim for gtk 4
Fix macos shim for gtk 4
Python
lgpl-2.1
amolenaar/gaphor,amolenaar/gaphor
4e3042ed2e76ab3563cfd0f53a20b82d9ec545c3
masters/master.client.skia/master_site_config.py
masters/master.client.skia/master_site_config.py
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ActiveMaster definition.""" from config_bootstrap import Master class Skia(Master.Master3): project_name = 'Skia' master_port = 8053 slave_port = 8153 master_port_alt = 8253 repo_url = 'https://skia.googlesource.com/skia.git' production_host = None is_production_host = False buildbot_url = None
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ActiveMaster definition.""" from config_bootstrap import Master class Skia(Master.Master3): project_name = 'Skia' master_port = 8084 slave_port = 8184 master_port_alt = 8284 repo_url = 'https://skia.googlesource.com/skia.git' production_host = None is_production_host = False buildbot_url = None
Change Skia ports again, again.
Change Skia ports again, again. BUG=skia:761 Review URL: https://codereview.chromium.org/413273002 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@285363 0039d316-1c4b-4281-b951-d872f2087c98
Python
bsd-3-clause
eunchong/build,eunchong/build,eunchong/build,eunchong/build
4a84fe0c774638b7a00d37864b6d634200512f99
tests.py
tests.py
import unittest from stacklogger import srcfile class TestUtils(unittest.TestCase): def test_srcfile(self): self.assertTrue(srcfile("foo.py").endswith("foo.py")) self.assertTrue(srcfile("foo.pyc").endswith("foo.py")) self.assertTrue(srcfile("foo.pyo").endswith("foo.py")) self.assertTrue(srcfile("foo").endswith("foo"))
import inspect import unittest from stacklogger import srcfile currentframe = inspect.currentframe class FakeFrames(object): def fake_method(self): return currentframe() @property def fake_property(self): return currentframe() @classmethod def fake_classmethod(cls): return currentframe() @staticmethod def fake_staticmethod(): return currentframe() def fake_function(): return currentframe() class TestUtils(unittest.TestCase): def test_srcfile(self): self.assertTrue(srcfile("foo.py").endswith("foo.py")) self.assertTrue(srcfile("foo.pyc").endswith("foo.py")) self.assertTrue(srcfile("foo.pyo").endswith("foo.py")) self.assertTrue(srcfile("foo").endswith("foo"))
Build fake frames for later testing.
Build fake frames for later testing.
Python
isc
whilp/stacklogger
40ece09df1d757af55a306e99d03f045fc23ac95
git_update/__main__.py
git_update/__main__.py
#!/usr/bin/env python """Script for updating a directory of repositories.""" import logging import os import click from .actions import update_repo @click.command() @click.option('-d', '--debug', help='Set DEBUG level logging.', is_flag=True) @click.argument('dir', default='.') def main(**kwargs): """Update repositories in a directory. By default, the current working directory list is used for finding valid repositories. """ logging.basicConfig( level=logging.INFO, format='[%(levelname)s] %(name)s:%(funcName)s - %(message)s') log = logging.getLogger(__name__) if kwargs['debug']: logging.root.setLevel(logging.DEBUG) main_dir = kwargs['dir'] log.info('Finding directories in %s', main_dir) dir_list = os.listdir(main_dir) log.debug('List of directories: %s', dir_list) # Git directory was passed in, not a directory of Git directories if '.git' in dir_list: dir_list = [kwargs['dir']] for directory in dir_list: update_repo(os.path.join(main_dir, directory)) if __name__ == '__main__': main()
#!/usr/bin/env python """Script for updating a directory of repositories.""" import logging import os import click from .actions import update_repo def set_logging(ctx, param, value): """Set logging level based on how many verbose flags.""" logging_level = (logging.root.getEffectiveLevel() - value * 10) or 1 logging.basicConfig(level=logging_level, format='[%(levelname)s] %(name)s:%(funcName)s - %(message)s') @click.command() @click.option('-v', '--verbose', count=True, callback=set_logging, help='More verbose logging, use multiple times.') @click.argument('dir', default='.') def main(**kwargs): """Update repositories in a directory. By default, the current working directory list is used for finding valid repositories. """ log = logging.getLogger(__name__) main_dir = kwargs['dir'] log.info('Finding directories in %s', main_dir) dir_list = os.listdir(main_dir) log.debug('List of directories: %s', dir_list) # Git directory was passed in, not a directory of Git directories if '.git' in dir_list: dir_list = [kwargs['dir']] for directory in dir_list: update_repo(os.path.join(main_dir, directory)) if __name__ == '__main__': main()
Change to multiple verbose option
fix: Change to multiple verbose option
Python
mit
e4r7hbug/git_update
4b485e601b4410561ee4b4a681e392f4d141a339
runtests.py
runtests.py
#!/usr/bin/env python import sys import django from django.conf import settings if not settings.configured: settings.configure( AUTHENTICATION_BACKENDS=( 'django_authgroupex.auth.AuthGroupeXBackend', ), DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } }, INSTALLED_APPS=( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.sessions', 'django.contrib.sites', 'django_authgroupex', ), SITE_ID=1, SECRET_KEY='this-is-just-for-tests-so-not-that-secret', TEST_RUNNER = 'django.test.simple.DjangoTestSuiteRunner', AUTHGROUPEX_LOGIN_REDIRECT_URL='/login-success/' ) from django.test.utils import get_runner def runtests(): if hasattr(django, 'setup'): django.setup() apps = ['django_authgroupex', ] TestRunner = get_runner(settings) test_runner = TestRunner(verbosity=1, interactive=True, failfast=False) failures = test_runner.run_tests(apps) sys.exit(failures) if __name__ == '__main__': runtests()
#!/usr/bin/env python import sys import django from django.conf import settings if not settings.configured: settings.configure( AUTHENTICATION_BACKENDS=( 'django_authgroupex.auth.AuthGroupeXBackend', ), DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } }, INSTALLED_APPS=( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.sessions', 'django.contrib.sites', 'django_authgroupex', ), SITE_ID=1, SECRET_KEY='this-is-just-for-tests-so-not-that-secret', TEST_RUNNER = 'django.test.simple.DjangoTestSuiteRunner', AUTHGROUPEX_LOGIN_REDIRECT_URL='/login-success/', MIDDLEWARE_CLASSES=() ) from django.test.utils import get_runner def runtests(): if hasattr(django, 'setup'): django.setup() apps = ['django_authgroupex', ] TestRunner = get_runner(settings) test_runner = TestRunner(verbosity=1, interactive=True, failfast=False) failures = test_runner.run_tests(apps) sys.exit(failures) if __name__ == '__main__': runtests()
Configure MIDDLEWARE_CLASSES in test settings
Configure MIDDLEWARE_CLASSES in test settings Django 1.7 complained: (1_7.W001) MIDDLEWARE_CLASSES is not set. HINT: Django 1.7 changed the global defaults for the MIDDLEWARE_CLASSES. django.contrib.sessions.middleware.SessionMiddleware, django.contrib.auth.middleware.AuthenticationMiddleware, and django.contrib.messages.middleware.MessageMiddleware were removed from the defaults. If your project needs these middleware then you should configure this setting. Set this setting to nothing to make Django happy.
Python
bsd-2-clause
Polytechnique-org/django-authgroupex
98be6419eed3dd6d0f056acbb31850291827ed46
doc/make_version.py
doc/make_version.py
print """ Version Info ============ To obtain version info:: from scan.version import __version__, version_history print __version__ print version_history """ from scan.version import __version__, version_history print "Version history::" for line in version_history.splitlines(): print (" " + line)
print """ Version Info ============ To obtain version info:: from scan.version import __version__, version_history print __version__ print version_history """ import sys sys.path.append("..") from scan.version import __version__, version_history print "Version history::" for line in version_history.splitlines(): print (" " + line)
Include version detail in doc
Include version detail in doc
Python
epl-1.0
PythonScanClient/PyScanClient,PythonScanClient/PyScanClient
48b1cfaadd7642706a576d8ba9bf38c297a2d873
runtests.py
runtests.py
#!/usr/bin/env python import django from django.conf import settings from django.core.management import call_command settings.configure( DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', } }, ALLOWED_HOSTS=[ 'testserver', ], INSTALLED_APPS=[ 'django_nose', 'permissions', 'permissions.tests', ], ROOT_URLCONF='permissions.tests.urls', TEST_RUNNER='django_nose.NoseTestSuiteRunner' ) if django.VERSION[:2] >= (1, 7): from django import setup else: setup = lambda: None setup() call_command("test")
#!/usr/bin/env python import django from django.conf import settings from django.core.management import call_command settings.configure( DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', } }, ALLOWED_HOSTS=[ 'testserver', ], INSTALLED_APPS=[ 'django_nose', 'permissions', 'permissions.tests', ], MIDDLEWARE_CLASSES=[], ROOT_URLCONF='permissions.tests.urls', TEST_RUNNER='django_nose.NoseTestSuiteRunner' ) if django.VERSION[:2] >= (1, 7): from django import setup else: setup = lambda: None setup() call_command("test")
Add MIDDLEWARE_CLASSES to test settings
Add MIDDLEWARE_CLASSES to test settings Squelches a warning when using Django 1.7.
Python
mit
PSU-OIT-ARC/django-perms,wylee/django-perms
eba6e117c0a13b49219bb60e773f896b274b6601
tests/_support/configs/collection.py
tests/_support/configs/collection.py
from spec import eq_ from invoke import ctask, Collection @ctask def collection(c): c.run('false') # Ensures a kaboom if mocking fails ns = Collection(collection) ns.configure({'run': {'echo': True}})
from spec import eq_ from invoke import ctask, Collection @ctask def go(c): c.run('false') # Ensures a kaboom if mocking fails ns = Collection(go) ns.configure({'run': {'echo': True}})
Fix test fixture to match earlier test change
Fix test fixture to match earlier test change
Python
bsd-2-clause
singingwolfboy/invoke,kejbaly2/invoke,tyewang/invoke,frol/invoke,mattrobenolt/invoke,mkusz/invoke,pfmoore/invoke,mkusz/invoke,pyinvoke/invoke,kejbaly2/invoke,pfmoore/invoke,sophacles/invoke,frol/invoke,pyinvoke/invoke,mattrobenolt/invoke
c31c54624d7a46dfd9df96e32d2e07246868aecc
tomviz/python/DefaultITKTransform.py
tomviz/python/DefaultITKTransform.py
def transform_scalars(dataset): """Define this method for Python operators that transform the input array.""" from tomviz import utils import numpy as np import itk # Get the current volume as a numpy array. array = utils.get_array(dataset) # Set up some ITK variables itk_image_type = itk.Image.F3 itk_converter = itk.PyBuffer[itk_image_type] # Read the image into ITK itk_image = itk_converter.GetImageFromArray(array) # ITK filter (I have no idea if this is right) filter = \ itk.ConfidenceConnectedImageFilter[itk_image_type,itk.Image.SS3].New() filter.SetInitialNeighborhoodRadius(3) filter.SetMultiplier(3) filter.SetNumberOfIterations(25) filter.SetReplaceValue(255) filter.SetSeed((24,65,37)) filter.SetInput(itk_image) filter.Update() # Get the image back from ITK (result is a numpy image) result = itk.PyBuffer[itk.Image.SS3].GetArrayFromImage(filter.GetOutput()) # This is where the transformed data is set, it will display in tomviz. utils.set_array(dataset, result)
import tomviz.operators class DefaultITKTransform(tomviz.operators.CancelableOperator): def transform_scalars(self, dataset): """Define this method for Python operators that transform the input array. This example uses an ITK filter to add 10 to each voxel value.""" # Try imports to make sure we have everything that is needed try: from tomviz import itkutils import itk except Exception as exc: print("Could not import necessary module(s)") raise exc self.progress.value = 0 self.progress.maximum = 100 # Add a try/except around the ITK portion. ITK exceptions are # passed up to the Python layer, so we can at least report what # went wrong with the script, e.g., unsupported image type. try: self.progress.value = 0 self.progress.message = "Converting data to ITK image" # Get the ITK image itk_image = itkutils.convert_vtk_to_itk_image(dataset) itk_input_image_type = type(itk_image) self.progress.value = 30 self.progress.message = "Running filter" # ITK filter filter = itk.AddImageFilter[itk_input_image_type, # Input 1 itk_input_image_type, # Input 2 itk_input_image_type].New() # Output filter.SetInput1(itk_image) filter.SetConstant2(10) itkutils.observe_filter_progress(self, filter, 30, 70) try: filter.Update() except RuntimeError: # Exception thrown when ITK filter is aborted return self.progress.message = "Saving results" itkutils.set_array_from_itk_image(dataset, filter.GetOutput()) self.progress.value = 100 except Exception as exc: print("Problem encountered while running %s" % self.__class__.__name__) raise exc
Change the ITK example to use a simpler ITK filter
Change the ITK example to use a simpler ITK filter
Python
bsd-3-clause
cjh1/tomviz,cryos/tomviz,mathturtle/tomviz,OpenChemistry/tomviz,cjh1/tomviz,thewtex/tomviz,thewtex/tomviz,cryos/tomviz,mathturtle/tomviz,thewtex/tomviz,cjh1/tomviz,cryos/tomviz,OpenChemistry/tomviz,OpenChemistry/tomviz,OpenChemistry/tomviz,mathturtle/tomviz
8d8b122ecbb306bb53de4ee350104e7627e8b362
app/app/__init__.py
app/app/__init__.py
import os from pyramid.config import Configurator from sqlalchemy import engine_from_config from .models import DBSession, Base def main(global_config, **settings): '''This function returns a Pyramid WSGI application.''' settings['sqlalchemy.url'] = os.environ.get('DATABASE_URL') engine = engine_from_config(settings, 'sqlalchemy.') DBSession.configure(bind=engine) Base.metadata.bind = engine config = Configurator(settings=settings) config.include('pyramid_jinja2') config.add_static_view('static', 'static', cache_max_age=3600) config.add_route('index', '/') config.add_route('request_scene', '/request/{scene_id}') config.add_route('done', '/done') config.add_route('scene_status', '/scene/{scene_id}') config.add_route('ajax', '/ajax') config.scan() return config.make_wsgi_app()
import os from pyramid.config import Configurator from sqlalchemy import engine_from_config from .models import DBSession, Base def main(global_config, **settings): '''This function returns a Pyramid WSGI application.''' settings['sqlalchemy.url'] = os.environ.get('DATABASE_URL') engine = engine_from_config(settings, 'sqlalchemy.') DBSession.configure(bind=engine) Base.metadata.bind = engine config = Configurator(settings=settings) config.include('pyramid_jinja2') config.add_static_view('static', 'static', cache_max_age=3600) config.add_route('index', '/') config.add_route('request_scene', '/request/{scene_id}') config.add_route('request_preview', '/request_p/{scene_id}') config.add_route('done', '/done') config.add_route('scene_status', '/scene/{scene_id}') config.add_route('ajax', '/ajax') config.scan() return config.make_wsgi_app()
Add route for preview request
Add route for preview request
Python
mit
recombinators/snapsat,recombinators/snapsat,recombinators/snapsat
49367b2077c1ba6e09e10c05653d0dfc0164b1b7
programmingtheorems/python/theorem_of_summary.py
programmingtheorems/python/theorem_of_summary.py
#! /usr/bin/env python # Copyright Lajos Katona # # 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. def summary(start=1, end=10): result = 0 for i in range(start, end): result += i return result if __name__ == '__main__': print(summary(1, 15))
#! /usr/bin/env python # Copyright Lajos Katona # # 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. def summary(start=1, end=10): result = 0 for i in range(start, end): result += i return result if __name__ == '__main__': print(summary(1, 15))
Fix pep8 problem, extra new line after header
Fix pep8 problem, extra new line after header Change-Id: I6503a000202d321300c5f3cea708d18cf228e77d
Python
apache-2.0
elajkat/hugradexam,elajkat/hugradexam
4a1c1361f154c3deb1d575b1e0c69acca7827b17
dojango/__init__.py
dojango/__init__.py
VERSION = (0, 5, 6, 'final', 0) def get_version(): version = '%s.%s' % (VERSION[0], VERSION[1]) if VERSION[2]: version = '%s.%s' % (version, VERSION[2]) if VERSION[3:] == ('alpha', 0): version = '%s pre-alpha' % version else: if VERSION[3] != 'final': version = '%s %s %s' % (version, VERSION[3], VERSION[4]) #from django.utils.version import get_svn_revision #svn_rev = get_svn_revision() #if svn_rev != u'SVN-unknown': # version = "%s %s" % (version, svn_rev) return version
VERSION = (0, 5, 7, 'alpha', 0) def get_version(): version = '%s.%s' % (VERSION[0], VERSION[1]) if VERSION[2]: version = '%s.%s' % (version, VERSION[2]) if VERSION[3:] == ('alpha', 0): version = '%s pre-alpha' % version else: if VERSION[3] != 'final': version = '%s %s %s' % (version, VERSION[3], VERSION[4]) #from django.utils.version import get_svn_revision #svn_rev = get_svn_revision() #if svn_rev != u'SVN-unknown': # version = "%s %s" % (version, svn_rev) return version
Mark dojango as 0.5.7 alpha
Mark dojango as 0.5.7 alpha
Python
bsd-3-clause
william-gr/dojango,william-gr/dojango,ricard33/dojango,ricard33/dojango,klipstein/dojango,ofirr/dojango,ofirr/dojango,klipstein/dojango,ricard33/dojango,william-gr/dojango,ofirr/dojango
0654d962918327e5143fb9250ad344de26e284eb
electrumx_server.py
electrumx_server.py
#!/usr/bin/env python3 # # Copyright (c) 2016, Neil Booth # # All rights reserved. # # See the file "LICENCE" for information about the copyright # and warranty status of this software. '''Script to kick off the server.''' import logging import traceback from server.env import Env from server.controller import Controller def main(): '''Set up logging and run the server.''' logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)-9s %(message)-100s ' '%(name)s [%(filename)s:%(lineno)d]') logging.info('ElectrumX server starting') try: controller = Controller(Env()) controller.run() except Exception: traceback.print_exc() logging.critical('ElectrumX server terminated abnormally') else: logging.info('ElectrumX server terminated normally') if __name__ == '__main__': main()
#!/usr/bin/env python3 # # Copyright (c) 2016, Neil Booth # # All rights reserved. # # See the file "LICENCE" for information about the copyright # and warranty status of this software. '''Script to kick off the server.''' import logging import traceback from server.env import Env from server.controller import Controller def main(): '''Set up logging and run the server.''' logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)-7s %(message)-100s ' '[%(filename)s:%(lineno)d]') logging.info('ElectrumX server starting') try: controller = Controller(Env()) controller.run() except Exception: traceback.print_exc() logging.critical('ElectrumX server terminated abnormally') else: logging.info('ElectrumX server terminated normally') if __name__ == '__main__': main()
Remove logger name from logs
Remove logger name from logs
Python
mit
thelazier/electrumx,shsmith/electrumx,shsmith/electrumx,erasmospunk/electrumx,erasmospunk/electrumx,thelazier/electrumx
94264880688f5e2f8dbf098108bb05c2c244048d
froide_campaign/listeners.py
froide_campaign/listeners.py
from .models import Campaign, InformationObject def connect_info_object(sender, **kwargs): reference = kwargs.get('reference') if not reference: return if not reference.startswith('campaign:'): return namespace, campaign_value = reference.split(':', 1) try: campaign, slug = campaign_value.split('@', 1) except (ValueError, IndexError): return try: campaign_pk = int(campaign) except ValueError: return try: campaign = Campaign.objects.get(pk=campaign_pk) except Campaign.DoesNotExist: return try: kwargs = { 'pk': int(slug) } except ValueError: kwargs = {'slug': slug} try: iobj = InformationObject.objects.get(campaign=campaign, **kwargs) except InformationObject.DoesNotExist: return if iobj.foirequest is not None: return if iobj.publicbody != sender.public_body: return if not sender.public: return iobj.foirequest = sender iobj.save()
from .models import Campaign, InformationObject def connect_info_object(sender, **kwargs): reference = kwargs.get('reference') if not reference: return if not reference.startswith('campaign:'): return namespace, campaign_value = reference.split(':', 1) try: campaign, slug = campaign_value.split('@', 1) except (ValueError, IndexError): return try: campaign_pk = int(campaign) except ValueError: return try: campaign = Campaign.objects.get(pk=campaign_pk) except Campaign.DoesNotExist: return try: kwargs = { 'pk': int(slug) } except ValueError: kwargs = {'slug': slug} try: iobj = InformationObject.objects.get(campaign=campaign, **kwargs) except InformationObject.DoesNotExist: return if iobj.publicbody != sender.public_body: return if not sender.public: return if iobj.foirequest is None: iobj.foirequest = sender iobj.foirequests.add(sender) iobj.save()
Save request in new m2m filed
Save request in new m2m filed
Python
mit
okfde/froide-campaign,okfde/froide-campaign,okfde/froide-campaign
a910cd19890ef02a08aeb05c8ba450b2c59f0352
monitoring/nagios/plugin/__init__.py
monitoring/nagios/plugin/__init__.py
from monitoring.nagios.plugin.base import NagiosPlugin from monitoring.nagios.plugin.snmp import NagiosPluginSNMP from monitoring.nagios.plugin.secureshell import NagiosPluginSSH from monitoring.nagios.plugin.database import NagiosPluginMSSQL from monitoring.nagios.plugin.wmi import NagiosPluginWMI
from monitoring.nagios.plugin.base import NagiosPlugin from monitoring.nagios.plugin.snmp import NagiosPluginSNMP from monitoring.nagios.plugin.secureshell import NagiosPluginSSH from monitoring.nagios.plugin.database import NagiosPluginMSSQL from monitoring.nagios.plugin.wmi import NagiosPluginWMI from monitoring.nagios.plugin.http import NagiosPluginHTTP
Make NagiosPluginHTTP available from monitoring.nagios.plugin package.
Make NagiosPluginHTTP available from monitoring.nagios.plugin package.
Python
mit
bigbrozer/monitoring.nagios,bigbrozer/monitoring.nagios
f794c6ed1f6be231d79ac35759ad76270c3e14e0
brains/mapping/admin.py
brains/mapping/admin.py
from django.contrib import admin from mapping.models import Location, Report class LocationAdmin(admin.ModelAdmin): fieldsets = ((None, {'fields': ( ('name', 'suburb'), ('x', 'y'), 'building_type' )} ),) list_display = ['name', 'x', 'y', 'suburb'] list_filter = ['suburb'] search_fields = ['name'] readonly_fields = ['x', 'y', 'name', 'building_type', 'suburb'] actions = None def has_add_permission(self, request): return False class ReportAdmin(admin.ModelAdmin): fieldsets = ((None, {'fields': ('location', ('zombies_only', 'inside'), ('is_ruined', 'is_illuminated', 'has_tree'), ('zombies_present', 'barricade_level'), 'players', ('reported_by', 'origin', 'reported_date') )} ),) readonly_fields = ['players', 'reported_date'] admin.site.register(Location, LocationAdmin) admin.site.register(Report, ReportAdmin)
from django.contrib import admin from mapping.models import Location, Report class LocationAdmin(admin.ModelAdmin): fieldsets = ((None, {'fields': ( ('name', 'suburb'), ('x', 'y'), 'building_type' )} ),) list_display = ['name', 'x', 'y', 'suburb'] list_filter = ['suburb'] search_fields = ['name'] readonly_fields = ['x', 'y', 'name', 'building_type', 'suburb'] actions = None def has_add_permission(self, request): return False class ReportAdmin(admin.ModelAdmin): fieldsets = ((None, {'fields': ('location', ('zombies_only', 'inside'), ('is_ruined', 'is_illuminated', 'has_tree'), ('zombies_present', 'barricade_level'), 'players', ('reported_by', 'origin'), 'reported_date', )} ),) readonly_fields = ['location', 'zombies_only', 'inside', 'is_ruined', 'is_illuminated', 'has_tree', 'zombies_present', 'barricade_level', 'players', 'reported_by', 'origin', 'reported_date'] admin.site.register(Location, LocationAdmin) admin.site.register(Report, ReportAdmin)
Set everything on the report read only.
Set everything on the report read only.
Python
bsd-3-clause
crisisking/udbraaains,crisisking/udbraaains,crisisking/udbraaains,crisisking/udbraaains
e76bd7de6a0eb7f46e9e5ce3cdaec44943b848d2
pagseguro/configs.py
pagseguro/configs.py
# coding: utf-8 class Config(object): BASE_URL = "https://ws.pagseguro.uol.com.br" VERSION = "/v2/" CHECKOUT_SUFFIX = VERSION + "checkout" NOTIFICATION_SUFFIX = VERSION + "transactions/notifications/%s" TRANSACTION_SUFFIX = VERSION + "transactions/" CHECKOUT_URL = BASE_URL + CHECKOUT_SUFFIX NOTIFICATION_URL = BASE_URL + NOTIFICATION_SUFFIX TRANSACTION_URL = BASE_URL + TRANSACTION_SUFFIX CURRENCY = "BRL" HEADERS = { "Content-Type": "application/x-www-form-urlencoded; charset=ISO-8859-1" } REFERENCE_PREFIX = "REF%s" PAYMENT_HOST = "https://pagseguro.uol.com.br" PAYMENT_URL = PAYMENT_HOST + CHECKOUT_SUFFIX + "/payment.html?code=%s" DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%S'
# coding: utf-8 class Config(object): BASE_URL = "https://ws.pagseguro.uol.com.br" VERSION = "/v2/" CHECKOUT_SUFFIX = VERSION + "checkout" CHARSET = "UTF-8" # ISO-8859-1 NOTIFICATION_SUFFIX = VERSION + "transactions/notifications/%s" TRANSACTION_SUFFIX = VERSION + "transactions/" CHECKOUT_URL = BASE_URL + CHECKOUT_SUFFIX NOTIFICATION_URL = BASE_URL + NOTIFICATION_SUFFIX TRANSACTION_URL = BASE_URL + TRANSACTION_SUFFIX CURRENCY = "BRL" HEADERS = { "Content-Type": "application/x-www-form-urlencoded; charset={}".format(CHARSET) } REFERENCE_PREFIX = "REF%s" PAYMENT_HOST = "https://pagseguro.uol.com.br" PAYMENT_URL = PAYMENT_HOST + CHECKOUT_SUFFIX + "/payment.html?code=%s" DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%S'
Fix charset default to UTF-8
Fix charset default to UTF-8
Python
mit
vintasoftware/python-pagseguro,rochacbruno/python-pagseguro,rgcarrasqueira/python-pagseguro
08461a2f61b5a5981a6da9f6ef91a362eed92bfd
pycroft/__init__.py
pycroft/__init__.py
# -*- coding: utf-8 -*- # Copyright (c) 2014 The Pycroft Authors. See the AUTHORS file. # This file is part of the Pycroft project and licensed under the terms of # the Apache License, Version 2.0. See the LICENSE file for details. """ pycroft ~~~~~~~~~~~~~~ This package contains everything. :copyright: (c) 2011 by AG DSN. """ import json, collections, pkgutil class Config(object): def __init__(self): self._config_data = None self._package = "pycroft" self._resource = "config.json" def load(self): data = (pkgutil.get_data(self._package, self._resource) or pkgutil.get_data(self._package, self._resource+".default")) if data is None: raise Exception( "Could not load config file {1} " "from package {0}".format(self._package, self._resource) ) self._config_data = json.loads(data) if not isinstance(self._config_data, collections.Mapping): raise Exception("Config must be a JSON object!") def __getitem__(self, key): if self._config_data is None: self.load() return self._config_data[key] def __setitem__(self, key, value): raise Exception("It is not possible to set configuration entries!") config = Config()
# -*- coding: utf-8 -*- # Copyright (c) 2014 The Pycroft Authors. See the AUTHORS file. # This file is part of the Pycroft project and licensed under the terms of # the Apache License, Version 2.0. See the LICENSE file for details. """ pycroft ~~~~~~~~~~~~~~ This package contains everything. :copyright: (c) 2011 by AG DSN. """ import json, collections, pkgutil class Config(object): def __init__(self): self._config_data = None self._package = "pycroft" self._resource = "config.json" def load(self): data = None try: data = pkgutil.get_data(self._package, self._resource) except IOError: data = pkgutil.get_data(self._package, self._resource+".default") if data is None: raise Exception( "Could not load config file {1} " "from package {0}".format(self._package, self._resource) ) self._config_data = json.loads(data) if not isinstance(self._config_data, collections.Mapping): raise Exception("Config must be a JSON object!") def __getitem__(self, key): if self._config_data is None: self.load() return self._config_data[key] def __setitem__(self, key, value): raise Exception("It is not possible to set configuration entries!") config = Config()
Fix config loader (bug in commit:5bdf6e47 / commit:eefe7561)
Fix config loader (bug in commit:5bdf6e47 / commit:eefe7561)
Python
apache-2.0
lukasjuhrich/pycroft,agdsn/pycroft,agdsn/pycroft,lukasjuhrich/pycroft,agdsn/pycroft,lukasjuhrich/pycroft,lukasjuhrich/pycroft,agdsn/pycroft,agdsn/pycroft
92595871f908aa22d353a2490f851da23f3d1f64
gitcd/Config/FilePersonal.py
gitcd/Config/FilePersonal.py
import os import yaml from gitcd.Config.Parser import Parser from gitcd.Config.DefaultsPersonal import DefaultsPersonal class FilePersonal: loaded = False filename = ".gitcd-personal" parser = Parser() defaults = DefaultsPersonal() config = False def setFilename(self, configFilename: str): self.filename = configFilename def load(self): if not os.path.isfile(self.filename): self.config = self.defaults.load() else: self.config = self.parser.load(self.filename) def write(self): self.parser.write(self.filename, self.config) def getToken(self): return self.config['token'] def setToken(self, token): self.config['token'] = token
import os import yaml from gitcd.Config.Parser import Parser from gitcd.Config.DefaultsPersonal import DefaultsPersonal class FilePersonal: loaded = False filename = ".gitcd-personal" parser = Parser() defaults = DefaultsPersonal() config = False def setFilename(self, configFilename: str): self.filename = configFilename def load(self): if not os.path.isfile(self.filename): self.config = self.defaults.load() else: self.config = self.parser.load(self.filename) def write(self): self.parser.write(self.filename, self.config) # add .gitcd-personal to .gitignore gitignore = ".gitignore" if not os.path.isfile(gitignore): gitignoreContent = self.filename else: with open(gitignore, "r") as gitignoreFile: gitignoreContent = gitignoreFile.read() # if not yet in gitignore if "\n%s\n" % (self.filename) not in gitignoreContent: # add it gitignoreContent = "%s\n%s\n" % (gitignoreContent, self.filename) with open(gitignore, "w") as gitignoreFile: gitignoreFile.write(gitignoreContent) def getToken(self): return self.config['token'] def setToken(self, token): self.config['token'] = token
Add .gitcd-personal to .gitignore automaticly
Add .gitcd-personal to .gitignore automaticly
Python
apache-2.0
claudio-walser/gitcd,claudio-walser/gitcd
4dd86439d4c8393ac9c3bb6b958a1c8cb45b243a
gitfs/views/history_index.py
gitfs/views/history_index.py
from .view import View class HistoryIndexView(View): pass
from .view import View from errno import ENOENT from stat import S_IFDIR from gitfs import FuseMethodNotImplemented, FuseOSError from log import log class HistoryIndexView(View): def getattr(self, path, fh=None): ''' Returns a dictionary with keys identical to the stat C structure of stat(2). st_atime, st_mtime and st_ctime should be floats. NOTE: There is an incombatibility between Linux and Mac OS X concerning st_nlink of directories. Mac OS X counts all files inside the directory, while Linux counts only the subdirectories. ''' if path != '/': raise FuseOSError(ENOENT) return dict(st_mode=(S_IFDIR | 0755), st_nlink=2) def opendir(self, path): return 0 def releasedir(self, path, fi): pass def access(self, path, amode): log.info('%s %s', path, amode) return 0 def readdir(self, path, fh): return ['.', '..', 'commits everywhere']
Add mandatory methods to HistoryIndexView (refactor when working)
Add mandatory methods to HistoryIndexView (refactor when working)
Python
apache-2.0
PressLabs/gitfs,ksmaheshkumar/gitfs,rowhit/gitfs,PressLabs/gitfs,bussiere/gitfs
26353ac1c70c1bf47d6f33a0ab8880ec0fb1a002
examples/effects.py
examples/effects.py
import zounds from zounds.spectral import time_stretch, pitch_shift from zounds.ui import AppSettings import argparse sr = zounds.SR11025() BaseModel = zounds.stft(resample_to=sr, store_resampled=True) @zounds.simple_in_memory_settings class Sound(BaseModel): pass if __name__ == '__main__': parser = argparse.ArgumentParser(parents=[ AppSettings() ]) parser.add_argument( '--sound-uri', default='https://archive.org/download/LucaBrasi2/06-Kevin_Gates-Out_The_Mud_Prod_By_The_Runners_The_Monarch.ogg') args = parser.parse_args() _id = Sound.process(meta=args.sound_uri) snd = Sound(_id) original = snd.resampled slow = zounds.AudioSamples(time_stretch(original, 0.75).squeeze(), sr) fast = zounds.AudioSamples(time_stretch(original, 1.25).squeeze(), sr) higher = zounds.AudioSamples( pitch_shift(original[:zounds.Seconds(10)], 1.0).squeeze(), sr) lower = zounds.AudioSamples( pitch_shift(original[:zounds.Seconds(10)], -1.0).squeeze(), sr) app = zounds.ZoundsApp( model=Sound, visualization_feature=Sound.fft, audio_feature=Sound.resampled, globals=globals(), locals=locals(), secret=args.app_secret) app.start(args.port)
Add an example of phase vocoder based time stretch and pitch shift capabilities
Add an example of phase vocoder based time stretch and pitch shift capabilities
Python
mit
JohnVinyard/zounds,JohnVinyard/zounds,JohnVinyard/zounds,JohnVinyard/zounds
36da7bdc8402494b5ef3588289739e1696ad6002
docs/_ext/djangodummy/settings.py
docs/_ext/djangodummy/settings.py
# Settings file to allow parsing API documentation of Django modules, # and provide defaults to use in the documentation. # # This file is placed in a subdirectory, # so the docs root won't be detected by find_packages() # Display sane URLs in the docs: STATIC_URL = '/static/'
# Settings file to allow parsing API documentation of Django modules, # and provide defaults to use in the documentation. # # This file is placed in a subdirectory, # so the docs root won't be detected by find_packages() # Display sane URLs in the docs: STATIC_URL = '/static/' # Avoid error for missing the secret key SECRET_KEY = 'docs'
Fix autodoc support with Django 1.5
Fix autodoc support with Django 1.5
Python
apache-2.0
django-fluent/django-fluent-contents,ixc/django-fluent-contents,pombredanne/django-fluent-contents,django-fluent/django-fluent-contents,ixc/django-fluent-contents,pombredanne/django-fluent-contents,jpotterm/django-fluent-contents,edoburu/django-fluent-contents,edoburu/django-fluent-contents,jpotterm/django-fluent-contents,jpotterm/django-fluent-contents,edoburu/django-fluent-contents,django-fluent/django-fluent-contents,ixc/django-fluent-contents,pombredanne/django-fluent-contents
9cefd4d933590dcea28cf221e6c5706c81cac882
invocations/testing.py
invocations/testing.py
from invoke import ctask as task @task def test(ctx, module=None, runner='spec'): """ Run a Spec or Nose-powered internal test suite. Say ``--module=foo``/``-m foo`` to just run ``tests/foo.py``. Defaults to running the ``spec`` tool; may override by saying e.g. ``runner='nosetests'``. """ # Allow selecting specific submodule specific_module = " --tests=tests/%s.py" % module args = (specific_module if module else "") # Use pty so the spec/nose/Python process buffers "correctly" ctx.run(runner + args, pty=True)
from invoke import ctask as task @task(help={ 'module': "Just runs tests/STRING.py.", 'runner': "Use STRING to run tests instead of 'spec'." }) def test(ctx, module=None, runner='spec'): """ Run a Spec or Nose-powered internal test suite. """ # Allow selecting specific submodule specific_module = " --tests=tests/%s.py" % module args = (specific_module if module else "") # Use pty so the spec/nose/Python process buffers "correctly" ctx.run(runner + args, pty=True)
Move docstring arg bits into per-arg help
Move docstring arg bits into per-arg help
Python
bsd-2-clause
mrjmad/invocations,singingwolfboy/invocations,pyinvoke/invocations,alex/invocations
9aeece4a5e3e7e987a709a128509cc0d8dc11e9d
tests/conftest.py
tests/conftest.py
import mock import pytest from scrapi import settings settings.DEBUG = True settings.CELERY_ALWAYS_EAGER = True settings.CELERY_EAGER_PROPAGATES_EXCEPTIONS = True @pytest.fixture(autouse=True) def harvester(monkeypatch): import_mock = mock.MagicMock() harvester_mock = mock.MagicMock() import_mock.return_value = harvester_mock monkeypatch.setattr('scrapi.tasks.import_harvester', import_mock) monkeypatch.setattr('scrapi.util.import_harvester', import_mock) return harvester_mock @pytest.fixture(autouse=True) def timestamp_patch(monkeypatch): monkeypatch.setattr('scrapi.util.timestamp', lambda: 'TIME') monkeypatch.setattr('scrapi.tasks.timestamp', lambda: 'TIME')
import mock import pytest from scrapi import settings from scrapi import database database._manager = database.DatabaseManager(keyspace='test') settings.DEBUG = True settings.CELERY_ALWAYS_EAGER = True settings.CELERY_EAGER_PROPAGATES_EXCEPTIONS = True @pytest.fixture(autouse=True) def harvester(monkeypatch): import_mock = mock.MagicMock() harvester_mock = mock.MagicMock() import_mock.return_value = harvester_mock monkeypatch.setattr('scrapi.util.import_harvester', import_mock) monkeypatch.setattr('scrapi.tasks.import_harvester', import_mock) return harvester_mock @pytest.fixture(autouse=True) def timestamp_patch(monkeypatch): monkeypatch.setattr('scrapi.util.timestamp', lambda: 'TIME') monkeypatch.setattr('scrapi.tasks.timestamp', lambda: 'TIME') def pytest_configure(config): config.addinivalue_line( 'markers', 'cassandra: Handles setup and teardown for tests using cassandra' ) def pytest_runtest_setup(item): marker = item.get_marker('cassandra') if marker is not None: if not database.setup(): pytest.skip('No connection to Cassandra') def pytest_runtest_teardown(item, nextitem): marker = item.get_marker('cassandra') if marker is not None: database.tear_down(force=True)
Add pytest markers for cassandra tests
Add pytest markers for cassandra tests
Python
apache-2.0
icereval/scrapi,alexgarciac/scrapi,jeffreyliu3230/scrapi,erinspace/scrapi,fabianvf/scrapi,felliott/scrapi,ostwald/scrapi,fabianvf/scrapi,felliott/scrapi,mehanig/scrapi,erinspace/scrapi,CenterForOpenScience/scrapi,mehanig/scrapi,CenterForOpenScience/scrapi
00b5599e574740680e6c08884510ad605294fad2
tests/conftest.py
tests/conftest.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Shared fixtures for :mod:`pytest`.""" from __future__ import print_function, absolute_import import os import pytest # noqa import gryaml from py2neo_compat import py2neo_ver @pytest.fixture def graphdb(): """Fixture connecting to graphdb.""" if 'NEO4J_URI' not in os.environ: pytest.skip('Need NEO4J_URI environment variable set') graphdb = gryaml.connect(uri=os.environ['NEO4J_URI']) graphdb.cypher.execute('MATCH (n) DETACH DELETE n') return graphdb @pytest.yield_fixture def graphdb_offline(): """Ensure the database is not connected.""" if py2neo_ver < 2: pytest.skip('Offline not supported in py2neo < 2') neo4j_uri_env = os.environ.get('NEO4J_URI', None) if neo4j_uri_env: del os.environ['NEO4J_URI'] old_graphdb = gryaml._py2neo.graphdb gryaml._py2neo.graphdb = None yield gryaml._py2neo.graphdb = old_graphdb if neo4j_uri_env: os.environ['NEO4J_URI'] = neo4j_uri_env
#!/usr/bin/env python # -*- coding: utf-8 -*- """Shared fixtures for :mod:`pytest`.""" from __future__ import print_function, absolute_import import os import pytest # noqa import gryaml from py2neo_compat import py2neo_ver @pytest.fixture def graphdb(): """Fixture connecting to graphdb.""" if 'NEO4J_URI' not in os.environ: pytest.skip('Need NEO4J_URI environment variable set') graphdb = gryaml.connect(uri=os.environ['NEO4J_URI']) graphdb.delete_all() return graphdb @pytest.yield_fixture def graphdb_offline(): """Ensure the database is not connected.""" if py2neo_ver < 2: pytest.skip('Offline not supported in py2neo < 2') neo4j_uri_env = os.environ.get('NEO4J_URI', None) if neo4j_uri_env: del os.environ['NEO4J_URI'] old_graphdb = gryaml._py2neo.graphdb gryaml._py2neo.graphdb = None yield gryaml._py2neo.graphdb = old_graphdb if neo4j_uri_env: os.environ['NEO4J_URI'] = neo4j_uri_env
Use `delete_all` instead of running cypher query
Use `delete_all` instead of running cypher query
Python
mit
wcooley/python-gryaml
0d1ab7106e438b418b575c4e0f6c22797158358a
tests/settings.py
tests/settings.py
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'test.db', } } INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'tests', )
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'test.db', } } INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'tests', ) SECRET_KEY = 'abc123'
Add required SECRET_KEY setting for Django 1.5+
Add required SECRET_KEY setting for Django 1.5+
Python
bsd-2-clause
bruth/django-preserialize,scottp-dpaw/django-preserialize
99f8fc1ec43aa7a1b96b2d8446a77111dbc61195
tests/test_cli.py
tests/test_cli.py
from mdformat._cli import run def test_no_files_passed(): assert run(()) == 0
from mdformat._cli import run def test_no_files_passed(): assert run(()) == 0 def test_format(tmp_path): unformatted_markdown = "\n\n# A header\n\n" formatted_markdown = "# A header\n" file_path = tmp_path / "test_markdown.md" file_path.write_text(unformatted_markdown) assert run((str(file_path),)) == 0 assert file_path.read_text() == formatted_markdown
Add a test for formatting with cli
Add a test for formatting with cli
Python
mit
executablebooks/mdformat
af3dd1da24754e32c8a75165ab90d5178e68a548
integrations/mailer/setup.py
integrations/mailer/setup.py
#!/usr/bin/env python import setuptools version = '3.3.0' setuptools.setup( name="alerta-mailer", version=version, description='Send emails from Alerta', url='https://github.com/alerta/alerta-contrib', license='MIT', author='Nick Satterly', author_email='[email protected]', py_modules=['mailer'], data_files=[('.', ['email.tmpl', 'email.html.tmpl'])], install_requires=[ 'alerta', 'kombu', 'redis', 'jinja2' ], include_package_data=True, zip_safe=False, entry_points={ 'console_scripts': [ 'alerta-mailer = mailer:main' ] }, keywords="alerta monitoring mailer sendmail smtp", classifiers=[ 'Topic :: System :: Monitoring', ] )
#!/usr/bin/env python import setuptools version = '3.3.1' setuptools.setup( name="alerta-mailer", version=version, description='Send emails from Alerta', url='https://github.com/alerta/alerta-contrib', license='MIT', author='Nick Satterly', author_email='[email protected]', py_modules=['mailer'], data_files=[('.', ['email.tmpl', 'email.html.tmpl'])], install_requires=[ 'alerta', 'kombu', 'redis', 'jinja2' ], include_package_data=True, zip_safe=False, entry_points={ 'console_scripts': [ 'alerta-mailer = mailer:main' ] }, keywords="alerta monitoring mailer sendmail smtp", classifiers=[ 'Topic :: System :: Monitoring', ] )
Increase the version number due this bugfix
Increase the version number due this bugfix
Python
mit
msupino/alerta-contrib,msupino/alerta-contrib,alerta/alerta-contrib,alerta/alerta-contrib,alerta/alerta-contrib
76087634d8c165657b35074e54ae7a8ee71f6f75
tests/test_xorshift_rand.py
tests/test_xorshift_rand.py
# Copyright 2014 Anonymous7 from Reddit, Julian Andrews # # This software may be modified and distributed under the terms # of the MIT license. See the LICENSE file for details. from __future__ import absolute_import, division import collections import unittest import eval7.xorshift_rand class XorshiftRandTestCase(unittest.TestCase): SAMPLE_COUNT = 10000000 BINS = 1000 DELTA = 450 def check_uniform(self, counter): expected_count = self.SAMPLE_COUNT / self.BINS self.assertEqual(set(range(self.BINS)), set(counter.keys())) for count in counter.values(): self.assertAlmostEqual( count, expected_count, delta=self.DELTA ) def test_random_is_uniform(self): sample = ( eval7.xorshift_rand.random() for i in range(self.SAMPLE_COUNT) ) counter = collections.Counter(int(num * self.BINS) for num in sample) self.check_uniform(counter) def test_randint_is_uniform(self): sample = ( eval7.xorshift_rand.randint(self.BINS) for i in range(self.SAMPLE_COUNT) ) self.check_uniform(collections.Counter(sample))
# Copyright 2014 Anonymous7 from Reddit, Julian Andrews # # This software may be modified and distributed under the terms # of the MIT license. See the LICENSE file for details. from __future__ import absolute_import, division import collections import unittest import eval7.xorshift_rand class XorshiftRandTestCase(unittest.TestCase): SAMPLE_COUNT = 1000000 BINS = 1000 DELTA = 125 def check_uniform(self, counter): expected_count = self.SAMPLE_COUNT / self.BINS self.assertEqual(set(range(self.BINS)), set(counter.keys())) for count in counter.values(): self.assertAlmostEqual( count, expected_count, delta=self.DELTA ) def test_random_is_uniform(self): sample = ( eval7.xorshift_rand.random() for i in range(self.SAMPLE_COUNT) ) counter = collections.Counter(int(num * self.BINS) for num in sample) self.check_uniform(counter) def test_randint_is_uniform(self): sample = ( eval7.xorshift_rand.randint(self.BINS) for i in range(self.SAMPLE_COUNT) ) self.check_uniform(collections.Counter(sample))
Reduce sample count for xorshift_rand tests
Reduce sample count for xorshift_rand tests
Python
mit
JulianAndrews/pyeval7,JulianAndrews/pyeval7
e4fde66624f74c4b0bbfae7c7c11a50884a0a73c
pyfr/readers/base.py
pyfr/readers/base.py
# -*- coding: utf-8 -*- from abc import ABCMeta, abstractmethod import uuid class BaseReader(object, metaclass=ABCMeta): @abstractmethod def __init__(self): pass @abstractmethod def _to_raw_pyfrm(self): pass def to_pyfrm(self): mesh = self._to_raw_pyfrm() # Add metadata mesh['mesh_uuid'] = str(uuid.uuid4()) return mesh
# -*- coding: utf-8 -*- from abc import ABCMeta, abstractmethod import uuid import numpy as np class BaseReader(object, metaclass=ABCMeta): @abstractmethod def __init__(self): pass @abstractmethod def _to_raw_pyfrm(self): pass def to_pyfrm(self): mesh = self._to_raw_pyfrm() # Add metadata mesh['mesh_uuid'] = np.array(str(uuid.uuid4()), dtype='S') return mesh
Fix the HDF5 type of mesh_uuid for imported meshes.
Fix the HDF5 type of mesh_uuid for imported meshes.
Python
bsd-3-clause
BrianVermeire/PyFR,Aerojspark/PyFR
7e448e9267c375195f3fcd5c80ed9e602cce0c91
genes/posix/commands.py
genes/posix/commands.py
from genes.process.commands import get_env_run from .traits import only_posix run = get_env_run() @only_posix() def chmod(*args): # FIXME: this is ugly, name the args run(['chmod'] + list(*args))
from genes.process.commands import get_env_run from .traits import only_posix run = get_env_run() @only_posix() def chmod(*args): # FIXME: this is ugly, name the args run(['chmod'] + list(args))
Fix args to list. Args is a tuple, list takes a tuple
Fix args to list. Args is a tuple, list takes a tuple
Python
mit
hatchery/genepool,hatchery/Genepool2
0af3f7ddd1912d18d502ca1795c596397d9cd495
python/triple-sum.py
python/triple-sum.py
# A special triplet is defined as: a <= b <= c for # a in list_a, b in list_b, and c in list_c def get_num_special_triplets(list_a, list_b, list_c): num_special_triplets = 0 for b in list_b: len_a_candidates = len([a for a in list_a if a <= b]) len_c_candidates = len([c for c in list_c if c <= b]) num_special_triplets += 1 * len_a_candidates * len_c_candidates return num_special_triplets if __name__ == '__main__': _ = input().split() list_a = list(set(map(int, input().rstrip().split()))) list_b = list(set(map(int, input().rstrip().split()))) list_c = list(set(map(int, input().rstrip().split()))) num_special_triplets = get_num_special_triplets(list_a, list_b, list_c) print(num_special_triplets)
# A special triplet is defined as: a <= b <= c for # a in list_a, b in list_b, and c in list_c def get_num_special_triplets(list_a, list_b, list_c): # remove duplicates and sort lists list_a = sorted(set(list_a)) list_b = sorted(set(list_b)) list_c = sorted(set(list_c)) num_special_triplets = 0 for b in list_b: len_a_candidates = num_elements_less_than(b, list_a) len_c_candidates = num_elements_less_than(b, list_c) num_special_triplets += 1 * len_a_candidates * len_c_candidates return num_special_triplets def num_elements_less_than(target, sorted_list): for index, candidate in enumerate(sorted_list): if candidate > target: return index return len(sorted_list) if __name__ == '__main__': _ = input().split() list_a = list(map(int, input().rstrip().split())) list_b = list(map(int, input().rstrip().split())) list_c = list(map(int, input().rstrip().split())) num_special_triplets = get_num_special_triplets(list_a, list_b, list_c) print(num_special_triplets)
Sort lists prior to computing len of candidates
Sort lists prior to computing len of candidates
Python
mit
rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank
90cbe055e9f0722de7619fbd777a10e2b95d63b3
tests/constants_test.py
tests/constants_test.py
import unittest from mtglib.constants import base_url, card_flags class DescribeConstants(unittest.TestCase): def should_have_base_url(self): url = ('http://gatherer.wizards.com/Pages/Search/Default.aspx' '?output=standard&action=advanced&') assert base_url == url def should_have_card_flags(self): assert card_flags == ['text', 'color', 'subtype', 'type', 'set', 'cmc', 'power', 'tough', 'rarity', 'name', 'block']
import unittest from nose.tools import eq_ from mtglib.constants import base_url, card_flags class DescribeConstants(unittest.TestCase): def should_have_base_url(self): url = ('http://gatherer.wizards.com/Pages/Search/Default.aspx' '?output=standard&action=advanced&') eq_(base_url, url) def should_have_card_flags(self): eq_(card_flags, ['text', 'color', 'subtype', 'type', 'set', 'cmc', 'power', 'tough', 'rarity', 'name', 'block'])
Use helper function for testing equality.
Use helper function for testing equality.
Python
mit
chigby/mtg,chigby/mtg
2daee974533d1510a17280cddb5a4dfc147338fa
tests/level/test_map.py
tests/level/test_map.py
import unittest from hunting.level.map import LevelTile, LevelMap class TestPathfinding(unittest.TestCase): def test_basic_diagonal(self): level_map = LevelMap() level_map.set_map([[LevelTile() for _ in range(0, 5)] for _ in range(0, 5)]) self.assertEqual([(1, 1), (2, 2), (3, 3), (4, 4)], level_map.a_star_path(0, 0, 4, 4)) def test_paths_around_wall(self): level_map = LevelMap() level_map.set_map([[LevelTile() for _ in range(0, 3)] for _ in range(0, 5)]) for x in range(1, 5): level_map[x][1].blocks = True self.assertEqual([(3, 0), (2, 0), (1, 0), (0, 1), (1, 2), (2, 2), (3, 2), (4, 2)], level_map.a_star_path(4, 0, 4, 2))
import unittest from hunting.level.map import LevelTile, LevelMap class TestPathfinding(unittest.TestCase): def test_basic_diagonal(self): level_map = LevelMap([[LevelTile() for _ in range(0, 5)] for _ in range(0, 5)]) self.assertEqual([(1, 1), (2, 2), (3, 3), (4, 4)], level_map.a_star_path(0, 0, 4, 4)) def test_paths_around_wall(self): level_map = LevelMap([[LevelTile() for _ in range(0, 3)] for _ in range(0, 5)]) for x in range(1, 5): level_map[x][1].blocks = True self.assertEqual([(3, 0), (2, 0), (1, 0), (0, 1), (1, 2), (2, 2), (3, 2), (4, 2)], level_map.a_star_path(4, 0, 4, 2)) def tests_force_pathable_endpoint_parameter(self): level_map = LevelMap([[LevelTile(False, False)], [LevelTile(True, True)]]) self.assertEqual([(1, 0)], level_map.a_star_path(0, 0, 1, 0, True)) self.assertEqual([], level_map.a_star_path(0, 0, 1, 0, False))
Add test for force_pathable_endpoint pathfind param
Add test for force_pathable_endpoint pathfind param This parameter is intended to allow pathing to adjacent squares of an unpassable square. This is necessary because if you want to pathfind to a monster which blocks a square, you don't want to actually go *onto* the square, you just want to go next to it, presumably so you can hit it.
Python
mit
MoyTW/RL_Arena_Experiment
822cc689ce44b1c43ac118b2a13c6d0024d2e194
tests/raw_text_tests.py
tests/raw_text_tests.py
from nose.tools import istest, assert_equal from mammoth.raw_text import extract_raw_text_from_element from mammoth import documents @istest def raw_text_of_text_element_is_value(): assert_equal("Hello", extract_raw_text_from_element(documents.Text("Hello"))) @istest def raw_text_of_paragraph_is_terminated_with_newlines(): paragraph = documents.paragraph(children=[documents.Text("Hello")]) assert_equal("Hello\n\n", extract_raw_text_from_element(paragraph)) @istest def non_text_element_without_children_has_no_raw_text(): tab = documents.Tab() assert not hasattr(tab, "children") assert_equal("", extract_raw_text_from_element(documents.Tab()))
from nose.tools import istest, assert_equal from mammoth.raw_text import extract_raw_text_from_element from mammoth import documents @istest def text_element_is_converted_to_text_content(): element = documents.Text("Hello.") result = extract_raw_text_from_element(element) assert_equal("Hello.", result) @istest def paragraphs_are_terminated_with_newlines(): element = documents.paragraph( children=[ documents.Text("Hello "), documents.Text("world."), ], ) result = extract_raw_text_from_element(element) assert_equal("Hello world.\n\n", result) @istest def children_are_recursively_converted_to_text(): element = documents.document([ documents.paragraph( [ documents.text("Hello "), documents.text("world.") ], {} ) ]) result = extract_raw_text_from_element(element) assert_equal("Hello world.\n\n", result) @istest def non_text_element_without_children_is_converted_to_empty_string(): element = documents.line_break assert not hasattr(element, "children") result = extract_raw_text_from_element(element) assert_equal("", result)
Make raw text tests consistent with mammoth.js
Make raw text tests consistent with mammoth.js
Python
bsd-2-clause
mwilliamson/python-mammoth
fd5387f1bb8ac99ed421c61fdff777316a4d3191
tests/test_publisher.py
tests/test_publisher.py
import pytest import pika from mettle.settings import get_settings from mettle.publisher import publish_event def test_long_routing_key(): settings = get_settings() conn = pika.BlockingConnection(pika.URLParameters(settings.rabbit_url)) chan = conn.channel() exchange = settings['state_exchange'] chan.exchange_declare(exchange=exchange, type='topic', durable=True) with pytest.raises(ValueError): publish_event(chan, exchange, dict( description=None, tablename='a' * 8000, name="foo", pipeline_names=None, id=15, updated_by='vagrant', ))
import pytest import pika from mettle.settings import get_settings from mettle.publisher import publish_event @pytest.mark.xfail(reason="Need RabbitMQ fixture") def test_long_routing_key(): settings = get_settings() conn = pika.BlockingConnection(pika.URLParameters(settings.rabbit_url)) chan = conn.channel() exchange = settings['state_exchange'] chan.exchange_declare(exchange=exchange, type='topic', durable=True) with pytest.raises(ValueError): publish_event(chan, exchange, dict( description=None, tablename='a' * 8000, name="foo", pipeline_names=None, id=15, updated_by='vagrant', ))
Mark test as xfail so that releases can be cut
Mark test as xfail so that releases can be cut
Python
mit
yougov/mettle,yougov/mettle,yougov/mettle,yougov/mettle
53636a17cd50d704b7b4563d0b23a474677051f4
hub/prototype/config.py
hub/prototype/config.py
# put this into ~/.alphahub/config.py and make sure it's # not readable by anyone else (it contains passwords!) # the host we run on and want to receive packets on; note # that "localhost" is probably the wrong thing here, you # want your actual host name here so the sockets bind the # right way and receive packets from the outside HOST = "the.hub.machine.tld" # the servers we listen to; for now each server can just # have one port and secret key on the hub even if it runs # multiple game servers; not sure if we need to allow more # than that yet :-/ SERVERS = { "some.game.server.tld": (42, "somesecret"), } # the other hubs we echo to; note that we don't yet change # the packets in any way, so they'll look like they really # come from us; not good, but we'll need to define a new # packet format for forwarded userinfo strings first, then # we can fix this :-/ HUBS = { "some.hub.server.tld": (84, "anothersecret"), }
# put this into ~/.alphahub/config.py and make sure it's # not readable by anyone else (it contains passwords!) # the host we run on and want to receive packets on; note # that "localhost" is probably the wrong thing here, you # want your actual host name here so the sockets bind the # right way and receive packets from the outside HOST = "the.hub.machine.tld" # the servers we listen to; for now each server can just # have one port and secret key on the hub even if it runs # multiple game servers; not sure if we need to allow more # than that yet :-/ SERVERS = { "some.game.server.tld": (42, "somesecret"), "some.other.game.tld": (543, "monkeyspam"), } # the other hubs we echo to; note that we don't yet change # the packets in any way, so they'll look like they really # come from us; not good, but we'll need to define a new # packet format for forwarded userinfo strings first, then # we can fix this :-/ HUBS = { "some.hub.server.tld": (84, "anothersecret"), }
Make sure we give an example for two servers.
Make sure we give an example for two servers.
Python
agpl-3.0
madprof/alpha-hub
d185407ac4caf5648ef4c12eab83fec81c307407
tests/test_trackable.py
tests/test_trackable.py
# -*- coding: utf-8 -*- """ test_trackable ~~~~~~~~~~~~~~ Trackable tests """ import pytest from utils import authenticate, logout pytestmark = pytest.mark.trackable() def test_trackable_flag(app, client): e = '[email protected]' authenticate(client, email=e) logout(client) authenticate(client, email=e) with app.app_context(): user = app.security.datastore.find_user(email=e) assert user.last_login_at is not None assert user.current_login_at is not None assert user.last_login_ip == 'untrackable' assert user.current_login_ip == 'untrackable' assert user.login_count == 2
# -*- coding: utf-8 -*- """ test_trackable ~~~~~~~~~~~~~~ Trackable tests """ import pytest from utils import authenticate, logout pytestmark = pytest.mark.trackable() def test_trackable_flag(app, client): e = '[email protected]' authenticate(client, email=e) logout(client) authenticate(client, email=e, headers={'X-Forwarded-For': '127.0.0.1'}) with app.app_context(): user = app.security.datastore.find_user(email=e) assert user.last_login_at is not None assert user.current_login_at is not None assert user.last_login_ip == 'untrackable' assert user.current_login_ip == '127.0.0.1' assert user.login_count == 2
Add mock X-Forwarded-For header in trackable tests
Add mock X-Forwarded-For header in trackable tests
Python
mit
pawl/flask-security,reustle/flask-security,jonafato/flask-security,asmodehn/flask-security,quokkaproject/flask-security,LeonhardPrintz/flask-security-fork,dommert/flask-security,LeonhardPrintz/flask-security-fork,fuhrysteve/flask-security,CodeSolid/flask-security,simright/flask-security,inveniosoftware/flask-security-fork,x5a/flask-security,mafrosis/flask-security,Samael500/flask-security,dlakata/flask-security,inveniosoftware/flask-security-fork,fuhrysteve/flask-security,inveniosoftware/flask-security-fork,redpandalabs/flask-security,fmerges/flask-security,wjt/flask-security,CodeSolid/flask-security,yingbo/flask-security,asmodehn/flask-security,reustle/flask-security,felix1m/flask-security,themylogin/flask-security,a-pertsev/flask-security,GregoryVigoTorres/flask-security,x5a/flask-security,quokkaproject/flask-security,tatataufik/flask-security,Samael500/flask-security,jonafato/flask-security,mik3cap/private-flask-security,a-pertsev/flask-security,guoqiao/flask-security,themylogin/flask-security,LeonhardPrintz/flask-security-fork,GregoryVigoTorres/flask-security,dommert/flask-security,fmerges/flask-security,yingbo/flask-security,mik3cap/private-flask-security,pawl/flask-security,simright/flask-security,nfvs/flask-security,tatataufik/flask-security,dlakata/flask-security,felix1m/flask-security,covertgeek/flask-security,mafrosis/flask-security,wjt/flask-security,covertgeek/flask-security,mattupstate/flask-security,redpandalabs/flask-security,guoqiao/flask-security,mattupstate/flask-security,nfvs/flask-security
3bd9214465547ff6cd0f7ed94edf8dacf10135b5
registration/backends/simple/urls.py
registration/backends/simple/urls.py
""" URLconf for registration and activation, using django-registration's one-step backend. If the default behavior of these views is acceptable to you, simply use a line like this in your root URLconf to set up the default URLs for registration:: (r'^accounts/', include('registration.backends.simple.urls')), This will also automatically set up the views in ``django.contrib.auth`` at sensible default locations. If you'd like to customize registration behavior, feel free to set up your own URL patterns for these views instead. """ from django.conf.urls import include, url from django.views.generic.base import TemplateView from registration.backends.simple.views import RegistrationView urlpatterns = [ url(r'^register/$', RegistrationView.as_view(), name='registration_register'), url(r'^register/closed/$', TemplateView.as_view( template_name='registration/registration_closed.html'), name='registration_disallowed'), url(r'', include('registration.auth_urls')), ]
""" URLconf for registration and activation, using django-registration's one-step backend. If the default behavior of these views is acceptable to you, simply use a line like this in your root URLconf to set up the default URLs for registration:: (r'^accounts/', include('registration.backends.simple.urls')), This will also automatically set up the views in ``django.contrib.auth`` at sensible default locations. If you'd like to customize registration behavior, feel free to set up your own URL patterns for these views instead. """ from django.conf.urls import include, url from django.views.generic.base import TemplateView from .views import RegistrationView urlpatterns = [ url(r'^register/$', RegistrationView.as_view(), name='registration_register'), url(r'^register/closed/$', TemplateView.as_view( template_name='registration/registration_closed.html'), name='registration_disallowed'), url(r'', include('registration.auth_urls')), ]
Clean up an import in simple backend URLs.
Clean up an import in simple backend URLs.
Python
bsd-3-clause
dirtycoder/django-registration,ubernostrum/django-registration,myimages/django-registration,tdruez/django-registration,awakeup/django-registration
d2eb124651862d61f28519a5d9dc0ab1a0133fb7
remotecv/result_store/redis_store.py
remotecv/result_store/redis_store.py
from redis import Redis from remotecv.result_store import BaseStore from remotecv.utils import logger class ResultStore(BaseStore): WEEK = 604800 redis_instance = None def __init__(self, config): super(ResultStore, self).__init__(config) if not ResultStore.redis_instance: ResultStore.redis_instance = Redis( host=config.redis_host, port=config.redis_port, db=config.redis_database, password=config.redis_password, ) self.storage = ResultStore.redis_instance def store(self, key, points): result = self.serialize(points) logger.debug("Points found: %s", result) redis_key = "thumbor-detector-%s" % key self.storage.setex(redis_key, result, 2 * self.WEEK)
from redis import Redis from remotecv.result_store import BaseStore from remotecv.utils import logger class ResultStore(BaseStore): WEEK = 604800 redis_instance = None def __init__(self, config): super(ResultStore, self).__init__(config) if not ResultStore.redis_instance: ResultStore.redis_instance = Redis( host=config.redis_host, port=config.redis_port, db=config.redis_database, password=config.redis_password, ) self.storage = ResultStore.redis_instance def store(self, key, points): result = self.serialize(points) logger.debug("Points found: %s", result) redis_key = "thumbor-detector-%s" % key self.storage.setex( name=redis_key, value=result, time=2 * self.WEEK, )
Make compatible with py-redis 3.x
Make compatible with py-redis 3.x Fixes https://github.com/thumbor/remotecv/issues/25
Python
mit
thumbor/remotecv
73ce10193c497fdffee178ab877d173287417047
climlab/__init__.py
climlab/__init__.py
__version__ = '0.4.0' # This list defines all the modules that will be loaded if a user invokes # from climLab import * # totally out of date! #__all__ = ["constants", "thermo", "orbital_table", # "long_orbital_table", "insolation", "ebm", # "column", "convadj"] #from climlab import radiation # this should ensure that we can still import constants.py as climlab.constants from climlab.utils import constants from climlab.utils import thermo, legendre # some more useful shorcuts #from climlab.model import ebm, column from climlab.model.column import GreyRadiationModel, RadiativeConvectiveModel, BandRCModel from climlab.model.ebm import EBM, EBM_annual, EBM_seasonal from climlab.domain import domain from climlab.domain.field import Field, global_mean from climlab.domain.axis import Axis from climlab.domain.initial import column_state, surface_state from climlab.process.process import Process, process_like, get_axes from climlab.process.time_dependent_process import TimeDependentProcess from climlab.process.implicit import ImplicitProcess from climlab.process.diagnostic import DiagnosticProcess from climlab.process.energy_budget import EnergyBudget
__version__ = '0.4.1dev' # This list defines all the modules that will be loaded if a user invokes # from climLab import * # totally out of date! #__all__ = ["constants", "thermo", "orbital_table", # "long_orbital_table", "insolation", "ebm", # "column", "convadj"] #from climlab import radiation # this should ensure that we can still import constants.py as climlab.constants from climlab.utils import constants from climlab.utils import thermo, legendre # some more useful shorcuts #from climlab.model import ebm, column from climlab.model.column import GreyRadiationModel, RadiativeConvectiveModel, BandRCModel from climlab.model.ebm import EBM, EBM_annual, EBM_seasonal from climlab.domain import domain from climlab.domain.field import Field, global_mean from climlab.domain.axis import Axis from climlab.domain.initial import column_state, surface_state from climlab.process.process import Process, process_like, get_axes from climlab.process.time_dependent_process import TimeDependentProcess from climlab.process.implicit import ImplicitProcess from climlab.process.diagnostic import DiagnosticProcess from climlab.process.energy_budget import EnergyBudget
Increment version number to 0.4.1dev
Increment version number to 0.4.1dev
Python
mit
brian-rose/climlab,brian-rose/climlab,cjcardinale/climlab,cjcardinale/climlab,cjcardinale/climlab
4dfbe6ea079b32644c9086351f911ce1a2b2b0e1
easy_maps/geocode.py
easy_maps/geocode.py
# -*- coding: utf-8 -*- from __future__ import absolute_import from django.utils.encoding import smart_str from geopy import geocoders from geopy.exc import GeocoderServiceError class Error(Exception): pass def google_v3(address): """ Given an address, return ``(computed_address, (latitude, longitude))`` tuple using Google Geocoding API v3. """ try: g = geocoders.GoogleV3() address = smart_str(address) return g.geocode(address, exactly_one=False)[0] except (UnboundLocalError, ValueError, GeocoderServiceError) as e: raise Error(e)
# -*- coding: utf-8 -*- from __future__ import absolute_import from django.utils.encoding import smart_str from geopy import geocoders from geopy.exc import GeocoderServiceError class Error(Exception): pass def google_v3(address): """ Given an address, return ``(computed_address, (latitude, longitude))`` tuple using Google Geocoding API v3. """ try: g = geocoders.GoogleV3() address = smart_str(address) results = g.geocode(address, exactly_one=False) if results is not None: return results[0] raise Error('No results found') except (UnboundLocalError, ValueError, GeocoderServiceError) as e: raise Error(e)
Resolve the 500 error when google send a no results info
Resolve the 500 error when google send a no results info
Python
mit
duixteam/django-easy-maps,kmike/django-easy-maps,Gonzasestopal/django-easy-maps,kmike/django-easy-maps,bashu/django-easy-maps,bashu/django-easy-maps,Gonzasestopal/django-easy-maps
47dc3c9af512b89525048564f32e71b012ed2f19
elevator/__init__.py
elevator/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- __title__ = "Elevator" __author__ = "Oleiade" __license__ = "BSD" from client import Elevator
Update : bind client Elevator class to package root
Update : bind client Elevator class to package root
Python
mit
oleiade/Elevator
7c6f1bfca63ea0db8e07156b5122d0986b9cd1a5
backend/breach/tests/test_sniffer.py
backend/breach/tests/test_sniffer.py
from mock import patch from django.test import TestCase from breach.sniffer import Sniffer class SnifferTest(TestCase): def setUp(self): self.endpoint = 'http://localhost' self.sniffer = Sniffer(self.endpoint, '147.102.239.229', 'dionyziz.com', 'wlan0', '8080') @patch('breach.sniffer.requests') def test_sniffer_start(self, requests): self.sniffer.start() self.assertTrue(requests.post.called) @patch('breach.sniffer.requests') def test_sniffer_read(self, requests): self.sniffer.read() self.assertTrue(requests.get.called) @patch('breach.sniffer.requests') def test_sniffer_delete(self, requests): self.sniffer.delete() self.assertTrue(requests.post.called)
from mock import patch from django.test import TestCase from breach.sniffer import Sniffer class SnifferTest(TestCase): def setUp(self): self.endpoint = 'http://localhost' sniffer_params = { 'snifferendpoint': self.endpoint, 'sourceip': '147.102.239.229', 'host': 'dionyziz.com', 'interface': 'wlan0', 'port': '8080', 'calibration_wait': 0.0 } self.sniffer = Sniffer(sniffer_params) @patch('breach.sniffer.requests') def test_sniffer_start(self, requests): self.sniffer.start() self.assertTrue(requests.post.called) @patch('breach.sniffer.requests') def test_sniffer_read(self, requests): self.sniffer.read() self.assertTrue(requests.get.called) @patch('breach.sniffer.requests') def test_sniffer_delete(self, requests): self.sniffer.delete() self.assertTrue(requests.post.called)
Update sniffer tests with new argument passing
Update sniffer tests with new argument passing
Python
mit
dimkarakostas/rupture,dionyziz/rupture,esarafianou/rupture,dionyziz/rupture,esarafianou/rupture,dimkarakostas/rupture,dimriou/rupture,dimriou/rupture,dimriou/rupture,dionyziz/rupture,esarafianou/rupture,dionyziz/rupture,dimkarakostas/rupture,dimkarakostas/rupture,dimriou/rupture,dionyziz/rupture,dimriou/rupture,esarafianou/rupture,dimkarakostas/rupture
34e17142f565cfc27c15522212c4240944cb4001
sauce/lib/helpers.py
sauce/lib/helpers.py
# -*- coding: utf-8 -*- """WebHelpers used in SAUCE. @author: moschlar """ from tg import url as tgurl from webhelpers import date, feedgenerator, html, number, misc, text import re, textwrap #log = logging.getLogger(__name__) # shortcut for links link_to = html.tags.link_to def link(label, url='', **attrs): return link_to(label, tgurl(url), **attrs) def strftimedelta(delta, format='%D Days %hh:%mm:%ss'): '''Return a string representing the timedelta element. Possible format codes are: %D days %h hours %hh hours with leading zero %m minutes %mm minutes with leading zero %s seconds %ss seconds with leading zero ''' totalSeconds = delta.seconds hours, remainder = divmod(totalSeconds, 3600) minutes, seconds = divmod(remainder, 60) result = format.replace('%D', str(delta.days)).\ replace('%hh', '%02d' % hours).replace('%mm', '%02d' % minutes).\ replace('%ss', '%02d' % seconds).\ replace('%h', str(hours)).replace('%m', str(minutes)).\ replace('%s', str(seconds)) return result def striphtml(text): return re.sub('<[^<]+?>', ' ', text).strip() def cut(text, max=200): if len(text) < max: return text else: return textwrap.wrap(text, max)[0] + ' ...'
# -*- coding: utf-8 -*- """WebHelpers used in SAUCE. @author: moschlar """ from datetime import datetime from tg import url as tgurl #from webhelpers import date, feedgenerator, html, number, misc, text import webhelpers as w from webhelpers.html.tags import link_to from webhelpers.text import truncate from webhelpers.date import distance_of_time_in_words import re #log = logging.getLogger(__name__) cut = lambda text, max=200: truncate(text, max, whole_word=True) strftimedelta = lambda delta, granularity='minute': distance_of_time_in_words(datetime.now(), datetime.now()+delta, granularity) def link(label, url='', **attrs): return link_to(label, tgurl(url), **attrs) def striphtml(text): return re.sub('<[^<]+?>', ' ', text).strip()
Replace my own helper functions with webhelper ones
Replace my own helper functions with webhelper ones
Python
agpl-3.0
moschlar/SAUCE,moschlar/SAUCE,moschlar/SAUCE,moschlar/SAUCE
c12f040fe9b0bbc3e47aed8f942de04216251f51
importer/loaders.py
importer/loaders.py
import xlrd import os base_loader_error = 'The Loader class can only be used by extending it.' excel_extensions = [ '.xls', '.xlsx', ] class Loader(object): def __init__(self, file_info, autoload=True): self.filename = file_info.path if autoload is True: return self.open() def open(self): raise NotImplementedError(base_loader_error) def close(self): pass @classmethod def sniff(cls, file_info): raise NotImplementedError(base_loader_error) class ExcelLoader(Loader): supports_sheets = True type_name = 'excel' def open(self): self.backend = xlrd.open_workbook(self.filename) self.sheet_names = self.backend.sheet_names() self.sheet_count = len(self.sheet_names) def sheet_by_name(self, name): """ Returns a sheet based on it's name. """ return self.backend.sheet_by_name(name) def close(self): self.backend.release_resources() @classmethod def sniff(cls, file_info): # TODO: Find a way to really sniff the file. return os.path.splitext(file_info.path)[-1] in excel_extensions # TODO: Finish Loader for importing from CSV data. class CSVLoader(Loader): supports_sheets = False
from django.conf import settings import xlrd import os base_loader_error = 'The Loader class can only be used by extending it.' extensions = getattr( settings, 'IMPORTER_EXTENSIONS', { 'excel': ('.xls', '.xlsx'), } ) class Loader(object): def __init__(self, file_info, autoload=True): self.filename = file_info.path if autoload is True: return self.open() def open(self): raise NotImplementedError(base_loader_error) def close(self): pass @classmethod def sniff(cls, file_info): raise NotImplementedError(base_loader_error) class ExcelLoader(Loader): supports_sheets = True type_name = 'excel' def open(self): self.backend = xlrd.open_workbook(self.filename) self.sheet_names = self.backend.sheet_names() self.sheet_count = len(self.sheet_names) def sheet_by_name(self, name): """ Returns a sheet based on it's name. """ return self.backend.sheet_by_name(name) def close(self): self.backend.release_resources() @classmethod def sniff(cls, file_info): # TODO: Find a way to really sniff the file. if not 'excel' in extensions: return False return os.path.splitext(file_info.path)[-1] in extensions['excel'] # TODO: Finish Loader for importing from CSV data. class CSVLoader(Loader): supports_sheets = False
Allow configuration of extensions for types.
Allow configuration of extensions for types.
Python
mit
monokrome/django-drift
25993238cb18212a2b83b2d6b0aa98939d38f192
scripts/lwtnn-split-keras-network.py
scripts/lwtnn-split-keras-network.py
#!/usr/bin/env python3 """ Convert a keras model, saved with model.save(...) to a weights and architecture component. """ import argparse def get_args(): d = '(default: %(default)s)' parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('model') parser.add_argument('-w','--weight-file-name', default='weights.h5', help=d) parser.add_argument('-a', '--architecture-file-name', default='architecture.json', help=d) return parser.parse_args() def run(): args = get_args() import keras m = keras.models.load_model(args.model) m.save_weights(args.weight_file_name) with open(args.architecture_file_name,'w') as arch: arch.write(m.to_json(indent=2)) if __name__ == '__main__': run()
#!/usr/bin/env python3 """ Convert a keras model, saved with model.save(...) to a weights and architecture component. """ import argparse def get_args(): d = '(default: %(default)s)' parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('model') parser.add_argument('-w','--weight-file-name', default='weights.h5', help=d) parser.add_argument('-a', '--architecture-file-name', default='architecture.json', help=d) return parser.parse_args() def run(): args = get_args() from h5py import File import json m = File(args.model,'r') with File(args.weight_file_name,'w') as w: for name, wt in w.items(): w.copy(wt, name) arch = json.loads(m.attrs['model_config']) with open(args.architecture_file_name,'w') as arch_file: arch_file.write(json.dumps(arch,indent=2)) if __name__ == '__main__': run()
Remove Keras from network splitter
Remove Keras from network splitter Keras isn't as stable as h5py and json. This commit removes the keras dependency from the network splitting function.
Python
mit
lwtnn/lwtnn,lwtnn/lwtnn,lwtnn/lwtnn
dfeb82974768e96efc4cba1388ac4bf098d3fbf4
UM/Qt/Bindings/MeshFileHandlerProxy.py
UM/Qt/Bindings/MeshFileHandlerProxy.py
from PyQt5.QtCore import QObject, pyqtSlot, pyqtProperty, pyqtSignal from UM.Application import Application from UM.Logger import Logger class MeshFileHandlerProxy(QObject): def __init__(self, parent = None): super().__init__(parent) self._mesh_handler = Application.getInstance().getMeshFileHandler() @pyqtProperty("QStringList", constant=True) def supportedReadFileTypes(self): fileTypes = [] fileTypes.append("All Supported Files (*{0})(*{0})".format(' *'.join(self._mesh_handler.getSupportedFileTypesRead()))) for ext in self._mesh_handler.getSupportedFileTypesRead(): fileTypes.append("{0} file (*.{0})(*.{0})".format(ext[1:])) fileTypes.append("All Files (*.*)(*)") return fileTypes @pyqtProperty("QStringList", constant=True) def supportedWriteFileTypes(self): return self._mesh_handler.getSupportedFileTypesWrite() def createMeshFileHandlerProxy(engine, scriptEngine): return MeshFileHandlerProxy()
from PyQt5.QtCore import QObject, pyqtSlot, pyqtProperty, pyqtSignal from UM.Application import Application from UM.Logger import Logger class MeshFileHandlerProxy(QObject): def __init__(self, parent = None): super().__init__(parent) self._mesh_handler = Application.getInstance().getMeshFileHandler() @pyqtProperty("QStringList", constant=True) def supportedReadFileTypes(self): file_types = [] all_types = [] for ext, desc in self._mesh_handler.getSupportedFileTypesRead().items(): file_types.append("{0} (*.{1})(*.{1})".format(desc, ext)) all_types.append("*.{0}".format(ext)) file_types.sort() file_types.insert(0, "All Supported Types ({0})({0})".format(" ".join(all_types))) file_types.append("All Files (*.*)(*)") return file_types @pyqtProperty("QStringList", constant=True) def supportedWriteFileTypes(self): #TODO: Implement return [] def createMeshFileHandlerProxy(engine, script_engine): return MeshFileHandlerProxy()
Update the supported file types list exposed to QML to use the new dict correctly
Update the supported file types list exposed to QML to use the new dict correctly
Python
agpl-3.0
onitake/Uranium,onitake/Uranium
3916efe4a017fe9e0fb1c5fe09b99f374d7a4060
instana/__init__.py
instana/__init__.py
""" Instana sensor and tracer. It consists of two modules that can be used as entry points: - sensor: activates the meter to collect and transmit all kind of built-in metrics - tracer: OpenTracing tracer implementation. It implicitly activates the meter """ __author__ = 'Instana Inc.' __copyright__ = 'Copyright 2016 Instana Inc.' __credits__ = ['Pavlo Baron'] __license__ = 'MIT' __version__ = '0.0.1' __maintainer__ = 'Pavlo Baron' __email__ = '[email protected]' __all__ = ['sensor', 'tracer']
""" Instana sensor and tracer. It consists of two modules that can be used as entry points: - sensor: activates the meter to collect and transmit all kind of built-in metrics - tracer: OpenTracing tracer implementation. It implicitly activates the meter """ __author__ = 'Instana Inc.' __copyright__ = 'Copyright 2017 Instana Inc.' __credits__ = ['Pavlo Baron', 'Peter Giacomo Lombardo'] __license__ = 'MIT' __version__ = '0.6.6' __maintainer__ = 'Peter Giacomo Lombardo' __email__ = '[email protected]' __all__ = ['sensor', 'tracer']
Update module init file; begin version stamping here.
Update module init file; begin version stamping here.
Python
mit
instana/python-sensor,instana/python-sensor
67fd73f8f035ac0e13a64971d9d54662df46a77f
karm/test/__karmutil.py
karm/test/__karmutil.py
import sys import os def dcopid(): '''Get dcop id of karm. Fail if more than one instance running.''' id = stdin = stdout = None try: ( stdin, stdout ) = os.popen2( "dcop" ) l = stdout.readline() while l: if l.startswith( "karm" ): if not id: id = l else: raise "Only one instance of karm may be running." l = stdout.readline() if not id: raise "No karm instance found. Try running dcop at command-line to verify it works." except: if stdin: stdin.close() if stdout: stdout.close() print sys.exc_info()[0] sys.exit(1) stdin.close() stdout.close() # strip trailing newline return id.strip() def test( goal, actual ): '''Raise exception if goal != actual.''' if goal != actual: path, scriptname = os.path.split( sys.argv[0] ) raise "%s: expected '%s', got '%s'" % ( scriptname, goal, actual )
import sys import os class KarmTestError( Exception ): pass def dcopid(): '''Get dcop id of karm. Fail if more than one instance running.''' id = stdin = stdout = None ( stdin, stdout ) = os.popen2( "dcop" ) l = stdout.readline() while l: if l.startswith( "karm" ): if not id: id = l else: raise KarmTestError( "Only one instance of karm may be running." ) l = stdout.readline() if not id: raise KarmTestError( "No karm instance found. Try running dcop at command-line to verify it works." ) stdin.close() stdout.close() # strip trailing newline return id.strip() def test( goal, actual ): '''Raise exception if goal != actual.''' if goal != actual: path, scriptname = os.path.split( sys.argv[0] ) raise KarmTestError( "%s: expected '%s', got '%s'" % ( scriptname, goal, actual ) )
Add KarmTestError we can distinguish and print full tracebacks for unexpected errors. Delete exception trapping--let the test scripts do that.
Add KarmTestError we can distinguish and print full tracebacks for unexpected errors. Delete exception trapping--let the test scripts do that. svn path=/trunk/kdepim/; revision=367066
Python
lgpl-2.1
lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi
f71676ab56e3f1b5a8fb1283cf08f5a170ee5bf2
web/zoohackathon2016/report/models.py
web/zoohackathon2016/report/models.py
from __future__ import unicode_literals from django.db import models from model_utils import Choices class Report(models.Model): """Store report information""" REPORT_TYPES = Choices( ('A', 'Shop/Market'), ('B', 'Restaraunt/Eatery'), ('C', 'Live Animal Display'), ('D', 'Poaching'), ('E', 'Other'), ) latitude = models.DecimalField(max_digits=9, decimal_places=6) longitude = models.DecimalField(max_digits=9, decimal_places=6) event_time = models.DateTimeField() arrival_time = models.DateTimeField(auto_now_add=True) modified_time = models.DateTimeField(auto_now=True) report_type = models.CharField(max_length=2, choices=REPORT_TYPES) device_id = models.CharField(max_length=50) def __unicode__(self): return u"({0}, {1}) {2}".format(self.latitude, self.longitude, self.get_report_type_display())
from __future__ import unicode_literals from django.db import models from model_utils import Choices class Report(models.Model): """Store report information""" REPORT_TYPES = Choices( ('A', 'Shop/Market'), ('B', 'Restaurant/Eatery'), ('C', 'Live Animal Display'), ('D', 'Poaching'), ('E', 'Other'), ) latitude = models.DecimalField(max_digits=9, decimal_places=6) longitude = models.DecimalField(max_digits=9, decimal_places=6) event_time = models.DateTimeField() arrival_time = models.DateTimeField(auto_now_add=True) modified_time = models.DateTimeField(auto_now=True) report_type = models.CharField(max_length=2, choices=REPORT_TYPES) device_id = models.CharField(max_length=50) def __unicode__(self): return u"({0}, {1}) {2}".format(self.latitude, self.longitude, self.get_report_type_display())
Fix spelling of Restaurant in web backend
Fix spelling of Restaurant in web backend
Python
apache-2.0
gmuthetatau/zoohackathon2016,gmuthetatau/zoohackathon2016,gmuthetatau/zoohackathon2016
3698f0a51056f32c7595c1baca578d25764cc768
cnddh/config_prd.py
cnddh/config_prd.py
AMBIENTE = u'linux' PROD = False DEBUG = False LOG = False LOGPATH = './Application.log' EMAIL_HOST = 'smtp.gmail.com' EMAIL_LOGIN = '[email protected]' EMAIL_PASSWORD = 'senha' EMAIL_PORT = 587 DATABASE_URI = 'mysql://root:senha@localhost/cnddh_db' ECHO = False UPLOADS_DEFAULT_DEST = r'C:\Temp\upload' TIMEZONE = 'America/Sao_Paulo' LOCALE = 'pt_BR'
AMBIENTE = u'linux' PROD = False DEBUG = False LOG = False LOGPATH = './Application.log' EMAIL_HOST = 'smtp.gmail.com' EMAIL_LOGIN = '[email protected]' EMAIL_PASSWORD = 'senha' EMAIL_PORT = 587 DATABASE_URI = 'mysql://root:senha@localhost/cnddh_db' ECHO = False SQLALCHEMY_TRACK_MODIFICATIONS = False UPLOADS_DEFAULT_DEST = r'C:\Temp\upload' TIMEZONE = 'America/Sao_Paulo' LOCALE = 'pt_BR'
Add some key in config
Add some key in config
Python
apache-2.0
dedeco/cnddh-denuncias,dedeco/cnddh-denuncias,dedeco/cnddh-denuncias
85ca0da68126da149438199a83fddf2befa18eea
src/psd_tools2/psd/color_mode_data.py
src/psd_tools2/psd/color_mode_data.py
""" Color mode data structure. """ from __future__ import absolute_import, unicode_literals import attr import logging from psd_tools2.psd.base import ValueElement from psd_tools2.utils import ( read_length_block, write_length_block, write_bytes ) logger = logging.getLogger(__name__) class ColorModeData(ValueElement): """ Color mode data section of the PSD file. For indexed color images the data is the color table for the image in a non-interleaved order. Duotone images also have this data, but the data format is undocumented. """ @classmethod def read(cls, fp): """Read the element from a file-like object. :param fp: file-like object :rtype: ColorModeData """ value = read_length_block(fp) logger.debug('reading color mode data, len=%d' % (len(value))) # TODO: Parse color table. return cls(value) def write(self, fp): """Write the element to a file-like object. :param fp: file-like object """ def writer(f): return write_bytes(f, self.value) logger.debug('writing color mode data, len=%d' % (len(self.value))) return write_length_block(fp, writer)
""" Color mode data structure. """ from __future__ import absolute_import, unicode_literals import attr import logging from psd_tools2.psd.base import ValueElement from psd_tools2.utils import ( read_length_block, write_length_block, write_bytes ) logger = logging.getLogger(__name__) @attr.s(repr=False, slots=True) class ColorModeData(ValueElement): """ Color mode data section of the PSD file. For indexed color images the data is the color table for the image in a non-interleaved order. Duotone images also have this data, but the data format is undocumented. """ value = attr.ib(default=b'', type=bytes) @classmethod def read(cls, fp): """Read the element from a file-like object. :param fp: file-like object :rtype: ColorModeData """ value = read_length_block(fp) logger.debug('reading color mode data, len=%d' % (len(value))) # TODO: Parse color table. return cls(value) def write(self, fp): """Write the element to a file-like object. :param fp: file-like object """ def writer(f): return write_bytes(f, self.value) logger.debug('writing color mode data, len=%d' % (len(self.value))) return write_length_block(fp, writer)
Fix empty color mode write
Fix empty color mode write
Python
mit
psd-tools/psd-tools,kmike/psd-tools,kmike/psd-tools
7ea8a4110ec2b696ff8124e0881d8cf769d8c365
src/puzzle/heuristics/analyze_word.py
src/puzzle/heuristics/analyze_word.py
import re from data import warehouse _WORD_REGEX = re.compile(r'^\w+$', re.IGNORECASE) def score_word(word): if not _valid(word): return False if word in warehouse.get('/words/unigram/trie'): return 1 return .1 def _valid(word): if not word: return False if not _WORD_REGEX.match(word): return False return True def score_anagram(word): if not _valid(word): return 0 index = warehouse.get('/words/unigram/anagram_index') if word not in index: return 0 results = index[word] if len(results) > 1: return 1 if word in results: return 0 # Input word == anagram word. return 1 # New word found. def score_cryptogram(word): if not _valid(word): return 0 # TODO: Analyze letter frequencies. # TODO: Reject words which have impossible patterns (e.g. 'aaabaaa'). return .1
import re from data import warehouse _WORD_REGEX = re.compile(r'^\w+$', re.IGNORECASE) def score_word(word): if not _valid(word): return False if word in warehouse.get('/words/unigram'): return 1 return .1 def _valid(word): if not word: return False if not _WORD_REGEX.match(word): return False return True def score_anagram(word): if not _valid(word): return 0 index = warehouse.get('/words/unigram/anagram_index') if word not in index: return 0 results = index[word] if len(results) > 1: return 1 if word in results: return 0 # Input word == anagram word. return 1 # New word found. def score_cryptogram(word): if not _valid(word): return 0 # TODO: Analyze letter frequencies. # TODO: Reject words which have impossible patterns (e.g. 'aaabaaa'). return .1
Use unigrams from warehouse module.
Use unigrams from warehouse module.
Python
mit
PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge
19f4b7d46d3aa57bb81dc34e2639a4c192b58cb1
meanrecipes/__main__.py
meanrecipes/__main__.py
#!/usr/bin/env python3 from flask import Flask, url_for, render_template app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/recipe/search/<term>') def recipe(term=None): ingredients = [[300.0, 'g', 'flour'], [400.5, 'kg', 'chocolate']] method = ['Step 1', 'Step 2'] return render_template('recipe.json', title=term, ingredients=ingredients, method=method) if __name__ == '__main__': app.run(debug = True)
#!/usr/bin/env python3 from flask import Flask, url_for, render_template, make_response app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/recipe/search/<term>') def recipe(term=None): ingredients = [[300.0, 'g', 'flour'], [400.5, 'kg', 'chocolate']] method = ['Step 1', 'Step 2'] resp = make_response(render_template('recipe.json', title=term, ingredients=ingredients, method=method)) resp.mimetype = 'application/json' return resp if __name__ == '__main__': app.run(debug = True)
Set application/json mimetype for response.
Set application/json mimetype for response.
Python
bsd-2-clause
kkelk/MeanRecipes,kkelk/MeanRecipes,kkelk/MeanRecipes,kkelk/MeanRecipes
511c0a480aa2353d30224f7dbde822a02a8dd2c4
appengine_config.py
appengine_config.py
"""Configuration.""" import logging import os import re from google.appengine.ext.appstats import recording logging.info('Loading %s from %s', __name__, __file__) # Custom webapp middleware to add Appstats. def webapp_add_wsgi_middleware(app): app = recording.appstats_wsgi_middleware(app) return app # Appstats URL. # TODO: Drop this once it is the default. appstats_stats_url = '/_ah/stats' # Custom Appstats path normalization. def appstats_normalize_path(path): if path.startswith('/user/'): return '/user/X' if path.startswith('/user_popup/'): return '/user_popup/X' if path.startswith('/rss/'): i = path.find('/', 5) if i > 0: return path[:i] + '/X' return re.sub(r'\d+', 'X', path) # Declare the Django version we need. from google.appengine.dist import use_library use_library('django', '1.0') # Fail early if we can't import Django 1.x. Log identifying information. import django logging.info('django.__file__ = %r, django.VERSION = %r', django.__file__, django.VERSION) assert django.VERSION[0] >= 1, "This Django version is too old"
"""Configuration.""" import logging import os import re from google.appengine.ext.appstats import recording logging.info('Loading %s from %s', __name__, __file__) # Custom webapp middleware to add Appstats. def webapp_add_wsgi_middleware(app): app = recording.appstats_wsgi_middleware(app) return app # Appstats URL. # TODO: Drop this once it is the default. appstats_stats_url = '/_ah/stats' # Custom Appstats path normalization. def appstats_normalize_path(path): if path.startswith('/user/'): return '/user/X' if path.startswith('/user_popup/'): return '/user_popup/X' if path.startswith('/rss/'): i = path.find('/', 5) if i > 0: return path[:i] + '/X' return re.sub(r'\d+', 'X', path) # Declare the Django version we need. from google.appengine.dist import use_library use_library('django', '1.1') # Fail early if we can't import Django 1.x. Log identifying information. import django logging.info('django.__file__ = %r, django.VERSION = %r', django.__file__, django.VERSION) assert django.VERSION[0] >= 1, "This Django version is too old"
Switch Django version from 1.0 to 1.1
Switch Django version from 1.0 to 1.1
Python
apache-2.0
riannucci/rietveldv2,riannucci/rietveldv2
d237c121955b7249e0e2ab5580d2abc2d19b0f25
noveltorpedo/models.py
noveltorpedo/models.py
from django.db import models class Author(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Story(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) title = models.CharField(max_length=255) contents = models.TextField(default='') def __str__(self): return self.title
from django.db import models class Author(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Story(models.Model): authors = models.ManyToManyField(Author) title = models.CharField(max_length=255) contents = models.TextField(default='') def __str__(self): return self.title
Allow a story to have many authors
Allow a story to have many authors
Python
mit
NovelTorpedo/noveltorpedo,NovelTorpedo/noveltorpedo,NovelTorpedo/noveltorpedo,NovelTorpedo/noveltorpedo
8b33c216b2da4a7bf480d79675325134777db9ae
wsme/release.py
wsme/release.py
name = "WSME" version = "0.3" description = "Web Services Made Easy" author = "Christophe de Vienne" email = "[email protected]" url = "http://bitbucket.org/cdevienne/wsme" license = "MIT"
name = "WSME" version = "0.3" description = """Web Services Made Easy makes it easy to \ implement multi-protocol webservices.""" author = "Christophe de Vienne" email = "[email protected]" url = "http://bitbucket.org/cdevienne/wsme" license = "MIT"
Change a bit the short description to make it more explicit
Change a bit the short description to make it more explicit
Python
mit
stackforge/wsme
0ac053e9c27f8381bb1aceff0bfdb12fc9c952cb
tests/test_config.py
tests/test_config.py
from pytest import fixture from oshino.config import Config, RiemannConfig @fixture def base_config(): return Config({"riemann": {"host": "localhost", "port": 5555 }, "interval": 5 }) @fixture def incomplete_config(): return Config({}) class TestBase(object): def test_base_config_interval(self, base_config): assert base_config.interval == 5 class TestRiemann(object): def test_base_config_get_riemann(self, base_config): assert isinstance(base_config.riemann, RiemannConfig) def test_incomplete_config_get_riemann(self, incomplete_config): assert isinstance(incomplete_config.riemann, RiemannConfig)
from pytest import fixture from oshino.config import Config, RiemannConfig @fixture def base_config(): return Config({"riemann": {"host": "localhost", "port": 5555 }, "interval": 5 }) @fixture def incomplete_config(): return Config({}) class TestBase(object): def test_base_config_interval(self, base_config): assert base_config.interval == 5 class TestRiemann(object): def test_base_config_get_riemann(self, base_config): assert isinstance(base_config.riemann, RiemannConfig) def test_incomplete_config_get_riemann(self, incomplete_config): assert isinstance(incomplete_config.riemann, RiemannConfig) def test_riemann_default_host(self, incomplete_config): assert incomplete_config.riemann.host == "localhost" def test_riemann_default_port(self, incomplete_config): assert incomplete_config.riemann.port == 5555
Test default values for Riemann
Test default values for Riemann
Python
mit
CodersOfTheNight/oshino
c205742520f4d2882d666e13a06c487d886ec7bc
trac/web/__init__.py
trac/web/__init__.py
# With mod_python we'll have to delay importing trac.web.api until # modpython_frontend.handler() has been called since the # PYTHON_EGG_CACHE variable is set from there # # TODO: Remove this once the Genshi zip_safe issue has been resolved. import os from pkg_resources import get_distribution if not os.path.isdir(get_distribution('genshi').location): try: import mod_python.apache import sys if 'trac.web.modpython_frontend' in sys.modules: from trac.web.api import * except ImportError: from trac.web.api import * else: from trac.web.api import *
# Workaround for http://bugs.python.org/issue6763 and # http://bugs.python.org/issue5853 thread issues import mimetypes mimetypes.init() # With mod_python we'll have to delay importing trac.web.api until # modpython_frontend.handler() has been called since the # PYTHON_EGG_CACHE variable is set from there # # TODO: Remove this once the Genshi zip_safe issue has been resolved. import os from pkg_resources import get_distribution if not os.path.isdir(get_distribution('genshi').location): try: import mod_python.apache import sys if 'trac.web.modpython_frontend' in sys.modules: from trac.web.api import * except ImportError: from trac.web.api import * else: from trac.web.api import *
Fix race condition during `mimetypes` initialization.
Fix race condition during `mimetypes` initialization. Initial patch from Steven R. Loomis. Closes #8629. git-svn-id: 0d96b0c1a6983ccc08b3732614f4d6bfcf9cbb42@9740 af82e41b-90c4-0310-8c96-b1721e28e2e2
Python
bsd-3-clause
rbaumg/trac,rbaumg/trac,rbaumg/trac,rbaumg/trac
d8b3e511b00c9b5a8c7951e16d06173fe93d6501
engine/util.py
engine/util.py
import json import threading import Queue from datetime import datetime,date,timedelta import time from tornado import gen from tornado.ioloop import IOLoop @gen.coroutine def async_sleep(seconds): yield gen.Task(IOLoop.instance().add_timeout, time.time() + seconds) def delayed(seconds): def f(x): time.sleep(seconds) return x return f def call_in_background(f, *args): '''Call function in background in a separate thread / coroutine''' result = Queue.Queue(1) t = threading.Thread(target=lambda: result.put(f(*args))) t.start() return result def get_id_from_slug(slug): '''Remove '/' from a part of url if it is present''' return slug if slug[-1] != '/' else slug[:-1] def my_print(s): '''Pretty printing with timestamp''' print "[" + str(datetime.now()) + "] " + s class DateTimeEncoder(json.JSONEncoder): '''Auxuliary class that lets us encode dates in json''' def default(self, obj): if isinstance(obj, datetime): return obj.isoformat() elif isinstance(obj, date): return obj.isoformat() elif isinstance(obj, timedelta): return (datetime.min + obj).time().isoformat() else: return super(DateTimeEncoder, self).default(obj)
import json import threading import Queue from datetime import datetime,date,timedelta import time import numpy from tornado import gen from tornado.ioloop import IOLoop @gen.coroutine def async_sleep(seconds): yield gen.Task(IOLoop.instance().add_timeout, time.time() + seconds) def delayed(seconds): def f(x): time.sleep(seconds) return x return f def call_in_background(f, *args): '''Call function in background in a separate thread / coroutine''' result = Queue.Queue(1) t = threading.Thread(target=lambda: result.put(f(*args))) t.start() return result def get_id_from_slug(slug): '''Remove '/' from a part of url if it is present''' return slug if slug[-1] != '/' else slug[:-1] def my_print(s): '''Pretty printing with timestamp''' print "[" + str(datetime.now()) + "] " + s class DateTimeEncoder(json.JSONEncoder): '''Auxuliary class that lets us encode dates in json''' def default(self, obj): if hasattr(obj, 'isoformat'): return obj.isoformat() elif isinstance(obj, datetime): return obj.isoformat() elif isinstance(obj, date): return obj.isoformat() elif isinstance(obj, timedelta): return (datetime.min + obj).time().isoformat() elif isinstance(obj, numpy.generic): return numpy.asscalar(obj) else: return super(DateTimeEncoder, self).default(obj)
Fix conditions in JSON encoder
Fix conditions in JSON encoder
Python
apache-2.0
METASPACE2020/sm-engine,SpatialMetabolomics/SM_distributed,METASPACE2020/sm-engine,SpatialMetabolomics/SM_distributed,SpatialMetabolomics/SM_distributed,SpatialMetabolomics/SM_distributed
43905a102092bdd50de1f8997cd19cb617b348b3
tests/cart_tests.py
tests/cart_tests.py
import importlib import os import sys import unittest import code import struct code_path = os.path.dirname(__file__) code_path = os.path.join(code_path, os.pardir) sys.path.append(code_path) import MOS6502 class TestCartHeaderParsing(unittest.TestCase): def testMagic(self): cpu = MOS6502.CPU() cpu.loadRom("../smb1.nes") self.assertEqual(cpu.rom != None, True) def testRomBanks(self): cpu = MOS6502.CPU() cpu.loadRom("../smb1.nes") self.assertEqual(cpu.rom.numRomBanks, 2) self.assertEqual(cpu.rom.numVromBanks, 1) if __name__ == '__main__': unittest.main()
import importlib import os import sys import unittest import code import struct code_path = os.path.dirname(__file__) code_path = os.path.join(code_path, os.pardir) sys.path.append(code_path) import MOS6502 class TestCartHeaderParsing(unittest.TestCase): def testMagic(self): cpu = MOS6502.CPU() cpu.loadRom("../smb1.nes") self.assertEqual(cpu.rom != None, True) def testRomBanks(self): cpu = MOS6502.CPU() cpu.loadRom("../smb1.nes") self.assertEqual(cpu.rom.numRomBanks, 2) self.assertEqual(cpu.rom.numVromBanks, 1) startAddr = cpu.ReadMemWord(cpu.reset) firstByte = cpu.ReadMemory(startAddr) self.assertEqual(firstByte, 0x78) if __name__ == '__main__': unittest.main()
Use the reset adder from the banks properly
Use the reset adder from the banks properly
Python
bsd-2-clause
pusscat/refNes
f0e8999ad139a8da8d3762ee1d318f23928edd9c
tests/modelstest.py
tests/modelstest.py
# Copyright (C) 2010 rPath, Inc. import testsuite testsuite.setup() from testrunner import testcase from rpath_repeater import models class TestBase(testcase.TestCaseWithWorkDir): pass class ModelsTest(TestBase): def testModelToXml(self): files = models.ImageFiles([ models.ImageFile(title="i1", sha1="s1", size=1), models.ImageFile(title="i2", sha1="s2"), ]) metadata = models.ImageMetadata(owner="me") files.append(metadata) self.failUnlessEqual(files.toXml(), '<files><file><title>i1</title><size>1</size><sha1>s1</sha1></file><file><title>i2</title><sha1>s2</sha1></file><metadata><owner>me</owner></metadata></files>') testsuite.main()
# Copyright (C) 2010 rPath, Inc. import testsuite testsuite.setup() from testrunner import testcase from rpath_repeater import models class TestBase(testcase.TestCaseWithWorkDir): pass class ModelsTest(TestBase): def testModelToXml(self): files = models.ImageFiles([ models.ImageFile(title="i1", sha1="s1", size=1), models.ImageFile(title="i2", sha1="s2"), ]) self.failUnlessEqual(files.toXml(), '<files><file><title>i1</title><size>1</size><sha1>s1</sha1></file><file><title>i2</title><sha1>s2</sha1></file></files>') testsuite.main()
Fix test after metadata changes
Fix test after metadata changes
Python
apache-2.0
sassoftware/rpath-repeater
face46431ce58600e99a745707a1cdf3ae2b34e2
tests/test_fonts.py
tests/test_fonts.py
""" tests.test_fonts ~~~~~~~~~~~~~~~~~~~~~ Test fonts API. :copyright: (c) 2018 Yoan Tournade. :license: AGPL, see LICENSE for more details. """ import requests def test_api_fonts_list(latex_on_http_api_url): """ The API list available fonts. """ r = requests.get("{}/fonts".format(latex_on_http_api_url), allow_redirects=False) assert r.status_code == 200 payload = r.json() assert "fonts" in payload fonts = payload["fonts"] assert isinstance(fonts, list) is True for font in fonts: assert "family" in font assert "name" in font assert "styles" in font assert isinstance(font["styles"], list) is True assert len(fonts) == 421
""" tests.test_fonts ~~~~~~~~~~~~~~~~~~~~~ Test fonts API. :copyright: (c) 2018 Yoan Tournade. :license: AGPL, see LICENSE for more details. """ import requests def test_api_fonts_list(latex_on_http_api_url): """ The API list available fonts. """ r = requests.get("{}/fonts".format(latex_on_http_api_url), allow_redirects=False) assert r.status_code == 200 payload = r.json() assert "fonts" in payload fonts = payload["fonts"] assert isinstance(fonts, list) is True for font in fonts: assert "family" in font assert "name" in font assert "styles" in font assert isinstance(font["styles"], list) is True assert len(fonts) == 2030
Update number of fonts in Docker image
Update number of fonts in Docker image
Python
agpl-3.0
YtoTech/latex-on-http,YtoTech/latex-on-http
3a5fb18a385ffd0533da94632d917e3c0bcfb051
tests/test_nulls.py
tests/test_nulls.py
from tests.models import EventWithNulls, EventWithNoNulls import pytest @pytest.mark.django_db def test_recurs_can_be_explicitly_none_if_none_is_allowed(): # Check we can save None correctly event = EventWithNulls.objects.create(recurs=None) assert event.recurs is None # Check we can deserialize None correctly reloaded = EventWithNulls.objects.get(pk=event.pk) assert reloaded.recurs is None @pytest.mark.django_db def test_recurs_cannot_be_explicitly_none_if_none_is_disallowed(): with pytest.raises(ValueError): EventWithNoNulls.objects.create(recurs=None)
from recurrence import Recurrence from tests.models import EventWithNulls, EventWithNoNulls import pytest @pytest.mark.django_db def test_recurs_can_be_explicitly_none_if_none_is_allowed(): # Check we can save None correctly event = EventWithNulls.objects.create(recurs=None) assert event.recurs is None # Check we can deserialize None correctly reloaded = EventWithNulls.objects.get(pk=event.pk) assert reloaded.recurs is None @pytest.mark.django_db def test_recurs_cannot_be_explicitly_none_if_none_is_disallowed(): with pytest.raises(ValueError): EventWithNoNulls.objects.create(recurs=None) @pytest.mark.django_db def test_recurs_can_be_empty_even_if_none_is_disallowed(): event = EventWithNoNulls.objects.create(recurs=Recurrence()) assert event.recurs == Recurrence()
Add a test for saving an empty recurrence object
Add a test for saving an empty recurrence object I wasn't sure whether this would fail on models which don't accept null values. Turns out it's allowed, so we should make sure it stays allowed.
Python
bsd-3-clause
linux2400/django-recurrence,linux2400/django-recurrence,django-recurrence/django-recurrence,Nikola-K/django-recurrence,FrankSalad/django-recurrence,Nikola-K/django-recurrence,FrankSalad/django-recurrence,django-recurrence/django-recurrence
cd2e4cce080413feb7685ec9a788327b8bca9053
tests/test_style.py
tests/test_style.py
import pkg_resources import unittest class CodeStyleTestCase(unittest.TestCase): def test_code_style(self): flake8 = pkg_resources.load_entry_point('flake8', 'console_scripts', 'flake8') try: flake8([]) except SystemExit as e: if e.code != 0: self.fail('Code style checks failed')
import logging import pkg_resources import unittest class CodeStyleTestCase(unittest.TestCase): def test_code_style(self): logger = logging.getLogger('flake8') logger.setLevel(logging.ERROR) flake8 = pkg_resources.load_entry_point('flake8', 'console_scripts', 'flake8') try: flake8([]) except SystemExit as e: if e.code != 0: self.fail('Code style checks failed')
Decrease noise from code-style test
Decrease noise from code-style test
Python
mit
ministryofjustice/bai2
59e47de06a175084538140481c7a702ff020e919
libvcs/__about__.py
libvcs/__about__.py
__title__ = 'libvcs' __package_name__ = 'libvcs' __description__ = 'vcs abstraction layer' __version__ = '0.3.0' __author__ = 'Tony Narlock' __github__ = 'https://github.com/vcs-python/libvcs' __pypi__ = 'https://pypi.org/project/libvcs/' __email__ = '[email protected]' __license__ = 'MIT' __copyright__ = 'Copyright 2016- Tony Narlock'
__title__ = 'libvcs' __package_name__ = 'libvcs' __description__ = 'vcs abstraction layer' __version__ = '0.3.0' __author__ = 'Tony Narlock' __github__ = 'https://github.com/vcs-python/libvcs' __docs__ = 'https://libvcs.git-pull.com' __tracker__ = 'https://github.com/vcs-python/libvcs/issues' __pypi__ = 'https://pypi.org/project/libvcs/' __email__ = '[email protected]' __license__ = 'MIT' __copyright__ = 'Copyright 2016- Tony Narlock'
Add metadata for tracker and docs
Add metadata for tracker and docs
Python
mit
tony/libvcs
5cf8516db40a8581eb80a1fb64a0b11da37527dd
libxau/conanfile.py
libxau/conanfile.py
from conans import ConanFile, AutoToolsBuildEnvironment, tools import os class LibxauConan(ConanFile): name = "libxau" version = "1.0.8" license = "Custom https://cgit.freedesktop.org/xorg/lib/libXau/tree/COPYING" url = "https://github.com/trigger-happy/conan-packages" description = "X11 authorisation library" settings = "os", "compiler", "build_type", "arch" options = {"shared": [True, False]} default_options = "shared=False" generators = "cmake" def source(self): pkgLink = 'https://xorg.freedesktop.org/releases/individual/lib/libXau-{version}.tar.bz2'.format(version=self.version) self.run("curl -JOL " + pkgLink) self.run("tar xf libXau-{version}.tar.bz2".format(version=self.version)) def build(self): envBuild = AutoToolsBuildEnvironment(self) installPrefix=os.getcwd() with tools.chdir("libXau-{version}".format(version=self.version)): with tools.environment_append(envBuild.vars): self.run("./configure --prefix={0}".format(installPrefix)) self.run("make install") def package(self): self.copy("lib/*", dst=".", keep_path=True) self.copy("include/*", dst=".", keep_path=True) def package_info(self): self.cpp_info.libs = ["libXau"]
from conans import ConanFile, AutoToolsBuildEnvironment, tools import os class LibxauConan(ConanFile): name = "libxau" version = "1.0.8" license = "Custom https://cgit.freedesktop.org/xorg/lib/libXau/tree/COPYING" url = "https://github.com/trigger-happy/conan-packages" description = "X11 authorisation library" settings = "os", "compiler", "build_type", "arch" options = {"shared": [True, False]} default_options = "shared=False" generators = "cmake" def source(self): pkgLink = 'https://xorg.freedesktop.org/releases/individual/lib/libXau-{version}.tar.bz2'.format(version=self.version) self.run("curl -JOL " + pkgLink) self.run("tar xf libXau-{version}.tar.bz2".format(version=self.version)) def build(self): envBuild = AutoToolsBuildEnvironment(self) installPrefix=os.getcwd() with tools.chdir("libXau-{version}".format(version=self.version)): with tools.environment_append(envBuild.vars): self.run("./configure --prefix={0}".format(installPrefix)) self.run("make install") def package(self): self.copy("lib/*", dst=".", keep_path=True) self.copy("include/*", dst=".", keep_path=True) def package_info(self): self.cpp_info.libs = ["Xau"]
Fix incorrect libxau library name
Fix incorrect libxau library name
Python
mit
trigger-happy/conan-packages
d8c1c7da47e2568cecc1fd6dff0fec7661b39125
turbosms/routers.py
turbosms/routers.py
class SMSRouter(object): app_label = 'sms' db_name = 'sms' def db_for_read(self, model, **hints): if model._meta.app_label == self.app_label: return self.db_name return None def db_for_write(self, model, **hints): if model._meta.app_label == self.app_label: return self.db_name return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == self.app_label or \ obj2._meta.app_label == self.app_label: return False return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == self.app_label: return False return None
class TurboSMSRouter(object): app_label = 'turbosms' db_name = 'turbosms' def db_for_read(self, model, **hints): if model._meta.app_label == self.app_label: return self.db_name return None def db_for_write(self, model, **hints): if model._meta.app_label == self.app_label: return self.db_name return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == self.app_label or \ obj2._meta.app_label == self.app_label: return False return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == self.app_label: return False return None
Fix bug in sms router.
Fix bug in sms router.
Python
isc
pmaigutyak/mp-turbosms
5fade4bc26c2637a479a69051cee37a1a859c71a
load_hilma.py
load_hilma.py
#!/usr/bin/env python3 import xml.etree.ElementTree as ET import sys import pymongo from pathlib import Path import argh from xml2json import etree_to_dict from hilma_conversion import get_handler hilma_to_dict = lambda notice: etree_to_dict(notice, get_handler) def load_hilma_xml(inputfile, collection): root = ET.parse(inputfile).getroot() notices = list(root.iterfind('WRAPPED_NOTICE')) notices = map(hilma_to_dict, notices) collection.ensure_index('ID', unique=True) for n in notices: # Use the ID as primary key n.update('_id', n['ID']) collection.save(n) def sync_hilma_xml_directory(directory, mongo_uri=None, mongo_db='openhilma'): if mongo_uri is None: client = pymongo.MongoClient() else: client = pymongo.MongoClient(mongo_uri) db = client[mongo_db] collection = db.notices paths = sorted(Path(directory).glob("*.xml")) for fpath in paths: load_hilma_xml(fpath.open(), collection) if __name__ == '__main__': argh.dispatch_command(sync_hilma_xml_directory)
#!/usr/bin/env python3 import xml.etree.ElementTree as ET import sys import pymongo from pathlib import Path import argh from xml2json import etree_to_dict from hilma_conversion import get_handler hilma_to_dict = lambda notice: etree_to_dict(notice, get_handler) def load_hilma_xml(inputfile, collection): root = ET.parse(inputfile).getroot() notices = list(root.iterfind('WRAPPED_NOTICE')) notices = map(hilma_to_dict, notices) for n in notices: # Use the ID as primary key n.update({'_id': n['ID']}) collection.save(n) def sync_hilma_xml_directory(directory, mongo_uri=None, mongo_db='openhilma'): if mongo_uri is None: client = pymongo.MongoClient() else: client = pymongo.MongoClient(mongo_uri) db = client[mongo_db] collection = db.notices paths = sorted(Path(directory).glob("*.xml")) for fpath in paths: load_hilma_xml(fpath.open(), collection) if __name__ == '__main__': argh.dispatch_command(sync_hilma_xml_directory)
Use the notice ID as priary key
Use the notice ID as priary key Gentlemen, drop your DBs!
Python
agpl-3.0
jampekka/openhilma
816874f692c7ef9de5aa8782fab1747e96199229
moksha/live/flot.py
moksha/live/flot.py
# This file is part of Moksha. # # Moksha is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Moksha is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Moksha. If not, see <http://www.gnu.org/licenses/>. # # Copyright 2008, Red Hat, Inc. # Authors: Luke Macken <[email protected]> from tw.jquery.flot import FlotWidget from moksha.live import LiveWidget class LiveFlotWidget(LiveWidget): """ A live graphing widget """ topic = 'flot_example' children = [FlotWidget('flot')] params = ['id', 'data', 'options', 'height', 'width', 'onconnectedframe', 'onmessageframe'] onmessageframe = '$.plot($("#${id}"),json[0]["data"],json[0]["options"])' template = '<div id="${id}" style="width:${width};height:${height};" />' height = '250px' width = '390px' options = {} data = [{}]
# This file is part of Moksha. # # Moksha is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Moksha is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Moksha. If not, see <http://www.gnu.org/licenses/>. # # Copyright 2008, Red Hat, Inc. # Authors: Luke Macken <[email protected]> from tw.jquery.flot import FlotWidget from moksha.live import LiveWidget class LiveFlotWidget(LiveWidget): """ A live graphing widget """ topic = 'flot_example' params = ['id', 'data', 'options', 'height', 'width', 'onmessageframe'] children = [FlotWidget('flot')] onmessageframe = '$.plot($("#${id}"),json[0]["data"],json[0]["options"])' template = '<div id="${id}" style="width:${width};height:${height};" />' height = '250px' width = '390px' options = {} data = [{}]
Clean up some LiveFlotWidget params
Clean up some LiveFlotWidget params
Python
apache-2.0
ralphbean/moksha,lmacken/moksha,lmacken/moksha,pombredanne/moksha,ralphbean/moksha,mokshaproject/moksha,pombredanne/moksha,mokshaproject/moksha,mokshaproject/moksha,pombredanne/moksha,mokshaproject/moksha,pombredanne/moksha,ralphbean/moksha,lmacken/moksha
cb5dc31aa3b77d2bf4aab08785749d24da80f325
taggit_autosuggest_select2/models.py
taggit_autosuggest_select2/models.py
try: from south.modelsinspector import add_ignored_fields add_ignored_fields(["^taggit_autosuggest\.managers"]) except ImportError: pass # without south this can fail silently
try: from south.modelsinspector import add_ignored_fields add_ignored_fields(["^taggit_autosuggest_select2\.managers"]) except ImportError: pass # without south this can fail silently
Correct ignored module name for South.
Correct ignored module name for South.
Python
mit
iris-edu/django-taggit-autosuggest-select2,kpantic/django-taggit-autosuggest-select2,iris-edu/django-taggit-autosuggest-select2,kpantic/django-taggit-autosuggest-select2,iris-edu-int/django-taggit-autosuggest-select2,iris-edu-int/django-taggit-autosuggest-select2,iris-edu/django-taggit-autosuggest-select2,iris-edu-int/django-taggit-autosuggest-select2,kpantic/django-taggit-autosuggest-select2
8bc2b19e9aef410832555fb9962c243f0d4aef96
brink/decorators.py
brink/decorators.py
def require_request_model(cls, *args, validate=True, **kwargs): """ Makes a handler require that a request body that map towards the given model is provided. Unless the ``validate`` option is set to ``False`` the data will be validated against the model's fields. The model will be passed to the handler as the last positional argument. :: @require_request_model(Model) async def handle_model(request, model): return 200, model """ def decorator(handler): async def new_handler(request): body = await request.json() model = cls(**body) if validate: model.validate() return await handler(request, *args, model, **kwargs) return new_handler return decorator
import asyncio def require_request_model(cls, *args, validate=True, **kwargs): """ Makes a handler require that a request body that map towards the given model is provided. Unless the ``validate`` option is set to ``False`` the data will be validated against the model's fields. The model will be passed to the handler as the last positional argument. :: @require_request_model(Model) async def handle_model(request, model): return 200, model """ def decorator(handler): async def new_handler(request): body = await request.json() model = cls(**body) if validate: model.validate() return await handler(request, *args, model, **kwargs) return new_handler return decorator def use_ws_subhandlers(handler): """ Allows the handler to return any number of **subhandlers** that will be run in parallel. This makes it much cleaner and easier to write a handler that both listens for incoming messages on the socket connection, while also watching a changefeed from RethinkDB. Example usage :: @use_ws_subhandlers async def handle_feed(request, ws): async def handle_incoming(_, ws): async for msg in ws: await Item(value=msg.data).save() async def handle_change(_, ws): async for item in await Item.changes(): ws.send_json(item) return [handle_incoming, handle_change] """ async def new_handler(request, ws): handlers = await handler(request, ws) tasks = [request.app.loop.create_task(h(request, ws)) for h in handlers] try: await asyncio.gather(*tasks) finally: for task in tasks: task.cancel() await ws.close() return new_handler
Add decorator for using websocket subhandlers
Add decorator for using websocket subhandlers
Python
bsd-3-clause
brinkframework/brink
2501bb03e836ac29cc1defa8591446ff217771b2
tests/test_model.py
tests/test_model.py
"""Sample unittests.""" import unittest2 as unittest from domain_models import model from domain_models import fields class User(model.DomainModel): """Example user domain model.""" id = fields.Int() email = fields.String() first_name = fields.Unicode() last_name = fields.Unicode() gender = fields.String() birth_date = fields.String() __view_key__ = [id, email] __unique_key__ = id class SampleTests(unittest.TestCase): """Sample tests tests.""" def test_set_and_get_attrs(self): """Test setting and getting of domain model attributes.""" user = User() user.id = 1 user.email = '[email protected]' user.first_name = 'John' user.last_name = 'Smith' user.gender = 'male' user.birth_date = '05/04/1988' self.assertEqual(user.id, 1) self.assertEqual(user.email, '[email protected]') self.assertEqual(user.first_name, u'John') self.assertEqual(user.last_name, u'Smith') self.assertEqual(user.gender, 'male') self.assertEqual(user.birth_date, '05/04/1988')
"""Sample unittests.""" import unittest2 as unittest from domain_models import model from domain_models import fields class User(model.DomainModel): """Example user domain model.""" id = fields.Int() email = fields.String() first_name = fields.Unicode() last_name = fields.Unicode() gender = fields.String() birth_date = fields.String() __view_key__ = [id, email] __unique_key__ = id class SampleTests(unittest.TestCase): """Sample tests tests.""" def test_set_and_get_attrs(self): """Test setting and getting of domain model attributes.""" user = User() user.id = 1 user.email = '[email protected]' user.first_name = 'John' user.last_name = 'Smith' user.gender = 'male' user.birth_date = '05/04/1988' self.assertEqual(user.id, 1) self.assertEqual(user.email, '[email protected]') self.assertEqual(user.first_name, unicode('John')) self.assertEqual(user.last_name, unicode('Smith')) self.assertEqual(user.gender, 'male') self.assertEqual(user.birth_date, '05/04/1988')
Fix of tests with unicode strings
Fix of tests with unicode strings
Python
bsd-3-clause
ets-labs/domain_models,ets-labs/python-domain-models,rmk135/domain_models
cb798ae8f7f6e810a87137a56cd04be76596a2dd
photutils/tests/test_psfs.py
photutils/tests/test_psfs.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import division import numpy as np from astropy.tests.helper import pytest from photutils.psf import GaussianPSF try: from scipy import optimize HAS_SCIPY = True except ImportError: HAS_SCIPY = False widths = [0.001, 0.01, 0.1, 1] @pytest.mark.skipif('not HAS_SCIPY') @pytest.mark.parametrize(('width'), widths) def test_subpixel_gauss_psf(width): """ Test subpixel accuracy of Gaussian PSF by checking the sum o pixels. """ gauss_psf = GaussianPSF(width) y, x = np.mgrid[-10:11, -10:11] assert np.abs(gauss_psf(x, y).sum() - 1) < 1E-12 @pytest.mark.skipif('not HAS_SCIPY') def test_gaussian_PSF_integral(): """ Test if Gaussian PSF integrates to unity on larger scales. """ psf = GaussianPSF(10) y, x = np.mgrid[-100:101, -100:101] assert np.abs(psf(y, x).sum() - 1) < 1E-12
# Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import division import numpy as np from astropy.tests.helper import pytest from ..psf import GaussianPSF try: from scipy import optimize HAS_SCIPY = True except ImportError: HAS_SCIPY = False widths = [0.001, 0.01, 0.1, 1] @pytest.mark.skipif('not HAS_SCIPY') @pytest.mark.parametrize(('width'), widths) def test_subpixel_gauss_psf(width): """ Test subpixel accuracy of Gaussian PSF by checking the sum o pixels. """ gauss_psf = GaussianPSF(width) y, x = np.mgrid[-10:11, -10:11] assert np.abs(gauss_psf(x, y).sum() - 1) < 1E-12 @pytest.mark.skipif('not HAS_SCIPY') def test_gaussian_PSF_integral(): """ Test if Gaussian PSF integrates to unity on larger scales. """ psf = GaussianPSF(10) y, x = np.mgrid[-100:101, -100:101] assert np.abs(psf(y, x).sum() - 1) < 1E-12
Use relative imports for consistency; pep8
Use relative imports for consistency; pep8
Python
bsd-3-clause
larrybradley/photutils,astropy/photutils
66df1b2719aa278c37f1c70ef550659c22d93d10
tests/unit/fakes.py
tests/unit/fakes.py
# Copyright 2012 Intel Inc, OpenStack LLC. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ Fakes For filter and weight tests. """ from openstack.common.scheduler import weights class FakeWeigher1(weights.BaseHostWeigher): def __init__(self): pass class FakeWeigher2(weights.BaseHostWeigher): def __init__(self): pass class FakeClass(object): def __init__(self): pass
# Copyright 2012 Intel Inc, OpenStack Foundation. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ Fakes For filter and weight tests. """ from openstack.common.scheduler import weights class FakeWeigher1(weights.BaseHostWeigher): def __init__(self): pass class FakeWeigher2(weights.BaseHostWeigher): def __init__(self): pass class FakeClass(object): def __init__(self): pass
Fix Copyright Headers - Rename LLC to Foundation
Fix Copyright Headers - Rename LLC to Foundation One code change, rest are in headers Change-Id: I73f59681358629e1ad74e49d3d3ca13fcb5c2eb1
Python
apache-2.0
openstack/oslo.i18n,varunarya10/oslo.i18n
65fd070a88e06bb040e8c96babc6b4c86ca29730
validatish/error.py
validatish/error.py
""" Module containing package exception classes. """ class Invalid(Exception): def __init__(self, message, exceptions=None, validator=None): Exception.__init__(self, message, exceptions) self.message = message self.exceptions = exceptions self.validator = validator def __str__(self): return self.message __unicode__ = __str__ def __repr__(self): if self.exceptions: return 'validatish.Invalid("%s", exceptions=%s, validator=%s)' % (self.message, self.exceptions, self.validator) else: return 'validatish.Invalid("%s", validator=%s)' % (self.message, self.validator) @property def errors(self): return list(_flatten(self._fetch_errors(), _keepstrings)) def _fetch_errors(self): if self.exceptions is None: yield self.message else: for e in self.exceptions: yield e._fetch_errors() def _flatten(s, toiter=iter): try: it = toiter(s) except TypeError: yield s else: for elem in it: for subelem in _flatten(elem, toiter): yield subelem def _keepstrings(seq): if isinstance(seq, basestring): raise TypeError return iter(seq)
""" Module containing package exception classes. """ class Invalid(Exception): def __init__(self, message, exceptions=None, validator=None): Exception.__init__(self, message, exceptions) self.message = message self.exceptions = exceptions self.validator = validator def __str__(self): return self.message __unicode__ = __str__ def __repr__(self): if self.exceptions: return 'validatish.Invalid("%s", exceptions=%s, validator=%s)' % (self.message, self.exceptions, self.validator) else: return 'validatish.Invalid("%s", validator=%s)' % (self.message, self.validator) @property def errors(self): return list(_flatten(self._fetch_errors(), _keepstrings)) def _fetch_errors(self): if self.exceptions is None: yield self.message else: for e in self.exceptions: yield e._fetch_errors() # Hide Python 2.6 deprecation warning. def _get_message(self): return self._message def _set_message(self, message): self._message = message message = property(_get_message, _set_message) def _flatten(s, toiter=iter): try: it = toiter(s) except TypeError: yield s else: for elem in it: for subelem in _flatten(elem, toiter): yield subelem def _keepstrings(seq): if isinstance(seq, basestring): raise TypeError return iter(seq)
Hide Python 2.6 Exception.message deprecation warnings
Hide Python 2.6 Exception.message deprecation warnings
Python
bsd-3-clause
ish/validatish,ish/validatish
5c620a504327696b9cfe3ffc423ae7ae6e915e78
dec02/dec02part1.py
dec02/dec02part1.py
# Advent of Code # Dec 2, Part 1 # @geekygirlsarah
# Advent of Code # Dec 2, Part 1 # @geekygirlsarah inputFile = "input.txt" # Tracking vars finalCode = "" lastNumber = 5 # start here tempNumber = 0 with open(inputFile) as f: while True: line = f.readline(-1) if not line: # print "End of file" break # print ("Line: ", line) print ("First number=" + str(lastNumber)) for dir in line: print("dir=" + dir) if dir == "U": tempNumber = lastNumber - 3 elif dir == "D": tempNumber = lastNumber + 3 elif dir == "L": tempNumber = lastNumber - 1 elif dir == "R": tempNumber = lastNumber + 1 elif dir == "\n": break # Boundary checks to undo out of bounds if dir == "U" and tempNumber < 1: tempNumber = lastNumber elif dir == "D" and tempNumber > 9: tempNumber = lastNumber elif dir == "L" and (tempNumber == 0 or tempNumber == 3 or tempNumber == 6): tempNumber = lastNumber elif dir == "R" and (tempNumber == 10 or tempNumber == 7 or tempNumber == 4): tempNumber = lastNumber print ("New number: " + str(tempNumber)) lastNumber = tempNumber # last number validated, so add to code finalCode = finalCode + str(tempNumber) print("Final code: " + finalCode)
Add 12/2 part 1 solution
Add 12/2 part 1 solution
Python
mit
geekygirlsarah/adventofcode2016
356dd5294280db3334f86354202f0d68881254b9
joerd/check.py
joerd/check.py
import zipfile import tarfile import shutil import tempfile from osgeo import gdal def is_zip(tmp): """ Returns True if the NamedTemporaryFile given as the argument appears to be a well-formed Zip file. """ try: zip_file = zipfile.ZipFile(tmp.name, 'r') test_result = zip_file.testzip() return test_result is None except: pass return False def tar_gz_has_gdal(member_name): """ Returns a function which, when called with a NamedTemporaryFile, returns True if that file is a GZip-encoded TAR file containing a `member_name` member which can be opened with GDAL. """ def func(tmp): try: tar = tarfile.open(tmp.name, mode='r:gz', errorlevel=2) with tempfile.NamedTemporaryFile() as tmp_member: shutil.copyfileobj(tar.extractfile(member_name), tmp_member) return is_gdal(tmp_member) except (tarfile.TarError, IOError, OSError) as e: return False def is_gdal(tmp): """ Returns true if the NamedTemporaryFile given as the argument appears to be a well-formed GDAL raster file. """ try: ds = gdal.Open(tmp.name) band = ds.GetRasterBand(1) band.ComputeBandStats() return True except: pass return False
import zipfile import tarfile import shutil import tempfile from osgeo import gdal def is_zip(tmp): """ Returns True if the NamedTemporaryFile given as the argument appears to be a well-formed Zip file. """ try: zip_file = zipfile.ZipFile(tmp.name, 'r') test_result = zip_file.testzip() return test_result is None except: pass return False def tar_gz_has_gdal(member_name): """ Returns a function which, when called with a NamedTemporaryFile, returns True if that file is a GZip-encoded TAR file containing a `member_name` member which can be opened with GDAL. """ def func(tmp): try: tar = tarfile.open(tmp.name, mode='r:gz', errorlevel=2) with tempfile.NamedTemporaryFile() as tmp_member: shutil.copyfileobj(tar.extractfile(member_name), tmp_member) tmp_member.seek(0) return is_gdal(tmp_member) except (tarfile.TarError, IOError, OSError) as e: return False return func def is_gdal(tmp): """ Returns true if the NamedTemporaryFile given as the argument appears to be a well-formed GDAL raster file. """ try: ds = gdal.Open(tmp.name) band = ds.GetRasterBand(1) band.ComputeBandStats() return True except: pass return False
Return verifier function, not None. Also reset the temporary file to the beginning before verifying it.
Return verifier function, not None. Also reset the temporary file to the beginning before verifying it.
Python
mit
mapzen/joerd,tilezen/joerd
9353a5e2369e819c092c94d224b09c321f5b5ff0
utils/get_collection_object_count.py
utils/get_collection_object_count.py
#!/usr/bin/env python # -*- coding: utf8 -*- import sys, os import argparse from deepharvest.deepharvest_nuxeo import DeepHarvestNuxeo def main(argv=None): parser = argparse.ArgumentParser(description='Print count of objects for a given collection.') parser.add_argument('path', help="Nuxeo path to collection") parser.add_argument('--pynuxrc', default='~/.pynuxrc-prod', help="rcfile for use with pynux utils") if argv is None: argv = parser.parse_args() dh = DeepHarvestNuxeo(argv.path, '', pynuxrc=argv.pynuxrc) print "about to fetch objects for path {}".format(dh.path) objects = dh.fetch_objects() object_count = len(objects) print "finished fetching objects. {} found".format(object_count) print "about to iterate through objects and get components" component_count = 0 for obj in objects: components = dh.fetch_components(obj) component_count = component_count + len(components) print "finished fetching components. {} found".format(component_count) print "Grand Total: {}".format(object_count + component_count) if __name__ == "__main__": sys.exit(main())
#!/usr/bin/env python # -*- coding: utf8 -*- import sys, os import argparse from deepharvest.deepharvest_nuxeo import DeepHarvestNuxeo def main(argv=None): parser = argparse.ArgumentParser(description='Print count of objects for a given collection.') parser.add_argument('path', help="Nuxeo path to collection") parser.add_argument('--pynuxrc', default='~/.pynuxrc-prod', help="rcfile for use with pynux utils") parser.add_argument('--components', action='store_true', help="show counts for object components") if argv is None: argv = parser.parse_args() dh = DeepHarvestNuxeo(argv.path, '', pynuxrc=argv.pynuxrc) print "about to fetch objects for path {}".format(dh.path) objects = dh.fetch_objects() object_count = len(objects) print "finished fetching objects. {} found".format(object_count) if not argv.components: return print "about to iterate through objects and get components" component_count = 0 for obj in objects: components = dh.fetch_components(obj) component_count = component_count + len(components) print "finished fetching components. {} found".format(component_count) print "Grand Total: {}".format(object_count + component_count) if __name__ == "__main__": sys.exit(main())
Add option to count components
Add option to count components
Python
bsd-3-clause
barbarahui/nuxeo-calisphere,barbarahui/nuxeo-calisphere
d84e6aa022ef5e256807738c35e5069a0a1380d7
app/main/forms/frameworks.py
app/main/forms/frameworks.py
from flask.ext.wtf import Form from wtforms import BooleanField from wtforms.validators import DataRequired, Length from dmutils.forms import StripWhitespaceStringField class SignerDetailsForm(Form): signerName = StripWhitespaceStringField('Full name', validators=[ DataRequired(message="You must provide the full name of the person signing on behalf of the company."), Length(max=255, message="You must provide a name under 256 characters.") ]) signerRole = StripWhitespaceStringField( 'Role at the company', validators=[ DataRequired(message="You must provide the role of the person signing on behalf of the company."), Length(max=255, message="You must provide a role under 256 characters.") ], description='The person signing must have the authority to agree to the framework terms, ' 'eg director or company secretary.' ) class ContractReviewForm(Form): authorisation = BooleanField( 'Authorisation', validators=[DataRequired(message="You must confirm you have the authority to return the agreement.")] )
from flask.ext.wtf import Form from wtforms import BooleanField from wtforms.validators import DataRequired, Length from dmutils.forms import StripWhitespaceStringField class SignerDetailsForm(Form): signerName = StripWhitespaceStringField('Full name', validators=[ DataRequired(message="You must provide the full name of the person signing on behalf of the company."), Length(max=255, message="You must provide a name under 256 characters.") ]) signerRole = StripWhitespaceStringField( 'Role at the company', validators=[ DataRequired(message="You must provide the role of the person signing on behalf of the company."), Length(max=255, message="You must provide a role under 256 characters.") ], description='The person signing must have the authority to agree to the framework terms, ' 'eg director or company secretary.' ) class ContractReviewForm(Form): authorisation = BooleanField( 'Authorisation', validators=[DataRequired(message="You must confirm you have the authority to return the agreement.")] ) class AcceptAgreementVariationForm(Form): accept_changes = BooleanField( 'I accept these proposed changes', validators=[ DataRequired(message="If you agree to the proposed changes then you must check the box before saving.") ] )
Add form for accepting contract variation
Add form for accepting contract variation
Python
mit
alphagov/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend