commit
stringlengths
40
40
old_file
stringlengths
4
118
new_file
stringlengths
4
118
old_contents
stringlengths
0
2.94k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
444
message
stringlengths
16
3.45k
lang
stringclasses
1 value
license
stringclasses
13 values
repos
stringlengths
5
43.2k
prompt
stringlengths
17
4.58k
response
stringlengths
1
4.43k
prompt_tagged
stringlengths
58
4.62k
response_tagged
stringlengths
1
4.43k
text
stringlengths
132
7.29k
text_tagged
stringlengths
173
7.33k
232c80a0ce03f4b2cbef9bf4f86546fa2110cf47
setup.py
setup.py
import versioneer from setuptools import setup setup( name='domain_events', version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), description='Send and receive domain events via RabbitMQ', author='Ableton AG', author_email='webteam@ableton.com', url='https://github.com/AbletonAG/domain-events', license='MIT', packages=['domain_events'], install_requires=["pika >= 0.10.0"], zip_safe=False, )
import versioneer from setuptools import setup, find_packages setup( name='domain_events', version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), description='Send and receive domain events via RabbitMQ', author='Ableton AG', author_email='webteam@ableton.com', url='https://github.com/AbletonAG/domain-events', license='MIT', packages=find_packages(), install_requires=["pika >= 0.10.0"], zip_safe=False, )
Add django app and tests to source distribution
Add django app and tests to source distribution
Python
mit
AbletonAG/domain-events
import versioneer from setuptools import setup setup( name='domain_events', version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), description='Send and receive domain events via RabbitMQ', author='Ableton AG', author_email='webteam@ableton.com', url='https://github.com/AbletonAG/domain-events', license='MIT', packages=['domain_events'], install_requires=["pika >= 0.10.0"], zip_safe=False, ) Add django app and tests to source distribution
import versioneer from setuptools import setup, find_packages setup( name='domain_events', version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), description='Send and receive domain events via RabbitMQ', author='Ableton AG', author_email='webteam@ableton.com', url='https://github.com/AbletonAG/domain-events', license='MIT', packages=find_packages(), install_requires=["pika >= 0.10.0"], zip_safe=False, )
<commit_before>import versioneer from setuptools import setup setup( name='domain_events', version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), description='Send and receive domain events via RabbitMQ', author='Ableton AG', author_email='webteam@ableton.com', url='https://github.com/AbletonAG/domain-events', license='MIT', packages=['domain_events'], install_requires=["pika >= 0.10.0"], zip_safe=False, ) <commit_msg>Add django app and tests to source distribution<commit_after>
import versioneer from setuptools import setup, find_packages setup( name='domain_events', version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), description='Send and receive domain events via RabbitMQ', author='Ableton AG', author_email='webteam@ableton.com', url='https://github.com/AbletonAG/domain-events', license='MIT', packages=find_packages(), install_requires=["pika >= 0.10.0"], zip_safe=False, )
import versioneer from setuptools import setup setup( name='domain_events', version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), description='Send and receive domain events via RabbitMQ', author='Ableton AG', author_email='webteam@ableton.com', url='https://github.com/AbletonAG/domain-events', license='MIT', packages=['domain_events'], install_requires=["pika >= 0.10.0"], zip_safe=False, ) Add django app and tests to source distributionimport versioneer from setuptools import setup, find_packages setup( name='domain_events', version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), description='Send and receive domain events via RabbitMQ', author='Ableton AG', author_email='webteam@ableton.com', url='https://github.com/AbletonAG/domain-events', license='MIT', packages=find_packages(), install_requires=["pika >= 0.10.0"], zip_safe=False, )
<commit_before>import versioneer from setuptools import setup setup( name='domain_events', version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), description='Send and receive domain events via RabbitMQ', author='Ableton AG', author_email='webteam@ableton.com', url='https://github.com/AbletonAG/domain-events', license='MIT', packages=['domain_events'], install_requires=["pika >= 0.10.0"], zip_safe=False, ) <commit_msg>Add django app and tests to source distribution<commit_after>import versioneer from setuptools import setup, find_packages setup( name='domain_events', version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), description='Send and receive domain events via RabbitMQ', author='Ableton AG', author_email='webteam@ableton.com', url='https://github.com/AbletonAG/domain-events', license='MIT', packages=find_packages(), install_requires=["pika >= 0.10.0"], zip_safe=False, )
2c141722aa8478b7e6a078d02206a26db3772a95
setup.py
setup.py
import os from setuptools import setup def getPackages(base): packages = [] def visit(arg, directory, files): if '__init__.py' in files: packages.append(directory.replace('/', '.')) os.path.walk(base, visit, None) return packages setup( name='tryfer', version='0.1', description='Twisted Zipkin Tracing Library', classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 2.7', 'Framework :: Twisted' ], license='APL2', url='https://github.com/racker/tryfer', packages=getPackages('tryfer'), install_requires=[ 'Twisted >= 12.0.0', 'thrift == 0.8.0', 'scrivener == 0.2' ], )
import os from setuptools import setup def getPackages(base): packages = [] def visit(arg, directory, files): if '__init__.py' in files: packages.append(directory.replace('/', '.')) os.path.walk(base, visit, None) return packages setup( name='tryfer', version='0.1', description='Twisted Zipkin Tracing Library', classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 2.7', 'Framework :: Twisted' ], maintainer='David Reid', maintainer_email='david.reid@rackspace.com', license='APL2', url='https://github.com/racker/tryfer', long_description=open('README.rst').read(), packages=getPackages('tryfer'), install_requires=[ 'Twisted >= 12.0.0', 'thrift == 0.8.0', 'scrivener == 0.2' ], )
Add maintainer and long description.
Add maintainer and long description.
Python
apache-2.0
tryfer/tryfer
import os from setuptools import setup def getPackages(base): packages = [] def visit(arg, directory, files): if '__init__.py' in files: packages.append(directory.replace('/', '.')) os.path.walk(base, visit, None) return packages setup( name='tryfer', version='0.1', description='Twisted Zipkin Tracing Library', classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 2.7', 'Framework :: Twisted' ], license='APL2', url='https://github.com/racker/tryfer', packages=getPackages('tryfer'), install_requires=[ 'Twisted >= 12.0.0', 'thrift == 0.8.0', 'scrivener == 0.2' ], ) Add maintainer and long description.
import os from setuptools import setup def getPackages(base): packages = [] def visit(arg, directory, files): if '__init__.py' in files: packages.append(directory.replace('/', '.')) os.path.walk(base, visit, None) return packages setup( name='tryfer', version='0.1', description='Twisted Zipkin Tracing Library', classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 2.7', 'Framework :: Twisted' ], maintainer='David Reid', maintainer_email='david.reid@rackspace.com', license='APL2', url='https://github.com/racker/tryfer', long_description=open('README.rst').read(), packages=getPackages('tryfer'), install_requires=[ 'Twisted >= 12.0.0', 'thrift == 0.8.0', 'scrivener == 0.2' ], )
<commit_before>import os from setuptools import setup def getPackages(base): packages = [] def visit(arg, directory, files): if '__init__.py' in files: packages.append(directory.replace('/', '.')) os.path.walk(base, visit, None) return packages setup( name='tryfer', version='0.1', description='Twisted Zipkin Tracing Library', classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 2.7', 'Framework :: Twisted' ], license='APL2', url='https://github.com/racker/tryfer', packages=getPackages('tryfer'), install_requires=[ 'Twisted >= 12.0.0', 'thrift == 0.8.0', 'scrivener == 0.2' ], ) <commit_msg>Add maintainer and long description.<commit_after>
import os from setuptools import setup def getPackages(base): packages = [] def visit(arg, directory, files): if '__init__.py' in files: packages.append(directory.replace('/', '.')) os.path.walk(base, visit, None) return packages setup( name='tryfer', version='0.1', description='Twisted Zipkin Tracing Library', classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 2.7', 'Framework :: Twisted' ], maintainer='David Reid', maintainer_email='david.reid@rackspace.com', license='APL2', url='https://github.com/racker/tryfer', long_description=open('README.rst').read(), packages=getPackages('tryfer'), install_requires=[ 'Twisted >= 12.0.0', 'thrift == 0.8.0', 'scrivener == 0.2' ], )
import os from setuptools import setup def getPackages(base): packages = [] def visit(arg, directory, files): if '__init__.py' in files: packages.append(directory.replace('/', '.')) os.path.walk(base, visit, None) return packages setup( name='tryfer', version='0.1', description='Twisted Zipkin Tracing Library', classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 2.7', 'Framework :: Twisted' ], license='APL2', url='https://github.com/racker/tryfer', packages=getPackages('tryfer'), install_requires=[ 'Twisted >= 12.0.0', 'thrift == 0.8.0', 'scrivener == 0.2' ], ) Add maintainer and long description.import os from setuptools import setup def getPackages(base): packages = [] def visit(arg, directory, files): if '__init__.py' in files: packages.append(directory.replace('/', '.')) os.path.walk(base, visit, None) return packages setup( name='tryfer', version='0.1', description='Twisted Zipkin Tracing Library', classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 2.7', 'Framework :: Twisted' ], maintainer='David Reid', maintainer_email='david.reid@rackspace.com', license='APL2', url='https://github.com/racker/tryfer', long_description=open('README.rst').read(), packages=getPackages('tryfer'), install_requires=[ 'Twisted >= 12.0.0', 'thrift == 0.8.0', 'scrivener == 0.2' ], )
<commit_before>import os from setuptools import setup def getPackages(base): packages = [] def visit(arg, directory, files): if '__init__.py' in files: packages.append(directory.replace('/', '.')) os.path.walk(base, visit, None) return packages setup( name='tryfer', version='0.1', description='Twisted Zipkin Tracing Library', classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 2.7', 'Framework :: Twisted' ], license='APL2', url='https://github.com/racker/tryfer', packages=getPackages('tryfer'), install_requires=[ 'Twisted >= 12.0.0', 'thrift == 0.8.0', 'scrivener == 0.2' ], ) <commit_msg>Add maintainer and long description.<commit_after>import os from setuptools import setup def getPackages(base): packages = [] def visit(arg, directory, files): if '__init__.py' in files: packages.append(directory.replace('/', '.')) os.path.walk(base, visit, None) return packages setup( name='tryfer', version='0.1', description='Twisted Zipkin Tracing Library', classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 2.7', 'Framework :: Twisted' ], maintainer='David Reid', maintainer_email='david.reid@rackspace.com', license='APL2', url='https://github.com/racker/tryfer', long_description=open('README.rst').read(), packages=getPackages('tryfer'), install_requires=[ 'Twisted >= 12.0.0', 'thrift == 0.8.0', 'scrivener == 0.2' ], )
17ec7f6350890384069611ee485ef1b26d0867ed
setup.py
setup.py
#!/usr/bin/python import time from datetime import date from setuptools import setup from pagekite.common import APPVER import os try: # This borks sdist. os.remove('.SELF') except: pass setup( name="pagekite", version=APPVER.replace('github', 'dev%d' % time.time()), license="AGPLv3+", author="Bjarni R. Einarsson", author_email="bre@pagekite.net", url="http://pagekite.org/", description="""PageKite makes localhost servers visible to the world.""", long_description="""\ PageKite is a system for running publicly visible servers (generally web servers) on machines without a direct connection to the Internet, such as mobile devices or computers behind restrictive firewalls. PageKite works around NAT, firewalls and IP-address limitations by using a combination of tunnels and reverse proxies. Natively supported protocols: HTTP, HTTPS Partially supported protocols: IRC, Finger Any other TCP-based service, including SSH and VNC, may be exposed as well to clients supporting HTTP Proxies. """, packages=['pagekite', 'pagekite.ui', 'pagekite.proto'], scripts=['scripts/pagekite', 'scripts/lapcat'], install_requires=['SocksipyChain >= 2.0.9'] )
#!/usr/bin/python import time from datetime import date from setuptools import setup from pagekite.common import APPVER import os try: # This borks sdist. os.remove('.SELF') except: pass setup( name="pagekite", version=APPVER.replace('github', 'dev%d' % (120*int(time.time()/120))), license="AGPLv3+", author="Bjarni R. Einarsson", author_email="bre@pagekite.net", url="http://pagekite.org/", description="""PageKite makes localhost servers visible to the world.""", long_description="""\ PageKite is a system for running publicly visible servers (generally web servers) on machines without a direct connection to the Internet, such as mobile devices or computers behind restrictive firewalls. PageKite works around NAT, firewalls and IP-address limitations by using a combination of tunnels and reverse proxies. Natively supported protocols: HTTP, HTTPS Partially supported protocols: IRC, Finger Any other TCP-based service, including SSH and VNC, may be exposed as well to clients supporting HTTP Proxies. """, packages=['pagekite', 'pagekite.ui', 'pagekite.proto'], scripts=['scripts/pagekite', 'scripts/lapcat'], install_requires=['SocksipyChain >= 2.0.9'] )
Reduce dev version number resolution
Reduce dev version number resolution
Python
agpl-3.0
lyoshenka/PyPagekite,lyoshenka/PyPagekite,output/PyPagekite,output/PyPagekite,pagekite/PyPagekite,lyoshenka/PyPagekite,pagekite/PyPagekite,pagekite/PyPagekite,output/PyPagekite
#!/usr/bin/python import time from datetime import date from setuptools import setup from pagekite.common import APPVER import os try: # This borks sdist. os.remove('.SELF') except: pass setup( name="pagekite", version=APPVER.replace('github', 'dev%d' % time.time()), license="AGPLv3+", author="Bjarni R. Einarsson", author_email="bre@pagekite.net", url="http://pagekite.org/", description="""PageKite makes localhost servers visible to the world.""", long_description="""\ PageKite is a system for running publicly visible servers (generally web servers) on machines without a direct connection to the Internet, such as mobile devices or computers behind restrictive firewalls. PageKite works around NAT, firewalls and IP-address limitations by using a combination of tunnels and reverse proxies. Natively supported protocols: HTTP, HTTPS Partially supported protocols: IRC, Finger Any other TCP-based service, including SSH and VNC, may be exposed as well to clients supporting HTTP Proxies. """, packages=['pagekite', 'pagekite.ui', 'pagekite.proto'], scripts=['scripts/pagekite', 'scripts/lapcat'], install_requires=['SocksipyChain >= 2.0.9'] ) Reduce dev version number resolution
#!/usr/bin/python import time from datetime import date from setuptools import setup from pagekite.common import APPVER import os try: # This borks sdist. os.remove('.SELF') except: pass setup( name="pagekite", version=APPVER.replace('github', 'dev%d' % (120*int(time.time()/120))), license="AGPLv3+", author="Bjarni R. Einarsson", author_email="bre@pagekite.net", url="http://pagekite.org/", description="""PageKite makes localhost servers visible to the world.""", long_description="""\ PageKite is a system for running publicly visible servers (generally web servers) on machines without a direct connection to the Internet, such as mobile devices or computers behind restrictive firewalls. PageKite works around NAT, firewalls and IP-address limitations by using a combination of tunnels and reverse proxies. Natively supported protocols: HTTP, HTTPS Partially supported protocols: IRC, Finger Any other TCP-based service, including SSH and VNC, may be exposed as well to clients supporting HTTP Proxies. """, packages=['pagekite', 'pagekite.ui', 'pagekite.proto'], scripts=['scripts/pagekite', 'scripts/lapcat'], install_requires=['SocksipyChain >= 2.0.9'] )
<commit_before>#!/usr/bin/python import time from datetime import date from setuptools import setup from pagekite.common import APPVER import os try: # This borks sdist. os.remove('.SELF') except: pass setup( name="pagekite", version=APPVER.replace('github', 'dev%d' % time.time()), license="AGPLv3+", author="Bjarni R. Einarsson", author_email="bre@pagekite.net", url="http://pagekite.org/", description="""PageKite makes localhost servers visible to the world.""", long_description="""\ PageKite is a system for running publicly visible servers (generally web servers) on machines without a direct connection to the Internet, such as mobile devices or computers behind restrictive firewalls. PageKite works around NAT, firewalls and IP-address limitations by using a combination of tunnels and reverse proxies. Natively supported protocols: HTTP, HTTPS Partially supported protocols: IRC, Finger Any other TCP-based service, including SSH and VNC, may be exposed as well to clients supporting HTTP Proxies. """, packages=['pagekite', 'pagekite.ui', 'pagekite.proto'], scripts=['scripts/pagekite', 'scripts/lapcat'], install_requires=['SocksipyChain >= 2.0.9'] ) <commit_msg>Reduce dev version number resolution<commit_after>
#!/usr/bin/python import time from datetime import date from setuptools import setup from pagekite.common import APPVER import os try: # This borks sdist. os.remove('.SELF') except: pass setup( name="pagekite", version=APPVER.replace('github', 'dev%d' % (120*int(time.time()/120))), license="AGPLv3+", author="Bjarni R. Einarsson", author_email="bre@pagekite.net", url="http://pagekite.org/", description="""PageKite makes localhost servers visible to the world.""", long_description="""\ PageKite is a system for running publicly visible servers (generally web servers) on machines without a direct connection to the Internet, such as mobile devices or computers behind restrictive firewalls. PageKite works around NAT, firewalls and IP-address limitations by using a combination of tunnels and reverse proxies. Natively supported protocols: HTTP, HTTPS Partially supported protocols: IRC, Finger Any other TCP-based service, including SSH and VNC, may be exposed as well to clients supporting HTTP Proxies. """, packages=['pagekite', 'pagekite.ui', 'pagekite.proto'], scripts=['scripts/pagekite', 'scripts/lapcat'], install_requires=['SocksipyChain >= 2.0.9'] )
#!/usr/bin/python import time from datetime import date from setuptools import setup from pagekite.common import APPVER import os try: # This borks sdist. os.remove('.SELF') except: pass setup( name="pagekite", version=APPVER.replace('github', 'dev%d' % time.time()), license="AGPLv3+", author="Bjarni R. Einarsson", author_email="bre@pagekite.net", url="http://pagekite.org/", description="""PageKite makes localhost servers visible to the world.""", long_description="""\ PageKite is a system for running publicly visible servers (generally web servers) on machines without a direct connection to the Internet, such as mobile devices or computers behind restrictive firewalls. PageKite works around NAT, firewalls and IP-address limitations by using a combination of tunnels and reverse proxies. Natively supported protocols: HTTP, HTTPS Partially supported protocols: IRC, Finger Any other TCP-based service, including SSH and VNC, may be exposed as well to clients supporting HTTP Proxies. """, packages=['pagekite', 'pagekite.ui', 'pagekite.proto'], scripts=['scripts/pagekite', 'scripts/lapcat'], install_requires=['SocksipyChain >= 2.0.9'] ) Reduce dev version number resolution#!/usr/bin/python import time from datetime import date from setuptools import setup from pagekite.common import APPVER import os try: # This borks sdist. os.remove('.SELF') except: pass setup( name="pagekite", version=APPVER.replace('github', 'dev%d' % (120*int(time.time()/120))), license="AGPLv3+", author="Bjarni R. Einarsson", author_email="bre@pagekite.net", url="http://pagekite.org/", description="""PageKite makes localhost servers visible to the world.""", long_description="""\ PageKite is a system for running publicly visible servers (generally web servers) on machines without a direct connection to the Internet, such as mobile devices or computers behind restrictive firewalls. PageKite works around NAT, firewalls and IP-address limitations by using a combination of tunnels and reverse proxies. Natively supported protocols: HTTP, HTTPS Partially supported protocols: IRC, Finger Any other TCP-based service, including SSH and VNC, may be exposed as well to clients supporting HTTP Proxies. """, packages=['pagekite', 'pagekite.ui', 'pagekite.proto'], scripts=['scripts/pagekite', 'scripts/lapcat'], install_requires=['SocksipyChain >= 2.0.9'] )
<commit_before>#!/usr/bin/python import time from datetime import date from setuptools import setup from pagekite.common import APPVER import os try: # This borks sdist. os.remove('.SELF') except: pass setup( name="pagekite", version=APPVER.replace('github', 'dev%d' % time.time()), license="AGPLv3+", author="Bjarni R. Einarsson", author_email="bre@pagekite.net", url="http://pagekite.org/", description="""PageKite makes localhost servers visible to the world.""", long_description="""\ PageKite is a system for running publicly visible servers (generally web servers) on machines without a direct connection to the Internet, such as mobile devices or computers behind restrictive firewalls. PageKite works around NAT, firewalls and IP-address limitations by using a combination of tunnels and reverse proxies. Natively supported protocols: HTTP, HTTPS Partially supported protocols: IRC, Finger Any other TCP-based service, including SSH and VNC, may be exposed as well to clients supporting HTTP Proxies. """, packages=['pagekite', 'pagekite.ui', 'pagekite.proto'], scripts=['scripts/pagekite', 'scripts/lapcat'], install_requires=['SocksipyChain >= 2.0.9'] ) <commit_msg>Reduce dev version number resolution<commit_after>#!/usr/bin/python import time from datetime import date from setuptools import setup from pagekite.common import APPVER import os try: # This borks sdist. os.remove('.SELF') except: pass setup( name="pagekite", version=APPVER.replace('github', 'dev%d' % (120*int(time.time()/120))), license="AGPLv3+", author="Bjarni R. Einarsson", author_email="bre@pagekite.net", url="http://pagekite.org/", description="""PageKite makes localhost servers visible to the world.""", long_description="""\ PageKite is a system for running publicly visible servers (generally web servers) on machines without a direct connection to the Internet, such as mobile devices or computers behind restrictive firewalls. PageKite works around NAT, firewalls and IP-address limitations by using a combination of tunnels and reverse proxies. Natively supported protocols: HTTP, HTTPS Partially supported protocols: IRC, Finger Any other TCP-based service, including SSH and VNC, may be exposed as well to clients supporting HTTP Proxies. """, packages=['pagekite', 'pagekite.ui', 'pagekite.proto'], scripts=['scripts/pagekite', 'scripts/lapcat'], install_requires=['SocksipyChain >= 2.0.9'] )
740f29abddc9ab05b5a395b8b69a54cae5ace0bf
setup.py
setup.py
# -*- coding: utf-8 -*- # # setup.py # anytop # from setuptools import setup setup( name='anytop', version='0.2.1', description='Streaming frequency distribution viewer.', long_description=open('README.rst').read(), author='Lars Yencken', author_email='lars@yencken.org', url='http://github.com/larsyencken/anytop', entry_points={ 'console_scripts': [ 'anytop = anytop.top:main', 'anyhist = anytop.histogram:main', ], }, packages=['anytop'], license='ISC', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.7', ], test_suite='tests', )
# -*- coding: utf-8 -*- # # setup.py # anytop # from setuptools import setup setup( name='anytop', version='0.2.1', description='Streaming frequency distribution viewer.', long_description=open('README.rst').read(), author='Lars Yencken', author_email='lars@yencken.org', url='http://github.com/larsyencken/anytop', entry_points={ 'console_scripts': [ 'anytop = anytop.top:main', 'anyhist = anytop.histogram:main', ], }, packages=['anytop'], license='ISC', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.7', "Programming Language :: Python :: 3", 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], test_suite='tests', )
Add Python 3 trove classifiers.
Add Python 3 trove classifiers.
Python
isc
larsyencken/anytop
# -*- coding: utf-8 -*- # # setup.py # anytop # from setuptools import setup setup( name='anytop', version='0.2.1', description='Streaming frequency distribution viewer.', long_description=open('README.rst').read(), author='Lars Yencken', author_email='lars@yencken.org', url='http://github.com/larsyencken/anytop', entry_points={ 'console_scripts': [ 'anytop = anytop.top:main', 'anyhist = anytop.histogram:main', ], }, packages=['anytop'], license='ISC', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.7', ], test_suite='tests', ) Add Python 3 trove classifiers.
# -*- coding: utf-8 -*- # # setup.py # anytop # from setuptools import setup setup( name='anytop', version='0.2.1', description='Streaming frequency distribution viewer.', long_description=open('README.rst').read(), author='Lars Yencken', author_email='lars@yencken.org', url='http://github.com/larsyencken/anytop', entry_points={ 'console_scripts': [ 'anytop = anytop.top:main', 'anyhist = anytop.histogram:main', ], }, packages=['anytop'], license='ISC', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.7', "Programming Language :: Python :: 3", 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], test_suite='tests', )
<commit_before># -*- coding: utf-8 -*- # # setup.py # anytop # from setuptools import setup setup( name='anytop', version='0.2.1', description='Streaming frequency distribution viewer.', long_description=open('README.rst').read(), author='Lars Yencken', author_email='lars@yencken.org', url='http://github.com/larsyencken/anytop', entry_points={ 'console_scripts': [ 'anytop = anytop.top:main', 'anyhist = anytop.histogram:main', ], }, packages=['anytop'], license='ISC', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.7', ], test_suite='tests', ) <commit_msg>Add Python 3 trove classifiers.<commit_after>
# -*- coding: utf-8 -*- # # setup.py # anytop # from setuptools import setup setup( name='anytop', version='0.2.1', description='Streaming frequency distribution viewer.', long_description=open('README.rst').read(), author='Lars Yencken', author_email='lars@yencken.org', url='http://github.com/larsyencken/anytop', entry_points={ 'console_scripts': [ 'anytop = anytop.top:main', 'anyhist = anytop.histogram:main', ], }, packages=['anytop'], license='ISC', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.7', "Programming Language :: Python :: 3", 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], test_suite='tests', )
# -*- coding: utf-8 -*- # # setup.py # anytop # from setuptools import setup setup( name='anytop', version='0.2.1', description='Streaming frequency distribution viewer.', long_description=open('README.rst').read(), author='Lars Yencken', author_email='lars@yencken.org', url='http://github.com/larsyencken/anytop', entry_points={ 'console_scripts': [ 'anytop = anytop.top:main', 'anyhist = anytop.histogram:main', ], }, packages=['anytop'], license='ISC', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.7', ], test_suite='tests', ) Add Python 3 trove classifiers.# -*- coding: utf-8 -*- # # setup.py # anytop # from setuptools import setup setup( name='anytop', version='0.2.1', description='Streaming frequency distribution viewer.', long_description=open('README.rst').read(), author='Lars Yencken', author_email='lars@yencken.org', url='http://github.com/larsyencken/anytop', entry_points={ 'console_scripts': [ 'anytop = anytop.top:main', 'anyhist = anytop.histogram:main', ], }, packages=['anytop'], license='ISC', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.7', "Programming Language :: Python :: 3", 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], test_suite='tests', )
<commit_before># -*- coding: utf-8 -*- # # setup.py # anytop # from setuptools import setup setup( name='anytop', version='0.2.1', description='Streaming frequency distribution viewer.', long_description=open('README.rst').read(), author='Lars Yencken', author_email='lars@yencken.org', url='http://github.com/larsyencken/anytop', entry_points={ 'console_scripts': [ 'anytop = anytop.top:main', 'anyhist = anytop.histogram:main', ], }, packages=['anytop'], license='ISC', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.7', ], test_suite='tests', ) <commit_msg>Add Python 3 trove classifiers.<commit_after># -*- coding: utf-8 -*- # # setup.py # anytop # from setuptools import setup setup( name='anytop', version='0.2.1', description='Streaming frequency distribution viewer.', long_description=open('README.rst').read(), author='Lars Yencken', author_email='lars@yencken.org', url='http://github.com/larsyencken/anytop', entry_points={ 'console_scripts': [ 'anytop = anytop.top:main', 'anyhist = anytop.histogram:main', ], }, packages=['anytop'], license='ISC', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.7', "Programming Language :: Python :: 3", 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], test_suite='tests', )
f8e2d9a36cc60c711e006dba1265f7fdef74cb5a
setup.py
setup.py
from setuptools import setup setup( name='tower', version='0.3.2', description='Pull strings from a variety of sources, collapse whitespace, ' 'support context (msgctxt), and merging .pot files.', long_description=open('README.rst').read(), author='Wil Clouser', author_email='wclouser@mozilla.com', url='http://github.com/clouserw/tower', license='BSD', packages=['tower'], include_package_data=True, zip_safe=False, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', # I don't know what exactly this means, but why not? 'Environment :: Web Environment :: Mozilla', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
from setuptools import setup setup( name='tower', version='0.3.3', description='Pull strings from a variety of sources, collapse whitespace, ' 'support context (msgctxt), and merging .pot files.', long_description=open('README.rst').read(), author='Wil Clouser', author_email='wclouser@mozilla.com', url='http://github.com/clouserw/tower', license='BSD', packages=['tower'], include_package_data=True, zip_safe=False, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', # I don't know what exactly this means, but why not? 'Environment :: Web Environment :: Mozilla', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
Update version to pick up plurals fix
Update version to pick up plurals fix
Python
bsd-3-clause
clouserw/tower
from setuptools import setup setup( name='tower', version='0.3.2', description='Pull strings from a variety of sources, collapse whitespace, ' 'support context (msgctxt), and merging .pot files.', long_description=open('README.rst').read(), author='Wil Clouser', author_email='wclouser@mozilla.com', url='http://github.com/clouserw/tower', license='BSD', packages=['tower'], include_package_data=True, zip_safe=False, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', # I don't know what exactly this means, but why not? 'Environment :: Web Environment :: Mozilla', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ] ) Update version to pick up plurals fix
from setuptools import setup setup( name='tower', version='0.3.3', description='Pull strings from a variety of sources, collapse whitespace, ' 'support context (msgctxt), and merging .pot files.', long_description=open('README.rst').read(), author='Wil Clouser', author_email='wclouser@mozilla.com', url='http://github.com/clouserw/tower', license='BSD', packages=['tower'], include_package_data=True, zip_safe=False, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', # I don't know what exactly this means, but why not? 'Environment :: Web Environment :: Mozilla', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
<commit_before>from setuptools import setup setup( name='tower', version='0.3.2', description='Pull strings from a variety of sources, collapse whitespace, ' 'support context (msgctxt), and merging .pot files.', long_description=open('README.rst').read(), author='Wil Clouser', author_email='wclouser@mozilla.com', url='http://github.com/clouserw/tower', license='BSD', packages=['tower'], include_package_data=True, zip_safe=False, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', # I don't know what exactly this means, but why not? 'Environment :: Web Environment :: Mozilla', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ] ) <commit_msg>Update version to pick up plurals fix<commit_after>
from setuptools import setup setup( name='tower', version='0.3.3', description='Pull strings from a variety of sources, collapse whitespace, ' 'support context (msgctxt), and merging .pot files.', long_description=open('README.rst').read(), author='Wil Clouser', author_email='wclouser@mozilla.com', url='http://github.com/clouserw/tower', license='BSD', packages=['tower'], include_package_data=True, zip_safe=False, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', # I don't know what exactly this means, but why not? 'Environment :: Web Environment :: Mozilla', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
from setuptools import setup setup( name='tower', version='0.3.2', description='Pull strings from a variety of sources, collapse whitespace, ' 'support context (msgctxt), and merging .pot files.', long_description=open('README.rst').read(), author='Wil Clouser', author_email='wclouser@mozilla.com', url='http://github.com/clouserw/tower', license='BSD', packages=['tower'], include_package_data=True, zip_safe=False, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', # I don't know what exactly this means, but why not? 'Environment :: Web Environment :: Mozilla', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ] ) Update version to pick up plurals fixfrom setuptools import setup setup( name='tower', version='0.3.3', description='Pull strings from a variety of sources, collapse whitespace, ' 'support context (msgctxt), and merging .pot files.', long_description=open('README.rst').read(), author='Wil Clouser', author_email='wclouser@mozilla.com', url='http://github.com/clouserw/tower', license='BSD', packages=['tower'], include_package_data=True, zip_safe=False, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', # I don't know what exactly this means, but why not? 'Environment :: Web Environment :: Mozilla', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
<commit_before>from setuptools import setup setup( name='tower', version='0.3.2', description='Pull strings from a variety of sources, collapse whitespace, ' 'support context (msgctxt), and merging .pot files.', long_description=open('README.rst').read(), author='Wil Clouser', author_email='wclouser@mozilla.com', url='http://github.com/clouserw/tower', license='BSD', packages=['tower'], include_package_data=True, zip_safe=False, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', # I don't know what exactly this means, but why not? 'Environment :: Web Environment :: Mozilla', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ] ) <commit_msg>Update version to pick up plurals fix<commit_after>from setuptools import setup setup( name='tower', version='0.3.3', description='Pull strings from a variety of sources, collapse whitespace, ' 'support context (msgctxt), and merging .pot files.', long_description=open('README.rst').read(), author='Wil Clouser', author_email='wclouser@mozilla.com', url='http://github.com/clouserw/tower', license='BSD', packages=['tower'], include_package_data=True, zip_safe=False, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', # I don't know what exactly this means, but why not? 'Environment :: Web Environment :: Mozilla', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
1fa8d33feffa26944d89cb059530edb9e6bf047b
setup.py
setup.py
from setuptools import find_packages, setup setup( name='caar', version='5.0.0-beta.5', url='http://github.com/nickpowersys/CaaR/', license='BSD 3-Clause License', author='Nicholas A. Brown', author_email='nbprofessional@gmail.com', description='Accelerating analysis of time stamped sensor observations and ' 'cycling device operations.', install_requires=[ 'configparser', 'future', 'numpy', 'pandas', ], packages=find_packages(exclude=['docs']), package_data={ }, data_files=[ ], include_package_data=True, platforms='any', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Scientific/Engineering :: Information Analysis', 'Topic :: Software Development :: Libraries :: Python Modules', ], extras_require={ 'testing': ['pytest'], } )
from setuptools import find_packages, setup setup( name='caar', version='5.0.0-beta.6', url='http://github.com/nickpowersys/CaaR/', license='BSD 3-Clause License', author='Nicholas A. Brown', author_email='nbprofessional@gmail.com', description='Accelerating analysis of time stamped sensor observations and ' 'cycling device operations.', install_requires=[ 'configparser', 'future', 'numpy', 'pandas', ], packages=find_packages(exclude=['docs']), package_data={ }, data_files=[ ], include_package_data=True, platforms='any', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Scientific/Engineering :: Information Analysis', 'Topic :: Software Development :: Libraries :: Python Modules', ], extras_require={ 'testing': ['pytest'], } )
Build wheel excluding local backports
Build wheel excluding local backports
Python
bsd-3-clause
nickpowersys/CaaR
from setuptools import find_packages, setup setup( name='caar', version='5.0.0-beta.5', url='http://github.com/nickpowersys/CaaR/', license='BSD 3-Clause License', author='Nicholas A. Brown', author_email='nbprofessional@gmail.com', description='Accelerating analysis of time stamped sensor observations and ' 'cycling device operations.', install_requires=[ 'configparser', 'future', 'numpy', 'pandas', ], packages=find_packages(exclude=['docs']), package_data={ }, data_files=[ ], include_package_data=True, platforms='any', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Scientific/Engineering :: Information Analysis', 'Topic :: Software Development :: Libraries :: Python Modules', ], extras_require={ 'testing': ['pytest'], } ) Build wheel excluding local backports
from setuptools import find_packages, setup setup( name='caar', version='5.0.0-beta.6', url='http://github.com/nickpowersys/CaaR/', license='BSD 3-Clause License', author='Nicholas A. Brown', author_email='nbprofessional@gmail.com', description='Accelerating analysis of time stamped sensor observations and ' 'cycling device operations.', install_requires=[ 'configparser', 'future', 'numpy', 'pandas', ], packages=find_packages(exclude=['docs']), package_data={ }, data_files=[ ], include_package_data=True, platforms='any', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Scientific/Engineering :: Information Analysis', 'Topic :: Software Development :: Libraries :: Python Modules', ], extras_require={ 'testing': ['pytest'], } )
<commit_before>from setuptools import find_packages, setup setup( name='caar', version='5.0.0-beta.5', url='http://github.com/nickpowersys/CaaR/', license='BSD 3-Clause License', author='Nicholas A. Brown', author_email='nbprofessional@gmail.com', description='Accelerating analysis of time stamped sensor observations and ' 'cycling device operations.', install_requires=[ 'configparser', 'future', 'numpy', 'pandas', ], packages=find_packages(exclude=['docs']), package_data={ }, data_files=[ ], include_package_data=True, platforms='any', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Scientific/Engineering :: Information Analysis', 'Topic :: Software Development :: Libraries :: Python Modules', ], extras_require={ 'testing': ['pytest'], } ) <commit_msg>Build wheel excluding local backports<commit_after>
from setuptools import find_packages, setup setup( name='caar', version='5.0.0-beta.6', url='http://github.com/nickpowersys/CaaR/', license='BSD 3-Clause License', author='Nicholas A. Brown', author_email='nbprofessional@gmail.com', description='Accelerating analysis of time stamped sensor observations and ' 'cycling device operations.', install_requires=[ 'configparser', 'future', 'numpy', 'pandas', ], packages=find_packages(exclude=['docs']), package_data={ }, data_files=[ ], include_package_data=True, platforms='any', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Scientific/Engineering :: Information Analysis', 'Topic :: Software Development :: Libraries :: Python Modules', ], extras_require={ 'testing': ['pytest'], } )
from setuptools import find_packages, setup setup( name='caar', version='5.0.0-beta.5', url='http://github.com/nickpowersys/CaaR/', license='BSD 3-Clause License', author='Nicholas A. Brown', author_email='nbprofessional@gmail.com', description='Accelerating analysis of time stamped sensor observations and ' 'cycling device operations.', install_requires=[ 'configparser', 'future', 'numpy', 'pandas', ], packages=find_packages(exclude=['docs']), package_data={ }, data_files=[ ], include_package_data=True, platforms='any', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Scientific/Engineering :: Information Analysis', 'Topic :: Software Development :: Libraries :: Python Modules', ], extras_require={ 'testing': ['pytest'], } ) Build wheel excluding local backportsfrom setuptools import find_packages, setup setup( name='caar', version='5.0.0-beta.6', url='http://github.com/nickpowersys/CaaR/', license='BSD 3-Clause License', author='Nicholas A. Brown', author_email='nbprofessional@gmail.com', description='Accelerating analysis of time stamped sensor observations and ' 'cycling device operations.', install_requires=[ 'configparser', 'future', 'numpy', 'pandas', ], packages=find_packages(exclude=['docs']), package_data={ }, data_files=[ ], include_package_data=True, platforms='any', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Scientific/Engineering :: Information Analysis', 'Topic :: Software Development :: Libraries :: Python Modules', ], extras_require={ 'testing': ['pytest'], } )
<commit_before>from setuptools import find_packages, setup setup( name='caar', version='5.0.0-beta.5', url='http://github.com/nickpowersys/CaaR/', license='BSD 3-Clause License', author='Nicholas A. Brown', author_email='nbprofessional@gmail.com', description='Accelerating analysis of time stamped sensor observations and ' 'cycling device operations.', install_requires=[ 'configparser', 'future', 'numpy', 'pandas', ], packages=find_packages(exclude=['docs']), package_data={ }, data_files=[ ], include_package_data=True, platforms='any', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Scientific/Engineering :: Information Analysis', 'Topic :: Software Development :: Libraries :: Python Modules', ], extras_require={ 'testing': ['pytest'], } ) <commit_msg>Build wheel excluding local backports<commit_after>from setuptools import find_packages, setup setup( name='caar', version='5.0.0-beta.6', url='http://github.com/nickpowersys/CaaR/', license='BSD 3-Clause License', author='Nicholas A. Brown', author_email='nbprofessional@gmail.com', description='Accelerating analysis of time stamped sensor observations and ' 'cycling device operations.', install_requires=[ 'configparser', 'future', 'numpy', 'pandas', ], packages=find_packages(exclude=['docs']), package_data={ }, data_files=[ ], include_package_data=True, platforms='any', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Scientific/Engineering :: Information Analysis', 'Topic :: Software Development :: Libraries :: Python Modules', ], extras_require={ 'testing': ['pytest'], } )
79358f9eb3b12b45d3e1ebe8840aed9e9d8a7274
setup.py
setup.py
#!/usr/bin/env python from setuptools import setup, find_packages setup( name='django-oscar-fancypages', version=":versiontools:fancypages:", url='https://github.com/tangentlabs/django-oscar-fancypages', author="Sebastian Vetter", author_email="sebastian.vetter@tangentsnowball.com.au", description="Adding fancy CMS-style pages to Oscar", long_description=open('README.rst').read(), keywords="django, oscar, e-commerce, cms, pages, flatpages", license='BSD', platforms=['linux'], packages=find_packages(exclude=["sandbox*", "tests*"]), include_package_data=True, install_requires=[ 'versiontools>=1.9.1', 'Django>=1.4.1', 'django-oscar>=0.3', 'django-model-utils>=1.1.0', 'django-compressor>=1.2', ], dependency_links=[ 'http://github.com/tangentlabs/django-oscar/tarball/master#egg=django-oscar-0.4' ], # See http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', #'License :: OSI Approved :: BSD License', 'Operating System :: Unix', 'Programming Language :: Python' ] )
#!/usr/bin/env python from setuptools import setup, find_packages setup( name='django-oscar-fancypages', version=":versiontools:fancypages:", url='https://github.com/tangentlabs/django-oscar-fancypages', author="Sebastian Vetter", author_email="sebastian.vetter@tangentsnowball.com.au", description="Adding fancy CMS-style pages to Oscar", long_description=open('README.rst').read(), keywords="django, oscar, e-commerce, cms, pages, flatpages", license='BSD', platforms=['linux'], packages=find_packages(exclude=["sandbox*", "tests*"]), include_package_data=True, install_requires=[ 'versiontools>=1.9.1', 'Django>=1.4.2', 'django-oscar>=0.3', 'django-model-utils>=1.1.0', 'django-compressor>=1.2', ], dependency_links=[ 'http://github.com/tangentlabs/django-oscar/tarball/master#egg=django-oscar-0.4' ], # See http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', #'License :: OSI Approved :: BSD License', 'Operating System :: Unix', 'Programming Language :: Python' ] )
Update django to use latest security release
Update django to use latest security release
Python
bsd-3-clause
tangentlabs/django-oscar-fancypages,tangentlabs/django-oscar-fancypages
#!/usr/bin/env python from setuptools import setup, find_packages setup( name='django-oscar-fancypages', version=":versiontools:fancypages:", url='https://github.com/tangentlabs/django-oscar-fancypages', author="Sebastian Vetter", author_email="sebastian.vetter@tangentsnowball.com.au", description="Adding fancy CMS-style pages to Oscar", long_description=open('README.rst').read(), keywords="django, oscar, e-commerce, cms, pages, flatpages", license='BSD', platforms=['linux'], packages=find_packages(exclude=["sandbox*", "tests*"]), include_package_data=True, install_requires=[ 'versiontools>=1.9.1', 'Django>=1.4.1', 'django-oscar>=0.3', 'django-model-utils>=1.1.0', 'django-compressor>=1.2', ], dependency_links=[ 'http://github.com/tangentlabs/django-oscar/tarball/master#egg=django-oscar-0.4' ], # See http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', #'License :: OSI Approved :: BSD License', 'Operating System :: Unix', 'Programming Language :: Python' ] ) Update django to use latest security release
#!/usr/bin/env python from setuptools import setup, find_packages setup( name='django-oscar-fancypages', version=":versiontools:fancypages:", url='https://github.com/tangentlabs/django-oscar-fancypages', author="Sebastian Vetter", author_email="sebastian.vetter@tangentsnowball.com.au", description="Adding fancy CMS-style pages to Oscar", long_description=open('README.rst').read(), keywords="django, oscar, e-commerce, cms, pages, flatpages", license='BSD', platforms=['linux'], packages=find_packages(exclude=["sandbox*", "tests*"]), include_package_data=True, install_requires=[ 'versiontools>=1.9.1', 'Django>=1.4.2', 'django-oscar>=0.3', 'django-model-utils>=1.1.0', 'django-compressor>=1.2', ], dependency_links=[ 'http://github.com/tangentlabs/django-oscar/tarball/master#egg=django-oscar-0.4' ], # See http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', #'License :: OSI Approved :: BSD License', 'Operating System :: Unix', 'Programming Language :: Python' ] )
<commit_before>#!/usr/bin/env python from setuptools import setup, find_packages setup( name='django-oscar-fancypages', version=":versiontools:fancypages:", url='https://github.com/tangentlabs/django-oscar-fancypages', author="Sebastian Vetter", author_email="sebastian.vetter@tangentsnowball.com.au", description="Adding fancy CMS-style pages to Oscar", long_description=open('README.rst').read(), keywords="django, oscar, e-commerce, cms, pages, flatpages", license='BSD', platforms=['linux'], packages=find_packages(exclude=["sandbox*", "tests*"]), include_package_data=True, install_requires=[ 'versiontools>=1.9.1', 'Django>=1.4.1', 'django-oscar>=0.3', 'django-model-utils>=1.1.0', 'django-compressor>=1.2', ], dependency_links=[ 'http://github.com/tangentlabs/django-oscar/tarball/master#egg=django-oscar-0.4' ], # See http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', #'License :: OSI Approved :: BSD License', 'Operating System :: Unix', 'Programming Language :: Python' ] ) <commit_msg>Update django to use latest security release<commit_after>
#!/usr/bin/env python from setuptools import setup, find_packages setup( name='django-oscar-fancypages', version=":versiontools:fancypages:", url='https://github.com/tangentlabs/django-oscar-fancypages', author="Sebastian Vetter", author_email="sebastian.vetter@tangentsnowball.com.au", description="Adding fancy CMS-style pages to Oscar", long_description=open('README.rst').read(), keywords="django, oscar, e-commerce, cms, pages, flatpages", license='BSD', platforms=['linux'], packages=find_packages(exclude=["sandbox*", "tests*"]), include_package_data=True, install_requires=[ 'versiontools>=1.9.1', 'Django>=1.4.2', 'django-oscar>=0.3', 'django-model-utils>=1.1.0', 'django-compressor>=1.2', ], dependency_links=[ 'http://github.com/tangentlabs/django-oscar/tarball/master#egg=django-oscar-0.4' ], # See http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', #'License :: OSI Approved :: BSD License', 'Operating System :: Unix', 'Programming Language :: Python' ] )
#!/usr/bin/env python from setuptools import setup, find_packages setup( name='django-oscar-fancypages', version=":versiontools:fancypages:", url='https://github.com/tangentlabs/django-oscar-fancypages', author="Sebastian Vetter", author_email="sebastian.vetter@tangentsnowball.com.au", description="Adding fancy CMS-style pages to Oscar", long_description=open('README.rst').read(), keywords="django, oscar, e-commerce, cms, pages, flatpages", license='BSD', platforms=['linux'], packages=find_packages(exclude=["sandbox*", "tests*"]), include_package_data=True, install_requires=[ 'versiontools>=1.9.1', 'Django>=1.4.1', 'django-oscar>=0.3', 'django-model-utils>=1.1.0', 'django-compressor>=1.2', ], dependency_links=[ 'http://github.com/tangentlabs/django-oscar/tarball/master#egg=django-oscar-0.4' ], # See http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', #'License :: OSI Approved :: BSD License', 'Operating System :: Unix', 'Programming Language :: Python' ] ) Update django to use latest security release#!/usr/bin/env python from setuptools import setup, find_packages setup( name='django-oscar-fancypages', version=":versiontools:fancypages:", url='https://github.com/tangentlabs/django-oscar-fancypages', author="Sebastian Vetter", author_email="sebastian.vetter@tangentsnowball.com.au", description="Adding fancy CMS-style pages to Oscar", long_description=open('README.rst').read(), keywords="django, oscar, e-commerce, cms, pages, flatpages", license='BSD', platforms=['linux'], packages=find_packages(exclude=["sandbox*", "tests*"]), include_package_data=True, install_requires=[ 'versiontools>=1.9.1', 'Django>=1.4.2', 'django-oscar>=0.3', 'django-model-utils>=1.1.0', 'django-compressor>=1.2', ], dependency_links=[ 'http://github.com/tangentlabs/django-oscar/tarball/master#egg=django-oscar-0.4' ], # See http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', #'License :: OSI Approved :: BSD License', 'Operating System :: Unix', 'Programming Language :: Python' ] )
<commit_before>#!/usr/bin/env python from setuptools import setup, find_packages setup( name='django-oscar-fancypages', version=":versiontools:fancypages:", url='https://github.com/tangentlabs/django-oscar-fancypages', author="Sebastian Vetter", author_email="sebastian.vetter@tangentsnowball.com.au", description="Adding fancy CMS-style pages to Oscar", long_description=open('README.rst').read(), keywords="django, oscar, e-commerce, cms, pages, flatpages", license='BSD', platforms=['linux'], packages=find_packages(exclude=["sandbox*", "tests*"]), include_package_data=True, install_requires=[ 'versiontools>=1.9.1', 'Django>=1.4.1', 'django-oscar>=0.3', 'django-model-utils>=1.1.0', 'django-compressor>=1.2', ], dependency_links=[ 'http://github.com/tangentlabs/django-oscar/tarball/master#egg=django-oscar-0.4' ], # See http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', #'License :: OSI Approved :: BSD License', 'Operating System :: Unix', 'Programming Language :: Python' ] ) <commit_msg>Update django to use latest security release<commit_after>#!/usr/bin/env python from setuptools import setup, find_packages setup( name='django-oscar-fancypages', version=":versiontools:fancypages:", url='https://github.com/tangentlabs/django-oscar-fancypages', author="Sebastian Vetter", author_email="sebastian.vetter@tangentsnowball.com.au", description="Adding fancy CMS-style pages to Oscar", long_description=open('README.rst').read(), keywords="django, oscar, e-commerce, cms, pages, flatpages", license='BSD', platforms=['linux'], packages=find_packages(exclude=["sandbox*", "tests*"]), include_package_data=True, install_requires=[ 'versiontools>=1.9.1', 'Django>=1.4.2', 'django-oscar>=0.3', 'django-model-utils>=1.1.0', 'django-compressor>=1.2', ], dependency_links=[ 'http://github.com/tangentlabs/django-oscar/tarball/master#egg=django-oscar-0.4' ], # See http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', #'License :: OSI Approved :: BSD License', 'Operating System :: Unix', 'Programming Language :: Python' ] )
659d9be59ad816680d9c8fc13e4be67627e1d290
ecommerce/courses/utils.py
ecommerce/courses/utils.py
import hashlib from django.conf import settings from django.core.cache import cache from edx_rest_api_client.client import EdxRestApiClient from ecommerce.core.url_utils import get_lms_url def mode_for_seat(product): """ Returns the enrollment mode (aka course mode) for the specified product. If the specified product does not include a 'certificate_type' attribute it is likely the bulk purchase "enrollment code" product variant of the single-seat product, so we attempt to locate the 'seat_type' attribute in its place. """ mode = getattr(product.attr, 'certificate_type', getattr(product.attr, 'seat_type', None)) if not mode: return 'audit' if mode == 'professional' and not product.attr.id_verification_required: return 'no-id-professional' return mode def get_course_info_from_lms(course_key): """ Get course information from LMS via the course api and cache """ api = EdxRestApiClient(get_lms_url('api/courses/v1/')) cache_key = 'courses_api_detail_{}'.format(course_key) cache_hash = hashlib.md5(cache_key).hexdigest() course = cache.get(cache_hash) if not course: # pragma: no cover course = api.courses(course_key).get() cache.set(cache_hash, course, settings.COURSES_API_CACHE_TIMEOUT) return course
import hashlib from django.conf import settings from django.core.cache import cache from edx_rest_api_client.client import EdxRestApiClient from ecommerce.core.url_utils import get_lms_url def mode_for_seat(product): """ Returns the enrollment mode (aka course mode) for the specified product. If the specified product does not include a 'certificate_type' attribute it is likely the bulk purchase "enrollment code" product variant of the single-seat product, so we attempt to locate the 'seat_type' attribute in its place. """ mode = getattr(product.attr, 'certificate_type', getattr(product.attr, 'seat_type', None)) if not mode: return 'audit' if mode == 'professional' and not getattr(product.attr, 'id_verification_required', False): return 'no-id-professional' return mode def get_course_info_from_lms(course_key): """ Get course information from LMS via the course api and cache """ api = EdxRestApiClient(get_lms_url('api/courses/v1/')) cache_key = 'courses_api_detail_{}'.format(course_key) cache_hash = hashlib.md5(cache_key).hexdigest() course = cache.get(cache_hash) if not course: # pragma: no cover course = api.courses(course_key).get() cache.set(cache_hash, course, settings.COURSES_API_CACHE_TIMEOUT) return course
Handle for missing product attribute
mattdrayer/WL-525: Handle for missing product attribute
Python
agpl-3.0
mferenca/HMS-ecommerce,edx/ecommerce,eduNEXT/edunext-ecommerce,eduNEXT/edunext-ecommerce,eduNEXT/edunext-ecommerce,mferenca/HMS-ecommerce,edx/ecommerce,eduNEXT/edunext-ecommerce,edx/ecommerce,mferenca/HMS-ecommerce,edx/ecommerce
import hashlib from django.conf import settings from django.core.cache import cache from edx_rest_api_client.client import EdxRestApiClient from ecommerce.core.url_utils import get_lms_url def mode_for_seat(product): """ Returns the enrollment mode (aka course mode) for the specified product. If the specified product does not include a 'certificate_type' attribute it is likely the bulk purchase "enrollment code" product variant of the single-seat product, so we attempt to locate the 'seat_type' attribute in its place. """ mode = getattr(product.attr, 'certificate_type', getattr(product.attr, 'seat_type', None)) if not mode: return 'audit' if mode == 'professional' and not product.attr.id_verification_required: return 'no-id-professional' return mode def get_course_info_from_lms(course_key): """ Get course information from LMS via the course api and cache """ api = EdxRestApiClient(get_lms_url('api/courses/v1/')) cache_key = 'courses_api_detail_{}'.format(course_key) cache_hash = hashlib.md5(cache_key).hexdigest() course = cache.get(cache_hash) if not course: # pragma: no cover course = api.courses(course_key).get() cache.set(cache_hash, course, settings.COURSES_API_CACHE_TIMEOUT) return course mattdrayer/WL-525: Handle for missing product attribute
import hashlib from django.conf import settings from django.core.cache import cache from edx_rest_api_client.client import EdxRestApiClient from ecommerce.core.url_utils import get_lms_url def mode_for_seat(product): """ Returns the enrollment mode (aka course mode) for the specified product. If the specified product does not include a 'certificate_type' attribute it is likely the bulk purchase "enrollment code" product variant of the single-seat product, so we attempt to locate the 'seat_type' attribute in its place. """ mode = getattr(product.attr, 'certificate_type', getattr(product.attr, 'seat_type', None)) if not mode: return 'audit' if mode == 'professional' and not getattr(product.attr, 'id_verification_required', False): return 'no-id-professional' return mode def get_course_info_from_lms(course_key): """ Get course information from LMS via the course api and cache """ api = EdxRestApiClient(get_lms_url('api/courses/v1/')) cache_key = 'courses_api_detail_{}'.format(course_key) cache_hash = hashlib.md5(cache_key).hexdigest() course = cache.get(cache_hash) if not course: # pragma: no cover course = api.courses(course_key).get() cache.set(cache_hash, course, settings.COURSES_API_CACHE_TIMEOUT) return course
<commit_before>import hashlib from django.conf import settings from django.core.cache import cache from edx_rest_api_client.client import EdxRestApiClient from ecommerce.core.url_utils import get_lms_url def mode_for_seat(product): """ Returns the enrollment mode (aka course mode) for the specified product. If the specified product does not include a 'certificate_type' attribute it is likely the bulk purchase "enrollment code" product variant of the single-seat product, so we attempt to locate the 'seat_type' attribute in its place. """ mode = getattr(product.attr, 'certificate_type', getattr(product.attr, 'seat_type', None)) if not mode: return 'audit' if mode == 'professional' and not product.attr.id_verification_required: return 'no-id-professional' return mode def get_course_info_from_lms(course_key): """ Get course information from LMS via the course api and cache """ api = EdxRestApiClient(get_lms_url('api/courses/v1/')) cache_key = 'courses_api_detail_{}'.format(course_key) cache_hash = hashlib.md5(cache_key).hexdigest() course = cache.get(cache_hash) if not course: # pragma: no cover course = api.courses(course_key).get() cache.set(cache_hash, course, settings.COURSES_API_CACHE_TIMEOUT) return course <commit_msg>mattdrayer/WL-525: Handle for missing product attribute<commit_after>
import hashlib from django.conf import settings from django.core.cache import cache from edx_rest_api_client.client import EdxRestApiClient from ecommerce.core.url_utils import get_lms_url def mode_for_seat(product): """ Returns the enrollment mode (aka course mode) for the specified product. If the specified product does not include a 'certificate_type' attribute it is likely the bulk purchase "enrollment code" product variant of the single-seat product, so we attempt to locate the 'seat_type' attribute in its place. """ mode = getattr(product.attr, 'certificate_type', getattr(product.attr, 'seat_type', None)) if not mode: return 'audit' if mode == 'professional' and not getattr(product.attr, 'id_verification_required', False): return 'no-id-professional' return mode def get_course_info_from_lms(course_key): """ Get course information from LMS via the course api and cache """ api = EdxRestApiClient(get_lms_url('api/courses/v1/')) cache_key = 'courses_api_detail_{}'.format(course_key) cache_hash = hashlib.md5(cache_key).hexdigest() course = cache.get(cache_hash) if not course: # pragma: no cover course = api.courses(course_key).get() cache.set(cache_hash, course, settings.COURSES_API_CACHE_TIMEOUT) return course
import hashlib from django.conf import settings from django.core.cache import cache from edx_rest_api_client.client import EdxRestApiClient from ecommerce.core.url_utils import get_lms_url def mode_for_seat(product): """ Returns the enrollment mode (aka course mode) for the specified product. If the specified product does not include a 'certificate_type' attribute it is likely the bulk purchase "enrollment code" product variant of the single-seat product, so we attempt to locate the 'seat_type' attribute in its place. """ mode = getattr(product.attr, 'certificate_type', getattr(product.attr, 'seat_type', None)) if not mode: return 'audit' if mode == 'professional' and not product.attr.id_verification_required: return 'no-id-professional' return mode def get_course_info_from_lms(course_key): """ Get course information from LMS via the course api and cache """ api = EdxRestApiClient(get_lms_url('api/courses/v1/')) cache_key = 'courses_api_detail_{}'.format(course_key) cache_hash = hashlib.md5(cache_key).hexdigest() course = cache.get(cache_hash) if not course: # pragma: no cover course = api.courses(course_key).get() cache.set(cache_hash, course, settings.COURSES_API_CACHE_TIMEOUT) return course mattdrayer/WL-525: Handle for missing product attributeimport hashlib from django.conf import settings from django.core.cache import cache from edx_rest_api_client.client import EdxRestApiClient from ecommerce.core.url_utils import get_lms_url def mode_for_seat(product): """ Returns the enrollment mode (aka course mode) for the specified product. If the specified product does not include a 'certificate_type' attribute it is likely the bulk purchase "enrollment code" product variant of the single-seat product, so we attempt to locate the 'seat_type' attribute in its place. """ mode = getattr(product.attr, 'certificate_type', getattr(product.attr, 'seat_type', None)) if not mode: return 'audit' if mode == 'professional' and not getattr(product.attr, 'id_verification_required', False): return 'no-id-professional' return mode def get_course_info_from_lms(course_key): """ Get course information from LMS via the course api and cache """ api = EdxRestApiClient(get_lms_url('api/courses/v1/')) cache_key = 'courses_api_detail_{}'.format(course_key) cache_hash = hashlib.md5(cache_key).hexdigest() course = cache.get(cache_hash) if not course: # pragma: no cover course = api.courses(course_key).get() cache.set(cache_hash, course, settings.COURSES_API_CACHE_TIMEOUT) return course
<commit_before>import hashlib from django.conf import settings from django.core.cache import cache from edx_rest_api_client.client import EdxRestApiClient from ecommerce.core.url_utils import get_lms_url def mode_for_seat(product): """ Returns the enrollment mode (aka course mode) for the specified product. If the specified product does not include a 'certificate_type' attribute it is likely the bulk purchase "enrollment code" product variant of the single-seat product, so we attempt to locate the 'seat_type' attribute in its place. """ mode = getattr(product.attr, 'certificate_type', getattr(product.attr, 'seat_type', None)) if not mode: return 'audit' if mode == 'professional' and not product.attr.id_verification_required: return 'no-id-professional' return mode def get_course_info_from_lms(course_key): """ Get course information from LMS via the course api and cache """ api = EdxRestApiClient(get_lms_url('api/courses/v1/')) cache_key = 'courses_api_detail_{}'.format(course_key) cache_hash = hashlib.md5(cache_key).hexdigest() course = cache.get(cache_hash) if not course: # pragma: no cover course = api.courses(course_key).get() cache.set(cache_hash, course, settings.COURSES_API_CACHE_TIMEOUT) return course <commit_msg>mattdrayer/WL-525: Handle for missing product attribute<commit_after>import hashlib from django.conf import settings from django.core.cache import cache from edx_rest_api_client.client import EdxRestApiClient from ecommerce.core.url_utils import get_lms_url def mode_for_seat(product): """ Returns the enrollment mode (aka course mode) for the specified product. If the specified product does not include a 'certificate_type' attribute it is likely the bulk purchase "enrollment code" product variant of the single-seat product, so we attempt to locate the 'seat_type' attribute in its place. """ mode = getattr(product.attr, 'certificate_type', getattr(product.attr, 'seat_type', None)) if not mode: return 'audit' if mode == 'professional' and not getattr(product.attr, 'id_verification_required', False): return 'no-id-professional' return mode def get_course_info_from_lms(course_key): """ Get course information from LMS via the course api and cache """ api = EdxRestApiClient(get_lms_url('api/courses/v1/')) cache_key = 'courses_api_detail_{}'.format(course_key) cache_hash = hashlib.md5(cache_key).hexdigest() course = cache.get(cache_hash) if not course: # pragma: no cover course = api.courses(course_key).get() cache.set(cache_hash, course, settings.COURSES_API_CACHE_TIMEOUT) return course
9c32e25169fa2d0be74bdf320da401ddcb2491e3
studygroups/forms.py
studygroups/forms.py
from django import forms from studygroups.models import Application from studygroups.models import Reminder from localflavor.us.forms import USPhoneNumberField class ApplicationForm(forms.ModelForm): mobile = USPhoneNumberField(required=False) def clean(self): cleaned_data = super(ApplicationForm, self).clean() contact_method = cleaned_data.get("contact_method") if contact_method == Application.EMAIL and not cleaned_data.get('email'): self.add_error('email', "Please enter your email address or change your preferred contact method.") elif contact_method == Application.TEXT and not cleaned_data.get('mobile'): self.add_error('mobile', "Please enter your mobile number or change your preferred contact method.") class Meta: model = Application labels = { 'mobile': 'What is your mobile number?', 'contact_method': 'Preferred Method of Contact.', 'computer_access': 'Do you have access to a computer outside of the library?', 'goals': 'In one sentence, please explain your goals for taking this course.', 'support': 'A successful study group requires the support of all of its members. How will you help your peers achieve their goals?', } exclude = ['accepted_at'] widgets = {'study_group': forms.HiddenInput} class MessageForm(forms.ModelForm): class Meta: model = Reminder exclude = ['meeting_time', 'created_at', 'sent_at'] widgets = {'study_group': forms.HiddenInput}
from django import forms from studygroups.models import Application from studygroups.models import Reminder from localflavor.us.forms import USPhoneNumberField class ApplicationForm(forms.ModelForm): mobile = USPhoneNumberField(required=False) def clean(self): cleaned_data = super(ApplicationForm, self).clean() contact_method = cleaned_data.get("contact_method") if contact_method == Application.EMAIL and not cleaned_data.get('email'): self.add_error('email', "Please enter your email address or change your preferred contact method.") elif contact_method == Application.TEXT and not cleaned_data.get('mobile'): self.add_error('mobile', "Please enter your mobile number or change your preferred contact method.") class Meta: model = Application labels = { 'mobile': 'What is your mobile number?', 'contact_method': 'Preferred Method of Contact.', 'computer_access': 'Can you bring your own laptop to the Learning Circle?', 'goals': 'In one sentence, please explain your goals for taking this course.', 'support': 'A successful study group requires the support of all of its members. How will you help your peers achieve their goals?', } exclude = ['accepted_at'] widgets = {'study_group': forms.HiddenInput} class MessageForm(forms.ModelForm): class Meta: model = Reminder exclude = ['meeting_time', 'created_at', 'sent_at'] widgets = {'study_group': forms.HiddenInput}
Update question about computer access
Update question about computer access
Python
mit
p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles
from django import forms from studygroups.models import Application from studygroups.models import Reminder from localflavor.us.forms import USPhoneNumberField class ApplicationForm(forms.ModelForm): mobile = USPhoneNumberField(required=False) def clean(self): cleaned_data = super(ApplicationForm, self).clean() contact_method = cleaned_data.get("contact_method") if contact_method == Application.EMAIL and not cleaned_data.get('email'): self.add_error('email', "Please enter your email address or change your preferred contact method.") elif contact_method == Application.TEXT and not cleaned_data.get('mobile'): self.add_error('mobile', "Please enter your mobile number or change your preferred contact method.") class Meta: model = Application labels = { 'mobile': 'What is your mobile number?', 'contact_method': 'Preferred Method of Contact.', 'computer_access': 'Do you have access to a computer outside of the library?', 'goals': 'In one sentence, please explain your goals for taking this course.', 'support': 'A successful study group requires the support of all of its members. How will you help your peers achieve their goals?', } exclude = ['accepted_at'] widgets = {'study_group': forms.HiddenInput} class MessageForm(forms.ModelForm): class Meta: model = Reminder exclude = ['meeting_time', 'created_at', 'sent_at'] widgets = {'study_group': forms.HiddenInput} Update question about computer access
from django import forms from studygroups.models import Application from studygroups.models import Reminder from localflavor.us.forms import USPhoneNumberField class ApplicationForm(forms.ModelForm): mobile = USPhoneNumberField(required=False) def clean(self): cleaned_data = super(ApplicationForm, self).clean() contact_method = cleaned_data.get("contact_method") if contact_method == Application.EMAIL and not cleaned_data.get('email'): self.add_error('email', "Please enter your email address or change your preferred contact method.") elif contact_method == Application.TEXT and not cleaned_data.get('mobile'): self.add_error('mobile', "Please enter your mobile number or change your preferred contact method.") class Meta: model = Application labels = { 'mobile': 'What is your mobile number?', 'contact_method': 'Preferred Method of Contact.', 'computer_access': 'Can you bring your own laptop to the Learning Circle?', 'goals': 'In one sentence, please explain your goals for taking this course.', 'support': 'A successful study group requires the support of all of its members. How will you help your peers achieve their goals?', } exclude = ['accepted_at'] widgets = {'study_group': forms.HiddenInput} class MessageForm(forms.ModelForm): class Meta: model = Reminder exclude = ['meeting_time', 'created_at', 'sent_at'] widgets = {'study_group': forms.HiddenInput}
<commit_before>from django import forms from studygroups.models import Application from studygroups.models import Reminder from localflavor.us.forms import USPhoneNumberField class ApplicationForm(forms.ModelForm): mobile = USPhoneNumberField(required=False) def clean(self): cleaned_data = super(ApplicationForm, self).clean() contact_method = cleaned_data.get("contact_method") if contact_method == Application.EMAIL and not cleaned_data.get('email'): self.add_error('email', "Please enter your email address or change your preferred contact method.") elif contact_method == Application.TEXT and not cleaned_data.get('mobile'): self.add_error('mobile', "Please enter your mobile number or change your preferred contact method.") class Meta: model = Application labels = { 'mobile': 'What is your mobile number?', 'contact_method': 'Preferred Method of Contact.', 'computer_access': 'Do you have access to a computer outside of the library?', 'goals': 'In one sentence, please explain your goals for taking this course.', 'support': 'A successful study group requires the support of all of its members. How will you help your peers achieve their goals?', } exclude = ['accepted_at'] widgets = {'study_group': forms.HiddenInput} class MessageForm(forms.ModelForm): class Meta: model = Reminder exclude = ['meeting_time', 'created_at', 'sent_at'] widgets = {'study_group': forms.HiddenInput} <commit_msg>Update question about computer access<commit_after>
from django import forms from studygroups.models import Application from studygroups.models import Reminder from localflavor.us.forms import USPhoneNumberField class ApplicationForm(forms.ModelForm): mobile = USPhoneNumberField(required=False) def clean(self): cleaned_data = super(ApplicationForm, self).clean() contact_method = cleaned_data.get("contact_method") if contact_method == Application.EMAIL and not cleaned_data.get('email'): self.add_error('email', "Please enter your email address or change your preferred contact method.") elif contact_method == Application.TEXT and not cleaned_data.get('mobile'): self.add_error('mobile', "Please enter your mobile number or change your preferred contact method.") class Meta: model = Application labels = { 'mobile': 'What is your mobile number?', 'contact_method': 'Preferred Method of Contact.', 'computer_access': 'Can you bring your own laptop to the Learning Circle?', 'goals': 'In one sentence, please explain your goals for taking this course.', 'support': 'A successful study group requires the support of all of its members. How will you help your peers achieve their goals?', } exclude = ['accepted_at'] widgets = {'study_group': forms.HiddenInput} class MessageForm(forms.ModelForm): class Meta: model = Reminder exclude = ['meeting_time', 'created_at', 'sent_at'] widgets = {'study_group': forms.HiddenInput}
from django import forms from studygroups.models import Application from studygroups.models import Reminder from localflavor.us.forms import USPhoneNumberField class ApplicationForm(forms.ModelForm): mobile = USPhoneNumberField(required=False) def clean(self): cleaned_data = super(ApplicationForm, self).clean() contact_method = cleaned_data.get("contact_method") if contact_method == Application.EMAIL and not cleaned_data.get('email'): self.add_error('email', "Please enter your email address or change your preferred contact method.") elif contact_method == Application.TEXT and not cleaned_data.get('mobile'): self.add_error('mobile', "Please enter your mobile number or change your preferred contact method.") class Meta: model = Application labels = { 'mobile': 'What is your mobile number?', 'contact_method': 'Preferred Method of Contact.', 'computer_access': 'Do you have access to a computer outside of the library?', 'goals': 'In one sentence, please explain your goals for taking this course.', 'support': 'A successful study group requires the support of all of its members. How will you help your peers achieve their goals?', } exclude = ['accepted_at'] widgets = {'study_group': forms.HiddenInput} class MessageForm(forms.ModelForm): class Meta: model = Reminder exclude = ['meeting_time', 'created_at', 'sent_at'] widgets = {'study_group': forms.HiddenInput} Update question about computer accessfrom django import forms from studygroups.models import Application from studygroups.models import Reminder from localflavor.us.forms import USPhoneNumberField class ApplicationForm(forms.ModelForm): mobile = USPhoneNumberField(required=False) def clean(self): cleaned_data = super(ApplicationForm, self).clean() contact_method = cleaned_data.get("contact_method") if contact_method == Application.EMAIL and not cleaned_data.get('email'): self.add_error('email', "Please enter your email address or change your preferred contact method.") elif contact_method == Application.TEXT and not cleaned_data.get('mobile'): self.add_error('mobile', "Please enter your mobile number or change your preferred contact method.") class Meta: model = Application labels = { 'mobile': 'What is your mobile number?', 'contact_method': 'Preferred Method of Contact.', 'computer_access': 'Can you bring your own laptop to the Learning Circle?', 'goals': 'In one sentence, please explain your goals for taking this course.', 'support': 'A successful study group requires the support of all of its members. How will you help your peers achieve their goals?', } exclude = ['accepted_at'] widgets = {'study_group': forms.HiddenInput} class MessageForm(forms.ModelForm): class Meta: model = Reminder exclude = ['meeting_time', 'created_at', 'sent_at'] widgets = {'study_group': forms.HiddenInput}
<commit_before>from django import forms from studygroups.models import Application from studygroups.models import Reminder from localflavor.us.forms import USPhoneNumberField class ApplicationForm(forms.ModelForm): mobile = USPhoneNumberField(required=False) def clean(self): cleaned_data = super(ApplicationForm, self).clean() contact_method = cleaned_data.get("contact_method") if contact_method == Application.EMAIL and not cleaned_data.get('email'): self.add_error('email', "Please enter your email address or change your preferred contact method.") elif contact_method == Application.TEXT and not cleaned_data.get('mobile'): self.add_error('mobile', "Please enter your mobile number or change your preferred contact method.") class Meta: model = Application labels = { 'mobile': 'What is your mobile number?', 'contact_method': 'Preferred Method of Contact.', 'computer_access': 'Do you have access to a computer outside of the library?', 'goals': 'In one sentence, please explain your goals for taking this course.', 'support': 'A successful study group requires the support of all of its members. How will you help your peers achieve their goals?', } exclude = ['accepted_at'] widgets = {'study_group': forms.HiddenInput} class MessageForm(forms.ModelForm): class Meta: model = Reminder exclude = ['meeting_time', 'created_at', 'sent_at'] widgets = {'study_group': forms.HiddenInput} <commit_msg>Update question about computer access<commit_after>from django import forms from studygroups.models import Application from studygroups.models import Reminder from localflavor.us.forms import USPhoneNumberField class ApplicationForm(forms.ModelForm): mobile = USPhoneNumberField(required=False) def clean(self): cleaned_data = super(ApplicationForm, self).clean() contact_method = cleaned_data.get("contact_method") if contact_method == Application.EMAIL and not cleaned_data.get('email'): self.add_error('email', "Please enter your email address or change your preferred contact method.") elif contact_method == Application.TEXT and not cleaned_data.get('mobile'): self.add_error('mobile', "Please enter your mobile number or change your preferred contact method.") class Meta: model = Application labels = { 'mobile': 'What is your mobile number?', 'contact_method': 'Preferred Method of Contact.', 'computer_access': 'Can you bring your own laptop to the Learning Circle?', 'goals': 'In one sentence, please explain your goals for taking this course.', 'support': 'A successful study group requires the support of all of its members. How will you help your peers achieve their goals?', } exclude = ['accepted_at'] widgets = {'study_group': forms.HiddenInput} class MessageForm(forms.ModelForm): class Meta: model = Reminder exclude = ['meeting_time', 'created_at', 'sent_at'] widgets = {'study_group': forms.HiddenInput}
4e0bbffd400885030af0cbba20cacde1804aefbc
blockbuster/bb_logging.py
blockbuster/bb_logging.py
import logging import logging.handlers # ######### Set up logging ########## # log.basicConfig(format="%(asctime)s - %(levelname)s: %(message)s", level=log.DEBUG) logger = logging.getLogger('bb_log') logger.setLevel(logging.DEBUG) # create file handler which logs even debug messages tfh = logging.handlers.TimedRotatingFileHandler('./logs/app.log', when='midnight', delay=False, encoding=None, backupCount=7) tfh.setLevel(logging.DEBUG) # create console handler with a higher log level ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) # create formatter and add it to the handlers formatterch = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s') formattertfh = logging.Formatter('%(asctime)s [%(levelname)s] [%(name)s] %(message)s') ch.setFormatter(formatterch) tfh.setFormatter(formattertfh) # add the handlers to logger logger.addHandler(ch) logger.addHandler(tfh)
import config import logging import logging.handlers # ######### Set up logging ########## # log.basicConfig(format="%(asctime)s - %(levelname)s: %(message)s", level=log.DEBUG) logger = logging.getLogger('bb_log') logger.setLevel(logging.DEBUG) # create file handler which logs even debug messages tfh = logging.handlers.TimedRotatingFileHandler(str.format('{0}/app.log', config.log_directory), when='midnight', delay=False, encoding=None, backupCount=7) tfh.setLevel(logging.DEBUG) # create console handler with a higher log level ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) # create formatter and add it to the handlers formatterch = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s') formattertfh = logging.Formatter('%(asctime)s [%(levelname)s] [%(name)s] %(message)s') ch.setFormatter(formatterch) tfh.setFormatter(formattertfh) # add the handlers to logger logger.addHandler(ch) logger.addHandler(tfh)
Change file logHandler to use configured path for log files
Change file logHandler to use configured path for log files
Python
mit
mattstibbs/blockbuster-server,mattstibbs/blockbuster-server
import logging import logging.handlers # ######### Set up logging ########## # log.basicConfig(format="%(asctime)s - %(levelname)s: %(message)s", level=log.DEBUG) logger = logging.getLogger('bb_log') logger.setLevel(logging.DEBUG) # create file handler which logs even debug messages tfh = logging.handlers.TimedRotatingFileHandler('./logs/app.log', when='midnight', delay=False, encoding=None, backupCount=7) tfh.setLevel(logging.DEBUG) # create console handler with a higher log level ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) # create formatter and add it to the handlers formatterch = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s') formattertfh = logging.Formatter('%(asctime)s [%(levelname)s] [%(name)s] %(message)s') ch.setFormatter(formatterch) tfh.setFormatter(formattertfh) # add the handlers to logger logger.addHandler(ch) logger.addHandler(tfh)Change file logHandler to use configured path for log files
import config import logging import logging.handlers # ######### Set up logging ########## # log.basicConfig(format="%(asctime)s - %(levelname)s: %(message)s", level=log.DEBUG) logger = logging.getLogger('bb_log') logger.setLevel(logging.DEBUG) # create file handler which logs even debug messages tfh = logging.handlers.TimedRotatingFileHandler(str.format('{0}/app.log', config.log_directory), when='midnight', delay=False, encoding=None, backupCount=7) tfh.setLevel(logging.DEBUG) # create console handler with a higher log level ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) # create formatter and add it to the handlers formatterch = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s') formattertfh = logging.Formatter('%(asctime)s [%(levelname)s] [%(name)s] %(message)s') ch.setFormatter(formatterch) tfh.setFormatter(formattertfh) # add the handlers to logger logger.addHandler(ch) logger.addHandler(tfh)
<commit_before>import logging import logging.handlers # ######### Set up logging ########## # log.basicConfig(format="%(asctime)s - %(levelname)s: %(message)s", level=log.DEBUG) logger = logging.getLogger('bb_log') logger.setLevel(logging.DEBUG) # create file handler which logs even debug messages tfh = logging.handlers.TimedRotatingFileHandler('./logs/app.log', when='midnight', delay=False, encoding=None, backupCount=7) tfh.setLevel(logging.DEBUG) # create console handler with a higher log level ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) # create formatter and add it to the handlers formatterch = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s') formattertfh = logging.Formatter('%(asctime)s [%(levelname)s] [%(name)s] %(message)s') ch.setFormatter(formatterch) tfh.setFormatter(formattertfh) # add the handlers to logger logger.addHandler(ch) logger.addHandler(tfh)<commit_msg>Change file logHandler to use configured path for log files<commit_after>
import config import logging import logging.handlers # ######### Set up logging ########## # log.basicConfig(format="%(asctime)s - %(levelname)s: %(message)s", level=log.DEBUG) logger = logging.getLogger('bb_log') logger.setLevel(logging.DEBUG) # create file handler which logs even debug messages tfh = logging.handlers.TimedRotatingFileHandler(str.format('{0}/app.log', config.log_directory), when='midnight', delay=False, encoding=None, backupCount=7) tfh.setLevel(logging.DEBUG) # create console handler with a higher log level ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) # create formatter and add it to the handlers formatterch = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s') formattertfh = logging.Formatter('%(asctime)s [%(levelname)s] [%(name)s] %(message)s') ch.setFormatter(formatterch) tfh.setFormatter(formattertfh) # add the handlers to logger logger.addHandler(ch) logger.addHandler(tfh)
import logging import logging.handlers # ######### Set up logging ########## # log.basicConfig(format="%(asctime)s - %(levelname)s: %(message)s", level=log.DEBUG) logger = logging.getLogger('bb_log') logger.setLevel(logging.DEBUG) # create file handler which logs even debug messages tfh = logging.handlers.TimedRotatingFileHandler('./logs/app.log', when='midnight', delay=False, encoding=None, backupCount=7) tfh.setLevel(logging.DEBUG) # create console handler with a higher log level ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) # create formatter and add it to the handlers formatterch = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s') formattertfh = logging.Formatter('%(asctime)s [%(levelname)s] [%(name)s] %(message)s') ch.setFormatter(formatterch) tfh.setFormatter(formattertfh) # add the handlers to logger logger.addHandler(ch) logger.addHandler(tfh)Change file logHandler to use configured path for log filesimport config import logging import logging.handlers # ######### Set up logging ########## # log.basicConfig(format="%(asctime)s - %(levelname)s: %(message)s", level=log.DEBUG) logger = logging.getLogger('bb_log') logger.setLevel(logging.DEBUG) # create file handler which logs even debug messages tfh = logging.handlers.TimedRotatingFileHandler(str.format('{0}/app.log', config.log_directory), when='midnight', delay=False, encoding=None, backupCount=7) tfh.setLevel(logging.DEBUG) # create console handler with a higher log level ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) # create formatter and add it to the handlers formatterch = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s') formattertfh = logging.Formatter('%(asctime)s [%(levelname)s] [%(name)s] %(message)s') ch.setFormatter(formatterch) tfh.setFormatter(formattertfh) # add the handlers to logger logger.addHandler(ch) logger.addHandler(tfh)
<commit_before>import logging import logging.handlers # ######### Set up logging ########## # log.basicConfig(format="%(asctime)s - %(levelname)s: %(message)s", level=log.DEBUG) logger = logging.getLogger('bb_log') logger.setLevel(logging.DEBUG) # create file handler which logs even debug messages tfh = logging.handlers.TimedRotatingFileHandler('./logs/app.log', when='midnight', delay=False, encoding=None, backupCount=7) tfh.setLevel(logging.DEBUG) # create console handler with a higher log level ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) # create formatter and add it to the handlers formatterch = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s') formattertfh = logging.Formatter('%(asctime)s [%(levelname)s] [%(name)s] %(message)s') ch.setFormatter(formatterch) tfh.setFormatter(formattertfh) # add the handlers to logger logger.addHandler(ch) logger.addHandler(tfh)<commit_msg>Change file logHandler to use configured path for log files<commit_after>import config import logging import logging.handlers # ######### Set up logging ########## # log.basicConfig(format="%(asctime)s - %(levelname)s: %(message)s", level=log.DEBUG) logger = logging.getLogger('bb_log') logger.setLevel(logging.DEBUG) # create file handler which logs even debug messages tfh = logging.handlers.TimedRotatingFileHandler(str.format('{0}/app.log', config.log_directory), when='midnight', delay=False, encoding=None, backupCount=7) tfh.setLevel(logging.DEBUG) # create console handler with a higher log level ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) # create formatter and add it to the handlers formatterch = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s') formattertfh = logging.Formatter('%(asctime)s [%(levelname)s] [%(name)s] %(message)s') ch.setFormatter(formatterch) tfh.setFormatter(formattertfh) # add the handlers to logger logger.addHandler(ch) logger.addHandler(tfh)
bf56b75607a6728b12470e0b48074d0ad8124b66
views.py
views.py
from flask import Flask, render_template, make_response from image_helpers import create_image app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/<width>x<height>') @app.route('/<width>X<height>') def serve_image(width, height): stringfile = create_image(width, height) response = make_response(stringfile.getvalue()) response.headers["Content-Type"] = "image/jpeg" return response if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')
from flask import Flask, render_template, make_response from image_helpers import create_image app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/<width>x<height>') @app.route('/<width>X<height>') @app.route('/<width>x<height>/') @app.route('/<width>X<height>/') def serve_image(width, height): stringfile = create_image(width, height) response = make_response(stringfile.getvalue()) response.headers["Content-Type"] = "image/jpeg" return response if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')
Add support for appending /
Add support for appending /
Python
mit
agnethesoraa/placepuppy,agnethesoraa/placepuppy
from flask import Flask, render_template, make_response from image_helpers import create_image app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/<width>x<height>') @app.route('/<width>X<height>') def serve_image(width, height): stringfile = create_image(width, height) response = make_response(stringfile.getvalue()) response.headers["Content-Type"] = "image/jpeg" return response if __name__ == '__main__': app.run(debug=True, host='0.0.0.0') Add support for appending /
from flask import Flask, render_template, make_response from image_helpers import create_image app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/<width>x<height>') @app.route('/<width>X<height>') @app.route('/<width>x<height>/') @app.route('/<width>X<height>/') def serve_image(width, height): stringfile = create_image(width, height) response = make_response(stringfile.getvalue()) response.headers["Content-Type"] = "image/jpeg" return response if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')
<commit_before>from flask import Flask, render_template, make_response from image_helpers import create_image app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/<width>x<height>') @app.route('/<width>X<height>') def serve_image(width, height): stringfile = create_image(width, height) response = make_response(stringfile.getvalue()) response.headers["Content-Type"] = "image/jpeg" return response if __name__ == '__main__': app.run(debug=True, host='0.0.0.0') <commit_msg>Add support for appending /<commit_after>
from flask import Flask, render_template, make_response from image_helpers import create_image app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/<width>x<height>') @app.route('/<width>X<height>') @app.route('/<width>x<height>/') @app.route('/<width>X<height>/') def serve_image(width, height): stringfile = create_image(width, height) response = make_response(stringfile.getvalue()) response.headers["Content-Type"] = "image/jpeg" return response if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')
from flask import Flask, render_template, make_response from image_helpers import create_image app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/<width>x<height>') @app.route('/<width>X<height>') def serve_image(width, height): stringfile = create_image(width, height) response = make_response(stringfile.getvalue()) response.headers["Content-Type"] = "image/jpeg" return response if __name__ == '__main__': app.run(debug=True, host='0.0.0.0') Add support for appending /from flask import Flask, render_template, make_response from image_helpers import create_image app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/<width>x<height>') @app.route('/<width>X<height>') @app.route('/<width>x<height>/') @app.route('/<width>X<height>/') def serve_image(width, height): stringfile = create_image(width, height) response = make_response(stringfile.getvalue()) response.headers["Content-Type"] = "image/jpeg" return response if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')
<commit_before>from flask import Flask, render_template, make_response from image_helpers import create_image app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/<width>x<height>') @app.route('/<width>X<height>') def serve_image(width, height): stringfile = create_image(width, height) response = make_response(stringfile.getvalue()) response.headers["Content-Type"] = "image/jpeg" return response if __name__ == '__main__': app.run(debug=True, host='0.0.0.0') <commit_msg>Add support for appending /<commit_after>from flask import Flask, render_template, make_response from image_helpers import create_image app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/<width>x<height>') @app.route('/<width>X<height>') @app.route('/<width>x<height>/') @app.route('/<width>X<height>/') def serve_image(width, height): stringfile = create_image(width, height) response = make_response(stringfile.getvalue()) response.headers["Content-Type"] = "image/jpeg" return response if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')
9e5be1a70936ce206e9f99dd90e4f26b3a78616e
fjord/settings/__init__.py
fjord/settings/__init__.py
import sys # This is imported as the DJANGO_SETTINGS_MODULE. It imports local.py # which imports base.py which imports funfactory.settings_base. # # Thus: # # 1. base.py overrides funfactory.settings_base # 2. local.py overrides everything # 3. if we're running tests, tests override local try: from fjord.settings.local import * except ImportError as exc: exc.args = tuple(['%s (did you rename settings/local.py-dist?)' % exc.args[0]]) raise exc TEST = len(sys.argv) > 1 and sys.argv[1] == 'test' if TEST: print 'TEST CONFIG' from fjord.settings.test import *
import sys # This is imported as the DJANGO_SETTINGS_MODULE. It imports local.py # which imports base.py which imports funfactory.settings_base. # # Thus: # # 1. base.py overrides funfactory.settings_base # 2. local.py overrides everything # 3. if we're running tests, tests override local try: from fjord.settings.local import * except ImportError as exc: exc.args = tuple(['%s (did you rename settings/local.py-dist?)' % exc.args[0]]) raise exc print sys.argv TEST = len(sys.argv) > 1 and sys.argv[1] == 'test' if TEST: print 'TEST CONFIG' from fjord.settings.test import *
Add debugging print statment for jenkins
Add debugging print statment for jenkins
Python
bsd-3-clause
staranjeet/fjord,rlr/fjord,rlr/fjord,DESHRAJ/fjord,lgp171188/fjord,hoosteeno/fjord,Ritsyy/fjord,staranjeet/fjord,lgp171188/fjord,mozilla/fjord,lgp171188/fjord,mozilla/fjord,lgp171188/fjord,DESHRAJ/fjord,mozilla/fjord,Ritsyy/fjord,staranjeet/fjord,rlr/fjord,DESHRAJ/fjord,hoosteeno/fjord,staranjeet/fjord,mozilla/fjord,rlr/fjord,hoosteeno/fjord,hoosteeno/fjord,Ritsyy/fjord,Ritsyy/fjord
import sys # This is imported as the DJANGO_SETTINGS_MODULE. It imports local.py # which imports base.py which imports funfactory.settings_base. # # Thus: # # 1. base.py overrides funfactory.settings_base # 2. local.py overrides everything # 3. if we're running tests, tests override local try: from fjord.settings.local import * except ImportError as exc: exc.args = tuple(['%s (did you rename settings/local.py-dist?)' % exc.args[0]]) raise exc TEST = len(sys.argv) > 1 and sys.argv[1] == 'test' if TEST: print 'TEST CONFIG' from fjord.settings.test import * Add debugging print statment for jenkins
import sys # This is imported as the DJANGO_SETTINGS_MODULE. It imports local.py # which imports base.py which imports funfactory.settings_base. # # Thus: # # 1. base.py overrides funfactory.settings_base # 2. local.py overrides everything # 3. if we're running tests, tests override local try: from fjord.settings.local import * except ImportError as exc: exc.args = tuple(['%s (did you rename settings/local.py-dist?)' % exc.args[0]]) raise exc print sys.argv TEST = len(sys.argv) > 1 and sys.argv[1] == 'test' if TEST: print 'TEST CONFIG' from fjord.settings.test import *
<commit_before>import sys # This is imported as the DJANGO_SETTINGS_MODULE. It imports local.py # which imports base.py which imports funfactory.settings_base. # # Thus: # # 1. base.py overrides funfactory.settings_base # 2. local.py overrides everything # 3. if we're running tests, tests override local try: from fjord.settings.local import * except ImportError as exc: exc.args = tuple(['%s (did you rename settings/local.py-dist?)' % exc.args[0]]) raise exc TEST = len(sys.argv) > 1 and sys.argv[1] == 'test' if TEST: print 'TEST CONFIG' from fjord.settings.test import * <commit_msg>Add debugging print statment for jenkins<commit_after>
import sys # This is imported as the DJANGO_SETTINGS_MODULE. It imports local.py # which imports base.py which imports funfactory.settings_base. # # Thus: # # 1. base.py overrides funfactory.settings_base # 2. local.py overrides everything # 3. if we're running tests, tests override local try: from fjord.settings.local import * except ImportError as exc: exc.args = tuple(['%s (did you rename settings/local.py-dist?)' % exc.args[0]]) raise exc print sys.argv TEST = len(sys.argv) > 1 and sys.argv[1] == 'test' if TEST: print 'TEST CONFIG' from fjord.settings.test import *
import sys # This is imported as the DJANGO_SETTINGS_MODULE. It imports local.py # which imports base.py which imports funfactory.settings_base. # # Thus: # # 1. base.py overrides funfactory.settings_base # 2. local.py overrides everything # 3. if we're running tests, tests override local try: from fjord.settings.local import * except ImportError as exc: exc.args = tuple(['%s (did you rename settings/local.py-dist?)' % exc.args[0]]) raise exc TEST = len(sys.argv) > 1 and sys.argv[1] == 'test' if TEST: print 'TEST CONFIG' from fjord.settings.test import * Add debugging print statment for jenkinsimport sys # This is imported as the DJANGO_SETTINGS_MODULE. It imports local.py # which imports base.py which imports funfactory.settings_base. # # Thus: # # 1. base.py overrides funfactory.settings_base # 2. local.py overrides everything # 3. if we're running tests, tests override local try: from fjord.settings.local import * except ImportError as exc: exc.args = tuple(['%s (did you rename settings/local.py-dist?)' % exc.args[0]]) raise exc print sys.argv TEST = len(sys.argv) > 1 and sys.argv[1] == 'test' if TEST: print 'TEST CONFIG' from fjord.settings.test import *
<commit_before>import sys # This is imported as the DJANGO_SETTINGS_MODULE. It imports local.py # which imports base.py which imports funfactory.settings_base. # # Thus: # # 1. base.py overrides funfactory.settings_base # 2. local.py overrides everything # 3. if we're running tests, tests override local try: from fjord.settings.local import * except ImportError as exc: exc.args = tuple(['%s (did you rename settings/local.py-dist?)' % exc.args[0]]) raise exc TEST = len(sys.argv) > 1 and sys.argv[1] == 'test' if TEST: print 'TEST CONFIG' from fjord.settings.test import * <commit_msg>Add debugging print statment for jenkins<commit_after>import sys # This is imported as the DJANGO_SETTINGS_MODULE. It imports local.py # which imports base.py which imports funfactory.settings_base. # # Thus: # # 1. base.py overrides funfactory.settings_base # 2. local.py overrides everything # 3. if we're running tests, tests override local try: from fjord.settings.local import * except ImportError as exc: exc.args = tuple(['%s (did you rename settings/local.py-dist?)' % exc.args[0]]) raise exc print sys.argv TEST = len(sys.argv) > 1 and sys.argv[1] == 'test' if TEST: print 'TEST CONFIG' from fjord.settings.test import *
734100112759b8f52be6013fb69988bd4b203f71
magnum/tests/functional/mesos/test_mesos_python_client.py
magnum/tests/functional/mesos/test_mesos_python_client.py
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from magnum.tests.functional.python_client_base import BayTest class TestBayModelResource(BayTest): coe = 'mesos' def test_baymodel_create_and_delete(self): self._test_baymodel_create_and_delete('test_mesos_baymodel') class TestBayResource(BayTest): coe = 'mesos' def test_bay_create_and_delete(self): baymodel_uuid = self._test_baymodel_create_and_delete( 'test_mesos_baymodel', delete=False, tls_disabled=True, network_driver='docker') self._test_bay_create_and_delete('test_mesos_bay', baymodel_uuid)
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from magnum.tests.functional.python_client_base import BayTest class TestBayModelResource(BayTest): coe = 'mesos' def test_baymodel_create_and_delete(self): self._test_baymodel_create_and_delete('test_mesos_baymodel', network_driver='docker') class TestBayResource(BayTest): coe = 'mesos' def test_bay_create_and_delete(self): baymodel_uuid = self._test_baymodel_create_and_delete( 'test_mesos_baymodel', delete=False, tls_disabled=True, network_driver='docker') self._test_bay_create_and_delete('test_mesos_bay', baymodel_uuid)
Fix mesos baymodel creation case
Functional: Fix mesos baymodel creation case Mesos expects a docker network driver type. Partially implements: blueprint mesos-functional-testing Change-Id: I74946b51c9cb852f016c6e265d1700ae8bc3aa17
Python
apache-2.0
openstack/magnum,openstack/magnum,ArchiFleKs/magnum,jay-lau/magnum,ArchiFleKs/magnum
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from magnum.tests.functional.python_client_base import BayTest class TestBayModelResource(BayTest): coe = 'mesos' def test_baymodel_create_and_delete(self): self._test_baymodel_create_and_delete('test_mesos_baymodel') class TestBayResource(BayTest): coe = 'mesos' def test_bay_create_and_delete(self): baymodel_uuid = self._test_baymodel_create_and_delete( 'test_mesos_baymodel', delete=False, tls_disabled=True, network_driver='docker') self._test_bay_create_and_delete('test_mesos_bay', baymodel_uuid) Functional: Fix mesos baymodel creation case Mesos expects a docker network driver type. Partially implements: blueprint mesos-functional-testing Change-Id: I74946b51c9cb852f016c6e265d1700ae8bc3aa17
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from magnum.tests.functional.python_client_base import BayTest class TestBayModelResource(BayTest): coe = 'mesos' def test_baymodel_create_and_delete(self): self._test_baymodel_create_and_delete('test_mesos_baymodel', network_driver='docker') class TestBayResource(BayTest): coe = 'mesos' def test_bay_create_and_delete(self): baymodel_uuid = self._test_baymodel_create_and_delete( 'test_mesos_baymodel', delete=False, tls_disabled=True, network_driver='docker') self._test_bay_create_and_delete('test_mesos_bay', baymodel_uuid)
<commit_before># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from magnum.tests.functional.python_client_base import BayTest class TestBayModelResource(BayTest): coe = 'mesos' def test_baymodel_create_and_delete(self): self._test_baymodel_create_and_delete('test_mesos_baymodel') class TestBayResource(BayTest): coe = 'mesos' def test_bay_create_and_delete(self): baymodel_uuid = self._test_baymodel_create_and_delete( 'test_mesos_baymodel', delete=False, tls_disabled=True, network_driver='docker') self._test_bay_create_and_delete('test_mesos_bay', baymodel_uuid) <commit_msg>Functional: Fix mesos baymodel creation case Mesos expects a docker network driver type. Partially implements: blueprint mesos-functional-testing Change-Id: I74946b51c9cb852f016c6e265d1700ae8bc3aa17<commit_after>
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from magnum.tests.functional.python_client_base import BayTest class TestBayModelResource(BayTest): coe = 'mesos' def test_baymodel_create_and_delete(self): self._test_baymodel_create_and_delete('test_mesos_baymodel', network_driver='docker') class TestBayResource(BayTest): coe = 'mesos' def test_bay_create_and_delete(self): baymodel_uuid = self._test_baymodel_create_and_delete( 'test_mesos_baymodel', delete=False, tls_disabled=True, network_driver='docker') self._test_bay_create_and_delete('test_mesos_bay', baymodel_uuid)
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from magnum.tests.functional.python_client_base import BayTest class TestBayModelResource(BayTest): coe = 'mesos' def test_baymodel_create_and_delete(self): self._test_baymodel_create_and_delete('test_mesos_baymodel') class TestBayResource(BayTest): coe = 'mesos' def test_bay_create_and_delete(self): baymodel_uuid = self._test_baymodel_create_and_delete( 'test_mesos_baymodel', delete=False, tls_disabled=True, network_driver='docker') self._test_bay_create_and_delete('test_mesos_bay', baymodel_uuid) Functional: Fix mesos baymodel creation case Mesos expects a docker network driver type. Partially implements: blueprint mesos-functional-testing Change-Id: I74946b51c9cb852f016c6e265d1700ae8bc3aa17# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from magnum.tests.functional.python_client_base import BayTest class TestBayModelResource(BayTest): coe = 'mesos' def test_baymodel_create_and_delete(self): self._test_baymodel_create_and_delete('test_mesos_baymodel', network_driver='docker') class TestBayResource(BayTest): coe = 'mesos' def test_bay_create_and_delete(self): baymodel_uuid = self._test_baymodel_create_and_delete( 'test_mesos_baymodel', delete=False, tls_disabled=True, network_driver='docker') self._test_bay_create_and_delete('test_mesos_bay', baymodel_uuid)
<commit_before># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from magnum.tests.functional.python_client_base import BayTest class TestBayModelResource(BayTest): coe = 'mesos' def test_baymodel_create_and_delete(self): self._test_baymodel_create_and_delete('test_mesos_baymodel') class TestBayResource(BayTest): coe = 'mesos' def test_bay_create_and_delete(self): baymodel_uuid = self._test_baymodel_create_and_delete( 'test_mesos_baymodel', delete=False, tls_disabled=True, network_driver='docker') self._test_bay_create_and_delete('test_mesos_bay', baymodel_uuid) <commit_msg>Functional: Fix mesos baymodel creation case Mesos expects a docker network driver type. Partially implements: blueprint mesos-functional-testing Change-Id: I74946b51c9cb852f016c6e265d1700ae8bc3aa17<commit_after># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from magnum.tests.functional.python_client_base import BayTest class TestBayModelResource(BayTest): coe = 'mesos' def test_baymodel_create_and_delete(self): self._test_baymodel_create_and_delete('test_mesos_baymodel', network_driver='docker') class TestBayResource(BayTest): coe = 'mesos' def test_bay_create_and_delete(self): baymodel_uuid = self._test_baymodel_create_and_delete( 'test_mesos_baymodel', delete=False, tls_disabled=True, network_driver='docker') self._test_bay_create_and_delete('test_mesos_bay', baymodel_uuid)
828c300973d47ce09844840176f2e9e68d955bbd
wrt/wrt-manifest-tizen-tests/const.py
wrt/wrt-manifest-tizen-tests/const.py
#!/usr/bin/env python import sys, os import itertools, shutil Tizen_User=os.environ['TIZEN_USER'] path = os.path.abspath(__file__) path = os.path.split(path)[0] os.chdir(path) print path device_ssh_ip = "" ssh_device = device_ssh_ip.split(",") path_tcs = path + "/tcs" path_result= path + "/result" path_allpairs = path + "/allpairs" path_resource = path + "/resource" seed_file = path_allpairs + "/positive/input_seed.txt" seed_negative = path_allpairs + "/negative" seed_positive =path_allpairs + "/positivee" seed_file_na = seed_negative + "/input_seed_negative.txt" selfcomb_file = path_allpairs + "/selfcomb.txt" output_file = path_allpairs + "/output.txt" output_file_ne = path_allpairs + "/output_negative.txt" report_path = path + "/report" report_file = report_path + "/wrt-manifest-tizen-tests.xml" report_summary_file = report_path + "/summary.xml" sh_path = path + "/script" log_path = report_path + "/log_" device_path = "/home/"+ Tizen_User +"/content/tct/" run_times = 3 version="6.35.1.2" name="wrt-manifest-tizen-tests"
#!/usr/bin/env python import sys, os import itertools, shutil Tizen_User = "app" if os.environ['TIZEN_USER']: Tizen_User = os.environ['TIZEN_USER'] path = os.path.abspath(__file__) path = os.path.split(path)[0] os.chdir(path) print path device_ssh_ip = "" ssh_device = device_ssh_ip.split(",") path_tcs = path + "/tcs" path_result= path + "/result" path_allpairs = path + "/allpairs" path_resource = path + "/resource" seed_file = path_allpairs + "/positive/input_seed.txt" seed_negative = path_allpairs + "/negative" seed_positive =path_allpairs + "/positivee" seed_file_na = seed_negative + "/input_seed_negative.txt" selfcomb_file = path_allpairs + "/selfcomb.txt" output_file = path_allpairs + "/output.txt" output_file_ne = path_allpairs + "/output_negative.txt" report_path = path + "/report" report_file = report_path + "/wrt-manifest-tizen-tests.xml" report_summary_file = report_path + "/summary.xml" sh_path = path + "/script" log_path = report_path + "/log_" device_path = "/home/"+ Tizen_User +"/content/tct/" run_times = 3 version="6.35.1.2" name="wrt-manifest-tizen-tests"
Update pyunit TIZEN_USER for default value
[wrt] Update pyunit TIZEN_USER for default value - Setting default value 'app' for TIZEN_USER in manifest Impacted tests(approved): new 0, update 264, delete 0 Unit test platform: [Tizen] Unit test result summary: pass 264, fail 0, block 0
Python
bsd-3-clause
jiajiax/crosswalk-test-suite,ibelem/crosswalk-test-suite,chunywang/crosswalk-test-suite,BruceDai/crosswalk-test-suite,haoyunfeix/crosswalk-test-suite,yunxliu/crosswalk-test-suite,jiajiax/crosswalk-test-suite,Shao-Feng/crosswalk-test-suite,crosswalk-project/crosswalk-test-suite,YongseopKim/crosswalk-test-suite,zqzhang/crosswalk-test-suite,BruceDai/crosswalk-test-suite,crosswalk-project/crosswalk-test-suite,kaixinjxq/crosswalk-test-suite,jiajiax/crosswalk-test-suite,zhuyongyong/crosswalk-test-suite,crosswalk-project/crosswalk-test-suite,haoyunfeix/crosswalk-test-suite,Honry/crosswalk-test-suite,pk-sam/crosswalk-test-suite,zhuyongyong/crosswalk-test-suite,chunywang/crosswalk-test-suite,yunxliu/crosswalk-test-suite,kaixinjxq/crosswalk-test-suite,kaixinjxq/crosswalk-test-suite,Honry/crosswalk-test-suite,zqzhang/crosswalk-test-suite,haoxli/crosswalk-test-suite,YongseopKim/crosswalk-test-suite,haoyunfeix/crosswalk-test-suite,zqzhang/crosswalk-test-suite,Honry/crosswalk-test-suite,YongseopKim/crosswalk-test-suite,yhe39/crosswalk-test-suite,jiajiax/crosswalk-test-suite,zhuyongyong/crosswalk-test-suite,wanghongjuan/crosswalk-test-suite,chunywang/crosswalk-test-suite,Shao-Feng/crosswalk-test-suite,zqzhang/crosswalk-test-suite,XiaosongWei/crosswalk-test-suite,JianfengXu/crosswalk-test-suite,BruceDai/crosswalk-test-suite,haoyunfeix/crosswalk-test-suite,jacky-young/crosswalk-test-suite,haoyunfeix/crosswalk-test-suite,yhe39/crosswalk-test-suite,kaixinjxq/crosswalk-test-suite,pk-sam/crosswalk-test-suite,zqzhang/crosswalk-test-suite,crosswalk-project/crosswalk-test-suite,jiajiax/crosswalk-test-suite,JianfengXu/crosswalk-test-suite,XiaosongWei/crosswalk-test-suite,kaixinjxq/crosswalk-test-suite,kaixinjxq/crosswalk-test-suite,crosswalk-project/crosswalk-test-suite,wanghongjuan/crosswalk-test-suite,JianfengXu/crosswalk-test-suite,Shao-Feng/crosswalk-test-suite,yunxliu/crosswalk-test-suite,yhe39/crosswalk-test-suite,ibelem/crosswalk-test-suite,haoxli/crosswalk-test-suite,ibelem/crosswalk-test-suite,JianfengXu/crosswalk-test-suite,wanghongjuan/crosswalk-test-suite,kaixinjxq/crosswalk-test-suite,yhe39/crosswalk-test-suite,wanghongjuan/crosswalk-test-suite,yunxliu/crosswalk-test-suite,ibelem/crosswalk-test-suite,crosswalk-project/crosswalk-test-suite,chunywang/crosswalk-test-suite,kangxu/crosswalk-test-suite,yhe39/crosswalk-test-suite,XiaosongWei/crosswalk-test-suite,kangxu/crosswalk-test-suite,qiuzhong/crosswalk-test-suite,kangxu/crosswalk-test-suite,zhuyongyong/crosswalk-test-suite,JianfengXu/crosswalk-test-suite,pk-sam/crosswalk-test-suite,BruceDai/crosswalk-test-suite,haoyunfeix/crosswalk-test-suite,chunywang/crosswalk-test-suite,Shao-Feng/crosswalk-test-suite,kangxu/crosswalk-test-suite,Shao-Feng/crosswalk-test-suite,ibelem/crosswalk-test-suite,JianfengXu/crosswalk-test-suite,YongseopKim/crosswalk-test-suite,ibelem/crosswalk-test-suite,pk-sam/crosswalk-test-suite,zhuyongyong/crosswalk-test-suite,jiajiax/crosswalk-test-suite,haoxli/crosswalk-test-suite,chunywang/crosswalk-test-suite,yhe39/crosswalk-test-suite,XiaosongWei/crosswalk-test-suite,kangxu/crosswalk-test-suite,JianfengXu/crosswalk-test-suite,jacky-young/crosswalk-test-suite,jacky-young/crosswalk-test-suite,Shao-Feng/crosswalk-test-suite,Honry/crosswalk-test-suite,haoxli/crosswalk-test-suite,jacky-young/crosswalk-test-suite,haoxli/crosswalk-test-suite,BruceDai/crosswalk-test-suite,zhuyongyong/crosswalk-test-suite,wanghongjuan/crosswalk-test-suite,pk-sam/crosswalk-test-suite,yhe39/crosswalk-test-suite,yunxliu/crosswalk-test-suite,wanghongjuan/crosswalk-test-suite,YongseopKim/crosswalk-test-suite,BruceDai/crosswalk-test-suite,chunywang/crosswalk-test-suite,yhe39/crosswalk-test-suite,zqzhang/crosswalk-test-suite,ibelem/crosswalk-test-suite,yunxliu/crosswalk-test-suite,kangxu/crosswalk-test-suite,chunywang/crosswalk-test-suite,crosswalk-project/crosswalk-test-suite,XiaosongWei/crosswalk-test-suite,wanghongjuan/crosswalk-test-suite,haoxli/crosswalk-test-suite,BruceDai/crosswalk-test-suite,XiaosongWei/crosswalk-test-suite,qiuzhong/crosswalk-test-suite,crosswalk-project/crosswalk-test-suite,Honry/crosswalk-test-suite,zhuyongyong/crosswalk-test-suite,qiuzhong/crosswalk-test-suite,yunxliu/crosswalk-test-suite,Honry/crosswalk-test-suite,kangxu/crosswalk-test-suite,kaixinjxq/crosswalk-test-suite,Shao-Feng/crosswalk-test-suite,jiajiax/crosswalk-test-suite,Honry/crosswalk-test-suite,haoxli/crosswalk-test-suite,YongseopKim/crosswalk-test-suite,kangxu/crosswalk-test-suite,yunxliu/crosswalk-test-suite,haoyunfeix/crosswalk-test-suite,BruceDai/crosswalk-test-suite,YongseopKim/crosswalk-test-suite,qiuzhong/crosswalk-test-suite,wanghongjuan/crosswalk-test-suite,zqzhang/crosswalk-test-suite,zhuyongyong/crosswalk-test-suite,zqzhang/crosswalk-test-suite,XiaosongWei/crosswalk-test-suite,pk-sam/crosswalk-test-suite,qiuzhong/crosswalk-test-suite,Honry/crosswalk-test-suite,qiuzhong/crosswalk-test-suite,haoyunfeix/crosswalk-test-suite,pk-sam/crosswalk-test-suite,jacky-young/crosswalk-test-suite,ibelem/crosswalk-test-suite,haoxli/crosswalk-test-suite,qiuzhong/crosswalk-test-suite,jacky-young/crosswalk-test-suite
#!/usr/bin/env python import sys, os import itertools, shutil Tizen_User=os.environ['TIZEN_USER'] path = os.path.abspath(__file__) path = os.path.split(path)[0] os.chdir(path) print path device_ssh_ip = "" ssh_device = device_ssh_ip.split(",") path_tcs = path + "/tcs" path_result= path + "/result" path_allpairs = path + "/allpairs" path_resource = path + "/resource" seed_file = path_allpairs + "/positive/input_seed.txt" seed_negative = path_allpairs + "/negative" seed_positive =path_allpairs + "/positivee" seed_file_na = seed_negative + "/input_seed_negative.txt" selfcomb_file = path_allpairs + "/selfcomb.txt" output_file = path_allpairs + "/output.txt" output_file_ne = path_allpairs + "/output_negative.txt" report_path = path + "/report" report_file = report_path + "/wrt-manifest-tizen-tests.xml" report_summary_file = report_path + "/summary.xml" sh_path = path + "/script" log_path = report_path + "/log_" device_path = "/home/"+ Tizen_User +"/content/tct/" run_times = 3 version="6.35.1.2" name="wrt-manifest-tizen-tests" [wrt] Update pyunit TIZEN_USER for default value - Setting default value 'app' for TIZEN_USER in manifest Impacted tests(approved): new 0, update 264, delete 0 Unit test platform: [Tizen] Unit test result summary: pass 264, fail 0, block 0
#!/usr/bin/env python import sys, os import itertools, shutil Tizen_User = "app" if os.environ['TIZEN_USER']: Tizen_User = os.environ['TIZEN_USER'] path = os.path.abspath(__file__) path = os.path.split(path)[0] os.chdir(path) print path device_ssh_ip = "" ssh_device = device_ssh_ip.split(",") path_tcs = path + "/tcs" path_result= path + "/result" path_allpairs = path + "/allpairs" path_resource = path + "/resource" seed_file = path_allpairs + "/positive/input_seed.txt" seed_negative = path_allpairs + "/negative" seed_positive =path_allpairs + "/positivee" seed_file_na = seed_negative + "/input_seed_negative.txt" selfcomb_file = path_allpairs + "/selfcomb.txt" output_file = path_allpairs + "/output.txt" output_file_ne = path_allpairs + "/output_negative.txt" report_path = path + "/report" report_file = report_path + "/wrt-manifest-tizen-tests.xml" report_summary_file = report_path + "/summary.xml" sh_path = path + "/script" log_path = report_path + "/log_" device_path = "/home/"+ Tizen_User +"/content/tct/" run_times = 3 version="6.35.1.2" name="wrt-manifest-tizen-tests"
<commit_before>#!/usr/bin/env python import sys, os import itertools, shutil Tizen_User=os.environ['TIZEN_USER'] path = os.path.abspath(__file__) path = os.path.split(path)[0] os.chdir(path) print path device_ssh_ip = "" ssh_device = device_ssh_ip.split(",") path_tcs = path + "/tcs" path_result= path + "/result" path_allpairs = path + "/allpairs" path_resource = path + "/resource" seed_file = path_allpairs + "/positive/input_seed.txt" seed_negative = path_allpairs + "/negative" seed_positive =path_allpairs + "/positivee" seed_file_na = seed_negative + "/input_seed_negative.txt" selfcomb_file = path_allpairs + "/selfcomb.txt" output_file = path_allpairs + "/output.txt" output_file_ne = path_allpairs + "/output_negative.txt" report_path = path + "/report" report_file = report_path + "/wrt-manifest-tizen-tests.xml" report_summary_file = report_path + "/summary.xml" sh_path = path + "/script" log_path = report_path + "/log_" device_path = "/home/"+ Tizen_User +"/content/tct/" run_times = 3 version="6.35.1.2" name="wrt-manifest-tizen-tests" <commit_msg>[wrt] Update pyunit TIZEN_USER for default value - Setting default value 'app' for TIZEN_USER in manifest Impacted tests(approved): new 0, update 264, delete 0 Unit test platform: [Tizen] Unit test result summary: pass 264, fail 0, block 0<commit_after>
#!/usr/bin/env python import sys, os import itertools, shutil Tizen_User = "app" if os.environ['TIZEN_USER']: Tizen_User = os.environ['TIZEN_USER'] path = os.path.abspath(__file__) path = os.path.split(path)[0] os.chdir(path) print path device_ssh_ip = "" ssh_device = device_ssh_ip.split(",") path_tcs = path + "/tcs" path_result= path + "/result" path_allpairs = path + "/allpairs" path_resource = path + "/resource" seed_file = path_allpairs + "/positive/input_seed.txt" seed_negative = path_allpairs + "/negative" seed_positive =path_allpairs + "/positivee" seed_file_na = seed_negative + "/input_seed_negative.txt" selfcomb_file = path_allpairs + "/selfcomb.txt" output_file = path_allpairs + "/output.txt" output_file_ne = path_allpairs + "/output_negative.txt" report_path = path + "/report" report_file = report_path + "/wrt-manifest-tizen-tests.xml" report_summary_file = report_path + "/summary.xml" sh_path = path + "/script" log_path = report_path + "/log_" device_path = "/home/"+ Tizen_User +"/content/tct/" run_times = 3 version="6.35.1.2" name="wrt-manifest-tizen-tests"
#!/usr/bin/env python import sys, os import itertools, shutil Tizen_User=os.environ['TIZEN_USER'] path = os.path.abspath(__file__) path = os.path.split(path)[0] os.chdir(path) print path device_ssh_ip = "" ssh_device = device_ssh_ip.split(",") path_tcs = path + "/tcs" path_result= path + "/result" path_allpairs = path + "/allpairs" path_resource = path + "/resource" seed_file = path_allpairs + "/positive/input_seed.txt" seed_negative = path_allpairs + "/negative" seed_positive =path_allpairs + "/positivee" seed_file_na = seed_negative + "/input_seed_negative.txt" selfcomb_file = path_allpairs + "/selfcomb.txt" output_file = path_allpairs + "/output.txt" output_file_ne = path_allpairs + "/output_negative.txt" report_path = path + "/report" report_file = report_path + "/wrt-manifest-tizen-tests.xml" report_summary_file = report_path + "/summary.xml" sh_path = path + "/script" log_path = report_path + "/log_" device_path = "/home/"+ Tizen_User +"/content/tct/" run_times = 3 version="6.35.1.2" name="wrt-manifest-tizen-tests" [wrt] Update pyunit TIZEN_USER for default value - Setting default value 'app' for TIZEN_USER in manifest Impacted tests(approved): new 0, update 264, delete 0 Unit test platform: [Tizen] Unit test result summary: pass 264, fail 0, block 0#!/usr/bin/env python import sys, os import itertools, shutil Tizen_User = "app" if os.environ['TIZEN_USER']: Tizen_User = os.environ['TIZEN_USER'] path = os.path.abspath(__file__) path = os.path.split(path)[0] os.chdir(path) print path device_ssh_ip = "" ssh_device = device_ssh_ip.split(",") path_tcs = path + "/tcs" path_result= path + "/result" path_allpairs = path + "/allpairs" path_resource = path + "/resource" seed_file = path_allpairs + "/positive/input_seed.txt" seed_negative = path_allpairs + "/negative" seed_positive =path_allpairs + "/positivee" seed_file_na = seed_negative + "/input_seed_negative.txt" selfcomb_file = path_allpairs + "/selfcomb.txt" output_file = path_allpairs + "/output.txt" output_file_ne = path_allpairs + "/output_negative.txt" report_path = path + "/report" report_file = report_path + "/wrt-manifest-tizen-tests.xml" report_summary_file = report_path + "/summary.xml" sh_path = path + "/script" log_path = report_path + "/log_" device_path = "/home/"+ Tizen_User +"/content/tct/" run_times = 3 version="6.35.1.2" name="wrt-manifest-tizen-tests"
<commit_before>#!/usr/bin/env python import sys, os import itertools, shutil Tizen_User=os.environ['TIZEN_USER'] path = os.path.abspath(__file__) path = os.path.split(path)[0] os.chdir(path) print path device_ssh_ip = "" ssh_device = device_ssh_ip.split(",") path_tcs = path + "/tcs" path_result= path + "/result" path_allpairs = path + "/allpairs" path_resource = path + "/resource" seed_file = path_allpairs + "/positive/input_seed.txt" seed_negative = path_allpairs + "/negative" seed_positive =path_allpairs + "/positivee" seed_file_na = seed_negative + "/input_seed_negative.txt" selfcomb_file = path_allpairs + "/selfcomb.txt" output_file = path_allpairs + "/output.txt" output_file_ne = path_allpairs + "/output_negative.txt" report_path = path + "/report" report_file = report_path + "/wrt-manifest-tizen-tests.xml" report_summary_file = report_path + "/summary.xml" sh_path = path + "/script" log_path = report_path + "/log_" device_path = "/home/"+ Tizen_User +"/content/tct/" run_times = 3 version="6.35.1.2" name="wrt-manifest-tizen-tests" <commit_msg>[wrt] Update pyunit TIZEN_USER for default value - Setting default value 'app' for TIZEN_USER in manifest Impacted tests(approved): new 0, update 264, delete 0 Unit test platform: [Tizen] Unit test result summary: pass 264, fail 0, block 0<commit_after>#!/usr/bin/env python import sys, os import itertools, shutil Tizen_User = "app" if os.environ['TIZEN_USER']: Tizen_User = os.environ['TIZEN_USER'] path = os.path.abspath(__file__) path = os.path.split(path)[0] os.chdir(path) print path device_ssh_ip = "" ssh_device = device_ssh_ip.split(",") path_tcs = path + "/tcs" path_result= path + "/result" path_allpairs = path + "/allpairs" path_resource = path + "/resource" seed_file = path_allpairs + "/positive/input_seed.txt" seed_negative = path_allpairs + "/negative" seed_positive =path_allpairs + "/positivee" seed_file_na = seed_negative + "/input_seed_negative.txt" selfcomb_file = path_allpairs + "/selfcomb.txt" output_file = path_allpairs + "/output.txt" output_file_ne = path_allpairs + "/output_negative.txt" report_path = path + "/report" report_file = report_path + "/wrt-manifest-tizen-tests.xml" report_summary_file = report_path + "/summary.xml" sh_path = path + "/script" log_path = report_path + "/log_" device_path = "/home/"+ Tizen_User +"/content/tct/" run_times = 3 version="6.35.1.2" name="wrt-manifest-tizen-tests"
0f4208dd6088a6a96a0145045b11cf2d152db30d
src/samples/pillow.py
src/samples/pillow.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from libavg import app, avg from PIL import Image # Demonstrates interoperability with pillow (https://pillow.readthedocs.org/index.html) class MyMainDiv(app.MainDiv): def onInit(self): self.toggleTouchVisualization() srcbmp = avg.Bitmap("rgb24-64x64.png") pixels = srcbmp.getPixels(False) image = Image.frombytes("RGBA", (64,64), pixels) # Need to swap red and blue. b,g,r,a = image.split() image = Image.merge("RGBA", (r,g,b,a)) image.save("foo.jpg") destbmp = avg.Bitmap((64,64), avg.B8G8R8A8, "") destbmp.setPixels(image.tobytes()) node = avg.ImageNode(parent=self) node.setBitmap(destbmp) def onExit(self): pass def onFrame(self): pass app.App().run(MyMainDiv())
#!/usr/bin/env python # -*- coding: utf-8 -*- from libavg import app, avg from PIL import Image # Demonstrates interoperability with pillow (https://pillow.readthedocs.io) class MyMainDiv(app.MainDiv): def onInit(self): self.toggleTouchVisualization() srcbmp = avg.Bitmap("rgb24-64x64.png") pixels = srcbmp.getPixels(False) image = Image.frombytes("RGBA", (64,64), pixels) # Need to swap red and blue. b,g,r,a = image.split() image = Image.merge("RGBA", (r,g,b,a)) image.save("foo.png") destbmp = avg.Bitmap((64,64), avg.B8G8R8A8, "") destbmp.setPixels(image.tobytes()) node = avg.ImageNode(parent=self) node.setBitmap(destbmp) def onExit(self): pass def onFrame(self): pass app.App().run(MyMainDiv())
Update link in the comment and change saved image format to .png
Update link in the comment and change saved image format to .png
Python
lgpl-2.1
libavg/libavg,libavg/libavg,libavg/libavg,libavg/libavg
#!/usr/bin/env python # -*- coding: utf-8 -*- from libavg import app, avg from PIL import Image # Demonstrates interoperability with pillow (https://pillow.readthedocs.org/index.html) class MyMainDiv(app.MainDiv): def onInit(self): self.toggleTouchVisualization() srcbmp = avg.Bitmap("rgb24-64x64.png") pixels = srcbmp.getPixels(False) image = Image.frombytes("RGBA", (64,64), pixels) # Need to swap red and blue. b,g,r,a = image.split() image = Image.merge("RGBA", (r,g,b,a)) image.save("foo.jpg") destbmp = avg.Bitmap((64,64), avg.B8G8R8A8, "") destbmp.setPixels(image.tobytes()) node = avg.ImageNode(parent=self) node.setBitmap(destbmp) def onExit(self): pass def onFrame(self): pass app.App().run(MyMainDiv()) Update link in the comment and change saved image format to .png
#!/usr/bin/env python # -*- coding: utf-8 -*- from libavg import app, avg from PIL import Image # Demonstrates interoperability with pillow (https://pillow.readthedocs.io) class MyMainDiv(app.MainDiv): def onInit(self): self.toggleTouchVisualization() srcbmp = avg.Bitmap("rgb24-64x64.png") pixels = srcbmp.getPixels(False) image = Image.frombytes("RGBA", (64,64), pixels) # Need to swap red and blue. b,g,r,a = image.split() image = Image.merge("RGBA", (r,g,b,a)) image.save("foo.png") destbmp = avg.Bitmap((64,64), avg.B8G8R8A8, "") destbmp.setPixels(image.tobytes()) node = avg.ImageNode(parent=self) node.setBitmap(destbmp) def onExit(self): pass def onFrame(self): pass app.App().run(MyMainDiv())
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- from libavg import app, avg from PIL import Image # Demonstrates interoperability with pillow (https://pillow.readthedocs.org/index.html) class MyMainDiv(app.MainDiv): def onInit(self): self.toggleTouchVisualization() srcbmp = avg.Bitmap("rgb24-64x64.png") pixels = srcbmp.getPixels(False) image = Image.frombytes("RGBA", (64,64), pixels) # Need to swap red and blue. b,g,r,a = image.split() image = Image.merge("RGBA", (r,g,b,a)) image.save("foo.jpg") destbmp = avg.Bitmap((64,64), avg.B8G8R8A8, "") destbmp.setPixels(image.tobytes()) node = avg.ImageNode(parent=self) node.setBitmap(destbmp) def onExit(self): pass def onFrame(self): pass app.App().run(MyMainDiv()) <commit_msg>Update link in the comment and change saved image format to .png<commit_after>
#!/usr/bin/env python # -*- coding: utf-8 -*- from libavg import app, avg from PIL import Image # Demonstrates interoperability with pillow (https://pillow.readthedocs.io) class MyMainDiv(app.MainDiv): def onInit(self): self.toggleTouchVisualization() srcbmp = avg.Bitmap("rgb24-64x64.png") pixels = srcbmp.getPixels(False) image = Image.frombytes("RGBA", (64,64), pixels) # Need to swap red and blue. b,g,r,a = image.split() image = Image.merge("RGBA", (r,g,b,a)) image.save("foo.png") destbmp = avg.Bitmap((64,64), avg.B8G8R8A8, "") destbmp.setPixels(image.tobytes()) node = avg.ImageNode(parent=self) node.setBitmap(destbmp) def onExit(self): pass def onFrame(self): pass app.App().run(MyMainDiv())
#!/usr/bin/env python # -*- coding: utf-8 -*- from libavg import app, avg from PIL import Image # Demonstrates interoperability with pillow (https://pillow.readthedocs.org/index.html) class MyMainDiv(app.MainDiv): def onInit(self): self.toggleTouchVisualization() srcbmp = avg.Bitmap("rgb24-64x64.png") pixels = srcbmp.getPixels(False) image = Image.frombytes("RGBA", (64,64), pixels) # Need to swap red and blue. b,g,r,a = image.split() image = Image.merge("RGBA", (r,g,b,a)) image.save("foo.jpg") destbmp = avg.Bitmap((64,64), avg.B8G8R8A8, "") destbmp.setPixels(image.tobytes()) node = avg.ImageNode(parent=self) node.setBitmap(destbmp) def onExit(self): pass def onFrame(self): pass app.App().run(MyMainDiv()) Update link in the comment and change saved image format to .png#!/usr/bin/env python # -*- coding: utf-8 -*- from libavg import app, avg from PIL import Image # Demonstrates interoperability with pillow (https://pillow.readthedocs.io) class MyMainDiv(app.MainDiv): def onInit(self): self.toggleTouchVisualization() srcbmp = avg.Bitmap("rgb24-64x64.png") pixels = srcbmp.getPixels(False) image = Image.frombytes("RGBA", (64,64), pixels) # Need to swap red and blue. b,g,r,a = image.split() image = Image.merge("RGBA", (r,g,b,a)) image.save("foo.png") destbmp = avg.Bitmap((64,64), avg.B8G8R8A8, "") destbmp.setPixels(image.tobytes()) node = avg.ImageNode(parent=self) node.setBitmap(destbmp) def onExit(self): pass def onFrame(self): pass app.App().run(MyMainDiv())
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- from libavg import app, avg from PIL import Image # Demonstrates interoperability with pillow (https://pillow.readthedocs.org/index.html) class MyMainDiv(app.MainDiv): def onInit(self): self.toggleTouchVisualization() srcbmp = avg.Bitmap("rgb24-64x64.png") pixels = srcbmp.getPixels(False) image = Image.frombytes("RGBA", (64,64), pixels) # Need to swap red and blue. b,g,r,a = image.split() image = Image.merge("RGBA", (r,g,b,a)) image.save("foo.jpg") destbmp = avg.Bitmap((64,64), avg.B8G8R8A8, "") destbmp.setPixels(image.tobytes()) node = avg.ImageNode(parent=self) node.setBitmap(destbmp) def onExit(self): pass def onFrame(self): pass app.App().run(MyMainDiv()) <commit_msg>Update link in the comment and change saved image format to .png<commit_after>#!/usr/bin/env python # -*- coding: utf-8 -*- from libavg import app, avg from PIL import Image # Demonstrates interoperability with pillow (https://pillow.readthedocs.io) class MyMainDiv(app.MainDiv): def onInit(self): self.toggleTouchVisualization() srcbmp = avg.Bitmap("rgb24-64x64.png") pixels = srcbmp.getPixels(False) image = Image.frombytes("RGBA", (64,64), pixels) # Need to swap red and blue. b,g,r,a = image.split() image = Image.merge("RGBA", (r,g,b,a)) image.save("foo.png") destbmp = avg.Bitmap((64,64), avg.B8G8R8A8, "") destbmp.setPixels(image.tobytes()) node = avg.ImageNode(parent=self) node.setBitmap(destbmp) def onExit(self): pass def onFrame(self): pass app.App().run(MyMainDiv())
360005d65575c4b47b25dc8308e8a5611a00e584
tools/bootstrap_project.py
tools/bootstrap_project.py
# TODO: Implement!
# TODO: Implement! ''' We want a folder structure something like this: |-bin |-conf |-doc | \-paper |-experiments | \-2000-01-01-example | |-audit | |-bin | |-conf | |-data | |-doc | |-lib | |-log | |-raw | |-results | |-run | \-tmp |-lib |-raw |-results \-src '''
Add comments in bootstrap script
Add comments in bootstrap script
Python
mit
pharmbio/sciluigi,pharmbio/sciluigi,samuell/sciluigi
# TODO: Implement! Add comments in bootstrap script
# TODO: Implement! ''' We want a folder structure something like this: |-bin |-conf |-doc | \-paper |-experiments | \-2000-01-01-example | |-audit | |-bin | |-conf | |-data | |-doc | |-lib | |-log | |-raw | |-results | |-run | \-tmp |-lib |-raw |-results \-src '''
<commit_before># TODO: Implement! <commit_msg>Add comments in bootstrap script<commit_after>
# TODO: Implement! ''' We want a folder structure something like this: |-bin |-conf |-doc | \-paper |-experiments | \-2000-01-01-example | |-audit | |-bin | |-conf | |-data | |-doc | |-lib | |-log | |-raw | |-results | |-run | \-tmp |-lib |-raw |-results \-src '''
# TODO: Implement! Add comments in bootstrap script# TODO: Implement! ''' We want a folder structure something like this: |-bin |-conf |-doc | \-paper |-experiments | \-2000-01-01-example | |-audit | |-bin | |-conf | |-data | |-doc | |-lib | |-log | |-raw | |-results | |-run | \-tmp |-lib |-raw |-results \-src '''
<commit_before># TODO: Implement! <commit_msg>Add comments in bootstrap script<commit_after># TODO: Implement! ''' We want a folder structure something like this: |-bin |-conf |-doc | \-paper |-experiments | \-2000-01-01-example | |-audit | |-bin | |-conf | |-data | |-doc | |-lib | |-log | |-raw | |-results | |-run | \-tmp |-lib |-raw |-results \-src '''
75ff727cd29ae1b379c551f46217fa75bf0fb2bc
videoeditor.py
videoeditor.py
from moviepy.editor import * def bake_annotations(video_file, end_point, annotations): clip = VideoFileClip(video_file) composite_clips = [clip] #for annotation in annotations: # txt_clip = TextClip(annotation["text"], color="white", fontsize=70) # txt_clip = txt_clip.set_position(("center", "bottom")) # txt_clip = txt_clip.set_duration(0.5) # txt_clip = txt_clip.set_start(float(annotation["time"]) / 1000.0) # composite_clips.append(txt_clip) #final_video = CompositeVideoClip(composite_clips) final_video = generate_pauses(clip, annotations) final_video.write_videofile("video-out/" + end_point, audio=False) def generate_pauses(video_clip, annotations): """Takes in a regular video clip, and bakes in annotation pauses""" pause_time = 1 for annotation in reversed(annotations): current_annotation_time = annotation["time"] / 1000.0 video_clip = video_clip.fx(vfx.freeze, t=current_annotation_time, freeze_duration=pause_time) return video_clip
from moviepy.editor import * def bake_annotations(video_file, end_point, annotations): clip = VideoFileClip(video_file) composite_clips = [clip] #for annotation in annotations: # txt_clip = TextClip(annotation["text"], color="white", fontsize=70) # txt_clip = txt_clip.set_position(("center", "bottom")) # txt_clip = txt_clip.set_duration(0.5) # txt_clip = txt_clip.set_start(float(annotation["time"]) / 1000.0) # composite_clips.append(txt_clip) #final_video = CompositeVideoClip(composite_clips) final_video = generate_pauses(clip, annotations) final_video.write_videofile("video-out/" + end_point) def generate_pauses(video_clip, annotations): """Takes in a regular video clip, and bakes in annotation pauses""" for annotation in reversed(annotations): pause_time = len(annotation["text"]) * 0.4 current_annotation_time = annotation["time"] / 1000.0 video_clip = video_clip.fx(vfx.freeze, t=current_annotation_time, freeze_duration=pause_time) return video_clip
Make pause dependant on annotation text length
Make pause dependant on annotation text length
Python
mit
melonmanchan/achso-video-exporter,melonmanchan/achso-video-exporter
from moviepy.editor import * def bake_annotations(video_file, end_point, annotations): clip = VideoFileClip(video_file) composite_clips = [clip] #for annotation in annotations: # txt_clip = TextClip(annotation["text"], color="white", fontsize=70) # txt_clip = txt_clip.set_position(("center", "bottom")) # txt_clip = txt_clip.set_duration(0.5) # txt_clip = txt_clip.set_start(float(annotation["time"]) / 1000.0) # composite_clips.append(txt_clip) #final_video = CompositeVideoClip(composite_clips) final_video = generate_pauses(clip, annotations) final_video.write_videofile("video-out/" + end_point, audio=False) def generate_pauses(video_clip, annotations): """Takes in a regular video clip, and bakes in annotation pauses""" pause_time = 1 for annotation in reversed(annotations): current_annotation_time = annotation["time"] / 1000.0 video_clip = video_clip.fx(vfx.freeze, t=current_annotation_time, freeze_duration=pause_time) return video_clip Make pause dependant on annotation text length
from moviepy.editor import * def bake_annotations(video_file, end_point, annotations): clip = VideoFileClip(video_file) composite_clips = [clip] #for annotation in annotations: # txt_clip = TextClip(annotation["text"], color="white", fontsize=70) # txt_clip = txt_clip.set_position(("center", "bottom")) # txt_clip = txt_clip.set_duration(0.5) # txt_clip = txt_clip.set_start(float(annotation["time"]) / 1000.0) # composite_clips.append(txt_clip) #final_video = CompositeVideoClip(composite_clips) final_video = generate_pauses(clip, annotations) final_video.write_videofile("video-out/" + end_point) def generate_pauses(video_clip, annotations): """Takes in a regular video clip, and bakes in annotation pauses""" for annotation in reversed(annotations): pause_time = len(annotation["text"]) * 0.4 current_annotation_time = annotation["time"] / 1000.0 video_clip = video_clip.fx(vfx.freeze, t=current_annotation_time, freeze_duration=pause_time) return video_clip
<commit_before>from moviepy.editor import * def bake_annotations(video_file, end_point, annotations): clip = VideoFileClip(video_file) composite_clips = [clip] #for annotation in annotations: # txt_clip = TextClip(annotation["text"], color="white", fontsize=70) # txt_clip = txt_clip.set_position(("center", "bottom")) # txt_clip = txt_clip.set_duration(0.5) # txt_clip = txt_clip.set_start(float(annotation["time"]) / 1000.0) # composite_clips.append(txt_clip) #final_video = CompositeVideoClip(composite_clips) final_video = generate_pauses(clip, annotations) final_video.write_videofile("video-out/" + end_point, audio=False) def generate_pauses(video_clip, annotations): """Takes in a regular video clip, and bakes in annotation pauses""" pause_time = 1 for annotation in reversed(annotations): current_annotation_time = annotation["time"] / 1000.0 video_clip = video_clip.fx(vfx.freeze, t=current_annotation_time, freeze_duration=pause_time) return video_clip <commit_msg>Make pause dependant on annotation text length<commit_after>
from moviepy.editor import * def bake_annotations(video_file, end_point, annotations): clip = VideoFileClip(video_file) composite_clips = [clip] #for annotation in annotations: # txt_clip = TextClip(annotation["text"], color="white", fontsize=70) # txt_clip = txt_clip.set_position(("center", "bottom")) # txt_clip = txt_clip.set_duration(0.5) # txt_clip = txt_clip.set_start(float(annotation["time"]) / 1000.0) # composite_clips.append(txt_clip) #final_video = CompositeVideoClip(composite_clips) final_video = generate_pauses(clip, annotations) final_video.write_videofile("video-out/" + end_point) def generate_pauses(video_clip, annotations): """Takes in a regular video clip, and bakes in annotation pauses""" for annotation in reversed(annotations): pause_time = len(annotation["text"]) * 0.4 current_annotation_time = annotation["time"] / 1000.0 video_clip = video_clip.fx(vfx.freeze, t=current_annotation_time, freeze_duration=pause_time) return video_clip
from moviepy.editor import * def bake_annotations(video_file, end_point, annotations): clip = VideoFileClip(video_file) composite_clips = [clip] #for annotation in annotations: # txt_clip = TextClip(annotation["text"], color="white", fontsize=70) # txt_clip = txt_clip.set_position(("center", "bottom")) # txt_clip = txt_clip.set_duration(0.5) # txt_clip = txt_clip.set_start(float(annotation["time"]) / 1000.0) # composite_clips.append(txt_clip) #final_video = CompositeVideoClip(composite_clips) final_video = generate_pauses(clip, annotations) final_video.write_videofile("video-out/" + end_point, audio=False) def generate_pauses(video_clip, annotations): """Takes in a regular video clip, and bakes in annotation pauses""" pause_time = 1 for annotation in reversed(annotations): current_annotation_time = annotation["time"] / 1000.0 video_clip = video_clip.fx(vfx.freeze, t=current_annotation_time, freeze_duration=pause_time) return video_clip Make pause dependant on annotation text lengthfrom moviepy.editor import * def bake_annotations(video_file, end_point, annotations): clip = VideoFileClip(video_file) composite_clips = [clip] #for annotation in annotations: # txt_clip = TextClip(annotation["text"], color="white", fontsize=70) # txt_clip = txt_clip.set_position(("center", "bottom")) # txt_clip = txt_clip.set_duration(0.5) # txt_clip = txt_clip.set_start(float(annotation["time"]) / 1000.0) # composite_clips.append(txt_clip) #final_video = CompositeVideoClip(composite_clips) final_video = generate_pauses(clip, annotations) final_video.write_videofile("video-out/" + end_point) def generate_pauses(video_clip, annotations): """Takes in a regular video clip, and bakes in annotation pauses""" for annotation in reversed(annotations): pause_time = len(annotation["text"]) * 0.4 current_annotation_time = annotation["time"] / 1000.0 video_clip = video_clip.fx(vfx.freeze, t=current_annotation_time, freeze_duration=pause_time) return video_clip
<commit_before>from moviepy.editor import * def bake_annotations(video_file, end_point, annotations): clip = VideoFileClip(video_file) composite_clips = [clip] #for annotation in annotations: # txt_clip = TextClip(annotation["text"], color="white", fontsize=70) # txt_clip = txt_clip.set_position(("center", "bottom")) # txt_clip = txt_clip.set_duration(0.5) # txt_clip = txt_clip.set_start(float(annotation["time"]) / 1000.0) # composite_clips.append(txt_clip) #final_video = CompositeVideoClip(composite_clips) final_video = generate_pauses(clip, annotations) final_video.write_videofile("video-out/" + end_point, audio=False) def generate_pauses(video_clip, annotations): """Takes in a regular video clip, and bakes in annotation pauses""" pause_time = 1 for annotation in reversed(annotations): current_annotation_time = annotation["time"] / 1000.0 video_clip = video_clip.fx(vfx.freeze, t=current_annotation_time, freeze_duration=pause_time) return video_clip <commit_msg>Make pause dependant on annotation text length<commit_after>from moviepy.editor import * def bake_annotations(video_file, end_point, annotations): clip = VideoFileClip(video_file) composite_clips = [clip] #for annotation in annotations: # txt_clip = TextClip(annotation["text"], color="white", fontsize=70) # txt_clip = txt_clip.set_position(("center", "bottom")) # txt_clip = txt_clip.set_duration(0.5) # txt_clip = txt_clip.set_start(float(annotation["time"]) / 1000.0) # composite_clips.append(txt_clip) #final_video = CompositeVideoClip(composite_clips) final_video = generate_pauses(clip, annotations) final_video.write_videofile("video-out/" + end_point) def generate_pauses(video_clip, annotations): """Takes in a regular video clip, and bakes in annotation pauses""" for annotation in reversed(annotations): pause_time = len(annotation["text"]) * 0.4 current_annotation_time = annotation["time"] / 1000.0 video_clip = video_clip.fx(vfx.freeze, t=current_annotation_time, freeze_duration=pause_time) return video_clip
bb3019eed45b684739e7847b24d9999da12492c4
src/slack/monitor.py
src/slack/monitor.py
import logging import os from slackclient import SlackClient import logging logger = logging.getLogger(__name__) def get_message_info(event, bot_name): return event['channel'], event['user'], event['text'][len(bot_name) + 1:].strip() def reply(event, bot_name, client, repo): channel, user, message = get_message_info(event, bot_name) try: message = repo.get_card_path(message) except Exception as e: message = "Unable to find card you requested, sorry." client.server.channels.find(channel).send_message(message) def monitor(repo): # TODO: get this from API bot_name = "<@U2J5GAF96>" #os.environ["SLACK_BOT_TOKEN"] = token = os.environ["CHOPBOT_3000_TOKEN"] client = SlackClient(token) if client.rtm_connect(): while True: events = client.rtm_read() try: for event in events: if event['type'] == 'message' and event['text'].startswith(bot_name): reply(event, bot_name, client, repo) except Exception as e: logger.error("Invalid event received")
import logging import os import time from slackclient import SlackClient import logging logger = logging.getLogger(__name__) def get_message_info(event, bot_name): return event['channel'], event['user'], event['text'][len(bot_name) + 1:].strip() def reply(event, bot_name, client, repo): channel, user, message = get_message_info(event, bot_name) try: message = repo.get_card_path(message) except Exception as e: message = "Unable to find card you requested, sorry." client.server.channels.find(channel).send_message(message) def monitor(repo): # TODO: get this from API bot_name = "<@U2J5GAF96>" token = os.environ["CHOPBOT_3000_TOKEN"] client = SlackClient(token) if client.rtm_connect(): while True: events = client.rtm_read() try: if len(events) == 0: logger.debug("No events. Sleeping...") time.sleep(1) for event in events: logger.info("Received an event with text: ") logger.info(event) if event['type'] == 'message' and event['text'].startswith(bot_name): reply(event, bot_name, client, repo) except Exception as e: logger.error("Invalid event received") logger.error(e)
Add sleep step and logging to bot integration
Add sleep step and logging to bot integration
Python
mit
baylesj/chopBot3000,baylesj/chopBot3000
import logging import os from slackclient import SlackClient import logging logger = logging.getLogger(__name__) def get_message_info(event, bot_name): return event['channel'], event['user'], event['text'][len(bot_name) + 1:].strip() def reply(event, bot_name, client, repo): channel, user, message = get_message_info(event, bot_name) try: message = repo.get_card_path(message) except Exception as e: message = "Unable to find card you requested, sorry." client.server.channels.find(channel).send_message(message) def monitor(repo): # TODO: get this from API bot_name = "<@U2J5GAF96>" #os.environ["SLACK_BOT_TOKEN"] = token = os.environ["CHOPBOT_3000_TOKEN"] client = SlackClient(token) if client.rtm_connect(): while True: events = client.rtm_read() try: for event in events: if event['type'] == 'message' and event['text'].startswith(bot_name): reply(event, bot_name, client, repo) except Exception as e: logger.error("Invalid event received") Add sleep step and logging to bot integration
import logging import os import time from slackclient import SlackClient import logging logger = logging.getLogger(__name__) def get_message_info(event, bot_name): return event['channel'], event['user'], event['text'][len(bot_name) + 1:].strip() def reply(event, bot_name, client, repo): channel, user, message = get_message_info(event, bot_name) try: message = repo.get_card_path(message) except Exception as e: message = "Unable to find card you requested, sorry." client.server.channels.find(channel).send_message(message) def monitor(repo): # TODO: get this from API bot_name = "<@U2J5GAF96>" token = os.environ["CHOPBOT_3000_TOKEN"] client = SlackClient(token) if client.rtm_connect(): while True: events = client.rtm_read() try: if len(events) == 0: logger.debug("No events. Sleeping...") time.sleep(1) for event in events: logger.info("Received an event with text: ") logger.info(event) if event['type'] == 'message' and event['text'].startswith(bot_name): reply(event, bot_name, client, repo) except Exception as e: logger.error("Invalid event received") logger.error(e)
<commit_before>import logging import os from slackclient import SlackClient import logging logger = logging.getLogger(__name__) def get_message_info(event, bot_name): return event['channel'], event['user'], event['text'][len(bot_name) + 1:].strip() def reply(event, bot_name, client, repo): channel, user, message = get_message_info(event, bot_name) try: message = repo.get_card_path(message) except Exception as e: message = "Unable to find card you requested, sorry." client.server.channels.find(channel).send_message(message) def monitor(repo): # TODO: get this from API bot_name = "<@U2J5GAF96>" #os.environ["SLACK_BOT_TOKEN"] = token = os.environ["CHOPBOT_3000_TOKEN"] client = SlackClient(token) if client.rtm_connect(): while True: events = client.rtm_read() try: for event in events: if event['type'] == 'message' and event['text'].startswith(bot_name): reply(event, bot_name, client, repo) except Exception as e: logger.error("Invalid event received") <commit_msg>Add sleep step and logging to bot integration<commit_after>
import logging import os import time from slackclient import SlackClient import logging logger = logging.getLogger(__name__) def get_message_info(event, bot_name): return event['channel'], event['user'], event['text'][len(bot_name) + 1:].strip() def reply(event, bot_name, client, repo): channel, user, message = get_message_info(event, bot_name) try: message = repo.get_card_path(message) except Exception as e: message = "Unable to find card you requested, sorry." client.server.channels.find(channel).send_message(message) def monitor(repo): # TODO: get this from API bot_name = "<@U2J5GAF96>" token = os.environ["CHOPBOT_3000_TOKEN"] client = SlackClient(token) if client.rtm_connect(): while True: events = client.rtm_read() try: if len(events) == 0: logger.debug("No events. Sleeping...") time.sleep(1) for event in events: logger.info("Received an event with text: ") logger.info(event) if event['type'] == 'message' and event['text'].startswith(bot_name): reply(event, bot_name, client, repo) except Exception as e: logger.error("Invalid event received") logger.error(e)
import logging import os from slackclient import SlackClient import logging logger = logging.getLogger(__name__) def get_message_info(event, bot_name): return event['channel'], event['user'], event['text'][len(bot_name) + 1:].strip() def reply(event, bot_name, client, repo): channel, user, message = get_message_info(event, bot_name) try: message = repo.get_card_path(message) except Exception as e: message = "Unable to find card you requested, sorry." client.server.channels.find(channel).send_message(message) def monitor(repo): # TODO: get this from API bot_name = "<@U2J5GAF96>" #os.environ["SLACK_BOT_TOKEN"] = token = os.environ["CHOPBOT_3000_TOKEN"] client = SlackClient(token) if client.rtm_connect(): while True: events = client.rtm_read() try: for event in events: if event['type'] == 'message' and event['text'].startswith(bot_name): reply(event, bot_name, client, repo) except Exception as e: logger.error("Invalid event received") Add sleep step and logging to bot integrationimport logging import os import time from slackclient import SlackClient import logging logger = logging.getLogger(__name__) def get_message_info(event, bot_name): return event['channel'], event['user'], event['text'][len(bot_name) + 1:].strip() def reply(event, bot_name, client, repo): channel, user, message = get_message_info(event, bot_name) try: message = repo.get_card_path(message) except Exception as e: message = "Unable to find card you requested, sorry." client.server.channels.find(channel).send_message(message) def monitor(repo): # TODO: get this from API bot_name = "<@U2J5GAF96>" token = os.environ["CHOPBOT_3000_TOKEN"] client = SlackClient(token) if client.rtm_connect(): while True: events = client.rtm_read() try: if len(events) == 0: logger.debug("No events. Sleeping...") time.sleep(1) for event in events: logger.info("Received an event with text: ") logger.info(event) if event['type'] == 'message' and event['text'].startswith(bot_name): reply(event, bot_name, client, repo) except Exception as e: logger.error("Invalid event received") logger.error(e)
<commit_before>import logging import os from slackclient import SlackClient import logging logger = logging.getLogger(__name__) def get_message_info(event, bot_name): return event['channel'], event['user'], event['text'][len(bot_name) + 1:].strip() def reply(event, bot_name, client, repo): channel, user, message = get_message_info(event, bot_name) try: message = repo.get_card_path(message) except Exception as e: message = "Unable to find card you requested, sorry." client.server.channels.find(channel).send_message(message) def monitor(repo): # TODO: get this from API bot_name = "<@U2J5GAF96>" #os.environ["SLACK_BOT_TOKEN"] = token = os.environ["CHOPBOT_3000_TOKEN"] client = SlackClient(token) if client.rtm_connect(): while True: events = client.rtm_read() try: for event in events: if event['type'] == 'message' and event['text'].startswith(bot_name): reply(event, bot_name, client, repo) except Exception as e: logger.error("Invalid event received") <commit_msg>Add sleep step and logging to bot integration<commit_after>import logging import os import time from slackclient import SlackClient import logging logger = logging.getLogger(__name__) def get_message_info(event, bot_name): return event['channel'], event['user'], event['text'][len(bot_name) + 1:].strip() def reply(event, bot_name, client, repo): channel, user, message = get_message_info(event, bot_name) try: message = repo.get_card_path(message) except Exception as e: message = "Unable to find card you requested, sorry." client.server.channels.find(channel).send_message(message) def monitor(repo): # TODO: get this from API bot_name = "<@U2J5GAF96>" token = os.environ["CHOPBOT_3000_TOKEN"] client = SlackClient(token) if client.rtm_connect(): while True: events = client.rtm_read() try: if len(events) == 0: logger.debug("No events. Sleeping...") time.sleep(1) for event in events: logger.info("Received an event with text: ") logger.info(event) if event['type'] == 'message' and event['text'].startswith(bot_name): reply(event, bot_name, client, repo) except Exception as e: logger.error("Invalid event received") logger.error(e)
412233eff937f64579827e7a7c64963d23a716fa
zipa/module.py
zipa/module.py
import sys from .magic import SelfWrapper def register_module(name): self = sys.modules['zipa'] sys.modules[name] = SelfWrapper(self) class ModuleImporter(object): def __init__(self, module_name): self.name = module_name def find_module(self, name, path=None): if name.startswith('{}.'.format(self.name)): return self return None def load_module(self, name): register_module(name)
import sys from .magic import SelfWrapper def register_module(name): self = sys.modules['zipa'] sys.modules[name] = SelfWrapper(self) class ModuleImporter(object): def __init__(self, module_name): self.module = module_name + '.' def find_module(self, name, path=None): if name.startswith(self.module): return self return None def load_module(self, name): register_module(name)
Make the logic more readable
Make the logic more readable
Python
apache-2.0
PressLabs/zipa
import sys from .magic import SelfWrapper def register_module(name): self = sys.modules['zipa'] sys.modules[name] = SelfWrapper(self) class ModuleImporter(object): def __init__(self, module_name): self.name = module_name def find_module(self, name, path=None): if name.startswith('{}.'.format(self.name)): return self return None def load_module(self, name): register_module(name) Make the logic more readable
import sys from .magic import SelfWrapper def register_module(name): self = sys.modules['zipa'] sys.modules[name] = SelfWrapper(self) class ModuleImporter(object): def __init__(self, module_name): self.module = module_name + '.' def find_module(self, name, path=None): if name.startswith(self.module): return self return None def load_module(self, name): register_module(name)
<commit_before>import sys from .magic import SelfWrapper def register_module(name): self = sys.modules['zipa'] sys.modules[name] = SelfWrapper(self) class ModuleImporter(object): def __init__(self, module_name): self.name = module_name def find_module(self, name, path=None): if name.startswith('{}.'.format(self.name)): return self return None def load_module(self, name): register_module(name) <commit_msg>Make the logic more readable<commit_after>
import sys from .magic import SelfWrapper def register_module(name): self = sys.modules['zipa'] sys.modules[name] = SelfWrapper(self) class ModuleImporter(object): def __init__(self, module_name): self.module = module_name + '.' def find_module(self, name, path=None): if name.startswith(self.module): return self return None def load_module(self, name): register_module(name)
import sys from .magic import SelfWrapper def register_module(name): self = sys.modules['zipa'] sys.modules[name] = SelfWrapper(self) class ModuleImporter(object): def __init__(self, module_name): self.name = module_name def find_module(self, name, path=None): if name.startswith('{}.'.format(self.name)): return self return None def load_module(self, name): register_module(name) Make the logic more readableimport sys from .magic import SelfWrapper def register_module(name): self = sys.modules['zipa'] sys.modules[name] = SelfWrapper(self) class ModuleImporter(object): def __init__(self, module_name): self.module = module_name + '.' def find_module(self, name, path=None): if name.startswith(self.module): return self return None def load_module(self, name): register_module(name)
<commit_before>import sys from .magic import SelfWrapper def register_module(name): self = sys.modules['zipa'] sys.modules[name] = SelfWrapper(self) class ModuleImporter(object): def __init__(self, module_name): self.name = module_name def find_module(self, name, path=None): if name.startswith('{}.'.format(self.name)): return self return None def load_module(self, name): register_module(name) <commit_msg>Make the logic more readable<commit_after>import sys from .magic import SelfWrapper def register_module(name): self = sys.modules['zipa'] sys.modules[name] = SelfWrapper(self) class ModuleImporter(object): def __init__(self, module_name): self.module = module_name + '.' def find_module(self, name, path=None): if name.startswith(self.module): return self return None def load_module(self, name): register_module(name)
6aee1c51d2607047091280abb56d2956cebe1ebb
zvm/zstring.py
zvm/zstring.py
# # A ZString-to-ASCII Universal Translator. # # For the license of this file, please consult the LICENSE file in the # root directory of this distribution. # class ZStringEndOfString(Exception): """No more data left in string.""" class ZStringStream(object): """This class takes an address and a ZMemory, and treats that as the begginning of a ZString. Subsequent calls to get() will return one ZChar code at a time, raising ZStringEndOfString when there is no more data.""" def __init__(self, zmem, addr): self._mem = zmem self._addr = addr self._has_ended = False self._get_block() def _get_block(self): from bitfield import BitField chunk = self._mem[self._addr:self._addr+2] print chunk self._data = BitField(''.join([chr(x) for x in chunk])) self._addr += 2 self._char_in_block = 0 def get(self, num=1): if self._has_ended: raise ZStringEndOfString offset = self._char_in_block * 5 print offset zchar = self._data[offset:offset+5] if self._char_in_block == 2: # If end-of-string marker is set... if self._data[15] == 1: self._has_ended = True else: self._get_block() else: self._char_in_block += 1 return zchar
# # A ZString-to-ASCII Universal Translator. # # For the license of this file, please consult the LICENSE file in the # root directory of this distribution. # class ZStringEndOfString(Exception): """No more data left in string.""" class ZStringStream(object): """This class takes an address and a ZMemory, and treats that as the begginning of a ZString. Subsequent calls to get() will return one ZChar code at a time, raising ZStringEndOfString when there is no more data.""" def __init__(self, zmem, addr): self._mem = zmem self._addr = addr self._has_ended = False self._get_block() def _get_block(self): from bitfield import BitField chunk = self._mem[self._addr:self._addr+2] self._data = BitField(''.join([chr(x) for x in chunk])) self._addr += 2 self._char_in_block = 0 def get(self, num=1): if self._has_ended: raise ZStringEndOfString # We must read in sequence bits 14-10, 9-5, 4-0. offset = (2 - self._char_in_block) * 5 zchar = self._data[offset:offset+5] if self._char_in_block == 2: # If end-of-string marker is set... if self._data[15] == 1: self._has_ended = True else: self._get_block() else: self._char_in_block += 1 return zchar
Make the string translator return the actual right values!
Make the string translator return the actual right values! * zvm/zstring.py: (ZStringStream._get_block): Remove debug printing. (ZStringStream.get): Make the offset calculations work on the correct bits of the data chunk. Remove debug printing.
Python
bsd-3-clause
sussman/zvm,sussman/zvm
# # A ZString-to-ASCII Universal Translator. # # For the license of this file, please consult the LICENSE file in the # root directory of this distribution. # class ZStringEndOfString(Exception): """No more data left in string.""" class ZStringStream(object): """This class takes an address and a ZMemory, and treats that as the begginning of a ZString. Subsequent calls to get() will return one ZChar code at a time, raising ZStringEndOfString when there is no more data.""" def __init__(self, zmem, addr): self._mem = zmem self._addr = addr self._has_ended = False self._get_block() def _get_block(self): from bitfield import BitField chunk = self._mem[self._addr:self._addr+2] print chunk self._data = BitField(''.join([chr(x) for x in chunk])) self._addr += 2 self._char_in_block = 0 def get(self, num=1): if self._has_ended: raise ZStringEndOfString offset = self._char_in_block * 5 print offset zchar = self._data[offset:offset+5] if self._char_in_block == 2: # If end-of-string marker is set... if self._data[15] == 1: self._has_ended = True else: self._get_block() else: self._char_in_block += 1 return zchar Make the string translator return the actual right values! * zvm/zstring.py: (ZStringStream._get_block): Remove debug printing. (ZStringStream.get): Make the offset calculations work on the correct bits of the data chunk. Remove debug printing.
# # A ZString-to-ASCII Universal Translator. # # For the license of this file, please consult the LICENSE file in the # root directory of this distribution. # class ZStringEndOfString(Exception): """No more data left in string.""" class ZStringStream(object): """This class takes an address and a ZMemory, and treats that as the begginning of a ZString. Subsequent calls to get() will return one ZChar code at a time, raising ZStringEndOfString when there is no more data.""" def __init__(self, zmem, addr): self._mem = zmem self._addr = addr self._has_ended = False self._get_block() def _get_block(self): from bitfield import BitField chunk = self._mem[self._addr:self._addr+2] self._data = BitField(''.join([chr(x) for x in chunk])) self._addr += 2 self._char_in_block = 0 def get(self, num=1): if self._has_ended: raise ZStringEndOfString # We must read in sequence bits 14-10, 9-5, 4-0. offset = (2 - self._char_in_block) * 5 zchar = self._data[offset:offset+5] if self._char_in_block == 2: # If end-of-string marker is set... if self._data[15] == 1: self._has_ended = True else: self._get_block() else: self._char_in_block += 1 return zchar
<commit_before># # A ZString-to-ASCII Universal Translator. # # For the license of this file, please consult the LICENSE file in the # root directory of this distribution. # class ZStringEndOfString(Exception): """No more data left in string.""" class ZStringStream(object): """This class takes an address and a ZMemory, and treats that as the begginning of a ZString. Subsequent calls to get() will return one ZChar code at a time, raising ZStringEndOfString when there is no more data.""" def __init__(self, zmem, addr): self._mem = zmem self._addr = addr self._has_ended = False self._get_block() def _get_block(self): from bitfield import BitField chunk = self._mem[self._addr:self._addr+2] print chunk self._data = BitField(''.join([chr(x) for x in chunk])) self._addr += 2 self._char_in_block = 0 def get(self, num=1): if self._has_ended: raise ZStringEndOfString offset = self._char_in_block * 5 print offset zchar = self._data[offset:offset+5] if self._char_in_block == 2: # If end-of-string marker is set... if self._data[15] == 1: self._has_ended = True else: self._get_block() else: self._char_in_block += 1 return zchar <commit_msg>Make the string translator return the actual right values! * zvm/zstring.py: (ZStringStream._get_block): Remove debug printing. (ZStringStream.get): Make the offset calculations work on the correct bits of the data chunk. Remove debug printing.<commit_after>
# # A ZString-to-ASCII Universal Translator. # # For the license of this file, please consult the LICENSE file in the # root directory of this distribution. # class ZStringEndOfString(Exception): """No more data left in string.""" class ZStringStream(object): """This class takes an address and a ZMemory, and treats that as the begginning of a ZString. Subsequent calls to get() will return one ZChar code at a time, raising ZStringEndOfString when there is no more data.""" def __init__(self, zmem, addr): self._mem = zmem self._addr = addr self._has_ended = False self._get_block() def _get_block(self): from bitfield import BitField chunk = self._mem[self._addr:self._addr+2] self._data = BitField(''.join([chr(x) for x in chunk])) self._addr += 2 self._char_in_block = 0 def get(self, num=1): if self._has_ended: raise ZStringEndOfString # We must read in sequence bits 14-10, 9-5, 4-0. offset = (2 - self._char_in_block) * 5 zchar = self._data[offset:offset+5] if self._char_in_block == 2: # If end-of-string marker is set... if self._data[15] == 1: self._has_ended = True else: self._get_block() else: self._char_in_block += 1 return zchar
# # A ZString-to-ASCII Universal Translator. # # For the license of this file, please consult the LICENSE file in the # root directory of this distribution. # class ZStringEndOfString(Exception): """No more data left in string.""" class ZStringStream(object): """This class takes an address and a ZMemory, and treats that as the begginning of a ZString. Subsequent calls to get() will return one ZChar code at a time, raising ZStringEndOfString when there is no more data.""" def __init__(self, zmem, addr): self._mem = zmem self._addr = addr self._has_ended = False self._get_block() def _get_block(self): from bitfield import BitField chunk = self._mem[self._addr:self._addr+2] print chunk self._data = BitField(''.join([chr(x) for x in chunk])) self._addr += 2 self._char_in_block = 0 def get(self, num=1): if self._has_ended: raise ZStringEndOfString offset = self._char_in_block * 5 print offset zchar = self._data[offset:offset+5] if self._char_in_block == 2: # If end-of-string marker is set... if self._data[15] == 1: self._has_ended = True else: self._get_block() else: self._char_in_block += 1 return zchar Make the string translator return the actual right values! * zvm/zstring.py: (ZStringStream._get_block): Remove debug printing. (ZStringStream.get): Make the offset calculations work on the correct bits of the data chunk. Remove debug printing.# # A ZString-to-ASCII Universal Translator. # # For the license of this file, please consult the LICENSE file in the # root directory of this distribution. # class ZStringEndOfString(Exception): """No more data left in string.""" class ZStringStream(object): """This class takes an address and a ZMemory, and treats that as the begginning of a ZString. Subsequent calls to get() will return one ZChar code at a time, raising ZStringEndOfString when there is no more data.""" def __init__(self, zmem, addr): self._mem = zmem self._addr = addr self._has_ended = False self._get_block() def _get_block(self): from bitfield import BitField chunk = self._mem[self._addr:self._addr+2] self._data = BitField(''.join([chr(x) for x in chunk])) self._addr += 2 self._char_in_block = 0 def get(self, num=1): if self._has_ended: raise ZStringEndOfString # We must read in sequence bits 14-10, 9-5, 4-0. offset = (2 - self._char_in_block) * 5 zchar = self._data[offset:offset+5] if self._char_in_block == 2: # If end-of-string marker is set... if self._data[15] == 1: self._has_ended = True else: self._get_block() else: self._char_in_block += 1 return zchar
<commit_before># # A ZString-to-ASCII Universal Translator. # # For the license of this file, please consult the LICENSE file in the # root directory of this distribution. # class ZStringEndOfString(Exception): """No more data left in string.""" class ZStringStream(object): """This class takes an address and a ZMemory, and treats that as the begginning of a ZString. Subsequent calls to get() will return one ZChar code at a time, raising ZStringEndOfString when there is no more data.""" def __init__(self, zmem, addr): self._mem = zmem self._addr = addr self._has_ended = False self._get_block() def _get_block(self): from bitfield import BitField chunk = self._mem[self._addr:self._addr+2] print chunk self._data = BitField(''.join([chr(x) for x in chunk])) self._addr += 2 self._char_in_block = 0 def get(self, num=1): if self._has_ended: raise ZStringEndOfString offset = self._char_in_block * 5 print offset zchar = self._data[offset:offset+5] if self._char_in_block == 2: # If end-of-string marker is set... if self._data[15] == 1: self._has_ended = True else: self._get_block() else: self._char_in_block += 1 return zchar <commit_msg>Make the string translator return the actual right values! * zvm/zstring.py: (ZStringStream._get_block): Remove debug printing. (ZStringStream.get): Make the offset calculations work on the correct bits of the data chunk. Remove debug printing.<commit_after># # A ZString-to-ASCII Universal Translator. # # For the license of this file, please consult the LICENSE file in the # root directory of this distribution. # class ZStringEndOfString(Exception): """No more data left in string.""" class ZStringStream(object): """This class takes an address and a ZMemory, and treats that as the begginning of a ZString. Subsequent calls to get() will return one ZChar code at a time, raising ZStringEndOfString when there is no more data.""" def __init__(self, zmem, addr): self._mem = zmem self._addr = addr self._has_ended = False self._get_block() def _get_block(self): from bitfield import BitField chunk = self._mem[self._addr:self._addr+2] self._data = BitField(''.join([chr(x) for x in chunk])) self._addr += 2 self._char_in_block = 0 def get(self, num=1): if self._has_ended: raise ZStringEndOfString # We must read in sequence bits 14-10, 9-5, 4-0. offset = (2 - self._char_in_block) * 5 zchar = self._data[offset:offset+5] if self._char_in_block == 2: # If end-of-string marker is set... if self._data[15] == 1: self._has_ended = True else: self._get_block() else: self._char_in_block += 1 return zchar
2fcef274bb3ee23329fb523ec9b3d59266584fe9
runtests.py
runtests.py
import sys try: from django.conf import settings from django.test.utils import get_runner settings.configure( DEBUG=True, USE_TZ=True, DATABASES={ "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:", } }, INSTALLED_APPS=[ "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.staticfiles", "django.contrib.sites", "chartit", "chartit_tests", ], SITE_ID=1, MIDDLEWARE_CLASSES=(), STATIC_URL='/static/' ) try: import django setup = django.setup except AttributeError: pass else: setup() except ImportError: import traceback traceback.print_exc() raise ImportError("To fix this error, run: pip install -r requirements-test.txt") def run_tests(*test_args): if not test_args: test_args = ["chartit_tests"] # Run tests TestRunner = get_runner(settings) test_runner = TestRunner() failures = test_runner.run_tests(test_args) if failures: sys.exit(bool(failures)) if __name__ == "__main__": run_tests(*sys.argv[1:])
import sys try: from django.conf import settings from django.test.utils import get_runner settings.configure( DEBUG=True, USE_TZ=True, DATABASES={ "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:", } }, INSTALLED_APPS=[ "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.staticfiles", "django.contrib.sites", "chartit", "chartit_tests", ], SITE_ID=1, MIDDLEWARE_CLASSES=(), STATIC_URL='/static/' ) try: import django setup = django.setup except AttributeError: pass else: setup() except ImportError: import traceback traceback.print_exc() raise ImportError("To fix this error, run: pip install -r requirements.txt") def run_tests(*test_args): if not test_args: test_args = ["chartit_tests"] # Run tests TestRunner = get_runner(settings) test_runner = TestRunner() failures = test_runner.run_tests(test_args) if failures: sys.exit(bool(failures)) if __name__ == "__main__": run_tests(*sys.argv[1:])
Update file name in error message
Update file name in error message
Python
bsd-2-clause
pgollakota/django-chartit,pgollakota/django-chartit,pgollakota/django-chartit
import sys try: from django.conf import settings from django.test.utils import get_runner settings.configure( DEBUG=True, USE_TZ=True, DATABASES={ "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:", } }, INSTALLED_APPS=[ "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.staticfiles", "django.contrib.sites", "chartit", "chartit_tests", ], SITE_ID=1, MIDDLEWARE_CLASSES=(), STATIC_URL='/static/' ) try: import django setup = django.setup except AttributeError: pass else: setup() except ImportError: import traceback traceback.print_exc() raise ImportError("To fix this error, run: pip install -r requirements-test.txt") def run_tests(*test_args): if not test_args: test_args = ["chartit_tests"] # Run tests TestRunner = get_runner(settings) test_runner = TestRunner() failures = test_runner.run_tests(test_args) if failures: sys.exit(bool(failures)) if __name__ == "__main__": run_tests(*sys.argv[1:]) Update file name in error message
import sys try: from django.conf import settings from django.test.utils import get_runner settings.configure( DEBUG=True, USE_TZ=True, DATABASES={ "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:", } }, INSTALLED_APPS=[ "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.staticfiles", "django.contrib.sites", "chartit", "chartit_tests", ], SITE_ID=1, MIDDLEWARE_CLASSES=(), STATIC_URL='/static/' ) try: import django setup = django.setup except AttributeError: pass else: setup() except ImportError: import traceback traceback.print_exc() raise ImportError("To fix this error, run: pip install -r requirements.txt") def run_tests(*test_args): if not test_args: test_args = ["chartit_tests"] # Run tests TestRunner = get_runner(settings) test_runner = TestRunner() failures = test_runner.run_tests(test_args) if failures: sys.exit(bool(failures)) if __name__ == "__main__": run_tests(*sys.argv[1:])
<commit_before>import sys try: from django.conf import settings from django.test.utils import get_runner settings.configure( DEBUG=True, USE_TZ=True, DATABASES={ "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:", } }, INSTALLED_APPS=[ "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.staticfiles", "django.contrib.sites", "chartit", "chartit_tests", ], SITE_ID=1, MIDDLEWARE_CLASSES=(), STATIC_URL='/static/' ) try: import django setup = django.setup except AttributeError: pass else: setup() except ImportError: import traceback traceback.print_exc() raise ImportError("To fix this error, run: pip install -r requirements-test.txt") def run_tests(*test_args): if not test_args: test_args = ["chartit_tests"] # Run tests TestRunner = get_runner(settings) test_runner = TestRunner() failures = test_runner.run_tests(test_args) if failures: sys.exit(bool(failures)) if __name__ == "__main__": run_tests(*sys.argv[1:]) <commit_msg>Update file name in error message<commit_after>
import sys try: from django.conf import settings from django.test.utils import get_runner settings.configure( DEBUG=True, USE_TZ=True, DATABASES={ "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:", } }, INSTALLED_APPS=[ "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.staticfiles", "django.contrib.sites", "chartit", "chartit_tests", ], SITE_ID=1, MIDDLEWARE_CLASSES=(), STATIC_URL='/static/' ) try: import django setup = django.setup except AttributeError: pass else: setup() except ImportError: import traceback traceback.print_exc() raise ImportError("To fix this error, run: pip install -r requirements.txt") def run_tests(*test_args): if not test_args: test_args = ["chartit_tests"] # Run tests TestRunner = get_runner(settings) test_runner = TestRunner() failures = test_runner.run_tests(test_args) if failures: sys.exit(bool(failures)) if __name__ == "__main__": run_tests(*sys.argv[1:])
import sys try: from django.conf import settings from django.test.utils import get_runner settings.configure( DEBUG=True, USE_TZ=True, DATABASES={ "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:", } }, INSTALLED_APPS=[ "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.staticfiles", "django.contrib.sites", "chartit", "chartit_tests", ], SITE_ID=1, MIDDLEWARE_CLASSES=(), STATIC_URL='/static/' ) try: import django setup = django.setup except AttributeError: pass else: setup() except ImportError: import traceback traceback.print_exc() raise ImportError("To fix this error, run: pip install -r requirements-test.txt") def run_tests(*test_args): if not test_args: test_args = ["chartit_tests"] # Run tests TestRunner = get_runner(settings) test_runner = TestRunner() failures = test_runner.run_tests(test_args) if failures: sys.exit(bool(failures)) if __name__ == "__main__": run_tests(*sys.argv[1:]) Update file name in error messageimport sys try: from django.conf import settings from django.test.utils import get_runner settings.configure( DEBUG=True, USE_TZ=True, DATABASES={ "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:", } }, INSTALLED_APPS=[ "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.staticfiles", "django.contrib.sites", "chartit", "chartit_tests", ], SITE_ID=1, MIDDLEWARE_CLASSES=(), STATIC_URL='/static/' ) try: import django setup = django.setup except AttributeError: pass else: setup() except ImportError: import traceback traceback.print_exc() raise ImportError("To fix this error, run: pip install -r requirements.txt") def run_tests(*test_args): if not test_args: test_args = ["chartit_tests"] # Run tests TestRunner = get_runner(settings) test_runner = TestRunner() failures = test_runner.run_tests(test_args) if failures: sys.exit(bool(failures)) if __name__ == "__main__": run_tests(*sys.argv[1:])
<commit_before>import sys try: from django.conf import settings from django.test.utils import get_runner settings.configure( DEBUG=True, USE_TZ=True, DATABASES={ "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:", } }, INSTALLED_APPS=[ "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.staticfiles", "django.contrib.sites", "chartit", "chartit_tests", ], SITE_ID=1, MIDDLEWARE_CLASSES=(), STATIC_URL='/static/' ) try: import django setup = django.setup except AttributeError: pass else: setup() except ImportError: import traceback traceback.print_exc() raise ImportError("To fix this error, run: pip install -r requirements-test.txt") def run_tests(*test_args): if not test_args: test_args = ["chartit_tests"] # Run tests TestRunner = get_runner(settings) test_runner = TestRunner() failures = test_runner.run_tests(test_args) if failures: sys.exit(bool(failures)) if __name__ == "__main__": run_tests(*sys.argv[1:]) <commit_msg>Update file name in error message<commit_after>import sys try: from django.conf import settings from django.test.utils import get_runner settings.configure( DEBUG=True, USE_TZ=True, DATABASES={ "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:", } }, INSTALLED_APPS=[ "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.staticfiles", "django.contrib.sites", "chartit", "chartit_tests", ], SITE_ID=1, MIDDLEWARE_CLASSES=(), STATIC_URL='/static/' ) try: import django setup = django.setup except AttributeError: pass else: setup() except ImportError: import traceback traceback.print_exc() raise ImportError("To fix this error, run: pip install -r requirements.txt") def run_tests(*test_args): if not test_args: test_args = ["chartit_tests"] # Run tests TestRunner = get_runner(settings) test_runner = TestRunner() failures = test_runner.run_tests(test_args) if failures: sys.exit(bool(failures)) if __name__ == "__main__": run_tests(*sys.argv[1:])
16372a41a14ccb5ff7148bcb913864598f5be321
src/twitchHandler.py
src/twitchHandler.py
from twitch import TwitchClient class TwitchHandler: async def validateStream(url, twitch_id): client = TwitchClient(client_id=twitch_id) channelName = url.split('/')[-1] channels = client.search.channels(channelName) if channels: channel = channels[0] return 'World of Warcraft' in channel.game return False async def fetchStreamInfo(url, twitch_id): client = TwitchClient(client_id=twitch_id) channelName = url.split('/')[-1] channels = client.search.channels(channelName) title = None description = None avatar = None views = None followers = None if channels: channel = channels[0] for ch in channels: if ch.display_name == channelName: channel = ch break avatar = channel.logo title = channel.status description = channel.description views = channel.views followers = channel.followers return title, description, avatar, views, followers
from twitch import TwitchClient class TwitchHandler: async def validateStream(url, twitch_id): client = TwitchClient(client_id=twitch_id) channelName = url.split('/')[-1] channels = client.search.channels(channelName) if channels: for ch in channels: if ch.name.casefold() == channelName.casefold(): return 'World of Warcraft' in ch.game return False async def fetchStreamInfo(url, twitch_id): client = TwitchClient(client_id=twitch_id) channelName = url.split('/')[-1] channels = client.search.channels(channelName) title = None description = None avatar = None views = None followers = None if channels: channel = channels[0] for ch in channels: if ch.name.casefold() == channelName.casefold(): channel = ch break avatar = channel.logo title = channel.status description = channel.description views = channel.views followers = channel.followers return title, description, avatar, views, followers
Fix Bot Errors with Selecting Wrong Users
Fix Bot Errors with Selecting Wrong Users Also fix validation in case the zeroth user isn't correct, which is happening a bunch. Compare the names casefolded incase of mismatch in capitalization.
Python
mit
lgkern/PriestPy
from twitch import TwitchClient class TwitchHandler: async def validateStream(url, twitch_id): client = TwitchClient(client_id=twitch_id) channelName = url.split('/')[-1] channels = client.search.channels(channelName) if channels: channel = channels[0] return 'World of Warcraft' in channel.game return False async def fetchStreamInfo(url, twitch_id): client = TwitchClient(client_id=twitch_id) channelName = url.split('/')[-1] channels = client.search.channels(channelName) title = None description = None avatar = None views = None followers = None if channels: channel = channels[0] for ch in channels: if ch.display_name == channelName: channel = ch break avatar = channel.logo title = channel.status description = channel.description views = channel.views followers = channel.followers return title, description, avatar, views, followers Fix Bot Errors with Selecting Wrong Users Also fix validation in case the zeroth user isn't correct, which is happening a bunch. Compare the names casefolded incase of mismatch in capitalization.
from twitch import TwitchClient class TwitchHandler: async def validateStream(url, twitch_id): client = TwitchClient(client_id=twitch_id) channelName = url.split('/')[-1] channels = client.search.channels(channelName) if channels: for ch in channels: if ch.name.casefold() == channelName.casefold(): return 'World of Warcraft' in ch.game return False async def fetchStreamInfo(url, twitch_id): client = TwitchClient(client_id=twitch_id) channelName = url.split('/')[-1] channels = client.search.channels(channelName) title = None description = None avatar = None views = None followers = None if channels: channel = channels[0] for ch in channels: if ch.name.casefold() == channelName.casefold(): channel = ch break avatar = channel.logo title = channel.status description = channel.description views = channel.views followers = channel.followers return title, description, avatar, views, followers
<commit_before>from twitch import TwitchClient class TwitchHandler: async def validateStream(url, twitch_id): client = TwitchClient(client_id=twitch_id) channelName = url.split('/')[-1] channels = client.search.channels(channelName) if channels: channel = channels[0] return 'World of Warcraft' in channel.game return False async def fetchStreamInfo(url, twitch_id): client = TwitchClient(client_id=twitch_id) channelName = url.split('/')[-1] channels = client.search.channels(channelName) title = None description = None avatar = None views = None followers = None if channels: channel = channels[0] for ch in channels: if ch.display_name == channelName: channel = ch break avatar = channel.logo title = channel.status description = channel.description views = channel.views followers = channel.followers return title, description, avatar, views, followers <commit_msg>Fix Bot Errors with Selecting Wrong Users Also fix validation in case the zeroth user isn't correct, which is happening a bunch. Compare the names casefolded incase of mismatch in capitalization.<commit_after>
from twitch import TwitchClient class TwitchHandler: async def validateStream(url, twitch_id): client = TwitchClient(client_id=twitch_id) channelName = url.split('/')[-1] channels = client.search.channels(channelName) if channels: for ch in channels: if ch.name.casefold() == channelName.casefold(): return 'World of Warcraft' in ch.game return False async def fetchStreamInfo(url, twitch_id): client = TwitchClient(client_id=twitch_id) channelName = url.split('/')[-1] channels = client.search.channels(channelName) title = None description = None avatar = None views = None followers = None if channels: channel = channels[0] for ch in channels: if ch.name.casefold() == channelName.casefold(): channel = ch break avatar = channel.logo title = channel.status description = channel.description views = channel.views followers = channel.followers return title, description, avatar, views, followers
from twitch import TwitchClient class TwitchHandler: async def validateStream(url, twitch_id): client = TwitchClient(client_id=twitch_id) channelName = url.split('/')[-1] channels = client.search.channels(channelName) if channels: channel = channels[0] return 'World of Warcraft' in channel.game return False async def fetchStreamInfo(url, twitch_id): client = TwitchClient(client_id=twitch_id) channelName = url.split('/')[-1] channels = client.search.channels(channelName) title = None description = None avatar = None views = None followers = None if channels: channel = channels[0] for ch in channels: if ch.display_name == channelName: channel = ch break avatar = channel.logo title = channel.status description = channel.description views = channel.views followers = channel.followers return title, description, avatar, views, followers Fix Bot Errors with Selecting Wrong Users Also fix validation in case the zeroth user isn't correct, which is happening a bunch. Compare the names casefolded incase of mismatch in capitalization.from twitch import TwitchClient class TwitchHandler: async def validateStream(url, twitch_id): client = TwitchClient(client_id=twitch_id) channelName = url.split('/')[-1] channels = client.search.channels(channelName) if channels: for ch in channels: if ch.name.casefold() == channelName.casefold(): return 'World of Warcraft' in ch.game return False async def fetchStreamInfo(url, twitch_id): client = TwitchClient(client_id=twitch_id) channelName = url.split('/')[-1] channels = client.search.channels(channelName) title = None description = None avatar = None views = None followers = None if channels: channel = channels[0] for ch in channels: if ch.name.casefold() == channelName.casefold(): channel = ch break avatar = channel.logo title = channel.status description = channel.description views = channel.views followers = channel.followers return title, description, avatar, views, followers
<commit_before>from twitch import TwitchClient class TwitchHandler: async def validateStream(url, twitch_id): client = TwitchClient(client_id=twitch_id) channelName = url.split('/')[-1] channels = client.search.channels(channelName) if channels: channel = channels[0] return 'World of Warcraft' in channel.game return False async def fetchStreamInfo(url, twitch_id): client = TwitchClient(client_id=twitch_id) channelName = url.split('/')[-1] channels = client.search.channels(channelName) title = None description = None avatar = None views = None followers = None if channels: channel = channels[0] for ch in channels: if ch.display_name == channelName: channel = ch break avatar = channel.logo title = channel.status description = channel.description views = channel.views followers = channel.followers return title, description, avatar, views, followers <commit_msg>Fix Bot Errors with Selecting Wrong Users Also fix validation in case the zeroth user isn't correct, which is happening a bunch. Compare the names casefolded incase of mismatch in capitalization.<commit_after>from twitch import TwitchClient class TwitchHandler: async def validateStream(url, twitch_id): client = TwitchClient(client_id=twitch_id) channelName = url.split('/')[-1] channels = client.search.channels(channelName) if channels: for ch in channels: if ch.name.casefold() == channelName.casefold(): return 'World of Warcraft' in ch.game return False async def fetchStreamInfo(url, twitch_id): client = TwitchClient(client_id=twitch_id) channelName = url.split('/')[-1] channels = client.search.channels(channelName) title = None description = None avatar = None views = None followers = None if channels: channel = channels[0] for ch in channels: if ch.name.casefold() == channelName.casefold(): channel = ch break avatar = channel.logo title = channel.status description = channel.description views = channel.views followers = channel.followers return title, description, avatar, views, followers
a7a050f71901abfc9477e70b7fc3319cf17b078a
thefeeder/public_message_datatype.py
thefeeder/public_message_datatype.py
import collections import logging from datatypes.core import DictionaryValidator from datatypes.validators import geo_json_validator, entry_validator from voluptuous import All schema = { "title_number": All(str), "extent": geo_json_validator.geo_json_schema, "property_description": entry_validator.entry_schema, "price_paid": entry_validator.entry_schema, } logging.basicConfig(level=logging.INFO) logger = logging.getLogger() logger.addHandler(logging.StreamHandler()) class PublicMessageDatatype(DictionaryValidator): def to_canonical_form(self, data): # self.validate(data) TODO: this is not working filtered = {} for expected_key in schema.iterkeys(): found = data.get(expected_key) if found: filtered[expected_key] = found return filtered def define_error_dictionary(self): return { "title_number": "title_number is a required field", "property_description": "property_description is a required field", "price_paid": "price_paid is a required field", "extent": "Extent must be well formed", } def define_schema(self): return schema
import collections import logging from datatypes.core import DictionaryValidator from datatypes.validators import geo_json_validator, entry_validator from voluptuous import All schema = { "title_number": All(str), "tenure" : All(str), "class_of_title" : All(str), "extent": geo_json_validator.geo_json_schema, "property_description": entry_validator.entry_schema, "price_paid": entry_validator.entry_schema, } logging.basicConfig(level=logging.INFO) logger = logging.getLogger() logger.addHandler(logging.StreamHandler()) class PublicMessageDatatype(DictionaryValidator): def to_canonical_form(self, data): # self.validate(data) TODO: this is not working filtered = {} for expected_key in schema.iterkeys(): found = data.get(expected_key) if found: filtered[expected_key] = found return filtered def define_error_dictionary(self): return { "title_number": "title_number is a required field", "tenure": "title_number is a required field", "class_of_title": "title_number is a required field", "property_description": "property_description is a required field", "price_paid": "price_paid is a required field", "extent": "Extent must be well formed", } def define_schema(self): return schema
Update public schema to include class_of_title and tenure
Update public schema to include class_of_title and tenure
Python
mit
LandRegistry/the-feeder-alpha,LandRegistry/the-feeder-alpha
import collections import logging from datatypes.core import DictionaryValidator from datatypes.validators import geo_json_validator, entry_validator from voluptuous import All schema = { "title_number": All(str), "extent": geo_json_validator.geo_json_schema, "property_description": entry_validator.entry_schema, "price_paid": entry_validator.entry_schema, } logging.basicConfig(level=logging.INFO) logger = logging.getLogger() logger.addHandler(logging.StreamHandler()) class PublicMessageDatatype(DictionaryValidator): def to_canonical_form(self, data): # self.validate(data) TODO: this is not working filtered = {} for expected_key in schema.iterkeys(): found = data.get(expected_key) if found: filtered[expected_key] = found return filtered def define_error_dictionary(self): return { "title_number": "title_number is a required field", "property_description": "property_description is a required field", "price_paid": "price_paid is a required field", "extent": "Extent must be well formed", } def define_schema(self): return schema Update public schema to include class_of_title and tenure
import collections import logging from datatypes.core import DictionaryValidator from datatypes.validators import geo_json_validator, entry_validator from voluptuous import All schema = { "title_number": All(str), "tenure" : All(str), "class_of_title" : All(str), "extent": geo_json_validator.geo_json_schema, "property_description": entry_validator.entry_schema, "price_paid": entry_validator.entry_schema, } logging.basicConfig(level=logging.INFO) logger = logging.getLogger() logger.addHandler(logging.StreamHandler()) class PublicMessageDatatype(DictionaryValidator): def to_canonical_form(self, data): # self.validate(data) TODO: this is not working filtered = {} for expected_key in schema.iterkeys(): found = data.get(expected_key) if found: filtered[expected_key] = found return filtered def define_error_dictionary(self): return { "title_number": "title_number is a required field", "tenure": "title_number is a required field", "class_of_title": "title_number is a required field", "property_description": "property_description is a required field", "price_paid": "price_paid is a required field", "extent": "Extent must be well formed", } def define_schema(self): return schema
<commit_before>import collections import logging from datatypes.core import DictionaryValidator from datatypes.validators import geo_json_validator, entry_validator from voluptuous import All schema = { "title_number": All(str), "extent": geo_json_validator.geo_json_schema, "property_description": entry_validator.entry_schema, "price_paid": entry_validator.entry_schema, } logging.basicConfig(level=logging.INFO) logger = logging.getLogger() logger.addHandler(logging.StreamHandler()) class PublicMessageDatatype(DictionaryValidator): def to_canonical_form(self, data): # self.validate(data) TODO: this is not working filtered = {} for expected_key in schema.iterkeys(): found = data.get(expected_key) if found: filtered[expected_key] = found return filtered def define_error_dictionary(self): return { "title_number": "title_number is a required field", "property_description": "property_description is a required field", "price_paid": "price_paid is a required field", "extent": "Extent must be well formed", } def define_schema(self): return schema <commit_msg>Update public schema to include class_of_title and tenure<commit_after>
import collections import logging from datatypes.core import DictionaryValidator from datatypes.validators import geo_json_validator, entry_validator from voluptuous import All schema = { "title_number": All(str), "tenure" : All(str), "class_of_title" : All(str), "extent": geo_json_validator.geo_json_schema, "property_description": entry_validator.entry_schema, "price_paid": entry_validator.entry_schema, } logging.basicConfig(level=logging.INFO) logger = logging.getLogger() logger.addHandler(logging.StreamHandler()) class PublicMessageDatatype(DictionaryValidator): def to_canonical_form(self, data): # self.validate(data) TODO: this is not working filtered = {} for expected_key in schema.iterkeys(): found = data.get(expected_key) if found: filtered[expected_key] = found return filtered def define_error_dictionary(self): return { "title_number": "title_number is a required field", "tenure": "title_number is a required field", "class_of_title": "title_number is a required field", "property_description": "property_description is a required field", "price_paid": "price_paid is a required field", "extent": "Extent must be well formed", } def define_schema(self): return schema
import collections import logging from datatypes.core import DictionaryValidator from datatypes.validators import geo_json_validator, entry_validator from voluptuous import All schema = { "title_number": All(str), "extent": geo_json_validator.geo_json_schema, "property_description": entry_validator.entry_schema, "price_paid": entry_validator.entry_schema, } logging.basicConfig(level=logging.INFO) logger = logging.getLogger() logger.addHandler(logging.StreamHandler()) class PublicMessageDatatype(DictionaryValidator): def to_canonical_form(self, data): # self.validate(data) TODO: this is not working filtered = {} for expected_key in schema.iterkeys(): found = data.get(expected_key) if found: filtered[expected_key] = found return filtered def define_error_dictionary(self): return { "title_number": "title_number is a required field", "property_description": "property_description is a required field", "price_paid": "price_paid is a required field", "extent": "Extent must be well formed", } def define_schema(self): return schema Update public schema to include class_of_title and tenureimport collections import logging from datatypes.core import DictionaryValidator from datatypes.validators import geo_json_validator, entry_validator from voluptuous import All schema = { "title_number": All(str), "tenure" : All(str), "class_of_title" : All(str), "extent": geo_json_validator.geo_json_schema, "property_description": entry_validator.entry_schema, "price_paid": entry_validator.entry_schema, } logging.basicConfig(level=logging.INFO) logger = logging.getLogger() logger.addHandler(logging.StreamHandler()) class PublicMessageDatatype(DictionaryValidator): def to_canonical_form(self, data): # self.validate(data) TODO: this is not working filtered = {} for expected_key in schema.iterkeys(): found = data.get(expected_key) if found: filtered[expected_key] = found return filtered def define_error_dictionary(self): return { "title_number": "title_number is a required field", "tenure": "title_number is a required field", "class_of_title": "title_number is a required field", "property_description": "property_description is a required field", "price_paid": "price_paid is a required field", "extent": "Extent must be well formed", } def define_schema(self): return schema
<commit_before>import collections import logging from datatypes.core import DictionaryValidator from datatypes.validators import geo_json_validator, entry_validator from voluptuous import All schema = { "title_number": All(str), "extent": geo_json_validator.geo_json_schema, "property_description": entry_validator.entry_schema, "price_paid": entry_validator.entry_schema, } logging.basicConfig(level=logging.INFO) logger = logging.getLogger() logger.addHandler(logging.StreamHandler()) class PublicMessageDatatype(DictionaryValidator): def to_canonical_form(self, data): # self.validate(data) TODO: this is not working filtered = {} for expected_key in schema.iterkeys(): found = data.get(expected_key) if found: filtered[expected_key] = found return filtered def define_error_dictionary(self): return { "title_number": "title_number is a required field", "property_description": "property_description is a required field", "price_paid": "price_paid is a required field", "extent": "Extent must be well formed", } def define_schema(self): return schema <commit_msg>Update public schema to include class_of_title and tenure<commit_after>import collections import logging from datatypes.core import DictionaryValidator from datatypes.validators import geo_json_validator, entry_validator from voluptuous import All schema = { "title_number": All(str), "tenure" : All(str), "class_of_title" : All(str), "extent": geo_json_validator.geo_json_schema, "property_description": entry_validator.entry_schema, "price_paid": entry_validator.entry_schema, } logging.basicConfig(level=logging.INFO) logger = logging.getLogger() logger.addHandler(logging.StreamHandler()) class PublicMessageDatatype(DictionaryValidator): def to_canonical_form(self, data): # self.validate(data) TODO: this is not working filtered = {} for expected_key in schema.iterkeys(): found = data.get(expected_key) if found: filtered[expected_key] = found return filtered def define_error_dictionary(self): return { "title_number": "title_number is a required field", "tenure": "title_number is a required field", "class_of_title": "title_number is a required field", "property_description": "property_description is a required field", "price_paid": "price_paid is a required field", "extent": "Extent must be well formed", } def define_schema(self): return schema
9834830788bf9fe594bf4a4e67de36231fcd8990
stars/serializers.py
stars/serializers.py
from .models import Star from rest_framework import serializers class StarSerializer(serializers.ModelSerializer): class Meta: model = Star fields = ('pk', 'date', 'text', 'from_user', 'to_user', 'category', 'subcategory') class StarSmallSerializer(serializers.ModelSerializer): class Meta: model = Star depth = 1 fields = ('pk', 'date', 'text', 'category', 'from_user') class StarSwaggerSerializer(serializers.ModelSerializer): class Meta: model = Star fields = ('pk', 'category', 'subcategory', 'text') class StarEmployeesSubcategoriesSerializer(serializers.Serializer): subcategory__pk = serializers.IntegerField() subcategory__name = serializers.CharField(max_length=100) num_stars = serializers.IntegerField() class StarTopEmployeeLists(serializers.Serializer): to_user__id = serializers.IntegerField() to_user__username = serializers.CharField(max_length=100) to_user__first_name = serializers.CharField(max_length=100) to_user__last_name = serializers.CharField(max_length=100) num_stars = serializers.IntegerField()
from .models import Star from employees.models import Employee from rest_framework import serializers class EmployeeSimpleSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ('pk', 'username', 'first_name', 'last_name') class StarSerializer(serializers.ModelSerializer): class Meta: model = Star fields = ('pk', 'date', 'text', 'from_user', 'to_user', 'category', 'subcategory') class StarSmallSerializer(serializers.ModelSerializer): from_user = EmployeeSimpleSerializer() class Meta: model = Star depth = 1 fields = ('pk', 'date', 'text', 'category', 'from_user') class StarSwaggerSerializer(serializers.ModelSerializer): class Meta: model = Star fields = ('pk', 'category', 'subcategory', 'text') class StarEmployeesSubcategoriesSerializer(serializers.Serializer): subcategory__pk = serializers.IntegerField() subcategory__name = serializers.CharField(max_length=100) num_stars = serializers.IntegerField() class StarTopEmployeeLists(serializers.Serializer): to_user__id = serializers.IntegerField() to_user__username = serializers.CharField(max_length=100) to_user__first_name = serializers.CharField(max_length=100) to_user__last_name = serializers.CharField(max_length=100) num_stars = serializers.IntegerField()
Add EmployeeSimpleSerializer in order to avoid publish sensitive user data such passwords and other related fields
Add EmployeeSimpleSerializer in order to avoid publish sensitive user data such passwords and other related fields
Python
apache-2.0
belatrix/BackendAllStars
from .models import Star from rest_framework import serializers class StarSerializer(serializers.ModelSerializer): class Meta: model = Star fields = ('pk', 'date', 'text', 'from_user', 'to_user', 'category', 'subcategory') class StarSmallSerializer(serializers.ModelSerializer): class Meta: model = Star depth = 1 fields = ('pk', 'date', 'text', 'category', 'from_user') class StarSwaggerSerializer(serializers.ModelSerializer): class Meta: model = Star fields = ('pk', 'category', 'subcategory', 'text') class StarEmployeesSubcategoriesSerializer(serializers.Serializer): subcategory__pk = serializers.IntegerField() subcategory__name = serializers.CharField(max_length=100) num_stars = serializers.IntegerField() class StarTopEmployeeLists(serializers.Serializer): to_user__id = serializers.IntegerField() to_user__username = serializers.CharField(max_length=100) to_user__first_name = serializers.CharField(max_length=100) to_user__last_name = serializers.CharField(max_length=100) num_stars = serializers.IntegerField() Add EmployeeSimpleSerializer in order to avoid publish sensitive user data such passwords and other related fields
from .models import Star from employees.models import Employee from rest_framework import serializers class EmployeeSimpleSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ('pk', 'username', 'first_name', 'last_name') class StarSerializer(serializers.ModelSerializer): class Meta: model = Star fields = ('pk', 'date', 'text', 'from_user', 'to_user', 'category', 'subcategory') class StarSmallSerializer(serializers.ModelSerializer): from_user = EmployeeSimpleSerializer() class Meta: model = Star depth = 1 fields = ('pk', 'date', 'text', 'category', 'from_user') class StarSwaggerSerializer(serializers.ModelSerializer): class Meta: model = Star fields = ('pk', 'category', 'subcategory', 'text') class StarEmployeesSubcategoriesSerializer(serializers.Serializer): subcategory__pk = serializers.IntegerField() subcategory__name = serializers.CharField(max_length=100) num_stars = serializers.IntegerField() class StarTopEmployeeLists(serializers.Serializer): to_user__id = serializers.IntegerField() to_user__username = serializers.CharField(max_length=100) to_user__first_name = serializers.CharField(max_length=100) to_user__last_name = serializers.CharField(max_length=100) num_stars = serializers.IntegerField()
<commit_before>from .models import Star from rest_framework import serializers class StarSerializer(serializers.ModelSerializer): class Meta: model = Star fields = ('pk', 'date', 'text', 'from_user', 'to_user', 'category', 'subcategory') class StarSmallSerializer(serializers.ModelSerializer): class Meta: model = Star depth = 1 fields = ('pk', 'date', 'text', 'category', 'from_user') class StarSwaggerSerializer(serializers.ModelSerializer): class Meta: model = Star fields = ('pk', 'category', 'subcategory', 'text') class StarEmployeesSubcategoriesSerializer(serializers.Serializer): subcategory__pk = serializers.IntegerField() subcategory__name = serializers.CharField(max_length=100) num_stars = serializers.IntegerField() class StarTopEmployeeLists(serializers.Serializer): to_user__id = serializers.IntegerField() to_user__username = serializers.CharField(max_length=100) to_user__first_name = serializers.CharField(max_length=100) to_user__last_name = serializers.CharField(max_length=100) num_stars = serializers.IntegerField() <commit_msg>Add EmployeeSimpleSerializer in order to avoid publish sensitive user data such passwords and other related fields<commit_after>
from .models import Star from employees.models import Employee from rest_framework import serializers class EmployeeSimpleSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ('pk', 'username', 'first_name', 'last_name') class StarSerializer(serializers.ModelSerializer): class Meta: model = Star fields = ('pk', 'date', 'text', 'from_user', 'to_user', 'category', 'subcategory') class StarSmallSerializer(serializers.ModelSerializer): from_user = EmployeeSimpleSerializer() class Meta: model = Star depth = 1 fields = ('pk', 'date', 'text', 'category', 'from_user') class StarSwaggerSerializer(serializers.ModelSerializer): class Meta: model = Star fields = ('pk', 'category', 'subcategory', 'text') class StarEmployeesSubcategoriesSerializer(serializers.Serializer): subcategory__pk = serializers.IntegerField() subcategory__name = serializers.CharField(max_length=100) num_stars = serializers.IntegerField() class StarTopEmployeeLists(serializers.Serializer): to_user__id = serializers.IntegerField() to_user__username = serializers.CharField(max_length=100) to_user__first_name = serializers.CharField(max_length=100) to_user__last_name = serializers.CharField(max_length=100) num_stars = serializers.IntegerField()
from .models import Star from rest_framework import serializers class StarSerializer(serializers.ModelSerializer): class Meta: model = Star fields = ('pk', 'date', 'text', 'from_user', 'to_user', 'category', 'subcategory') class StarSmallSerializer(serializers.ModelSerializer): class Meta: model = Star depth = 1 fields = ('pk', 'date', 'text', 'category', 'from_user') class StarSwaggerSerializer(serializers.ModelSerializer): class Meta: model = Star fields = ('pk', 'category', 'subcategory', 'text') class StarEmployeesSubcategoriesSerializer(serializers.Serializer): subcategory__pk = serializers.IntegerField() subcategory__name = serializers.CharField(max_length=100) num_stars = serializers.IntegerField() class StarTopEmployeeLists(serializers.Serializer): to_user__id = serializers.IntegerField() to_user__username = serializers.CharField(max_length=100) to_user__first_name = serializers.CharField(max_length=100) to_user__last_name = serializers.CharField(max_length=100) num_stars = serializers.IntegerField() Add EmployeeSimpleSerializer in order to avoid publish sensitive user data such passwords and other related fieldsfrom .models import Star from employees.models import Employee from rest_framework import serializers class EmployeeSimpleSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ('pk', 'username', 'first_name', 'last_name') class StarSerializer(serializers.ModelSerializer): class Meta: model = Star fields = ('pk', 'date', 'text', 'from_user', 'to_user', 'category', 'subcategory') class StarSmallSerializer(serializers.ModelSerializer): from_user = EmployeeSimpleSerializer() class Meta: model = Star depth = 1 fields = ('pk', 'date', 'text', 'category', 'from_user') class StarSwaggerSerializer(serializers.ModelSerializer): class Meta: model = Star fields = ('pk', 'category', 'subcategory', 'text') class StarEmployeesSubcategoriesSerializer(serializers.Serializer): subcategory__pk = serializers.IntegerField() subcategory__name = serializers.CharField(max_length=100) num_stars = serializers.IntegerField() class StarTopEmployeeLists(serializers.Serializer): to_user__id = serializers.IntegerField() to_user__username = serializers.CharField(max_length=100) to_user__first_name = serializers.CharField(max_length=100) to_user__last_name = serializers.CharField(max_length=100) num_stars = serializers.IntegerField()
<commit_before>from .models import Star from rest_framework import serializers class StarSerializer(serializers.ModelSerializer): class Meta: model = Star fields = ('pk', 'date', 'text', 'from_user', 'to_user', 'category', 'subcategory') class StarSmallSerializer(serializers.ModelSerializer): class Meta: model = Star depth = 1 fields = ('pk', 'date', 'text', 'category', 'from_user') class StarSwaggerSerializer(serializers.ModelSerializer): class Meta: model = Star fields = ('pk', 'category', 'subcategory', 'text') class StarEmployeesSubcategoriesSerializer(serializers.Serializer): subcategory__pk = serializers.IntegerField() subcategory__name = serializers.CharField(max_length=100) num_stars = serializers.IntegerField() class StarTopEmployeeLists(serializers.Serializer): to_user__id = serializers.IntegerField() to_user__username = serializers.CharField(max_length=100) to_user__first_name = serializers.CharField(max_length=100) to_user__last_name = serializers.CharField(max_length=100) num_stars = serializers.IntegerField() <commit_msg>Add EmployeeSimpleSerializer in order to avoid publish sensitive user data such passwords and other related fields<commit_after>from .models import Star from employees.models import Employee from rest_framework import serializers class EmployeeSimpleSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ('pk', 'username', 'first_name', 'last_name') class StarSerializer(serializers.ModelSerializer): class Meta: model = Star fields = ('pk', 'date', 'text', 'from_user', 'to_user', 'category', 'subcategory') class StarSmallSerializer(serializers.ModelSerializer): from_user = EmployeeSimpleSerializer() class Meta: model = Star depth = 1 fields = ('pk', 'date', 'text', 'category', 'from_user') class StarSwaggerSerializer(serializers.ModelSerializer): class Meta: model = Star fields = ('pk', 'category', 'subcategory', 'text') class StarEmployeesSubcategoriesSerializer(serializers.Serializer): subcategory__pk = serializers.IntegerField() subcategory__name = serializers.CharField(max_length=100) num_stars = serializers.IntegerField() class StarTopEmployeeLists(serializers.Serializer): to_user__id = serializers.IntegerField() to_user__username = serializers.CharField(max_length=100) to_user__first_name = serializers.CharField(max_length=100) to_user__last_name = serializers.CharField(max_length=100) num_stars = serializers.IntegerField()
a84f382055cc5443819694bc3ec58895bcbf57ca
pskb_website/utils.py
pskb_website/utils.py
import re from unicodedata import normalize _punct_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.]+') # From http://flask.pocoo.org/snippets/5/ def slugify(text, delim=u'-'): """Generates an slightly worse ASCII-only slug.""" result = [] for word in _punct_re.split(text.lower()): word = normalize('NFKD', word).encode('ascii', 'ignore') if word: result.append(word) return unicode(delim.join(result))
import re from unicodedata import normalize _punct_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.:]+') # From http://flask.pocoo.org/snippets/5/ def slugify(text, delim=u'-'): """Generates an slightly worse ASCII-only slug.""" result = [] for word in _punct_re.split(text.lower()): word = normalize('NFKD', word).encode('ascii', 'ignore') if word: result.append(word) return unicode(delim.join(result))
Change ":" in titles to "-" for better SEO
Change ":" in titles to "-" for better SEO
Python
agpl-3.0
pluralsight/guides-cms,paulocheque/guides-cms,paulocheque/guides-cms,pluralsight/guides-cms,pluralsight/guides-cms,paulocheque/guides-cms
import re from unicodedata import normalize _punct_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.]+') # From http://flask.pocoo.org/snippets/5/ def slugify(text, delim=u'-'): """Generates an slightly worse ASCII-only slug.""" result = [] for word in _punct_re.split(text.lower()): word = normalize('NFKD', word).encode('ascii', 'ignore') if word: result.append(word) return unicode(delim.join(result)) Change ":" in titles to "-" for better SEO
import re from unicodedata import normalize _punct_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.:]+') # From http://flask.pocoo.org/snippets/5/ def slugify(text, delim=u'-'): """Generates an slightly worse ASCII-only slug.""" result = [] for word in _punct_re.split(text.lower()): word = normalize('NFKD', word).encode('ascii', 'ignore') if word: result.append(word) return unicode(delim.join(result))
<commit_before>import re from unicodedata import normalize _punct_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.]+') # From http://flask.pocoo.org/snippets/5/ def slugify(text, delim=u'-'): """Generates an slightly worse ASCII-only slug.""" result = [] for word in _punct_re.split(text.lower()): word = normalize('NFKD', word).encode('ascii', 'ignore') if word: result.append(word) return unicode(delim.join(result)) <commit_msg>Change ":" in titles to "-" for better SEO<commit_after>
import re from unicodedata import normalize _punct_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.:]+') # From http://flask.pocoo.org/snippets/5/ def slugify(text, delim=u'-'): """Generates an slightly worse ASCII-only slug.""" result = [] for word in _punct_re.split(text.lower()): word = normalize('NFKD', word).encode('ascii', 'ignore') if word: result.append(word) return unicode(delim.join(result))
import re from unicodedata import normalize _punct_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.]+') # From http://flask.pocoo.org/snippets/5/ def slugify(text, delim=u'-'): """Generates an slightly worse ASCII-only slug.""" result = [] for word in _punct_re.split(text.lower()): word = normalize('NFKD', word).encode('ascii', 'ignore') if word: result.append(word) return unicode(delim.join(result)) Change ":" in titles to "-" for better SEOimport re from unicodedata import normalize _punct_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.:]+') # From http://flask.pocoo.org/snippets/5/ def slugify(text, delim=u'-'): """Generates an slightly worse ASCII-only slug.""" result = [] for word in _punct_re.split(text.lower()): word = normalize('NFKD', word).encode('ascii', 'ignore') if word: result.append(word) return unicode(delim.join(result))
<commit_before>import re from unicodedata import normalize _punct_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.]+') # From http://flask.pocoo.org/snippets/5/ def slugify(text, delim=u'-'): """Generates an slightly worse ASCII-only slug.""" result = [] for word in _punct_re.split(text.lower()): word = normalize('NFKD', word).encode('ascii', 'ignore') if word: result.append(word) return unicode(delim.join(result)) <commit_msg>Change ":" in titles to "-" for better SEO<commit_after>import re from unicodedata import normalize _punct_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.:]+') # From http://flask.pocoo.org/snippets/5/ def slugify(text, delim=u'-'): """Generates an slightly worse ASCII-only slug.""" result = [] for word in _punct_re.split(text.lower()): word = normalize('NFKD', word).encode('ascii', 'ignore') if word: result.append(word) return unicode(delim.join(result))
dcb2c6d3472282c7dde4522e68cf45c27cb46b37
tests/accounts/test_models.py
tests/accounts/test_models.py
import pytest from components.accounts.factories import EditorFactory from components.accounts.models import Editor pytestmark = pytest.mark.django_db class TestEditors: def test_factory(self): factory = EditorFactory() assert isinstance(factory, Editor) assert 'dancer' in factory.username
import pytest from components.accounts.factories import EditorFactory from components.accounts.models import Editor pytestmark = pytest.mark.django_db class TestEditors: def test_factory(self): factory = EditorFactory() assert isinstance(factory, Editor) assert 'dancer' in factory.username def test_failing_creation(self): with pytest.raises(ValueError): Editor.objects.create_user(username='')
Add a silly failing test.
Add a silly failing test.
Python
apache-2.0
hello-base/web,hello-base/web,hello-base/web,hello-base/web
import pytest from components.accounts.factories import EditorFactory from components.accounts.models import Editor pytestmark = pytest.mark.django_db class TestEditors: def test_factory(self): factory = EditorFactory() assert isinstance(factory, Editor) assert 'dancer' in factory.username Add a silly failing test.
import pytest from components.accounts.factories import EditorFactory from components.accounts.models import Editor pytestmark = pytest.mark.django_db class TestEditors: def test_factory(self): factory = EditorFactory() assert isinstance(factory, Editor) assert 'dancer' in factory.username def test_failing_creation(self): with pytest.raises(ValueError): Editor.objects.create_user(username='')
<commit_before>import pytest from components.accounts.factories import EditorFactory from components.accounts.models import Editor pytestmark = pytest.mark.django_db class TestEditors: def test_factory(self): factory = EditorFactory() assert isinstance(factory, Editor) assert 'dancer' in factory.username <commit_msg>Add a silly failing test.<commit_after>
import pytest from components.accounts.factories import EditorFactory from components.accounts.models import Editor pytestmark = pytest.mark.django_db class TestEditors: def test_factory(self): factory = EditorFactory() assert isinstance(factory, Editor) assert 'dancer' in factory.username def test_failing_creation(self): with pytest.raises(ValueError): Editor.objects.create_user(username='')
import pytest from components.accounts.factories import EditorFactory from components.accounts.models import Editor pytestmark = pytest.mark.django_db class TestEditors: def test_factory(self): factory = EditorFactory() assert isinstance(factory, Editor) assert 'dancer' in factory.username Add a silly failing test.import pytest from components.accounts.factories import EditorFactory from components.accounts.models import Editor pytestmark = pytest.mark.django_db class TestEditors: def test_factory(self): factory = EditorFactory() assert isinstance(factory, Editor) assert 'dancer' in factory.username def test_failing_creation(self): with pytest.raises(ValueError): Editor.objects.create_user(username='')
<commit_before>import pytest from components.accounts.factories import EditorFactory from components.accounts.models import Editor pytestmark = pytest.mark.django_db class TestEditors: def test_factory(self): factory = EditorFactory() assert isinstance(factory, Editor) assert 'dancer' in factory.username <commit_msg>Add a silly failing test.<commit_after>import pytest from components.accounts.factories import EditorFactory from components.accounts.models import Editor pytestmark = pytest.mark.django_db class TestEditors: def test_factory(self): factory = EditorFactory() assert isinstance(factory, Editor) assert 'dancer' in factory.username def test_failing_creation(self): with pytest.raises(ValueError): Editor.objects.create_user(username='')
e6a991b91587f0ef081114b0d15390f682563071
antfarm/base.py
antfarm/base.py
import logging log = logging.getLogger(__name__) from .request import Request class App(object): ''' Base Application class. Create an instance of this, passing configuration options, and use the resulting instance as your WSGI application callable. application = App(root_view=myview) You can also sub-class this to provide the root_view. ''' def __init__(self, **opts): self.root_view = opts['root_view'] self.opts = opts def __call__(self, environ, start_response): request = Request(self, environ) response = self.root_view(request) start_response(response.status, response.build_headers()) return response
import logging log = logging.getLogger(__name__) from .request import Request class App(object): ''' Base Application class. Create an instance of this, passing configuration options, and use the resulting instance as your WSGI application callable. application = App(root_view=myview) You can also sub-class this to provide the root_view. ''' def __init__(self, **opts): for key, val in opts.items(): setattr(self, key, val) def __call__(self, environ, start_response): request = Request(self, environ) response = self.root_view(request) start_response(response.status, response.build_headers()) return response
Update the app with all supplied config arguments
Update the app with all supplied config arguments
Python
mit
funkybob/antfarm
import logging log = logging.getLogger(__name__) from .request import Request class App(object): ''' Base Application class. Create an instance of this, passing configuration options, and use the resulting instance as your WSGI application callable. application = App(root_view=myview) You can also sub-class this to provide the root_view. ''' def __init__(self, **opts): self.root_view = opts['root_view'] self.opts = opts def __call__(self, environ, start_response): request = Request(self, environ) response = self.root_view(request) start_response(response.status, response.build_headers()) return response Update the app with all supplied config arguments
import logging log = logging.getLogger(__name__) from .request import Request class App(object): ''' Base Application class. Create an instance of this, passing configuration options, and use the resulting instance as your WSGI application callable. application = App(root_view=myview) You can also sub-class this to provide the root_view. ''' def __init__(self, **opts): for key, val in opts.items(): setattr(self, key, val) def __call__(self, environ, start_response): request = Request(self, environ) response = self.root_view(request) start_response(response.status, response.build_headers()) return response
<commit_before> import logging log = logging.getLogger(__name__) from .request import Request class App(object): ''' Base Application class. Create an instance of this, passing configuration options, and use the resulting instance as your WSGI application callable. application = App(root_view=myview) You can also sub-class this to provide the root_view. ''' def __init__(self, **opts): self.root_view = opts['root_view'] self.opts = opts def __call__(self, environ, start_response): request = Request(self, environ) response = self.root_view(request) start_response(response.status, response.build_headers()) return response <commit_msg>Update the app with all supplied config arguments<commit_after>
import logging log = logging.getLogger(__name__) from .request import Request class App(object): ''' Base Application class. Create an instance of this, passing configuration options, and use the resulting instance as your WSGI application callable. application = App(root_view=myview) You can also sub-class this to provide the root_view. ''' def __init__(self, **opts): for key, val in opts.items(): setattr(self, key, val) def __call__(self, environ, start_response): request = Request(self, environ) response = self.root_view(request) start_response(response.status, response.build_headers()) return response
import logging log = logging.getLogger(__name__) from .request import Request class App(object): ''' Base Application class. Create an instance of this, passing configuration options, and use the resulting instance as your WSGI application callable. application = App(root_view=myview) You can also sub-class this to provide the root_view. ''' def __init__(self, **opts): self.root_view = opts['root_view'] self.opts = opts def __call__(self, environ, start_response): request = Request(self, environ) response = self.root_view(request) start_response(response.status, response.build_headers()) return response Update the app with all supplied config arguments import logging log = logging.getLogger(__name__) from .request import Request class App(object): ''' Base Application class. Create an instance of this, passing configuration options, and use the resulting instance as your WSGI application callable. application = App(root_view=myview) You can also sub-class this to provide the root_view. ''' def __init__(self, **opts): for key, val in opts.items(): setattr(self, key, val) def __call__(self, environ, start_response): request = Request(self, environ) response = self.root_view(request) start_response(response.status, response.build_headers()) return response
<commit_before> import logging log = logging.getLogger(__name__) from .request import Request class App(object): ''' Base Application class. Create an instance of this, passing configuration options, and use the resulting instance as your WSGI application callable. application = App(root_view=myview) You can also sub-class this to provide the root_view. ''' def __init__(self, **opts): self.root_view = opts['root_view'] self.opts = opts def __call__(self, environ, start_response): request = Request(self, environ) response = self.root_view(request) start_response(response.status, response.build_headers()) return response <commit_msg>Update the app with all supplied config arguments<commit_after> import logging log = logging.getLogger(__name__) from .request import Request class App(object): ''' Base Application class. Create an instance of this, passing configuration options, and use the resulting instance as your WSGI application callable. application = App(root_view=myview) You can also sub-class this to provide the root_view. ''' def __init__(self, **opts): for key, val in opts.items(): setattr(self, key, val) def __call__(self, environ, start_response): request = Request(self, environ) response = self.root_view(request) start_response(response.status, response.build_headers()) return response
fc39c6afa49a312413468dfdffcc2de94bb7d78e
tests/test_runner.py
tests/test_runner.py
import unittest from mo.runner import Variable class TestVariable(unittest.TestCase): def test_default(self): v = Variable('name', {'default': 'default'}) self.assertEqual(v.value, 'default') self.assertEqual(str(v), 'default') def test_value(self): v = Variable('name', {'default': 'default'}, 'value') self.assertEqual(v.value, 'value') self.assertEqual(str(v), 'value') def test_str(self): v = Variable('name', {'default': 'abc'}) self.assertEqual(str(v), v.value)
import unittest from mo.runner import Task, Variable class TestVariable(unittest.TestCase): def test_default(self): v = Variable('name', {'default': 'default'}) self.assertEqual(v.value, 'default') self.assertEqual(str(v), 'default') def test_value(self): v = Variable('name', {'default': 'default'}, 'value') self.assertEqual(v.value, 'value') self.assertEqual(str(v), 'value') def test_str(self): v = Variable('name', {'default': 'abc'}) self.assertEqual(str(v), v.value) class TestTask(unittest.TestCase): def test_variables(self): t = Task('name', {'description': '', 'command': '{{ v }}'}, {'v': 'variable'}) self.assertEqual(t.commands[0], 'variable')
Add some more tests for tasks
Add some more tests for tasks
Python
mit
thomasleese/mo
import unittest from mo.runner import Variable class TestVariable(unittest.TestCase): def test_default(self): v = Variable('name', {'default': 'default'}) self.assertEqual(v.value, 'default') self.assertEqual(str(v), 'default') def test_value(self): v = Variable('name', {'default': 'default'}, 'value') self.assertEqual(v.value, 'value') self.assertEqual(str(v), 'value') def test_str(self): v = Variable('name', {'default': 'abc'}) self.assertEqual(str(v), v.value) Add some more tests for tasks
import unittest from mo.runner import Task, Variable class TestVariable(unittest.TestCase): def test_default(self): v = Variable('name', {'default': 'default'}) self.assertEqual(v.value, 'default') self.assertEqual(str(v), 'default') def test_value(self): v = Variable('name', {'default': 'default'}, 'value') self.assertEqual(v.value, 'value') self.assertEqual(str(v), 'value') def test_str(self): v = Variable('name', {'default': 'abc'}) self.assertEqual(str(v), v.value) class TestTask(unittest.TestCase): def test_variables(self): t = Task('name', {'description': '', 'command': '{{ v }}'}, {'v': 'variable'}) self.assertEqual(t.commands[0], 'variable')
<commit_before>import unittest from mo.runner import Variable class TestVariable(unittest.TestCase): def test_default(self): v = Variable('name', {'default': 'default'}) self.assertEqual(v.value, 'default') self.assertEqual(str(v), 'default') def test_value(self): v = Variable('name', {'default': 'default'}, 'value') self.assertEqual(v.value, 'value') self.assertEqual(str(v), 'value') def test_str(self): v = Variable('name', {'default': 'abc'}) self.assertEqual(str(v), v.value) <commit_msg>Add some more tests for tasks<commit_after>
import unittest from mo.runner import Task, Variable class TestVariable(unittest.TestCase): def test_default(self): v = Variable('name', {'default': 'default'}) self.assertEqual(v.value, 'default') self.assertEqual(str(v), 'default') def test_value(self): v = Variable('name', {'default': 'default'}, 'value') self.assertEqual(v.value, 'value') self.assertEqual(str(v), 'value') def test_str(self): v = Variable('name', {'default': 'abc'}) self.assertEqual(str(v), v.value) class TestTask(unittest.TestCase): def test_variables(self): t = Task('name', {'description': '', 'command': '{{ v }}'}, {'v': 'variable'}) self.assertEqual(t.commands[0], 'variable')
import unittest from mo.runner import Variable class TestVariable(unittest.TestCase): def test_default(self): v = Variable('name', {'default': 'default'}) self.assertEqual(v.value, 'default') self.assertEqual(str(v), 'default') def test_value(self): v = Variable('name', {'default': 'default'}, 'value') self.assertEqual(v.value, 'value') self.assertEqual(str(v), 'value') def test_str(self): v = Variable('name', {'default': 'abc'}) self.assertEqual(str(v), v.value) Add some more tests for tasksimport unittest from mo.runner import Task, Variable class TestVariable(unittest.TestCase): def test_default(self): v = Variable('name', {'default': 'default'}) self.assertEqual(v.value, 'default') self.assertEqual(str(v), 'default') def test_value(self): v = Variable('name', {'default': 'default'}, 'value') self.assertEqual(v.value, 'value') self.assertEqual(str(v), 'value') def test_str(self): v = Variable('name', {'default': 'abc'}) self.assertEqual(str(v), v.value) class TestTask(unittest.TestCase): def test_variables(self): t = Task('name', {'description': '', 'command': '{{ v }}'}, {'v': 'variable'}) self.assertEqual(t.commands[0], 'variable')
<commit_before>import unittest from mo.runner import Variable class TestVariable(unittest.TestCase): def test_default(self): v = Variable('name', {'default': 'default'}) self.assertEqual(v.value, 'default') self.assertEqual(str(v), 'default') def test_value(self): v = Variable('name', {'default': 'default'}, 'value') self.assertEqual(v.value, 'value') self.assertEqual(str(v), 'value') def test_str(self): v = Variable('name', {'default': 'abc'}) self.assertEqual(str(v), v.value) <commit_msg>Add some more tests for tasks<commit_after>import unittest from mo.runner import Task, Variable class TestVariable(unittest.TestCase): def test_default(self): v = Variable('name', {'default': 'default'}) self.assertEqual(v.value, 'default') self.assertEqual(str(v), 'default') def test_value(self): v = Variable('name', {'default': 'default'}, 'value') self.assertEqual(v.value, 'value') self.assertEqual(str(v), 'value') def test_str(self): v = Variable('name', {'default': 'abc'}) self.assertEqual(str(v), v.value) class TestTask(unittest.TestCase): def test_variables(self): t = Task('name', {'description': '', 'command': '{{ v }}'}, {'v': 'variable'}) self.assertEqual(t.commands[0], 'variable')
fd36968474dbeba7e3d195e8b5ab12be7ff0eb87
src/misc/parse_tool_playbook_yaml.py
src/misc/parse_tool_playbook_yaml.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os import argparse import re import yaml def get_revision_number(yaml_content, tool_name): for tool in yaml_content['tools']: if tool["name"] == tool_name: if tool.has_key("revision"): print tool["revision"][0] def get_owner(yaml_content, tool_name): for tool in yaml_content['tools']: if tool["name"] == tool_name: print tool['owner'] if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--file', required=True) parser.add_argument('--tool_name', required=True) parser.add_argument('--tool_function', required=True) args = parser.parse_args() with open(args.file,'r') as yaml_file: yaml_content = yaml.load(yaml_file) functions = { 'get_revision_number': get_revision_number, 'get_owner': get_owner } functions[args.tool_function](yaml_content, args.tool_name)
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os import argparse import re import yaml def get_revision_number(yaml_content, tool_name): for tool in yaml_content['tools']: if tool["name"] == tool_name: if tool.has_key("revisions"): print tool["revisions"][0] def get_owner(yaml_content, tool_name): for tool in yaml_content['tools']: if tool["name"] == tool_name: print tool['owner'] if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--file', required=True) parser.add_argument('--tool_name', required=True) parser.add_argument('--tool_function', required=True) args = parser.parse_args() with open(args.file,'r') as yaml_file: yaml_content = yaml.load(yaml_file) functions = { 'get_revision_number': get_revision_number, 'get_owner': get_owner } functions[args.tool_function](yaml_content, args.tool_name)
Correct key for revision in tool playbook parser
Correct key for revision in tool playbook parser
Python
apache-2.0
ASaiM/framework,ASaiM/framework
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os import argparse import re import yaml def get_revision_number(yaml_content, tool_name): for tool in yaml_content['tools']: if tool["name"] == tool_name: if tool.has_key("revision"): print tool["revision"][0] def get_owner(yaml_content, tool_name): for tool in yaml_content['tools']: if tool["name"] == tool_name: print tool['owner'] if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--file', required=True) parser.add_argument('--tool_name', required=True) parser.add_argument('--tool_function', required=True) args = parser.parse_args() with open(args.file,'r') as yaml_file: yaml_content = yaml.load(yaml_file) functions = { 'get_revision_number': get_revision_number, 'get_owner': get_owner } functions[args.tool_function](yaml_content, args.tool_name)Correct key for revision in tool playbook parser
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os import argparse import re import yaml def get_revision_number(yaml_content, tool_name): for tool in yaml_content['tools']: if tool["name"] == tool_name: if tool.has_key("revisions"): print tool["revisions"][0] def get_owner(yaml_content, tool_name): for tool in yaml_content['tools']: if tool["name"] == tool_name: print tool['owner'] if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--file', required=True) parser.add_argument('--tool_name', required=True) parser.add_argument('--tool_function', required=True) args = parser.parse_args() with open(args.file,'r') as yaml_file: yaml_content = yaml.load(yaml_file) functions = { 'get_revision_number': get_revision_number, 'get_owner': get_owner } functions[args.tool_function](yaml_content, args.tool_name)
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os import argparse import re import yaml def get_revision_number(yaml_content, tool_name): for tool in yaml_content['tools']: if tool["name"] == tool_name: if tool.has_key("revision"): print tool["revision"][0] def get_owner(yaml_content, tool_name): for tool in yaml_content['tools']: if tool["name"] == tool_name: print tool['owner'] if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--file', required=True) parser.add_argument('--tool_name', required=True) parser.add_argument('--tool_function', required=True) args = parser.parse_args() with open(args.file,'r') as yaml_file: yaml_content = yaml.load(yaml_file) functions = { 'get_revision_number': get_revision_number, 'get_owner': get_owner } functions[args.tool_function](yaml_content, args.tool_name)<commit_msg>Correct key for revision in tool playbook parser<commit_after>
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os import argparse import re import yaml def get_revision_number(yaml_content, tool_name): for tool in yaml_content['tools']: if tool["name"] == tool_name: if tool.has_key("revisions"): print tool["revisions"][0] def get_owner(yaml_content, tool_name): for tool in yaml_content['tools']: if tool["name"] == tool_name: print tool['owner'] if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--file', required=True) parser.add_argument('--tool_name', required=True) parser.add_argument('--tool_function', required=True) args = parser.parse_args() with open(args.file,'r') as yaml_file: yaml_content = yaml.load(yaml_file) functions = { 'get_revision_number': get_revision_number, 'get_owner': get_owner } functions[args.tool_function](yaml_content, args.tool_name)
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os import argparse import re import yaml def get_revision_number(yaml_content, tool_name): for tool in yaml_content['tools']: if tool["name"] == tool_name: if tool.has_key("revision"): print tool["revision"][0] def get_owner(yaml_content, tool_name): for tool in yaml_content['tools']: if tool["name"] == tool_name: print tool['owner'] if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--file', required=True) parser.add_argument('--tool_name', required=True) parser.add_argument('--tool_function', required=True) args = parser.parse_args() with open(args.file,'r') as yaml_file: yaml_content = yaml.load(yaml_file) functions = { 'get_revision_number': get_revision_number, 'get_owner': get_owner } functions[args.tool_function](yaml_content, args.tool_name)Correct key for revision in tool playbook parser#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os import argparse import re import yaml def get_revision_number(yaml_content, tool_name): for tool in yaml_content['tools']: if tool["name"] == tool_name: if tool.has_key("revisions"): print tool["revisions"][0] def get_owner(yaml_content, tool_name): for tool in yaml_content['tools']: if tool["name"] == tool_name: print tool['owner'] if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--file', required=True) parser.add_argument('--tool_name', required=True) parser.add_argument('--tool_function', required=True) args = parser.parse_args() with open(args.file,'r') as yaml_file: yaml_content = yaml.load(yaml_file) functions = { 'get_revision_number': get_revision_number, 'get_owner': get_owner } functions[args.tool_function](yaml_content, args.tool_name)
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os import argparse import re import yaml def get_revision_number(yaml_content, tool_name): for tool in yaml_content['tools']: if tool["name"] == tool_name: if tool.has_key("revision"): print tool["revision"][0] def get_owner(yaml_content, tool_name): for tool in yaml_content['tools']: if tool["name"] == tool_name: print tool['owner'] if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--file', required=True) parser.add_argument('--tool_name', required=True) parser.add_argument('--tool_function', required=True) args = parser.parse_args() with open(args.file,'r') as yaml_file: yaml_content = yaml.load(yaml_file) functions = { 'get_revision_number': get_revision_number, 'get_owner': get_owner } functions[args.tool_function](yaml_content, args.tool_name)<commit_msg>Correct key for revision in tool playbook parser<commit_after>#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os import argparse import re import yaml def get_revision_number(yaml_content, tool_name): for tool in yaml_content['tools']: if tool["name"] == tool_name: if tool.has_key("revisions"): print tool["revisions"][0] def get_owner(yaml_content, tool_name): for tool in yaml_content['tools']: if tool["name"] == tool_name: print tool['owner'] if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--file', required=True) parser.add_argument('--tool_name', required=True) parser.add_argument('--tool_function', required=True) args = parser.parse_args() with open(args.file,'r') as yaml_file: yaml_content = yaml.load(yaml_file) functions = { 'get_revision_number': get_revision_number, 'get_owner': get_owner } functions[args.tool_function](yaml_content, args.tool_name)
5bb8d24d90b7e6fab72f4f4988ea3055d3250b7e
src/nodeconductor_assembly_waldur/invoices/serializers.py
src/nodeconductor_assembly_waldur/invoices/serializers.py
from rest_framework import serializers from . import models class OpenStackItemSerializer(serializers.HyperlinkedModelSerializer): class Meta(object): model = models.OpenStackItem fields = ('package_details', 'package', 'price', 'start', 'end') extra_kwargs = { 'package': {'lookup_field': 'uuid', 'view_name': 'openstack-package-detail'}, } def to_representation(self, instance): instance.package_details['name'] = instance.name return super(OpenStackItemSerializer, self).to_representation(instance) class InvoiceSerializer(serializers.HyperlinkedModelSerializer): total = serializers.DecimalField(max_digits=15, decimal_places=7) openstack_items = OpenStackItemSerializer(many=True) class Meta(object): model = models.Invoice fields = ( 'url', 'uuid', 'customer', 'total', 'openstack_items', 'state', 'year', 'month' ) view_name = 'invoice-detail' extra_kwargs = { 'url': {'lookup_field': 'uuid'}, 'customer': {'lookup_field': 'uuid'}, }
from rest_framework import serializers from . import models class OpenStackItemSerializer(serializers.HyperlinkedModelSerializer): class Meta(object): model = models.OpenStackItem fields = ('package_details', 'package', 'price', 'start', 'end') extra_kwargs = { 'package': {'lookup_field': 'uuid', 'view_name': 'openstack-package-detail'}, } def to_representation(self, instance): instance.package_details['name'] = instance.name return super(OpenStackItemSerializer, self).to_representation(instance) class InvoiceSerializer(serializers.HyperlinkedModelSerializer): total = serializers.DecimalField(max_digits=15, decimal_places=7) openstack_items = OpenStackItemSerializer(many=True) class Meta(object): model = models.Invoice fields = ( 'url', 'uuid', 'customer', 'total', 'openstack_items', 'state', 'year', 'month' ) extra_kwargs = { 'url': {'lookup_field': 'uuid'}, 'customer': {'lookup_field': 'uuid'}, }
Remove redundant view_name variable in serializer
Remove redundant view_name variable in serializer - WAL-109
Python
mit
opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind
from rest_framework import serializers from . import models class OpenStackItemSerializer(serializers.HyperlinkedModelSerializer): class Meta(object): model = models.OpenStackItem fields = ('package_details', 'package', 'price', 'start', 'end') extra_kwargs = { 'package': {'lookup_field': 'uuid', 'view_name': 'openstack-package-detail'}, } def to_representation(self, instance): instance.package_details['name'] = instance.name return super(OpenStackItemSerializer, self).to_representation(instance) class InvoiceSerializer(serializers.HyperlinkedModelSerializer): total = serializers.DecimalField(max_digits=15, decimal_places=7) openstack_items = OpenStackItemSerializer(many=True) class Meta(object): model = models.Invoice fields = ( 'url', 'uuid', 'customer', 'total', 'openstack_items', 'state', 'year', 'month' ) view_name = 'invoice-detail' extra_kwargs = { 'url': {'lookup_field': 'uuid'}, 'customer': {'lookup_field': 'uuid'}, } Remove redundant view_name variable in serializer - WAL-109
from rest_framework import serializers from . import models class OpenStackItemSerializer(serializers.HyperlinkedModelSerializer): class Meta(object): model = models.OpenStackItem fields = ('package_details', 'package', 'price', 'start', 'end') extra_kwargs = { 'package': {'lookup_field': 'uuid', 'view_name': 'openstack-package-detail'}, } def to_representation(self, instance): instance.package_details['name'] = instance.name return super(OpenStackItemSerializer, self).to_representation(instance) class InvoiceSerializer(serializers.HyperlinkedModelSerializer): total = serializers.DecimalField(max_digits=15, decimal_places=7) openstack_items = OpenStackItemSerializer(many=True) class Meta(object): model = models.Invoice fields = ( 'url', 'uuid', 'customer', 'total', 'openstack_items', 'state', 'year', 'month' ) extra_kwargs = { 'url': {'lookup_field': 'uuid'}, 'customer': {'lookup_field': 'uuid'}, }
<commit_before>from rest_framework import serializers from . import models class OpenStackItemSerializer(serializers.HyperlinkedModelSerializer): class Meta(object): model = models.OpenStackItem fields = ('package_details', 'package', 'price', 'start', 'end') extra_kwargs = { 'package': {'lookup_field': 'uuid', 'view_name': 'openstack-package-detail'}, } def to_representation(self, instance): instance.package_details['name'] = instance.name return super(OpenStackItemSerializer, self).to_representation(instance) class InvoiceSerializer(serializers.HyperlinkedModelSerializer): total = serializers.DecimalField(max_digits=15, decimal_places=7) openstack_items = OpenStackItemSerializer(many=True) class Meta(object): model = models.Invoice fields = ( 'url', 'uuid', 'customer', 'total', 'openstack_items', 'state', 'year', 'month' ) view_name = 'invoice-detail' extra_kwargs = { 'url': {'lookup_field': 'uuid'}, 'customer': {'lookup_field': 'uuid'}, } <commit_msg>Remove redundant view_name variable in serializer - WAL-109<commit_after>
from rest_framework import serializers from . import models class OpenStackItemSerializer(serializers.HyperlinkedModelSerializer): class Meta(object): model = models.OpenStackItem fields = ('package_details', 'package', 'price', 'start', 'end') extra_kwargs = { 'package': {'lookup_field': 'uuid', 'view_name': 'openstack-package-detail'}, } def to_representation(self, instance): instance.package_details['name'] = instance.name return super(OpenStackItemSerializer, self).to_representation(instance) class InvoiceSerializer(serializers.HyperlinkedModelSerializer): total = serializers.DecimalField(max_digits=15, decimal_places=7) openstack_items = OpenStackItemSerializer(many=True) class Meta(object): model = models.Invoice fields = ( 'url', 'uuid', 'customer', 'total', 'openstack_items', 'state', 'year', 'month' ) extra_kwargs = { 'url': {'lookup_field': 'uuid'}, 'customer': {'lookup_field': 'uuid'}, }
from rest_framework import serializers from . import models class OpenStackItemSerializer(serializers.HyperlinkedModelSerializer): class Meta(object): model = models.OpenStackItem fields = ('package_details', 'package', 'price', 'start', 'end') extra_kwargs = { 'package': {'lookup_field': 'uuid', 'view_name': 'openstack-package-detail'}, } def to_representation(self, instance): instance.package_details['name'] = instance.name return super(OpenStackItemSerializer, self).to_representation(instance) class InvoiceSerializer(serializers.HyperlinkedModelSerializer): total = serializers.DecimalField(max_digits=15, decimal_places=7) openstack_items = OpenStackItemSerializer(many=True) class Meta(object): model = models.Invoice fields = ( 'url', 'uuid', 'customer', 'total', 'openstack_items', 'state', 'year', 'month' ) view_name = 'invoice-detail' extra_kwargs = { 'url': {'lookup_field': 'uuid'}, 'customer': {'lookup_field': 'uuid'}, } Remove redundant view_name variable in serializer - WAL-109from rest_framework import serializers from . import models class OpenStackItemSerializer(serializers.HyperlinkedModelSerializer): class Meta(object): model = models.OpenStackItem fields = ('package_details', 'package', 'price', 'start', 'end') extra_kwargs = { 'package': {'lookup_field': 'uuid', 'view_name': 'openstack-package-detail'}, } def to_representation(self, instance): instance.package_details['name'] = instance.name return super(OpenStackItemSerializer, self).to_representation(instance) class InvoiceSerializer(serializers.HyperlinkedModelSerializer): total = serializers.DecimalField(max_digits=15, decimal_places=7) openstack_items = OpenStackItemSerializer(many=True) class Meta(object): model = models.Invoice fields = ( 'url', 'uuid', 'customer', 'total', 'openstack_items', 'state', 'year', 'month' ) extra_kwargs = { 'url': {'lookup_field': 'uuid'}, 'customer': {'lookup_field': 'uuid'}, }
<commit_before>from rest_framework import serializers from . import models class OpenStackItemSerializer(serializers.HyperlinkedModelSerializer): class Meta(object): model = models.OpenStackItem fields = ('package_details', 'package', 'price', 'start', 'end') extra_kwargs = { 'package': {'lookup_field': 'uuid', 'view_name': 'openstack-package-detail'}, } def to_representation(self, instance): instance.package_details['name'] = instance.name return super(OpenStackItemSerializer, self).to_representation(instance) class InvoiceSerializer(serializers.HyperlinkedModelSerializer): total = serializers.DecimalField(max_digits=15, decimal_places=7) openstack_items = OpenStackItemSerializer(many=True) class Meta(object): model = models.Invoice fields = ( 'url', 'uuid', 'customer', 'total', 'openstack_items', 'state', 'year', 'month' ) view_name = 'invoice-detail' extra_kwargs = { 'url': {'lookup_field': 'uuid'}, 'customer': {'lookup_field': 'uuid'}, } <commit_msg>Remove redundant view_name variable in serializer - WAL-109<commit_after>from rest_framework import serializers from . import models class OpenStackItemSerializer(serializers.HyperlinkedModelSerializer): class Meta(object): model = models.OpenStackItem fields = ('package_details', 'package', 'price', 'start', 'end') extra_kwargs = { 'package': {'lookup_field': 'uuid', 'view_name': 'openstack-package-detail'}, } def to_representation(self, instance): instance.package_details['name'] = instance.name return super(OpenStackItemSerializer, self).to_representation(instance) class InvoiceSerializer(serializers.HyperlinkedModelSerializer): total = serializers.DecimalField(max_digits=15, decimal_places=7) openstack_items = OpenStackItemSerializer(many=True) class Meta(object): model = models.Invoice fields = ( 'url', 'uuid', 'customer', 'total', 'openstack_items', 'state', 'year', 'month' ) extra_kwargs = { 'url': {'lookup_field': 'uuid'}, 'customer': {'lookup_field': 'uuid'}, }
608fc063e5b153b99b79cab2248b586db3ebda1f
tests/test_pybind11.py
tests/test_pybind11.py
import sys import os d = os.path.dirname(__file__) sys.path.append(os.path.join(d, '../')) import jtrace # para = jtrace.Paraboloid(0.0, 0.0) # print(para.A) # print(para.B) # vec = jtrace.Vec3() # print(vec.MagnitudeSquared()) # vec = jtrace.Vec3(1, 2, 3) # print(vec.MagnitudeSquared()) # unitvec = vec.UnitVec3() # print(unitvec.Magnitude()) # ray = jtrace.Ray(jtrace.Vec3(), jtrace.Vec3(0,0,1)) # print(ray) # print(ray(1.0)) # print(ray(1.3)) ray = jtrace.Ray(jtrace.Vec3(0,0.5,0), jtrace.Vec3(0,0,1)) para = jtrace.Paraboloid(1, 1) print(para.intersect(ray)) asphere = jtrace.Asphere(1.0, -1.0, [0.0, 0.001], 0.0) print(asphere) print(asphere.alpha) isec = asphere.intersect(ray) print(isec) print(asphere(isec.point.x, isec.point.y)) print(ray(isec.t))
import sys import os import jtrace # para = jtrace.Paraboloid(0.0, 0.0) # print(para.A) # print(para.B) # vec = jtrace.Vec3() # print(vec.MagnitudeSquared()) # vec = jtrace.Vec3(1, 2, 3) # print(vec.MagnitudeSquared()) # unitvec = vec.UnitVec3() # print(unitvec.Magnitude()) # ray = jtrace.Ray(jtrace.Vec3(), jtrace.Vec3(0,0,1)) # print(ray) # print(ray(1.0)) # print(ray(1.3)) ray = jtrace.Ray(jtrace.Vec3(0,0.5,0), jtrace.Vec3(0,0,1)) para = jtrace.Paraboloid(1, 1) print(para.intersect(ray)) asphere = jtrace.Asphere(1.0, -1.0, [0.0, 0.001], 0.0) print(asphere) print(asphere.alpha) isec = asphere.intersect(ray) print(isec) print(asphere(isec.point.x, isec.point.y)) print(ray(isec.t))
Remove sys.path hacking from test
Remove sys.path hacking from test
Python
bsd-2-clause
jmeyers314/batoid,jmeyers314/jtrace,jmeyers314/batoid,jmeyers314/jtrace,jmeyers314/jtrace
import sys import os d = os.path.dirname(__file__) sys.path.append(os.path.join(d, '../')) import jtrace # para = jtrace.Paraboloid(0.0, 0.0) # print(para.A) # print(para.B) # vec = jtrace.Vec3() # print(vec.MagnitudeSquared()) # vec = jtrace.Vec3(1, 2, 3) # print(vec.MagnitudeSquared()) # unitvec = vec.UnitVec3() # print(unitvec.Magnitude()) # ray = jtrace.Ray(jtrace.Vec3(), jtrace.Vec3(0,0,1)) # print(ray) # print(ray(1.0)) # print(ray(1.3)) ray = jtrace.Ray(jtrace.Vec3(0,0.5,0), jtrace.Vec3(0,0,1)) para = jtrace.Paraboloid(1, 1) print(para.intersect(ray)) asphere = jtrace.Asphere(1.0, -1.0, [0.0, 0.001], 0.0) print(asphere) print(asphere.alpha) isec = asphere.intersect(ray) print(isec) print(asphere(isec.point.x, isec.point.y)) print(ray(isec.t)) Remove sys.path hacking from test
import sys import os import jtrace # para = jtrace.Paraboloid(0.0, 0.0) # print(para.A) # print(para.B) # vec = jtrace.Vec3() # print(vec.MagnitudeSquared()) # vec = jtrace.Vec3(1, 2, 3) # print(vec.MagnitudeSquared()) # unitvec = vec.UnitVec3() # print(unitvec.Magnitude()) # ray = jtrace.Ray(jtrace.Vec3(), jtrace.Vec3(0,0,1)) # print(ray) # print(ray(1.0)) # print(ray(1.3)) ray = jtrace.Ray(jtrace.Vec3(0,0.5,0), jtrace.Vec3(0,0,1)) para = jtrace.Paraboloid(1, 1) print(para.intersect(ray)) asphere = jtrace.Asphere(1.0, -1.0, [0.0, 0.001], 0.0) print(asphere) print(asphere.alpha) isec = asphere.intersect(ray) print(isec) print(asphere(isec.point.x, isec.point.y)) print(ray(isec.t))
<commit_before>import sys import os d = os.path.dirname(__file__) sys.path.append(os.path.join(d, '../')) import jtrace # para = jtrace.Paraboloid(0.0, 0.0) # print(para.A) # print(para.B) # vec = jtrace.Vec3() # print(vec.MagnitudeSquared()) # vec = jtrace.Vec3(1, 2, 3) # print(vec.MagnitudeSquared()) # unitvec = vec.UnitVec3() # print(unitvec.Magnitude()) # ray = jtrace.Ray(jtrace.Vec3(), jtrace.Vec3(0,0,1)) # print(ray) # print(ray(1.0)) # print(ray(1.3)) ray = jtrace.Ray(jtrace.Vec3(0,0.5,0), jtrace.Vec3(0,0,1)) para = jtrace.Paraboloid(1, 1) print(para.intersect(ray)) asphere = jtrace.Asphere(1.0, -1.0, [0.0, 0.001], 0.0) print(asphere) print(asphere.alpha) isec = asphere.intersect(ray) print(isec) print(asphere(isec.point.x, isec.point.y)) print(ray(isec.t)) <commit_msg>Remove sys.path hacking from test<commit_after>
import sys import os import jtrace # para = jtrace.Paraboloid(0.0, 0.0) # print(para.A) # print(para.B) # vec = jtrace.Vec3() # print(vec.MagnitudeSquared()) # vec = jtrace.Vec3(1, 2, 3) # print(vec.MagnitudeSquared()) # unitvec = vec.UnitVec3() # print(unitvec.Magnitude()) # ray = jtrace.Ray(jtrace.Vec3(), jtrace.Vec3(0,0,1)) # print(ray) # print(ray(1.0)) # print(ray(1.3)) ray = jtrace.Ray(jtrace.Vec3(0,0.5,0), jtrace.Vec3(0,0,1)) para = jtrace.Paraboloid(1, 1) print(para.intersect(ray)) asphere = jtrace.Asphere(1.0, -1.0, [0.0, 0.001], 0.0) print(asphere) print(asphere.alpha) isec = asphere.intersect(ray) print(isec) print(asphere(isec.point.x, isec.point.y)) print(ray(isec.t))
import sys import os d = os.path.dirname(__file__) sys.path.append(os.path.join(d, '../')) import jtrace # para = jtrace.Paraboloid(0.0, 0.0) # print(para.A) # print(para.B) # vec = jtrace.Vec3() # print(vec.MagnitudeSquared()) # vec = jtrace.Vec3(1, 2, 3) # print(vec.MagnitudeSquared()) # unitvec = vec.UnitVec3() # print(unitvec.Magnitude()) # ray = jtrace.Ray(jtrace.Vec3(), jtrace.Vec3(0,0,1)) # print(ray) # print(ray(1.0)) # print(ray(1.3)) ray = jtrace.Ray(jtrace.Vec3(0,0.5,0), jtrace.Vec3(0,0,1)) para = jtrace.Paraboloid(1, 1) print(para.intersect(ray)) asphere = jtrace.Asphere(1.0, -1.0, [0.0, 0.001], 0.0) print(asphere) print(asphere.alpha) isec = asphere.intersect(ray) print(isec) print(asphere(isec.point.x, isec.point.y)) print(ray(isec.t)) Remove sys.path hacking from testimport sys import os import jtrace # para = jtrace.Paraboloid(0.0, 0.0) # print(para.A) # print(para.B) # vec = jtrace.Vec3() # print(vec.MagnitudeSquared()) # vec = jtrace.Vec3(1, 2, 3) # print(vec.MagnitudeSquared()) # unitvec = vec.UnitVec3() # print(unitvec.Magnitude()) # ray = jtrace.Ray(jtrace.Vec3(), jtrace.Vec3(0,0,1)) # print(ray) # print(ray(1.0)) # print(ray(1.3)) ray = jtrace.Ray(jtrace.Vec3(0,0.5,0), jtrace.Vec3(0,0,1)) para = jtrace.Paraboloid(1, 1) print(para.intersect(ray)) asphere = jtrace.Asphere(1.0, -1.0, [0.0, 0.001], 0.0) print(asphere) print(asphere.alpha) isec = asphere.intersect(ray) print(isec) print(asphere(isec.point.x, isec.point.y)) print(ray(isec.t))
<commit_before>import sys import os d = os.path.dirname(__file__) sys.path.append(os.path.join(d, '../')) import jtrace # para = jtrace.Paraboloid(0.0, 0.0) # print(para.A) # print(para.B) # vec = jtrace.Vec3() # print(vec.MagnitudeSquared()) # vec = jtrace.Vec3(1, 2, 3) # print(vec.MagnitudeSquared()) # unitvec = vec.UnitVec3() # print(unitvec.Magnitude()) # ray = jtrace.Ray(jtrace.Vec3(), jtrace.Vec3(0,0,1)) # print(ray) # print(ray(1.0)) # print(ray(1.3)) ray = jtrace.Ray(jtrace.Vec3(0,0.5,0), jtrace.Vec3(0,0,1)) para = jtrace.Paraboloid(1, 1) print(para.intersect(ray)) asphere = jtrace.Asphere(1.0, -1.0, [0.0, 0.001], 0.0) print(asphere) print(asphere.alpha) isec = asphere.intersect(ray) print(isec) print(asphere(isec.point.x, isec.point.y)) print(ray(isec.t)) <commit_msg>Remove sys.path hacking from test<commit_after>import sys import os import jtrace # para = jtrace.Paraboloid(0.0, 0.0) # print(para.A) # print(para.B) # vec = jtrace.Vec3() # print(vec.MagnitudeSquared()) # vec = jtrace.Vec3(1, 2, 3) # print(vec.MagnitudeSquared()) # unitvec = vec.UnitVec3() # print(unitvec.Magnitude()) # ray = jtrace.Ray(jtrace.Vec3(), jtrace.Vec3(0,0,1)) # print(ray) # print(ray(1.0)) # print(ray(1.3)) ray = jtrace.Ray(jtrace.Vec3(0,0.5,0), jtrace.Vec3(0,0,1)) para = jtrace.Paraboloid(1, 1) print(para.intersect(ray)) asphere = jtrace.Asphere(1.0, -1.0, [0.0, 0.001], 0.0) print(asphere) print(asphere.alpha) isec = asphere.intersect(ray) print(isec) print(asphere(isec.point.x, isec.point.y)) print(ray(isec.t))
bad9909ac1149063cf97fc03787c203a17308552
bqueryd/node.py
bqueryd/node.py
#!/srv/python/venv/bin/ipython -i import bqueryd import os import sys import logging import ConfigParser config = ConfigParser.RawConfigParser() config.read(['/etc/bqueryd.cfg', os.path.expanduser('~/.bqueryd.cfg')]) redis_url=config.get('Main', 'redis_url') if __name__ == '__main__': if '-v' in sys.argv: loglevel = logging.DEBUG else: loglevel = logging.INFO if 'controller' in sys.argv: bqueryd.ControllerNode(redis_url=redis_url, loglevel=loglevel).go() elif 'worker' in sys.argv: bqueryd.WorkerNode(redis_url=redis_url, loglevel=loglevel).go() else: if len(sys.argv) > 1 and sys.argv[1].startswith('tcp:'): a = bqueryd.RPC(address=sys.argv[1], redis_url=redis_url, loglevel=loglevel) else: a = bqueryd.RPC(redis_url=redis_url, loglevel=loglevel) sys.stderr.write('Run this script with python -i , and then you will have a variable named "a" as a connection.\n')
#!/srv/python/venv/bin/ipython -i import bqueryd import os import sys import logging import ConfigParser config = ConfigParser.RawConfigParser() config.read(['/etc/bqueryd.cfg', os.path.expanduser('~/.bqueryd.cfg')]) redis_url=config.get('Main', 'redis_url') if __name__ == '__main__': if '-v' in sys.argv: loglevel = logging.DEBUG else: loglevel = logging.INFO if 'controller' in sys.argv: bqueryd.ControllerNode(redis_url=redis_url, loglevel=loglevel).go() elif 'worker' in sys.argv: bqueryd.WorkerNode(redis_url=redis_url, loglevel=loglevel).go() else: if len(sys.argv) > 1 and sys.argv[1].startswith('tcp:'): rpc = bqueryd.RPC(address=sys.argv[1], redis_url=redis_url, loglevel=loglevel) else: rpc = bqueryd.RPC(redis_url=redis_url, loglevel=loglevel) sys.stderr.write('Run this script with python -i , and then you will have a variable named "rpc" as a connection.\n')
Use var named "rpc" and not "a"
Use var named "rpc" and not "a"
Python
bsd-3-clause
visualfabriq/bqueryd
#!/srv/python/venv/bin/ipython -i import bqueryd import os import sys import logging import ConfigParser config = ConfigParser.RawConfigParser() config.read(['/etc/bqueryd.cfg', os.path.expanduser('~/.bqueryd.cfg')]) redis_url=config.get('Main', 'redis_url') if __name__ == '__main__': if '-v' in sys.argv: loglevel = logging.DEBUG else: loglevel = logging.INFO if 'controller' in sys.argv: bqueryd.ControllerNode(redis_url=redis_url, loglevel=loglevel).go() elif 'worker' in sys.argv: bqueryd.WorkerNode(redis_url=redis_url, loglevel=loglevel).go() else: if len(sys.argv) > 1 and sys.argv[1].startswith('tcp:'): a = bqueryd.RPC(address=sys.argv[1], redis_url=redis_url, loglevel=loglevel) else: a = bqueryd.RPC(redis_url=redis_url, loglevel=loglevel) sys.stderr.write('Run this script with python -i , and then you will have a variable named "a" as a connection.\n') Use var named "rpc" and not "a"
#!/srv/python/venv/bin/ipython -i import bqueryd import os import sys import logging import ConfigParser config = ConfigParser.RawConfigParser() config.read(['/etc/bqueryd.cfg', os.path.expanduser('~/.bqueryd.cfg')]) redis_url=config.get('Main', 'redis_url') if __name__ == '__main__': if '-v' in sys.argv: loglevel = logging.DEBUG else: loglevel = logging.INFO if 'controller' in sys.argv: bqueryd.ControllerNode(redis_url=redis_url, loglevel=loglevel).go() elif 'worker' in sys.argv: bqueryd.WorkerNode(redis_url=redis_url, loglevel=loglevel).go() else: if len(sys.argv) > 1 and sys.argv[1].startswith('tcp:'): rpc = bqueryd.RPC(address=sys.argv[1], redis_url=redis_url, loglevel=loglevel) else: rpc = bqueryd.RPC(redis_url=redis_url, loglevel=loglevel) sys.stderr.write('Run this script with python -i , and then you will have a variable named "rpc" as a connection.\n')
<commit_before>#!/srv/python/venv/bin/ipython -i import bqueryd import os import sys import logging import ConfigParser config = ConfigParser.RawConfigParser() config.read(['/etc/bqueryd.cfg', os.path.expanduser('~/.bqueryd.cfg')]) redis_url=config.get('Main', 'redis_url') if __name__ == '__main__': if '-v' in sys.argv: loglevel = logging.DEBUG else: loglevel = logging.INFO if 'controller' in sys.argv: bqueryd.ControllerNode(redis_url=redis_url, loglevel=loglevel).go() elif 'worker' in sys.argv: bqueryd.WorkerNode(redis_url=redis_url, loglevel=loglevel).go() else: if len(sys.argv) > 1 and sys.argv[1].startswith('tcp:'): a = bqueryd.RPC(address=sys.argv[1], redis_url=redis_url, loglevel=loglevel) else: a = bqueryd.RPC(redis_url=redis_url, loglevel=loglevel) sys.stderr.write('Run this script with python -i , and then you will have a variable named "a" as a connection.\n') <commit_msg>Use var named "rpc" and not "a"<commit_after>
#!/srv/python/venv/bin/ipython -i import bqueryd import os import sys import logging import ConfigParser config = ConfigParser.RawConfigParser() config.read(['/etc/bqueryd.cfg', os.path.expanduser('~/.bqueryd.cfg')]) redis_url=config.get('Main', 'redis_url') if __name__ == '__main__': if '-v' in sys.argv: loglevel = logging.DEBUG else: loglevel = logging.INFO if 'controller' in sys.argv: bqueryd.ControllerNode(redis_url=redis_url, loglevel=loglevel).go() elif 'worker' in sys.argv: bqueryd.WorkerNode(redis_url=redis_url, loglevel=loglevel).go() else: if len(sys.argv) > 1 and sys.argv[1].startswith('tcp:'): rpc = bqueryd.RPC(address=sys.argv[1], redis_url=redis_url, loglevel=loglevel) else: rpc = bqueryd.RPC(redis_url=redis_url, loglevel=loglevel) sys.stderr.write('Run this script with python -i , and then you will have a variable named "rpc" as a connection.\n')
#!/srv/python/venv/bin/ipython -i import bqueryd import os import sys import logging import ConfigParser config = ConfigParser.RawConfigParser() config.read(['/etc/bqueryd.cfg', os.path.expanduser('~/.bqueryd.cfg')]) redis_url=config.get('Main', 'redis_url') if __name__ == '__main__': if '-v' in sys.argv: loglevel = logging.DEBUG else: loglevel = logging.INFO if 'controller' in sys.argv: bqueryd.ControllerNode(redis_url=redis_url, loglevel=loglevel).go() elif 'worker' in sys.argv: bqueryd.WorkerNode(redis_url=redis_url, loglevel=loglevel).go() else: if len(sys.argv) > 1 and sys.argv[1].startswith('tcp:'): a = bqueryd.RPC(address=sys.argv[1], redis_url=redis_url, loglevel=loglevel) else: a = bqueryd.RPC(redis_url=redis_url, loglevel=loglevel) sys.stderr.write('Run this script with python -i , and then you will have a variable named "a" as a connection.\n') Use var named "rpc" and not "a"#!/srv/python/venv/bin/ipython -i import bqueryd import os import sys import logging import ConfigParser config = ConfigParser.RawConfigParser() config.read(['/etc/bqueryd.cfg', os.path.expanduser('~/.bqueryd.cfg')]) redis_url=config.get('Main', 'redis_url') if __name__ == '__main__': if '-v' in sys.argv: loglevel = logging.DEBUG else: loglevel = logging.INFO if 'controller' in sys.argv: bqueryd.ControllerNode(redis_url=redis_url, loglevel=loglevel).go() elif 'worker' in sys.argv: bqueryd.WorkerNode(redis_url=redis_url, loglevel=loglevel).go() else: if len(sys.argv) > 1 and sys.argv[1].startswith('tcp:'): rpc = bqueryd.RPC(address=sys.argv[1], redis_url=redis_url, loglevel=loglevel) else: rpc = bqueryd.RPC(redis_url=redis_url, loglevel=loglevel) sys.stderr.write('Run this script with python -i , and then you will have a variable named "rpc" as a connection.\n')
<commit_before>#!/srv/python/venv/bin/ipython -i import bqueryd import os import sys import logging import ConfigParser config = ConfigParser.RawConfigParser() config.read(['/etc/bqueryd.cfg', os.path.expanduser('~/.bqueryd.cfg')]) redis_url=config.get('Main', 'redis_url') if __name__ == '__main__': if '-v' in sys.argv: loglevel = logging.DEBUG else: loglevel = logging.INFO if 'controller' in sys.argv: bqueryd.ControllerNode(redis_url=redis_url, loglevel=loglevel).go() elif 'worker' in sys.argv: bqueryd.WorkerNode(redis_url=redis_url, loglevel=loglevel).go() else: if len(sys.argv) > 1 and sys.argv[1].startswith('tcp:'): a = bqueryd.RPC(address=sys.argv[1], redis_url=redis_url, loglevel=loglevel) else: a = bqueryd.RPC(redis_url=redis_url, loglevel=loglevel) sys.stderr.write('Run this script with python -i , and then you will have a variable named "a" as a connection.\n') <commit_msg>Use var named "rpc" and not "a"<commit_after>#!/srv/python/venv/bin/ipython -i import bqueryd import os import sys import logging import ConfigParser config = ConfigParser.RawConfigParser() config.read(['/etc/bqueryd.cfg', os.path.expanduser('~/.bqueryd.cfg')]) redis_url=config.get('Main', 'redis_url') if __name__ == '__main__': if '-v' in sys.argv: loglevel = logging.DEBUG else: loglevel = logging.INFO if 'controller' in sys.argv: bqueryd.ControllerNode(redis_url=redis_url, loglevel=loglevel).go() elif 'worker' in sys.argv: bqueryd.WorkerNode(redis_url=redis_url, loglevel=loglevel).go() else: if len(sys.argv) > 1 and sys.argv[1].startswith('tcp:'): rpc = bqueryd.RPC(address=sys.argv[1], redis_url=redis_url, loglevel=loglevel) else: rpc = bqueryd.RPC(redis_url=redis_url, loglevel=loglevel) sys.stderr.write('Run this script with python -i , and then you will have a variable named "rpc" as a connection.\n')
69f5ee4a703a52d09799b0a9978cb35a05ab18c6
docs/cryptography-docs.py
docs/cryptography-docs.py
from docutils import nodes from sphinx.util.compat import Directive, make_admonition DANGER_MESSAGE = """ This is a "Hazardous Materials" module. You should **ONLY** use it if you're 100% absolutely sure that you know what you're doing because this module is full of land mines, dragons, and dinosaurs with laser guns. """ class HazmatDirective(Directive): def run(self): ad = make_admonition( Hazmat, self.name, [], self.options, nodes.paragraph("", DANGER_MESSAGE), self.lineno, self.content_offset, self.block_text, self.state, self.state_machine ) ad[0].line = self.lineno return ad class Hazmat(nodes.Admonition, nodes.Element): pass def visit_hazmat_node(self, node): return self.visit_admonition(node, "danger") def depart_hazmat_node(self, node): return self.depart_admonition(node) def setup(app): app.add_node( Hazmat, html=(visit_hazmat_node, depart_hazmat_node) ) app.add_directive("hazmat", HazmatDirective)
from docutils import nodes from sphinx.util.compat import Directive, make_admonition DANGER_MESSAGE = """ This is a "Hazardous Materials" module. You should **ONLY** use it if you're 100% absolutely sure that you know what you're doing because this module is full of land mines, dragons, and dinosaurs with laser guns. """ class HazmatDirective(Directive): def run(self): ad = make_admonition( Hazmat, self.name, [], self.options, nodes.paragraph("", DANGER_MESSAGE), self.lineno, self.content_offset, self.block_text, self.state, self.state_machine ) ad[0].line = self.lineno return ad class Hazmat(nodes.Admonition, nodes.Element): pass def html_visit_hazmat_node(self, node): return self.visit_admonition(node, "danger") def latex_visit_hazmat_node(self, node): return self.visit_admonition(node) def depart_hazmat_node(self, node): return self.depart_admonition(node) def setup(app): app.add_node( Hazmat, html=(html_visit_hazmat_node, depart_hazmat_node), latex=(latex_visit_hazmat_node, depart_hazmat_node), ) app.add_directive("hazmat", HazmatDirective)
Fix latex compilation (needed for pdf on read the docs)
Fix latex compilation (needed for pdf on read the docs)
Python
bsd-3-clause
skeuomorf/cryptography,sholsapp/cryptography,Lukasa/cryptography,glyph/cryptography,glyph/cryptography,Hasimir/cryptography,sholsapp/cryptography,kimvais/cryptography,kimvais/cryptography,Lukasa/cryptography,dstufft/cryptography,dstufft/cryptography,Ayrx/cryptography,kimvais/cryptography,dstufft/cryptography,bwhmather/cryptography,skeuomorf/cryptography,Hasimir/cryptography,kimvais/cryptography,bwhmather/cryptography,Ayrx/cryptography,Hasimir/cryptography,dstufft/cryptography,skeuomorf/cryptography,sholsapp/cryptography,dstufft/cryptography,Ayrx/cryptography,Hasimir/cryptography,bwhmather/cryptography,Ayrx/cryptography,skeuomorf/cryptography,bwhmather/cryptography,sholsapp/cryptography,Lukasa/cryptography
from docutils import nodes from sphinx.util.compat import Directive, make_admonition DANGER_MESSAGE = """ This is a "Hazardous Materials" module. You should **ONLY** use it if you're 100% absolutely sure that you know what you're doing because this module is full of land mines, dragons, and dinosaurs with laser guns. """ class HazmatDirective(Directive): def run(self): ad = make_admonition( Hazmat, self.name, [], self.options, nodes.paragraph("", DANGER_MESSAGE), self.lineno, self.content_offset, self.block_text, self.state, self.state_machine ) ad[0].line = self.lineno return ad class Hazmat(nodes.Admonition, nodes.Element): pass def visit_hazmat_node(self, node): return self.visit_admonition(node, "danger") def depart_hazmat_node(self, node): return self.depart_admonition(node) def setup(app): app.add_node( Hazmat, html=(visit_hazmat_node, depart_hazmat_node) ) app.add_directive("hazmat", HazmatDirective) Fix latex compilation (needed for pdf on read the docs)
from docutils import nodes from sphinx.util.compat import Directive, make_admonition DANGER_MESSAGE = """ This is a "Hazardous Materials" module. You should **ONLY** use it if you're 100% absolutely sure that you know what you're doing because this module is full of land mines, dragons, and dinosaurs with laser guns. """ class HazmatDirective(Directive): def run(self): ad = make_admonition( Hazmat, self.name, [], self.options, nodes.paragraph("", DANGER_MESSAGE), self.lineno, self.content_offset, self.block_text, self.state, self.state_machine ) ad[0].line = self.lineno return ad class Hazmat(nodes.Admonition, nodes.Element): pass def html_visit_hazmat_node(self, node): return self.visit_admonition(node, "danger") def latex_visit_hazmat_node(self, node): return self.visit_admonition(node) def depart_hazmat_node(self, node): return self.depart_admonition(node) def setup(app): app.add_node( Hazmat, html=(html_visit_hazmat_node, depart_hazmat_node), latex=(latex_visit_hazmat_node, depart_hazmat_node), ) app.add_directive("hazmat", HazmatDirective)
<commit_before>from docutils import nodes from sphinx.util.compat import Directive, make_admonition DANGER_MESSAGE = """ This is a "Hazardous Materials" module. You should **ONLY** use it if you're 100% absolutely sure that you know what you're doing because this module is full of land mines, dragons, and dinosaurs with laser guns. """ class HazmatDirective(Directive): def run(self): ad = make_admonition( Hazmat, self.name, [], self.options, nodes.paragraph("", DANGER_MESSAGE), self.lineno, self.content_offset, self.block_text, self.state, self.state_machine ) ad[0].line = self.lineno return ad class Hazmat(nodes.Admonition, nodes.Element): pass def visit_hazmat_node(self, node): return self.visit_admonition(node, "danger") def depart_hazmat_node(self, node): return self.depart_admonition(node) def setup(app): app.add_node( Hazmat, html=(visit_hazmat_node, depart_hazmat_node) ) app.add_directive("hazmat", HazmatDirective) <commit_msg>Fix latex compilation (needed for pdf on read the docs)<commit_after>
from docutils import nodes from sphinx.util.compat import Directive, make_admonition DANGER_MESSAGE = """ This is a "Hazardous Materials" module. You should **ONLY** use it if you're 100% absolutely sure that you know what you're doing because this module is full of land mines, dragons, and dinosaurs with laser guns. """ class HazmatDirective(Directive): def run(self): ad = make_admonition( Hazmat, self.name, [], self.options, nodes.paragraph("", DANGER_MESSAGE), self.lineno, self.content_offset, self.block_text, self.state, self.state_machine ) ad[0].line = self.lineno return ad class Hazmat(nodes.Admonition, nodes.Element): pass def html_visit_hazmat_node(self, node): return self.visit_admonition(node, "danger") def latex_visit_hazmat_node(self, node): return self.visit_admonition(node) def depart_hazmat_node(self, node): return self.depart_admonition(node) def setup(app): app.add_node( Hazmat, html=(html_visit_hazmat_node, depart_hazmat_node), latex=(latex_visit_hazmat_node, depart_hazmat_node), ) app.add_directive("hazmat", HazmatDirective)
from docutils import nodes from sphinx.util.compat import Directive, make_admonition DANGER_MESSAGE = """ This is a "Hazardous Materials" module. You should **ONLY** use it if you're 100% absolutely sure that you know what you're doing because this module is full of land mines, dragons, and dinosaurs with laser guns. """ class HazmatDirective(Directive): def run(self): ad = make_admonition( Hazmat, self.name, [], self.options, nodes.paragraph("", DANGER_MESSAGE), self.lineno, self.content_offset, self.block_text, self.state, self.state_machine ) ad[0].line = self.lineno return ad class Hazmat(nodes.Admonition, nodes.Element): pass def visit_hazmat_node(self, node): return self.visit_admonition(node, "danger") def depart_hazmat_node(self, node): return self.depart_admonition(node) def setup(app): app.add_node( Hazmat, html=(visit_hazmat_node, depart_hazmat_node) ) app.add_directive("hazmat", HazmatDirective) Fix latex compilation (needed for pdf on read the docs)from docutils import nodes from sphinx.util.compat import Directive, make_admonition DANGER_MESSAGE = """ This is a "Hazardous Materials" module. You should **ONLY** use it if you're 100% absolutely sure that you know what you're doing because this module is full of land mines, dragons, and dinosaurs with laser guns. """ class HazmatDirective(Directive): def run(self): ad = make_admonition( Hazmat, self.name, [], self.options, nodes.paragraph("", DANGER_MESSAGE), self.lineno, self.content_offset, self.block_text, self.state, self.state_machine ) ad[0].line = self.lineno return ad class Hazmat(nodes.Admonition, nodes.Element): pass def html_visit_hazmat_node(self, node): return self.visit_admonition(node, "danger") def latex_visit_hazmat_node(self, node): return self.visit_admonition(node) def depart_hazmat_node(self, node): return self.depart_admonition(node) def setup(app): app.add_node( Hazmat, html=(html_visit_hazmat_node, depart_hazmat_node), latex=(latex_visit_hazmat_node, depart_hazmat_node), ) app.add_directive("hazmat", HazmatDirective)
<commit_before>from docutils import nodes from sphinx.util.compat import Directive, make_admonition DANGER_MESSAGE = """ This is a "Hazardous Materials" module. You should **ONLY** use it if you're 100% absolutely sure that you know what you're doing because this module is full of land mines, dragons, and dinosaurs with laser guns. """ class HazmatDirective(Directive): def run(self): ad = make_admonition( Hazmat, self.name, [], self.options, nodes.paragraph("", DANGER_MESSAGE), self.lineno, self.content_offset, self.block_text, self.state, self.state_machine ) ad[0].line = self.lineno return ad class Hazmat(nodes.Admonition, nodes.Element): pass def visit_hazmat_node(self, node): return self.visit_admonition(node, "danger") def depart_hazmat_node(self, node): return self.depart_admonition(node) def setup(app): app.add_node( Hazmat, html=(visit_hazmat_node, depart_hazmat_node) ) app.add_directive("hazmat", HazmatDirective) <commit_msg>Fix latex compilation (needed for pdf on read the docs)<commit_after>from docutils import nodes from sphinx.util.compat import Directive, make_admonition DANGER_MESSAGE = """ This is a "Hazardous Materials" module. You should **ONLY** use it if you're 100% absolutely sure that you know what you're doing because this module is full of land mines, dragons, and dinosaurs with laser guns. """ class HazmatDirective(Directive): def run(self): ad = make_admonition( Hazmat, self.name, [], self.options, nodes.paragraph("", DANGER_MESSAGE), self.lineno, self.content_offset, self.block_text, self.state, self.state_machine ) ad[0].line = self.lineno return ad class Hazmat(nodes.Admonition, nodes.Element): pass def html_visit_hazmat_node(self, node): return self.visit_admonition(node, "danger") def latex_visit_hazmat_node(self, node): return self.visit_admonition(node) def depart_hazmat_node(self, node): return self.depart_admonition(node) def setup(app): app.add_node( Hazmat, html=(html_visit_hazmat_node, depart_hazmat_node), latex=(latex_visit_hazmat_node, depart_hazmat_node), ) app.add_directive("hazmat", HazmatDirective)
a8e42b122916696dbe63ddae3190502b296b47ec
label_response/__init__.py
label_response/__init__.py
import json def check_labels(api): with open('config.json', 'r') as fd: config = json.load(fd) if not config['active']: return labels = config['labels'] for label, comment in labels.items(): if api.payload['label']['name'].lower() == label: api.post_comment(comment) method = check_labels
import json def check_labels(api, config): if not config.get('active'): return labels = config.get('labels', []) for label, comment in labels.items(): if api.payload['label']['name'].lower() == label: api.post_comment(comment) methods = [check_labels]
Support for multiple methods, and leave the config file to hooker
Support for multiple methods, and leave the config file to hooker
Python
mpl-2.0
servo-automation/highfive,servo-automation/highfive,servo-highfive/highfive
import json def check_labels(api): with open('config.json', 'r') as fd: config = json.load(fd) if not config['active']: return labels = config['labels'] for label, comment in labels.items(): if api.payload['label']['name'].lower() == label: api.post_comment(comment) method = check_labels Support for multiple methods, and leave the config file to hooker
import json def check_labels(api, config): if not config.get('active'): return labels = config.get('labels', []) for label, comment in labels.items(): if api.payload['label']['name'].lower() == label: api.post_comment(comment) methods = [check_labels]
<commit_before>import json def check_labels(api): with open('config.json', 'r') as fd: config = json.load(fd) if not config['active']: return labels = config['labels'] for label, comment in labels.items(): if api.payload['label']['name'].lower() == label: api.post_comment(comment) method = check_labels <commit_msg>Support for multiple methods, and leave the config file to hooker<commit_after>
import json def check_labels(api, config): if not config.get('active'): return labels = config.get('labels', []) for label, comment in labels.items(): if api.payload['label']['name'].lower() == label: api.post_comment(comment) methods = [check_labels]
import json def check_labels(api): with open('config.json', 'r') as fd: config = json.load(fd) if not config['active']: return labels = config['labels'] for label, comment in labels.items(): if api.payload['label']['name'].lower() == label: api.post_comment(comment) method = check_labels Support for multiple methods, and leave the config file to hookerimport json def check_labels(api, config): if not config.get('active'): return labels = config.get('labels', []) for label, comment in labels.items(): if api.payload['label']['name'].lower() == label: api.post_comment(comment) methods = [check_labels]
<commit_before>import json def check_labels(api): with open('config.json', 'r') as fd: config = json.load(fd) if not config['active']: return labels = config['labels'] for label, comment in labels.items(): if api.payload['label']['name'].lower() == label: api.post_comment(comment) method = check_labels <commit_msg>Support for multiple methods, and leave the config file to hooker<commit_after>import json def check_labels(api, config): if not config.get('active'): return labels = config.get('labels', []) for label, comment in labels.items(): if api.payload['label']['name'].lower() == label: api.post_comment(comment) methods = [check_labels]
ecfdaee676fe6c0dd9609c944bc5f25b38e0ed05
validator/__init__.py
validator/__init__.py
__version__ = '1.10.76' class ValidationTimeout(Exception): """Validation has timed out. May be replaced by the exception type raised by an external timeout handler when run in a server environment.""" def __init__(self, timeout): self.timeout = timeout def __str__(self): return 'Validation timeout after %d seconds' % self.timeout
__version__ = '1.11.0' class ValidationTimeout(Exception): """Validation has timed out. May be replaced by the exception type raised by an external timeout handler when run in a server environment.""" def __init__(self, timeout): self.timeout = timeout def __str__(self): return 'Validation timeout after %d seconds' % self.timeout
Prepare release 1.11.0. Note that this release deprecates the validator.
Prepare release 1.11.0. Note that this release deprecates the validator.
Python
bsd-3-clause
mozilla/amo-validator,mozilla/amo-validator,mozilla/amo-validator,mozilla/amo-validator
__version__ = '1.10.76' class ValidationTimeout(Exception): """Validation has timed out. May be replaced by the exception type raised by an external timeout handler when run in a server environment.""" def __init__(self, timeout): self.timeout = timeout def __str__(self): return 'Validation timeout after %d seconds' % self.timeout Prepare release 1.11.0. Note that this release deprecates the validator.
__version__ = '1.11.0' class ValidationTimeout(Exception): """Validation has timed out. May be replaced by the exception type raised by an external timeout handler when run in a server environment.""" def __init__(self, timeout): self.timeout = timeout def __str__(self): return 'Validation timeout after %d seconds' % self.timeout
<commit_before>__version__ = '1.10.76' class ValidationTimeout(Exception): """Validation has timed out. May be replaced by the exception type raised by an external timeout handler when run in a server environment.""" def __init__(self, timeout): self.timeout = timeout def __str__(self): return 'Validation timeout after %d seconds' % self.timeout <commit_msg>Prepare release 1.11.0. Note that this release deprecates the validator.<commit_after>
__version__ = '1.11.0' class ValidationTimeout(Exception): """Validation has timed out. May be replaced by the exception type raised by an external timeout handler when run in a server environment.""" def __init__(self, timeout): self.timeout = timeout def __str__(self): return 'Validation timeout after %d seconds' % self.timeout
__version__ = '1.10.76' class ValidationTimeout(Exception): """Validation has timed out. May be replaced by the exception type raised by an external timeout handler when run in a server environment.""" def __init__(self, timeout): self.timeout = timeout def __str__(self): return 'Validation timeout after %d seconds' % self.timeout Prepare release 1.11.0. Note that this release deprecates the validator.__version__ = '1.11.0' class ValidationTimeout(Exception): """Validation has timed out. May be replaced by the exception type raised by an external timeout handler when run in a server environment.""" def __init__(self, timeout): self.timeout = timeout def __str__(self): return 'Validation timeout after %d seconds' % self.timeout
<commit_before>__version__ = '1.10.76' class ValidationTimeout(Exception): """Validation has timed out. May be replaced by the exception type raised by an external timeout handler when run in a server environment.""" def __init__(self, timeout): self.timeout = timeout def __str__(self): return 'Validation timeout after %d seconds' % self.timeout <commit_msg>Prepare release 1.11.0. Note that this release deprecates the validator.<commit_after>__version__ = '1.11.0' class ValidationTimeout(Exception): """Validation has timed out. May be replaced by the exception type raised by an external timeout handler when run in a server environment.""" def __init__(self, timeout): self.timeout = timeout def __str__(self): return 'Validation timeout after %d seconds' % self.timeout
a01e924ccd80a11b2f5c59828c5395b92d9fd5a7
scripts/load_firebase.py
scripts/load_firebase.py
import argparse import requests import time DEFAULT_DEVICE = 0 DEFAULT_FILE = '../data/ECG_data.csv' def main(device=0, filename=DEFAULT_FILE): print("Loading firebase for device #%d" % device) with open(filename) as f: index = 0 count = 0 timestamp = int(time.time() * 1000) for line in f: line = line.strip() ts, value = line.split(',', 1) count += float(value) index += 1 if index == 10: # Dump timestamp += 1 print("Sending %s: %s" % (str(timestamp), str(count / 10))) requests.put('https://ubervest.firebaseio.com/devices/0/hr/' + str(timestamp) + '.json', data=str(count / 10)) count = 0 index = 0 timestamp += 1 requests.put('https://ubervest.firebaseio.com/devices/0/hr/' + str(timestamp) + '.json', data=str(count / 10)) if __name__ == "__main__": parser = argparse.ArgumentParser(description='Load sample data for a given device') parser.add_argument('--d', type=int, default=DEFAULT_DEVICE, help="The ID of the device to load with data.") parser.add_argument('--f', type=str, default=DEFAULT_FILE, help="The ID of the device to load with data.") args = parser.parse_args() main(device=args.d, filename=args.f)
import argparse import requests import time DEFAULT_DEVICE = 0 DEFAULT_FILE = '../data/ECG_data.csv' def main(device=0, filename=DEFAULT_FILE): print("Loading firebase for device #%d" % device) with open(filename) as f: index = 0 count = 0 timestamp = int(time.time() * 1000) for line in f: line = line.strip() ts, value = line.split(',', 1) count += float(value) index += 1 if index == 10: # Dump timestamp += 1 print("Sending %s: %s" % (str(timestamp), str(count / 10))) requests.put(('https://ubervest.firebaseio.com/devices/%d/hr/' % device) + str(timestamp) + '.json', data=str(count / 10)) count = 0 index = 0 timestamp += 1 requests.put(('https://ubervest.firebaseio.com/devices/%d/hr/' % device) + str(timestamp) + '.json', data=str(count / 10)) if __name__ == "__main__": parser = argparse.ArgumentParser(description='Load sample data for a given device') parser.add_argument('--d', type=int, default=DEFAULT_DEVICE, help="The ID of the device to load with data.") parser.add_argument('--f', type=str, default=DEFAULT_FILE, help="The ID of the device to load with data.") args = parser.parse_args() main(device=args.d, filename=args.f)
Update ID of device in load script
Update ID of device in load script
Python
mit
easyCZ/SLIP-A-2015,easyCZ/SLIP-A-2015,easyCZ/SLIP-A-2015,easyCZ/SLIP-A-2015,easyCZ/SLIP-A-2015,easyCZ/SLIP-A-2015
import argparse import requests import time DEFAULT_DEVICE = 0 DEFAULT_FILE = '../data/ECG_data.csv' def main(device=0, filename=DEFAULT_FILE): print("Loading firebase for device #%d" % device) with open(filename) as f: index = 0 count = 0 timestamp = int(time.time() * 1000) for line in f: line = line.strip() ts, value = line.split(',', 1) count += float(value) index += 1 if index == 10: # Dump timestamp += 1 print("Sending %s: %s" % (str(timestamp), str(count / 10))) requests.put('https://ubervest.firebaseio.com/devices/0/hr/' + str(timestamp) + '.json', data=str(count / 10)) count = 0 index = 0 timestamp += 1 requests.put('https://ubervest.firebaseio.com/devices/0/hr/' + str(timestamp) + '.json', data=str(count / 10)) if __name__ == "__main__": parser = argparse.ArgumentParser(description='Load sample data for a given device') parser.add_argument('--d', type=int, default=DEFAULT_DEVICE, help="The ID of the device to load with data.") parser.add_argument('--f', type=str, default=DEFAULT_FILE, help="The ID of the device to load with data.") args = parser.parse_args() main(device=args.d, filename=args.f)Update ID of device in load script
import argparse import requests import time DEFAULT_DEVICE = 0 DEFAULT_FILE = '../data/ECG_data.csv' def main(device=0, filename=DEFAULT_FILE): print("Loading firebase for device #%d" % device) with open(filename) as f: index = 0 count = 0 timestamp = int(time.time() * 1000) for line in f: line = line.strip() ts, value = line.split(',', 1) count += float(value) index += 1 if index == 10: # Dump timestamp += 1 print("Sending %s: %s" % (str(timestamp), str(count / 10))) requests.put(('https://ubervest.firebaseio.com/devices/%d/hr/' % device) + str(timestamp) + '.json', data=str(count / 10)) count = 0 index = 0 timestamp += 1 requests.put(('https://ubervest.firebaseio.com/devices/%d/hr/' % device) + str(timestamp) + '.json', data=str(count / 10)) if __name__ == "__main__": parser = argparse.ArgumentParser(description='Load sample data for a given device') parser.add_argument('--d', type=int, default=DEFAULT_DEVICE, help="The ID of the device to load with data.") parser.add_argument('--f', type=str, default=DEFAULT_FILE, help="The ID of the device to load with data.") args = parser.parse_args() main(device=args.d, filename=args.f)
<commit_before>import argparse import requests import time DEFAULT_DEVICE = 0 DEFAULT_FILE = '../data/ECG_data.csv' def main(device=0, filename=DEFAULT_FILE): print("Loading firebase for device #%d" % device) with open(filename) as f: index = 0 count = 0 timestamp = int(time.time() * 1000) for line in f: line = line.strip() ts, value = line.split(',', 1) count += float(value) index += 1 if index == 10: # Dump timestamp += 1 print("Sending %s: %s" % (str(timestamp), str(count / 10))) requests.put('https://ubervest.firebaseio.com/devices/0/hr/' + str(timestamp) + '.json', data=str(count / 10)) count = 0 index = 0 timestamp += 1 requests.put('https://ubervest.firebaseio.com/devices/0/hr/' + str(timestamp) + '.json', data=str(count / 10)) if __name__ == "__main__": parser = argparse.ArgumentParser(description='Load sample data for a given device') parser.add_argument('--d', type=int, default=DEFAULT_DEVICE, help="The ID of the device to load with data.") parser.add_argument('--f', type=str, default=DEFAULT_FILE, help="The ID of the device to load with data.") args = parser.parse_args() main(device=args.d, filename=args.f)<commit_msg>Update ID of device in load script<commit_after>
import argparse import requests import time DEFAULT_DEVICE = 0 DEFAULT_FILE = '../data/ECG_data.csv' def main(device=0, filename=DEFAULT_FILE): print("Loading firebase for device #%d" % device) with open(filename) as f: index = 0 count = 0 timestamp = int(time.time() * 1000) for line in f: line = line.strip() ts, value = line.split(',', 1) count += float(value) index += 1 if index == 10: # Dump timestamp += 1 print("Sending %s: %s" % (str(timestamp), str(count / 10))) requests.put(('https://ubervest.firebaseio.com/devices/%d/hr/' % device) + str(timestamp) + '.json', data=str(count / 10)) count = 0 index = 0 timestamp += 1 requests.put(('https://ubervest.firebaseio.com/devices/%d/hr/' % device) + str(timestamp) + '.json', data=str(count / 10)) if __name__ == "__main__": parser = argparse.ArgumentParser(description='Load sample data for a given device') parser.add_argument('--d', type=int, default=DEFAULT_DEVICE, help="The ID of the device to load with data.") parser.add_argument('--f', type=str, default=DEFAULT_FILE, help="The ID of the device to load with data.") args = parser.parse_args() main(device=args.d, filename=args.f)
import argparse import requests import time DEFAULT_DEVICE = 0 DEFAULT_FILE = '../data/ECG_data.csv' def main(device=0, filename=DEFAULT_FILE): print("Loading firebase for device #%d" % device) with open(filename) as f: index = 0 count = 0 timestamp = int(time.time() * 1000) for line in f: line = line.strip() ts, value = line.split(',', 1) count += float(value) index += 1 if index == 10: # Dump timestamp += 1 print("Sending %s: %s" % (str(timestamp), str(count / 10))) requests.put('https://ubervest.firebaseio.com/devices/0/hr/' + str(timestamp) + '.json', data=str(count / 10)) count = 0 index = 0 timestamp += 1 requests.put('https://ubervest.firebaseio.com/devices/0/hr/' + str(timestamp) + '.json', data=str(count / 10)) if __name__ == "__main__": parser = argparse.ArgumentParser(description='Load sample data for a given device') parser.add_argument('--d', type=int, default=DEFAULT_DEVICE, help="The ID of the device to load with data.") parser.add_argument('--f', type=str, default=DEFAULT_FILE, help="The ID of the device to load with data.") args = parser.parse_args() main(device=args.d, filename=args.f)Update ID of device in load scriptimport argparse import requests import time DEFAULT_DEVICE = 0 DEFAULT_FILE = '../data/ECG_data.csv' def main(device=0, filename=DEFAULT_FILE): print("Loading firebase for device #%d" % device) with open(filename) as f: index = 0 count = 0 timestamp = int(time.time() * 1000) for line in f: line = line.strip() ts, value = line.split(',', 1) count += float(value) index += 1 if index == 10: # Dump timestamp += 1 print("Sending %s: %s" % (str(timestamp), str(count / 10))) requests.put(('https://ubervest.firebaseio.com/devices/%d/hr/' % device) + str(timestamp) + '.json', data=str(count / 10)) count = 0 index = 0 timestamp += 1 requests.put(('https://ubervest.firebaseio.com/devices/%d/hr/' % device) + str(timestamp) + '.json', data=str(count / 10)) if __name__ == "__main__": parser = argparse.ArgumentParser(description='Load sample data for a given device') parser.add_argument('--d', type=int, default=DEFAULT_DEVICE, help="The ID of the device to load with data.") parser.add_argument('--f', type=str, default=DEFAULT_FILE, help="The ID of the device to load with data.") args = parser.parse_args() main(device=args.d, filename=args.f)
<commit_before>import argparse import requests import time DEFAULT_DEVICE = 0 DEFAULT_FILE = '../data/ECG_data.csv' def main(device=0, filename=DEFAULT_FILE): print("Loading firebase for device #%d" % device) with open(filename) as f: index = 0 count = 0 timestamp = int(time.time() * 1000) for line in f: line = line.strip() ts, value = line.split(',', 1) count += float(value) index += 1 if index == 10: # Dump timestamp += 1 print("Sending %s: %s" % (str(timestamp), str(count / 10))) requests.put('https://ubervest.firebaseio.com/devices/0/hr/' + str(timestamp) + '.json', data=str(count / 10)) count = 0 index = 0 timestamp += 1 requests.put('https://ubervest.firebaseio.com/devices/0/hr/' + str(timestamp) + '.json', data=str(count / 10)) if __name__ == "__main__": parser = argparse.ArgumentParser(description='Load sample data for a given device') parser.add_argument('--d', type=int, default=DEFAULT_DEVICE, help="The ID of the device to load with data.") parser.add_argument('--f', type=str, default=DEFAULT_FILE, help="The ID of the device to load with data.") args = parser.parse_args() main(device=args.d, filename=args.f)<commit_msg>Update ID of device in load script<commit_after>import argparse import requests import time DEFAULT_DEVICE = 0 DEFAULT_FILE = '../data/ECG_data.csv' def main(device=0, filename=DEFAULT_FILE): print("Loading firebase for device #%d" % device) with open(filename) as f: index = 0 count = 0 timestamp = int(time.time() * 1000) for line in f: line = line.strip() ts, value = line.split(',', 1) count += float(value) index += 1 if index == 10: # Dump timestamp += 1 print("Sending %s: %s" % (str(timestamp), str(count / 10))) requests.put(('https://ubervest.firebaseio.com/devices/%d/hr/' % device) + str(timestamp) + '.json', data=str(count / 10)) count = 0 index = 0 timestamp += 1 requests.put(('https://ubervest.firebaseio.com/devices/%d/hr/' % device) + str(timestamp) + '.json', data=str(count / 10)) if __name__ == "__main__": parser = argparse.ArgumentParser(description='Load sample data for a given device') parser.add_argument('--d', type=int, default=DEFAULT_DEVICE, help="The ID of the device to load with data.") parser.add_argument('--f', type=str, default=DEFAULT_FILE, help="The ID of the device to load with data.") args = parser.parse_args() main(device=args.d, filename=args.f)
07096ba58e61580168c85dbcbecb107824096871
python/tutorial/example.py
python/tutorial/example.py
from matasano.util.byte_xor import byte_list_xor import sys if __name__ == "__main__": if len(sys.argv) != 2: print("Usage:\n\t python -m example.py <string to encrypt>") quit() input_str = sys.argv[1] # Convert string to list of bytes byte_list_input = [ord(c) for c in input_str] # XOR the string with the byte 1 (flips last bit) output_list = byte_list_xor(byte_list_input, [1]*len(input_str)) # Convert list back to string output_str = "".join(chr(b) for b in output_list) print("The encrypted string is: {}".format(output_str))
from matasano.util.byte_xor import byte_list_xor import sys if __name__ == "__main__": if len(sys.argv) != 2: print("Usage:\n\t python -m example.py <string to encrypt>") quit() input_str = sys.argv[1] # Convert string to list of bytes byte_list_input = [ord(c) for c in input_str] # XOR the string with the byte 2 (flips secondd last bit) output_list = byte_list_xor(byte_list_input, [2]*len(input_str)) # Convert list back to string output_str = "".join(chr(b) for b in output_list) print("The encrypted string is: {}".format(output_str))
Change XOR to flip second last bit
Change XOR to flip second last bit Making change to cause merge conflict as an example.
Python
mit
TheLunchtimeAttack/matasano-challenges,TheLunchtimeAttack/matasano-challenges
from matasano.util.byte_xor import byte_list_xor import sys if __name__ == "__main__": if len(sys.argv) != 2: print("Usage:\n\t python -m example.py <string to encrypt>") quit() input_str = sys.argv[1] # Convert string to list of bytes byte_list_input = [ord(c) for c in input_str] # XOR the string with the byte 1 (flips last bit) output_list = byte_list_xor(byte_list_input, [1]*len(input_str)) # Convert list back to string output_str = "".join(chr(b) for b in output_list) print("The encrypted string is: {}".format(output_str))Change XOR to flip second last bit Making change to cause merge conflict as an example.
from matasano.util.byte_xor import byte_list_xor import sys if __name__ == "__main__": if len(sys.argv) != 2: print("Usage:\n\t python -m example.py <string to encrypt>") quit() input_str = sys.argv[1] # Convert string to list of bytes byte_list_input = [ord(c) for c in input_str] # XOR the string with the byte 2 (flips secondd last bit) output_list = byte_list_xor(byte_list_input, [2]*len(input_str)) # Convert list back to string output_str = "".join(chr(b) for b in output_list) print("The encrypted string is: {}".format(output_str))
<commit_before>from matasano.util.byte_xor import byte_list_xor import sys if __name__ == "__main__": if len(sys.argv) != 2: print("Usage:\n\t python -m example.py <string to encrypt>") quit() input_str = sys.argv[1] # Convert string to list of bytes byte_list_input = [ord(c) for c in input_str] # XOR the string with the byte 1 (flips last bit) output_list = byte_list_xor(byte_list_input, [1]*len(input_str)) # Convert list back to string output_str = "".join(chr(b) for b in output_list) print("The encrypted string is: {}".format(output_str))<commit_msg>Change XOR to flip second last bit Making change to cause merge conflict as an example.<commit_after>
from matasano.util.byte_xor import byte_list_xor import sys if __name__ == "__main__": if len(sys.argv) != 2: print("Usage:\n\t python -m example.py <string to encrypt>") quit() input_str = sys.argv[1] # Convert string to list of bytes byte_list_input = [ord(c) for c in input_str] # XOR the string with the byte 2 (flips secondd last bit) output_list = byte_list_xor(byte_list_input, [2]*len(input_str)) # Convert list back to string output_str = "".join(chr(b) for b in output_list) print("The encrypted string is: {}".format(output_str))
from matasano.util.byte_xor import byte_list_xor import sys if __name__ == "__main__": if len(sys.argv) != 2: print("Usage:\n\t python -m example.py <string to encrypt>") quit() input_str = sys.argv[1] # Convert string to list of bytes byte_list_input = [ord(c) for c in input_str] # XOR the string with the byte 1 (flips last bit) output_list = byte_list_xor(byte_list_input, [1]*len(input_str)) # Convert list back to string output_str = "".join(chr(b) for b in output_list) print("The encrypted string is: {}".format(output_str))Change XOR to flip second last bit Making change to cause merge conflict as an example.from matasano.util.byte_xor import byte_list_xor import sys if __name__ == "__main__": if len(sys.argv) != 2: print("Usage:\n\t python -m example.py <string to encrypt>") quit() input_str = sys.argv[1] # Convert string to list of bytes byte_list_input = [ord(c) for c in input_str] # XOR the string with the byte 2 (flips secondd last bit) output_list = byte_list_xor(byte_list_input, [2]*len(input_str)) # Convert list back to string output_str = "".join(chr(b) for b in output_list) print("The encrypted string is: {}".format(output_str))
<commit_before>from matasano.util.byte_xor import byte_list_xor import sys if __name__ == "__main__": if len(sys.argv) != 2: print("Usage:\n\t python -m example.py <string to encrypt>") quit() input_str = sys.argv[1] # Convert string to list of bytes byte_list_input = [ord(c) for c in input_str] # XOR the string with the byte 1 (flips last bit) output_list = byte_list_xor(byte_list_input, [1]*len(input_str)) # Convert list back to string output_str = "".join(chr(b) for b in output_list) print("The encrypted string is: {}".format(output_str))<commit_msg>Change XOR to flip second last bit Making change to cause merge conflict as an example.<commit_after>from matasano.util.byte_xor import byte_list_xor import sys if __name__ == "__main__": if len(sys.argv) != 2: print("Usage:\n\t python -m example.py <string to encrypt>") quit() input_str = sys.argv[1] # Convert string to list of bytes byte_list_input = [ord(c) for c in input_str] # XOR the string with the byte 2 (flips secondd last bit) output_list = byte_list_xor(byte_list_input, [2]*len(input_str)) # Convert list back to string output_str = "".join(chr(b) for b in output_list) print("The encrypted string is: {}".format(output_str))
be3e22f391e50bfdfb83f73382c392afc2fc9f1f
scripts/registrations.py
scripts/registrations.py
from competition.models import (Competition, RegistrationQuestion, RegistrationQuestionResponse) import csv import StringIO def run(): shirt = RegistrationQuestion.objects.filter(question__contains="shirt") for c in Competition.objects.all().order_by('start_time'): print c.name csv_content = StringIO.StringIO() writer = csv.writer(csv_content) for r in c.registration_set.filter(active=True).order_by('signup_date'): try: size = r.response_set.get(question=shirt).choices.get().choice except RegistrationQuestionResponse.DoesNotExist: size = None writer.writerow([r.signup_date, r.user.username, r.user.get_full_name(), size]) print csv_content.getvalue()
from competition.models import (Competition, RegistrationQuestion, RegistrationQuestionResponse) import csv import StringIO def run(): shirt = RegistrationQuestion.objects.filter(question__contains="shirt") for c in Competition.objects.all().order_by('start_time'): print c.name csv_content = StringIO.StringIO() writer = csv.writer(csv_content) for r in c.registration_set.filter(active=True).order_by('signup_date'): try: size = r.response_set.get(question=shirt).choices.get().choice except RegistrationQuestionResponse.DoesNotExist: size = None writer.writerow([r.signup_date, r.user.username, r.user.get_full_name(), r.user.email, size]) print csv_content.getvalue()
Add email address to registration script output
Add email address to registration script output
Python
bsd-3-clause
siggame/webserver,siggame/webserver,siggame/webserver
from competition.models import (Competition, RegistrationQuestion, RegistrationQuestionResponse) import csv import StringIO def run(): shirt = RegistrationQuestion.objects.filter(question__contains="shirt") for c in Competition.objects.all().order_by('start_time'): print c.name csv_content = StringIO.StringIO() writer = csv.writer(csv_content) for r in c.registration_set.filter(active=True).order_by('signup_date'): try: size = r.response_set.get(question=shirt).choices.get().choice except RegistrationQuestionResponse.DoesNotExist: size = None writer.writerow([r.signup_date, r.user.username, r.user.get_full_name(), size]) print csv_content.getvalue() Add email address to registration script output
from competition.models import (Competition, RegistrationQuestion, RegistrationQuestionResponse) import csv import StringIO def run(): shirt = RegistrationQuestion.objects.filter(question__contains="shirt") for c in Competition.objects.all().order_by('start_time'): print c.name csv_content = StringIO.StringIO() writer = csv.writer(csv_content) for r in c.registration_set.filter(active=True).order_by('signup_date'): try: size = r.response_set.get(question=shirt).choices.get().choice except RegistrationQuestionResponse.DoesNotExist: size = None writer.writerow([r.signup_date, r.user.username, r.user.get_full_name(), r.user.email, size]) print csv_content.getvalue()
<commit_before>from competition.models import (Competition, RegistrationQuestion, RegistrationQuestionResponse) import csv import StringIO def run(): shirt = RegistrationQuestion.objects.filter(question__contains="shirt") for c in Competition.objects.all().order_by('start_time'): print c.name csv_content = StringIO.StringIO() writer = csv.writer(csv_content) for r in c.registration_set.filter(active=True).order_by('signup_date'): try: size = r.response_set.get(question=shirt).choices.get().choice except RegistrationQuestionResponse.DoesNotExist: size = None writer.writerow([r.signup_date, r.user.username, r.user.get_full_name(), size]) print csv_content.getvalue() <commit_msg>Add email address to registration script output<commit_after>
from competition.models import (Competition, RegistrationQuestion, RegistrationQuestionResponse) import csv import StringIO def run(): shirt = RegistrationQuestion.objects.filter(question__contains="shirt") for c in Competition.objects.all().order_by('start_time'): print c.name csv_content = StringIO.StringIO() writer = csv.writer(csv_content) for r in c.registration_set.filter(active=True).order_by('signup_date'): try: size = r.response_set.get(question=shirt).choices.get().choice except RegistrationQuestionResponse.DoesNotExist: size = None writer.writerow([r.signup_date, r.user.username, r.user.get_full_name(), r.user.email, size]) print csv_content.getvalue()
from competition.models import (Competition, RegistrationQuestion, RegistrationQuestionResponse) import csv import StringIO def run(): shirt = RegistrationQuestion.objects.filter(question__contains="shirt") for c in Competition.objects.all().order_by('start_time'): print c.name csv_content = StringIO.StringIO() writer = csv.writer(csv_content) for r in c.registration_set.filter(active=True).order_by('signup_date'): try: size = r.response_set.get(question=shirt).choices.get().choice except RegistrationQuestionResponse.DoesNotExist: size = None writer.writerow([r.signup_date, r.user.username, r.user.get_full_name(), size]) print csv_content.getvalue() Add email address to registration script outputfrom competition.models import (Competition, RegistrationQuestion, RegistrationQuestionResponse) import csv import StringIO def run(): shirt = RegistrationQuestion.objects.filter(question__contains="shirt") for c in Competition.objects.all().order_by('start_time'): print c.name csv_content = StringIO.StringIO() writer = csv.writer(csv_content) for r in c.registration_set.filter(active=True).order_by('signup_date'): try: size = r.response_set.get(question=shirt).choices.get().choice except RegistrationQuestionResponse.DoesNotExist: size = None writer.writerow([r.signup_date, r.user.username, r.user.get_full_name(), r.user.email, size]) print csv_content.getvalue()
<commit_before>from competition.models import (Competition, RegistrationQuestion, RegistrationQuestionResponse) import csv import StringIO def run(): shirt = RegistrationQuestion.objects.filter(question__contains="shirt") for c in Competition.objects.all().order_by('start_time'): print c.name csv_content = StringIO.StringIO() writer = csv.writer(csv_content) for r in c.registration_set.filter(active=True).order_by('signup_date'): try: size = r.response_set.get(question=shirt).choices.get().choice except RegistrationQuestionResponse.DoesNotExist: size = None writer.writerow([r.signup_date, r.user.username, r.user.get_full_name(), size]) print csv_content.getvalue() <commit_msg>Add email address to registration script output<commit_after>from competition.models import (Competition, RegistrationQuestion, RegistrationQuestionResponse) import csv import StringIO def run(): shirt = RegistrationQuestion.objects.filter(question__contains="shirt") for c in Competition.objects.all().order_by('start_time'): print c.name csv_content = StringIO.StringIO() writer = csv.writer(csv_content) for r in c.registration_set.filter(active=True).order_by('signup_date'): try: size = r.response_set.get(question=shirt).choices.get().choice except RegistrationQuestionResponse.DoesNotExist: size = None writer.writerow([r.signup_date, r.user.username, r.user.get_full_name(), r.user.email, size]) print csv_content.getvalue()
f2752572d915563ea5a3361dbb7a3fee08b04660
tests/test_mmstats.py
tests/test_mmstats.py
import mmstats def test_uint(): class MyStats(mmstats.MmStats): apples = mmstats.UIntStat() oranges = mmstats.UIntStat() mmst = MyStats() # Basic format assert mmst.mmap[0] == '\x01' assert mmst.mmap.find('applesL') != -1 assert mmst.mmap.find('orangesL') != -1 # Stat manipulation assert mmst.apples == 0 assert mmst.oranges == 0 mmst.apples = 1 assert mmst.apples == 1 assert mmst.oranges == 0
import mmstats def test_uint(): class MyStats(mmstats.MmStats): zebras = mmstats.UIntStat() apples = mmstats.UIntStat() oranges = mmstats.UIntStat() mmst = MyStats() # Basic format assert mmst.mmap[0] == '\x01' assert mmst.mmap.find('applesL') != -1 assert mmst.mmap.find('orangesL') != -1 assert mmst.mmap.find('zebrasL') != -1 # Stat manipulation assert mmst.apples == 0 assert mmst.oranges == 0 assert mmst.zebras == 0 mmst.apples = 1 assert mmst.apples == 1 assert mmst.oranges == 0 assert mmst.zebras == 0 mmst.zebras = 9001 assert mmst.apples == 1 assert mmst.oranges == 0 assert mmst.zebras == 9001
Make basic test a bit more thorough
Make basic test a bit more thorough
Python
bsd-3-clause
schmichael/mmstats,schmichael/mmstats,schmichael/mmstats,schmichael/mmstats
import mmstats def test_uint(): class MyStats(mmstats.MmStats): apples = mmstats.UIntStat() oranges = mmstats.UIntStat() mmst = MyStats() # Basic format assert mmst.mmap[0] == '\x01' assert mmst.mmap.find('applesL') != -1 assert mmst.mmap.find('orangesL') != -1 # Stat manipulation assert mmst.apples == 0 assert mmst.oranges == 0 mmst.apples = 1 assert mmst.apples == 1 assert mmst.oranges == 0 Make basic test a bit more thorough
import mmstats def test_uint(): class MyStats(mmstats.MmStats): zebras = mmstats.UIntStat() apples = mmstats.UIntStat() oranges = mmstats.UIntStat() mmst = MyStats() # Basic format assert mmst.mmap[0] == '\x01' assert mmst.mmap.find('applesL') != -1 assert mmst.mmap.find('orangesL') != -1 assert mmst.mmap.find('zebrasL') != -1 # Stat manipulation assert mmst.apples == 0 assert mmst.oranges == 0 assert mmst.zebras == 0 mmst.apples = 1 assert mmst.apples == 1 assert mmst.oranges == 0 assert mmst.zebras == 0 mmst.zebras = 9001 assert mmst.apples == 1 assert mmst.oranges == 0 assert mmst.zebras == 9001
<commit_before>import mmstats def test_uint(): class MyStats(mmstats.MmStats): apples = mmstats.UIntStat() oranges = mmstats.UIntStat() mmst = MyStats() # Basic format assert mmst.mmap[0] == '\x01' assert mmst.mmap.find('applesL') != -1 assert mmst.mmap.find('orangesL') != -1 # Stat manipulation assert mmst.apples == 0 assert mmst.oranges == 0 mmst.apples = 1 assert mmst.apples == 1 assert mmst.oranges == 0 <commit_msg>Make basic test a bit more thorough<commit_after>
import mmstats def test_uint(): class MyStats(mmstats.MmStats): zebras = mmstats.UIntStat() apples = mmstats.UIntStat() oranges = mmstats.UIntStat() mmst = MyStats() # Basic format assert mmst.mmap[0] == '\x01' assert mmst.mmap.find('applesL') != -1 assert mmst.mmap.find('orangesL') != -1 assert mmst.mmap.find('zebrasL') != -1 # Stat manipulation assert mmst.apples == 0 assert mmst.oranges == 0 assert mmst.zebras == 0 mmst.apples = 1 assert mmst.apples == 1 assert mmst.oranges == 0 assert mmst.zebras == 0 mmst.zebras = 9001 assert mmst.apples == 1 assert mmst.oranges == 0 assert mmst.zebras == 9001
import mmstats def test_uint(): class MyStats(mmstats.MmStats): apples = mmstats.UIntStat() oranges = mmstats.UIntStat() mmst = MyStats() # Basic format assert mmst.mmap[0] == '\x01' assert mmst.mmap.find('applesL') != -1 assert mmst.mmap.find('orangesL') != -1 # Stat manipulation assert mmst.apples == 0 assert mmst.oranges == 0 mmst.apples = 1 assert mmst.apples == 1 assert mmst.oranges == 0 Make basic test a bit more thoroughimport mmstats def test_uint(): class MyStats(mmstats.MmStats): zebras = mmstats.UIntStat() apples = mmstats.UIntStat() oranges = mmstats.UIntStat() mmst = MyStats() # Basic format assert mmst.mmap[0] == '\x01' assert mmst.mmap.find('applesL') != -1 assert mmst.mmap.find('orangesL') != -1 assert mmst.mmap.find('zebrasL') != -1 # Stat manipulation assert mmst.apples == 0 assert mmst.oranges == 0 assert mmst.zebras == 0 mmst.apples = 1 assert mmst.apples == 1 assert mmst.oranges == 0 assert mmst.zebras == 0 mmst.zebras = 9001 assert mmst.apples == 1 assert mmst.oranges == 0 assert mmst.zebras == 9001
<commit_before>import mmstats def test_uint(): class MyStats(mmstats.MmStats): apples = mmstats.UIntStat() oranges = mmstats.UIntStat() mmst = MyStats() # Basic format assert mmst.mmap[0] == '\x01' assert mmst.mmap.find('applesL') != -1 assert mmst.mmap.find('orangesL') != -1 # Stat manipulation assert mmst.apples == 0 assert mmst.oranges == 0 mmst.apples = 1 assert mmst.apples == 1 assert mmst.oranges == 0 <commit_msg>Make basic test a bit more thorough<commit_after>import mmstats def test_uint(): class MyStats(mmstats.MmStats): zebras = mmstats.UIntStat() apples = mmstats.UIntStat() oranges = mmstats.UIntStat() mmst = MyStats() # Basic format assert mmst.mmap[0] == '\x01' assert mmst.mmap.find('applesL') != -1 assert mmst.mmap.find('orangesL') != -1 assert mmst.mmap.find('zebrasL') != -1 # Stat manipulation assert mmst.apples == 0 assert mmst.oranges == 0 assert mmst.zebras == 0 mmst.apples = 1 assert mmst.apples == 1 assert mmst.oranges == 0 assert mmst.zebras == 0 mmst.zebras = 9001 assert mmst.apples == 1 assert mmst.oranges == 0 assert mmst.zebras == 9001
18c287a9cfba6e06e1e41db5e23f57b58db64980
command_line/small_molecule.py
command_line/small_molecule.py
import sys from xia2_main import run if __name__ == '__main__': if 'small_molecule=true' not in sys.argv: sys.argv.insert(1, 'small_molecule=true') run()
from __future__ import division if __name__ == '__main__': import sys if 'small_molecule=true' not in sys.argv: sys.argv.insert(1, 'small_molecule=true') # clean up command-line so we know what was happening i.e. xia2.small_molecule # becomes xia2 small_molecule=true (and other things) but without repeating # itself import libtbx.load_env libtbx.env.dispatcher_name = 'xia2' from xia2_main import run run()
Reduce redundancy in corrected command-line; replace dispatcher name with xia2 from xia2.small molecule for print out
Reduce redundancy in corrected command-line; replace dispatcher name with xia2 from xia2.small molecule for print out
Python
bsd-3-clause
xia2/xia2,xia2/xia2
import sys from xia2_main import run if __name__ == '__main__': if 'small_molecule=true' not in sys.argv: sys.argv.insert(1, 'small_molecule=true') run() Reduce redundancy in corrected command-line; replace dispatcher name with xia2 from xia2.small molecule for print out
from __future__ import division if __name__ == '__main__': import sys if 'small_molecule=true' not in sys.argv: sys.argv.insert(1, 'small_molecule=true') # clean up command-line so we know what was happening i.e. xia2.small_molecule # becomes xia2 small_molecule=true (and other things) but without repeating # itself import libtbx.load_env libtbx.env.dispatcher_name = 'xia2' from xia2_main import run run()
<commit_before>import sys from xia2_main import run if __name__ == '__main__': if 'small_molecule=true' not in sys.argv: sys.argv.insert(1, 'small_molecule=true') run() <commit_msg>Reduce redundancy in corrected command-line; replace dispatcher name with xia2 from xia2.small molecule for print out<commit_after>
from __future__ import division if __name__ == '__main__': import sys if 'small_molecule=true' not in sys.argv: sys.argv.insert(1, 'small_molecule=true') # clean up command-line so we know what was happening i.e. xia2.small_molecule # becomes xia2 small_molecule=true (and other things) but without repeating # itself import libtbx.load_env libtbx.env.dispatcher_name = 'xia2' from xia2_main import run run()
import sys from xia2_main import run if __name__ == '__main__': if 'small_molecule=true' not in sys.argv: sys.argv.insert(1, 'small_molecule=true') run() Reduce redundancy in corrected command-line; replace dispatcher name with xia2 from xia2.small molecule for print outfrom __future__ import division if __name__ == '__main__': import sys if 'small_molecule=true' not in sys.argv: sys.argv.insert(1, 'small_molecule=true') # clean up command-line so we know what was happening i.e. xia2.small_molecule # becomes xia2 small_molecule=true (and other things) but without repeating # itself import libtbx.load_env libtbx.env.dispatcher_name = 'xia2' from xia2_main import run run()
<commit_before>import sys from xia2_main import run if __name__ == '__main__': if 'small_molecule=true' not in sys.argv: sys.argv.insert(1, 'small_molecule=true') run() <commit_msg>Reduce redundancy in corrected command-line; replace dispatcher name with xia2 from xia2.small molecule for print out<commit_after>from __future__ import division if __name__ == '__main__': import sys if 'small_molecule=true' not in sys.argv: sys.argv.insert(1, 'small_molecule=true') # clean up command-line so we know what was happening i.e. xia2.small_molecule # becomes xia2 small_molecule=true (and other things) but without repeating # itself import libtbx.load_env libtbx.env.dispatcher_name = 'xia2' from xia2_main import run run()
986675f8b415ddbe3d9bccc9d9c88ee00f9d589c
tldextract_app/handlers.py
tldextract_app/handlers.py
from cStringIO import StringIO import tldextract import web try: import json except ImportError: from django.utils import simplejson as json urls = ( '/api/extract', 'Extract', '/api/re', 'TheRegex', '/test', 'Test', ) class Extract: def GET(self): url = web.input(url='').url if not url: return web.webapi.badrequest() ext = tldextract.extract(url)._asdict() web.header('Content-Type', 'application/json') return json.dumps(ext) + '\n' class TheRegex: def GET(self): extractor = tldextract.tldextract._get_extract_tld_re() web.header('Content-Type', 'text/html; charset=utf-8') return '<br/>'.join(extractor.tlds) class Test: def GET(self): stream = StringIO() tldextract.tldextract.run_tests(stream) return stream.getvalue() app = web.application(urls, globals()) main = app.cgirun()
from cStringIO import StringIO import tldextract import web try: import json except ImportError: from django.utils import simplejson as json urls = ( '/api/extract', 'Extract', '/api/re', 'TLDSet', '/test', 'Test', ) class Extract: def GET(self): url = web.input(url='').url if not url: return web.webapi.badrequest() ext = tldextract.extract(url)._asdict() web.header('Content-Type', 'application/json') return json.dumps(ext) + '\n' class TLDSet: def GET(self): extractor = tldextract.tldextract._get_tld_extractor() web.header('Content-Type', 'text/html; charset=utf-8') return '<br/>'.join(sorted(extractor.tlds)) class Test: def GET(self): stream = StringIO() tldextract.tldextract.run_tests(stream) return stream.getvalue() app = web.application(urls, globals()) main = app.cgirun()
Fix viewing live TLD definitions on GAE
Fix viewing live TLD definitions on GAE
Python
bsd-3-clause
john-kurkowski/tldextract,jvrsantacruz/tldextract,TeamHG-Memex/tldextract,pombredanne/tldextract,jvanasco/tldextract
from cStringIO import StringIO import tldextract import web try: import json except ImportError: from django.utils import simplejson as json urls = ( '/api/extract', 'Extract', '/api/re', 'TheRegex', '/test', 'Test', ) class Extract: def GET(self): url = web.input(url='').url if not url: return web.webapi.badrequest() ext = tldextract.extract(url)._asdict() web.header('Content-Type', 'application/json') return json.dumps(ext) + '\n' class TheRegex: def GET(self): extractor = tldextract.tldextract._get_extract_tld_re() web.header('Content-Type', 'text/html; charset=utf-8') return '<br/>'.join(extractor.tlds) class Test: def GET(self): stream = StringIO() tldextract.tldextract.run_tests(stream) return stream.getvalue() app = web.application(urls, globals()) main = app.cgirun() Fix viewing live TLD definitions on GAE
from cStringIO import StringIO import tldextract import web try: import json except ImportError: from django.utils import simplejson as json urls = ( '/api/extract', 'Extract', '/api/re', 'TLDSet', '/test', 'Test', ) class Extract: def GET(self): url = web.input(url='').url if not url: return web.webapi.badrequest() ext = tldextract.extract(url)._asdict() web.header('Content-Type', 'application/json') return json.dumps(ext) + '\n' class TLDSet: def GET(self): extractor = tldextract.tldextract._get_tld_extractor() web.header('Content-Type', 'text/html; charset=utf-8') return '<br/>'.join(sorted(extractor.tlds)) class Test: def GET(self): stream = StringIO() tldextract.tldextract.run_tests(stream) return stream.getvalue() app = web.application(urls, globals()) main = app.cgirun()
<commit_before>from cStringIO import StringIO import tldextract import web try: import json except ImportError: from django.utils import simplejson as json urls = ( '/api/extract', 'Extract', '/api/re', 'TheRegex', '/test', 'Test', ) class Extract: def GET(self): url = web.input(url='').url if not url: return web.webapi.badrequest() ext = tldextract.extract(url)._asdict() web.header('Content-Type', 'application/json') return json.dumps(ext) + '\n' class TheRegex: def GET(self): extractor = tldextract.tldextract._get_extract_tld_re() web.header('Content-Type', 'text/html; charset=utf-8') return '<br/>'.join(extractor.tlds) class Test: def GET(self): stream = StringIO() tldextract.tldextract.run_tests(stream) return stream.getvalue() app = web.application(urls, globals()) main = app.cgirun() <commit_msg>Fix viewing live TLD definitions on GAE<commit_after>
from cStringIO import StringIO import tldextract import web try: import json except ImportError: from django.utils import simplejson as json urls = ( '/api/extract', 'Extract', '/api/re', 'TLDSet', '/test', 'Test', ) class Extract: def GET(self): url = web.input(url='').url if not url: return web.webapi.badrequest() ext = tldextract.extract(url)._asdict() web.header('Content-Type', 'application/json') return json.dumps(ext) + '\n' class TLDSet: def GET(self): extractor = tldextract.tldextract._get_tld_extractor() web.header('Content-Type', 'text/html; charset=utf-8') return '<br/>'.join(sorted(extractor.tlds)) class Test: def GET(self): stream = StringIO() tldextract.tldextract.run_tests(stream) return stream.getvalue() app = web.application(urls, globals()) main = app.cgirun()
from cStringIO import StringIO import tldextract import web try: import json except ImportError: from django.utils import simplejson as json urls = ( '/api/extract', 'Extract', '/api/re', 'TheRegex', '/test', 'Test', ) class Extract: def GET(self): url = web.input(url='').url if not url: return web.webapi.badrequest() ext = tldextract.extract(url)._asdict() web.header('Content-Type', 'application/json') return json.dumps(ext) + '\n' class TheRegex: def GET(self): extractor = tldextract.tldextract._get_extract_tld_re() web.header('Content-Type', 'text/html; charset=utf-8') return '<br/>'.join(extractor.tlds) class Test: def GET(self): stream = StringIO() tldextract.tldextract.run_tests(stream) return stream.getvalue() app = web.application(urls, globals()) main = app.cgirun() Fix viewing live TLD definitions on GAEfrom cStringIO import StringIO import tldextract import web try: import json except ImportError: from django.utils import simplejson as json urls = ( '/api/extract', 'Extract', '/api/re', 'TLDSet', '/test', 'Test', ) class Extract: def GET(self): url = web.input(url='').url if not url: return web.webapi.badrequest() ext = tldextract.extract(url)._asdict() web.header('Content-Type', 'application/json') return json.dumps(ext) + '\n' class TLDSet: def GET(self): extractor = tldextract.tldextract._get_tld_extractor() web.header('Content-Type', 'text/html; charset=utf-8') return '<br/>'.join(sorted(extractor.tlds)) class Test: def GET(self): stream = StringIO() tldextract.tldextract.run_tests(stream) return stream.getvalue() app = web.application(urls, globals()) main = app.cgirun()
<commit_before>from cStringIO import StringIO import tldextract import web try: import json except ImportError: from django.utils import simplejson as json urls = ( '/api/extract', 'Extract', '/api/re', 'TheRegex', '/test', 'Test', ) class Extract: def GET(self): url = web.input(url='').url if not url: return web.webapi.badrequest() ext = tldextract.extract(url)._asdict() web.header('Content-Type', 'application/json') return json.dumps(ext) + '\n' class TheRegex: def GET(self): extractor = tldextract.tldextract._get_extract_tld_re() web.header('Content-Type', 'text/html; charset=utf-8') return '<br/>'.join(extractor.tlds) class Test: def GET(self): stream = StringIO() tldextract.tldextract.run_tests(stream) return stream.getvalue() app = web.application(urls, globals()) main = app.cgirun() <commit_msg>Fix viewing live TLD definitions on GAE<commit_after>from cStringIO import StringIO import tldextract import web try: import json except ImportError: from django.utils import simplejson as json urls = ( '/api/extract', 'Extract', '/api/re', 'TLDSet', '/test', 'Test', ) class Extract: def GET(self): url = web.input(url='').url if not url: return web.webapi.badrequest() ext = tldextract.extract(url)._asdict() web.header('Content-Type', 'application/json') return json.dumps(ext) + '\n' class TLDSet: def GET(self): extractor = tldextract.tldextract._get_tld_extractor() web.header('Content-Type', 'text/html; charset=utf-8') return '<br/>'.join(sorted(extractor.tlds)) class Test: def GET(self): stream = StringIO() tldextract.tldextract.run_tests(stream) return stream.getvalue() app = web.application(urls, globals()) main = app.cgirun()
194449e880bf50cde799a1853474c8075e4cf5d4
derrida/__init__.py
derrida/__init__.py
__version_info__ = (1, 2, 0, None) # Dot-connect all but the last. Last is dash-connected if not None. __version__ = '.'.join([str(i) for i in __version_info__[:-1]]) if __version_info__[-1] is not None: __version__ += ('-%s' % (__version_info__[-1],)) # context processor to add version to the template environment def context_extras(request): return { # software version 'SW_VERSION': __version__ }
__version_info__ = (1, 3, 0, 'dev') # Dot-connect all but the last. Last is dash-connected if not None. __version__ = '.'.join([str(i) for i in __version_info__[:-1]]) if __version_info__[-1] is not None: __version__ += ('-%s' % (__version_info__[-1],)) # context processor to add version to the template environment def context_extras(request): return { # software version 'SW_VERSION': __version__ }
Set develop version to 1.3-dev
Set develop version to 1.3-dev
Python
apache-2.0
Princeton-CDH/derrida-django,Princeton-CDH/derrida-django,Princeton-CDH/derrida-django,Princeton-CDH/derrida-django
__version_info__ = (1, 2, 0, None) # Dot-connect all but the last. Last is dash-connected if not None. __version__ = '.'.join([str(i) for i in __version_info__[:-1]]) if __version_info__[-1] is not None: __version__ += ('-%s' % (__version_info__[-1],)) # context processor to add version to the template environment def context_extras(request): return { # software version 'SW_VERSION': __version__ } Set develop version to 1.3-dev
__version_info__ = (1, 3, 0, 'dev') # Dot-connect all but the last. Last is dash-connected if not None. __version__ = '.'.join([str(i) for i in __version_info__[:-1]]) if __version_info__[-1] is not None: __version__ += ('-%s' % (__version_info__[-1],)) # context processor to add version to the template environment def context_extras(request): return { # software version 'SW_VERSION': __version__ }
<commit_before>__version_info__ = (1, 2, 0, None) # Dot-connect all but the last. Last is dash-connected if not None. __version__ = '.'.join([str(i) for i in __version_info__[:-1]]) if __version_info__[-1] is not None: __version__ += ('-%s' % (__version_info__[-1],)) # context processor to add version to the template environment def context_extras(request): return { # software version 'SW_VERSION': __version__ } <commit_msg>Set develop version to 1.3-dev<commit_after>
__version_info__ = (1, 3, 0, 'dev') # Dot-connect all but the last. Last is dash-connected if not None. __version__ = '.'.join([str(i) for i in __version_info__[:-1]]) if __version_info__[-1] is not None: __version__ += ('-%s' % (__version_info__[-1],)) # context processor to add version to the template environment def context_extras(request): return { # software version 'SW_VERSION': __version__ }
__version_info__ = (1, 2, 0, None) # Dot-connect all but the last. Last is dash-connected if not None. __version__ = '.'.join([str(i) for i in __version_info__[:-1]]) if __version_info__[-1] is not None: __version__ += ('-%s' % (__version_info__[-1],)) # context processor to add version to the template environment def context_extras(request): return { # software version 'SW_VERSION': __version__ } Set develop version to 1.3-dev__version_info__ = (1, 3, 0, 'dev') # Dot-connect all but the last. Last is dash-connected if not None. __version__ = '.'.join([str(i) for i in __version_info__[:-1]]) if __version_info__[-1] is not None: __version__ += ('-%s' % (__version_info__[-1],)) # context processor to add version to the template environment def context_extras(request): return { # software version 'SW_VERSION': __version__ }
<commit_before>__version_info__ = (1, 2, 0, None) # Dot-connect all but the last. Last is dash-connected if not None. __version__ = '.'.join([str(i) for i in __version_info__[:-1]]) if __version_info__[-1] is not None: __version__ += ('-%s' % (__version_info__[-1],)) # context processor to add version to the template environment def context_extras(request): return { # software version 'SW_VERSION': __version__ } <commit_msg>Set develop version to 1.3-dev<commit_after>__version_info__ = (1, 3, 0, 'dev') # Dot-connect all but the last. Last is dash-connected if not None. __version__ = '.'.join([str(i) for i in __version_info__[:-1]]) if __version_info__[-1] is not None: __version__ += ('-%s' % (__version_info__[-1],)) # context processor to add version to the template environment def context_extras(request): return { # software version 'SW_VERSION': __version__ }
3fc765bad65e405f6303bf5ea76e8b4f6de17c13
Instanssi/admin_programme/forms.py
Instanssi/admin_programme/forms.py
# -*- coding: utf-8 -*- from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Fieldset, ButtonHolder from Instanssi.ext_programme.models import ProgrammeEvent class ProgrammeEventForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ProgrammeEventForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Fieldset( u'Tapahtuma', 'event_type', 'title', 'description', 'start', 'end', 'presenters', 'presenters_titles', 'icon_original', 'email', 'home_url', 'twitter_url', 'github_url', 'facebook_url', 'linkedin_url', 'wiki_url', 'gplus_url', ButtonHolder ( Submit('submit', u'Tallenna') ) ) ) class Meta: model = ProgrammeEvent exclude = ('event','icon_small',)
# -*- coding: utf-8 -*- from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Fieldset, ButtonHolder from Instanssi.ext_programme.models import ProgrammeEvent class ProgrammeEventForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ProgrammeEventForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Fieldset( u'Tapahtuma', 'event_type', 'title', 'description', 'start', 'end', 'presenters', 'presenters_titles', 'icon_original', 'email', 'home_url', 'twitter_url', 'github_url', 'facebook_url', 'linkedin_url', 'wiki_url', 'gplus_url', 'active', ButtonHolder ( Submit('submit', u'Tallenna') ) ) ) class Meta: model = ProgrammeEvent exclude = ('event','icon_small',)
Add active field to form.
admin_programme: Add active field to form.
Python
mit
Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org
# -*- coding: utf-8 -*- from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Fieldset, ButtonHolder from Instanssi.ext_programme.models import ProgrammeEvent class ProgrammeEventForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ProgrammeEventForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Fieldset( u'Tapahtuma', 'event_type', 'title', 'description', 'start', 'end', 'presenters', 'presenters_titles', 'icon_original', 'email', 'home_url', 'twitter_url', 'github_url', 'facebook_url', 'linkedin_url', 'wiki_url', 'gplus_url', ButtonHolder ( Submit('submit', u'Tallenna') ) ) ) class Meta: model = ProgrammeEvent exclude = ('event','icon_small',) admin_programme: Add active field to form.
# -*- coding: utf-8 -*- from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Fieldset, ButtonHolder from Instanssi.ext_programme.models import ProgrammeEvent class ProgrammeEventForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ProgrammeEventForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Fieldset( u'Tapahtuma', 'event_type', 'title', 'description', 'start', 'end', 'presenters', 'presenters_titles', 'icon_original', 'email', 'home_url', 'twitter_url', 'github_url', 'facebook_url', 'linkedin_url', 'wiki_url', 'gplus_url', 'active', ButtonHolder ( Submit('submit', u'Tallenna') ) ) ) class Meta: model = ProgrammeEvent exclude = ('event','icon_small',)
<commit_before># -*- coding: utf-8 -*- from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Fieldset, ButtonHolder from Instanssi.ext_programme.models import ProgrammeEvent class ProgrammeEventForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ProgrammeEventForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Fieldset( u'Tapahtuma', 'event_type', 'title', 'description', 'start', 'end', 'presenters', 'presenters_titles', 'icon_original', 'email', 'home_url', 'twitter_url', 'github_url', 'facebook_url', 'linkedin_url', 'wiki_url', 'gplus_url', ButtonHolder ( Submit('submit', u'Tallenna') ) ) ) class Meta: model = ProgrammeEvent exclude = ('event','icon_small',) <commit_msg>admin_programme: Add active field to form.<commit_after>
# -*- coding: utf-8 -*- from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Fieldset, ButtonHolder from Instanssi.ext_programme.models import ProgrammeEvent class ProgrammeEventForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ProgrammeEventForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Fieldset( u'Tapahtuma', 'event_type', 'title', 'description', 'start', 'end', 'presenters', 'presenters_titles', 'icon_original', 'email', 'home_url', 'twitter_url', 'github_url', 'facebook_url', 'linkedin_url', 'wiki_url', 'gplus_url', 'active', ButtonHolder ( Submit('submit', u'Tallenna') ) ) ) class Meta: model = ProgrammeEvent exclude = ('event','icon_small',)
# -*- coding: utf-8 -*- from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Fieldset, ButtonHolder from Instanssi.ext_programme.models import ProgrammeEvent class ProgrammeEventForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ProgrammeEventForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Fieldset( u'Tapahtuma', 'event_type', 'title', 'description', 'start', 'end', 'presenters', 'presenters_titles', 'icon_original', 'email', 'home_url', 'twitter_url', 'github_url', 'facebook_url', 'linkedin_url', 'wiki_url', 'gplus_url', ButtonHolder ( Submit('submit', u'Tallenna') ) ) ) class Meta: model = ProgrammeEvent exclude = ('event','icon_small',) admin_programme: Add active field to form.# -*- coding: utf-8 -*- from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Fieldset, ButtonHolder from Instanssi.ext_programme.models import ProgrammeEvent class ProgrammeEventForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ProgrammeEventForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Fieldset( u'Tapahtuma', 'event_type', 'title', 'description', 'start', 'end', 'presenters', 'presenters_titles', 'icon_original', 'email', 'home_url', 'twitter_url', 'github_url', 'facebook_url', 'linkedin_url', 'wiki_url', 'gplus_url', 'active', ButtonHolder ( Submit('submit', u'Tallenna') ) ) ) class Meta: model = ProgrammeEvent exclude = ('event','icon_small',)
<commit_before># -*- coding: utf-8 -*- from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Fieldset, ButtonHolder from Instanssi.ext_programme.models import ProgrammeEvent class ProgrammeEventForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ProgrammeEventForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Fieldset( u'Tapahtuma', 'event_type', 'title', 'description', 'start', 'end', 'presenters', 'presenters_titles', 'icon_original', 'email', 'home_url', 'twitter_url', 'github_url', 'facebook_url', 'linkedin_url', 'wiki_url', 'gplus_url', ButtonHolder ( Submit('submit', u'Tallenna') ) ) ) class Meta: model = ProgrammeEvent exclude = ('event','icon_small',) <commit_msg>admin_programme: Add active field to form.<commit_after># -*- coding: utf-8 -*- from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Fieldset, ButtonHolder from Instanssi.ext_programme.models import ProgrammeEvent class ProgrammeEventForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ProgrammeEventForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Fieldset( u'Tapahtuma', 'event_type', 'title', 'description', 'start', 'end', 'presenters', 'presenters_titles', 'icon_original', 'email', 'home_url', 'twitter_url', 'github_url', 'facebook_url', 'linkedin_url', 'wiki_url', 'gplus_url', 'active', ButtonHolder ( Submit('submit', u'Tallenna') ) ) ) class Meta: model = ProgrammeEvent exclude = ('event','icon_small',)
f14107b723bcf62b327b10d8726b2bf8ef2031eb
tests/test_manifest_delivery_base.py
tests/test_manifest_delivery_base.py
import yaml from app.config import QueueNames def test_queue_names_set_in_manifest_delivery_base_correctly(): with open("manifest-delivery-base.yml", 'r') as stream: search = ' -Q ' yml_commands = [y['command'] for y in yaml.load(stream)['applications']] watched_queues = set() for command in yml_commands: start_of_queue_arg = command.find(search) if start_of_queue_arg > 0: start_of_queue_names = start_of_queue_arg + len(search) queues = command[start_of_queue_names:].split(',') watched_queues.update(queues) # ses-callbacks isn't used in api (only used in SNS lambda) ignored_queues = {'ses-callbacks'} watched_queues -= ignored_queues assert watched_queues == set(QueueNames.all_queues())
import yaml from app.config import QueueNames def test_queue_names_set_in_manifest_delivery_base_correctly(): with open("manifest-delivery-base.yml", 'r') as stream: search = ' -Q ' yml_commands = [y['command'] for y in yaml.load(stream)['applications']] watched_queues = set() for command in yml_commands: start_of_queue_arg = command.find(search) if start_of_queue_arg > 0: start_of_queue_names = start_of_queue_arg + len(search) queues = command[start_of_queue_names:].split(',') for q in queues: if "2>" in q: q = q.split("2>")[0].strip() watched_queues.add(q) # ses-callbacks isn't used in api (only used in SNS lambda) ignored_queues = {'ses-callbacks'} watched_queues -= ignored_queues assert watched_queues == set(QueueNames.all_queues())
Fix test that checks queues
Fix test that checks queues
Python
mit
alphagov/notifications-api,alphagov/notifications-api
import yaml from app.config import QueueNames def test_queue_names_set_in_manifest_delivery_base_correctly(): with open("manifest-delivery-base.yml", 'r') as stream: search = ' -Q ' yml_commands = [y['command'] for y in yaml.load(stream)['applications']] watched_queues = set() for command in yml_commands: start_of_queue_arg = command.find(search) if start_of_queue_arg > 0: start_of_queue_names = start_of_queue_arg + len(search) queues = command[start_of_queue_names:].split(',') watched_queues.update(queues) # ses-callbacks isn't used in api (only used in SNS lambda) ignored_queues = {'ses-callbacks'} watched_queues -= ignored_queues assert watched_queues == set(QueueNames.all_queues()) Fix test that checks queues
import yaml from app.config import QueueNames def test_queue_names_set_in_manifest_delivery_base_correctly(): with open("manifest-delivery-base.yml", 'r') as stream: search = ' -Q ' yml_commands = [y['command'] for y in yaml.load(stream)['applications']] watched_queues = set() for command in yml_commands: start_of_queue_arg = command.find(search) if start_of_queue_arg > 0: start_of_queue_names = start_of_queue_arg + len(search) queues = command[start_of_queue_names:].split(',') for q in queues: if "2>" in q: q = q.split("2>")[0].strip() watched_queues.add(q) # ses-callbacks isn't used in api (only used in SNS lambda) ignored_queues = {'ses-callbacks'} watched_queues -= ignored_queues assert watched_queues == set(QueueNames.all_queues())
<commit_before>import yaml from app.config import QueueNames def test_queue_names_set_in_manifest_delivery_base_correctly(): with open("manifest-delivery-base.yml", 'r') as stream: search = ' -Q ' yml_commands = [y['command'] for y in yaml.load(stream)['applications']] watched_queues = set() for command in yml_commands: start_of_queue_arg = command.find(search) if start_of_queue_arg > 0: start_of_queue_names = start_of_queue_arg + len(search) queues = command[start_of_queue_names:].split(',') watched_queues.update(queues) # ses-callbacks isn't used in api (only used in SNS lambda) ignored_queues = {'ses-callbacks'} watched_queues -= ignored_queues assert watched_queues == set(QueueNames.all_queues()) <commit_msg>Fix test that checks queues<commit_after>
import yaml from app.config import QueueNames def test_queue_names_set_in_manifest_delivery_base_correctly(): with open("manifest-delivery-base.yml", 'r') as stream: search = ' -Q ' yml_commands = [y['command'] for y in yaml.load(stream)['applications']] watched_queues = set() for command in yml_commands: start_of_queue_arg = command.find(search) if start_of_queue_arg > 0: start_of_queue_names = start_of_queue_arg + len(search) queues = command[start_of_queue_names:].split(',') for q in queues: if "2>" in q: q = q.split("2>")[0].strip() watched_queues.add(q) # ses-callbacks isn't used in api (only used in SNS lambda) ignored_queues = {'ses-callbacks'} watched_queues -= ignored_queues assert watched_queues == set(QueueNames.all_queues())
import yaml from app.config import QueueNames def test_queue_names_set_in_manifest_delivery_base_correctly(): with open("manifest-delivery-base.yml", 'r') as stream: search = ' -Q ' yml_commands = [y['command'] for y in yaml.load(stream)['applications']] watched_queues = set() for command in yml_commands: start_of_queue_arg = command.find(search) if start_of_queue_arg > 0: start_of_queue_names = start_of_queue_arg + len(search) queues = command[start_of_queue_names:].split(',') watched_queues.update(queues) # ses-callbacks isn't used in api (only used in SNS lambda) ignored_queues = {'ses-callbacks'} watched_queues -= ignored_queues assert watched_queues == set(QueueNames.all_queues()) Fix test that checks queuesimport yaml from app.config import QueueNames def test_queue_names_set_in_manifest_delivery_base_correctly(): with open("manifest-delivery-base.yml", 'r') as stream: search = ' -Q ' yml_commands = [y['command'] for y in yaml.load(stream)['applications']] watched_queues = set() for command in yml_commands: start_of_queue_arg = command.find(search) if start_of_queue_arg > 0: start_of_queue_names = start_of_queue_arg + len(search) queues = command[start_of_queue_names:].split(',') for q in queues: if "2>" in q: q = q.split("2>")[0].strip() watched_queues.add(q) # ses-callbacks isn't used in api (only used in SNS lambda) ignored_queues = {'ses-callbacks'} watched_queues -= ignored_queues assert watched_queues == set(QueueNames.all_queues())
<commit_before>import yaml from app.config import QueueNames def test_queue_names_set_in_manifest_delivery_base_correctly(): with open("manifest-delivery-base.yml", 'r') as stream: search = ' -Q ' yml_commands = [y['command'] for y in yaml.load(stream)['applications']] watched_queues = set() for command in yml_commands: start_of_queue_arg = command.find(search) if start_of_queue_arg > 0: start_of_queue_names = start_of_queue_arg + len(search) queues = command[start_of_queue_names:].split(',') watched_queues.update(queues) # ses-callbacks isn't used in api (only used in SNS lambda) ignored_queues = {'ses-callbacks'} watched_queues -= ignored_queues assert watched_queues == set(QueueNames.all_queues()) <commit_msg>Fix test that checks queues<commit_after>import yaml from app.config import QueueNames def test_queue_names_set_in_manifest_delivery_base_correctly(): with open("manifest-delivery-base.yml", 'r') as stream: search = ' -Q ' yml_commands = [y['command'] for y in yaml.load(stream)['applications']] watched_queues = set() for command in yml_commands: start_of_queue_arg = command.find(search) if start_of_queue_arg > 0: start_of_queue_names = start_of_queue_arg + len(search) queues = command[start_of_queue_names:].split(',') for q in queues: if "2>" in q: q = q.split("2>")[0].strip() watched_queues.add(q) # ses-callbacks isn't used in api (only used in SNS lambda) ignored_queues = {'ses-callbacks'} watched_queues -= ignored_queues assert watched_queues == set(QueueNames.all_queues())
e889b37d6db1ca29e874e11cdc122159fe9da136
trigrams.py
trigrams.py
# -*- coding: utf-8 -*- """Generate random story using trigrams.""" import io import string def read_file(): """Open and read file input.""" f = io.open('sherlock_small.txt', 'r') lines = ''.join(f.readlines()) print(lines) return lines def strip_punct(text): """Do stuff.""" # strip punct from # print(type(text)) for c in string.punctuation: text.replace(c, ' ') text = read_file() strip_punct(text)
# -*- coding: utf-8 -*- """Generate random story using trigrams.""" import io import string def read_file(): """Open and read file input.""" f = io.open('sherlock_small.txt', 'r') lines = ''.join(f.readlines()) # print(lines) return lines def strip_punct(text): """Do stuff.""" # strip punct from # print(type(text)) for c in string.punctuation: text = text.replace(c, ' ') return text text = read_file() print(strip_punct(text))
Add return statement to strip_punct
Add return statement to strip_punct
Python
mit
bgarnaat/401_trigrams
# -*- coding: utf-8 -*- """Generate random story using trigrams.""" import io import string def read_file(): """Open and read file input.""" f = io.open('sherlock_small.txt', 'r') lines = ''.join(f.readlines()) print(lines) return lines def strip_punct(text): """Do stuff.""" # strip punct from # print(type(text)) for c in string.punctuation: text.replace(c, ' ') text = read_file() strip_punct(text) Add return statement to strip_punct
# -*- coding: utf-8 -*- """Generate random story using trigrams.""" import io import string def read_file(): """Open and read file input.""" f = io.open('sherlock_small.txt', 'r') lines = ''.join(f.readlines()) # print(lines) return lines def strip_punct(text): """Do stuff.""" # strip punct from # print(type(text)) for c in string.punctuation: text = text.replace(c, ' ') return text text = read_file() print(strip_punct(text))
<commit_before># -*- coding: utf-8 -*- """Generate random story using trigrams.""" import io import string def read_file(): """Open and read file input.""" f = io.open('sherlock_small.txt', 'r') lines = ''.join(f.readlines()) print(lines) return lines def strip_punct(text): """Do stuff.""" # strip punct from # print(type(text)) for c in string.punctuation: text.replace(c, ' ') text = read_file() strip_punct(text) <commit_msg>Add return statement to strip_punct<commit_after>
# -*- coding: utf-8 -*- """Generate random story using trigrams.""" import io import string def read_file(): """Open and read file input.""" f = io.open('sherlock_small.txt', 'r') lines = ''.join(f.readlines()) # print(lines) return lines def strip_punct(text): """Do stuff.""" # strip punct from # print(type(text)) for c in string.punctuation: text = text.replace(c, ' ') return text text = read_file() print(strip_punct(text))
# -*- coding: utf-8 -*- """Generate random story using trigrams.""" import io import string def read_file(): """Open and read file input.""" f = io.open('sherlock_small.txt', 'r') lines = ''.join(f.readlines()) print(lines) return lines def strip_punct(text): """Do stuff.""" # strip punct from # print(type(text)) for c in string.punctuation: text.replace(c, ' ') text = read_file() strip_punct(text) Add return statement to strip_punct# -*- coding: utf-8 -*- """Generate random story using trigrams.""" import io import string def read_file(): """Open and read file input.""" f = io.open('sherlock_small.txt', 'r') lines = ''.join(f.readlines()) # print(lines) return lines def strip_punct(text): """Do stuff.""" # strip punct from # print(type(text)) for c in string.punctuation: text = text.replace(c, ' ') return text text = read_file() print(strip_punct(text))
<commit_before># -*- coding: utf-8 -*- """Generate random story using trigrams.""" import io import string def read_file(): """Open and read file input.""" f = io.open('sherlock_small.txt', 'r') lines = ''.join(f.readlines()) print(lines) return lines def strip_punct(text): """Do stuff.""" # strip punct from # print(type(text)) for c in string.punctuation: text.replace(c, ' ') text = read_file() strip_punct(text) <commit_msg>Add return statement to strip_punct<commit_after># -*- coding: utf-8 -*- """Generate random story using trigrams.""" import io import string def read_file(): """Open and read file input.""" f = io.open('sherlock_small.txt', 'r') lines = ''.join(f.readlines()) # print(lines) return lines def strip_punct(text): """Do stuff.""" # strip punct from # print(type(text)) for c in string.punctuation: text = text.replace(c, ' ') return text text = read_file() print(strip_punct(text))
3375ac1b2f44a18db1b5014de72fe048005c954c
txircd/modules/cmd_pass.py
txircd/modules/cmd_pass.py
from twisted.words.protocols import irc from txircd.modbase import Command, Module class PassCommand(Command, Module): def onUse(self, user, params): if user.registered == 0: user.sendMessage(irc.ERR_ALREADYREGISTRED, ":Unauthorized command (already registered)") return if not params: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "PASS", ":Not enough parameters") return user.password = params[0] def onRegister(self, user): if self.ircd.server_password and self.ircd.server_password != user.password: user.sendMessage("ERROR", ":Closing link: ({}@{}) [Access denied]".format(user.username, user.hostname), to=None, prefix=None) return False def Spawner(object): def __init__(self, ircd): self.ircd = ircd self.passcmd = PassCommand() def spawn(): return { "actions": { "register": [self.passcmd.onRegister] }, "commands": { "PASS": self.passcmd } } def cleanup(): self.ircd.actions.remove(self.passcmd) del self.ircd.commands["PASS"] del self.passcmd
from twisted.words.protocols import irc from txircd.modbase import Command, Module class PassCommand(Command, Module): def onUse(self, user, data): user.password = data["password"] def processParams(self, user, params): if user.registered == 0: user.sendMessage(irc.ERR_ALREADYREGISTRED, ":Unauthorized command (already registered)") return {} if not params: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "PASS", ":Not enough parameters") return {} return { "user": user, "password": params[0] } def onRegister(self, user): if self.ircd.server_password and self.ircd.server_password != user.password: user.sendMessage("ERROR", ":Closing link: ({}@{}) [Access denied]".format(user.username, user.hostname), to=None, prefix=None) return False def Spawner(object): def __init__(self, ircd): self.ircd = ircd self.passcmd = PassCommand() def spawn(): return { "actions": { "register": [self.passcmd.onRegister] }, "commands": { "PASS": self.passcmd } } def cleanup(): self.ircd.actions.remove(self.passcmd) del self.ircd.commands["PASS"] del self.passcmd
Make the PASS command take advantage of processParams and handle the data dict correctly
Make the PASS command take advantage of processParams and handle the data dict correctly
Python
bsd-3-clause
DesertBus/txircd,Heufneutje/txircd,ElementalAlchemist/txircd
from twisted.words.protocols import irc from txircd.modbase import Command, Module class PassCommand(Command, Module): def onUse(self, user, params): if user.registered == 0: user.sendMessage(irc.ERR_ALREADYREGISTRED, ":Unauthorized command (already registered)") return if not params: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "PASS", ":Not enough parameters") return user.password = params[0] def onRegister(self, user): if self.ircd.server_password and self.ircd.server_password != user.password: user.sendMessage("ERROR", ":Closing link: ({}@{}) [Access denied]".format(user.username, user.hostname), to=None, prefix=None) return False def Spawner(object): def __init__(self, ircd): self.ircd = ircd self.passcmd = PassCommand() def spawn(): return { "actions": { "register": [self.passcmd.onRegister] }, "commands": { "PASS": self.passcmd } } def cleanup(): self.ircd.actions.remove(self.passcmd) del self.ircd.commands["PASS"] del self.passcmdMake the PASS command take advantage of processParams and handle the data dict correctly
from twisted.words.protocols import irc from txircd.modbase import Command, Module class PassCommand(Command, Module): def onUse(self, user, data): user.password = data["password"] def processParams(self, user, params): if user.registered == 0: user.sendMessage(irc.ERR_ALREADYREGISTRED, ":Unauthorized command (already registered)") return {} if not params: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "PASS", ":Not enough parameters") return {} return { "user": user, "password": params[0] } def onRegister(self, user): if self.ircd.server_password and self.ircd.server_password != user.password: user.sendMessage("ERROR", ":Closing link: ({}@{}) [Access denied]".format(user.username, user.hostname), to=None, prefix=None) return False def Spawner(object): def __init__(self, ircd): self.ircd = ircd self.passcmd = PassCommand() def spawn(): return { "actions": { "register": [self.passcmd.onRegister] }, "commands": { "PASS": self.passcmd } } def cleanup(): self.ircd.actions.remove(self.passcmd) del self.ircd.commands["PASS"] del self.passcmd
<commit_before>from twisted.words.protocols import irc from txircd.modbase import Command, Module class PassCommand(Command, Module): def onUse(self, user, params): if user.registered == 0: user.sendMessage(irc.ERR_ALREADYREGISTRED, ":Unauthorized command (already registered)") return if not params: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "PASS", ":Not enough parameters") return user.password = params[0] def onRegister(self, user): if self.ircd.server_password and self.ircd.server_password != user.password: user.sendMessage("ERROR", ":Closing link: ({}@{}) [Access denied]".format(user.username, user.hostname), to=None, prefix=None) return False def Spawner(object): def __init__(self, ircd): self.ircd = ircd self.passcmd = PassCommand() def spawn(): return { "actions": { "register": [self.passcmd.onRegister] }, "commands": { "PASS": self.passcmd } } def cleanup(): self.ircd.actions.remove(self.passcmd) del self.ircd.commands["PASS"] del self.passcmd<commit_msg>Make the PASS command take advantage of processParams and handle the data dict correctly<commit_after>
from twisted.words.protocols import irc from txircd.modbase import Command, Module class PassCommand(Command, Module): def onUse(self, user, data): user.password = data["password"] def processParams(self, user, params): if user.registered == 0: user.sendMessage(irc.ERR_ALREADYREGISTRED, ":Unauthorized command (already registered)") return {} if not params: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "PASS", ":Not enough parameters") return {} return { "user": user, "password": params[0] } def onRegister(self, user): if self.ircd.server_password and self.ircd.server_password != user.password: user.sendMessage("ERROR", ":Closing link: ({}@{}) [Access denied]".format(user.username, user.hostname), to=None, prefix=None) return False def Spawner(object): def __init__(self, ircd): self.ircd = ircd self.passcmd = PassCommand() def spawn(): return { "actions": { "register": [self.passcmd.onRegister] }, "commands": { "PASS": self.passcmd } } def cleanup(): self.ircd.actions.remove(self.passcmd) del self.ircd.commands["PASS"] del self.passcmd
from twisted.words.protocols import irc from txircd.modbase import Command, Module class PassCommand(Command, Module): def onUse(self, user, params): if user.registered == 0: user.sendMessage(irc.ERR_ALREADYREGISTRED, ":Unauthorized command (already registered)") return if not params: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "PASS", ":Not enough parameters") return user.password = params[0] def onRegister(self, user): if self.ircd.server_password and self.ircd.server_password != user.password: user.sendMessage("ERROR", ":Closing link: ({}@{}) [Access denied]".format(user.username, user.hostname), to=None, prefix=None) return False def Spawner(object): def __init__(self, ircd): self.ircd = ircd self.passcmd = PassCommand() def spawn(): return { "actions": { "register": [self.passcmd.onRegister] }, "commands": { "PASS": self.passcmd } } def cleanup(): self.ircd.actions.remove(self.passcmd) del self.ircd.commands["PASS"] del self.passcmdMake the PASS command take advantage of processParams and handle the data dict correctlyfrom twisted.words.protocols import irc from txircd.modbase import Command, Module class PassCommand(Command, Module): def onUse(self, user, data): user.password = data["password"] def processParams(self, user, params): if user.registered == 0: user.sendMessage(irc.ERR_ALREADYREGISTRED, ":Unauthorized command (already registered)") return {} if not params: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "PASS", ":Not enough parameters") return {} return { "user": user, "password": params[0] } def onRegister(self, user): if self.ircd.server_password and self.ircd.server_password != user.password: user.sendMessage("ERROR", ":Closing link: ({}@{}) [Access denied]".format(user.username, user.hostname), to=None, prefix=None) return False def Spawner(object): def __init__(self, ircd): self.ircd = ircd self.passcmd = PassCommand() def spawn(): return { "actions": { "register": [self.passcmd.onRegister] }, "commands": { "PASS": self.passcmd } } def cleanup(): self.ircd.actions.remove(self.passcmd) del self.ircd.commands["PASS"] del self.passcmd
<commit_before>from twisted.words.protocols import irc from txircd.modbase import Command, Module class PassCommand(Command, Module): def onUse(self, user, params): if user.registered == 0: user.sendMessage(irc.ERR_ALREADYREGISTRED, ":Unauthorized command (already registered)") return if not params: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "PASS", ":Not enough parameters") return user.password = params[0] def onRegister(self, user): if self.ircd.server_password and self.ircd.server_password != user.password: user.sendMessage("ERROR", ":Closing link: ({}@{}) [Access denied]".format(user.username, user.hostname), to=None, prefix=None) return False def Spawner(object): def __init__(self, ircd): self.ircd = ircd self.passcmd = PassCommand() def spawn(): return { "actions": { "register": [self.passcmd.onRegister] }, "commands": { "PASS": self.passcmd } } def cleanup(): self.ircd.actions.remove(self.passcmd) del self.ircd.commands["PASS"] del self.passcmd<commit_msg>Make the PASS command take advantage of processParams and handle the data dict correctly<commit_after>from twisted.words.protocols import irc from txircd.modbase import Command, Module class PassCommand(Command, Module): def onUse(self, user, data): user.password = data["password"] def processParams(self, user, params): if user.registered == 0: user.sendMessage(irc.ERR_ALREADYREGISTRED, ":Unauthorized command (already registered)") return {} if not params: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "PASS", ":Not enough parameters") return {} return { "user": user, "password": params[0] } def onRegister(self, user): if self.ircd.server_password and self.ircd.server_password != user.password: user.sendMessage("ERROR", ":Closing link: ({}@{}) [Access denied]".format(user.username, user.hostname), to=None, prefix=None) return False def Spawner(object): def __init__(self, ircd): self.ircd = ircd self.passcmd = PassCommand() def spawn(): return { "actions": { "register": [self.passcmd.onRegister] }, "commands": { "PASS": self.passcmd } } def cleanup(): self.ircd.actions.remove(self.passcmd) del self.ircd.commands["PASS"] del self.passcmd
ff62c68bf26898f6c432ea340d868c0eca005a31
APITaxi/documentation/examples.py
APITaxi/documentation/examples.py
# -*- coding: utf-8 -*- from flask import Blueprint, render_template, url_for as base_url_for from flask.ext.security import current_user from ..extensions import user_datastore from ..models.taxis import Taxi from functools import partial mod = Blueprint('examples', __name__) @mod.route('/documentation/examples') def doc_index(): if not current_user.is_anonymous(): apikeys_operator = set() apikeys_moteur = set() if 'operateur' in current_user.roles: apikeys_operator.add(('your token', current_user.apikey)) if 'moteur' in current_user.roles: apikeys_moteur.add(('your token', current_user.apikey)) apikeys_operator.add(('neotaxi', user_datastore.find_user(email='neotaxi').apikey)) apikeys_moteur.add(('neomap', user_datastore.find_user(email='neomap').apikey)) taxis = Taxi.query.filter(Taxi.added_by==user_datastore.\ find_user(email='neotaxi').id).all() else: apikeys_operator = [('anonymous', 'token')] apikeys_moteur = [('anonymous', 'token')] taxis = [] url_for = partial(base_url_for, _external=True) return render_template('documentation/examples.html', apikeys_operator=apikeys_operator, apikeys_moteur=apikeys_moteur, taxis=taxis, url_for=url_for)
# -*- coding: utf-8 -*- from flask import Blueprint, render_template, url_for as base_url_for from flask.ext.security import current_user from ..extensions import user_datastore from ..models.taxis import Taxi from functools import partial mod = Blueprint('examples', __name__) @mod.route('/documentation/examples') def doc_index(): if not current_user.is_anonymous: apikeys_operator = set() apikeys_moteur = set() if 'operateur' in current_user.roles: apikeys_operator.add(('your token', current_user.apikey)) if 'moteur' in current_user.roles: apikeys_moteur.add(('your token', current_user.apikey)) apikeys_operator.add(('neotaxi', user_datastore.find_user(email='neotaxi').apikey)) apikeys_moteur.add(('neomap', user_datastore.find_user(email='neomap').apikey)) taxis = Taxi.query.filter(Taxi.added_by==user_datastore.\ find_user(email='neotaxi').id).all() else: apikeys_operator = [('anonymous', 'token')] apikeys_moteur = [('anonymous', 'token')] taxis = [] url_for = partial(base_url_for, _external=True) return render_template('documentation/examples.html', apikeys_operator=apikeys_operator, apikeys_moteur=apikeys_moteur, taxis=taxis, url_for=url_for)
Fix test for anonymity in documentation
Fix test for anonymity in documentation
Python
agpl-3.0
openmaraude/APITaxi,l-vincent-l/APITaxi,l-vincent-l/APITaxi,openmaraude/APITaxi
# -*- coding: utf-8 -*- from flask import Blueprint, render_template, url_for as base_url_for from flask.ext.security import current_user from ..extensions import user_datastore from ..models.taxis import Taxi from functools import partial mod = Blueprint('examples', __name__) @mod.route('/documentation/examples') def doc_index(): if not current_user.is_anonymous(): apikeys_operator = set() apikeys_moteur = set() if 'operateur' in current_user.roles: apikeys_operator.add(('your token', current_user.apikey)) if 'moteur' in current_user.roles: apikeys_moteur.add(('your token', current_user.apikey)) apikeys_operator.add(('neotaxi', user_datastore.find_user(email='neotaxi').apikey)) apikeys_moteur.add(('neomap', user_datastore.find_user(email='neomap').apikey)) taxis = Taxi.query.filter(Taxi.added_by==user_datastore.\ find_user(email='neotaxi').id).all() else: apikeys_operator = [('anonymous', 'token')] apikeys_moteur = [('anonymous', 'token')] taxis = [] url_for = partial(base_url_for, _external=True) return render_template('documentation/examples.html', apikeys_operator=apikeys_operator, apikeys_moteur=apikeys_moteur, taxis=taxis, url_for=url_for) Fix test for anonymity in documentation
# -*- coding: utf-8 -*- from flask import Blueprint, render_template, url_for as base_url_for from flask.ext.security import current_user from ..extensions import user_datastore from ..models.taxis import Taxi from functools import partial mod = Blueprint('examples', __name__) @mod.route('/documentation/examples') def doc_index(): if not current_user.is_anonymous: apikeys_operator = set() apikeys_moteur = set() if 'operateur' in current_user.roles: apikeys_operator.add(('your token', current_user.apikey)) if 'moteur' in current_user.roles: apikeys_moteur.add(('your token', current_user.apikey)) apikeys_operator.add(('neotaxi', user_datastore.find_user(email='neotaxi').apikey)) apikeys_moteur.add(('neomap', user_datastore.find_user(email='neomap').apikey)) taxis = Taxi.query.filter(Taxi.added_by==user_datastore.\ find_user(email='neotaxi').id).all() else: apikeys_operator = [('anonymous', 'token')] apikeys_moteur = [('anonymous', 'token')] taxis = [] url_for = partial(base_url_for, _external=True) return render_template('documentation/examples.html', apikeys_operator=apikeys_operator, apikeys_moteur=apikeys_moteur, taxis=taxis, url_for=url_for)
<commit_before># -*- coding: utf-8 -*- from flask import Blueprint, render_template, url_for as base_url_for from flask.ext.security import current_user from ..extensions import user_datastore from ..models.taxis import Taxi from functools import partial mod = Blueprint('examples', __name__) @mod.route('/documentation/examples') def doc_index(): if not current_user.is_anonymous(): apikeys_operator = set() apikeys_moteur = set() if 'operateur' in current_user.roles: apikeys_operator.add(('your token', current_user.apikey)) if 'moteur' in current_user.roles: apikeys_moteur.add(('your token', current_user.apikey)) apikeys_operator.add(('neotaxi', user_datastore.find_user(email='neotaxi').apikey)) apikeys_moteur.add(('neomap', user_datastore.find_user(email='neomap').apikey)) taxis = Taxi.query.filter(Taxi.added_by==user_datastore.\ find_user(email='neotaxi').id).all() else: apikeys_operator = [('anonymous', 'token')] apikeys_moteur = [('anonymous', 'token')] taxis = [] url_for = partial(base_url_for, _external=True) return render_template('documentation/examples.html', apikeys_operator=apikeys_operator, apikeys_moteur=apikeys_moteur, taxis=taxis, url_for=url_for) <commit_msg>Fix test for anonymity in documentation<commit_after>
# -*- coding: utf-8 -*- from flask import Blueprint, render_template, url_for as base_url_for from flask.ext.security import current_user from ..extensions import user_datastore from ..models.taxis import Taxi from functools import partial mod = Blueprint('examples', __name__) @mod.route('/documentation/examples') def doc_index(): if not current_user.is_anonymous: apikeys_operator = set() apikeys_moteur = set() if 'operateur' in current_user.roles: apikeys_operator.add(('your token', current_user.apikey)) if 'moteur' in current_user.roles: apikeys_moteur.add(('your token', current_user.apikey)) apikeys_operator.add(('neotaxi', user_datastore.find_user(email='neotaxi').apikey)) apikeys_moteur.add(('neomap', user_datastore.find_user(email='neomap').apikey)) taxis = Taxi.query.filter(Taxi.added_by==user_datastore.\ find_user(email='neotaxi').id).all() else: apikeys_operator = [('anonymous', 'token')] apikeys_moteur = [('anonymous', 'token')] taxis = [] url_for = partial(base_url_for, _external=True) return render_template('documentation/examples.html', apikeys_operator=apikeys_operator, apikeys_moteur=apikeys_moteur, taxis=taxis, url_for=url_for)
# -*- coding: utf-8 -*- from flask import Blueprint, render_template, url_for as base_url_for from flask.ext.security import current_user from ..extensions import user_datastore from ..models.taxis import Taxi from functools import partial mod = Blueprint('examples', __name__) @mod.route('/documentation/examples') def doc_index(): if not current_user.is_anonymous(): apikeys_operator = set() apikeys_moteur = set() if 'operateur' in current_user.roles: apikeys_operator.add(('your token', current_user.apikey)) if 'moteur' in current_user.roles: apikeys_moteur.add(('your token', current_user.apikey)) apikeys_operator.add(('neotaxi', user_datastore.find_user(email='neotaxi').apikey)) apikeys_moteur.add(('neomap', user_datastore.find_user(email='neomap').apikey)) taxis = Taxi.query.filter(Taxi.added_by==user_datastore.\ find_user(email='neotaxi').id).all() else: apikeys_operator = [('anonymous', 'token')] apikeys_moteur = [('anonymous', 'token')] taxis = [] url_for = partial(base_url_for, _external=True) return render_template('documentation/examples.html', apikeys_operator=apikeys_operator, apikeys_moteur=apikeys_moteur, taxis=taxis, url_for=url_for) Fix test for anonymity in documentation# -*- coding: utf-8 -*- from flask import Blueprint, render_template, url_for as base_url_for from flask.ext.security import current_user from ..extensions import user_datastore from ..models.taxis import Taxi from functools import partial mod = Blueprint('examples', __name__) @mod.route('/documentation/examples') def doc_index(): if not current_user.is_anonymous: apikeys_operator = set() apikeys_moteur = set() if 'operateur' in current_user.roles: apikeys_operator.add(('your token', current_user.apikey)) if 'moteur' in current_user.roles: apikeys_moteur.add(('your token', current_user.apikey)) apikeys_operator.add(('neotaxi', user_datastore.find_user(email='neotaxi').apikey)) apikeys_moteur.add(('neomap', user_datastore.find_user(email='neomap').apikey)) taxis = Taxi.query.filter(Taxi.added_by==user_datastore.\ find_user(email='neotaxi').id).all() else: apikeys_operator = [('anonymous', 'token')] apikeys_moteur = [('anonymous', 'token')] taxis = [] url_for = partial(base_url_for, _external=True) return render_template('documentation/examples.html', apikeys_operator=apikeys_operator, apikeys_moteur=apikeys_moteur, taxis=taxis, url_for=url_for)
<commit_before># -*- coding: utf-8 -*- from flask import Blueprint, render_template, url_for as base_url_for from flask.ext.security import current_user from ..extensions import user_datastore from ..models.taxis import Taxi from functools import partial mod = Blueprint('examples', __name__) @mod.route('/documentation/examples') def doc_index(): if not current_user.is_anonymous(): apikeys_operator = set() apikeys_moteur = set() if 'operateur' in current_user.roles: apikeys_operator.add(('your token', current_user.apikey)) if 'moteur' in current_user.roles: apikeys_moteur.add(('your token', current_user.apikey)) apikeys_operator.add(('neotaxi', user_datastore.find_user(email='neotaxi').apikey)) apikeys_moteur.add(('neomap', user_datastore.find_user(email='neomap').apikey)) taxis = Taxi.query.filter(Taxi.added_by==user_datastore.\ find_user(email='neotaxi').id).all() else: apikeys_operator = [('anonymous', 'token')] apikeys_moteur = [('anonymous', 'token')] taxis = [] url_for = partial(base_url_for, _external=True) return render_template('documentation/examples.html', apikeys_operator=apikeys_operator, apikeys_moteur=apikeys_moteur, taxis=taxis, url_for=url_for) <commit_msg>Fix test for anonymity in documentation<commit_after># -*- coding: utf-8 -*- from flask import Blueprint, render_template, url_for as base_url_for from flask.ext.security import current_user from ..extensions import user_datastore from ..models.taxis import Taxi from functools import partial mod = Blueprint('examples', __name__) @mod.route('/documentation/examples') def doc_index(): if not current_user.is_anonymous: apikeys_operator = set() apikeys_moteur = set() if 'operateur' in current_user.roles: apikeys_operator.add(('your token', current_user.apikey)) if 'moteur' in current_user.roles: apikeys_moteur.add(('your token', current_user.apikey)) apikeys_operator.add(('neotaxi', user_datastore.find_user(email='neotaxi').apikey)) apikeys_moteur.add(('neomap', user_datastore.find_user(email='neomap').apikey)) taxis = Taxi.query.filter(Taxi.added_by==user_datastore.\ find_user(email='neotaxi').id).all() else: apikeys_operator = [('anonymous', 'token')] apikeys_moteur = [('anonymous', 'token')] taxis = [] url_for = partial(base_url_for, _external=True) return render_template('documentation/examples.html', apikeys_operator=apikeys_operator, apikeys_moteur=apikeys_moteur, taxis=taxis, url_for=url_for)
8bd94920eb508849851ea851554d05c7a16ee932
Source/Common/Experiments/scintilla_simple.py
Source/Common/Experiments/scintilla_simple.py
import wb_scintilla import sys from PyQt5 import QtWidgets from PyQt5 import QtGui from PyQt5 import QtCore app =QtWidgets.QApplication( sys.argv ) scintilla = wb_scintilla.WbScintilla( None ) for name in sorted( dir(scintilla) ): if name[0] != '_': print( name ) scintilla.insertText( 0, 'line 1\n' ) scintilla.insertText( len('line 1\n'), 'line 2\n' ) scintilla.show() app.exec_()
import wb_scintilla import sys from PyQt5 import QtWidgets from PyQt5 import QtGui from PyQt5 import QtCore app =QtWidgets.QApplication( sys.argv ) scintilla = wb_scintilla.WbScintilla( None ) if False: for name in sorted( dir(scintilla) ): if name[0] != '_': print( name ) scintilla.insertText( 0, 'line one is here\n' ) scintilla.insertText( len('line one is here\n'), 'line Two is here\n' ) scintilla.indicSetStyle( 0, scintilla.INDIC_STRIKE ) scintilla.setIndicatorValue( 0 ) scintilla.indicatorFillRange( 5, 4 ) scintilla.resize( 400, 300 ) scintilla.show() app.exec_()
Add indicator example to simple test.
Add indicator example to simple test.
Python
apache-2.0
barry-scott/scm-workbench,barry-scott/git-workbench,barry-scott/git-workbench,barry-scott/scm-workbench,barry-scott/scm-workbench
import wb_scintilla import sys from PyQt5 import QtWidgets from PyQt5 import QtGui from PyQt5 import QtCore app =QtWidgets.QApplication( sys.argv ) scintilla = wb_scintilla.WbScintilla( None ) for name in sorted( dir(scintilla) ): if name[0] != '_': print( name ) scintilla.insertText( 0, 'line 1\n' ) scintilla.insertText( len('line 1\n'), 'line 2\n' ) scintilla.show() app.exec_() Add indicator example to simple test.
import wb_scintilla import sys from PyQt5 import QtWidgets from PyQt5 import QtGui from PyQt5 import QtCore app =QtWidgets.QApplication( sys.argv ) scintilla = wb_scintilla.WbScintilla( None ) if False: for name in sorted( dir(scintilla) ): if name[0] != '_': print( name ) scintilla.insertText( 0, 'line one is here\n' ) scintilla.insertText( len('line one is here\n'), 'line Two is here\n' ) scintilla.indicSetStyle( 0, scintilla.INDIC_STRIKE ) scintilla.setIndicatorValue( 0 ) scintilla.indicatorFillRange( 5, 4 ) scintilla.resize( 400, 300 ) scintilla.show() app.exec_()
<commit_before>import wb_scintilla import sys from PyQt5 import QtWidgets from PyQt5 import QtGui from PyQt5 import QtCore app =QtWidgets.QApplication( sys.argv ) scintilla = wb_scintilla.WbScintilla( None ) for name in sorted( dir(scintilla) ): if name[0] != '_': print( name ) scintilla.insertText( 0, 'line 1\n' ) scintilla.insertText( len('line 1\n'), 'line 2\n' ) scintilla.show() app.exec_() <commit_msg>Add indicator example to simple test.<commit_after>
import wb_scintilla import sys from PyQt5 import QtWidgets from PyQt5 import QtGui from PyQt5 import QtCore app =QtWidgets.QApplication( sys.argv ) scintilla = wb_scintilla.WbScintilla( None ) if False: for name in sorted( dir(scintilla) ): if name[0] != '_': print( name ) scintilla.insertText( 0, 'line one is here\n' ) scintilla.insertText( len('line one is here\n'), 'line Two is here\n' ) scintilla.indicSetStyle( 0, scintilla.INDIC_STRIKE ) scintilla.setIndicatorValue( 0 ) scintilla.indicatorFillRange( 5, 4 ) scintilla.resize( 400, 300 ) scintilla.show() app.exec_()
import wb_scintilla import sys from PyQt5 import QtWidgets from PyQt5 import QtGui from PyQt5 import QtCore app =QtWidgets.QApplication( sys.argv ) scintilla = wb_scintilla.WbScintilla( None ) for name in sorted( dir(scintilla) ): if name[0] != '_': print( name ) scintilla.insertText( 0, 'line 1\n' ) scintilla.insertText( len('line 1\n'), 'line 2\n' ) scintilla.show() app.exec_() Add indicator example to simple test.import wb_scintilla import sys from PyQt5 import QtWidgets from PyQt5 import QtGui from PyQt5 import QtCore app =QtWidgets.QApplication( sys.argv ) scintilla = wb_scintilla.WbScintilla( None ) if False: for name in sorted( dir(scintilla) ): if name[0] != '_': print( name ) scintilla.insertText( 0, 'line one is here\n' ) scintilla.insertText( len('line one is here\n'), 'line Two is here\n' ) scintilla.indicSetStyle( 0, scintilla.INDIC_STRIKE ) scintilla.setIndicatorValue( 0 ) scintilla.indicatorFillRange( 5, 4 ) scintilla.resize( 400, 300 ) scintilla.show() app.exec_()
<commit_before>import wb_scintilla import sys from PyQt5 import QtWidgets from PyQt5 import QtGui from PyQt5 import QtCore app =QtWidgets.QApplication( sys.argv ) scintilla = wb_scintilla.WbScintilla( None ) for name in sorted( dir(scintilla) ): if name[0] != '_': print( name ) scintilla.insertText( 0, 'line 1\n' ) scintilla.insertText( len('line 1\n'), 'line 2\n' ) scintilla.show() app.exec_() <commit_msg>Add indicator example to simple test.<commit_after>import wb_scintilla import sys from PyQt5 import QtWidgets from PyQt5 import QtGui from PyQt5 import QtCore app =QtWidgets.QApplication( sys.argv ) scintilla = wb_scintilla.WbScintilla( None ) if False: for name in sorted( dir(scintilla) ): if name[0] != '_': print( name ) scintilla.insertText( 0, 'line one is here\n' ) scintilla.insertText( len('line one is here\n'), 'line Two is here\n' ) scintilla.indicSetStyle( 0, scintilla.INDIC_STRIKE ) scintilla.setIndicatorValue( 0 ) scintilla.indicatorFillRange( 5, 4 ) scintilla.resize( 400, 300 ) scintilla.show() app.exec_()
13ce6044fa2105ab4c543be0f72a4ba4faf1d890
src/billing/factories.py
src/billing/factories.py
import factory import random from billing.models import Billing, OrderBilling from member.factories import ClientFactory from order.factories import OrderFactory class BillingFactory(factory.DjangoModelFactory): class Meta: model = Billing client = factory.SubFactory(ClientFactory) total_amount = random.randrange(1, stop=75, step=1) billing_month = random.randrange(1, stop=12, step=1) billing_year = random.randrange(2016, stop=2020, step=1) detail = {"123": 123} class BillingOrder(factory.DjangoModelFactory): billing_id = BillingFactory() order_id = OrderFactory()
import factory import random from billing.models import Billing, OrderBilling from member.factories import ClientFactory from order.factories import OrderFactory class BillingFactory(factory.DjangoModelFactory): class Meta: model = Billing client = factory.SubFactory(ClientFactory) total_amount = random.randrange(1, stop=75, step=1) billing_month = random.randrange(1, stop=12, step=1) billing_year = random.randrange(2016, stop=2020, step=1) detail = {"123": 123} class BillingOrder(factory.DjangoModelFactory): billing_id = BillingFactory().id order_id = OrderFactory()
Fix BillingOrder factory to properly set billing_id property
Fix BillingOrder factory to properly set billing_id property
Python
agpl-3.0
savoirfairelinux/sous-chef,savoirfairelinux/sous-chef,savoirfairelinux/santropol-feast,savoirfairelinux/sous-chef,savoirfairelinux/santropol-feast,madmath/sous-chef,madmath/sous-chef,savoirfairelinux/santropol-feast,madmath/sous-chef
import factory import random from billing.models import Billing, OrderBilling from member.factories import ClientFactory from order.factories import OrderFactory class BillingFactory(factory.DjangoModelFactory): class Meta: model = Billing client = factory.SubFactory(ClientFactory) total_amount = random.randrange(1, stop=75, step=1) billing_month = random.randrange(1, stop=12, step=1) billing_year = random.randrange(2016, stop=2020, step=1) detail = {"123": 123} class BillingOrder(factory.DjangoModelFactory): billing_id = BillingFactory() order_id = OrderFactory() Fix BillingOrder factory to properly set billing_id property
import factory import random from billing.models import Billing, OrderBilling from member.factories import ClientFactory from order.factories import OrderFactory class BillingFactory(factory.DjangoModelFactory): class Meta: model = Billing client = factory.SubFactory(ClientFactory) total_amount = random.randrange(1, stop=75, step=1) billing_month = random.randrange(1, stop=12, step=1) billing_year = random.randrange(2016, stop=2020, step=1) detail = {"123": 123} class BillingOrder(factory.DjangoModelFactory): billing_id = BillingFactory().id order_id = OrderFactory()
<commit_before>import factory import random from billing.models import Billing, OrderBilling from member.factories import ClientFactory from order.factories import OrderFactory class BillingFactory(factory.DjangoModelFactory): class Meta: model = Billing client = factory.SubFactory(ClientFactory) total_amount = random.randrange(1, stop=75, step=1) billing_month = random.randrange(1, stop=12, step=1) billing_year = random.randrange(2016, stop=2020, step=1) detail = {"123": 123} class BillingOrder(factory.DjangoModelFactory): billing_id = BillingFactory() order_id = OrderFactory() <commit_msg>Fix BillingOrder factory to properly set billing_id property<commit_after>
import factory import random from billing.models import Billing, OrderBilling from member.factories import ClientFactory from order.factories import OrderFactory class BillingFactory(factory.DjangoModelFactory): class Meta: model = Billing client = factory.SubFactory(ClientFactory) total_amount = random.randrange(1, stop=75, step=1) billing_month = random.randrange(1, stop=12, step=1) billing_year = random.randrange(2016, stop=2020, step=1) detail = {"123": 123} class BillingOrder(factory.DjangoModelFactory): billing_id = BillingFactory().id order_id = OrderFactory()
import factory import random from billing.models import Billing, OrderBilling from member.factories import ClientFactory from order.factories import OrderFactory class BillingFactory(factory.DjangoModelFactory): class Meta: model = Billing client = factory.SubFactory(ClientFactory) total_amount = random.randrange(1, stop=75, step=1) billing_month = random.randrange(1, stop=12, step=1) billing_year = random.randrange(2016, stop=2020, step=1) detail = {"123": 123} class BillingOrder(factory.DjangoModelFactory): billing_id = BillingFactory() order_id = OrderFactory() Fix BillingOrder factory to properly set billing_id propertyimport factory import random from billing.models import Billing, OrderBilling from member.factories import ClientFactory from order.factories import OrderFactory class BillingFactory(factory.DjangoModelFactory): class Meta: model = Billing client = factory.SubFactory(ClientFactory) total_amount = random.randrange(1, stop=75, step=1) billing_month = random.randrange(1, stop=12, step=1) billing_year = random.randrange(2016, stop=2020, step=1) detail = {"123": 123} class BillingOrder(factory.DjangoModelFactory): billing_id = BillingFactory().id order_id = OrderFactory()
<commit_before>import factory import random from billing.models import Billing, OrderBilling from member.factories import ClientFactory from order.factories import OrderFactory class BillingFactory(factory.DjangoModelFactory): class Meta: model = Billing client = factory.SubFactory(ClientFactory) total_amount = random.randrange(1, stop=75, step=1) billing_month = random.randrange(1, stop=12, step=1) billing_year = random.randrange(2016, stop=2020, step=1) detail = {"123": 123} class BillingOrder(factory.DjangoModelFactory): billing_id = BillingFactory() order_id = OrderFactory() <commit_msg>Fix BillingOrder factory to properly set billing_id property<commit_after>import factory import random from billing.models import Billing, OrderBilling from member.factories import ClientFactory from order.factories import OrderFactory class BillingFactory(factory.DjangoModelFactory): class Meta: model = Billing client = factory.SubFactory(ClientFactory) total_amount = random.randrange(1, stop=75, step=1) billing_month = random.randrange(1, stop=12, step=1) billing_year = random.randrange(2016, stop=2020, step=1) detail = {"123": 123} class BillingOrder(factory.DjangoModelFactory): billing_id = BillingFactory().id order_id = OrderFactory()
2168557dc088be1b991f7eb42dabac144e3add3b
src/ggrc/models/event.py
src/ggrc/models/event.py
# Copyright (C) 2017 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> from ggrc import db from ggrc.models.mixins import Base class Event(Base, db.Model): __tablename__ = 'events' action = db.Column( db.Enum(u'POST', u'PUT', u'DELETE', u'BULK', u'GET'), nullable=False, ) resource_id = db.Column(db.Integer) resource_type = db.Column(db.String) revisions = db.relationship( 'Revision', backref='event', cascade='all, delete-orphan', ) _publish_attrs = [ 'action', 'resource_id', 'resource_type', 'revisions', ] _include_links = [ 'revisions', ] @staticmethod def _extra_table_args(class_): return ( db.Index('events_modified_by', 'modified_by_id'), db.Index( 'ix_{}_updated_at'.format(class_.__tablename__), 'updated_at', ), ) @classmethod def eager_query(cls): from sqlalchemy import orm query = super(Event, cls).eager_query() return query.options( orm.subqueryload('revisions').undefer_group('Revision_complete'), )
# Copyright (C) 2017 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> from ggrc import db from ggrc.models.mixins import Base class Event(Base, db.Model): __tablename__ = 'events' action = db.Column( db.Enum(u'POST', u'PUT', u'DELETE', u'BULK', u'GET'), nullable=False, ) resource_id = db.Column(db.Integer) resource_type = db.Column(db.String) revisions = db.relationship( 'Revision', backref='event', cascade='all, delete-orphan', ) _publish_attrs = [ 'action', 'resource_id', 'resource_type', 'revisions', ] _include_links = [ 'revisions', ] @staticmethod def _extra_table_args(class_): return ( db.Index('events_modified_by', 'modified_by_id'), ) @classmethod def eager_query(cls): from sqlalchemy import orm query = super(Event, cls).eager_query() return query.options( orm.subqueryload('revisions').undefer_group('Revision_complete'), )
Remove redundant index declaration from Event
Remove redundant index declaration from Event The updated at index is already declared in ChangeTracked mixin which is included in the Base mixin.
Python
apache-2.0
plamut/ggrc-core,VinnieJohns/ggrc-core,VinnieJohns/ggrc-core,selahssea/ggrc-core,selahssea/ggrc-core,VinnieJohns/ggrc-core,plamut/ggrc-core,plamut/ggrc-core,selahssea/ggrc-core,selahssea/ggrc-core,plamut/ggrc-core,VinnieJohns/ggrc-core
# Copyright (C) 2017 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> from ggrc import db from ggrc.models.mixins import Base class Event(Base, db.Model): __tablename__ = 'events' action = db.Column( db.Enum(u'POST', u'PUT', u'DELETE', u'BULK', u'GET'), nullable=False, ) resource_id = db.Column(db.Integer) resource_type = db.Column(db.String) revisions = db.relationship( 'Revision', backref='event', cascade='all, delete-orphan', ) _publish_attrs = [ 'action', 'resource_id', 'resource_type', 'revisions', ] _include_links = [ 'revisions', ] @staticmethod def _extra_table_args(class_): return ( db.Index('events_modified_by', 'modified_by_id'), db.Index( 'ix_{}_updated_at'.format(class_.__tablename__), 'updated_at', ), ) @classmethod def eager_query(cls): from sqlalchemy import orm query = super(Event, cls).eager_query() return query.options( orm.subqueryload('revisions').undefer_group('Revision_complete'), ) Remove redundant index declaration from Event The updated at index is already declared in ChangeTracked mixin which is included in the Base mixin.
# Copyright (C) 2017 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> from ggrc import db from ggrc.models.mixins import Base class Event(Base, db.Model): __tablename__ = 'events' action = db.Column( db.Enum(u'POST', u'PUT', u'DELETE', u'BULK', u'GET'), nullable=False, ) resource_id = db.Column(db.Integer) resource_type = db.Column(db.String) revisions = db.relationship( 'Revision', backref='event', cascade='all, delete-orphan', ) _publish_attrs = [ 'action', 'resource_id', 'resource_type', 'revisions', ] _include_links = [ 'revisions', ] @staticmethod def _extra_table_args(class_): return ( db.Index('events_modified_by', 'modified_by_id'), ) @classmethod def eager_query(cls): from sqlalchemy import orm query = super(Event, cls).eager_query() return query.options( orm.subqueryload('revisions').undefer_group('Revision_complete'), )
<commit_before># Copyright (C) 2017 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> from ggrc import db from ggrc.models.mixins import Base class Event(Base, db.Model): __tablename__ = 'events' action = db.Column( db.Enum(u'POST', u'PUT', u'DELETE', u'BULK', u'GET'), nullable=False, ) resource_id = db.Column(db.Integer) resource_type = db.Column(db.String) revisions = db.relationship( 'Revision', backref='event', cascade='all, delete-orphan', ) _publish_attrs = [ 'action', 'resource_id', 'resource_type', 'revisions', ] _include_links = [ 'revisions', ] @staticmethod def _extra_table_args(class_): return ( db.Index('events_modified_by', 'modified_by_id'), db.Index( 'ix_{}_updated_at'.format(class_.__tablename__), 'updated_at', ), ) @classmethod def eager_query(cls): from sqlalchemy import orm query = super(Event, cls).eager_query() return query.options( orm.subqueryload('revisions').undefer_group('Revision_complete'), ) <commit_msg>Remove redundant index declaration from Event The updated at index is already declared in ChangeTracked mixin which is included in the Base mixin.<commit_after>
# Copyright (C) 2017 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> from ggrc import db from ggrc.models.mixins import Base class Event(Base, db.Model): __tablename__ = 'events' action = db.Column( db.Enum(u'POST', u'PUT', u'DELETE', u'BULK', u'GET'), nullable=False, ) resource_id = db.Column(db.Integer) resource_type = db.Column(db.String) revisions = db.relationship( 'Revision', backref='event', cascade='all, delete-orphan', ) _publish_attrs = [ 'action', 'resource_id', 'resource_type', 'revisions', ] _include_links = [ 'revisions', ] @staticmethod def _extra_table_args(class_): return ( db.Index('events_modified_by', 'modified_by_id'), ) @classmethod def eager_query(cls): from sqlalchemy import orm query = super(Event, cls).eager_query() return query.options( orm.subqueryload('revisions').undefer_group('Revision_complete'), )
# Copyright (C) 2017 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> from ggrc import db from ggrc.models.mixins import Base class Event(Base, db.Model): __tablename__ = 'events' action = db.Column( db.Enum(u'POST', u'PUT', u'DELETE', u'BULK', u'GET'), nullable=False, ) resource_id = db.Column(db.Integer) resource_type = db.Column(db.String) revisions = db.relationship( 'Revision', backref='event', cascade='all, delete-orphan', ) _publish_attrs = [ 'action', 'resource_id', 'resource_type', 'revisions', ] _include_links = [ 'revisions', ] @staticmethod def _extra_table_args(class_): return ( db.Index('events_modified_by', 'modified_by_id'), db.Index( 'ix_{}_updated_at'.format(class_.__tablename__), 'updated_at', ), ) @classmethod def eager_query(cls): from sqlalchemy import orm query = super(Event, cls).eager_query() return query.options( orm.subqueryload('revisions').undefer_group('Revision_complete'), ) Remove redundant index declaration from Event The updated at index is already declared in ChangeTracked mixin which is included in the Base mixin.# Copyright (C) 2017 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> from ggrc import db from ggrc.models.mixins import Base class Event(Base, db.Model): __tablename__ = 'events' action = db.Column( db.Enum(u'POST', u'PUT', u'DELETE', u'BULK', u'GET'), nullable=False, ) resource_id = db.Column(db.Integer) resource_type = db.Column(db.String) revisions = db.relationship( 'Revision', backref='event', cascade='all, delete-orphan', ) _publish_attrs = [ 'action', 'resource_id', 'resource_type', 'revisions', ] _include_links = [ 'revisions', ] @staticmethod def _extra_table_args(class_): return ( db.Index('events_modified_by', 'modified_by_id'), ) @classmethod def eager_query(cls): from sqlalchemy import orm query = super(Event, cls).eager_query() return query.options( orm.subqueryload('revisions').undefer_group('Revision_complete'), )
<commit_before># Copyright (C) 2017 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> from ggrc import db from ggrc.models.mixins import Base class Event(Base, db.Model): __tablename__ = 'events' action = db.Column( db.Enum(u'POST', u'PUT', u'DELETE', u'BULK', u'GET'), nullable=False, ) resource_id = db.Column(db.Integer) resource_type = db.Column(db.String) revisions = db.relationship( 'Revision', backref='event', cascade='all, delete-orphan', ) _publish_attrs = [ 'action', 'resource_id', 'resource_type', 'revisions', ] _include_links = [ 'revisions', ] @staticmethod def _extra_table_args(class_): return ( db.Index('events_modified_by', 'modified_by_id'), db.Index( 'ix_{}_updated_at'.format(class_.__tablename__), 'updated_at', ), ) @classmethod def eager_query(cls): from sqlalchemy import orm query = super(Event, cls).eager_query() return query.options( orm.subqueryload('revisions').undefer_group('Revision_complete'), ) <commit_msg>Remove redundant index declaration from Event The updated at index is already declared in ChangeTracked mixin which is included in the Base mixin.<commit_after># Copyright (C) 2017 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> from ggrc import db from ggrc.models.mixins import Base class Event(Base, db.Model): __tablename__ = 'events' action = db.Column( db.Enum(u'POST', u'PUT', u'DELETE', u'BULK', u'GET'), nullable=False, ) resource_id = db.Column(db.Integer) resource_type = db.Column(db.String) revisions = db.relationship( 'Revision', backref='event', cascade='all, delete-orphan', ) _publish_attrs = [ 'action', 'resource_id', 'resource_type', 'revisions', ] _include_links = [ 'revisions', ] @staticmethod def _extra_table_args(class_): return ( db.Index('events_modified_by', 'modified_by_id'), ) @classmethod def eager_query(cls): from sqlalchemy import orm query = super(Event, cls).eager_query() return query.options( orm.subqueryload('revisions').undefer_group('Revision_complete'), )
fe11cc39e394d44f06b743d5b967625b6d12575f
api/parsers/datanasa.py
api/parsers/datanasa.py
import json from flaskext.mongoalchemy import BaseQuery import requests from api import app from api import db ENDPOINT = 'http://data.nasa.gov/api/' class DatasetQuery(BaseQuery): def get_by_remote_id(self, pk): return self.filter(self.type.remote_id==pk) class Dataset(db.Document): """ Represents a dataset, we could split this out to hold all the actual data, slug, url, title, etc """ remote_id = db.IntField() data = db.StringField() query_class = DatasetQuery def get_dataset(id): response = requests.get(ENDPOINT + 'get_dataset?id=%s' % id) dataset_data = json.loads(response.text) dataset = Dataset(remote_id = id, data=response.text) dataset.save()
import json from flaskext.mongoalchemy import BaseQuery import requests from api import app from api import db ENDPOINT = 'http://data.nasa.gov/api/' class DatasetQuery(BaseQuery): def get_by_remote_id(self, pk): return self.filter(self.type.remote_id==pk).first() def get_by_slug(self, slug): return self.filter(self.type.slug==slug).first() class Dataset(db.Document): """ Represents a dataset, we could split this out to hold all the actual data, slug, url, title, etc """ remote_id = db.IntField() slug = db.StringField() data = db.StringField() query_class = DatasetQuery def get_dataset(id): response = requests.get(ENDPOINT + 'get_dataset?id=%s' % id) slug = json.loads(response.text).get('post').get('slug') dataset = Dataset(remote_id = id, slug=slug, data=response.text) dataset.save()
Add slug to the db and allow querying it
Add slug to the db and allow querying it
Python
mit
oxford-space-apps/open-data-api
import json from flaskext.mongoalchemy import BaseQuery import requests from api import app from api import db ENDPOINT = 'http://data.nasa.gov/api/' class DatasetQuery(BaseQuery): def get_by_remote_id(self, pk): return self.filter(self.type.remote_id==pk) class Dataset(db.Document): """ Represents a dataset, we could split this out to hold all the actual data, slug, url, title, etc """ remote_id = db.IntField() data = db.StringField() query_class = DatasetQuery def get_dataset(id): response = requests.get(ENDPOINT + 'get_dataset?id=%s' % id) dataset_data = json.loads(response.text) dataset = Dataset(remote_id = id, data=response.text) dataset.save() Add slug to the db and allow querying it
import json from flaskext.mongoalchemy import BaseQuery import requests from api import app from api import db ENDPOINT = 'http://data.nasa.gov/api/' class DatasetQuery(BaseQuery): def get_by_remote_id(self, pk): return self.filter(self.type.remote_id==pk).first() def get_by_slug(self, slug): return self.filter(self.type.slug==slug).first() class Dataset(db.Document): """ Represents a dataset, we could split this out to hold all the actual data, slug, url, title, etc """ remote_id = db.IntField() slug = db.StringField() data = db.StringField() query_class = DatasetQuery def get_dataset(id): response = requests.get(ENDPOINT + 'get_dataset?id=%s' % id) slug = json.loads(response.text).get('post').get('slug') dataset = Dataset(remote_id = id, slug=slug, data=response.text) dataset.save()
<commit_before>import json from flaskext.mongoalchemy import BaseQuery import requests from api import app from api import db ENDPOINT = 'http://data.nasa.gov/api/' class DatasetQuery(BaseQuery): def get_by_remote_id(self, pk): return self.filter(self.type.remote_id==pk) class Dataset(db.Document): """ Represents a dataset, we could split this out to hold all the actual data, slug, url, title, etc """ remote_id = db.IntField() data = db.StringField() query_class = DatasetQuery def get_dataset(id): response = requests.get(ENDPOINT + 'get_dataset?id=%s' % id) dataset_data = json.loads(response.text) dataset = Dataset(remote_id = id, data=response.text) dataset.save() <commit_msg>Add slug to the db and allow querying it<commit_after>
import json from flaskext.mongoalchemy import BaseQuery import requests from api import app from api import db ENDPOINT = 'http://data.nasa.gov/api/' class DatasetQuery(BaseQuery): def get_by_remote_id(self, pk): return self.filter(self.type.remote_id==pk).first() def get_by_slug(self, slug): return self.filter(self.type.slug==slug).first() class Dataset(db.Document): """ Represents a dataset, we could split this out to hold all the actual data, slug, url, title, etc """ remote_id = db.IntField() slug = db.StringField() data = db.StringField() query_class = DatasetQuery def get_dataset(id): response = requests.get(ENDPOINT + 'get_dataset?id=%s' % id) slug = json.loads(response.text).get('post').get('slug') dataset = Dataset(remote_id = id, slug=slug, data=response.text) dataset.save()
import json from flaskext.mongoalchemy import BaseQuery import requests from api import app from api import db ENDPOINT = 'http://data.nasa.gov/api/' class DatasetQuery(BaseQuery): def get_by_remote_id(self, pk): return self.filter(self.type.remote_id==pk) class Dataset(db.Document): """ Represents a dataset, we could split this out to hold all the actual data, slug, url, title, etc """ remote_id = db.IntField() data = db.StringField() query_class = DatasetQuery def get_dataset(id): response = requests.get(ENDPOINT + 'get_dataset?id=%s' % id) dataset_data = json.loads(response.text) dataset = Dataset(remote_id = id, data=response.text) dataset.save() Add slug to the db and allow querying itimport json from flaskext.mongoalchemy import BaseQuery import requests from api import app from api import db ENDPOINT = 'http://data.nasa.gov/api/' class DatasetQuery(BaseQuery): def get_by_remote_id(self, pk): return self.filter(self.type.remote_id==pk).first() def get_by_slug(self, slug): return self.filter(self.type.slug==slug).first() class Dataset(db.Document): """ Represents a dataset, we could split this out to hold all the actual data, slug, url, title, etc """ remote_id = db.IntField() slug = db.StringField() data = db.StringField() query_class = DatasetQuery def get_dataset(id): response = requests.get(ENDPOINT + 'get_dataset?id=%s' % id) slug = json.loads(response.text).get('post').get('slug') dataset = Dataset(remote_id = id, slug=slug, data=response.text) dataset.save()
<commit_before>import json from flaskext.mongoalchemy import BaseQuery import requests from api import app from api import db ENDPOINT = 'http://data.nasa.gov/api/' class DatasetQuery(BaseQuery): def get_by_remote_id(self, pk): return self.filter(self.type.remote_id==pk) class Dataset(db.Document): """ Represents a dataset, we could split this out to hold all the actual data, slug, url, title, etc """ remote_id = db.IntField() data = db.StringField() query_class = DatasetQuery def get_dataset(id): response = requests.get(ENDPOINT + 'get_dataset?id=%s' % id) dataset_data = json.loads(response.text) dataset = Dataset(remote_id = id, data=response.text) dataset.save() <commit_msg>Add slug to the db and allow querying it<commit_after>import json from flaskext.mongoalchemy import BaseQuery import requests from api import app from api import db ENDPOINT = 'http://data.nasa.gov/api/' class DatasetQuery(BaseQuery): def get_by_remote_id(self, pk): return self.filter(self.type.remote_id==pk).first() def get_by_slug(self, slug): return self.filter(self.type.slug==slug).first() class Dataset(db.Document): """ Represents a dataset, we could split this out to hold all the actual data, slug, url, title, etc """ remote_id = db.IntField() slug = db.StringField() data = db.StringField() query_class = DatasetQuery def get_dataset(id): response = requests.get(ENDPOINT + 'get_dataset?id=%s' % id) slug = json.loads(response.text).get('post').get('slug') dataset = Dataset(remote_id = id, slug=slug, data=response.text) dataset.save()
3193eead48f0aeb2bb46fa6cce64a959ae19cece
web/imgtl/template.py
web/imgtl/template.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import re from jinja2 import evalcontextfilter, Markup, escape RE_NL2BR = re.compile(r'(\\r)?\\n', re.UNICODE | re.MULTILINE) @evalcontextfilter def jinja2_filter_nl2br(eval_ctx, value): res = RE_NL2BR.sub('<br>\n', unicode(escape(value))) if eval_ctx.autoescape: res = Markup(res) return res def jinja2_filter_dt(value, format='%Y-%m-%d %H:%M:%S'): return value.strftime(format)
#!/usr/bin/env python # -*- coding: utf-8 -*- import re from jinja2 import evalcontextfilter, Markup, escape RE_NL2BR = re.compile(r'(\r)?\n', re.UNICODE | re.MULTILINE) @evalcontextfilter def jinja2_filter_nl2br(eval_ctx, value): res = RE_NL2BR.sub('<br>\n', unicode(escape(value))) if eval_ctx.autoescape: res = Markup(res) return res def jinja2_filter_dt(value, format='%Y-%m-%d %H:%M:%S'): return value.strftime(format)
Fix newline not processed problem
Fix newline not processed problem
Python
mit
revi/imgtl,imgtl/imgtl,revi/imgtl,imgtl/imgtl,revi/imgtl
#!/usr/bin/env python # -*- coding: utf-8 -*- import re from jinja2 import evalcontextfilter, Markup, escape RE_NL2BR = re.compile(r'(\\r)?\\n', re.UNICODE | re.MULTILINE) @evalcontextfilter def jinja2_filter_nl2br(eval_ctx, value): res = RE_NL2BR.sub('<br>\n', unicode(escape(value))) if eval_ctx.autoescape: res = Markup(res) return res def jinja2_filter_dt(value, format='%Y-%m-%d %H:%M:%S'): return value.strftime(format) Fix newline not processed problem
#!/usr/bin/env python # -*- coding: utf-8 -*- import re from jinja2 import evalcontextfilter, Markup, escape RE_NL2BR = re.compile(r'(\r)?\n', re.UNICODE | re.MULTILINE) @evalcontextfilter def jinja2_filter_nl2br(eval_ctx, value): res = RE_NL2BR.sub('<br>\n', unicode(escape(value))) if eval_ctx.autoescape: res = Markup(res) return res def jinja2_filter_dt(value, format='%Y-%m-%d %H:%M:%S'): return value.strftime(format)
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- import re from jinja2 import evalcontextfilter, Markup, escape RE_NL2BR = re.compile(r'(\\r)?\\n', re.UNICODE | re.MULTILINE) @evalcontextfilter def jinja2_filter_nl2br(eval_ctx, value): res = RE_NL2BR.sub('<br>\n', unicode(escape(value))) if eval_ctx.autoescape: res = Markup(res) return res def jinja2_filter_dt(value, format='%Y-%m-%d %H:%M:%S'): return value.strftime(format) <commit_msg>Fix newline not processed problem<commit_after>
#!/usr/bin/env python # -*- coding: utf-8 -*- import re from jinja2 import evalcontextfilter, Markup, escape RE_NL2BR = re.compile(r'(\r)?\n', re.UNICODE | re.MULTILINE) @evalcontextfilter def jinja2_filter_nl2br(eval_ctx, value): res = RE_NL2BR.sub('<br>\n', unicode(escape(value))) if eval_ctx.autoescape: res = Markup(res) return res def jinja2_filter_dt(value, format='%Y-%m-%d %H:%M:%S'): return value.strftime(format)
#!/usr/bin/env python # -*- coding: utf-8 -*- import re from jinja2 import evalcontextfilter, Markup, escape RE_NL2BR = re.compile(r'(\\r)?\\n', re.UNICODE | re.MULTILINE) @evalcontextfilter def jinja2_filter_nl2br(eval_ctx, value): res = RE_NL2BR.sub('<br>\n', unicode(escape(value))) if eval_ctx.autoescape: res = Markup(res) return res def jinja2_filter_dt(value, format='%Y-%m-%d %H:%M:%S'): return value.strftime(format) Fix newline not processed problem#!/usr/bin/env python # -*- coding: utf-8 -*- import re from jinja2 import evalcontextfilter, Markup, escape RE_NL2BR = re.compile(r'(\r)?\n', re.UNICODE | re.MULTILINE) @evalcontextfilter def jinja2_filter_nl2br(eval_ctx, value): res = RE_NL2BR.sub('<br>\n', unicode(escape(value))) if eval_ctx.autoescape: res = Markup(res) return res def jinja2_filter_dt(value, format='%Y-%m-%d %H:%M:%S'): return value.strftime(format)
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- import re from jinja2 import evalcontextfilter, Markup, escape RE_NL2BR = re.compile(r'(\\r)?\\n', re.UNICODE | re.MULTILINE) @evalcontextfilter def jinja2_filter_nl2br(eval_ctx, value): res = RE_NL2BR.sub('<br>\n', unicode(escape(value))) if eval_ctx.autoescape: res = Markup(res) return res def jinja2_filter_dt(value, format='%Y-%m-%d %H:%M:%S'): return value.strftime(format) <commit_msg>Fix newline not processed problem<commit_after>#!/usr/bin/env python # -*- coding: utf-8 -*- import re from jinja2 import evalcontextfilter, Markup, escape RE_NL2BR = re.compile(r'(\r)?\n', re.UNICODE | re.MULTILINE) @evalcontextfilter def jinja2_filter_nl2br(eval_ctx, value): res = RE_NL2BR.sub('<br>\n', unicode(escape(value))) if eval_ctx.autoescape: res = Markup(res) return res def jinja2_filter_dt(value, format='%Y-%m-%d %H:%M:%S'): return value.strftime(format)
56e6ab84025f071c04701d3dc736b68e82361139
apitestcase/testcase.py
apitestcase/testcase.py
import types import unittest import requests class TestCase(object): """ Add assetion methods for HTTP Requests to TestCase """ hosts = [] def assertGet(self, endpoint="", status_code=200, body=""): """ Asserts GET requests on a given endpoint """ for host in self.hosts: response = requests.get(host+endpoint) self.assertEqual(response.status_code, status_code) if isinstance(body, types.StringType): self.assertIn(body, response.content) elif isinstance(body, list): for content in body: self.assertIn(content, response.content)
import unittest import requests class TestCase(object): """ Add assetion methods for HTTP Requests to TestCase """ hosts = [] def assertGet(self, endpoint="", status_code=200, body=""): """ Asserts GET requests on a given endpoint """ for host in self.hosts: response = requests.get(host+endpoint) self.assertEqual(response.status_code, status_code) if isinstance(body, str): self.assertIn(body, response.content) elif isinstance(body, list): for content in body: self.assertIn(content, response.content)
Change assertGet body check from StringType to str
Change assertGet body check from StringType to str
Python
mit
bramwelt/apitestcase
import types import unittest import requests class TestCase(object): """ Add assetion methods for HTTP Requests to TestCase """ hosts = [] def assertGet(self, endpoint="", status_code=200, body=""): """ Asserts GET requests on a given endpoint """ for host in self.hosts: response = requests.get(host+endpoint) self.assertEqual(response.status_code, status_code) if isinstance(body, types.StringType): self.assertIn(body, response.content) elif isinstance(body, list): for content in body: self.assertIn(content, response.content) Change assertGet body check from StringType to str
import unittest import requests class TestCase(object): """ Add assetion methods for HTTP Requests to TestCase """ hosts = [] def assertGet(self, endpoint="", status_code=200, body=""): """ Asserts GET requests on a given endpoint """ for host in self.hosts: response = requests.get(host+endpoint) self.assertEqual(response.status_code, status_code) if isinstance(body, str): self.assertIn(body, response.content) elif isinstance(body, list): for content in body: self.assertIn(content, response.content)
<commit_before>import types import unittest import requests class TestCase(object): """ Add assetion methods for HTTP Requests to TestCase """ hosts = [] def assertGet(self, endpoint="", status_code=200, body=""): """ Asserts GET requests on a given endpoint """ for host in self.hosts: response = requests.get(host+endpoint) self.assertEqual(response.status_code, status_code) if isinstance(body, types.StringType): self.assertIn(body, response.content) elif isinstance(body, list): for content in body: self.assertIn(content, response.content) <commit_msg>Change assertGet body check from StringType to str<commit_after>
import unittest import requests class TestCase(object): """ Add assetion methods for HTTP Requests to TestCase """ hosts = [] def assertGet(self, endpoint="", status_code=200, body=""): """ Asserts GET requests on a given endpoint """ for host in self.hosts: response = requests.get(host+endpoint) self.assertEqual(response.status_code, status_code) if isinstance(body, str): self.assertIn(body, response.content) elif isinstance(body, list): for content in body: self.assertIn(content, response.content)
import types import unittest import requests class TestCase(object): """ Add assetion methods for HTTP Requests to TestCase """ hosts = [] def assertGet(self, endpoint="", status_code=200, body=""): """ Asserts GET requests on a given endpoint """ for host in self.hosts: response = requests.get(host+endpoint) self.assertEqual(response.status_code, status_code) if isinstance(body, types.StringType): self.assertIn(body, response.content) elif isinstance(body, list): for content in body: self.assertIn(content, response.content) Change assertGet body check from StringType to strimport unittest import requests class TestCase(object): """ Add assetion methods for HTTP Requests to TestCase """ hosts = [] def assertGet(self, endpoint="", status_code=200, body=""): """ Asserts GET requests on a given endpoint """ for host in self.hosts: response = requests.get(host+endpoint) self.assertEqual(response.status_code, status_code) if isinstance(body, str): self.assertIn(body, response.content) elif isinstance(body, list): for content in body: self.assertIn(content, response.content)
<commit_before>import types import unittest import requests class TestCase(object): """ Add assetion methods for HTTP Requests to TestCase """ hosts = [] def assertGet(self, endpoint="", status_code=200, body=""): """ Asserts GET requests on a given endpoint """ for host in self.hosts: response = requests.get(host+endpoint) self.assertEqual(response.status_code, status_code) if isinstance(body, types.StringType): self.assertIn(body, response.content) elif isinstance(body, list): for content in body: self.assertIn(content, response.content) <commit_msg>Change assertGet body check from StringType to str<commit_after>import unittest import requests class TestCase(object): """ Add assetion methods for HTTP Requests to TestCase """ hosts = [] def assertGet(self, endpoint="", status_code=200, body=""): """ Asserts GET requests on a given endpoint """ for host in self.hosts: response = requests.get(host+endpoint) self.assertEqual(response.status_code, status_code) if isinstance(body, str): self.assertIn(body, response.content) elif isinstance(body, list): for content in body: self.assertIn(content, response.content)
8126e8951ced9462afce1964cb4f256fabcc05a9
tests/test__utils.py
tests/test__utils.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import import pytest import numpy as np import dask_distance._utils def test__bool_cmp_mtx_cnt(): u = np.array([0, 0, 0, 1, 1, 1, 1, 1, 1, 1], dtype=bool) v = np.array([0, 1, 1, 0, 0, 0, 1, 1, 1, 1], dtype=bool) uv_cmp_mtx = dask_distance._utils._bool_cmp_mtx_cnt(u, v) uv_cmp_mtx_exp = np.array([[1, 2], [3, 4]], dtype=float) assert (np.array(uv_cmp_mtx) == uv_cmp_mtx_exp).all()
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import import pytest import numpy as np import dask_distance._utils @pytest.mark.parametrize("et, u, v", [ (ValueError, np.zeros((2,), dtype=bool), np.zeros((3,), dtype=bool)), ]) def test__bool_cmp_mtx_cnt_err(et, u, v): with pytest.raises(et): dask_distance._utils._bool_cmp_mtx_cnt(u, v) def test__bool_cmp_mtx_cnt(): u = np.array([0, 0, 0, 1, 1, 1, 1, 1, 1, 1], dtype=bool) v = np.array([0, 1, 1, 0, 0, 0, 1, 1, 1, 1], dtype=bool) uv_cmp_mtx = dask_distance._utils._bool_cmp_mtx_cnt(u, v) uv_cmp_mtx_exp = np.array([[1, 2], [3, 4]], dtype=float) assert (np.array(uv_cmp_mtx) == uv_cmp_mtx_exp).all()
Test mismatched array lengths error in utils
Test mismatched array lengths error in utils Adds a test for `_bool_cmp_mtx_cnt` to make sure that if two arrays are provided with two different lengths that it will raise a `ValueError`.
Python
bsd-3-clause
jakirkham/dask-distance
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import import pytest import numpy as np import dask_distance._utils def test__bool_cmp_mtx_cnt(): u = np.array([0, 0, 0, 1, 1, 1, 1, 1, 1, 1], dtype=bool) v = np.array([0, 1, 1, 0, 0, 0, 1, 1, 1, 1], dtype=bool) uv_cmp_mtx = dask_distance._utils._bool_cmp_mtx_cnt(u, v) uv_cmp_mtx_exp = np.array([[1, 2], [3, 4]], dtype=float) assert (np.array(uv_cmp_mtx) == uv_cmp_mtx_exp).all() Test mismatched array lengths error in utils Adds a test for `_bool_cmp_mtx_cnt` to make sure that if two arrays are provided with two different lengths that it will raise a `ValueError`.
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import import pytest import numpy as np import dask_distance._utils @pytest.mark.parametrize("et, u, v", [ (ValueError, np.zeros((2,), dtype=bool), np.zeros((3,), dtype=bool)), ]) def test__bool_cmp_mtx_cnt_err(et, u, v): with pytest.raises(et): dask_distance._utils._bool_cmp_mtx_cnt(u, v) def test__bool_cmp_mtx_cnt(): u = np.array([0, 0, 0, 1, 1, 1, 1, 1, 1, 1], dtype=bool) v = np.array([0, 1, 1, 0, 0, 0, 1, 1, 1, 1], dtype=bool) uv_cmp_mtx = dask_distance._utils._bool_cmp_mtx_cnt(u, v) uv_cmp_mtx_exp = np.array([[1, 2], [3, 4]], dtype=float) assert (np.array(uv_cmp_mtx) == uv_cmp_mtx_exp).all()
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import import pytest import numpy as np import dask_distance._utils def test__bool_cmp_mtx_cnt(): u = np.array([0, 0, 0, 1, 1, 1, 1, 1, 1, 1], dtype=bool) v = np.array([0, 1, 1, 0, 0, 0, 1, 1, 1, 1], dtype=bool) uv_cmp_mtx = dask_distance._utils._bool_cmp_mtx_cnt(u, v) uv_cmp_mtx_exp = np.array([[1, 2], [3, 4]], dtype=float) assert (np.array(uv_cmp_mtx) == uv_cmp_mtx_exp).all() <commit_msg>Test mismatched array lengths error in utils Adds a test for `_bool_cmp_mtx_cnt` to make sure that if two arrays are provided with two different lengths that it will raise a `ValueError`.<commit_after>
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import import pytest import numpy as np import dask_distance._utils @pytest.mark.parametrize("et, u, v", [ (ValueError, np.zeros((2,), dtype=bool), np.zeros((3,), dtype=bool)), ]) def test__bool_cmp_mtx_cnt_err(et, u, v): with pytest.raises(et): dask_distance._utils._bool_cmp_mtx_cnt(u, v) def test__bool_cmp_mtx_cnt(): u = np.array([0, 0, 0, 1, 1, 1, 1, 1, 1, 1], dtype=bool) v = np.array([0, 1, 1, 0, 0, 0, 1, 1, 1, 1], dtype=bool) uv_cmp_mtx = dask_distance._utils._bool_cmp_mtx_cnt(u, v) uv_cmp_mtx_exp = np.array([[1, 2], [3, 4]], dtype=float) assert (np.array(uv_cmp_mtx) == uv_cmp_mtx_exp).all()
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import import pytest import numpy as np import dask_distance._utils def test__bool_cmp_mtx_cnt(): u = np.array([0, 0, 0, 1, 1, 1, 1, 1, 1, 1], dtype=bool) v = np.array([0, 1, 1, 0, 0, 0, 1, 1, 1, 1], dtype=bool) uv_cmp_mtx = dask_distance._utils._bool_cmp_mtx_cnt(u, v) uv_cmp_mtx_exp = np.array([[1, 2], [3, 4]], dtype=float) assert (np.array(uv_cmp_mtx) == uv_cmp_mtx_exp).all() Test mismatched array lengths error in utils Adds a test for `_bool_cmp_mtx_cnt` to make sure that if two arrays are provided with two different lengths that it will raise a `ValueError`.#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import import pytest import numpy as np import dask_distance._utils @pytest.mark.parametrize("et, u, v", [ (ValueError, np.zeros((2,), dtype=bool), np.zeros((3,), dtype=bool)), ]) def test__bool_cmp_mtx_cnt_err(et, u, v): with pytest.raises(et): dask_distance._utils._bool_cmp_mtx_cnt(u, v) def test__bool_cmp_mtx_cnt(): u = np.array([0, 0, 0, 1, 1, 1, 1, 1, 1, 1], dtype=bool) v = np.array([0, 1, 1, 0, 0, 0, 1, 1, 1, 1], dtype=bool) uv_cmp_mtx = dask_distance._utils._bool_cmp_mtx_cnt(u, v) uv_cmp_mtx_exp = np.array([[1, 2], [3, 4]], dtype=float) assert (np.array(uv_cmp_mtx) == uv_cmp_mtx_exp).all()
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import import pytest import numpy as np import dask_distance._utils def test__bool_cmp_mtx_cnt(): u = np.array([0, 0, 0, 1, 1, 1, 1, 1, 1, 1], dtype=bool) v = np.array([0, 1, 1, 0, 0, 0, 1, 1, 1, 1], dtype=bool) uv_cmp_mtx = dask_distance._utils._bool_cmp_mtx_cnt(u, v) uv_cmp_mtx_exp = np.array([[1, 2], [3, 4]], dtype=float) assert (np.array(uv_cmp_mtx) == uv_cmp_mtx_exp).all() <commit_msg>Test mismatched array lengths error in utils Adds a test for `_bool_cmp_mtx_cnt` to make sure that if two arrays are provided with two different lengths that it will raise a `ValueError`.<commit_after>#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import import pytest import numpy as np import dask_distance._utils @pytest.mark.parametrize("et, u, v", [ (ValueError, np.zeros((2,), dtype=bool), np.zeros((3,), dtype=bool)), ]) def test__bool_cmp_mtx_cnt_err(et, u, v): with pytest.raises(et): dask_distance._utils._bool_cmp_mtx_cnt(u, v) def test__bool_cmp_mtx_cnt(): u = np.array([0, 0, 0, 1, 1, 1, 1, 1, 1, 1], dtype=bool) v = np.array([0, 1, 1, 0, 0, 0, 1, 1, 1, 1], dtype=bool) uv_cmp_mtx = dask_distance._utils._bool_cmp_mtx_cnt(u, v) uv_cmp_mtx_exp = np.array([[1, 2], [3, 4]], dtype=float) assert (np.array(uv_cmp_mtx) == uv_cmp_mtx_exp).all()
2313e2aae705481df5d7ea6c09fcf5e4eaa80cf7
tests/test_client.py
tests/test_client.py
import pytest from aiohttp_json_rpc.client import JsonRpcClient pytestmark = pytest.mark.asyncio(reason='Depends on asyncio') async def test_client_autoconnect(rpc_context): async def ping(request): return 'pong' rpc_context.rpc.add_methods( ('', ping), ) client = JsonRpcClient( url='ws://{host}:{port}{url}'.format( host=rpc_context.host, port=rpc_context.port, url=rpc_context.url, ) ) assert not hasattr(client, '_ws') assert await client.call('ping') == 'pong' assert hasattr(client, '_ws') initial_ws = client._ws assert await client.call('ping') == 'pong' assert initial_ws is client._ws await client.disconnect() assert not hasattr(client, '_ws')
import pytest from aiohttp_json_rpc.client import JsonRpcClient pytestmark = pytest.mark.asyncio(reason='Depends on asyncio') async def test_client_connect_disconnect(rpc_context): async def ping(request): return 'pong' rpc_context.rpc.add_methods( ('', ping), ) client = JsonRpcClient( url='ws://{host}:{port}{url}'.format( host=rpc_context.host, port=rpc_context.port, url=rpc_context.url, ) ) await client.connect_url( 'ws://{host}:{port}{url}'.format( host=rpc_context.host, port=rpc_context.port, url=rpc_context.url, ) ) assert await client.call('ping') == 'pong' await client.disconnect() assert not hasattr(client, '_ws') await client.connect( host=rpc_context.host, port=rpc_context.port, url=rpc_context.url, ) assert await client.call('ping') == 'pong' await client.disconnect() async def test_client_autoconnect(rpc_context): async def ping(request): return 'pong' rpc_context.rpc.add_methods( ('', ping), ) client = JsonRpcClient( url='ws://{host}:{port}{url}'.format( host=rpc_context.host, port=rpc_context.port, url=rpc_context.url, ) ) assert not hasattr(client, '_ws') assert await client.call('ping') == 'pong' assert hasattr(client, '_ws') initial_ws = client._ws assert await client.call('ping') == 'pong' assert initial_ws is client._ws await client.disconnect()
Add test for client connect/disconnect methods
Add test for client connect/disconnect methods
Python
apache-2.0
pengutronix/aiohttp-json-rpc,pengutronix/aiohttp-json-rpc,pengutronix/aiohttp-json-rpc
import pytest from aiohttp_json_rpc.client import JsonRpcClient pytestmark = pytest.mark.asyncio(reason='Depends on asyncio') async def test_client_autoconnect(rpc_context): async def ping(request): return 'pong' rpc_context.rpc.add_methods( ('', ping), ) client = JsonRpcClient( url='ws://{host}:{port}{url}'.format( host=rpc_context.host, port=rpc_context.port, url=rpc_context.url, ) ) assert not hasattr(client, '_ws') assert await client.call('ping') == 'pong' assert hasattr(client, '_ws') initial_ws = client._ws assert await client.call('ping') == 'pong' assert initial_ws is client._ws await client.disconnect() assert not hasattr(client, '_ws') Add test for client connect/disconnect methods
import pytest from aiohttp_json_rpc.client import JsonRpcClient pytestmark = pytest.mark.asyncio(reason='Depends on asyncio') async def test_client_connect_disconnect(rpc_context): async def ping(request): return 'pong' rpc_context.rpc.add_methods( ('', ping), ) client = JsonRpcClient( url='ws://{host}:{port}{url}'.format( host=rpc_context.host, port=rpc_context.port, url=rpc_context.url, ) ) await client.connect_url( 'ws://{host}:{port}{url}'.format( host=rpc_context.host, port=rpc_context.port, url=rpc_context.url, ) ) assert await client.call('ping') == 'pong' await client.disconnect() assert not hasattr(client, '_ws') await client.connect( host=rpc_context.host, port=rpc_context.port, url=rpc_context.url, ) assert await client.call('ping') == 'pong' await client.disconnect() async def test_client_autoconnect(rpc_context): async def ping(request): return 'pong' rpc_context.rpc.add_methods( ('', ping), ) client = JsonRpcClient( url='ws://{host}:{port}{url}'.format( host=rpc_context.host, port=rpc_context.port, url=rpc_context.url, ) ) assert not hasattr(client, '_ws') assert await client.call('ping') == 'pong' assert hasattr(client, '_ws') initial_ws = client._ws assert await client.call('ping') == 'pong' assert initial_ws is client._ws await client.disconnect()
<commit_before>import pytest from aiohttp_json_rpc.client import JsonRpcClient pytestmark = pytest.mark.asyncio(reason='Depends on asyncio') async def test_client_autoconnect(rpc_context): async def ping(request): return 'pong' rpc_context.rpc.add_methods( ('', ping), ) client = JsonRpcClient( url='ws://{host}:{port}{url}'.format( host=rpc_context.host, port=rpc_context.port, url=rpc_context.url, ) ) assert not hasattr(client, '_ws') assert await client.call('ping') == 'pong' assert hasattr(client, '_ws') initial_ws = client._ws assert await client.call('ping') == 'pong' assert initial_ws is client._ws await client.disconnect() assert not hasattr(client, '_ws') <commit_msg>Add test for client connect/disconnect methods<commit_after>
import pytest from aiohttp_json_rpc.client import JsonRpcClient pytestmark = pytest.mark.asyncio(reason='Depends on asyncio') async def test_client_connect_disconnect(rpc_context): async def ping(request): return 'pong' rpc_context.rpc.add_methods( ('', ping), ) client = JsonRpcClient( url='ws://{host}:{port}{url}'.format( host=rpc_context.host, port=rpc_context.port, url=rpc_context.url, ) ) await client.connect_url( 'ws://{host}:{port}{url}'.format( host=rpc_context.host, port=rpc_context.port, url=rpc_context.url, ) ) assert await client.call('ping') == 'pong' await client.disconnect() assert not hasattr(client, '_ws') await client.connect( host=rpc_context.host, port=rpc_context.port, url=rpc_context.url, ) assert await client.call('ping') == 'pong' await client.disconnect() async def test_client_autoconnect(rpc_context): async def ping(request): return 'pong' rpc_context.rpc.add_methods( ('', ping), ) client = JsonRpcClient( url='ws://{host}:{port}{url}'.format( host=rpc_context.host, port=rpc_context.port, url=rpc_context.url, ) ) assert not hasattr(client, '_ws') assert await client.call('ping') == 'pong' assert hasattr(client, '_ws') initial_ws = client._ws assert await client.call('ping') == 'pong' assert initial_ws is client._ws await client.disconnect()
import pytest from aiohttp_json_rpc.client import JsonRpcClient pytestmark = pytest.mark.asyncio(reason='Depends on asyncio') async def test_client_autoconnect(rpc_context): async def ping(request): return 'pong' rpc_context.rpc.add_methods( ('', ping), ) client = JsonRpcClient( url='ws://{host}:{port}{url}'.format( host=rpc_context.host, port=rpc_context.port, url=rpc_context.url, ) ) assert not hasattr(client, '_ws') assert await client.call('ping') == 'pong' assert hasattr(client, '_ws') initial_ws = client._ws assert await client.call('ping') == 'pong' assert initial_ws is client._ws await client.disconnect() assert not hasattr(client, '_ws') Add test for client connect/disconnect methodsimport pytest from aiohttp_json_rpc.client import JsonRpcClient pytestmark = pytest.mark.asyncio(reason='Depends on asyncio') async def test_client_connect_disconnect(rpc_context): async def ping(request): return 'pong' rpc_context.rpc.add_methods( ('', ping), ) client = JsonRpcClient( url='ws://{host}:{port}{url}'.format( host=rpc_context.host, port=rpc_context.port, url=rpc_context.url, ) ) await client.connect_url( 'ws://{host}:{port}{url}'.format( host=rpc_context.host, port=rpc_context.port, url=rpc_context.url, ) ) assert await client.call('ping') == 'pong' await client.disconnect() assert not hasattr(client, '_ws') await client.connect( host=rpc_context.host, port=rpc_context.port, url=rpc_context.url, ) assert await client.call('ping') == 'pong' await client.disconnect() async def test_client_autoconnect(rpc_context): async def ping(request): return 'pong' rpc_context.rpc.add_methods( ('', ping), ) client = JsonRpcClient( url='ws://{host}:{port}{url}'.format( host=rpc_context.host, port=rpc_context.port, url=rpc_context.url, ) ) assert not hasattr(client, '_ws') assert await client.call('ping') == 'pong' assert hasattr(client, '_ws') initial_ws = client._ws assert await client.call('ping') == 'pong' assert initial_ws is client._ws await client.disconnect()
<commit_before>import pytest from aiohttp_json_rpc.client import JsonRpcClient pytestmark = pytest.mark.asyncio(reason='Depends on asyncio') async def test_client_autoconnect(rpc_context): async def ping(request): return 'pong' rpc_context.rpc.add_methods( ('', ping), ) client = JsonRpcClient( url='ws://{host}:{port}{url}'.format( host=rpc_context.host, port=rpc_context.port, url=rpc_context.url, ) ) assert not hasattr(client, '_ws') assert await client.call('ping') == 'pong' assert hasattr(client, '_ws') initial_ws = client._ws assert await client.call('ping') == 'pong' assert initial_ws is client._ws await client.disconnect() assert not hasattr(client, '_ws') <commit_msg>Add test for client connect/disconnect methods<commit_after>import pytest from aiohttp_json_rpc.client import JsonRpcClient pytestmark = pytest.mark.asyncio(reason='Depends on asyncio') async def test_client_connect_disconnect(rpc_context): async def ping(request): return 'pong' rpc_context.rpc.add_methods( ('', ping), ) client = JsonRpcClient( url='ws://{host}:{port}{url}'.format( host=rpc_context.host, port=rpc_context.port, url=rpc_context.url, ) ) await client.connect_url( 'ws://{host}:{port}{url}'.format( host=rpc_context.host, port=rpc_context.port, url=rpc_context.url, ) ) assert await client.call('ping') == 'pong' await client.disconnect() assert not hasattr(client, '_ws') await client.connect( host=rpc_context.host, port=rpc_context.port, url=rpc_context.url, ) assert await client.call('ping') == 'pong' await client.disconnect() async def test_client_autoconnect(rpc_context): async def ping(request): return 'pong' rpc_context.rpc.add_methods( ('', ping), ) client = JsonRpcClient( url='ws://{host}:{port}{url}'.format( host=rpc_context.host, port=rpc_context.port, url=rpc_context.url, ) ) assert not hasattr(client, '_ws') assert await client.call('ping') == 'pong' assert hasattr(client, '_ws') initial_ws = client._ws assert await client.call('ping') == 'pong' assert initial_ws is client._ws await client.disconnect()
135b949eb33c75ba097aa17ade777bd39877365e
tests/test_flake8.py
tests/test_flake8.py
from subprocess import CalledProcessError, check_output as run FLAKE8_COMMAND = 'flake8' FLAKE8_INPUTS = [ 'skylines', 'tests' ] FLAKE8_EXCLUDES = [ 'geoid.py' ] def pytest_generate_tests(metafunc): metafunc.parametrize('folder', FLAKE8_INPUTS) def test_flake8(folder): """ Run skylines package through flake8 """ try: run([FLAKE8_COMMAND, folder, '--exclude=' + ','.join(FLAKE8_EXCLUDES)]) except CalledProcessError, e: print e.output raise AssertionError('flake8 has found errors.') except OSError: raise OSError('Failed to run flake8. Please check that you have ' 'installed it properly.')
from subprocess import CalledProcessError, check_output as run FLAKE8_COMMAND = 'flake8' FLAKE8_INPUTS = [ 'skylines', 'tests' ] def pytest_generate_tests(metafunc): metafunc.parametrize('folder', FLAKE8_INPUTS) def test_flake8(folder): """ Run skylines package through flake8 """ try: run([FLAKE8_COMMAND, folder]) except CalledProcessError, e: print e.output raise AssertionError('flake8 has found errors.') except OSError: raise OSError('Failed to run flake8. Please check that you have ' 'installed it properly.')
Revert "flake8: Ignore geoid.py issues"
Revert "flake8: Ignore geoid.py issues" This reverts commit a70cea27c37c1ced21d51b950f49d4987f501385.
Python
agpl-3.0
shadowoneau/skylines,skylines-project/skylines,RBE-Avionik/skylines,TobiasLohner/SkyLines,RBE-Avionik/skylines,kerel-fs/skylines,TobiasLohner/SkyLines,skylines-project/skylines,Harry-R/skylines,shadowoneau/skylines,Harry-R/skylines,snip/skylines,Turbo87/skylines,skylines-project/skylines,skylines-project/skylines,Turbo87/skylines,shadowoneau/skylines,shadowoneau/skylines,snip/skylines,snip/skylines,Turbo87/skylines,Harry-R/skylines,Harry-R/skylines,RBE-Avionik/skylines,Turbo87/skylines,kerel-fs/skylines,RBE-Avionik/skylines,TobiasLohner/SkyLines,kerel-fs/skylines
from subprocess import CalledProcessError, check_output as run FLAKE8_COMMAND = 'flake8' FLAKE8_INPUTS = [ 'skylines', 'tests' ] FLAKE8_EXCLUDES = [ 'geoid.py' ] def pytest_generate_tests(metafunc): metafunc.parametrize('folder', FLAKE8_INPUTS) def test_flake8(folder): """ Run skylines package through flake8 """ try: run([FLAKE8_COMMAND, folder, '--exclude=' + ','.join(FLAKE8_EXCLUDES)]) except CalledProcessError, e: print e.output raise AssertionError('flake8 has found errors.') except OSError: raise OSError('Failed to run flake8. Please check that you have ' 'installed it properly.') Revert "flake8: Ignore geoid.py issues" This reverts commit a70cea27c37c1ced21d51b950f49d4987f501385.
from subprocess import CalledProcessError, check_output as run FLAKE8_COMMAND = 'flake8' FLAKE8_INPUTS = [ 'skylines', 'tests' ] def pytest_generate_tests(metafunc): metafunc.parametrize('folder', FLAKE8_INPUTS) def test_flake8(folder): """ Run skylines package through flake8 """ try: run([FLAKE8_COMMAND, folder]) except CalledProcessError, e: print e.output raise AssertionError('flake8 has found errors.') except OSError: raise OSError('Failed to run flake8. Please check that you have ' 'installed it properly.')
<commit_before>from subprocess import CalledProcessError, check_output as run FLAKE8_COMMAND = 'flake8' FLAKE8_INPUTS = [ 'skylines', 'tests' ] FLAKE8_EXCLUDES = [ 'geoid.py' ] def pytest_generate_tests(metafunc): metafunc.parametrize('folder', FLAKE8_INPUTS) def test_flake8(folder): """ Run skylines package through flake8 """ try: run([FLAKE8_COMMAND, folder, '--exclude=' + ','.join(FLAKE8_EXCLUDES)]) except CalledProcessError, e: print e.output raise AssertionError('flake8 has found errors.') except OSError: raise OSError('Failed to run flake8. Please check that you have ' 'installed it properly.') <commit_msg>Revert "flake8: Ignore geoid.py issues" This reverts commit a70cea27c37c1ced21d51b950f49d4987f501385.<commit_after>
from subprocess import CalledProcessError, check_output as run FLAKE8_COMMAND = 'flake8' FLAKE8_INPUTS = [ 'skylines', 'tests' ] def pytest_generate_tests(metafunc): metafunc.parametrize('folder', FLAKE8_INPUTS) def test_flake8(folder): """ Run skylines package through flake8 """ try: run([FLAKE8_COMMAND, folder]) except CalledProcessError, e: print e.output raise AssertionError('flake8 has found errors.') except OSError: raise OSError('Failed to run flake8. Please check that you have ' 'installed it properly.')
from subprocess import CalledProcessError, check_output as run FLAKE8_COMMAND = 'flake8' FLAKE8_INPUTS = [ 'skylines', 'tests' ] FLAKE8_EXCLUDES = [ 'geoid.py' ] def pytest_generate_tests(metafunc): metafunc.parametrize('folder', FLAKE8_INPUTS) def test_flake8(folder): """ Run skylines package through flake8 """ try: run([FLAKE8_COMMAND, folder, '--exclude=' + ','.join(FLAKE8_EXCLUDES)]) except CalledProcessError, e: print e.output raise AssertionError('flake8 has found errors.') except OSError: raise OSError('Failed to run flake8. Please check that you have ' 'installed it properly.') Revert "flake8: Ignore geoid.py issues" This reverts commit a70cea27c37c1ced21d51b950f49d4987f501385.from subprocess import CalledProcessError, check_output as run FLAKE8_COMMAND = 'flake8' FLAKE8_INPUTS = [ 'skylines', 'tests' ] def pytest_generate_tests(metafunc): metafunc.parametrize('folder', FLAKE8_INPUTS) def test_flake8(folder): """ Run skylines package through flake8 """ try: run([FLAKE8_COMMAND, folder]) except CalledProcessError, e: print e.output raise AssertionError('flake8 has found errors.') except OSError: raise OSError('Failed to run flake8. Please check that you have ' 'installed it properly.')
<commit_before>from subprocess import CalledProcessError, check_output as run FLAKE8_COMMAND = 'flake8' FLAKE8_INPUTS = [ 'skylines', 'tests' ] FLAKE8_EXCLUDES = [ 'geoid.py' ] def pytest_generate_tests(metafunc): metafunc.parametrize('folder', FLAKE8_INPUTS) def test_flake8(folder): """ Run skylines package through flake8 """ try: run([FLAKE8_COMMAND, folder, '--exclude=' + ','.join(FLAKE8_EXCLUDES)]) except CalledProcessError, e: print e.output raise AssertionError('flake8 has found errors.') except OSError: raise OSError('Failed to run flake8. Please check that you have ' 'installed it properly.') <commit_msg>Revert "flake8: Ignore geoid.py issues" This reverts commit a70cea27c37c1ced21d51b950f49d4987f501385.<commit_after>from subprocess import CalledProcessError, check_output as run FLAKE8_COMMAND = 'flake8' FLAKE8_INPUTS = [ 'skylines', 'tests' ] def pytest_generate_tests(metafunc): metafunc.parametrize('folder', FLAKE8_INPUTS) def test_flake8(folder): """ Run skylines package through flake8 """ try: run([FLAKE8_COMMAND, folder]) except CalledProcessError, e: print e.output raise AssertionError('flake8 has found errors.') except OSError: raise OSError('Failed to run flake8. Please check that you have ' 'installed it properly.')
776fcbce9f23e799cd3101ddfa0bb966898d7064
tests/test_status.py
tests/test_status.py
import re import pkg_resources from pip import __version__ from pip.commands.status import search_packages_info from tests.test_pip import reset_env, run_pip def test_status(): """ Test end to end test for status command. """ dist = pkg_resources.get_distribution('pip') reset_env() result = run_pip('status', 'pip') lines = result.stdout.split('\n') assert len(lines) == 7 assert '---', lines[0] assert re.match('^Name\: pip$', lines[1]) assert re.match('^Version\: %s$' % __version__, lines[2]) assert 'Location: %s' % dist.location, lines[3] assert 'Files:' == lines[4] assert 'Cannot locate installed-files.txt' == lines[5] def test_find_package_not_found(): """ Test trying to get info about a inexistent package. """ result = search_packages_info(['abcd3']) assert len(list(result)) == 0 def test_search_any_case(): """ Search for a package in any case. """ result = list(search_packages_info(['PIP'])) assert len(result) == 1 assert 'pip' == result[0]['name']
import re import pkg_resources from pip import __version__ from pip.commands.status import search_packages_info from tests.test_pip import reset_env, run_pip def test_status(): """ Test end to end test for status command. """ dist = pkg_resources.get_distribution('pip') reset_env() result = run_pip('status', 'pip') lines = result.stdout.split('\n') assert len(lines) == 7 assert '---', lines[0] assert re.match('^Name\: pip$', lines[1]) assert re.match('^Version\: %s$' % __version__, lines[2]) assert 'Location: %s' % dist.location, lines[3] assert 'Files:' == lines[4] assert 'Cannot locate installed-files.txt' == lines[5] def test_missing_argument(): """ Test status command with no arguments. """ dist = pkg_resources.get_distribution('pip') reset_env() result = run_pip('status') assert 'ERROR: Missing required argument (status query).' in result.stdout def test_find_package_not_found(): """ Test trying to get info about a inexistent package. """ result = search_packages_info(['abcd3']) assert len(list(result)) == 0 def test_search_any_case(): """ Search for a package in any case. """ result = list(search_packages_info(['PIP'])) assert len(result) == 1 assert 'pip' == result[0]['name'] def test_more_than_one_package(): """ Search for more than one package. """ result = list(search_packages_info(['Pip', 'Nose', 'Virtualenv'])) assert len(result) == 3
Test search for more than one distribution.
Test search for more than one distribution.
Python
mit
fiber-space/pip,qwcode/pip,msabramo/pip,blarghmatey/pip,jamezpolley/pip,jythontools/pip,ChristopherHogan/pip,rouge8/pip,rbtcollins/pip,qwcode/pip,nthall/pip,esc/pip,chaoallsome/pip,ianw/pip,jamezpolley/pip,jamezpolley/pip,pradyunsg/pip,KarelJakubec/pip,haridsv/pip,zorosteven/pip,fiber-space/pip,pfmoore/pip,h4ck3rm1k3/pip,erikrose/pip,yati-sagade/pip,esc/pip,pjdelport/pip,qbdsoft/pip,Ivoz/pip,techtonik/pip,mattrobenolt/pip,nthall/pip,cjerdonek/pip,zenlambda/pip,luzfcb/pip,caosmo/pip,ncoghlan/pip,willingc/pip,ChristopherHogan/pip,alquerci/pip,mujiansu/pip,Carreau/pip,graingert/pip,xavfernandez/pip,natefoo/pip,ncoghlan/pip,Gabriel439/pip,tdsmith/pip,esc/pip,h4ck3rm1k3/pip,sigmavirus24/pip,natefoo/pip,zvezdan/pip,atdaemon/pip,ianw/pip,rbtcollins/pip,zvezdan/pip,rbtcollins/pip,mindw/pip,sbidoul/pip,willingc/pip,alex/pip,graingert/pip,Gabriel439/pip,dstufft/pip,blarghmatey/pip,jasonkying/pip,squidsoup/pip,RonnyPfannschmidt/pip,pypa/pip,jmagnusson/pip,sigmavirus24/pip,wkeyword/pip,supriyantomaftuh/pip,wkeyword/pip,patricklaw/pip,prasaianooz/pip,pjdelport/pip,prasaianooz/pip,ncoghlan/pip,chaoallsome/pip,tdsmith/pip,zvezdan/pip,sbidoul/pip,zorosteven/pip,pypa/pip,KarelJakubec/pip,dstufft/pip,alquerci/pip,atdaemon/pip,harrisonfeng/pip,benesch/pip,blarghmatey/pip,haridsv/pip,harrisonfeng/pip,radiosilence/pip,mujiansu/pip,squidsoup/pip,wkeyword/pip,supriyantomaftuh/pip,James-Firth/pip,habnabit/pip,benesch/pip,qbdsoft/pip,fiber-space/pip,davidovich/pip,haridsv/pip,caosmo/pip,zenlambda/pip,xavfernandez/pip,cjerdonek/pip,jasonkying/pip,h4ck3rm1k3/pip,rouge8/pip,mindw/pip,tdsmith/pip,natefoo/pip,habnabit/pip,pfmoore/pip,davidovich/pip,atdaemon/pip,sigmavirus24/pip,chaoallsome/pip,yati-sagade/pip,jythontools/pip,luzfcb/pip,willingc/pip,RonnyPfannschmidt/pip,jmagnusson/pip,yati-sagade/pip,zenlambda/pip,techtonik/pip,minrk/pip,luzfcb/pip,Ivoz/pip,benesch/pip,prasaianooz/pip,pradyunsg/pip,mujiansu/pip,qbdsoft/pip,minrk/pip,erikrose/pip,techtonik/pip,Gabriel439/pip,ChristopherHogan/pip,supriyantomaftuh/pip,Carreau/pip,jythontools/pip,mattrobenolt/pip,davidovich/pip,msabramo/pip,erikrose/pip,KarelJakubec/pip,xavfernandez/pip,rouge8/pip,nthall/pip,jmagnusson/pip,zorosteven/pip,habnabit/pip,squidsoup/pip,alex/pip,RonnyPfannschmidt/pip,graingert/pip,patricklaw/pip,caosmo/pip,harrisonfeng/pip,mindw/pip,James-Firth/pip,jasonkying/pip,alex/pip,James-Firth/pip,pjdelport/pip,dstufft/pip
import re import pkg_resources from pip import __version__ from pip.commands.status import search_packages_info from tests.test_pip import reset_env, run_pip def test_status(): """ Test end to end test for status command. """ dist = pkg_resources.get_distribution('pip') reset_env() result = run_pip('status', 'pip') lines = result.stdout.split('\n') assert len(lines) == 7 assert '---', lines[0] assert re.match('^Name\: pip$', lines[1]) assert re.match('^Version\: %s$' % __version__, lines[2]) assert 'Location: %s' % dist.location, lines[3] assert 'Files:' == lines[4] assert 'Cannot locate installed-files.txt' == lines[5] def test_find_package_not_found(): """ Test trying to get info about a inexistent package. """ result = search_packages_info(['abcd3']) assert len(list(result)) == 0 def test_search_any_case(): """ Search for a package in any case. """ result = list(search_packages_info(['PIP'])) assert len(result) == 1 assert 'pip' == result[0]['name'] Test search for more than one distribution.
import re import pkg_resources from pip import __version__ from pip.commands.status import search_packages_info from tests.test_pip import reset_env, run_pip def test_status(): """ Test end to end test for status command. """ dist = pkg_resources.get_distribution('pip') reset_env() result = run_pip('status', 'pip') lines = result.stdout.split('\n') assert len(lines) == 7 assert '---', lines[0] assert re.match('^Name\: pip$', lines[1]) assert re.match('^Version\: %s$' % __version__, lines[2]) assert 'Location: %s' % dist.location, lines[3] assert 'Files:' == lines[4] assert 'Cannot locate installed-files.txt' == lines[5] def test_missing_argument(): """ Test status command with no arguments. """ dist = pkg_resources.get_distribution('pip') reset_env() result = run_pip('status') assert 'ERROR: Missing required argument (status query).' in result.stdout def test_find_package_not_found(): """ Test trying to get info about a inexistent package. """ result = search_packages_info(['abcd3']) assert len(list(result)) == 0 def test_search_any_case(): """ Search for a package in any case. """ result = list(search_packages_info(['PIP'])) assert len(result) == 1 assert 'pip' == result[0]['name'] def test_more_than_one_package(): """ Search for more than one package. """ result = list(search_packages_info(['Pip', 'Nose', 'Virtualenv'])) assert len(result) == 3
<commit_before>import re import pkg_resources from pip import __version__ from pip.commands.status import search_packages_info from tests.test_pip import reset_env, run_pip def test_status(): """ Test end to end test for status command. """ dist = pkg_resources.get_distribution('pip') reset_env() result = run_pip('status', 'pip') lines = result.stdout.split('\n') assert len(lines) == 7 assert '---', lines[0] assert re.match('^Name\: pip$', lines[1]) assert re.match('^Version\: %s$' % __version__, lines[2]) assert 'Location: %s' % dist.location, lines[3] assert 'Files:' == lines[4] assert 'Cannot locate installed-files.txt' == lines[5] def test_find_package_not_found(): """ Test trying to get info about a inexistent package. """ result = search_packages_info(['abcd3']) assert len(list(result)) == 0 def test_search_any_case(): """ Search for a package in any case. """ result = list(search_packages_info(['PIP'])) assert len(result) == 1 assert 'pip' == result[0]['name'] <commit_msg>Test search for more than one distribution.<commit_after>
import re import pkg_resources from pip import __version__ from pip.commands.status import search_packages_info from tests.test_pip import reset_env, run_pip def test_status(): """ Test end to end test for status command. """ dist = pkg_resources.get_distribution('pip') reset_env() result = run_pip('status', 'pip') lines = result.stdout.split('\n') assert len(lines) == 7 assert '---', lines[0] assert re.match('^Name\: pip$', lines[1]) assert re.match('^Version\: %s$' % __version__, lines[2]) assert 'Location: %s' % dist.location, lines[3] assert 'Files:' == lines[4] assert 'Cannot locate installed-files.txt' == lines[5] def test_missing_argument(): """ Test status command with no arguments. """ dist = pkg_resources.get_distribution('pip') reset_env() result = run_pip('status') assert 'ERROR: Missing required argument (status query).' in result.stdout def test_find_package_not_found(): """ Test trying to get info about a inexistent package. """ result = search_packages_info(['abcd3']) assert len(list(result)) == 0 def test_search_any_case(): """ Search for a package in any case. """ result = list(search_packages_info(['PIP'])) assert len(result) == 1 assert 'pip' == result[0]['name'] def test_more_than_one_package(): """ Search for more than one package. """ result = list(search_packages_info(['Pip', 'Nose', 'Virtualenv'])) assert len(result) == 3
import re import pkg_resources from pip import __version__ from pip.commands.status import search_packages_info from tests.test_pip import reset_env, run_pip def test_status(): """ Test end to end test for status command. """ dist = pkg_resources.get_distribution('pip') reset_env() result = run_pip('status', 'pip') lines = result.stdout.split('\n') assert len(lines) == 7 assert '---', lines[0] assert re.match('^Name\: pip$', lines[1]) assert re.match('^Version\: %s$' % __version__, lines[2]) assert 'Location: %s' % dist.location, lines[3] assert 'Files:' == lines[4] assert 'Cannot locate installed-files.txt' == lines[5] def test_find_package_not_found(): """ Test trying to get info about a inexistent package. """ result = search_packages_info(['abcd3']) assert len(list(result)) == 0 def test_search_any_case(): """ Search for a package in any case. """ result = list(search_packages_info(['PIP'])) assert len(result) == 1 assert 'pip' == result[0]['name'] Test search for more than one distribution.import re import pkg_resources from pip import __version__ from pip.commands.status import search_packages_info from tests.test_pip import reset_env, run_pip def test_status(): """ Test end to end test for status command. """ dist = pkg_resources.get_distribution('pip') reset_env() result = run_pip('status', 'pip') lines = result.stdout.split('\n') assert len(lines) == 7 assert '---', lines[0] assert re.match('^Name\: pip$', lines[1]) assert re.match('^Version\: %s$' % __version__, lines[2]) assert 'Location: %s' % dist.location, lines[3] assert 'Files:' == lines[4] assert 'Cannot locate installed-files.txt' == lines[5] def test_missing_argument(): """ Test status command with no arguments. """ dist = pkg_resources.get_distribution('pip') reset_env() result = run_pip('status') assert 'ERROR: Missing required argument (status query).' in result.stdout def test_find_package_not_found(): """ Test trying to get info about a inexistent package. """ result = search_packages_info(['abcd3']) assert len(list(result)) == 0 def test_search_any_case(): """ Search for a package in any case. """ result = list(search_packages_info(['PIP'])) assert len(result) == 1 assert 'pip' == result[0]['name'] def test_more_than_one_package(): """ Search for more than one package. """ result = list(search_packages_info(['Pip', 'Nose', 'Virtualenv'])) assert len(result) == 3
<commit_before>import re import pkg_resources from pip import __version__ from pip.commands.status import search_packages_info from tests.test_pip import reset_env, run_pip def test_status(): """ Test end to end test for status command. """ dist = pkg_resources.get_distribution('pip') reset_env() result = run_pip('status', 'pip') lines = result.stdout.split('\n') assert len(lines) == 7 assert '---', lines[0] assert re.match('^Name\: pip$', lines[1]) assert re.match('^Version\: %s$' % __version__, lines[2]) assert 'Location: %s' % dist.location, lines[3] assert 'Files:' == lines[4] assert 'Cannot locate installed-files.txt' == lines[5] def test_find_package_not_found(): """ Test trying to get info about a inexistent package. """ result = search_packages_info(['abcd3']) assert len(list(result)) == 0 def test_search_any_case(): """ Search for a package in any case. """ result = list(search_packages_info(['PIP'])) assert len(result) == 1 assert 'pip' == result[0]['name'] <commit_msg>Test search for more than one distribution.<commit_after>import re import pkg_resources from pip import __version__ from pip.commands.status import search_packages_info from tests.test_pip import reset_env, run_pip def test_status(): """ Test end to end test for status command. """ dist = pkg_resources.get_distribution('pip') reset_env() result = run_pip('status', 'pip') lines = result.stdout.split('\n') assert len(lines) == 7 assert '---', lines[0] assert re.match('^Name\: pip$', lines[1]) assert re.match('^Version\: %s$' % __version__, lines[2]) assert 'Location: %s' % dist.location, lines[3] assert 'Files:' == lines[4] assert 'Cannot locate installed-files.txt' == lines[5] def test_missing_argument(): """ Test status command with no arguments. """ dist = pkg_resources.get_distribution('pip') reset_env() result = run_pip('status') assert 'ERROR: Missing required argument (status query).' in result.stdout def test_find_package_not_found(): """ Test trying to get info about a inexistent package. """ result = search_packages_info(['abcd3']) assert len(list(result)) == 0 def test_search_any_case(): """ Search for a package in any case. """ result = list(search_packages_info(['PIP'])) assert len(result) == 1 assert 'pip' == result[0]['name'] def test_more_than_one_package(): """ Search for more than one package. """ result = list(search_packages_info(['Pip', 'Nose', 'Virtualenv'])) assert len(result) == 3
f5373bb2153715c6d349d48890d9f03b1e24b847
backslash/contrib/keepalive_thread.py
backslash/contrib/keepalive_thread.py
import threading import logbook _logger = logbook.Logger(__name__) class KeepaliveThread(threading.Thread): def __init__(self, client, session, interval): super(KeepaliveThread, self).__init__() self._client = client self._session = session self._interval = interval / 2.0 self._stopped_event = threading.Event() self.daemon = True def run(self): while not self._stopped_event.is_set(): self._stopped_event.wait(timeout=self._interval) self._session.send_keepalive() def stop(self): self._stopped_event.set()
import threading import logbook _logger = logbook.Logger(__name__) class KeepaliveThread(threading.Thread): def __init__(self, client, session, interval): super(KeepaliveThread, self).__init__() self._client = client self._session = session self._interval = interval / 2.0 self._stopped_event = threading.Event() self.daemon = True def run(self): _logger.debug('Backslash keepalive thread started') try: while not self._stopped_event.is_set(): self._stopped_event.wait(timeout=self._interval) self._session.send_keepalive() except Exception: #pylint: disable=broad-except _logger.error('Quitting keepalive thread due to exception', exc_info=True) raise finally: _logger.debug('Backslash keepalive thread terminated') def stop(self): self._stopped_event.set()
Add debug logs to keepalive thread
Add debug logs to keepalive thread
Python
bsd-3-clause
vmalloc/backslash-python,slash-testing/backslash-python
import threading import logbook _logger = logbook.Logger(__name__) class KeepaliveThread(threading.Thread): def __init__(self, client, session, interval): super(KeepaliveThread, self).__init__() self._client = client self._session = session self._interval = interval / 2.0 self._stopped_event = threading.Event() self.daemon = True def run(self): while not self._stopped_event.is_set(): self._stopped_event.wait(timeout=self._interval) self._session.send_keepalive() def stop(self): self._stopped_event.set() Add debug logs to keepalive thread
import threading import logbook _logger = logbook.Logger(__name__) class KeepaliveThread(threading.Thread): def __init__(self, client, session, interval): super(KeepaliveThread, self).__init__() self._client = client self._session = session self._interval = interval / 2.0 self._stopped_event = threading.Event() self.daemon = True def run(self): _logger.debug('Backslash keepalive thread started') try: while not self._stopped_event.is_set(): self._stopped_event.wait(timeout=self._interval) self._session.send_keepalive() except Exception: #pylint: disable=broad-except _logger.error('Quitting keepalive thread due to exception', exc_info=True) raise finally: _logger.debug('Backslash keepalive thread terminated') def stop(self): self._stopped_event.set()
<commit_before>import threading import logbook _logger = logbook.Logger(__name__) class KeepaliveThread(threading.Thread): def __init__(self, client, session, interval): super(KeepaliveThread, self).__init__() self._client = client self._session = session self._interval = interval / 2.0 self._stopped_event = threading.Event() self.daemon = True def run(self): while not self._stopped_event.is_set(): self._stopped_event.wait(timeout=self._interval) self._session.send_keepalive() def stop(self): self._stopped_event.set() <commit_msg>Add debug logs to keepalive thread<commit_after>
import threading import logbook _logger = logbook.Logger(__name__) class KeepaliveThread(threading.Thread): def __init__(self, client, session, interval): super(KeepaliveThread, self).__init__() self._client = client self._session = session self._interval = interval / 2.0 self._stopped_event = threading.Event() self.daemon = True def run(self): _logger.debug('Backslash keepalive thread started') try: while not self._stopped_event.is_set(): self._stopped_event.wait(timeout=self._interval) self._session.send_keepalive() except Exception: #pylint: disable=broad-except _logger.error('Quitting keepalive thread due to exception', exc_info=True) raise finally: _logger.debug('Backslash keepalive thread terminated') def stop(self): self._stopped_event.set()
import threading import logbook _logger = logbook.Logger(__name__) class KeepaliveThread(threading.Thread): def __init__(self, client, session, interval): super(KeepaliveThread, self).__init__() self._client = client self._session = session self._interval = interval / 2.0 self._stopped_event = threading.Event() self.daemon = True def run(self): while not self._stopped_event.is_set(): self._stopped_event.wait(timeout=self._interval) self._session.send_keepalive() def stop(self): self._stopped_event.set() Add debug logs to keepalive threadimport threading import logbook _logger = logbook.Logger(__name__) class KeepaliveThread(threading.Thread): def __init__(self, client, session, interval): super(KeepaliveThread, self).__init__() self._client = client self._session = session self._interval = interval / 2.0 self._stopped_event = threading.Event() self.daemon = True def run(self): _logger.debug('Backslash keepalive thread started') try: while not self._stopped_event.is_set(): self._stopped_event.wait(timeout=self._interval) self._session.send_keepalive() except Exception: #pylint: disable=broad-except _logger.error('Quitting keepalive thread due to exception', exc_info=True) raise finally: _logger.debug('Backslash keepalive thread terminated') def stop(self): self._stopped_event.set()
<commit_before>import threading import logbook _logger = logbook.Logger(__name__) class KeepaliveThread(threading.Thread): def __init__(self, client, session, interval): super(KeepaliveThread, self).__init__() self._client = client self._session = session self._interval = interval / 2.0 self._stopped_event = threading.Event() self.daemon = True def run(self): while not self._stopped_event.is_set(): self._stopped_event.wait(timeout=self._interval) self._session.send_keepalive() def stop(self): self._stopped_event.set() <commit_msg>Add debug logs to keepalive thread<commit_after>import threading import logbook _logger = logbook.Logger(__name__) class KeepaliveThread(threading.Thread): def __init__(self, client, session, interval): super(KeepaliveThread, self).__init__() self._client = client self._session = session self._interval = interval / 2.0 self._stopped_event = threading.Event() self.daemon = True def run(self): _logger.debug('Backslash keepalive thread started') try: while not self._stopped_event.is_set(): self._stopped_event.wait(timeout=self._interval) self._session.send_keepalive() except Exception: #pylint: disable=broad-except _logger.error('Quitting keepalive thread due to exception', exc_info=True) raise finally: _logger.debug('Backslash keepalive thread terminated') def stop(self): self._stopped_event.set()
2b9740d875faddc4b30835e5540e5aa7733e288e
apps/reactions/admin.py
apps/reactions/admin.py
from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from .models import Reaction class ReactionAdmin(admin.ModelAdmin): fieldsets = ( (None, { 'fields': ('content_type', 'object_pk'), }), (_('Content'), { 'fields': ('author', 'editor', 'reaction'), }), (_('Metadata'), { 'fields': ('deleted', 'ip_address'), }), ) list_display = ('author_full_name', 'content_type', 'object_pk', 'ip_address', 'created', 'updated', 'deleted') list_filter = ('created', 'updated', 'deleted') date_hierarchy = 'updated' ordering = ('-updated',) raw_id_fields = ('author', 'editor') search_fields = ('reaction', 'author__username', 'author__email', 'author__first_name', 'author__last_name', 'ip_address') def author_full_name(self, obj): full_name = obj.author.get_full_name() if not full_name: return obj.author.username else: return full_name author_full_name.short_description = _('Author') admin.site.register(Reaction, ReactionAdmin)
from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from .models import Reaction class ReactionAdmin(admin.ModelAdmin): fieldsets = ( (None, { 'fields': ('content_type', 'object_pk'), }), (_('Content'), { 'fields': ('author', 'editor', 'reaction'), }), (_('Metadata'), { 'fields': ('deleted', 'ip_address'), }), ) list_display = ('author_full_name', 'content_type', 'object_pk', 'ip_address', 'created', 'updated', 'deleted') list_filter = ('created', 'updated', 'deleted') date_hierarchy = 'created' ordering = ('-created',) raw_id_fields = ('author', 'editor') search_fields = ('reaction', 'author__username', 'author__email', 'author__first_name', 'author__last_name', 'ip_address') def author_full_name(self, obj): full_name = obj.author.get_full_name() if not full_name: return obj.author.username else: return full_name author_full_name.short_description = _('Author') admin.site.register(Reaction, ReactionAdmin)
Use created for ordering and date_hierarchy in ReactionAdmin.
Use created for ordering and date_hierarchy in ReactionAdmin.
Python
bsd-3-clause
onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site
from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from .models import Reaction class ReactionAdmin(admin.ModelAdmin): fieldsets = ( (None, { 'fields': ('content_type', 'object_pk'), }), (_('Content'), { 'fields': ('author', 'editor', 'reaction'), }), (_('Metadata'), { 'fields': ('deleted', 'ip_address'), }), ) list_display = ('author_full_name', 'content_type', 'object_pk', 'ip_address', 'created', 'updated', 'deleted') list_filter = ('created', 'updated', 'deleted') date_hierarchy = 'updated' ordering = ('-updated',) raw_id_fields = ('author', 'editor') search_fields = ('reaction', 'author__username', 'author__email', 'author__first_name', 'author__last_name', 'ip_address') def author_full_name(self, obj): full_name = obj.author.get_full_name() if not full_name: return obj.author.username else: return full_name author_full_name.short_description = _('Author') admin.site.register(Reaction, ReactionAdmin) Use created for ordering and date_hierarchy in ReactionAdmin.
from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from .models import Reaction class ReactionAdmin(admin.ModelAdmin): fieldsets = ( (None, { 'fields': ('content_type', 'object_pk'), }), (_('Content'), { 'fields': ('author', 'editor', 'reaction'), }), (_('Metadata'), { 'fields': ('deleted', 'ip_address'), }), ) list_display = ('author_full_name', 'content_type', 'object_pk', 'ip_address', 'created', 'updated', 'deleted') list_filter = ('created', 'updated', 'deleted') date_hierarchy = 'created' ordering = ('-created',) raw_id_fields = ('author', 'editor') search_fields = ('reaction', 'author__username', 'author__email', 'author__first_name', 'author__last_name', 'ip_address') def author_full_name(self, obj): full_name = obj.author.get_full_name() if not full_name: return obj.author.username else: return full_name author_full_name.short_description = _('Author') admin.site.register(Reaction, ReactionAdmin)
<commit_before>from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from .models import Reaction class ReactionAdmin(admin.ModelAdmin): fieldsets = ( (None, { 'fields': ('content_type', 'object_pk'), }), (_('Content'), { 'fields': ('author', 'editor', 'reaction'), }), (_('Metadata'), { 'fields': ('deleted', 'ip_address'), }), ) list_display = ('author_full_name', 'content_type', 'object_pk', 'ip_address', 'created', 'updated', 'deleted') list_filter = ('created', 'updated', 'deleted') date_hierarchy = 'updated' ordering = ('-updated',) raw_id_fields = ('author', 'editor') search_fields = ('reaction', 'author__username', 'author__email', 'author__first_name', 'author__last_name', 'ip_address') def author_full_name(self, obj): full_name = obj.author.get_full_name() if not full_name: return obj.author.username else: return full_name author_full_name.short_description = _('Author') admin.site.register(Reaction, ReactionAdmin) <commit_msg>Use created for ordering and date_hierarchy in ReactionAdmin.<commit_after>
from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from .models import Reaction class ReactionAdmin(admin.ModelAdmin): fieldsets = ( (None, { 'fields': ('content_type', 'object_pk'), }), (_('Content'), { 'fields': ('author', 'editor', 'reaction'), }), (_('Metadata'), { 'fields': ('deleted', 'ip_address'), }), ) list_display = ('author_full_name', 'content_type', 'object_pk', 'ip_address', 'created', 'updated', 'deleted') list_filter = ('created', 'updated', 'deleted') date_hierarchy = 'created' ordering = ('-created',) raw_id_fields = ('author', 'editor') search_fields = ('reaction', 'author__username', 'author__email', 'author__first_name', 'author__last_name', 'ip_address') def author_full_name(self, obj): full_name = obj.author.get_full_name() if not full_name: return obj.author.username else: return full_name author_full_name.short_description = _('Author') admin.site.register(Reaction, ReactionAdmin)
from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from .models import Reaction class ReactionAdmin(admin.ModelAdmin): fieldsets = ( (None, { 'fields': ('content_type', 'object_pk'), }), (_('Content'), { 'fields': ('author', 'editor', 'reaction'), }), (_('Metadata'), { 'fields': ('deleted', 'ip_address'), }), ) list_display = ('author_full_name', 'content_type', 'object_pk', 'ip_address', 'created', 'updated', 'deleted') list_filter = ('created', 'updated', 'deleted') date_hierarchy = 'updated' ordering = ('-updated',) raw_id_fields = ('author', 'editor') search_fields = ('reaction', 'author__username', 'author__email', 'author__first_name', 'author__last_name', 'ip_address') def author_full_name(self, obj): full_name = obj.author.get_full_name() if not full_name: return obj.author.username else: return full_name author_full_name.short_description = _('Author') admin.site.register(Reaction, ReactionAdmin) Use created for ordering and date_hierarchy in ReactionAdmin.from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from .models import Reaction class ReactionAdmin(admin.ModelAdmin): fieldsets = ( (None, { 'fields': ('content_type', 'object_pk'), }), (_('Content'), { 'fields': ('author', 'editor', 'reaction'), }), (_('Metadata'), { 'fields': ('deleted', 'ip_address'), }), ) list_display = ('author_full_name', 'content_type', 'object_pk', 'ip_address', 'created', 'updated', 'deleted') list_filter = ('created', 'updated', 'deleted') date_hierarchy = 'created' ordering = ('-created',) raw_id_fields = ('author', 'editor') search_fields = ('reaction', 'author__username', 'author__email', 'author__first_name', 'author__last_name', 'ip_address') def author_full_name(self, obj): full_name = obj.author.get_full_name() if not full_name: return obj.author.username else: return full_name author_full_name.short_description = _('Author') admin.site.register(Reaction, ReactionAdmin)
<commit_before>from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from .models import Reaction class ReactionAdmin(admin.ModelAdmin): fieldsets = ( (None, { 'fields': ('content_type', 'object_pk'), }), (_('Content'), { 'fields': ('author', 'editor', 'reaction'), }), (_('Metadata'), { 'fields': ('deleted', 'ip_address'), }), ) list_display = ('author_full_name', 'content_type', 'object_pk', 'ip_address', 'created', 'updated', 'deleted') list_filter = ('created', 'updated', 'deleted') date_hierarchy = 'updated' ordering = ('-updated',) raw_id_fields = ('author', 'editor') search_fields = ('reaction', 'author__username', 'author__email', 'author__first_name', 'author__last_name', 'ip_address') def author_full_name(self, obj): full_name = obj.author.get_full_name() if not full_name: return obj.author.username else: return full_name author_full_name.short_description = _('Author') admin.site.register(Reaction, ReactionAdmin) <commit_msg>Use created for ordering and date_hierarchy in ReactionAdmin.<commit_after>from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from .models import Reaction class ReactionAdmin(admin.ModelAdmin): fieldsets = ( (None, { 'fields': ('content_type', 'object_pk'), }), (_('Content'), { 'fields': ('author', 'editor', 'reaction'), }), (_('Metadata'), { 'fields': ('deleted', 'ip_address'), }), ) list_display = ('author_full_name', 'content_type', 'object_pk', 'ip_address', 'created', 'updated', 'deleted') list_filter = ('created', 'updated', 'deleted') date_hierarchy = 'created' ordering = ('-created',) raw_id_fields = ('author', 'editor') search_fields = ('reaction', 'author__username', 'author__email', 'author__first_name', 'author__last_name', 'ip_address') def author_full_name(self, obj): full_name = obj.author.get_full_name() if not full_name: return obj.author.username else: return full_name author_full_name.short_description = _('Author') admin.site.register(Reaction, ReactionAdmin)
6e307688aede207fcdcb5e8ccb86a548dd12c2b4
src/metpy/_version.py
src/metpy/_version.py
# Copyright (c) 2019 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """Tools for versioning.""" def get_version(): """Get MetPy's version. Either get it from package metadata, or get it using version control information if a development install. """ try: from setuptools_scm import get_version return get_version(root='..', relative_to=__file__, version_scheme='post-release', local_scheme='dirty-tag') except (ImportError, LookupError): from pkg_resources import get_distribution return get_distribution(__package__).version
# Copyright (c) 2019 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """Tools for versioning.""" def get_version(): """Get MetPy's version. Either get it from package metadata, or get it using version control information if a development install. """ try: from setuptools_scm import get_version return get_version(root='../..', relative_to=__file__, version_scheme='post-release', local_scheme='dirty-tag') except (ImportError, LookupError): from pkg_resources import get_distribution return get_distribution(__package__).version
Fix getting version for development install
MNT: Fix getting version for development install Path wasn't updated when we moved source code to 'src/'.
Python
bsd-3-clause
dopplershift/MetPy,Unidata/MetPy,dopplershift/MetPy,Unidata/MetPy
# Copyright (c) 2019 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """Tools for versioning.""" def get_version(): """Get MetPy's version. Either get it from package metadata, or get it using version control information if a development install. """ try: from setuptools_scm import get_version return get_version(root='..', relative_to=__file__, version_scheme='post-release', local_scheme='dirty-tag') except (ImportError, LookupError): from pkg_resources import get_distribution return get_distribution(__package__).version MNT: Fix getting version for development install Path wasn't updated when we moved source code to 'src/'.
# Copyright (c) 2019 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """Tools for versioning.""" def get_version(): """Get MetPy's version. Either get it from package metadata, or get it using version control information if a development install. """ try: from setuptools_scm import get_version return get_version(root='../..', relative_to=__file__, version_scheme='post-release', local_scheme='dirty-tag') except (ImportError, LookupError): from pkg_resources import get_distribution return get_distribution(__package__).version
<commit_before># Copyright (c) 2019 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """Tools for versioning.""" def get_version(): """Get MetPy's version. Either get it from package metadata, or get it using version control information if a development install. """ try: from setuptools_scm import get_version return get_version(root='..', relative_to=__file__, version_scheme='post-release', local_scheme='dirty-tag') except (ImportError, LookupError): from pkg_resources import get_distribution return get_distribution(__package__).version <commit_msg>MNT: Fix getting version for development install Path wasn't updated when we moved source code to 'src/'.<commit_after>
# Copyright (c) 2019 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """Tools for versioning.""" def get_version(): """Get MetPy's version. Either get it from package metadata, or get it using version control information if a development install. """ try: from setuptools_scm import get_version return get_version(root='../..', relative_to=__file__, version_scheme='post-release', local_scheme='dirty-tag') except (ImportError, LookupError): from pkg_resources import get_distribution return get_distribution(__package__).version
# Copyright (c) 2019 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """Tools for versioning.""" def get_version(): """Get MetPy's version. Either get it from package metadata, or get it using version control information if a development install. """ try: from setuptools_scm import get_version return get_version(root='..', relative_to=__file__, version_scheme='post-release', local_scheme='dirty-tag') except (ImportError, LookupError): from pkg_resources import get_distribution return get_distribution(__package__).version MNT: Fix getting version for development install Path wasn't updated when we moved source code to 'src/'.# Copyright (c) 2019 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """Tools for versioning.""" def get_version(): """Get MetPy's version. Either get it from package metadata, or get it using version control information if a development install. """ try: from setuptools_scm import get_version return get_version(root='../..', relative_to=__file__, version_scheme='post-release', local_scheme='dirty-tag') except (ImportError, LookupError): from pkg_resources import get_distribution return get_distribution(__package__).version
<commit_before># Copyright (c) 2019 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """Tools for versioning.""" def get_version(): """Get MetPy's version. Either get it from package metadata, or get it using version control information if a development install. """ try: from setuptools_scm import get_version return get_version(root='..', relative_to=__file__, version_scheme='post-release', local_scheme='dirty-tag') except (ImportError, LookupError): from pkg_resources import get_distribution return get_distribution(__package__).version <commit_msg>MNT: Fix getting version for development install Path wasn't updated when we moved source code to 'src/'.<commit_after># Copyright (c) 2019 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """Tools for versioning.""" def get_version(): """Get MetPy's version. Either get it from package metadata, or get it using version control information if a development install. """ try: from setuptools_scm import get_version return get_version(root='../..', relative_to=__file__, version_scheme='post-release', local_scheme='dirty-tag') except (ImportError, LookupError): from pkg_resources import get_distribution return get_distribution(__package__).version
c143503012ee0e726e199882afaed0b00541f32d
tests/web_api/test_handlers.py
tests/web_api/test_handlers.py
# -*- coding: utf-8 -*- from openfisca_web_api.handlers import get_flat_trace def test_flat_trace(): tree = { 'name': 'a', 'period': 2019, 'children': [ { 'name': 'b', 'period': 2019, 'children': [], 'parameters': [], 'value': None } ], 'parameters': [], 'value': None } trace = get_flat_trace(tree) assert len(trace) == 2 assert trace['a<2019>']['dependencies'] == ['b<2019>'] assert trace['b<2019>']['dependencies'] == [] def test_flat_trace_with_cache(): tree = [{ 'children': [{ 'children': [{ 'children': [], 'name': 'c', 'parameters': [], 'period': 2019, 'value': None }], 'name': 'b', 'parameters': [], 'period': 2019, 'value': None }, { 'children': [], 'name': 'b', 'parameters': [], 'period': 2019, 'value': None }], 'name': 'a', 'parameters': [], 'period': 2019, 'value': None }] trace = get_flat_trace(tree) assert trace['b<2019>']['dependencies'] == ['c<2019>']
# -*- coding: utf-8 -*- from openfisca_web_api.handlers import get_flat_trace def test_flat_trace(): tree = { 'name': 'a', 'period': 2019, 'children': [ { 'name': 'b', 'period': 2019, 'children': [], 'parameters': [], 'value': None } ], 'parameters': [], 'value': None } trace = get_flat_trace(tree) assert len(trace) == 2 assert trace['a<2019>']['dependencies'] == ['b<2019>'] assert trace['b<2019>']['dependencies'] == [] def test_flat_trace_with_cache(): tree = { 'children': [ { 'children': [{ 'children': [], 'name': 'c', 'parameters': [], 'period': 2019, 'value': None } ], 'name': 'b', 'parameters': [], 'period': 2019, 'value': None }, { 'children': [], 'name': 'b', 'parameters': [], 'period': 2019, 'value': None } ], 'name': 'a', 'parameters': [], 'period': 2019, 'value': None } trace = get_flat_trace(tree) assert trace['b<2019>']['dependencies'] == ['c<2019>']
Fix error on flat trace with cahe test
Fix error on flat trace with cahe test
Python
agpl-3.0
openfisca/openfisca-core,openfisca/openfisca-core
# -*- coding: utf-8 -*- from openfisca_web_api.handlers import get_flat_trace def test_flat_trace(): tree = { 'name': 'a', 'period': 2019, 'children': [ { 'name': 'b', 'period': 2019, 'children': [], 'parameters': [], 'value': None } ], 'parameters': [], 'value': None } trace = get_flat_trace(tree) assert len(trace) == 2 assert trace['a<2019>']['dependencies'] == ['b<2019>'] assert trace['b<2019>']['dependencies'] == [] def test_flat_trace_with_cache(): tree = [{ 'children': [{ 'children': [{ 'children': [], 'name': 'c', 'parameters': [], 'period': 2019, 'value': None }], 'name': 'b', 'parameters': [], 'period': 2019, 'value': None }, { 'children': [], 'name': 'b', 'parameters': [], 'period': 2019, 'value': None }], 'name': 'a', 'parameters': [], 'period': 2019, 'value': None }] trace = get_flat_trace(tree) assert trace['b<2019>']['dependencies'] == ['c<2019>'] Fix error on flat trace with cahe test
# -*- coding: utf-8 -*- from openfisca_web_api.handlers import get_flat_trace def test_flat_trace(): tree = { 'name': 'a', 'period': 2019, 'children': [ { 'name': 'b', 'period': 2019, 'children': [], 'parameters': [], 'value': None } ], 'parameters': [], 'value': None } trace = get_flat_trace(tree) assert len(trace) == 2 assert trace['a<2019>']['dependencies'] == ['b<2019>'] assert trace['b<2019>']['dependencies'] == [] def test_flat_trace_with_cache(): tree = { 'children': [ { 'children': [{ 'children': [], 'name': 'c', 'parameters': [], 'period': 2019, 'value': None } ], 'name': 'b', 'parameters': [], 'period': 2019, 'value': None }, { 'children': [], 'name': 'b', 'parameters': [], 'period': 2019, 'value': None } ], 'name': 'a', 'parameters': [], 'period': 2019, 'value': None } trace = get_flat_trace(tree) assert trace['b<2019>']['dependencies'] == ['c<2019>']
<commit_before># -*- coding: utf-8 -*- from openfisca_web_api.handlers import get_flat_trace def test_flat_trace(): tree = { 'name': 'a', 'period': 2019, 'children': [ { 'name': 'b', 'period': 2019, 'children': [], 'parameters': [], 'value': None } ], 'parameters': [], 'value': None } trace = get_flat_trace(tree) assert len(trace) == 2 assert trace['a<2019>']['dependencies'] == ['b<2019>'] assert trace['b<2019>']['dependencies'] == [] def test_flat_trace_with_cache(): tree = [{ 'children': [{ 'children': [{ 'children': [], 'name': 'c', 'parameters': [], 'period': 2019, 'value': None }], 'name': 'b', 'parameters': [], 'period': 2019, 'value': None }, { 'children': [], 'name': 'b', 'parameters': [], 'period': 2019, 'value': None }], 'name': 'a', 'parameters': [], 'period': 2019, 'value': None }] trace = get_flat_trace(tree) assert trace['b<2019>']['dependencies'] == ['c<2019>'] <commit_msg>Fix error on flat trace with cahe test<commit_after>
# -*- coding: utf-8 -*- from openfisca_web_api.handlers import get_flat_trace def test_flat_trace(): tree = { 'name': 'a', 'period': 2019, 'children': [ { 'name': 'b', 'period': 2019, 'children': [], 'parameters': [], 'value': None } ], 'parameters': [], 'value': None } trace = get_flat_trace(tree) assert len(trace) == 2 assert trace['a<2019>']['dependencies'] == ['b<2019>'] assert trace['b<2019>']['dependencies'] == [] def test_flat_trace_with_cache(): tree = { 'children': [ { 'children': [{ 'children': [], 'name': 'c', 'parameters': [], 'period': 2019, 'value': None } ], 'name': 'b', 'parameters': [], 'period': 2019, 'value': None }, { 'children': [], 'name': 'b', 'parameters': [], 'period': 2019, 'value': None } ], 'name': 'a', 'parameters': [], 'period': 2019, 'value': None } trace = get_flat_trace(tree) assert trace['b<2019>']['dependencies'] == ['c<2019>']
# -*- coding: utf-8 -*- from openfisca_web_api.handlers import get_flat_trace def test_flat_trace(): tree = { 'name': 'a', 'period': 2019, 'children': [ { 'name': 'b', 'period': 2019, 'children': [], 'parameters': [], 'value': None } ], 'parameters': [], 'value': None } trace = get_flat_trace(tree) assert len(trace) == 2 assert trace['a<2019>']['dependencies'] == ['b<2019>'] assert trace['b<2019>']['dependencies'] == [] def test_flat_trace_with_cache(): tree = [{ 'children': [{ 'children': [{ 'children': [], 'name': 'c', 'parameters': [], 'period': 2019, 'value': None }], 'name': 'b', 'parameters': [], 'period': 2019, 'value': None }, { 'children': [], 'name': 'b', 'parameters': [], 'period': 2019, 'value': None }], 'name': 'a', 'parameters': [], 'period': 2019, 'value': None }] trace = get_flat_trace(tree) assert trace['b<2019>']['dependencies'] == ['c<2019>'] Fix error on flat trace with cahe test# -*- coding: utf-8 -*- from openfisca_web_api.handlers import get_flat_trace def test_flat_trace(): tree = { 'name': 'a', 'period': 2019, 'children': [ { 'name': 'b', 'period': 2019, 'children': [], 'parameters': [], 'value': None } ], 'parameters': [], 'value': None } trace = get_flat_trace(tree) assert len(trace) == 2 assert trace['a<2019>']['dependencies'] == ['b<2019>'] assert trace['b<2019>']['dependencies'] == [] def test_flat_trace_with_cache(): tree = { 'children': [ { 'children': [{ 'children': [], 'name': 'c', 'parameters': [], 'period': 2019, 'value': None } ], 'name': 'b', 'parameters': [], 'period': 2019, 'value': None }, { 'children': [], 'name': 'b', 'parameters': [], 'period': 2019, 'value': None } ], 'name': 'a', 'parameters': [], 'period': 2019, 'value': None } trace = get_flat_trace(tree) assert trace['b<2019>']['dependencies'] == ['c<2019>']
<commit_before># -*- coding: utf-8 -*- from openfisca_web_api.handlers import get_flat_trace def test_flat_trace(): tree = { 'name': 'a', 'period': 2019, 'children': [ { 'name': 'b', 'period': 2019, 'children': [], 'parameters': [], 'value': None } ], 'parameters': [], 'value': None } trace = get_flat_trace(tree) assert len(trace) == 2 assert trace['a<2019>']['dependencies'] == ['b<2019>'] assert trace['b<2019>']['dependencies'] == [] def test_flat_trace_with_cache(): tree = [{ 'children': [{ 'children': [{ 'children': [], 'name': 'c', 'parameters': [], 'period': 2019, 'value': None }], 'name': 'b', 'parameters': [], 'period': 2019, 'value': None }, { 'children': [], 'name': 'b', 'parameters': [], 'period': 2019, 'value': None }], 'name': 'a', 'parameters': [], 'period': 2019, 'value': None }] trace = get_flat_trace(tree) assert trace['b<2019>']['dependencies'] == ['c<2019>'] <commit_msg>Fix error on flat trace with cahe test<commit_after># -*- coding: utf-8 -*- from openfisca_web_api.handlers import get_flat_trace def test_flat_trace(): tree = { 'name': 'a', 'period': 2019, 'children': [ { 'name': 'b', 'period': 2019, 'children': [], 'parameters': [], 'value': None } ], 'parameters': [], 'value': None } trace = get_flat_trace(tree) assert len(trace) == 2 assert trace['a<2019>']['dependencies'] == ['b<2019>'] assert trace['b<2019>']['dependencies'] == [] def test_flat_trace_with_cache(): tree = { 'children': [ { 'children': [{ 'children': [], 'name': 'c', 'parameters': [], 'period': 2019, 'value': None } ], 'name': 'b', 'parameters': [], 'period': 2019, 'value': None }, { 'children': [], 'name': 'b', 'parameters': [], 'period': 2019, 'value': None } ], 'name': 'a', 'parameters': [], 'period': 2019, 'value': None } trace = get_flat_trace(tree) assert trace['b<2019>']['dependencies'] == ['c<2019>']
2a47ff10958d27785a35d3f5f3a3ccc6b1283021
app/commands.py
app/commands.py
from faker import Faker import click from app.database import db from app.user.models import User @click.option('--num_users', default=5, help='Number of users.') def populate_db(num_users): """Populates the database with seed data.""" fake = Faker() users = [] for _ in range(num_users): users.append( User( fake.user_name(), fake.email(), fake.word() + fake.word(), fake.ipv4() ) ) users.append( User( 'cburmeister', 'cburmeister@discogs.com', 'test123', fake.ipv4(), active=True, is_admin=True ) ) for user in users: db.session.add(user) db.session.commit() def create_db(): """Creates the database.""" db.create_all() def drop_db(): """Drops the database.""" if click.confirm('Are you sure?', abort=True): db.drop_all() def recreate_db(): """Same as running drop_db() and create_db().""" drop_db() create_db()
from faker import Faker import click from app.database import db from app.user.models import User @click.option('--num_users', default=5, help='Number of users.') def populate_db(num_users): """Populates the database with seed data.""" fake = Faker() users = [] for _ in range(num_users): users.append( User( username=fake.user_name(), email=fake.email(), password=fake.word() + fake.word(), remote_addr=fake.ipv4() ) ) users.append( User( username='cburmeister', email='cburmeister@discogs.com', password='test123', remote_addr=fake.ipv4(), active=True, is_admin=True ) ) for user in users: db.session.add(user) db.session.commit() def create_db(): """Creates the database.""" db.create_all() def drop_db(): """Drops the database.""" if click.confirm('Are you sure?', abort=True): db.drop_all() def recreate_db(): """Same as running drop_db() and create_db().""" drop_db() create_db()
Use kwargs when calling User.__init__
Use kwargs when calling User.__init__
Python
mit
cburmeister/flask-bones,cburmeister/flask-bones,cburmeister/flask-bones
from faker import Faker import click from app.database import db from app.user.models import User @click.option('--num_users', default=5, help='Number of users.') def populate_db(num_users): """Populates the database with seed data.""" fake = Faker() users = [] for _ in range(num_users): users.append( User( fake.user_name(), fake.email(), fake.word() + fake.word(), fake.ipv4() ) ) users.append( User( 'cburmeister', 'cburmeister@discogs.com', 'test123', fake.ipv4(), active=True, is_admin=True ) ) for user in users: db.session.add(user) db.session.commit() def create_db(): """Creates the database.""" db.create_all() def drop_db(): """Drops the database.""" if click.confirm('Are you sure?', abort=True): db.drop_all() def recreate_db(): """Same as running drop_db() and create_db().""" drop_db() create_db() Use kwargs when calling User.__init__
from faker import Faker import click from app.database import db from app.user.models import User @click.option('--num_users', default=5, help='Number of users.') def populate_db(num_users): """Populates the database with seed data.""" fake = Faker() users = [] for _ in range(num_users): users.append( User( username=fake.user_name(), email=fake.email(), password=fake.word() + fake.word(), remote_addr=fake.ipv4() ) ) users.append( User( username='cburmeister', email='cburmeister@discogs.com', password='test123', remote_addr=fake.ipv4(), active=True, is_admin=True ) ) for user in users: db.session.add(user) db.session.commit() def create_db(): """Creates the database.""" db.create_all() def drop_db(): """Drops the database.""" if click.confirm('Are you sure?', abort=True): db.drop_all() def recreate_db(): """Same as running drop_db() and create_db().""" drop_db() create_db()
<commit_before>from faker import Faker import click from app.database import db from app.user.models import User @click.option('--num_users', default=5, help='Number of users.') def populate_db(num_users): """Populates the database with seed data.""" fake = Faker() users = [] for _ in range(num_users): users.append( User( fake.user_name(), fake.email(), fake.word() + fake.word(), fake.ipv4() ) ) users.append( User( 'cburmeister', 'cburmeister@discogs.com', 'test123', fake.ipv4(), active=True, is_admin=True ) ) for user in users: db.session.add(user) db.session.commit() def create_db(): """Creates the database.""" db.create_all() def drop_db(): """Drops the database.""" if click.confirm('Are you sure?', abort=True): db.drop_all() def recreate_db(): """Same as running drop_db() and create_db().""" drop_db() create_db() <commit_msg>Use kwargs when calling User.__init__<commit_after>
from faker import Faker import click from app.database import db from app.user.models import User @click.option('--num_users', default=5, help='Number of users.') def populate_db(num_users): """Populates the database with seed data.""" fake = Faker() users = [] for _ in range(num_users): users.append( User( username=fake.user_name(), email=fake.email(), password=fake.word() + fake.word(), remote_addr=fake.ipv4() ) ) users.append( User( username='cburmeister', email='cburmeister@discogs.com', password='test123', remote_addr=fake.ipv4(), active=True, is_admin=True ) ) for user in users: db.session.add(user) db.session.commit() def create_db(): """Creates the database.""" db.create_all() def drop_db(): """Drops the database.""" if click.confirm('Are you sure?', abort=True): db.drop_all() def recreate_db(): """Same as running drop_db() and create_db().""" drop_db() create_db()
from faker import Faker import click from app.database import db from app.user.models import User @click.option('--num_users', default=5, help='Number of users.') def populate_db(num_users): """Populates the database with seed data.""" fake = Faker() users = [] for _ in range(num_users): users.append( User( fake.user_name(), fake.email(), fake.word() + fake.word(), fake.ipv4() ) ) users.append( User( 'cburmeister', 'cburmeister@discogs.com', 'test123', fake.ipv4(), active=True, is_admin=True ) ) for user in users: db.session.add(user) db.session.commit() def create_db(): """Creates the database.""" db.create_all() def drop_db(): """Drops the database.""" if click.confirm('Are you sure?', abort=True): db.drop_all() def recreate_db(): """Same as running drop_db() and create_db().""" drop_db() create_db() Use kwargs when calling User.__init__from faker import Faker import click from app.database import db from app.user.models import User @click.option('--num_users', default=5, help='Number of users.') def populate_db(num_users): """Populates the database with seed data.""" fake = Faker() users = [] for _ in range(num_users): users.append( User( username=fake.user_name(), email=fake.email(), password=fake.word() + fake.word(), remote_addr=fake.ipv4() ) ) users.append( User( username='cburmeister', email='cburmeister@discogs.com', password='test123', remote_addr=fake.ipv4(), active=True, is_admin=True ) ) for user in users: db.session.add(user) db.session.commit() def create_db(): """Creates the database.""" db.create_all() def drop_db(): """Drops the database.""" if click.confirm('Are you sure?', abort=True): db.drop_all() def recreate_db(): """Same as running drop_db() and create_db().""" drop_db() create_db()
<commit_before>from faker import Faker import click from app.database import db from app.user.models import User @click.option('--num_users', default=5, help='Number of users.') def populate_db(num_users): """Populates the database with seed data.""" fake = Faker() users = [] for _ in range(num_users): users.append( User( fake.user_name(), fake.email(), fake.word() + fake.word(), fake.ipv4() ) ) users.append( User( 'cburmeister', 'cburmeister@discogs.com', 'test123', fake.ipv4(), active=True, is_admin=True ) ) for user in users: db.session.add(user) db.session.commit() def create_db(): """Creates the database.""" db.create_all() def drop_db(): """Drops the database.""" if click.confirm('Are you sure?', abort=True): db.drop_all() def recreate_db(): """Same as running drop_db() and create_db().""" drop_db() create_db() <commit_msg>Use kwargs when calling User.__init__<commit_after>from faker import Faker import click from app.database import db from app.user.models import User @click.option('--num_users', default=5, help='Number of users.') def populate_db(num_users): """Populates the database with seed data.""" fake = Faker() users = [] for _ in range(num_users): users.append( User( username=fake.user_name(), email=fake.email(), password=fake.word() + fake.word(), remote_addr=fake.ipv4() ) ) users.append( User( username='cburmeister', email='cburmeister@discogs.com', password='test123', remote_addr=fake.ipv4(), active=True, is_admin=True ) ) for user in users: db.session.add(user) db.session.commit() def create_db(): """Creates the database.""" db.create_all() def drop_db(): """Drops the database.""" if click.confirm('Are you sure?', abort=True): db.drop_all() def recreate_db(): """Same as running drop_db() and create_db().""" drop_db() create_db()
957a311d8fa26b18715eada3484f07bbe609818a
stationspinner/libs/drf_extensions.py
stationspinner/libs/drf_extensions.py
from rest_framework import permissions, viewsets, serializers import json class CapsulerPermission(permissions.IsAuthenticated): """ Standard capsuler access permission. If the data was pulled from the api by one of the api keys registered to this user, this permission class will grant access to it. """ def has_object_permission(self, request, view, obj): return request.user.is_owner(obj) class CapsulerViewset(viewsets.ModelViewSet): permission_classes = [CapsulerPermission] def perform_create(self, serializer): serializer.save(owner=self.request.user) class JSONField(serializers.Field): def to_representation(self, obj): return obj def to_internal_value(self, data): return data
from rest_framework import permissions, viewsets, serializers import json class CapsulerPermission(permissions.IsAuthenticated): """ Standard capsuler access permission. If the data was pulled from the api by one of the api keys registered to this user, this permission class will grant access to it. """ def has_object_permission(self, request, view, obj): return request.user.is_owner(obj) class CapsulerViewset(viewsets.ModelViewSet): permission_classes = [CapsulerPermission] def perform_create(self, serializer): serializer.save(owner=self.request.user) class JSONField(serializers.Field): def to_representation(self, obj): return obj def to_internal_value(self, data): return data class ValidatedIDsMixin(object): ''' Use this mixin to get valid IDs for corporation or characters from request ''' def filter_valid_IDs(self, params, user): ids = params.get(self.validation_lookup_key, '') if len(ids) > 0: ids = map(int, str(ids).split(',')) valid, invalid = self.validation_class.objects.filter_valid(ids, user) else: valid = [] invalid = [] return valid, invalid
Add mixin for evaluating characterIDs
Add mixin for evaluating characterIDs
Python
agpl-3.0
kriberg/stationspinner,kriberg/stationspinner
from rest_framework import permissions, viewsets, serializers import json class CapsulerPermission(permissions.IsAuthenticated): """ Standard capsuler access permission. If the data was pulled from the api by one of the api keys registered to this user, this permission class will grant access to it. """ def has_object_permission(self, request, view, obj): return request.user.is_owner(obj) class CapsulerViewset(viewsets.ModelViewSet): permission_classes = [CapsulerPermission] def perform_create(self, serializer): serializer.save(owner=self.request.user) class JSONField(serializers.Field): def to_representation(self, obj): return obj def to_internal_value(self, data): return dataAdd mixin for evaluating characterIDs
from rest_framework import permissions, viewsets, serializers import json class CapsulerPermission(permissions.IsAuthenticated): """ Standard capsuler access permission. If the data was pulled from the api by one of the api keys registered to this user, this permission class will grant access to it. """ def has_object_permission(self, request, view, obj): return request.user.is_owner(obj) class CapsulerViewset(viewsets.ModelViewSet): permission_classes = [CapsulerPermission] def perform_create(self, serializer): serializer.save(owner=self.request.user) class JSONField(serializers.Field): def to_representation(self, obj): return obj def to_internal_value(self, data): return data class ValidatedIDsMixin(object): ''' Use this mixin to get valid IDs for corporation or characters from request ''' def filter_valid_IDs(self, params, user): ids = params.get(self.validation_lookup_key, '') if len(ids) > 0: ids = map(int, str(ids).split(',')) valid, invalid = self.validation_class.objects.filter_valid(ids, user) else: valid = [] invalid = [] return valid, invalid
<commit_before>from rest_framework import permissions, viewsets, serializers import json class CapsulerPermission(permissions.IsAuthenticated): """ Standard capsuler access permission. If the data was pulled from the api by one of the api keys registered to this user, this permission class will grant access to it. """ def has_object_permission(self, request, view, obj): return request.user.is_owner(obj) class CapsulerViewset(viewsets.ModelViewSet): permission_classes = [CapsulerPermission] def perform_create(self, serializer): serializer.save(owner=self.request.user) class JSONField(serializers.Field): def to_representation(self, obj): return obj def to_internal_value(self, data): return data<commit_msg>Add mixin for evaluating characterIDs<commit_after>
from rest_framework import permissions, viewsets, serializers import json class CapsulerPermission(permissions.IsAuthenticated): """ Standard capsuler access permission. If the data was pulled from the api by one of the api keys registered to this user, this permission class will grant access to it. """ def has_object_permission(self, request, view, obj): return request.user.is_owner(obj) class CapsulerViewset(viewsets.ModelViewSet): permission_classes = [CapsulerPermission] def perform_create(self, serializer): serializer.save(owner=self.request.user) class JSONField(serializers.Field): def to_representation(self, obj): return obj def to_internal_value(self, data): return data class ValidatedIDsMixin(object): ''' Use this mixin to get valid IDs for corporation or characters from request ''' def filter_valid_IDs(self, params, user): ids = params.get(self.validation_lookup_key, '') if len(ids) > 0: ids = map(int, str(ids).split(',')) valid, invalid = self.validation_class.objects.filter_valid(ids, user) else: valid = [] invalid = [] return valid, invalid
from rest_framework import permissions, viewsets, serializers import json class CapsulerPermission(permissions.IsAuthenticated): """ Standard capsuler access permission. If the data was pulled from the api by one of the api keys registered to this user, this permission class will grant access to it. """ def has_object_permission(self, request, view, obj): return request.user.is_owner(obj) class CapsulerViewset(viewsets.ModelViewSet): permission_classes = [CapsulerPermission] def perform_create(self, serializer): serializer.save(owner=self.request.user) class JSONField(serializers.Field): def to_representation(self, obj): return obj def to_internal_value(self, data): return dataAdd mixin for evaluating characterIDsfrom rest_framework import permissions, viewsets, serializers import json class CapsulerPermission(permissions.IsAuthenticated): """ Standard capsuler access permission. If the data was pulled from the api by one of the api keys registered to this user, this permission class will grant access to it. """ def has_object_permission(self, request, view, obj): return request.user.is_owner(obj) class CapsulerViewset(viewsets.ModelViewSet): permission_classes = [CapsulerPermission] def perform_create(self, serializer): serializer.save(owner=self.request.user) class JSONField(serializers.Field): def to_representation(self, obj): return obj def to_internal_value(self, data): return data class ValidatedIDsMixin(object): ''' Use this mixin to get valid IDs for corporation or characters from request ''' def filter_valid_IDs(self, params, user): ids = params.get(self.validation_lookup_key, '') if len(ids) > 0: ids = map(int, str(ids).split(',')) valid, invalid = self.validation_class.objects.filter_valid(ids, user) else: valid = [] invalid = [] return valid, invalid
<commit_before>from rest_framework import permissions, viewsets, serializers import json class CapsulerPermission(permissions.IsAuthenticated): """ Standard capsuler access permission. If the data was pulled from the api by one of the api keys registered to this user, this permission class will grant access to it. """ def has_object_permission(self, request, view, obj): return request.user.is_owner(obj) class CapsulerViewset(viewsets.ModelViewSet): permission_classes = [CapsulerPermission] def perform_create(self, serializer): serializer.save(owner=self.request.user) class JSONField(serializers.Field): def to_representation(self, obj): return obj def to_internal_value(self, data): return data<commit_msg>Add mixin for evaluating characterIDs<commit_after>from rest_framework import permissions, viewsets, serializers import json class CapsulerPermission(permissions.IsAuthenticated): """ Standard capsuler access permission. If the data was pulled from the api by one of the api keys registered to this user, this permission class will grant access to it. """ def has_object_permission(self, request, view, obj): return request.user.is_owner(obj) class CapsulerViewset(viewsets.ModelViewSet): permission_classes = [CapsulerPermission] def perform_create(self, serializer): serializer.save(owner=self.request.user) class JSONField(serializers.Field): def to_representation(self, obj): return obj def to_internal_value(self, data): return data class ValidatedIDsMixin(object): ''' Use this mixin to get valid IDs for corporation or characters from request ''' def filter_valid_IDs(self, params, user): ids = params.get(self.validation_lookup_key, '') if len(ids) > 0: ids = map(int, str(ids).split(',')) valid, invalid = self.validation_class.objects.filter_valid(ids, user) else: valid = [] invalid = [] return valid, invalid
80e0d9c0e9b0f809eaede0c3c3053daf99e0ce4b
boto3facade/__init__.py
boto3facade/__init__.py
"""A simple facade for boto3.""" import os import inspect __version__ = "0.5.2" __dir__ = os.path.dirname(inspect.getfile(inspect.currentframe()))
"""A simple facade for boto3.""" import os import inspect __version__ = "0.5.3" __dir__ = os.path.dirname(inspect.getfile(inspect.currentframe()))
Fix formatting of pypi docs
Fix formatting of pypi docs
Python
mit
InnovativeTravel/boto3facade,FindHotel/boto3facade
"""A simple facade for boto3.""" import os import inspect __version__ = "0.5.2" __dir__ = os.path.dirname(inspect.getfile(inspect.currentframe())) Fix formatting of pypi docs
"""A simple facade for boto3.""" import os import inspect __version__ = "0.5.3" __dir__ = os.path.dirname(inspect.getfile(inspect.currentframe()))
<commit_before>"""A simple facade for boto3.""" import os import inspect __version__ = "0.5.2" __dir__ = os.path.dirname(inspect.getfile(inspect.currentframe())) <commit_msg>Fix formatting of pypi docs<commit_after>
"""A simple facade for boto3.""" import os import inspect __version__ = "0.5.3" __dir__ = os.path.dirname(inspect.getfile(inspect.currentframe()))
"""A simple facade for boto3.""" import os import inspect __version__ = "0.5.2" __dir__ = os.path.dirname(inspect.getfile(inspect.currentframe())) Fix formatting of pypi docs"""A simple facade for boto3.""" import os import inspect __version__ = "0.5.3" __dir__ = os.path.dirname(inspect.getfile(inspect.currentframe()))
<commit_before>"""A simple facade for boto3.""" import os import inspect __version__ = "0.5.2" __dir__ = os.path.dirname(inspect.getfile(inspect.currentframe())) <commit_msg>Fix formatting of pypi docs<commit_after>"""A simple facade for boto3.""" import os import inspect __version__ = "0.5.3" __dir__ = os.path.dirname(inspect.getfile(inspect.currentframe()))
ec7791663ed866d240edbaf5e0dd766e9418e1ff
cla_backend/apps/status/tests/smoketests.py
cla_backend/apps/status/tests/smoketests.py
import unittest from celery import Celery from django.conf import settings from django.db import connection class SmokeTests(unittest.TestCase): def setUp(self): pass def test_can_access_db(self): cursor = connection.cursor() cursor.execute('SELECT 1') row = cursor.fetchone() self.assertEqual(1, row[0]) def test_can_access_celery(self): if not getattr(settings, 'CELERY_ALWAYS_EAGER', False): conn = Celery('cla_backend').connection() conn.connect() conn.release()
import unittest from celery import Celery from django.conf import settings from django.db import connection class SmokeTests(unittest.TestCase): def setUp(self): pass def test_can_access_db(self): "access the database" cursor = connection.cursor() cursor.execute('SELECT 1') row = cursor.fetchone() self.assertEqual(1, row[0]) def test_can_access_celery(self): "connect to SQS" if not getattr(settings, 'CELERY_ALWAYS_EAGER', False): conn = Celery('cla_backend').connection() conn.connect() conn.release()
Add docstrings so that hubot can say what went wrong
Add docstrings so that hubot can say what went wrong
Python
mit
ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend
import unittest from celery import Celery from django.conf import settings from django.db import connection class SmokeTests(unittest.TestCase): def setUp(self): pass def test_can_access_db(self): cursor = connection.cursor() cursor.execute('SELECT 1') row = cursor.fetchone() self.assertEqual(1, row[0]) def test_can_access_celery(self): if not getattr(settings, 'CELERY_ALWAYS_EAGER', False): conn = Celery('cla_backend').connection() conn.connect() conn.release() Add docstrings so that hubot can say what went wrong
import unittest from celery import Celery from django.conf import settings from django.db import connection class SmokeTests(unittest.TestCase): def setUp(self): pass def test_can_access_db(self): "access the database" cursor = connection.cursor() cursor.execute('SELECT 1') row = cursor.fetchone() self.assertEqual(1, row[0]) def test_can_access_celery(self): "connect to SQS" if not getattr(settings, 'CELERY_ALWAYS_EAGER', False): conn = Celery('cla_backend').connection() conn.connect() conn.release()
<commit_before>import unittest from celery import Celery from django.conf import settings from django.db import connection class SmokeTests(unittest.TestCase): def setUp(self): pass def test_can_access_db(self): cursor = connection.cursor() cursor.execute('SELECT 1') row = cursor.fetchone() self.assertEqual(1, row[0]) def test_can_access_celery(self): if not getattr(settings, 'CELERY_ALWAYS_EAGER', False): conn = Celery('cla_backend').connection() conn.connect() conn.release() <commit_msg>Add docstrings so that hubot can say what went wrong<commit_after>
import unittest from celery import Celery from django.conf import settings from django.db import connection class SmokeTests(unittest.TestCase): def setUp(self): pass def test_can_access_db(self): "access the database" cursor = connection.cursor() cursor.execute('SELECT 1') row = cursor.fetchone() self.assertEqual(1, row[0]) def test_can_access_celery(self): "connect to SQS" if not getattr(settings, 'CELERY_ALWAYS_EAGER', False): conn = Celery('cla_backend').connection() conn.connect() conn.release()
import unittest from celery import Celery from django.conf import settings from django.db import connection class SmokeTests(unittest.TestCase): def setUp(self): pass def test_can_access_db(self): cursor = connection.cursor() cursor.execute('SELECT 1') row = cursor.fetchone() self.assertEqual(1, row[0]) def test_can_access_celery(self): if not getattr(settings, 'CELERY_ALWAYS_EAGER', False): conn = Celery('cla_backend').connection() conn.connect() conn.release() Add docstrings so that hubot can say what went wrongimport unittest from celery import Celery from django.conf import settings from django.db import connection class SmokeTests(unittest.TestCase): def setUp(self): pass def test_can_access_db(self): "access the database" cursor = connection.cursor() cursor.execute('SELECT 1') row = cursor.fetchone() self.assertEqual(1, row[0]) def test_can_access_celery(self): "connect to SQS" if not getattr(settings, 'CELERY_ALWAYS_EAGER', False): conn = Celery('cla_backend').connection() conn.connect() conn.release()
<commit_before>import unittest from celery import Celery from django.conf import settings from django.db import connection class SmokeTests(unittest.TestCase): def setUp(self): pass def test_can_access_db(self): cursor = connection.cursor() cursor.execute('SELECT 1') row = cursor.fetchone() self.assertEqual(1, row[0]) def test_can_access_celery(self): if not getattr(settings, 'CELERY_ALWAYS_EAGER', False): conn = Celery('cla_backend').connection() conn.connect() conn.release() <commit_msg>Add docstrings so that hubot can say what went wrong<commit_after>import unittest from celery import Celery from django.conf import settings from django.db import connection class SmokeTests(unittest.TestCase): def setUp(self): pass def test_can_access_db(self): "access the database" cursor = connection.cursor() cursor.execute('SELECT 1') row = cursor.fetchone() self.assertEqual(1, row[0]) def test_can_access_celery(self): "connect to SQS" if not getattr(settings, 'CELERY_ALWAYS_EAGER', False): conn = Celery('cla_backend').connection() conn.connect() conn.release()
8ef2f7c7a2606971181ffcb968286dd321b8dcb6
pytips/default_settings.py
pytips/default_settings.py
# -*- coding: utf-8 -*- DEBUG = True # If you think this is my actual secret key, I have a bridge to sell you. SECRET_KEY = '\x1a\x16\xd5U\xdc\x0fL\x91\x1f\x11\x08{\xa2}\xae>\xf0\x15\xd9)\xe68%!' # By default, just use SQLite in memory SQLALCHEMY_DATABASE_URI = 'sqlite:////tmp/test.db'
# -*- coding: utf-8 -*- DEBUG = True # If you think this is my actual secret key, I have a bridge to sell you. SECRET_KEY = '\x1a\x16\xd5U\xdc\x0fL\x91\x1f\x11\x08{\xa2}\xae>\xf0\x15\xd9)\xe68%!' # By default, just use SQLite in memory SQLALCHEMY_DATABASE_URI = 'sqlite://'
Change default back to in-memory.
Change default back to in-memory. --HG-- branch : local-db
Python
isc
gthank/pytips,gthank/pytips,gthank/pytips,gthank/pytips
# -*- coding: utf-8 -*- DEBUG = True # If you think this is my actual secret key, I have a bridge to sell you. SECRET_KEY = '\x1a\x16\xd5U\xdc\x0fL\x91\x1f\x11\x08{\xa2}\xae>\xf0\x15\xd9)\xe68%!' # By default, just use SQLite in memory SQLALCHEMY_DATABASE_URI = 'sqlite:////tmp/test.db' Change default back to in-memory. --HG-- branch : local-db
# -*- coding: utf-8 -*- DEBUG = True # If you think this is my actual secret key, I have a bridge to sell you. SECRET_KEY = '\x1a\x16\xd5U\xdc\x0fL\x91\x1f\x11\x08{\xa2}\xae>\xf0\x15\xd9)\xe68%!' # By default, just use SQLite in memory SQLALCHEMY_DATABASE_URI = 'sqlite://'
<commit_before># -*- coding: utf-8 -*- DEBUG = True # If you think this is my actual secret key, I have a bridge to sell you. SECRET_KEY = '\x1a\x16\xd5U\xdc\x0fL\x91\x1f\x11\x08{\xa2}\xae>\xf0\x15\xd9)\xe68%!' # By default, just use SQLite in memory SQLALCHEMY_DATABASE_URI = 'sqlite:////tmp/test.db' <commit_msg>Change default back to in-memory. --HG-- branch : local-db<commit_after>
# -*- coding: utf-8 -*- DEBUG = True # If you think this is my actual secret key, I have a bridge to sell you. SECRET_KEY = '\x1a\x16\xd5U\xdc\x0fL\x91\x1f\x11\x08{\xa2}\xae>\xf0\x15\xd9)\xe68%!' # By default, just use SQLite in memory SQLALCHEMY_DATABASE_URI = 'sqlite://'
# -*- coding: utf-8 -*- DEBUG = True # If you think this is my actual secret key, I have a bridge to sell you. SECRET_KEY = '\x1a\x16\xd5U\xdc\x0fL\x91\x1f\x11\x08{\xa2}\xae>\xf0\x15\xd9)\xe68%!' # By default, just use SQLite in memory SQLALCHEMY_DATABASE_URI = 'sqlite:////tmp/test.db' Change default back to in-memory. --HG-- branch : local-db# -*- coding: utf-8 -*- DEBUG = True # If you think this is my actual secret key, I have a bridge to sell you. SECRET_KEY = '\x1a\x16\xd5U\xdc\x0fL\x91\x1f\x11\x08{\xa2}\xae>\xf0\x15\xd9)\xe68%!' # By default, just use SQLite in memory SQLALCHEMY_DATABASE_URI = 'sqlite://'
<commit_before># -*- coding: utf-8 -*- DEBUG = True # If you think this is my actual secret key, I have a bridge to sell you. SECRET_KEY = '\x1a\x16\xd5U\xdc\x0fL\x91\x1f\x11\x08{\xa2}\xae>\xf0\x15\xd9)\xe68%!' # By default, just use SQLite in memory SQLALCHEMY_DATABASE_URI = 'sqlite:////tmp/test.db' <commit_msg>Change default back to in-memory. --HG-- branch : local-db<commit_after># -*- coding: utf-8 -*- DEBUG = True # If you think this is my actual secret key, I have a bridge to sell you. SECRET_KEY = '\x1a\x16\xd5U\xdc\x0fL\x91\x1f\x11\x08{\xa2}\xae>\xf0\x15\xd9)\xe68%!' # By default, just use SQLite in memory SQLALCHEMY_DATABASE_URI = 'sqlite://'
25027605e5a370dfb0cb40ab9aeddafc89090441
download.py
download.py
# coding=utf-8 import urllib2 import json import re # album_url = 'http://www.ximalaya.com/7712455/album/6333174' album_url = 'http://www.ximalaya.com/7712455/album/4474664' headers = {'User-Agent': 'Safari/537.36'} resp = urllib2.urlopen(urllib2.Request(album_url, headers=headers)) ids = re.search('sound_ids=\"(.*)\"', resp.read()).group(1).split(',') for ind, f in enumerate(ids): url = 'http://www.ximalaya.com/tracks/{}.json'.format(f) resp = urllib2.urlopen(urllib2.Request(url, headers=headers)) data = json.loads(resp.read()) output = data['title'] + data['play_path_64'][-4:] print output, data['play_path_64'] with open(output, 'wb') as local: local.write(urllib2.urlopen(data['play_path_64']).read())
# coding=utf-8 from urllib2 import urlopen, Request import json import re class XmlyDownloader(object): def __init__(self): self.headers = {'User-Agent': 'Safari/537.36'} def getIDs(self, url): resp = urlopen(Request(url, headers=self.headers)) return re.search('sound_ids=\"(.*)\"', resp.read()).group(1).split(',') def download_file(self, ID): url = 'http://www.ximalaya.com/tracks/{}.json'.format(ID) resp = urlopen(Request(url, headers=self.headers)) data = json.loads(resp.read()) output = data['title'] + data['play_path_64'][-4:] print output, data['play_path_64'] with open(output, 'wb') as local: local.write(urlopen(data['play_path_64']).read()) def download_album(self, album_url): for ID in self.getIDs(album_url): self.download_file(ID) if __name__ == '__main__': album_url = 'http://www.ximalaya.com/7712455/album/4474664' xmly = XmlyDownloader() xmly.download_album(album_url)
Rewrite the script in a package fasshion.
Rewrite the script in a package fasshion.
Python
mit
bangbangbear/ximalayaDownloader
# coding=utf-8 import urllib2 import json import re # album_url = 'http://www.ximalaya.com/7712455/album/6333174' album_url = 'http://www.ximalaya.com/7712455/album/4474664' headers = {'User-Agent': 'Safari/537.36'} resp = urllib2.urlopen(urllib2.Request(album_url, headers=headers)) ids = re.search('sound_ids=\"(.*)\"', resp.read()).group(1).split(',') for ind, f in enumerate(ids): url = 'http://www.ximalaya.com/tracks/{}.json'.format(f) resp = urllib2.urlopen(urllib2.Request(url, headers=headers)) data = json.loads(resp.read()) output = data['title'] + data['play_path_64'][-4:] print output, data['play_path_64'] with open(output, 'wb') as local: local.write(urllib2.urlopen(data['play_path_64']).read()) Rewrite the script in a package fasshion.
# coding=utf-8 from urllib2 import urlopen, Request import json import re class XmlyDownloader(object): def __init__(self): self.headers = {'User-Agent': 'Safari/537.36'} def getIDs(self, url): resp = urlopen(Request(url, headers=self.headers)) return re.search('sound_ids=\"(.*)\"', resp.read()).group(1).split(',') def download_file(self, ID): url = 'http://www.ximalaya.com/tracks/{}.json'.format(ID) resp = urlopen(Request(url, headers=self.headers)) data = json.loads(resp.read()) output = data['title'] + data['play_path_64'][-4:] print output, data['play_path_64'] with open(output, 'wb') as local: local.write(urlopen(data['play_path_64']).read()) def download_album(self, album_url): for ID in self.getIDs(album_url): self.download_file(ID) if __name__ == '__main__': album_url = 'http://www.ximalaya.com/7712455/album/4474664' xmly = XmlyDownloader() xmly.download_album(album_url)
<commit_before># coding=utf-8 import urllib2 import json import re # album_url = 'http://www.ximalaya.com/7712455/album/6333174' album_url = 'http://www.ximalaya.com/7712455/album/4474664' headers = {'User-Agent': 'Safari/537.36'} resp = urllib2.urlopen(urllib2.Request(album_url, headers=headers)) ids = re.search('sound_ids=\"(.*)\"', resp.read()).group(1).split(',') for ind, f in enumerate(ids): url = 'http://www.ximalaya.com/tracks/{}.json'.format(f) resp = urllib2.urlopen(urllib2.Request(url, headers=headers)) data = json.loads(resp.read()) output = data['title'] + data['play_path_64'][-4:] print output, data['play_path_64'] with open(output, 'wb') as local: local.write(urllib2.urlopen(data['play_path_64']).read()) <commit_msg>Rewrite the script in a package fasshion.<commit_after>
# coding=utf-8 from urllib2 import urlopen, Request import json import re class XmlyDownloader(object): def __init__(self): self.headers = {'User-Agent': 'Safari/537.36'} def getIDs(self, url): resp = urlopen(Request(url, headers=self.headers)) return re.search('sound_ids=\"(.*)\"', resp.read()).group(1).split(',') def download_file(self, ID): url = 'http://www.ximalaya.com/tracks/{}.json'.format(ID) resp = urlopen(Request(url, headers=self.headers)) data = json.loads(resp.read()) output = data['title'] + data['play_path_64'][-4:] print output, data['play_path_64'] with open(output, 'wb') as local: local.write(urlopen(data['play_path_64']).read()) def download_album(self, album_url): for ID in self.getIDs(album_url): self.download_file(ID) if __name__ == '__main__': album_url = 'http://www.ximalaya.com/7712455/album/4474664' xmly = XmlyDownloader() xmly.download_album(album_url)
# coding=utf-8 import urllib2 import json import re # album_url = 'http://www.ximalaya.com/7712455/album/6333174' album_url = 'http://www.ximalaya.com/7712455/album/4474664' headers = {'User-Agent': 'Safari/537.36'} resp = urllib2.urlopen(urllib2.Request(album_url, headers=headers)) ids = re.search('sound_ids=\"(.*)\"', resp.read()).group(1).split(',') for ind, f in enumerate(ids): url = 'http://www.ximalaya.com/tracks/{}.json'.format(f) resp = urllib2.urlopen(urllib2.Request(url, headers=headers)) data = json.loads(resp.read()) output = data['title'] + data['play_path_64'][-4:] print output, data['play_path_64'] with open(output, 'wb') as local: local.write(urllib2.urlopen(data['play_path_64']).read()) Rewrite the script in a package fasshion.# coding=utf-8 from urllib2 import urlopen, Request import json import re class XmlyDownloader(object): def __init__(self): self.headers = {'User-Agent': 'Safari/537.36'} def getIDs(self, url): resp = urlopen(Request(url, headers=self.headers)) return re.search('sound_ids=\"(.*)\"', resp.read()).group(1).split(',') def download_file(self, ID): url = 'http://www.ximalaya.com/tracks/{}.json'.format(ID) resp = urlopen(Request(url, headers=self.headers)) data = json.loads(resp.read()) output = data['title'] + data['play_path_64'][-4:] print output, data['play_path_64'] with open(output, 'wb') as local: local.write(urlopen(data['play_path_64']).read()) def download_album(self, album_url): for ID in self.getIDs(album_url): self.download_file(ID) if __name__ == '__main__': album_url = 'http://www.ximalaya.com/7712455/album/4474664' xmly = XmlyDownloader() xmly.download_album(album_url)
<commit_before># coding=utf-8 import urllib2 import json import re # album_url = 'http://www.ximalaya.com/7712455/album/6333174' album_url = 'http://www.ximalaya.com/7712455/album/4474664' headers = {'User-Agent': 'Safari/537.36'} resp = urllib2.urlopen(urllib2.Request(album_url, headers=headers)) ids = re.search('sound_ids=\"(.*)\"', resp.read()).group(1).split(',') for ind, f in enumerate(ids): url = 'http://www.ximalaya.com/tracks/{}.json'.format(f) resp = urllib2.urlopen(urllib2.Request(url, headers=headers)) data = json.loads(resp.read()) output = data['title'] + data['play_path_64'][-4:] print output, data['play_path_64'] with open(output, 'wb') as local: local.write(urllib2.urlopen(data['play_path_64']).read()) <commit_msg>Rewrite the script in a package fasshion.<commit_after># coding=utf-8 from urllib2 import urlopen, Request import json import re class XmlyDownloader(object): def __init__(self): self.headers = {'User-Agent': 'Safari/537.36'} def getIDs(self, url): resp = urlopen(Request(url, headers=self.headers)) return re.search('sound_ids=\"(.*)\"', resp.read()).group(1).split(',') def download_file(self, ID): url = 'http://www.ximalaya.com/tracks/{}.json'.format(ID) resp = urlopen(Request(url, headers=self.headers)) data = json.loads(resp.read()) output = data['title'] + data['play_path_64'][-4:] print output, data['play_path_64'] with open(output, 'wb') as local: local.write(urlopen(data['play_path_64']).read()) def download_album(self, album_url): for ID in self.getIDs(album_url): self.download_file(ID) if __name__ == '__main__': album_url = 'http://www.ximalaya.com/7712455/album/4474664' xmly = XmlyDownloader() xmly.download_album(album_url)
cb3156b5bc279295b5c932a36818d5ed460b31d5
ynr/urls.py
ynr/urls.py
from __future__ import unicode_literals import sys from django.conf import settings from django.conf.urls import include, url from django.views.generic import TemplateView from django.contrib import admin from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ url(r'^parties/', include('parties.urls')), url(r'^', include('candidates.urls')), url(r'^tasks/', include('tasks.urls')), url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^accounts/', include('allauth.urls')), url(r'^upload_document/', include('official_documents.urls')), url(r'^results/', include('results.urls')), url(r'^robots\.txt$', TemplateView.as_view( template_name='robots.txt', content_type='text/plain')), ] if settings.DEBUG: import debug_toolbar urlpatterns += [ url(r'^__debug__/', include(debug_toolbar.urls)), ] if settings.DEBUG or settings.RUNNING_TESTS: urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
from __future__ import unicode_literals import sys from django.conf import settings from django.conf.urls import include, url from django.views.generic import TemplateView from django.contrib import admin from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ url(r'^parties/', include('parties.urls')), url(r'^', include('candidates.urls')), url(r'^tasks/', include('tasks.urls')), url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^accounts/', include('allauth.urls')), url(r'^upload_document/', include('official_documents.urls')), url(r'^results/', include('results.urls')), url(r'^robots\.txt$', TemplateView.as_view( template_name='robots.txt', content_type='text/plain')), ] if settings.DEBUG: import debug_toolbar urlpatterns += [ url(r'^__debug__/', include(debug_toolbar.urls)), ] if settings.DEBUG or getattr(settings, 'RUNNING_TESTS', False): urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Use getattr in case setting doesn't exist
Use getattr in case setting doesn't exist
Python
agpl-3.0
DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative
from __future__ import unicode_literals import sys from django.conf import settings from django.conf.urls import include, url from django.views.generic import TemplateView from django.contrib import admin from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ url(r'^parties/', include('parties.urls')), url(r'^', include('candidates.urls')), url(r'^tasks/', include('tasks.urls')), url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^accounts/', include('allauth.urls')), url(r'^upload_document/', include('official_documents.urls')), url(r'^results/', include('results.urls')), url(r'^robots\.txt$', TemplateView.as_view( template_name='robots.txt', content_type='text/plain')), ] if settings.DEBUG: import debug_toolbar urlpatterns += [ url(r'^__debug__/', include(debug_toolbar.urls)), ] if settings.DEBUG or settings.RUNNING_TESTS: urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Use getattr in case setting doesn't exist
from __future__ import unicode_literals import sys from django.conf import settings from django.conf.urls import include, url from django.views.generic import TemplateView from django.contrib import admin from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ url(r'^parties/', include('parties.urls')), url(r'^', include('candidates.urls')), url(r'^tasks/', include('tasks.urls')), url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^accounts/', include('allauth.urls')), url(r'^upload_document/', include('official_documents.urls')), url(r'^results/', include('results.urls')), url(r'^robots\.txt$', TemplateView.as_view( template_name='robots.txt', content_type='text/plain')), ] if settings.DEBUG: import debug_toolbar urlpatterns += [ url(r'^__debug__/', include(debug_toolbar.urls)), ] if settings.DEBUG or getattr(settings, 'RUNNING_TESTS', False): urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
<commit_before>from __future__ import unicode_literals import sys from django.conf import settings from django.conf.urls import include, url from django.views.generic import TemplateView from django.contrib import admin from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ url(r'^parties/', include('parties.urls')), url(r'^', include('candidates.urls')), url(r'^tasks/', include('tasks.urls')), url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^accounts/', include('allauth.urls')), url(r'^upload_document/', include('official_documents.urls')), url(r'^results/', include('results.urls')), url(r'^robots\.txt$', TemplateView.as_view( template_name='robots.txt', content_type='text/plain')), ] if settings.DEBUG: import debug_toolbar urlpatterns += [ url(r'^__debug__/', include(debug_toolbar.urls)), ] if settings.DEBUG or settings.RUNNING_TESTS: urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) <commit_msg>Use getattr in case setting doesn't exist<commit_after>
from __future__ import unicode_literals import sys from django.conf import settings from django.conf.urls import include, url from django.views.generic import TemplateView from django.contrib import admin from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ url(r'^parties/', include('parties.urls')), url(r'^', include('candidates.urls')), url(r'^tasks/', include('tasks.urls')), url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^accounts/', include('allauth.urls')), url(r'^upload_document/', include('official_documents.urls')), url(r'^results/', include('results.urls')), url(r'^robots\.txt$', TemplateView.as_view( template_name='robots.txt', content_type='text/plain')), ] if settings.DEBUG: import debug_toolbar urlpatterns += [ url(r'^__debug__/', include(debug_toolbar.urls)), ] if settings.DEBUG or getattr(settings, 'RUNNING_TESTS', False): urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
from __future__ import unicode_literals import sys from django.conf import settings from django.conf.urls import include, url from django.views.generic import TemplateView from django.contrib import admin from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ url(r'^parties/', include('parties.urls')), url(r'^', include('candidates.urls')), url(r'^tasks/', include('tasks.urls')), url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^accounts/', include('allauth.urls')), url(r'^upload_document/', include('official_documents.urls')), url(r'^results/', include('results.urls')), url(r'^robots\.txt$', TemplateView.as_view( template_name='robots.txt', content_type='text/plain')), ] if settings.DEBUG: import debug_toolbar urlpatterns += [ url(r'^__debug__/', include(debug_toolbar.urls)), ] if settings.DEBUG or settings.RUNNING_TESTS: urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Use getattr in case setting doesn't existfrom __future__ import unicode_literals import sys from django.conf import settings from django.conf.urls import include, url from django.views.generic import TemplateView from django.contrib import admin from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ url(r'^parties/', include('parties.urls')), url(r'^', include('candidates.urls')), url(r'^tasks/', include('tasks.urls')), url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^accounts/', include('allauth.urls')), url(r'^upload_document/', include('official_documents.urls')), url(r'^results/', include('results.urls')), url(r'^robots\.txt$', TemplateView.as_view( template_name='robots.txt', content_type='text/plain')), ] if settings.DEBUG: import debug_toolbar urlpatterns += [ url(r'^__debug__/', include(debug_toolbar.urls)), ] if settings.DEBUG or getattr(settings, 'RUNNING_TESTS', False): urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
<commit_before>from __future__ import unicode_literals import sys from django.conf import settings from django.conf.urls import include, url from django.views.generic import TemplateView from django.contrib import admin from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ url(r'^parties/', include('parties.urls')), url(r'^', include('candidates.urls')), url(r'^tasks/', include('tasks.urls')), url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^accounts/', include('allauth.urls')), url(r'^upload_document/', include('official_documents.urls')), url(r'^results/', include('results.urls')), url(r'^robots\.txt$', TemplateView.as_view( template_name='robots.txt', content_type='text/plain')), ] if settings.DEBUG: import debug_toolbar urlpatterns += [ url(r'^__debug__/', include(debug_toolbar.urls)), ] if settings.DEBUG or settings.RUNNING_TESTS: urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) <commit_msg>Use getattr in case setting doesn't exist<commit_after>from __future__ import unicode_literals import sys from django.conf import settings from django.conf.urls import include, url from django.views.generic import TemplateView from django.contrib import admin from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ url(r'^parties/', include('parties.urls')), url(r'^', include('candidates.urls')), url(r'^tasks/', include('tasks.urls')), url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^accounts/', include('allauth.urls')), url(r'^upload_document/', include('official_documents.urls')), url(r'^results/', include('results.urls')), url(r'^robots\.txt$', TemplateView.as_view( template_name='robots.txt', content_type='text/plain')), ] if settings.DEBUG: import debug_toolbar urlpatterns += [ url(r'^__debug__/', include(debug_toolbar.urls)), ] if settings.DEBUG or getattr(settings, 'RUNNING_TESTS', False): urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
fd10df8ff5e1312a3ec93bcb6abc1800aafa78cc
collaboration/dispatch/__init__.py
collaboration/dispatch/__init__.py
"""Multi-consumer multi-producer dispatching mechanism Originally based on pydispatch (BSD) http://pypi.python.org/pypi/PyDispatcher/2.0.1 See license.txt for original license. Heavily modified for Django's purposes. """ from sugar3.dispatch.dispatcher import Signal
"""Multi-consumer multi-producer dispatching mechanism Originally based on pydispatch (BSD) http://pypi.python.org/pypi/PyDispatcher/2.0.1 See license.txt for original license. Heavily modified for Django's purposes. """
Remove unused import 'Signal' (F401)
Remove unused import 'Signal' (F401)
Python
mit
walterbender/turtleart,AlanJAS/turtleart
"""Multi-consumer multi-producer dispatching mechanism Originally based on pydispatch (BSD) http://pypi.python.org/pypi/PyDispatcher/2.0.1 See license.txt for original license. Heavily modified for Django's purposes. """ from sugar3.dispatch.dispatcher import Signal Remove unused import 'Signal' (F401)
"""Multi-consumer multi-producer dispatching mechanism Originally based on pydispatch (BSD) http://pypi.python.org/pypi/PyDispatcher/2.0.1 See license.txt for original license. Heavily modified for Django's purposes. """
<commit_before>"""Multi-consumer multi-producer dispatching mechanism Originally based on pydispatch (BSD) http://pypi.python.org/pypi/PyDispatcher/2.0.1 See license.txt for original license. Heavily modified for Django's purposes. """ from sugar3.dispatch.dispatcher import Signal <commit_msg>Remove unused import 'Signal' (F401)<commit_after>
"""Multi-consumer multi-producer dispatching mechanism Originally based on pydispatch (BSD) http://pypi.python.org/pypi/PyDispatcher/2.0.1 See license.txt for original license. Heavily modified for Django's purposes. """
"""Multi-consumer multi-producer dispatching mechanism Originally based on pydispatch (BSD) http://pypi.python.org/pypi/PyDispatcher/2.0.1 See license.txt for original license. Heavily modified for Django's purposes. """ from sugar3.dispatch.dispatcher import Signal Remove unused import 'Signal' (F401)"""Multi-consumer multi-producer dispatching mechanism Originally based on pydispatch (BSD) http://pypi.python.org/pypi/PyDispatcher/2.0.1 See license.txt for original license. Heavily modified for Django's purposes. """
<commit_before>"""Multi-consumer multi-producer dispatching mechanism Originally based on pydispatch (BSD) http://pypi.python.org/pypi/PyDispatcher/2.0.1 See license.txt for original license. Heavily modified for Django's purposes. """ from sugar3.dispatch.dispatcher import Signal <commit_msg>Remove unused import 'Signal' (F401)<commit_after>"""Multi-consumer multi-producer dispatching mechanism Originally based on pydispatch (BSD) http://pypi.python.org/pypi/PyDispatcher/2.0.1 See license.txt for original license. Heavily modified for Django's purposes. """
7d6e6318e0696aed8011b86817aa48460f5ad969
scripts/buildtool/cmake.py
scripts/buildtool/cmake.py
import string TEMPL = """\ # $WARNING # Only Windows builds supported with CMake cmake_minimum_required(VERSION 2.8 FATAL_ERROR) project($PROJNAME) if(NOT DEFINED WIN32) message(FATAL_ERROR "Only Windows supported with CMake") endif() include_directories($INCDIRS) add_executable($EXENAME $SOURCES) """ def run(obj): t = string.Template(TEMPL).substitute( WARNING=obj._warning, PROJNAME='game', EXENAME='Game', INCDIRS=' '.join(obj._incldirs), SOURCES=' '.join(obj._get_atoms(None, 'WINDOWS'))) obj._write_file('CMakeLists.txt', t)
import string TEMPL = """\ # $WARNING # Only Windows builds supported with CMake cmake_minimum_required(VERSION 2.8 FATAL_ERROR) project($PROJNAME) if(NOT DEFINED WIN32) message(FATAL_ERROR "Only Windows supported with CMake") endif() include_directories($INCDIRS) add_executable($EXENAME WIN32 $SOURCES) """ def run(obj): t = string.Template(TEMPL).substitute( WARNING=obj._warning, PROJNAME='game', EXENAME='Game', INCDIRS=' '.join(obj._incldirs), SOURCES=' '.join(obj._get_atoms(None, 'WINDOWS'))) obj._write_file('CMakeLists.txt', t)
Fix incorrect windows subsystem in CMake backend
Fix incorrect windows subsystem in CMake backend
Python
bsd-2-clause
depp/sglib,depp/sglib
import string TEMPL = """\ # $WARNING # Only Windows builds supported with CMake cmake_minimum_required(VERSION 2.8 FATAL_ERROR) project($PROJNAME) if(NOT DEFINED WIN32) message(FATAL_ERROR "Only Windows supported with CMake") endif() include_directories($INCDIRS) add_executable($EXENAME $SOURCES) """ def run(obj): t = string.Template(TEMPL).substitute( WARNING=obj._warning, PROJNAME='game', EXENAME='Game', INCDIRS=' '.join(obj._incldirs), SOURCES=' '.join(obj._get_atoms(None, 'WINDOWS'))) obj._write_file('CMakeLists.txt', t) Fix incorrect windows subsystem in CMake backend
import string TEMPL = """\ # $WARNING # Only Windows builds supported with CMake cmake_minimum_required(VERSION 2.8 FATAL_ERROR) project($PROJNAME) if(NOT DEFINED WIN32) message(FATAL_ERROR "Only Windows supported with CMake") endif() include_directories($INCDIRS) add_executable($EXENAME WIN32 $SOURCES) """ def run(obj): t = string.Template(TEMPL).substitute( WARNING=obj._warning, PROJNAME='game', EXENAME='Game', INCDIRS=' '.join(obj._incldirs), SOURCES=' '.join(obj._get_atoms(None, 'WINDOWS'))) obj._write_file('CMakeLists.txt', t)
<commit_before>import string TEMPL = """\ # $WARNING # Only Windows builds supported with CMake cmake_minimum_required(VERSION 2.8 FATAL_ERROR) project($PROJNAME) if(NOT DEFINED WIN32) message(FATAL_ERROR "Only Windows supported with CMake") endif() include_directories($INCDIRS) add_executable($EXENAME $SOURCES) """ def run(obj): t = string.Template(TEMPL).substitute( WARNING=obj._warning, PROJNAME='game', EXENAME='Game', INCDIRS=' '.join(obj._incldirs), SOURCES=' '.join(obj._get_atoms(None, 'WINDOWS'))) obj._write_file('CMakeLists.txt', t) <commit_msg>Fix incorrect windows subsystem in CMake backend<commit_after>
import string TEMPL = """\ # $WARNING # Only Windows builds supported with CMake cmake_minimum_required(VERSION 2.8 FATAL_ERROR) project($PROJNAME) if(NOT DEFINED WIN32) message(FATAL_ERROR "Only Windows supported with CMake") endif() include_directories($INCDIRS) add_executable($EXENAME WIN32 $SOURCES) """ def run(obj): t = string.Template(TEMPL).substitute( WARNING=obj._warning, PROJNAME='game', EXENAME='Game', INCDIRS=' '.join(obj._incldirs), SOURCES=' '.join(obj._get_atoms(None, 'WINDOWS'))) obj._write_file('CMakeLists.txt', t)
import string TEMPL = """\ # $WARNING # Only Windows builds supported with CMake cmake_minimum_required(VERSION 2.8 FATAL_ERROR) project($PROJNAME) if(NOT DEFINED WIN32) message(FATAL_ERROR "Only Windows supported with CMake") endif() include_directories($INCDIRS) add_executable($EXENAME $SOURCES) """ def run(obj): t = string.Template(TEMPL).substitute( WARNING=obj._warning, PROJNAME='game', EXENAME='Game', INCDIRS=' '.join(obj._incldirs), SOURCES=' '.join(obj._get_atoms(None, 'WINDOWS'))) obj._write_file('CMakeLists.txt', t) Fix incorrect windows subsystem in CMake backendimport string TEMPL = """\ # $WARNING # Only Windows builds supported with CMake cmake_minimum_required(VERSION 2.8 FATAL_ERROR) project($PROJNAME) if(NOT DEFINED WIN32) message(FATAL_ERROR "Only Windows supported with CMake") endif() include_directories($INCDIRS) add_executable($EXENAME WIN32 $SOURCES) """ def run(obj): t = string.Template(TEMPL).substitute( WARNING=obj._warning, PROJNAME='game', EXENAME='Game', INCDIRS=' '.join(obj._incldirs), SOURCES=' '.join(obj._get_atoms(None, 'WINDOWS'))) obj._write_file('CMakeLists.txt', t)
<commit_before>import string TEMPL = """\ # $WARNING # Only Windows builds supported with CMake cmake_minimum_required(VERSION 2.8 FATAL_ERROR) project($PROJNAME) if(NOT DEFINED WIN32) message(FATAL_ERROR "Only Windows supported with CMake") endif() include_directories($INCDIRS) add_executable($EXENAME $SOURCES) """ def run(obj): t = string.Template(TEMPL).substitute( WARNING=obj._warning, PROJNAME='game', EXENAME='Game', INCDIRS=' '.join(obj._incldirs), SOURCES=' '.join(obj._get_atoms(None, 'WINDOWS'))) obj._write_file('CMakeLists.txt', t) <commit_msg>Fix incorrect windows subsystem in CMake backend<commit_after>import string TEMPL = """\ # $WARNING # Only Windows builds supported with CMake cmake_minimum_required(VERSION 2.8 FATAL_ERROR) project($PROJNAME) if(NOT DEFINED WIN32) message(FATAL_ERROR "Only Windows supported with CMake") endif() include_directories($INCDIRS) add_executable($EXENAME WIN32 $SOURCES) """ def run(obj): t = string.Template(TEMPL).substitute( WARNING=obj._warning, PROJNAME='game', EXENAME='Game', INCDIRS=' '.join(obj._incldirs), SOURCES=' '.join(obj._get_atoms(None, 'WINDOWS'))) obj._write_file('CMakeLists.txt', t)
f39b1e44ae3bd709b4b11995f809536ae2e6cc5b
dbaas/physical/admin/parameter.py
dbaas/physical/admin/parameter.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django_services import admin from ..service.parameter import ParameterService from ..forms.parameter import ParameterForm class ParameterAdmin(admin.DjangoServicesAdmin): form = ParameterForm service_class = ParameterService search_fields = ("name",) list_filter = ("engine_type", "dynamic", ) list_display = ("name", "engine_type", "dynamic", "class_path") save_on_top = True
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django_services import admin from ..service.parameter import ParameterService from ..forms.parameter import ParameterForm class ParameterAdmin(admin.DjangoServicesAdmin): form = ParameterForm service_class = ParameterService search_fields = ("name",) list_filter = ("engine_type", "dynamic", ) list_display = ("name", "engine_type", "dynamic", "custom_method") save_on_top = True
Rename model field class_path to custom_method
Rename model field class_path to custom_method
Python
bsd-3-clause
globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django_services import admin from ..service.parameter import ParameterService from ..forms.parameter import ParameterForm class ParameterAdmin(admin.DjangoServicesAdmin): form = ParameterForm service_class = ParameterService search_fields = ("name",) list_filter = ("engine_type", "dynamic", ) list_display = ("name", "engine_type", "dynamic", "class_path") save_on_top = True Rename model field class_path to custom_method
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django_services import admin from ..service.parameter import ParameterService from ..forms.parameter import ParameterForm class ParameterAdmin(admin.DjangoServicesAdmin): form = ParameterForm service_class = ParameterService search_fields = ("name",) list_filter = ("engine_type", "dynamic", ) list_display = ("name", "engine_type", "dynamic", "custom_method") save_on_top = True
<commit_before># -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django_services import admin from ..service.parameter import ParameterService from ..forms.parameter import ParameterForm class ParameterAdmin(admin.DjangoServicesAdmin): form = ParameterForm service_class = ParameterService search_fields = ("name",) list_filter = ("engine_type", "dynamic", ) list_display = ("name", "engine_type", "dynamic", "class_path") save_on_top = True <commit_msg>Rename model field class_path to custom_method<commit_after>
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django_services import admin from ..service.parameter import ParameterService from ..forms.parameter import ParameterForm class ParameterAdmin(admin.DjangoServicesAdmin): form = ParameterForm service_class = ParameterService search_fields = ("name",) list_filter = ("engine_type", "dynamic", ) list_display = ("name", "engine_type", "dynamic", "custom_method") save_on_top = True
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django_services import admin from ..service.parameter import ParameterService from ..forms.parameter import ParameterForm class ParameterAdmin(admin.DjangoServicesAdmin): form = ParameterForm service_class = ParameterService search_fields = ("name",) list_filter = ("engine_type", "dynamic", ) list_display = ("name", "engine_type", "dynamic", "class_path") save_on_top = True Rename model field class_path to custom_method# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django_services import admin from ..service.parameter import ParameterService from ..forms.parameter import ParameterForm class ParameterAdmin(admin.DjangoServicesAdmin): form = ParameterForm service_class = ParameterService search_fields = ("name",) list_filter = ("engine_type", "dynamic", ) list_display = ("name", "engine_type", "dynamic", "custom_method") save_on_top = True
<commit_before># -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django_services import admin from ..service.parameter import ParameterService from ..forms.parameter import ParameterForm class ParameterAdmin(admin.DjangoServicesAdmin): form = ParameterForm service_class = ParameterService search_fields = ("name",) list_filter = ("engine_type", "dynamic", ) list_display = ("name", "engine_type", "dynamic", "class_path") save_on_top = True <commit_msg>Rename model field class_path to custom_method<commit_after># -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django_services import admin from ..service.parameter import ParameterService from ..forms.parameter import ParameterForm class ParameterAdmin(admin.DjangoServicesAdmin): form = ParameterForm service_class = ParameterService search_fields = ("name",) list_filter = ("engine_type", "dynamic", ) list_display = ("name", "engine_type", "dynamic", "custom_method") save_on_top = True
febf5e96847fd01b82f7b9a8e30a5cdae30120f5
layers.py
layers.py
import lasagne import numpy as np WIDTH_INDEX = 3 HEIGHT_INDEX = 2 LAYER_INDEX = 1 class SpatialPoolingLayer(lasagne.layers.Layer): # I assume that all bins has square shape for simplicity # Maybe later I change this behaviour def __init__(self, incoming, bin_sizes, **kwargs): super(SpatialPoolingLayer, self).__init__(incoming, **kwargs) self.bin_sizes = self.add_param(np.array(bin_sizes), (len(bin_sizes),), name="bin_sizes") def get_output_shape_for(self, input_shape): return np.sum(np.power(self.bin_sizes, 2)) def get_output_for(self, input, **kwargs): layers = [] for bin_size in self.bin_sizes: win_size = (np.ceil(input.shape[WIDTH_INDEX] / bin_size), np.ceil(input.shape[HEIGHT_INDEX] / bin_size)) stride = (np.floor(input.shape[WIDTH_INDEX] / bin_size), np.floor(input.shape[HEIGHT_INDEX] / bin_size)) layers.append(lasagne.layers.flatten( lasagne.layers.MaxPool2DLayer(input, pool_size=win_size, stride=stride) )) return lasagne.layers.concat(layers)
import lasagne import numpy as np from theano import tensor as T WIDTH_INDEX = 3 HEIGHT_INDEX = 2 LAYER_INDEX = 1 class SpatialPoolingLayer(lasagne.layers.Layer): # I assume that all bins has square shape for simplicity # Maybe later I change this behaviour def __init__(self, incoming, bin_sizes, **kwargs): super(SpatialPoolingLayer, self).__init__(incoming, **kwargs) self.bin_sizes = self.add_param(np.array(bin_sizes), (len(bin_sizes),), name="bin_sizes") def get_output_shape_for(self, input_shape): return T.sum(T.power(self.bin_sizes, 2)) def get_output_for(self, input, **kwargs): layers = [] for bin_size in self.bin_sizes: win_size = (np.ceil(input.shape[WIDTH_INDEX] / bin_size), np.ceil(input.shape[HEIGHT_INDEX] / bin_size)) stride = (np.floor(input.shape[WIDTH_INDEX] / bin_size), np.floor(input.shape[HEIGHT_INDEX] / bin_size)) layers.append(lasagne.layers.flatten( lasagne.layers.MaxPool2DLayer(input, pool_size=win_size, stride=stride) )) return lasagne.layers.concat(layers)
Fix syntax in spatial layer
Fix syntax in spatial layer
Python
mit
dimmddr/roadSignsNN
import lasagne import numpy as np WIDTH_INDEX = 3 HEIGHT_INDEX = 2 LAYER_INDEX = 1 class SpatialPoolingLayer(lasagne.layers.Layer): # I assume that all bins has square shape for simplicity # Maybe later I change this behaviour def __init__(self, incoming, bin_sizes, **kwargs): super(SpatialPoolingLayer, self).__init__(incoming, **kwargs) self.bin_sizes = self.add_param(np.array(bin_sizes), (len(bin_sizes),), name="bin_sizes") def get_output_shape_for(self, input_shape): return np.sum(np.power(self.bin_sizes, 2)) def get_output_for(self, input, **kwargs): layers = [] for bin_size in self.bin_sizes: win_size = (np.ceil(input.shape[WIDTH_INDEX] / bin_size), np.ceil(input.shape[HEIGHT_INDEX] / bin_size)) stride = (np.floor(input.shape[WIDTH_INDEX] / bin_size), np.floor(input.shape[HEIGHT_INDEX] / bin_size)) layers.append(lasagne.layers.flatten( lasagne.layers.MaxPool2DLayer(input, pool_size=win_size, stride=stride) )) return lasagne.layers.concat(layers) Fix syntax in spatial layer
import lasagne import numpy as np from theano import tensor as T WIDTH_INDEX = 3 HEIGHT_INDEX = 2 LAYER_INDEX = 1 class SpatialPoolingLayer(lasagne.layers.Layer): # I assume that all bins has square shape for simplicity # Maybe later I change this behaviour def __init__(self, incoming, bin_sizes, **kwargs): super(SpatialPoolingLayer, self).__init__(incoming, **kwargs) self.bin_sizes = self.add_param(np.array(bin_sizes), (len(bin_sizes),), name="bin_sizes") def get_output_shape_for(self, input_shape): return T.sum(T.power(self.bin_sizes, 2)) def get_output_for(self, input, **kwargs): layers = [] for bin_size in self.bin_sizes: win_size = (np.ceil(input.shape[WIDTH_INDEX] / bin_size), np.ceil(input.shape[HEIGHT_INDEX] / bin_size)) stride = (np.floor(input.shape[WIDTH_INDEX] / bin_size), np.floor(input.shape[HEIGHT_INDEX] / bin_size)) layers.append(lasagne.layers.flatten( lasagne.layers.MaxPool2DLayer(input, pool_size=win_size, stride=stride) )) return lasagne.layers.concat(layers)
<commit_before>import lasagne import numpy as np WIDTH_INDEX = 3 HEIGHT_INDEX = 2 LAYER_INDEX = 1 class SpatialPoolingLayer(lasagne.layers.Layer): # I assume that all bins has square shape for simplicity # Maybe later I change this behaviour def __init__(self, incoming, bin_sizes, **kwargs): super(SpatialPoolingLayer, self).__init__(incoming, **kwargs) self.bin_sizes = self.add_param(np.array(bin_sizes), (len(bin_sizes),), name="bin_sizes") def get_output_shape_for(self, input_shape): return np.sum(np.power(self.bin_sizes, 2)) def get_output_for(self, input, **kwargs): layers = [] for bin_size in self.bin_sizes: win_size = (np.ceil(input.shape[WIDTH_INDEX] / bin_size), np.ceil(input.shape[HEIGHT_INDEX] / bin_size)) stride = (np.floor(input.shape[WIDTH_INDEX] / bin_size), np.floor(input.shape[HEIGHT_INDEX] / bin_size)) layers.append(lasagne.layers.flatten( lasagne.layers.MaxPool2DLayer(input, pool_size=win_size, stride=stride) )) return lasagne.layers.concat(layers) <commit_msg>Fix syntax in spatial layer<commit_after>
import lasagne import numpy as np from theano import tensor as T WIDTH_INDEX = 3 HEIGHT_INDEX = 2 LAYER_INDEX = 1 class SpatialPoolingLayer(lasagne.layers.Layer): # I assume that all bins has square shape for simplicity # Maybe later I change this behaviour def __init__(self, incoming, bin_sizes, **kwargs): super(SpatialPoolingLayer, self).__init__(incoming, **kwargs) self.bin_sizes = self.add_param(np.array(bin_sizes), (len(bin_sizes),), name="bin_sizes") def get_output_shape_for(self, input_shape): return T.sum(T.power(self.bin_sizes, 2)) def get_output_for(self, input, **kwargs): layers = [] for bin_size in self.bin_sizes: win_size = (np.ceil(input.shape[WIDTH_INDEX] / bin_size), np.ceil(input.shape[HEIGHT_INDEX] / bin_size)) stride = (np.floor(input.shape[WIDTH_INDEX] / bin_size), np.floor(input.shape[HEIGHT_INDEX] / bin_size)) layers.append(lasagne.layers.flatten( lasagne.layers.MaxPool2DLayer(input, pool_size=win_size, stride=stride) )) return lasagne.layers.concat(layers)
import lasagne import numpy as np WIDTH_INDEX = 3 HEIGHT_INDEX = 2 LAYER_INDEX = 1 class SpatialPoolingLayer(lasagne.layers.Layer): # I assume that all bins has square shape for simplicity # Maybe later I change this behaviour def __init__(self, incoming, bin_sizes, **kwargs): super(SpatialPoolingLayer, self).__init__(incoming, **kwargs) self.bin_sizes = self.add_param(np.array(bin_sizes), (len(bin_sizes),), name="bin_sizes") def get_output_shape_for(self, input_shape): return np.sum(np.power(self.bin_sizes, 2)) def get_output_for(self, input, **kwargs): layers = [] for bin_size in self.bin_sizes: win_size = (np.ceil(input.shape[WIDTH_INDEX] / bin_size), np.ceil(input.shape[HEIGHT_INDEX] / bin_size)) stride = (np.floor(input.shape[WIDTH_INDEX] / bin_size), np.floor(input.shape[HEIGHT_INDEX] / bin_size)) layers.append(lasagne.layers.flatten( lasagne.layers.MaxPool2DLayer(input, pool_size=win_size, stride=stride) )) return lasagne.layers.concat(layers) Fix syntax in spatial layerimport lasagne import numpy as np from theano import tensor as T WIDTH_INDEX = 3 HEIGHT_INDEX = 2 LAYER_INDEX = 1 class SpatialPoolingLayer(lasagne.layers.Layer): # I assume that all bins has square shape for simplicity # Maybe later I change this behaviour def __init__(self, incoming, bin_sizes, **kwargs): super(SpatialPoolingLayer, self).__init__(incoming, **kwargs) self.bin_sizes = self.add_param(np.array(bin_sizes), (len(bin_sizes),), name="bin_sizes") def get_output_shape_for(self, input_shape): return T.sum(T.power(self.bin_sizes, 2)) def get_output_for(self, input, **kwargs): layers = [] for bin_size in self.bin_sizes: win_size = (np.ceil(input.shape[WIDTH_INDEX] / bin_size), np.ceil(input.shape[HEIGHT_INDEX] / bin_size)) stride = (np.floor(input.shape[WIDTH_INDEX] / bin_size), np.floor(input.shape[HEIGHT_INDEX] / bin_size)) layers.append(lasagne.layers.flatten( lasagne.layers.MaxPool2DLayer(input, pool_size=win_size, stride=stride) )) return lasagne.layers.concat(layers)
<commit_before>import lasagne import numpy as np WIDTH_INDEX = 3 HEIGHT_INDEX = 2 LAYER_INDEX = 1 class SpatialPoolingLayer(lasagne.layers.Layer): # I assume that all bins has square shape for simplicity # Maybe later I change this behaviour def __init__(self, incoming, bin_sizes, **kwargs): super(SpatialPoolingLayer, self).__init__(incoming, **kwargs) self.bin_sizes = self.add_param(np.array(bin_sizes), (len(bin_sizes),), name="bin_sizes") def get_output_shape_for(self, input_shape): return np.sum(np.power(self.bin_sizes, 2)) def get_output_for(self, input, **kwargs): layers = [] for bin_size in self.bin_sizes: win_size = (np.ceil(input.shape[WIDTH_INDEX] / bin_size), np.ceil(input.shape[HEIGHT_INDEX] / bin_size)) stride = (np.floor(input.shape[WIDTH_INDEX] / bin_size), np.floor(input.shape[HEIGHT_INDEX] / bin_size)) layers.append(lasagne.layers.flatten( lasagne.layers.MaxPool2DLayer(input, pool_size=win_size, stride=stride) )) return lasagne.layers.concat(layers) <commit_msg>Fix syntax in spatial layer<commit_after>import lasagne import numpy as np from theano import tensor as T WIDTH_INDEX = 3 HEIGHT_INDEX = 2 LAYER_INDEX = 1 class SpatialPoolingLayer(lasagne.layers.Layer): # I assume that all bins has square shape for simplicity # Maybe later I change this behaviour def __init__(self, incoming, bin_sizes, **kwargs): super(SpatialPoolingLayer, self).__init__(incoming, **kwargs) self.bin_sizes = self.add_param(np.array(bin_sizes), (len(bin_sizes),), name="bin_sizes") def get_output_shape_for(self, input_shape): return T.sum(T.power(self.bin_sizes, 2)) def get_output_for(self, input, **kwargs): layers = [] for bin_size in self.bin_sizes: win_size = (np.ceil(input.shape[WIDTH_INDEX] / bin_size), np.ceil(input.shape[HEIGHT_INDEX] / bin_size)) stride = (np.floor(input.shape[WIDTH_INDEX] / bin_size), np.floor(input.shape[HEIGHT_INDEX] / bin_size)) layers.append(lasagne.layers.flatten( lasagne.layers.MaxPool2DLayer(input, pool_size=win_size, stride=stride) )) return lasagne.layers.concat(layers)
f433a77ec569512e23d71827036652dd60065b15
fabfile.py
fabfile.py
from fabric.api import execute, local, settings, task @task def docs(): local('make -C docs/ html') @task def autodocs(): auto(docs) @task def test(path=None): path = path or 'tests/' local('nosetests ' + path) @task def autotest(path=None): auto(test, path=path) @task def coverage(path=None): path = path or 'tests/' local( 'nosetests --with-coverage --cover-package=mopidy ' '--cover-branches --cover-html ' + path) @task def autocoverage(path=None): auto(coverage, path=path) def auto(task, *args, **kwargs): while True: local('clear') with settings(warn_only=True): execute(task, *args, **kwargs) local( 'inotifywait -q -e create -e modify -e delete ' '--exclude ".*\.(pyc|sw.)" -r docs/ mopidy/ tests/') @task def update_authors(): # Keep authors in the order of appearance and use awk to filter out dupes local( "git log --format='- %aN <%aE>' --reverse | awk '!x[$0]++' > AUTHORS")
from fabric.api import execute, local, settings, task @task def docs(): local('make -C docs/ html') @task def autodocs(): auto(docs) @task def test(path=None): path = path or 'tests/' local('nosetests ' + path) @task def autotest(path=None): auto(test, path=path) @task def coverage(path=None): path = path or 'tests/' local( 'nosetests --with-coverage --cover-package=mopidy ' '--cover-branches --cover-html ' + path) @task def autocoverage(path=None): auto(coverage, path=path) @task def lint(path=None): path = path or '.' local('flake8 $(find %s -iname "*.py")' % path) @task def autolint(path=None): auto(lint, path=path) def auto(task, *args, **kwargs): while True: local('clear') with settings(warn_only=True): execute(task, *args, **kwargs) local( 'inotifywait -q -e create -e modify -e delete ' '--exclude ".*\.(pyc|sw.)" -r docs/ mopidy/ tests/') @task def update_authors(): # Keep authors in the order of appearance and use awk to filter out dupes local( "git log --format='- %aN <%aE>' --reverse | awk '!x[$0]++' > AUTHORS")
Add lint/autolint tasks for running flake8 on everything
fab: Add lint/autolint tasks for running flake8 on everything
Python
apache-2.0
jcass77/mopidy,ali/mopidy,bencevans/mopidy,dbrgn/mopidy,adamcik/mopidy,rawdlite/mopidy,pacificIT/mopidy,abarisain/mopidy,vrs01/mopidy,woutervanwijk/mopidy,mokieyue/mopidy,bencevans/mopidy,hkariti/mopidy,SuperStarPL/mopidy,mopidy/mopidy,diandiankan/mopidy,dbrgn/mopidy,tkem/mopidy,rawdlite/mopidy,kingosticks/mopidy,swak/mopidy,pacificIT/mopidy,glogiotatidis/mopidy,quartz55/mopidy,mokieyue/mopidy,ali/mopidy,bacontext/mopidy,vrs01/mopidy,dbrgn/mopidy,adamcik/mopidy,woutervanwijk/mopidy,diandiankan/mopidy,mokieyue/mopidy,pacificIT/mopidy,swak/mopidy,swak/mopidy,bencevans/mopidy,mopidy/mopidy,bencevans/mopidy,glogiotatidis/mopidy,diandiankan/mopidy,hkariti/mopidy,vrs01/mopidy,mokieyue/mopidy,vrs01/mopidy,liamw9534/mopidy,priestd09/mopidy,jodal/mopidy,jmarsik/mopidy,glogiotatidis/mopidy,bacontext/mopidy,swak/mopidy,ali/mopidy,tkem/mopidy,rawdlite/mopidy,hkariti/mopidy,rawdlite/mopidy,liamw9534/mopidy,mopidy/mopidy,kingosticks/mopidy,jmarsik/mopidy,bacontext/mopidy,tkem/mopidy,priestd09/mopidy,SuperStarPL/mopidy,adamcik/mopidy,ZenithDK/mopidy,abarisain/mopidy,jodal/mopidy,quartz55/mopidy,SuperStarPL/mopidy,ZenithDK/mopidy,jcass77/mopidy,diandiankan/mopidy,bacontext/mopidy,jmarsik/mopidy,pacificIT/mopidy,ZenithDK/mopidy,SuperStarPL/mopidy,quartz55/mopidy,tkem/mopidy,glogiotatidis/mopidy,quartz55/mopidy,ZenithDK/mopidy,dbrgn/mopidy,priestd09/mopidy,jcass77/mopidy,hkariti/mopidy,jodal/mopidy,ali/mopidy,jmarsik/mopidy,kingosticks/mopidy
from fabric.api import execute, local, settings, task @task def docs(): local('make -C docs/ html') @task def autodocs(): auto(docs) @task def test(path=None): path = path or 'tests/' local('nosetests ' + path) @task def autotest(path=None): auto(test, path=path) @task def coverage(path=None): path = path or 'tests/' local( 'nosetests --with-coverage --cover-package=mopidy ' '--cover-branches --cover-html ' + path) @task def autocoverage(path=None): auto(coverage, path=path) def auto(task, *args, **kwargs): while True: local('clear') with settings(warn_only=True): execute(task, *args, **kwargs) local( 'inotifywait -q -e create -e modify -e delete ' '--exclude ".*\.(pyc|sw.)" -r docs/ mopidy/ tests/') @task def update_authors(): # Keep authors in the order of appearance and use awk to filter out dupes local( "git log --format='- %aN <%aE>' --reverse | awk '!x[$0]++' > AUTHORS") fab: Add lint/autolint tasks for running flake8 on everything
from fabric.api import execute, local, settings, task @task def docs(): local('make -C docs/ html') @task def autodocs(): auto(docs) @task def test(path=None): path = path or 'tests/' local('nosetests ' + path) @task def autotest(path=None): auto(test, path=path) @task def coverage(path=None): path = path or 'tests/' local( 'nosetests --with-coverage --cover-package=mopidy ' '--cover-branches --cover-html ' + path) @task def autocoverage(path=None): auto(coverage, path=path) @task def lint(path=None): path = path or '.' local('flake8 $(find %s -iname "*.py")' % path) @task def autolint(path=None): auto(lint, path=path) def auto(task, *args, **kwargs): while True: local('clear') with settings(warn_only=True): execute(task, *args, **kwargs) local( 'inotifywait -q -e create -e modify -e delete ' '--exclude ".*\.(pyc|sw.)" -r docs/ mopidy/ tests/') @task def update_authors(): # Keep authors in the order of appearance and use awk to filter out dupes local( "git log --format='- %aN <%aE>' --reverse | awk '!x[$0]++' > AUTHORS")
<commit_before>from fabric.api import execute, local, settings, task @task def docs(): local('make -C docs/ html') @task def autodocs(): auto(docs) @task def test(path=None): path = path or 'tests/' local('nosetests ' + path) @task def autotest(path=None): auto(test, path=path) @task def coverage(path=None): path = path or 'tests/' local( 'nosetests --with-coverage --cover-package=mopidy ' '--cover-branches --cover-html ' + path) @task def autocoverage(path=None): auto(coverage, path=path) def auto(task, *args, **kwargs): while True: local('clear') with settings(warn_only=True): execute(task, *args, **kwargs) local( 'inotifywait -q -e create -e modify -e delete ' '--exclude ".*\.(pyc|sw.)" -r docs/ mopidy/ tests/') @task def update_authors(): # Keep authors in the order of appearance and use awk to filter out dupes local( "git log --format='- %aN <%aE>' --reverse | awk '!x[$0]++' > AUTHORS") <commit_msg>fab: Add lint/autolint tasks for running flake8 on everything<commit_after>
from fabric.api import execute, local, settings, task @task def docs(): local('make -C docs/ html') @task def autodocs(): auto(docs) @task def test(path=None): path = path or 'tests/' local('nosetests ' + path) @task def autotest(path=None): auto(test, path=path) @task def coverage(path=None): path = path or 'tests/' local( 'nosetests --with-coverage --cover-package=mopidy ' '--cover-branches --cover-html ' + path) @task def autocoverage(path=None): auto(coverage, path=path) @task def lint(path=None): path = path or '.' local('flake8 $(find %s -iname "*.py")' % path) @task def autolint(path=None): auto(lint, path=path) def auto(task, *args, **kwargs): while True: local('clear') with settings(warn_only=True): execute(task, *args, **kwargs) local( 'inotifywait -q -e create -e modify -e delete ' '--exclude ".*\.(pyc|sw.)" -r docs/ mopidy/ tests/') @task def update_authors(): # Keep authors in the order of appearance and use awk to filter out dupes local( "git log --format='- %aN <%aE>' --reverse | awk '!x[$0]++' > AUTHORS")
from fabric.api import execute, local, settings, task @task def docs(): local('make -C docs/ html') @task def autodocs(): auto(docs) @task def test(path=None): path = path or 'tests/' local('nosetests ' + path) @task def autotest(path=None): auto(test, path=path) @task def coverage(path=None): path = path or 'tests/' local( 'nosetests --with-coverage --cover-package=mopidy ' '--cover-branches --cover-html ' + path) @task def autocoverage(path=None): auto(coverage, path=path) def auto(task, *args, **kwargs): while True: local('clear') with settings(warn_only=True): execute(task, *args, **kwargs) local( 'inotifywait -q -e create -e modify -e delete ' '--exclude ".*\.(pyc|sw.)" -r docs/ mopidy/ tests/') @task def update_authors(): # Keep authors in the order of appearance and use awk to filter out dupes local( "git log --format='- %aN <%aE>' --reverse | awk '!x[$0]++' > AUTHORS") fab: Add lint/autolint tasks for running flake8 on everythingfrom fabric.api import execute, local, settings, task @task def docs(): local('make -C docs/ html') @task def autodocs(): auto(docs) @task def test(path=None): path = path or 'tests/' local('nosetests ' + path) @task def autotest(path=None): auto(test, path=path) @task def coverage(path=None): path = path or 'tests/' local( 'nosetests --with-coverage --cover-package=mopidy ' '--cover-branches --cover-html ' + path) @task def autocoverage(path=None): auto(coverage, path=path) @task def lint(path=None): path = path or '.' local('flake8 $(find %s -iname "*.py")' % path) @task def autolint(path=None): auto(lint, path=path) def auto(task, *args, **kwargs): while True: local('clear') with settings(warn_only=True): execute(task, *args, **kwargs) local( 'inotifywait -q -e create -e modify -e delete ' '--exclude ".*\.(pyc|sw.)" -r docs/ mopidy/ tests/') @task def update_authors(): # Keep authors in the order of appearance and use awk to filter out dupes local( "git log --format='- %aN <%aE>' --reverse | awk '!x[$0]++' > AUTHORS")
<commit_before>from fabric.api import execute, local, settings, task @task def docs(): local('make -C docs/ html') @task def autodocs(): auto(docs) @task def test(path=None): path = path or 'tests/' local('nosetests ' + path) @task def autotest(path=None): auto(test, path=path) @task def coverage(path=None): path = path or 'tests/' local( 'nosetests --with-coverage --cover-package=mopidy ' '--cover-branches --cover-html ' + path) @task def autocoverage(path=None): auto(coverage, path=path) def auto(task, *args, **kwargs): while True: local('clear') with settings(warn_only=True): execute(task, *args, **kwargs) local( 'inotifywait -q -e create -e modify -e delete ' '--exclude ".*\.(pyc|sw.)" -r docs/ mopidy/ tests/') @task def update_authors(): # Keep authors in the order of appearance and use awk to filter out dupes local( "git log --format='- %aN <%aE>' --reverse | awk '!x[$0]++' > AUTHORS") <commit_msg>fab: Add lint/autolint tasks for running flake8 on everything<commit_after>from fabric.api import execute, local, settings, task @task def docs(): local('make -C docs/ html') @task def autodocs(): auto(docs) @task def test(path=None): path = path or 'tests/' local('nosetests ' + path) @task def autotest(path=None): auto(test, path=path) @task def coverage(path=None): path = path or 'tests/' local( 'nosetests --with-coverage --cover-package=mopidy ' '--cover-branches --cover-html ' + path) @task def autocoverage(path=None): auto(coverage, path=path) @task def lint(path=None): path = path or '.' local('flake8 $(find %s -iname "*.py")' % path) @task def autolint(path=None): auto(lint, path=path) def auto(task, *args, **kwargs): while True: local('clear') with settings(warn_only=True): execute(task, *args, **kwargs) local( 'inotifywait -q -e create -e modify -e delete ' '--exclude ".*\.(pyc|sw.)" -r docs/ mopidy/ tests/') @task def update_authors(): # Keep authors in the order of appearance and use awk to filter out dupes local( "git log --format='- %aN <%aE>' --reverse | awk '!x[$0]++' > AUTHORS")
589bfc0f5e57215aa69746e82100375d6f3b8cc9
kpub/tests/test_counts.py
kpub/tests/test_counts.py
import kpub def test_annual_count(): # Does the cumulative count match the annual count? db = kpub.PublicationDB() annual = db.get_annual_publication_count() cumul = db.get_annual_publication_count_cumulative() assert annual['k2'][2010] == 0 # K2 didn't exist in 2010 # The first K2 papers started appearing in 2014; the cumulative counts should reflect that: assert (annual['k2'][2014] + annual['k2'][2015]) == cumul['k2'][2015] assert (annual['k2'][2014] + annual['k2'][2015] + annual['k2'][2016]) == cumul['k2'][2016] # Are the values returned by get_metrics consistent? for year in range(2009, 2019): metrics = db.get_metrics(year=year) assert metrics['publication_count'] == annual['both'][year] assert metrics['kepler_count'] == annual['kepler'][year] assert metrics['k2_count'] == annual['k2'][year]
import kpub def test_annual_count(): # Does the cumulative count match the annual count? db = kpub.PublicationDB() annual = db.get_annual_publication_count() cumul = db.get_annual_publication_count_cumulative() assert annual['k2'][2010] == 0 # K2 didn't exist in 2010 # The first K2 papers started appearing in 2014; the cumulative counts should reflect that: assert (annual['k2'][2014] + annual['k2'][2015]) == cumul['k2'][2015] assert (annual['k2'][2014] + annual['k2'][2015] + annual['k2'][2016]) == cumul['k2'][2016] # Are the values returned by get_metrics consistent? for year in range(2009, 2019): metrics = db.get_metrics(year=year) assert metrics['publication_count'] == annual['both'][year] assert metrics['kepler_count'] == annual['kepler'][year] assert metrics['k2_count'] == annual['k2'][year] # Can we pass multiple years to get_metrics? metrics = db.get_metrics(year=[2011, 2012]) assert metrics['publication_count'] == annual['both'][2011] + annual['both'][2012]
Add a test for the new multi-year feature
Add a test for the new multi-year feature
Python
mit
KeplerGO/kpub
import kpub def test_annual_count(): # Does the cumulative count match the annual count? db = kpub.PublicationDB() annual = db.get_annual_publication_count() cumul = db.get_annual_publication_count_cumulative() assert annual['k2'][2010] == 0 # K2 didn't exist in 2010 # The first K2 papers started appearing in 2014; the cumulative counts should reflect that: assert (annual['k2'][2014] + annual['k2'][2015]) == cumul['k2'][2015] assert (annual['k2'][2014] + annual['k2'][2015] + annual['k2'][2016]) == cumul['k2'][2016] # Are the values returned by get_metrics consistent? for year in range(2009, 2019): metrics = db.get_metrics(year=year) assert metrics['publication_count'] == annual['both'][year] assert metrics['kepler_count'] == annual['kepler'][year] assert metrics['k2_count'] == annual['k2'][year] Add a test for the new multi-year feature
import kpub def test_annual_count(): # Does the cumulative count match the annual count? db = kpub.PublicationDB() annual = db.get_annual_publication_count() cumul = db.get_annual_publication_count_cumulative() assert annual['k2'][2010] == 0 # K2 didn't exist in 2010 # The first K2 papers started appearing in 2014; the cumulative counts should reflect that: assert (annual['k2'][2014] + annual['k2'][2015]) == cumul['k2'][2015] assert (annual['k2'][2014] + annual['k2'][2015] + annual['k2'][2016]) == cumul['k2'][2016] # Are the values returned by get_metrics consistent? for year in range(2009, 2019): metrics = db.get_metrics(year=year) assert metrics['publication_count'] == annual['both'][year] assert metrics['kepler_count'] == annual['kepler'][year] assert metrics['k2_count'] == annual['k2'][year] # Can we pass multiple years to get_metrics? metrics = db.get_metrics(year=[2011, 2012]) assert metrics['publication_count'] == annual['both'][2011] + annual['both'][2012]
<commit_before>import kpub def test_annual_count(): # Does the cumulative count match the annual count? db = kpub.PublicationDB() annual = db.get_annual_publication_count() cumul = db.get_annual_publication_count_cumulative() assert annual['k2'][2010] == 0 # K2 didn't exist in 2010 # The first K2 papers started appearing in 2014; the cumulative counts should reflect that: assert (annual['k2'][2014] + annual['k2'][2015]) == cumul['k2'][2015] assert (annual['k2'][2014] + annual['k2'][2015] + annual['k2'][2016]) == cumul['k2'][2016] # Are the values returned by get_metrics consistent? for year in range(2009, 2019): metrics = db.get_metrics(year=year) assert metrics['publication_count'] == annual['both'][year] assert metrics['kepler_count'] == annual['kepler'][year] assert metrics['k2_count'] == annual['k2'][year] <commit_msg>Add a test for the new multi-year feature<commit_after>
import kpub def test_annual_count(): # Does the cumulative count match the annual count? db = kpub.PublicationDB() annual = db.get_annual_publication_count() cumul = db.get_annual_publication_count_cumulative() assert annual['k2'][2010] == 0 # K2 didn't exist in 2010 # The first K2 papers started appearing in 2014; the cumulative counts should reflect that: assert (annual['k2'][2014] + annual['k2'][2015]) == cumul['k2'][2015] assert (annual['k2'][2014] + annual['k2'][2015] + annual['k2'][2016]) == cumul['k2'][2016] # Are the values returned by get_metrics consistent? for year in range(2009, 2019): metrics = db.get_metrics(year=year) assert metrics['publication_count'] == annual['both'][year] assert metrics['kepler_count'] == annual['kepler'][year] assert metrics['k2_count'] == annual['k2'][year] # Can we pass multiple years to get_metrics? metrics = db.get_metrics(year=[2011, 2012]) assert metrics['publication_count'] == annual['both'][2011] + annual['both'][2012]
import kpub def test_annual_count(): # Does the cumulative count match the annual count? db = kpub.PublicationDB() annual = db.get_annual_publication_count() cumul = db.get_annual_publication_count_cumulative() assert annual['k2'][2010] == 0 # K2 didn't exist in 2010 # The first K2 papers started appearing in 2014; the cumulative counts should reflect that: assert (annual['k2'][2014] + annual['k2'][2015]) == cumul['k2'][2015] assert (annual['k2'][2014] + annual['k2'][2015] + annual['k2'][2016]) == cumul['k2'][2016] # Are the values returned by get_metrics consistent? for year in range(2009, 2019): metrics = db.get_metrics(year=year) assert metrics['publication_count'] == annual['both'][year] assert metrics['kepler_count'] == annual['kepler'][year] assert metrics['k2_count'] == annual['k2'][year] Add a test for the new multi-year featureimport kpub def test_annual_count(): # Does the cumulative count match the annual count? db = kpub.PublicationDB() annual = db.get_annual_publication_count() cumul = db.get_annual_publication_count_cumulative() assert annual['k2'][2010] == 0 # K2 didn't exist in 2010 # The first K2 papers started appearing in 2014; the cumulative counts should reflect that: assert (annual['k2'][2014] + annual['k2'][2015]) == cumul['k2'][2015] assert (annual['k2'][2014] + annual['k2'][2015] + annual['k2'][2016]) == cumul['k2'][2016] # Are the values returned by get_metrics consistent? for year in range(2009, 2019): metrics = db.get_metrics(year=year) assert metrics['publication_count'] == annual['both'][year] assert metrics['kepler_count'] == annual['kepler'][year] assert metrics['k2_count'] == annual['k2'][year] # Can we pass multiple years to get_metrics? metrics = db.get_metrics(year=[2011, 2012]) assert metrics['publication_count'] == annual['both'][2011] + annual['both'][2012]
<commit_before>import kpub def test_annual_count(): # Does the cumulative count match the annual count? db = kpub.PublicationDB() annual = db.get_annual_publication_count() cumul = db.get_annual_publication_count_cumulative() assert annual['k2'][2010] == 0 # K2 didn't exist in 2010 # The first K2 papers started appearing in 2014; the cumulative counts should reflect that: assert (annual['k2'][2014] + annual['k2'][2015]) == cumul['k2'][2015] assert (annual['k2'][2014] + annual['k2'][2015] + annual['k2'][2016]) == cumul['k2'][2016] # Are the values returned by get_metrics consistent? for year in range(2009, 2019): metrics = db.get_metrics(year=year) assert metrics['publication_count'] == annual['both'][year] assert metrics['kepler_count'] == annual['kepler'][year] assert metrics['k2_count'] == annual['k2'][year] <commit_msg>Add a test for the new multi-year feature<commit_after>import kpub def test_annual_count(): # Does the cumulative count match the annual count? db = kpub.PublicationDB() annual = db.get_annual_publication_count() cumul = db.get_annual_publication_count_cumulative() assert annual['k2'][2010] == 0 # K2 didn't exist in 2010 # The first K2 papers started appearing in 2014; the cumulative counts should reflect that: assert (annual['k2'][2014] + annual['k2'][2015]) == cumul['k2'][2015] assert (annual['k2'][2014] + annual['k2'][2015] + annual['k2'][2016]) == cumul['k2'][2016] # Are the values returned by get_metrics consistent? for year in range(2009, 2019): metrics = db.get_metrics(year=year) assert metrics['publication_count'] == annual['both'][year] assert metrics['kepler_count'] == annual['kepler'][year] assert metrics['k2_count'] == annual['k2'][year] # Can we pass multiple years to get_metrics? metrics = db.get_metrics(year=[2011, 2012]) assert metrics['publication_count'] == annual['both'][2011] + annual['both'][2012]
276111f633b6151368eb38f01b222567c5ebed97
labsys/auth/decorators.py
labsys/auth/decorators.py
from functools import wraps from flask import abort from flask_login import current_user from labsys.auth.models import Permission def permission_required(permission): def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): if not current_user.can(permission): abort(403) return f(*args, **kwargs) return decorated_function return decorator def admin_required(f): return permission_required(Permission.ADMINISTER) (f)
from functools import wraps from flask import abort, current_app from flask_login import current_user from labsys.auth.models import Permission def permission_required(permission): def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): if not current_user.can(permission) and \ not current_app.config['TESTING'] == True: abort(403) return f(*args, **kwargs) return decorated_function return decorator def admin_required(f): return permission_required(Permission.ADMINISTER) (f)
Verify if it's a testing app for permissioning
:rocket: Verify if it's a testing app for permissioning
Python
mit
gems-uff/labsys,gems-uff/labsys,gems-uff/labsys
from functools import wraps from flask import abort from flask_login import current_user from labsys.auth.models import Permission def permission_required(permission): def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): if not current_user.can(permission): abort(403) return f(*args, **kwargs) return decorated_function return decorator def admin_required(f): return permission_required(Permission.ADMINISTER) (f) :rocket: Verify if it's a testing app for permissioning
from functools import wraps from flask import abort, current_app from flask_login import current_user from labsys.auth.models import Permission def permission_required(permission): def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): if not current_user.can(permission) and \ not current_app.config['TESTING'] == True: abort(403) return f(*args, **kwargs) return decorated_function return decorator def admin_required(f): return permission_required(Permission.ADMINISTER) (f)
<commit_before>from functools import wraps from flask import abort from flask_login import current_user from labsys.auth.models import Permission def permission_required(permission): def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): if not current_user.can(permission): abort(403) return f(*args, **kwargs) return decorated_function return decorator def admin_required(f): return permission_required(Permission.ADMINISTER) (f) <commit_msg>:rocket: Verify if it's a testing app for permissioning<commit_after>
from functools import wraps from flask import abort, current_app from flask_login import current_user from labsys.auth.models import Permission def permission_required(permission): def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): if not current_user.can(permission) and \ not current_app.config['TESTING'] == True: abort(403) return f(*args, **kwargs) return decorated_function return decorator def admin_required(f): return permission_required(Permission.ADMINISTER) (f)
from functools import wraps from flask import abort from flask_login import current_user from labsys.auth.models import Permission def permission_required(permission): def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): if not current_user.can(permission): abort(403) return f(*args, **kwargs) return decorated_function return decorator def admin_required(f): return permission_required(Permission.ADMINISTER) (f) :rocket: Verify if it's a testing app for permissioningfrom functools import wraps from flask import abort, current_app from flask_login import current_user from labsys.auth.models import Permission def permission_required(permission): def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): if not current_user.can(permission) and \ not current_app.config['TESTING'] == True: abort(403) return f(*args, **kwargs) return decorated_function return decorator def admin_required(f): return permission_required(Permission.ADMINISTER) (f)
<commit_before>from functools import wraps from flask import abort from flask_login import current_user from labsys.auth.models import Permission def permission_required(permission): def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): if not current_user.can(permission): abort(403) return f(*args, **kwargs) return decorated_function return decorator def admin_required(f): return permission_required(Permission.ADMINISTER) (f) <commit_msg>:rocket: Verify if it's a testing app for permissioning<commit_after>from functools import wraps from flask import abort, current_app from flask_login import current_user from labsys.auth.models import Permission def permission_required(permission): def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): if not current_user.can(permission) and \ not current_app.config['TESTING'] == True: abort(403) return f(*args, **kwargs) return decorated_function return decorator def admin_required(f): return permission_required(Permission.ADMINISTER) (f)
e39e3f1c512c7766dd72b728dae322b427ab60a3
wluopensource/osl_flatpages/models.py
wluopensource/osl_flatpages/models.py
from django.db import models import markdown class Flatpage(models.Model): page_name = models.CharField(max_length=100, primary_key=True, unique=True) markdown_content = models.TextField('content') content = models.TextField(editable=False) def __unicode__(self): return self.page_name def save(self, force_insert=False, force_update=False): self.content = markdown.markdown(self.markdown_content) super(Flatpage, self).save(force_insert, force_update)
from django.db import models import markdown class Flatpage(models.Model): page_name = models.CharField(max_length=100, primary_key=True, unique=True) title = models.CharField(max_length=100) description = models.CharField(max_length=255) markdown_content = models.TextField('content') content = models.TextField(editable=False) def __unicode__(self): return self.page_name def save(self, force_insert=False, force_update=False): self.content = markdown.markdown(self.markdown_content) super(Flatpage, self).save(force_insert, force_update)
Change osl_flatpage model to separate meta data from content
Change osl_flatpage model to separate meta data from content
Python
bsd-3-clause
jeffcharles/Open-Source-at-Laurier-Website,jeffcharles/Open-Source-at-Laurier-Website,jeffcharles/Open-Source-at-Laurier-Website,jeffcharles/Open-Source-at-Laurier-Website
from django.db import models import markdown class Flatpage(models.Model): page_name = models.CharField(max_length=100, primary_key=True, unique=True) markdown_content = models.TextField('content') content = models.TextField(editable=False) def __unicode__(self): return self.page_name def save(self, force_insert=False, force_update=False): self.content = markdown.markdown(self.markdown_content) super(Flatpage, self).save(force_insert, force_update) Change osl_flatpage model to separate meta data from content
from django.db import models import markdown class Flatpage(models.Model): page_name = models.CharField(max_length=100, primary_key=True, unique=True) title = models.CharField(max_length=100) description = models.CharField(max_length=255) markdown_content = models.TextField('content') content = models.TextField(editable=False) def __unicode__(self): return self.page_name def save(self, force_insert=False, force_update=False): self.content = markdown.markdown(self.markdown_content) super(Flatpage, self).save(force_insert, force_update)
<commit_before>from django.db import models import markdown class Flatpage(models.Model): page_name = models.CharField(max_length=100, primary_key=True, unique=True) markdown_content = models.TextField('content') content = models.TextField(editable=False) def __unicode__(self): return self.page_name def save(self, force_insert=False, force_update=False): self.content = markdown.markdown(self.markdown_content) super(Flatpage, self).save(force_insert, force_update) <commit_msg>Change osl_flatpage model to separate meta data from content<commit_after>
from django.db import models import markdown class Flatpage(models.Model): page_name = models.CharField(max_length=100, primary_key=True, unique=True) title = models.CharField(max_length=100) description = models.CharField(max_length=255) markdown_content = models.TextField('content') content = models.TextField(editable=False) def __unicode__(self): return self.page_name def save(self, force_insert=False, force_update=False): self.content = markdown.markdown(self.markdown_content) super(Flatpage, self).save(force_insert, force_update)
from django.db import models import markdown class Flatpage(models.Model): page_name = models.CharField(max_length=100, primary_key=True, unique=True) markdown_content = models.TextField('content') content = models.TextField(editable=False) def __unicode__(self): return self.page_name def save(self, force_insert=False, force_update=False): self.content = markdown.markdown(self.markdown_content) super(Flatpage, self).save(force_insert, force_update) Change osl_flatpage model to separate meta data from contentfrom django.db import models import markdown class Flatpage(models.Model): page_name = models.CharField(max_length=100, primary_key=True, unique=True) title = models.CharField(max_length=100) description = models.CharField(max_length=255) markdown_content = models.TextField('content') content = models.TextField(editable=False) def __unicode__(self): return self.page_name def save(self, force_insert=False, force_update=False): self.content = markdown.markdown(self.markdown_content) super(Flatpage, self).save(force_insert, force_update)
<commit_before>from django.db import models import markdown class Flatpage(models.Model): page_name = models.CharField(max_length=100, primary_key=True, unique=True) markdown_content = models.TextField('content') content = models.TextField(editable=False) def __unicode__(self): return self.page_name def save(self, force_insert=False, force_update=False): self.content = markdown.markdown(self.markdown_content) super(Flatpage, self).save(force_insert, force_update) <commit_msg>Change osl_flatpage model to separate meta data from content<commit_after>from django.db import models import markdown class Flatpage(models.Model): page_name = models.CharField(max_length=100, primary_key=True, unique=True) title = models.CharField(max_length=100) description = models.CharField(max_length=255) markdown_content = models.TextField('content') content = models.TextField(editable=False) def __unicode__(self): return self.page_name def save(self, force_insert=False, force_update=False): self.content = markdown.markdown(self.markdown_content) super(Flatpage, self).save(force_insert, force_update)
d6052e0c1aafef8fa0a5c051838d649c080e0b10
invite/urls.py
invite/urls.py
from django.urls import path from invite import views app_name = 'invite' urlpatterns = [ path('$', views.index, name='index'), path('invite/$', views.invite, name='invite'), path('resend/(?P<code>.*)/$', views.resend, name='resend'), path('revoke/(?P<code>.*)/$', views.revoke, name='revoke'), path('login/$', views.log_in_user, name='login'), path('logout/$', views.log_out_user, name='edit_logout'), path('amnesia/$', views.amnesia, name='amnesia'), path('reset/$', views.reset, name='reset'), path('signup/$', views.signup, name='account_signup'), path('about/$', views.about, name='about'), path('check/$', views.check, name='check'), ]
from django.urls import re_path from invite import views app_name = 'invite' urlpatterns = [ re_path(r'^$', views.index, name='index'), re_path(r'^invite/$', views.invite, name='invite'), re_path(r'^resend/(?P<code>.*)/$', views.resend, name='resend'), re_path(r'^revoke/(?P<code>.*)/$', views.revoke, name='revoke'), re_path(r'^login/$', views.log_in_user, name='login'), re_path(r'^logout/$', views.log_out_user, name='edit_logout'), re_path(r'^amnesia/$', views.amnesia, name='amnesia'), re_path(r'^reset/$', views.reset, name='reset'), re_path(r'^signup/$', views.signup, name='account_signup'), re_path(r'^about/$', views.about, name='about'), re_path(r'^check/$', views.check, name='check'), ]
Replace usage of url with re_path.
Replace usage of url with re_path.
Python
bsd-3-clause
unt-libraries/django-invite,unt-libraries/django-invite
from django.urls import path from invite import views app_name = 'invite' urlpatterns = [ path('$', views.index, name='index'), path('invite/$', views.invite, name='invite'), path('resend/(?P<code>.*)/$', views.resend, name='resend'), path('revoke/(?P<code>.*)/$', views.revoke, name='revoke'), path('login/$', views.log_in_user, name='login'), path('logout/$', views.log_out_user, name='edit_logout'), path('amnesia/$', views.amnesia, name='amnesia'), path('reset/$', views.reset, name='reset'), path('signup/$', views.signup, name='account_signup'), path('about/$', views.about, name='about'), path('check/$', views.check, name='check'), ] Replace usage of url with re_path.
from django.urls import re_path from invite import views app_name = 'invite' urlpatterns = [ re_path(r'^$', views.index, name='index'), re_path(r'^invite/$', views.invite, name='invite'), re_path(r'^resend/(?P<code>.*)/$', views.resend, name='resend'), re_path(r'^revoke/(?P<code>.*)/$', views.revoke, name='revoke'), re_path(r'^login/$', views.log_in_user, name='login'), re_path(r'^logout/$', views.log_out_user, name='edit_logout'), re_path(r'^amnesia/$', views.amnesia, name='amnesia'), re_path(r'^reset/$', views.reset, name='reset'), re_path(r'^signup/$', views.signup, name='account_signup'), re_path(r'^about/$', views.about, name='about'), re_path(r'^check/$', views.check, name='check'), ]
<commit_before>from django.urls import path from invite import views app_name = 'invite' urlpatterns = [ path('$', views.index, name='index'), path('invite/$', views.invite, name='invite'), path('resend/(?P<code>.*)/$', views.resend, name='resend'), path('revoke/(?P<code>.*)/$', views.revoke, name='revoke'), path('login/$', views.log_in_user, name='login'), path('logout/$', views.log_out_user, name='edit_logout'), path('amnesia/$', views.amnesia, name='amnesia'), path('reset/$', views.reset, name='reset'), path('signup/$', views.signup, name='account_signup'), path('about/$', views.about, name='about'), path('check/$', views.check, name='check'), ] <commit_msg>Replace usage of url with re_path.<commit_after>
from django.urls import re_path from invite import views app_name = 'invite' urlpatterns = [ re_path(r'^$', views.index, name='index'), re_path(r'^invite/$', views.invite, name='invite'), re_path(r'^resend/(?P<code>.*)/$', views.resend, name='resend'), re_path(r'^revoke/(?P<code>.*)/$', views.revoke, name='revoke'), re_path(r'^login/$', views.log_in_user, name='login'), re_path(r'^logout/$', views.log_out_user, name='edit_logout'), re_path(r'^amnesia/$', views.amnesia, name='amnesia'), re_path(r'^reset/$', views.reset, name='reset'), re_path(r'^signup/$', views.signup, name='account_signup'), re_path(r'^about/$', views.about, name='about'), re_path(r'^check/$', views.check, name='check'), ]
from django.urls import path from invite import views app_name = 'invite' urlpatterns = [ path('$', views.index, name='index'), path('invite/$', views.invite, name='invite'), path('resend/(?P<code>.*)/$', views.resend, name='resend'), path('revoke/(?P<code>.*)/$', views.revoke, name='revoke'), path('login/$', views.log_in_user, name='login'), path('logout/$', views.log_out_user, name='edit_logout'), path('amnesia/$', views.amnesia, name='amnesia'), path('reset/$', views.reset, name='reset'), path('signup/$', views.signup, name='account_signup'), path('about/$', views.about, name='about'), path('check/$', views.check, name='check'), ] Replace usage of url with re_path.from django.urls import re_path from invite import views app_name = 'invite' urlpatterns = [ re_path(r'^$', views.index, name='index'), re_path(r'^invite/$', views.invite, name='invite'), re_path(r'^resend/(?P<code>.*)/$', views.resend, name='resend'), re_path(r'^revoke/(?P<code>.*)/$', views.revoke, name='revoke'), re_path(r'^login/$', views.log_in_user, name='login'), re_path(r'^logout/$', views.log_out_user, name='edit_logout'), re_path(r'^amnesia/$', views.amnesia, name='amnesia'), re_path(r'^reset/$', views.reset, name='reset'), re_path(r'^signup/$', views.signup, name='account_signup'), re_path(r'^about/$', views.about, name='about'), re_path(r'^check/$', views.check, name='check'), ]
<commit_before>from django.urls import path from invite import views app_name = 'invite' urlpatterns = [ path('$', views.index, name='index'), path('invite/$', views.invite, name='invite'), path('resend/(?P<code>.*)/$', views.resend, name='resend'), path('revoke/(?P<code>.*)/$', views.revoke, name='revoke'), path('login/$', views.log_in_user, name='login'), path('logout/$', views.log_out_user, name='edit_logout'), path('amnesia/$', views.amnesia, name='amnesia'), path('reset/$', views.reset, name='reset'), path('signup/$', views.signup, name='account_signup'), path('about/$', views.about, name='about'), path('check/$', views.check, name='check'), ] <commit_msg>Replace usage of url with re_path.<commit_after>from django.urls import re_path from invite import views app_name = 'invite' urlpatterns = [ re_path(r'^$', views.index, name='index'), re_path(r'^invite/$', views.invite, name='invite'), re_path(r'^resend/(?P<code>.*)/$', views.resend, name='resend'), re_path(r'^revoke/(?P<code>.*)/$', views.revoke, name='revoke'), re_path(r'^login/$', views.log_in_user, name='login'), re_path(r'^logout/$', views.log_out_user, name='edit_logout'), re_path(r'^amnesia/$', views.amnesia, name='amnesia'), re_path(r'^reset/$', views.reset, name='reset'), re_path(r'^signup/$', views.signup, name='account_signup'), re_path(r'^about/$', views.about, name='about'), re_path(r'^check/$', views.check, name='check'), ]
24c9ec73aed1337e1262143c5879bee3f936142c
data.py
data.py
import string ROWS = 12 COLUMNS = 14 TMPL_OPTIONS = { 'page-size': 'Letter' } PERCENTAGE_TO_CROP_SCAN_IMG = 0.005 PERCENTAGE_TO_CROP_CHAR_IMG = 0.1 CROPPED_IMG_NAME = "cropped_picture.bmp" CUT_CHAR_IMGS_DIR = "cutting_output_images" MAX_COLUMNS_PER_PAGE = 14 MAX_ROWS_PER_PAEG = 12 RELA_PIXELS_CHARACTER_BAR_HEIGHT = 30 RELA_PIXELS_WRITING_BOX_HEIGHT = 100 RELA_PIXELS_WRITING_BOX_WIDTH = 100 RELA_PIXELS_BORDER_WIDTH = 1 def get_flat_chars(): chars = unicode(string.lowercase) chars += unicode(string.uppercase) chars += unicode(string.digits) chars += unicode(string.punctuation) print chars return chars def get_chars(): chars = get_flat_chars() result = [chars[i:i + COLUMNS] for i in xrange(0, len(chars), COLUMNS)] result[-1] = result[-1].ljust(COLUMNS) result.extend([' ' * COLUMNS for i in xrange(len(result), ROWS)]) return result def get_sample_chars(): return iter("AaBb")
import string ROWS = 12 COLUMNS = 14 TMPL_OPTIONS = { 'page-size': 'Letter' } PERCENTAGE_TO_CROP_SCAN_IMG = 0.005 PERCENTAGE_TO_CROP_CHAR_IMG = 0.1 CROPPED_IMG_NAME = "cropped_picture.bmp" CUT_CHAR_IMGS_DIR = "cutting_output_images" MAX_COLUMNS_PER_PAGE = 14 MAX_ROWS_PER_PAEG = 12 RELA_PIXELS_CHARACTER_BAR_HEIGHT = 30 RELA_PIXELS_WRITING_BOX_HEIGHT = 70 RELA_PIXELS_WRITING_BOX_WIDTH = 70 RELA_PIXELS_BORDER_WIDTH = 2 def get_flat_chars(): chars = unicode(string.lowercase) chars += unicode(string.uppercase) chars += unicode(string.digits) chars += unicode(string.punctuation) print chars return chars def get_chars(): chars = get_flat_chars() result = [chars[i:i + COLUMNS] for i in xrange(0, len(chars), COLUMNS)] result[-1] = result[-1].ljust(COLUMNS) result.extend([' ' * COLUMNS for i in xrange(len(result), ROWS)]) return result def get_sample_chars(): return iter("AaBb")
Change constant variables to fit new template
Change constant variables to fit new template
Python
mit
fontify/fontify,fontify/fontify,fontify/fontify,fontify/fontify
import string ROWS = 12 COLUMNS = 14 TMPL_OPTIONS = { 'page-size': 'Letter' } PERCENTAGE_TO_CROP_SCAN_IMG = 0.005 PERCENTAGE_TO_CROP_CHAR_IMG = 0.1 CROPPED_IMG_NAME = "cropped_picture.bmp" CUT_CHAR_IMGS_DIR = "cutting_output_images" MAX_COLUMNS_PER_PAGE = 14 MAX_ROWS_PER_PAEG = 12 RELA_PIXELS_CHARACTER_BAR_HEIGHT = 30 RELA_PIXELS_WRITING_BOX_HEIGHT = 100 RELA_PIXELS_WRITING_BOX_WIDTH = 100 RELA_PIXELS_BORDER_WIDTH = 1 def get_flat_chars(): chars = unicode(string.lowercase) chars += unicode(string.uppercase) chars += unicode(string.digits) chars += unicode(string.punctuation) print chars return chars def get_chars(): chars = get_flat_chars() result = [chars[i:i + COLUMNS] for i in xrange(0, len(chars), COLUMNS)] result[-1] = result[-1].ljust(COLUMNS) result.extend([' ' * COLUMNS for i in xrange(len(result), ROWS)]) return result def get_sample_chars(): return iter("AaBb") Change constant variables to fit new template
import string ROWS = 12 COLUMNS = 14 TMPL_OPTIONS = { 'page-size': 'Letter' } PERCENTAGE_TO_CROP_SCAN_IMG = 0.005 PERCENTAGE_TO_CROP_CHAR_IMG = 0.1 CROPPED_IMG_NAME = "cropped_picture.bmp" CUT_CHAR_IMGS_DIR = "cutting_output_images" MAX_COLUMNS_PER_PAGE = 14 MAX_ROWS_PER_PAEG = 12 RELA_PIXELS_CHARACTER_BAR_HEIGHT = 30 RELA_PIXELS_WRITING_BOX_HEIGHT = 70 RELA_PIXELS_WRITING_BOX_WIDTH = 70 RELA_PIXELS_BORDER_WIDTH = 2 def get_flat_chars(): chars = unicode(string.lowercase) chars += unicode(string.uppercase) chars += unicode(string.digits) chars += unicode(string.punctuation) print chars return chars def get_chars(): chars = get_flat_chars() result = [chars[i:i + COLUMNS] for i in xrange(0, len(chars), COLUMNS)] result[-1] = result[-1].ljust(COLUMNS) result.extend([' ' * COLUMNS for i in xrange(len(result), ROWS)]) return result def get_sample_chars(): return iter("AaBb")
<commit_before>import string ROWS = 12 COLUMNS = 14 TMPL_OPTIONS = { 'page-size': 'Letter' } PERCENTAGE_TO_CROP_SCAN_IMG = 0.005 PERCENTAGE_TO_CROP_CHAR_IMG = 0.1 CROPPED_IMG_NAME = "cropped_picture.bmp" CUT_CHAR_IMGS_DIR = "cutting_output_images" MAX_COLUMNS_PER_PAGE = 14 MAX_ROWS_PER_PAEG = 12 RELA_PIXELS_CHARACTER_BAR_HEIGHT = 30 RELA_PIXELS_WRITING_BOX_HEIGHT = 100 RELA_PIXELS_WRITING_BOX_WIDTH = 100 RELA_PIXELS_BORDER_WIDTH = 1 def get_flat_chars(): chars = unicode(string.lowercase) chars += unicode(string.uppercase) chars += unicode(string.digits) chars += unicode(string.punctuation) print chars return chars def get_chars(): chars = get_flat_chars() result = [chars[i:i + COLUMNS] for i in xrange(0, len(chars), COLUMNS)] result[-1] = result[-1].ljust(COLUMNS) result.extend([' ' * COLUMNS for i in xrange(len(result), ROWS)]) return result def get_sample_chars(): return iter("AaBb") <commit_msg>Change constant variables to fit new template<commit_after>
import string ROWS = 12 COLUMNS = 14 TMPL_OPTIONS = { 'page-size': 'Letter' } PERCENTAGE_TO_CROP_SCAN_IMG = 0.005 PERCENTAGE_TO_CROP_CHAR_IMG = 0.1 CROPPED_IMG_NAME = "cropped_picture.bmp" CUT_CHAR_IMGS_DIR = "cutting_output_images" MAX_COLUMNS_PER_PAGE = 14 MAX_ROWS_PER_PAEG = 12 RELA_PIXELS_CHARACTER_BAR_HEIGHT = 30 RELA_PIXELS_WRITING_BOX_HEIGHT = 70 RELA_PIXELS_WRITING_BOX_WIDTH = 70 RELA_PIXELS_BORDER_WIDTH = 2 def get_flat_chars(): chars = unicode(string.lowercase) chars += unicode(string.uppercase) chars += unicode(string.digits) chars += unicode(string.punctuation) print chars return chars def get_chars(): chars = get_flat_chars() result = [chars[i:i + COLUMNS] for i in xrange(0, len(chars), COLUMNS)] result[-1] = result[-1].ljust(COLUMNS) result.extend([' ' * COLUMNS for i in xrange(len(result), ROWS)]) return result def get_sample_chars(): return iter("AaBb")
import string ROWS = 12 COLUMNS = 14 TMPL_OPTIONS = { 'page-size': 'Letter' } PERCENTAGE_TO_CROP_SCAN_IMG = 0.005 PERCENTAGE_TO_CROP_CHAR_IMG = 0.1 CROPPED_IMG_NAME = "cropped_picture.bmp" CUT_CHAR_IMGS_DIR = "cutting_output_images" MAX_COLUMNS_PER_PAGE = 14 MAX_ROWS_PER_PAEG = 12 RELA_PIXELS_CHARACTER_BAR_HEIGHT = 30 RELA_PIXELS_WRITING_BOX_HEIGHT = 100 RELA_PIXELS_WRITING_BOX_WIDTH = 100 RELA_PIXELS_BORDER_WIDTH = 1 def get_flat_chars(): chars = unicode(string.lowercase) chars += unicode(string.uppercase) chars += unicode(string.digits) chars += unicode(string.punctuation) print chars return chars def get_chars(): chars = get_flat_chars() result = [chars[i:i + COLUMNS] for i in xrange(0, len(chars), COLUMNS)] result[-1] = result[-1].ljust(COLUMNS) result.extend([' ' * COLUMNS for i in xrange(len(result), ROWS)]) return result def get_sample_chars(): return iter("AaBb") Change constant variables to fit new templateimport string ROWS = 12 COLUMNS = 14 TMPL_OPTIONS = { 'page-size': 'Letter' } PERCENTAGE_TO_CROP_SCAN_IMG = 0.005 PERCENTAGE_TO_CROP_CHAR_IMG = 0.1 CROPPED_IMG_NAME = "cropped_picture.bmp" CUT_CHAR_IMGS_DIR = "cutting_output_images" MAX_COLUMNS_PER_PAGE = 14 MAX_ROWS_PER_PAEG = 12 RELA_PIXELS_CHARACTER_BAR_HEIGHT = 30 RELA_PIXELS_WRITING_BOX_HEIGHT = 70 RELA_PIXELS_WRITING_BOX_WIDTH = 70 RELA_PIXELS_BORDER_WIDTH = 2 def get_flat_chars(): chars = unicode(string.lowercase) chars += unicode(string.uppercase) chars += unicode(string.digits) chars += unicode(string.punctuation) print chars return chars def get_chars(): chars = get_flat_chars() result = [chars[i:i + COLUMNS] for i in xrange(0, len(chars), COLUMNS)] result[-1] = result[-1].ljust(COLUMNS) result.extend([' ' * COLUMNS for i in xrange(len(result), ROWS)]) return result def get_sample_chars(): return iter("AaBb")
<commit_before>import string ROWS = 12 COLUMNS = 14 TMPL_OPTIONS = { 'page-size': 'Letter' } PERCENTAGE_TO_CROP_SCAN_IMG = 0.005 PERCENTAGE_TO_CROP_CHAR_IMG = 0.1 CROPPED_IMG_NAME = "cropped_picture.bmp" CUT_CHAR_IMGS_DIR = "cutting_output_images" MAX_COLUMNS_PER_PAGE = 14 MAX_ROWS_PER_PAEG = 12 RELA_PIXELS_CHARACTER_BAR_HEIGHT = 30 RELA_PIXELS_WRITING_BOX_HEIGHT = 100 RELA_PIXELS_WRITING_BOX_WIDTH = 100 RELA_PIXELS_BORDER_WIDTH = 1 def get_flat_chars(): chars = unicode(string.lowercase) chars += unicode(string.uppercase) chars += unicode(string.digits) chars += unicode(string.punctuation) print chars return chars def get_chars(): chars = get_flat_chars() result = [chars[i:i + COLUMNS] for i in xrange(0, len(chars), COLUMNS)] result[-1] = result[-1].ljust(COLUMNS) result.extend([' ' * COLUMNS for i in xrange(len(result), ROWS)]) return result def get_sample_chars(): return iter("AaBb") <commit_msg>Change constant variables to fit new template<commit_after>import string ROWS = 12 COLUMNS = 14 TMPL_OPTIONS = { 'page-size': 'Letter' } PERCENTAGE_TO_CROP_SCAN_IMG = 0.005 PERCENTAGE_TO_CROP_CHAR_IMG = 0.1 CROPPED_IMG_NAME = "cropped_picture.bmp" CUT_CHAR_IMGS_DIR = "cutting_output_images" MAX_COLUMNS_PER_PAGE = 14 MAX_ROWS_PER_PAEG = 12 RELA_PIXELS_CHARACTER_BAR_HEIGHT = 30 RELA_PIXELS_WRITING_BOX_HEIGHT = 70 RELA_PIXELS_WRITING_BOX_WIDTH = 70 RELA_PIXELS_BORDER_WIDTH = 2 def get_flat_chars(): chars = unicode(string.lowercase) chars += unicode(string.uppercase) chars += unicode(string.digits) chars += unicode(string.punctuation) print chars return chars def get_chars(): chars = get_flat_chars() result = [chars[i:i + COLUMNS] for i in xrange(0, len(chars), COLUMNS)] result[-1] = result[-1].ljust(COLUMNS) result.extend([' ' * COLUMNS for i in xrange(len(result), ROWS)]) return result def get_sample_chars(): return iter("AaBb")
dc60ed6efdd4eb9a78e29623acee7505f2d864e6
Lib/test/test_fork1.py
Lib/test/test_fork1.py
"""This test checks for correct fork() behavior. We want fork1() semantics -- only the forking thread survives in the child after a fork(). On some systems (e.g. Solaris without posix threads) we find that all active threads survive in the child after a fork(); this is an error. """ import os, sys, time, thread LONGSLEEP = 2 SHORTSLEEP = 0.5 alive = {} def f(id): while 1: alive[id] = os.getpid() try: time.sleep(SHORTSLEEP) except IOError: pass def main(): for i in range(4): thread.start_new(f, (i,)) time.sleep(LONGSLEEP) a = alive.keys() a.sort() assert a == range(4) cpid = os.fork() if cpid == 0: # Child time.sleep(LONGSLEEP) n = 0 pid = os.getpid() for key in alive.keys(): if alive[key] == pid: n = n+1 os._exit(n) else: # Parent spid, status = os.waitpid(cpid, 0) assert spid == cpid assert status == 0, "cause = %d, exit = %d" % (status&0xff, status>>8) main()
"""This test checks for correct fork() behavior. We want fork1() semantics -- only the forking thread survives in the child after a fork(). On some systems (e.g. Solaris without posix threads) we find that all active threads survive in the child after a fork(); this is an error. """ import os, sys, time, thread LONGSLEEP = 2 SHORTSLEEP = 0.5 NUM_THREADS = 4 alive = {} def f(id): while 1: alive[id] = os.getpid() try: time.sleep(SHORTSLEEP) except IOError: pass def main(): for i in range(NUM_THREADS): thread.start_new(f, (i,)) time.sleep(LONGSLEEP) a = alive.keys() a.sort() assert a == range(NUM_THREADS) prefork_lives = alive.copy() cpid = os.fork() if cpid == 0: # Child time.sleep(LONGSLEEP) n = 0 for key in alive.keys(): if alive[key] != prefork_lives[key]: n = n+1 os._exit(n) else: # Parent spid, status = os.waitpid(cpid, 0) assert spid == cpid assert status == 0, "cause = %d, exit = %d" % (status&0xff, status>>8) main()
Use a constant to specify the number of child threads to create.
Use a constant to specify the number of child threads to create. Instead of assuming that the number process ids of the threads is the same as the process id of the controlling process, use a copy of the dictionary and check for changes in the process ids of the threads from the thread's process ids in the parent process. This makes the test make more sense on systems which assign a new pid to each thread (i.e., Linux). This doesn't fix the other problems evident with this test on Linux.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
"""This test checks for correct fork() behavior. We want fork1() semantics -- only the forking thread survives in the child after a fork(). On some systems (e.g. Solaris without posix threads) we find that all active threads survive in the child after a fork(); this is an error. """ import os, sys, time, thread LONGSLEEP = 2 SHORTSLEEP = 0.5 alive = {} def f(id): while 1: alive[id] = os.getpid() try: time.sleep(SHORTSLEEP) except IOError: pass def main(): for i in range(4): thread.start_new(f, (i,)) time.sleep(LONGSLEEP) a = alive.keys() a.sort() assert a == range(4) cpid = os.fork() if cpid == 0: # Child time.sleep(LONGSLEEP) n = 0 pid = os.getpid() for key in alive.keys(): if alive[key] == pid: n = n+1 os._exit(n) else: # Parent spid, status = os.waitpid(cpid, 0) assert spid == cpid assert status == 0, "cause = %d, exit = %d" % (status&0xff, status>>8) main() Use a constant to specify the number of child threads to create. Instead of assuming that the number process ids of the threads is the same as the process id of the controlling process, use a copy of the dictionary and check for changes in the process ids of the threads from the thread's process ids in the parent process. This makes the test make more sense on systems which assign a new pid to each thread (i.e., Linux). This doesn't fix the other problems evident with this test on Linux.
"""This test checks for correct fork() behavior. We want fork1() semantics -- only the forking thread survives in the child after a fork(). On some systems (e.g. Solaris without posix threads) we find that all active threads survive in the child after a fork(); this is an error. """ import os, sys, time, thread LONGSLEEP = 2 SHORTSLEEP = 0.5 NUM_THREADS = 4 alive = {} def f(id): while 1: alive[id] = os.getpid() try: time.sleep(SHORTSLEEP) except IOError: pass def main(): for i in range(NUM_THREADS): thread.start_new(f, (i,)) time.sleep(LONGSLEEP) a = alive.keys() a.sort() assert a == range(NUM_THREADS) prefork_lives = alive.copy() cpid = os.fork() if cpid == 0: # Child time.sleep(LONGSLEEP) n = 0 for key in alive.keys(): if alive[key] != prefork_lives[key]: n = n+1 os._exit(n) else: # Parent spid, status = os.waitpid(cpid, 0) assert spid == cpid assert status == 0, "cause = %d, exit = %d" % (status&0xff, status>>8) main()
<commit_before>"""This test checks for correct fork() behavior. We want fork1() semantics -- only the forking thread survives in the child after a fork(). On some systems (e.g. Solaris without posix threads) we find that all active threads survive in the child after a fork(); this is an error. """ import os, sys, time, thread LONGSLEEP = 2 SHORTSLEEP = 0.5 alive = {} def f(id): while 1: alive[id] = os.getpid() try: time.sleep(SHORTSLEEP) except IOError: pass def main(): for i in range(4): thread.start_new(f, (i,)) time.sleep(LONGSLEEP) a = alive.keys() a.sort() assert a == range(4) cpid = os.fork() if cpid == 0: # Child time.sleep(LONGSLEEP) n = 0 pid = os.getpid() for key in alive.keys(): if alive[key] == pid: n = n+1 os._exit(n) else: # Parent spid, status = os.waitpid(cpid, 0) assert spid == cpid assert status == 0, "cause = %d, exit = %d" % (status&0xff, status>>8) main() <commit_msg>Use a constant to specify the number of child threads to create. Instead of assuming that the number process ids of the threads is the same as the process id of the controlling process, use a copy of the dictionary and check for changes in the process ids of the threads from the thread's process ids in the parent process. This makes the test make more sense on systems which assign a new pid to each thread (i.e., Linux). This doesn't fix the other problems evident with this test on Linux.<commit_after>
"""This test checks for correct fork() behavior. We want fork1() semantics -- only the forking thread survives in the child after a fork(). On some systems (e.g. Solaris without posix threads) we find that all active threads survive in the child after a fork(); this is an error. """ import os, sys, time, thread LONGSLEEP = 2 SHORTSLEEP = 0.5 NUM_THREADS = 4 alive = {} def f(id): while 1: alive[id] = os.getpid() try: time.sleep(SHORTSLEEP) except IOError: pass def main(): for i in range(NUM_THREADS): thread.start_new(f, (i,)) time.sleep(LONGSLEEP) a = alive.keys() a.sort() assert a == range(NUM_THREADS) prefork_lives = alive.copy() cpid = os.fork() if cpid == 0: # Child time.sleep(LONGSLEEP) n = 0 for key in alive.keys(): if alive[key] != prefork_lives[key]: n = n+1 os._exit(n) else: # Parent spid, status = os.waitpid(cpid, 0) assert spid == cpid assert status == 0, "cause = %d, exit = %d" % (status&0xff, status>>8) main()
"""This test checks for correct fork() behavior. We want fork1() semantics -- only the forking thread survives in the child after a fork(). On some systems (e.g. Solaris without posix threads) we find that all active threads survive in the child after a fork(); this is an error. """ import os, sys, time, thread LONGSLEEP = 2 SHORTSLEEP = 0.5 alive = {} def f(id): while 1: alive[id] = os.getpid() try: time.sleep(SHORTSLEEP) except IOError: pass def main(): for i in range(4): thread.start_new(f, (i,)) time.sleep(LONGSLEEP) a = alive.keys() a.sort() assert a == range(4) cpid = os.fork() if cpid == 0: # Child time.sleep(LONGSLEEP) n = 0 pid = os.getpid() for key in alive.keys(): if alive[key] == pid: n = n+1 os._exit(n) else: # Parent spid, status = os.waitpid(cpid, 0) assert spid == cpid assert status == 0, "cause = %d, exit = %d" % (status&0xff, status>>8) main() Use a constant to specify the number of child threads to create. Instead of assuming that the number process ids of the threads is the same as the process id of the controlling process, use a copy of the dictionary and check for changes in the process ids of the threads from the thread's process ids in the parent process. This makes the test make more sense on systems which assign a new pid to each thread (i.e., Linux). This doesn't fix the other problems evident with this test on Linux."""This test checks for correct fork() behavior. We want fork1() semantics -- only the forking thread survives in the child after a fork(). On some systems (e.g. Solaris without posix threads) we find that all active threads survive in the child after a fork(); this is an error. """ import os, sys, time, thread LONGSLEEP = 2 SHORTSLEEP = 0.5 NUM_THREADS = 4 alive = {} def f(id): while 1: alive[id] = os.getpid() try: time.sleep(SHORTSLEEP) except IOError: pass def main(): for i in range(NUM_THREADS): thread.start_new(f, (i,)) time.sleep(LONGSLEEP) a = alive.keys() a.sort() assert a == range(NUM_THREADS) prefork_lives = alive.copy() cpid = os.fork() if cpid == 0: # Child time.sleep(LONGSLEEP) n = 0 for key in alive.keys(): if alive[key] != prefork_lives[key]: n = n+1 os._exit(n) else: # Parent spid, status = os.waitpid(cpid, 0) assert spid == cpid assert status == 0, "cause = %d, exit = %d" % (status&0xff, status>>8) main()
<commit_before>"""This test checks for correct fork() behavior. We want fork1() semantics -- only the forking thread survives in the child after a fork(). On some systems (e.g. Solaris without posix threads) we find that all active threads survive in the child after a fork(); this is an error. """ import os, sys, time, thread LONGSLEEP = 2 SHORTSLEEP = 0.5 alive = {} def f(id): while 1: alive[id] = os.getpid() try: time.sleep(SHORTSLEEP) except IOError: pass def main(): for i in range(4): thread.start_new(f, (i,)) time.sleep(LONGSLEEP) a = alive.keys() a.sort() assert a == range(4) cpid = os.fork() if cpid == 0: # Child time.sleep(LONGSLEEP) n = 0 pid = os.getpid() for key in alive.keys(): if alive[key] == pid: n = n+1 os._exit(n) else: # Parent spid, status = os.waitpid(cpid, 0) assert spid == cpid assert status == 0, "cause = %d, exit = %d" % (status&0xff, status>>8) main() <commit_msg>Use a constant to specify the number of child threads to create. Instead of assuming that the number process ids of the threads is the same as the process id of the controlling process, use a copy of the dictionary and check for changes in the process ids of the threads from the thread's process ids in the parent process. This makes the test make more sense on systems which assign a new pid to each thread (i.e., Linux). This doesn't fix the other problems evident with this test on Linux.<commit_after>"""This test checks for correct fork() behavior. We want fork1() semantics -- only the forking thread survives in the child after a fork(). On some systems (e.g. Solaris without posix threads) we find that all active threads survive in the child after a fork(); this is an error. """ import os, sys, time, thread LONGSLEEP = 2 SHORTSLEEP = 0.5 NUM_THREADS = 4 alive = {} def f(id): while 1: alive[id] = os.getpid() try: time.sleep(SHORTSLEEP) except IOError: pass def main(): for i in range(NUM_THREADS): thread.start_new(f, (i,)) time.sleep(LONGSLEEP) a = alive.keys() a.sort() assert a == range(NUM_THREADS) prefork_lives = alive.copy() cpid = os.fork() if cpid == 0: # Child time.sleep(LONGSLEEP) n = 0 for key in alive.keys(): if alive[key] != prefork_lives[key]: n = n+1 os._exit(n) else: # Parent spid, status = os.waitpid(cpid, 0) assert spid == cpid assert status == 0, "cause = %d, exit = %d" % (status&0xff, status>>8) main()
be5dd49826b08b6d2489db72a76ed00f978b0fbe
st2reactor/st2reactor/rules/worker.py
st2reactor/st2reactor/rules/worker.py
from st2common.transport.reactor import get_trigger_queue def work(): # TODO Listen on this queue and dispatch message to the rules engine queue = get_trigger_queue(name='st2.trigger_dispatch.rules_engine', routing_key='#') pass
from kombu import Connection from kombu.mixins import ConsumerMixin from oslo.config import cfg from st2common import log as logging from st2common.transport.reactor import get_trigger_queue from st2common.util.greenpooldispatch import BufferedDispatcher LOG = logging.getLogger(__name__) RULESENGINE_WORK_Q = get_trigger_queue(name='st2.trigger_dispatch.rules_engine', routing_key='#') class Worker(ConsumerMixin): def __init__(self, connection): self.connection = connection self._dispatcher = BufferedDispatcher() def shutdown(self): self._dispatcher.shutdown() def get_consumers(self, Consumer, channel): consumer = Consumer(queues=[RULESENGINE_WORK_Q], accept=['pickle'], callbacks=[self.process_task]) # use prefetch_count=1 for fair dispatch. This way workers that finish an item get the next # task and the work does not get queued behind any single large item. consumer.qos(prefetch_count=1) return [consumer] def process_task(self, body, message): # LOG.debug('process_task') # LOG.debug(' body: %s', body) # LOG.debug(' message.properties: %s', message.properties) # LOG.debug(' message.delivery_info: %s', message.delivery_info) try: self._dispatcher.dispatch(self._do_process_task, body) finally: message.ack() def _do_process_task(self, body): pass def work(): with Connection(cfg.CONF.messaging.url) as conn: worker = Worker(conn) try: worker.run() except: worker.shutdown() raise
Handle messages posted to the TriggerInstance work Q.
Handle messages posted to the TriggerInstance work Q.
Python
apache-2.0
StackStorm/st2,grengojbo/st2,pinterb/st2,Itxaka/st2,lakshmi-kannan/st2,StackStorm/st2,grengojbo/st2,StackStorm/st2,peak6/st2,Itxaka/st2,punalpatel/st2,tonybaloney/st2,pixelrebel/st2,dennybaa/st2,lakshmi-kannan/st2,armab/st2,dennybaa/st2,jtopjian/st2,alfasin/st2,pixelrebel/st2,pinterb/st2,punalpatel/st2,nzlosh/st2,pixelrebel/st2,jtopjian/st2,alfasin/st2,Plexxi/st2,emedvedev/st2,Itxaka/st2,nzlosh/st2,Plexxi/st2,punalpatel/st2,lakshmi-kannan/st2,jtopjian/st2,peak6/st2,tonybaloney/st2,alfasin/st2,pinterb/st2,Plexxi/st2,nzlosh/st2,StackStorm/st2,peak6/st2,armab/st2,nzlosh/st2,Plexxi/st2,tonybaloney/st2,emedvedev/st2,dennybaa/st2,grengojbo/st2,armab/st2,emedvedev/st2
from st2common.transport.reactor import get_trigger_queue def work(): # TODO Listen on this queue and dispatch message to the rules engine queue = get_trigger_queue(name='st2.trigger_dispatch.rules_engine', routing_key='#') pass Handle messages posted to the TriggerInstance work Q.
from kombu import Connection from kombu.mixins import ConsumerMixin from oslo.config import cfg from st2common import log as logging from st2common.transport.reactor import get_trigger_queue from st2common.util.greenpooldispatch import BufferedDispatcher LOG = logging.getLogger(__name__) RULESENGINE_WORK_Q = get_trigger_queue(name='st2.trigger_dispatch.rules_engine', routing_key='#') class Worker(ConsumerMixin): def __init__(self, connection): self.connection = connection self._dispatcher = BufferedDispatcher() def shutdown(self): self._dispatcher.shutdown() def get_consumers(self, Consumer, channel): consumer = Consumer(queues=[RULESENGINE_WORK_Q], accept=['pickle'], callbacks=[self.process_task]) # use prefetch_count=1 for fair dispatch. This way workers that finish an item get the next # task and the work does not get queued behind any single large item. consumer.qos(prefetch_count=1) return [consumer] def process_task(self, body, message): # LOG.debug('process_task') # LOG.debug(' body: %s', body) # LOG.debug(' message.properties: %s', message.properties) # LOG.debug(' message.delivery_info: %s', message.delivery_info) try: self._dispatcher.dispatch(self._do_process_task, body) finally: message.ack() def _do_process_task(self, body): pass def work(): with Connection(cfg.CONF.messaging.url) as conn: worker = Worker(conn) try: worker.run() except: worker.shutdown() raise
<commit_before>from st2common.transport.reactor import get_trigger_queue def work(): # TODO Listen on this queue and dispatch message to the rules engine queue = get_trigger_queue(name='st2.trigger_dispatch.rules_engine', routing_key='#') pass <commit_msg>Handle messages posted to the TriggerInstance work Q.<commit_after>
from kombu import Connection from kombu.mixins import ConsumerMixin from oslo.config import cfg from st2common import log as logging from st2common.transport.reactor import get_trigger_queue from st2common.util.greenpooldispatch import BufferedDispatcher LOG = logging.getLogger(__name__) RULESENGINE_WORK_Q = get_trigger_queue(name='st2.trigger_dispatch.rules_engine', routing_key='#') class Worker(ConsumerMixin): def __init__(self, connection): self.connection = connection self._dispatcher = BufferedDispatcher() def shutdown(self): self._dispatcher.shutdown() def get_consumers(self, Consumer, channel): consumer = Consumer(queues=[RULESENGINE_WORK_Q], accept=['pickle'], callbacks=[self.process_task]) # use prefetch_count=1 for fair dispatch. This way workers that finish an item get the next # task and the work does not get queued behind any single large item. consumer.qos(prefetch_count=1) return [consumer] def process_task(self, body, message): # LOG.debug('process_task') # LOG.debug(' body: %s', body) # LOG.debug(' message.properties: %s', message.properties) # LOG.debug(' message.delivery_info: %s', message.delivery_info) try: self._dispatcher.dispatch(self._do_process_task, body) finally: message.ack() def _do_process_task(self, body): pass def work(): with Connection(cfg.CONF.messaging.url) as conn: worker = Worker(conn) try: worker.run() except: worker.shutdown() raise
from st2common.transport.reactor import get_trigger_queue def work(): # TODO Listen on this queue and dispatch message to the rules engine queue = get_trigger_queue(name='st2.trigger_dispatch.rules_engine', routing_key='#') pass Handle messages posted to the TriggerInstance work Q.from kombu import Connection from kombu.mixins import ConsumerMixin from oslo.config import cfg from st2common import log as logging from st2common.transport.reactor import get_trigger_queue from st2common.util.greenpooldispatch import BufferedDispatcher LOG = logging.getLogger(__name__) RULESENGINE_WORK_Q = get_trigger_queue(name='st2.trigger_dispatch.rules_engine', routing_key='#') class Worker(ConsumerMixin): def __init__(self, connection): self.connection = connection self._dispatcher = BufferedDispatcher() def shutdown(self): self._dispatcher.shutdown() def get_consumers(self, Consumer, channel): consumer = Consumer(queues=[RULESENGINE_WORK_Q], accept=['pickle'], callbacks=[self.process_task]) # use prefetch_count=1 for fair dispatch. This way workers that finish an item get the next # task and the work does not get queued behind any single large item. consumer.qos(prefetch_count=1) return [consumer] def process_task(self, body, message): # LOG.debug('process_task') # LOG.debug(' body: %s', body) # LOG.debug(' message.properties: %s', message.properties) # LOG.debug(' message.delivery_info: %s', message.delivery_info) try: self._dispatcher.dispatch(self._do_process_task, body) finally: message.ack() def _do_process_task(self, body): pass def work(): with Connection(cfg.CONF.messaging.url) as conn: worker = Worker(conn) try: worker.run() except: worker.shutdown() raise
<commit_before>from st2common.transport.reactor import get_trigger_queue def work(): # TODO Listen on this queue and dispatch message to the rules engine queue = get_trigger_queue(name='st2.trigger_dispatch.rules_engine', routing_key='#') pass <commit_msg>Handle messages posted to the TriggerInstance work Q.<commit_after>from kombu import Connection from kombu.mixins import ConsumerMixin from oslo.config import cfg from st2common import log as logging from st2common.transport.reactor import get_trigger_queue from st2common.util.greenpooldispatch import BufferedDispatcher LOG = logging.getLogger(__name__) RULESENGINE_WORK_Q = get_trigger_queue(name='st2.trigger_dispatch.rules_engine', routing_key='#') class Worker(ConsumerMixin): def __init__(self, connection): self.connection = connection self._dispatcher = BufferedDispatcher() def shutdown(self): self._dispatcher.shutdown() def get_consumers(self, Consumer, channel): consumer = Consumer(queues=[RULESENGINE_WORK_Q], accept=['pickle'], callbacks=[self.process_task]) # use prefetch_count=1 for fair dispatch. This way workers that finish an item get the next # task and the work does not get queued behind any single large item. consumer.qos(prefetch_count=1) return [consumer] def process_task(self, body, message): # LOG.debug('process_task') # LOG.debug(' body: %s', body) # LOG.debug(' message.properties: %s', message.properties) # LOG.debug(' message.delivery_info: %s', message.delivery_info) try: self._dispatcher.dispatch(self._do_process_task, body) finally: message.ack() def _do_process_task(self, body): pass def work(): with Connection(cfg.CONF.messaging.url) as conn: worker = Worker(conn) try: worker.run() except: worker.shutdown() raise
e83266987db962f2546da84f5f507ff4f67e3499
django_vend/stores/outlet_urls.py
django_vend/stores/outlet_urls.py
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.OutletList.as_view(), name='vend_outlet_list'), ]
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.OutletList.as_view(), name='vend_outlet_list'), url(r'^(?P<uid>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/$', views.OutletDetail.as_view(), name='vend_outlet_detail'), ]
Add urlconf entry for VendOutlet detail
Add urlconf entry for VendOutlet detail
Python
bsd-3-clause
remarkablerocket/django-vend,remarkablerocket/django-vend
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.OutletList.as_view(), name='vend_outlet_list'), ] Add urlconf entry for VendOutlet detail
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.OutletList.as_view(), name='vend_outlet_list'), url(r'^(?P<uid>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/$', views.OutletDetail.as_view(), name='vend_outlet_detail'), ]
<commit_before>from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.OutletList.as_view(), name='vend_outlet_list'), ] <commit_msg>Add urlconf entry for VendOutlet detail<commit_after>
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.OutletList.as_view(), name='vend_outlet_list'), url(r'^(?P<uid>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/$', views.OutletDetail.as_view(), name='vend_outlet_detail'), ]
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.OutletList.as_view(), name='vend_outlet_list'), ] Add urlconf entry for VendOutlet detailfrom django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.OutletList.as_view(), name='vend_outlet_list'), url(r'^(?P<uid>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/$', views.OutletDetail.as_view(), name='vend_outlet_detail'), ]
<commit_before>from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.OutletList.as_view(), name='vend_outlet_list'), ] <commit_msg>Add urlconf entry for VendOutlet detail<commit_after>from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.OutletList.as_view(), name='vend_outlet_list'), url(r'^(?P<uid>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/$', views.OutletDetail.as_view(), name='vend_outlet_detail'), ]
1b28a83dd7a8c5698de266656f07dcd3f98826f2
tensorforce/core/memories/__init__.py
tensorforce/core/memories/__init__.py
# Copyright 2017 reinforce.io. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== from tensorforce.core.memories.memory import Memory from tensorforce.core.memories.prioritized_replay import PrioritizedReplay from tensorforce.core.memories.queue import Queue from tensorforce.core.memories.latest import Latest from tensorforce.core.memories.replay import Replay memories = dict( latest=Latest, replay=Replay, prioritized_replay=PrioritizedReplay # prioritized_replay=PrioritizedReplay, # naive_prioritized_replay=NaivePrioritizedReplay ) __all__ = ['memories', 'Memory', 'Queue', 'Latest', 'Replay', 'PrioritizedReplay']
# Copyright 2017 reinforce.io. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== from tensorforce.core.memories.memory import Memory from tensorforce.core.memories.queue import Queue from tensorforce.core.memories.latest import Latest from tensorforce.core.memories.replay import Replay from tensorforce.core.memories.prioritized_replay import PrioritizedReplay memories = dict( latest=Latest, replay=Replay, prioritized_replay=PrioritizedReplay # prioritized_replay=PrioritizedReplay, # naive_prioritized_replay=NaivePrioritizedReplay ) __all__ = ['memories', 'Memory', 'Queue', 'Latest', 'Replay', 'PrioritizedReplay']
Change import order in memories
Change import order in memories
Python
apache-2.0
lefnire/tensorforce,reinforceio/tensorforce
# Copyright 2017 reinforce.io. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== from tensorforce.core.memories.memory import Memory from tensorforce.core.memories.prioritized_replay import PrioritizedReplay from tensorforce.core.memories.queue import Queue from tensorforce.core.memories.latest import Latest from tensorforce.core.memories.replay import Replay memories = dict( latest=Latest, replay=Replay, prioritized_replay=PrioritizedReplay # prioritized_replay=PrioritizedReplay, # naive_prioritized_replay=NaivePrioritizedReplay ) __all__ = ['memories', 'Memory', 'Queue', 'Latest', 'Replay', 'PrioritizedReplay'] Change import order in memories
# Copyright 2017 reinforce.io. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== from tensorforce.core.memories.memory import Memory from tensorforce.core.memories.queue import Queue from tensorforce.core.memories.latest import Latest from tensorforce.core.memories.replay import Replay from tensorforce.core.memories.prioritized_replay import PrioritizedReplay memories = dict( latest=Latest, replay=Replay, prioritized_replay=PrioritizedReplay # prioritized_replay=PrioritizedReplay, # naive_prioritized_replay=NaivePrioritizedReplay ) __all__ = ['memories', 'Memory', 'Queue', 'Latest', 'Replay', 'PrioritizedReplay']
<commit_before># Copyright 2017 reinforce.io. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== from tensorforce.core.memories.memory import Memory from tensorforce.core.memories.prioritized_replay import PrioritizedReplay from tensorforce.core.memories.queue import Queue from tensorforce.core.memories.latest import Latest from tensorforce.core.memories.replay import Replay memories = dict( latest=Latest, replay=Replay, prioritized_replay=PrioritizedReplay # prioritized_replay=PrioritizedReplay, # naive_prioritized_replay=NaivePrioritizedReplay ) __all__ = ['memories', 'Memory', 'Queue', 'Latest', 'Replay', 'PrioritizedReplay'] <commit_msg>Change import order in memories<commit_after>
# Copyright 2017 reinforce.io. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== from tensorforce.core.memories.memory import Memory from tensorforce.core.memories.queue import Queue from tensorforce.core.memories.latest import Latest from tensorforce.core.memories.replay import Replay from tensorforce.core.memories.prioritized_replay import PrioritizedReplay memories = dict( latest=Latest, replay=Replay, prioritized_replay=PrioritizedReplay # prioritized_replay=PrioritizedReplay, # naive_prioritized_replay=NaivePrioritizedReplay ) __all__ = ['memories', 'Memory', 'Queue', 'Latest', 'Replay', 'PrioritizedReplay']
# Copyright 2017 reinforce.io. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== from tensorforce.core.memories.memory import Memory from tensorforce.core.memories.prioritized_replay import PrioritizedReplay from tensorforce.core.memories.queue import Queue from tensorforce.core.memories.latest import Latest from tensorforce.core.memories.replay import Replay memories = dict( latest=Latest, replay=Replay, prioritized_replay=PrioritizedReplay # prioritized_replay=PrioritizedReplay, # naive_prioritized_replay=NaivePrioritizedReplay ) __all__ = ['memories', 'Memory', 'Queue', 'Latest', 'Replay', 'PrioritizedReplay'] Change import order in memories# Copyright 2017 reinforce.io. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== from tensorforce.core.memories.memory import Memory from tensorforce.core.memories.queue import Queue from tensorforce.core.memories.latest import Latest from tensorforce.core.memories.replay import Replay from tensorforce.core.memories.prioritized_replay import PrioritizedReplay memories = dict( latest=Latest, replay=Replay, prioritized_replay=PrioritizedReplay # prioritized_replay=PrioritizedReplay, # naive_prioritized_replay=NaivePrioritizedReplay ) __all__ = ['memories', 'Memory', 'Queue', 'Latest', 'Replay', 'PrioritizedReplay']
<commit_before># Copyright 2017 reinforce.io. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== from tensorforce.core.memories.memory import Memory from tensorforce.core.memories.prioritized_replay import PrioritizedReplay from tensorforce.core.memories.queue import Queue from tensorforce.core.memories.latest import Latest from tensorforce.core.memories.replay import Replay memories = dict( latest=Latest, replay=Replay, prioritized_replay=PrioritizedReplay # prioritized_replay=PrioritizedReplay, # naive_prioritized_replay=NaivePrioritizedReplay ) __all__ = ['memories', 'Memory', 'Queue', 'Latest', 'Replay', 'PrioritizedReplay'] <commit_msg>Change import order in memories<commit_after># Copyright 2017 reinforce.io. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== from tensorforce.core.memories.memory import Memory from tensorforce.core.memories.queue import Queue from tensorforce.core.memories.latest import Latest from tensorforce.core.memories.replay import Replay from tensorforce.core.memories.prioritized_replay import PrioritizedReplay memories = dict( latest=Latest, replay=Replay, prioritized_replay=PrioritizedReplay # prioritized_replay=PrioritizedReplay, # naive_prioritized_replay=NaivePrioritizedReplay ) __all__ = ['memories', 'Memory', 'Queue', 'Latest', 'Replay', 'PrioritizedReplay']
9dffd8819d998d9e850709ee0a7a0f33e6cb186d
tools/np_suppressions.py
tools/np_suppressions.py
suppressions = [ # This one cannot be covered by any Python language test because there is # no code pathway to it. But it is part of the C API, so must not be # excised from the code. [ r".*/multiarray/mapping\.", "PyArray_MapIterReset" ], # PyArray_Std trivially forwards to and appears to be superceded by # __New_PyArray_Std, which is exercised by the test framework. [ r".*/multiarray/calculation\.", "PyArray_Std" ], # PyCapsule_Check is declared in a header, and used in # multiarray/ctors.c. So it isn't really untested. [ r".*/multiarray/common\.", "PyCapsule_Check" ], ]
suppressions = [ # This one cannot be covered by any Python language test because there is # no code pathway to it. But it is part of the C API, so must not be # excised from the code. [ r".*/multiarray/mapping\.", "PyArray_MapIterReset" ], # PyArray_Std trivially forwards to and appears to be superceded by # __New_PyArray_Std, which is exercised by the test framework. [ r".*/multiarray/calculation\.", "PyArray_Std" ], # PyCapsule_Check is declared in a header, and used in # multiarray/ctors.c. So it isn't really untested. [ r".*/multiarray/common\.", "PyCapsule_Check" ], # It is unclear why these aren't called by the array casting tests in # test_npy_arraytypes.py, when other X_to_X functions are called. [ r".*/libnumpy/npy_arraytypes\.", "DATETIME_to_DATETIME" ], [ r".*/libnumpy/npy_arraytypes\.", "TIMEDELTA_to_TIMEDELTA" ], [ r".*/libnumpy/npy_arraytypes\.", "BOOL_to_BOOL" ], [ r".*/libnumpy/npy_arraytypes\.", "BYTE_to_BYTE" ], [ r".*/libnumpy/npy_arraytypes\.", "UBYTE_to_UBYTE" ], [ r".*/libnumpy/npy_arraytypes\.", "LONGLONG_to_LONGLONG" ], [ r".*/libnumpy/npy_arraytypes\.", "ULONGLONG_to_ULONGLONG" ], ]
Add supressions for array casting functions that don't seem to be callable.
Add supressions for array casting functions that don't seem to be callable.
Python
bsd-3-clause
teoliphant/numpy-refactor,teoliphant/numpy-refactor,teoliphant/numpy-refactor,teoliphant/numpy-refactor,teoliphant/numpy-refactor
suppressions = [ # This one cannot be covered by any Python language test because there is # no code pathway to it. But it is part of the C API, so must not be # excised from the code. [ r".*/multiarray/mapping\.", "PyArray_MapIterReset" ], # PyArray_Std trivially forwards to and appears to be superceded by # __New_PyArray_Std, which is exercised by the test framework. [ r".*/multiarray/calculation\.", "PyArray_Std" ], # PyCapsule_Check is declared in a header, and used in # multiarray/ctors.c. So it isn't really untested. [ r".*/multiarray/common\.", "PyCapsule_Check" ], ] Add supressions for array casting functions that don't seem to be callable.
suppressions = [ # This one cannot be covered by any Python language test because there is # no code pathway to it. But it is part of the C API, so must not be # excised from the code. [ r".*/multiarray/mapping\.", "PyArray_MapIterReset" ], # PyArray_Std trivially forwards to and appears to be superceded by # __New_PyArray_Std, which is exercised by the test framework. [ r".*/multiarray/calculation\.", "PyArray_Std" ], # PyCapsule_Check is declared in a header, and used in # multiarray/ctors.c. So it isn't really untested. [ r".*/multiarray/common\.", "PyCapsule_Check" ], # It is unclear why these aren't called by the array casting tests in # test_npy_arraytypes.py, when other X_to_X functions are called. [ r".*/libnumpy/npy_arraytypes\.", "DATETIME_to_DATETIME" ], [ r".*/libnumpy/npy_arraytypes\.", "TIMEDELTA_to_TIMEDELTA" ], [ r".*/libnumpy/npy_arraytypes\.", "BOOL_to_BOOL" ], [ r".*/libnumpy/npy_arraytypes\.", "BYTE_to_BYTE" ], [ r".*/libnumpy/npy_arraytypes\.", "UBYTE_to_UBYTE" ], [ r".*/libnumpy/npy_arraytypes\.", "LONGLONG_to_LONGLONG" ], [ r".*/libnumpy/npy_arraytypes\.", "ULONGLONG_to_ULONGLONG" ], ]
<commit_before>suppressions = [ # This one cannot be covered by any Python language test because there is # no code pathway to it. But it is part of the C API, so must not be # excised from the code. [ r".*/multiarray/mapping\.", "PyArray_MapIterReset" ], # PyArray_Std trivially forwards to and appears to be superceded by # __New_PyArray_Std, which is exercised by the test framework. [ r".*/multiarray/calculation\.", "PyArray_Std" ], # PyCapsule_Check is declared in a header, and used in # multiarray/ctors.c. So it isn't really untested. [ r".*/multiarray/common\.", "PyCapsule_Check" ], ] <commit_msg>Add supressions for array casting functions that don't seem to be callable.<commit_after>
suppressions = [ # This one cannot be covered by any Python language test because there is # no code pathway to it. But it is part of the C API, so must not be # excised from the code. [ r".*/multiarray/mapping\.", "PyArray_MapIterReset" ], # PyArray_Std trivially forwards to and appears to be superceded by # __New_PyArray_Std, which is exercised by the test framework. [ r".*/multiarray/calculation\.", "PyArray_Std" ], # PyCapsule_Check is declared in a header, and used in # multiarray/ctors.c. So it isn't really untested. [ r".*/multiarray/common\.", "PyCapsule_Check" ], # It is unclear why these aren't called by the array casting tests in # test_npy_arraytypes.py, when other X_to_X functions are called. [ r".*/libnumpy/npy_arraytypes\.", "DATETIME_to_DATETIME" ], [ r".*/libnumpy/npy_arraytypes\.", "TIMEDELTA_to_TIMEDELTA" ], [ r".*/libnumpy/npy_arraytypes\.", "BOOL_to_BOOL" ], [ r".*/libnumpy/npy_arraytypes\.", "BYTE_to_BYTE" ], [ r".*/libnumpy/npy_arraytypes\.", "UBYTE_to_UBYTE" ], [ r".*/libnumpy/npy_arraytypes\.", "LONGLONG_to_LONGLONG" ], [ r".*/libnumpy/npy_arraytypes\.", "ULONGLONG_to_ULONGLONG" ], ]
suppressions = [ # This one cannot be covered by any Python language test because there is # no code pathway to it. But it is part of the C API, so must not be # excised from the code. [ r".*/multiarray/mapping\.", "PyArray_MapIterReset" ], # PyArray_Std trivially forwards to and appears to be superceded by # __New_PyArray_Std, which is exercised by the test framework. [ r".*/multiarray/calculation\.", "PyArray_Std" ], # PyCapsule_Check is declared in a header, and used in # multiarray/ctors.c. So it isn't really untested. [ r".*/multiarray/common\.", "PyCapsule_Check" ], ] Add supressions for array casting functions that don't seem to be callable.suppressions = [ # This one cannot be covered by any Python language test because there is # no code pathway to it. But it is part of the C API, so must not be # excised from the code. [ r".*/multiarray/mapping\.", "PyArray_MapIterReset" ], # PyArray_Std trivially forwards to and appears to be superceded by # __New_PyArray_Std, which is exercised by the test framework. [ r".*/multiarray/calculation\.", "PyArray_Std" ], # PyCapsule_Check is declared in a header, and used in # multiarray/ctors.c. So it isn't really untested. [ r".*/multiarray/common\.", "PyCapsule_Check" ], # It is unclear why these aren't called by the array casting tests in # test_npy_arraytypes.py, when other X_to_X functions are called. [ r".*/libnumpy/npy_arraytypes\.", "DATETIME_to_DATETIME" ], [ r".*/libnumpy/npy_arraytypes\.", "TIMEDELTA_to_TIMEDELTA" ], [ r".*/libnumpy/npy_arraytypes\.", "BOOL_to_BOOL" ], [ r".*/libnumpy/npy_arraytypes\.", "BYTE_to_BYTE" ], [ r".*/libnumpy/npy_arraytypes\.", "UBYTE_to_UBYTE" ], [ r".*/libnumpy/npy_arraytypes\.", "LONGLONG_to_LONGLONG" ], [ r".*/libnumpy/npy_arraytypes\.", "ULONGLONG_to_ULONGLONG" ], ]
<commit_before>suppressions = [ # This one cannot be covered by any Python language test because there is # no code pathway to it. But it is part of the C API, so must not be # excised from the code. [ r".*/multiarray/mapping\.", "PyArray_MapIterReset" ], # PyArray_Std trivially forwards to and appears to be superceded by # __New_PyArray_Std, which is exercised by the test framework. [ r".*/multiarray/calculation\.", "PyArray_Std" ], # PyCapsule_Check is declared in a header, and used in # multiarray/ctors.c. So it isn't really untested. [ r".*/multiarray/common\.", "PyCapsule_Check" ], ] <commit_msg>Add supressions for array casting functions that don't seem to be callable.<commit_after>suppressions = [ # This one cannot be covered by any Python language test because there is # no code pathway to it. But it is part of the C API, so must not be # excised from the code. [ r".*/multiarray/mapping\.", "PyArray_MapIterReset" ], # PyArray_Std trivially forwards to and appears to be superceded by # __New_PyArray_Std, which is exercised by the test framework. [ r".*/multiarray/calculation\.", "PyArray_Std" ], # PyCapsule_Check is declared in a header, and used in # multiarray/ctors.c. So it isn't really untested. [ r".*/multiarray/common\.", "PyCapsule_Check" ], # It is unclear why these aren't called by the array casting tests in # test_npy_arraytypes.py, when other X_to_X functions are called. [ r".*/libnumpy/npy_arraytypes\.", "DATETIME_to_DATETIME" ], [ r".*/libnumpy/npy_arraytypes\.", "TIMEDELTA_to_TIMEDELTA" ], [ r".*/libnumpy/npy_arraytypes\.", "BOOL_to_BOOL" ], [ r".*/libnumpy/npy_arraytypes\.", "BYTE_to_BYTE" ], [ r".*/libnumpy/npy_arraytypes\.", "UBYTE_to_UBYTE" ], [ r".*/libnumpy/npy_arraytypes\.", "LONGLONG_to_LONGLONG" ], [ r".*/libnumpy/npy_arraytypes\.", "ULONGLONG_to_ULONGLONG" ], ]
627c1fb7128a1419e7a1598f4585bef1c216910d
ckanext/nhm/settings.py
ckanext/nhm/settings.py
#!/usr/bin/env python # encoding: utf-8 # # This file is part of ckanext-nhm # Created by the Natural History Museum in London, UK COLLECTION_CONTACTS = { u'Data Portal / Other': u'data@nhm.ac.uk', u'Algae, Fungi & Plants': u'm.carine@nhm.ac.uk', u'Economic & Environmental Earth Sciences': u'g.miller@nhm.ac.uk', u'Fossil Invertebrates & Plants': u'z.hughes@nhm.ac.uk@nhm.ac.uk', u'Fossil Vertebrates & Anthropology': u'm.richter@nhm.ac.uk', u'Insects': u'g.broad@nhm.ac.uk', u'Invertebrates': u'm.lowe@nhm.ac.uk', u'Library & Archives': u'library@nhm.ac.uk', u'Mineral & Planetary Sciences': u'm.rumsey@nhm.ac.uk', u'Vertebrates': u'simon.loader@nhm.ac.uk', }
#!/usr/bin/env python # encoding: utf-8 # # This file is part of ckanext-nhm # Created by the Natural History Museum in London, UK from collections import OrderedDict # the order here matters as the default option should always be first in the dict so that it is # automatically selected in combo boxes that use this list as a source for options COLLECTION_CONTACTS = OrderedDict([ (u'Data Portal / Other', u'data@nhm.ac.uk'), (u'Algae, Fungi & Plants', u'm.carine@nhm.ac.uk'), (u'Economic & Environmental Earth Sciences', u'g.miller@nhm.ac.uk'), (u'Fossil Invertebrates & Plants', u'z.hughes@nhm.ac.uk@nhm.ac.uk'), (u'Fossil Vertebrates & Anthropology', u'm.richter@nhm.ac.uk'), (u'Insects', u'g.broad@nhm.ac.uk'), (u'Invertebrates', u'm.lowe@nhm.ac.uk'), (u'Library & Archives', u'library@nhm.ac.uk'), (u'Mineral & Planetary Sciences', u'm.rumsey@nhm.ac.uk'), (u'Vertebrates', u'simon.loader@nhm.ac.uk'), ])
Use an OrderedDict to ensure the first option is the default option
Use an OrderedDict to ensure the first option is the default option
Python
mit
NaturalHistoryMuseum/ckanext-nhm,NaturalHistoryMuseum/ckanext-nhm,NaturalHistoryMuseum/ckanext-nhm
#!/usr/bin/env python # encoding: utf-8 # # This file is part of ckanext-nhm # Created by the Natural History Museum in London, UK COLLECTION_CONTACTS = { u'Data Portal / Other': u'data@nhm.ac.uk', u'Algae, Fungi & Plants': u'm.carine@nhm.ac.uk', u'Economic & Environmental Earth Sciences': u'g.miller@nhm.ac.uk', u'Fossil Invertebrates & Plants': u'z.hughes@nhm.ac.uk@nhm.ac.uk', u'Fossil Vertebrates & Anthropology': u'm.richter@nhm.ac.uk', u'Insects': u'g.broad@nhm.ac.uk', u'Invertebrates': u'm.lowe@nhm.ac.uk', u'Library & Archives': u'library@nhm.ac.uk', u'Mineral & Planetary Sciences': u'm.rumsey@nhm.ac.uk', u'Vertebrates': u'simon.loader@nhm.ac.uk', } Use an OrderedDict to ensure the first option is the default option
#!/usr/bin/env python # encoding: utf-8 # # This file is part of ckanext-nhm # Created by the Natural History Museum in London, UK from collections import OrderedDict # the order here matters as the default option should always be first in the dict so that it is # automatically selected in combo boxes that use this list as a source for options COLLECTION_CONTACTS = OrderedDict([ (u'Data Portal / Other', u'data@nhm.ac.uk'), (u'Algae, Fungi & Plants', u'm.carine@nhm.ac.uk'), (u'Economic & Environmental Earth Sciences', u'g.miller@nhm.ac.uk'), (u'Fossil Invertebrates & Plants', u'z.hughes@nhm.ac.uk@nhm.ac.uk'), (u'Fossil Vertebrates & Anthropology', u'm.richter@nhm.ac.uk'), (u'Insects', u'g.broad@nhm.ac.uk'), (u'Invertebrates', u'm.lowe@nhm.ac.uk'), (u'Library & Archives', u'library@nhm.ac.uk'), (u'Mineral & Planetary Sciences', u'm.rumsey@nhm.ac.uk'), (u'Vertebrates', u'simon.loader@nhm.ac.uk'), ])
<commit_before>#!/usr/bin/env python # encoding: utf-8 # # This file is part of ckanext-nhm # Created by the Natural History Museum in London, UK COLLECTION_CONTACTS = { u'Data Portal / Other': u'data@nhm.ac.uk', u'Algae, Fungi & Plants': u'm.carine@nhm.ac.uk', u'Economic & Environmental Earth Sciences': u'g.miller@nhm.ac.uk', u'Fossil Invertebrates & Plants': u'z.hughes@nhm.ac.uk@nhm.ac.uk', u'Fossil Vertebrates & Anthropology': u'm.richter@nhm.ac.uk', u'Insects': u'g.broad@nhm.ac.uk', u'Invertebrates': u'm.lowe@nhm.ac.uk', u'Library & Archives': u'library@nhm.ac.uk', u'Mineral & Planetary Sciences': u'm.rumsey@nhm.ac.uk', u'Vertebrates': u'simon.loader@nhm.ac.uk', } <commit_msg>Use an OrderedDict to ensure the first option is the default option<commit_after>
#!/usr/bin/env python # encoding: utf-8 # # This file is part of ckanext-nhm # Created by the Natural History Museum in London, UK from collections import OrderedDict # the order here matters as the default option should always be first in the dict so that it is # automatically selected in combo boxes that use this list as a source for options COLLECTION_CONTACTS = OrderedDict([ (u'Data Portal / Other', u'data@nhm.ac.uk'), (u'Algae, Fungi & Plants', u'm.carine@nhm.ac.uk'), (u'Economic & Environmental Earth Sciences', u'g.miller@nhm.ac.uk'), (u'Fossil Invertebrates & Plants', u'z.hughes@nhm.ac.uk@nhm.ac.uk'), (u'Fossil Vertebrates & Anthropology', u'm.richter@nhm.ac.uk'), (u'Insects', u'g.broad@nhm.ac.uk'), (u'Invertebrates', u'm.lowe@nhm.ac.uk'), (u'Library & Archives', u'library@nhm.ac.uk'), (u'Mineral & Planetary Sciences', u'm.rumsey@nhm.ac.uk'), (u'Vertebrates', u'simon.loader@nhm.ac.uk'), ])
#!/usr/bin/env python # encoding: utf-8 # # This file is part of ckanext-nhm # Created by the Natural History Museum in London, UK COLLECTION_CONTACTS = { u'Data Portal / Other': u'data@nhm.ac.uk', u'Algae, Fungi & Plants': u'm.carine@nhm.ac.uk', u'Economic & Environmental Earth Sciences': u'g.miller@nhm.ac.uk', u'Fossil Invertebrates & Plants': u'z.hughes@nhm.ac.uk@nhm.ac.uk', u'Fossil Vertebrates & Anthropology': u'm.richter@nhm.ac.uk', u'Insects': u'g.broad@nhm.ac.uk', u'Invertebrates': u'm.lowe@nhm.ac.uk', u'Library & Archives': u'library@nhm.ac.uk', u'Mineral & Planetary Sciences': u'm.rumsey@nhm.ac.uk', u'Vertebrates': u'simon.loader@nhm.ac.uk', } Use an OrderedDict to ensure the first option is the default option#!/usr/bin/env python # encoding: utf-8 # # This file is part of ckanext-nhm # Created by the Natural History Museum in London, UK from collections import OrderedDict # the order here matters as the default option should always be first in the dict so that it is # automatically selected in combo boxes that use this list as a source for options COLLECTION_CONTACTS = OrderedDict([ (u'Data Portal / Other', u'data@nhm.ac.uk'), (u'Algae, Fungi & Plants', u'm.carine@nhm.ac.uk'), (u'Economic & Environmental Earth Sciences', u'g.miller@nhm.ac.uk'), (u'Fossil Invertebrates & Plants', u'z.hughes@nhm.ac.uk@nhm.ac.uk'), (u'Fossil Vertebrates & Anthropology', u'm.richter@nhm.ac.uk'), (u'Insects', u'g.broad@nhm.ac.uk'), (u'Invertebrates', u'm.lowe@nhm.ac.uk'), (u'Library & Archives', u'library@nhm.ac.uk'), (u'Mineral & Planetary Sciences', u'm.rumsey@nhm.ac.uk'), (u'Vertebrates', u'simon.loader@nhm.ac.uk'), ])
<commit_before>#!/usr/bin/env python # encoding: utf-8 # # This file is part of ckanext-nhm # Created by the Natural History Museum in London, UK COLLECTION_CONTACTS = { u'Data Portal / Other': u'data@nhm.ac.uk', u'Algae, Fungi & Plants': u'm.carine@nhm.ac.uk', u'Economic & Environmental Earth Sciences': u'g.miller@nhm.ac.uk', u'Fossil Invertebrates & Plants': u'z.hughes@nhm.ac.uk@nhm.ac.uk', u'Fossil Vertebrates & Anthropology': u'm.richter@nhm.ac.uk', u'Insects': u'g.broad@nhm.ac.uk', u'Invertebrates': u'm.lowe@nhm.ac.uk', u'Library & Archives': u'library@nhm.ac.uk', u'Mineral & Planetary Sciences': u'm.rumsey@nhm.ac.uk', u'Vertebrates': u'simon.loader@nhm.ac.uk', } <commit_msg>Use an OrderedDict to ensure the first option is the default option<commit_after>#!/usr/bin/env python # encoding: utf-8 # # This file is part of ckanext-nhm # Created by the Natural History Museum in London, UK from collections import OrderedDict # the order here matters as the default option should always be first in the dict so that it is # automatically selected in combo boxes that use this list as a source for options COLLECTION_CONTACTS = OrderedDict([ (u'Data Portal / Other', u'data@nhm.ac.uk'), (u'Algae, Fungi & Plants', u'm.carine@nhm.ac.uk'), (u'Economic & Environmental Earth Sciences', u'g.miller@nhm.ac.uk'), (u'Fossil Invertebrates & Plants', u'z.hughes@nhm.ac.uk@nhm.ac.uk'), (u'Fossil Vertebrates & Anthropology', u'm.richter@nhm.ac.uk'), (u'Insects', u'g.broad@nhm.ac.uk'), (u'Invertebrates', u'm.lowe@nhm.ac.uk'), (u'Library & Archives', u'library@nhm.ac.uk'), (u'Mineral & Planetary Sciences', u'm.rumsey@nhm.ac.uk'), (u'Vertebrates', u'simon.loader@nhm.ac.uk'), ])
6c1af25e427ddc9d5bcbdca017d39813c34030bd
bandnames/bandnames/settings/local.py
bandnames/bandnames/settings/local.py
from __future__ import absolute_import from os.path import join, normpath from .base import * DEBUG = True TEMPLATE_DEBUG = DEBUG EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': normpath(join(DJANGO_ROOT, 'bandnames.db')), 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', } } INSTALLED_APPS += ( 'debug_toolbar', ) MIDDLEWARE_CLASSES += ( 'debug_toolbar.middleware.DebugToolbarMiddleware', ) DEBUG_TOOLBAR_PATCH_SETTINGS = False INTERNAL_IPS = ('127.0.0.1',)
from __future__ import absolute_import from os.path import join, normpath from .base import * DEBUG = True TEMPLATE_DEBUG = DEBUG EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': normpath(join(DJANGO_ROOT, 'bandnames.db')), 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', } } INSTALLED_APPS += ( # 'debug_toolbar', ) MIDDLEWARE_CLASSES += ( # 'debug_toolbar.middleware.DebugToolbarMiddleware', ) DEBUG_TOOLBAR_PATCH_SETTINGS = False INTERNAL_IPS = ('127.0.0.1',)
Remove debug toolbar due to 'TypeError: process() takes exactly 3 arguments (2 given)'
Remove debug toolbar due to 'TypeError: process() takes exactly 3 arguments (2 given)'
Python
mit
pyepye/bandnames,pyepye/bandnames
from __future__ import absolute_import from os.path import join, normpath from .base import * DEBUG = True TEMPLATE_DEBUG = DEBUG EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': normpath(join(DJANGO_ROOT, 'bandnames.db')), 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', } } INSTALLED_APPS += ( 'debug_toolbar', ) MIDDLEWARE_CLASSES += ( 'debug_toolbar.middleware.DebugToolbarMiddleware', ) DEBUG_TOOLBAR_PATCH_SETTINGS = False INTERNAL_IPS = ('127.0.0.1',) Remove debug toolbar due to 'TypeError: process() takes exactly 3 arguments (2 given)'
from __future__ import absolute_import from os.path import join, normpath from .base import * DEBUG = True TEMPLATE_DEBUG = DEBUG EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': normpath(join(DJANGO_ROOT, 'bandnames.db')), 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', } } INSTALLED_APPS += ( # 'debug_toolbar', ) MIDDLEWARE_CLASSES += ( # 'debug_toolbar.middleware.DebugToolbarMiddleware', ) DEBUG_TOOLBAR_PATCH_SETTINGS = False INTERNAL_IPS = ('127.0.0.1',)
<commit_before>from __future__ import absolute_import from os.path import join, normpath from .base import * DEBUG = True TEMPLATE_DEBUG = DEBUG EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': normpath(join(DJANGO_ROOT, 'bandnames.db')), 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', } } INSTALLED_APPS += ( 'debug_toolbar', ) MIDDLEWARE_CLASSES += ( 'debug_toolbar.middleware.DebugToolbarMiddleware', ) DEBUG_TOOLBAR_PATCH_SETTINGS = False INTERNAL_IPS = ('127.0.0.1',) <commit_msg>Remove debug toolbar due to 'TypeError: process() takes exactly 3 arguments (2 given)'<commit_after>
from __future__ import absolute_import from os.path import join, normpath from .base import * DEBUG = True TEMPLATE_DEBUG = DEBUG EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': normpath(join(DJANGO_ROOT, 'bandnames.db')), 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', } } INSTALLED_APPS += ( # 'debug_toolbar', ) MIDDLEWARE_CLASSES += ( # 'debug_toolbar.middleware.DebugToolbarMiddleware', ) DEBUG_TOOLBAR_PATCH_SETTINGS = False INTERNAL_IPS = ('127.0.0.1',)
from __future__ import absolute_import from os.path import join, normpath from .base import * DEBUG = True TEMPLATE_DEBUG = DEBUG EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': normpath(join(DJANGO_ROOT, 'bandnames.db')), 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', } } INSTALLED_APPS += ( 'debug_toolbar', ) MIDDLEWARE_CLASSES += ( 'debug_toolbar.middleware.DebugToolbarMiddleware', ) DEBUG_TOOLBAR_PATCH_SETTINGS = False INTERNAL_IPS = ('127.0.0.1',) Remove debug toolbar due to 'TypeError: process() takes exactly 3 arguments (2 given)'from __future__ import absolute_import from os.path import join, normpath from .base import * DEBUG = True TEMPLATE_DEBUG = DEBUG EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': normpath(join(DJANGO_ROOT, 'bandnames.db')), 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', } } INSTALLED_APPS += ( # 'debug_toolbar', ) MIDDLEWARE_CLASSES += ( # 'debug_toolbar.middleware.DebugToolbarMiddleware', ) DEBUG_TOOLBAR_PATCH_SETTINGS = False INTERNAL_IPS = ('127.0.0.1',)
<commit_before>from __future__ import absolute_import from os.path import join, normpath from .base import * DEBUG = True TEMPLATE_DEBUG = DEBUG EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': normpath(join(DJANGO_ROOT, 'bandnames.db')), 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', } } INSTALLED_APPS += ( 'debug_toolbar', ) MIDDLEWARE_CLASSES += ( 'debug_toolbar.middleware.DebugToolbarMiddleware', ) DEBUG_TOOLBAR_PATCH_SETTINGS = False INTERNAL_IPS = ('127.0.0.1',) <commit_msg>Remove debug toolbar due to 'TypeError: process() takes exactly 3 arguments (2 given)'<commit_after>from __future__ import absolute_import from os.path import join, normpath from .base import * DEBUG = True TEMPLATE_DEBUG = DEBUG EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': normpath(join(DJANGO_ROOT, 'bandnames.db')), 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', } } INSTALLED_APPS += ( # 'debug_toolbar', ) MIDDLEWARE_CLASSES += ( # 'debug_toolbar.middleware.DebugToolbarMiddleware', ) DEBUG_TOOLBAR_PATCH_SETTINGS = False INTERNAL_IPS = ('127.0.0.1',)
5b1d13f29984997181b953f36d637b6e187ec220
blankspot/node_registration/models.py
blankspot/node_registration/models.py
from django.db import models class Position(models.Model): first_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50, blank=True, null=True) nick = models.CharField(max_length=128) email = models.EmailField(max_length=254) street = models.CharField(max_length=200, blank=True, null=True) city = models.CharField(max_length=100, blank=True, null=True) address_description = models.TextField(blank=True, null=True) altitude = models.FloatField(blank=True, null=True) latitude = models.FloatField(blank=True, null=True) def __unicode__(self): return (self.street) def get_absolute_url(self): return reverse('position-detail', kwargs={'pk': self.pk})
from django.db import models class Position(models.Model): first_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50, blank=True, null=True) nick = models.CharField(max_length=128) email = models.EmailField(max_length=254) street = models.CharField(max_length=200, blank=True, null=True) city = models.CharField(max_length=100, blank=True, null=True) address_description = models.TextField(blank=True, null=True) longitude = models.FloatField(blank=True, null=True) latitude = models.FloatField(blank=True, null=True) def __unicode__(self): return (self.street) def get_absolute_url(self): return reverse('position-detail', kwargs={'pk': self.pk})
Rename column altitude to longitude ...
Rename column altitude to longitude ...
Python
agpl-3.0
frlan/blankspot
from django.db import models class Position(models.Model): first_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50, blank=True, null=True) nick = models.CharField(max_length=128) email = models.EmailField(max_length=254) street = models.CharField(max_length=200, blank=True, null=True) city = models.CharField(max_length=100, blank=True, null=True) address_description = models.TextField(blank=True, null=True) altitude = models.FloatField(blank=True, null=True) latitude = models.FloatField(blank=True, null=True) def __unicode__(self): return (self.street) def get_absolute_url(self): return reverse('position-detail', kwargs={'pk': self.pk}) Rename column altitude to longitude ...
from django.db import models class Position(models.Model): first_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50, blank=True, null=True) nick = models.CharField(max_length=128) email = models.EmailField(max_length=254) street = models.CharField(max_length=200, blank=True, null=True) city = models.CharField(max_length=100, blank=True, null=True) address_description = models.TextField(blank=True, null=True) longitude = models.FloatField(blank=True, null=True) latitude = models.FloatField(blank=True, null=True) def __unicode__(self): return (self.street) def get_absolute_url(self): return reverse('position-detail', kwargs={'pk': self.pk})
<commit_before>from django.db import models class Position(models.Model): first_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50, blank=True, null=True) nick = models.CharField(max_length=128) email = models.EmailField(max_length=254) street = models.CharField(max_length=200, blank=True, null=True) city = models.CharField(max_length=100, blank=True, null=True) address_description = models.TextField(blank=True, null=True) altitude = models.FloatField(blank=True, null=True) latitude = models.FloatField(blank=True, null=True) def __unicode__(self): return (self.street) def get_absolute_url(self): return reverse('position-detail', kwargs={'pk': self.pk}) <commit_msg>Rename column altitude to longitude ...<commit_after>
from django.db import models class Position(models.Model): first_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50, blank=True, null=True) nick = models.CharField(max_length=128) email = models.EmailField(max_length=254) street = models.CharField(max_length=200, blank=True, null=True) city = models.CharField(max_length=100, blank=True, null=True) address_description = models.TextField(blank=True, null=True) longitude = models.FloatField(blank=True, null=True) latitude = models.FloatField(blank=True, null=True) def __unicode__(self): return (self.street) def get_absolute_url(self): return reverse('position-detail', kwargs={'pk': self.pk})
from django.db import models class Position(models.Model): first_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50, blank=True, null=True) nick = models.CharField(max_length=128) email = models.EmailField(max_length=254) street = models.CharField(max_length=200, blank=True, null=True) city = models.CharField(max_length=100, blank=True, null=True) address_description = models.TextField(blank=True, null=True) altitude = models.FloatField(blank=True, null=True) latitude = models.FloatField(blank=True, null=True) def __unicode__(self): return (self.street) def get_absolute_url(self): return reverse('position-detail', kwargs={'pk': self.pk}) Rename column altitude to longitude ...from django.db import models class Position(models.Model): first_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50, blank=True, null=True) nick = models.CharField(max_length=128) email = models.EmailField(max_length=254) street = models.CharField(max_length=200, blank=True, null=True) city = models.CharField(max_length=100, blank=True, null=True) address_description = models.TextField(blank=True, null=True) longitude = models.FloatField(blank=True, null=True) latitude = models.FloatField(blank=True, null=True) def __unicode__(self): return (self.street) def get_absolute_url(self): return reverse('position-detail', kwargs={'pk': self.pk})
<commit_before>from django.db import models class Position(models.Model): first_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50, blank=True, null=True) nick = models.CharField(max_length=128) email = models.EmailField(max_length=254) street = models.CharField(max_length=200, blank=True, null=True) city = models.CharField(max_length=100, blank=True, null=True) address_description = models.TextField(blank=True, null=True) altitude = models.FloatField(blank=True, null=True) latitude = models.FloatField(blank=True, null=True) def __unicode__(self): return (self.street) def get_absolute_url(self): return reverse('position-detail', kwargs={'pk': self.pk}) <commit_msg>Rename column altitude to longitude ...<commit_after>from django.db import models class Position(models.Model): first_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50, blank=True, null=True) nick = models.CharField(max_length=128) email = models.EmailField(max_length=254) street = models.CharField(max_length=200, blank=True, null=True) city = models.CharField(max_length=100, blank=True, null=True) address_description = models.TextField(blank=True, null=True) longitude = models.FloatField(blank=True, null=True) latitude = models.FloatField(blank=True, null=True) def __unicode__(self): return (self.street) def get_absolute_url(self): return reverse('position-detail', kwargs={'pk': self.pk})
bcaee4414402017985f8a25134a5cecc99a1c8bb
docker/build_scripts/ssl-check.py
docker/build_scripts/ssl-check.py
# cf. https://github.com/pypa/manylinux/issues/53 GOOD_SSL = "https://google.com" BAD_SSL = "https://self-signed.badssl.com" import sys print("Testing SSL certificate checking for Python:", sys.version) if (sys.version_info[:2] < (2, 7) or sys.version_info[:2] < (3, 4)): print("This version never checks SSL certs; skipping tests") sys.exit(0) if sys.version_info[0] >= 3: from urllib.request import urlopen EXC = OSError else: from urllib import urlopen EXC = IOError print("Connecting to %s should work" % (GOOD_SSL,)) urlopen(GOOD_SSL) print("...it did, yay.") print("Connecting to %s should fail" % (BAD_SSL,)) try: urlopen(BAD_SSL) # If we get here then we failed: print("...it DIDN'T!!!!!11!!1one!") sys.exit(1) except EXC: print("...it did, yay.")
# cf. https://github.com/pypa/manylinux/issues/53 GOOD_SSL = "https://google.com" BAD_SSL = "https://self-signed.badssl.com" import sys print("Testing SSL certificate checking for Python:", sys.version) if (sys.version_info[:2] < (3, 4)): print("This version never checks SSL certs; skipping tests") sys.exit(0) if sys.version_info[0] >= 3: from urllib.request import urlopen EXC = OSError else: from urllib import urlopen EXC = IOError print("Connecting to %s should work" % (GOOD_SSL,)) urlopen(GOOD_SSL) print("...it did, yay.") print("Connecting to %s should fail" % (BAD_SSL,)) try: urlopen(BAD_SSL) # If we get here then we failed: print("...it DIDN'T!!!!!11!!1one!") sys.exit(1) except EXC: print("...it did, yay.")
Remove leftover relic from supporting CPython 2.6.
Remove leftover relic from supporting CPython 2.6.
Python
mit
pypa/manylinux,manylinux/manylinux,pypa/manylinux,pypa/manylinux,manylinux/manylinux,Parsely/manylinux,Parsely/manylinux
# cf. https://github.com/pypa/manylinux/issues/53 GOOD_SSL = "https://google.com" BAD_SSL = "https://self-signed.badssl.com" import sys print("Testing SSL certificate checking for Python:", sys.version) if (sys.version_info[:2] < (2, 7) or sys.version_info[:2] < (3, 4)): print("This version never checks SSL certs; skipping tests") sys.exit(0) if sys.version_info[0] >= 3: from urllib.request import urlopen EXC = OSError else: from urllib import urlopen EXC = IOError print("Connecting to %s should work" % (GOOD_SSL,)) urlopen(GOOD_SSL) print("...it did, yay.") print("Connecting to %s should fail" % (BAD_SSL,)) try: urlopen(BAD_SSL) # If we get here then we failed: print("...it DIDN'T!!!!!11!!1one!") sys.exit(1) except EXC: print("...it did, yay.")Remove leftover relic from supporting CPython 2.6.
# cf. https://github.com/pypa/manylinux/issues/53 GOOD_SSL = "https://google.com" BAD_SSL = "https://self-signed.badssl.com" import sys print("Testing SSL certificate checking for Python:", sys.version) if (sys.version_info[:2] < (3, 4)): print("This version never checks SSL certs; skipping tests") sys.exit(0) if sys.version_info[0] >= 3: from urllib.request import urlopen EXC = OSError else: from urllib import urlopen EXC = IOError print("Connecting to %s should work" % (GOOD_SSL,)) urlopen(GOOD_SSL) print("...it did, yay.") print("Connecting to %s should fail" % (BAD_SSL,)) try: urlopen(BAD_SSL) # If we get here then we failed: print("...it DIDN'T!!!!!11!!1one!") sys.exit(1) except EXC: print("...it did, yay.")
<commit_before># cf. https://github.com/pypa/manylinux/issues/53 GOOD_SSL = "https://google.com" BAD_SSL = "https://self-signed.badssl.com" import sys print("Testing SSL certificate checking for Python:", sys.version) if (sys.version_info[:2] < (2, 7) or sys.version_info[:2] < (3, 4)): print("This version never checks SSL certs; skipping tests") sys.exit(0) if sys.version_info[0] >= 3: from urllib.request import urlopen EXC = OSError else: from urllib import urlopen EXC = IOError print("Connecting to %s should work" % (GOOD_SSL,)) urlopen(GOOD_SSL) print("...it did, yay.") print("Connecting to %s should fail" % (BAD_SSL,)) try: urlopen(BAD_SSL) # If we get here then we failed: print("...it DIDN'T!!!!!11!!1one!") sys.exit(1) except EXC: print("...it did, yay.")<commit_msg>Remove leftover relic from supporting CPython 2.6.<commit_after>
# cf. https://github.com/pypa/manylinux/issues/53 GOOD_SSL = "https://google.com" BAD_SSL = "https://self-signed.badssl.com" import sys print("Testing SSL certificate checking for Python:", sys.version) if (sys.version_info[:2] < (3, 4)): print("This version never checks SSL certs; skipping tests") sys.exit(0) if sys.version_info[0] >= 3: from urllib.request import urlopen EXC = OSError else: from urllib import urlopen EXC = IOError print("Connecting to %s should work" % (GOOD_SSL,)) urlopen(GOOD_SSL) print("...it did, yay.") print("Connecting to %s should fail" % (BAD_SSL,)) try: urlopen(BAD_SSL) # If we get here then we failed: print("...it DIDN'T!!!!!11!!1one!") sys.exit(1) except EXC: print("...it did, yay.")
# cf. https://github.com/pypa/manylinux/issues/53 GOOD_SSL = "https://google.com" BAD_SSL = "https://self-signed.badssl.com" import sys print("Testing SSL certificate checking for Python:", sys.version) if (sys.version_info[:2] < (2, 7) or sys.version_info[:2] < (3, 4)): print("This version never checks SSL certs; skipping tests") sys.exit(0) if sys.version_info[0] >= 3: from urllib.request import urlopen EXC = OSError else: from urllib import urlopen EXC = IOError print("Connecting to %s should work" % (GOOD_SSL,)) urlopen(GOOD_SSL) print("...it did, yay.") print("Connecting to %s should fail" % (BAD_SSL,)) try: urlopen(BAD_SSL) # If we get here then we failed: print("...it DIDN'T!!!!!11!!1one!") sys.exit(1) except EXC: print("...it did, yay.")Remove leftover relic from supporting CPython 2.6.# cf. https://github.com/pypa/manylinux/issues/53 GOOD_SSL = "https://google.com" BAD_SSL = "https://self-signed.badssl.com" import sys print("Testing SSL certificate checking for Python:", sys.version) if (sys.version_info[:2] < (3, 4)): print("This version never checks SSL certs; skipping tests") sys.exit(0) if sys.version_info[0] >= 3: from urllib.request import urlopen EXC = OSError else: from urllib import urlopen EXC = IOError print("Connecting to %s should work" % (GOOD_SSL,)) urlopen(GOOD_SSL) print("...it did, yay.") print("Connecting to %s should fail" % (BAD_SSL,)) try: urlopen(BAD_SSL) # If we get here then we failed: print("...it DIDN'T!!!!!11!!1one!") sys.exit(1) except EXC: print("...it did, yay.")
<commit_before># cf. https://github.com/pypa/manylinux/issues/53 GOOD_SSL = "https://google.com" BAD_SSL = "https://self-signed.badssl.com" import sys print("Testing SSL certificate checking for Python:", sys.version) if (sys.version_info[:2] < (2, 7) or sys.version_info[:2] < (3, 4)): print("This version never checks SSL certs; skipping tests") sys.exit(0) if sys.version_info[0] >= 3: from urllib.request import urlopen EXC = OSError else: from urllib import urlopen EXC = IOError print("Connecting to %s should work" % (GOOD_SSL,)) urlopen(GOOD_SSL) print("...it did, yay.") print("Connecting to %s should fail" % (BAD_SSL,)) try: urlopen(BAD_SSL) # If we get here then we failed: print("...it DIDN'T!!!!!11!!1one!") sys.exit(1) except EXC: print("...it did, yay.")<commit_msg>Remove leftover relic from supporting CPython 2.6.<commit_after># cf. https://github.com/pypa/manylinux/issues/53 GOOD_SSL = "https://google.com" BAD_SSL = "https://self-signed.badssl.com" import sys print("Testing SSL certificate checking for Python:", sys.version) if (sys.version_info[:2] < (3, 4)): print("This version never checks SSL certs; skipping tests") sys.exit(0) if sys.version_info[0] >= 3: from urllib.request import urlopen EXC = OSError else: from urllib import urlopen EXC = IOError print("Connecting to %s should work" % (GOOD_SSL,)) urlopen(GOOD_SSL) print("...it did, yay.") print("Connecting to %s should fail" % (BAD_SSL,)) try: urlopen(BAD_SSL) # If we get here then we failed: print("...it DIDN'T!!!!!11!!1one!") sys.exit(1) except EXC: print("...it did, yay.")
e79b92888fa9dfc57a274f3377cf425776ccb468
food.py
food.py
# Food Class class Food: def __init__(self, x, y): self.location = (x, y) self.eaten = False def getX(self): return self.location[0] def getY(self): return self.location[1] def setX(self, newX): self.location[0] = newX def setY(self, newY): self.location[1] = newY def isEaten(self): return eaten def setEaten(self, isItEaten): self.eaten = isItEaten
# Food Class class Food: def __init__(self, x, y): self.location = (x, y) self.eaten = False def getX(self): return self.location[0] def getY(self): return self.location[1] def setX(self, newX): self.location[0] = newX def setY(self, newY): self.location[1] = newY def isEaten(self): return self.eaten def setEaten(self, isItEaten): self.eaten = isItEaten
Add self before eaten on isEaten for Food
Add self before eaten on isEaten for Food
Python
mit
MEhlinger/rpi_pushbutton_games
# Food Class class Food: def __init__(self, x, y): self.location = (x, y) self.eaten = False def getX(self): return self.location[0] def getY(self): return self.location[1] def setX(self, newX): self.location[0] = newX def setY(self, newY): self.location[1] = newY def isEaten(self): return eaten def setEaten(self, isItEaten): self.eaten = isItEatenAdd self before eaten on isEaten for Food
# Food Class class Food: def __init__(self, x, y): self.location = (x, y) self.eaten = False def getX(self): return self.location[0] def getY(self): return self.location[1] def setX(self, newX): self.location[0] = newX def setY(self, newY): self.location[1] = newY def isEaten(self): return self.eaten def setEaten(self, isItEaten): self.eaten = isItEaten
<commit_before># Food Class class Food: def __init__(self, x, y): self.location = (x, y) self.eaten = False def getX(self): return self.location[0] def getY(self): return self.location[1] def setX(self, newX): self.location[0] = newX def setY(self, newY): self.location[1] = newY def isEaten(self): return eaten def setEaten(self, isItEaten): self.eaten = isItEaten<commit_msg>Add self before eaten on isEaten for Food<commit_after>
# Food Class class Food: def __init__(self, x, y): self.location = (x, y) self.eaten = False def getX(self): return self.location[0] def getY(self): return self.location[1] def setX(self, newX): self.location[0] = newX def setY(self, newY): self.location[1] = newY def isEaten(self): return self.eaten def setEaten(self, isItEaten): self.eaten = isItEaten
# Food Class class Food: def __init__(self, x, y): self.location = (x, y) self.eaten = False def getX(self): return self.location[0] def getY(self): return self.location[1] def setX(self, newX): self.location[0] = newX def setY(self, newY): self.location[1] = newY def isEaten(self): return eaten def setEaten(self, isItEaten): self.eaten = isItEatenAdd self before eaten on isEaten for Food# Food Class class Food: def __init__(self, x, y): self.location = (x, y) self.eaten = False def getX(self): return self.location[0] def getY(self): return self.location[1] def setX(self, newX): self.location[0] = newX def setY(self, newY): self.location[1] = newY def isEaten(self): return self.eaten def setEaten(self, isItEaten): self.eaten = isItEaten
<commit_before># Food Class class Food: def __init__(self, x, y): self.location = (x, y) self.eaten = False def getX(self): return self.location[0] def getY(self): return self.location[1] def setX(self, newX): self.location[0] = newX def setY(self, newY): self.location[1] = newY def isEaten(self): return eaten def setEaten(self, isItEaten): self.eaten = isItEaten<commit_msg>Add self before eaten on isEaten for Food<commit_after># Food Class class Food: def __init__(self, x, y): self.location = (x, y) self.eaten = False def getX(self): return self.location[0] def getY(self): return self.location[1] def setX(self, newX): self.location[0] = newX def setY(self, newY): self.location[1] = newY def isEaten(self): return self.eaten def setEaten(self, isItEaten): self.eaten = isItEaten
3912afaf9e069ae914c535af21155d10da930494
tests/unit/utils/test_translations.py
tests/unit/utils/test_translations.py
import subprocess import os from flask import current_app from babel.support import Translations, NullTranslations from flaskbb.utils.translations import FlaskBBDomain from flaskbb.extensions import plugin_manager def _compile_translations(): PLUGINS_FOLDER = os.path.join(current_app.root_path, "plugins") translations_folder = os.path.join(current_app.root_path, "translations") subprocess.call(["pybabel", "compile", "-d", translations_folder]) for plugin in plugin_manager.all_plugins: plugin_folder = os.path.join(PLUGINS_FOLDER, plugin) translations_folder = os.path.join(plugin_folder, "translations") subprocess.call(["pybabel", "compile", "-d", translations_folder]) def test_flaskbbdomain_translations(default_settings): domain = FlaskBBDomain(current_app) with current_app.test_request_context(): assert domain.get_translations_cache() == {} # no compiled translations are available assert isinstance(domain.get_translations(), NullTranslations) # lets compile them and test again _compile_translations() # now there should be translations :) assert isinstance(domain.get_translations(), Translations)
import subprocess import os from flask import current_app from babel.support import Translations, NullTranslations from flaskbb.utils.translations import FlaskBBDomain from flaskbb.extensions import plugin_manager def _remove_compiled_translations(): translations_folder = os.path.join(current_app.root_path, "translations") # walks through the translations folder and deletes all files # ending with .mo for root, dirs, files in os.walk(translations_folder): for name in files: if name.endswith(".mo"): os.unlink(os.path.join(root, name)) def _compile_translations(): PLUGINS_FOLDER = os.path.join(current_app.root_path, "plugins") translations_folder = os.path.join(current_app.root_path, "translations") subprocess.call(["pybabel", "compile", "-d", translations_folder]) for plugin in plugin_manager.all_plugins: plugin_folder = os.path.join(PLUGINS_FOLDER, plugin) translations_folder = os.path.join(plugin_folder, "translations") subprocess.call(["pybabel", "compile", "-d", translations_folder]) def test_flaskbbdomain_translations(default_settings): domain = FlaskBBDomain(current_app) with current_app.test_request_context(): assert domain.get_translations_cache() == {} # just to be on the safe side that there are really no compiled # translations available _remove_compiled_translations() # no compiled translations are available assert isinstance(domain.get_translations(), NullTranslations) # lets compile them and test again _compile_translations() # now there should be translations :) assert isinstance(domain.get_translations(), Translations)
Remove the compiled translations for testing
Remove the compiled translations for testing
Python
bsd-3-clause
zky001/flaskbb,realityone/flaskbb,dromanow/flaskbb,qitianchan/flaskbb,realityone/flaskbb,SeanChen0617/flaskbb,SeanChen0617/flaskbb-1,SeanChen0617/flaskbb,zky001/flaskbb,emile2016/flaskbb,China-jp/flaskbb,dromanow/flaskbb,lucius-feng/flaskbb,dromanow/flaskbb,SeanChen0617/flaskbb-1,qitianchan/flaskbb,emile2016/flaskbb,realityone/flaskbb,zky001/flaskbb,SeanChen0617/flaskbb-1,SeanChen0617/flaskbb,China-jp/flaskbb,China-jp/flaskbb,lucius-feng/flaskbb,lucius-feng/flaskbb,emile2016/flaskbb,qitianchan/flaskbb
import subprocess import os from flask import current_app from babel.support import Translations, NullTranslations from flaskbb.utils.translations import FlaskBBDomain from flaskbb.extensions import plugin_manager def _compile_translations(): PLUGINS_FOLDER = os.path.join(current_app.root_path, "plugins") translations_folder = os.path.join(current_app.root_path, "translations") subprocess.call(["pybabel", "compile", "-d", translations_folder]) for plugin in plugin_manager.all_plugins: plugin_folder = os.path.join(PLUGINS_FOLDER, plugin) translations_folder = os.path.join(plugin_folder, "translations") subprocess.call(["pybabel", "compile", "-d", translations_folder]) def test_flaskbbdomain_translations(default_settings): domain = FlaskBBDomain(current_app) with current_app.test_request_context(): assert domain.get_translations_cache() == {} # no compiled translations are available assert isinstance(domain.get_translations(), NullTranslations) # lets compile them and test again _compile_translations() # now there should be translations :) assert isinstance(domain.get_translations(), Translations) Remove the compiled translations for testing
import subprocess import os from flask import current_app from babel.support import Translations, NullTranslations from flaskbb.utils.translations import FlaskBBDomain from flaskbb.extensions import plugin_manager def _remove_compiled_translations(): translations_folder = os.path.join(current_app.root_path, "translations") # walks through the translations folder and deletes all files # ending with .mo for root, dirs, files in os.walk(translations_folder): for name in files: if name.endswith(".mo"): os.unlink(os.path.join(root, name)) def _compile_translations(): PLUGINS_FOLDER = os.path.join(current_app.root_path, "plugins") translations_folder = os.path.join(current_app.root_path, "translations") subprocess.call(["pybabel", "compile", "-d", translations_folder]) for plugin in plugin_manager.all_plugins: plugin_folder = os.path.join(PLUGINS_FOLDER, plugin) translations_folder = os.path.join(plugin_folder, "translations") subprocess.call(["pybabel", "compile", "-d", translations_folder]) def test_flaskbbdomain_translations(default_settings): domain = FlaskBBDomain(current_app) with current_app.test_request_context(): assert domain.get_translations_cache() == {} # just to be on the safe side that there are really no compiled # translations available _remove_compiled_translations() # no compiled translations are available assert isinstance(domain.get_translations(), NullTranslations) # lets compile them and test again _compile_translations() # now there should be translations :) assert isinstance(domain.get_translations(), Translations)
<commit_before>import subprocess import os from flask import current_app from babel.support import Translations, NullTranslations from flaskbb.utils.translations import FlaskBBDomain from flaskbb.extensions import plugin_manager def _compile_translations(): PLUGINS_FOLDER = os.path.join(current_app.root_path, "plugins") translations_folder = os.path.join(current_app.root_path, "translations") subprocess.call(["pybabel", "compile", "-d", translations_folder]) for plugin in plugin_manager.all_plugins: plugin_folder = os.path.join(PLUGINS_FOLDER, plugin) translations_folder = os.path.join(plugin_folder, "translations") subprocess.call(["pybabel", "compile", "-d", translations_folder]) def test_flaskbbdomain_translations(default_settings): domain = FlaskBBDomain(current_app) with current_app.test_request_context(): assert domain.get_translations_cache() == {} # no compiled translations are available assert isinstance(domain.get_translations(), NullTranslations) # lets compile them and test again _compile_translations() # now there should be translations :) assert isinstance(domain.get_translations(), Translations) <commit_msg>Remove the compiled translations for testing<commit_after>
import subprocess import os from flask import current_app from babel.support import Translations, NullTranslations from flaskbb.utils.translations import FlaskBBDomain from flaskbb.extensions import plugin_manager def _remove_compiled_translations(): translations_folder = os.path.join(current_app.root_path, "translations") # walks through the translations folder and deletes all files # ending with .mo for root, dirs, files in os.walk(translations_folder): for name in files: if name.endswith(".mo"): os.unlink(os.path.join(root, name)) def _compile_translations(): PLUGINS_FOLDER = os.path.join(current_app.root_path, "plugins") translations_folder = os.path.join(current_app.root_path, "translations") subprocess.call(["pybabel", "compile", "-d", translations_folder]) for plugin in plugin_manager.all_plugins: plugin_folder = os.path.join(PLUGINS_FOLDER, plugin) translations_folder = os.path.join(plugin_folder, "translations") subprocess.call(["pybabel", "compile", "-d", translations_folder]) def test_flaskbbdomain_translations(default_settings): domain = FlaskBBDomain(current_app) with current_app.test_request_context(): assert domain.get_translations_cache() == {} # just to be on the safe side that there are really no compiled # translations available _remove_compiled_translations() # no compiled translations are available assert isinstance(domain.get_translations(), NullTranslations) # lets compile them and test again _compile_translations() # now there should be translations :) assert isinstance(domain.get_translations(), Translations)
import subprocess import os from flask import current_app from babel.support import Translations, NullTranslations from flaskbb.utils.translations import FlaskBBDomain from flaskbb.extensions import plugin_manager def _compile_translations(): PLUGINS_FOLDER = os.path.join(current_app.root_path, "plugins") translations_folder = os.path.join(current_app.root_path, "translations") subprocess.call(["pybabel", "compile", "-d", translations_folder]) for plugin in plugin_manager.all_plugins: plugin_folder = os.path.join(PLUGINS_FOLDER, plugin) translations_folder = os.path.join(plugin_folder, "translations") subprocess.call(["pybabel", "compile", "-d", translations_folder]) def test_flaskbbdomain_translations(default_settings): domain = FlaskBBDomain(current_app) with current_app.test_request_context(): assert domain.get_translations_cache() == {} # no compiled translations are available assert isinstance(domain.get_translations(), NullTranslations) # lets compile them and test again _compile_translations() # now there should be translations :) assert isinstance(domain.get_translations(), Translations) Remove the compiled translations for testingimport subprocess import os from flask import current_app from babel.support import Translations, NullTranslations from flaskbb.utils.translations import FlaskBBDomain from flaskbb.extensions import plugin_manager def _remove_compiled_translations(): translations_folder = os.path.join(current_app.root_path, "translations") # walks through the translations folder and deletes all files # ending with .mo for root, dirs, files in os.walk(translations_folder): for name in files: if name.endswith(".mo"): os.unlink(os.path.join(root, name)) def _compile_translations(): PLUGINS_FOLDER = os.path.join(current_app.root_path, "plugins") translations_folder = os.path.join(current_app.root_path, "translations") subprocess.call(["pybabel", "compile", "-d", translations_folder]) for plugin in plugin_manager.all_plugins: plugin_folder = os.path.join(PLUGINS_FOLDER, plugin) translations_folder = os.path.join(plugin_folder, "translations") subprocess.call(["pybabel", "compile", "-d", translations_folder]) def test_flaskbbdomain_translations(default_settings): domain = FlaskBBDomain(current_app) with current_app.test_request_context(): assert domain.get_translations_cache() == {} # just to be on the safe side that there are really no compiled # translations available _remove_compiled_translations() # no compiled translations are available assert isinstance(domain.get_translations(), NullTranslations) # lets compile them and test again _compile_translations() # now there should be translations :) assert isinstance(domain.get_translations(), Translations)
<commit_before>import subprocess import os from flask import current_app from babel.support import Translations, NullTranslations from flaskbb.utils.translations import FlaskBBDomain from flaskbb.extensions import plugin_manager def _compile_translations(): PLUGINS_FOLDER = os.path.join(current_app.root_path, "plugins") translations_folder = os.path.join(current_app.root_path, "translations") subprocess.call(["pybabel", "compile", "-d", translations_folder]) for plugin in plugin_manager.all_plugins: plugin_folder = os.path.join(PLUGINS_FOLDER, plugin) translations_folder = os.path.join(plugin_folder, "translations") subprocess.call(["pybabel", "compile", "-d", translations_folder]) def test_flaskbbdomain_translations(default_settings): domain = FlaskBBDomain(current_app) with current_app.test_request_context(): assert domain.get_translations_cache() == {} # no compiled translations are available assert isinstance(domain.get_translations(), NullTranslations) # lets compile them and test again _compile_translations() # now there should be translations :) assert isinstance(domain.get_translations(), Translations) <commit_msg>Remove the compiled translations for testing<commit_after>import subprocess import os from flask import current_app from babel.support import Translations, NullTranslations from flaskbb.utils.translations import FlaskBBDomain from flaskbb.extensions import plugin_manager def _remove_compiled_translations(): translations_folder = os.path.join(current_app.root_path, "translations") # walks through the translations folder and deletes all files # ending with .mo for root, dirs, files in os.walk(translations_folder): for name in files: if name.endswith(".mo"): os.unlink(os.path.join(root, name)) def _compile_translations(): PLUGINS_FOLDER = os.path.join(current_app.root_path, "plugins") translations_folder = os.path.join(current_app.root_path, "translations") subprocess.call(["pybabel", "compile", "-d", translations_folder]) for plugin in plugin_manager.all_plugins: plugin_folder = os.path.join(PLUGINS_FOLDER, plugin) translations_folder = os.path.join(plugin_folder, "translations") subprocess.call(["pybabel", "compile", "-d", translations_folder]) def test_flaskbbdomain_translations(default_settings): domain = FlaskBBDomain(current_app) with current_app.test_request_context(): assert domain.get_translations_cache() == {} # just to be on the safe side that there are really no compiled # translations available _remove_compiled_translations() # no compiled translations are available assert isinstance(domain.get_translations(), NullTranslations) # lets compile them and test again _compile_translations() # now there should be translations :) assert isinstance(domain.get_translations(), Translations)
03085721fed3bd5880cbd44c1b146acded6c7719
tardis_code_compare.py
tardis_code_compare.py
import os import pandas as pd import astropy.units as units class CodeComparisonOutputFile(object): first_column_name = 'VEL' def __init__(self, times, data_table, model_name, data_first_column): self.times = times self.data_table = data_table self.data_table.insert(0, 'wav', data_first_column) self.model_name = model_name @property def times_str(self): return ' '.join([str(time) for time in self.times]) @property def fname(self): return self.data_type + '_{}_tardis.txt'.format(self.model_name) def write(self, dest='.'): path = os.path.join(dest, self.fname) with open(path, mode='w+') as f: f.write('#NTIMES: {}\n'.format(len(self.times))) f.write('#N{}: {}\n'.format(self.first_column_name, len(self.data_table))) f.write('#TIMES[d]: ' + self.times_str + '\n') f.write(self.column_description + '\n') self.data_table.to_csv(f, index=False, float_format='%.6E', sep=' ', header=False) @staticmethod def get_times_from_simulations(simulations): times = [ sim.model.time_explosion.to(units.day).value for sim in simulations ] return times @classmethod def from_simulations(cls, simulations, model_name): times = cls.get_times_from_simulations(simulations) data_table = cls.get_data_table(simulations) data_first_column = cls.get_data_first_column(simulations) return cls(times, data_table, model_name, data_first_column) @staticmethod def get_data_first_column(simulations): pass @staticmethod def get_data_table(simulations): pass class SpectralOutputFile(CodeComparisonOutputFile): data_type = 'spectra' first_column_name = 'WAVE' column_description = ('#wavelength[Ang] flux_t0[erg/s/Ang] ' 'flux_t1[erg/s/Ang] ... flux_tn[erg/s/Ang]') @staticmethod def get_data_first_column(simulations): return simulations[0].runner.spectrum.wavelength.value @staticmethod def get_data_table(simulations): spectra = [ sim.runner.spectrum_integrated.luminosity_density_lambda.value for sim in simulations ] return pd.DataFrame(spectra).T class TGasOutputFile(CodeComparisonOutputFile): data_type = 'tgas' column_description = '#vel_mid[km/s] Tgas_t0[K] Tgas_t1[K] ... Tgas_tn[K]'
Add generation of spectral output file
Add generation of spectral output file
Python
bsd-3-clause
tardis-sn/tardisanalysis
Add generation of spectral output file
import os import pandas as pd import astropy.units as units class CodeComparisonOutputFile(object): first_column_name = 'VEL' def __init__(self, times, data_table, model_name, data_first_column): self.times = times self.data_table = data_table self.data_table.insert(0, 'wav', data_first_column) self.model_name = model_name @property def times_str(self): return ' '.join([str(time) for time in self.times]) @property def fname(self): return self.data_type + '_{}_tardis.txt'.format(self.model_name) def write(self, dest='.'): path = os.path.join(dest, self.fname) with open(path, mode='w+') as f: f.write('#NTIMES: {}\n'.format(len(self.times))) f.write('#N{}: {}\n'.format(self.first_column_name, len(self.data_table))) f.write('#TIMES[d]: ' + self.times_str + '\n') f.write(self.column_description + '\n') self.data_table.to_csv(f, index=False, float_format='%.6E', sep=' ', header=False) @staticmethod def get_times_from_simulations(simulations): times = [ sim.model.time_explosion.to(units.day).value for sim in simulations ] return times @classmethod def from_simulations(cls, simulations, model_name): times = cls.get_times_from_simulations(simulations) data_table = cls.get_data_table(simulations) data_first_column = cls.get_data_first_column(simulations) return cls(times, data_table, model_name, data_first_column) @staticmethod def get_data_first_column(simulations): pass @staticmethod def get_data_table(simulations): pass class SpectralOutputFile(CodeComparisonOutputFile): data_type = 'spectra' first_column_name = 'WAVE' column_description = ('#wavelength[Ang] flux_t0[erg/s/Ang] ' 'flux_t1[erg/s/Ang] ... flux_tn[erg/s/Ang]') @staticmethod def get_data_first_column(simulations): return simulations[0].runner.spectrum.wavelength.value @staticmethod def get_data_table(simulations): spectra = [ sim.runner.spectrum_integrated.luminosity_density_lambda.value for sim in simulations ] return pd.DataFrame(spectra).T class TGasOutputFile(CodeComparisonOutputFile): data_type = 'tgas' column_description = '#vel_mid[km/s] Tgas_t0[K] Tgas_t1[K] ... Tgas_tn[K]'
<commit_before> <commit_msg>Add generation of spectral output file<commit_after>
import os import pandas as pd import astropy.units as units class CodeComparisonOutputFile(object): first_column_name = 'VEL' def __init__(self, times, data_table, model_name, data_first_column): self.times = times self.data_table = data_table self.data_table.insert(0, 'wav', data_first_column) self.model_name = model_name @property def times_str(self): return ' '.join([str(time) for time in self.times]) @property def fname(self): return self.data_type + '_{}_tardis.txt'.format(self.model_name) def write(self, dest='.'): path = os.path.join(dest, self.fname) with open(path, mode='w+') as f: f.write('#NTIMES: {}\n'.format(len(self.times))) f.write('#N{}: {}\n'.format(self.first_column_name, len(self.data_table))) f.write('#TIMES[d]: ' + self.times_str + '\n') f.write(self.column_description + '\n') self.data_table.to_csv(f, index=False, float_format='%.6E', sep=' ', header=False) @staticmethod def get_times_from_simulations(simulations): times = [ sim.model.time_explosion.to(units.day).value for sim in simulations ] return times @classmethod def from_simulations(cls, simulations, model_name): times = cls.get_times_from_simulations(simulations) data_table = cls.get_data_table(simulations) data_first_column = cls.get_data_first_column(simulations) return cls(times, data_table, model_name, data_first_column) @staticmethod def get_data_first_column(simulations): pass @staticmethod def get_data_table(simulations): pass class SpectralOutputFile(CodeComparisonOutputFile): data_type = 'spectra' first_column_name = 'WAVE' column_description = ('#wavelength[Ang] flux_t0[erg/s/Ang] ' 'flux_t1[erg/s/Ang] ... flux_tn[erg/s/Ang]') @staticmethod def get_data_first_column(simulations): return simulations[0].runner.spectrum.wavelength.value @staticmethod def get_data_table(simulations): spectra = [ sim.runner.spectrum_integrated.luminosity_density_lambda.value for sim in simulations ] return pd.DataFrame(spectra).T class TGasOutputFile(CodeComparisonOutputFile): data_type = 'tgas' column_description = '#vel_mid[km/s] Tgas_t0[K] Tgas_t1[K] ... Tgas_tn[K]'
Add generation of spectral output fileimport os import pandas as pd import astropy.units as units class CodeComparisonOutputFile(object): first_column_name = 'VEL' def __init__(self, times, data_table, model_name, data_first_column): self.times = times self.data_table = data_table self.data_table.insert(0, 'wav', data_first_column) self.model_name = model_name @property def times_str(self): return ' '.join([str(time) for time in self.times]) @property def fname(self): return self.data_type + '_{}_tardis.txt'.format(self.model_name) def write(self, dest='.'): path = os.path.join(dest, self.fname) with open(path, mode='w+') as f: f.write('#NTIMES: {}\n'.format(len(self.times))) f.write('#N{}: {}\n'.format(self.first_column_name, len(self.data_table))) f.write('#TIMES[d]: ' + self.times_str + '\n') f.write(self.column_description + '\n') self.data_table.to_csv(f, index=False, float_format='%.6E', sep=' ', header=False) @staticmethod def get_times_from_simulations(simulations): times = [ sim.model.time_explosion.to(units.day).value for sim in simulations ] return times @classmethod def from_simulations(cls, simulations, model_name): times = cls.get_times_from_simulations(simulations) data_table = cls.get_data_table(simulations) data_first_column = cls.get_data_first_column(simulations) return cls(times, data_table, model_name, data_first_column) @staticmethod def get_data_first_column(simulations): pass @staticmethod def get_data_table(simulations): pass class SpectralOutputFile(CodeComparisonOutputFile): data_type = 'spectra' first_column_name = 'WAVE' column_description = ('#wavelength[Ang] flux_t0[erg/s/Ang] ' 'flux_t1[erg/s/Ang] ... flux_tn[erg/s/Ang]') @staticmethod def get_data_first_column(simulations): return simulations[0].runner.spectrum.wavelength.value @staticmethod def get_data_table(simulations): spectra = [ sim.runner.spectrum_integrated.luminosity_density_lambda.value for sim in simulations ] return pd.DataFrame(spectra).T class TGasOutputFile(CodeComparisonOutputFile): data_type = 'tgas' column_description = '#vel_mid[km/s] Tgas_t0[K] Tgas_t1[K] ... Tgas_tn[K]'
<commit_before> <commit_msg>Add generation of spectral output file<commit_after>import os import pandas as pd import astropy.units as units class CodeComparisonOutputFile(object): first_column_name = 'VEL' def __init__(self, times, data_table, model_name, data_first_column): self.times = times self.data_table = data_table self.data_table.insert(0, 'wav', data_first_column) self.model_name = model_name @property def times_str(self): return ' '.join([str(time) for time in self.times]) @property def fname(self): return self.data_type + '_{}_tardis.txt'.format(self.model_name) def write(self, dest='.'): path = os.path.join(dest, self.fname) with open(path, mode='w+') as f: f.write('#NTIMES: {}\n'.format(len(self.times))) f.write('#N{}: {}\n'.format(self.first_column_name, len(self.data_table))) f.write('#TIMES[d]: ' + self.times_str + '\n') f.write(self.column_description + '\n') self.data_table.to_csv(f, index=False, float_format='%.6E', sep=' ', header=False) @staticmethod def get_times_from_simulations(simulations): times = [ sim.model.time_explosion.to(units.day).value for sim in simulations ] return times @classmethod def from_simulations(cls, simulations, model_name): times = cls.get_times_from_simulations(simulations) data_table = cls.get_data_table(simulations) data_first_column = cls.get_data_first_column(simulations) return cls(times, data_table, model_name, data_first_column) @staticmethod def get_data_first_column(simulations): pass @staticmethod def get_data_table(simulations): pass class SpectralOutputFile(CodeComparisonOutputFile): data_type = 'spectra' first_column_name = 'WAVE' column_description = ('#wavelength[Ang] flux_t0[erg/s/Ang] ' 'flux_t1[erg/s/Ang] ... flux_tn[erg/s/Ang]') @staticmethod def get_data_first_column(simulations): return simulations[0].runner.spectrum.wavelength.value @staticmethod def get_data_table(simulations): spectra = [ sim.runner.spectrum_integrated.luminosity_density_lambda.value for sim in simulations ] return pd.DataFrame(spectra).T class TGasOutputFile(CodeComparisonOutputFile): data_type = 'tgas' column_description = '#vel_mid[km/s] Tgas_t0[K] Tgas_t1[K] ... Tgas_tn[K]'
6daf3d416be4a54b8fbb4cbedc833d086b40fe9d
importlib_resources/tests/test_path.py
importlib_resources/tests/test_path.py
import io import os.path import pathlib import sys import unittest import importlib_resources as resources from . import data from . import util class CommonTests(util.CommonTests, unittest.TestCase): def execute(self, package, path): with resources.path(package, path): pass class PathTests(unittest.TestCase): def test_reading(self): # Path should be readable. # Test also implicitly verifies the returned object is a pathlib.Path # instance. with resources.path(data, 'utf-8.file') as path: # pathlib.Path.read_text() was introduced in Python 3.5. with path.open('r', encoding='utf-8') as file: text = file.read() self.assertEqual('Hello, UTF-8 world!\n', text)
import io import os.path import pathlib import sys import unittest import importlib_resources as resources from . import data from . import util class CommonTests(util.CommonTests, unittest.TestCase): def execute(self, package, path): with resources.path(package, path): pass class PathTests: def test_reading(self): # Path should be readable. # Test also implicitly verifies the returned object is a pathlib.Path # instance. with resources.path(self.data, 'utf-8.file') as path: # pathlib.Path.read_text() was introduced in Python 3.5. with path.open('r', encoding='utf-8') as file: text = file.read() self.assertEqual('Hello, UTF-8 world!\n', text) class PathDiskTests(PathTests, unittest.TestCase): data = data class PathZipTests(PathTests, util.ZipSetup, unittest.TestCase): pass
Test zip data for path()
Test zip data for path()
Python
apache-2.0
python/importlib_resources
import io import os.path import pathlib import sys import unittest import importlib_resources as resources from . import data from . import util class CommonTests(util.CommonTests, unittest.TestCase): def execute(self, package, path): with resources.path(package, path): pass class PathTests(unittest.TestCase): def test_reading(self): # Path should be readable. # Test also implicitly verifies the returned object is a pathlib.Path # instance. with resources.path(data, 'utf-8.file') as path: # pathlib.Path.read_text() was introduced in Python 3.5. with path.open('r', encoding='utf-8') as file: text = file.read() self.assertEqual('Hello, UTF-8 world!\n', text) Test zip data for path()
import io import os.path import pathlib import sys import unittest import importlib_resources as resources from . import data from . import util class CommonTests(util.CommonTests, unittest.TestCase): def execute(self, package, path): with resources.path(package, path): pass class PathTests: def test_reading(self): # Path should be readable. # Test also implicitly verifies the returned object is a pathlib.Path # instance. with resources.path(self.data, 'utf-8.file') as path: # pathlib.Path.read_text() was introduced in Python 3.5. with path.open('r', encoding='utf-8') as file: text = file.read() self.assertEqual('Hello, UTF-8 world!\n', text) class PathDiskTests(PathTests, unittest.TestCase): data = data class PathZipTests(PathTests, util.ZipSetup, unittest.TestCase): pass
<commit_before>import io import os.path import pathlib import sys import unittest import importlib_resources as resources from . import data from . import util class CommonTests(util.CommonTests, unittest.TestCase): def execute(self, package, path): with resources.path(package, path): pass class PathTests(unittest.TestCase): def test_reading(self): # Path should be readable. # Test also implicitly verifies the returned object is a pathlib.Path # instance. with resources.path(data, 'utf-8.file') as path: # pathlib.Path.read_text() was introduced in Python 3.5. with path.open('r', encoding='utf-8') as file: text = file.read() self.assertEqual('Hello, UTF-8 world!\n', text) <commit_msg>Test zip data for path()<commit_after>
import io import os.path import pathlib import sys import unittest import importlib_resources as resources from . import data from . import util class CommonTests(util.CommonTests, unittest.TestCase): def execute(self, package, path): with resources.path(package, path): pass class PathTests: def test_reading(self): # Path should be readable. # Test also implicitly verifies the returned object is a pathlib.Path # instance. with resources.path(self.data, 'utf-8.file') as path: # pathlib.Path.read_text() was introduced in Python 3.5. with path.open('r', encoding='utf-8') as file: text = file.read() self.assertEqual('Hello, UTF-8 world!\n', text) class PathDiskTests(PathTests, unittest.TestCase): data = data class PathZipTests(PathTests, util.ZipSetup, unittest.TestCase): pass
import io import os.path import pathlib import sys import unittest import importlib_resources as resources from . import data from . import util class CommonTests(util.CommonTests, unittest.TestCase): def execute(self, package, path): with resources.path(package, path): pass class PathTests(unittest.TestCase): def test_reading(self): # Path should be readable. # Test also implicitly verifies the returned object is a pathlib.Path # instance. with resources.path(data, 'utf-8.file') as path: # pathlib.Path.read_text() was introduced in Python 3.5. with path.open('r', encoding='utf-8') as file: text = file.read() self.assertEqual('Hello, UTF-8 world!\n', text) Test zip data for path()import io import os.path import pathlib import sys import unittest import importlib_resources as resources from . import data from . import util class CommonTests(util.CommonTests, unittest.TestCase): def execute(self, package, path): with resources.path(package, path): pass class PathTests: def test_reading(self): # Path should be readable. # Test also implicitly verifies the returned object is a pathlib.Path # instance. with resources.path(self.data, 'utf-8.file') as path: # pathlib.Path.read_text() was introduced in Python 3.5. with path.open('r', encoding='utf-8') as file: text = file.read() self.assertEqual('Hello, UTF-8 world!\n', text) class PathDiskTests(PathTests, unittest.TestCase): data = data class PathZipTests(PathTests, util.ZipSetup, unittest.TestCase): pass
<commit_before>import io import os.path import pathlib import sys import unittest import importlib_resources as resources from . import data from . import util class CommonTests(util.CommonTests, unittest.TestCase): def execute(self, package, path): with resources.path(package, path): pass class PathTests(unittest.TestCase): def test_reading(self): # Path should be readable. # Test also implicitly verifies the returned object is a pathlib.Path # instance. with resources.path(data, 'utf-8.file') as path: # pathlib.Path.read_text() was introduced in Python 3.5. with path.open('r', encoding='utf-8') as file: text = file.read() self.assertEqual('Hello, UTF-8 world!\n', text) <commit_msg>Test zip data for path()<commit_after>import io import os.path import pathlib import sys import unittest import importlib_resources as resources from . import data from . import util class CommonTests(util.CommonTests, unittest.TestCase): def execute(self, package, path): with resources.path(package, path): pass class PathTests: def test_reading(self): # Path should be readable. # Test also implicitly verifies the returned object is a pathlib.Path # instance. with resources.path(self.data, 'utf-8.file') as path: # pathlib.Path.read_text() was introduced in Python 3.5. with path.open('r', encoding='utf-8') as file: text = file.read() self.assertEqual('Hello, UTF-8 world!\n', text) class PathDiskTests(PathTests, unittest.TestCase): data = data class PathZipTests(PathTests, util.ZipSetup, unittest.TestCase): pass
8aa855fc2a0242f90301404062eaa3e62352d627
api/base/exceptions.py
api/base/exceptions.py
from rest_framework import status from rest_framework.exceptions import APIException, ParseError def json_api_exception_handler(exc, context): """ Custom exception handler that returns errors object as an array """ # Import inside method to avoid errors when the OSF is loaded without Django from rest_framework.views import exception_handler response = exception_handler(exc, context) # Error objects may have the following members. Title removed to avoid clash with node "title" errors. top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta'] errors = [] if response: message = response.data if isinstance(message, dict): for key, value in message.iteritems(): if key in top_level_error_keys: errors.append({key: value}) else: if isinstance(value, list): for reason in value: errors.append({'source': {'pointer': '/data/attributes/' + key}, 'detail': reason}) else: errors.append({'source': {'pointer': '/data/attributes/' + key}, 'detail': value}) elif isinstance(message, (list, tuple)): for error in message: errors.append({'detail': error}) else: errors.append({'detail': message}) response.data = {'errors': errors} return response # Custom Exceptions the Django Rest Framework does not support class Gone(APIException): status_code = status.HTTP_410_GONE default_detail = ('The requested resource is no longer available.') class InvalidFilterError(ParseError): """Raised when client passes an invalid filter in the querystring.""" default_detail = 'Querystring contains an invalid filter.'
from rest_framework import status from rest_framework.exceptions import APIException, ParseError def json_api_exception_handler(exc, context): """ Custom exception handler that returns errors object as an array """ # Import inside method to avoid errors when the OSF is loaded without Django from rest_framework.views import exception_handler response = exception_handler(exc, context) # Error objects may have the following members. Title removed to avoid clash with node "title" errors. top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta'] errors = [] if response: message = response.data if isinstance(message, dict): for key, value in message.iteritems(): if key in top_level_error_keys: errors.append({key: value}) else: if isinstance(value, str): value = [value] errors.extend([{'source': {'pointer': '/data/attributes/' + key}, 'detail': reason} for reason in value]) elif isinstance(message, (list, tuple)): for error in message: errors.append({'detail': error}) else: errors.append({'detail': message}) response.data = {'errors': errors} return response # Custom Exceptions the Django Rest Framework does not support class Gone(APIException): status_code = status.HTTP_410_GONE default_detail = ('The requested resource is no longer available.') class InvalidFilterError(ParseError): """Raised when client passes an invalid filter in the querystring.""" default_detail = 'Querystring contains an invalid filter.'
Use list comprehensions and consolidate error formatting where error details are either a list or a string.
Use list comprehensions and consolidate error formatting where error details are either a list or a string.
Python
apache-2.0
felliott/osf.io,samchrisinger/osf.io,Ghalko/osf.io,kch8qx/osf.io,kwierman/osf.io,acshi/osf.io,CenterForOpenScience/osf.io,emetsger/osf.io,haoyuchen1992/osf.io,kwierman/osf.io,kch8qx/osf.io,cslzchen/osf.io,arpitar/osf.io,kwierman/osf.io,billyhunt/osf.io,mattclark/osf.io,danielneis/osf.io,danielneis/osf.io,cwisecarver/osf.io,rdhyee/osf.io,rdhyee/osf.io,kwierman/osf.io,amyshi188/osf.io,samanehsan/osf.io,hmoco/osf.io,samchrisinger/osf.io,billyhunt/osf.io,KAsante95/osf.io,pattisdr/osf.io,jnayak1/osf.io,mluke93/osf.io,cosenal/osf.io,Nesiehr/osf.io,brianjgeiger/osf.io,billyhunt/osf.io,felliott/osf.io,SSJohns/osf.io,SSJohns/osf.io,cslzchen/osf.io,mluo613/osf.io,caseyrygt/osf.io,wearpants/osf.io,binoculars/osf.io,mfraezz/osf.io,ZobairAlijan/osf.io,TomHeatwole/osf.io,mluo613/osf.io,abought/osf.io,pattisdr/osf.io,alexschiller/osf.io,laurenrevere/osf.io,rdhyee/osf.io,caseyrollins/osf.io,monikagrabowska/osf.io,amyshi188/osf.io,zachjanicki/osf.io,TomBaxter/osf.io,caseyrygt/osf.io,cslzchen/osf.io,Nesiehr/osf.io,kch8qx/osf.io,doublebits/osf.io,samanehsan/osf.io,laurenrevere/osf.io,RomanZWang/osf.io,DanielSBrown/osf.io,monikagrabowska/osf.io,mluo613/osf.io,KAsante95/osf.io,chennan47/osf.io,brandonPurvis/osf.io,caneruguz/osf.io,erinspace/osf.io,caneruguz/osf.io,mfraezz/osf.io,kch8qx/osf.io,GageGaskins/osf.io,petermalcolm/osf.io,billyhunt/osf.io,mluo613/osf.io,Johnetordoff/osf.io,zamattiac/osf.io,CenterForOpenScience/osf.io,crcresearch/osf.io,erinspace/osf.io,felliott/osf.io,haoyuchen1992/osf.io,emetsger/osf.io,petermalcolm/osf.io,njantrania/osf.io,njantrania/osf.io,caseyrollins/osf.io,danielneis/osf.io,CenterForOpenScience/osf.io,zamattiac/osf.io,GageGaskins/osf.io,brandonPurvis/osf.io,adlius/osf.io,chrisseto/osf.io,icereval/osf.io,brandonPurvis/osf.io,RomanZWang/osf.io,aaxelb/osf.io,amyshi188/osf.io,chrisseto/osf.io,samanehsan/osf.io,amyshi188/osf.io,crcresearch/osf.io,hmoco/osf.io,samchrisinger/osf.io,GageGaskins/osf.io,hmoco/osf.io,doublebits/osf.io,cosenal/osf.io,cwisecarver/osf.io,haoyuchen1992/osf.io,Nesiehr/osf.io,monikagrabowska/osf.io,SSJohns/osf.io,DanielSBrown/osf.io,njantrania/osf.io,cwisecarver/osf.io,samanehsan/osf.io,arpitar/osf.io,ZobairAlijan/osf.io,brianjgeiger/osf.io,wearpants/osf.io,adlius/osf.io,abought/osf.io,KAsante95/osf.io,emetsger/osf.io,caseyrygt/osf.io,abought/osf.io,brianjgeiger/osf.io,ticklemepierce/osf.io,rdhyee/osf.io,asanfilippo7/osf.io,binoculars/osf.io,aaxelb/osf.io,caseyrygt/osf.io,zamattiac/osf.io,saradbowman/osf.io,wearpants/osf.io,doublebits/osf.io,kch8qx/osf.io,DanielSBrown/osf.io,HalcyonChimera/osf.io,GageGaskins/osf.io,crcresearch/osf.io,TomHeatwole/osf.io,leb2dg/osf.io,Ghalko/osf.io,TomBaxter/osf.io,acshi/osf.io,icereval/osf.io,TomHeatwole/osf.io,aaxelb/osf.io,Ghalko/osf.io,mluo613/osf.io,sloria/osf.io,CenterForOpenScience/osf.io,doublebits/osf.io,mluke93/osf.io,TomBaxter/osf.io,DanielSBrown/osf.io,Nesiehr/osf.io,RomanZWang/osf.io,caneruguz/osf.io,SSJohns/osf.io,ticklemepierce/osf.io,adlius/osf.io,mfraezz/osf.io,RomanZWang/osf.io,arpitar/osf.io,acshi/osf.io,wearpants/osf.io,ZobairAlijan/osf.io,brianjgeiger/osf.io,adlius/osf.io,chrisseto/osf.io,leb2dg/osf.io,doublebits/osf.io,baylee-d/osf.io,aaxelb/osf.io,abought/osf.io,petermalcolm/osf.io,mluke93/osf.io,chennan47/osf.io,sloria/osf.io,ticklemepierce/osf.io,HalcyonChimera/osf.io,KAsante95/osf.io,chrisseto/osf.io,Johnetordoff/osf.io,cosenal/osf.io,emetsger/osf.io,pattisdr/osf.io,brandonPurvis/osf.io,hmoco/osf.io,TomHeatwole/osf.io,jnayak1/osf.io,petermalcolm/osf.io,leb2dg/osf.io,zachjanicki/osf.io,zachjanicki/osf.io,felliott/osf.io,zamattiac/osf.io,asanfilippo7/osf.io,baylee-d/osf.io,monikagrabowska/osf.io,alexschiller/osf.io,ticklemepierce/osf.io,jnayak1/osf.io,cwisecarver/osf.io,haoyuchen1992/osf.io,alexschiller/osf.io,HalcyonChimera/osf.io,brandonPurvis/osf.io,erinspace/osf.io,acshi/osf.io,ZobairAlijan/osf.io,baylee-d/osf.io,billyhunt/osf.io,Johnetordoff/osf.io,samchrisinger/osf.io,zachjanicki/osf.io,binoculars/osf.io,mfraezz/osf.io,caneruguz/osf.io,Johnetordoff/osf.io,arpitar/osf.io,icereval/osf.io,sloria/osf.io,RomanZWang/osf.io,HalcyonChimera/osf.io,mattclark/osf.io,asanfilippo7/osf.io,mluke93/osf.io,mattclark/osf.io,GageGaskins/osf.io,saradbowman/osf.io,danielneis/osf.io,caseyrollins/osf.io,alexschiller/osf.io,alexschiller/osf.io,njantrania/osf.io,laurenrevere/osf.io,monikagrabowska/osf.io,cslzchen/osf.io,KAsante95/osf.io,cosenal/osf.io,leb2dg/osf.io,Ghalko/osf.io,asanfilippo7/osf.io,chennan47/osf.io,acshi/osf.io,jnayak1/osf.io
from rest_framework import status from rest_framework.exceptions import APIException, ParseError def json_api_exception_handler(exc, context): """ Custom exception handler that returns errors object as an array """ # Import inside method to avoid errors when the OSF is loaded without Django from rest_framework.views import exception_handler response = exception_handler(exc, context) # Error objects may have the following members. Title removed to avoid clash with node "title" errors. top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta'] errors = [] if response: message = response.data if isinstance(message, dict): for key, value in message.iteritems(): if key in top_level_error_keys: errors.append({key: value}) else: if isinstance(value, list): for reason in value: errors.append({'source': {'pointer': '/data/attributes/' + key}, 'detail': reason}) else: errors.append({'source': {'pointer': '/data/attributes/' + key}, 'detail': value}) elif isinstance(message, (list, tuple)): for error in message: errors.append({'detail': error}) else: errors.append({'detail': message}) response.data = {'errors': errors} return response # Custom Exceptions the Django Rest Framework does not support class Gone(APIException): status_code = status.HTTP_410_GONE default_detail = ('The requested resource is no longer available.') class InvalidFilterError(ParseError): """Raised when client passes an invalid filter in the querystring.""" default_detail = 'Querystring contains an invalid filter.' Use list comprehensions and consolidate error formatting where error details are either a list or a string.
from rest_framework import status from rest_framework.exceptions import APIException, ParseError def json_api_exception_handler(exc, context): """ Custom exception handler that returns errors object as an array """ # Import inside method to avoid errors when the OSF is loaded without Django from rest_framework.views import exception_handler response = exception_handler(exc, context) # Error objects may have the following members. Title removed to avoid clash with node "title" errors. top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta'] errors = [] if response: message = response.data if isinstance(message, dict): for key, value in message.iteritems(): if key in top_level_error_keys: errors.append({key: value}) else: if isinstance(value, str): value = [value] errors.extend([{'source': {'pointer': '/data/attributes/' + key}, 'detail': reason} for reason in value]) elif isinstance(message, (list, tuple)): for error in message: errors.append({'detail': error}) else: errors.append({'detail': message}) response.data = {'errors': errors} return response # Custom Exceptions the Django Rest Framework does not support class Gone(APIException): status_code = status.HTTP_410_GONE default_detail = ('The requested resource is no longer available.') class InvalidFilterError(ParseError): """Raised when client passes an invalid filter in the querystring.""" default_detail = 'Querystring contains an invalid filter.'
<commit_before> from rest_framework import status from rest_framework.exceptions import APIException, ParseError def json_api_exception_handler(exc, context): """ Custom exception handler that returns errors object as an array """ # Import inside method to avoid errors when the OSF is loaded without Django from rest_framework.views import exception_handler response = exception_handler(exc, context) # Error objects may have the following members. Title removed to avoid clash with node "title" errors. top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta'] errors = [] if response: message = response.data if isinstance(message, dict): for key, value in message.iteritems(): if key in top_level_error_keys: errors.append({key: value}) else: if isinstance(value, list): for reason in value: errors.append({'source': {'pointer': '/data/attributes/' + key}, 'detail': reason}) else: errors.append({'source': {'pointer': '/data/attributes/' + key}, 'detail': value}) elif isinstance(message, (list, tuple)): for error in message: errors.append({'detail': error}) else: errors.append({'detail': message}) response.data = {'errors': errors} return response # Custom Exceptions the Django Rest Framework does not support class Gone(APIException): status_code = status.HTTP_410_GONE default_detail = ('The requested resource is no longer available.') class InvalidFilterError(ParseError): """Raised when client passes an invalid filter in the querystring.""" default_detail = 'Querystring contains an invalid filter.' <commit_msg>Use list comprehensions and consolidate error formatting where error details are either a list or a string.<commit_after>
from rest_framework import status from rest_framework.exceptions import APIException, ParseError def json_api_exception_handler(exc, context): """ Custom exception handler that returns errors object as an array """ # Import inside method to avoid errors when the OSF is loaded without Django from rest_framework.views import exception_handler response = exception_handler(exc, context) # Error objects may have the following members. Title removed to avoid clash with node "title" errors. top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta'] errors = [] if response: message = response.data if isinstance(message, dict): for key, value in message.iteritems(): if key in top_level_error_keys: errors.append({key: value}) else: if isinstance(value, str): value = [value] errors.extend([{'source': {'pointer': '/data/attributes/' + key}, 'detail': reason} for reason in value]) elif isinstance(message, (list, tuple)): for error in message: errors.append({'detail': error}) else: errors.append({'detail': message}) response.data = {'errors': errors} return response # Custom Exceptions the Django Rest Framework does not support class Gone(APIException): status_code = status.HTTP_410_GONE default_detail = ('The requested resource is no longer available.') class InvalidFilterError(ParseError): """Raised when client passes an invalid filter in the querystring.""" default_detail = 'Querystring contains an invalid filter.'
from rest_framework import status from rest_framework.exceptions import APIException, ParseError def json_api_exception_handler(exc, context): """ Custom exception handler that returns errors object as an array """ # Import inside method to avoid errors when the OSF is loaded without Django from rest_framework.views import exception_handler response = exception_handler(exc, context) # Error objects may have the following members. Title removed to avoid clash with node "title" errors. top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta'] errors = [] if response: message = response.data if isinstance(message, dict): for key, value in message.iteritems(): if key in top_level_error_keys: errors.append({key: value}) else: if isinstance(value, list): for reason in value: errors.append({'source': {'pointer': '/data/attributes/' + key}, 'detail': reason}) else: errors.append({'source': {'pointer': '/data/attributes/' + key}, 'detail': value}) elif isinstance(message, (list, tuple)): for error in message: errors.append({'detail': error}) else: errors.append({'detail': message}) response.data = {'errors': errors} return response # Custom Exceptions the Django Rest Framework does not support class Gone(APIException): status_code = status.HTTP_410_GONE default_detail = ('The requested resource is no longer available.') class InvalidFilterError(ParseError): """Raised when client passes an invalid filter in the querystring.""" default_detail = 'Querystring contains an invalid filter.' Use list comprehensions and consolidate error formatting where error details are either a list or a string. from rest_framework import status from rest_framework.exceptions import APIException, ParseError def json_api_exception_handler(exc, context): """ Custom exception handler that returns errors object as an array """ # Import inside method to avoid errors when the OSF is loaded without Django from rest_framework.views import exception_handler response = exception_handler(exc, context) # Error objects may have the following members. Title removed to avoid clash with node "title" errors. top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta'] errors = [] if response: message = response.data if isinstance(message, dict): for key, value in message.iteritems(): if key in top_level_error_keys: errors.append({key: value}) else: if isinstance(value, str): value = [value] errors.extend([{'source': {'pointer': '/data/attributes/' + key}, 'detail': reason} for reason in value]) elif isinstance(message, (list, tuple)): for error in message: errors.append({'detail': error}) else: errors.append({'detail': message}) response.data = {'errors': errors} return response # Custom Exceptions the Django Rest Framework does not support class Gone(APIException): status_code = status.HTTP_410_GONE default_detail = ('The requested resource is no longer available.') class InvalidFilterError(ParseError): """Raised when client passes an invalid filter in the querystring.""" default_detail = 'Querystring contains an invalid filter.'
<commit_before> from rest_framework import status from rest_framework.exceptions import APIException, ParseError def json_api_exception_handler(exc, context): """ Custom exception handler that returns errors object as an array """ # Import inside method to avoid errors when the OSF is loaded without Django from rest_framework.views import exception_handler response = exception_handler(exc, context) # Error objects may have the following members. Title removed to avoid clash with node "title" errors. top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta'] errors = [] if response: message = response.data if isinstance(message, dict): for key, value in message.iteritems(): if key in top_level_error_keys: errors.append({key: value}) else: if isinstance(value, list): for reason in value: errors.append({'source': {'pointer': '/data/attributes/' + key}, 'detail': reason}) else: errors.append({'source': {'pointer': '/data/attributes/' + key}, 'detail': value}) elif isinstance(message, (list, tuple)): for error in message: errors.append({'detail': error}) else: errors.append({'detail': message}) response.data = {'errors': errors} return response # Custom Exceptions the Django Rest Framework does not support class Gone(APIException): status_code = status.HTTP_410_GONE default_detail = ('The requested resource is no longer available.') class InvalidFilterError(ParseError): """Raised when client passes an invalid filter in the querystring.""" default_detail = 'Querystring contains an invalid filter.' <commit_msg>Use list comprehensions and consolidate error formatting where error details are either a list or a string.<commit_after> from rest_framework import status from rest_framework.exceptions import APIException, ParseError def json_api_exception_handler(exc, context): """ Custom exception handler that returns errors object as an array """ # Import inside method to avoid errors when the OSF is loaded without Django from rest_framework.views import exception_handler response = exception_handler(exc, context) # Error objects may have the following members. Title removed to avoid clash with node "title" errors. top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta'] errors = [] if response: message = response.data if isinstance(message, dict): for key, value in message.iteritems(): if key in top_level_error_keys: errors.append({key: value}) else: if isinstance(value, str): value = [value] errors.extend([{'source': {'pointer': '/data/attributes/' + key}, 'detail': reason} for reason in value]) elif isinstance(message, (list, tuple)): for error in message: errors.append({'detail': error}) else: errors.append({'detail': message}) response.data = {'errors': errors} return response # Custom Exceptions the Django Rest Framework does not support class Gone(APIException): status_code = status.HTTP_410_GONE default_detail = ('The requested resource is no longer available.') class InvalidFilterError(ParseError): """Raised when client passes an invalid filter in the querystring.""" default_detail = 'Querystring contains an invalid filter.'
e84a06ea851a81648ba6ee54c88a61c049e913f2
gorilla/__init__.py
gorilla/__init__.py
# __ __ __ # .-----.-----.----|__| | .---.-. # | _ | _ | _| | | | _ | # |___ |_____|__| |__|__|__|___._| # |_____| # """ gorilla ~~~~~~~ Convenient approach to monkey patching. :copyright: Copyright 2014-2016 by Christopher Crouzet. :license: MIT, see LICENSE for details. """ from gorilla.decorators import apply, name, patch from gorilla.utils import get_original_attribute __version__ = '0.1.0' __all__ = [ 'decorators', 'extension', 'settings', 'utils' ]
# __ __ __ # .-----.-----.----|__| | .---.-. # | _ | _ | _| | | | _ | # |___ |_____|__| |__|__|__|___._| # |_____| # """ gorilla ~~~~~~~ Convenient approach to monkey patching. :copyright: Copyright 2014-2016 by Christopher Crouzet. :license: MIT, see LICENSE for details. """ from gorilla.decorators import apply, name, patch __version__ = '0.1.0' __all__ = [ 'decorators', 'extension', 'settings', 'utils' ]
Remove the `get_original_attribute` shortcut from the root module.
Remove the `get_original_attribute` shortcut from the root module.
Python
mit
christophercrouzet/gorilla
# __ __ __ # .-----.-----.----|__| | .---.-. # | _ | _ | _| | | | _ | # |___ |_____|__| |__|__|__|___._| # |_____| # """ gorilla ~~~~~~~ Convenient approach to monkey patching. :copyright: Copyright 2014-2016 by Christopher Crouzet. :license: MIT, see LICENSE for details. """ from gorilla.decorators import apply, name, patch from gorilla.utils import get_original_attribute __version__ = '0.1.0' __all__ = [ 'decorators', 'extension', 'settings', 'utils' ] Remove the `get_original_attribute` shortcut from the root module.
# __ __ __ # .-----.-----.----|__| | .---.-. # | _ | _ | _| | | | _ | # |___ |_____|__| |__|__|__|___._| # |_____| # """ gorilla ~~~~~~~ Convenient approach to monkey patching. :copyright: Copyright 2014-2016 by Christopher Crouzet. :license: MIT, see LICENSE for details. """ from gorilla.decorators import apply, name, patch __version__ = '0.1.0' __all__ = [ 'decorators', 'extension', 'settings', 'utils' ]
<commit_before># __ __ __ # .-----.-----.----|__| | .---.-. # | _ | _ | _| | | | _ | # |___ |_____|__| |__|__|__|___._| # |_____| # """ gorilla ~~~~~~~ Convenient approach to monkey patching. :copyright: Copyright 2014-2016 by Christopher Crouzet. :license: MIT, see LICENSE for details. """ from gorilla.decorators import apply, name, patch from gorilla.utils import get_original_attribute __version__ = '0.1.0' __all__ = [ 'decorators', 'extension', 'settings', 'utils' ] <commit_msg>Remove the `get_original_attribute` shortcut from the root module.<commit_after>
# __ __ __ # .-----.-----.----|__| | .---.-. # | _ | _ | _| | | | _ | # |___ |_____|__| |__|__|__|___._| # |_____| # """ gorilla ~~~~~~~ Convenient approach to monkey patching. :copyright: Copyright 2014-2016 by Christopher Crouzet. :license: MIT, see LICENSE for details. """ from gorilla.decorators import apply, name, patch __version__ = '0.1.0' __all__ = [ 'decorators', 'extension', 'settings', 'utils' ]
# __ __ __ # .-----.-----.----|__| | .---.-. # | _ | _ | _| | | | _ | # |___ |_____|__| |__|__|__|___._| # |_____| # """ gorilla ~~~~~~~ Convenient approach to monkey patching. :copyright: Copyright 2014-2016 by Christopher Crouzet. :license: MIT, see LICENSE for details. """ from gorilla.decorators import apply, name, patch from gorilla.utils import get_original_attribute __version__ = '0.1.0' __all__ = [ 'decorators', 'extension', 'settings', 'utils' ] Remove the `get_original_attribute` shortcut from the root module.# __ __ __ # .-----.-----.----|__| | .---.-. # | _ | _ | _| | | | _ | # |___ |_____|__| |__|__|__|___._| # |_____| # """ gorilla ~~~~~~~ Convenient approach to monkey patching. :copyright: Copyright 2014-2016 by Christopher Crouzet. :license: MIT, see LICENSE for details. """ from gorilla.decorators import apply, name, patch __version__ = '0.1.0' __all__ = [ 'decorators', 'extension', 'settings', 'utils' ]
<commit_before># __ __ __ # .-----.-----.----|__| | .---.-. # | _ | _ | _| | | | _ | # |___ |_____|__| |__|__|__|___._| # |_____| # """ gorilla ~~~~~~~ Convenient approach to monkey patching. :copyright: Copyright 2014-2016 by Christopher Crouzet. :license: MIT, see LICENSE for details. """ from gorilla.decorators import apply, name, patch from gorilla.utils import get_original_attribute __version__ = '0.1.0' __all__ = [ 'decorators', 'extension', 'settings', 'utils' ] <commit_msg>Remove the `get_original_attribute` shortcut from the root module.<commit_after># __ __ __ # .-----.-----.----|__| | .---.-. # | _ | _ | _| | | | _ | # |___ |_____|__| |__|__|__|___._| # |_____| # """ gorilla ~~~~~~~ Convenient approach to monkey patching. :copyright: Copyright 2014-2016 by Christopher Crouzet. :license: MIT, see LICENSE for details. """ from gorilla.decorators import apply, name, patch __version__ = '0.1.0' __all__ = [ 'decorators', 'extension', 'settings', 'utils' ]
7b382ac1dda54b30fb02dff681b031368f72eb42
httpobs/__init__.py
httpobs/__init__.py
SOURCE_URL = 'https://github.com/mozilla/http-observatory' VERSION = '0.9.2'
SOURCE_URL = 'https://github.com/mozilla/http-observatory' VERSION = '0.9.3'
Increment release version to 0.9.3
Increment release version to 0.9.3
Python
mpl-2.0
mozilla/http-observatory,mozilla/http-observatory,mozilla/http-observatory,april/http-observatory,april/http-observatory,april/http-observatory
SOURCE_URL = 'https://github.com/mozilla/http-observatory' VERSION = '0.9.2' Increment release version to 0.9.3
SOURCE_URL = 'https://github.com/mozilla/http-observatory' VERSION = '0.9.3'
<commit_before>SOURCE_URL = 'https://github.com/mozilla/http-observatory' VERSION = '0.9.2' <commit_msg>Increment release version to 0.9.3<commit_after>
SOURCE_URL = 'https://github.com/mozilla/http-observatory' VERSION = '0.9.3'
SOURCE_URL = 'https://github.com/mozilla/http-observatory' VERSION = '0.9.2' Increment release version to 0.9.3SOURCE_URL = 'https://github.com/mozilla/http-observatory' VERSION = '0.9.3'
<commit_before>SOURCE_URL = 'https://github.com/mozilla/http-observatory' VERSION = '0.9.2' <commit_msg>Increment release version to 0.9.3<commit_after>SOURCE_URL = 'https://github.com/mozilla/http-observatory' VERSION = '0.9.3'
9580418cfaaacd0f324df3337e332de4410cb3d1
server_dev.py
server_dev.py
import projects from flask import Flask, render_template, abort app = Flask(__name__) @app.errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 @app.route('/') def index(): project_list = projects.get_projects() return render_template('index.html', projects=project_list) @app.route('/blog', strict_slashes=False) def blog(): return "Flasktopress isn't quite ready yet, but we're stoked that it's coming." @app.route('/<project>', strict_slashes=False) def project(project): project_list = projects.get_projects() if project in project_list: project_data = project_list[project] return "Contact %s to join the %s project!" % (project_data['project_leaders'][0]['name'], project_data['project_title']) else: abort(404) if __name__ == '__main__': app.run(debug=True)
import projects from flask import Flask, render_template, abort app = Flask(__name__) def route(*a, **kw): kw['strict_slashes'] = kw.get('strict_slashes', False) return app.route(*a, **kw) @app.errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 @route('/') def index(): project_list = projects.get_projects() return render_template('index.html', projects=project_list) @route('/blog') def blog(): return "Flasktopress isn't quite ready yet, but we're stoked that it's coming." @route('/<project>') def project(project): project_list = projects.get_projects() if project in project_list: project_data = project_list[project] return "Contact %s to join the %s project!" % (project_data['project_leaders'][0]['name'], project_data['project_title']) else: abort(404) if __name__ == '__main__': app.run(debug=True)
Refactor slash-unpickiness as a function and redecorate
Refactor slash-unpickiness as a function and redecorate
Python
mit
teslaworksumn/teslaworks.net,teslaworksumn/teslaworks.net
import projects from flask import Flask, render_template, abort app = Flask(__name__) @app.errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 @app.route('/') def index(): project_list = projects.get_projects() return render_template('index.html', projects=project_list) @app.route('/blog', strict_slashes=False) def blog(): return "Flasktopress isn't quite ready yet, but we're stoked that it's coming." @app.route('/<project>', strict_slashes=False) def project(project): project_list = projects.get_projects() if project in project_list: project_data = project_list[project] return "Contact %s to join the %s project!" % (project_data['project_leaders'][0]['name'], project_data['project_title']) else: abort(404) if __name__ == '__main__': app.run(debug=True) Refactor slash-unpickiness as a function and redecorate
import projects from flask import Flask, render_template, abort app = Flask(__name__) def route(*a, **kw): kw['strict_slashes'] = kw.get('strict_slashes', False) return app.route(*a, **kw) @app.errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 @route('/') def index(): project_list = projects.get_projects() return render_template('index.html', projects=project_list) @route('/blog') def blog(): return "Flasktopress isn't quite ready yet, but we're stoked that it's coming." @route('/<project>') def project(project): project_list = projects.get_projects() if project in project_list: project_data = project_list[project] return "Contact %s to join the %s project!" % (project_data['project_leaders'][0]['name'], project_data['project_title']) else: abort(404) if __name__ == '__main__': app.run(debug=True)
<commit_before>import projects from flask import Flask, render_template, abort app = Flask(__name__) @app.errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 @app.route('/') def index(): project_list = projects.get_projects() return render_template('index.html', projects=project_list) @app.route('/blog', strict_slashes=False) def blog(): return "Flasktopress isn't quite ready yet, but we're stoked that it's coming." @app.route('/<project>', strict_slashes=False) def project(project): project_list = projects.get_projects() if project in project_list: project_data = project_list[project] return "Contact %s to join the %s project!" % (project_data['project_leaders'][0]['name'], project_data['project_title']) else: abort(404) if __name__ == '__main__': app.run(debug=True) <commit_msg>Refactor slash-unpickiness as a function and redecorate<commit_after>
import projects from flask import Flask, render_template, abort app = Flask(__name__) def route(*a, **kw): kw['strict_slashes'] = kw.get('strict_slashes', False) return app.route(*a, **kw) @app.errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 @route('/') def index(): project_list = projects.get_projects() return render_template('index.html', projects=project_list) @route('/blog') def blog(): return "Flasktopress isn't quite ready yet, but we're stoked that it's coming." @route('/<project>') def project(project): project_list = projects.get_projects() if project in project_list: project_data = project_list[project] return "Contact %s to join the %s project!" % (project_data['project_leaders'][0]['name'], project_data['project_title']) else: abort(404) if __name__ == '__main__': app.run(debug=True)
import projects from flask import Flask, render_template, abort app = Flask(__name__) @app.errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 @app.route('/') def index(): project_list = projects.get_projects() return render_template('index.html', projects=project_list) @app.route('/blog', strict_slashes=False) def blog(): return "Flasktopress isn't quite ready yet, but we're stoked that it's coming." @app.route('/<project>', strict_slashes=False) def project(project): project_list = projects.get_projects() if project in project_list: project_data = project_list[project] return "Contact %s to join the %s project!" % (project_data['project_leaders'][0]['name'], project_data['project_title']) else: abort(404) if __name__ == '__main__': app.run(debug=True) Refactor slash-unpickiness as a function and redecorateimport projects from flask import Flask, render_template, abort app = Flask(__name__) def route(*a, **kw): kw['strict_slashes'] = kw.get('strict_slashes', False) return app.route(*a, **kw) @app.errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 @route('/') def index(): project_list = projects.get_projects() return render_template('index.html', projects=project_list) @route('/blog') def blog(): return "Flasktopress isn't quite ready yet, but we're stoked that it's coming." @route('/<project>') def project(project): project_list = projects.get_projects() if project in project_list: project_data = project_list[project] return "Contact %s to join the %s project!" % (project_data['project_leaders'][0]['name'], project_data['project_title']) else: abort(404) if __name__ == '__main__': app.run(debug=True)
<commit_before>import projects from flask import Flask, render_template, abort app = Flask(__name__) @app.errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 @app.route('/') def index(): project_list = projects.get_projects() return render_template('index.html', projects=project_list) @app.route('/blog', strict_slashes=False) def blog(): return "Flasktopress isn't quite ready yet, but we're stoked that it's coming." @app.route('/<project>', strict_slashes=False) def project(project): project_list = projects.get_projects() if project in project_list: project_data = project_list[project] return "Contact %s to join the %s project!" % (project_data['project_leaders'][0]['name'], project_data['project_title']) else: abort(404) if __name__ == '__main__': app.run(debug=True) <commit_msg>Refactor slash-unpickiness as a function and redecorate<commit_after>import projects from flask import Flask, render_template, abort app = Flask(__name__) def route(*a, **kw): kw['strict_slashes'] = kw.get('strict_slashes', False) return app.route(*a, **kw) @app.errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 @route('/') def index(): project_list = projects.get_projects() return render_template('index.html', projects=project_list) @route('/blog') def blog(): return "Flasktopress isn't quite ready yet, but we're stoked that it's coming." @route('/<project>') def project(project): project_list = projects.get_projects() if project in project_list: project_data = project_list[project] return "Contact %s to join the %s project!" % (project_data['project_leaders'][0]['name'], project_data['project_title']) else: abort(404) if __name__ == '__main__': app.run(debug=True)
ddab25e03c96ad6c4950ee38fe5dcd73da5aa05c
shared/api.py
shared/api.py
from __future__ import print_function import boto3 import json import os import btr3baseball jobTable = os.environ['JOB_TABLE'] jobQueue = os.environ['JOB_QUEUE'] queue = boto3.resource('sqs').get_queue_by_name(QueueName=jobQueue) jobRepo = btr3baseball.JobRepository(jobTable) dsRepo = btr3baseball.DatasourceRepository() def main(event, context): method = event['method'] if method == 'submitJob': return submitJob(event, context) elif method == 'getJob': return getJob(event, context) elif method == 'listDatasources': return listDatasources(event, context) elif method == 'getDatasource': return getDatasource(event, context) else: return null def submitJob(event, context): # Put initial entry in dynamo db jobId = jobRepo.createJob(event) # Put the job ID on the SQS queue response = queue.send_message(MessageBody=jobId) # Update the DB entry with sqs message ID for traceability return jobRepo.updateWithMessageId(jobId, response.get('MessageId')) def getJob(event, context): return jobRepo.getJob(event['jobId']) def listDatasources(event, context): return dsRepo.listDatasources() def getDatasource(event, context): return dsRepo.getDatasource(event['datasourceId'])
from __future__ import print_function import boto3 import json import os import btr3baseball jobTable = os.environ['JOB_TABLE'] jobQueue = os.environ['JOB_QUEUE'] queue = boto3.resource('sqs').get_queue_by_name(QueueName=jobQueue) jobRepo = btr3baseball.JobRepository(jobTable) dsRepo = btr3baseball.DatasourceRepository() def main(event, context): method = event['method'] if method == 'submitJob': return submitJob(event['data'], context) elif method == 'getJob': return getJob(event['data'], context) elif method == 'listDatasources': return listDatasources(event['data'], context) elif method == 'getDatasource': return getDatasource(event['data'], context) else: return None def submitJob(event, context): # Put initial entry in dynamo db jobId = jobRepo.createJob(event) # Put the job ID on the SQS queue response = queue.send_message(MessageBody=jobId) # Update the DB entry with sqs message ID for traceability return jobRepo.updateWithMessageId(jobId, response.get('MessageId')) def getJob(event, context): return jobRepo.getJob(event['jobId']) def listDatasources(event, context): return dsRepo.listDatasources() def getDatasource(event, context): return dsRepo.getDatasource(event['datasourceId'])
Add wrapper for event data elem
Add wrapper for event data elem
Python
apache-2.0
bryantrobbins/baseball,bryantrobbins/baseball,bryantrobbins/baseball,bryantrobbins/baseball,bryantrobbins/baseball
from __future__ import print_function import boto3 import json import os import btr3baseball jobTable = os.environ['JOB_TABLE'] jobQueue = os.environ['JOB_QUEUE'] queue = boto3.resource('sqs').get_queue_by_name(QueueName=jobQueue) jobRepo = btr3baseball.JobRepository(jobTable) dsRepo = btr3baseball.DatasourceRepository() def main(event, context): method = event['method'] if method == 'submitJob': return submitJob(event, context) elif method == 'getJob': return getJob(event, context) elif method == 'listDatasources': return listDatasources(event, context) elif method == 'getDatasource': return getDatasource(event, context) else: return null def submitJob(event, context): # Put initial entry in dynamo db jobId = jobRepo.createJob(event) # Put the job ID on the SQS queue response = queue.send_message(MessageBody=jobId) # Update the DB entry with sqs message ID for traceability return jobRepo.updateWithMessageId(jobId, response.get('MessageId')) def getJob(event, context): return jobRepo.getJob(event['jobId']) def listDatasources(event, context): return dsRepo.listDatasources() def getDatasource(event, context): return dsRepo.getDatasource(event['datasourceId']) Add wrapper for event data elem
from __future__ import print_function import boto3 import json import os import btr3baseball jobTable = os.environ['JOB_TABLE'] jobQueue = os.environ['JOB_QUEUE'] queue = boto3.resource('sqs').get_queue_by_name(QueueName=jobQueue) jobRepo = btr3baseball.JobRepository(jobTable) dsRepo = btr3baseball.DatasourceRepository() def main(event, context): method = event['method'] if method == 'submitJob': return submitJob(event['data'], context) elif method == 'getJob': return getJob(event['data'], context) elif method == 'listDatasources': return listDatasources(event['data'], context) elif method == 'getDatasource': return getDatasource(event['data'], context) else: return None def submitJob(event, context): # Put initial entry in dynamo db jobId = jobRepo.createJob(event) # Put the job ID on the SQS queue response = queue.send_message(MessageBody=jobId) # Update the DB entry with sqs message ID for traceability return jobRepo.updateWithMessageId(jobId, response.get('MessageId')) def getJob(event, context): return jobRepo.getJob(event['jobId']) def listDatasources(event, context): return dsRepo.listDatasources() def getDatasource(event, context): return dsRepo.getDatasource(event['datasourceId'])
<commit_before>from __future__ import print_function import boto3 import json import os import btr3baseball jobTable = os.environ['JOB_TABLE'] jobQueue = os.environ['JOB_QUEUE'] queue = boto3.resource('sqs').get_queue_by_name(QueueName=jobQueue) jobRepo = btr3baseball.JobRepository(jobTable) dsRepo = btr3baseball.DatasourceRepository() def main(event, context): method = event['method'] if method == 'submitJob': return submitJob(event, context) elif method == 'getJob': return getJob(event, context) elif method == 'listDatasources': return listDatasources(event, context) elif method == 'getDatasource': return getDatasource(event, context) else: return null def submitJob(event, context): # Put initial entry in dynamo db jobId = jobRepo.createJob(event) # Put the job ID on the SQS queue response = queue.send_message(MessageBody=jobId) # Update the DB entry with sqs message ID for traceability return jobRepo.updateWithMessageId(jobId, response.get('MessageId')) def getJob(event, context): return jobRepo.getJob(event['jobId']) def listDatasources(event, context): return dsRepo.listDatasources() def getDatasource(event, context): return dsRepo.getDatasource(event['datasourceId']) <commit_msg>Add wrapper for event data elem<commit_after>
from __future__ import print_function import boto3 import json import os import btr3baseball jobTable = os.environ['JOB_TABLE'] jobQueue = os.environ['JOB_QUEUE'] queue = boto3.resource('sqs').get_queue_by_name(QueueName=jobQueue) jobRepo = btr3baseball.JobRepository(jobTable) dsRepo = btr3baseball.DatasourceRepository() def main(event, context): method = event['method'] if method == 'submitJob': return submitJob(event['data'], context) elif method == 'getJob': return getJob(event['data'], context) elif method == 'listDatasources': return listDatasources(event['data'], context) elif method == 'getDatasource': return getDatasource(event['data'], context) else: return None def submitJob(event, context): # Put initial entry in dynamo db jobId = jobRepo.createJob(event) # Put the job ID on the SQS queue response = queue.send_message(MessageBody=jobId) # Update the DB entry with sqs message ID for traceability return jobRepo.updateWithMessageId(jobId, response.get('MessageId')) def getJob(event, context): return jobRepo.getJob(event['jobId']) def listDatasources(event, context): return dsRepo.listDatasources() def getDatasource(event, context): return dsRepo.getDatasource(event['datasourceId'])
from __future__ import print_function import boto3 import json import os import btr3baseball jobTable = os.environ['JOB_TABLE'] jobQueue = os.environ['JOB_QUEUE'] queue = boto3.resource('sqs').get_queue_by_name(QueueName=jobQueue) jobRepo = btr3baseball.JobRepository(jobTable) dsRepo = btr3baseball.DatasourceRepository() def main(event, context): method = event['method'] if method == 'submitJob': return submitJob(event, context) elif method == 'getJob': return getJob(event, context) elif method == 'listDatasources': return listDatasources(event, context) elif method == 'getDatasource': return getDatasource(event, context) else: return null def submitJob(event, context): # Put initial entry in dynamo db jobId = jobRepo.createJob(event) # Put the job ID on the SQS queue response = queue.send_message(MessageBody=jobId) # Update the DB entry with sqs message ID for traceability return jobRepo.updateWithMessageId(jobId, response.get('MessageId')) def getJob(event, context): return jobRepo.getJob(event['jobId']) def listDatasources(event, context): return dsRepo.listDatasources() def getDatasource(event, context): return dsRepo.getDatasource(event['datasourceId']) Add wrapper for event data elemfrom __future__ import print_function import boto3 import json import os import btr3baseball jobTable = os.environ['JOB_TABLE'] jobQueue = os.environ['JOB_QUEUE'] queue = boto3.resource('sqs').get_queue_by_name(QueueName=jobQueue) jobRepo = btr3baseball.JobRepository(jobTable) dsRepo = btr3baseball.DatasourceRepository() def main(event, context): method = event['method'] if method == 'submitJob': return submitJob(event['data'], context) elif method == 'getJob': return getJob(event['data'], context) elif method == 'listDatasources': return listDatasources(event['data'], context) elif method == 'getDatasource': return getDatasource(event['data'], context) else: return None def submitJob(event, context): # Put initial entry in dynamo db jobId = jobRepo.createJob(event) # Put the job ID on the SQS queue response = queue.send_message(MessageBody=jobId) # Update the DB entry with sqs message ID for traceability return jobRepo.updateWithMessageId(jobId, response.get('MessageId')) def getJob(event, context): return jobRepo.getJob(event['jobId']) def listDatasources(event, context): return dsRepo.listDatasources() def getDatasource(event, context): return dsRepo.getDatasource(event['datasourceId'])
<commit_before>from __future__ import print_function import boto3 import json import os import btr3baseball jobTable = os.environ['JOB_TABLE'] jobQueue = os.environ['JOB_QUEUE'] queue = boto3.resource('sqs').get_queue_by_name(QueueName=jobQueue) jobRepo = btr3baseball.JobRepository(jobTable) dsRepo = btr3baseball.DatasourceRepository() def main(event, context): method = event['method'] if method == 'submitJob': return submitJob(event, context) elif method == 'getJob': return getJob(event, context) elif method == 'listDatasources': return listDatasources(event, context) elif method == 'getDatasource': return getDatasource(event, context) else: return null def submitJob(event, context): # Put initial entry in dynamo db jobId = jobRepo.createJob(event) # Put the job ID on the SQS queue response = queue.send_message(MessageBody=jobId) # Update the DB entry with sqs message ID for traceability return jobRepo.updateWithMessageId(jobId, response.get('MessageId')) def getJob(event, context): return jobRepo.getJob(event['jobId']) def listDatasources(event, context): return dsRepo.listDatasources() def getDatasource(event, context): return dsRepo.getDatasource(event['datasourceId']) <commit_msg>Add wrapper for event data elem<commit_after>from __future__ import print_function import boto3 import json import os import btr3baseball jobTable = os.environ['JOB_TABLE'] jobQueue = os.environ['JOB_QUEUE'] queue = boto3.resource('sqs').get_queue_by_name(QueueName=jobQueue) jobRepo = btr3baseball.JobRepository(jobTable) dsRepo = btr3baseball.DatasourceRepository() def main(event, context): method = event['method'] if method == 'submitJob': return submitJob(event['data'], context) elif method == 'getJob': return getJob(event['data'], context) elif method == 'listDatasources': return listDatasources(event['data'], context) elif method == 'getDatasource': return getDatasource(event['data'], context) else: return None def submitJob(event, context): # Put initial entry in dynamo db jobId = jobRepo.createJob(event) # Put the job ID on the SQS queue response = queue.send_message(MessageBody=jobId) # Update the DB entry with sqs message ID for traceability return jobRepo.updateWithMessageId(jobId, response.get('MessageId')) def getJob(event, context): return jobRepo.getJob(event['jobId']) def listDatasources(event, context): return dsRepo.listDatasources() def getDatasource(event, context): return dsRepo.getDatasource(event['datasourceId'])
d1911215a0c7043c5011da55707f6a40938c7d59
alarme/extras/sensor/web/views/home.py
alarme/extras/sensor/web/views/home.py
from aiohttp.web import HTTPFound from .core import CoreView from ..util import login_required, handle_exception class Home(CoreView): @login_required async def req(self): return HTTPFound(self.request.app.router.get('control').url()) @handle_exception async def get(self): self.sensor.app.stop() return await self.req() @handle_exception async def post(self): return await self.req()
from aiohttp.web import HTTPFound from .core import CoreView from ..util import login_required, handle_exception class Home(CoreView): @login_required async def req(self): return HTTPFound(self.request.app.router.get('control').url()) @handle_exception async def get(self): return await self.req() @handle_exception async def post(self): return await self.req()
Remove debug app exit on / access (web sensor)
Remove debug app exit on / access (web sensor)
Python
mit
insolite/alarme,insolite/alarme,insolite/alarme
from aiohttp.web import HTTPFound from .core import CoreView from ..util import login_required, handle_exception class Home(CoreView): @login_required async def req(self): return HTTPFound(self.request.app.router.get('control').url()) @handle_exception async def get(self): self.sensor.app.stop() return await self.req() @handle_exception async def post(self): return await self.req() Remove debug app exit on / access (web sensor)
from aiohttp.web import HTTPFound from .core import CoreView from ..util import login_required, handle_exception class Home(CoreView): @login_required async def req(self): return HTTPFound(self.request.app.router.get('control').url()) @handle_exception async def get(self): return await self.req() @handle_exception async def post(self): return await self.req()
<commit_before>from aiohttp.web import HTTPFound from .core import CoreView from ..util import login_required, handle_exception class Home(CoreView): @login_required async def req(self): return HTTPFound(self.request.app.router.get('control').url()) @handle_exception async def get(self): self.sensor.app.stop() return await self.req() @handle_exception async def post(self): return await self.req() <commit_msg>Remove debug app exit on / access (web sensor)<commit_after>
from aiohttp.web import HTTPFound from .core import CoreView from ..util import login_required, handle_exception class Home(CoreView): @login_required async def req(self): return HTTPFound(self.request.app.router.get('control').url()) @handle_exception async def get(self): return await self.req() @handle_exception async def post(self): return await self.req()
from aiohttp.web import HTTPFound from .core import CoreView from ..util import login_required, handle_exception class Home(CoreView): @login_required async def req(self): return HTTPFound(self.request.app.router.get('control').url()) @handle_exception async def get(self): self.sensor.app.stop() return await self.req() @handle_exception async def post(self): return await self.req() Remove debug app exit on / access (web sensor)from aiohttp.web import HTTPFound from .core import CoreView from ..util import login_required, handle_exception class Home(CoreView): @login_required async def req(self): return HTTPFound(self.request.app.router.get('control').url()) @handle_exception async def get(self): return await self.req() @handle_exception async def post(self): return await self.req()
<commit_before>from aiohttp.web import HTTPFound from .core import CoreView from ..util import login_required, handle_exception class Home(CoreView): @login_required async def req(self): return HTTPFound(self.request.app.router.get('control').url()) @handle_exception async def get(self): self.sensor.app.stop() return await self.req() @handle_exception async def post(self): return await self.req() <commit_msg>Remove debug app exit on / access (web sensor)<commit_after>from aiohttp.web import HTTPFound from .core import CoreView from ..util import login_required, handle_exception class Home(CoreView): @login_required async def req(self): return HTTPFound(self.request.app.router.get('control').url()) @handle_exception async def get(self): return await self.req() @handle_exception async def post(self): return await self.req()
41deccb4cde9d553db021f1da90759b4b1b14665
picaxe/urls.py
picaxe/urls.py
from django.conf.urls import patterns, include, url from django.contrib import admin urlpatterns = patterns('', # Examples: # url(r'^$', 'picaxe.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'photologue/', include('photologue.urls', namespace='photologue')), )
from django.conf.urls import patterns, include, url from django.contrib import admin from django.contrib.sites.models import Site urlpatterns = patterns('', # Examples: # url(r'^$', 'picaxe.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'photologue/', include('photologue.urls', namespace='photologue')), ) admin.site.unregister(Site)
Remove django.contrib.sites from admin interface
Remove django.contrib.sites from admin interface
Python
mit
TuinfeesT/PicAxe
from django.conf.urls import patterns, include, url from django.contrib import admin urlpatterns = patterns('', # Examples: # url(r'^$', 'picaxe.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'photologue/', include('photologue.urls', namespace='photologue')), ) Remove django.contrib.sites from admin interface
from django.conf.urls import patterns, include, url from django.contrib import admin from django.contrib.sites.models import Site urlpatterns = patterns('', # Examples: # url(r'^$', 'picaxe.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'photologue/', include('photologue.urls', namespace='photologue')), ) admin.site.unregister(Site)
<commit_before>from django.conf.urls import patterns, include, url from django.contrib import admin urlpatterns = patterns('', # Examples: # url(r'^$', 'picaxe.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'photologue/', include('photologue.urls', namespace='photologue')), ) <commit_msg>Remove django.contrib.sites from admin interface<commit_after>
from django.conf.urls import patterns, include, url from django.contrib import admin from django.contrib.sites.models import Site urlpatterns = patterns('', # Examples: # url(r'^$', 'picaxe.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'photologue/', include('photologue.urls', namespace='photologue')), ) admin.site.unregister(Site)
from django.conf.urls import patterns, include, url from django.contrib import admin urlpatterns = patterns('', # Examples: # url(r'^$', 'picaxe.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'photologue/', include('photologue.urls', namespace='photologue')), ) Remove django.contrib.sites from admin interfacefrom django.conf.urls import patterns, include, url from django.contrib import admin from django.contrib.sites.models import Site urlpatterns = patterns('', # Examples: # url(r'^$', 'picaxe.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'photologue/', include('photologue.urls', namespace='photologue')), ) admin.site.unregister(Site)
<commit_before>from django.conf.urls import patterns, include, url from django.contrib import admin urlpatterns = patterns('', # Examples: # url(r'^$', 'picaxe.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'photologue/', include('photologue.urls', namespace='photologue')), ) <commit_msg>Remove django.contrib.sites from admin interface<commit_after>from django.conf.urls import patterns, include, url from django.contrib import admin from django.contrib.sites.models import Site urlpatterns = patterns('', # Examples: # url(r'^$', 'picaxe.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'photologue/', include('photologue.urls', namespace='photologue')), ) admin.site.unregister(Site)
3bf64037a2b8da9704a7da2f1546b6e5e0a3c78e
panoptes_client/avatar.py
panoptes_client/avatar.py
from panoptes_client.panoptes import ( Panoptes, PanoptesAPIException, PanoptesObject, LinkResolver, ) from panoptes_client.project import Project class Avatar(PanoptesObject): _api_slug = 'avatar' _link_slug = 'avatars' _edit_attributes = () @classmethod def http_get(cls, path, params={}, headers={}): project = params.pop('project') # print() # print(Project.url(project.id)) # print() avatar_response = Panoptes.client().get( Project.url(project.id) + cls.url(path), params, headers, ) print(avatar_response.raw) return avatar_response LinkResolver.register(Avatar) LinkResolver.register(Avatar, 'avatar')
from panoptes_client.panoptes import ( Panoptes, PanoptesAPIException, PanoptesObject, LinkResolver, ) from panoptes_client.project import Project class Avatar(PanoptesObject): _api_slug = 'avatar' _link_slug = 'avatars' _edit_attributes = () @classmethod def http_get(cls, path, params={}, headers={}): project = params.pop('project') # print() # print(Project.url(project.id)) # print() avatar_response = Panoptes.client().get( Project.url(project.id) + cls.url(path), params, headers, ) print(avatar_response.raw) return avatar_response LinkResolver.register(Avatar) LinkResolver.register(Avatar, 'avatar')
Add blank lines according to hound
Add blank lines according to hound
Python
apache-2.0
zooniverse/panoptes-python-client
from panoptes_client.panoptes import ( Panoptes, PanoptesAPIException, PanoptesObject, LinkResolver, ) from panoptes_client.project import Project class Avatar(PanoptesObject): _api_slug = 'avatar' _link_slug = 'avatars' _edit_attributes = () @classmethod def http_get(cls, path, params={}, headers={}): project = params.pop('project') # print() # print(Project.url(project.id)) # print() avatar_response = Panoptes.client().get( Project.url(project.id) + cls.url(path), params, headers, ) print(avatar_response.raw) return avatar_response LinkResolver.register(Avatar) LinkResolver.register(Avatar, 'avatar') Add blank lines according to hound
from panoptes_client.panoptes import ( Panoptes, PanoptesAPIException, PanoptesObject, LinkResolver, ) from panoptes_client.project import Project class Avatar(PanoptesObject): _api_slug = 'avatar' _link_slug = 'avatars' _edit_attributes = () @classmethod def http_get(cls, path, params={}, headers={}): project = params.pop('project') # print() # print(Project.url(project.id)) # print() avatar_response = Panoptes.client().get( Project.url(project.id) + cls.url(path), params, headers, ) print(avatar_response.raw) return avatar_response LinkResolver.register(Avatar) LinkResolver.register(Avatar, 'avatar')
<commit_before>from panoptes_client.panoptes import ( Panoptes, PanoptesAPIException, PanoptesObject, LinkResolver, ) from panoptes_client.project import Project class Avatar(PanoptesObject): _api_slug = 'avatar' _link_slug = 'avatars' _edit_attributes = () @classmethod def http_get(cls, path, params={}, headers={}): project = params.pop('project') # print() # print(Project.url(project.id)) # print() avatar_response = Panoptes.client().get( Project.url(project.id) + cls.url(path), params, headers, ) print(avatar_response.raw) return avatar_response LinkResolver.register(Avatar) LinkResolver.register(Avatar, 'avatar') <commit_msg>Add blank lines according to hound<commit_after>
from panoptes_client.panoptes import ( Panoptes, PanoptesAPIException, PanoptesObject, LinkResolver, ) from panoptes_client.project import Project class Avatar(PanoptesObject): _api_slug = 'avatar' _link_slug = 'avatars' _edit_attributes = () @classmethod def http_get(cls, path, params={}, headers={}): project = params.pop('project') # print() # print(Project.url(project.id)) # print() avatar_response = Panoptes.client().get( Project.url(project.id) + cls.url(path), params, headers, ) print(avatar_response.raw) return avatar_response LinkResolver.register(Avatar) LinkResolver.register(Avatar, 'avatar')
from panoptes_client.panoptes import ( Panoptes, PanoptesAPIException, PanoptesObject, LinkResolver, ) from panoptes_client.project import Project class Avatar(PanoptesObject): _api_slug = 'avatar' _link_slug = 'avatars' _edit_attributes = () @classmethod def http_get(cls, path, params={}, headers={}): project = params.pop('project') # print() # print(Project.url(project.id)) # print() avatar_response = Panoptes.client().get( Project.url(project.id) + cls.url(path), params, headers, ) print(avatar_response.raw) return avatar_response LinkResolver.register(Avatar) LinkResolver.register(Avatar, 'avatar') Add blank lines according to houndfrom panoptes_client.panoptes import ( Panoptes, PanoptesAPIException, PanoptesObject, LinkResolver, ) from panoptes_client.project import Project class Avatar(PanoptesObject): _api_slug = 'avatar' _link_slug = 'avatars' _edit_attributes = () @classmethod def http_get(cls, path, params={}, headers={}): project = params.pop('project') # print() # print(Project.url(project.id)) # print() avatar_response = Panoptes.client().get( Project.url(project.id) + cls.url(path), params, headers, ) print(avatar_response.raw) return avatar_response LinkResolver.register(Avatar) LinkResolver.register(Avatar, 'avatar')
<commit_before>from panoptes_client.panoptes import ( Panoptes, PanoptesAPIException, PanoptesObject, LinkResolver, ) from panoptes_client.project import Project class Avatar(PanoptesObject): _api_slug = 'avatar' _link_slug = 'avatars' _edit_attributes = () @classmethod def http_get(cls, path, params={}, headers={}): project = params.pop('project') # print() # print(Project.url(project.id)) # print() avatar_response = Panoptes.client().get( Project.url(project.id) + cls.url(path), params, headers, ) print(avatar_response.raw) return avatar_response LinkResolver.register(Avatar) LinkResolver.register(Avatar, 'avatar') <commit_msg>Add blank lines according to hound<commit_after>from panoptes_client.panoptes import ( Panoptes, PanoptesAPIException, PanoptesObject, LinkResolver, ) from panoptes_client.project import Project class Avatar(PanoptesObject): _api_slug = 'avatar' _link_slug = 'avatars' _edit_attributes = () @classmethod def http_get(cls, path, params={}, headers={}): project = params.pop('project') # print() # print(Project.url(project.id)) # print() avatar_response = Panoptes.client().get( Project.url(project.id) + cls.url(path), params, headers, ) print(avatar_response.raw) return avatar_response LinkResolver.register(Avatar) LinkResolver.register(Avatar, 'avatar')
32cdc4fa334f3d415c0ce8f4fa37fa7d4c721915
fabfile.py
fabfile.py
import os from fabric.api import task, run, local, sudo, cd, env env.hosts = [ os.environ['TWWEB_HOST'], ] def virtualenv(command, user=None): run('source /var/www/envs/twweb/bin/activate && ' + command) @task def deploy(): local('git push origin development') local('git checkout master') local('git merge development') local('git push origin master') with cd('/var/www/twweb'): run('git fetch origin') run('git merge origin/master') run('npm install') run('grunt ember_handlebars sass browserify uglify') virtualenv('pip install -r /var/www/twweb/requirements.txt') virtualenv('python manage.py collectstatic --noinput') virtualenv('python manage.py migrate') sudo('/bin/chown -R www-data:www-data /var/www/twweb/logs/') sudo('/usr/sbin/service twweb restart', shell=False) sudo('/usr/sbin/service twweb-status restart', shell=False) sudo('/usr/sbin/service twweb-celery restart', shell=False) local('git checkout development')
import os from fabric.api import task, run, local, sudo, cd, env env.hosts = [ os.environ['TWWEB_HOST'], ] def virtualenv(command, user=None): run('source /var/www/envs/twweb/bin/activate && ' + command) @task def deploy(): local('git push origin development') local('git checkout master') local('git merge development') local('git push origin master') with cd('/var/www/twweb'): run('git fetch origin') run('git merge origin/master') run('npm install') run('grunt ember_handlebars sass browserify uglify') virtualenv('pip install -r /var/www/twweb/requirements.txt') virtualenv('python manage.py collectstatic --noinput') virtualenv('python manage.py migrate') sudo('/bin/chown -R www-data:www-data /var/www/twweb/logs/', shell=False) sudo('/usr/sbin/service twweb restart', shell=False) sudo('/usr/sbin/service twweb-status restart', shell=False) sudo('/usr/sbin/service twweb-celery restart', shell=False) local('git checkout development')
Use shell=False when chowning logs folder.
Use shell=False when chowning logs folder.
Python
agpl-3.0
coddingtonbear/inthe.am,coddingtonbear/inthe.am,coddingtonbear/inthe.am,coddingtonbear/inthe.am,coddingtonbear/inthe.am
import os from fabric.api import task, run, local, sudo, cd, env env.hosts = [ os.environ['TWWEB_HOST'], ] def virtualenv(command, user=None): run('source /var/www/envs/twweb/bin/activate && ' + command) @task def deploy(): local('git push origin development') local('git checkout master') local('git merge development') local('git push origin master') with cd('/var/www/twweb'): run('git fetch origin') run('git merge origin/master') run('npm install') run('grunt ember_handlebars sass browserify uglify') virtualenv('pip install -r /var/www/twweb/requirements.txt') virtualenv('python manage.py collectstatic --noinput') virtualenv('python manage.py migrate') sudo('/bin/chown -R www-data:www-data /var/www/twweb/logs/') sudo('/usr/sbin/service twweb restart', shell=False) sudo('/usr/sbin/service twweb-status restart', shell=False) sudo('/usr/sbin/service twweb-celery restart', shell=False) local('git checkout development') Use shell=False when chowning logs folder.
import os from fabric.api import task, run, local, sudo, cd, env env.hosts = [ os.environ['TWWEB_HOST'], ] def virtualenv(command, user=None): run('source /var/www/envs/twweb/bin/activate && ' + command) @task def deploy(): local('git push origin development') local('git checkout master') local('git merge development') local('git push origin master') with cd('/var/www/twweb'): run('git fetch origin') run('git merge origin/master') run('npm install') run('grunt ember_handlebars sass browserify uglify') virtualenv('pip install -r /var/www/twweb/requirements.txt') virtualenv('python manage.py collectstatic --noinput') virtualenv('python manage.py migrate') sudo('/bin/chown -R www-data:www-data /var/www/twweb/logs/', shell=False) sudo('/usr/sbin/service twweb restart', shell=False) sudo('/usr/sbin/service twweb-status restart', shell=False) sudo('/usr/sbin/service twweb-celery restart', shell=False) local('git checkout development')
<commit_before>import os from fabric.api import task, run, local, sudo, cd, env env.hosts = [ os.environ['TWWEB_HOST'], ] def virtualenv(command, user=None): run('source /var/www/envs/twweb/bin/activate && ' + command) @task def deploy(): local('git push origin development') local('git checkout master') local('git merge development') local('git push origin master') with cd('/var/www/twweb'): run('git fetch origin') run('git merge origin/master') run('npm install') run('grunt ember_handlebars sass browserify uglify') virtualenv('pip install -r /var/www/twweb/requirements.txt') virtualenv('python manage.py collectstatic --noinput') virtualenv('python manage.py migrate') sudo('/bin/chown -R www-data:www-data /var/www/twweb/logs/') sudo('/usr/sbin/service twweb restart', shell=False) sudo('/usr/sbin/service twweb-status restart', shell=False) sudo('/usr/sbin/service twweb-celery restart', shell=False) local('git checkout development') <commit_msg>Use shell=False when chowning logs folder.<commit_after>
import os from fabric.api import task, run, local, sudo, cd, env env.hosts = [ os.environ['TWWEB_HOST'], ] def virtualenv(command, user=None): run('source /var/www/envs/twweb/bin/activate && ' + command) @task def deploy(): local('git push origin development') local('git checkout master') local('git merge development') local('git push origin master') with cd('/var/www/twweb'): run('git fetch origin') run('git merge origin/master') run('npm install') run('grunt ember_handlebars sass browserify uglify') virtualenv('pip install -r /var/www/twweb/requirements.txt') virtualenv('python manage.py collectstatic --noinput') virtualenv('python manage.py migrate') sudo('/bin/chown -R www-data:www-data /var/www/twweb/logs/', shell=False) sudo('/usr/sbin/service twweb restart', shell=False) sudo('/usr/sbin/service twweb-status restart', shell=False) sudo('/usr/sbin/service twweb-celery restart', shell=False) local('git checkout development')
import os from fabric.api import task, run, local, sudo, cd, env env.hosts = [ os.environ['TWWEB_HOST'], ] def virtualenv(command, user=None): run('source /var/www/envs/twweb/bin/activate && ' + command) @task def deploy(): local('git push origin development') local('git checkout master') local('git merge development') local('git push origin master') with cd('/var/www/twweb'): run('git fetch origin') run('git merge origin/master') run('npm install') run('grunt ember_handlebars sass browserify uglify') virtualenv('pip install -r /var/www/twweb/requirements.txt') virtualenv('python manage.py collectstatic --noinput') virtualenv('python manage.py migrate') sudo('/bin/chown -R www-data:www-data /var/www/twweb/logs/') sudo('/usr/sbin/service twweb restart', shell=False) sudo('/usr/sbin/service twweb-status restart', shell=False) sudo('/usr/sbin/service twweb-celery restart', shell=False) local('git checkout development') Use shell=False when chowning logs folder.import os from fabric.api import task, run, local, sudo, cd, env env.hosts = [ os.environ['TWWEB_HOST'], ] def virtualenv(command, user=None): run('source /var/www/envs/twweb/bin/activate && ' + command) @task def deploy(): local('git push origin development') local('git checkout master') local('git merge development') local('git push origin master') with cd('/var/www/twweb'): run('git fetch origin') run('git merge origin/master') run('npm install') run('grunt ember_handlebars sass browserify uglify') virtualenv('pip install -r /var/www/twweb/requirements.txt') virtualenv('python manage.py collectstatic --noinput') virtualenv('python manage.py migrate') sudo('/bin/chown -R www-data:www-data /var/www/twweb/logs/', shell=False) sudo('/usr/sbin/service twweb restart', shell=False) sudo('/usr/sbin/service twweb-status restart', shell=False) sudo('/usr/sbin/service twweb-celery restart', shell=False) local('git checkout development')
<commit_before>import os from fabric.api import task, run, local, sudo, cd, env env.hosts = [ os.environ['TWWEB_HOST'], ] def virtualenv(command, user=None): run('source /var/www/envs/twweb/bin/activate && ' + command) @task def deploy(): local('git push origin development') local('git checkout master') local('git merge development') local('git push origin master') with cd('/var/www/twweb'): run('git fetch origin') run('git merge origin/master') run('npm install') run('grunt ember_handlebars sass browserify uglify') virtualenv('pip install -r /var/www/twweb/requirements.txt') virtualenv('python manage.py collectstatic --noinput') virtualenv('python manage.py migrate') sudo('/bin/chown -R www-data:www-data /var/www/twweb/logs/') sudo('/usr/sbin/service twweb restart', shell=False) sudo('/usr/sbin/service twweb-status restart', shell=False) sudo('/usr/sbin/service twweb-celery restart', shell=False) local('git checkout development') <commit_msg>Use shell=False when chowning logs folder.<commit_after>import os from fabric.api import task, run, local, sudo, cd, env env.hosts = [ os.environ['TWWEB_HOST'], ] def virtualenv(command, user=None): run('source /var/www/envs/twweb/bin/activate && ' + command) @task def deploy(): local('git push origin development') local('git checkout master') local('git merge development') local('git push origin master') with cd('/var/www/twweb'): run('git fetch origin') run('git merge origin/master') run('npm install') run('grunt ember_handlebars sass browserify uglify') virtualenv('pip install -r /var/www/twweb/requirements.txt') virtualenv('python manage.py collectstatic --noinput') virtualenv('python manage.py migrate') sudo('/bin/chown -R www-data:www-data /var/www/twweb/logs/', shell=False) sudo('/usr/sbin/service twweb restart', shell=False) sudo('/usr/sbin/service twweb-status restart', shell=False) sudo('/usr/sbin/service twweb-celery restart', shell=False) local('git checkout development')