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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9c0d1f252bad1837545fa848c39786a98e6fd0ea
|
setup.py
|
setup.py
|
from distutils.core import setup
setup(
name='xirvik-tools',
version='0.0.1',
author='Fa An',
author_email='2998784916@qq.com',
packages=['xirvik'],
url='https://faan/xirvik-tools',
license='LICENSE.txt',
description='Xirvik (ruTorrent mostly) tools.',
long_description=open('README.rst').read(),
scripts=['bin/xirvik-mirror', 'bin/xirvik-start-torrents'],
install_requires=[
'cached-property>=1.0.0',
'OSExtension>=0.1.5',
'requests>=2.6.0',
'sh>=1.09',
],
)
|
from distutils.core import setup
setup(
name='xirvik-tools',
version='0.0.2',
author='Fa An',
author_email='2998784916@qq.com',
packages=['xirvik', 'xirvik.client'],
url='https://faan/xirvik-tools',
license='LICENSE.txt',
description='Xirvik (ruTorrent mostly) tools.',
long_description=open('README.rst').read(),
scripts=['bin/xirvik-mirror', 'bin/xirvik-start-torrents'],
install_requires=[
'cached-property>=1.0.0',
'OSExtension>=0.1.5',
'requests>=2.6.0',
'sh>=1.09',
],
)
|
Add client part of package
|
Add client part of package
|
Python
|
mit
|
Tatsh/xirvik-tools
|
from distutils.core import setup
setup(
name='xirvik-tools',
version='0.0.1',
author='Fa An',
author_email='2998784916@qq.com',
packages=['xirvik'],
url='https://faan/xirvik-tools',
license='LICENSE.txt',
description='Xirvik (ruTorrent mostly) tools.',
long_description=open('README.rst').read(),
scripts=['bin/xirvik-mirror', 'bin/xirvik-start-torrents'],
install_requires=[
'cached-property>=1.0.0',
'OSExtension>=0.1.5',
'requests>=2.6.0',
'sh>=1.09',
],
)
Add client part of package
|
from distutils.core import setup
setup(
name='xirvik-tools',
version='0.0.2',
author='Fa An',
author_email='2998784916@qq.com',
packages=['xirvik', 'xirvik.client'],
url='https://faan/xirvik-tools',
license='LICENSE.txt',
description='Xirvik (ruTorrent mostly) tools.',
long_description=open('README.rst').read(),
scripts=['bin/xirvik-mirror', 'bin/xirvik-start-torrents'],
install_requires=[
'cached-property>=1.0.0',
'OSExtension>=0.1.5',
'requests>=2.6.0',
'sh>=1.09',
],
)
|
<commit_before>from distutils.core import setup
setup(
name='xirvik-tools',
version='0.0.1',
author='Fa An',
author_email='2998784916@qq.com',
packages=['xirvik'],
url='https://faan/xirvik-tools',
license='LICENSE.txt',
description='Xirvik (ruTorrent mostly) tools.',
long_description=open('README.rst').read(),
scripts=['bin/xirvik-mirror', 'bin/xirvik-start-torrents'],
install_requires=[
'cached-property>=1.0.0',
'OSExtension>=0.1.5',
'requests>=2.6.0',
'sh>=1.09',
],
)
<commit_msg>Add client part of package<commit_after>
|
from distutils.core import setup
setup(
name='xirvik-tools',
version='0.0.2',
author='Fa An',
author_email='2998784916@qq.com',
packages=['xirvik', 'xirvik.client'],
url='https://faan/xirvik-tools',
license='LICENSE.txt',
description='Xirvik (ruTorrent mostly) tools.',
long_description=open('README.rst').read(),
scripts=['bin/xirvik-mirror', 'bin/xirvik-start-torrents'],
install_requires=[
'cached-property>=1.0.0',
'OSExtension>=0.1.5',
'requests>=2.6.0',
'sh>=1.09',
],
)
|
from distutils.core import setup
setup(
name='xirvik-tools',
version='0.0.1',
author='Fa An',
author_email='2998784916@qq.com',
packages=['xirvik'],
url='https://faan/xirvik-tools',
license='LICENSE.txt',
description='Xirvik (ruTorrent mostly) tools.',
long_description=open('README.rst').read(),
scripts=['bin/xirvik-mirror', 'bin/xirvik-start-torrents'],
install_requires=[
'cached-property>=1.0.0',
'OSExtension>=0.1.5',
'requests>=2.6.0',
'sh>=1.09',
],
)
Add client part of packagefrom distutils.core import setup
setup(
name='xirvik-tools',
version='0.0.2',
author='Fa An',
author_email='2998784916@qq.com',
packages=['xirvik', 'xirvik.client'],
url='https://faan/xirvik-tools',
license='LICENSE.txt',
description='Xirvik (ruTorrent mostly) tools.',
long_description=open('README.rst').read(),
scripts=['bin/xirvik-mirror', 'bin/xirvik-start-torrents'],
install_requires=[
'cached-property>=1.0.0',
'OSExtension>=0.1.5',
'requests>=2.6.0',
'sh>=1.09',
],
)
|
<commit_before>from distutils.core import setup
setup(
name='xirvik-tools',
version='0.0.1',
author='Fa An',
author_email='2998784916@qq.com',
packages=['xirvik'],
url='https://faan/xirvik-tools',
license='LICENSE.txt',
description='Xirvik (ruTorrent mostly) tools.',
long_description=open('README.rst').read(),
scripts=['bin/xirvik-mirror', 'bin/xirvik-start-torrents'],
install_requires=[
'cached-property>=1.0.0',
'OSExtension>=0.1.5',
'requests>=2.6.0',
'sh>=1.09',
],
)
<commit_msg>Add client part of package<commit_after>from distutils.core import setup
setup(
name='xirvik-tools',
version='0.0.2',
author='Fa An',
author_email='2998784916@qq.com',
packages=['xirvik', 'xirvik.client'],
url='https://faan/xirvik-tools',
license='LICENSE.txt',
description='Xirvik (ruTorrent mostly) tools.',
long_description=open('README.rst').read(),
scripts=['bin/xirvik-mirror', 'bin/xirvik-start-torrents'],
install_requires=[
'cached-property>=1.0.0',
'OSExtension>=0.1.5',
'requests>=2.6.0',
'sh>=1.09',
],
)
|
6ef5da6a4fc0eb54b575cfbc2dcebcbbe755db25
|
setup.py
|
setup.py
|
import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='mezzanine-sermons',
version='0.1.0',
packages=['mezzanine_sermons'],
include_package_data=True,
license='BSD License',
description='A simple mezzanine app which facilitates the management and playing of sermons',
long_description=README,
url='https://github.com/philipsouthwell/mezzanine-sermons',
author='Philip Southwell',
author_email='phil@zoothink.com',
keywords=['django', 'mezzanine'],
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
|
import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='mezzanine-sermons',
version='0.1.1',
packages=['mezzanine_sermons'],
include_package_data=True,
license='BSD License',
description='A simple mezzanine app which facilitates the management and playing of sermons',
long_description=README,
url='https://github.com/philipsouthwell/mezzanine-sermons',
author='Philip Southwell',
author_email='phil@zoothink.com',
keywords=['django', 'mezzanine'],
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
|
Change version number for release
|
Change version number for release
|
Python
|
bsd-2-clause
|
philipsouthwell/mezzanine-sermons,philipsouthwell/mezzanine-sermons
|
import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='mezzanine-sermons',
version='0.1.0',
packages=['mezzanine_sermons'],
include_package_data=True,
license='BSD License',
description='A simple mezzanine app which facilitates the management and playing of sermons',
long_description=README,
url='https://github.com/philipsouthwell/mezzanine-sermons',
author='Philip Southwell',
author_email='phil@zoothink.com',
keywords=['django', 'mezzanine'],
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
Change version number for release
|
import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='mezzanine-sermons',
version='0.1.1',
packages=['mezzanine_sermons'],
include_package_data=True,
license='BSD License',
description='A simple mezzanine app which facilitates the management and playing of sermons',
long_description=README,
url='https://github.com/philipsouthwell/mezzanine-sermons',
author='Philip Southwell',
author_email='phil@zoothink.com',
keywords=['django', 'mezzanine'],
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
|
<commit_before>import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='mezzanine-sermons',
version='0.1.0',
packages=['mezzanine_sermons'],
include_package_data=True,
license='BSD License',
description='A simple mezzanine app which facilitates the management and playing of sermons',
long_description=README,
url='https://github.com/philipsouthwell/mezzanine-sermons',
author='Philip Southwell',
author_email='phil@zoothink.com',
keywords=['django', 'mezzanine'],
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
<commit_msg>Change version number for release<commit_after>
|
import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='mezzanine-sermons',
version='0.1.1',
packages=['mezzanine_sermons'],
include_package_data=True,
license='BSD License',
description='A simple mezzanine app which facilitates the management and playing of sermons',
long_description=README,
url='https://github.com/philipsouthwell/mezzanine-sermons',
author='Philip Southwell',
author_email='phil@zoothink.com',
keywords=['django', 'mezzanine'],
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
|
import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='mezzanine-sermons',
version='0.1.0',
packages=['mezzanine_sermons'],
include_package_data=True,
license='BSD License',
description='A simple mezzanine app which facilitates the management and playing of sermons',
long_description=README,
url='https://github.com/philipsouthwell/mezzanine-sermons',
author='Philip Southwell',
author_email='phil@zoothink.com',
keywords=['django', 'mezzanine'],
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
Change version number for releaseimport os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='mezzanine-sermons',
version='0.1.1',
packages=['mezzanine_sermons'],
include_package_data=True,
license='BSD License',
description='A simple mezzanine app which facilitates the management and playing of sermons',
long_description=README,
url='https://github.com/philipsouthwell/mezzanine-sermons',
author='Philip Southwell',
author_email='phil@zoothink.com',
keywords=['django', 'mezzanine'],
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
|
<commit_before>import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='mezzanine-sermons',
version='0.1.0',
packages=['mezzanine_sermons'],
include_package_data=True,
license='BSD License',
description='A simple mezzanine app which facilitates the management and playing of sermons',
long_description=README,
url='https://github.com/philipsouthwell/mezzanine-sermons',
author='Philip Southwell',
author_email='phil@zoothink.com',
keywords=['django', 'mezzanine'],
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
<commit_msg>Change version number for release<commit_after>import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='mezzanine-sermons',
version='0.1.1',
packages=['mezzanine_sermons'],
include_package_data=True,
license='BSD License',
description='A simple mezzanine app which facilitates the management and playing of sermons',
long_description=README,
url='https://github.com/philipsouthwell/mezzanine-sermons',
author='Philip Southwell',
author_email='phil@zoothink.com',
keywords=['django', 'mezzanine'],
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
|
485302db80a519413bbc637ea25fa0f285b0458c
|
setup.py
|
setup.py
|
import re
from setuptools import setup
with open('pytest_mock.py') as f:
m = re.search("version = '(.*)'", f.read())
assert m is not None
version = m.group(1)
setup(
name='pytest-mock',
version=version,
entry_points={
'pytest11': ['pytest_mock = pytest_mock'],
},
py_modules=['pytest_mock'],
platforms='any',
install_requires=[
'pytest>=2.7',
],
extras_require={
':python_version=="2.6" or python_version=="2.7"': ['mock'],
},
url='https://github.com/pytest-dev/pytest-mock/',
license='LGPL',
author='Bruno Oliveira',
author_email='nicoddemus@gmail.com',
description='Thin-wrapper around the mock package for easier use with py.test',
long_description=open('README.rst').read(),
keywords="pytest mock",
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Software Development :: Testing',
]
)
|
import re
from setuptools import setup
with open('pytest_mock.py') as f:
m = re.search("version = '(.*)'", f.read())
assert m is not None
version = m.group(1)
setup(
name='pytest-mock',
version=version,
entry_points={
'pytest11': ['pytest_mock = pytest_mock'],
},
py_modules=['pytest_mock'],
platforms='any',
install_requires=[
'pytest>=2.7',
],
extras_require={
':python_version=="2.6" or python_version=="2.7"': ['mock'],
},
url='https://github.com/pytest-dev/pytest-mock/',
license='LGPL',
author='Bruno Oliveira',
author_email='nicoddemus@gmail.com',
description='Thin-wrapper around the mock package for easier use with py.test',
long_description=open('README.rst').read(),
keywords="pytest mock",
classifiers=[
'Development Status :: 4 - Beta',
'Framework :: Pytest',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Software Development :: Testing',
]
)
|
Add Framework::Pytest to list of classifiers
|
Add Framework::Pytest to list of classifiers
|
Python
|
mit
|
pytest-dev/pytest-mock,asfaltboy/pytest-mock
|
import re
from setuptools import setup
with open('pytest_mock.py') as f:
m = re.search("version = '(.*)'", f.read())
assert m is not None
version = m.group(1)
setup(
name='pytest-mock',
version=version,
entry_points={
'pytest11': ['pytest_mock = pytest_mock'],
},
py_modules=['pytest_mock'],
platforms='any',
install_requires=[
'pytest>=2.7',
],
extras_require={
':python_version=="2.6" or python_version=="2.7"': ['mock'],
},
url='https://github.com/pytest-dev/pytest-mock/',
license='LGPL',
author='Bruno Oliveira',
author_email='nicoddemus@gmail.com',
description='Thin-wrapper around the mock package for easier use with py.test',
long_description=open('README.rst').read(),
keywords="pytest mock",
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Software Development :: Testing',
]
)
Add Framework::Pytest to list of classifiers
|
import re
from setuptools import setup
with open('pytest_mock.py') as f:
m = re.search("version = '(.*)'", f.read())
assert m is not None
version = m.group(1)
setup(
name='pytest-mock',
version=version,
entry_points={
'pytest11': ['pytest_mock = pytest_mock'],
},
py_modules=['pytest_mock'],
platforms='any',
install_requires=[
'pytest>=2.7',
],
extras_require={
':python_version=="2.6" or python_version=="2.7"': ['mock'],
},
url='https://github.com/pytest-dev/pytest-mock/',
license='LGPL',
author='Bruno Oliveira',
author_email='nicoddemus@gmail.com',
description='Thin-wrapper around the mock package for easier use with py.test',
long_description=open('README.rst').read(),
keywords="pytest mock",
classifiers=[
'Development Status :: 4 - Beta',
'Framework :: Pytest',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Software Development :: Testing',
]
)
|
<commit_before>import re
from setuptools import setup
with open('pytest_mock.py') as f:
m = re.search("version = '(.*)'", f.read())
assert m is not None
version = m.group(1)
setup(
name='pytest-mock',
version=version,
entry_points={
'pytest11': ['pytest_mock = pytest_mock'],
},
py_modules=['pytest_mock'],
platforms='any',
install_requires=[
'pytest>=2.7',
],
extras_require={
':python_version=="2.6" or python_version=="2.7"': ['mock'],
},
url='https://github.com/pytest-dev/pytest-mock/',
license='LGPL',
author='Bruno Oliveira',
author_email='nicoddemus@gmail.com',
description='Thin-wrapper around the mock package for easier use with py.test',
long_description=open('README.rst').read(),
keywords="pytest mock",
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Software Development :: Testing',
]
)
<commit_msg>Add Framework::Pytest to list of classifiers<commit_after>
|
import re
from setuptools import setup
with open('pytest_mock.py') as f:
m = re.search("version = '(.*)'", f.read())
assert m is not None
version = m.group(1)
setup(
name='pytest-mock',
version=version,
entry_points={
'pytest11': ['pytest_mock = pytest_mock'],
},
py_modules=['pytest_mock'],
platforms='any',
install_requires=[
'pytest>=2.7',
],
extras_require={
':python_version=="2.6" or python_version=="2.7"': ['mock'],
},
url='https://github.com/pytest-dev/pytest-mock/',
license='LGPL',
author='Bruno Oliveira',
author_email='nicoddemus@gmail.com',
description='Thin-wrapper around the mock package for easier use with py.test',
long_description=open('README.rst').read(),
keywords="pytest mock",
classifiers=[
'Development Status :: 4 - Beta',
'Framework :: Pytest',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Software Development :: Testing',
]
)
|
import re
from setuptools import setup
with open('pytest_mock.py') as f:
m = re.search("version = '(.*)'", f.read())
assert m is not None
version = m.group(1)
setup(
name='pytest-mock',
version=version,
entry_points={
'pytest11': ['pytest_mock = pytest_mock'],
},
py_modules=['pytest_mock'],
platforms='any',
install_requires=[
'pytest>=2.7',
],
extras_require={
':python_version=="2.6" or python_version=="2.7"': ['mock'],
},
url='https://github.com/pytest-dev/pytest-mock/',
license='LGPL',
author='Bruno Oliveira',
author_email='nicoddemus@gmail.com',
description='Thin-wrapper around the mock package for easier use with py.test',
long_description=open('README.rst').read(),
keywords="pytest mock",
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Software Development :: Testing',
]
)
Add Framework::Pytest to list of classifiersimport re
from setuptools import setup
with open('pytest_mock.py') as f:
m = re.search("version = '(.*)'", f.read())
assert m is not None
version = m.group(1)
setup(
name='pytest-mock',
version=version,
entry_points={
'pytest11': ['pytest_mock = pytest_mock'],
},
py_modules=['pytest_mock'],
platforms='any',
install_requires=[
'pytest>=2.7',
],
extras_require={
':python_version=="2.6" or python_version=="2.7"': ['mock'],
},
url='https://github.com/pytest-dev/pytest-mock/',
license='LGPL',
author='Bruno Oliveira',
author_email='nicoddemus@gmail.com',
description='Thin-wrapper around the mock package for easier use with py.test',
long_description=open('README.rst').read(),
keywords="pytest mock",
classifiers=[
'Development Status :: 4 - Beta',
'Framework :: Pytest',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Software Development :: Testing',
]
)
|
<commit_before>import re
from setuptools import setup
with open('pytest_mock.py') as f:
m = re.search("version = '(.*)'", f.read())
assert m is not None
version = m.group(1)
setup(
name='pytest-mock',
version=version,
entry_points={
'pytest11': ['pytest_mock = pytest_mock'],
},
py_modules=['pytest_mock'],
platforms='any',
install_requires=[
'pytest>=2.7',
],
extras_require={
':python_version=="2.6" or python_version=="2.7"': ['mock'],
},
url='https://github.com/pytest-dev/pytest-mock/',
license='LGPL',
author='Bruno Oliveira',
author_email='nicoddemus@gmail.com',
description='Thin-wrapper around the mock package for easier use with py.test',
long_description=open('README.rst').read(),
keywords="pytest mock",
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Software Development :: Testing',
]
)
<commit_msg>Add Framework::Pytest to list of classifiers<commit_after>import re
from setuptools import setup
with open('pytest_mock.py') as f:
m = re.search("version = '(.*)'", f.read())
assert m is not None
version = m.group(1)
setup(
name='pytest-mock',
version=version,
entry_points={
'pytest11': ['pytest_mock = pytest_mock'],
},
py_modules=['pytest_mock'],
platforms='any',
install_requires=[
'pytest>=2.7',
],
extras_require={
':python_version=="2.6" or python_version=="2.7"': ['mock'],
},
url='https://github.com/pytest-dev/pytest-mock/',
license='LGPL',
author='Bruno Oliveira',
author_email='nicoddemus@gmail.com',
description='Thin-wrapper around the mock package for easier use with py.test',
long_description=open('README.rst').read(),
keywords="pytest mock",
classifiers=[
'Development Status :: 4 - Beta',
'Framework :: Pytest',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Software Development :: Testing',
]
)
|
c94b2bf4a438e0eb284d9aaa31d38f145631ada4
|
setup.py
|
setup.py
|
from setuptools import setup, find_packages
setup(
name = 'AtomSeeker',
version = '0.0.1',
description = 'Analyzer for MP4/MOV format file',
packages = find_packages(),
author = 'Katsuki Kobayashi',
author_email = 'rare@tirasweel.org',
license = 'BSD 2-Clause License',
entry_points = """
[console_scripts]
atomseek = atomseeker.cmdline:main
""",
)
|
from setuptools import setup, find_packages
setup(
name='AtomSeeker',
version='0.0.1',
description='Analyzer for MP4/MOV format file',
packages=find_packages(),
author='Katsuki Kobayashi',
author_email='rare@tirasweel.org',
license='BSD 2-Clause License',
entry_points="""
[console_scripts]
atomseek = atomseeker.cmdline:main
""",
)
|
Remove spaces around `=` operator
|
Remove spaces around `=` operator
|
Python
|
bsd-2-clause
|
rarewin/AtomSeeker,rarewin/AtomSeeker
|
from setuptools import setup, find_packages
setup(
name = 'AtomSeeker',
version = '0.0.1',
description = 'Analyzer for MP4/MOV format file',
packages = find_packages(),
author = 'Katsuki Kobayashi',
author_email = 'rare@tirasweel.org',
license = 'BSD 2-Clause License',
entry_points = """
[console_scripts]
atomseek = atomseeker.cmdline:main
""",
)
Remove spaces around `=` operator
|
from setuptools import setup, find_packages
setup(
name='AtomSeeker',
version='0.0.1',
description='Analyzer for MP4/MOV format file',
packages=find_packages(),
author='Katsuki Kobayashi',
author_email='rare@tirasweel.org',
license='BSD 2-Clause License',
entry_points="""
[console_scripts]
atomseek = atomseeker.cmdline:main
""",
)
|
<commit_before>from setuptools import setup, find_packages
setup(
name = 'AtomSeeker',
version = '0.0.1',
description = 'Analyzer for MP4/MOV format file',
packages = find_packages(),
author = 'Katsuki Kobayashi',
author_email = 'rare@tirasweel.org',
license = 'BSD 2-Clause License',
entry_points = """
[console_scripts]
atomseek = atomseeker.cmdline:main
""",
)
<commit_msg>Remove spaces around `=` operator<commit_after>
|
from setuptools import setup, find_packages
setup(
name='AtomSeeker',
version='0.0.1',
description='Analyzer for MP4/MOV format file',
packages=find_packages(),
author='Katsuki Kobayashi',
author_email='rare@tirasweel.org',
license='BSD 2-Clause License',
entry_points="""
[console_scripts]
atomseek = atomseeker.cmdline:main
""",
)
|
from setuptools import setup, find_packages
setup(
name = 'AtomSeeker',
version = '0.0.1',
description = 'Analyzer for MP4/MOV format file',
packages = find_packages(),
author = 'Katsuki Kobayashi',
author_email = 'rare@tirasweel.org',
license = 'BSD 2-Clause License',
entry_points = """
[console_scripts]
atomseek = atomseeker.cmdline:main
""",
)
Remove spaces around `=` operatorfrom setuptools import setup, find_packages
setup(
name='AtomSeeker',
version='0.0.1',
description='Analyzer for MP4/MOV format file',
packages=find_packages(),
author='Katsuki Kobayashi',
author_email='rare@tirasweel.org',
license='BSD 2-Clause License',
entry_points="""
[console_scripts]
atomseek = atomseeker.cmdline:main
""",
)
|
<commit_before>from setuptools import setup, find_packages
setup(
name = 'AtomSeeker',
version = '0.0.1',
description = 'Analyzer for MP4/MOV format file',
packages = find_packages(),
author = 'Katsuki Kobayashi',
author_email = 'rare@tirasweel.org',
license = 'BSD 2-Clause License',
entry_points = """
[console_scripts]
atomseek = atomseeker.cmdline:main
""",
)
<commit_msg>Remove spaces around `=` operator<commit_after>from setuptools import setup, find_packages
setup(
name='AtomSeeker',
version='0.0.1',
description='Analyzer for MP4/MOV format file',
packages=find_packages(),
author='Katsuki Kobayashi',
author_email='rare@tirasweel.org',
license='BSD 2-Clause License',
entry_points="""
[console_scripts]
atomseek = atomseeker.cmdline:main
""",
)
|
2ad0d2f848aaef1adda348154545507566db304f
|
setup.py
|
setup.py
|
from setuptools import setup, find_packages
setup(
name='panoptes_client',
url='https://github.com/zooniverse/panoptes-python-client',
author='Adam McMaster',
author_email='adam@zooniverse.org',
version='1.0.3',
packages=find_packages(),
include_package_data=True,
install_requires=[
'requests>=2.4.2,<2.20',
'future>=0.16,<0.17',
'python-magic>=0.4,<0.5',
'redo>=1.7',
],
extras_require={
'testing': [
'mock>=2.0,<2.1',
],
'docs': [
'sphinx',
],
':python_version == "2.7"': ['futures'],
}
)
|
from setuptools import setup, find_packages
setup(
name='panoptes_client',
url='https://github.com/zooniverse/panoptes-python-client',
author='Adam McMaster',
author_email='adam@zooniverse.org',
version='1.0.3',
packages=find_packages(),
include_package_data=True,
install_requires=[
'requests>=2.4.2,<2.21',
'future>=0.16,<0.17',
'python-magic>=0.4,<0.5',
'redo>=1.7',
],
extras_require={
'testing': [
'mock>=2.0,<2.1',
],
'docs': [
'sphinx',
],
':python_version == "2.7"': ['futures'],
}
)
|
Update requests requirement from <2.20,>=2.4.2 to >=2.4.2,<2.21
|
Update requests requirement from <2.20,>=2.4.2 to >=2.4.2,<2.21
Updates the requirements on [requests](https://github.com/requests/requests) to permit the latest version.
- [Release notes](https://github.com/requests/requests/releases)
- [Changelog](https://github.com/requests/requests/blob/master/HISTORY.md)
- [Commits](https://github.com/requests/requests/commits/v2.20.0)
Signed-off-by: dependabot[bot] <5bdcd3c0d4d24ae3e71b3b452a024c6324c7e4bb@dependabot.com>
|
Python
|
apache-2.0
|
zooniverse/panoptes-python-client
|
from setuptools import setup, find_packages
setup(
name='panoptes_client',
url='https://github.com/zooniverse/panoptes-python-client',
author='Adam McMaster',
author_email='adam@zooniverse.org',
version='1.0.3',
packages=find_packages(),
include_package_data=True,
install_requires=[
'requests>=2.4.2,<2.20',
'future>=0.16,<0.17',
'python-magic>=0.4,<0.5',
'redo>=1.7',
],
extras_require={
'testing': [
'mock>=2.0,<2.1',
],
'docs': [
'sphinx',
],
':python_version == "2.7"': ['futures'],
}
)
Update requests requirement from <2.20,>=2.4.2 to >=2.4.2,<2.21
Updates the requirements on [requests](https://github.com/requests/requests) to permit the latest version.
- [Release notes](https://github.com/requests/requests/releases)
- [Changelog](https://github.com/requests/requests/blob/master/HISTORY.md)
- [Commits](https://github.com/requests/requests/commits/v2.20.0)
Signed-off-by: dependabot[bot] <5bdcd3c0d4d24ae3e71b3b452a024c6324c7e4bb@dependabot.com>
|
from setuptools import setup, find_packages
setup(
name='panoptes_client',
url='https://github.com/zooniverse/panoptes-python-client',
author='Adam McMaster',
author_email='adam@zooniverse.org',
version='1.0.3',
packages=find_packages(),
include_package_data=True,
install_requires=[
'requests>=2.4.2,<2.21',
'future>=0.16,<0.17',
'python-magic>=0.4,<0.5',
'redo>=1.7',
],
extras_require={
'testing': [
'mock>=2.0,<2.1',
],
'docs': [
'sphinx',
],
':python_version == "2.7"': ['futures'],
}
)
|
<commit_before>from setuptools import setup, find_packages
setup(
name='panoptes_client',
url='https://github.com/zooniverse/panoptes-python-client',
author='Adam McMaster',
author_email='adam@zooniverse.org',
version='1.0.3',
packages=find_packages(),
include_package_data=True,
install_requires=[
'requests>=2.4.2,<2.20',
'future>=0.16,<0.17',
'python-magic>=0.4,<0.5',
'redo>=1.7',
],
extras_require={
'testing': [
'mock>=2.0,<2.1',
],
'docs': [
'sphinx',
],
':python_version == "2.7"': ['futures'],
}
)
<commit_msg>Update requests requirement from <2.20,>=2.4.2 to >=2.4.2,<2.21
Updates the requirements on [requests](https://github.com/requests/requests) to permit the latest version.
- [Release notes](https://github.com/requests/requests/releases)
- [Changelog](https://github.com/requests/requests/blob/master/HISTORY.md)
- [Commits](https://github.com/requests/requests/commits/v2.20.0)
Signed-off-by: dependabot[bot] <5bdcd3c0d4d24ae3e71b3b452a024c6324c7e4bb@dependabot.com><commit_after>
|
from setuptools import setup, find_packages
setup(
name='panoptes_client',
url='https://github.com/zooniverse/panoptes-python-client',
author='Adam McMaster',
author_email='adam@zooniverse.org',
version='1.0.3',
packages=find_packages(),
include_package_data=True,
install_requires=[
'requests>=2.4.2,<2.21',
'future>=0.16,<0.17',
'python-magic>=0.4,<0.5',
'redo>=1.7',
],
extras_require={
'testing': [
'mock>=2.0,<2.1',
],
'docs': [
'sphinx',
],
':python_version == "2.7"': ['futures'],
}
)
|
from setuptools import setup, find_packages
setup(
name='panoptes_client',
url='https://github.com/zooniverse/panoptes-python-client',
author='Adam McMaster',
author_email='adam@zooniverse.org',
version='1.0.3',
packages=find_packages(),
include_package_data=True,
install_requires=[
'requests>=2.4.2,<2.20',
'future>=0.16,<0.17',
'python-magic>=0.4,<0.5',
'redo>=1.7',
],
extras_require={
'testing': [
'mock>=2.0,<2.1',
],
'docs': [
'sphinx',
],
':python_version == "2.7"': ['futures'],
}
)
Update requests requirement from <2.20,>=2.4.2 to >=2.4.2,<2.21
Updates the requirements on [requests](https://github.com/requests/requests) to permit the latest version.
- [Release notes](https://github.com/requests/requests/releases)
- [Changelog](https://github.com/requests/requests/blob/master/HISTORY.md)
- [Commits](https://github.com/requests/requests/commits/v2.20.0)
Signed-off-by: dependabot[bot] <5bdcd3c0d4d24ae3e71b3b452a024c6324c7e4bb@dependabot.com>from setuptools import setup, find_packages
setup(
name='panoptes_client',
url='https://github.com/zooniverse/panoptes-python-client',
author='Adam McMaster',
author_email='adam@zooniverse.org',
version='1.0.3',
packages=find_packages(),
include_package_data=True,
install_requires=[
'requests>=2.4.2,<2.21',
'future>=0.16,<0.17',
'python-magic>=0.4,<0.5',
'redo>=1.7',
],
extras_require={
'testing': [
'mock>=2.0,<2.1',
],
'docs': [
'sphinx',
],
':python_version == "2.7"': ['futures'],
}
)
|
<commit_before>from setuptools import setup, find_packages
setup(
name='panoptes_client',
url='https://github.com/zooniverse/panoptes-python-client',
author='Adam McMaster',
author_email='adam@zooniverse.org',
version='1.0.3',
packages=find_packages(),
include_package_data=True,
install_requires=[
'requests>=2.4.2,<2.20',
'future>=0.16,<0.17',
'python-magic>=0.4,<0.5',
'redo>=1.7',
],
extras_require={
'testing': [
'mock>=2.0,<2.1',
],
'docs': [
'sphinx',
],
':python_version == "2.7"': ['futures'],
}
)
<commit_msg>Update requests requirement from <2.20,>=2.4.2 to >=2.4.2,<2.21
Updates the requirements on [requests](https://github.com/requests/requests) to permit the latest version.
- [Release notes](https://github.com/requests/requests/releases)
- [Changelog](https://github.com/requests/requests/blob/master/HISTORY.md)
- [Commits](https://github.com/requests/requests/commits/v2.20.0)
Signed-off-by: dependabot[bot] <5bdcd3c0d4d24ae3e71b3b452a024c6324c7e4bb@dependabot.com><commit_after>from setuptools import setup, find_packages
setup(
name='panoptes_client',
url='https://github.com/zooniverse/panoptes-python-client',
author='Adam McMaster',
author_email='adam@zooniverse.org',
version='1.0.3',
packages=find_packages(),
include_package_data=True,
install_requires=[
'requests>=2.4.2,<2.21',
'future>=0.16,<0.17',
'python-magic>=0.4,<0.5',
'redo>=1.7',
],
extras_require={
'testing': [
'mock>=2.0,<2.1',
],
'docs': [
'sphinx',
],
':python_version == "2.7"': ['futures'],
}
)
|
9e2e2bda5c8e42b0795612c0138eafbcd6b63eb5
|
setup.py
|
setup.py
|
from setuptools import setup
setup(
name='django-logentry-admin',
author='Yuri Prezument',
author_email='y@yprez.com',
version='0.1.5',
packages=['logentry_admin'],
package_data={
'logentry_admin': ['templates/admin/admin/logentry/change_form.html']
},
license='ISC',
url='http://github.com/yprez/django-logentry-admin',
description='Show all LogEntry objects in the Django admin site.',
long_description=open('README.rst').read(),
install_requires=[
'Django>=1.7',
],
classifiers=[
'Development Status :: 3 - Alpha',
'Framework :: Django',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: ISC License (ISCL)',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
)
|
from setuptools import setup
with open('README.rst') as f:
readme = f.read()
with open('CHANGELOG.rst') as f:
changelog = f.read()
setup(
name='django-logentry-admin',
author='Yuri Prezument',
author_email='y@yprez.com',
version='0.1.5',
packages=['logentry_admin'],
package_data={
'logentry_admin': ['templates/admin/admin/logentry/change_form.html']
},
license='ISC',
url='http://github.com/yprez/django-logentry-admin',
description='Show all LogEntry objects in the Django admin site.',
long_description=readme + '\n\n' + changelog,
install_requires=[
'Django>=1.7',
],
classifiers=[
'Development Status :: 3 - Alpha',
'Framework :: Django',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: ISC License (ISCL)',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
)
|
Add changelog to readme, and open/close both files properly
|
Add changelog to readme, and open/close both files properly
|
Python
|
isc
|
yprez/django-logentry-admin,yprez/django-logentry-admin
|
from setuptools import setup
setup(
name='django-logentry-admin',
author='Yuri Prezument',
author_email='y@yprez.com',
version='0.1.5',
packages=['logentry_admin'],
package_data={
'logentry_admin': ['templates/admin/admin/logentry/change_form.html']
},
license='ISC',
url='http://github.com/yprez/django-logentry-admin',
description='Show all LogEntry objects in the Django admin site.',
long_description=open('README.rst').read(),
install_requires=[
'Django>=1.7',
],
classifiers=[
'Development Status :: 3 - Alpha',
'Framework :: Django',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: ISC License (ISCL)',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
)
Add changelog to readme, and open/close both files properly
|
from setuptools import setup
with open('README.rst') as f:
readme = f.read()
with open('CHANGELOG.rst') as f:
changelog = f.read()
setup(
name='django-logentry-admin',
author='Yuri Prezument',
author_email='y@yprez.com',
version='0.1.5',
packages=['logentry_admin'],
package_data={
'logentry_admin': ['templates/admin/admin/logentry/change_form.html']
},
license='ISC',
url='http://github.com/yprez/django-logentry-admin',
description='Show all LogEntry objects in the Django admin site.',
long_description=readme + '\n\n' + changelog,
install_requires=[
'Django>=1.7',
],
classifiers=[
'Development Status :: 3 - Alpha',
'Framework :: Django',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: ISC License (ISCL)',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
)
|
<commit_before>from setuptools import setup
setup(
name='django-logentry-admin',
author='Yuri Prezument',
author_email='y@yprez.com',
version='0.1.5',
packages=['logentry_admin'],
package_data={
'logentry_admin': ['templates/admin/admin/logentry/change_form.html']
},
license='ISC',
url='http://github.com/yprez/django-logentry-admin',
description='Show all LogEntry objects in the Django admin site.',
long_description=open('README.rst').read(),
install_requires=[
'Django>=1.7',
],
classifiers=[
'Development Status :: 3 - Alpha',
'Framework :: Django',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: ISC License (ISCL)',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
)
<commit_msg>Add changelog to readme, and open/close both files properly<commit_after>
|
from setuptools import setup
with open('README.rst') as f:
readme = f.read()
with open('CHANGELOG.rst') as f:
changelog = f.read()
setup(
name='django-logentry-admin',
author='Yuri Prezument',
author_email='y@yprez.com',
version='0.1.5',
packages=['logentry_admin'],
package_data={
'logentry_admin': ['templates/admin/admin/logentry/change_form.html']
},
license='ISC',
url='http://github.com/yprez/django-logentry-admin',
description='Show all LogEntry objects in the Django admin site.',
long_description=readme + '\n\n' + changelog,
install_requires=[
'Django>=1.7',
],
classifiers=[
'Development Status :: 3 - Alpha',
'Framework :: Django',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: ISC License (ISCL)',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
)
|
from setuptools import setup
setup(
name='django-logentry-admin',
author='Yuri Prezument',
author_email='y@yprez.com',
version='0.1.5',
packages=['logentry_admin'],
package_data={
'logentry_admin': ['templates/admin/admin/logentry/change_form.html']
},
license='ISC',
url='http://github.com/yprez/django-logentry-admin',
description='Show all LogEntry objects in the Django admin site.',
long_description=open('README.rst').read(),
install_requires=[
'Django>=1.7',
],
classifiers=[
'Development Status :: 3 - Alpha',
'Framework :: Django',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: ISC License (ISCL)',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
)
Add changelog to readme, and open/close both files properlyfrom setuptools import setup
with open('README.rst') as f:
readme = f.read()
with open('CHANGELOG.rst') as f:
changelog = f.read()
setup(
name='django-logentry-admin',
author='Yuri Prezument',
author_email='y@yprez.com',
version='0.1.5',
packages=['logentry_admin'],
package_data={
'logentry_admin': ['templates/admin/admin/logentry/change_form.html']
},
license='ISC',
url='http://github.com/yprez/django-logentry-admin',
description='Show all LogEntry objects in the Django admin site.',
long_description=readme + '\n\n' + changelog,
install_requires=[
'Django>=1.7',
],
classifiers=[
'Development Status :: 3 - Alpha',
'Framework :: Django',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: ISC License (ISCL)',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
)
|
<commit_before>from setuptools import setup
setup(
name='django-logentry-admin',
author='Yuri Prezument',
author_email='y@yprez.com',
version='0.1.5',
packages=['logentry_admin'],
package_data={
'logentry_admin': ['templates/admin/admin/logentry/change_form.html']
},
license='ISC',
url='http://github.com/yprez/django-logentry-admin',
description='Show all LogEntry objects in the Django admin site.',
long_description=open('README.rst').read(),
install_requires=[
'Django>=1.7',
],
classifiers=[
'Development Status :: 3 - Alpha',
'Framework :: Django',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: ISC License (ISCL)',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
)
<commit_msg>Add changelog to readme, and open/close both files properly<commit_after>from setuptools import setup
with open('README.rst') as f:
readme = f.read()
with open('CHANGELOG.rst') as f:
changelog = f.read()
setup(
name='django-logentry-admin',
author='Yuri Prezument',
author_email='y@yprez.com',
version='0.1.5',
packages=['logentry_admin'],
package_data={
'logentry_admin': ['templates/admin/admin/logentry/change_form.html']
},
license='ISC',
url='http://github.com/yprez/django-logentry-admin',
description='Show all LogEntry objects in the Django admin site.',
long_description=readme + '\n\n' + changelog,
install_requires=[
'Django>=1.7',
],
classifiers=[
'Development Status :: 3 - Alpha',
'Framework :: Django',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: ISC License (ISCL)',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
)
|
e91f0586949b035b8e3f4c11999712d3134bf787
|
setup.py
|
setup.py
|
"""setup.py file."""
import uuid
from setuptools import setup, find_packages
from pip.req import parse_requirements
__author__ = 'David Barroso <dbarrosop@dravetech.com>'
install_reqs = parse_requirements('requirements.txt', session=uuid.uuid1())
reqs = [str(ir.req) for ir in install_reqs]
setup(
name="napalm-nxos",
version="0.5.2",
packages=find_packages(),
author="David Barroso",
author_email="dbarrosop@dravetech.com",
description="Network Automation and Programmability Abstraction Layer with Multivendor support",
classifiers=[
'Topic :: Utilities',
'Programming Language :: Python',
'Operating System :: POSIX :: Linux',
'Operating System :: MacOS',
],
url="https://github.com/napalm-automation/napalm-nxos",
include_package_data=True,
install_requires=reqs,
)
|
"""setup.py file."""
import uuid
from setuptools import setup, find_packages
from pip.req import parse_requirements
__author__ = 'David Barroso <dbarrosop@dravetech.com>'
install_reqs = parse_requirements('requirements.txt', session=uuid.uuid1())
reqs = [str(ir.req) for ir in install_reqs]
setup(
name="napalm-nxos",
version="0.5.2",
packages=find_packages(exclude=["test", "test.*"]),
author="David Barroso",
author_email="dbarrosop@dravetech.com",
description="Network Automation and Programmability Abstraction Layer with Multivendor support",
classifiers=[
'Topic :: Utilities',
'Programming Language :: Python',
'Operating System :: POSIX :: Linux',
'Operating System :: MacOS',
],
url="https://github.com/napalm-automation/napalm-nxos",
include_package_data=True,
install_requires=reqs,
)
|
Exclude the test/ directory & files from being installed as a package.
|
Exclude the test/ directory & files from being installed as a package.
|
Python
|
apache-2.0
|
napalm-automation/napalm,spotify/napalm,napalm-automation/napalm-nxos,spotify/napalm
|
"""setup.py file."""
import uuid
from setuptools import setup, find_packages
from pip.req import parse_requirements
__author__ = 'David Barroso <dbarrosop@dravetech.com>'
install_reqs = parse_requirements('requirements.txt', session=uuid.uuid1())
reqs = [str(ir.req) for ir in install_reqs]
setup(
name="napalm-nxos",
version="0.5.2",
packages=find_packages(),
author="David Barroso",
author_email="dbarrosop@dravetech.com",
description="Network Automation and Programmability Abstraction Layer with Multivendor support",
classifiers=[
'Topic :: Utilities',
'Programming Language :: Python',
'Operating System :: POSIX :: Linux',
'Operating System :: MacOS',
],
url="https://github.com/napalm-automation/napalm-nxos",
include_package_data=True,
install_requires=reqs,
)
Exclude the test/ directory & files from being installed as a package.
|
"""setup.py file."""
import uuid
from setuptools import setup, find_packages
from pip.req import parse_requirements
__author__ = 'David Barroso <dbarrosop@dravetech.com>'
install_reqs = parse_requirements('requirements.txt', session=uuid.uuid1())
reqs = [str(ir.req) for ir in install_reqs]
setup(
name="napalm-nxos",
version="0.5.2",
packages=find_packages(exclude=["test", "test.*"]),
author="David Barroso",
author_email="dbarrosop@dravetech.com",
description="Network Automation and Programmability Abstraction Layer with Multivendor support",
classifiers=[
'Topic :: Utilities',
'Programming Language :: Python',
'Operating System :: POSIX :: Linux',
'Operating System :: MacOS',
],
url="https://github.com/napalm-automation/napalm-nxos",
include_package_data=True,
install_requires=reqs,
)
|
<commit_before>"""setup.py file."""
import uuid
from setuptools import setup, find_packages
from pip.req import parse_requirements
__author__ = 'David Barroso <dbarrosop@dravetech.com>'
install_reqs = parse_requirements('requirements.txt', session=uuid.uuid1())
reqs = [str(ir.req) for ir in install_reqs]
setup(
name="napalm-nxos",
version="0.5.2",
packages=find_packages(),
author="David Barroso",
author_email="dbarrosop@dravetech.com",
description="Network Automation and Programmability Abstraction Layer with Multivendor support",
classifiers=[
'Topic :: Utilities',
'Programming Language :: Python',
'Operating System :: POSIX :: Linux',
'Operating System :: MacOS',
],
url="https://github.com/napalm-automation/napalm-nxos",
include_package_data=True,
install_requires=reqs,
)
<commit_msg>Exclude the test/ directory & files from being installed as a package.<commit_after>
|
"""setup.py file."""
import uuid
from setuptools import setup, find_packages
from pip.req import parse_requirements
__author__ = 'David Barroso <dbarrosop@dravetech.com>'
install_reqs = parse_requirements('requirements.txt', session=uuid.uuid1())
reqs = [str(ir.req) for ir in install_reqs]
setup(
name="napalm-nxos",
version="0.5.2",
packages=find_packages(exclude=["test", "test.*"]),
author="David Barroso",
author_email="dbarrosop@dravetech.com",
description="Network Automation and Programmability Abstraction Layer with Multivendor support",
classifiers=[
'Topic :: Utilities',
'Programming Language :: Python',
'Operating System :: POSIX :: Linux',
'Operating System :: MacOS',
],
url="https://github.com/napalm-automation/napalm-nxos",
include_package_data=True,
install_requires=reqs,
)
|
"""setup.py file."""
import uuid
from setuptools import setup, find_packages
from pip.req import parse_requirements
__author__ = 'David Barroso <dbarrosop@dravetech.com>'
install_reqs = parse_requirements('requirements.txt', session=uuid.uuid1())
reqs = [str(ir.req) for ir in install_reqs]
setup(
name="napalm-nxos",
version="0.5.2",
packages=find_packages(),
author="David Barroso",
author_email="dbarrosop@dravetech.com",
description="Network Automation and Programmability Abstraction Layer with Multivendor support",
classifiers=[
'Topic :: Utilities',
'Programming Language :: Python',
'Operating System :: POSIX :: Linux',
'Operating System :: MacOS',
],
url="https://github.com/napalm-automation/napalm-nxos",
include_package_data=True,
install_requires=reqs,
)
Exclude the test/ directory & files from being installed as a package."""setup.py file."""
import uuid
from setuptools import setup, find_packages
from pip.req import parse_requirements
__author__ = 'David Barroso <dbarrosop@dravetech.com>'
install_reqs = parse_requirements('requirements.txt', session=uuid.uuid1())
reqs = [str(ir.req) for ir in install_reqs]
setup(
name="napalm-nxos",
version="0.5.2",
packages=find_packages(exclude=["test", "test.*"]),
author="David Barroso",
author_email="dbarrosop@dravetech.com",
description="Network Automation and Programmability Abstraction Layer with Multivendor support",
classifiers=[
'Topic :: Utilities',
'Programming Language :: Python',
'Operating System :: POSIX :: Linux',
'Operating System :: MacOS',
],
url="https://github.com/napalm-automation/napalm-nxos",
include_package_data=True,
install_requires=reqs,
)
|
<commit_before>"""setup.py file."""
import uuid
from setuptools import setup, find_packages
from pip.req import parse_requirements
__author__ = 'David Barroso <dbarrosop@dravetech.com>'
install_reqs = parse_requirements('requirements.txt', session=uuid.uuid1())
reqs = [str(ir.req) for ir in install_reqs]
setup(
name="napalm-nxos",
version="0.5.2",
packages=find_packages(),
author="David Barroso",
author_email="dbarrosop@dravetech.com",
description="Network Automation and Programmability Abstraction Layer with Multivendor support",
classifiers=[
'Topic :: Utilities',
'Programming Language :: Python',
'Operating System :: POSIX :: Linux',
'Operating System :: MacOS',
],
url="https://github.com/napalm-automation/napalm-nxos",
include_package_data=True,
install_requires=reqs,
)
<commit_msg>Exclude the test/ directory & files from being installed as a package.<commit_after>"""setup.py file."""
import uuid
from setuptools import setup, find_packages
from pip.req import parse_requirements
__author__ = 'David Barroso <dbarrosop@dravetech.com>'
install_reqs = parse_requirements('requirements.txt', session=uuid.uuid1())
reqs = [str(ir.req) for ir in install_reqs]
setup(
name="napalm-nxos",
version="0.5.2",
packages=find_packages(exclude=["test", "test.*"]),
author="David Barroso",
author_email="dbarrosop@dravetech.com",
description="Network Automation and Programmability Abstraction Layer with Multivendor support",
classifiers=[
'Topic :: Utilities',
'Programming Language :: Python',
'Operating System :: POSIX :: Linux',
'Operating System :: MacOS',
],
url="https://github.com/napalm-automation/napalm-nxos",
include_package_data=True,
install_requires=reqs,
)
|
da4684ef09e0edee3a2d147d759d53f0944abf2f
|
setup.py
|
setup.py
|
#!/usr/bin/env python
import sys
from setuptools import find_packages, setup
install_requires = [
'cssselect',
'cssutils',
'lxml',
]
tests_require = [
'exam',
'pytest',
]
setup(
name='toronado',
version='0.0.4',
author='ted kaemming, disqus',
author_email='ted@disqus.com',
packages=find_packages(exclude=('tests',)),
install_requires=install_requires,
tests_require=tests_require,
extras_require={
'tests': tests_require,
},
zip_safe=False,
license='Apache License 2.0',
)
|
#!/usr/bin/env python
import sys
from setuptools import find_packages, setup
install_requires = [
'cssselect',
'cssutils',
'lxml',
]
tests_require = [
'exam',
'pytest',
]
setup(
name='toronado',
version='0.0.4',
author='ted kaemming, disqus',
author_email='ted@disqus.com',
packages=find_packages(exclude=('tests',)),
install_requires=install_requires,
tests_require=tests_require,
extras_require={
'tests': tests_require,
},
zip_safe=False,
license='Apache License 2.0',
classifiers=[
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
],
)
|
Add classifiers for the supported versions
|
Add classifiers for the supported versions
|
Python
|
apache-2.0
|
disqus/toronado
|
#!/usr/bin/env python
import sys
from setuptools import find_packages, setup
install_requires = [
'cssselect',
'cssutils',
'lxml',
]
tests_require = [
'exam',
'pytest',
]
setup(
name='toronado',
version='0.0.4',
author='ted kaemming, disqus',
author_email='ted@disqus.com',
packages=find_packages(exclude=('tests',)),
install_requires=install_requires,
tests_require=tests_require,
extras_require={
'tests': tests_require,
},
zip_safe=False,
license='Apache License 2.0',
)
Add classifiers for the supported versions
|
#!/usr/bin/env python
import sys
from setuptools import find_packages, setup
install_requires = [
'cssselect',
'cssutils',
'lxml',
]
tests_require = [
'exam',
'pytest',
]
setup(
name='toronado',
version='0.0.4',
author='ted kaemming, disqus',
author_email='ted@disqus.com',
packages=find_packages(exclude=('tests',)),
install_requires=install_requires,
tests_require=tests_require,
extras_require={
'tests': tests_require,
},
zip_safe=False,
license='Apache License 2.0',
classifiers=[
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
],
)
|
<commit_before>#!/usr/bin/env python
import sys
from setuptools import find_packages, setup
install_requires = [
'cssselect',
'cssutils',
'lxml',
]
tests_require = [
'exam',
'pytest',
]
setup(
name='toronado',
version='0.0.4',
author='ted kaemming, disqus',
author_email='ted@disqus.com',
packages=find_packages(exclude=('tests',)),
install_requires=install_requires,
tests_require=tests_require,
extras_require={
'tests': tests_require,
},
zip_safe=False,
license='Apache License 2.0',
)
<commit_msg>Add classifiers for the supported versions<commit_after>
|
#!/usr/bin/env python
import sys
from setuptools import find_packages, setup
install_requires = [
'cssselect',
'cssutils',
'lxml',
]
tests_require = [
'exam',
'pytest',
]
setup(
name='toronado',
version='0.0.4',
author='ted kaemming, disqus',
author_email='ted@disqus.com',
packages=find_packages(exclude=('tests',)),
install_requires=install_requires,
tests_require=tests_require,
extras_require={
'tests': tests_require,
},
zip_safe=False,
license='Apache License 2.0',
classifiers=[
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
],
)
|
#!/usr/bin/env python
import sys
from setuptools import find_packages, setup
install_requires = [
'cssselect',
'cssutils',
'lxml',
]
tests_require = [
'exam',
'pytest',
]
setup(
name='toronado',
version='0.0.4',
author='ted kaemming, disqus',
author_email='ted@disqus.com',
packages=find_packages(exclude=('tests',)),
install_requires=install_requires,
tests_require=tests_require,
extras_require={
'tests': tests_require,
},
zip_safe=False,
license='Apache License 2.0',
)
Add classifiers for the supported versions#!/usr/bin/env python
import sys
from setuptools import find_packages, setup
install_requires = [
'cssselect',
'cssutils',
'lxml',
]
tests_require = [
'exam',
'pytest',
]
setup(
name='toronado',
version='0.0.4',
author='ted kaemming, disqus',
author_email='ted@disqus.com',
packages=find_packages(exclude=('tests',)),
install_requires=install_requires,
tests_require=tests_require,
extras_require={
'tests': tests_require,
},
zip_safe=False,
license='Apache License 2.0',
classifiers=[
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
],
)
|
<commit_before>#!/usr/bin/env python
import sys
from setuptools import find_packages, setup
install_requires = [
'cssselect',
'cssutils',
'lxml',
]
tests_require = [
'exam',
'pytest',
]
setup(
name='toronado',
version='0.0.4',
author='ted kaemming, disqus',
author_email='ted@disqus.com',
packages=find_packages(exclude=('tests',)),
install_requires=install_requires,
tests_require=tests_require,
extras_require={
'tests': tests_require,
},
zip_safe=False,
license='Apache License 2.0',
)
<commit_msg>Add classifiers for the supported versions<commit_after>#!/usr/bin/env python
import sys
from setuptools import find_packages, setup
install_requires = [
'cssselect',
'cssutils',
'lxml',
]
tests_require = [
'exam',
'pytest',
]
setup(
name='toronado',
version='0.0.4',
author='ted kaemming, disqus',
author_email='ted@disqus.com',
packages=find_packages(exclude=('tests',)),
install_requires=install_requires,
tests_require=tests_require,
extras_require={
'tests': tests_require,
},
zip_safe=False,
license='Apache License 2.0',
classifiers=[
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
],
)
|
d3f50efd67522f21781aaff2bdb6f2a1bf3151e0
|
setup.py
|
setup.py
|
from setuptools import setup, find_packages
setup(
name = 'dictsheet',
version = '0.0.3',
keywords = ('dictsheet', 'spreadsheet', 'gspread'),
description = 'Dict wrapper for google spreadsheet',
license = 'MIT License',
install_requires = ['gspread>=0.4.1'],
url = 'https://github.com/previa/dictsheet',
author = 'Chandler Huang, Xander Li',
author_email = 'previa@gmail.com',
packages = find_packages(),
platforms = 'any',
)
|
from setuptools import setup, find_packages
from pip.req import parse_requirements
install_reqs = parse_requirements('requirements.txt', session=False)
reqs = [str(ir.req) for ir in install_reqs]
# REFERENCE:
# http://stackoverflow.com/questions/14399534/how-can-i-reference-requirements-txt-for-the-install-requires-kwarg-in-setuptool
setup(
name = 'dictsheet',
version = '0.0.9',
keywords = ('dictsheet', 'spreadsheet', 'gspread'),
description = 'Dict wrapper for google spreadsheet',
license = 'MIT License',
install_requires = reqs,
data_files = ['requirements.txt', 'README.md', 'LICENSE.txt'],
url = 'https://github.com/previa/dictsheet',
author = 'Chandler Huang, Xander Li',
author_email = 'previa@gmail.com',
packages = find_packages(),
platforms = 'any',
)
|
Include packages in requirements.txt to install_requires().
|
[Feature] Include packages in requirements.txt to install_requires().
|
Python
|
mit
|
previa/dictsheet
|
from setuptools import setup, find_packages
setup(
name = 'dictsheet',
version = '0.0.3',
keywords = ('dictsheet', 'spreadsheet', 'gspread'),
description = 'Dict wrapper for google spreadsheet',
license = 'MIT License',
install_requires = ['gspread>=0.4.1'],
url = 'https://github.com/previa/dictsheet',
author = 'Chandler Huang, Xander Li',
author_email = 'previa@gmail.com',
packages = find_packages(),
platforms = 'any',
)
[Feature] Include packages in requirements.txt to install_requires().
|
from setuptools import setup, find_packages
from pip.req import parse_requirements
install_reqs = parse_requirements('requirements.txt', session=False)
reqs = [str(ir.req) for ir in install_reqs]
# REFERENCE:
# http://stackoverflow.com/questions/14399534/how-can-i-reference-requirements-txt-for-the-install-requires-kwarg-in-setuptool
setup(
name = 'dictsheet',
version = '0.0.9',
keywords = ('dictsheet', 'spreadsheet', 'gspread'),
description = 'Dict wrapper for google spreadsheet',
license = 'MIT License',
install_requires = reqs,
data_files = ['requirements.txt', 'README.md', 'LICENSE.txt'],
url = 'https://github.com/previa/dictsheet',
author = 'Chandler Huang, Xander Li',
author_email = 'previa@gmail.com',
packages = find_packages(),
platforms = 'any',
)
|
<commit_before>from setuptools import setup, find_packages
setup(
name = 'dictsheet',
version = '0.0.3',
keywords = ('dictsheet', 'spreadsheet', 'gspread'),
description = 'Dict wrapper for google spreadsheet',
license = 'MIT License',
install_requires = ['gspread>=0.4.1'],
url = 'https://github.com/previa/dictsheet',
author = 'Chandler Huang, Xander Li',
author_email = 'previa@gmail.com',
packages = find_packages(),
platforms = 'any',
)
<commit_msg>[Feature] Include packages in requirements.txt to install_requires().<commit_after>
|
from setuptools import setup, find_packages
from pip.req import parse_requirements
install_reqs = parse_requirements('requirements.txt', session=False)
reqs = [str(ir.req) for ir in install_reqs]
# REFERENCE:
# http://stackoverflow.com/questions/14399534/how-can-i-reference-requirements-txt-for-the-install-requires-kwarg-in-setuptool
setup(
name = 'dictsheet',
version = '0.0.9',
keywords = ('dictsheet', 'spreadsheet', 'gspread'),
description = 'Dict wrapper for google spreadsheet',
license = 'MIT License',
install_requires = reqs,
data_files = ['requirements.txt', 'README.md', 'LICENSE.txt'],
url = 'https://github.com/previa/dictsheet',
author = 'Chandler Huang, Xander Li',
author_email = 'previa@gmail.com',
packages = find_packages(),
platforms = 'any',
)
|
from setuptools import setup, find_packages
setup(
name = 'dictsheet',
version = '0.0.3',
keywords = ('dictsheet', 'spreadsheet', 'gspread'),
description = 'Dict wrapper for google spreadsheet',
license = 'MIT License',
install_requires = ['gspread>=0.4.1'],
url = 'https://github.com/previa/dictsheet',
author = 'Chandler Huang, Xander Li',
author_email = 'previa@gmail.com',
packages = find_packages(),
platforms = 'any',
)
[Feature] Include packages in requirements.txt to install_requires().from setuptools import setup, find_packages
from pip.req import parse_requirements
install_reqs = parse_requirements('requirements.txt', session=False)
reqs = [str(ir.req) for ir in install_reqs]
# REFERENCE:
# http://stackoverflow.com/questions/14399534/how-can-i-reference-requirements-txt-for-the-install-requires-kwarg-in-setuptool
setup(
name = 'dictsheet',
version = '0.0.9',
keywords = ('dictsheet', 'spreadsheet', 'gspread'),
description = 'Dict wrapper for google spreadsheet',
license = 'MIT License',
install_requires = reqs,
data_files = ['requirements.txt', 'README.md', 'LICENSE.txt'],
url = 'https://github.com/previa/dictsheet',
author = 'Chandler Huang, Xander Li',
author_email = 'previa@gmail.com',
packages = find_packages(),
platforms = 'any',
)
|
<commit_before>from setuptools import setup, find_packages
setup(
name = 'dictsheet',
version = '0.0.3',
keywords = ('dictsheet', 'spreadsheet', 'gspread'),
description = 'Dict wrapper for google spreadsheet',
license = 'MIT License',
install_requires = ['gspread>=0.4.1'],
url = 'https://github.com/previa/dictsheet',
author = 'Chandler Huang, Xander Li',
author_email = 'previa@gmail.com',
packages = find_packages(),
platforms = 'any',
)
<commit_msg>[Feature] Include packages in requirements.txt to install_requires().<commit_after>from setuptools import setup, find_packages
from pip.req import parse_requirements
install_reqs = parse_requirements('requirements.txt', session=False)
reqs = [str(ir.req) for ir in install_reqs]
# REFERENCE:
# http://stackoverflow.com/questions/14399534/how-can-i-reference-requirements-txt-for-the-install-requires-kwarg-in-setuptool
setup(
name = 'dictsheet',
version = '0.0.9',
keywords = ('dictsheet', 'spreadsheet', 'gspread'),
description = 'Dict wrapper for google spreadsheet',
license = 'MIT License',
install_requires = reqs,
data_files = ['requirements.txt', 'README.md', 'LICENSE.txt'],
url = 'https://github.com/previa/dictsheet',
author = 'Chandler Huang, Xander Li',
author_email = 'previa@gmail.com',
packages = find_packages(),
platforms = 'any',
)
|
dcf791dc3c0c827125ce1e1e4400f60de7c70509
|
shopify/product/tasks.py
|
shopify/product/tasks.py
|
from decimal import Decimal
from django.conf import settings
from django.core.mail import EmailMessage
from celery.utils.log import get_task_logger
from .csv_attach import CSVAttachmentWriter
from .models import Transaction
from celeryapp import app
logger = get_task_logger(__name__)
@app.task(max_retries=3)
def email_journal_vouchers_import():
"""
"""
try:
credits = Transaction.objects.export_transactions()
debit = Decimal(0)
attachment = CSVAttachmentWriter()
for credit in credits:
attachment.writerow([credit['product__account_number'], '',
credit['price__sum']])
debit += credit['price__sum']
attachment.writerow([settings.SHOPIFY_DEBIT_ACCOUNT_NUMBER, debit, ''])
message = EmailMessage('Journal Vouchers Import', '',
to=[m[1] for m in settings.MANAGERS])
message.attach(attachment.getname(), attachment.getvalue(), 'text/csv')
message.send()
except Exception as exc:
logger.debug("MIP export failed: %s" % exc)
logger.warn('MIP export failed, retrying')
raise email_mip_import_file.retry(exc=exc)
|
from decimal import Decimal
from django.conf import settings
from django.core.mail import EmailMessage
from celery.utils.log import get_task_logger
from .csv_attach import CSVAttachmentWriter
from .models import Transaction
from celeryapp import app
logger = get_task_logger(__name__)
@app.task(max_retries=3)
def email_journal_vouchers_import():
"""
"""
try:
credits = Transaction.objects.export_transactions()
debit = Decimal(0)
attachment = CSVAttachmentWriter()
for credit in credits:
attachment.writerow([credit['product__account_number'], '',
credit['price__sum']])
debit += credit['price__sum']
debit_account = getattr(settings, 'SHOPIFY_DEBIT_ACCOUNT_NUMBER', None)
attachment.writerow([debit_account, debit, ''])
message = EmailMessage('Journal Vouchers Import', '',
to=[m[1] for m in settings.MANAGERS])
message.attach(attachment.getname(), attachment.getvalue(), 'text/csv')
message.send()
except Exception as exc:
logger.debug("MIP export failed: %s" % exc)
logger.warn('MIP export failed, retrying')
raise email_mip_import_file.retry(exc=exc)
|
Fix accessing settings for debit account number
|
Fix accessing settings for debit account number
|
Python
|
bsd-3-clause
|
CorbanU/corban-shopify,CorbanU/corban-shopify
|
from decimal import Decimal
from django.conf import settings
from django.core.mail import EmailMessage
from celery.utils.log import get_task_logger
from .csv_attach import CSVAttachmentWriter
from .models import Transaction
from celeryapp import app
logger = get_task_logger(__name__)
@app.task(max_retries=3)
def email_journal_vouchers_import():
"""
"""
try:
credits = Transaction.objects.export_transactions()
debit = Decimal(0)
attachment = CSVAttachmentWriter()
for credit in credits:
attachment.writerow([credit['product__account_number'], '',
credit['price__sum']])
debit += credit['price__sum']
attachment.writerow([settings.SHOPIFY_DEBIT_ACCOUNT_NUMBER, debit, ''])
message = EmailMessage('Journal Vouchers Import', '',
to=[m[1] for m in settings.MANAGERS])
message.attach(attachment.getname(), attachment.getvalue(), 'text/csv')
message.send()
except Exception as exc:
logger.debug("MIP export failed: %s" % exc)
logger.warn('MIP export failed, retrying')
raise email_mip_import_file.retry(exc=exc)
Fix accessing settings for debit account number
|
from decimal import Decimal
from django.conf import settings
from django.core.mail import EmailMessage
from celery.utils.log import get_task_logger
from .csv_attach import CSVAttachmentWriter
from .models import Transaction
from celeryapp import app
logger = get_task_logger(__name__)
@app.task(max_retries=3)
def email_journal_vouchers_import():
"""
"""
try:
credits = Transaction.objects.export_transactions()
debit = Decimal(0)
attachment = CSVAttachmentWriter()
for credit in credits:
attachment.writerow([credit['product__account_number'], '',
credit['price__sum']])
debit += credit['price__sum']
debit_account = getattr(settings, 'SHOPIFY_DEBIT_ACCOUNT_NUMBER', None)
attachment.writerow([debit_account, debit, ''])
message = EmailMessage('Journal Vouchers Import', '',
to=[m[1] for m in settings.MANAGERS])
message.attach(attachment.getname(), attachment.getvalue(), 'text/csv')
message.send()
except Exception as exc:
logger.debug("MIP export failed: %s" % exc)
logger.warn('MIP export failed, retrying')
raise email_mip_import_file.retry(exc=exc)
|
<commit_before>from decimal import Decimal
from django.conf import settings
from django.core.mail import EmailMessage
from celery.utils.log import get_task_logger
from .csv_attach import CSVAttachmentWriter
from .models import Transaction
from celeryapp import app
logger = get_task_logger(__name__)
@app.task(max_retries=3)
def email_journal_vouchers_import():
"""
"""
try:
credits = Transaction.objects.export_transactions()
debit = Decimal(0)
attachment = CSVAttachmentWriter()
for credit in credits:
attachment.writerow([credit['product__account_number'], '',
credit['price__sum']])
debit += credit['price__sum']
attachment.writerow([settings.SHOPIFY_DEBIT_ACCOUNT_NUMBER, debit, ''])
message = EmailMessage('Journal Vouchers Import', '',
to=[m[1] for m in settings.MANAGERS])
message.attach(attachment.getname(), attachment.getvalue(), 'text/csv')
message.send()
except Exception as exc:
logger.debug("MIP export failed: %s" % exc)
logger.warn('MIP export failed, retrying')
raise email_mip_import_file.retry(exc=exc)
<commit_msg>Fix accessing settings for debit account number<commit_after>
|
from decimal import Decimal
from django.conf import settings
from django.core.mail import EmailMessage
from celery.utils.log import get_task_logger
from .csv_attach import CSVAttachmentWriter
from .models import Transaction
from celeryapp import app
logger = get_task_logger(__name__)
@app.task(max_retries=3)
def email_journal_vouchers_import():
"""
"""
try:
credits = Transaction.objects.export_transactions()
debit = Decimal(0)
attachment = CSVAttachmentWriter()
for credit in credits:
attachment.writerow([credit['product__account_number'], '',
credit['price__sum']])
debit += credit['price__sum']
debit_account = getattr(settings, 'SHOPIFY_DEBIT_ACCOUNT_NUMBER', None)
attachment.writerow([debit_account, debit, ''])
message = EmailMessage('Journal Vouchers Import', '',
to=[m[1] for m in settings.MANAGERS])
message.attach(attachment.getname(), attachment.getvalue(), 'text/csv')
message.send()
except Exception as exc:
logger.debug("MIP export failed: %s" % exc)
logger.warn('MIP export failed, retrying')
raise email_mip_import_file.retry(exc=exc)
|
from decimal import Decimal
from django.conf import settings
from django.core.mail import EmailMessage
from celery.utils.log import get_task_logger
from .csv_attach import CSVAttachmentWriter
from .models import Transaction
from celeryapp import app
logger = get_task_logger(__name__)
@app.task(max_retries=3)
def email_journal_vouchers_import():
"""
"""
try:
credits = Transaction.objects.export_transactions()
debit = Decimal(0)
attachment = CSVAttachmentWriter()
for credit in credits:
attachment.writerow([credit['product__account_number'], '',
credit['price__sum']])
debit += credit['price__sum']
attachment.writerow([settings.SHOPIFY_DEBIT_ACCOUNT_NUMBER, debit, ''])
message = EmailMessage('Journal Vouchers Import', '',
to=[m[1] for m in settings.MANAGERS])
message.attach(attachment.getname(), attachment.getvalue(), 'text/csv')
message.send()
except Exception as exc:
logger.debug("MIP export failed: %s" % exc)
logger.warn('MIP export failed, retrying')
raise email_mip_import_file.retry(exc=exc)
Fix accessing settings for debit account numberfrom decimal import Decimal
from django.conf import settings
from django.core.mail import EmailMessage
from celery.utils.log import get_task_logger
from .csv_attach import CSVAttachmentWriter
from .models import Transaction
from celeryapp import app
logger = get_task_logger(__name__)
@app.task(max_retries=3)
def email_journal_vouchers_import():
"""
"""
try:
credits = Transaction.objects.export_transactions()
debit = Decimal(0)
attachment = CSVAttachmentWriter()
for credit in credits:
attachment.writerow([credit['product__account_number'], '',
credit['price__sum']])
debit += credit['price__sum']
debit_account = getattr(settings, 'SHOPIFY_DEBIT_ACCOUNT_NUMBER', None)
attachment.writerow([debit_account, debit, ''])
message = EmailMessage('Journal Vouchers Import', '',
to=[m[1] for m in settings.MANAGERS])
message.attach(attachment.getname(), attachment.getvalue(), 'text/csv')
message.send()
except Exception as exc:
logger.debug("MIP export failed: %s" % exc)
logger.warn('MIP export failed, retrying')
raise email_mip_import_file.retry(exc=exc)
|
<commit_before>from decimal import Decimal
from django.conf import settings
from django.core.mail import EmailMessage
from celery.utils.log import get_task_logger
from .csv_attach import CSVAttachmentWriter
from .models import Transaction
from celeryapp import app
logger = get_task_logger(__name__)
@app.task(max_retries=3)
def email_journal_vouchers_import():
"""
"""
try:
credits = Transaction.objects.export_transactions()
debit = Decimal(0)
attachment = CSVAttachmentWriter()
for credit in credits:
attachment.writerow([credit['product__account_number'], '',
credit['price__sum']])
debit += credit['price__sum']
attachment.writerow([settings.SHOPIFY_DEBIT_ACCOUNT_NUMBER, debit, ''])
message = EmailMessage('Journal Vouchers Import', '',
to=[m[1] for m in settings.MANAGERS])
message.attach(attachment.getname(), attachment.getvalue(), 'text/csv')
message.send()
except Exception as exc:
logger.debug("MIP export failed: %s" % exc)
logger.warn('MIP export failed, retrying')
raise email_mip_import_file.retry(exc=exc)
<commit_msg>Fix accessing settings for debit account number<commit_after>from decimal import Decimal
from django.conf import settings
from django.core.mail import EmailMessage
from celery.utils.log import get_task_logger
from .csv_attach import CSVAttachmentWriter
from .models import Transaction
from celeryapp import app
logger = get_task_logger(__name__)
@app.task(max_retries=3)
def email_journal_vouchers_import():
"""
"""
try:
credits = Transaction.objects.export_transactions()
debit = Decimal(0)
attachment = CSVAttachmentWriter()
for credit in credits:
attachment.writerow([credit['product__account_number'], '',
credit['price__sum']])
debit += credit['price__sum']
debit_account = getattr(settings, 'SHOPIFY_DEBIT_ACCOUNT_NUMBER', None)
attachment.writerow([debit_account, debit, ''])
message = EmailMessage('Journal Vouchers Import', '',
to=[m[1] for m in settings.MANAGERS])
message.attach(attachment.getname(), attachment.getvalue(), 'text/csv')
message.send()
except Exception as exc:
logger.debug("MIP export failed: %s" % exc)
logger.warn('MIP export failed, retrying')
raise email_mip_import_file.retry(exc=exc)
|
9fd6e1f96d62934c20b554b112ed8954b1066767
|
setup.py
|
setup.py
|
import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='django-envelope',
version=__import__('envelope').__version__,
description='A contact form app for Django',
long_description=read('README.rst'),
author='Zbigniew Siciarz',
author_email='zbigniew@siciarz.net',
url='http://github.com/zsiciarz/django-envelope',
download_url='http://pypi.python.org/pypi/django-envelope',
license='MIT',
install_requires=['Django>=1.8'],
packages=find_packages(exclude=['example_project', 'tests']),
include_package_data=True,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Utilities',
],
)
|
import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='django-envelope',
version=__import__('envelope').__version__,
description='A contact form app for Django',
long_description=read('README.rst'),
author='Zbigniew Siciarz',
author_email='zbigniew@siciarz.net',
url='http://github.com/zsiciarz/django-envelope',
download_url='http://pypi.python.org/pypi/django-envelope',
license='MIT',
install_requires=['Django>=1.8'],
packages=find_packages(exclude=['example_project', 'tests']),
include_package_data=True,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Utilities',
],
)
|
Mark package as Python 3.6-compatible.
|
Mark package as Python 3.6-compatible.
|
Python
|
mit
|
zsiciarz/django-envelope,zsiciarz/django-envelope
|
import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='django-envelope',
version=__import__('envelope').__version__,
description='A contact form app for Django',
long_description=read('README.rst'),
author='Zbigniew Siciarz',
author_email='zbigniew@siciarz.net',
url='http://github.com/zsiciarz/django-envelope',
download_url='http://pypi.python.org/pypi/django-envelope',
license='MIT',
install_requires=['Django>=1.8'],
packages=find_packages(exclude=['example_project', 'tests']),
include_package_data=True,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Utilities',
],
)
Mark package as Python 3.6-compatible.
|
import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='django-envelope',
version=__import__('envelope').__version__,
description='A contact form app for Django',
long_description=read('README.rst'),
author='Zbigniew Siciarz',
author_email='zbigniew@siciarz.net',
url='http://github.com/zsiciarz/django-envelope',
download_url='http://pypi.python.org/pypi/django-envelope',
license='MIT',
install_requires=['Django>=1.8'],
packages=find_packages(exclude=['example_project', 'tests']),
include_package_data=True,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Utilities',
],
)
|
<commit_before>import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='django-envelope',
version=__import__('envelope').__version__,
description='A contact form app for Django',
long_description=read('README.rst'),
author='Zbigniew Siciarz',
author_email='zbigniew@siciarz.net',
url='http://github.com/zsiciarz/django-envelope',
download_url='http://pypi.python.org/pypi/django-envelope',
license='MIT',
install_requires=['Django>=1.8'],
packages=find_packages(exclude=['example_project', 'tests']),
include_package_data=True,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Utilities',
],
)
<commit_msg>Mark package as Python 3.6-compatible.<commit_after>
|
import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='django-envelope',
version=__import__('envelope').__version__,
description='A contact form app for Django',
long_description=read('README.rst'),
author='Zbigniew Siciarz',
author_email='zbigniew@siciarz.net',
url='http://github.com/zsiciarz/django-envelope',
download_url='http://pypi.python.org/pypi/django-envelope',
license='MIT',
install_requires=['Django>=1.8'],
packages=find_packages(exclude=['example_project', 'tests']),
include_package_data=True,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Utilities',
],
)
|
import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='django-envelope',
version=__import__('envelope').__version__,
description='A contact form app for Django',
long_description=read('README.rst'),
author='Zbigniew Siciarz',
author_email='zbigniew@siciarz.net',
url='http://github.com/zsiciarz/django-envelope',
download_url='http://pypi.python.org/pypi/django-envelope',
license='MIT',
install_requires=['Django>=1.8'],
packages=find_packages(exclude=['example_project', 'tests']),
include_package_data=True,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Utilities',
],
)
Mark package as Python 3.6-compatible.import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='django-envelope',
version=__import__('envelope').__version__,
description='A contact form app for Django',
long_description=read('README.rst'),
author='Zbigniew Siciarz',
author_email='zbigniew@siciarz.net',
url='http://github.com/zsiciarz/django-envelope',
download_url='http://pypi.python.org/pypi/django-envelope',
license='MIT',
install_requires=['Django>=1.8'],
packages=find_packages(exclude=['example_project', 'tests']),
include_package_data=True,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Utilities',
],
)
|
<commit_before>import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='django-envelope',
version=__import__('envelope').__version__,
description='A contact form app for Django',
long_description=read('README.rst'),
author='Zbigniew Siciarz',
author_email='zbigniew@siciarz.net',
url='http://github.com/zsiciarz/django-envelope',
download_url='http://pypi.python.org/pypi/django-envelope',
license='MIT',
install_requires=['Django>=1.8'],
packages=find_packages(exclude=['example_project', 'tests']),
include_package_data=True,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Utilities',
],
)
<commit_msg>Mark package as Python 3.6-compatible.<commit_after>import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='django-envelope',
version=__import__('envelope').__version__,
description='A contact form app for Django',
long_description=read('README.rst'),
author='Zbigniew Siciarz',
author_email='zbigniew@siciarz.net',
url='http://github.com/zsiciarz/django-envelope',
download_url='http://pypi.python.org/pypi/django-envelope',
license='MIT',
install_requires=['Django>=1.8'],
packages=find_packages(exclude=['example_project', 'tests']),
include_package_data=True,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Utilities',
],
)
|
663d0674ebdfd2f4ea5483479890e3a762d57755
|
l10n_ar_aeroo_sale/__openerp__.py
|
l10n_ar_aeroo_sale/__openerp__.py
|
# -*- coding: utf-8 -*-
{
'name': 'Argentinian Like Sale Order Aeroo Report',
'version': '1.0',
'category': 'Localization/Argentina',
'sequence': 14,
'summary': '',
'description': """
Argentinian Like Sale Order / Quotation Aeroo Report
====================================================
""",
'author': 'Ingenieria ADHOC',
'website': 'www.ingadhoc.com',
'images': [
],
'depends': [
'report_extended_sale',
'l10n_ar_aeroo_base',
'portal_sale',
],
'data': [
'report_configuration_defaults_data.xml',
'sale_order_report.xml',
'sale_order_template.xml',
],
'demo': [
],
'test': [
],
'installable': True,
'auto_install': False,
'application': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
# -*- coding: utf-8 -*-
{
'name': 'Argentinian Like Sale Order Aeroo Report',
'version': '1.0',
'category': 'Localization/Argentina',
'sequence': 14,
'summary': '',
'description': """
Argentinian Like Sale Order / Quotation Aeroo Report
====================================================
""",
'author': 'Ingenieria ADHOC',
'website': 'www.ingadhoc.com',
'images': [
],
'depends': [
'report_extended_sale',
'l10n_ar_aeroo_base',
'l10n_ar_aeroo_invoice', #esta dependencia es porque actualizamos algo que crea portal_sale con un valor de las invoice
'portal_sale',
],
'data': [
'report_configuration_defaults_data.xml',
'sale_order_report.xml',
'sale_order_template.xml',
],
'demo': [
],
'test': [
],
'installable': True,
'auto_install': False,
'application': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
FIX dependency on aeroo rpoert
|
FIX dependency on aeroo rpoert
|
Python
|
agpl-3.0
|
bmya/odoo-argentina,ingadhoc/odoo-argentina,jobiols/odoo-argentina,bmya/odoo-argentina,adhoc-dev/odoo-argentina,adrianpaesani/odoo-argentina,jobiols/odoo-argentina,adrianpaesani/odoo-argentina,adhoc-dev/odoo-argentina
|
# -*- coding: utf-8 -*-
{
'name': 'Argentinian Like Sale Order Aeroo Report',
'version': '1.0',
'category': 'Localization/Argentina',
'sequence': 14,
'summary': '',
'description': """
Argentinian Like Sale Order / Quotation Aeroo Report
====================================================
""",
'author': 'Ingenieria ADHOC',
'website': 'www.ingadhoc.com',
'images': [
],
'depends': [
'report_extended_sale',
'l10n_ar_aeroo_base',
'portal_sale',
],
'data': [
'report_configuration_defaults_data.xml',
'sale_order_report.xml',
'sale_order_template.xml',
],
'demo': [
],
'test': [
],
'installable': True,
'auto_install': False,
'application': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:FIX dependency on aeroo rpoert
|
# -*- coding: utf-8 -*-
{
'name': 'Argentinian Like Sale Order Aeroo Report',
'version': '1.0',
'category': 'Localization/Argentina',
'sequence': 14,
'summary': '',
'description': """
Argentinian Like Sale Order / Quotation Aeroo Report
====================================================
""",
'author': 'Ingenieria ADHOC',
'website': 'www.ingadhoc.com',
'images': [
],
'depends': [
'report_extended_sale',
'l10n_ar_aeroo_base',
'l10n_ar_aeroo_invoice', #esta dependencia es porque actualizamos algo que crea portal_sale con un valor de las invoice
'portal_sale',
],
'data': [
'report_configuration_defaults_data.xml',
'sale_order_report.xml',
'sale_order_template.xml',
],
'demo': [
],
'test': [
],
'installable': True,
'auto_install': False,
'application': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
<commit_before># -*- coding: utf-8 -*-
{
'name': 'Argentinian Like Sale Order Aeroo Report',
'version': '1.0',
'category': 'Localization/Argentina',
'sequence': 14,
'summary': '',
'description': """
Argentinian Like Sale Order / Quotation Aeroo Report
====================================================
""",
'author': 'Ingenieria ADHOC',
'website': 'www.ingadhoc.com',
'images': [
],
'depends': [
'report_extended_sale',
'l10n_ar_aeroo_base',
'portal_sale',
],
'data': [
'report_configuration_defaults_data.xml',
'sale_order_report.xml',
'sale_order_template.xml',
],
'demo': [
],
'test': [
],
'installable': True,
'auto_install': False,
'application': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:<commit_msg>FIX dependency on aeroo rpoert<commit_after>
|
# -*- coding: utf-8 -*-
{
'name': 'Argentinian Like Sale Order Aeroo Report',
'version': '1.0',
'category': 'Localization/Argentina',
'sequence': 14,
'summary': '',
'description': """
Argentinian Like Sale Order / Quotation Aeroo Report
====================================================
""",
'author': 'Ingenieria ADHOC',
'website': 'www.ingadhoc.com',
'images': [
],
'depends': [
'report_extended_sale',
'l10n_ar_aeroo_base',
'l10n_ar_aeroo_invoice', #esta dependencia es porque actualizamos algo que crea portal_sale con un valor de las invoice
'portal_sale',
],
'data': [
'report_configuration_defaults_data.xml',
'sale_order_report.xml',
'sale_order_template.xml',
],
'demo': [
],
'test': [
],
'installable': True,
'auto_install': False,
'application': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
# -*- coding: utf-8 -*-
{
'name': 'Argentinian Like Sale Order Aeroo Report',
'version': '1.0',
'category': 'Localization/Argentina',
'sequence': 14,
'summary': '',
'description': """
Argentinian Like Sale Order / Quotation Aeroo Report
====================================================
""",
'author': 'Ingenieria ADHOC',
'website': 'www.ingadhoc.com',
'images': [
],
'depends': [
'report_extended_sale',
'l10n_ar_aeroo_base',
'portal_sale',
],
'data': [
'report_configuration_defaults_data.xml',
'sale_order_report.xml',
'sale_order_template.xml',
],
'demo': [
],
'test': [
],
'installable': True,
'auto_install': False,
'application': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:FIX dependency on aeroo rpoert# -*- coding: utf-8 -*-
{
'name': 'Argentinian Like Sale Order Aeroo Report',
'version': '1.0',
'category': 'Localization/Argentina',
'sequence': 14,
'summary': '',
'description': """
Argentinian Like Sale Order / Quotation Aeroo Report
====================================================
""",
'author': 'Ingenieria ADHOC',
'website': 'www.ingadhoc.com',
'images': [
],
'depends': [
'report_extended_sale',
'l10n_ar_aeroo_base',
'l10n_ar_aeroo_invoice', #esta dependencia es porque actualizamos algo que crea portal_sale con un valor de las invoice
'portal_sale',
],
'data': [
'report_configuration_defaults_data.xml',
'sale_order_report.xml',
'sale_order_template.xml',
],
'demo': [
],
'test': [
],
'installable': True,
'auto_install': False,
'application': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
<commit_before># -*- coding: utf-8 -*-
{
'name': 'Argentinian Like Sale Order Aeroo Report',
'version': '1.0',
'category': 'Localization/Argentina',
'sequence': 14,
'summary': '',
'description': """
Argentinian Like Sale Order / Quotation Aeroo Report
====================================================
""",
'author': 'Ingenieria ADHOC',
'website': 'www.ingadhoc.com',
'images': [
],
'depends': [
'report_extended_sale',
'l10n_ar_aeroo_base',
'portal_sale',
],
'data': [
'report_configuration_defaults_data.xml',
'sale_order_report.xml',
'sale_order_template.xml',
],
'demo': [
],
'test': [
],
'installable': True,
'auto_install': False,
'application': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:<commit_msg>FIX dependency on aeroo rpoert<commit_after># -*- coding: utf-8 -*-
{
'name': 'Argentinian Like Sale Order Aeroo Report',
'version': '1.0',
'category': 'Localization/Argentina',
'sequence': 14,
'summary': '',
'description': """
Argentinian Like Sale Order / Quotation Aeroo Report
====================================================
""",
'author': 'Ingenieria ADHOC',
'website': 'www.ingadhoc.com',
'images': [
],
'depends': [
'report_extended_sale',
'l10n_ar_aeroo_base',
'l10n_ar_aeroo_invoice', #esta dependencia es porque actualizamos algo que crea portal_sale con un valor de las invoice
'portal_sale',
],
'data': [
'report_configuration_defaults_data.xml',
'sale_order_report.xml',
'sale_order_template.xml',
],
'demo': [
],
'test': [
],
'installable': True,
'auto_install': False,
'application': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
d508def47782bb89a89846400c3d1a25e81f078b
|
setup.py
|
setup.py
|
from setuptools import setup, find_packages
setup(name='pyroSAR',
packages=find_packages(),
include_package_data=True,
version='0.1',
description='a framework for large-scale SAR satellite data processing',
classifiers=[
'Programming Language :: Python :: 2.7',
],
install_requires=['progressbar==2.3',
'pathos>=0.2',
'numpy',
'scoop'],
url='https://github.com/johntruckenbrodt/pyroSAR.git',
author='John Truckenbrodt',
author_email='john.truckenbrodt@uni-jena.de',
license='MIT',
zip_safe=False)
|
from setuptools import setup, find_packages
import os
# Create .pyrosar in HOME - Directory
directory = os.path.join(os.path.expanduser("~"), '.pyrosar')
if not os.path.exists(directory):
os.makedirs(directory)
setup(name='pyroSAR',
packages=find_packages(),
include_package_data=True,
version='0.1',
description='a framework for large-scale SAR satellite data processing',
classifiers=[
'Programming Language :: Python :: 2.7',
],
install_requires=['progressbar==2.3',
'pathos>=0.2',
'numpy',
'scoop'],
url='https://github.com/johntruckenbrodt/pyroSAR.git',
author='John Truckenbrodt',
author_email='john.truckenbrodt@uni-jena.de',
license='MIT',
zip_safe=False)
|
Add DIR to HOME * Add .pyrosar directory to HOME-path.
|
Add DIR to HOME
* Add .pyrosar directory to HOME-path.
|
Python
|
mit
|
johntruckenbrodt/pyroSAR,johntruckenbrodt/pyroSAR
|
from setuptools import setup, find_packages
setup(name='pyroSAR',
packages=find_packages(),
include_package_data=True,
version='0.1',
description='a framework for large-scale SAR satellite data processing',
classifiers=[
'Programming Language :: Python :: 2.7',
],
install_requires=['progressbar==2.3',
'pathos>=0.2',
'numpy',
'scoop'],
url='https://github.com/johntruckenbrodt/pyroSAR.git',
author='John Truckenbrodt',
author_email='john.truckenbrodt@uni-jena.de',
license='MIT',
zip_safe=False)
Add DIR to HOME
* Add .pyrosar directory to HOME-path.
|
from setuptools import setup, find_packages
import os
# Create .pyrosar in HOME - Directory
directory = os.path.join(os.path.expanduser("~"), '.pyrosar')
if not os.path.exists(directory):
os.makedirs(directory)
setup(name='pyroSAR',
packages=find_packages(),
include_package_data=True,
version='0.1',
description='a framework for large-scale SAR satellite data processing',
classifiers=[
'Programming Language :: Python :: 2.7',
],
install_requires=['progressbar==2.3',
'pathos>=0.2',
'numpy',
'scoop'],
url='https://github.com/johntruckenbrodt/pyroSAR.git',
author='John Truckenbrodt',
author_email='john.truckenbrodt@uni-jena.de',
license='MIT',
zip_safe=False)
|
<commit_before>from setuptools import setup, find_packages
setup(name='pyroSAR',
packages=find_packages(),
include_package_data=True,
version='0.1',
description='a framework for large-scale SAR satellite data processing',
classifiers=[
'Programming Language :: Python :: 2.7',
],
install_requires=['progressbar==2.3',
'pathos>=0.2',
'numpy',
'scoop'],
url='https://github.com/johntruckenbrodt/pyroSAR.git',
author='John Truckenbrodt',
author_email='john.truckenbrodt@uni-jena.de',
license='MIT',
zip_safe=False)
<commit_msg>Add DIR to HOME
* Add .pyrosar directory to HOME-path.<commit_after>
|
from setuptools import setup, find_packages
import os
# Create .pyrosar in HOME - Directory
directory = os.path.join(os.path.expanduser("~"), '.pyrosar')
if not os.path.exists(directory):
os.makedirs(directory)
setup(name='pyroSAR',
packages=find_packages(),
include_package_data=True,
version='0.1',
description='a framework for large-scale SAR satellite data processing',
classifiers=[
'Programming Language :: Python :: 2.7',
],
install_requires=['progressbar==2.3',
'pathos>=0.2',
'numpy',
'scoop'],
url='https://github.com/johntruckenbrodt/pyroSAR.git',
author='John Truckenbrodt',
author_email='john.truckenbrodt@uni-jena.de',
license='MIT',
zip_safe=False)
|
from setuptools import setup, find_packages
setup(name='pyroSAR',
packages=find_packages(),
include_package_data=True,
version='0.1',
description='a framework for large-scale SAR satellite data processing',
classifiers=[
'Programming Language :: Python :: 2.7',
],
install_requires=['progressbar==2.3',
'pathos>=0.2',
'numpy',
'scoop'],
url='https://github.com/johntruckenbrodt/pyroSAR.git',
author='John Truckenbrodt',
author_email='john.truckenbrodt@uni-jena.de',
license='MIT',
zip_safe=False)
Add DIR to HOME
* Add .pyrosar directory to HOME-path.from setuptools import setup, find_packages
import os
# Create .pyrosar in HOME - Directory
directory = os.path.join(os.path.expanduser("~"), '.pyrosar')
if not os.path.exists(directory):
os.makedirs(directory)
setup(name='pyroSAR',
packages=find_packages(),
include_package_data=True,
version='0.1',
description='a framework for large-scale SAR satellite data processing',
classifiers=[
'Programming Language :: Python :: 2.7',
],
install_requires=['progressbar==2.3',
'pathos>=0.2',
'numpy',
'scoop'],
url='https://github.com/johntruckenbrodt/pyroSAR.git',
author='John Truckenbrodt',
author_email='john.truckenbrodt@uni-jena.de',
license='MIT',
zip_safe=False)
|
<commit_before>from setuptools import setup, find_packages
setup(name='pyroSAR',
packages=find_packages(),
include_package_data=True,
version='0.1',
description='a framework for large-scale SAR satellite data processing',
classifiers=[
'Programming Language :: Python :: 2.7',
],
install_requires=['progressbar==2.3',
'pathos>=0.2',
'numpy',
'scoop'],
url='https://github.com/johntruckenbrodt/pyroSAR.git',
author='John Truckenbrodt',
author_email='john.truckenbrodt@uni-jena.de',
license='MIT',
zip_safe=False)
<commit_msg>Add DIR to HOME
* Add .pyrosar directory to HOME-path.<commit_after>from setuptools import setup, find_packages
import os
# Create .pyrosar in HOME - Directory
directory = os.path.join(os.path.expanduser("~"), '.pyrosar')
if not os.path.exists(directory):
os.makedirs(directory)
setup(name='pyroSAR',
packages=find_packages(),
include_package_data=True,
version='0.1',
description='a framework for large-scale SAR satellite data processing',
classifiers=[
'Programming Language :: Python :: 2.7',
],
install_requires=['progressbar==2.3',
'pathos>=0.2',
'numpy',
'scoop'],
url='https://github.com/johntruckenbrodt/pyroSAR.git',
author='John Truckenbrodt',
author_email='john.truckenbrodt@uni-jena.de',
license='MIT',
zip_safe=False)
|
9ff382cd398bf1ff3d700ad3eb567d48945a142b
|
setup.py
|
setup.py
|
try:
from setuptools import setup
from setuptools import find_packages
packages = find_packages()
except ImportError:
from distutils.core import setup
import os
packages = [x.strip('./').replace('/','.') for x in os.popen('find . -name "__init__.py" | xargs -n1 dirname').read().strip().split('\n')]
if bytes is str:
raise Exception("This module is designed for python 3 only. Please install an older version to use python 2.")
setup(
name='archinfo',
version='8.20.1.7',
python_requires='>=3.5',
packages=packages,
package_data={'archinfo': ['py.typed']},
url="https://github.com/angr/archinfo",
)
|
try:
from setuptools import setup
from setuptools import find_packages
packages = find_packages()
except ImportError:
from distutils.core import setup
import os
packages = [x.strip('./').replace('/','.') for x in os.popen('find . -name "__init__.py" | xargs -n1 dirname').read().strip().split('\n')]
if bytes is str:
raise Exception("This module is designed for python 3 only. Please install an older version to use python 2.")
setup(
name='archinfo',
version='8.20.1.7',
python_requires='>=3.6',
packages=packages,
package_data={'archinfo': ['py.typed']},
url="https://github.com/angr/archinfo",
)
|
Mark requirement for python 3.6
|
Mark requirement for python 3.6
|
Python
|
bsd-2-clause
|
angr/archinfo
|
try:
from setuptools import setup
from setuptools import find_packages
packages = find_packages()
except ImportError:
from distutils.core import setup
import os
packages = [x.strip('./').replace('/','.') for x in os.popen('find . -name "__init__.py" | xargs -n1 dirname').read().strip().split('\n')]
if bytes is str:
raise Exception("This module is designed for python 3 only. Please install an older version to use python 2.")
setup(
name='archinfo',
version='8.20.1.7',
python_requires='>=3.5',
packages=packages,
package_data={'archinfo': ['py.typed']},
url="https://github.com/angr/archinfo",
)
Mark requirement for python 3.6
|
try:
from setuptools import setup
from setuptools import find_packages
packages = find_packages()
except ImportError:
from distutils.core import setup
import os
packages = [x.strip('./').replace('/','.') for x in os.popen('find . -name "__init__.py" | xargs -n1 dirname').read().strip().split('\n')]
if bytes is str:
raise Exception("This module is designed for python 3 only. Please install an older version to use python 2.")
setup(
name='archinfo',
version='8.20.1.7',
python_requires='>=3.6',
packages=packages,
package_data={'archinfo': ['py.typed']},
url="https://github.com/angr/archinfo",
)
|
<commit_before>try:
from setuptools import setup
from setuptools import find_packages
packages = find_packages()
except ImportError:
from distutils.core import setup
import os
packages = [x.strip('./').replace('/','.') for x in os.popen('find . -name "__init__.py" | xargs -n1 dirname').read().strip().split('\n')]
if bytes is str:
raise Exception("This module is designed for python 3 only. Please install an older version to use python 2.")
setup(
name='archinfo',
version='8.20.1.7',
python_requires='>=3.5',
packages=packages,
package_data={'archinfo': ['py.typed']},
url="https://github.com/angr/archinfo",
)
<commit_msg>Mark requirement for python 3.6<commit_after>
|
try:
from setuptools import setup
from setuptools import find_packages
packages = find_packages()
except ImportError:
from distutils.core import setup
import os
packages = [x.strip('./').replace('/','.') for x in os.popen('find . -name "__init__.py" | xargs -n1 dirname').read().strip().split('\n')]
if bytes is str:
raise Exception("This module is designed for python 3 only. Please install an older version to use python 2.")
setup(
name='archinfo',
version='8.20.1.7',
python_requires='>=3.6',
packages=packages,
package_data={'archinfo': ['py.typed']},
url="https://github.com/angr/archinfo",
)
|
try:
from setuptools import setup
from setuptools import find_packages
packages = find_packages()
except ImportError:
from distutils.core import setup
import os
packages = [x.strip('./').replace('/','.') for x in os.popen('find . -name "__init__.py" | xargs -n1 dirname').read().strip().split('\n')]
if bytes is str:
raise Exception("This module is designed for python 3 only. Please install an older version to use python 2.")
setup(
name='archinfo',
version='8.20.1.7',
python_requires='>=3.5',
packages=packages,
package_data={'archinfo': ['py.typed']},
url="https://github.com/angr/archinfo",
)
Mark requirement for python 3.6try:
from setuptools import setup
from setuptools import find_packages
packages = find_packages()
except ImportError:
from distutils.core import setup
import os
packages = [x.strip('./').replace('/','.') for x in os.popen('find . -name "__init__.py" | xargs -n1 dirname').read().strip().split('\n')]
if bytes is str:
raise Exception("This module is designed for python 3 only. Please install an older version to use python 2.")
setup(
name='archinfo',
version='8.20.1.7',
python_requires='>=3.6',
packages=packages,
package_data={'archinfo': ['py.typed']},
url="https://github.com/angr/archinfo",
)
|
<commit_before>try:
from setuptools import setup
from setuptools import find_packages
packages = find_packages()
except ImportError:
from distutils.core import setup
import os
packages = [x.strip('./').replace('/','.') for x in os.popen('find . -name "__init__.py" | xargs -n1 dirname').read().strip().split('\n')]
if bytes is str:
raise Exception("This module is designed for python 3 only. Please install an older version to use python 2.")
setup(
name='archinfo',
version='8.20.1.7',
python_requires='>=3.5',
packages=packages,
package_data={'archinfo': ['py.typed']},
url="https://github.com/angr/archinfo",
)
<commit_msg>Mark requirement for python 3.6<commit_after>try:
from setuptools import setup
from setuptools import find_packages
packages = find_packages()
except ImportError:
from distutils.core import setup
import os
packages = [x.strip('./').replace('/','.') for x in os.popen('find . -name "__init__.py" | xargs -n1 dirname').read().strip().split('\n')]
if bytes is str:
raise Exception("This module is designed for python 3 only. Please install an older version to use python 2.")
setup(
name='archinfo',
version='8.20.1.7',
python_requires='>=3.6',
packages=packages,
package_data={'archinfo': ['py.typed']},
url="https://github.com/angr/archinfo",
)
|
0b3220b0e212bba1dd197e6d2304249142b332c8
|
presentationsapp/views.py
|
presentationsapp/views.py
|
from django.shortcuts import render, redirect
from models import *
# Create your views here.
def index(req):
return render(req, "landing.html", {'request': req})
def login(req):
return render(req, "login.html", {'request': req})
def register(req):
if req.method == 'POST':
try:
user = User(email = req.POST['email'])
user.set_password(req.POST['password'])
req.session['email'] = req.POST['email']
return redirect("/")
except:
# I'm kind of lazy
pass
return render(req, "register.html", {'request': req})
def logout(req):
del req.session['email']
return redirect("/")
|
from django.shortcuts import render, redirect
from models import *
# Create your views here.
def index(req):
return render(req, "landing.html", {'request': req})
def login(req):
if req.method == 'POST':
try:
user = User.objects.get(email = req.POST['email'])
if user.check_password(req.POST['password']):
req.session['email'] = req.POST['email']
return redirect("/")
except:
pass
return render(req, "login.html", {'request': req})
def register(req):
if req.method == 'POST':
try:
user = User(email = req.POST['email'])
user.set_password(req.POST['password'])
user.save()
req.session['email'] = req.POST['email']
return redirect("/")
except:
# I'm kind of lazy
pass
return render(req, "register.html", {'request': req})
def logout(req):
del req.session['email']
return redirect("/")
|
Add save for registration & login logic
|
Add save for registration & login logic
|
Python
|
mit
|
masonsbro/presentations
|
from django.shortcuts import render, redirect
from models import *
# Create your views here.
def index(req):
return render(req, "landing.html", {'request': req})
def login(req):
return render(req, "login.html", {'request': req})
def register(req):
if req.method == 'POST':
try:
user = User(email = req.POST['email'])
user.set_password(req.POST['password'])
req.session['email'] = req.POST['email']
return redirect("/")
except:
# I'm kind of lazy
pass
return render(req, "register.html", {'request': req})
def logout(req):
del req.session['email']
return redirect("/")
Add save for registration & login logic
|
from django.shortcuts import render, redirect
from models import *
# Create your views here.
def index(req):
return render(req, "landing.html", {'request': req})
def login(req):
if req.method == 'POST':
try:
user = User.objects.get(email = req.POST['email'])
if user.check_password(req.POST['password']):
req.session['email'] = req.POST['email']
return redirect("/")
except:
pass
return render(req, "login.html", {'request': req})
def register(req):
if req.method == 'POST':
try:
user = User(email = req.POST['email'])
user.set_password(req.POST['password'])
user.save()
req.session['email'] = req.POST['email']
return redirect("/")
except:
# I'm kind of lazy
pass
return render(req, "register.html", {'request': req})
def logout(req):
del req.session['email']
return redirect("/")
|
<commit_before>from django.shortcuts import render, redirect
from models import *
# Create your views here.
def index(req):
return render(req, "landing.html", {'request': req})
def login(req):
return render(req, "login.html", {'request': req})
def register(req):
if req.method == 'POST':
try:
user = User(email = req.POST['email'])
user.set_password(req.POST['password'])
req.session['email'] = req.POST['email']
return redirect("/")
except:
# I'm kind of lazy
pass
return render(req, "register.html", {'request': req})
def logout(req):
del req.session['email']
return redirect("/")
<commit_msg>Add save for registration & login logic<commit_after>
|
from django.shortcuts import render, redirect
from models import *
# Create your views here.
def index(req):
return render(req, "landing.html", {'request': req})
def login(req):
if req.method == 'POST':
try:
user = User.objects.get(email = req.POST['email'])
if user.check_password(req.POST['password']):
req.session['email'] = req.POST['email']
return redirect("/")
except:
pass
return render(req, "login.html", {'request': req})
def register(req):
if req.method == 'POST':
try:
user = User(email = req.POST['email'])
user.set_password(req.POST['password'])
user.save()
req.session['email'] = req.POST['email']
return redirect("/")
except:
# I'm kind of lazy
pass
return render(req, "register.html", {'request': req})
def logout(req):
del req.session['email']
return redirect("/")
|
from django.shortcuts import render, redirect
from models import *
# Create your views here.
def index(req):
return render(req, "landing.html", {'request': req})
def login(req):
return render(req, "login.html", {'request': req})
def register(req):
if req.method == 'POST':
try:
user = User(email = req.POST['email'])
user.set_password(req.POST['password'])
req.session['email'] = req.POST['email']
return redirect("/")
except:
# I'm kind of lazy
pass
return render(req, "register.html", {'request': req})
def logout(req):
del req.session['email']
return redirect("/")
Add save for registration & login logicfrom django.shortcuts import render, redirect
from models import *
# Create your views here.
def index(req):
return render(req, "landing.html", {'request': req})
def login(req):
if req.method == 'POST':
try:
user = User.objects.get(email = req.POST['email'])
if user.check_password(req.POST['password']):
req.session['email'] = req.POST['email']
return redirect("/")
except:
pass
return render(req, "login.html", {'request': req})
def register(req):
if req.method == 'POST':
try:
user = User(email = req.POST['email'])
user.set_password(req.POST['password'])
user.save()
req.session['email'] = req.POST['email']
return redirect("/")
except:
# I'm kind of lazy
pass
return render(req, "register.html", {'request': req})
def logout(req):
del req.session['email']
return redirect("/")
|
<commit_before>from django.shortcuts import render, redirect
from models import *
# Create your views here.
def index(req):
return render(req, "landing.html", {'request': req})
def login(req):
return render(req, "login.html", {'request': req})
def register(req):
if req.method == 'POST':
try:
user = User(email = req.POST['email'])
user.set_password(req.POST['password'])
req.session['email'] = req.POST['email']
return redirect("/")
except:
# I'm kind of lazy
pass
return render(req, "register.html", {'request': req})
def logout(req):
del req.session['email']
return redirect("/")
<commit_msg>Add save for registration & login logic<commit_after>from django.shortcuts import render, redirect
from models import *
# Create your views here.
def index(req):
return render(req, "landing.html", {'request': req})
def login(req):
if req.method == 'POST':
try:
user = User.objects.get(email = req.POST['email'])
if user.check_password(req.POST['password']):
req.session['email'] = req.POST['email']
return redirect("/")
except:
pass
return render(req, "login.html", {'request': req})
def register(req):
if req.method == 'POST':
try:
user = User(email = req.POST['email'])
user.set_password(req.POST['password'])
user.save()
req.session['email'] = req.POST['email']
return redirect("/")
except:
# I'm kind of lazy
pass
return render(req, "register.html", {'request': req})
def logout(req):
del req.session['email']
return redirect("/")
|
6e8895d08ff85bf5ba35765161890e77faba5715
|
pryvate/blueprints/simple/simple.py
|
pryvate/blueprints/simple/simple.py
|
"""Simple blueprint."""
import os
from flask import Blueprint, current_app, render_template
blueprint = Blueprint('simple', __name__, url_prefix='/simple',
template_folder='templates')
@blueprint.route('', methods=['GET'])
def get_simple():
"""List all packages."""
packages = os.listdir(current_app.config['BASEDIR'])
return render_template('simple.html', packages=packages)
@blueprint.route('/<package>', methods=['GET'])
@blueprint.route('/<package>/', methods=['GET'])
def get_package(package):
"""List versions of a package."""
package_path = os.path.join(current_app.config['BASEDIR'],
package.lower())
files = os.listdir(package_path)
packages = []
for filename in files:
if filename.endswith('md5'):
with open(os.path.join(package_path, filename), 'r') as md5_digest:
item = {
'name': package,
'version': filename.replace('.md5', ''),
'digest': md5_digest.read()
}
packages.append(item)
return render_template('simple_package.html', packages=packages,
letter=package[:1].lower())
|
"""Simple blueprint."""
import os
from flask import Blueprint, current_app, make_response, render_template
blueprint = Blueprint('simple', __name__, url_prefix='/simple',
template_folder='templates')
@blueprint.route('', methods=['POST'])
def search_simple():
"""Handling pip search."""
return make_response('Not implemented', 501)
@blueprint.route('', methods=['GET'])
def get_simple():
"""List all packages."""
packages = os.listdir(current_app.config['BASEDIR'])
return render_template('simple.html', packages=packages)
@blueprint.route('/<package>', methods=['GET'])
@blueprint.route('/<package>/', methods=['GET'])
def get_package(package):
"""List versions of a package."""
package_path = os.path.join(current_app.config['BASEDIR'],
package.lower())
files = os.listdir(package_path)
packages = []
for filename in files:
if filename.endswith('md5'):
with open(os.path.join(package_path, filename), 'r') as md5_digest:
item = {
'name': package,
'version': filename.replace('.md5', ''),
'digest': md5_digest.read()
}
packages.append(item)
return render_template('simple_package.html', packages=packages,
letter=package[:1].lower())
|
Return 501 on pip search requests
|
Return 501 on pip search requests
|
Python
|
mit
|
Dinoshauer/pryvate,Dinoshauer/pryvate
|
"""Simple blueprint."""
import os
from flask import Blueprint, current_app, render_template
blueprint = Blueprint('simple', __name__, url_prefix='/simple',
template_folder='templates')
@blueprint.route('', methods=['GET'])
def get_simple():
"""List all packages."""
packages = os.listdir(current_app.config['BASEDIR'])
return render_template('simple.html', packages=packages)
@blueprint.route('/<package>', methods=['GET'])
@blueprint.route('/<package>/', methods=['GET'])
def get_package(package):
"""List versions of a package."""
package_path = os.path.join(current_app.config['BASEDIR'],
package.lower())
files = os.listdir(package_path)
packages = []
for filename in files:
if filename.endswith('md5'):
with open(os.path.join(package_path, filename), 'r') as md5_digest:
item = {
'name': package,
'version': filename.replace('.md5', ''),
'digest': md5_digest.read()
}
packages.append(item)
return render_template('simple_package.html', packages=packages,
letter=package[:1].lower())
Return 501 on pip search requests
|
"""Simple blueprint."""
import os
from flask import Blueprint, current_app, make_response, render_template
blueprint = Blueprint('simple', __name__, url_prefix='/simple',
template_folder='templates')
@blueprint.route('', methods=['POST'])
def search_simple():
"""Handling pip search."""
return make_response('Not implemented', 501)
@blueprint.route('', methods=['GET'])
def get_simple():
"""List all packages."""
packages = os.listdir(current_app.config['BASEDIR'])
return render_template('simple.html', packages=packages)
@blueprint.route('/<package>', methods=['GET'])
@blueprint.route('/<package>/', methods=['GET'])
def get_package(package):
"""List versions of a package."""
package_path = os.path.join(current_app.config['BASEDIR'],
package.lower())
files = os.listdir(package_path)
packages = []
for filename in files:
if filename.endswith('md5'):
with open(os.path.join(package_path, filename), 'r') as md5_digest:
item = {
'name': package,
'version': filename.replace('.md5', ''),
'digest': md5_digest.read()
}
packages.append(item)
return render_template('simple_package.html', packages=packages,
letter=package[:1].lower())
|
<commit_before>"""Simple blueprint."""
import os
from flask import Blueprint, current_app, render_template
blueprint = Blueprint('simple', __name__, url_prefix='/simple',
template_folder='templates')
@blueprint.route('', methods=['GET'])
def get_simple():
"""List all packages."""
packages = os.listdir(current_app.config['BASEDIR'])
return render_template('simple.html', packages=packages)
@blueprint.route('/<package>', methods=['GET'])
@blueprint.route('/<package>/', methods=['GET'])
def get_package(package):
"""List versions of a package."""
package_path = os.path.join(current_app.config['BASEDIR'],
package.lower())
files = os.listdir(package_path)
packages = []
for filename in files:
if filename.endswith('md5'):
with open(os.path.join(package_path, filename), 'r') as md5_digest:
item = {
'name': package,
'version': filename.replace('.md5', ''),
'digest': md5_digest.read()
}
packages.append(item)
return render_template('simple_package.html', packages=packages,
letter=package[:1].lower())
<commit_msg>Return 501 on pip search requests<commit_after>
|
"""Simple blueprint."""
import os
from flask import Blueprint, current_app, make_response, render_template
blueprint = Blueprint('simple', __name__, url_prefix='/simple',
template_folder='templates')
@blueprint.route('', methods=['POST'])
def search_simple():
"""Handling pip search."""
return make_response('Not implemented', 501)
@blueprint.route('', methods=['GET'])
def get_simple():
"""List all packages."""
packages = os.listdir(current_app.config['BASEDIR'])
return render_template('simple.html', packages=packages)
@blueprint.route('/<package>', methods=['GET'])
@blueprint.route('/<package>/', methods=['GET'])
def get_package(package):
"""List versions of a package."""
package_path = os.path.join(current_app.config['BASEDIR'],
package.lower())
files = os.listdir(package_path)
packages = []
for filename in files:
if filename.endswith('md5'):
with open(os.path.join(package_path, filename), 'r') as md5_digest:
item = {
'name': package,
'version': filename.replace('.md5', ''),
'digest': md5_digest.read()
}
packages.append(item)
return render_template('simple_package.html', packages=packages,
letter=package[:1].lower())
|
"""Simple blueprint."""
import os
from flask import Blueprint, current_app, render_template
blueprint = Blueprint('simple', __name__, url_prefix='/simple',
template_folder='templates')
@blueprint.route('', methods=['GET'])
def get_simple():
"""List all packages."""
packages = os.listdir(current_app.config['BASEDIR'])
return render_template('simple.html', packages=packages)
@blueprint.route('/<package>', methods=['GET'])
@blueprint.route('/<package>/', methods=['GET'])
def get_package(package):
"""List versions of a package."""
package_path = os.path.join(current_app.config['BASEDIR'],
package.lower())
files = os.listdir(package_path)
packages = []
for filename in files:
if filename.endswith('md5'):
with open(os.path.join(package_path, filename), 'r') as md5_digest:
item = {
'name': package,
'version': filename.replace('.md5', ''),
'digest': md5_digest.read()
}
packages.append(item)
return render_template('simple_package.html', packages=packages,
letter=package[:1].lower())
Return 501 on pip search requests"""Simple blueprint."""
import os
from flask import Blueprint, current_app, make_response, render_template
blueprint = Blueprint('simple', __name__, url_prefix='/simple',
template_folder='templates')
@blueprint.route('', methods=['POST'])
def search_simple():
"""Handling pip search."""
return make_response('Not implemented', 501)
@blueprint.route('', methods=['GET'])
def get_simple():
"""List all packages."""
packages = os.listdir(current_app.config['BASEDIR'])
return render_template('simple.html', packages=packages)
@blueprint.route('/<package>', methods=['GET'])
@blueprint.route('/<package>/', methods=['GET'])
def get_package(package):
"""List versions of a package."""
package_path = os.path.join(current_app.config['BASEDIR'],
package.lower())
files = os.listdir(package_path)
packages = []
for filename in files:
if filename.endswith('md5'):
with open(os.path.join(package_path, filename), 'r') as md5_digest:
item = {
'name': package,
'version': filename.replace('.md5', ''),
'digest': md5_digest.read()
}
packages.append(item)
return render_template('simple_package.html', packages=packages,
letter=package[:1].lower())
|
<commit_before>"""Simple blueprint."""
import os
from flask import Blueprint, current_app, render_template
blueprint = Blueprint('simple', __name__, url_prefix='/simple',
template_folder='templates')
@blueprint.route('', methods=['GET'])
def get_simple():
"""List all packages."""
packages = os.listdir(current_app.config['BASEDIR'])
return render_template('simple.html', packages=packages)
@blueprint.route('/<package>', methods=['GET'])
@blueprint.route('/<package>/', methods=['GET'])
def get_package(package):
"""List versions of a package."""
package_path = os.path.join(current_app.config['BASEDIR'],
package.lower())
files = os.listdir(package_path)
packages = []
for filename in files:
if filename.endswith('md5'):
with open(os.path.join(package_path, filename), 'r') as md5_digest:
item = {
'name': package,
'version': filename.replace('.md5', ''),
'digest': md5_digest.read()
}
packages.append(item)
return render_template('simple_package.html', packages=packages,
letter=package[:1].lower())
<commit_msg>Return 501 on pip search requests<commit_after>"""Simple blueprint."""
import os
from flask import Blueprint, current_app, make_response, render_template
blueprint = Blueprint('simple', __name__, url_prefix='/simple',
template_folder='templates')
@blueprint.route('', methods=['POST'])
def search_simple():
"""Handling pip search."""
return make_response('Not implemented', 501)
@blueprint.route('', methods=['GET'])
def get_simple():
"""List all packages."""
packages = os.listdir(current_app.config['BASEDIR'])
return render_template('simple.html', packages=packages)
@blueprint.route('/<package>', methods=['GET'])
@blueprint.route('/<package>/', methods=['GET'])
def get_package(package):
"""List versions of a package."""
package_path = os.path.join(current_app.config['BASEDIR'],
package.lower())
files = os.listdir(package_path)
packages = []
for filename in files:
if filename.endswith('md5'):
with open(os.path.join(package_path, filename), 'r') as md5_digest:
item = {
'name': package,
'version': filename.replace('.md5', ''),
'digest': md5_digest.read()
}
packages.append(item)
return render_template('simple_package.html', packages=packages,
letter=package[:1].lower())
|
1c7c0f081711654095023a984978cd812ac94fb6
|
numpy/tests/typing/reveal/modules.py
|
numpy/tests/typing/reveal/modules.py
|
import numpy as np
reveal_type(np) # E: ModuleType
reveal_type(np.char) # E: ModuleType
reveal_type(np.compat) # E: ModuleType
reveal_type(np.core) # E: ModuleType
reveal_type(np.ctypeslib) # E: ModuleType
reveal_type(np.emath) # E: ModuleType
reveal_type(np.fft) # E: ModuleType
reveal_type(np.lib) # E: ModuleType
reveal_type(np.linalg) # E: ModuleType
reveal_type(np.ma) # E: ModuleType
reveal_type(np.matrixlib) # E: ModuleType
reveal_type(np.polynomial) # E: ModuleType
reveal_type(np.random) # E: ModuleType
reveal_type(np.rec) # E: ModuleType
reveal_type(np.testing) # E: ModuleType
reveal_type(np.version) # E: ModuleType
# TODO: Remove when annotations have been added to `np.testing.assert_equal`
reveal_type(np.testing.assert_equal) # E: Any
|
import numpy as np
reveal_type(np) # E: ModuleType
reveal_type(np.char) # E: ModuleType
reveal_type(np.ctypeslib) # E: ModuleType
reveal_type(np.emath) # E: ModuleType
reveal_type(np.fft) # E: ModuleType
reveal_type(np.lib) # E: ModuleType
reveal_type(np.linalg) # E: ModuleType
reveal_type(np.ma) # E: ModuleType
reveal_type(np.matrixlib) # E: ModuleType
reveal_type(np.polynomial) # E: ModuleType
reveal_type(np.random) # E: ModuleType
reveal_type(np.rec) # E: ModuleType
reveal_type(np.testing) # E: ModuleType
reveal_type(np.version) # E: ModuleType
# TODO: Remove when annotations have been added to `np.testing.assert_equal`
reveal_type(np.testing.assert_equal) # E: Any
|
Remove `compat` and `core` from the tests
|
TST: Remove `compat` and `core` from the tests
|
Python
|
bsd-3-clause
|
anntzer/numpy,numpy/numpy,rgommers/numpy,mhvk/numpy,anntzer/numpy,seberg/numpy,numpy/numpy,madphysicist/numpy,madphysicist/numpy,madphysicist/numpy,mattip/numpy,mattip/numpy,endolith/numpy,numpy/numpy,jakirkham/numpy,grlee77/numpy,simongibbons/numpy,grlee77/numpy,charris/numpy,anntzer/numpy,jakirkham/numpy,seberg/numpy,simongibbons/numpy,jakirkham/numpy,endolith/numpy,pbrod/numpy,pdebuyl/numpy,pdebuyl/numpy,pdebuyl/numpy,mattip/numpy,mhvk/numpy,anntzer/numpy,simongibbons/numpy,jakirkham/numpy,seberg/numpy,charris/numpy,grlee77/numpy,grlee77/numpy,grlee77/numpy,rgommers/numpy,pbrod/numpy,simongibbons/numpy,seberg/numpy,charris/numpy,rgommers/numpy,mhvk/numpy,pbrod/numpy,pbrod/numpy,pdebuyl/numpy,endolith/numpy,simongibbons/numpy,pbrod/numpy,mattip/numpy,jakirkham/numpy,charris/numpy,madphysicist/numpy,numpy/numpy,madphysicist/numpy,rgommers/numpy,mhvk/numpy,endolith/numpy,mhvk/numpy
|
import numpy as np
reveal_type(np) # E: ModuleType
reveal_type(np.char) # E: ModuleType
reveal_type(np.compat) # E: ModuleType
reveal_type(np.core) # E: ModuleType
reveal_type(np.ctypeslib) # E: ModuleType
reveal_type(np.emath) # E: ModuleType
reveal_type(np.fft) # E: ModuleType
reveal_type(np.lib) # E: ModuleType
reveal_type(np.linalg) # E: ModuleType
reveal_type(np.ma) # E: ModuleType
reveal_type(np.matrixlib) # E: ModuleType
reveal_type(np.polynomial) # E: ModuleType
reveal_type(np.random) # E: ModuleType
reveal_type(np.rec) # E: ModuleType
reveal_type(np.testing) # E: ModuleType
reveal_type(np.version) # E: ModuleType
# TODO: Remove when annotations have been added to `np.testing.assert_equal`
reveal_type(np.testing.assert_equal) # E: Any
TST: Remove `compat` and `core` from the tests
|
import numpy as np
reveal_type(np) # E: ModuleType
reveal_type(np.char) # E: ModuleType
reveal_type(np.ctypeslib) # E: ModuleType
reveal_type(np.emath) # E: ModuleType
reveal_type(np.fft) # E: ModuleType
reveal_type(np.lib) # E: ModuleType
reveal_type(np.linalg) # E: ModuleType
reveal_type(np.ma) # E: ModuleType
reveal_type(np.matrixlib) # E: ModuleType
reveal_type(np.polynomial) # E: ModuleType
reveal_type(np.random) # E: ModuleType
reveal_type(np.rec) # E: ModuleType
reveal_type(np.testing) # E: ModuleType
reveal_type(np.version) # E: ModuleType
# TODO: Remove when annotations have been added to `np.testing.assert_equal`
reveal_type(np.testing.assert_equal) # E: Any
|
<commit_before>import numpy as np
reveal_type(np) # E: ModuleType
reveal_type(np.char) # E: ModuleType
reveal_type(np.compat) # E: ModuleType
reveal_type(np.core) # E: ModuleType
reveal_type(np.ctypeslib) # E: ModuleType
reveal_type(np.emath) # E: ModuleType
reveal_type(np.fft) # E: ModuleType
reveal_type(np.lib) # E: ModuleType
reveal_type(np.linalg) # E: ModuleType
reveal_type(np.ma) # E: ModuleType
reveal_type(np.matrixlib) # E: ModuleType
reveal_type(np.polynomial) # E: ModuleType
reveal_type(np.random) # E: ModuleType
reveal_type(np.rec) # E: ModuleType
reveal_type(np.testing) # E: ModuleType
reveal_type(np.version) # E: ModuleType
# TODO: Remove when annotations have been added to `np.testing.assert_equal`
reveal_type(np.testing.assert_equal) # E: Any
<commit_msg>TST: Remove `compat` and `core` from the tests<commit_after>
|
import numpy as np
reveal_type(np) # E: ModuleType
reveal_type(np.char) # E: ModuleType
reveal_type(np.ctypeslib) # E: ModuleType
reveal_type(np.emath) # E: ModuleType
reveal_type(np.fft) # E: ModuleType
reveal_type(np.lib) # E: ModuleType
reveal_type(np.linalg) # E: ModuleType
reveal_type(np.ma) # E: ModuleType
reveal_type(np.matrixlib) # E: ModuleType
reveal_type(np.polynomial) # E: ModuleType
reveal_type(np.random) # E: ModuleType
reveal_type(np.rec) # E: ModuleType
reveal_type(np.testing) # E: ModuleType
reveal_type(np.version) # E: ModuleType
# TODO: Remove when annotations have been added to `np.testing.assert_equal`
reveal_type(np.testing.assert_equal) # E: Any
|
import numpy as np
reveal_type(np) # E: ModuleType
reveal_type(np.char) # E: ModuleType
reveal_type(np.compat) # E: ModuleType
reveal_type(np.core) # E: ModuleType
reveal_type(np.ctypeslib) # E: ModuleType
reveal_type(np.emath) # E: ModuleType
reveal_type(np.fft) # E: ModuleType
reveal_type(np.lib) # E: ModuleType
reveal_type(np.linalg) # E: ModuleType
reveal_type(np.ma) # E: ModuleType
reveal_type(np.matrixlib) # E: ModuleType
reveal_type(np.polynomial) # E: ModuleType
reveal_type(np.random) # E: ModuleType
reveal_type(np.rec) # E: ModuleType
reveal_type(np.testing) # E: ModuleType
reveal_type(np.version) # E: ModuleType
# TODO: Remove when annotations have been added to `np.testing.assert_equal`
reveal_type(np.testing.assert_equal) # E: Any
TST: Remove `compat` and `core` from the testsimport numpy as np
reveal_type(np) # E: ModuleType
reveal_type(np.char) # E: ModuleType
reveal_type(np.ctypeslib) # E: ModuleType
reveal_type(np.emath) # E: ModuleType
reveal_type(np.fft) # E: ModuleType
reveal_type(np.lib) # E: ModuleType
reveal_type(np.linalg) # E: ModuleType
reveal_type(np.ma) # E: ModuleType
reveal_type(np.matrixlib) # E: ModuleType
reveal_type(np.polynomial) # E: ModuleType
reveal_type(np.random) # E: ModuleType
reveal_type(np.rec) # E: ModuleType
reveal_type(np.testing) # E: ModuleType
reveal_type(np.version) # E: ModuleType
# TODO: Remove when annotations have been added to `np.testing.assert_equal`
reveal_type(np.testing.assert_equal) # E: Any
|
<commit_before>import numpy as np
reveal_type(np) # E: ModuleType
reveal_type(np.char) # E: ModuleType
reveal_type(np.compat) # E: ModuleType
reveal_type(np.core) # E: ModuleType
reveal_type(np.ctypeslib) # E: ModuleType
reveal_type(np.emath) # E: ModuleType
reveal_type(np.fft) # E: ModuleType
reveal_type(np.lib) # E: ModuleType
reveal_type(np.linalg) # E: ModuleType
reveal_type(np.ma) # E: ModuleType
reveal_type(np.matrixlib) # E: ModuleType
reveal_type(np.polynomial) # E: ModuleType
reveal_type(np.random) # E: ModuleType
reveal_type(np.rec) # E: ModuleType
reveal_type(np.testing) # E: ModuleType
reveal_type(np.version) # E: ModuleType
# TODO: Remove when annotations have been added to `np.testing.assert_equal`
reveal_type(np.testing.assert_equal) # E: Any
<commit_msg>TST: Remove `compat` and `core` from the tests<commit_after>import numpy as np
reveal_type(np) # E: ModuleType
reveal_type(np.char) # E: ModuleType
reveal_type(np.ctypeslib) # E: ModuleType
reveal_type(np.emath) # E: ModuleType
reveal_type(np.fft) # E: ModuleType
reveal_type(np.lib) # E: ModuleType
reveal_type(np.linalg) # E: ModuleType
reveal_type(np.ma) # E: ModuleType
reveal_type(np.matrixlib) # E: ModuleType
reveal_type(np.polynomial) # E: ModuleType
reveal_type(np.random) # E: ModuleType
reveal_type(np.rec) # E: ModuleType
reveal_type(np.testing) # E: ModuleType
reveal_type(np.version) # E: ModuleType
# TODO: Remove when annotations have been added to `np.testing.assert_equal`
reveal_type(np.testing.assert_equal) # E: Any
|
5054e882194adae4b76681e78c45d41ae2c2f0f7
|
pymatgen/util/sequence.py
|
pymatgen/util/sequence.py
|
# coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
"""
This module provides utilities to chunk large sequences and display progress
bars during processing.
"""
import math
def get_chunks(sequence, size=1):
"""
Args:
sequence ():
size ():
Returns:
"""
chunks = int(math.ceil(len(sequence) / float(size)))
return [sequence[i * size : (i + 1) * size] for i in range(chunks)]
class PBarSafe:
"""
Progress bar.
"""
def __init__(self, total):
"""
Args:
total (): Total value.
"""
self.total = total
self.done = 0
self.report()
def update(self, amount):
"""
Update progress bar by amount.
Args:
amount (float):
"""
self.done += amount
self.report()
def report(self):
"""
Print progress.
"""
print("{} of {} done {:.1%}".format(self.done, self.total, self.done / self.total))
try:
# noinspection PyUnresolvedReferences
if get_ipython().__class__.__name__ == "ZMQInteractiveShell": # type: ignore
from tqdm import tqdm_notebook as PBar
else: # likely 'TerminalInteractiveShell'
from tqdm import tqdm as PBar
except NameError:
try:
from tqdm import tqdm as PBar
except ImportError:
PBar = PBarSafe
except ImportError:
PBar = PBarSafe
|
# coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
"""
This module provides utilities to chunk large sequences and display progress
bars during processing.
"""
import math
def get_chunks(sequence, size=1):
"""
Args:
sequence ():
size ():
Returns:
"""
chunks = int(math.ceil(len(sequence) / float(size)))
return [sequence[i * size : (i + 1) * size] for i in range(chunks)]
class PBarSafe:
"""
Progress bar.
"""
def __init__(self, total, **kwargs):
"""
Args:
total (): Total value.
"""
self.total = total
self.done = 0
self.report()
def update(self, amount):
"""
Update progress bar by amount.
Args:
amount (float):
"""
self.done += amount
self.report()
def report(self):
"""
Print progress.
"""
print("{} of {} done {:.1%}".format(self.done, self.total, self.done / self.total))
try:
# noinspection PyUnresolvedReferences
if get_ipython().__class__.__name__ == "ZMQInteractiveShell": # type: ignore
from tqdm import tqdm_notebook as PBar
else: # likely 'TerminalInteractiveShell'
from tqdm import tqdm as PBar
except NameError:
try:
from tqdm import tqdm as PBar
except ImportError:
PBar = PBarSafe
except ImportError:
PBar = PBarSafe
|
Allow `PBar` to accept any kwargs (e.g. those used by `tqdm`)
|
Allow `PBar` to accept any kwargs (e.g. those used by `tqdm`)
|
Python
|
mit
|
gVallverdu/pymatgen,vorwerkc/pymatgen,vorwerkc/pymatgen,davidwaroquiers/pymatgen,gVallverdu/pymatgen,gVallverdu/pymatgen,fraricci/pymatgen,vorwerkc/pymatgen,gVallverdu/pymatgen,davidwaroquiers/pymatgen,fraricci/pymatgen,davidwaroquiers/pymatgen,davidwaroquiers/pymatgen,fraricci/pymatgen,vorwerkc/pymatgen,fraricci/pymatgen
|
# coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
"""
This module provides utilities to chunk large sequences and display progress
bars during processing.
"""
import math
def get_chunks(sequence, size=1):
"""
Args:
sequence ():
size ():
Returns:
"""
chunks = int(math.ceil(len(sequence) / float(size)))
return [sequence[i * size : (i + 1) * size] for i in range(chunks)]
class PBarSafe:
"""
Progress bar.
"""
def __init__(self, total):
"""
Args:
total (): Total value.
"""
self.total = total
self.done = 0
self.report()
def update(self, amount):
"""
Update progress bar by amount.
Args:
amount (float):
"""
self.done += amount
self.report()
def report(self):
"""
Print progress.
"""
print("{} of {} done {:.1%}".format(self.done, self.total, self.done / self.total))
try:
# noinspection PyUnresolvedReferences
if get_ipython().__class__.__name__ == "ZMQInteractiveShell": # type: ignore
from tqdm import tqdm_notebook as PBar
else: # likely 'TerminalInteractiveShell'
from tqdm import tqdm as PBar
except NameError:
try:
from tqdm import tqdm as PBar
except ImportError:
PBar = PBarSafe
except ImportError:
PBar = PBarSafe
Allow `PBar` to accept any kwargs (e.g. those used by `tqdm`)
|
# coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
"""
This module provides utilities to chunk large sequences and display progress
bars during processing.
"""
import math
def get_chunks(sequence, size=1):
"""
Args:
sequence ():
size ():
Returns:
"""
chunks = int(math.ceil(len(sequence) / float(size)))
return [sequence[i * size : (i + 1) * size] for i in range(chunks)]
class PBarSafe:
"""
Progress bar.
"""
def __init__(self, total, **kwargs):
"""
Args:
total (): Total value.
"""
self.total = total
self.done = 0
self.report()
def update(self, amount):
"""
Update progress bar by amount.
Args:
amount (float):
"""
self.done += amount
self.report()
def report(self):
"""
Print progress.
"""
print("{} of {} done {:.1%}".format(self.done, self.total, self.done / self.total))
try:
# noinspection PyUnresolvedReferences
if get_ipython().__class__.__name__ == "ZMQInteractiveShell": # type: ignore
from tqdm import tqdm_notebook as PBar
else: # likely 'TerminalInteractiveShell'
from tqdm import tqdm as PBar
except NameError:
try:
from tqdm import tqdm as PBar
except ImportError:
PBar = PBarSafe
except ImportError:
PBar = PBarSafe
|
<commit_before># coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
"""
This module provides utilities to chunk large sequences and display progress
bars during processing.
"""
import math
def get_chunks(sequence, size=1):
"""
Args:
sequence ():
size ():
Returns:
"""
chunks = int(math.ceil(len(sequence) / float(size)))
return [sequence[i * size : (i + 1) * size] for i in range(chunks)]
class PBarSafe:
"""
Progress bar.
"""
def __init__(self, total):
"""
Args:
total (): Total value.
"""
self.total = total
self.done = 0
self.report()
def update(self, amount):
"""
Update progress bar by amount.
Args:
amount (float):
"""
self.done += amount
self.report()
def report(self):
"""
Print progress.
"""
print("{} of {} done {:.1%}".format(self.done, self.total, self.done / self.total))
try:
# noinspection PyUnresolvedReferences
if get_ipython().__class__.__name__ == "ZMQInteractiveShell": # type: ignore
from tqdm import tqdm_notebook as PBar
else: # likely 'TerminalInteractiveShell'
from tqdm import tqdm as PBar
except NameError:
try:
from tqdm import tqdm as PBar
except ImportError:
PBar = PBarSafe
except ImportError:
PBar = PBarSafe
<commit_msg>Allow `PBar` to accept any kwargs (e.g. those used by `tqdm`)<commit_after>
|
# coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
"""
This module provides utilities to chunk large sequences and display progress
bars during processing.
"""
import math
def get_chunks(sequence, size=1):
"""
Args:
sequence ():
size ():
Returns:
"""
chunks = int(math.ceil(len(sequence) / float(size)))
return [sequence[i * size : (i + 1) * size] for i in range(chunks)]
class PBarSafe:
"""
Progress bar.
"""
def __init__(self, total, **kwargs):
"""
Args:
total (): Total value.
"""
self.total = total
self.done = 0
self.report()
def update(self, amount):
"""
Update progress bar by amount.
Args:
amount (float):
"""
self.done += amount
self.report()
def report(self):
"""
Print progress.
"""
print("{} of {} done {:.1%}".format(self.done, self.total, self.done / self.total))
try:
# noinspection PyUnresolvedReferences
if get_ipython().__class__.__name__ == "ZMQInteractiveShell": # type: ignore
from tqdm import tqdm_notebook as PBar
else: # likely 'TerminalInteractiveShell'
from tqdm import tqdm as PBar
except NameError:
try:
from tqdm import tqdm as PBar
except ImportError:
PBar = PBarSafe
except ImportError:
PBar = PBarSafe
|
# coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
"""
This module provides utilities to chunk large sequences and display progress
bars during processing.
"""
import math
def get_chunks(sequence, size=1):
"""
Args:
sequence ():
size ():
Returns:
"""
chunks = int(math.ceil(len(sequence) / float(size)))
return [sequence[i * size : (i + 1) * size] for i in range(chunks)]
class PBarSafe:
"""
Progress bar.
"""
def __init__(self, total):
"""
Args:
total (): Total value.
"""
self.total = total
self.done = 0
self.report()
def update(self, amount):
"""
Update progress bar by amount.
Args:
amount (float):
"""
self.done += amount
self.report()
def report(self):
"""
Print progress.
"""
print("{} of {} done {:.1%}".format(self.done, self.total, self.done / self.total))
try:
# noinspection PyUnresolvedReferences
if get_ipython().__class__.__name__ == "ZMQInteractiveShell": # type: ignore
from tqdm import tqdm_notebook as PBar
else: # likely 'TerminalInteractiveShell'
from tqdm import tqdm as PBar
except NameError:
try:
from tqdm import tqdm as PBar
except ImportError:
PBar = PBarSafe
except ImportError:
PBar = PBarSafe
Allow `PBar` to accept any kwargs (e.g. those used by `tqdm`)# coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
"""
This module provides utilities to chunk large sequences and display progress
bars during processing.
"""
import math
def get_chunks(sequence, size=1):
"""
Args:
sequence ():
size ():
Returns:
"""
chunks = int(math.ceil(len(sequence) / float(size)))
return [sequence[i * size : (i + 1) * size] for i in range(chunks)]
class PBarSafe:
"""
Progress bar.
"""
def __init__(self, total, **kwargs):
"""
Args:
total (): Total value.
"""
self.total = total
self.done = 0
self.report()
def update(self, amount):
"""
Update progress bar by amount.
Args:
amount (float):
"""
self.done += amount
self.report()
def report(self):
"""
Print progress.
"""
print("{} of {} done {:.1%}".format(self.done, self.total, self.done / self.total))
try:
# noinspection PyUnresolvedReferences
if get_ipython().__class__.__name__ == "ZMQInteractiveShell": # type: ignore
from tqdm import tqdm_notebook as PBar
else: # likely 'TerminalInteractiveShell'
from tqdm import tqdm as PBar
except NameError:
try:
from tqdm import tqdm as PBar
except ImportError:
PBar = PBarSafe
except ImportError:
PBar = PBarSafe
|
<commit_before># coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
"""
This module provides utilities to chunk large sequences and display progress
bars during processing.
"""
import math
def get_chunks(sequence, size=1):
"""
Args:
sequence ():
size ():
Returns:
"""
chunks = int(math.ceil(len(sequence) / float(size)))
return [sequence[i * size : (i + 1) * size] for i in range(chunks)]
class PBarSafe:
"""
Progress bar.
"""
def __init__(self, total):
"""
Args:
total (): Total value.
"""
self.total = total
self.done = 0
self.report()
def update(self, amount):
"""
Update progress bar by amount.
Args:
amount (float):
"""
self.done += amount
self.report()
def report(self):
"""
Print progress.
"""
print("{} of {} done {:.1%}".format(self.done, self.total, self.done / self.total))
try:
# noinspection PyUnresolvedReferences
if get_ipython().__class__.__name__ == "ZMQInteractiveShell": # type: ignore
from tqdm import tqdm_notebook as PBar
else: # likely 'TerminalInteractiveShell'
from tqdm import tqdm as PBar
except NameError:
try:
from tqdm import tqdm as PBar
except ImportError:
PBar = PBarSafe
except ImportError:
PBar = PBarSafe
<commit_msg>Allow `PBar` to accept any kwargs (e.g. those used by `tqdm`)<commit_after># coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
"""
This module provides utilities to chunk large sequences and display progress
bars during processing.
"""
import math
def get_chunks(sequence, size=1):
"""
Args:
sequence ():
size ():
Returns:
"""
chunks = int(math.ceil(len(sequence) / float(size)))
return [sequence[i * size : (i + 1) * size] for i in range(chunks)]
class PBarSafe:
"""
Progress bar.
"""
def __init__(self, total, **kwargs):
"""
Args:
total (): Total value.
"""
self.total = total
self.done = 0
self.report()
def update(self, amount):
"""
Update progress bar by amount.
Args:
amount (float):
"""
self.done += amount
self.report()
def report(self):
"""
Print progress.
"""
print("{} of {} done {:.1%}".format(self.done, self.total, self.done / self.total))
try:
# noinspection PyUnresolvedReferences
if get_ipython().__class__.__name__ == "ZMQInteractiveShell": # type: ignore
from tqdm import tqdm_notebook as PBar
else: # likely 'TerminalInteractiveShell'
from tqdm import tqdm as PBar
except NameError:
try:
from tqdm import tqdm as PBar
except ImportError:
PBar = PBarSafe
except ImportError:
PBar = PBarSafe
|
6fa751accb736b3c32522ca498210ffeebfef650
|
pytablereader/tsv/core.py
|
pytablereader/tsv/core.py
|
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from .._validator import FileValidator, TextValidator
from ..csv.core import CsvTableFileLoader, CsvTableTextLoader
class TsvTableFileLoader(CsvTableFileLoader):
"""
Tab separated values (TSV) format file loader class.
:param str file_path: Path to the loading TSV file.
.. py:attribute:: table_name
Table name string. Defaults to ``%(filename)s``.
"""
@property
def format_name(self):
return "tsv"
def __init__(self, file_path):
super().__init__(file_path)
self.delimiter = "\t"
self._validator = FileValidator(file_path)
class TsvTableTextLoader(CsvTableTextLoader):
"""
Tab separated values (TSV) format text loader class.
:param str text: TSV text to load.
.. py:attribute:: table_name
Table name string. Defaults to ``%(format_name)s%(format_id)s``.
"""
@property
def format_name(self):
return "tsv"
def __init__(self, text):
super().__init__(text)
self.delimiter = "\t"
self._validator = TextValidator(text)
|
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from .._validator import FileValidator, TextValidator
from ..csv.core import CsvTableFileLoader, CsvTableTextLoader
class TsvTableFileLoader(CsvTableFileLoader):
"""
Tab separated values (TSV) format file loader class.
:param str file_path: Path to the loading TSV file.
.. py:attribute:: table_name
Table name string. Defaults to ``%(filename)s``.
"""
@property
def format_name(self):
return "tsv"
def __init__(self, file_path, quoting_flags=None, type_hints=None, type_hint_rules=None):
super().__init__(file_path, quoting_flags, type_hints, type_hint_rules)
self.delimiter = "\t"
self._validator = FileValidator(file_path)
class TsvTableTextLoader(CsvTableTextLoader):
"""
Tab separated values (TSV) format text loader class.
:param str text: TSV text to load.
.. py:attribute:: table_name
Table name string. Defaults to ``%(format_name)s%(format_id)s``.
"""
@property
def format_name(self):
return "tsv"
def __init__(self, text, quoting_flags=None, type_hints=None, type_hint_rules=None):
super().__init__(text, quoting_flags, type_hints, type_hint_rules)
self.delimiter = "\t"
self._validator = TextValidator(text)
|
Modify TsvTableFileLoader/TsvTableTextLoader to accept additional keyword arguments
|
Modify TsvTableFileLoader/TsvTableTextLoader to accept additional keyword arguments
|
Python
|
mit
|
thombashi/pytablereader,thombashi/pytablereader,thombashi/pytablereader
|
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from .._validator import FileValidator, TextValidator
from ..csv.core import CsvTableFileLoader, CsvTableTextLoader
class TsvTableFileLoader(CsvTableFileLoader):
"""
Tab separated values (TSV) format file loader class.
:param str file_path: Path to the loading TSV file.
.. py:attribute:: table_name
Table name string. Defaults to ``%(filename)s``.
"""
@property
def format_name(self):
return "tsv"
def __init__(self, file_path):
super().__init__(file_path)
self.delimiter = "\t"
self._validator = FileValidator(file_path)
class TsvTableTextLoader(CsvTableTextLoader):
"""
Tab separated values (TSV) format text loader class.
:param str text: TSV text to load.
.. py:attribute:: table_name
Table name string. Defaults to ``%(format_name)s%(format_id)s``.
"""
@property
def format_name(self):
return "tsv"
def __init__(self, text):
super().__init__(text)
self.delimiter = "\t"
self._validator = TextValidator(text)
Modify TsvTableFileLoader/TsvTableTextLoader to accept additional keyword arguments
|
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from .._validator import FileValidator, TextValidator
from ..csv.core import CsvTableFileLoader, CsvTableTextLoader
class TsvTableFileLoader(CsvTableFileLoader):
"""
Tab separated values (TSV) format file loader class.
:param str file_path: Path to the loading TSV file.
.. py:attribute:: table_name
Table name string. Defaults to ``%(filename)s``.
"""
@property
def format_name(self):
return "tsv"
def __init__(self, file_path, quoting_flags=None, type_hints=None, type_hint_rules=None):
super().__init__(file_path, quoting_flags, type_hints, type_hint_rules)
self.delimiter = "\t"
self._validator = FileValidator(file_path)
class TsvTableTextLoader(CsvTableTextLoader):
"""
Tab separated values (TSV) format text loader class.
:param str text: TSV text to load.
.. py:attribute:: table_name
Table name string. Defaults to ``%(format_name)s%(format_id)s``.
"""
@property
def format_name(self):
return "tsv"
def __init__(self, text, quoting_flags=None, type_hints=None, type_hint_rules=None):
super().__init__(text, quoting_flags, type_hints, type_hint_rules)
self.delimiter = "\t"
self._validator = TextValidator(text)
|
<commit_before>"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from .._validator import FileValidator, TextValidator
from ..csv.core import CsvTableFileLoader, CsvTableTextLoader
class TsvTableFileLoader(CsvTableFileLoader):
"""
Tab separated values (TSV) format file loader class.
:param str file_path: Path to the loading TSV file.
.. py:attribute:: table_name
Table name string. Defaults to ``%(filename)s``.
"""
@property
def format_name(self):
return "tsv"
def __init__(self, file_path):
super().__init__(file_path)
self.delimiter = "\t"
self._validator = FileValidator(file_path)
class TsvTableTextLoader(CsvTableTextLoader):
"""
Tab separated values (TSV) format text loader class.
:param str text: TSV text to load.
.. py:attribute:: table_name
Table name string. Defaults to ``%(format_name)s%(format_id)s``.
"""
@property
def format_name(self):
return "tsv"
def __init__(self, text):
super().__init__(text)
self.delimiter = "\t"
self._validator = TextValidator(text)
<commit_msg>Modify TsvTableFileLoader/TsvTableTextLoader to accept additional keyword arguments<commit_after>
|
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from .._validator import FileValidator, TextValidator
from ..csv.core import CsvTableFileLoader, CsvTableTextLoader
class TsvTableFileLoader(CsvTableFileLoader):
"""
Tab separated values (TSV) format file loader class.
:param str file_path: Path to the loading TSV file.
.. py:attribute:: table_name
Table name string. Defaults to ``%(filename)s``.
"""
@property
def format_name(self):
return "tsv"
def __init__(self, file_path, quoting_flags=None, type_hints=None, type_hint_rules=None):
super().__init__(file_path, quoting_flags, type_hints, type_hint_rules)
self.delimiter = "\t"
self._validator = FileValidator(file_path)
class TsvTableTextLoader(CsvTableTextLoader):
"""
Tab separated values (TSV) format text loader class.
:param str text: TSV text to load.
.. py:attribute:: table_name
Table name string. Defaults to ``%(format_name)s%(format_id)s``.
"""
@property
def format_name(self):
return "tsv"
def __init__(self, text, quoting_flags=None, type_hints=None, type_hint_rules=None):
super().__init__(text, quoting_flags, type_hints, type_hint_rules)
self.delimiter = "\t"
self._validator = TextValidator(text)
|
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from .._validator import FileValidator, TextValidator
from ..csv.core import CsvTableFileLoader, CsvTableTextLoader
class TsvTableFileLoader(CsvTableFileLoader):
"""
Tab separated values (TSV) format file loader class.
:param str file_path: Path to the loading TSV file.
.. py:attribute:: table_name
Table name string. Defaults to ``%(filename)s``.
"""
@property
def format_name(self):
return "tsv"
def __init__(self, file_path):
super().__init__(file_path)
self.delimiter = "\t"
self._validator = FileValidator(file_path)
class TsvTableTextLoader(CsvTableTextLoader):
"""
Tab separated values (TSV) format text loader class.
:param str text: TSV text to load.
.. py:attribute:: table_name
Table name string. Defaults to ``%(format_name)s%(format_id)s``.
"""
@property
def format_name(self):
return "tsv"
def __init__(self, text):
super().__init__(text)
self.delimiter = "\t"
self._validator = TextValidator(text)
Modify TsvTableFileLoader/TsvTableTextLoader to accept additional keyword arguments"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from .._validator import FileValidator, TextValidator
from ..csv.core import CsvTableFileLoader, CsvTableTextLoader
class TsvTableFileLoader(CsvTableFileLoader):
"""
Tab separated values (TSV) format file loader class.
:param str file_path: Path to the loading TSV file.
.. py:attribute:: table_name
Table name string. Defaults to ``%(filename)s``.
"""
@property
def format_name(self):
return "tsv"
def __init__(self, file_path, quoting_flags=None, type_hints=None, type_hint_rules=None):
super().__init__(file_path, quoting_flags, type_hints, type_hint_rules)
self.delimiter = "\t"
self._validator = FileValidator(file_path)
class TsvTableTextLoader(CsvTableTextLoader):
"""
Tab separated values (TSV) format text loader class.
:param str text: TSV text to load.
.. py:attribute:: table_name
Table name string. Defaults to ``%(format_name)s%(format_id)s``.
"""
@property
def format_name(self):
return "tsv"
def __init__(self, text, quoting_flags=None, type_hints=None, type_hint_rules=None):
super().__init__(text, quoting_flags, type_hints, type_hint_rules)
self.delimiter = "\t"
self._validator = TextValidator(text)
|
<commit_before>"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from .._validator import FileValidator, TextValidator
from ..csv.core import CsvTableFileLoader, CsvTableTextLoader
class TsvTableFileLoader(CsvTableFileLoader):
"""
Tab separated values (TSV) format file loader class.
:param str file_path: Path to the loading TSV file.
.. py:attribute:: table_name
Table name string. Defaults to ``%(filename)s``.
"""
@property
def format_name(self):
return "tsv"
def __init__(self, file_path):
super().__init__(file_path)
self.delimiter = "\t"
self._validator = FileValidator(file_path)
class TsvTableTextLoader(CsvTableTextLoader):
"""
Tab separated values (TSV) format text loader class.
:param str text: TSV text to load.
.. py:attribute:: table_name
Table name string. Defaults to ``%(format_name)s%(format_id)s``.
"""
@property
def format_name(self):
return "tsv"
def __init__(self, text):
super().__init__(text)
self.delimiter = "\t"
self._validator = TextValidator(text)
<commit_msg>Modify TsvTableFileLoader/TsvTableTextLoader to accept additional keyword arguments<commit_after>"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from .._validator import FileValidator, TextValidator
from ..csv.core import CsvTableFileLoader, CsvTableTextLoader
class TsvTableFileLoader(CsvTableFileLoader):
"""
Tab separated values (TSV) format file loader class.
:param str file_path: Path to the loading TSV file.
.. py:attribute:: table_name
Table name string. Defaults to ``%(filename)s``.
"""
@property
def format_name(self):
return "tsv"
def __init__(self, file_path, quoting_flags=None, type_hints=None, type_hint_rules=None):
super().__init__(file_path, quoting_flags, type_hints, type_hint_rules)
self.delimiter = "\t"
self._validator = FileValidator(file_path)
class TsvTableTextLoader(CsvTableTextLoader):
"""
Tab separated values (TSV) format text loader class.
:param str text: TSV text to load.
.. py:attribute:: table_name
Table name string. Defaults to ``%(format_name)s%(format_id)s``.
"""
@property
def format_name(self):
return "tsv"
def __init__(self, text, quoting_flags=None, type_hints=None, type_hint_rules=None):
super().__init__(text, quoting_flags, type_hints, type_hint_rules)
self.delimiter = "\t"
self._validator = TextValidator(text)
|
566a200a11a587a9293d6926348c3df77a4c840d
|
project/apps/api/management/commands/denormalize.py
|
project/apps/api/management/commands/denormalize.py
|
from django.core.management.base import (
BaseCommand,
)
from apps.api.models import (
Convention,
Contest,
Contestant,
Performance,
)
class Command(BaseCommand):
help = "Command to denormailze data."
def handle(self, *args, **options):
vs = Convention.objects.all()
for v in vs:
v.save()
ts = Contest.objects.all()
for t in ts:
t.save()
cs = Contestant.objects.all()
for c in cs:
c.save()
ps = Performance.objects.all()
for p in ps:
p.save()
for t in ts:
t.rank()
return "Done"
|
from django.core.management.base import (
BaseCommand,
)
from apps.api.models import (
Convention,
Contest,
Contestant,
Performance,
)
class Command(BaseCommand):
help = "Command to denormailze data."
def handle(self, *args, **options):
vs = Convention.objects.all()
for v in vs:
v.save()
ts = Contest.objects.all()
for t in ts:
t.save()
cs = Contestant.objects.all()
for c in cs:
c.save()
ps = Performance.objects.all()
for p in ps:
p.save()
return "Done"
|
Remove ranking from denormalization command
|
Remove ranking from denormalization command
|
Python
|
bsd-2-clause
|
barberscore/barberscore-api,dbinetti/barberscore,barberscore/barberscore-api,dbinetti/barberscore-django,barberscore/barberscore-api,dbinetti/barberscore,barberscore/barberscore-api,dbinetti/barberscore-django
|
from django.core.management.base import (
BaseCommand,
)
from apps.api.models import (
Convention,
Contest,
Contestant,
Performance,
)
class Command(BaseCommand):
help = "Command to denormailze data."
def handle(self, *args, **options):
vs = Convention.objects.all()
for v in vs:
v.save()
ts = Contest.objects.all()
for t in ts:
t.save()
cs = Contestant.objects.all()
for c in cs:
c.save()
ps = Performance.objects.all()
for p in ps:
p.save()
for t in ts:
t.rank()
return "Done"
Remove ranking from denormalization command
|
from django.core.management.base import (
BaseCommand,
)
from apps.api.models import (
Convention,
Contest,
Contestant,
Performance,
)
class Command(BaseCommand):
help = "Command to denormailze data."
def handle(self, *args, **options):
vs = Convention.objects.all()
for v in vs:
v.save()
ts = Contest.objects.all()
for t in ts:
t.save()
cs = Contestant.objects.all()
for c in cs:
c.save()
ps = Performance.objects.all()
for p in ps:
p.save()
return "Done"
|
<commit_before>from django.core.management.base import (
BaseCommand,
)
from apps.api.models import (
Convention,
Contest,
Contestant,
Performance,
)
class Command(BaseCommand):
help = "Command to denormailze data."
def handle(self, *args, **options):
vs = Convention.objects.all()
for v in vs:
v.save()
ts = Contest.objects.all()
for t in ts:
t.save()
cs = Contestant.objects.all()
for c in cs:
c.save()
ps = Performance.objects.all()
for p in ps:
p.save()
for t in ts:
t.rank()
return "Done"
<commit_msg>Remove ranking from denormalization command<commit_after>
|
from django.core.management.base import (
BaseCommand,
)
from apps.api.models import (
Convention,
Contest,
Contestant,
Performance,
)
class Command(BaseCommand):
help = "Command to denormailze data."
def handle(self, *args, **options):
vs = Convention.objects.all()
for v in vs:
v.save()
ts = Contest.objects.all()
for t in ts:
t.save()
cs = Contestant.objects.all()
for c in cs:
c.save()
ps = Performance.objects.all()
for p in ps:
p.save()
return "Done"
|
from django.core.management.base import (
BaseCommand,
)
from apps.api.models import (
Convention,
Contest,
Contestant,
Performance,
)
class Command(BaseCommand):
help = "Command to denormailze data."
def handle(self, *args, **options):
vs = Convention.objects.all()
for v in vs:
v.save()
ts = Contest.objects.all()
for t in ts:
t.save()
cs = Contestant.objects.all()
for c in cs:
c.save()
ps = Performance.objects.all()
for p in ps:
p.save()
for t in ts:
t.rank()
return "Done"
Remove ranking from denormalization commandfrom django.core.management.base import (
BaseCommand,
)
from apps.api.models import (
Convention,
Contest,
Contestant,
Performance,
)
class Command(BaseCommand):
help = "Command to denormailze data."
def handle(self, *args, **options):
vs = Convention.objects.all()
for v in vs:
v.save()
ts = Contest.objects.all()
for t in ts:
t.save()
cs = Contestant.objects.all()
for c in cs:
c.save()
ps = Performance.objects.all()
for p in ps:
p.save()
return "Done"
|
<commit_before>from django.core.management.base import (
BaseCommand,
)
from apps.api.models import (
Convention,
Contest,
Contestant,
Performance,
)
class Command(BaseCommand):
help = "Command to denormailze data."
def handle(self, *args, **options):
vs = Convention.objects.all()
for v in vs:
v.save()
ts = Contest.objects.all()
for t in ts:
t.save()
cs = Contestant.objects.all()
for c in cs:
c.save()
ps = Performance.objects.all()
for p in ps:
p.save()
for t in ts:
t.rank()
return "Done"
<commit_msg>Remove ranking from denormalization command<commit_after>from django.core.management.base import (
BaseCommand,
)
from apps.api.models import (
Convention,
Contest,
Contestant,
Performance,
)
class Command(BaseCommand):
help = "Command to denormailze data."
def handle(self, *args, **options):
vs = Convention.objects.all()
for v in vs:
v.save()
ts = Contest.objects.all()
for t in ts:
t.save()
cs = Contestant.objects.all()
for c in cs:
c.save()
ps = Performance.objects.all()
for p in ps:
p.save()
return "Done"
|
f18cf3c17e450eb6f8db5288ecf146eff0968a47
|
xmt/select.py
|
xmt/select.py
|
from itertools import groupby
from nltk.translate.gleu_score import sentence_gleu as gleu
from nltk.tokenize.toktok import ToktokTokenizer
_tokenize = ToktokTokenizer().tokenize
def select_first(p):
"""
Return (hypothesis, reference) translation pairs using the first
realization result per item.
"""
pairs = []
rows = p.join('item', 'g-result')
for i_id, group in groupby(rows, key=lambda row: row['g-result:i-id']):
row = next(group)
pairs.append((row['g-result:surface'], row['item:i-translation']))
return pairs
def select_oracle(p):
"""
Return (hypothesis, reference) translation pairs using the
realization result per item with the highest GLEU score.
"""
pairs = []
rows = p.join('item', 'g-result')
for i_id, group in groupby(rows, key=lambda row: row['g-result:i-id']):
hrs = ((r['g-result:surface'], r['item:i-translation']) for r in group)
ranked = [(gleu(_tokenize(r), _tokenize(h)), h, r) for h, r in hrs]
_, hyp, ref = sorted(ranked, key=lambda r: r[0])[-1]
pairs.append((hyp, ref))
return pairs
|
from itertools import groupby
from nltk.translate import bleu_score
from nltk.tokenize.toktok import ToktokTokenizer
_tokenize = ToktokTokenizer().tokenize
_smoother = bleu_score.SmoothingFunction().method3
bleu = bleu_score.sentence_bleu
def select_first(p):
"""
Return (hypothesis, reference) translation pairs using the first
realization result per item.
"""
pairs = []
rows = p.join('item', 'g-result')
for i_id, group in groupby(rows, key=lambda row: row['g-result:i-id']):
row = next(group)
pairs.append((row['g-result:surface'], row['item:i-translation']))
return pairs
def select_oracle(p):
"""
Return (hypothesis, reference) translation pairs using the
realization result per item with the highest GLEU score.
"""
pairs = []
rows = p.join('item', 'g-result')
for i_id, group in groupby(rows, key=lambda row: row['g-result:i-id']):
scored = []
for res in group:
ref = res['item:i-translation']
hyp = res['g-result:surface']
scored.append(
(bleu([_tokenize(ref)], _tokenize(hyp),
smoothing_function=_smoother), hyp, ref)
)
_, hyp, ref = sorted(scored, key=lambda r: r[0])[-1]
pairs.append((hyp, ref))
return pairs
|
Use NIST-BLEU instead of GLEU for oracle.
|
Use NIST-BLEU instead of GLEU for oracle.
|
Python
|
mit
|
goodmami/xmt,goodmami/xmt
|
from itertools import groupby
from nltk.translate.gleu_score import sentence_gleu as gleu
from nltk.tokenize.toktok import ToktokTokenizer
_tokenize = ToktokTokenizer().tokenize
def select_first(p):
"""
Return (hypothesis, reference) translation pairs using the first
realization result per item.
"""
pairs = []
rows = p.join('item', 'g-result')
for i_id, group in groupby(rows, key=lambda row: row['g-result:i-id']):
row = next(group)
pairs.append((row['g-result:surface'], row['item:i-translation']))
return pairs
def select_oracle(p):
"""
Return (hypothesis, reference) translation pairs using the
realization result per item with the highest GLEU score.
"""
pairs = []
rows = p.join('item', 'g-result')
for i_id, group in groupby(rows, key=lambda row: row['g-result:i-id']):
hrs = ((r['g-result:surface'], r['item:i-translation']) for r in group)
ranked = [(gleu(_tokenize(r), _tokenize(h)), h, r) for h, r in hrs]
_, hyp, ref = sorted(ranked, key=lambda r: r[0])[-1]
pairs.append((hyp, ref))
return pairs
Use NIST-BLEU instead of GLEU for oracle.
|
from itertools import groupby
from nltk.translate import bleu_score
from nltk.tokenize.toktok import ToktokTokenizer
_tokenize = ToktokTokenizer().tokenize
_smoother = bleu_score.SmoothingFunction().method3
bleu = bleu_score.sentence_bleu
def select_first(p):
"""
Return (hypothesis, reference) translation pairs using the first
realization result per item.
"""
pairs = []
rows = p.join('item', 'g-result')
for i_id, group in groupby(rows, key=lambda row: row['g-result:i-id']):
row = next(group)
pairs.append((row['g-result:surface'], row['item:i-translation']))
return pairs
def select_oracle(p):
"""
Return (hypothesis, reference) translation pairs using the
realization result per item with the highest GLEU score.
"""
pairs = []
rows = p.join('item', 'g-result')
for i_id, group in groupby(rows, key=lambda row: row['g-result:i-id']):
scored = []
for res in group:
ref = res['item:i-translation']
hyp = res['g-result:surface']
scored.append(
(bleu([_tokenize(ref)], _tokenize(hyp),
smoothing_function=_smoother), hyp, ref)
)
_, hyp, ref = sorted(scored, key=lambda r: r[0])[-1]
pairs.append((hyp, ref))
return pairs
|
<commit_before>
from itertools import groupby
from nltk.translate.gleu_score import sentence_gleu as gleu
from nltk.tokenize.toktok import ToktokTokenizer
_tokenize = ToktokTokenizer().tokenize
def select_first(p):
"""
Return (hypothesis, reference) translation pairs using the first
realization result per item.
"""
pairs = []
rows = p.join('item', 'g-result')
for i_id, group in groupby(rows, key=lambda row: row['g-result:i-id']):
row = next(group)
pairs.append((row['g-result:surface'], row['item:i-translation']))
return pairs
def select_oracle(p):
"""
Return (hypothesis, reference) translation pairs using the
realization result per item with the highest GLEU score.
"""
pairs = []
rows = p.join('item', 'g-result')
for i_id, group in groupby(rows, key=lambda row: row['g-result:i-id']):
hrs = ((r['g-result:surface'], r['item:i-translation']) for r in group)
ranked = [(gleu(_tokenize(r), _tokenize(h)), h, r) for h, r in hrs]
_, hyp, ref = sorted(ranked, key=lambda r: r[0])[-1]
pairs.append((hyp, ref))
return pairs
<commit_msg>Use NIST-BLEU instead of GLEU for oracle.<commit_after>
|
from itertools import groupby
from nltk.translate import bleu_score
from nltk.tokenize.toktok import ToktokTokenizer
_tokenize = ToktokTokenizer().tokenize
_smoother = bleu_score.SmoothingFunction().method3
bleu = bleu_score.sentence_bleu
def select_first(p):
"""
Return (hypothesis, reference) translation pairs using the first
realization result per item.
"""
pairs = []
rows = p.join('item', 'g-result')
for i_id, group in groupby(rows, key=lambda row: row['g-result:i-id']):
row = next(group)
pairs.append((row['g-result:surface'], row['item:i-translation']))
return pairs
def select_oracle(p):
"""
Return (hypothesis, reference) translation pairs using the
realization result per item with the highest GLEU score.
"""
pairs = []
rows = p.join('item', 'g-result')
for i_id, group in groupby(rows, key=lambda row: row['g-result:i-id']):
scored = []
for res in group:
ref = res['item:i-translation']
hyp = res['g-result:surface']
scored.append(
(bleu([_tokenize(ref)], _tokenize(hyp),
smoothing_function=_smoother), hyp, ref)
)
_, hyp, ref = sorted(scored, key=lambda r: r[0])[-1]
pairs.append((hyp, ref))
return pairs
|
from itertools import groupby
from nltk.translate.gleu_score import sentence_gleu as gleu
from nltk.tokenize.toktok import ToktokTokenizer
_tokenize = ToktokTokenizer().tokenize
def select_first(p):
"""
Return (hypothesis, reference) translation pairs using the first
realization result per item.
"""
pairs = []
rows = p.join('item', 'g-result')
for i_id, group in groupby(rows, key=lambda row: row['g-result:i-id']):
row = next(group)
pairs.append((row['g-result:surface'], row['item:i-translation']))
return pairs
def select_oracle(p):
"""
Return (hypothesis, reference) translation pairs using the
realization result per item with the highest GLEU score.
"""
pairs = []
rows = p.join('item', 'g-result')
for i_id, group in groupby(rows, key=lambda row: row['g-result:i-id']):
hrs = ((r['g-result:surface'], r['item:i-translation']) for r in group)
ranked = [(gleu(_tokenize(r), _tokenize(h)), h, r) for h, r in hrs]
_, hyp, ref = sorted(ranked, key=lambda r: r[0])[-1]
pairs.append((hyp, ref))
return pairs
Use NIST-BLEU instead of GLEU for oracle.
from itertools import groupby
from nltk.translate import bleu_score
from nltk.tokenize.toktok import ToktokTokenizer
_tokenize = ToktokTokenizer().tokenize
_smoother = bleu_score.SmoothingFunction().method3
bleu = bleu_score.sentence_bleu
def select_first(p):
"""
Return (hypothesis, reference) translation pairs using the first
realization result per item.
"""
pairs = []
rows = p.join('item', 'g-result')
for i_id, group in groupby(rows, key=lambda row: row['g-result:i-id']):
row = next(group)
pairs.append((row['g-result:surface'], row['item:i-translation']))
return pairs
def select_oracle(p):
"""
Return (hypothesis, reference) translation pairs using the
realization result per item with the highest GLEU score.
"""
pairs = []
rows = p.join('item', 'g-result')
for i_id, group in groupby(rows, key=lambda row: row['g-result:i-id']):
scored = []
for res in group:
ref = res['item:i-translation']
hyp = res['g-result:surface']
scored.append(
(bleu([_tokenize(ref)], _tokenize(hyp),
smoothing_function=_smoother), hyp, ref)
)
_, hyp, ref = sorted(scored, key=lambda r: r[0])[-1]
pairs.append((hyp, ref))
return pairs
|
<commit_before>
from itertools import groupby
from nltk.translate.gleu_score import sentence_gleu as gleu
from nltk.tokenize.toktok import ToktokTokenizer
_tokenize = ToktokTokenizer().tokenize
def select_first(p):
"""
Return (hypothesis, reference) translation pairs using the first
realization result per item.
"""
pairs = []
rows = p.join('item', 'g-result')
for i_id, group in groupby(rows, key=lambda row: row['g-result:i-id']):
row = next(group)
pairs.append((row['g-result:surface'], row['item:i-translation']))
return pairs
def select_oracle(p):
"""
Return (hypothesis, reference) translation pairs using the
realization result per item with the highest GLEU score.
"""
pairs = []
rows = p.join('item', 'g-result')
for i_id, group in groupby(rows, key=lambda row: row['g-result:i-id']):
hrs = ((r['g-result:surface'], r['item:i-translation']) for r in group)
ranked = [(gleu(_tokenize(r), _tokenize(h)), h, r) for h, r in hrs]
_, hyp, ref = sorted(ranked, key=lambda r: r[0])[-1]
pairs.append((hyp, ref))
return pairs
<commit_msg>Use NIST-BLEU instead of GLEU for oracle.<commit_after>
from itertools import groupby
from nltk.translate import bleu_score
from nltk.tokenize.toktok import ToktokTokenizer
_tokenize = ToktokTokenizer().tokenize
_smoother = bleu_score.SmoothingFunction().method3
bleu = bleu_score.sentence_bleu
def select_first(p):
"""
Return (hypothesis, reference) translation pairs using the first
realization result per item.
"""
pairs = []
rows = p.join('item', 'g-result')
for i_id, group in groupby(rows, key=lambda row: row['g-result:i-id']):
row = next(group)
pairs.append((row['g-result:surface'], row['item:i-translation']))
return pairs
def select_oracle(p):
"""
Return (hypothesis, reference) translation pairs using the
realization result per item with the highest GLEU score.
"""
pairs = []
rows = p.join('item', 'g-result')
for i_id, group in groupby(rows, key=lambda row: row['g-result:i-id']):
scored = []
for res in group:
ref = res['item:i-translation']
hyp = res['g-result:surface']
scored.append(
(bleu([_tokenize(ref)], _tokenize(hyp),
smoothing_function=_smoother), hyp, ref)
)
_, hyp, ref = sorted(scored, key=lambda r: r[0])[-1]
pairs.append((hyp, ref))
return pairs
|
3d53d70ea657bcdd0f6ed28b4c9ae1f8e894b45a
|
cellcounter/accounts/models.py
|
cellcounter/accounts/models.py
|
import os
import simplejson as json
from django.db import models
from django.contrib.auth.models import User
from django_extensions.db.fields.json import JSONField
from django.conf import settings
from django.db.models.signals import post_save
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
keyboard = JSONField(blank=True, null=True)
def __unicode__(self):
return u"Profile of user: {}".format(self.user.username)
def create_user_profile(sender, instance, created, **kwargs):
if created:
profile = UserProfile.objects.create(user=instance)
try:
# TODO Get this from database?
profile.keyboard = json.load(open(os.path.join(settings.PROJECT_DIR,
'accounts/keyboard.json'), 'r'))
profile.save()
except IOError:
# If a default keyboard configuration is not provided do nothing
# TODO Should this throw a configuration exception
pass
post_save.connect(create_user_profile, sender=User)
|
import os
import simplejson as json
from django.db import models
from django.contrib.auth.models import User
from django_extensions.db.fields.json import JSONField
from django.conf import settings
from django.db.models.signals import post_save
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
keyboard = JSONField(blank=True, null=True)
def __unicode__(self):
return u"Profile of user %s" % (self.user.username)
def create_user_profile(sender, instance, created, **kwargs):
if created:
profile = UserProfile.objects.create(user=instance)
try:
# TODO Get this from database?
profile.keyboard = json.load(open(os.path.join(settings.PROJECT_DIR,
'accounts/keyboard.json'), 'r'))
profile.save()
except IOError:
# If a default keyboard configuration is not provided do nothing
# TODO Should this throw a configuration exception
pass
post_save.connect(create_user_profile, sender=User)
|
Correct unicde function so UserProfile is correctly displayed in the admin form
|
Correct unicde function so UserProfile is correctly displayed in the admin form
|
Python
|
mit
|
haematologic/cellcounter,haematologic/cellcounter,cellcounter/cellcounter,cellcounter/cellcounter,haematologic/cellcounter,cellcounter/cellcounter,cellcounter/cellcounter
|
import os
import simplejson as json
from django.db import models
from django.contrib.auth.models import User
from django_extensions.db.fields.json import JSONField
from django.conf import settings
from django.db.models.signals import post_save
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
keyboard = JSONField(blank=True, null=True)
def __unicode__(self):
return u"Profile of user: {}".format(self.user.username)
def create_user_profile(sender, instance, created, **kwargs):
if created:
profile = UserProfile.objects.create(user=instance)
try:
# TODO Get this from database?
profile.keyboard = json.load(open(os.path.join(settings.PROJECT_DIR,
'accounts/keyboard.json'), 'r'))
profile.save()
except IOError:
# If a default keyboard configuration is not provided do nothing
# TODO Should this throw a configuration exception
pass
post_save.connect(create_user_profile, sender=User)
Correct unicde function so UserProfile is correctly displayed in the admin form
|
import os
import simplejson as json
from django.db import models
from django.contrib.auth.models import User
from django_extensions.db.fields.json import JSONField
from django.conf import settings
from django.db.models.signals import post_save
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
keyboard = JSONField(blank=True, null=True)
def __unicode__(self):
return u"Profile of user %s" % (self.user.username)
def create_user_profile(sender, instance, created, **kwargs):
if created:
profile = UserProfile.objects.create(user=instance)
try:
# TODO Get this from database?
profile.keyboard = json.load(open(os.path.join(settings.PROJECT_DIR,
'accounts/keyboard.json'), 'r'))
profile.save()
except IOError:
# If a default keyboard configuration is not provided do nothing
# TODO Should this throw a configuration exception
pass
post_save.connect(create_user_profile, sender=User)
|
<commit_before>import os
import simplejson as json
from django.db import models
from django.contrib.auth.models import User
from django_extensions.db.fields.json import JSONField
from django.conf import settings
from django.db.models.signals import post_save
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
keyboard = JSONField(blank=True, null=True)
def __unicode__(self):
return u"Profile of user: {}".format(self.user.username)
def create_user_profile(sender, instance, created, **kwargs):
if created:
profile = UserProfile.objects.create(user=instance)
try:
# TODO Get this from database?
profile.keyboard = json.load(open(os.path.join(settings.PROJECT_DIR,
'accounts/keyboard.json'), 'r'))
profile.save()
except IOError:
# If a default keyboard configuration is not provided do nothing
# TODO Should this throw a configuration exception
pass
post_save.connect(create_user_profile, sender=User)
<commit_msg>Correct unicde function so UserProfile is correctly displayed in the admin form<commit_after>
|
import os
import simplejson as json
from django.db import models
from django.contrib.auth.models import User
from django_extensions.db.fields.json import JSONField
from django.conf import settings
from django.db.models.signals import post_save
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
keyboard = JSONField(blank=True, null=True)
def __unicode__(self):
return u"Profile of user %s" % (self.user.username)
def create_user_profile(sender, instance, created, **kwargs):
if created:
profile = UserProfile.objects.create(user=instance)
try:
# TODO Get this from database?
profile.keyboard = json.load(open(os.path.join(settings.PROJECT_DIR,
'accounts/keyboard.json'), 'r'))
profile.save()
except IOError:
# If a default keyboard configuration is not provided do nothing
# TODO Should this throw a configuration exception
pass
post_save.connect(create_user_profile, sender=User)
|
import os
import simplejson as json
from django.db import models
from django.contrib.auth.models import User
from django_extensions.db.fields.json import JSONField
from django.conf import settings
from django.db.models.signals import post_save
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
keyboard = JSONField(blank=True, null=True)
def __unicode__(self):
return u"Profile of user: {}".format(self.user.username)
def create_user_profile(sender, instance, created, **kwargs):
if created:
profile = UserProfile.objects.create(user=instance)
try:
# TODO Get this from database?
profile.keyboard = json.load(open(os.path.join(settings.PROJECT_DIR,
'accounts/keyboard.json'), 'r'))
profile.save()
except IOError:
# If a default keyboard configuration is not provided do nothing
# TODO Should this throw a configuration exception
pass
post_save.connect(create_user_profile, sender=User)
Correct unicde function so UserProfile is correctly displayed in the admin formimport os
import simplejson as json
from django.db import models
from django.contrib.auth.models import User
from django_extensions.db.fields.json import JSONField
from django.conf import settings
from django.db.models.signals import post_save
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
keyboard = JSONField(blank=True, null=True)
def __unicode__(self):
return u"Profile of user %s" % (self.user.username)
def create_user_profile(sender, instance, created, **kwargs):
if created:
profile = UserProfile.objects.create(user=instance)
try:
# TODO Get this from database?
profile.keyboard = json.load(open(os.path.join(settings.PROJECT_DIR,
'accounts/keyboard.json'), 'r'))
profile.save()
except IOError:
# If a default keyboard configuration is not provided do nothing
# TODO Should this throw a configuration exception
pass
post_save.connect(create_user_profile, sender=User)
|
<commit_before>import os
import simplejson as json
from django.db import models
from django.contrib.auth.models import User
from django_extensions.db.fields.json import JSONField
from django.conf import settings
from django.db.models.signals import post_save
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
keyboard = JSONField(blank=True, null=True)
def __unicode__(self):
return u"Profile of user: {}".format(self.user.username)
def create_user_profile(sender, instance, created, **kwargs):
if created:
profile = UserProfile.objects.create(user=instance)
try:
# TODO Get this from database?
profile.keyboard = json.load(open(os.path.join(settings.PROJECT_DIR,
'accounts/keyboard.json'), 'r'))
profile.save()
except IOError:
# If a default keyboard configuration is not provided do nothing
# TODO Should this throw a configuration exception
pass
post_save.connect(create_user_profile, sender=User)
<commit_msg>Correct unicde function so UserProfile is correctly displayed in the admin form<commit_after>import os
import simplejson as json
from django.db import models
from django.contrib.auth.models import User
from django_extensions.db.fields.json import JSONField
from django.conf import settings
from django.db.models.signals import post_save
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
keyboard = JSONField(blank=True, null=True)
def __unicode__(self):
return u"Profile of user %s" % (self.user.username)
def create_user_profile(sender, instance, created, **kwargs):
if created:
profile = UserProfile.objects.create(user=instance)
try:
# TODO Get this from database?
profile.keyboard = json.load(open(os.path.join(settings.PROJECT_DIR,
'accounts/keyboard.json'), 'r'))
profile.save()
except IOError:
# If a default keyboard configuration is not provided do nothing
# TODO Should this throw a configuration exception
pass
post_save.connect(create_user_profile, sender=User)
|
499add1d29847490141cda4625d9a4199e386283
|
ncdc_download/download_mapper2.py
|
ncdc_download/download_mapper2.py
|
#!/usr/bin/env python3
import ftplib
import gzip
import os
import sys
host = 'ftp.ncdc.noaa.gov'
base = '/pub/data/noaa'
retries = 3
ftp = ftplib.FTP(host)
ftp.login()
for line in sys.stdin:
(year, filename) = line.strip().split()
for i in range(retries):
sys.stderr.write('reporter:status:Processing file %s/%s (FTP attempt %d of %d)\n' % (year,
filename, i + 1, retries))
try:
ftp.retrbinary('RETR %s/%s/%s' % (base, year, filename), open(filename, 'wb').write)
except ftplib.all_errors as error:
sys.stderr.write('%s\n' % error)
continue
count = 0
for record in gzip.open(filename, 'rb'):
print('%s\t%s' % (year, record.decode('ISO-8859-1').strip()))
count += 1
sys.stderr.write('reporter:counter:NCDC Download,%s,%d\n' % (year, count))
os.remove(filename)
break
else:
ftp.quit()
sys.exit(1)
ftp.quit()
|
#!/usr/bin/env python3
import ftplib
import gzip
import os
import sys
host = 'ftp.ncdc.noaa.gov'
base = '/pub/data/noaa'
retries = 3
ftp = ftplib.FTP(host)
ftp.login()
for line in sys.stdin:
(year, filename) = line.strip().split()
for i in range(retries):
sys.stderr.write('reporter:status:Processing file %s/%s (FTP attempt %d of %d)\n' % (year,
filename, i + 1, retries))
try:
ftp.retrbinary('RETR %s/%s/%s' % (base, year, filename), open(filename, 'wb').write)
except ftplib.all_errors as error:
sys.stderr.write('%s\n' % error)
continue
count = 0
for record in gzip.open(filename, 'rb'):
print('%s\t%s' % (year, record.decode('ISO-8859-1').strip()))
count += 1
os.remove(filename)
sys.stderr.write('reporter:counter:NCDC Download,%s,%d\n' % (year, count))
break
else:
ftp.quit()
sys.exit(1)
ftp.quit()
|
Remove downloaded file before updating counter
|
Remove downloaded file before updating counter
|
Python
|
mit
|
simonbrady/cat,simonbrady/cat
|
#!/usr/bin/env python3
import ftplib
import gzip
import os
import sys
host = 'ftp.ncdc.noaa.gov'
base = '/pub/data/noaa'
retries = 3
ftp = ftplib.FTP(host)
ftp.login()
for line in sys.stdin:
(year, filename) = line.strip().split()
for i in range(retries):
sys.stderr.write('reporter:status:Processing file %s/%s (FTP attempt %d of %d)\n' % (year,
filename, i + 1, retries))
try:
ftp.retrbinary('RETR %s/%s/%s' % (base, year, filename), open(filename, 'wb').write)
except ftplib.all_errors as error:
sys.stderr.write('%s\n' % error)
continue
count = 0
for record in gzip.open(filename, 'rb'):
print('%s\t%s' % (year, record.decode('ISO-8859-1').strip()))
count += 1
sys.stderr.write('reporter:counter:NCDC Download,%s,%d\n' % (year, count))
os.remove(filename)
break
else:
ftp.quit()
sys.exit(1)
ftp.quit()
Remove downloaded file before updating counter
|
#!/usr/bin/env python3
import ftplib
import gzip
import os
import sys
host = 'ftp.ncdc.noaa.gov'
base = '/pub/data/noaa'
retries = 3
ftp = ftplib.FTP(host)
ftp.login()
for line in sys.stdin:
(year, filename) = line.strip().split()
for i in range(retries):
sys.stderr.write('reporter:status:Processing file %s/%s (FTP attempt %d of %d)\n' % (year,
filename, i + 1, retries))
try:
ftp.retrbinary('RETR %s/%s/%s' % (base, year, filename), open(filename, 'wb').write)
except ftplib.all_errors as error:
sys.stderr.write('%s\n' % error)
continue
count = 0
for record in gzip.open(filename, 'rb'):
print('%s\t%s' % (year, record.decode('ISO-8859-1').strip()))
count += 1
os.remove(filename)
sys.stderr.write('reporter:counter:NCDC Download,%s,%d\n' % (year, count))
break
else:
ftp.quit()
sys.exit(1)
ftp.quit()
|
<commit_before>#!/usr/bin/env python3
import ftplib
import gzip
import os
import sys
host = 'ftp.ncdc.noaa.gov'
base = '/pub/data/noaa'
retries = 3
ftp = ftplib.FTP(host)
ftp.login()
for line in sys.stdin:
(year, filename) = line.strip().split()
for i in range(retries):
sys.stderr.write('reporter:status:Processing file %s/%s (FTP attempt %d of %d)\n' % (year,
filename, i + 1, retries))
try:
ftp.retrbinary('RETR %s/%s/%s' % (base, year, filename), open(filename, 'wb').write)
except ftplib.all_errors as error:
sys.stderr.write('%s\n' % error)
continue
count = 0
for record in gzip.open(filename, 'rb'):
print('%s\t%s' % (year, record.decode('ISO-8859-1').strip()))
count += 1
sys.stderr.write('reporter:counter:NCDC Download,%s,%d\n' % (year, count))
os.remove(filename)
break
else:
ftp.quit()
sys.exit(1)
ftp.quit()
<commit_msg>Remove downloaded file before updating counter<commit_after>
|
#!/usr/bin/env python3
import ftplib
import gzip
import os
import sys
host = 'ftp.ncdc.noaa.gov'
base = '/pub/data/noaa'
retries = 3
ftp = ftplib.FTP(host)
ftp.login()
for line in sys.stdin:
(year, filename) = line.strip().split()
for i in range(retries):
sys.stderr.write('reporter:status:Processing file %s/%s (FTP attempt %d of %d)\n' % (year,
filename, i + 1, retries))
try:
ftp.retrbinary('RETR %s/%s/%s' % (base, year, filename), open(filename, 'wb').write)
except ftplib.all_errors as error:
sys.stderr.write('%s\n' % error)
continue
count = 0
for record in gzip.open(filename, 'rb'):
print('%s\t%s' % (year, record.decode('ISO-8859-1').strip()))
count += 1
os.remove(filename)
sys.stderr.write('reporter:counter:NCDC Download,%s,%d\n' % (year, count))
break
else:
ftp.quit()
sys.exit(1)
ftp.quit()
|
#!/usr/bin/env python3
import ftplib
import gzip
import os
import sys
host = 'ftp.ncdc.noaa.gov'
base = '/pub/data/noaa'
retries = 3
ftp = ftplib.FTP(host)
ftp.login()
for line in sys.stdin:
(year, filename) = line.strip().split()
for i in range(retries):
sys.stderr.write('reporter:status:Processing file %s/%s (FTP attempt %d of %d)\n' % (year,
filename, i + 1, retries))
try:
ftp.retrbinary('RETR %s/%s/%s' % (base, year, filename), open(filename, 'wb').write)
except ftplib.all_errors as error:
sys.stderr.write('%s\n' % error)
continue
count = 0
for record in gzip.open(filename, 'rb'):
print('%s\t%s' % (year, record.decode('ISO-8859-1').strip()))
count += 1
sys.stderr.write('reporter:counter:NCDC Download,%s,%d\n' % (year, count))
os.remove(filename)
break
else:
ftp.quit()
sys.exit(1)
ftp.quit()
Remove downloaded file before updating counter#!/usr/bin/env python3
import ftplib
import gzip
import os
import sys
host = 'ftp.ncdc.noaa.gov'
base = '/pub/data/noaa'
retries = 3
ftp = ftplib.FTP(host)
ftp.login()
for line in sys.stdin:
(year, filename) = line.strip().split()
for i in range(retries):
sys.stderr.write('reporter:status:Processing file %s/%s (FTP attempt %d of %d)\n' % (year,
filename, i + 1, retries))
try:
ftp.retrbinary('RETR %s/%s/%s' % (base, year, filename), open(filename, 'wb').write)
except ftplib.all_errors as error:
sys.stderr.write('%s\n' % error)
continue
count = 0
for record in gzip.open(filename, 'rb'):
print('%s\t%s' % (year, record.decode('ISO-8859-1').strip()))
count += 1
os.remove(filename)
sys.stderr.write('reporter:counter:NCDC Download,%s,%d\n' % (year, count))
break
else:
ftp.quit()
sys.exit(1)
ftp.quit()
|
<commit_before>#!/usr/bin/env python3
import ftplib
import gzip
import os
import sys
host = 'ftp.ncdc.noaa.gov'
base = '/pub/data/noaa'
retries = 3
ftp = ftplib.FTP(host)
ftp.login()
for line in sys.stdin:
(year, filename) = line.strip().split()
for i in range(retries):
sys.stderr.write('reporter:status:Processing file %s/%s (FTP attempt %d of %d)\n' % (year,
filename, i + 1, retries))
try:
ftp.retrbinary('RETR %s/%s/%s' % (base, year, filename), open(filename, 'wb').write)
except ftplib.all_errors as error:
sys.stderr.write('%s\n' % error)
continue
count = 0
for record in gzip.open(filename, 'rb'):
print('%s\t%s' % (year, record.decode('ISO-8859-1').strip()))
count += 1
sys.stderr.write('reporter:counter:NCDC Download,%s,%d\n' % (year, count))
os.remove(filename)
break
else:
ftp.quit()
sys.exit(1)
ftp.quit()
<commit_msg>Remove downloaded file before updating counter<commit_after>#!/usr/bin/env python3
import ftplib
import gzip
import os
import sys
host = 'ftp.ncdc.noaa.gov'
base = '/pub/data/noaa'
retries = 3
ftp = ftplib.FTP(host)
ftp.login()
for line in sys.stdin:
(year, filename) = line.strip().split()
for i in range(retries):
sys.stderr.write('reporter:status:Processing file %s/%s (FTP attempt %d of %d)\n' % (year,
filename, i + 1, retries))
try:
ftp.retrbinary('RETR %s/%s/%s' % (base, year, filename), open(filename, 'wb').write)
except ftplib.all_errors as error:
sys.stderr.write('%s\n' % error)
continue
count = 0
for record in gzip.open(filename, 'rb'):
print('%s\t%s' % (year, record.decode('ISO-8859-1').strip()))
count += 1
os.remove(filename)
sys.stderr.write('reporter:counter:NCDC Download,%s,%d\n' % (year, count))
break
else:
ftp.quit()
sys.exit(1)
ftp.quit()
|
1d1dcccc31cb566ec0e8d37926cf72fecef1b70d
|
weaveserver/services/simpledb/__init__.py
|
weaveserver/services/simpledb/__init__.py
|
from .service import SimpleDatabaseService
__meta__ = {
"name": "Simple Database",
"class": SimpleDatabaseService,
"deps": ["messaging", "appmanager"],
"config": []
}
|
from .service import SimpleDatabaseService
__meta__ = {
"name": "Simple Database",
"class": SimpleDatabaseService,
"deps": ["messaging", "appmanager"],
"config": [
{
"name": "core",
"loaders": [
{"type": "env"},
{"type": "sysvarfile"}
]
}
]
}
|
Add sysvarfile and env config loaders to simpledb.
|
Add sysvarfile and env config loaders to simpledb.
|
Python
|
mit
|
supersaiyanmode/HomePiServer,supersaiyanmode/HomePiServer,supersaiyanmode/HomePiServer
|
from .service import SimpleDatabaseService
__meta__ = {
"name": "Simple Database",
"class": SimpleDatabaseService,
"deps": ["messaging", "appmanager"],
"config": []
}
Add sysvarfile and env config loaders to simpledb.
|
from .service import SimpleDatabaseService
__meta__ = {
"name": "Simple Database",
"class": SimpleDatabaseService,
"deps": ["messaging", "appmanager"],
"config": [
{
"name": "core",
"loaders": [
{"type": "env"},
{"type": "sysvarfile"}
]
}
]
}
|
<commit_before>from .service import SimpleDatabaseService
__meta__ = {
"name": "Simple Database",
"class": SimpleDatabaseService,
"deps": ["messaging", "appmanager"],
"config": []
}
<commit_msg>Add sysvarfile and env config loaders to simpledb.<commit_after>
|
from .service import SimpleDatabaseService
__meta__ = {
"name": "Simple Database",
"class": SimpleDatabaseService,
"deps": ["messaging", "appmanager"],
"config": [
{
"name": "core",
"loaders": [
{"type": "env"},
{"type": "sysvarfile"}
]
}
]
}
|
from .service import SimpleDatabaseService
__meta__ = {
"name": "Simple Database",
"class": SimpleDatabaseService,
"deps": ["messaging", "appmanager"],
"config": []
}
Add sysvarfile and env config loaders to simpledb.from .service import SimpleDatabaseService
__meta__ = {
"name": "Simple Database",
"class": SimpleDatabaseService,
"deps": ["messaging", "appmanager"],
"config": [
{
"name": "core",
"loaders": [
{"type": "env"},
{"type": "sysvarfile"}
]
}
]
}
|
<commit_before>from .service import SimpleDatabaseService
__meta__ = {
"name": "Simple Database",
"class": SimpleDatabaseService,
"deps": ["messaging", "appmanager"],
"config": []
}
<commit_msg>Add sysvarfile and env config loaders to simpledb.<commit_after>from .service import SimpleDatabaseService
__meta__ = {
"name": "Simple Database",
"class": SimpleDatabaseService,
"deps": ["messaging", "appmanager"],
"config": [
{
"name": "core",
"loaders": [
{"type": "env"},
{"type": "sysvarfile"}
]
}
]
}
|
96512dd8484353bacd134a0bf9db774a166d530c
|
mitmproxy/platform/osx.py
|
mitmproxy/platform/osx.py
|
import subprocess
import pf
"""
Doing this the "right" way by using DIOCNATLOOK on the pf device turns out
to be a pain. Apple has made a number of modifications to the data
structures returned, and compiling userspace tools to test and work with
this turns out to be a pain in the ass. Parsing pfctl output is short,
simple, and works.
Note: Also Tested with FreeBSD 10 pkgng Python 2.7.x.
Should work almost exactly as on Mac OS X and except with some changes to
the output processing of pfctl (see pf.py).
"""
class Resolver(object):
STATECMD = ("sudo", "-n", "/sbin/pfctl", "-s", "state")
def original_addr(self, csock):
peer = csock.getpeername()
try:
stxt = subprocess.check_output(self.STATECMD, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
if "sudo: a password is required" in e.output:
insufficient_priv = True
else:
raise RuntimeError("Error getting pfctl state: " + repr(e))
else:
insufficient_priv = "sudo: a password is required" in stxt
if insufficient_priv:
raise RuntimeError(
"Insufficient privileges to access pfctl. "
"See http://mitmproxy.org/doc/transparent/osx.html for details.")
return pf.lookup(peer[0], peer[1], stxt)
|
import subprocess
import pf
"""
Doing this the "right" way by using DIOCNATLOOK on the pf device turns out
to be a pain. Apple has made a number of modifications to the data
structures returned, and compiling userspace tools to test and work with
this turns out to be a pain in the ass. Parsing pfctl output is short,
simple, and works.
Note: Also Tested with FreeBSD 10 pkgng Python 2.7.x.
Should work almost exactly as on Mac OS X and except with some changes to
the output processing of pfctl (see pf.py).
"""
class Resolver(object):
STATECMD = ("sudo", "-n", "/sbin/pfctl", "-s", "state")
def original_addr(self, csock):
peer = csock.getpeername()
try:
stxt = subprocess.check_output(self.STATECMD, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
if "sudo: a password is required" in e.output:
insufficient_priv = True
else:
raise RuntimeError("Error getting pfctl state: " + repr(e))
else:
insufficient_priv = "sudo: a password is required" in stxt
if insufficient_priv:
raise RuntimeError(
"Insufficient privileges to access pfctl. "
"See http://docs.mitmproxy.org/en/latest/transparent/osx.html for details.")
return pf.lookup(peer[0], peer[1], stxt)
|
Include correct documentation URL in error message
|
Include correct documentation URL in error message
|
Python
|
mit
|
mhils/mitmproxy,laurmurclar/mitmproxy,vhaupert/mitmproxy,dufferzafar/mitmproxy,mitmproxy/mitmproxy,laurmurclar/mitmproxy,cortesi/mitmproxy,vhaupert/mitmproxy,StevenVanAcker/mitmproxy,jvillacorta/mitmproxy,mitmproxy/mitmproxy,zlorb/mitmproxy,StevenVanAcker/mitmproxy,dwfreed/mitmproxy,Kriechi/mitmproxy,dwfreed/mitmproxy,xaxa89/mitmproxy,gzzhanghao/mitmproxy,cortesi/mitmproxy,ddworken/mitmproxy,jvillacorta/mitmproxy,dufferzafar/mitmproxy,ddworken/mitmproxy,ujjwal96/mitmproxy,MatthewShao/mitmproxy,tdickers/mitmproxy,ujjwal96/mitmproxy,MatthewShao/mitmproxy,Kriechi/mitmproxy,mhils/mitmproxy,cortesi/mitmproxy,gzzhanghao/mitmproxy,tdickers/mitmproxy,gzzhanghao/mitmproxy,mhils/mitmproxy,dufferzafar/mitmproxy,jvillacorta/mitmproxy,vhaupert/mitmproxy,ddworken/mitmproxy,StevenVanAcker/mitmproxy,tdickers/mitmproxy,laurmurclar/mitmproxy,ujjwal96/mitmproxy,xaxa89/mitmproxy,mosajjal/mitmproxy,MatthewShao/mitmproxy,mitmproxy/mitmproxy,ujjwal96/mitmproxy,ddworken/mitmproxy,Kriechi/mitmproxy,mosajjal/mitmproxy,mhils/mitmproxy,xaxa89/mitmproxy,mosajjal/mitmproxy,MatthewShao/mitmproxy,mosajjal/mitmproxy,jvillacorta/mitmproxy,dufferzafar/mitmproxy,StevenVanAcker/mitmproxy,mitmproxy/mitmproxy,cortesi/mitmproxy,vhaupert/mitmproxy,laurmurclar/mitmproxy,dwfreed/mitmproxy,dwfreed/mitmproxy,zlorb/mitmproxy,xaxa89/mitmproxy,mitmproxy/mitmproxy,tdickers/mitmproxy,Kriechi/mitmproxy,zlorb/mitmproxy,gzzhanghao/mitmproxy,zlorb/mitmproxy,mhils/mitmproxy
|
import subprocess
import pf
"""
Doing this the "right" way by using DIOCNATLOOK on the pf device turns out
to be a pain. Apple has made a number of modifications to the data
structures returned, and compiling userspace tools to test and work with
this turns out to be a pain in the ass. Parsing pfctl output is short,
simple, and works.
Note: Also Tested with FreeBSD 10 pkgng Python 2.7.x.
Should work almost exactly as on Mac OS X and except with some changes to
the output processing of pfctl (see pf.py).
"""
class Resolver(object):
STATECMD = ("sudo", "-n", "/sbin/pfctl", "-s", "state")
def original_addr(self, csock):
peer = csock.getpeername()
try:
stxt = subprocess.check_output(self.STATECMD, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
if "sudo: a password is required" in e.output:
insufficient_priv = True
else:
raise RuntimeError("Error getting pfctl state: " + repr(e))
else:
insufficient_priv = "sudo: a password is required" in stxt
if insufficient_priv:
raise RuntimeError(
"Insufficient privileges to access pfctl. "
"See http://mitmproxy.org/doc/transparent/osx.html for details.")
return pf.lookup(peer[0], peer[1], stxt)
Include correct documentation URL in error message
|
import subprocess
import pf
"""
Doing this the "right" way by using DIOCNATLOOK on the pf device turns out
to be a pain. Apple has made a number of modifications to the data
structures returned, and compiling userspace tools to test and work with
this turns out to be a pain in the ass. Parsing pfctl output is short,
simple, and works.
Note: Also Tested with FreeBSD 10 pkgng Python 2.7.x.
Should work almost exactly as on Mac OS X and except with some changes to
the output processing of pfctl (see pf.py).
"""
class Resolver(object):
STATECMD = ("sudo", "-n", "/sbin/pfctl", "-s", "state")
def original_addr(self, csock):
peer = csock.getpeername()
try:
stxt = subprocess.check_output(self.STATECMD, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
if "sudo: a password is required" in e.output:
insufficient_priv = True
else:
raise RuntimeError("Error getting pfctl state: " + repr(e))
else:
insufficient_priv = "sudo: a password is required" in stxt
if insufficient_priv:
raise RuntimeError(
"Insufficient privileges to access pfctl. "
"See http://docs.mitmproxy.org/en/latest/transparent/osx.html for details.")
return pf.lookup(peer[0], peer[1], stxt)
|
<commit_before>import subprocess
import pf
"""
Doing this the "right" way by using DIOCNATLOOK on the pf device turns out
to be a pain. Apple has made a number of modifications to the data
structures returned, and compiling userspace tools to test and work with
this turns out to be a pain in the ass. Parsing pfctl output is short,
simple, and works.
Note: Also Tested with FreeBSD 10 pkgng Python 2.7.x.
Should work almost exactly as on Mac OS X and except with some changes to
the output processing of pfctl (see pf.py).
"""
class Resolver(object):
STATECMD = ("sudo", "-n", "/sbin/pfctl", "-s", "state")
def original_addr(self, csock):
peer = csock.getpeername()
try:
stxt = subprocess.check_output(self.STATECMD, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
if "sudo: a password is required" in e.output:
insufficient_priv = True
else:
raise RuntimeError("Error getting pfctl state: " + repr(e))
else:
insufficient_priv = "sudo: a password is required" in stxt
if insufficient_priv:
raise RuntimeError(
"Insufficient privileges to access pfctl. "
"See http://mitmproxy.org/doc/transparent/osx.html for details.")
return pf.lookup(peer[0], peer[1], stxt)
<commit_msg>Include correct documentation URL in error message<commit_after>
|
import subprocess
import pf
"""
Doing this the "right" way by using DIOCNATLOOK on the pf device turns out
to be a pain. Apple has made a number of modifications to the data
structures returned, and compiling userspace tools to test and work with
this turns out to be a pain in the ass. Parsing pfctl output is short,
simple, and works.
Note: Also Tested with FreeBSD 10 pkgng Python 2.7.x.
Should work almost exactly as on Mac OS X and except with some changes to
the output processing of pfctl (see pf.py).
"""
class Resolver(object):
STATECMD = ("sudo", "-n", "/sbin/pfctl", "-s", "state")
def original_addr(self, csock):
peer = csock.getpeername()
try:
stxt = subprocess.check_output(self.STATECMD, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
if "sudo: a password is required" in e.output:
insufficient_priv = True
else:
raise RuntimeError("Error getting pfctl state: " + repr(e))
else:
insufficient_priv = "sudo: a password is required" in stxt
if insufficient_priv:
raise RuntimeError(
"Insufficient privileges to access pfctl. "
"See http://docs.mitmproxy.org/en/latest/transparent/osx.html for details.")
return pf.lookup(peer[0], peer[1], stxt)
|
import subprocess
import pf
"""
Doing this the "right" way by using DIOCNATLOOK on the pf device turns out
to be a pain. Apple has made a number of modifications to the data
structures returned, and compiling userspace tools to test and work with
this turns out to be a pain in the ass. Parsing pfctl output is short,
simple, and works.
Note: Also Tested with FreeBSD 10 pkgng Python 2.7.x.
Should work almost exactly as on Mac OS X and except with some changes to
the output processing of pfctl (see pf.py).
"""
class Resolver(object):
STATECMD = ("sudo", "-n", "/sbin/pfctl", "-s", "state")
def original_addr(self, csock):
peer = csock.getpeername()
try:
stxt = subprocess.check_output(self.STATECMD, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
if "sudo: a password is required" in e.output:
insufficient_priv = True
else:
raise RuntimeError("Error getting pfctl state: " + repr(e))
else:
insufficient_priv = "sudo: a password is required" in stxt
if insufficient_priv:
raise RuntimeError(
"Insufficient privileges to access pfctl. "
"See http://mitmproxy.org/doc/transparent/osx.html for details.")
return pf.lookup(peer[0], peer[1], stxt)
Include correct documentation URL in error messageimport subprocess
import pf
"""
Doing this the "right" way by using DIOCNATLOOK on the pf device turns out
to be a pain. Apple has made a number of modifications to the data
structures returned, and compiling userspace tools to test and work with
this turns out to be a pain in the ass. Parsing pfctl output is short,
simple, and works.
Note: Also Tested with FreeBSD 10 pkgng Python 2.7.x.
Should work almost exactly as on Mac OS X and except with some changes to
the output processing of pfctl (see pf.py).
"""
class Resolver(object):
STATECMD = ("sudo", "-n", "/sbin/pfctl", "-s", "state")
def original_addr(self, csock):
peer = csock.getpeername()
try:
stxt = subprocess.check_output(self.STATECMD, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
if "sudo: a password is required" in e.output:
insufficient_priv = True
else:
raise RuntimeError("Error getting pfctl state: " + repr(e))
else:
insufficient_priv = "sudo: a password is required" in stxt
if insufficient_priv:
raise RuntimeError(
"Insufficient privileges to access pfctl. "
"See http://docs.mitmproxy.org/en/latest/transparent/osx.html for details.")
return pf.lookup(peer[0], peer[1], stxt)
|
<commit_before>import subprocess
import pf
"""
Doing this the "right" way by using DIOCNATLOOK on the pf device turns out
to be a pain. Apple has made a number of modifications to the data
structures returned, and compiling userspace tools to test and work with
this turns out to be a pain in the ass. Parsing pfctl output is short,
simple, and works.
Note: Also Tested with FreeBSD 10 pkgng Python 2.7.x.
Should work almost exactly as on Mac OS X and except with some changes to
the output processing of pfctl (see pf.py).
"""
class Resolver(object):
STATECMD = ("sudo", "-n", "/sbin/pfctl", "-s", "state")
def original_addr(self, csock):
peer = csock.getpeername()
try:
stxt = subprocess.check_output(self.STATECMD, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
if "sudo: a password is required" in e.output:
insufficient_priv = True
else:
raise RuntimeError("Error getting pfctl state: " + repr(e))
else:
insufficient_priv = "sudo: a password is required" in stxt
if insufficient_priv:
raise RuntimeError(
"Insufficient privileges to access pfctl. "
"See http://mitmproxy.org/doc/transparent/osx.html for details.")
return pf.lookup(peer[0], peer[1], stxt)
<commit_msg>Include correct documentation URL in error message<commit_after>import subprocess
import pf
"""
Doing this the "right" way by using DIOCNATLOOK on the pf device turns out
to be a pain. Apple has made a number of modifications to the data
structures returned, and compiling userspace tools to test and work with
this turns out to be a pain in the ass. Parsing pfctl output is short,
simple, and works.
Note: Also Tested with FreeBSD 10 pkgng Python 2.7.x.
Should work almost exactly as on Mac OS X and except with some changes to
the output processing of pfctl (see pf.py).
"""
class Resolver(object):
STATECMD = ("sudo", "-n", "/sbin/pfctl", "-s", "state")
def original_addr(self, csock):
peer = csock.getpeername()
try:
stxt = subprocess.check_output(self.STATECMD, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
if "sudo: a password is required" in e.output:
insufficient_priv = True
else:
raise RuntimeError("Error getting pfctl state: " + repr(e))
else:
insufficient_priv = "sudo: a password is required" in stxt
if insufficient_priv:
raise RuntimeError(
"Insufficient privileges to access pfctl. "
"See http://docs.mitmproxy.org/en/latest/transparent/osx.html for details.")
return pf.lookup(peer[0], peer[1], stxt)
|
d500e290f8c1422f74b1d8c8d2bbb8ec9e5529cb
|
misc/singleton.py
|
misc/singleton.py
|
"""
File: singleton.py
Purpose: Defines a class whose subclasses will act like the singleton pattern.
"""
class Singleton(object):
"""
This is a class that implements singleton for its subclasses.
The technique is based on a variant of other techniques found in:
http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python
https://gist.github.com/werediver/4396488
The technique is simply to build a map of classes to their unique instances.
The first time called for some particular
class the class is mapped to the instance. On other class to the same class, the mapped instance is returned.
"""
_instances = {}
@classmethod
def instance(cls):
if cls not in cls._instances:
cls._instances[cls] = cls()
return cls._instances[cls]
|
class Singleton(object):
"""
This is a class that implements singleton for its subclasses.
The technique is based on a variant of other techniques found in:
http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python
https://gist.github.com/werediver/4396488
The technique is simply to build a map of classes to their unique instances.
The first time called for some particular
class the class is mapped to the instance. On other class to the same class, the mapped instance is returned.
Classes that use this must:
1) Add Singleton as a superclass.
2) Have this signature for the constructor: __init__(self, *args, **kwargs)
"""
_instances = {}
@classmethod
def instance(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = cls(*args, **kwargs)
return cls._instances[cls]
|
Add comments to Singleton about usage.
|
Add comments to Singleton about usage.
|
Python
|
mit
|
dpazel/music_rep
|
"""
File: singleton.py
Purpose: Defines a class whose subclasses will act like the singleton pattern.
"""
class Singleton(object):
"""
This is a class that implements singleton for its subclasses.
The technique is based on a variant of other techniques found in:
http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python
https://gist.github.com/werediver/4396488
The technique is simply to build a map of classes to their unique instances.
The first time called for some particular
class the class is mapped to the instance. On other class to the same class, the mapped instance is returned.
"""
_instances = {}
@classmethod
def instance(cls):
if cls not in cls._instances:
cls._instances[cls] = cls()
return cls._instances[cls]
Add comments to Singleton about usage.
|
class Singleton(object):
"""
This is a class that implements singleton for its subclasses.
The technique is based on a variant of other techniques found in:
http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python
https://gist.github.com/werediver/4396488
The technique is simply to build a map of classes to their unique instances.
The first time called for some particular
class the class is mapped to the instance. On other class to the same class, the mapped instance is returned.
Classes that use this must:
1) Add Singleton as a superclass.
2) Have this signature for the constructor: __init__(self, *args, **kwargs)
"""
_instances = {}
@classmethod
def instance(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = cls(*args, **kwargs)
return cls._instances[cls]
|
<commit_before>"""
File: singleton.py
Purpose: Defines a class whose subclasses will act like the singleton pattern.
"""
class Singleton(object):
"""
This is a class that implements singleton for its subclasses.
The technique is based on a variant of other techniques found in:
http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python
https://gist.github.com/werediver/4396488
The technique is simply to build a map of classes to their unique instances.
The first time called for some particular
class the class is mapped to the instance. On other class to the same class, the mapped instance is returned.
"""
_instances = {}
@classmethod
def instance(cls):
if cls not in cls._instances:
cls._instances[cls] = cls()
return cls._instances[cls]
<commit_msg>Add comments to Singleton about usage.<commit_after>
|
class Singleton(object):
"""
This is a class that implements singleton for its subclasses.
The technique is based on a variant of other techniques found in:
http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python
https://gist.github.com/werediver/4396488
The technique is simply to build a map of classes to their unique instances.
The first time called for some particular
class the class is mapped to the instance. On other class to the same class, the mapped instance is returned.
Classes that use this must:
1) Add Singleton as a superclass.
2) Have this signature for the constructor: __init__(self, *args, **kwargs)
"""
_instances = {}
@classmethod
def instance(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = cls(*args, **kwargs)
return cls._instances[cls]
|
"""
File: singleton.py
Purpose: Defines a class whose subclasses will act like the singleton pattern.
"""
class Singleton(object):
"""
This is a class that implements singleton for its subclasses.
The technique is based on a variant of other techniques found in:
http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python
https://gist.github.com/werediver/4396488
The technique is simply to build a map of classes to their unique instances.
The first time called for some particular
class the class is mapped to the instance. On other class to the same class, the mapped instance is returned.
"""
_instances = {}
@classmethod
def instance(cls):
if cls not in cls._instances:
cls._instances[cls] = cls()
return cls._instances[cls]
Add comments to Singleton about usage.
class Singleton(object):
"""
This is a class that implements singleton for its subclasses.
The technique is based on a variant of other techniques found in:
http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python
https://gist.github.com/werediver/4396488
The technique is simply to build a map of classes to their unique instances.
The first time called for some particular
class the class is mapped to the instance. On other class to the same class, the mapped instance is returned.
Classes that use this must:
1) Add Singleton as a superclass.
2) Have this signature for the constructor: __init__(self, *args, **kwargs)
"""
_instances = {}
@classmethod
def instance(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = cls(*args, **kwargs)
return cls._instances[cls]
|
<commit_before>"""
File: singleton.py
Purpose: Defines a class whose subclasses will act like the singleton pattern.
"""
class Singleton(object):
"""
This is a class that implements singleton for its subclasses.
The technique is based on a variant of other techniques found in:
http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python
https://gist.github.com/werediver/4396488
The technique is simply to build a map of classes to their unique instances.
The first time called for some particular
class the class is mapped to the instance. On other class to the same class, the mapped instance is returned.
"""
_instances = {}
@classmethod
def instance(cls):
if cls not in cls._instances:
cls._instances[cls] = cls()
return cls._instances[cls]
<commit_msg>Add comments to Singleton about usage.<commit_after>
class Singleton(object):
"""
This is a class that implements singleton for its subclasses.
The technique is based on a variant of other techniques found in:
http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python
https://gist.github.com/werediver/4396488
The technique is simply to build a map of classes to their unique instances.
The first time called for some particular
class the class is mapped to the instance. On other class to the same class, the mapped instance is returned.
Classes that use this must:
1) Add Singleton as a superclass.
2) Have this signature for the constructor: __init__(self, *args, **kwargs)
"""
_instances = {}
@classmethod
def instance(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = cls(*args, **kwargs)
return cls._instances[cls]
|
6b04211b42e76f6428fbaac361059fad4bef70de
|
txircd/modules/conn_join.py
|
txircd/modules/conn_join.py
|
from txircd.channel import IRCChannel
from txircd.modbase import Module
class Autojoin(Module):
def joinOnConnect(self, user):
if "client_join_on_connect" in self.ircd.servconfig:
for channel in self.ircd.servconfig["client_join_on_connect"]:
user.join(self.ircd.channels[channel] if channel in self.ircd.channels else IRCChannel(self.ircd, channel))
class Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
self.conn_join = None
def spawn(self):
self.conn_join = Autojoin().hook(self.ircd)
return {
"actions": {
"register": self.conn_join.joinOnConnect
}
}
def cleanup(self):
self.ircd.actions["register"].remove(self.conn_join.joinOnConnect)
|
from txircd.channel import IRCChannel
from txircd.modbase import Module
class Autojoin(Module):
def joinOnConnect(self, user):
if "client_join_on_connect" in self.ircd.servconfig:
for channel in self.ircd.servconfig["client_join_on_connect"]:
user.join(self.ircd.channels[channel] if channel in self.ircd.channels else IRCChannel(self.ircd, channel))
return True
class Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
self.conn_join = None
def spawn(self):
self.conn_join = Autojoin().hook(self.ircd)
return {
"actions": {
"register": [self.conn_join.joinOnConnect]
}
}
def cleanup(self):
self.ircd.actions["register"].remove(self.conn_join.joinOnConnect)
|
Fix once again nobody being allowed to connect
|
Fix once again nobody being allowed to connect
|
Python
|
bsd-3-clause
|
Heufneutje/txircd,DesertBus/txircd,ElementalAlchemist/txircd
|
from txircd.channel import IRCChannel
from txircd.modbase import Module
class Autojoin(Module):
def joinOnConnect(self, user):
if "client_join_on_connect" in self.ircd.servconfig:
for channel in self.ircd.servconfig["client_join_on_connect"]:
user.join(self.ircd.channels[channel] if channel in self.ircd.channels else IRCChannel(self.ircd, channel))
class Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
self.conn_join = None
def spawn(self):
self.conn_join = Autojoin().hook(self.ircd)
return {
"actions": {
"register": self.conn_join.joinOnConnect
}
}
def cleanup(self):
self.ircd.actions["register"].remove(self.conn_join.joinOnConnect)Fix once again nobody being allowed to connect
|
from txircd.channel import IRCChannel
from txircd.modbase import Module
class Autojoin(Module):
def joinOnConnect(self, user):
if "client_join_on_connect" in self.ircd.servconfig:
for channel in self.ircd.servconfig["client_join_on_connect"]:
user.join(self.ircd.channels[channel] if channel in self.ircd.channels else IRCChannel(self.ircd, channel))
return True
class Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
self.conn_join = None
def spawn(self):
self.conn_join = Autojoin().hook(self.ircd)
return {
"actions": {
"register": [self.conn_join.joinOnConnect]
}
}
def cleanup(self):
self.ircd.actions["register"].remove(self.conn_join.joinOnConnect)
|
<commit_before>from txircd.channel import IRCChannel
from txircd.modbase import Module
class Autojoin(Module):
def joinOnConnect(self, user):
if "client_join_on_connect" in self.ircd.servconfig:
for channel in self.ircd.servconfig["client_join_on_connect"]:
user.join(self.ircd.channels[channel] if channel in self.ircd.channels else IRCChannel(self.ircd, channel))
class Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
self.conn_join = None
def spawn(self):
self.conn_join = Autojoin().hook(self.ircd)
return {
"actions": {
"register": self.conn_join.joinOnConnect
}
}
def cleanup(self):
self.ircd.actions["register"].remove(self.conn_join.joinOnConnect)<commit_msg>Fix once again nobody being allowed to connect<commit_after>
|
from txircd.channel import IRCChannel
from txircd.modbase import Module
class Autojoin(Module):
def joinOnConnect(self, user):
if "client_join_on_connect" in self.ircd.servconfig:
for channel in self.ircd.servconfig["client_join_on_connect"]:
user.join(self.ircd.channels[channel] if channel in self.ircd.channels else IRCChannel(self.ircd, channel))
return True
class Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
self.conn_join = None
def spawn(self):
self.conn_join = Autojoin().hook(self.ircd)
return {
"actions": {
"register": [self.conn_join.joinOnConnect]
}
}
def cleanup(self):
self.ircd.actions["register"].remove(self.conn_join.joinOnConnect)
|
from txircd.channel import IRCChannel
from txircd.modbase import Module
class Autojoin(Module):
def joinOnConnect(self, user):
if "client_join_on_connect" in self.ircd.servconfig:
for channel in self.ircd.servconfig["client_join_on_connect"]:
user.join(self.ircd.channels[channel] if channel in self.ircd.channels else IRCChannel(self.ircd, channel))
class Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
self.conn_join = None
def spawn(self):
self.conn_join = Autojoin().hook(self.ircd)
return {
"actions": {
"register": self.conn_join.joinOnConnect
}
}
def cleanup(self):
self.ircd.actions["register"].remove(self.conn_join.joinOnConnect)Fix once again nobody being allowed to connectfrom txircd.channel import IRCChannel
from txircd.modbase import Module
class Autojoin(Module):
def joinOnConnect(self, user):
if "client_join_on_connect" in self.ircd.servconfig:
for channel in self.ircd.servconfig["client_join_on_connect"]:
user.join(self.ircd.channels[channel] if channel in self.ircd.channels else IRCChannel(self.ircd, channel))
return True
class Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
self.conn_join = None
def spawn(self):
self.conn_join = Autojoin().hook(self.ircd)
return {
"actions": {
"register": [self.conn_join.joinOnConnect]
}
}
def cleanup(self):
self.ircd.actions["register"].remove(self.conn_join.joinOnConnect)
|
<commit_before>from txircd.channel import IRCChannel
from txircd.modbase import Module
class Autojoin(Module):
def joinOnConnect(self, user):
if "client_join_on_connect" in self.ircd.servconfig:
for channel in self.ircd.servconfig["client_join_on_connect"]:
user.join(self.ircd.channels[channel] if channel in self.ircd.channels else IRCChannel(self.ircd, channel))
class Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
self.conn_join = None
def spawn(self):
self.conn_join = Autojoin().hook(self.ircd)
return {
"actions": {
"register": self.conn_join.joinOnConnect
}
}
def cleanup(self):
self.ircd.actions["register"].remove(self.conn_join.joinOnConnect)<commit_msg>Fix once again nobody being allowed to connect<commit_after>from txircd.channel import IRCChannel
from txircd.modbase import Module
class Autojoin(Module):
def joinOnConnect(self, user):
if "client_join_on_connect" in self.ircd.servconfig:
for channel in self.ircd.servconfig["client_join_on_connect"]:
user.join(self.ircd.channels[channel] if channel in self.ircd.channels else IRCChannel(self.ircd, channel))
return True
class Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
self.conn_join = None
def spawn(self):
self.conn_join = Autojoin().hook(self.ircd)
return {
"actions": {
"register": [self.conn_join.joinOnConnect]
}
}
def cleanup(self):
self.ircd.actions["register"].remove(self.conn_join.joinOnConnect)
|
dcf0e140303259f7b3df2609281b635dbcd4806f
|
knapsack.py
|
knapsack.py
|
# Knapsack 0-1 function wieights, values and size n.
from pyspark.sql import Row
from pyspark.sql.functions import lit
from pyspark.sql.functions import col
# Greedy implementation of 0-1 Knapsack algorithm.
def knapsack(knapsackDF, W):
ratioDF = knapsackDF.withColumn("ratio", lit(knapsackDF.values / knapsackDF.weights))
ratioDF.sort(col("ratio").desc())
partialSumsDF = (ratioDF
.map(lambda x: x)
)
return partialSumsDF
knapsackData = [('thing1', 1, 2), ('thing2', 2, 3), ('thing3', 4, 5)]
knapsackData = sqlContext.createDataFrame(knapsackData, ['item', 'weights', 'values'])
k = knapsack(knapsackData, 5)
print k.take(3)
|
# Knapsack 0-1 function wieights, values and size n.
import sys
import pyspark.sql.functions as func
from pyspark.sql.window import Window
from pyspark.sql import Row
from pyspark.sql.functions import lit
from pyspark.sql.functions import col
# Greedy implementation of 0-1 Knapsack algorithm.
def knapsack(knapsackDF, W):
ratioDF = knapsackDF.withColumn("ratio", lit(knapsackDF.values / knapsackDF.weights))
ratioDF.sort(col("ratio").desc())
partialSumsDF = (ratioDF
.map(lambda x: x)
)
return partialSumsDF
knapsackData = [('thing1', 1, 2), ('thing2', 2, 3), ('thing3', 4, 5)]
knapsackData = sqlContext.createDataFrame(knapsackData, ['item', 'weights', 'values'])
k = knapsack(knapsackData, 5)
print k.take(3)
|
Add Window functions to attempt partial sum
|
Add Window functions to attempt partial sum
|
Python
|
apache-2.0
|
drulm/Spark_Knapsack,drulm/Spark_Knapsack
|
# Knapsack 0-1 function wieights, values and size n.
from pyspark.sql import Row
from pyspark.sql.functions import lit
from pyspark.sql.functions import col
# Greedy implementation of 0-1 Knapsack algorithm.
def knapsack(knapsackDF, W):
ratioDF = knapsackDF.withColumn("ratio", lit(knapsackDF.values / knapsackDF.weights))
ratioDF.sort(col("ratio").desc())
partialSumsDF = (ratioDF
.map(lambda x: x)
)
return partialSumsDF
knapsackData = [('thing1', 1, 2), ('thing2', 2, 3), ('thing3', 4, 5)]
knapsackData = sqlContext.createDataFrame(knapsackData, ['item', 'weights', 'values'])
k = knapsack(knapsackData, 5)
print k.take(3)
Add Window functions to attempt partial sum
|
# Knapsack 0-1 function wieights, values and size n.
import sys
import pyspark.sql.functions as func
from pyspark.sql.window import Window
from pyspark.sql import Row
from pyspark.sql.functions import lit
from pyspark.sql.functions import col
# Greedy implementation of 0-1 Knapsack algorithm.
def knapsack(knapsackDF, W):
ratioDF = knapsackDF.withColumn("ratio", lit(knapsackDF.values / knapsackDF.weights))
ratioDF.sort(col("ratio").desc())
partialSumsDF = (ratioDF
.map(lambda x: x)
)
return partialSumsDF
knapsackData = [('thing1', 1, 2), ('thing2', 2, 3), ('thing3', 4, 5)]
knapsackData = sqlContext.createDataFrame(knapsackData, ['item', 'weights', 'values'])
k = knapsack(knapsackData, 5)
print k.take(3)
|
<commit_before>
# Knapsack 0-1 function wieights, values and size n.
from pyspark.sql import Row
from pyspark.sql.functions import lit
from pyspark.sql.functions import col
# Greedy implementation of 0-1 Knapsack algorithm.
def knapsack(knapsackDF, W):
ratioDF = knapsackDF.withColumn("ratio", lit(knapsackDF.values / knapsackDF.weights))
ratioDF.sort(col("ratio").desc())
partialSumsDF = (ratioDF
.map(lambda x: x)
)
return partialSumsDF
knapsackData = [('thing1', 1, 2), ('thing2', 2, 3), ('thing3', 4, 5)]
knapsackData = sqlContext.createDataFrame(knapsackData, ['item', 'weights', 'values'])
k = knapsack(knapsackData, 5)
print k.take(3)
<commit_msg>Add Window functions to attempt partial sum<commit_after>
|
# Knapsack 0-1 function wieights, values and size n.
import sys
import pyspark.sql.functions as func
from pyspark.sql.window import Window
from pyspark.sql import Row
from pyspark.sql.functions import lit
from pyspark.sql.functions import col
# Greedy implementation of 0-1 Knapsack algorithm.
def knapsack(knapsackDF, W):
ratioDF = knapsackDF.withColumn("ratio", lit(knapsackDF.values / knapsackDF.weights))
ratioDF.sort(col("ratio").desc())
partialSumsDF = (ratioDF
.map(lambda x: x)
)
return partialSumsDF
knapsackData = [('thing1', 1, 2), ('thing2', 2, 3), ('thing3', 4, 5)]
knapsackData = sqlContext.createDataFrame(knapsackData, ['item', 'weights', 'values'])
k = knapsack(knapsackData, 5)
print k.take(3)
|
# Knapsack 0-1 function wieights, values and size n.
from pyspark.sql import Row
from pyspark.sql.functions import lit
from pyspark.sql.functions import col
# Greedy implementation of 0-1 Knapsack algorithm.
def knapsack(knapsackDF, W):
ratioDF = knapsackDF.withColumn("ratio", lit(knapsackDF.values / knapsackDF.weights))
ratioDF.sort(col("ratio").desc())
partialSumsDF = (ratioDF
.map(lambda x: x)
)
return partialSumsDF
knapsackData = [('thing1', 1, 2), ('thing2', 2, 3), ('thing3', 4, 5)]
knapsackData = sqlContext.createDataFrame(knapsackData, ['item', 'weights', 'values'])
k = knapsack(knapsackData, 5)
print k.take(3)
Add Window functions to attempt partial sum
# Knapsack 0-1 function wieights, values and size n.
import sys
import pyspark.sql.functions as func
from pyspark.sql.window import Window
from pyspark.sql import Row
from pyspark.sql.functions import lit
from pyspark.sql.functions import col
# Greedy implementation of 0-1 Knapsack algorithm.
def knapsack(knapsackDF, W):
ratioDF = knapsackDF.withColumn("ratio", lit(knapsackDF.values / knapsackDF.weights))
ratioDF.sort(col("ratio").desc())
partialSumsDF = (ratioDF
.map(lambda x: x)
)
return partialSumsDF
knapsackData = [('thing1', 1, 2), ('thing2', 2, 3), ('thing3', 4, 5)]
knapsackData = sqlContext.createDataFrame(knapsackData, ['item', 'weights', 'values'])
k = knapsack(knapsackData, 5)
print k.take(3)
|
<commit_before>
# Knapsack 0-1 function wieights, values and size n.
from pyspark.sql import Row
from pyspark.sql.functions import lit
from pyspark.sql.functions import col
# Greedy implementation of 0-1 Knapsack algorithm.
def knapsack(knapsackDF, W):
ratioDF = knapsackDF.withColumn("ratio", lit(knapsackDF.values / knapsackDF.weights))
ratioDF.sort(col("ratio").desc())
partialSumsDF = (ratioDF
.map(lambda x: x)
)
return partialSumsDF
knapsackData = [('thing1', 1, 2), ('thing2', 2, 3), ('thing3', 4, 5)]
knapsackData = sqlContext.createDataFrame(knapsackData, ['item', 'weights', 'values'])
k = knapsack(knapsackData, 5)
print k.take(3)
<commit_msg>Add Window functions to attempt partial sum<commit_after>
# Knapsack 0-1 function wieights, values and size n.
import sys
import pyspark.sql.functions as func
from pyspark.sql.window import Window
from pyspark.sql import Row
from pyspark.sql.functions import lit
from pyspark.sql.functions import col
# Greedy implementation of 0-1 Knapsack algorithm.
def knapsack(knapsackDF, W):
ratioDF = knapsackDF.withColumn("ratio", lit(knapsackDF.values / knapsackDF.weights))
ratioDF.sort(col("ratio").desc())
partialSumsDF = (ratioDF
.map(lambda x: x)
)
return partialSumsDF
knapsackData = [('thing1', 1, 2), ('thing2', 2, 3), ('thing3', 4, 5)]
knapsackData = sqlContext.createDataFrame(knapsackData, ['item', 'weights', 'values'])
k = knapsack(knapsackData, 5)
print k.take(3)
|
f0166ba101c131b5331e141128fc65e71c753015
|
flocker/common/__init__.py
|
flocker/common/__init__.py
|
# Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Shared flocker components.
"""
__all__ = [
'INode', 'FakeNode', 'ProcessNode', 'gather_deferreds',
'auto_threaded', 'auto_openstack_logging',
'get_all_ips',
]
import platform
from ._ipc import INode, FakeNode, ProcessNode
from ._defer import gather_deferreds
from ._thread import auto_threaded
from ._net import get_all_ips
if platform.system() == 'Linux':
# For some reason I don't understand, keystoneclient has problems on OS X.
# Fortunately, we don't need keystoneclient on OS X.
from ._openstack import auto_openstack_logging
|
# Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Shared flocker components.
"""
__all__ = [
'INode', 'FakeNode', 'ProcessNode', 'gather_deferreds',
'auto_threaded', 'auto_openstack_logging',
'get_all_ips', 'ipaddress_from_string',
]
import platform
from ._ipc import INode, FakeNode, ProcessNode
from ._defer import gather_deferreds
from ._thread import auto_threaded
from ._net import get_all_ips, ipaddress_from_string
if platform.system() == 'Linux':
# For some reason I don't understand, keystoneclient has problems on OS X.
# Fortunately, we don't need keystoneclient on OS X.
from ._openstack import auto_openstack_logging
|
Make the new helper function public
|
Make the new helper function public
|
Python
|
apache-2.0
|
Azulinho/flocker,1d4Nf6/flocker,hackday-profilers/flocker,wallnerryan/flocker-profiles,mbrukman/flocker,adamtheturtle/flocker,1d4Nf6/flocker,AndyHuu/flocker,jml/flocker,wallnerryan/flocker-profiles,achanda/flocker,agonzalezro/flocker,AndyHuu/flocker,adamtheturtle/flocker,runcom/flocker,achanda/flocker,runcom/flocker,agonzalezro/flocker,lukemarsden/flocker,1d4Nf6/flocker,jml/flocker,wallnerryan/flocker-profiles,runcom/flocker,w4ngyi/flocker,mbrukman/flocker,achanda/flocker,hackday-profilers/flocker,lukemarsden/flocker,LaynePeng/flocker,moypray/flocker,jml/flocker,adamtheturtle/flocker,hackday-profilers/flocker,agonzalezro/flocker,w4ngyi/flocker,w4ngyi/flocker,LaynePeng/flocker,moypray/flocker,mbrukman/flocker,lukemarsden/flocker,LaynePeng/flocker,Azulinho/flocker,moypray/flocker,Azulinho/flocker,AndyHuu/flocker
|
# Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Shared flocker components.
"""
__all__ = [
'INode', 'FakeNode', 'ProcessNode', 'gather_deferreds',
'auto_threaded', 'auto_openstack_logging',
'get_all_ips',
]
import platform
from ._ipc import INode, FakeNode, ProcessNode
from ._defer import gather_deferreds
from ._thread import auto_threaded
from ._net import get_all_ips
if platform.system() == 'Linux':
# For some reason I don't understand, keystoneclient has problems on OS X.
# Fortunately, we don't need keystoneclient on OS X.
from ._openstack import auto_openstack_logging
Make the new helper function public
|
# Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Shared flocker components.
"""
__all__ = [
'INode', 'FakeNode', 'ProcessNode', 'gather_deferreds',
'auto_threaded', 'auto_openstack_logging',
'get_all_ips', 'ipaddress_from_string',
]
import platform
from ._ipc import INode, FakeNode, ProcessNode
from ._defer import gather_deferreds
from ._thread import auto_threaded
from ._net import get_all_ips, ipaddress_from_string
if platform.system() == 'Linux':
# For some reason I don't understand, keystoneclient has problems on OS X.
# Fortunately, we don't need keystoneclient on OS X.
from ._openstack import auto_openstack_logging
|
<commit_before># Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Shared flocker components.
"""
__all__ = [
'INode', 'FakeNode', 'ProcessNode', 'gather_deferreds',
'auto_threaded', 'auto_openstack_logging',
'get_all_ips',
]
import platform
from ._ipc import INode, FakeNode, ProcessNode
from ._defer import gather_deferreds
from ._thread import auto_threaded
from ._net import get_all_ips
if platform.system() == 'Linux':
# For some reason I don't understand, keystoneclient has problems on OS X.
# Fortunately, we don't need keystoneclient on OS X.
from ._openstack import auto_openstack_logging
<commit_msg>Make the new helper function public<commit_after>
|
# Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Shared flocker components.
"""
__all__ = [
'INode', 'FakeNode', 'ProcessNode', 'gather_deferreds',
'auto_threaded', 'auto_openstack_logging',
'get_all_ips', 'ipaddress_from_string',
]
import platform
from ._ipc import INode, FakeNode, ProcessNode
from ._defer import gather_deferreds
from ._thread import auto_threaded
from ._net import get_all_ips, ipaddress_from_string
if platform.system() == 'Linux':
# For some reason I don't understand, keystoneclient has problems on OS X.
# Fortunately, we don't need keystoneclient on OS X.
from ._openstack import auto_openstack_logging
|
# Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Shared flocker components.
"""
__all__ = [
'INode', 'FakeNode', 'ProcessNode', 'gather_deferreds',
'auto_threaded', 'auto_openstack_logging',
'get_all_ips',
]
import platform
from ._ipc import INode, FakeNode, ProcessNode
from ._defer import gather_deferreds
from ._thread import auto_threaded
from ._net import get_all_ips
if platform.system() == 'Linux':
# For some reason I don't understand, keystoneclient has problems on OS X.
# Fortunately, we don't need keystoneclient on OS X.
from ._openstack import auto_openstack_logging
Make the new helper function public# Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Shared flocker components.
"""
__all__ = [
'INode', 'FakeNode', 'ProcessNode', 'gather_deferreds',
'auto_threaded', 'auto_openstack_logging',
'get_all_ips', 'ipaddress_from_string',
]
import platform
from ._ipc import INode, FakeNode, ProcessNode
from ._defer import gather_deferreds
from ._thread import auto_threaded
from ._net import get_all_ips, ipaddress_from_string
if platform.system() == 'Linux':
# For some reason I don't understand, keystoneclient has problems on OS X.
# Fortunately, we don't need keystoneclient on OS X.
from ._openstack import auto_openstack_logging
|
<commit_before># Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Shared flocker components.
"""
__all__ = [
'INode', 'FakeNode', 'ProcessNode', 'gather_deferreds',
'auto_threaded', 'auto_openstack_logging',
'get_all_ips',
]
import platform
from ._ipc import INode, FakeNode, ProcessNode
from ._defer import gather_deferreds
from ._thread import auto_threaded
from ._net import get_all_ips
if platform.system() == 'Linux':
# For some reason I don't understand, keystoneclient has problems on OS X.
# Fortunately, we don't need keystoneclient on OS X.
from ._openstack import auto_openstack_logging
<commit_msg>Make the new helper function public<commit_after># Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Shared flocker components.
"""
__all__ = [
'INode', 'FakeNode', 'ProcessNode', 'gather_deferreds',
'auto_threaded', 'auto_openstack_logging',
'get_all_ips', 'ipaddress_from_string',
]
import platform
from ._ipc import INode, FakeNode, ProcessNode
from ._defer import gather_deferreds
from ._thread import auto_threaded
from ._net import get_all_ips, ipaddress_from_string
if platform.system() == 'Linux':
# For some reason I don't understand, keystoneclient has problems on OS X.
# Fortunately, we don't need keystoneclient on OS X.
from ._openstack import auto_openstack_logging
|
f30a560db83d8a7ac87685c69f5b519faaa929fa
|
project_issue_department/__openerp__.py
|
project_issue_department/__openerp__.py
|
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2012 Daniel Reis
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': 'Project Issue with Department',
'version': '1.1',
"category": "Project Management",
'description': """\
Add Department field to Project Issues.
Selecting a Project for an issue will automatically populate this with the
Project's defined Department.
""",
'author': 'Daniel Reis',
'website': 'daniel.reis@securitas.pt',
'depends': [
'project_issue',
'project_department',
],
'update_xml': [
'project_issue_view.xml',
'security/ir.model.access.csv',
],
'installable': True,
'application': False,
'auto_install': True,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2012 Daniel Reis
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': 'Project Issue with Department',
'version': '1.1',
"category": "Project Management",
'description': """\
Add Department field to Project Issues.
Selecting a Project for an issue will automatically populate this with the
Project's defined Department.
""",
'author': 'Daniel Reis',
'website': 'daniel.reis@securitas.pt',
'depends': [
'project_issue',
'project_department',
],
'update_xml': [
'project_issue_view.xml',
'security/ir.model.access.csv',
],
'installable': True,
'application': False,
'auto_install': True,
}
|
Fix pep8 to pass super checks
|
Fix pep8 to pass super checks
|
Python
|
agpl-3.0
|
OCA/department,Antiun/department,acsone/department,kmee/department,Endika/department
|
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2012 Daniel Reis
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': 'Project Issue with Department',
'version': '1.1',
"category": "Project Management",
'description': """\
Add Department field to Project Issues.
Selecting a Project for an issue will automatically populate this with the
Project's defined Department.
""",
'author': 'Daniel Reis',
'website': 'daniel.reis@securitas.pt',
'depends': [
'project_issue',
'project_department',
],
'update_xml': [
'project_issue_view.xml',
'security/ir.model.access.csv',
],
'installable': True,
'application': False,
'auto_install': True,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
Fix pep8 to pass super checks
|
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2012 Daniel Reis
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': 'Project Issue with Department',
'version': '1.1',
"category": "Project Management",
'description': """\
Add Department field to Project Issues.
Selecting a Project for an issue will automatically populate this with the
Project's defined Department.
""",
'author': 'Daniel Reis',
'website': 'daniel.reis@securitas.pt',
'depends': [
'project_issue',
'project_department',
],
'update_xml': [
'project_issue_view.xml',
'security/ir.model.access.csv',
],
'installable': True,
'application': False,
'auto_install': True,
}
|
<commit_before># -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2012 Daniel Reis
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': 'Project Issue with Department',
'version': '1.1',
"category": "Project Management",
'description': """\
Add Department field to Project Issues.
Selecting a Project for an issue will automatically populate this with the
Project's defined Department.
""",
'author': 'Daniel Reis',
'website': 'daniel.reis@securitas.pt',
'depends': [
'project_issue',
'project_department',
],
'update_xml': [
'project_issue_view.xml',
'security/ir.model.access.csv',
],
'installable': True,
'application': False,
'auto_install': True,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
<commit_msg>Fix pep8 to pass super checks<commit_after>
|
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2012 Daniel Reis
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': 'Project Issue with Department',
'version': '1.1',
"category": "Project Management",
'description': """\
Add Department field to Project Issues.
Selecting a Project for an issue will automatically populate this with the
Project's defined Department.
""",
'author': 'Daniel Reis',
'website': 'daniel.reis@securitas.pt',
'depends': [
'project_issue',
'project_department',
],
'update_xml': [
'project_issue_view.xml',
'security/ir.model.access.csv',
],
'installable': True,
'application': False,
'auto_install': True,
}
|
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2012 Daniel Reis
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': 'Project Issue with Department',
'version': '1.1',
"category": "Project Management",
'description': """\
Add Department field to Project Issues.
Selecting a Project for an issue will automatically populate this with the
Project's defined Department.
""",
'author': 'Daniel Reis',
'website': 'daniel.reis@securitas.pt',
'depends': [
'project_issue',
'project_department',
],
'update_xml': [
'project_issue_view.xml',
'security/ir.model.access.csv',
],
'installable': True,
'application': False,
'auto_install': True,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
Fix pep8 to pass super checks# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2012 Daniel Reis
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': 'Project Issue with Department',
'version': '1.1',
"category": "Project Management",
'description': """\
Add Department field to Project Issues.
Selecting a Project for an issue will automatically populate this with the
Project's defined Department.
""",
'author': 'Daniel Reis',
'website': 'daniel.reis@securitas.pt',
'depends': [
'project_issue',
'project_department',
],
'update_xml': [
'project_issue_view.xml',
'security/ir.model.access.csv',
],
'installable': True,
'application': False,
'auto_install': True,
}
|
<commit_before># -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2012 Daniel Reis
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': 'Project Issue with Department',
'version': '1.1',
"category": "Project Management",
'description': """\
Add Department field to Project Issues.
Selecting a Project for an issue will automatically populate this with the
Project's defined Department.
""",
'author': 'Daniel Reis',
'website': 'daniel.reis@securitas.pt',
'depends': [
'project_issue',
'project_department',
],
'update_xml': [
'project_issue_view.xml',
'security/ir.model.access.csv',
],
'installable': True,
'application': False,
'auto_install': True,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
<commit_msg>Fix pep8 to pass super checks<commit_after># -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2012 Daniel Reis
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': 'Project Issue with Department',
'version': '1.1',
"category": "Project Management",
'description': """\
Add Department field to Project Issues.
Selecting a Project for an issue will automatically populate this with the
Project's defined Department.
""",
'author': 'Daniel Reis',
'website': 'daniel.reis@securitas.pt',
'depends': [
'project_issue',
'project_department',
],
'update_xml': [
'project_issue_view.xml',
'security/ir.model.access.csv',
],
'installable': True,
'application': False,
'auto_install': True,
}
|
8ecc9c870fdc156d4fbe24717ab77990a50da010
|
welltie.py
|
welltie.py
|
from flask import Flask, render_template
from synth.synth import generate_reflectivity, plot_logs
from StringIO import StringIO
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/plot')
def plot():
buffer = StringIO()
t, RC_t = generate_reflectivity()
start_z = 2300
end_z = 2600
start_t = 1.4
end_t = 2.5
plot_logs(buffer, 'png', t, RC_t, RC_t, start_t, end_t, title='synthetic')
return buffer.getvalue()
if __name__ == '__main__':
app.run(debug=True)
|
from flask import Flask, render_template, make_response
from synth.synth import generate_reflectivity, plot_logs
from StringIO import StringIO
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/plot')
def plot():
t, RC_t = generate_reflectivity()
start_z = 2300
end_z = 2600
start_t = 1.4
end_t = 2.5
buffer = StringIO()
plot_logs(buffer, 'png', t, RC_t, RC_t, start_t, end_t, title='reflectiviy')
response = make_response(buffer.getvalue())
response.headers['Content-Type'] ='image/png'
return response
if __name__ == '__main__':
app.run(debug=True)
|
Correct content type (png image) is now reported for the url /plot
|
Correct content type (png image) is now reported for the url /plot
|
Python
|
mit
|
MrHiccups/open-well-ties,MrHiccups/open-well-ties,MrHiccups/open-well-ties
|
from flask import Flask, render_template
from synth.synth import generate_reflectivity, plot_logs
from StringIO import StringIO
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/plot')
def plot():
buffer = StringIO()
t, RC_t = generate_reflectivity()
start_z = 2300
end_z = 2600
start_t = 1.4
end_t = 2.5
plot_logs(buffer, 'png', t, RC_t, RC_t, start_t, end_t, title='synthetic')
return buffer.getvalue()
if __name__ == '__main__':
app.run(debug=True)
Correct content type (png image) is now reported for the url /plot
|
from flask import Flask, render_template, make_response
from synth.synth import generate_reflectivity, plot_logs
from StringIO import StringIO
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/plot')
def plot():
t, RC_t = generate_reflectivity()
start_z = 2300
end_z = 2600
start_t = 1.4
end_t = 2.5
buffer = StringIO()
plot_logs(buffer, 'png', t, RC_t, RC_t, start_t, end_t, title='reflectiviy')
response = make_response(buffer.getvalue())
response.headers['Content-Type'] ='image/png'
return response
if __name__ == '__main__':
app.run(debug=True)
|
<commit_before>from flask import Flask, render_template
from synth.synth import generate_reflectivity, plot_logs
from StringIO import StringIO
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/plot')
def plot():
buffer = StringIO()
t, RC_t = generate_reflectivity()
start_z = 2300
end_z = 2600
start_t = 1.4
end_t = 2.5
plot_logs(buffer, 'png', t, RC_t, RC_t, start_t, end_t, title='synthetic')
return buffer.getvalue()
if __name__ == '__main__':
app.run(debug=True)
<commit_msg>Correct content type (png image) is now reported for the url /plot<commit_after>
|
from flask import Flask, render_template, make_response
from synth.synth import generate_reflectivity, plot_logs
from StringIO import StringIO
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/plot')
def plot():
t, RC_t = generate_reflectivity()
start_z = 2300
end_z = 2600
start_t = 1.4
end_t = 2.5
buffer = StringIO()
plot_logs(buffer, 'png', t, RC_t, RC_t, start_t, end_t, title='reflectiviy')
response = make_response(buffer.getvalue())
response.headers['Content-Type'] ='image/png'
return response
if __name__ == '__main__':
app.run(debug=True)
|
from flask import Flask, render_template
from synth.synth import generate_reflectivity, plot_logs
from StringIO import StringIO
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/plot')
def plot():
buffer = StringIO()
t, RC_t = generate_reflectivity()
start_z = 2300
end_z = 2600
start_t = 1.4
end_t = 2.5
plot_logs(buffer, 'png', t, RC_t, RC_t, start_t, end_t, title='synthetic')
return buffer.getvalue()
if __name__ == '__main__':
app.run(debug=True)
Correct content type (png image) is now reported for the url /plotfrom flask import Flask, render_template, make_response
from synth.synth import generate_reflectivity, plot_logs
from StringIO import StringIO
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/plot')
def plot():
t, RC_t = generate_reflectivity()
start_z = 2300
end_z = 2600
start_t = 1.4
end_t = 2.5
buffer = StringIO()
plot_logs(buffer, 'png', t, RC_t, RC_t, start_t, end_t, title='reflectiviy')
response = make_response(buffer.getvalue())
response.headers['Content-Type'] ='image/png'
return response
if __name__ == '__main__':
app.run(debug=True)
|
<commit_before>from flask import Flask, render_template
from synth.synth import generate_reflectivity, plot_logs
from StringIO import StringIO
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/plot')
def plot():
buffer = StringIO()
t, RC_t = generate_reflectivity()
start_z = 2300
end_z = 2600
start_t = 1.4
end_t = 2.5
plot_logs(buffer, 'png', t, RC_t, RC_t, start_t, end_t, title='synthetic')
return buffer.getvalue()
if __name__ == '__main__':
app.run(debug=True)
<commit_msg>Correct content type (png image) is now reported for the url /plot<commit_after>from flask import Flask, render_template, make_response
from synth.synth import generate_reflectivity, plot_logs
from StringIO import StringIO
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/plot')
def plot():
t, RC_t = generate_reflectivity()
start_z = 2300
end_z = 2600
start_t = 1.4
end_t = 2.5
buffer = StringIO()
plot_logs(buffer, 'png', t, RC_t, RC_t, start_t, end_t, title='reflectiviy')
response = make_response(buffer.getvalue())
response.headers['Content-Type'] ='image/png'
return response
if __name__ == '__main__':
app.run(debug=True)
|
d851aae653ce87aed9b9f6ac3cf7f5312672a08c
|
radmin/templatetags/radmin_extras.py
|
radmin/templatetags/radmin_extras.py
|
from django import template
import json
from django.conf import settings
register = template.Library()
@register.simple_tag(takes_context=True)
def get_admin_context(context):
ctx = {'location':None, 'param1':None, 'param2':None, 'static':settings.STATIC_URL}
try:
context['app_list']
if len(context['app_list']) > 1:
# we are at /admin/
ctx['location'] = 'admin_index'
return json.dumps(ctx)
elif len(context['app_list']) == 1:
#We are at the app index eg: /admin/app/
ctx['location'] = 'app_index'
ctx['param1'] = context['app_list'][0]['name'].lower()
return json.dumps(ctx)
except KeyError:
pass
try:
# we are in the list view of the model eg: admin/app/model/
ctx['location']= 'model_list'
module_name = context['module_name'].lower()
# django adds an 's' to every model name in this view, so we are gonna
ctx['param1'] = module_name
return json.dumps(ctx)
except KeyError:
pass
try:
# editing a model
ctx['location']= 'model_edit'
ctx['param1'] = context['original'].__class__.__name__.lower()
ctx['param2'] = context['original'].pk
return json.dumps(ctx)
except KeyError:
pass
return json.dumps(ctx)
|
from django import template
import json
from django.conf import settings
register = template.Library()
@register.simple_tag(takes_context=True)
def get_admin_context(context):
ctx = {'location':None, 'param1':None, 'param2':None, 'static':settings.STATIC_URL}
try:
context['app_list']
if len(context['app_list']) > 1:
# we are at /admin/
ctx['location'] = 'admin_index'
return json.dumps(ctx)
elif len(context['app_list']) == 1:
#We are at the app index eg: /admin/app/
ctx['location'] = 'app_index'
ctx['param1'] = context['app_list'][0]['name'].lower()
return json.dumps(ctx)
except KeyError:
pass
try:
# we are in the list view of the model eg: admin/app/model/
ctx['location']= 'model_list'
module_name = context['module_name'].lower()
# django adds an 's' to every model name in this view, so we are gonna
ctx['param1'] = module_name
return json.dumps(ctx)
except KeyError:
pass
try:
# editing a model
ctx['location']= 'model_edit'
if context['original'] is not None:
ctx['param1'] = context['original'].__class__.__name__.lower()
ctx['param2'] = context['original'].pk
return json.dumps(ctx)
except KeyError:
pass
return json.dumps(ctx)
|
Check if original object is None
|
Check if original object is None
|
Python
|
bsd-2-clause
|
mick-t/django-radmin-console,mick-t/django-radmin-console,mick-t/django-radmin-console
|
from django import template
import json
from django.conf import settings
register = template.Library()
@register.simple_tag(takes_context=True)
def get_admin_context(context):
ctx = {'location':None, 'param1':None, 'param2':None, 'static':settings.STATIC_URL}
try:
context['app_list']
if len(context['app_list']) > 1:
# we are at /admin/
ctx['location'] = 'admin_index'
return json.dumps(ctx)
elif len(context['app_list']) == 1:
#We are at the app index eg: /admin/app/
ctx['location'] = 'app_index'
ctx['param1'] = context['app_list'][0]['name'].lower()
return json.dumps(ctx)
except KeyError:
pass
try:
# we are in the list view of the model eg: admin/app/model/
ctx['location']= 'model_list'
module_name = context['module_name'].lower()
# django adds an 's' to every model name in this view, so we are gonna
ctx['param1'] = module_name
return json.dumps(ctx)
except KeyError:
pass
try:
# editing a model
ctx['location']= 'model_edit'
ctx['param1'] = context['original'].__class__.__name__.lower()
ctx['param2'] = context['original'].pk
return json.dumps(ctx)
except KeyError:
pass
return json.dumps(ctx)
Check if original object is None
|
from django import template
import json
from django.conf import settings
register = template.Library()
@register.simple_tag(takes_context=True)
def get_admin_context(context):
ctx = {'location':None, 'param1':None, 'param2':None, 'static':settings.STATIC_URL}
try:
context['app_list']
if len(context['app_list']) > 1:
# we are at /admin/
ctx['location'] = 'admin_index'
return json.dumps(ctx)
elif len(context['app_list']) == 1:
#We are at the app index eg: /admin/app/
ctx['location'] = 'app_index'
ctx['param1'] = context['app_list'][0]['name'].lower()
return json.dumps(ctx)
except KeyError:
pass
try:
# we are in the list view of the model eg: admin/app/model/
ctx['location']= 'model_list'
module_name = context['module_name'].lower()
# django adds an 's' to every model name in this view, so we are gonna
ctx['param1'] = module_name
return json.dumps(ctx)
except KeyError:
pass
try:
# editing a model
ctx['location']= 'model_edit'
if context['original'] is not None:
ctx['param1'] = context['original'].__class__.__name__.lower()
ctx['param2'] = context['original'].pk
return json.dumps(ctx)
except KeyError:
pass
return json.dumps(ctx)
|
<commit_before>from django import template
import json
from django.conf import settings
register = template.Library()
@register.simple_tag(takes_context=True)
def get_admin_context(context):
ctx = {'location':None, 'param1':None, 'param2':None, 'static':settings.STATIC_URL}
try:
context['app_list']
if len(context['app_list']) > 1:
# we are at /admin/
ctx['location'] = 'admin_index'
return json.dumps(ctx)
elif len(context['app_list']) == 1:
#We are at the app index eg: /admin/app/
ctx['location'] = 'app_index'
ctx['param1'] = context['app_list'][0]['name'].lower()
return json.dumps(ctx)
except KeyError:
pass
try:
# we are in the list view of the model eg: admin/app/model/
ctx['location']= 'model_list'
module_name = context['module_name'].lower()
# django adds an 's' to every model name in this view, so we are gonna
ctx['param1'] = module_name
return json.dumps(ctx)
except KeyError:
pass
try:
# editing a model
ctx['location']= 'model_edit'
ctx['param1'] = context['original'].__class__.__name__.lower()
ctx['param2'] = context['original'].pk
return json.dumps(ctx)
except KeyError:
pass
return json.dumps(ctx)
<commit_msg>Check if original object is None<commit_after>
|
from django import template
import json
from django.conf import settings
register = template.Library()
@register.simple_tag(takes_context=True)
def get_admin_context(context):
ctx = {'location':None, 'param1':None, 'param2':None, 'static':settings.STATIC_URL}
try:
context['app_list']
if len(context['app_list']) > 1:
# we are at /admin/
ctx['location'] = 'admin_index'
return json.dumps(ctx)
elif len(context['app_list']) == 1:
#We are at the app index eg: /admin/app/
ctx['location'] = 'app_index'
ctx['param1'] = context['app_list'][0]['name'].lower()
return json.dumps(ctx)
except KeyError:
pass
try:
# we are in the list view of the model eg: admin/app/model/
ctx['location']= 'model_list'
module_name = context['module_name'].lower()
# django adds an 's' to every model name in this view, so we are gonna
ctx['param1'] = module_name
return json.dumps(ctx)
except KeyError:
pass
try:
# editing a model
ctx['location']= 'model_edit'
if context['original'] is not None:
ctx['param1'] = context['original'].__class__.__name__.lower()
ctx['param2'] = context['original'].pk
return json.dumps(ctx)
except KeyError:
pass
return json.dumps(ctx)
|
from django import template
import json
from django.conf import settings
register = template.Library()
@register.simple_tag(takes_context=True)
def get_admin_context(context):
ctx = {'location':None, 'param1':None, 'param2':None, 'static':settings.STATIC_URL}
try:
context['app_list']
if len(context['app_list']) > 1:
# we are at /admin/
ctx['location'] = 'admin_index'
return json.dumps(ctx)
elif len(context['app_list']) == 1:
#We are at the app index eg: /admin/app/
ctx['location'] = 'app_index'
ctx['param1'] = context['app_list'][0]['name'].lower()
return json.dumps(ctx)
except KeyError:
pass
try:
# we are in the list view of the model eg: admin/app/model/
ctx['location']= 'model_list'
module_name = context['module_name'].lower()
# django adds an 's' to every model name in this view, so we are gonna
ctx['param1'] = module_name
return json.dumps(ctx)
except KeyError:
pass
try:
# editing a model
ctx['location']= 'model_edit'
ctx['param1'] = context['original'].__class__.__name__.lower()
ctx['param2'] = context['original'].pk
return json.dumps(ctx)
except KeyError:
pass
return json.dumps(ctx)
Check if original object is Nonefrom django import template
import json
from django.conf import settings
register = template.Library()
@register.simple_tag(takes_context=True)
def get_admin_context(context):
ctx = {'location':None, 'param1':None, 'param2':None, 'static':settings.STATIC_URL}
try:
context['app_list']
if len(context['app_list']) > 1:
# we are at /admin/
ctx['location'] = 'admin_index'
return json.dumps(ctx)
elif len(context['app_list']) == 1:
#We are at the app index eg: /admin/app/
ctx['location'] = 'app_index'
ctx['param1'] = context['app_list'][0]['name'].lower()
return json.dumps(ctx)
except KeyError:
pass
try:
# we are in the list view of the model eg: admin/app/model/
ctx['location']= 'model_list'
module_name = context['module_name'].lower()
# django adds an 's' to every model name in this view, so we are gonna
ctx['param1'] = module_name
return json.dumps(ctx)
except KeyError:
pass
try:
# editing a model
ctx['location']= 'model_edit'
if context['original'] is not None:
ctx['param1'] = context['original'].__class__.__name__.lower()
ctx['param2'] = context['original'].pk
return json.dumps(ctx)
except KeyError:
pass
return json.dumps(ctx)
|
<commit_before>from django import template
import json
from django.conf import settings
register = template.Library()
@register.simple_tag(takes_context=True)
def get_admin_context(context):
ctx = {'location':None, 'param1':None, 'param2':None, 'static':settings.STATIC_URL}
try:
context['app_list']
if len(context['app_list']) > 1:
# we are at /admin/
ctx['location'] = 'admin_index'
return json.dumps(ctx)
elif len(context['app_list']) == 1:
#We are at the app index eg: /admin/app/
ctx['location'] = 'app_index'
ctx['param1'] = context['app_list'][0]['name'].lower()
return json.dumps(ctx)
except KeyError:
pass
try:
# we are in the list view of the model eg: admin/app/model/
ctx['location']= 'model_list'
module_name = context['module_name'].lower()
# django adds an 's' to every model name in this view, so we are gonna
ctx['param1'] = module_name
return json.dumps(ctx)
except KeyError:
pass
try:
# editing a model
ctx['location']= 'model_edit'
ctx['param1'] = context['original'].__class__.__name__.lower()
ctx['param2'] = context['original'].pk
return json.dumps(ctx)
except KeyError:
pass
return json.dumps(ctx)
<commit_msg>Check if original object is None<commit_after>from django import template
import json
from django.conf import settings
register = template.Library()
@register.simple_tag(takes_context=True)
def get_admin_context(context):
ctx = {'location':None, 'param1':None, 'param2':None, 'static':settings.STATIC_URL}
try:
context['app_list']
if len(context['app_list']) > 1:
# we are at /admin/
ctx['location'] = 'admin_index'
return json.dumps(ctx)
elif len(context['app_list']) == 1:
#We are at the app index eg: /admin/app/
ctx['location'] = 'app_index'
ctx['param1'] = context['app_list'][0]['name'].lower()
return json.dumps(ctx)
except KeyError:
pass
try:
# we are in the list view of the model eg: admin/app/model/
ctx['location']= 'model_list'
module_name = context['module_name'].lower()
# django adds an 's' to every model name in this view, so we are gonna
ctx['param1'] = module_name
return json.dumps(ctx)
except KeyError:
pass
try:
# editing a model
ctx['location']= 'model_edit'
if context['original'] is not None:
ctx['param1'] = context['original'].__class__.__name__.lower()
ctx['param2'] = context['original'].pk
return json.dumps(ctx)
except KeyError:
pass
return json.dumps(ctx)
|
4b7e2812768159961f297ccf7b8a23c2d436ede2
|
dduplicated/fileManager.py
|
dduplicated/fileManager.py
|
import os
from threading import Thread
def _delete(path):
os.remove(path)
def _link(src, path):
os.symlink(src, path)
def manager_files(paths, link):
# The first file is preserved to not delete all files in directories.
first = True
src = ""
deleted_files = []
linked_files = []
errors = []
for path in paths:
if os.path.isfile(path):
if first:
first = False
src = path
else:
Thread(target=_delete, args=(path)).start()
deleted_files.append(path)
if link:
Thread(target=_link, args=(src, path)).start()
linked_files.append(path)
else:
errors.append("Not identified by file: \"{}\"".format(path))
return {"preserved": src, "linked_files": linked_files, "deleted_files": deleted_files, "errors": errors}
# Try The Voight-Kampff if you not recognize if is a replicant or not, all is suspect
def manager(duplicates, create_link=False):
if len(duplicates) == 0:
return None
processed_files = []
for files_by_hash in duplicates.values():
processed_files.append(manager_files(files_by_hash, create_link))
return processed_files
def delete(duplicates):
return manager(duplicates)
def link(duplicates):
return manager(duplicates, True)
|
import os
from threading import Thread
def _delete(path):
os.remove(path)
def _link(src, path):
os.symlink(src, path)
def manager_files(paths, link):
# The first file is preserved to not delete all files in directories.
first = True
src = ""
deleted_files = []
linked_files = []
errors = []
for path in paths:
if os.path.isfile(path):
if first:
first = False
src = path
else:
Thread(target=_delete, args=(path)).start()
deleted_files.append(path)
if link:
Thread(target=_link, args=(src, path)).start()
linked_files.append(path)
else:
errors.append("Not identified by file: \"{}\"".format(path))
return {"preserved": src, "linked_files": linked_files, "deleted_files": deleted_files, "errors": errors}
# Try The Voight-Kampff if you not recognize if is a replicant or not, all is suspect
def manager(duplicates, create_link=False):
if len(duplicates) == 0:
return None
processed_files = []
for files_by_hash in duplicates.values():
processed_files.append(manager_files(files_by_hash, create_link))
return processed_files
def delete(duplicates):
return manager(duplicates)
def link(duplicates):
return manager(duplicates, True)
|
Fix spacing in last method of file.
|
Fix spacing in last method of file.
Signed-off-by: messiasthi <8562fc1efba9a3c99753c749fdfb1b6932b70fbf@gmail.com>
|
Python
|
mit
|
messiasthi/dduplicated-cli
|
import os
from threading import Thread
def _delete(path):
os.remove(path)
def _link(src, path):
os.symlink(src, path)
def manager_files(paths, link):
# The first file is preserved to not delete all files in directories.
first = True
src = ""
deleted_files = []
linked_files = []
errors = []
for path in paths:
if os.path.isfile(path):
if first:
first = False
src = path
else:
Thread(target=_delete, args=(path)).start()
deleted_files.append(path)
if link:
Thread(target=_link, args=(src, path)).start()
linked_files.append(path)
else:
errors.append("Not identified by file: \"{}\"".format(path))
return {"preserved": src, "linked_files": linked_files, "deleted_files": deleted_files, "errors": errors}
# Try The Voight-Kampff if you not recognize if is a replicant or not, all is suspect
def manager(duplicates, create_link=False):
if len(duplicates) == 0:
return None
processed_files = []
for files_by_hash in duplicates.values():
processed_files.append(manager_files(files_by_hash, create_link))
return processed_files
def delete(duplicates):
return manager(duplicates)
def link(duplicates):
return manager(duplicates, True)
Fix spacing in last method of file.
Signed-off-by: messiasthi <8562fc1efba9a3c99753c749fdfb1b6932b70fbf@gmail.com>
|
import os
from threading import Thread
def _delete(path):
os.remove(path)
def _link(src, path):
os.symlink(src, path)
def manager_files(paths, link):
# The first file is preserved to not delete all files in directories.
first = True
src = ""
deleted_files = []
linked_files = []
errors = []
for path in paths:
if os.path.isfile(path):
if first:
first = False
src = path
else:
Thread(target=_delete, args=(path)).start()
deleted_files.append(path)
if link:
Thread(target=_link, args=(src, path)).start()
linked_files.append(path)
else:
errors.append("Not identified by file: \"{}\"".format(path))
return {"preserved": src, "linked_files": linked_files, "deleted_files": deleted_files, "errors": errors}
# Try The Voight-Kampff if you not recognize if is a replicant or not, all is suspect
def manager(duplicates, create_link=False):
if len(duplicates) == 0:
return None
processed_files = []
for files_by_hash in duplicates.values():
processed_files.append(manager_files(files_by_hash, create_link))
return processed_files
def delete(duplicates):
return manager(duplicates)
def link(duplicates):
return manager(duplicates, True)
|
<commit_before>import os
from threading import Thread
def _delete(path):
os.remove(path)
def _link(src, path):
os.symlink(src, path)
def manager_files(paths, link):
# The first file is preserved to not delete all files in directories.
first = True
src = ""
deleted_files = []
linked_files = []
errors = []
for path in paths:
if os.path.isfile(path):
if first:
first = False
src = path
else:
Thread(target=_delete, args=(path)).start()
deleted_files.append(path)
if link:
Thread(target=_link, args=(src, path)).start()
linked_files.append(path)
else:
errors.append("Not identified by file: \"{}\"".format(path))
return {"preserved": src, "linked_files": linked_files, "deleted_files": deleted_files, "errors": errors}
# Try The Voight-Kampff if you not recognize if is a replicant or not, all is suspect
def manager(duplicates, create_link=False):
if len(duplicates) == 0:
return None
processed_files = []
for files_by_hash in duplicates.values():
processed_files.append(manager_files(files_by_hash, create_link))
return processed_files
def delete(duplicates):
return manager(duplicates)
def link(duplicates):
return manager(duplicates, True)
<commit_msg>Fix spacing in last method of file.
Signed-off-by: messiasthi <8562fc1efba9a3c99753c749fdfb1b6932b70fbf@gmail.com><commit_after>
|
import os
from threading import Thread
def _delete(path):
os.remove(path)
def _link(src, path):
os.symlink(src, path)
def manager_files(paths, link):
# The first file is preserved to not delete all files in directories.
first = True
src = ""
deleted_files = []
linked_files = []
errors = []
for path in paths:
if os.path.isfile(path):
if first:
first = False
src = path
else:
Thread(target=_delete, args=(path)).start()
deleted_files.append(path)
if link:
Thread(target=_link, args=(src, path)).start()
linked_files.append(path)
else:
errors.append("Not identified by file: \"{}\"".format(path))
return {"preserved": src, "linked_files": linked_files, "deleted_files": deleted_files, "errors": errors}
# Try The Voight-Kampff if you not recognize if is a replicant or not, all is suspect
def manager(duplicates, create_link=False):
if len(duplicates) == 0:
return None
processed_files = []
for files_by_hash in duplicates.values():
processed_files.append(manager_files(files_by_hash, create_link))
return processed_files
def delete(duplicates):
return manager(duplicates)
def link(duplicates):
return manager(duplicates, True)
|
import os
from threading import Thread
def _delete(path):
os.remove(path)
def _link(src, path):
os.symlink(src, path)
def manager_files(paths, link):
# The first file is preserved to not delete all files in directories.
first = True
src = ""
deleted_files = []
linked_files = []
errors = []
for path in paths:
if os.path.isfile(path):
if first:
first = False
src = path
else:
Thread(target=_delete, args=(path)).start()
deleted_files.append(path)
if link:
Thread(target=_link, args=(src, path)).start()
linked_files.append(path)
else:
errors.append("Not identified by file: \"{}\"".format(path))
return {"preserved": src, "linked_files": linked_files, "deleted_files": deleted_files, "errors": errors}
# Try The Voight-Kampff if you not recognize if is a replicant or not, all is suspect
def manager(duplicates, create_link=False):
if len(duplicates) == 0:
return None
processed_files = []
for files_by_hash in duplicates.values():
processed_files.append(manager_files(files_by_hash, create_link))
return processed_files
def delete(duplicates):
return manager(duplicates)
def link(duplicates):
return manager(duplicates, True)
Fix spacing in last method of file.
Signed-off-by: messiasthi <8562fc1efba9a3c99753c749fdfb1b6932b70fbf@gmail.com>import os
from threading import Thread
def _delete(path):
os.remove(path)
def _link(src, path):
os.symlink(src, path)
def manager_files(paths, link):
# The first file is preserved to not delete all files in directories.
first = True
src = ""
deleted_files = []
linked_files = []
errors = []
for path in paths:
if os.path.isfile(path):
if first:
first = False
src = path
else:
Thread(target=_delete, args=(path)).start()
deleted_files.append(path)
if link:
Thread(target=_link, args=(src, path)).start()
linked_files.append(path)
else:
errors.append("Not identified by file: \"{}\"".format(path))
return {"preserved": src, "linked_files": linked_files, "deleted_files": deleted_files, "errors": errors}
# Try The Voight-Kampff if you not recognize if is a replicant or not, all is suspect
def manager(duplicates, create_link=False):
if len(duplicates) == 0:
return None
processed_files = []
for files_by_hash in duplicates.values():
processed_files.append(manager_files(files_by_hash, create_link))
return processed_files
def delete(duplicates):
return manager(duplicates)
def link(duplicates):
return manager(duplicates, True)
|
<commit_before>import os
from threading import Thread
def _delete(path):
os.remove(path)
def _link(src, path):
os.symlink(src, path)
def manager_files(paths, link):
# The first file is preserved to not delete all files in directories.
first = True
src = ""
deleted_files = []
linked_files = []
errors = []
for path in paths:
if os.path.isfile(path):
if first:
first = False
src = path
else:
Thread(target=_delete, args=(path)).start()
deleted_files.append(path)
if link:
Thread(target=_link, args=(src, path)).start()
linked_files.append(path)
else:
errors.append("Not identified by file: \"{}\"".format(path))
return {"preserved": src, "linked_files": linked_files, "deleted_files": deleted_files, "errors": errors}
# Try The Voight-Kampff if you not recognize if is a replicant or not, all is suspect
def manager(duplicates, create_link=False):
if len(duplicates) == 0:
return None
processed_files = []
for files_by_hash in duplicates.values():
processed_files.append(manager_files(files_by_hash, create_link))
return processed_files
def delete(duplicates):
return manager(duplicates)
def link(duplicates):
return manager(duplicates, True)
<commit_msg>Fix spacing in last method of file.
Signed-off-by: messiasthi <8562fc1efba9a3c99753c749fdfb1b6932b70fbf@gmail.com><commit_after>import os
from threading import Thread
def _delete(path):
os.remove(path)
def _link(src, path):
os.symlink(src, path)
def manager_files(paths, link):
# The first file is preserved to not delete all files in directories.
first = True
src = ""
deleted_files = []
linked_files = []
errors = []
for path in paths:
if os.path.isfile(path):
if first:
first = False
src = path
else:
Thread(target=_delete, args=(path)).start()
deleted_files.append(path)
if link:
Thread(target=_link, args=(src, path)).start()
linked_files.append(path)
else:
errors.append("Not identified by file: \"{}\"".format(path))
return {"preserved": src, "linked_files": linked_files, "deleted_files": deleted_files, "errors": errors}
# Try The Voight-Kampff if you not recognize if is a replicant or not, all is suspect
def manager(duplicates, create_link=False):
if len(duplicates) == 0:
return None
processed_files = []
for files_by_hash in duplicates.values():
processed_files.append(manager_files(files_by_hash, create_link))
return processed_files
def delete(duplicates):
return manager(duplicates)
def link(duplicates):
return manager(duplicates, True)
|
146a2217fba0614d5f03e6a8648ced9613dc2cb8
|
readux/books/management/commands/web_export.py
|
readux/books/management/commands/web_export.py
|
from eulfedora.server import Repository
from django.core.management.base import BaseCommand
from readux.books import export
from readux.books.models import Volume
class Command(BaseCommand):
help = 'Construct web export of an annotated volume'
def add_arguments(self, parser):
parser.add_argument('pid', nargs='+', type=str)
def handle(self, *args, **options):
repo = Repository()
for pid in options['pid']:
vol = repo.get_object('emory:4ckk0', type=Volume)
export.static_website(vol)
|
from eulfedora.server import Repository
from django.core.management.base import BaseCommand
import shutil
from readux.books import annotate, export
from readux.books.models import Volume
class Command(BaseCommand):
help = 'Construct web export of an annotated volume'
def add_arguments(self, parser):
parser.add_argument('pid', nargs='+', type=str)
parser.add_argument('--static', action='store_true', default=False,
help='Generate built (static) site instead of jekyll site')
def handle(self, *args, **options):
print args
repo = Repository()
for pid in options['pid']:
vol = repo.get_object(pid, type=Volume)
tei = annotate.annotated_tei(vol.generate_volume_tei(),
vol.annotations())
zipfile = export.website(vol, tei, static=options['static'])
zipfilename = '%s-annotated-site.zip' % pid
shutil.copyfile(zipfile.name, zipfilename)
print 'Export for %s complete, zipfile is %s' % (vol.noid, zipfilename)
|
Update web export manage command to generate static/jekyll site
|
Update web export manage command to generate static/jekyll site
|
Python
|
apache-2.0
|
emory-libraries/readux,emory-libraries/readux,emory-libraries/readux
|
from eulfedora.server import Repository
from django.core.management.base import BaseCommand
from readux.books import export
from readux.books.models import Volume
class Command(BaseCommand):
help = 'Construct web export of an annotated volume'
def add_arguments(self, parser):
parser.add_argument('pid', nargs='+', type=str)
def handle(self, *args, **options):
repo = Repository()
for pid in options['pid']:
vol = repo.get_object('emory:4ckk0', type=Volume)
export.static_website(vol)
Update web export manage command to generate static/jekyll site
|
from eulfedora.server import Repository
from django.core.management.base import BaseCommand
import shutil
from readux.books import annotate, export
from readux.books.models import Volume
class Command(BaseCommand):
help = 'Construct web export of an annotated volume'
def add_arguments(self, parser):
parser.add_argument('pid', nargs='+', type=str)
parser.add_argument('--static', action='store_true', default=False,
help='Generate built (static) site instead of jekyll site')
def handle(self, *args, **options):
print args
repo = Repository()
for pid in options['pid']:
vol = repo.get_object(pid, type=Volume)
tei = annotate.annotated_tei(vol.generate_volume_tei(),
vol.annotations())
zipfile = export.website(vol, tei, static=options['static'])
zipfilename = '%s-annotated-site.zip' % pid
shutil.copyfile(zipfile.name, zipfilename)
print 'Export for %s complete, zipfile is %s' % (vol.noid, zipfilename)
|
<commit_before>from eulfedora.server import Repository
from django.core.management.base import BaseCommand
from readux.books import export
from readux.books.models import Volume
class Command(BaseCommand):
help = 'Construct web export of an annotated volume'
def add_arguments(self, parser):
parser.add_argument('pid', nargs='+', type=str)
def handle(self, *args, **options):
repo = Repository()
for pid in options['pid']:
vol = repo.get_object('emory:4ckk0', type=Volume)
export.static_website(vol)
<commit_msg>Update web export manage command to generate static/jekyll site<commit_after>
|
from eulfedora.server import Repository
from django.core.management.base import BaseCommand
import shutil
from readux.books import annotate, export
from readux.books.models import Volume
class Command(BaseCommand):
help = 'Construct web export of an annotated volume'
def add_arguments(self, parser):
parser.add_argument('pid', nargs='+', type=str)
parser.add_argument('--static', action='store_true', default=False,
help='Generate built (static) site instead of jekyll site')
def handle(self, *args, **options):
print args
repo = Repository()
for pid in options['pid']:
vol = repo.get_object(pid, type=Volume)
tei = annotate.annotated_tei(vol.generate_volume_tei(),
vol.annotations())
zipfile = export.website(vol, tei, static=options['static'])
zipfilename = '%s-annotated-site.zip' % pid
shutil.copyfile(zipfile.name, zipfilename)
print 'Export for %s complete, zipfile is %s' % (vol.noid, zipfilename)
|
from eulfedora.server import Repository
from django.core.management.base import BaseCommand
from readux.books import export
from readux.books.models import Volume
class Command(BaseCommand):
help = 'Construct web export of an annotated volume'
def add_arguments(self, parser):
parser.add_argument('pid', nargs='+', type=str)
def handle(self, *args, **options):
repo = Repository()
for pid in options['pid']:
vol = repo.get_object('emory:4ckk0', type=Volume)
export.static_website(vol)
Update web export manage command to generate static/jekyll sitefrom eulfedora.server import Repository
from django.core.management.base import BaseCommand
import shutil
from readux.books import annotate, export
from readux.books.models import Volume
class Command(BaseCommand):
help = 'Construct web export of an annotated volume'
def add_arguments(self, parser):
parser.add_argument('pid', nargs='+', type=str)
parser.add_argument('--static', action='store_true', default=False,
help='Generate built (static) site instead of jekyll site')
def handle(self, *args, **options):
print args
repo = Repository()
for pid in options['pid']:
vol = repo.get_object(pid, type=Volume)
tei = annotate.annotated_tei(vol.generate_volume_tei(),
vol.annotations())
zipfile = export.website(vol, tei, static=options['static'])
zipfilename = '%s-annotated-site.zip' % pid
shutil.copyfile(zipfile.name, zipfilename)
print 'Export for %s complete, zipfile is %s' % (vol.noid, zipfilename)
|
<commit_before>from eulfedora.server import Repository
from django.core.management.base import BaseCommand
from readux.books import export
from readux.books.models import Volume
class Command(BaseCommand):
help = 'Construct web export of an annotated volume'
def add_arguments(self, parser):
parser.add_argument('pid', nargs='+', type=str)
def handle(self, *args, **options):
repo = Repository()
for pid in options['pid']:
vol = repo.get_object('emory:4ckk0', type=Volume)
export.static_website(vol)
<commit_msg>Update web export manage command to generate static/jekyll site<commit_after>from eulfedora.server import Repository
from django.core.management.base import BaseCommand
import shutil
from readux.books import annotate, export
from readux.books.models import Volume
class Command(BaseCommand):
help = 'Construct web export of an annotated volume'
def add_arguments(self, parser):
parser.add_argument('pid', nargs='+', type=str)
parser.add_argument('--static', action='store_true', default=False,
help='Generate built (static) site instead of jekyll site')
def handle(self, *args, **options):
print args
repo = Repository()
for pid in options['pid']:
vol = repo.get_object(pid, type=Volume)
tei = annotate.annotated_tei(vol.generate_volume_tei(),
vol.annotations())
zipfile = export.website(vol, tei, static=options['static'])
zipfilename = '%s-annotated-site.zip' % pid
shutil.copyfile(zipfile.name, zipfilename)
print 'Export for %s complete, zipfile is %s' % (vol.noid, zipfilename)
|
a425db8ec0b21a5ff72af7481e7a7e30638ef9e3
|
sorl_thumbnail_serializer/fields.py
|
sorl_thumbnail_serializer/fields.py
|
from rest_framework import serializers
from sorl.thumbnail import get_thumbnail
class HyperlinkedSorlImageField(serializers.ImageField):
def __init__(self, dimensions, options={}, *args, **kwargs):
self.dimensions = dimensions
self.options = options
super(HyperlinkedSorlImageField, self).__init__(*args, **kwargs)
def to_native(self, value):
image = get_thumbnail(value, self.dimensions, **self.options)
try:
request = self.context.get('request', None)
return request.build_absolute_uri(image.url)
except Exception, e:
return super(HyperlinkedSorlImageField, self).to_native(image.url)
|
from rest_framework import serializers
from sorl.thumbnail import get_thumbnail
class HyperlinkedSorlImageField(serializers.ImageField):
def __init__(self, dimensions, options={}, *args, **kwargs):
self.dimensions = dimensions
self.options = options
super(HyperlinkedSorlImageField, self).__init__(*args, **kwargs)
def to_representation(self, value):
image = get_thumbnail(value, self.dimensions, **self.options)
try:
request = self.context.get('request', None)
return request.build_absolute_uri(image.url)
except Exception, e:
return super(HyperlinkedSorlImageField, self).to_native(image.url)
|
Support for DRF 3.0 and above
|
Support for DRF 3.0 and above
See http://www.django-rest-framework.org/topics/3.0-announcement/
|
Python
|
mit
|
dessibelle/sorl-thumbnail-serializer-field
|
from rest_framework import serializers
from sorl.thumbnail import get_thumbnail
class HyperlinkedSorlImageField(serializers.ImageField):
def __init__(self, dimensions, options={}, *args, **kwargs):
self.dimensions = dimensions
self.options = options
super(HyperlinkedSorlImageField, self).__init__(*args, **kwargs)
def to_native(self, value):
image = get_thumbnail(value, self.dimensions, **self.options)
try:
request = self.context.get('request', None)
return request.build_absolute_uri(image.url)
except Exception, e:
return super(HyperlinkedSorlImageField, self).to_native(image.url)
Support for DRF 3.0 and above
See http://www.django-rest-framework.org/topics/3.0-announcement/
|
from rest_framework import serializers
from sorl.thumbnail import get_thumbnail
class HyperlinkedSorlImageField(serializers.ImageField):
def __init__(self, dimensions, options={}, *args, **kwargs):
self.dimensions = dimensions
self.options = options
super(HyperlinkedSorlImageField, self).__init__(*args, **kwargs)
def to_representation(self, value):
image = get_thumbnail(value, self.dimensions, **self.options)
try:
request = self.context.get('request', None)
return request.build_absolute_uri(image.url)
except Exception, e:
return super(HyperlinkedSorlImageField, self).to_native(image.url)
|
<commit_before>from rest_framework import serializers
from sorl.thumbnail import get_thumbnail
class HyperlinkedSorlImageField(serializers.ImageField):
def __init__(self, dimensions, options={}, *args, **kwargs):
self.dimensions = dimensions
self.options = options
super(HyperlinkedSorlImageField, self).__init__(*args, **kwargs)
def to_native(self, value):
image = get_thumbnail(value, self.dimensions, **self.options)
try:
request = self.context.get('request', None)
return request.build_absolute_uri(image.url)
except Exception, e:
return super(HyperlinkedSorlImageField, self).to_native(image.url)
<commit_msg>Support for DRF 3.0 and above
See http://www.django-rest-framework.org/topics/3.0-announcement/<commit_after>
|
from rest_framework import serializers
from sorl.thumbnail import get_thumbnail
class HyperlinkedSorlImageField(serializers.ImageField):
def __init__(self, dimensions, options={}, *args, **kwargs):
self.dimensions = dimensions
self.options = options
super(HyperlinkedSorlImageField, self).__init__(*args, **kwargs)
def to_representation(self, value):
image = get_thumbnail(value, self.dimensions, **self.options)
try:
request = self.context.get('request', None)
return request.build_absolute_uri(image.url)
except Exception, e:
return super(HyperlinkedSorlImageField, self).to_native(image.url)
|
from rest_framework import serializers
from sorl.thumbnail import get_thumbnail
class HyperlinkedSorlImageField(serializers.ImageField):
def __init__(self, dimensions, options={}, *args, **kwargs):
self.dimensions = dimensions
self.options = options
super(HyperlinkedSorlImageField, self).__init__(*args, **kwargs)
def to_native(self, value):
image = get_thumbnail(value, self.dimensions, **self.options)
try:
request = self.context.get('request', None)
return request.build_absolute_uri(image.url)
except Exception, e:
return super(HyperlinkedSorlImageField, self).to_native(image.url)
Support for DRF 3.0 and above
See http://www.django-rest-framework.org/topics/3.0-announcement/from rest_framework import serializers
from sorl.thumbnail import get_thumbnail
class HyperlinkedSorlImageField(serializers.ImageField):
def __init__(self, dimensions, options={}, *args, **kwargs):
self.dimensions = dimensions
self.options = options
super(HyperlinkedSorlImageField, self).__init__(*args, **kwargs)
def to_representation(self, value):
image = get_thumbnail(value, self.dimensions, **self.options)
try:
request = self.context.get('request', None)
return request.build_absolute_uri(image.url)
except Exception, e:
return super(HyperlinkedSorlImageField, self).to_native(image.url)
|
<commit_before>from rest_framework import serializers
from sorl.thumbnail import get_thumbnail
class HyperlinkedSorlImageField(serializers.ImageField):
def __init__(self, dimensions, options={}, *args, **kwargs):
self.dimensions = dimensions
self.options = options
super(HyperlinkedSorlImageField, self).__init__(*args, **kwargs)
def to_native(self, value):
image = get_thumbnail(value, self.dimensions, **self.options)
try:
request = self.context.get('request', None)
return request.build_absolute_uri(image.url)
except Exception, e:
return super(HyperlinkedSorlImageField, self).to_native(image.url)
<commit_msg>Support for DRF 3.0 and above
See http://www.django-rest-framework.org/topics/3.0-announcement/<commit_after>from rest_framework import serializers
from sorl.thumbnail import get_thumbnail
class HyperlinkedSorlImageField(serializers.ImageField):
def __init__(self, dimensions, options={}, *args, **kwargs):
self.dimensions = dimensions
self.options = options
super(HyperlinkedSorlImageField, self).__init__(*args, **kwargs)
def to_representation(self, value):
image = get_thumbnail(value, self.dimensions, **self.options)
try:
request = self.context.get('request', None)
return request.build_absolute_uri(image.url)
except Exception, e:
return super(HyperlinkedSorlImageField, self).to_native(image.url)
|
89d2f9ef443b5cd17ec802e649843c086b48a0ca
|
yarn_api_client/__init__.py
|
yarn_api_client/__init__.py
|
# -*- coding: utf-8 -*-
__version__ = '0.3.4'
__all__ = ['ApplicationMaster', 'HistoryServer', 'NodeManager', 'ResourceManager']
from .application_master import ApplicationMaster
from .history_server import HistoryServer
from .node_manager import NodeManager
from .resource_manager import ResourceManager
|
# -*- coding: utf-8 -*-
__version__ = '0.3.5.dev'
__all__ = ['ApplicationMaster', 'HistoryServer', 'NodeManager', 'ResourceManager']
from .application_master import ApplicationMaster
from .history_server import HistoryServer
from .node_manager import NodeManager
from .resource_manager import ResourceManager
|
Prepare for next development iteration
|
Prepare for next development iteration
|
Python
|
bsd-3-clause
|
toidi/hadoop-yarn-api-python-client
|
# -*- coding: utf-8 -*-
__version__ = '0.3.4'
__all__ = ['ApplicationMaster', 'HistoryServer', 'NodeManager', 'ResourceManager']
from .application_master import ApplicationMaster
from .history_server import HistoryServer
from .node_manager import NodeManager
from .resource_manager import ResourceManager
Prepare for next development iteration
|
# -*- coding: utf-8 -*-
__version__ = '0.3.5.dev'
__all__ = ['ApplicationMaster', 'HistoryServer', 'NodeManager', 'ResourceManager']
from .application_master import ApplicationMaster
from .history_server import HistoryServer
from .node_manager import NodeManager
from .resource_manager import ResourceManager
|
<commit_before># -*- coding: utf-8 -*-
__version__ = '0.3.4'
__all__ = ['ApplicationMaster', 'HistoryServer', 'NodeManager', 'ResourceManager']
from .application_master import ApplicationMaster
from .history_server import HistoryServer
from .node_manager import NodeManager
from .resource_manager import ResourceManager
<commit_msg>Prepare for next development iteration<commit_after>
|
# -*- coding: utf-8 -*-
__version__ = '0.3.5.dev'
__all__ = ['ApplicationMaster', 'HistoryServer', 'NodeManager', 'ResourceManager']
from .application_master import ApplicationMaster
from .history_server import HistoryServer
from .node_manager import NodeManager
from .resource_manager import ResourceManager
|
# -*- coding: utf-8 -*-
__version__ = '0.3.4'
__all__ = ['ApplicationMaster', 'HistoryServer', 'NodeManager', 'ResourceManager']
from .application_master import ApplicationMaster
from .history_server import HistoryServer
from .node_manager import NodeManager
from .resource_manager import ResourceManager
Prepare for next development iteration# -*- coding: utf-8 -*-
__version__ = '0.3.5.dev'
__all__ = ['ApplicationMaster', 'HistoryServer', 'NodeManager', 'ResourceManager']
from .application_master import ApplicationMaster
from .history_server import HistoryServer
from .node_manager import NodeManager
from .resource_manager import ResourceManager
|
<commit_before># -*- coding: utf-8 -*-
__version__ = '0.3.4'
__all__ = ['ApplicationMaster', 'HistoryServer', 'NodeManager', 'ResourceManager']
from .application_master import ApplicationMaster
from .history_server import HistoryServer
from .node_manager import NodeManager
from .resource_manager import ResourceManager
<commit_msg>Prepare for next development iteration<commit_after># -*- coding: utf-8 -*-
__version__ = '0.3.5.dev'
__all__ = ['ApplicationMaster', 'HistoryServer', 'NodeManager', 'ResourceManager']
from .application_master import ApplicationMaster
from .history_server import HistoryServer
from .node_manager import NodeManager
from .resource_manager import ResourceManager
|
22209f8de06a4a179cddd885566066dd6acdb8dd
|
python_course_1604/class_01/tests/test_04.py
|
python_course_1604/class_01/tests/test_04.py
|
'''
Created on 6 Apr 2016
@author: fressi
'''
import unittest
import python_course_1604.class_01.exercize_04_stack_limit as exercize
from python_course_1604.tests.utils import skip_if_exercize_not_started
@skip_if_exercize_not_started(exercize)
class TestStackLimit(unittest.TestCase):
def test_failing_function(self):
result = exercize.measure_stack_limit()
assert recursive_function(-2) == result
def recursive_function(level):
try:
return recursive_function(level + 1)
except RuntimeError:
return level
|
'''
Created on 6 Apr 2016
@author: fressi
'''
import unittest
import python_course_1604.class_01.exercize_04_stack_limit as exercize
from python_course_1604.tests.utils import skip_if_exercize_not_started
@skip_if_exercize_not_started(exercize)
class TestStackLimit(unittest.TestCase):
def test_failing_function(self):
result = exercize.measure_stack_limit()
expected_result = recursive_function(-2)
assert result in range(expected_result - 5, expected_result + 5)
def recursive_function(level):
try:
return recursive_function(level + 1)
except RuntimeError:
return level
|
Make stack limit check more tollerant.
|
Make stack limit check more tollerant.
|
Python
|
apache-2.0
|
FedericoRessi/pythoncourse
|
'''
Created on 6 Apr 2016
@author: fressi
'''
import unittest
import python_course_1604.class_01.exercize_04_stack_limit as exercize
from python_course_1604.tests.utils import skip_if_exercize_not_started
@skip_if_exercize_not_started(exercize)
class TestStackLimit(unittest.TestCase):
def test_failing_function(self):
result = exercize.measure_stack_limit()
assert recursive_function(-2) == result
def recursive_function(level):
try:
return recursive_function(level + 1)
except RuntimeError:
return level
Make stack limit check more tollerant.
|
'''
Created on 6 Apr 2016
@author: fressi
'''
import unittest
import python_course_1604.class_01.exercize_04_stack_limit as exercize
from python_course_1604.tests.utils import skip_if_exercize_not_started
@skip_if_exercize_not_started(exercize)
class TestStackLimit(unittest.TestCase):
def test_failing_function(self):
result = exercize.measure_stack_limit()
expected_result = recursive_function(-2)
assert result in range(expected_result - 5, expected_result + 5)
def recursive_function(level):
try:
return recursive_function(level + 1)
except RuntimeError:
return level
|
<commit_before>'''
Created on 6 Apr 2016
@author: fressi
'''
import unittest
import python_course_1604.class_01.exercize_04_stack_limit as exercize
from python_course_1604.tests.utils import skip_if_exercize_not_started
@skip_if_exercize_not_started(exercize)
class TestStackLimit(unittest.TestCase):
def test_failing_function(self):
result = exercize.measure_stack_limit()
assert recursive_function(-2) == result
def recursive_function(level):
try:
return recursive_function(level + 1)
except RuntimeError:
return level
<commit_msg>Make stack limit check more tollerant.<commit_after>
|
'''
Created on 6 Apr 2016
@author: fressi
'''
import unittest
import python_course_1604.class_01.exercize_04_stack_limit as exercize
from python_course_1604.tests.utils import skip_if_exercize_not_started
@skip_if_exercize_not_started(exercize)
class TestStackLimit(unittest.TestCase):
def test_failing_function(self):
result = exercize.measure_stack_limit()
expected_result = recursive_function(-2)
assert result in range(expected_result - 5, expected_result + 5)
def recursive_function(level):
try:
return recursive_function(level + 1)
except RuntimeError:
return level
|
'''
Created on 6 Apr 2016
@author: fressi
'''
import unittest
import python_course_1604.class_01.exercize_04_stack_limit as exercize
from python_course_1604.tests.utils import skip_if_exercize_not_started
@skip_if_exercize_not_started(exercize)
class TestStackLimit(unittest.TestCase):
def test_failing_function(self):
result = exercize.measure_stack_limit()
assert recursive_function(-2) == result
def recursive_function(level):
try:
return recursive_function(level + 1)
except RuntimeError:
return level
Make stack limit check more tollerant.'''
Created on 6 Apr 2016
@author: fressi
'''
import unittest
import python_course_1604.class_01.exercize_04_stack_limit as exercize
from python_course_1604.tests.utils import skip_if_exercize_not_started
@skip_if_exercize_not_started(exercize)
class TestStackLimit(unittest.TestCase):
def test_failing_function(self):
result = exercize.measure_stack_limit()
expected_result = recursive_function(-2)
assert result in range(expected_result - 5, expected_result + 5)
def recursive_function(level):
try:
return recursive_function(level + 1)
except RuntimeError:
return level
|
<commit_before>'''
Created on 6 Apr 2016
@author: fressi
'''
import unittest
import python_course_1604.class_01.exercize_04_stack_limit as exercize
from python_course_1604.tests.utils import skip_if_exercize_not_started
@skip_if_exercize_not_started(exercize)
class TestStackLimit(unittest.TestCase):
def test_failing_function(self):
result = exercize.measure_stack_limit()
assert recursive_function(-2) == result
def recursive_function(level):
try:
return recursive_function(level + 1)
except RuntimeError:
return level
<commit_msg>Make stack limit check more tollerant.<commit_after>'''
Created on 6 Apr 2016
@author: fressi
'''
import unittest
import python_course_1604.class_01.exercize_04_stack_limit as exercize
from python_course_1604.tests.utils import skip_if_exercize_not_started
@skip_if_exercize_not_started(exercize)
class TestStackLimit(unittest.TestCase):
def test_failing_function(self):
result = exercize.measure_stack_limit()
expected_result = recursive_function(-2)
assert result in range(expected_result - 5, expected_result + 5)
def recursive_function(level):
try:
return recursive_function(level + 1)
except RuntimeError:
return level
|
84cd432f2df46e24e7eaee81d899bf33fe551b70
|
netsecus/korrekturtools.py
|
netsecus/korrekturtools.py
|
from __future__ import unicode_literals
import os
import logging
from . import helper
def readStatus(config, student):
student = student.lower()
path = config("attachment_path")
if not os.path.exists(path):
return
path = os.path.join(path, student)
if not os.path.exists(path):
return "Student ohne Abgabe"
path = os.path.join(path, "korrekturstatus.txt")
if not os.path.exists(path):
return "Unbearbeitet"
statusfile = open(path, "r")
status = statusfile.read()
statusfile.close()
return status
def writeStatus(config, student, status):
student = student.lower()
status = status.lower()
path = os.path.join(config("attachment_path"), student)
if not os.path.exists(path):
logging.error("Requested student '%s' hasn't submitted anything yet.")
return
path = os.path.join(path, "korrekturstatus.txt")
with open(path, "w") as statusfile:
statusfile.write(status)
|
from __future__ import unicode_literals
import os
import logging
import sqlite3
from . import helper
def readStatus(config, student):
database = getStatusTable(config)
cursor = database.cursor()
cursor.execute("SELECT status FROM status WHERE identifier = ?", (student,))
statusRow = cursor.fetchone()[0] # just get first status
if statusRow:
return statusRow
else:
return "Unbearbeitet"
def writeStatus(config, student, status):
database = getStatusTable(config)
cursor = database.cursor()
# Check if we need to create a new row first
cursor.execute("SELECT status FROM status WHERE identifier = ?", (student,))
statusRow = cursor.fetchone()[0]
if statusRow:
cursor.execute("UPDATE status SET status = ? WHERE identifier = ?", (status, student,))
else:
cursor.execute("INSERT INTO status VALUES(?, ?)", (student, status, ))
database.commit()
def getStatusTable(config):
statusDatabasePath = config("database_path")
statusDatabase = sqlite3.connect(statusDatabasePath)
cursor = statusDatabase.cursor()
cursor.execute("""CREATE TABLE IF NOT EXISTS status
(`identifier` text UNIQUE, `status` text, PRIMARY KEY (`identifier`));""")
return statusDatabase
|
Move status to database instead of status file (server side)
|
Move status to database instead of status file (server side)
|
Python
|
mit
|
hhucn/netsec-uebungssystem,hhucn/netsec-uebungssystem,hhucn/netsec-uebungssystem
|
from __future__ import unicode_literals
import os
import logging
from . import helper
def readStatus(config, student):
student = student.lower()
path = config("attachment_path")
if not os.path.exists(path):
return
path = os.path.join(path, student)
if not os.path.exists(path):
return "Student ohne Abgabe"
path = os.path.join(path, "korrekturstatus.txt")
if not os.path.exists(path):
return "Unbearbeitet"
statusfile = open(path, "r")
status = statusfile.read()
statusfile.close()
return status
def writeStatus(config, student, status):
student = student.lower()
status = status.lower()
path = os.path.join(config("attachment_path"), student)
if not os.path.exists(path):
logging.error("Requested student '%s' hasn't submitted anything yet.")
return
path = os.path.join(path, "korrekturstatus.txt")
with open(path, "w") as statusfile:
statusfile.write(status)
Move status to database instead of status file (server side)
|
from __future__ import unicode_literals
import os
import logging
import sqlite3
from . import helper
def readStatus(config, student):
database = getStatusTable(config)
cursor = database.cursor()
cursor.execute("SELECT status FROM status WHERE identifier = ?", (student,))
statusRow = cursor.fetchone()[0] # just get first status
if statusRow:
return statusRow
else:
return "Unbearbeitet"
def writeStatus(config, student, status):
database = getStatusTable(config)
cursor = database.cursor()
# Check if we need to create a new row first
cursor.execute("SELECT status FROM status WHERE identifier = ?", (student,))
statusRow = cursor.fetchone()[0]
if statusRow:
cursor.execute("UPDATE status SET status = ? WHERE identifier = ?", (status, student,))
else:
cursor.execute("INSERT INTO status VALUES(?, ?)", (student, status, ))
database.commit()
def getStatusTable(config):
statusDatabasePath = config("database_path")
statusDatabase = sqlite3.connect(statusDatabasePath)
cursor = statusDatabase.cursor()
cursor.execute("""CREATE TABLE IF NOT EXISTS status
(`identifier` text UNIQUE, `status` text, PRIMARY KEY (`identifier`));""")
return statusDatabase
|
<commit_before>from __future__ import unicode_literals
import os
import logging
from . import helper
def readStatus(config, student):
student = student.lower()
path = config("attachment_path")
if not os.path.exists(path):
return
path = os.path.join(path, student)
if not os.path.exists(path):
return "Student ohne Abgabe"
path = os.path.join(path, "korrekturstatus.txt")
if not os.path.exists(path):
return "Unbearbeitet"
statusfile = open(path, "r")
status = statusfile.read()
statusfile.close()
return status
def writeStatus(config, student, status):
student = student.lower()
status = status.lower()
path = os.path.join(config("attachment_path"), student)
if not os.path.exists(path):
logging.error("Requested student '%s' hasn't submitted anything yet.")
return
path = os.path.join(path, "korrekturstatus.txt")
with open(path, "w") as statusfile:
statusfile.write(status)
<commit_msg>Move status to database instead of status file (server side)<commit_after>
|
from __future__ import unicode_literals
import os
import logging
import sqlite3
from . import helper
def readStatus(config, student):
database = getStatusTable(config)
cursor = database.cursor()
cursor.execute("SELECT status FROM status WHERE identifier = ?", (student,))
statusRow = cursor.fetchone()[0] # just get first status
if statusRow:
return statusRow
else:
return "Unbearbeitet"
def writeStatus(config, student, status):
database = getStatusTable(config)
cursor = database.cursor()
# Check if we need to create a new row first
cursor.execute("SELECT status FROM status WHERE identifier = ?", (student,))
statusRow = cursor.fetchone()[0]
if statusRow:
cursor.execute("UPDATE status SET status = ? WHERE identifier = ?", (status, student,))
else:
cursor.execute("INSERT INTO status VALUES(?, ?)", (student, status, ))
database.commit()
def getStatusTable(config):
statusDatabasePath = config("database_path")
statusDatabase = sqlite3.connect(statusDatabasePath)
cursor = statusDatabase.cursor()
cursor.execute("""CREATE TABLE IF NOT EXISTS status
(`identifier` text UNIQUE, `status` text, PRIMARY KEY (`identifier`));""")
return statusDatabase
|
from __future__ import unicode_literals
import os
import logging
from . import helper
def readStatus(config, student):
student = student.lower()
path = config("attachment_path")
if not os.path.exists(path):
return
path = os.path.join(path, student)
if not os.path.exists(path):
return "Student ohne Abgabe"
path = os.path.join(path, "korrekturstatus.txt")
if not os.path.exists(path):
return "Unbearbeitet"
statusfile = open(path, "r")
status = statusfile.read()
statusfile.close()
return status
def writeStatus(config, student, status):
student = student.lower()
status = status.lower()
path = os.path.join(config("attachment_path"), student)
if not os.path.exists(path):
logging.error("Requested student '%s' hasn't submitted anything yet.")
return
path = os.path.join(path, "korrekturstatus.txt")
with open(path, "w") as statusfile:
statusfile.write(status)
Move status to database instead of status file (server side)from __future__ import unicode_literals
import os
import logging
import sqlite3
from . import helper
def readStatus(config, student):
database = getStatusTable(config)
cursor = database.cursor()
cursor.execute("SELECT status FROM status WHERE identifier = ?", (student,))
statusRow = cursor.fetchone()[0] # just get first status
if statusRow:
return statusRow
else:
return "Unbearbeitet"
def writeStatus(config, student, status):
database = getStatusTable(config)
cursor = database.cursor()
# Check if we need to create a new row first
cursor.execute("SELECT status FROM status WHERE identifier = ?", (student,))
statusRow = cursor.fetchone()[0]
if statusRow:
cursor.execute("UPDATE status SET status = ? WHERE identifier = ?", (status, student,))
else:
cursor.execute("INSERT INTO status VALUES(?, ?)", (student, status, ))
database.commit()
def getStatusTable(config):
statusDatabasePath = config("database_path")
statusDatabase = sqlite3.connect(statusDatabasePath)
cursor = statusDatabase.cursor()
cursor.execute("""CREATE TABLE IF NOT EXISTS status
(`identifier` text UNIQUE, `status` text, PRIMARY KEY (`identifier`));""")
return statusDatabase
|
<commit_before>from __future__ import unicode_literals
import os
import logging
from . import helper
def readStatus(config, student):
student = student.lower()
path = config("attachment_path")
if not os.path.exists(path):
return
path = os.path.join(path, student)
if not os.path.exists(path):
return "Student ohne Abgabe"
path = os.path.join(path, "korrekturstatus.txt")
if not os.path.exists(path):
return "Unbearbeitet"
statusfile = open(path, "r")
status = statusfile.read()
statusfile.close()
return status
def writeStatus(config, student, status):
student = student.lower()
status = status.lower()
path = os.path.join(config("attachment_path"), student)
if not os.path.exists(path):
logging.error("Requested student '%s' hasn't submitted anything yet.")
return
path = os.path.join(path, "korrekturstatus.txt")
with open(path, "w") as statusfile:
statusfile.write(status)
<commit_msg>Move status to database instead of status file (server side)<commit_after>from __future__ import unicode_literals
import os
import logging
import sqlite3
from . import helper
def readStatus(config, student):
database = getStatusTable(config)
cursor = database.cursor()
cursor.execute("SELECT status FROM status WHERE identifier = ?", (student,))
statusRow = cursor.fetchone()[0] # just get first status
if statusRow:
return statusRow
else:
return "Unbearbeitet"
def writeStatus(config, student, status):
database = getStatusTable(config)
cursor = database.cursor()
# Check if we need to create a new row first
cursor.execute("SELECT status FROM status WHERE identifier = ?", (student,))
statusRow = cursor.fetchone()[0]
if statusRow:
cursor.execute("UPDATE status SET status = ? WHERE identifier = ?", (status, student,))
else:
cursor.execute("INSERT INTO status VALUES(?, ?)", (student, status, ))
database.commit()
def getStatusTable(config):
statusDatabasePath = config("database_path")
statusDatabase = sqlite3.connect(statusDatabasePath)
cursor = statusDatabase.cursor()
cursor.execute("""CREATE TABLE IF NOT EXISTS status
(`identifier` text UNIQUE, `status` text, PRIMARY KEY (`identifier`));""")
return statusDatabase
|
3ec3948dfde67c15204964d35c2df1c60e7706a1
|
rwt/tests/test_scripts.py
|
rwt/tests/test_scripts.py
|
from __future__ import unicode_literals
import textwrap
import sys
import subprocess
from rwt import scripts
def test_pkg_imported(tmpdir):
"""
Create a script that loads cython and ensure it runs.
"""
body = textwrap.dedent("""
import cython
print("Successfully imported cython")
""").lstrip()
script_file = tmpdir / 'script'
script_file.write_text(body, 'utf-8')
pip_args = ['cython']
cmd = [sys.executable, '-m', 'rwt'] + pip_args + ['--', str(script_file)]
out = subprocess.check_output(cmd, universal_newlines=True)
assert 'Successfully imported cython' in out
class TestDepsReader:
def test_reads_files_with_attribute_assignment(self):
script = textwrap.dedent('''
__requires__=['foo']
x.a = 'bar'
''')
assert scripts.DepsReader(script).read() == ['foo']
|
from __future__ import unicode_literals
import textwrap
import sys
import subprocess
from rwt import scripts
def test_pkg_imported(tmpdir):
"""
Create a script that loads cython and ensure it runs.
"""
body = textwrap.dedent("""
import cython
print("Successfully imported cython")
""").lstrip()
script_file = tmpdir / 'script'
script_file.write_text(body, 'utf-8')
pip_args = ['cython']
cmd = [sys.executable, '-m', 'rwt'] + pip_args + ['--', str(script_file)]
out = subprocess.check_output(cmd, universal_newlines=True)
assert 'Successfully imported cython' in out
class TestDepsReader:
def test_reads_files_with_attribute_assignment(self):
script = textwrap.dedent('''
__requires__=['foo']
x.a = 'bar'
''')
assert scripts.DepsReader(script).read() == ['foo']
def test_reads_files_with_multiple_assignment(self):
script = textwrap.dedent('''
__requires__=['foo']
x, a = [a, x]
''')
assert scripts.DepsReader(script).read() == ['foo']
|
Add another test demonstrating that multiple assignment doesn't affect __requires__ parsing.
|
Add another test demonstrating that multiple assignment doesn't affect __requires__ parsing.
|
Python
|
mit
|
jaraco/rwt
|
from __future__ import unicode_literals
import textwrap
import sys
import subprocess
from rwt import scripts
def test_pkg_imported(tmpdir):
"""
Create a script that loads cython and ensure it runs.
"""
body = textwrap.dedent("""
import cython
print("Successfully imported cython")
""").lstrip()
script_file = tmpdir / 'script'
script_file.write_text(body, 'utf-8')
pip_args = ['cython']
cmd = [sys.executable, '-m', 'rwt'] + pip_args + ['--', str(script_file)]
out = subprocess.check_output(cmd, universal_newlines=True)
assert 'Successfully imported cython' in out
class TestDepsReader:
def test_reads_files_with_attribute_assignment(self):
script = textwrap.dedent('''
__requires__=['foo']
x.a = 'bar'
''')
assert scripts.DepsReader(script).read() == ['foo']
Add another test demonstrating that multiple assignment doesn't affect __requires__ parsing.
|
from __future__ import unicode_literals
import textwrap
import sys
import subprocess
from rwt import scripts
def test_pkg_imported(tmpdir):
"""
Create a script that loads cython and ensure it runs.
"""
body = textwrap.dedent("""
import cython
print("Successfully imported cython")
""").lstrip()
script_file = tmpdir / 'script'
script_file.write_text(body, 'utf-8')
pip_args = ['cython']
cmd = [sys.executable, '-m', 'rwt'] + pip_args + ['--', str(script_file)]
out = subprocess.check_output(cmd, universal_newlines=True)
assert 'Successfully imported cython' in out
class TestDepsReader:
def test_reads_files_with_attribute_assignment(self):
script = textwrap.dedent('''
__requires__=['foo']
x.a = 'bar'
''')
assert scripts.DepsReader(script).read() == ['foo']
def test_reads_files_with_multiple_assignment(self):
script = textwrap.dedent('''
__requires__=['foo']
x, a = [a, x]
''')
assert scripts.DepsReader(script).read() == ['foo']
|
<commit_before>from __future__ import unicode_literals
import textwrap
import sys
import subprocess
from rwt import scripts
def test_pkg_imported(tmpdir):
"""
Create a script that loads cython and ensure it runs.
"""
body = textwrap.dedent("""
import cython
print("Successfully imported cython")
""").lstrip()
script_file = tmpdir / 'script'
script_file.write_text(body, 'utf-8')
pip_args = ['cython']
cmd = [sys.executable, '-m', 'rwt'] + pip_args + ['--', str(script_file)]
out = subprocess.check_output(cmd, universal_newlines=True)
assert 'Successfully imported cython' in out
class TestDepsReader:
def test_reads_files_with_attribute_assignment(self):
script = textwrap.dedent('''
__requires__=['foo']
x.a = 'bar'
''')
assert scripts.DepsReader(script).read() == ['foo']
<commit_msg>Add another test demonstrating that multiple assignment doesn't affect __requires__ parsing.<commit_after>
|
from __future__ import unicode_literals
import textwrap
import sys
import subprocess
from rwt import scripts
def test_pkg_imported(tmpdir):
"""
Create a script that loads cython and ensure it runs.
"""
body = textwrap.dedent("""
import cython
print("Successfully imported cython")
""").lstrip()
script_file = tmpdir / 'script'
script_file.write_text(body, 'utf-8')
pip_args = ['cython']
cmd = [sys.executable, '-m', 'rwt'] + pip_args + ['--', str(script_file)]
out = subprocess.check_output(cmd, universal_newlines=True)
assert 'Successfully imported cython' in out
class TestDepsReader:
def test_reads_files_with_attribute_assignment(self):
script = textwrap.dedent('''
__requires__=['foo']
x.a = 'bar'
''')
assert scripts.DepsReader(script).read() == ['foo']
def test_reads_files_with_multiple_assignment(self):
script = textwrap.dedent('''
__requires__=['foo']
x, a = [a, x]
''')
assert scripts.DepsReader(script).read() == ['foo']
|
from __future__ import unicode_literals
import textwrap
import sys
import subprocess
from rwt import scripts
def test_pkg_imported(tmpdir):
"""
Create a script that loads cython and ensure it runs.
"""
body = textwrap.dedent("""
import cython
print("Successfully imported cython")
""").lstrip()
script_file = tmpdir / 'script'
script_file.write_text(body, 'utf-8')
pip_args = ['cython']
cmd = [sys.executable, '-m', 'rwt'] + pip_args + ['--', str(script_file)]
out = subprocess.check_output(cmd, universal_newlines=True)
assert 'Successfully imported cython' in out
class TestDepsReader:
def test_reads_files_with_attribute_assignment(self):
script = textwrap.dedent('''
__requires__=['foo']
x.a = 'bar'
''')
assert scripts.DepsReader(script).read() == ['foo']
Add another test demonstrating that multiple assignment doesn't affect __requires__ parsing.from __future__ import unicode_literals
import textwrap
import sys
import subprocess
from rwt import scripts
def test_pkg_imported(tmpdir):
"""
Create a script that loads cython and ensure it runs.
"""
body = textwrap.dedent("""
import cython
print("Successfully imported cython")
""").lstrip()
script_file = tmpdir / 'script'
script_file.write_text(body, 'utf-8')
pip_args = ['cython']
cmd = [sys.executable, '-m', 'rwt'] + pip_args + ['--', str(script_file)]
out = subprocess.check_output(cmd, universal_newlines=True)
assert 'Successfully imported cython' in out
class TestDepsReader:
def test_reads_files_with_attribute_assignment(self):
script = textwrap.dedent('''
__requires__=['foo']
x.a = 'bar'
''')
assert scripts.DepsReader(script).read() == ['foo']
def test_reads_files_with_multiple_assignment(self):
script = textwrap.dedent('''
__requires__=['foo']
x, a = [a, x]
''')
assert scripts.DepsReader(script).read() == ['foo']
|
<commit_before>from __future__ import unicode_literals
import textwrap
import sys
import subprocess
from rwt import scripts
def test_pkg_imported(tmpdir):
"""
Create a script that loads cython and ensure it runs.
"""
body = textwrap.dedent("""
import cython
print("Successfully imported cython")
""").lstrip()
script_file = tmpdir / 'script'
script_file.write_text(body, 'utf-8')
pip_args = ['cython']
cmd = [sys.executable, '-m', 'rwt'] + pip_args + ['--', str(script_file)]
out = subprocess.check_output(cmd, universal_newlines=True)
assert 'Successfully imported cython' in out
class TestDepsReader:
def test_reads_files_with_attribute_assignment(self):
script = textwrap.dedent('''
__requires__=['foo']
x.a = 'bar'
''')
assert scripts.DepsReader(script).read() == ['foo']
<commit_msg>Add another test demonstrating that multiple assignment doesn't affect __requires__ parsing.<commit_after>from __future__ import unicode_literals
import textwrap
import sys
import subprocess
from rwt import scripts
def test_pkg_imported(tmpdir):
"""
Create a script that loads cython and ensure it runs.
"""
body = textwrap.dedent("""
import cython
print("Successfully imported cython")
""").lstrip()
script_file = tmpdir / 'script'
script_file.write_text(body, 'utf-8')
pip_args = ['cython']
cmd = [sys.executable, '-m', 'rwt'] + pip_args + ['--', str(script_file)]
out = subprocess.check_output(cmd, universal_newlines=True)
assert 'Successfully imported cython' in out
class TestDepsReader:
def test_reads_files_with_attribute_assignment(self):
script = textwrap.dedent('''
__requires__=['foo']
x.a = 'bar'
''')
assert scripts.DepsReader(script).read() == ['foo']
def test_reads_files_with_multiple_assignment(self):
script = textwrap.dedent('''
__requires__=['foo']
x, a = [a, x]
''')
assert scripts.DepsReader(script).read() == ['foo']
|
0bd3fd319440a326277a021a0f1cf7324450407a
|
lava_scheduler_app/urls.py
|
lava_scheduler_app/urls.py
|
from django.conf.urls.defaults import url, patterns
urlpatterns = patterns(
'lava_scheduler_app.views',
url(r'index$', 'index'))
|
from django.conf.urls.defaults import url, patterns
urlpatterns = patterns(
'lava_scheduler_app.views',
url(r'$', 'index'))
|
Make /lava-server/scheduler/ be a valid URL
|
Make /lava-server/scheduler/ be a valid URL
|
Python
|
agpl-3.0
|
OSSystems/lava-server,Linaro/lava-server,Linaro/lava-server,OSSystems/lava-server,Linaro/lava-server,OSSystems/lava-server,Linaro/lava-server
|
from django.conf.urls.defaults import url, patterns
urlpatterns = patterns(
'lava_scheduler_app.views',
url(r'index$', 'index'))
Make /lava-server/scheduler/ be a valid URL
|
from django.conf.urls.defaults import url, patterns
urlpatterns = patterns(
'lava_scheduler_app.views',
url(r'$', 'index'))
|
<commit_before>from django.conf.urls.defaults import url, patterns
urlpatterns = patterns(
'lava_scheduler_app.views',
url(r'index$', 'index'))
<commit_msg>Make /lava-server/scheduler/ be a valid URL<commit_after>
|
from django.conf.urls.defaults import url, patterns
urlpatterns = patterns(
'lava_scheduler_app.views',
url(r'$', 'index'))
|
from django.conf.urls.defaults import url, patterns
urlpatterns = patterns(
'lava_scheduler_app.views',
url(r'index$', 'index'))
Make /lava-server/scheduler/ be a valid URLfrom django.conf.urls.defaults import url, patterns
urlpatterns = patterns(
'lava_scheduler_app.views',
url(r'$', 'index'))
|
<commit_before>from django.conf.urls.defaults import url, patterns
urlpatterns = patterns(
'lava_scheduler_app.views',
url(r'index$', 'index'))
<commit_msg>Make /lava-server/scheduler/ be a valid URL<commit_after>from django.conf.urls.defaults import url, patterns
urlpatterns = patterns(
'lava_scheduler_app.views',
url(r'$', 'index'))
|
5444e755e819004b4da6560d5a6caad2d9993945
|
klustakwik2/scripts.py
|
klustakwik2/scripts.py
|
'''
Utilities for scripts
'''
import sys
__all__ = ['parse_args']
def parse_args(num_args, allowed_params, msg, string_args=set()):
msg += '\nAllowed arguments and default values:\n'
for k, v in allowed_params.iteritems():
msg += '\n %s = %s' % (k, v)
if len(sys.argv)<=num_args:
print msg
exit(1)
params = {}
for spec in sys.argv[num_args+1:]:
name, val = spec.split('=')
if name not in string_args:
val = eval(val)
params[name] = val
for k in params.keys():
if k not in allowed_params:
print msg
exit(1)
for k, v in allowed_params.iteritems():
if k not in params:
params[k] = v
return sys.argv[1:num_args+1], params
|
'''
Utilities for scripts
'''
import sys
__all__ = ['parse_args']
def parse_args(num_args, allowed_params, msg, string_args=set()):
msg += '\nAllowed arguments and default values:\n'
for k, v in allowed_params.iteritems():
msg += '\n %s = %s' % (k, v)
if len(sys.argv)<=num_args:
print msg
exit(1)
params = {}
for spec in sys.argv[num_args+1:]:
name, val = spec.split('=')
if name not in string_args:
if val.lower()=='true':
val = 'True'
elif val.lower()=='false':
val = 'False'
val = eval(val)
params[name] = val
for k in params.keys():
if k not in allowed_params:
print msg
exit(1)
for k, v in allowed_params.iteritems():
if k not in params:
params[k] = v
return sys.argv[1:num_args+1], params
|
Handle true/false as well as True/False arguments
|
Handle true/false as well as True/False arguments
|
Python
|
bsd-3-clause
|
kwikteam/klustakwik2,benvermaercke/klustakwik2
|
'''
Utilities for scripts
'''
import sys
__all__ = ['parse_args']
def parse_args(num_args, allowed_params, msg, string_args=set()):
msg += '\nAllowed arguments and default values:\n'
for k, v in allowed_params.iteritems():
msg += '\n %s = %s' % (k, v)
if len(sys.argv)<=num_args:
print msg
exit(1)
params = {}
for spec in sys.argv[num_args+1:]:
name, val = spec.split('=')
if name not in string_args:
val = eval(val)
params[name] = val
for k in params.keys():
if k not in allowed_params:
print msg
exit(1)
for k, v in allowed_params.iteritems():
if k not in params:
params[k] = v
return sys.argv[1:num_args+1], params
Handle true/false as well as True/False arguments
|
'''
Utilities for scripts
'''
import sys
__all__ = ['parse_args']
def parse_args(num_args, allowed_params, msg, string_args=set()):
msg += '\nAllowed arguments and default values:\n'
for k, v in allowed_params.iteritems():
msg += '\n %s = %s' % (k, v)
if len(sys.argv)<=num_args:
print msg
exit(1)
params = {}
for spec in sys.argv[num_args+1:]:
name, val = spec.split('=')
if name not in string_args:
if val.lower()=='true':
val = 'True'
elif val.lower()=='false':
val = 'False'
val = eval(val)
params[name] = val
for k in params.keys():
if k not in allowed_params:
print msg
exit(1)
for k, v in allowed_params.iteritems():
if k not in params:
params[k] = v
return sys.argv[1:num_args+1], params
|
<commit_before>'''
Utilities for scripts
'''
import sys
__all__ = ['parse_args']
def parse_args(num_args, allowed_params, msg, string_args=set()):
msg += '\nAllowed arguments and default values:\n'
for k, v in allowed_params.iteritems():
msg += '\n %s = %s' % (k, v)
if len(sys.argv)<=num_args:
print msg
exit(1)
params = {}
for spec in sys.argv[num_args+1:]:
name, val = spec.split('=')
if name not in string_args:
val = eval(val)
params[name] = val
for k in params.keys():
if k not in allowed_params:
print msg
exit(1)
for k, v in allowed_params.iteritems():
if k not in params:
params[k] = v
return sys.argv[1:num_args+1], params
<commit_msg>Handle true/false as well as True/False arguments<commit_after>
|
'''
Utilities for scripts
'''
import sys
__all__ = ['parse_args']
def parse_args(num_args, allowed_params, msg, string_args=set()):
msg += '\nAllowed arguments and default values:\n'
for k, v in allowed_params.iteritems():
msg += '\n %s = %s' % (k, v)
if len(sys.argv)<=num_args:
print msg
exit(1)
params = {}
for spec in sys.argv[num_args+1:]:
name, val = spec.split('=')
if name not in string_args:
if val.lower()=='true':
val = 'True'
elif val.lower()=='false':
val = 'False'
val = eval(val)
params[name] = val
for k in params.keys():
if k not in allowed_params:
print msg
exit(1)
for k, v in allowed_params.iteritems():
if k not in params:
params[k] = v
return sys.argv[1:num_args+1], params
|
'''
Utilities for scripts
'''
import sys
__all__ = ['parse_args']
def parse_args(num_args, allowed_params, msg, string_args=set()):
msg += '\nAllowed arguments and default values:\n'
for k, v in allowed_params.iteritems():
msg += '\n %s = %s' % (k, v)
if len(sys.argv)<=num_args:
print msg
exit(1)
params = {}
for spec in sys.argv[num_args+1:]:
name, val = spec.split('=')
if name not in string_args:
val = eval(val)
params[name] = val
for k in params.keys():
if k not in allowed_params:
print msg
exit(1)
for k, v in allowed_params.iteritems():
if k not in params:
params[k] = v
return sys.argv[1:num_args+1], params
Handle true/false as well as True/False arguments'''
Utilities for scripts
'''
import sys
__all__ = ['parse_args']
def parse_args(num_args, allowed_params, msg, string_args=set()):
msg += '\nAllowed arguments and default values:\n'
for k, v in allowed_params.iteritems():
msg += '\n %s = %s' % (k, v)
if len(sys.argv)<=num_args:
print msg
exit(1)
params = {}
for spec in sys.argv[num_args+1:]:
name, val = spec.split('=')
if name not in string_args:
if val.lower()=='true':
val = 'True'
elif val.lower()=='false':
val = 'False'
val = eval(val)
params[name] = val
for k in params.keys():
if k not in allowed_params:
print msg
exit(1)
for k, v in allowed_params.iteritems():
if k not in params:
params[k] = v
return sys.argv[1:num_args+1], params
|
<commit_before>'''
Utilities for scripts
'''
import sys
__all__ = ['parse_args']
def parse_args(num_args, allowed_params, msg, string_args=set()):
msg += '\nAllowed arguments and default values:\n'
for k, v in allowed_params.iteritems():
msg += '\n %s = %s' % (k, v)
if len(sys.argv)<=num_args:
print msg
exit(1)
params = {}
for spec in sys.argv[num_args+1:]:
name, val = spec.split('=')
if name not in string_args:
val = eval(val)
params[name] = val
for k in params.keys():
if k not in allowed_params:
print msg
exit(1)
for k, v in allowed_params.iteritems():
if k not in params:
params[k] = v
return sys.argv[1:num_args+1], params
<commit_msg>Handle true/false as well as True/False arguments<commit_after>'''
Utilities for scripts
'''
import sys
__all__ = ['parse_args']
def parse_args(num_args, allowed_params, msg, string_args=set()):
msg += '\nAllowed arguments and default values:\n'
for k, v in allowed_params.iteritems():
msg += '\n %s = %s' % (k, v)
if len(sys.argv)<=num_args:
print msg
exit(1)
params = {}
for spec in sys.argv[num_args+1:]:
name, val = spec.split('=')
if name not in string_args:
if val.lower()=='true':
val = 'True'
elif val.lower()=='false':
val = 'False'
val = eval(val)
params[name] = val
for k in params.keys():
if k not in allowed_params:
print msg
exit(1)
for k, v in allowed_params.iteritems():
if k not in params:
params[k] = v
return sys.argv[1:num_args+1], params
|
cb334d281df315b59f9413a59be1289a7314cb68
|
src/load_remote_data.py
|
src/load_remote_data.py
|
#!/usr/bin/env python
import os
import requests
# local configuration
remote_data_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'data', 'remote')
# URLs at which data can be found
csv_url_summary_stats = 'http://dashboard.iatistandard.org/summary_stats.csv'
csv_url_humanitarian_stats = 'http://dashboard.iatistandard.org/humanitarian.csv'
with open(os.path.join(remote_data_path, 'summary_stats.csv'), 'wb') as f:
# load the data to write to the file
# TODO: Add error handling - URL loading
response = requests.get(csv_url_summary_stats)
if not response.ok:
print('There was a problem loading the Summary Statistics data')
# TODO: Add error handling - file writing
f.write(response.text.encode('utf-8'))
with open(os.path.join(remote_data_path, 'humanitarian.csv'), 'wb') as f:
# load the data to write to the file
# TODO: Add error handling - URL loading
response = requests.get(csv_url_humanitarian_stats)
if not response.ok:
print('There was a problem loading the Summary Statistics data')
# TODO: Add error handling - file writing
f.write(response.text.encode('utf-8'))
# TODO: Add mention of __main__ and main()
|
#!/usr/bin/env python
import os
import requests
# local configuration
remote_data_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'data', 'remote')
# URLs at which data can be found
csv_url_summary_stats = 'http://dashboard.iatistandard.org/summary_stats.csv'
csv_url_humanitarian_stats = 'http://dev.dashboard.iatistandard.org/humanitarian.csv'
with open(os.path.join(remote_data_path, 'summary_stats.csv'), 'wb') as f:
# load the data to write to the file
# TODO: Add error handling - URL loading
response = requests.get(csv_url_summary_stats)
if not response.ok:
print('There was a problem loading the Summary Statistics data')
# TODO: Add error handling - file writing
f.write(response.text.encode('utf-8'))
with open(os.path.join(remote_data_path, 'humanitarian.csv'), 'wb') as f:
# load the data to write to the file
# TODO: Add error handling - URL loading
response = requests.get(csv_url_humanitarian_stats)
if not response.ok:
print('There was a problem loading the Humanitarian Statistics data')
# TODO: Add error handling - file writing
f.write(response.text.encode('utf-8'))
# TODO: Add mention of __main__ and main()
|
Set a URL to download the humanitarian CSV from
|
Set a URL to download the humanitarian CSV from
and fix a copypaste error
|
Python
|
mit
|
devinit/grand-bargain-monitoring,devinit/grand-bargain-monitoring,devinit/grand-bargain-monitoring
|
#!/usr/bin/env python
import os
import requests
# local configuration
remote_data_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'data', 'remote')
# URLs at which data can be found
csv_url_summary_stats = 'http://dashboard.iatistandard.org/summary_stats.csv'
csv_url_humanitarian_stats = 'http://dashboard.iatistandard.org/humanitarian.csv'
with open(os.path.join(remote_data_path, 'summary_stats.csv'), 'wb') as f:
# load the data to write to the file
# TODO: Add error handling - URL loading
response = requests.get(csv_url_summary_stats)
if not response.ok:
print('There was a problem loading the Summary Statistics data')
# TODO: Add error handling - file writing
f.write(response.text.encode('utf-8'))
with open(os.path.join(remote_data_path, 'humanitarian.csv'), 'wb') as f:
# load the data to write to the file
# TODO: Add error handling - URL loading
response = requests.get(csv_url_humanitarian_stats)
if not response.ok:
print('There was a problem loading the Summary Statistics data')
# TODO: Add error handling - file writing
f.write(response.text.encode('utf-8'))
# TODO: Add mention of __main__ and main()
Set a URL to download the humanitarian CSV from
and fix a copypaste error
|
#!/usr/bin/env python
import os
import requests
# local configuration
remote_data_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'data', 'remote')
# URLs at which data can be found
csv_url_summary_stats = 'http://dashboard.iatistandard.org/summary_stats.csv'
csv_url_humanitarian_stats = 'http://dev.dashboard.iatistandard.org/humanitarian.csv'
with open(os.path.join(remote_data_path, 'summary_stats.csv'), 'wb') as f:
# load the data to write to the file
# TODO: Add error handling - URL loading
response = requests.get(csv_url_summary_stats)
if not response.ok:
print('There was a problem loading the Summary Statistics data')
# TODO: Add error handling - file writing
f.write(response.text.encode('utf-8'))
with open(os.path.join(remote_data_path, 'humanitarian.csv'), 'wb') as f:
# load the data to write to the file
# TODO: Add error handling - URL loading
response = requests.get(csv_url_humanitarian_stats)
if not response.ok:
print('There was a problem loading the Humanitarian Statistics data')
# TODO: Add error handling - file writing
f.write(response.text.encode('utf-8'))
# TODO: Add mention of __main__ and main()
|
<commit_before>#!/usr/bin/env python
import os
import requests
# local configuration
remote_data_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'data', 'remote')
# URLs at which data can be found
csv_url_summary_stats = 'http://dashboard.iatistandard.org/summary_stats.csv'
csv_url_humanitarian_stats = 'http://dashboard.iatistandard.org/humanitarian.csv'
with open(os.path.join(remote_data_path, 'summary_stats.csv'), 'wb') as f:
# load the data to write to the file
# TODO: Add error handling - URL loading
response = requests.get(csv_url_summary_stats)
if not response.ok:
print('There was a problem loading the Summary Statistics data')
# TODO: Add error handling - file writing
f.write(response.text.encode('utf-8'))
with open(os.path.join(remote_data_path, 'humanitarian.csv'), 'wb') as f:
# load the data to write to the file
# TODO: Add error handling - URL loading
response = requests.get(csv_url_humanitarian_stats)
if not response.ok:
print('There was a problem loading the Summary Statistics data')
# TODO: Add error handling - file writing
f.write(response.text.encode('utf-8'))
# TODO: Add mention of __main__ and main()
<commit_msg>Set a URL to download the humanitarian CSV from
and fix a copypaste error<commit_after>
|
#!/usr/bin/env python
import os
import requests
# local configuration
remote_data_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'data', 'remote')
# URLs at which data can be found
csv_url_summary_stats = 'http://dashboard.iatistandard.org/summary_stats.csv'
csv_url_humanitarian_stats = 'http://dev.dashboard.iatistandard.org/humanitarian.csv'
with open(os.path.join(remote_data_path, 'summary_stats.csv'), 'wb') as f:
# load the data to write to the file
# TODO: Add error handling - URL loading
response = requests.get(csv_url_summary_stats)
if not response.ok:
print('There was a problem loading the Summary Statistics data')
# TODO: Add error handling - file writing
f.write(response.text.encode('utf-8'))
with open(os.path.join(remote_data_path, 'humanitarian.csv'), 'wb') as f:
# load the data to write to the file
# TODO: Add error handling - URL loading
response = requests.get(csv_url_humanitarian_stats)
if not response.ok:
print('There was a problem loading the Humanitarian Statistics data')
# TODO: Add error handling - file writing
f.write(response.text.encode('utf-8'))
# TODO: Add mention of __main__ and main()
|
#!/usr/bin/env python
import os
import requests
# local configuration
remote_data_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'data', 'remote')
# URLs at which data can be found
csv_url_summary_stats = 'http://dashboard.iatistandard.org/summary_stats.csv'
csv_url_humanitarian_stats = 'http://dashboard.iatistandard.org/humanitarian.csv'
with open(os.path.join(remote_data_path, 'summary_stats.csv'), 'wb') as f:
# load the data to write to the file
# TODO: Add error handling - URL loading
response = requests.get(csv_url_summary_stats)
if not response.ok:
print('There was a problem loading the Summary Statistics data')
# TODO: Add error handling - file writing
f.write(response.text.encode('utf-8'))
with open(os.path.join(remote_data_path, 'humanitarian.csv'), 'wb') as f:
# load the data to write to the file
# TODO: Add error handling - URL loading
response = requests.get(csv_url_humanitarian_stats)
if not response.ok:
print('There was a problem loading the Summary Statistics data')
# TODO: Add error handling - file writing
f.write(response.text.encode('utf-8'))
# TODO: Add mention of __main__ and main()
Set a URL to download the humanitarian CSV from
and fix a copypaste error#!/usr/bin/env python
import os
import requests
# local configuration
remote_data_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'data', 'remote')
# URLs at which data can be found
csv_url_summary_stats = 'http://dashboard.iatistandard.org/summary_stats.csv'
csv_url_humanitarian_stats = 'http://dev.dashboard.iatistandard.org/humanitarian.csv'
with open(os.path.join(remote_data_path, 'summary_stats.csv'), 'wb') as f:
# load the data to write to the file
# TODO: Add error handling - URL loading
response = requests.get(csv_url_summary_stats)
if not response.ok:
print('There was a problem loading the Summary Statistics data')
# TODO: Add error handling - file writing
f.write(response.text.encode('utf-8'))
with open(os.path.join(remote_data_path, 'humanitarian.csv'), 'wb') as f:
# load the data to write to the file
# TODO: Add error handling - URL loading
response = requests.get(csv_url_humanitarian_stats)
if not response.ok:
print('There was a problem loading the Humanitarian Statistics data')
# TODO: Add error handling - file writing
f.write(response.text.encode('utf-8'))
# TODO: Add mention of __main__ and main()
|
<commit_before>#!/usr/bin/env python
import os
import requests
# local configuration
remote_data_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'data', 'remote')
# URLs at which data can be found
csv_url_summary_stats = 'http://dashboard.iatistandard.org/summary_stats.csv'
csv_url_humanitarian_stats = 'http://dashboard.iatistandard.org/humanitarian.csv'
with open(os.path.join(remote_data_path, 'summary_stats.csv'), 'wb') as f:
# load the data to write to the file
# TODO: Add error handling - URL loading
response = requests.get(csv_url_summary_stats)
if not response.ok:
print('There was a problem loading the Summary Statistics data')
# TODO: Add error handling - file writing
f.write(response.text.encode('utf-8'))
with open(os.path.join(remote_data_path, 'humanitarian.csv'), 'wb') as f:
# load the data to write to the file
# TODO: Add error handling - URL loading
response = requests.get(csv_url_humanitarian_stats)
if not response.ok:
print('There was a problem loading the Summary Statistics data')
# TODO: Add error handling - file writing
f.write(response.text.encode('utf-8'))
# TODO: Add mention of __main__ and main()
<commit_msg>Set a URL to download the humanitarian CSV from
and fix a copypaste error<commit_after>#!/usr/bin/env python
import os
import requests
# local configuration
remote_data_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'data', 'remote')
# URLs at which data can be found
csv_url_summary_stats = 'http://dashboard.iatistandard.org/summary_stats.csv'
csv_url_humanitarian_stats = 'http://dev.dashboard.iatistandard.org/humanitarian.csv'
with open(os.path.join(remote_data_path, 'summary_stats.csv'), 'wb') as f:
# load the data to write to the file
# TODO: Add error handling - URL loading
response = requests.get(csv_url_summary_stats)
if not response.ok:
print('There was a problem loading the Summary Statistics data')
# TODO: Add error handling - file writing
f.write(response.text.encode('utf-8'))
with open(os.path.join(remote_data_path, 'humanitarian.csv'), 'wb') as f:
# load the data to write to the file
# TODO: Add error handling - URL loading
response = requests.get(csv_url_humanitarian_stats)
if not response.ok:
print('There was a problem loading the Humanitarian Statistics data')
# TODO: Add error handling - file writing
f.write(response.text.encode('utf-8'))
# TODO: Add mention of __main__ and main()
|
727ec507284776f3eec91b644cd5bb112bdb0af1
|
july/people/forms.py
|
july/people/forms.py
|
from django import forms
class EditUserForm(forms.Form):
about_me = forms.CharField(widget=forms.Textarea, required=False)
url = forms.CharField(max_length=255, required=False)
facebook_url = forms.CharField(max_length=255, required=False)
email = forms.EmailField(max_length=255)
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
super(EditUserForm, self).__init__(*args, **kwargs)
if user:
self.fields['about_me'].initial=user.about_me
self.fields['url'].initial=user.url
self.fields['facebook_url'].initial=user.facebook_url
self.fields['email'].initial=user.email
|
from django import forms
class EditUserForm(forms.Form):
about_me = forms.CharField(widget=forms.Textarea, required=False)
url = forms.CharField(max_length=255, required=False)
facebook_url = forms.CharField(max_length=255, required=False)
email = forms.EmailField(max_length=255)
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
super(EditUserForm, self).__init__(*args, **kwargs)
if user:
self.fields['about_me'].initial=getattr(user, 'about_me', None)
self.fields['url'].initial=getattr(user, 'url', None)
self.fields['facebook_url'].initial=getattr(user, 'facebook_url', None)
self.fields['email'].initial=user.email
|
Use getattr for expando props
|
Use getattr for expando props
|
Python
|
mit
|
julython/julython.org,julython/julython.org,ChimeraCoder/GOctober,julython/julython.org,ChimeraCoder/GOctober,julython/julython.org,ChimeraCoder/GOctober
|
from django import forms
class EditUserForm(forms.Form):
about_me = forms.CharField(widget=forms.Textarea, required=False)
url = forms.CharField(max_length=255, required=False)
facebook_url = forms.CharField(max_length=255, required=False)
email = forms.EmailField(max_length=255)
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
super(EditUserForm, self).__init__(*args, **kwargs)
if user:
self.fields['about_me'].initial=user.about_me
self.fields['url'].initial=user.url
self.fields['facebook_url'].initial=user.facebook_url
self.fields['email'].initial=user.email
Use getattr for expando props
|
from django import forms
class EditUserForm(forms.Form):
about_me = forms.CharField(widget=forms.Textarea, required=False)
url = forms.CharField(max_length=255, required=False)
facebook_url = forms.CharField(max_length=255, required=False)
email = forms.EmailField(max_length=255)
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
super(EditUserForm, self).__init__(*args, **kwargs)
if user:
self.fields['about_me'].initial=getattr(user, 'about_me', None)
self.fields['url'].initial=getattr(user, 'url', None)
self.fields['facebook_url'].initial=getattr(user, 'facebook_url', None)
self.fields['email'].initial=user.email
|
<commit_before>from django import forms
class EditUserForm(forms.Form):
about_me = forms.CharField(widget=forms.Textarea, required=False)
url = forms.CharField(max_length=255, required=False)
facebook_url = forms.CharField(max_length=255, required=False)
email = forms.EmailField(max_length=255)
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
super(EditUserForm, self).__init__(*args, **kwargs)
if user:
self.fields['about_me'].initial=user.about_me
self.fields['url'].initial=user.url
self.fields['facebook_url'].initial=user.facebook_url
self.fields['email'].initial=user.email
<commit_msg>Use getattr for expando props<commit_after>
|
from django import forms
class EditUserForm(forms.Form):
about_me = forms.CharField(widget=forms.Textarea, required=False)
url = forms.CharField(max_length=255, required=False)
facebook_url = forms.CharField(max_length=255, required=False)
email = forms.EmailField(max_length=255)
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
super(EditUserForm, self).__init__(*args, **kwargs)
if user:
self.fields['about_me'].initial=getattr(user, 'about_me', None)
self.fields['url'].initial=getattr(user, 'url', None)
self.fields['facebook_url'].initial=getattr(user, 'facebook_url', None)
self.fields['email'].initial=user.email
|
from django import forms
class EditUserForm(forms.Form):
about_me = forms.CharField(widget=forms.Textarea, required=False)
url = forms.CharField(max_length=255, required=False)
facebook_url = forms.CharField(max_length=255, required=False)
email = forms.EmailField(max_length=255)
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
super(EditUserForm, self).__init__(*args, **kwargs)
if user:
self.fields['about_me'].initial=user.about_me
self.fields['url'].initial=user.url
self.fields['facebook_url'].initial=user.facebook_url
self.fields['email'].initial=user.email
Use getattr for expando propsfrom django import forms
class EditUserForm(forms.Form):
about_me = forms.CharField(widget=forms.Textarea, required=False)
url = forms.CharField(max_length=255, required=False)
facebook_url = forms.CharField(max_length=255, required=False)
email = forms.EmailField(max_length=255)
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
super(EditUserForm, self).__init__(*args, **kwargs)
if user:
self.fields['about_me'].initial=getattr(user, 'about_me', None)
self.fields['url'].initial=getattr(user, 'url', None)
self.fields['facebook_url'].initial=getattr(user, 'facebook_url', None)
self.fields['email'].initial=user.email
|
<commit_before>from django import forms
class EditUserForm(forms.Form):
about_me = forms.CharField(widget=forms.Textarea, required=False)
url = forms.CharField(max_length=255, required=False)
facebook_url = forms.CharField(max_length=255, required=False)
email = forms.EmailField(max_length=255)
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
super(EditUserForm, self).__init__(*args, **kwargs)
if user:
self.fields['about_me'].initial=user.about_me
self.fields['url'].initial=user.url
self.fields['facebook_url'].initial=user.facebook_url
self.fields['email'].initial=user.email
<commit_msg>Use getattr for expando props<commit_after>from django import forms
class EditUserForm(forms.Form):
about_me = forms.CharField(widget=forms.Textarea, required=False)
url = forms.CharField(max_length=255, required=False)
facebook_url = forms.CharField(max_length=255, required=False)
email = forms.EmailField(max_length=255)
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
super(EditUserForm, self).__init__(*args, **kwargs)
if user:
self.fields['about_me'].initial=getattr(user, 'about_me', None)
self.fields['url'].initial=getattr(user, 'url', None)
self.fields['facebook_url'].initial=getattr(user, 'facebook_url', None)
self.fields['email'].initial=user.email
|
d863aaf76d7e1e794f508aeb0f5383f67f463e68
|
ogn/collect/fetchddb.py
|
ogn/collect/fetchddb.py
|
from __future__ import absolute_import
from celery.utils.log import get_task_logger
from ogn.collect.celery import app
from ogn.model import Flarm
from ogn.utils import get_ddb
logger = get_task_logger(__name__)
@app.task
def update_ddb_data():
logger.info("Update ddb data.")
app.session.query(Flarm).delete()
devices = get_ddb()
logger.info("Devices: %s"%str(devices))
app.session.bulk_save_objects(devices)
app.session.commit()
return len(devices)
# TODO: Reimplement.
def import_ddb_data(filename='custom.txt'):
flarms = get_ddb(filename)
db.session.bulk_save_objects(flarms)
session.commit()
|
from __future__ import absolute_import
from celery.utils.log import get_task_logger
from ogn.collect.celery import app
from ogn.model import Flarm
from ogn.utils import get_ddb
logger = get_task_logger(__name__)
@app.task
def update_ddb_data():
logger.info("Update ddb data.")
app.session.query(Flarm).delete()
devices = get_ddb()
logger.debug("New Devices: %s" % str(devices))
app.session.bulk_save_objects(devices)
app.session.commit()
return len(devices)
@app.task
def import_ddb_data(filename='custom.txt'):
logger.info("Import ddb data from file.")
devices = get_ddb(filename)
app.session.bulk_save_objects(devices)
app.session.commit()
return len(devices)
|
Reimplement ddb import from file as celery task.
|
Reimplement ddb import from file as celery task.
|
Python
|
agpl-3.0
|
glidernet/ogn-python,glidernet/ogn-python,Meisterschueler/ogn-python,kerel-fs/ogn-python,glidernet/ogn-python,glidernet/ogn-python,Meisterschueler/ogn-python,Meisterschueler/ogn-python,Meisterschueler/ogn-python
|
from __future__ import absolute_import
from celery.utils.log import get_task_logger
from ogn.collect.celery import app
from ogn.model import Flarm
from ogn.utils import get_ddb
logger = get_task_logger(__name__)
@app.task
def update_ddb_data():
logger.info("Update ddb data.")
app.session.query(Flarm).delete()
devices = get_ddb()
logger.info("Devices: %s"%str(devices))
app.session.bulk_save_objects(devices)
app.session.commit()
return len(devices)
# TODO: Reimplement.
def import_ddb_data(filename='custom.txt'):
flarms = get_ddb(filename)
db.session.bulk_save_objects(flarms)
session.commit()
Reimplement ddb import from file as celery task.
|
from __future__ import absolute_import
from celery.utils.log import get_task_logger
from ogn.collect.celery import app
from ogn.model import Flarm
from ogn.utils import get_ddb
logger = get_task_logger(__name__)
@app.task
def update_ddb_data():
logger.info("Update ddb data.")
app.session.query(Flarm).delete()
devices = get_ddb()
logger.debug("New Devices: %s" % str(devices))
app.session.bulk_save_objects(devices)
app.session.commit()
return len(devices)
@app.task
def import_ddb_data(filename='custom.txt'):
logger.info("Import ddb data from file.")
devices = get_ddb(filename)
app.session.bulk_save_objects(devices)
app.session.commit()
return len(devices)
|
<commit_before>from __future__ import absolute_import
from celery.utils.log import get_task_logger
from ogn.collect.celery import app
from ogn.model import Flarm
from ogn.utils import get_ddb
logger = get_task_logger(__name__)
@app.task
def update_ddb_data():
logger.info("Update ddb data.")
app.session.query(Flarm).delete()
devices = get_ddb()
logger.info("Devices: %s"%str(devices))
app.session.bulk_save_objects(devices)
app.session.commit()
return len(devices)
# TODO: Reimplement.
def import_ddb_data(filename='custom.txt'):
flarms = get_ddb(filename)
db.session.bulk_save_objects(flarms)
session.commit()
<commit_msg>Reimplement ddb import from file as celery task.<commit_after>
|
from __future__ import absolute_import
from celery.utils.log import get_task_logger
from ogn.collect.celery import app
from ogn.model import Flarm
from ogn.utils import get_ddb
logger = get_task_logger(__name__)
@app.task
def update_ddb_data():
logger.info("Update ddb data.")
app.session.query(Flarm).delete()
devices = get_ddb()
logger.debug("New Devices: %s" % str(devices))
app.session.bulk_save_objects(devices)
app.session.commit()
return len(devices)
@app.task
def import_ddb_data(filename='custom.txt'):
logger.info("Import ddb data from file.")
devices = get_ddb(filename)
app.session.bulk_save_objects(devices)
app.session.commit()
return len(devices)
|
from __future__ import absolute_import
from celery.utils.log import get_task_logger
from ogn.collect.celery import app
from ogn.model import Flarm
from ogn.utils import get_ddb
logger = get_task_logger(__name__)
@app.task
def update_ddb_data():
logger.info("Update ddb data.")
app.session.query(Flarm).delete()
devices = get_ddb()
logger.info("Devices: %s"%str(devices))
app.session.bulk_save_objects(devices)
app.session.commit()
return len(devices)
# TODO: Reimplement.
def import_ddb_data(filename='custom.txt'):
flarms = get_ddb(filename)
db.session.bulk_save_objects(flarms)
session.commit()
Reimplement ddb import from file as celery task.from __future__ import absolute_import
from celery.utils.log import get_task_logger
from ogn.collect.celery import app
from ogn.model import Flarm
from ogn.utils import get_ddb
logger = get_task_logger(__name__)
@app.task
def update_ddb_data():
logger.info("Update ddb data.")
app.session.query(Flarm).delete()
devices = get_ddb()
logger.debug("New Devices: %s" % str(devices))
app.session.bulk_save_objects(devices)
app.session.commit()
return len(devices)
@app.task
def import_ddb_data(filename='custom.txt'):
logger.info("Import ddb data from file.")
devices = get_ddb(filename)
app.session.bulk_save_objects(devices)
app.session.commit()
return len(devices)
|
<commit_before>from __future__ import absolute_import
from celery.utils.log import get_task_logger
from ogn.collect.celery import app
from ogn.model import Flarm
from ogn.utils import get_ddb
logger = get_task_logger(__name__)
@app.task
def update_ddb_data():
logger.info("Update ddb data.")
app.session.query(Flarm).delete()
devices = get_ddb()
logger.info("Devices: %s"%str(devices))
app.session.bulk_save_objects(devices)
app.session.commit()
return len(devices)
# TODO: Reimplement.
def import_ddb_data(filename='custom.txt'):
flarms = get_ddb(filename)
db.session.bulk_save_objects(flarms)
session.commit()
<commit_msg>Reimplement ddb import from file as celery task.<commit_after>from __future__ import absolute_import
from celery.utils.log import get_task_logger
from ogn.collect.celery import app
from ogn.model import Flarm
from ogn.utils import get_ddb
logger = get_task_logger(__name__)
@app.task
def update_ddb_data():
logger.info("Update ddb data.")
app.session.query(Flarm).delete()
devices = get_ddb()
logger.debug("New Devices: %s" % str(devices))
app.session.bulk_save_objects(devices)
app.session.commit()
return len(devices)
@app.task
def import_ddb_data(filename='custom.txt'):
logger.info("Import ddb data from file.")
devices = get_ddb(filename)
app.session.bulk_save_objects(devices)
app.session.commit()
return len(devices)
|
2267f31ba91ea649c54a51ab3e8f3babbe72f44e
|
openliveq/collection.py
|
openliveq/collection.py
|
from collections import defaultdict
class Collection(object):
DOC_FROM = ["question_body", "best_answer_body"]
def __init__(self):
'''
Compute the following statistics
df: document frequency
cf: collection frequency
dn: total number of documents
cn: total number of words
'''
self.df = defaultdict(int)
self.cf = defaultdict(int)
self.dn = 0
self.cn = 0
def add(self, wordsets):
'''
Add a question
'''
for label in self.DOC_FROM:
for w in set(wordsets[label].keys()):
self.df[w] += 1
self.cf[w] += wordsets[label][w]
self.cn += wordsets[label][w]
self.dn += 1
|
from collections import defaultdict
class Collection(object):
DOC_FROM = ["question_body", "best_answer_body"]
def __init__(self):
'''
Compute the following statistics
df: document frequency
cf: collection frequency
dn: total number of documents
cn: total number of words
'''
self.df = defaultdict(int)
self.cf = defaultdict(int)
self.dn = 0
self.cn = 0
def add(self, wordsets):
'''
Add a question
'''
for label in self.DOC_FROM:
for w in set(wordsets[label].keys()):
self.df[w] += 1
self.cf[w] += wordsets[label][w]
self.cn += wordsets[label][w]
self.dn += 1
@property
def avgdlen(self):
return float(self.cn) / self.dn
|
Add avddlen property to Collection
|
Add avddlen property to Collection
|
Python
|
mit
|
mpkato/openliveq
|
from collections import defaultdict
class Collection(object):
DOC_FROM = ["question_body", "best_answer_body"]
def __init__(self):
'''
Compute the following statistics
df: document frequency
cf: collection frequency
dn: total number of documents
cn: total number of words
'''
self.df = defaultdict(int)
self.cf = defaultdict(int)
self.dn = 0
self.cn = 0
def add(self, wordsets):
'''
Add a question
'''
for label in self.DOC_FROM:
for w in set(wordsets[label].keys()):
self.df[w] += 1
self.cf[w] += wordsets[label][w]
self.cn += wordsets[label][w]
self.dn += 1
Add avddlen property to Collection
|
from collections import defaultdict
class Collection(object):
DOC_FROM = ["question_body", "best_answer_body"]
def __init__(self):
'''
Compute the following statistics
df: document frequency
cf: collection frequency
dn: total number of documents
cn: total number of words
'''
self.df = defaultdict(int)
self.cf = defaultdict(int)
self.dn = 0
self.cn = 0
def add(self, wordsets):
'''
Add a question
'''
for label in self.DOC_FROM:
for w in set(wordsets[label].keys()):
self.df[w] += 1
self.cf[w] += wordsets[label][w]
self.cn += wordsets[label][w]
self.dn += 1
@property
def avgdlen(self):
return float(self.cn) / self.dn
|
<commit_before>from collections import defaultdict
class Collection(object):
DOC_FROM = ["question_body", "best_answer_body"]
def __init__(self):
'''
Compute the following statistics
df: document frequency
cf: collection frequency
dn: total number of documents
cn: total number of words
'''
self.df = defaultdict(int)
self.cf = defaultdict(int)
self.dn = 0
self.cn = 0
def add(self, wordsets):
'''
Add a question
'''
for label in self.DOC_FROM:
for w in set(wordsets[label].keys()):
self.df[w] += 1
self.cf[w] += wordsets[label][w]
self.cn += wordsets[label][w]
self.dn += 1
<commit_msg>Add avddlen property to Collection<commit_after>
|
from collections import defaultdict
class Collection(object):
DOC_FROM = ["question_body", "best_answer_body"]
def __init__(self):
'''
Compute the following statistics
df: document frequency
cf: collection frequency
dn: total number of documents
cn: total number of words
'''
self.df = defaultdict(int)
self.cf = defaultdict(int)
self.dn = 0
self.cn = 0
def add(self, wordsets):
'''
Add a question
'''
for label in self.DOC_FROM:
for w in set(wordsets[label].keys()):
self.df[w] += 1
self.cf[w] += wordsets[label][w]
self.cn += wordsets[label][w]
self.dn += 1
@property
def avgdlen(self):
return float(self.cn) / self.dn
|
from collections import defaultdict
class Collection(object):
DOC_FROM = ["question_body", "best_answer_body"]
def __init__(self):
'''
Compute the following statistics
df: document frequency
cf: collection frequency
dn: total number of documents
cn: total number of words
'''
self.df = defaultdict(int)
self.cf = defaultdict(int)
self.dn = 0
self.cn = 0
def add(self, wordsets):
'''
Add a question
'''
for label in self.DOC_FROM:
for w in set(wordsets[label].keys()):
self.df[w] += 1
self.cf[w] += wordsets[label][w]
self.cn += wordsets[label][w]
self.dn += 1
Add avddlen property to Collectionfrom collections import defaultdict
class Collection(object):
DOC_FROM = ["question_body", "best_answer_body"]
def __init__(self):
'''
Compute the following statistics
df: document frequency
cf: collection frequency
dn: total number of documents
cn: total number of words
'''
self.df = defaultdict(int)
self.cf = defaultdict(int)
self.dn = 0
self.cn = 0
def add(self, wordsets):
'''
Add a question
'''
for label in self.DOC_FROM:
for w in set(wordsets[label].keys()):
self.df[w] += 1
self.cf[w] += wordsets[label][w]
self.cn += wordsets[label][w]
self.dn += 1
@property
def avgdlen(self):
return float(self.cn) / self.dn
|
<commit_before>from collections import defaultdict
class Collection(object):
DOC_FROM = ["question_body", "best_answer_body"]
def __init__(self):
'''
Compute the following statistics
df: document frequency
cf: collection frequency
dn: total number of documents
cn: total number of words
'''
self.df = defaultdict(int)
self.cf = defaultdict(int)
self.dn = 0
self.cn = 0
def add(self, wordsets):
'''
Add a question
'''
for label in self.DOC_FROM:
for w in set(wordsets[label].keys()):
self.df[w] += 1
self.cf[w] += wordsets[label][w]
self.cn += wordsets[label][w]
self.dn += 1
<commit_msg>Add avddlen property to Collection<commit_after>from collections import defaultdict
class Collection(object):
DOC_FROM = ["question_body", "best_answer_body"]
def __init__(self):
'''
Compute the following statistics
df: document frequency
cf: collection frequency
dn: total number of documents
cn: total number of words
'''
self.df = defaultdict(int)
self.cf = defaultdict(int)
self.dn = 0
self.cn = 0
def add(self, wordsets):
'''
Add a question
'''
for label in self.DOC_FROM:
for w in set(wordsets[label].keys()):
self.df[w] += 1
self.cf[w] += wordsets[label][w]
self.cn += wordsets[label][w]
self.dn += 1
@property
def avgdlen(self):
return float(self.cn) / self.dn
|
072eeaf0efbc299efac0be6fc7499f2d48dacd1a
|
BudgetModelHelper.py
|
BudgetModelHelper.py
|
from DataModel import DataModel
from DataModelAdapter import DataModelAdapter
from Ledger import Ledger
import pickle
DATA_FILE='ledger.pickle'
def get_ledger() :
result = None
try:
with open(DATA_FILE, 'rb') as infile:
result = pickle.load(infile)
except FileNotFoundError:
result = Ledger()
def get_model() :
model = DataModel()
model.setHeaders(list(model.root.keys()))
return model
def save_ledger(ledger) :
with open(DATA_FILE, 'wb') as outfile:
pickle.dump(ledger, outfile, pickle.HIGHEST_PROTOCOL)
|
from DataModel import DataModel
from DataModelAdapter import DataModelAdapter
from Ledger import Ledger
import pickle
DATA_FILE='ledger.pickle'
def get_ledger() :
result = None
try:
with open(DATA_FILE, 'rb') as infile:
result = pickle.load(infile)
except FileNotFoundError:
pass
except EOFError:
pass
if not result: result = Ledger()
return result
def get_model() :
model = DataModel()
model.setHeaders(list(model.root.keys()))
return model
def save_ledger(ledger) :
with open(DATA_FILE, 'wb') as outfile:
pickle.dump(ledger, outfile, pickle.HIGHEST_PROTOCOL)
|
Handle EOFError on pickle load
|
Handle EOFError on pickle load
|
Python
|
apache-2.0
|
mattdeckard/wherewithal
|
from DataModel import DataModel
from DataModelAdapter import DataModelAdapter
from Ledger import Ledger
import pickle
DATA_FILE='ledger.pickle'
def get_ledger() :
result = None
try:
with open(DATA_FILE, 'rb') as infile:
result = pickle.load(infile)
except FileNotFoundError:
result = Ledger()
def get_model() :
model = DataModel()
model.setHeaders(list(model.root.keys()))
return model
def save_ledger(ledger) :
with open(DATA_FILE, 'wb') as outfile:
pickle.dump(ledger, outfile, pickle.HIGHEST_PROTOCOL)
Handle EOFError on pickle load
|
from DataModel import DataModel
from DataModelAdapter import DataModelAdapter
from Ledger import Ledger
import pickle
DATA_FILE='ledger.pickle'
def get_ledger() :
result = None
try:
with open(DATA_FILE, 'rb') as infile:
result = pickle.load(infile)
except FileNotFoundError:
pass
except EOFError:
pass
if not result: result = Ledger()
return result
def get_model() :
model = DataModel()
model.setHeaders(list(model.root.keys()))
return model
def save_ledger(ledger) :
with open(DATA_FILE, 'wb') as outfile:
pickle.dump(ledger, outfile, pickle.HIGHEST_PROTOCOL)
|
<commit_before>from DataModel import DataModel
from DataModelAdapter import DataModelAdapter
from Ledger import Ledger
import pickle
DATA_FILE='ledger.pickle'
def get_ledger() :
result = None
try:
with open(DATA_FILE, 'rb') as infile:
result = pickle.load(infile)
except FileNotFoundError:
result = Ledger()
def get_model() :
model = DataModel()
model.setHeaders(list(model.root.keys()))
return model
def save_ledger(ledger) :
with open(DATA_FILE, 'wb') as outfile:
pickle.dump(ledger, outfile, pickle.HIGHEST_PROTOCOL)
<commit_msg>Handle EOFError on pickle load<commit_after>
|
from DataModel import DataModel
from DataModelAdapter import DataModelAdapter
from Ledger import Ledger
import pickle
DATA_FILE='ledger.pickle'
def get_ledger() :
result = None
try:
with open(DATA_FILE, 'rb') as infile:
result = pickle.load(infile)
except FileNotFoundError:
pass
except EOFError:
pass
if not result: result = Ledger()
return result
def get_model() :
model = DataModel()
model.setHeaders(list(model.root.keys()))
return model
def save_ledger(ledger) :
with open(DATA_FILE, 'wb') as outfile:
pickle.dump(ledger, outfile, pickle.HIGHEST_PROTOCOL)
|
from DataModel import DataModel
from DataModelAdapter import DataModelAdapter
from Ledger import Ledger
import pickle
DATA_FILE='ledger.pickle'
def get_ledger() :
result = None
try:
with open(DATA_FILE, 'rb') as infile:
result = pickle.load(infile)
except FileNotFoundError:
result = Ledger()
def get_model() :
model = DataModel()
model.setHeaders(list(model.root.keys()))
return model
def save_ledger(ledger) :
with open(DATA_FILE, 'wb') as outfile:
pickle.dump(ledger, outfile, pickle.HIGHEST_PROTOCOL)
Handle EOFError on pickle loadfrom DataModel import DataModel
from DataModelAdapter import DataModelAdapter
from Ledger import Ledger
import pickle
DATA_FILE='ledger.pickle'
def get_ledger() :
result = None
try:
with open(DATA_FILE, 'rb') as infile:
result = pickle.load(infile)
except FileNotFoundError:
pass
except EOFError:
pass
if not result: result = Ledger()
return result
def get_model() :
model = DataModel()
model.setHeaders(list(model.root.keys()))
return model
def save_ledger(ledger) :
with open(DATA_FILE, 'wb') as outfile:
pickle.dump(ledger, outfile, pickle.HIGHEST_PROTOCOL)
|
<commit_before>from DataModel import DataModel
from DataModelAdapter import DataModelAdapter
from Ledger import Ledger
import pickle
DATA_FILE='ledger.pickle'
def get_ledger() :
result = None
try:
with open(DATA_FILE, 'rb') as infile:
result = pickle.load(infile)
except FileNotFoundError:
result = Ledger()
def get_model() :
model = DataModel()
model.setHeaders(list(model.root.keys()))
return model
def save_ledger(ledger) :
with open(DATA_FILE, 'wb') as outfile:
pickle.dump(ledger, outfile, pickle.HIGHEST_PROTOCOL)
<commit_msg>Handle EOFError on pickle load<commit_after>from DataModel import DataModel
from DataModelAdapter import DataModelAdapter
from Ledger import Ledger
import pickle
DATA_FILE='ledger.pickle'
def get_ledger() :
result = None
try:
with open(DATA_FILE, 'rb') as infile:
result = pickle.load(infile)
except FileNotFoundError:
pass
except EOFError:
pass
if not result: result = Ledger()
return result
def get_model() :
model = DataModel()
model.setHeaders(list(model.root.keys()))
return model
def save_ledger(ledger) :
with open(DATA_FILE, 'wb') as outfile:
pickle.dump(ledger, outfile, pickle.HIGHEST_PROTOCOL)
|
631a8ad370ee12b336a4f53e111267bf97151f40
|
satchmo/apps/satchmo_store/shop/management/commands/satchmo_copy_static.py
|
satchmo/apps/satchmo_store/shop/management/commands/satchmo_copy_static.py
|
from django.core.management.base import NoArgsCommand
import os
import shutil
class Command(NoArgsCommand):
help = "Copy the satchmo static directory and files to the local project."
def handle_noargs(self, **options):
import satchmo_store
static_src = os.path.join(satchmo_store.__path__[0],'static')
static_dest = os.path.join(os.getcwd(), 'static')
if os.path.exists(static_dest):
print "Static directory exists. You must manually copy the files you need."
else:
shutil.copytree(static_src, static_dest)
for root, dirs, files in os.walk(static_dest):
if '.svn' in dirs:
shutil.rmtree(os.path.join(root,'.svn'), True)
print "Copied %s to %s" % (static_src, static_dest)
|
from django.core.management.base import NoArgsCommand
import os
import shutil
class Command(NoArgsCommand):
help = "Copy the satchmo static directory and files to the local project."
def handle_noargs(self, **options):
import satchmo_store
static_src = os.path.join(satchmo_store.__path__[0],'../../static')
static_dest = os.path.join(os.getcwd(), 'static')
if os.path.exists(static_dest):
print "Static directory exists. You must manually copy the files you need."
else:
shutil.copytree(static_src, static_dest)
for root, dirs, files in os.walk(static_dest):
if '.svn' in dirs:
shutil.rmtree(os.path.join(root,'.svn'), True)
print "Copied %s to %s" % (static_src, static_dest)
|
Change the static copy command so it works with new layout.
|
Change the static copy command so it works with new layout.
|
Python
|
bsd-3-clause
|
grengojbo/satchmo,grengojbo/satchmo
|
from django.core.management.base import NoArgsCommand
import os
import shutil
class Command(NoArgsCommand):
help = "Copy the satchmo static directory and files to the local project."
def handle_noargs(self, **options):
import satchmo_store
static_src = os.path.join(satchmo_store.__path__[0],'static')
static_dest = os.path.join(os.getcwd(), 'static')
if os.path.exists(static_dest):
print "Static directory exists. You must manually copy the files you need."
else:
shutil.copytree(static_src, static_dest)
for root, dirs, files in os.walk(static_dest):
if '.svn' in dirs:
shutil.rmtree(os.path.join(root,'.svn'), True)
print "Copied %s to %s" % (static_src, static_dest)
Change the static copy command so it works with new layout.
|
from django.core.management.base import NoArgsCommand
import os
import shutil
class Command(NoArgsCommand):
help = "Copy the satchmo static directory and files to the local project."
def handle_noargs(self, **options):
import satchmo_store
static_src = os.path.join(satchmo_store.__path__[0],'../../static')
static_dest = os.path.join(os.getcwd(), 'static')
if os.path.exists(static_dest):
print "Static directory exists. You must manually copy the files you need."
else:
shutil.copytree(static_src, static_dest)
for root, dirs, files in os.walk(static_dest):
if '.svn' in dirs:
shutil.rmtree(os.path.join(root,'.svn'), True)
print "Copied %s to %s" % (static_src, static_dest)
|
<commit_before>from django.core.management.base import NoArgsCommand
import os
import shutil
class Command(NoArgsCommand):
help = "Copy the satchmo static directory and files to the local project."
def handle_noargs(self, **options):
import satchmo_store
static_src = os.path.join(satchmo_store.__path__[0],'static')
static_dest = os.path.join(os.getcwd(), 'static')
if os.path.exists(static_dest):
print "Static directory exists. You must manually copy the files you need."
else:
shutil.copytree(static_src, static_dest)
for root, dirs, files in os.walk(static_dest):
if '.svn' in dirs:
shutil.rmtree(os.path.join(root,'.svn'), True)
print "Copied %s to %s" % (static_src, static_dest)
<commit_msg>Change the static copy command so it works with new layout.<commit_after>
|
from django.core.management.base import NoArgsCommand
import os
import shutil
class Command(NoArgsCommand):
help = "Copy the satchmo static directory and files to the local project."
def handle_noargs(self, **options):
import satchmo_store
static_src = os.path.join(satchmo_store.__path__[0],'../../static')
static_dest = os.path.join(os.getcwd(), 'static')
if os.path.exists(static_dest):
print "Static directory exists. You must manually copy the files you need."
else:
shutil.copytree(static_src, static_dest)
for root, dirs, files in os.walk(static_dest):
if '.svn' in dirs:
shutil.rmtree(os.path.join(root,'.svn'), True)
print "Copied %s to %s" % (static_src, static_dest)
|
from django.core.management.base import NoArgsCommand
import os
import shutil
class Command(NoArgsCommand):
help = "Copy the satchmo static directory and files to the local project."
def handle_noargs(self, **options):
import satchmo_store
static_src = os.path.join(satchmo_store.__path__[0],'static')
static_dest = os.path.join(os.getcwd(), 'static')
if os.path.exists(static_dest):
print "Static directory exists. You must manually copy the files you need."
else:
shutil.copytree(static_src, static_dest)
for root, dirs, files in os.walk(static_dest):
if '.svn' in dirs:
shutil.rmtree(os.path.join(root,'.svn'), True)
print "Copied %s to %s" % (static_src, static_dest)
Change the static copy command so it works with new layout.from django.core.management.base import NoArgsCommand
import os
import shutil
class Command(NoArgsCommand):
help = "Copy the satchmo static directory and files to the local project."
def handle_noargs(self, **options):
import satchmo_store
static_src = os.path.join(satchmo_store.__path__[0],'../../static')
static_dest = os.path.join(os.getcwd(), 'static')
if os.path.exists(static_dest):
print "Static directory exists. You must manually copy the files you need."
else:
shutil.copytree(static_src, static_dest)
for root, dirs, files in os.walk(static_dest):
if '.svn' in dirs:
shutil.rmtree(os.path.join(root,'.svn'), True)
print "Copied %s to %s" % (static_src, static_dest)
|
<commit_before>from django.core.management.base import NoArgsCommand
import os
import shutil
class Command(NoArgsCommand):
help = "Copy the satchmo static directory and files to the local project."
def handle_noargs(self, **options):
import satchmo_store
static_src = os.path.join(satchmo_store.__path__[0],'static')
static_dest = os.path.join(os.getcwd(), 'static')
if os.path.exists(static_dest):
print "Static directory exists. You must manually copy the files you need."
else:
shutil.copytree(static_src, static_dest)
for root, dirs, files in os.walk(static_dest):
if '.svn' in dirs:
shutil.rmtree(os.path.join(root,'.svn'), True)
print "Copied %s to %s" % (static_src, static_dest)
<commit_msg>Change the static copy command so it works with new layout.<commit_after>from django.core.management.base import NoArgsCommand
import os
import shutil
class Command(NoArgsCommand):
help = "Copy the satchmo static directory and files to the local project."
def handle_noargs(self, **options):
import satchmo_store
static_src = os.path.join(satchmo_store.__path__[0],'../../static')
static_dest = os.path.join(os.getcwd(), 'static')
if os.path.exists(static_dest):
print "Static directory exists. You must manually copy the files you need."
else:
shutil.copytree(static_src, static_dest)
for root, dirs, files in os.walk(static_dest):
if '.svn' in dirs:
shutil.rmtree(os.path.join(root,'.svn'), True)
print "Copied %s to %s" % (static_src, static_dest)
|
73f75efcfe69210d8e22ff55c19b02b7408b9671
|
pseudorandom.py
|
pseudorandom.py
|
from flask import Flask, render_template
from names import get_full_name
app = Flask(__name__)
@app.route("/")
def index():
return render_template('index.html', name=get_full_name())
if __name__ == "__main__":
app.run()
|
import os
from flask import Flask, render_template
from names import get_full_name
app = Flask(__name__)
@app.route("/")
def index():
return render_template('index.html', name=get_full_name())
if __name__ == "__main__":
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
|
Use environment variable PORT for flask port
|
Use environment variable PORT for flask port
|
Python
|
mit
|
treyhunner/pseudorandom.name,treyhunner/pseudorandom.name
|
from flask import Flask, render_template
from names import get_full_name
app = Flask(__name__)
@app.route("/")
def index():
return render_template('index.html', name=get_full_name())
if __name__ == "__main__":
app.run()
Use environment variable PORT for flask port
|
import os
from flask import Flask, render_template
from names import get_full_name
app = Flask(__name__)
@app.route("/")
def index():
return render_template('index.html', name=get_full_name())
if __name__ == "__main__":
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
|
<commit_before>from flask import Flask, render_template
from names import get_full_name
app = Flask(__name__)
@app.route("/")
def index():
return render_template('index.html', name=get_full_name())
if __name__ == "__main__":
app.run()
<commit_msg>Use environment variable PORT for flask port<commit_after>
|
import os
from flask import Flask, render_template
from names import get_full_name
app = Flask(__name__)
@app.route("/")
def index():
return render_template('index.html', name=get_full_name())
if __name__ == "__main__":
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
|
from flask import Flask, render_template
from names import get_full_name
app = Flask(__name__)
@app.route("/")
def index():
return render_template('index.html', name=get_full_name())
if __name__ == "__main__":
app.run()
Use environment variable PORT for flask portimport os
from flask import Flask, render_template
from names import get_full_name
app = Flask(__name__)
@app.route("/")
def index():
return render_template('index.html', name=get_full_name())
if __name__ == "__main__":
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
|
<commit_before>from flask import Flask, render_template
from names import get_full_name
app = Flask(__name__)
@app.route("/")
def index():
return render_template('index.html', name=get_full_name())
if __name__ == "__main__":
app.run()
<commit_msg>Use environment variable PORT for flask port<commit_after>import os
from flask import Flask, render_template
from names import get_full_name
app = Flask(__name__)
@app.route("/")
def index():
return render_template('index.html', name=get_full_name())
if __name__ == "__main__":
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
|
e77c1f15f9a3b1d6b6224f4621450707a5059079
|
yunity/resources/tests/integration/__init__.py
|
yunity/resources/tests/integration/__init__.py
|
"""
This package contains data files for our API integration tests.
In order to add a new integration test, create a new package with the following contents:
```
yunity/resources/tests/integration/test_name__tested_functionality
|-- __init__.py
|-- initial_data.py # defines the calls to setup the database with the data you need to run your test
|-- request.json # defines the request to the API
|-- response.json # defines the expectations on what gets returned from the API
`-- final_data.py # defines the expectations on the database after the API call has finished
```
"""
|
Add some documentation to integration tests
|
Add some documentation to integration tests
|
Python
|
agpl-3.0
|
yunity/foodsaving-backend,yunity/yunity-core,yunity/foodsaving-backend,yunity/foodsaving-backend,yunity/yunity-core
|
Add some documentation to integration tests
|
"""
This package contains data files for our API integration tests.
In order to add a new integration test, create a new package with the following contents:
```
yunity/resources/tests/integration/test_name__tested_functionality
|-- __init__.py
|-- initial_data.py # defines the calls to setup the database with the data you need to run your test
|-- request.json # defines the request to the API
|-- response.json # defines the expectations on what gets returned from the API
`-- final_data.py # defines the expectations on the database after the API call has finished
```
"""
|
<commit_before><commit_msg>Add some documentation to integration tests<commit_after>
|
"""
This package contains data files for our API integration tests.
In order to add a new integration test, create a new package with the following contents:
```
yunity/resources/tests/integration/test_name__tested_functionality
|-- __init__.py
|-- initial_data.py # defines the calls to setup the database with the data you need to run your test
|-- request.json # defines the request to the API
|-- response.json # defines the expectations on what gets returned from the API
`-- final_data.py # defines the expectations on the database after the API call has finished
```
"""
|
Add some documentation to integration tests"""
This package contains data files for our API integration tests.
In order to add a new integration test, create a new package with the following contents:
```
yunity/resources/tests/integration/test_name__tested_functionality
|-- __init__.py
|-- initial_data.py # defines the calls to setup the database with the data you need to run your test
|-- request.json # defines the request to the API
|-- response.json # defines the expectations on what gets returned from the API
`-- final_data.py # defines the expectations on the database after the API call has finished
```
"""
|
<commit_before><commit_msg>Add some documentation to integration tests<commit_after>"""
This package contains data files for our API integration tests.
In order to add a new integration test, create a new package with the following contents:
```
yunity/resources/tests/integration/test_name__tested_functionality
|-- __init__.py
|-- initial_data.py # defines the calls to setup the database with the data you need to run your test
|-- request.json # defines the request to the API
|-- response.json # defines the expectations on what gets returned from the API
`-- final_data.py # defines the expectations on the database after the API call has finished
```
"""
|
|
987b9c6d8a3cea616c3fd4f8f3985944171956ab
|
px/px_commandline_test.py
|
px/px_commandline_test.py
|
import px_commandline
def test_get_command_python():
assert px_commandline.get_command("python") == "python"
assert px_commandline.get_command("/apa/Python") == "Python"
assert px_commandline.get_command("python --help") == "python"
# These are inspired by Python 2.7.11 --help output
assert px_commandline.get_command("python apa.py") == "apa.py"
assert px_commandline.get_command("python /usr/bin/hej") == "hej"
assert px_commandline.get_command("python /usr/bin/hej gris --flaska") == "hej"
assert px_commandline.get_command("python -c cmd") == "python"
assert px_commandline.get_command("python -m mod") == "mod"
assert px_commandline.get_command("python -m mod --hej gris --frukt") == "mod"
assert px_commandline.get_command("Python -") == "Python"
assert px_commandline.get_command("python -W warning:spec apa.py") == "apa.py"
assert px_commandline.get_command("python -u -t -m mod") == "mod"
# Invalid command lines
assert px_commandline.get_command("python -W") == "python"
assert px_commandline.get_command("python -c") == "python"
assert px_commandline.get_command("python -m") == "python"
|
Add (failing) Python command line parsing tests
|
Add (failing) Python command line parsing tests
|
Python
|
mit
|
walles/px,walles/px
|
Add (failing) Python command line parsing tests
|
import px_commandline
def test_get_command_python():
assert px_commandline.get_command("python") == "python"
assert px_commandline.get_command("/apa/Python") == "Python"
assert px_commandline.get_command("python --help") == "python"
# These are inspired by Python 2.7.11 --help output
assert px_commandline.get_command("python apa.py") == "apa.py"
assert px_commandline.get_command("python /usr/bin/hej") == "hej"
assert px_commandline.get_command("python /usr/bin/hej gris --flaska") == "hej"
assert px_commandline.get_command("python -c cmd") == "python"
assert px_commandline.get_command("python -m mod") == "mod"
assert px_commandline.get_command("python -m mod --hej gris --frukt") == "mod"
assert px_commandline.get_command("Python -") == "Python"
assert px_commandline.get_command("python -W warning:spec apa.py") == "apa.py"
assert px_commandline.get_command("python -u -t -m mod") == "mod"
# Invalid command lines
assert px_commandline.get_command("python -W") == "python"
assert px_commandline.get_command("python -c") == "python"
assert px_commandline.get_command("python -m") == "python"
|
<commit_before><commit_msg>Add (failing) Python command line parsing tests<commit_after>
|
import px_commandline
def test_get_command_python():
assert px_commandline.get_command("python") == "python"
assert px_commandline.get_command("/apa/Python") == "Python"
assert px_commandline.get_command("python --help") == "python"
# These are inspired by Python 2.7.11 --help output
assert px_commandline.get_command("python apa.py") == "apa.py"
assert px_commandline.get_command("python /usr/bin/hej") == "hej"
assert px_commandline.get_command("python /usr/bin/hej gris --flaska") == "hej"
assert px_commandline.get_command("python -c cmd") == "python"
assert px_commandline.get_command("python -m mod") == "mod"
assert px_commandline.get_command("python -m mod --hej gris --frukt") == "mod"
assert px_commandline.get_command("Python -") == "Python"
assert px_commandline.get_command("python -W warning:spec apa.py") == "apa.py"
assert px_commandline.get_command("python -u -t -m mod") == "mod"
# Invalid command lines
assert px_commandline.get_command("python -W") == "python"
assert px_commandline.get_command("python -c") == "python"
assert px_commandline.get_command("python -m") == "python"
|
Add (failing) Python command line parsing testsimport px_commandline
def test_get_command_python():
assert px_commandline.get_command("python") == "python"
assert px_commandline.get_command("/apa/Python") == "Python"
assert px_commandline.get_command("python --help") == "python"
# These are inspired by Python 2.7.11 --help output
assert px_commandline.get_command("python apa.py") == "apa.py"
assert px_commandline.get_command("python /usr/bin/hej") == "hej"
assert px_commandline.get_command("python /usr/bin/hej gris --flaska") == "hej"
assert px_commandline.get_command("python -c cmd") == "python"
assert px_commandline.get_command("python -m mod") == "mod"
assert px_commandline.get_command("python -m mod --hej gris --frukt") == "mod"
assert px_commandline.get_command("Python -") == "Python"
assert px_commandline.get_command("python -W warning:spec apa.py") == "apa.py"
assert px_commandline.get_command("python -u -t -m mod") == "mod"
# Invalid command lines
assert px_commandline.get_command("python -W") == "python"
assert px_commandline.get_command("python -c") == "python"
assert px_commandline.get_command("python -m") == "python"
|
<commit_before><commit_msg>Add (failing) Python command line parsing tests<commit_after>import px_commandline
def test_get_command_python():
assert px_commandline.get_command("python") == "python"
assert px_commandline.get_command("/apa/Python") == "Python"
assert px_commandline.get_command("python --help") == "python"
# These are inspired by Python 2.7.11 --help output
assert px_commandline.get_command("python apa.py") == "apa.py"
assert px_commandline.get_command("python /usr/bin/hej") == "hej"
assert px_commandline.get_command("python /usr/bin/hej gris --flaska") == "hej"
assert px_commandline.get_command("python -c cmd") == "python"
assert px_commandline.get_command("python -m mod") == "mod"
assert px_commandline.get_command("python -m mod --hej gris --frukt") == "mod"
assert px_commandline.get_command("Python -") == "Python"
assert px_commandline.get_command("python -W warning:spec apa.py") == "apa.py"
assert px_commandline.get_command("python -u -t -m mod") == "mod"
# Invalid command lines
assert px_commandline.get_command("python -W") == "python"
assert px_commandline.get_command("python -c") == "python"
assert px_commandline.get_command("python -m") == "python"
|
|
41b1d36a9d5fcb0dd2f6da53a7a0d4604b21a0eb
|
tests/query_test/test_scan_range_lengths.py
|
tests/query_test/test_scan_range_lengths.py
|
#!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
# Validates running with different scan range length values
#
import pytest
from copy import copy
from tests.common.test_vector import TestDimension
from tests.common.impala_test_suite import ImpalaTestSuite, ALL_NODES_ONLY
# We use very small scan ranges to exercise corner cases in the HDFS scanner more
# thoroughly. In particular, it will exercise:
# 1. scan range with no tuple
# 2. tuple that span across multiple scan ranges
MAX_SCAN_RANGE_LENGTHS = [1, 2, 5]
class TestScanRangeLengths(ImpalaTestSuite):
@classmethod
def get_workload(cls):
return 'functional-query'
@classmethod
def add_test_dimensions(cls):
super(TestScanRangeLengths, cls).add_test_dimensions()
cls.TestMatrix.add_dimension(
TestDimension('max_scan_range_length', *MAX_SCAN_RANGE_LENGTHS))
def test_scan_ranges(self, vector):
if vector.get_value('table_format').file_format != 'text':
pytest.xfail(reason='IMP-636')
elif vector.get_value('table_format').compression_codec != 'none':
pytest.xfail(reason='IMPALA-122')
vector.get_value('exec_option')['max_scan_range_length'] =\
vector.get_value('max_scan_range_length')
self.run_test_case('QueryTest/hdfs-tiny-scan', vector)
|
#!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
# Validates running with different scan range length values
#
import pytest
from copy import copy
from tests.common.test_vector import TestDimension
from tests.common.impala_test_suite import ImpalaTestSuite, ALL_NODES_ONLY
# We use very small scan ranges to exercise corner cases in the HDFS scanner more
# thoroughly. In particular, it will exercise:
# 1. scan range with no tuple
# 2. tuple that span across multiple scan ranges
MAX_SCAN_RANGE_LENGTHS = [1, 2, 5]
class TestScanRangeLengths(ImpalaTestSuite):
@classmethod
def get_workload(cls):
return 'functional-query'
@classmethod
def add_test_dimensions(cls):
super(TestScanRangeLengths, cls).add_test_dimensions()
cls.TestMatrix.add_dimension(
TestDimension('max_scan_range_length', *MAX_SCAN_RANGE_LENGTHS))
def test_scan_ranges(self, vector):
if vector.get_value('table_format').file_format != 'text':
pytest.xfail(reason='IMP-636')
vector.get_value('exec_option')['max_scan_range_length'] =\
vector.get_value('max_scan_range_length')
self.run_test_case('QueryTest/hdfs-tiny-scan', vector)
|
Fix IMPALA-122: Lzo scanner with small scan ranges.
|
Fix IMPALA-122: Lzo scanner with small scan ranges.
Change-Id: I5226fd1a1aa368f5b291b78ad371363057ef574e
Reviewed-on: http://gerrit.ent.cloudera.com:8080/140
Reviewed-by: Skye Wanderman-Milne <6d4b168ab637b0a20cc9dbf96abb2537f372f946@cloudera.com>
Reviewed-by: Nong Li <99a5e5f8f5911755b88e0b536d46aafa102bed41@cloudera.com>
Tested-by: Nong Li <99a5e5f8f5911755b88e0b536d46aafa102bed41@cloudera.com>
|
Python
|
apache-2.0
|
michaelhkw/incubator-impala,cloudera/Impala,michaelhkw/incubator-impala,michaelhkw/incubator-impala,michaelhkw/incubator-impala,cloudera/Impala,cloudera/Impala,cloudera/Impala,michaelhkw/incubator-impala,michaelhkw/incubator-impala,cloudera/Impala,cloudera/Impala,michaelhkw/incubator-impala,cloudera/Impala
|
#!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
# Validates running with different scan range length values
#
import pytest
from copy import copy
from tests.common.test_vector import TestDimension
from tests.common.impala_test_suite import ImpalaTestSuite, ALL_NODES_ONLY
# We use very small scan ranges to exercise corner cases in the HDFS scanner more
# thoroughly. In particular, it will exercise:
# 1. scan range with no tuple
# 2. tuple that span across multiple scan ranges
MAX_SCAN_RANGE_LENGTHS = [1, 2, 5]
class TestScanRangeLengths(ImpalaTestSuite):
@classmethod
def get_workload(cls):
return 'functional-query'
@classmethod
def add_test_dimensions(cls):
super(TestScanRangeLengths, cls).add_test_dimensions()
cls.TestMatrix.add_dimension(
TestDimension('max_scan_range_length', *MAX_SCAN_RANGE_LENGTHS))
def test_scan_ranges(self, vector):
if vector.get_value('table_format').file_format != 'text':
pytest.xfail(reason='IMP-636')
elif vector.get_value('table_format').compression_codec != 'none':
pytest.xfail(reason='IMPALA-122')
vector.get_value('exec_option')['max_scan_range_length'] =\
vector.get_value('max_scan_range_length')
self.run_test_case('QueryTest/hdfs-tiny-scan', vector)
Fix IMPALA-122: Lzo scanner with small scan ranges.
Change-Id: I5226fd1a1aa368f5b291b78ad371363057ef574e
Reviewed-on: http://gerrit.ent.cloudera.com:8080/140
Reviewed-by: Skye Wanderman-Milne <6d4b168ab637b0a20cc9dbf96abb2537f372f946@cloudera.com>
Reviewed-by: Nong Li <99a5e5f8f5911755b88e0b536d46aafa102bed41@cloudera.com>
Tested-by: Nong Li <99a5e5f8f5911755b88e0b536d46aafa102bed41@cloudera.com>
|
#!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
# Validates running with different scan range length values
#
import pytest
from copy import copy
from tests.common.test_vector import TestDimension
from tests.common.impala_test_suite import ImpalaTestSuite, ALL_NODES_ONLY
# We use very small scan ranges to exercise corner cases in the HDFS scanner more
# thoroughly. In particular, it will exercise:
# 1. scan range with no tuple
# 2. tuple that span across multiple scan ranges
MAX_SCAN_RANGE_LENGTHS = [1, 2, 5]
class TestScanRangeLengths(ImpalaTestSuite):
@classmethod
def get_workload(cls):
return 'functional-query'
@classmethod
def add_test_dimensions(cls):
super(TestScanRangeLengths, cls).add_test_dimensions()
cls.TestMatrix.add_dimension(
TestDimension('max_scan_range_length', *MAX_SCAN_RANGE_LENGTHS))
def test_scan_ranges(self, vector):
if vector.get_value('table_format').file_format != 'text':
pytest.xfail(reason='IMP-636')
vector.get_value('exec_option')['max_scan_range_length'] =\
vector.get_value('max_scan_range_length')
self.run_test_case('QueryTest/hdfs-tiny-scan', vector)
|
<commit_before>#!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
# Validates running with different scan range length values
#
import pytest
from copy import copy
from tests.common.test_vector import TestDimension
from tests.common.impala_test_suite import ImpalaTestSuite, ALL_NODES_ONLY
# We use very small scan ranges to exercise corner cases in the HDFS scanner more
# thoroughly. In particular, it will exercise:
# 1. scan range with no tuple
# 2. tuple that span across multiple scan ranges
MAX_SCAN_RANGE_LENGTHS = [1, 2, 5]
class TestScanRangeLengths(ImpalaTestSuite):
@classmethod
def get_workload(cls):
return 'functional-query'
@classmethod
def add_test_dimensions(cls):
super(TestScanRangeLengths, cls).add_test_dimensions()
cls.TestMatrix.add_dimension(
TestDimension('max_scan_range_length', *MAX_SCAN_RANGE_LENGTHS))
def test_scan_ranges(self, vector):
if vector.get_value('table_format').file_format != 'text':
pytest.xfail(reason='IMP-636')
elif vector.get_value('table_format').compression_codec != 'none':
pytest.xfail(reason='IMPALA-122')
vector.get_value('exec_option')['max_scan_range_length'] =\
vector.get_value('max_scan_range_length')
self.run_test_case('QueryTest/hdfs-tiny-scan', vector)
<commit_msg>Fix IMPALA-122: Lzo scanner with small scan ranges.
Change-Id: I5226fd1a1aa368f5b291b78ad371363057ef574e
Reviewed-on: http://gerrit.ent.cloudera.com:8080/140
Reviewed-by: Skye Wanderman-Milne <6d4b168ab637b0a20cc9dbf96abb2537f372f946@cloudera.com>
Reviewed-by: Nong Li <99a5e5f8f5911755b88e0b536d46aafa102bed41@cloudera.com>
Tested-by: Nong Li <99a5e5f8f5911755b88e0b536d46aafa102bed41@cloudera.com><commit_after>
|
#!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
# Validates running with different scan range length values
#
import pytest
from copy import copy
from tests.common.test_vector import TestDimension
from tests.common.impala_test_suite import ImpalaTestSuite, ALL_NODES_ONLY
# We use very small scan ranges to exercise corner cases in the HDFS scanner more
# thoroughly. In particular, it will exercise:
# 1. scan range with no tuple
# 2. tuple that span across multiple scan ranges
MAX_SCAN_RANGE_LENGTHS = [1, 2, 5]
class TestScanRangeLengths(ImpalaTestSuite):
@classmethod
def get_workload(cls):
return 'functional-query'
@classmethod
def add_test_dimensions(cls):
super(TestScanRangeLengths, cls).add_test_dimensions()
cls.TestMatrix.add_dimension(
TestDimension('max_scan_range_length', *MAX_SCAN_RANGE_LENGTHS))
def test_scan_ranges(self, vector):
if vector.get_value('table_format').file_format != 'text':
pytest.xfail(reason='IMP-636')
vector.get_value('exec_option')['max_scan_range_length'] =\
vector.get_value('max_scan_range_length')
self.run_test_case('QueryTest/hdfs-tiny-scan', vector)
|
#!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
# Validates running with different scan range length values
#
import pytest
from copy import copy
from tests.common.test_vector import TestDimension
from tests.common.impala_test_suite import ImpalaTestSuite, ALL_NODES_ONLY
# We use very small scan ranges to exercise corner cases in the HDFS scanner more
# thoroughly. In particular, it will exercise:
# 1. scan range with no tuple
# 2. tuple that span across multiple scan ranges
MAX_SCAN_RANGE_LENGTHS = [1, 2, 5]
class TestScanRangeLengths(ImpalaTestSuite):
@classmethod
def get_workload(cls):
return 'functional-query'
@classmethod
def add_test_dimensions(cls):
super(TestScanRangeLengths, cls).add_test_dimensions()
cls.TestMatrix.add_dimension(
TestDimension('max_scan_range_length', *MAX_SCAN_RANGE_LENGTHS))
def test_scan_ranges(self, vector):
if vector.get_value('table_format').file_format != 'text':
pytest.xfail(reason='IMP-636')
elif vector.get_value('table_format').compression_codec != 'none':
pytest.xfail(reason='IMPALA-122')
vector.get_value('exec_option')['max_scan_range_length'] =\
vector.get_value('max_scan_range_length')
self.run_test_case('QueryTest/hdfs-tiny-scan', vector)
Fix IMPALA-122: Lzo scanner with small scan ranges.
Change-Id: I5226fd1a1aa368f5b291b78ad371363057ef574e
Reviewed-on: http://gerrit.ent.cloudera.com:8080/140
Reviewed-by: Skye Wanderman-Milne <6d4b168ab637b0a20cc9dbf96abb2537f372f946@cloudera.com>
Reviewed-by: Nong Li <99a5e5f8f5911755b88e0b536d46aafa102bed41@cloudera.com>
Tested-by: Nong Li <99a5e5f8f5911755b88e0b536d46aafa102bed41@cloudera.com>#!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
# Validates running with different scan range length values
#
import pytest
from copy import copy
from tests.common.test_vector import TestDimension
from tests.common.impala_test_suite import ImpalaTestSuite, ALL_NODES_ONLY
# We use very small scan ranges to exercise corner cases in the HDFS scanner more
# thoroughly. In particular, it will exercise:
# 1. scan range with no tuple
# 2. tuple that span across multiple scan ranges
MAX_SCAN_RANGE_LENGTHS = [1, 2, 5]
class TestScanRangeLengths(ImpalaTestSuite):
@classmethod
def get_workload(cls):
return 'functional-query'
@classmethod
def add_test_dimensions(cls):
super(TestScanRangeLengths, cls).add_test_dimensions()
cls.TestMatrix.add_dimension(
TestDimension('max_scan_range_length', *MAX_SCAN_RANGE_LENGTHS))
def test_scan_ranges(self, vector):
if vector.get_value('table_format').file_format != 'text':
pytest.xfail(reason='IMP-636')
vector.get_value('exec_option')['max_scan_range_length'] =\
vector.get_value('max_scan_range_length')
self.run_test_case('QueryTest/hdfs-tiny-scan', vector)
|
<commit_before>#!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
# Validates running with different scan range length values
#
import pytest
from copy import copy
from tests.common.test_vector import TestDimension
from tests.common.impala_test_suite import ImpalaTestSuite, ALL_NODES_ONLY
# We use very small scan ranges to exercise corner cases in the HDFS scanner more
# thoroughly. In particular, it will exercise:
# 1. scan range with no tuple
# 2. tuple that span across multiple scan ranges
MAX_SCAN_RANGE_LENGTHS = [1, 2, 5]
class TestScanRangeLengths(ImpalaTestSuite):
@classmethod
def get_workload(cls):
return 'functional-query'
@classmethod
def add_test_dimensions(cls):
super(TestScanRangeLengths, cls).add_test_dimensions()
cls.TestMatrix.add_dimension(
TestDimension('max_scan_range_length', *MAX_SCAN_RANGE_LENGTHS))
def test_scan_ranges(self, vector):
if vector.get_value('table_format').file_format != 'text':
pytest.xfail(reason='IMP-636')
elif vector.get_value('table_format').compression_codec != 'none':
pytest.xfail(reason='IMPALA-122')
vector.get_value('exec_option')['max_scan_range_length'] =\
vector.get_value('max_scan_range_length')
self.run_test_case('QueryTest/hdfs-tiny-scan', vector)
<commit_msg>Fix IMPALA-122: Lzo scanner with small scan ranges.
Change-Id: I5226fd1a1aa368f5b291b78ad371363057ef574e
Reviewed-on: http://gerrit.ent.cloudera.com:8080/140
Reviewed-by: Skye Wanderman-Milne <6d4b168ab637b0a20cc9dbf96abb2537f372f946@cloudera.com>
Reviewed-by: Nong Li <99a5e5f8f5911755b88e0b536d46aafa102bed41@cloudera.com>
Tested-by: Nong Li <99a5e5f8f5911755b88e0b536d46aafa102bed41@cloudera.com><commit_after>#!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
# Validates running with different scan range length values
#
import pytest
from copy import copy
from tests.common.test_vector import TestDimension
from tests.common.impala_test_suite import ImpalaTestSuite, ALL_NODES_ONLY
# We use very small scan ranges to exercise corner cases in the HDFS scanner more
# thoroughly. In particular, it will exercise:
# 1. scan range with no tuple
# 2. tuple that span across multiple scan ranges
MAX_SCAN_RANGE_LENGTHS = [1, 2, 5]
class TestScanRangeLengths(ImpalaTestSuite):
@classmethod
def get_workload(cls):
return 'functional-query'
@classmethod
def add_test_dimensions(cls):
super(TestScanRangeLengths, cls).add_test_dimensions()
cls.TestMatrix.add_dimension(
TestDimension('max_scan_range_length', *MAX_SCAN_RANGE_LENGTHS))
def test_scan_ranges(self, vector):
if vector.get_value('table_format').file_format != 'text':
pytest.xfail(reason='IMP-636')
vector.get_value('exec_option')['max_scan_range_length'] =\
vector.get_value('max_scan_range_length')
self.run_test_case('QueryTest/hdfs-tiny-scan', vector)
|
d1e56cfcd11bcd509d8fa3954c00e06a84bddd87
|
synapse/storage/engines/__init__.py
|
synapse/storage/engines/__init__.py
|
# -*- coding: utf-8 -*-
# Copyright 2015, 2016 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ._base import IncorrectDatabaseSetup
from .postgres import PostgresEngine
from .sqlite3 import Sqlite3Engine
import importlib
import platform
SUPPORTED_MODULE = {
"sqlite3": Sqlite3Engine,
"psycopg2": PostgresEngine,
}
def create_engine(database_config):
name = database_config["name"]
engine_class = SUPPORTED_MODULE.get(name, None)
if engine_class:
needs_pypy_hack = (name == "psycopg2" and
platform.python_implementation() == "PyPy")
if needs_pypy_hack:
module = importlib.import_module("psycopg2cffi")
else:
module = importlib.import_module(name)
return engine_class(module, database_config)
raise RuntimeError(
"Unsupported database engine '%s'" % (name,)
)
__all__ = ["create_engine", "IncorrectDatabaseSetup"]
|
# -*- coding: utf-8 -*-
# Copyright 2015, 2016 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ._base import IncorrectDatabaseSetup
from .postgres import PostgresEngine
from .sqlite3 import Sqlite3Engine
import importlib
import platform
SUPPORTED_MODULE = {
"sqlite3": Sqlite3Engine,
"psycopg2": PostgresEngine,
}
def create_engine(database_config):
name = database_config["name"]
engine_class = SUPPORTED_MODULE.get(name, None)
if engine_class:
# pypy requires psycopg2cffi rather than psycopg2
if (name == "psycopg2" and
platform.python_implementation() == "PyPy"):
name = "psycopg2cffi"
module = importlib.import_module(name)
return engine_class(module, database_config)
raise RuntimeError(
"Unsupported database engine '%s'" % (name,)
)
__all__ = ["create_engine", "IncorrectDatabaseSetup"]
|
Fix pep8 error on psycopg2cffi hack
|
Fix pep8 error on psycopg2cffi hack
|
Python
|
apache-2.0
|
matrix-org/synapse,matrix-org/synapse,matrix-org/synapse,matrix-org/synapse,matrix-org/synapse,matrix-org/synapse
|
# -*- coding: utf-8 -*-
# Copyright 2015, 2016 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ._base import IncorrectDatabaseSetup
from .postgres import PostgresEngine
from .sqlite3 import Sqlite3Engine
import importlib
import platform
SUPPORTED_MODULE = {
"sqlite3": Sqlite3Engine,
"psycopg2": PostgresEngine,
}
def create_engine(database_config):
name = database_config["name"]
engine_class = SUPPORTED_MODULE.get(name, None)
if engine_class:
needs_pypy_hack = (name == "psycopg2" and
platform.python_implementation() == "PyPy")
if needs_pypy_hack:
module = importlib.import_module("psycopg2cffi")
else:
module = importlib.import_module(name)
return engine_class(module, database_config)
raise RuntimeError(
"Unsupported database engine '%s'" % (name,)
)
__all__ = ["create_engine", "IncorrectDatabaseSetup"]
Fix pep8 error on psycopg2cffi hack
|
# -*- coding: utf-8 -*-
# Copyright 2015, 2016 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ._base import IncorrectDatabaseSetup
from .postgres import PostgresEngine
from .sqlite3 import Sqlite3Engine
import importlib
import platform
SUPPORTED_MODULE = {
"sqlite3": Sqlite3Engine,
"psycopg2": PostgresEngine,
}
def create_engine(database_config):
name = database_config["name"]
engine_class = SUPPORTED_MODULE.get(name, None)
if engine_class:
# pypy requires psycopg2cffi rather than psycopg2
if (name == "psycopg2" and
platform.python_implementation() == "PyPy"):
name = "psycopg2cffi"
module = importlib.import_module(name)
return engine_class(module, database_config)
raise RuntimeError(
"Unsupported database engine '%s'" % (name,)
)
__all__ = ["create_engine", "IncorrectDatabaseSetup"]
|
<commit_before># -*- coding: utf-8 -*-
# Copyright 2015, 2016 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ._base import IncorrectDatabaseSetup
from .postgres import PostgresEngine
from .sqlite3 import Sqlite3Engine
import importlib
import platform
SUPPORTED_MODULE = {
"sqlite3": Sqlite3Engine,
"psycopg2": PostgresEngine,
}
def create_engine(database_config):
name = database_config["name"]
engine_class = SUPPORTED_MODULE.get(name, None)
if engine_class:
needs_pypy_hack = (name == "psycopg2" and
platform.python_implementation() == "PyPy")
if needs_pypy_hack:
module = importlib.import_module("psycopg2cffi")
else:
module = importlib.import_module(name)
return engine_class(module, database_config)
raise RuntimeError(
"Unsupported database engine '%s'" % (name,)
)
__all__ = ["create_engine", "IncorrectDatabaseSetup"]
<commit_msg>Fix pep8 error on psycopg2cffi hack<commit_after>
|
# -*- coding: utf-8 -*-
# Copyright 2015, 2016 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ._base import IncorrectDatabaseSetup
from .postgres import PostgresEngine
from .sqlite3 import Sqlite3Engine
import importlib
import platform
SUPPORTED_MODULE = {
"sqlite3": Sqlite3Engine,
"psycopg2": PostgresEngine,
}
def create_engine(database_config):
name = database_config["name"]
engine_class = SUPPORTED_MODULE.get(name, None)
if engine_class:
# pypy requires psycopg2cffi rather than psycopg2
if (name == "psycopg2" and
platform.python_implementation() == "PyPy"):
name = "psycopg2cffi"
module = importlib.import_module(name)
return engine_class(module, database_config)
raise RuntimeError(
"Unsupported database engine '%s'" % (name,)
)
__all__ = ["create_engine", "IncorrectDatabaseSetup"]
|
# -*- coding: utf-8 -*-
# Copyright 2015, 2016 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ._base import IncorrectDatabaseSetup
from .postgres import PostgresEngine
from .sqlite3 import Sqlite3Engine
import importlib
import platform
SUPPORTED_MODULE = {
"sqlite3": Sqlite3Engine,
"psycopg2": PostgresEngine,
}
def create_engine(database_config):
name = database_config["name"]
engine_class = SUPPORTED_MODULE.get(name, None)
if engine_class:
needs_pypy_hack = (name == "psycopg2" and
platform.python_implementation() == "PyPy")
if needs_pypy_hack:
module = importlib.import_module("psycopg2cffi")
else:
module = importlib.import_module(name)
return engine_class(module, database_config)
raise RuntimeError(
"Unsupported database engine '%s'" % (name,)
)
__all__ = ["create_engine", "IncorrectDatabaseSetup"]
Fix pep8 error on psycopg2cffi hack# -*- coding: utf-8 -*-
# Copyright 2015, 2016 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ._base import IncorrectDatabaseSetup
from .postgres import PostgresEngine
from .sqlite3 import Sqlite3Engine
import importlib
import platform
SUPPORTED_MODULE = {
"sqlite3": Sqlite3Engine,
"psycopg2": PostgresEngine,
}
def create_engine(database_config):
name = database_config["name"]
engine_class = SUPPORTED_MODULE.get(name, None)
if engine_class:
# pypy requires psycopg2cffi rather than psycopg2
if (name == "psycopg2" and
platform.python_implementation() == "PyPy"):
name = "psycopg2cffi"
module = importlib.import_module(name)
return engine_class(module, database_config)
raise RuntimeError(
"Unsupported database engine '%s'" % (name,)
)
__all__ = ["create_engine", "IncorrectDatabaseSetup"]
|
<commit_before># -*- coding: utf-8 -*-
# Copyright 2015, 2016 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ._base import IncorrectDatabaseSetup
from .postgres import PostgresEngine
from .sqlite3 import Sqlite3Engine
import importlib
import platform
SUPPORTED_MODULE = {
"sqlite3": Sqlite3Engine,
"psycopg2": PostgresEngine,
}
def create_engine(database_config):
name = database_config["name"]
engine_class = SUPPORTED_MODULE.get(name, None)
if engine_class:
needs_pypy_hack = (name == "psycopg2" and
platform.python_implementation() == "PyPy")
if needs_pypy_hack:
module = importlib.import_module("psycopg2cffi")
else:
module = importlib.import_module(name)
return engine_class(module, database_config)
raise RuntimeError(
"Unsupported database engine '%s'" % (name,)
)
__all__ = ["create_engine", "IncorrectDatabaseSetup"]
<commit_msg>Fix pep8 error on psycopg2cffi hack<commit_after># -*- coding: utf-8 -*-
# Copyright 2015, 2016 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ._base import IncorrectDatabaseSetup
from .postgres import PostgresEngine
from .sqlite3 import Sqlite3Engine
import importlib
import platform
SUPPORTED_MODULE = {
"sqlite3": Sqlite3Engine,
"psycopg2": PostgresEngine,
}
def create_engine(database_config):
name = database_config["name"]
engine_class = SUPPORTED_MODULE.get(name, None)
if engine_class:
# pypy requires psycopg2cffi rather than psycopg2
if (name == "psycopg2" and
platform.python_implementation() == "PyPy"):
name = "psycopg2cffi"
module = importlib.import_module(name)
return engine_class(module, database_config)
raise RuntimeError(
"Unsupported database engine '%s'" % (name,)
)
__all__ = ["create_engine", "IncorrectDatabaseSetup"]
|
bc9636bbc251fd200b50251489f37792d660c69d
|
test/data/static_analysis_output.py
|
test/data/static_analysis_output.py
|
import unittest
class TestSimpleClass(unittest.TestCase):
def test_simple_method(self):
assert False # TODO: implement your test here
def test_simple_method_with_one_arg(self):
assert False # TODO: implement your test here
class TestClassWithInit(unittest.TestCase):
def test_object_initialization(self):
assert False # TODO: implement your test here
def test_method(self):
assert False # TODO: implement your test here
class TestOldStyleClass(unittest.TestCase):
def test_m(self):
assert False # TODO: implement your test here
class TestSubclassOfEmpty(unittest.TestCase):
def test_new_method(self):
assert False # TODO: implement your test here
class TestStandAloneFunction(unittest.TestCase):
def test_stand_alone_function(self):
assert False # TODO: implement your test here
class TestTopLevelClass(unittest.TestCase):
def test_method(self):
assert False # TODO: implement your test here
if __name__ == '__main__':
unittest.main()
|
import unittest
class TestSimpleClass(unittest.TestCase):
def test_simple_method(self):
assert False # TODO: implement your test here
def test_method_with_one_arg(self):
assert False # TODO: implement your test here
class TestClassWithInit(unittest.TestCase):
def test_object_initialization(self):
assert False # TODO: implement your test here
def test_method(self):
assert False # TODO: implement your test here
class TestOldStyleClass(unittest.TestCase):
def test_m(self):
assert False # TODO: implement your test here
class TestSubclassOfEmpty(unittest.TestCase):
def test_new_method(self):
assert False # TODO: implement your test here
class TestStandAloneFunction(unittest.TestCase):
def test_stand_alone_function(self):
assert False # TODO: implement your test here
class TestTopLevelClass(unittest.TestCase):
def test_method(self):
assert False # TODO: implement your test here
if __name__ == '__main__':
unittest.main()
|
Fix for the static analysis acceptance test.
|
Fix for the static analysis acceptance test.
|
Python
|
mit
|
mkwiatkowski/pythoscope,mkwiatkowski/pythoscope
|
import unittest
class TestSimpleClass(unittest.TestCase):
def test_simple_method(self):
assert False # TODO: implement your test here
def test_simple_method_with_one_arg(self):
assert False # TODO: implement your test here
class TestClassWithInit(unittest.TestCase):
def test_object_initialization(self):
assert False # TODO: implement your test here
def test_method(self):
assert False # TODO: implement your test here
class TestOldStyleClass(unittest.TestCase):
def test_m(self):
assert False # TODO: implement your test here
class TestSubclassOfEmpty(unittest.TestCase):
def test_new_method(self):
assert False # TODO: implement your test here
class TestStandAloneFunction(unittest.TestCase):
def test_stand_alone_function(self):
assert False # TODO: implement your test here
class TestTopLevelClass(unittest.TestCase):
def test_method(self):
assert False # TODO: implement your test here
if __name__ == '__main__':
unittest.main()
Fix for the static analysis acceptance test.
|
import unittest
class TestSimpleClass(unittest.TestCase):
def test_simple_method(self):
assert False # TODO: implement your test here
def test_method_with_one_arg(self):
assert False # TODO: implement your test here
class TestClassWithInit(unittest.TestCase):
def test_object_initialization(self):
assert False # TODO: implement your test here
def test_method(self):
assert False # TODO: implement your test here
class TestOldStyleClass(unittest.TestCase):
def test_m(self):
assert False # TODO: implement your test here
class TestSubclassOfEmpty(unittest.TestCase):
def test_new_method(self):
assert False # TODO: implement your test here
class TestStandAloneFunction(unittest.TestCase):
def test_stand_alone_function(self):
assert False # TODO: implement your test here
class TestTopLevelClass(unittest.TestCase):
def test_method(self):
assert False # TODO: implement your test here
if __name__ == '__main__':
unittest.main()
|
<commit_before>import unittest
class TestSimpleClass(unittest.TestCase):
def test_simple_method(self):
assert False # TODO: implement your test here
def test_simple_method_with_one_arg(self):
assert False # TODO: implement your test here
class TestClassWithInit(unittest.TestCase):
def test_object_initialization(self):
assert False # TODO: implement your test here
def test_method(self):
assert False # TODO: implement your test here
class TestOldStyleClass(unittest.TestCase):
def test_m(self):
assert False # TODO: implement your test here
class TestSubclassOfEmpty(unittest.TestCase):
def test_new_method(self):
assert False # TODO: implement your test here
class TestStandAloneFunction(unittest.TestCase):
def test_stand_alone_function(self):
assert False # TODO: implement your test here
class TestTopLevelClass(unittest.TestCase):
def test_method(self):
assert False # TODO: implement your test here
if __name__ == '__main__':
unittest.main()
<commit_msg> Fix for the static analysis acceptance test.<commit_after>
|
import unittest
class TestSimpleClass(unittest.TestCase):
def test_simple_method(self):
assert False # TODO: implement your test here
def test_method_with_one_arg(self):
assert False # TODO: implement your test here
class TestClassWithInit(unittest.TestCase):
def test_object_initialization(self):
assert False # TODO: implement your test here
def test_method(self):
assert False # TODO: implement your test here
class TestOldStyleClass(unittest.TestCase):
def test_m(self):
assert False # TODO: implement your test here
class TestSubclassOfEmpty(unittest.TestCase):
def test_new_method(self):
assert False # TODO: implement your test here
class TestStandAloneFunction(unittest.TestCase):
def test_stand_alone_function(self):
assert False # TODO: implement your test here
class TestTopLevelClass(unittest.TestCase):
def test_method(self):
assert False # TODO: implement your test here
if __name__ == '__main__':
unittest.main()
|
import unittest
class TestSimpleClass(unittest.TestCase):
def test_simple_method(self):
assert False # TODO: implement your test here
def test_simple_method_with_one_arg(self):
assert False # TODO: implement your test here
class TestClassWithInit(unittest.TestCase):
def test_object_initialization(self):
assert False # TODO: implement your test here
def test_method(self):
assert False # TODO: implement your test here
class TestOldStyleClass(unittest.TestCase):
def test_m(self):
assert False # TODO: implement your test here
class TestSubclassOfEmpty(unittest.TestCase):
def test_new_method(self):
assert False # TODO: implement your test here
class TestStandAloneFunction(unittest.TestCase):
def test_stand_alone_function(self):
assert False # TODO: implement your test here
class TestTopLevelClass(unittest.TestCase):
def test_method(self):
assert False # TODO: implement your test here
if __name__ == '__main__':
unittest.main()
Fix for the static analysis acceptance test.import unittest
class TestSimpleClass(unittest.TestCase):
def test_simple_method(self):
assert False # TODO: implement your test here
def test_method_with_one_arg(self):
assert False # TODO: implement your test here
class TestClassWithInit(unittest.TestCase):
def test_object_initialization(self):
assert False # TODO: implement your test here
def test_method(self):
assert False # TODO: implement your test here
class TestOldStyleClass(unittest.TestCase):
def test_m(self):
assert False # TODO: implement your test here
class TestSubclassOfEmpty(unittest.TestCase):
def test_new_method(self):
assert False # TODO: implement your test here
class TestStandAloneFunction(unittest.TestCase):
def test_stand_alone_function(self):
assert False # TODO: implement your test here
class TestTopLevelClass(unittest.TestCase):
def test_method(self):
assert False # TODO: implement your test here
if __name__ == '__main__':
unittest.main()
|
<commit_before>import unittest
class TestSimpleClass(unittest.TestCase):
def test_simple_method(self):
assert False # TODO: implement your test here
def test_simple_method_with_one_arg(self):
assert False # TODO: implement your test here
class TestClassWithInit(unittest.TestCase):
def test_object_initialization(self):
assert False # TODO: implement your test here
def test_method(self):
assert False # TODO: implement your test here
class TestOldStyleClass(unittest.TestCase):
def test_m(self):
assert False # TODO: implement your test here
class TestSubclassOfEmpty(unittest.TestCase):
def test_new_method(self):
assert False # TODO: implement your test here
class TestStandAloneFunction(unittest.TestCase):
def test_stand_alone_function(self):
assert False # TODO: implement your test here
class TestTopLevelClass(unittest.TestCase):
def test_method(self):
assert False # TODO: implement your test here
if __name__ == '__main__':
unittest.main()
<commit_msg> Fix for the static analysis acceptance test.<commit_after>import unittest
class TestSimpleClass(unittest.TestCase):
def test_simple_method(self):
assert False # TODO: implement your test here
def test_method_with_one_arg(self):
assert False # TODO: implement your test here
class TestClassWithInit(unittest.TestCase):
def test_object_initialization(self):
assert False # TODO: implement your test here
def test_method(self):
assert False # TODO: implement your test here
class TestOldStyleClass(unittest.TestCase):
def test_m(self):
assert False # TODO: implement your test here
class TestSubclassOfEmpty(unittest.TestCase):
def test_new_method(self):
assert False # TODO: implement your test here
class TestStandAloneFunction(unittest.TestCase):
def test_stand_alone_function(self):
assert False # TODO: implement your test here
class TestTopLevelClass(unittest.TestCase):
def test_method(self):
assert False # TODO: implement your test here
if __name__ == '__main__':
unittest.main()
|
c6858c13f479e97193dcf63694694f69a4e18112
|
docker/settings.py
|
docker/settings.py
|
from .base_settings import *
import os
INSTALLED_APPS += [
'data_aggregator.apps.DataAggregatorConfig',
'webpack_loader',
]
if os.getenv('ENV') == 'localdev':
DEBUG = True
DATA_AGGREGATOR_ACCESS_GROUP = 'u_test_group'
DATA_AGGREGATOR_THREADING_ENABLED = False
RESTCLIENTS_DAO_CACHE_CLASS = None
DATA_AGGREGATOR_THREADING_ENABLED = False
else:
DATA_AGGREGATOR_ACCESS_GROUP = os.getenv('ACCESS_GROUP', '')
DATA_AGGREGATOR_THREADING_ENABLED = True
WEBPACK_LOADER = {
'DEFAULT': {
'BUNDLE_DIR_NAME': 'data_aggregator/bundles/',
'STATS_FILE': os.path.join(BASE_DIR, 'data_aggregator', 'static', 'webpack-stats.json'),
}
}
RESTCLIENTS_CANVAS_POOL_SIZE = 25
ACADEMIC_CANVAS_ACCOUNT_ID = '84378'
|
from .base_settings import *
import os
INSTALLED_APPS += [
'data_aggregator.apps.DataAggregatorConfig',
'webpack_loader',
]
if os.getenv('ENV') == 'localdev':
DEBUG = True
DATA_AGGREGATOR_ACCESS_GROUP = 'u_test_group'
DATA_AGGREGATOR_THREADING_ENABLED = False
RESTCLIENTS_DAO_CACHE_CLASS = None
DATA_AGGREGATOR_THREADING_ENABLED = False
else:
DATA_AGGREGATOR_ACCESS_GROUP = os.getenv('ACCESS_GROUP', '')
DATA_AGGREGATOR_THREADING_ENABLED = True
WEBPACK_LOADER = {
'DEFAULT': {
'BUNDLE_DIR_NAME': 'data_aggregator/bundles/',
'STATS_FILE': os.path.join(BASE_DIR, 'data_aggregator', 'static', 'webpack-stats.json'),
}
}
RESTCLIENTS_CANVAS_POOL_SIZE = 50
ACADEMIC_CANVAS_ACCOUNT_ID = '84378'
|
Increase rest client connection pool size to 50
|
Increase rest client connection pool size to 50
|
Python
|
apache-2.0
|
uw-it-aca/canvas-analytics,uw-it-aca/canvas-analytics,uw-it-aca/canvas-analytics,uw-it-aca/canvas-analytics
|
from .base_settings import *
import os
INSTALLED_APPS += [
'data_aggregator.apps.DataAggregatorConfig',
'webpack_loader',
]
if os.getenv('ENV') == 'localdev':
DEBUG = True
DATA_AGGREGATOR_ACCESS_GROUP = 'u_test_group'
DATA_AGGREGATOR_THREADING_ENABLED = False
RESTCLIENTS_DAO_CACHE_CLASS = None
DATA_AGGREGATOR_THREADING_ENABLED = False
else:
DATA_AGGREGATOR_ACCESS_GROUP = os.getenv('ACCESS_GROUP', '')
DATA_AGGREGATOR_THREADING_ENABLED = True
WEBPACK_LOADER = {
'DEFAULT': {
'BUNDLE_DIR_NAME': 'data_aggregator/bundles/',
'STATS_FILE': os.path.join(BASE_DIR, 'data_aggregator', 'static', 'webpack-stats.json'),
}
}
RESTCLIENTS_CANVAS_POOL_SIZE = 25
ACADEMIC_CANVAS_ACCOUNT_ID = '84378'
Increase rest client connection pool size to 50
|
from .base_settings import *
import os
INSTALLED_APPS += [
'data_aggregator.apps.DataAggregatorConfig',
'webpack_loader',
]
if os.getenv('ENV') == 'localdev':
DEBUG = True
DATA_AGGREGATOR_ACCESS_GROUP = 'u_test_group'
DATA_AGGREGATOR_THREADING_ENABLED = False
RESTCLIENTS_DAO_CACHE_CLASS = None
DATA_AGGREGATOR_THREADING_ENABLED = False
else:
DATA_AGGREGATOR_ACCESS_GROUP = os.getenv('ACCESS_GROUP', '')
DATA_AGGREGATOR_THREADING_ENABLED = True
WEBPACK_LOADER = {
'DEFAULT': {
'BUNDLE_DIR_NAME': 'data_aggregator/bundles/',
'STATS_FILE': os.path.join(BASE_DIR, 'data_aggregator', 'static', 'webpack-stats.json'),
}
}
RESTCLIENTS_CANVAS_POOL_SIZE = 50
ACADEMIC_CANVAS_ACCOUNT_ID = '84378'
|
<commit_before>from .base_settings import *
import os
INSTALLED_APPS += [
'data_aggregator.apps.DataAggregatorConfig',
'webpack_loader',
]
if os.getenv('ENV') == 'localdev':
DEBUG = True
DATA_AGGREGATOR_ACCESS_GROUP = 'u_test_group'
DATA_AGGREGATOR_THREADING_ENABLED = False
RESTCLIENTS_DAO_CACHE_CLASS = None
DATA_AGGREGATOR_THREADING_ENABLED = False
else:
DATA_AGGREGATOR_ACCESS_GROUP = os.getenv('ACCESS_GROUP', '')
DATA_AGGREGATOR_THREADING_ENABLED = True
WEBPACK_LOADER = {
'DEFAULT': {
'BUNDLE_DIR_NAME': 'data_aggregator/bundles/',
'STATS_FILE': os.path.join(BASE_DIR, 'data_aggregator', 'static', 'webpack-stats.json'),
}
}
RESTCLIENTS_CANVAS_POOL_SIZE = 25
ACADEMIC_CANVAS_ACCOUNT_ID = '84378'
<commit_msg>Increase rest client connection pool size to 50<commit_after>
|
from .base_settings import *
import os
INSTALLED_APPS += [
'data_aggregator.apps.DataAggregatorConfig',
'webpack_loader',
]
if os.getenv('ENV') == 'localdev':
DEBUG = True
DATA_AGGREGATOR_ACCESS_GROUP = 'u_test_group'
DATA_AGGREGATOR_THREADING_ENABLED = False
RESTCLIENTS_DAO_CACHE_CLASS = None
DATA_AGGREGATOR_THREADING_ENABLED = False
else:
DATA_AGGREGATOR_ACCESS_GROUP = os.getenv('ACCESS_GROUP', '')
DATA_AGGREGATOR_THREADING_ENABLED = True
WEBPACK_LOADER = {
'DEFAULT': {
'BUNDLE_DIR_NAME': 'data_aggregator/bundles/',
'STATS_FILE': os.path.join(BASE_DIR, 'data_aggregator', 'static', 'webpack-stats.json'),
}
}
RESTCLIENTS_CANVAS_POOL_SIZE = 50
ACADEMIC_CANVAS_ACCOUNT_ID = '84378'
|
from .base_settings import *
import os
INSTALLED_APPS += [
'data_aggregator.apps.DataAggregatorConfig',
'webpack_loader',
]
if os.getenv('ENV') == 'localdev':
DEBUG = True
DATA_AGGREGATOR_ACCESS_GROUP = 'u_test_group'
DATA_AGGREGATOR_THREADING_ENABLED = False
RESTCLIENTS_DAO_CACHE_CLASS = None
DATA_AGGREGATOR_THREADING_ENABLED = False
else:
DATA_AGGREGATOR_ACCESS_GROUP = os.getenv('ACCESS_GROUP', '')
DATA_AGGREGATOR_THREADING_ENABLED = True
WEBPACK_LOADER = {
'DEFAULT': {
'BUNDLE_DIR_NAME': 'data_aggregator/bundles/',
'STATS_FILE': os.path.join(BASE_DIR, 'data_aggregator', 'static', 'webpack-stats.json'),
}
}
RESTCLIENTS_CANVAS_POOL_SIZE = 25
ACADEMIC_CANVAS_ACCOUNT_ID = '84378'
Increase rest client connection pool size to 50from .base_settings import *
import os
INSTALLED_APPS += [
'data_aggregator.apps.DataAggregatorConfig',
'webpack_loader',
]
if os.getenv('ENV') == 'localdev':
DEBUG = True
DATA_AGGREGATOR_ACCESS_GROUP = 'u_test_group'
DATA_AGGREGATOR_THREADING_ENABLED = False
RESTCLIENTS_DAO_CACHE_CLASS = None
DATA_AGGREGATOR_THREADING_ENABLED = False
else:
DATA_AGGREGATOR_ACCESS_GROUP = os.getenv('ACCESS_GROUP', '')
DATA_AGGREGATOR_THREADING_ENABLED = True
WEBPACK_LOADER = {
'DEFAULT': {
'BUNDLE_DIR_NAME': 'data_aggregator/bundles/',
'STATS_FILE': os.path.join(BASE_DIR, 'data_aggregator', 'static', 'webpack-stats.json'),
}
}
RESTCLIENTS_CANVAS_POOL_SIZE = 50
ACADEMIC_CANVAS_ACCOUNT_ID = '84378'
|
<commit_before>from .base_settings import *
import os
INSTALLED_APPS += [
'data_aggregator.apps.DataAggregatorConfig',
'webpack_loader',
]
if os.getenv('ENV') == 'localdev':
DEBUG = True
DATA_AGGREGATOR_ACCESS_GROUP = 'u_test_group'
DATA_AGGREGATOR_THREADING_ENABLED = False
RESTCLIENTS_DAO_CACHE_CLASS = None
DATA_AGGREGATOR_THREADING_ENABLED = False
else:
DATA_AGGREGATOR_ACCESS_GROUP = os.getenv('ACCESS_GROUP', '')
DATA_AGGREGATOR_THREADING_ENABLED = True
WEBPACK_LOADER = {
'DEFAULT': {
'BUNDLE_DIR_NAME': 'data_aggregator/bundles/',
'STATS_FILE': os.path.join(BASE_DIR, 'data_aggregator', 'static', 'webpack-stats.json'),
}
}
RESTCLIENTS_CANVAS_POOL_SIZE = 25
ACADEMIC_CANVAS_ACCOUNT_ID = '84378'
<commit_msg>Increase rest client connection pool size to 50<commit_after>from .base_settings import *
import os
INSTALLED_APPS += [
'data_aggregator.apps.DataAggregatorConfig',
'webpack_loader',
]
if os.getenv('ENV') == 'localdev':
DEBUG = True
DATA_AGGREGATOR_ACCESS_GROUP = 'u_test_group'
DATA_AGGREGATOR_THREADING_ENABLED = False
RESTCLIENTS_DAO_CACHE_CLASS = None
DATA_AGGREGATOR_THREADING_ENABLED = False
else:
DATA_AGGREGATOR_ACCESS_GROUP = os.getenv('ACCESS_GROUP', '')
DATA_AGGREGATOR_THREADING_ENABLED = True
WEBPACK_LOADER = {
'DEFAULT': {
'BUNDLE_DIR_NAME': 'data_aggregator/bundles/',
'STATS_FILE': os.path.join(BASE_DIR, 'data_aggregator', 'static', 'webpack-stats.json'),
}
}
RESTCLIENTS_CANVAS_POOL_SIZE = 50
ACADEMIC_CANVAS_ACCOUNT_ID = '84378'
|
d8cc0fdaea848ed5d626ba6ba4292fd3cb906da3
|
project7/TrackParser.py
|
project7/TrackParser.py
|
""" Created by Max 12/2/2017 """
import pprint
import numpy as np
class TrackParser:
@staticmethod
def parse_track(path_to_track_file: str) -> np.ndarray:
track = None
with open(path_to_track_file, 'r') as track_file:
lines = track_file.readlines()
dimensions_str = lines[0]
dims = dimensions_str.split(',')
track = np.zeros((int(dims[0]), int(dims[1])))
for line_index in range(1, len(lines)):
line = lines[line_index]
for char_index in range(len(line) - 1):
track_value = TrackParser.get_char_value(line[char_index])
track[line_index-1][char_index] = track_value
return track
@staticmethod
def get_char_value(char: str):
if char == '#':
return -1
elif char == '.':
return 0
elif char == 'S':
return 1
elif char == 'F':
return 2
else:
return -1
np.set_printoptions(linewidth=500)
pprint.pprint(TrackParser.parse_track("tracks/L-track.txt"), width=500)
|
""" Created by Max 12/2/2017 """
import pprint
import numpy as np
class TrackParser:
@staticmethod
def parse_track(path_to_track_file: str) -> np.ndarray:
track = None
with open(path_to_track_file, 'r') as track_file:
lines = track_file.readlines()
dimensions_str = lines[0]
dims = dimensions_str.split(',')
# (Y,X) coords.
track = np.zeros((int(dims[0]), int(dims[1])))
for line_index in range(1, len(lines)):
line = lines[line_index]
for char_index in range(len(line) - 1):
track_value = TrackParser.get_char_value(line[char_index])
track[line_index-1][char_index] = track_value
return track
@staticmethod
def get_char_value(char: str):
if char == '#':
return -1
elif char == '.':
return 0
elif char == 'S':
return 1
elif char == 'F':
return 2
else:
return -1
# np.set_printoptions(linewidth=500)
# pprint.pprint(TrackParser.parse_track("tracks/L-track.txt"), width=500)
|
Add comment to clarify coordinate order
|
Add comment to clarify coordinate order
coordinates are (y,x) in the track.
|
Python
|
apache-2.0
|
MaxRobinson/CS449,MaxRobinson/CS449,MaxRobinson/CS449
|
""" Created by Max 12/2/2017 """
import pprint
import numpy as np
class TrackParser:
@staticmethod
def parse_track(path_to_track_file: str) -> np.ndarray:
track = None
with open(path_to_track_file, 'r') as track_file:
lines = track_file.readlines()
dimensions_str = lines[0]
dims = dimensions_str.split(',')
track = np.zeros((int(dims[0]), int(dims[1])))
for line_index in range(1, len(lines)):
line = lines[line_index]
for char_index in range(len(line) - 1):
track_value = TrackParser.get_char_value(line[char_index])
track[line_index-1][char_index] = track_value
return track
@staticmethod
def get_char_value(char: str):
if char == '#':
return -1
elif char == '.':
return 0
elif char == 'S':
return 1
elif char == 'F':
return 2
else:
return -1
np.set_printoptions(linewidth=500)
pprint.pprint(TrackParser.parse_track("tracks/L-track.txt"), width=500)
Add comment to clarify coordinate order
coordinates are (y,x) in the track.
|
""" Created by Max 12/2/2017 """
import pprint
import numpy as np
class TrackParser:
@staticmethod
def parse_track(path_to_track_file: str) -> np.ndarray:
track = None
with open(path_to_track_file, 'r') as track_file:
lines = track_file.readlines()
dimensions_str = lines[0]
dims = dimensions_str.split(',')
# (Y,X) coords.
track = np.zeros((int(dims[0]), int(dims[1])))
for line_index in range(1, len(lines)):
line = lines[line_index]
for char_index in range(len(line) - 1):
track_value = TrackParser.get_char_value(line[char_index])
track[line_index-1][char_index] = track_value
return track
@staticmethod
def get_char_value(char: str):
if char == '#':
return -1
elif char == '.':
return 0
elif char == 'S':
return 1
elif char == 'F':
return 2
else:
return -1
# np.set_printoptions(linewidth=500)
# pprint.pprint(TrackParser.parse_track("tracks/L-track.txt"), width=500)
|
<commit_before>""" Created by Max 12/2/2017 """
import pprint
import numpy as np
class TrackParser:
@staticmethod
def parse_track(path_to_track_file: str) -> np.ndarray:
track = None
with open(path_to_track_file, 'r') as track_file:
lines = track_file.readlines()
dimensions_str = lines[0]
dims = dimensions_str.split(',')
track = np.zeros((int(dims[0]), int(dims[1])))
for line_index in range(1, len(lines)):
line = lines[line_index]
for char_index in range(len(line) - 1):
track_value = TrackParser.get_char_value(line[char_index])
track[line_index-1][char_index] = track_value
return track
@staticmethod
def get_char_value(char: str):
if char == '#':
return -1
elif char == '.':
return 0
elif char == 'S':
return 1
elif char == 'F':
return 2
else:
return -1
np.set_printoptions(linewidth=500)
pprint.pprint(TrackParser.parse_track("tracks/L-track.txt"), width=500)
<commit_msg>Add comment to clarify coordinate order
coordinates are (y,x) in the track.<commit_after>
|
""" Created by Max 12/2/2017 """
import pprint
import numpy as np
class TrackParser:
@staticmethod
def parse_track(path_to_track_file: str) -> np.ndarray:
track = None
with open(path_to_track_file, 'r') as track_file:
lines = track_file.readlines()
dimensions_str = lines[0]
dims = dimensions_str.split(',')
# (Y,X) coords.
track = np.zeros((int(dims[0]), int(dims[1])))
for line_index in range(1, len(lines)):
line = lines[line_index]
for char_index in range(len(line) - 1):
track_value = TrackParser.get_char_value(line[char_index])
track[line_index-1][char_index] = track_value
return track
@staticmethod
def get_char_value(char: str):
if char == '#':
return -1
elif char == '.':
return 0
elif char == 'S':
return 1
elif char == 'F':
return 2
else:
return -1
# np.set_printoptions(linewidth=500)
# pprint.pprint(TrackParser.parse_track("tracks/L-track.txt"), width=500)
|
""" Created by Max 12/2/2017 """
import pprint
import numpy as np
class TrackParser:
@staticmethod
def parse_track(path_to_track_file: str) -> np.ndarray:
track = None
with open(path_to_track_file, 'r') as track_file:
lines = track_file.readlines()
dimensions_str = lines[0]
dims = dimensions_str.split(',')
track = np.zeros((int(dims[0]), int(dims[1])))
for line_index in range(1, len(lines)):
line = lines[line_index]
for char_index in range(len(line) - 1):
track_value = TrackParser.get_char_value(line[char_index])
track[line_index-1][char_index] = track_value
return track
@staticmethod
def get_char_value(char: str):
if char == '#':
return -1
elif char == '.':
return 0
elif char == 'S':
return 1
elif char == 'F':
return 2
else:
return -1
np.set_printoptions(linewidth=500)
pprint.pprint(TrackParser.parse_track("tracks/L-track.txt"), width=500)
Add comment to clarify coordinate order
coordinates are (y,x) in the track.""" Created by Max 12/2/2017 """
import pprint
import numpy as np
class TrackParser:
@staticmethod
def parse_track(path_to_track_file: str) -> np.ndarray:
track = None
with open(path_to_track_file, 'r') as track_file:
lines = track_file.readlines()
dimensions_str = lines[0]
dims = dimensions_str.split(',')
# (Y,X) coords.
track = np.zeros((int(dims[0]), int(dims[1])))
for line_index in range(1, len(lines)):
line = lines[line_index]
for char_index in range(len(line) - 1):
track_value = TrackParser.get_char_value(line[char_index])
track[line_index-1][char_index] = track_value
return track
@staticmethod
def get_char_value(char: str):
if char == '#':
return -1
elif char == '.':
return 0
elif char == 'S':
return 1
elif char == 'F':
return 2
else:
return -1
# np.set_printoptions(linewidth=500)
# pprint.pprint(TrackParser.parse_track("tracks/L-track.txt"), width=500)
|
<commit_before>""" Created by Max 12/2/2017 """
import pprint
import numpy as np
class TrackParser:
@staticmethod
def parse_track(path_to_track_file: str) -> np.ndarray:
track = None
with open(path_to_track_file, 'r') as track_file:
lines = track_file.readlines()
dimensions_str = lines[0]
dims = dimensions_str.split(',')
track = np.zeros((int(dims[0]), int(dims[1])))
for line_index in range(1, len(lines)):
line = lines[line_index]
for char_index in range(len(line) - 1):
track_value = TrackParser.get_char_value(line[char_index])
track[line_index-1][char_index] = track_value
return track
@staticmethod
def get_char_value(char: str):
if char == '#':
return -1
elif char == '.':
return 0
elif char == 'S':
return 1
elif char == 'F':
return 2
else:
return -1
np.set_printoptions(linewidth=500)
pprint.pprint(TrackParser.parse_track("tracks/L-track.txt"), width=500)
<commit_msg>Add comment to clarify coordinate order
coordinates are (y,x) in the track.<commit_after>""" Created by Max 12/2/2017 """
import pprint
import numpy as np
class TrackParser:
@staticmethod
def parse_track(path_to_track_file: str) -> np.ndarray:
track = None
with open(path_to_track_file, 'r') as track_file:
lines = track_file.readlines()
dimensions_str = lines[0]
dims = dimensions_str.split(',')
# (Y,X) coords.
track = np.zeros((int(dims[0]), int(dims[1])))
for line_index in range(1, len(lines)):
line = lines[line_index]
for char_index in range(len(line) - 1):
track_value = TrackParser.get_char_value(line[char_index])
track[line_index-1][char_index] = track_value
return track
@staticmethod
def get_char_value(char: str):
if char == '#':
return -1
elif char == '.':
return 0
elif char == 'S':
return 1
elif char == 'F':
return 2
else:
return -1
# np.set_printoptions(linewidth=500)
# pprint.pprint(TrackParser.parse_track("tracks/L-track.txt"), width=500)
|
2806254823ae46e4a8fd7204cda58be6eea18743
|
tests/10_test_elbaas.py
|
tests/10_test_elbaas.py
|
import otc
class TestElbClient:
"""ELB client tests"""
def setUp(self):
"""Setup test cloud"""
self.cloud = otc.OtcCloud(cloud='test')
def tearDown(self):
pass
def test_elbclient_user_agent(self):
"""Check user agent"""
assert self.cloud.elbclient.client.USER_AGENT == 'python-otcclient'
def test_elbclient_elb(self):
"""List elbs"""
elbs = self.cloud.elbclient.elb.list()
assert len(elbs) >= 0
elbs = self.cloud.elbclient.elb.list(vpcid='foo')
assert len(elbs) >= 0
elbs = self.cloud.elbclient.elb.list('foo')
assert len(elbs) >= 0
def test_elbclient_listener(self):
"""List listeners"""
lstns = self.cloud.elbclient.listener.list()
assert len(lstns) >= 0
lstns = self.cloud.elbclient.listener.list('foo')
assert len(lstns) >= 0
lstns = self.cloud.elbclient.listener.list(elbid='foo')
assert len(lstns) >= 0
# vim: sts=4 sw=4 ts=4 et:
|
import otc
class TestElbClient:
"""ELB client tests"""
def setUp(self):
"""Setup test cloud"""
self.cloud = otc.OtcCloud(cloud='test')
def tearDown(self):
pass
def test_elbclient_user_agent(self):
"""Check user agent"""
assert self.cloud.elbclient.client.USER_AGENT == 'python-otcclient'
def test_elbclient_service_url(self):
"""Check ELB service url"""
assert self.cloud.elbclient.service_url == "https://elb.eu-de.otc.t-systems.com"
def test_elbclient_elb(self):
"""List elbs"""
elbs = self.cloud.elbclient.elb.list()
assert len(elbs) >= 0
elbs = self.cloud.elbclient.elb.list(vpcid='foo')
assert len(elbs) >= 0
elbs = self.cloud.elbclient.elb.list('foo')
assert len(elbs) >= 0
def test_elbclient_listener(self):
"""List listeners"""
lstns = self.cloud.elbclient.listener.list()
assert len(lstns) >= 0
lstns = self.cloud.elbclient.listener.list('foo')
assert len(lstns) >= 0
lstns = self.cloud.elbclient.listener.list(elbid='foo')
assert len(lstns) >= 0
# vim: sts=4 sw=4 ts=4 et:
|
Check the ELB service url
|
Check the ELB service url
|
Python
|
apache-2.0
|
zamiam69/otc
|
import otc
class TestElbClient:
"""ELB client tests"""
def setUp(self):
"""Setup test cloud"""
self.cloud = otc.OtcCloud(cloud='test')
def tearDown(self):
pass
def test_elbclient_user_agent(self):
"""Check user agent"""
assert self.cloud.elbclient.client.USER_AGENT == 'python-otcclient'
def test_elbclient_elb(self):
"""List elbs"""
elbs = self.cloud.elbclient.elb.list()
assert len(elbs) >= 0
elbs = self.cloud.elbclient.elb.list(vpcid='foo')
assert len(elbs) >= 0
elbs = self.cloud.elbclient.elb.list('foo')
assert len(elbs) >= 0
def test_elbclient_listener(self):
"""List listeners"""
lstns = self.cloud.elbclient.listener.list()
assert len(lstns) >= 0
lstns = self.cloud.elbclient.listener.list('foo')
assert len(lstns) >= 0
lstns = self.cloud.elbclient.listener.list(elbid='foo')
assert len(lstns) >= 0
# vim: sts=4 sw=4 ts=4 et:
Check the ELB service url
|
import otc
class TestElbClient:
"""ELB client tests"""
def setUp(self):
"""Setup test cloud"""
self.cloud = otc.OtcCloud(cloud='test')
def tearDown(self):
pass
def test_elbclient_user_agent(self):
"""Check user agent"""
assert self.cloud.elbclient.client.USER_AGENT == 'python-otcclient'
def test_elbclient_service_url(self):
"""Check ELB service url"""
assert self.cloud.elbclient.service_url == "https://elb.eu-de.otc.t-systems.com"
def test_elbclient_elb(self):
"""List elbs"""
elbs = self.cloud.elbclient.elb.list()
assert len(elbs) >= 0
elbs = self.cloud.elbclient.elb.list(vpcid='foo')
assert len(elbs) >= 0
elbs = self.cloud.elbclient.elb.list('foo')
assert len(elbs) >= 0
def test_elbclient_listener(self):
"""List listeners"""
lstns = self.cloud.elbclient.listener.list()
assert len(lstns) >= 0
lstns = self.cloud.elbclient.listener.list('foo')
assert len(lstns) >= 0
lstns = self.cloud.elbclient.listener.list(elbid='foo')
assert len(lstns) >= 0
# vim: sts=4 sw=4 ts=4 et:
|
<commit_before>import otc
class TestElbClient:
"""ELB client tests"""
def setUp(self):
"""Setup test cloud"""
self.cloud = otc.OtcCloud(cloud='test')
def tearDown(self):
pass
def test_elbclient_user_agent(self):
"""Check user agent"""
assert self.cloud.elbclient.client.USER_AGENT == 'python-otcclient'
def test_elbclient_elb(self):
"""List elbs"""
elbs = self.cloud.elbclient.elb.list()
assert len(elbs) >= 0
elbs = self.cloud.elbclient.elb.list(vpcid='foo')
assert len(elbs) >= 0
elbs = self.cloud.elbclient.elb.list('foo')
assert len(elbs) >= 0
def test_elbclient_listener(self):
"""List listeners"""
lstns = self.cloud.elbclient.listener.list()
assert len(lstns) >= 0
lstns = self.cloud.elbclient.listener.list('foo')
assert len(lstns) >= 0
lstns = self.cloud.elbclient.listener.list(elbid='foo')
assert len(lstns) >= 0
# vim: sts=4 sw=4 ts=4 et:
<commit_msg>Check the ELB service url<commit_after>
|
import otc
class TestElbClient:
"""ELB client tests"""
def setUp(self):
"""Setup test cloud"""
self.cloud = otc.OtcCloud(cloud='test')
def tearDown(self):
pass
def test_elbclient_user_agent(self):
"""Check user agent"""
assert self.cloud.elbclient.client.USER_AGENT == 'python-otcclient'
def test_elbclient_service_url(self):
"""Check ELB service url"""
assert self.cloud.elbclient.service_url == "https://elb.eu-de.otc.t-systems.com"
def test_elbclient_elb(self):
"""List elbs"""
elbs = self.cloud.elbclient.elb.list()
assert len(elbs) >= 0
elbs = self.cloud.elbclient.elb.list(vpcid='foo')
assert len(elbs) >= 0
elbs = self.cloud.elbclient.elb.list('foo')
assert len(elbs) >= 0
def test_elbclient_listener(self):
"""List listeners"""
lstns = self.cloud.elbclient.listener.list()
assert len(lstns) >= 0
lstns = self.cloud.elbclient.listener.list('foo')
assert len(lstns) >= 0
lstns = self.cloud.elbclient.listener.list(elbid='foo')
assert len(lstns) >= 0
# vim: sts=4 sw=4 ts=4 et:
|
import otc
class TestElbClient:
"""ELB client tests"""
def setUp(self):
"""Setup test cloud"""
self.cloud = otc.OtcCloud(cloud='test')
def tearDown(self):
pass
def test_elbclient_user_agent(self):
"""Check user agent"""
assert self.cloud.elbclient.client.USER_AGENT == 'python-otcclient'
def test_elbclient_elb(self):
"""List elbs"""
elbs = self.cloud.elbclient.elb.list()
assert len(elbs) >= 0
elbs = self.cloud.elbclient.elb.list(vpcid='foo')
assert len(elbs) >= 0
elbs = self.cloud.elbclient.elb.list('foo')
assert len(elbs) >= 0
def test_elbclient_listener(self):
"""List listeners"""
lstns = self.cloud.elbclient.listener.list()
assert len(lstns) >= 0
lstns = self.cloud.elbclient.listener.list('foo')
assert len(lstns) >= 0
lstns = self.cloud.elbclient.listener.list(elbid='foo')
assert len(lstns) >= 0
# vim: sts=4 sw=4 ts=4 et:
Check the ELB service urlimport otc
class TestElbClient:
"""ELB client tests"""
def setUp(self):
"""Setup test cloud"""
self.cloud = otc.OtcCloud(cloud='test')
def tearDown(self):
pass
def test_elbclient_user_agent(self):
"""Check user agent"""
assert self.cloud.elbclient.client.USER_AGENT == 'python-otcclient'
def test_elbclient_service_url(self):
"""Check ELB service url"""
assert self.cloud.elbclient.service_url == "https://elb.eu-de.otc.t-systems.com"
def test_elbclient_elb(self):
"""List elbs"""
elbs = self.cloud.elbclient.elb.list()
assert len(elbs) >= 0
elbs = self.cloud.elbclient.elb.list(vpcid='foo')
assert len(elbs) >= 0
elbs = self.cloud.elbclient.elb.list('foo')
assert len(elbs) >= 0
def test_elbclient_listener(self):
"""List listeners"""
lstns = self.cloud.elbclient.listener.list()
assert len(lstns) >= 0
lstns = self.cloud.elbclient.listener.list('foo')
assert len(lstns) >= 0
lstns = self.cloud.elbclient.listener.list(elbid='foo')
assert len(lstns) >= 0
# vim: sts=4 sw=4 ts=4 et:
|
<commit_before>import otc
class TestElbClient:
"""ELB client tests"""
def setUp(self):
"""Setup test cloud"""
self.cloud = otc.OtcCloud(cloud='test')
def tearDown(self):
pass
def test_elbclient_user_agent(self):
"""Check user agent"""
assert self.cloud.elbclient.client.USER_AGENT == 'python-otcclient'
def test_elbclient_elb(self):
"""List elbs"""
elbs = self.cloud.elbclient.elb.list()
assert len(elbs) >= 0
elbs = self.cloud.elbclient.elb.list(vpcid='foo')
assert len(elbs) >= 0
elbs = self.cloud.elbclient.elb.list('foo')
assert len(elbs) >= 0
def test_elbclient_listener(self):
"""List listeners"""
lstns = self.cloud.elbclient.listener.list()
assert len(lstns) >= 0
lstns = self.cloud.elbclient.listener.list('foo')
assert len(lstns) >= 0
lstns = self.cloud.elbclient.listener.list(elbid='foo')
assert len(lstns) >= 0
# vim: sts=4 sw=4 ts=4 et:
<commit_msg>Check the ELB service url<commit_after>import otc
class TestElbClient:
"""ELB client tests"""
def setUp(self):
"""Setup test cloud"""
self.cloud = otc.OtcCloud(cloud='test')
def tearDown(self):
pass
def test_elbclient_user_agent(self):
"""Check user agent"""
assert self.cloud.elbclient.client.USER_AGENT == 'python-otcclient'
def test_elbclient_service_url(self):
"""Check ELB service url"""
assert self.cloud.elbclient.service_url == "https://elb.eu-de.otc.t-systems.com"
def test_elbclient_elb(self):
"""List elbs"""
elbs = self.cloud.elbclient.elb.list()
assert len(elbs) >= 0
elbs = self.cloud.elbclient.elb.list(vpcid='foo')
assert len(elbs) >= 0
elbs = self.cloud.elbclient.elb.list('foo')
assert len(elbs) >= 0
def test_elbclient_listener(self):
"""List listeners"""
lstns = self.cloud.elbclient.listener.list()
assert len(lstns) >= 0
lstns = self.cloud.elbclient.listener.list('foo')
assert len(lstns) >= 0
lstns = self.cloud.elbclient.listener.list(elbid='foo')
assert len(lstns) >= 0
# vim: sts=4 sw=4 ts=4 et:
|
99e8ebb9b8107bcb4646218755d81dc6194470bb
|
permuta/misc/misc.py
|
permuta/misc/misc.py
|
import bisect
def binary_search(a, x):
i = bisect.bisect_left(a, x)
return i != len(a) and a[i] == x
def flatten(lst):
res = []
def dfs(l):
try:
for i in l:
dfs(i)
except:
res.append(i)
dfs(lst)
return res
def choose(l, k):
cur = []
def gen(at, left):
if left == 0:
yield list(cur)
elif at < l:
cur.append(at)
for res in gen(at + 1, left - 1):
yield res
cur.pop()
for res in gen(at + 1, left):
yield res
return gen(0, k)
def subsets(elems):
def bt(at, cur):
if at == len(elems):
yield cur
else:
for x in bt(at+1, cur): yield x
for x in bt(at+1, cur + [elems[at]]): yield x
for x in bt(0, []): yield x
|
import bisect
def binary_search(a, x):
i = bisect.bisect_left(a, x)
return i != len(a) and a[i] == x
def flatten(lst):
res = []
def dfs(l):
try:
for i in l:
dfs(i)
except:
res.append(l)
dfs(lst)
return res
def choose(l, k):
cur = []
def gen(at, left):
if left == 0:
yield list(cur)
elif at < l:
cur.append(at)
for res in gen(at + 1, left - 1):
yield res
cur.pop()
for res in gen(at + 1, left):
yield res
return gen(0, k)
def subsets(elems):
def bt(at, cur):
if at == len(elems):
yield cur
else:
for x in bt(at+1, cur): yield x
for x in bt(at+1, cur + [elems[at]]): yield x
for x in bt(0, []): yield x
|
Make flatten more portable again
|
Make flatten more portable again
|
Python
|
bsd-3-clause
|
PermutaTriangle/Permuta
|
import bisect
def binary_search(a, x):
i = bisect.bisect_left(a, x)
return i != len(a) and a[i] == x
def flatten(lst):
res = []
def dfs(l):
try:
for i in l:
dfs(i)
except:
res.append(i)
dfs(lst)
return res
def choose(l, k):
cur = []
def gen(at, left):
if left == 0:
yield list(cur)
elif at < l:
cur.append(at)
for res in gen(at + 1, left - 1):
yield res
cur.pop()
for res in gen(at + 1, left):
yield res
return gen(0, k)
def subsets(elems):
def bt(at, cur):
if at == len(elems):
yield cur
else:
for x in bt(at+1, cur): yield x
for x in bt(at+1, cur + [elems[at]]): yield x
for x in bt(0, []): yield x
Make flatten more portable again
|
import bisect
def binary_search(a, x):
i = bisect.bisect_left(a, x)
return i != len(a) and a[i] == x
def flatten(lst):
res = []
def dfs(l):
try:
for i in l:
dfs(i)
except:
res.append(l)
dfs(lst)
return res
def choose(l, k):
cur = []
def gen(at, left):
if left == 0:
yield list(cur)
elif at < l:
cur.append(at)
for res in gen(at + 1, left - 1):
yield res
cur.pop()
for res in gen(at + 1, left):
yield res
return gen(0, k)
def subsets(elems):
def bt(at, cur):
if at == len(elems):
yield cur
else:
for x in bt(at+1, cur): yield x
for x in bt(at+1, cur + [elems[at]]): yield x
for x in bt(0, []): yield x
|
<commit_before>
import bisect
def binary_search(a, x):
i = bisect.bisect_left(a, x)
return i != len(a) and a[i] == x
def flatten(lst):
res = []
def dfs(l):
try:
for i in l:
dfs(i)
except:
res.append(i)
dfs(lst)
return res
def choose(l, k):
cur = []
def gen(at, left):
if left == 0:
yield list(cur)
elif at < l:
cur.append(at)
for res in gen(at + 1, left - 1):
yield res
cur.pop()
for res in gen(at + 1, left):
yield res
return gen(0, k)
def subsets(elems):
def bt(at, cur):
if at == len(elems):
yield cur
else:
for x in bt(at+1, cur): yield x
for x in bt(at+1, cur + [elems[at]]): yield x
for x in bt(0, []): yield x
<commit_msg>Make flatten more portable again<commit_after>
|
import bisect
def binary_search(a, x):
i = bisect.bisect_left(a, x)
return i != len(a) and a[i] == x
def flatten(lst):
res = []
def dfs(l):
try:
for i in l:
dfs(i)
except:
res.append(l)
dfs(lst)
return res
def choose(l, k):
cur = []
def gen(at, left):
if left == 0:
yield list(cur)
elif at < l:
cur.append(at)
for res in gen(at + 1, left - 1):
yield res
cur.pop()
for res in gen(at + 1, left):
yield res
return gen(0, k)
def subsets(elems):
def bt(at, cur):
if at == len(elems):
yield cur
else:
for x in bt(at+1, cur): yield x
for x in bt(at+1, cur + [elems[at]]): yield x
for x in bt(0, []): yield x
|
import bisect
def binary_search(a, x):
i = bisect.bisect_left(a, x)
return i != len(a) and a[i] == x
def flatten(lst):
res = []
def dfs(l):
try:
for i in l:
dfs(i)
except:
res.append(i)
dfs(lst)
return res
def choose(l, k):
cur = []
def gen(at, left):
if left == 0:
yield list(cur)
elif at < l:
cur.append(at)
for res in gen(at + 1, left - 1):
yield res
cur.pop()
for res in gen(at + 1, left):
yield res
return gen(0, k)
def subsets(elems):
def bt(at, cur):
if at == len(elems):
yield cur
else:
for x in bt(at+1, cur): yield x
for x in bt(at+1, cur + [elems[at]]): yield x
for x in bt(0, []): yield x
Make flatten more portable again
import bisect
def binary_search(a, x):
i = bisect.bisect_left(a, x)
return i != len(a) and a[i] == x
def flatten(lst):
res = []
def dfs(l):
try:
for i in l:
dfs(i)
except:
res.append(l)
dfs(lst)
return res
def choose(l, k):
cur = []
def gen(at, left):
if left == 0:
yield list(cur)
elif at < l:
cur.append(at)
for res in gen(at + 1, left - 1):
yield res
cur.pop()
for res in gen(at + 1, left):
yield res
return gen(0, k)
def subsets(elems):
def bt(at, cur):
if at == len(elems):
yield cur
else:
for x in bt(at+1, cur): yield x
for x in bt(at+1, cur + [elems[at]]): yield x
for x in bt(0, []): yield x
|
<commit_before>
import bisect
def binary_search(a, x):
i = bisect.bisect_left(a, x)
return i != len(a) and a[i] == x
def flatten(lst):
res = []
def dfs(l):
try:
for i in l:
dfs(i)
except:
res.append(i)
dfs(lst)
return res
def choose(l, k):
cur = []
def gen(at, left):
if left == 0:
yield list(cur)
elif at < l:
cur.append(at)
for res in gen(at + 1, left - 1):
yield res
cur.pop()
for res in gen(at + 1, left):
yield res
return gen(0, k)
def subsets(elems):
def bt(at, cur):
if at == len(elems):
yield cur
else:
for x in bt(at+1, cur): yield x
for x in bt(at+1, cur + [elems[at]]): yield x
for x in bt(0, []): yield x
<commit_msg>Make flatten more portable again<commit_after>
import bisect
def binary_search(a, x):
i = bisect.bisect_left(a, x)
return i != len(a) and a[i] == x
def flatten(lst):
res = []
def dfs(l):
try:
for i in l:
dfs(i)
except:
res.append(l)
dfs(lst)
return res
def choose(l, k):
cur = []
def gen(at, left):
if left == 0:
yield list(cur)
elif at < l:
cur.append(at)
for res in gen(at + 1, left - 1):
yield res
cur.pop()
for res in gen(at + 1, left):
yield res
return gen(0, k)
def subsets(elems):
def bt(at, cur):
if at == len(elems):
yield cur
else:
for x in bt(at+1, cur): yield x
for x in bt(at+1, cur + [elems[at]]): yield x
for x in bt(0, []): yield x
|
5ec1ba120642686b87cec0ad2ccc2c1428c4a553
|
samples/config.default.py
|
samples/config.default.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
credentials = {
'verify-email.org': {
'username': 'YOURUSERNAME',
'password': 'YOURPASSWORD',
}
'emailhippo.com': {
'api_url': 'https://domain.com/api/v2',
'api_key': 'YOURAPIKEY',
}
}
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
credentials = {
'verify-email.org': {
'username': 'YOURUSERNAME',
'password': 'YOURPASSWORD',
}
'emailhippo.com': {
'api_url': 'https://domain.com/api/v2',
'api_key': 'YOURAPIKEY',
},
'email-validator.net': {
'api_key': '',
},
}
|
Add an other provider to config
|
Add an other provider to config
|
Python
|
bsd-3-clause
|
scls19fr/email-verif
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
credentials = {
'verify-email.org': {
'username': 'YOURUSERNAME',
'password': 'YOURPASSWORD',
}
'emailhippo.com': {
'api_url': 'https://domain.com/api/v2',
'api_key': 'YOURAPIKEY',
}
}
Add an other provider to config
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
credentials = {
'verify-email.org': {
'username': 'YOURUSERNAME',
'password': 'YOURPASSWORD',
}
'emailhippo.com': {
'api_url': 'https://domain.com/api/v2',
'api_key': 'YOURAPIKEY',
},
'email-validator.net': {
'api_key': '',
},
}
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
credentials = {
'verify-email.org': {
'username': 'YOURUSERNAME',
'password': 'YOURPASSWORD',
}
'emailhippo.com': {
'api_url': 'https://domain.com/api/v2',
'api_key': 'YOURAPIKEY',
}
}
<commit_msg>Add an other provider to config<commit_after>
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
credentials = {
'verify-email.org': {
'username': 'YOURUSERNAME',
'password': 'YOURPASSWORD',
}
'emailhippo.com': {
'api_url': 'https://domain.com/api/v2',
'api_key': 'YOURAPIKEY',
},
'email-validator.net': {
'api_key': '',
},
}
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
credentials = {
'verify-email.org': {
'username': 'YOURUSERNAME',
'password': 'YOURPASSWORD',
}
'emailhippo.com': {
'api_url': 'https://domain.com/api/v2',
'api_key': 'YOURAPIKEY',
}
}
Add an other provider to config#!/usr/bin/env python
# -*- coding: utf-8 -*-
credentials = {
'verify-email.org': {
'username': 'YOURUSERNAME',
'password': 'YOURPASSWORD',
}
'emailhippo.com': {
'api_url': 'https://domain.com/api/v2',
'api_key': 'YOURAPIKEY',
},
'email-validator.net': {
'api_key': '',
},
}
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
credentials = {
'verify-email.org': {
'username': 'YOURUSERNAME',
'password': 'YOURPASSWORD',
}
'emailhippo.com': {
'api_url': 'https://domain.com/api/v2',
'api_key': 'YOURAPIKEY',
}
}
<commit_msg>Add an other provider to config<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
credentials = {
'verify-email.org': {
'username': 'YOURUSERNAME',
'password': 'YOURPASSWORD',
}
'emailhippo.com': {
'api_url': 'https://domain.com/api/v2',
'api_key': 'YOURAPIKEY',
},
'email-validator.net': {
'api_key': '',
},
}
|
9bc9ec9468459ab49530e6463255cca38aba721c
|
findaconf/tests/test_site_routes.py
|
findaconf/tests/test_site_routes.py
|
# coding: utf-8
from unittest import TestCase
from findaconf import app, db
from findaconf.tests.config import set_app, unset_app
class TestSiteRoutes(TestCase):
def setUp(self):
self.app = set_app(app, db)
def tearDown(self):
unset_app(db)
# test routes from blueprint/site.py
def test_index(self):
resp = self.app.get('/')
assert resp.status_code == 200
assert resp.mimetype == 'text/html'
def test_find(self):
resp = self.app.get('/find', data={'query': 'sociology',
'month': 'February',
'year': 2015,
'region': 'Europe',
'location': 'University of Essex'})
assert resp.status_code == 200
assert resp.mimetype == 'text/html'
|
# coding: utf-8
from findaconf import app, db
from findaconf.tests.config import set_app, unset_app
from unittest import TestCase
class TestSiteRoutes(TestCase):
def setUp(self):
self.app = set_app(app, db)
def tearDown(self):
unset_app(db)
# test routes from blueprint/site.py
def test_index(self):
resp = self.app.get('/')
assert resp.status_code == 200
assert resp.mimetype == 'text/html'
def test_find(self):
resp = self.app.get('/find', data={'query': 'sociology',
'month': 'February',
'year': 2015,
'region': 'Europe',
'location': 'University of Essex'})
assert resp.status_code == 200
assert resp.mimetype == 'text/html'
def test_login(self):
# test if login page exists
resp = self.app.get('/login')
assert resp.status_code == 200
assert resp.mimetype == 'text/html'
# test if is there a link to login in the home page
resp = self.app.get('/')
assert 'href="/login"' in resp.data
|
Create tests for login page
|
Create tests for login page
|
Python
|
mit
|
cuducos/findaconf,cuducos/findaconf,koorukuroo/findaconf,cuducos/findaconf,koorukuroo/findaconf,koorukuroo/findaconf
|
# coding: utf-8
from unittest import TestCase
from findaconf import app, db
from findaconf.tests.config import set_app, unset_app
class TestSiteRoutes(TestCase):
def setUp(self):
self.app = set_app(app, db)
def tearDown(self):
unset_app(db)
# test routes from blueprint/site.py
def test_index(self):
resp = self.app.get('/')
assert resp.status_code == 200
assert resp.mimetype == 'text/html'
def test_find(self):
resp = self.app.get('/find', data={'query': 'sociology',
'month': 'February',
'year': 2015,
'region': 'Europe',
'location': 'University of Essex'})
assert resp.status_code == 200
assert resp.mimetype == 'text/html'
Create tests for login page
|
# coding: utf-8
from findaconf import app, db
from findaconf.tests.config import set_app, unset_app
from unittest import TestCase
class TestSiteRoutes(TestCase):
def setUp(self):
self.app = set_app(app, db)
def tearDown(self):
unset_app(db)
# test routes from blueprint/site.py
def test_index(self):
resp = self.app.get('/')
assert resp.status_code == 200
assert resp.mimetype == 'text/html'
def test_find(self):
resp = self.app.get('/find', data={'query': 'sociology',
'month': 'February',
'year': 2015,
'region': 'Europe',
'location': 'University of Essex'})
assert resp.status_code == 200
assert resp.mimetype == 'text/html'
def test_login(self):
# test if login page exists
resp = self.app.get('/login')
assert resp.status_code == 200
assert resp.mimetype == 'text/html'
# test if is there a link to login in the home page
resp = self.app.get('/')
assert 'href="/login"' in resp.data
|
<commit_before># coding: utf-8
from unittest import TestCase
from findaconf import app, db
from findaconf.tests.config import set_app, unset_app
class TestSiteRoutes(TestCase):
def setUp(self):
self.app = set_app(app, db)
def tearDown(self):
unset_app(db)
# test routes from blueprint/site.py
def test_index(self):
resp = self.app.get('/')
assert resp.status_code == 200
assert resp.mimetype == 'text/html'
def test_find(self):
resp = self.app.get('/find', data={'query': 'sociology',
'month': 'February',
'year': 2015,
'region': 'Europe',
'location': 'University of Essex'})
assert resp.status_code == 200
assert resp.mimetype == 'text/html'
<commit_msg>Create tests for login page<commit_after>
|
# coding: utf-8
from findaconf import app, db
from findaconf.tests.config import set_app, unset_app
from unittest import TestCase
class TestSiteRoutes(TestCase):
def setUp(self):
self.app = set_app(app, db)
def tearDown(self):
unset_app(db)
# test routes from blueprint/site.py
def test_index(self):
resp = self.app.get('/')
assert resp.status_code == 200
assert resp.mimetype == 'text/html'
def test_find(self):
resp = self.app.get('/find', data={'query': 'sociology',
'month': 'February',
'year': 2015,
'region': 'Europe',
'location': 'University of Essex'})
assert resp.status_code == 200
assert resp.mimetype == 'text/html'
def test_login(self):
# test if login page exists
resp = self.app.get('/login')
assert resp.status_code == 200
assert resp.mimetype == 'text/html'
# test if is there a link to login in the home page
resp = self.app.get('/')
assert 'href="/login"' in resp.data
|
# coding: utf-8
from unittest import TestCase
from findaconf import app, db
from findaconf.tests.config import set_app, unset_app
class TestSiteRoutes(TestCase):
def setUp(self):
self.app = set_app(app, db)
def tearDown(self):
unset_app(db)
# test routes from blueprint/site.py
def test_index(self):
resp = self.app.get('/')
assert resp.status_code == 200
assert resp.mimetype == 'text/html'
def test_find(self):
resp = self.app.get('/find', data={'query': 'sociology',
'month': 'February',
'year': 2015,
'region': 'Europe',
'location': 'University of Essex'})
assert resp.status_code == 200
assert resp.mimetype == 'text/html'
Create tests for login page# coding: utf-8
from findaconf import app, db
from findaconf.tests.config import set_app, unset_app
from unittest import TestCase
class TestSiteRoutes(TestCase):
def setUp(self):
self.app = set_app(app, db)
def tearDown(self):
unset_app(db)
# test routes from blueprint/site.py
def test_index(self):
resp = self.app.get('/')
assert resp.status_code == 200
assert resp.mimetype == 'text/html'
def test_find(self):
resp = self.app.get('/find', data={'query': 'sociology',
'month': 'February',
'year': 2015,
'region': 'Europe',
'location': 'University of Essex'})
assert resp.status_code == 200
assert resp.mimetype == 'text/html'
def test_login(self):
# test if login page exists
resp = self.app.get('/login')
assert resp.status_code == 200
assert resp.mimetype == 'text/html'
# test if is there a link to login in the home page
resp = self.app.get('/')
assert 'href="/login"' in resp.data
|
<commit_before># coding: utf-8
from unittest import TestCase
from findaconf import app, db
from findaconf.tests.config import set_app, unset_app
class TestSiteRoutes(TestCase):
def setUp(self):
self.app = set_app(app, db)
def tearDown(self):
unset_app(db)
# test routes from blueprint/site.py
def test_index(self):
resp = self.app.get('/')
assert resp.status_code == 200
assert resp.mimetype == 'text/html'
def test_find(self):
resp = self.app.get('/find', data={'query': 'sociology',
'month': 'February',
'year': 2015,
'region': 'Europe',
'location': 'University of Essex'})
assert resp.status_code == 200
assert resp.mimetype == 'text/html'
<commit_msg>Create tests for login page<commit_after># coding: utf-8
from findaconf import app, db
from findaconf.tests.config import set_app, unset_app
from unittest import TestCase
class TestSiteRoutes(TestCase):
def setUp(self):
self.app = set_app(app, db)
def tearDown(self):
unset_app(db)
# test routes from blueprint/site.py
def test_index(self):
resp = self.app.get('/')
assert resp.status_code == 200
assert resp.mimetype == 'text/html'
def test_find(self):
resp = self.app.get('/find', data={'query': 'sociology',
'month': 'February',
'year': 2015,
'region': 'Europe',
'location': 'University of Essex'})
assert resp.status_code == 200
assert resp.mimetype == 'text/html'
def test_login(self):
# test if login page exists
resp = self.app.get('/login')
assert resp.status_code == 200
assert resp.mimetype == 'text/html'
# test if is there a link to login in the home page
resp = self.app.get('/')
assert 'href="/login"' in resp.data
|
d8d6054a64c07952ff0a60ef5d86d7a5b572d1b4
|
fireplace/cards/brawl/blingbrawl.py
|
fireplace/cards/brawl/blingbrawl.py
|
"""
Blingtron's Beauteous Brawl
"""
from ..utils import *
# Cash In
class TP_Bling_HP2:
activate = Destroy(FRIENDLY_WEAPON)
# Blingtron's Blade
class TB_BlingBrawl_Blade1e:
events = Death(OWNER).on(Summon(CONTROLLER, RandomWeapon()))
# Blingtron's Blade HERO
class TB_BlingBrawl_Blade2:
events = Summon(CONTROLLER, WEAPON).on(
Buff(Summon.CARD, "TB_BlingBrawl_Blade1e")
)
|
"""
Blingtron's Beauteous Brawl
"""
from ..utils import *
# Cash In
class TP_Bling_HP2:
activate = Destroy(FRIENDLY_WEAPON)
# Blingtron's Blade
class TB_BlingBrawl_Blade1e:
events = Death(OWNER).on(Summon(CONTROLLER, RandomWeapon()))
# Blingtron's Blade HERO
class TB_BlingBrawl_Blade2:
events = Summon(CONTROLLER, WEAPON).on(
Buff(Summon.CARD, "TB_BlingBrawl_Blade1e")
)
# Sharpen (Unused)
class TB_BlingBrawl_Hero1p:
activate = Buff(FRIENDLY_WEAPON, "TB_BlingBrawl_Hero1e")
TB_BlingBrawl_Hero1e = buff(atk=1)
|
Implement Sharpen (unused Blingtron Brawl Hero Power)
|
Implement Sharpen (unused Blingtron Brawl Hero Power)
|
Python
|
agpl-3.0
|
Ragowit/fireplace,Ragowit/fireplace,smallnamespace/fireplace,NightKev/fireplace,smallnamespace/fireplace,beheh/fireplace,jleclanche/fireplace
|
"""
Blingtron's Beauteous Brawl
"""
from ..utils import *
# Cash In
class TP_Bling_HP2:
activate = Destroy(FRIENDLY_WEAPON)
# Blingtron's Blade
class TB_BlingBrawl_Blade1e:
events = Death(OWNER).on(Summon(CONTROLLER, RandomWeapon()))
# Blingtron's Blade HERO
class TB_BlingBrawl_Blade2:
events = Summon(CONTROLLER, WEAPON).on(
Buff(Summon.CARD, "TB_BlingBrawl_Blade1e")
)
Implement Sharpen (unused Blingtron Brawl Hero Power)
|
"""
Blingtron's Beauteous Brawl
"""
from ..utils import *
# Cash In
class TP_Bling_HP2:
activate = Destroy(FRIENDLY_WEAPON)
# Blingtron's Blade
class TB_BlingBrawl_Blade1e:
events = Death(OWNER).on(Summon(CONTROLLER, RandomWeapon()))
# Blingtron's Blade HERO
class TB_BlingBrawl_Blade2:
events = Summon(CONTROLLER, WEAPON).on(
Buff(Summon.CARD, "TB_BlingBrawl_Blade1e")
)
# Sharpen (Unused)
class TB_BlingBrawl_Hero1p:
activate = Buff(FRIENDLY_WEAPON, "TB_BlingBrawl_Hero1e")
TB_BlingBrawl_Hero1e = buff(atk=1)
|
<commit_before>"""
Blingtron's Beauteous Brawl
"""
from ..utils import *
# Cash In
class TP_Bling_HP2:
activate = Destroy(FRIENDLY_WEAPON)
# Blingtron's Blade
class TB_BlingBrawl_Blade1e:
events = Death(OWNER).on(Summon(CONTROLLER, RandomWeapon()))
# Blingtron's Blade HERO
class TB_BlingBrawl_Blade2:
events = Summon(CONTROLLER, WEAPON).on(
Buff(Summon.CARD, "TB_BlingBrawl_Blade1e")
)
<commit_msg>Implement Sharpen (unused Blingtron Brawl Hero Power)<commit_after>
|
"""
Blingtron's Beauteous Brawl
"""
from ..utils import *
# Cash In
class TP_Bling_HP2:
activate = Destroy(FRIENDLY_WEAPON)
# Blingtron's Blade
class TB_BlingBrawl_Blade1e:
events = Death(OWNER).on(Summon(CONTROLLER, RandomWeapon()))
# Blingtron's Blade HERO
class TB_BlingBrawl_Blade2:
events = Summon(CONTROLLER, WEAPON).on(
Buff(Summon.CARD, "TB_BlingBrawl_Blade1e")
)
# Sharpen (Unused)
class TB_BlingBrawl_Hero1p:
activate = Buff(FRIENDLY_WEAPON, "TB_BlingBrawl_Hero1e")
TB_BlingBrawl_Hero1e = buff(atk=1)
|
"""
Blingtron's Beauteous Brawl
"""
from ..utils import *
# Cash In
class TP_Bling_HP2:
activate = Destroy(FRIENDLY_WEAPON)
# Blingtron's Blade
class TB_BlingBrawl_Blade1e:
events = Death(OWNER).on(Summon(CONTROLLER, RandomWeapon()))
# Blingtron's Blade HERO
class TB_BlingBrawl_Blade2:
events = Summon(CONTROLLER, WEAPON).on(
Buff(Summon.CARD, "TB_BlingBrawl_Blade1e")
)
Implement Sharpen (unused Blingtron Brawl Hero Power)"""
Blingtron's Beauteous Brawl
"""
from ..utils import *
# Cash In
class TP_Bling_HP2:
activate = Destroy(FRIENDLY_WEAPON)
# Blingtron's Blade
class TB_BlingBrawl_Blade1e:
events = Death(OWNER).on(Summon(CONTROLLER, RandomWeapon()))
# Blingtron's Blade HERO
class TB_BlingBrawl_Blade2:
events = Summon(CONTROLLER, WEAPON).on(
Buff(Summon.CARD, "TB_BlingBrawl_Blade1e")
)
# Sharpen (Unused)
class TB_BlingBrawl_Hero1p:
activate = Buff(FRIENDLY_WEAPON, "TB_BlingBrawl_Hero1e")
TB_BlingBrawl_Hero1e = buff(atk=1)
|
<commit_before>"""
Blingtron's Beauteous Brawl
"""
from ..utils import *
# Cash In
class TP_Bling_HP2:
activate = Destroy(FRIENDLY_WEAPON)
# Blingtron's Blade
class TB_BlingBrawl_Blade1e:
events = Death(OWNER).on(Summon(CONTROLLER, RandomWeapon()))
# Blingtron's Blade HERO
class TB_BlingBrawl_Blade2:
events = Summon(CONTROLLER, WEAPON).on(
Buff(Summon.CARD, "TB_BlingBrawl_Blade1e")
)
<commit_msg>Implement Sharpen (unused Blingtron Brawl Hero Power)<commit_after>"""
Blingtron's Beauteous Brawl
"""
from ..utils import *
# Cash In
class TP_Bling_HP2:
activate = Destroy(FRIENDLY_WEAPON)
# Blingtron's Blade
class TB_BlingBrawl_Blade1e:
events = Death(OWNER).on(Summon(CONTROLLER, RandomWeapon()))
# Blingtron's Blade HERO
class TB_BlingBrawl_Blade2:
events = Summon(CONTROLLER, WEAPON).on(
Buff(Summon.CARD, "TB_BlingBrawl_Blade1e")
)
# Sharpen (Unused)
class TB_BlingBrawl_Hero1p:
activate = Buff(FRIENDLY_WEAPON, "TB_BlingBrawl_Hero1e")
TB_BlingBrawl_Hero1e = buff(atk=1)
|
86273d96e33e3bd686904377ba2b53fbbbcbc38b
|
tests/test_crossword.py
|
tests/test_crossword.py
|
import unittest
from crossword import Crossword
class CrosswordTestCase(unittest.TestCase):
def test_crossword_set_and_get_element(self):
c = Crossword(10, 10)
c[3, 3] = 'A'
self.assertEqual(c[3, 3], 'A')
|
import unittest
from crossword import Crossword
class CrosswordTestCase(unittest.TestCase):
def test_crossword_set_and_get_element(self):
crossword = Crossword(10, 10)
crossword[3, 3] = 'A'
self.assertEqual(crossword[3, 3], 'A')
|
Use a better variable name instead of one character
|
Use a better variable name instead of one character
|
Python
|
mit
|
svisser/crossword
|
import unittest
from crossword import Crossword
class CrosswordTestCase(unittest.TestCase):
def test_crossword_set_and_get_element(self):
c = Crossword(10, 10)
c[3, 3] = 'A'
self.assertEqual(c[3, 3], 'A')
Use a better variable name instead of one character
|
import unittest
from crossword import Crossword
class CrosswordTestCase(unittest.TestCase):
def test_crossword_set_and_get_element(self):
crossword = Crossword(10, 10)
crossword[3, 3] = 'A'
self.assertEqual(crossword[3, 3], 'A')
|
<commit_before>import unittest
from crossword import Crossword
class CrosswordTestCase(unittest.TestCase):
def test_crossword_set_and_get_element(self):
c = Crossword(10, 10)
c[3, 3] = 'A'
self.assertEqual(c[3, 3], 'A')
<commit_msg>Use a better variable name instead of one character<commit_after>
|
import unittest
from crossword import Crossword
class CrosswordTestCase(unittest.TestCase):
def test_crossword_set_and_get_element(self):
crossword = Crossword(10, 10)
crossword[3, 3] = 'A'
self.assertEqual(crossword[3, 3], 'A')
|
import unittest
from crossword import Crossword
class CrosswordTestCase(unittest.TestCase):
def test_crossword_set_and_get_element(self):
c = Crossword(10, 10)
c[3, 3] = 'A'
self.assertEqual(c[3, 3], 'A')
Use a better variable name instead of one characterimport unittest
from crossword import Crossword
class CrosswordTestCase(unittest.TestCase):
def test_crossword_set_and_get_element(self):
crossword = Crossword(10, 10)
crossword[3, 3] = 'A'
self.assertEqual(crossword[3, 3], 'A')
|
<commit_before>import unittest
from crossword import Crossword
class CrosswordTestCase(unittest.TestCase):
def test_crossword_set_and_get_element(self):
c = Crossword(10, 10)
c[3, 3] = 'A'
self.assertEqual(c[3, 3], 'A')
<commit_msg>Use a better variable name instead of one character<commit_after>import unittest
from crossword import Crossword
class CrosswordTestCase(unittest.TestCase):
def test_crossword_set_and_get_element(self):
crossword = Crossword(10, 10)
crossword[3, 3] = 'A'
self.assertEqual(crossword[3, 3], 'A')
|
10c2d1dcc9079a3166642a3d75947472ec377343
|
simple_scheduler/jobs/curl_job.py
|
simple_scheduler/jobs/curl_job.py
|
"""A job to send a HTTP GET periodically."""
import logging
import requests
from ndscheduler import job
logger = logging.getLogger(__name__)
class CurlJob(job.JobBase):
TIMEOUT = 10
@classmethod
def meta_info(cls):
return {
'job_class_string': '%s.%s' % (cls.__module__, cls.__name__),
'notes': ('This sends a HTTP GET to a particular URL'),
'arguments': [
# url
{'type': 'string', 'description': 'What URL you want to make a GET call?'},
],
'example_arguments': ('["http://localhost:8888/api/v1/jobs"]')
}
def run(self, url, *args, **kwargs):
print 'Calling GET on url: %s' % (url)
session = requests.Session()
session.request('GET',
url,
timeout=self.TIMEOUT,
headers=None,
data=None)
if __name__ == "__main__":
job = CurlJob.create_test_instance()
job.run('http://localhost:888/api/v1/jobs')
|
"""A job to send a HTTP GET periodically."""
import logging
import requests
from ndscheduler import job
logger = logging.getLogger(__name__)
class CurlJob(job.JobBase):
TIMEOUT = 10
@classmethod
def meta_info(cls):
return {
'job_class_string': '%s.%s' % (cls.__module__, cls.__name__),
'notes': ('This sends a HTTP request to a particular URL'),
'arguments': [
# url
{'type': 'string', 'description': 'What URL you want to make a GET call?'},
# Request Type
{'type': 'string', 'description': 'What request type do you want? '
'(currently supported: GET/DELETE)'},
],
'example_arguments': ('["http://localhost:8888/api/v1/jobs", "GET"]'
'["http://localhost:8888/api/v1/jobs/ba12e", "DELETE"]')
}
def run(self, url, request_type, *args, **kwargs):
print 'Calling GET on url: %s' % (url)
session = requests.Session()
result = session.request(request_type,
url,
timeout=self.TIMEOUT,
headers=None,
data=None)
print(result.text)
if __name__ == "__main__":
job = CurlJob.create_test_instance()
job.run('http://localhost:888/api/v1/jobs')
|
Add delete example in CURL job
|
Add delete example in CURL job
|
Python
|
bsd-2-clause
|
Nextdoor/ndscheduler,Nextdoor/ndscheduler,Nextdoor/ndscheduler,Nextdoor/ndscheduler
|
"""A job to send a HTTP GET periodically."""
import logging
import requests
from ndscheduler import job
logger = logging.getLogger(__name__)
class CurlJob(job.JobBase):
TIMEOUT = 10
@classmethod
def meta_info(cls):
return {
'job_class_string': '%s.%s' % (cls.__module__, cls.__name__),
'notes': ('This sends a HTTP GET to a particular URL'),
'arguments': [
# url
{'type': 'string', 'description': 'What URL you want to make a GET call?'},
],
'example_arguments': ('["http://localhost:8888/api/v1/jobs"]')
}
def run(self, url, *args, **kwargs):
print 'Calling GET on url: %s' % (url)
session = requests.Session()
session.request('GET',
url,
timeout=self.TIMEOUT,
headers=None,
data=None)
if __name__ == "__main__":
job = CurlJob.create_test_instance()
job.run('http://localhost:888/api/v1/jobs')
Add delete example in CURL job
|
"""A job to send a HTTP GET periodically."""
import logging
import requests
from ndscheduler import job
logger = logging.getLogger(__name__)
class CurlJob(job.JobBase):
TIMEOUT = 10
@classmethod
def meta_info(cls):
return {
'job_class_string': '%s.%s' % (cls.__module__, cls.__name__),
'notes': ('This sends a HTTP request to a particular URL'),
'arguments': [
# url
{'type': 'string', 'description': 'What URL you want to make a GET call?'},
# Request Type
{'type': 'string', 'description': 'What request type do you want? '
'(currently supported: GET/DELETE)'},
],
'example_arguments': ('["http://localhost:8888/api/v1/jobs", "GET"]'
'["http://localhost:8888/api/v1/jobs/ba12e", "DELETE"]')
}
def run(self, url, request_type, *args, **kwargs):
print 'Calling GET on url: %s' % (url)
session = requests.Session()
result = session.request(request_type,
url,
timeout=self.TIMEOUT,
headers=None,
data=None)
print(result.text)
if __name__ == "__main__":
job = CurlJob.create_test_instance()
job.run('http://localhost:888/api/v1/jobs')
|
<commit_before>"""A job to send a HTTP GET periodically."""
import logging
import requests
from ndscheduler import job
logger = logging.getLogger(__name__)
class CurlJob(job.JobBase):
TIMEOUT = 10
@classmethod
def meta_info(cls):
return {
'job_class_string': '%s.%s' % (cls.__module__, cls.__name__),
'notes': ('This sends a HTTP GET to a particular URL'),
'arguments': [
# url
{'type': 'string', 'description': 'What URL you want to make a GET call?'},
],
'example_arguments': ('["http://localhost:8888/api/v1/jobs"]')
}
def run(self, url, *args, **kwargs):
print 'Calling GET on url: %s' % (url)
session = requests.Session()
session.request('GET',
url,
timeout=self.TIMEOUT,
headers=None,
data=None)
if __name__ == "__main__":
job = CurlJob.create_test_instance()
job.run('http://localhost:888/api/v1/jobs')
<commit_msg>Add delete example in CURL job<commit_after>
|
"""A job to send a HTTP GET periodically."""
import logging
import requests
from ndscheduler import job
logger = logging.getLogger(__name__)
class CurlJob(job.JobBase):
TIMEOUT = 10
@classmethod
def meta_info(cls):
return {
'job_class_string': '%s.%s' % (cls.__module__, cls.__name__),
'notes': ('This sends a HTTP request to a particular URL'),
'arguments': [
# url
{'type': 'string', 'description': 'What URL you want to make a GET call?'},
# Request Type
{'type': 'string', 'description': 'What request type do you want? '
'(currently supported: GET/DELETE)'},
],
'example_arguments': ('["http://localhost:8888/api/v1/jobs", "GET"]'
'["http://localhost:8888/api/v1/jobs/ba12e", "DELETE"]')
}
def run(self, url, request_type, *args, **kwargs):
print 'Calling GET on url: %s' % (url)
session = requests.Session()
result = session.request(request_type,
url,
timeout=self.TIMEOUT,
headers=None,
data=None)
print(result.text)
if __name__ == "__main__":
job = CurlJob.create_test_instance()
job.run('http://localhost:888/api/v1/jobs')
|
"""A job to send a HTTP GET periodically."""
import logging
import requests
from ndscheduler import job
logger = logging.getLogger(__name__)
class CurlJob(job.JobBase):
TIMEOUT = 10
@classmethod
def meta_info(cls):
return {
'job_class_string': '%s.%s' % (cls.__module__, cls.__name__),
'notes': ('This sends a HTTP GET to a particular URL'),
'arguments': [
# url
{'type': 'string', 'description': 'What URL you want to make a GET call?'},
],
'example_arguments': ('["http://localhost:8888/api/v1/jobs"]')
}
def run(self, url, *args, **kwargs):
print 'Calling GET on url: %s' % (url)
session = requests.Session()
session.request('GET',
url,
timeout=self.TIMEOUT,
headers=None,
data=None)
if __name__ == "__main__":
job = CurlJob.create_test_instance()
job.run('http://localhost:888/api/v1/jobs')
Add delete example in CURL job"""A job to send a HTTP GET periodically."""
import logging
import requests
from ndscheduler import job
logger = logging.getLogger(__name__)
class CurlJob(job.JobBase):
TIMEOUT = 10
@classmethod
def meta_info(cls):
return {
'job_class_string': '%s.%s' % (cls.__module__, cls.__name__),
'notes': ('This sends a HTTP request to a particular URL'),
'arguments': [
# url
{'type': 'string', 'description': 'What URL you want to make a GET call?'},
# Request Type
{'type': 'string', 'description': 'What request type do you want? '
'(currently supported: GET/DELETE)'},
],
'example_arguments': ('["http://localhost:8888/api/v1/jobs", "GET"]'
'["http://localhost:8888/api/v1/jobs/ba12e", "DELETE"]')
}
def run(self, url, request_type, *args, **kwargs):
print 'Calling GET on url: %s' % (url)
session = requests.Session()
result = session.request(request_type,
url,
timeout=self.TIMEOUT,
headers=None,
data=None)
print(result.text)
if __name__ == "__main__":
job = CurlJob.create_test_instance()
job.run('http://localhost:888/api/v1/jobs')
|
<commit_before>"""A job to send a HTTP GET periodically."""
import logging
import requests
from ndscheduler import job
logger = logging.getLogger(__name__)
class CurlJob(job.JobBase):
TIMEOUT = 10
@classmethod
def meta_info(cls):
return {
'job_class_string': '%s.%s' % (cls.__module__, cls.__name__),
'notes': ('This sends a HTTP GET to a particular URL'),
'arguments': [
# url
{'type': 'string', 'description': 'What URL you want to make a GET call?'},
],
'example_arguments': ('["http://localhost:8888/api/v1/jobs"]')
}
def run(self, url, *args, **kwargs):
print 'Calling GET on url: %s' % (url)
session = requests.Session()
session.request('GET',
url,
timeout=self.TIMEOUT,
headers=None,
data=None)
if __name__ == "__main__":
job = CurlJob.create_test_instance()
job.run('http://localhost:888/api/v1/jobs')
<commit_msg>Add delete example in CURL job<commit_after>"""A job to send a HTTP GET periodically."""
import logging
import requests
from ndscheduler import job
logger = logging.getLogger(__name__)
class CurlJob(job.JobBase):
TIMEOUT = 10
@classmethod
def meta_info(cls):
return {
'job_class_string': '%s.%s' % (cls.__module__, cls.__name__),
'notes': ('This sends a HTTP request to a particular URL'),
'arguments': [
# url
{'type': 'string', 'description': 'What URL you want to make a GET call?'},
# Request Type
{'type': 'string', 'description': 'What request type do you want? '
'(currently supported: GET/DELETE)'},
],
'example_arguments': ('["http://localhost:8888/api/v1/jobs", "GET"]'
'["http://localhost:8888/api/v1/jobs/ba12e", "DELETE"]')
}
def run(self, url, request_type, *args, **kwargs):
print 'Calling GET on url: %s' % (url)
session = requests.Session()
result = session.request(request_type,
url,
timeout=self.TIMEOUT,
headers=None,
data=None)
print(result.text)
if __name__ == "__main__":
job = CurlJob.create_test_instance()
job.run('http://localhost:888/api/v1/jobs')
|
e4b640d6c7614e4b8d8767f64b7765ac95dbf440
|
mrburns/settings/server.py
|
mrburns/settings/server.py
|
import os
import socket
from .base import * # noqa
SERVER_ENV = os.getenv('DJANGO_SERVER_ENV')
SECRET_KEY = os.getenv('SECRET_KEY')
STATIC_URL = os.getenv('STATIC_URL', STATIC_URL)
DEBUG = TEMPLATE_DEBUG = False
ALLOWED_HOSTS = [
'webwewant.mozilla.org',
'webwewant.allizom.org',
# the server's IP (for monitors)
socket.gethostbyname(socket.gethostname()),
]
CACHES = {
'default': {
'BACKEND': 'redis_cache.cache.RedisCache',
'LOCATION': 'unix:/var/run/redis/redis.sock:1',
'OPTIONS': {
'PARSER_CLASS': 'redis.connection.HiredisParser',
}
},
'smithers': {
'BACKEND': 'redis_cache.cache.RedisCache',
'LOCATION': 'unix:/var/run/redis/redis.sock:0',
'OPTIONS': {
'PARSER_CLASS': 'redis.connection.HiredisParser',
}
}
}
DJANGO_REDIS_IGNORE_EXCEPTIONS = False
ENABLE_REDIS = True
|
import os
import socket
from .base import * # noqa
SERVER_ENV = os.getenv('DJANGO_SERVER_ENV')
SECRET_KEY = os.getenv('SECRET_KEY')
STATIC_URL = os.getenv('STATIC_URL', STATIC_URL)
DEBUG = TEMPLATE_DEBUG = False
ALLOWED_HOSTS = [
'webwewant.mozilla.org',
'webwewant.allizom.org',
'glow.cdn.mozilla.net',
# the server's IP (for monitors)
socket.gethostbyname(socket.gethostname()),
]
CACHES = {
'default': {
'BACKEND': 'redis_cache.cache.RedisCache',
'LOCATION': 'unix:/var/run/redis/redis.sock:1',
'OPTIONS': {
'PARSER_CLASS': 'redis.connection.HiredisParser',
}
},
'smithers': {
'BACKEND': 'redis_cache.cache.RedisCache',
'LOCATION': 'unix:/var/run/redis/redis.sock:0',
'OPTIONS': {
'PARSER_CLASS': 'redis.connection.HiredisParser',
}
}
}
DJANGO_REDIS_IGNORE_EXCEPTIONS = False
ENABLE_REDIS = True
|
Add CDN url to allowed hosts.
|
Add CDN url to allowed hosts.
|
Python
|
mpl-2.0
|
almossawi/mrburns,almossawi/mrburns,almossawi/mrburns,mozilla/mrburns,mozilla/mrburns,mozilla/mrburns,almossawi/mrburns
|
import os
import socket
from .base import * # noqa
SERVER_ENV = os.getenv('DJANGO_SERVER_ENV')
SECRET_KEY = os.getenv('SECRET_KEY')
STATIC_URL = os.getenv('STATIC_URL', STATIC_URL)
DEBUG = TEMPLATE_DEBUG = False
ALLOWED_HOSTS = [
'webwewant.mozilla.org',
'webwewant.allizom.org',
# the server's IP (for monitors)
socket.gethostbyname(socket.gethostname()),
]
CACHES = {
'default': {
'BACKEND': 'redis_cache.cache.RedisCache',
'LOCATION': 'unix:/var/run/redis/redis.sock:1',
'OPTIONS': {
'PARSER_CLASS': 'redis.connection.HiredisParser',
}
},
'smithers': {
'BACKEND': 'redis_cache.cache.RedisCache',
'LOCATION': 'unix:/var/run/redis/redis.sock:0',
'OPTIONS': {
'PARSER_CLASS': 'redis.connection.HiredisParser',
}
}
}
DJANGO_REDIS_IGNORE_EXCEPTIONS = False
ENABLE_REDIS = True
Add CDN url to allowed hosts.
|
import os
import socket
from .base import * # noqa
SERVER_ENV = os.getenv('DJANGO_SERVER_ENV')
SECRET_KEY = os.getenv('SECRET_KEY')
STATIC_URL = os.getenv('STATIC_URL', STATIC_URL)
DEBUG = TEMPLATE_DEBUG = False
ALLOWED_HOSTS = [
'webwewant.mozilla.org',
'webwewant.allizom.org',
'glow.cdn.mozilla.net',
# the server's IP (for monitors)
socket.gethostbyname(socket.gethostname()),
]
CACHES = {
'default': {
'BACKEND': 'redis_cache.cache.RedisCache',
'LOCATION': 'unix:/var/run/redis/redis.sock:1',
'OPTIONS': {
'PARSER_CLASS': 'redis.connection.HiredisParser',
}
},
'smithers': {
'BACKEND': 'redis_cache.cache.RedisCache',
'LOCATION': 'unix:/var/run/redis/redis.sock:0',
'OPTIONS': {
'PARSER_CLASS': 'redis.connection.HiredisParser',
}
}
}
DJANGO_REDIS_IGNORE_EXCEPTIONS = False
ENABLE_REDIS = True
|
<commit_before>import os
import socket
from .base import * # noqa
SERVER_ENV = os.getenv('DJANGO_SERVER_ENV')
SECRET_KEY = os.getenv('SECRET_KEY')
STATIC_URL = os.getenv('STATIC_URL', STATIC_URL)
DEBUG = TEMPLATE_DEBUG = False
ALLOWED_HOSTS = [
'webwewant.mozilla.org',
'webwewant.allizom.org',
# the server's IP (for monitors)
socket.gethostbyname(socket.gethostname()),
]
CACHES = {
'default': {
'BACKEND': 'redis_cache.cache.RedisCache',
'LOCATION': 'unix:/var/run/redis/redis.sock:1',
'OPTIONS': {
'PARSER_CLASS': 'redis.connection.HiredisParser',
}
},
'smithers': {
'BACKEND': 'redis_cache.cache.RedisCache',
'LOCATION': 'unix:/var/run/redis/redis.sock:0',
'OPTIONS': {
'PARSER_CLASS': 'redis.connection.HiredisParser',
}
}
}
DJANGO_REDIS_IGNORE_EXCEPTIONS = False
ENABLE_REDIS = True
<commit_msg>Add CDN url to allowed hosts.<commit_after>
|
import os
import socket
from .base import * # noqa
SERVER_ENV = os.getenv('DJANGO_SERVER_ENV')
SECRET_KEY = os.getenv('SECRET_KEY')
STATIC_URL = os.getenv('STATIC_URL', STATIC_URL)
DEBUG = TEMPLATE_DEBUG = False
ALLOWED_HOSTS = [
'webwewant.mozilla.org',
'webwewant.allizom.org',
'glow.cdn.mozilla.net',
# the server's IP (for monitors)
socket.gethostbyname(socket.gethostname()),
]
CACHES = {
'default': {
'BACKEND': 'redis_cache.cache.RedisCache',
'LOCATION': 'unix:/var/run/redis/redis.sock:1',
'OPTIONS': {
'PARSER_CLASS': 'redis.connection.HiredisParser',
}
},
'smithers': {
'BACKEND': 'redis_cache.cache.RedisCache',
'LOCATION': 'unix:/var/run/redis/redis.sock:0',
'OPTIONS': {
'PARSER_CLASS': 'redis.connection.HiredisParser',
}
}
}
DJANGO_REDIS_IGNORE_EXCEPTIONS = False
ENABLE_REDIS = True
|
import os
import socket
from .base import * # noqa
SERVER_ENV = os.getenv('DJANGO_SERVER_ENV')
SECRET_KEY = os.getenv('SECRET_KEY')
STATIC_URL = os.getenv('STATIC_URL', STATIC_URL)
DEBUG = TEMPLATE_DEBUG = False
ALLOWED_HOSTS = [
'webwewant.mozilla.org',
'webwewant.allizom.org',
# the server's IP (for monitors)
socket.gethostbyname(socket.gethostname()),
]
CACHES = {
'default': {
'BACKEND': 'redis_cache.cache.RedisCache',
'LOCATION': 'unix:/var/run/redis/redis.sock:1',
'OPTIONS': {
'PARSER_CLASS': 'redis.connection.HiredisParser',
}
},
'smithers': {
'BACKEND': 'redis_cache.cache.RedisCache',
'LOCATION': 'unix:/var/run/redis/redis.sock:0',
'OPTIONS': {
'PARSER_CLASS': 'redis.connection.HiredisParser',
}
}
}
DJANGO_REDIS_IGNORE_EXCEPTIONS = False
ENABLE_REDIS = True
Add CDN url to allowed hosts.import os
import socket
from .base import * # noqa
SERVER_ENV = os.getenv('DJANGO_SERVER_ENV')
SECRET_KEY = os.getenv('SECRET_KEY')
STATIC_URL = os.getenv('STATIC_URL', STATIC_URL)
DEBUG = TEMPLATE_DEBUG = False
ALLOWED_HOSTS = [
'webwewant.mozilla.org',
'webwewant.allizom.org',
'glow.cdn.mozilla.net',
# the server's IP (for monitors)
socket.gethostbyname(socket.gethostname()),
]
CACHES = {
'default': {
'BACKEND': 'redis_cache.cache.RedisCache',
'LOCATION': 'unix:/var/run/redis/redis.sock:1',
'OPTIONS': {
'PARSER_CLASS': 'redis.connection.HiredisParser',
}
},
'smithers': {
'BACKEND': 'redis_cache.cache.RedisCache',
'LOCATION': 'unix:/var/run/redis/redis.sock:0',
'OPTIONS': {
'PARSER_CLASS': 'redis.connection.HiredisParser',
}
}
}
DJANGO_REDIS_IGNORE_EXCEPTIONS = False
ENABLE_REDIS = True
|
<commit_before>import os
import socket
from .base import * # noqa
SERVER_ENV = os.getenv('DJANGO_SERVER_ENV')
SECRET_KEY = os.getenv('SECRET_KEY')
STATIC_URL = os.getenv('STATIC_URL', STATIC_URL)
DEBUG = TEMPLATE_DEBUG = False
ALLOWED_HOSTS = [
'webwewant.mozilla.org',
'webwewant.allizom.org',
# the server's IP (for monitors)
socket.gethostbyname(socket.gethostname()),
]
CACHES = {
'default': {
'BACKEND': 'redis_cache.cache.RedisCache',
'LOCATION': 'unix:/var/run/redis/redis.sock:1',
'OPTIONS': {
'PARSER_CLASS': 'redis.connection.HiredisParser',
}
},
'smithers': {
'BACKEND': 'redis_cache.cache.RedisCache',
'LOCATION': 'unix:/var/run/redis/redis.sock:0',
'OPTIONS': {
'PARSER_CLASS': 'redis.connection.HiredisParser',
}
}
}
DJANGO_REDIS_IGNORE_EXCEPTIONS = False
ENABLE_REDIS = True
<commit_msg>Add CDN url to allowed hosts.<commit_after>import os
import socket
from .base import * # noqa
SERVER_ENV = os.getenv('DJANGO_SERVER_ENV')
SECRET_KEY = os.getenv('SECRET_KEY')
STATIC_URL = os.getenv('STATIC_URL', STATIC_URL)
DEBUG = TEMPLATE_DEBUG = False
ALLOWED_HOSTS = [
'webwewant.mozilla.org',
'webwewant.allizom.org',
'glow.cdn.mozilla.net',
# the server's IP (for monitors)
socket.gethostbyname(socket.gethostname()),
]
CACHES = {
'default': {
'BACKEND': 'redis_cache.cache.RedisCache',
'LOCATION': 'unix:/var/run/redis/redis.sock:1',
'OPTIONS': {
'PARSER_CLASS': 'redis.connection.HiredisParser',
}
},
'smithers': {
'BACKEND': 'redis_cache.cache.RedisCache',
'LOCATION': 'unix:/var/run/redis/redis.sock:0',
'OPTIONS': {
'PARSER_CLASS': 'redis.connection.HiredisParser',
}
}
}
DJANGO_REDIS_IGNORE_EXCEPTIONS = False
ENABLE_REDIS = True
|
ab500891a44e7034e02889acc5f8ac1d44cb9aad
|
tests/test_error.py
|
tests/test_error.py
|
from __future__ import unicode_literals
import unittest
import six
import spotify
class ErrorTest(unittest.TestCase):
def test_error_has_error_code(self):
error = spotify.Error(0)
self.assertEqual(error.error_code, 0)
error = spotify.Error(1)
self.assertEqual(error.error_code, 1)
def test_error_has_error_message(self):
error = spotify.Error(0)
self.assertEqual(error.message, 'No error')
self.assertIsInstance(error.message, six.text_type)
error = spotify.Error(1)
self.assertEqual(error.message, 'Invalid library version')
def test_error_has_useful_repr(self):
error = spotify.Error(0)
self.assertEqual(repr(error), b"Error(u'No error',)")
def test_error_has_useful_str(self):
error = spotify.Error(0)
self.assertEqual(str(error), 'No error')
def test_error_has_error_constants(self):
self.assertEqual(spotify.Error.OK, 0)
self.assertEqual(spotify.Error.BAD_API_VERSION, 1)
|
from __future__ import unicode_literals
import unittest
import six
import spotify
class ErrorTest(unittest.TestCase):
def test_error_has_error_code(self):
error = spotify.Error(0)
self.assertEqual(error.error_code, 0)
error = spotify.Error(1)
self.assertEqual(error.error_code, 1)
def test_error_has_useful_repr(self):
error = spotify.Error(0)
self.assertIn('No error', repr(error))
def test_error_has_useful_string_representation(self):
error = spotify.Error(0)
self.assertEqual('%s' % error, 'No error')
self.assertIsInstance('%s' % error, six.text_type)
error = spotify.Error(1)
self.assertEqual('%s' % error, 'Invalid library version')
def test_error_has_error_constants(self):
self.assertEqual(spotify.Error.OK, 0)
self.assertEqual(spotify.Error.BAD_API_VERSION, 1)
|
Make Error behavior consistent across Pythons
|
Make Error behavior consistent across Pythons
|
Python
|
apache-2.0
|
felix1m/pyspotify,jodal/pyspotify,jodal/pyspotify,felix1m/pyspotify,kotamat/pyspotify,jodal/pyspotify,kotamat/pyspotify,mopidy/pyspotify,mopidy/pyspotify,kotamat/pyspotify,felix1m/pyspotify
|
from __future__ import unicode_literals
import unittest
import six
import spotify
class ErrorTest(unittest.TestCase):
def test_error_has_error_code(self):
error = spotify.Error(0)
self.assertEqual(error.error_code, 0)
error = spotify.Error(1)
self.assertEqual(error.error_code, 1)
def test_error_has_error_message(self):
error = spotify.Error(0)
self.assertEqual(error.message, 'No error')
self.assertIsInstance(error.message, six.text_type)
error = spotify.Error(1)
self.assertEqual(error.message, 'Invalid library version')
def test_error_has_useful_repr(self):
error = spotify.Error(0)
self.assertEqual(repr(error), b"Error(u'No error',)")
def test_error_has_useful_str(self):
error = spotify.Error(0)
self.assertEqual(str(error), 'No error')
def test_error_has_error_constants(self):
self.assertEqual(spotify.Error.OK, 0)
self.assertEqual(spotify.Error.BAD_API_VERSION, 1)
Make Error behavior consistent across Pythons
|
from __future__ import unicode_literals
import unittest
import six
import spotify
class ErrorTest(unittest.TestCase):
def test_error_has_error_code(self):
error = spotify.Error(0)
self.assertEqual(error.error_code, 0)
error = spotify.Error(1)
self.assertEqual(error.error_code, 1)
def test_error_has_useful_repr(self):
error = spotify.Error(0)
self.assertIn('No error', repr(error))
def test_error_has_useful_string_representation(self):
error = spotify.Error(0)
self.assertEqual('%s' % error, 'No error')
self.assertIsInstance('%s' % error, six.text_type)
error = spotify.Error(1)
self.assertEqual('%s' % error, 'Invalid library version')
def test_error_has_error_constants(self):
self.assertEqual(spotify.Error.OK, 0)
self.assertEqual(spotify.Error.BAD_API_VERSION, 1)
|
<commit_before>from __future__ import unicode_literals
import unittest
import six
import spotify
class ErrorTest(unittest.TestCase):
def test_error_has_error_code(self):
error = spotify.Error(0)
self.assertEqual(error.error_code, 0)
error = spotify.Error(1)
self.assertEqual(error.error_code, 1)
def test_error_has_error_message(self):
error = spotify.Error(0)
self.assertEqual(error.message, 'No error')
self.assertIsInstance(error.message, six.text_type)
error = spotify.Error(1)
self.assertEqual(error.message, 'Invalid library version')
def test_error_has_useful_repr(self):
error = spotify.Error(0)
self.assertEqual(repr(error), b"Error(u'No error',)")
def test_error_has_useful_str(self):
error = spotify.Error(0)
self.assertEqual(str(error), 'No error')
def test_error_has_error_constants(self):
self.assertEqual(spotify.Error.OK, 0)
self.assertEqual(spotify.Error.BAD_API_VERSION, 1)
<commit_msg>Make Error behavior consistent across Pythons<commit_after>
|
from __future__ import unicode_literals
import unittest
import six
import spotify
class ErrorTest(unittest.TestCase):
def test_error_has_error_code(self):
error = spotify.Error(0)
self.assertEqual(error.error_code, 0)
error = spotify.Error(1)
self.assertEqual(error.error_code, 1)
def test_error_has_useful_repr(self):
error = spotify.Error(0)
self.assertIn('No error', repr(error))
def test_error_has_useful_string_representation(self):
error = spotify.Error(0)
self.assertEqual('%s' % error, 'No error')
self.assertIsInstance('%s' % error, six.text_type)
error = spotify.Error(1)
self.assertEqual('%s' % error, 'Invalid library version')
def test_error_has_error_constants(self):
self.assertEqual(spotify.Error.OK, 0)
self.assertEqual(spotify.Error.BAD_API_VERSION, 1)
|
from __future__ import unicode_literals
import unittest
import six
import spotify
class ErrorTest(unittest.TestCase):
def test_error_has_error_code(self):
error = spotify.Error(0)
self.assertEqual(error.error_code, 0)
error = spotify.Error(1)
self.assertEqual(error.error_code, 1)
def test_error_has_error_message(self):
error = spotify.Error(0)
self.assertEqual(error.message, 'No error')
self.assertIsInstance(error.message, six.text_type)
error = spotify.Error(1)
self.assertEqual(error.message, 'Invalid library version')
def test_error_has_useful_repr(self):
error = spotify.Error(0)
self.assertEqual(repr(error), b"Error(u'No error',)")
def test_error_has_useful_str(self):
error = spotify.Error(0)
self.assertEqual(str(error), 'No error')
def test_error_has_error_constants(self):
self.assertEqual(spotify.Error.OK, 0)
self.assertEqual(spotify.Error.BAD_API_VERSION, 1)
Make Error behavior consistent across Pythonsfrom __future__ import unicode_literals
import unittest
import six
import spotify
class ErrorTest(unittest.TestCase):
def test_error_has_error_code(self):
error = spotify.Error(0)
self.assertEqual(error.error_code, 0)
error = spotify.Error(1)
self.assertEqual(error.error_code, 1)
def test_error_has_useful_repr(self):
error = spotify.Error(0)
self.assertIn('No error', repr(error))
def test_error_has_useful_string_representation(self):
error = spotify.Error(0)
self.assertEqual('%s' % error, 'No error')
self.assertIsInstance('%s' % error, six.text_type)
error = spotify.Error(1)
self.assertEqual('%s' % error, 'Invalid library version')
def test_error_has_error_constants(self):
self.assertEqual(spotify.Error.OK, 0)
self.assertEqual(spotify.Error.BAD_API_VERSION, 1)
|
<commit_before>from __future__ import unicode_literals
import unittest
import six
import spotify
class ErrorTest(unittest.TestCase):
def test_error_has_error_code(self):
error = spotify.Error(0)
self.assertEqual(error.error_code, 0)
error = spotify.Error(1)
self.assertEqual(error.error_code, 1)
def test_error_has_error_message(self):
error = spotify.Error(0)
self.assertEqual(error.message, 'No error')
self.assertIsInstance(error.message, six.text_type)
error = spotify.Error(1)
self.assertEqual(error.message, 'Invalid library version')
def test_error_has_useful_repr(self):
error = spotify.Error(0)
self.assertEqual(repr(error), b"Error(u'No error',)")
def test_error_has_useful_str(self):
error = spotify.Error(0)
self.assertEqual(str(error), 'No error')
def test_error_has_error_constants(self):
self.assertEqual(spotify.Error.OK, 0)
self.assertEqual(spotify.Error.BAD_API_VERSION, 1)
<commit_msg>Make Error behavior consistent across Pythons<commit_after>from __future__ import unicode_literals
import unittest
import six
import spotify
class ErrorTest(unittest.TestCase):
def test_error_has_error_code(self):
error = spotify.Error(0)
self.assertEqual(error.error_code, 0)
error = spotify.Error(1)
self.assertEqual(error.error_code, 1)
def test_error_has_useful_repr(self):
error = spotify.Error(0)
self.assertIn('No error', repr(error))
def test_error_has_useful_string_representation(self):
error = spotify.Error(0)
self.assertEqual('%s' % error, 'No error')
self.assertIsInstance('%s' % error, six.text_type)
error = spotify.Error(1)
self.assertEqual('%s' % error, 'Invalid library version')
def test_error_has_error_constants(self):
self.assertEqual(spotify.Error.OK, 0)
self.assertEqual(spotify.Error.BAD_API_VERSION, 1)
|
72bc614be6ed7f233fafeef11ab89561752be066
|
timpani/settings.py
|
timpani/settings.py
|
from . import database
def getAllSettings():
databaseConnection = database.ConnectionManager.getConnection("main")
query = databaseConnection.session.query(database.tables.Setting)
settings = query.all()
return {setting.name: setting.value for setting in settings}
def getSettingValue(name):
databaseConnection = database.ConnectionManager.getConnection("main")
query = databaseConnection.session.query(database.tables.Setting).filter(database.tables.Setting.name == name)
if query.count() > 0:
return query.first().value
return None
def setSettingValue(name, value):
databaseConnection = database.ConnectionManager.getConnection("main")
settingObj = database.tables.Setting(name = name, value = value)
databaseConnection.session.merge(settingObj)
databaseConnection.session.commit()
|
from . import database
def getAllSettings():
databaseConnection = database.ConnectionManager.getConnection("main")
query = databaseConnection.session.query(database.tables.Setting)
settings = query.all()
return {setting.name: setting.value for setting in settings}
def getSettingValue(name):
databaseConnection = database.ConnectionManager.getConnection("main")
query = databaseConnection.session
.query(database.tables.Setting)
.filter(database.tables.Setting.name == name)
if query.count() > 0:
return query.first().value
return None
def setSettingValue(name, value):
databaseConnection = database.ConnectionManager.getConnection("main")
settingObj = database.tables.Setting(name = name, value = value)
databaseConnection.session.merge(settingObj)
databaseConnection.session.commit()
|
Fix lines in auth.py to to be 79 chars or less
|
Fix lines in auth.py to to be 79 chars or less
|
Python
|
mit
|
ollien/Timpani,ollien/Timpani,ollien/Timpani
|
from . import database
def getAllSettings():
databaseConnection = database.ConnectionManager.getConnection("main")
query = databaseConnection.session.query(database.tables.Setting)
settings = query.all()
return {setting.name: setting.value for setting in settings}
def getSettingValue(name):
databaseConnection = database.ConnectionManager.getConnection("main")
query = databaseConnection.session.query(database.tables.Setting).filter(database.tables.Setting.name == name)
if query.count() > 0:
return query.first().value
return None
def setSettingValue(name, value):
databaseConnection = database.ConnectionManager.getConnection("main")
settingObj = database.tables.Setting(name = name, value = value)
databaseConnection.session.merge(settingObj)
databaseConnection.session.commit()
Fix lines in auth.py to to be 79 chars or less
|
from . import database
def getAllSettings():
databaseConnection = database.ConnectionManager.getConnection("main")
query = databaseConnection.session.query(database.tables.Setting)
settings = query.all()
return {setting.name: setting.value for setting in settings}
def getSettingValue(name):
databaseConnection = database.ConnectionManager.getConnection("main")
query = databaseConnection.session
.query(database.tables.Setting)
.filter(database.tables.Setting.name == name)
if query.count() > 0:
return query.first().value
return None
def setSettingValue(name, value):
databaseConnection = database.ConnectionManager.getConnection("main")
settingObj = database.tables.Setting(name = name, value = value)
databaseConnection.session.merge(settingObj)
databaseConnection.session.commit()
|
<commit_before>from . import database
def getAllSettings():
databaseConnection = database.ConnectionManager.getConnection("main")
query = databaseConnection.session.query(database.tables.Setting)
settings = query.all()
return {setting.name: setting.value for setting in settings}
def getSettingValue(name):
databaseConnection = database.ConnectionManager.getConnection("main")
query = databaseConnection.session.query(database.tables.Setting).filter(database.tables.Setting.name == name)
if query.count() > 0:
return query.first().value
return None
def setSettingValue(name, value):
databaseConnection = database.ConnectionManager.getConnection("main")
settingObj = database.tables.Setting(name = name, value = value)
databaseConnection.session.merge(settingObj)
databaseConnection.session.commit()
<commit_msg>Fix lines in auth.py to to be 79 chars or less<commit_after>
|
from . import database
def getAllSettings():
databaseConnection = database.ConnectionManager.getConnection("main")
query = databaseConnection.session.query(database.tables.Setting)
settings = query.all()
return {setting.name: setting.value for setting in settings}
def getSettingValue(name):
databaseConnection = database.ConnectionManager.getConnection("main")
query = databaseConnection.session
.query(database.tables.Setting)
.filter(database.tables.Setting.name == name)
if query.count() > 0:
return query.first().value
return None
def setSettingValue(name, value):
databaseConnection = database.ConnectionManager.getConnection("main")
settingObj = database.tables.Setting(name = name, value = value)
databaseConnection.session.merge(settingObj)
databaseConnection.session.commit()
|
from . import database
def getAllSettings():
databaseConnection = database.ConnectionManager.getConnection("main")
query = databaseConnection.session.query(database.tables.Setting)
settings = query.all()
return {setting.name: setting.value for setting in settings}
def getSettingValue(name):
databaseConnection = database.ConnectionManager.getConnection("main")
query = databaseConnection.session.query(database.tables.Setting).filter(database.tables.Setting.name == name)
if query.count() > 0:
return query.first().value
return None
def setSettingValue(name, value):
databaseConnection = database.ConnectionManager.getConnection("main")
settingObj = database.tables.Setting(name = name, value = value)
databaseConnection.session.merge(settingObj)
databaseConnection.session.commit()
Fix lines in auth.py to to be 79 chars or lessfrom . import database
def getAllSettings():
databaseConnection = database.ConnectionManager.getConnection("main")
query = databaseConnection.session.query(database.tables.Setting)
settings = query.all()
return {setting.name: setting.value for setting in settings}
def getSettingValue(name):
databaseConnection = database.ConnectionManager.getConnection("main")
query = databaseConnection.session
.query(database.tables.Setting)
.filter(database.tables.Setting.name == name)
if query.count() > 0:
return query.first().value
return None
def setSettingValue(name, value):
databaseConnection = database.ConnectionManager.getConnection("main")
settingObj = database.tables.Setting(name = name, value = value)
databaseConnection.session.merge(settingObj)
databaseConnection.session.commit()
|
<commit_before>from . import database
def getAllSettings():
databaseConnection = database.ConnectionManager.getConnection("main")
query = databaseConnection.session.query(database.tables.Setting)
settings = query.all()
return {setting.name: setting.value for setting in settings}
def getSettingValue(name):
databaseConnection = database.ConnectionManager.getConnection("main")
query = databaseConnection.session.query(database.tables.Setting).filter(database.tables.Setting.name == name)
if query.count() > 0:
return query.first().value
return None
def setSettingValue(name, value):
databaseConnection = database.ConnectionManager.getConnection("main")
settingObj = database.tables.Setting(name = name, value = value)
databaseConnection.session.merge(settingObj)
databaseConnection.session.commit()
<commit_msg>Fix lines in auth.py to to be 79 chars or less<commit_after>from . import database
def getAllSettings():
databaseConnection = database.ConnectionManager.getConnection("main")
query = databaseConnection.session.query(database.tables.Setting)
settings = query.all()
return {setting.name: setting.value for setting in settings}
def getSettingValue(name):
databaseConnection = database.ConnectionManager.getConnection("main")
query = databaseConnection.session
.query(database.tables.Setting)
.filter(database.tables.Setting.name == name)
if query.count() > 0:
return query.first().value
return None
def setSettingValue(name, value):
databaseConnection = database.ConnectionManager.getConnection("main")
settingObj = database.tables.Setting(name = name, value = value)
databaseConnection.session.merge(settingObj)
databaseConnection.session.commit()
|
8ee35fe46e978fcb17e99b50f045009ea8235067
|
tools/pdtools/pdtools/devices/camera.py
|
tools/pdtools/pdtools/devices/camera.py
|
import base64
import requests
import six
class Camera(object):
def __init__(self, host):
self.host = host
def get_image(self):
"""
Get an image from the camera.
Returns image data as a BytesIO/StringIO object.
"""
url = "http://{}/image.jpg".format(self.host)
encoded = base64.b64encode('admin:'.encode('utf-8')).decode('ascii')
headers = {
'Authorization': 'Basic ' + encoded
}
result = requests.get(url, headers=headers)
if result.ok:
return six.BytesIO(result.content)
else:
return None
|
import base64
import requests
import six
class Camera(object):
def __init__(self, host):
self.host = host
def __repr__(self):
return "Camera({})".format(self.host)
def get_image(self):
"""
Get an image from the camera.
Returns image data as a BytesIO/StringIO object.
"""
url = "http://{}/image.jpg".format(self.host)
encoded = base64.b64encode('admin:'.encode('utf-8')).decode('ascii')
headers = {
'Authorization': 'Basic ' + encoded
}
result = requests.get(url, headers=headers)
if result.ok:
return six.BytesIO(result.content)
else:
return None
|
Define __repr__ for pdtools Camera class.
|
Define __repr__ for pdtools Camera class.
|
Python
|
apache-2.0
|
ParadropLabs/Paradrop,ParadropLabs/Paradrop,ParadropLabs/Paradrop
|
import base64
import requests
import six
class Camera(object):
def __init__(self, host):
self.host = host
def get_image(self):
"""
Get an image from the camera.
Returns image data as a BytesIO/StringIO object.
"""
url = "http://{}/image.jpg".format(self.host)
encoded = base64.b64encode('admin:'.encode('utf-8')).decode('ascii')
headers = {
'Authorization': 'Basic ' + encoded
}
result = requests.get(url, headers=headers)
if result.ok:
return six.BytesIO(result.content)
else:
return None
Define __repr__ for pdtools Camera class.
|
import base64
import requests
import six
class Camera(object):
def __init__(self, host):
self.host = host
def __repr__(self):
return "Camera({})".format(self.host)
def get_image(self):
"""
Get an image from the camera.
Returns image data as a BytesIO/StringIO object.
"""
url = "http://{}/image.jpg".format(self.host)
encoded = base64.b64encode('admin:'.encode('utf-8')).decode('ascii')
headers = {
'Authorization': 'Basic ' + encoded
}
result = requests.get(url, headers=headers)
if result.ok:
return six.BytesIO(result.content)
else:
return None
|
<commit_before>import base64
import requests
import six
class Camera(object):
def __init__(self, host):
self.host = host
def get_image(self):
"""
Get an image from the camera.
Returns image data as a BytesIO/StringIO object.
"""
url = "http://{}/image.jpg".format(self.host)
encoded = base64.b64encode('admin:'.encode('utf-8')).decode('ascii')
headers = {
'Authorization': 'Basic ' + encoded
}
result = requests.get(url, headers=headers)
if result.ok:
return six.BytesIO(result.content)
else:
return None
<commit_msg>Define __repr__ for pdtools Camera class.<commit_after>
|
import base64
import requests
import six
class Camera(object):
def __init__(self, host):
self.host = host
def __repr__(self):
return "Camera({})".format(self.host)
def get_image(self):
"""
Get an image from the camera.
Returns image data as a BytesIO/StringIO object.
"""
url = "http://{}/image.jpg".format(self.host)
encoded = base64.b64encode('admin:'.encode('utf-8')).decode('ascii')
headers = {
'Authorization': 'Basic ' + encoded
}
result = requests.get(url, headers=headers)
if result.ok:
return six.BytesIO(result.content)
else:
return None
|
import base64
import requests
import six
class Camera(object):
def __init__(self, host):
self.host = host
def get_image(self):
"""
Get an image from the camera.
Returns image data as a BytesIO/StringIO object.
"""
url = "http://{}/image.jpg".format(self.host)
encoded = base64.b64encode('admin:'.encode('utf-8')).decode('ascii')
headers = {
'Authorization': 'Basic ' + encoded
}
result = requests.get(url, headers=headers)
if result.ok:
return six.BytesIO(result.content)
else:
return None
Define __repr__ for pdtools Camera class.import base64
import requests
import six
class Camera(object):
def __init__(self, host):
self.host = host
def __repr__(self):
return "Camera({})".format(self.host)
def get_image(self):
"""
Get an image from the camera.
Returns image data as a BytesIO/StringIO object.
"""
url = "http://{}/image.jpg".format(self.host)
encoded = base64.b64encode('admin:'.encode('utf-8')).decode('ascii')
headers = {
'Authorization': 'Basic ' + encoded
}
result = requests.get(url, headers=headers)
if result.ok:
return six.BytesIO(result.content)
else:
return None
|
<commit_before>import base64
import requests
import six
class Camera(object):
def __init__(self, host):
self.host = host
def get_image(self):
"""
Get an image from the camera.
Returns image data as a BytesIO/StringIO object.
"""
url = "http://{}/image.jpg".format(self.host)
encoded = base64.b64encode('admin:'.encode('utf-8')).decode('ascii')
headers = {
'Authorization': 'Basic ' + encoded
}
result = requests.get(url, headers=headers)
if result.ok:
return six.BytesIO(result.content)
else:
return None
<commit_msg>Define __repr__ for pdtools Camera class.<commit_after>import base64
import requests
import six
class Camera(object):
def __init__(self, host):
self.host = host
def __repr__(self):
return "Camera({})".format(self.host)
def get_image(self):
"""
Get an image from the camera.
Returns image data as a BytesIO/StringIO object.
"""
url = "http://{}/image.jpg".format(self.host)
encoded = base64.b64encode('admin:'.encode('utf-8')).decode('ascii')
headers = {
'Authorization': 'Basic ' + encoded
}
result = requests.get(url, headers=headers)
if result.ok:
return six.BytesIO(result.content)
else:
return None
|
3b6eaabe93a92782a1a5198ae4b03fa5e501a770
|
agir/activity/serializers.py
|
agir/activity/serializers.py
|
from rest_framework import serializers
from agir.events.serializers import EventSerializer
from agir.groups.serializers import SupportGroupSerializer
from agir.lib.serializers import FlexibleFieldsMixin
from agir.people.serializers import PersonSerializer
class ActivitySerializer(FlexibleFieldsMixin, serializers.Serializer):
id = serializers.CharField()
type = serializers.CharField()
subtype = serializers.CharField(source="type")
timestamp = serializers.DateTimeField()
event = EventSerializer(
fields=[
"id",
"name",
"startTime",
"endTime",
"participantCount",
"illustration",
"schedule",
"location",
"rsvp",
"routes",
]
)
supportGroup = SupportGroupSerializer(source="supportgroup", fields=["name", "url"])
individual = PersonSerializer(fields=["fullName"])
status = serializers.CharField()
|
from rest_framework import serializers
from agir.events.serializers import EventSerializer
from agir.groups.serializers import SupportGroupSerializer
from agir.lib.serializers import FlexibleFieldsMixin
from agir.people.serializers import PersonSerializer
class ActivitySerializer(FlexibleFieldsMixin, serializers.Serializer):
id = serializers.CharField()
type = serializers.CharField()
subtype = serializers.CharField(source="type")
timestamp = serializers.DateTimeField()
event = EventSerializer(
fields=[
"id",
"name",
"startTime",
"endTime",
"participantCount",
"illustration",
"schedule",
"location",
"rsvp",
"routes",
]
)
supportGroup = SupportGroupSerializer(source="supportgroup", fields=["name", "url"])
individual = PersonSerializer(fields=["fullName", "email"])
status = serializers.CharField()
|
Add individual email field to activity serializer
|
Add individual email field to activity serializer
|
Python
|
agpl-3.0
|
lafranceinsoumise/api-django,lafranceinsoumise/api-django,lafranceinsoumise/api-django,lafranceinsoumise/api-django
|
from rest_framework import serializers
from agir.events.serializers import EventSerializer
from agir.groups.serializers import SupportGroupSerializer
from agir.lib.serializers import FlexibleFieldsMixin
from agir.people.serializers import PersonSerializer
class ActivitySerializer(FlexibleFieldsMixin, serializers.Serializer):
id = serializers.CharField()
type = serializers.CharField()
subtype = serializers.CharField(source="type")
timestamp = serializers.DateTimeField()
event = EventSerializer(
fields=[
"id",
"name",
"startTime",
"endTime",
"participantCount",
"illustration",
"schedule",
"location",
"rsvp",
"routes",
]
)
supportGroup = SupportGroupSerializer(source="supportgroup", fields=["name", "url"])
individual = PersonSerializer(fields=["fullName"])
status = serializers.CharField()
Add individual email field to activity serializer
|
from rest_framework import serializers
from agir.events.serializers import EventSerializer
from agir.groups.serializers import SupportGroupSerializer
from agir.lib.serializers import FlexibleFieldsMixin
from agir.people.serializers import PersonSerializer
class ActivitySerializer(FlexibleFieldsMixin, serializers.Serializer):
id = serializers.CharField()
type = serializers.CharField()
subtype = serializers.CharField(source="type")
timestamp = serializers.DateTimeField()
event = EventSerializer(
fields=[
"id",
"name",
"startTime",
"endTime",
"participantCount",
"illustration",
"schedule",
"location",
"rsvp",
"routes",
]
)
supportGroup = SupportGroupSerializer(source="supportgroup", fields=["name", "url"])
individual = PersonSerializer(fields=["fullName", "email"])
status = serializers.CharField()
|
<commit_before>from rest_framework import serializers
from agir.events.serializers import EventSerializer
from agir.groups.serializers import SupportGroupSerializer
from agir.lib.serializers import FlexibleFieldsMixin
from agir.people.serializers import PersonSerializer
class ActivitySerializer(FlexibleFieldsMixin, serializers.Serializer):
id = serializers.CharField()
type = serializers.CharField()
subtype = serializers.CharField(source="type")
timestamp = serializers.DateTimeField()
event = EventSerializer(
fields=[
"id",
"name",
"startTime",
"endTime",
"participantCount",
"illustration",
"schedule",
"location",
"rsvp",
"routes",
]
)
supportGroup = SupportGroupSerializer(source="supportgroup", fields=["name", "url"])
individual = PersonSerializer(fields=["fullName"])
status = serializers.CharField()
<commit_msg>Add individual email field to activity serializer<commit_after>
|
from rest_framework import serializers
from agir.events.serializers import EventSerializer
from agir.groups.serializers import SupportGroupSerializer
from agir.lib.serializers import FlexibleFieldsMixin
from agir.people.serializers import PersonSerializer
class ActivitySerializer(FlexibleFieldsMixin, serializers.Serializer):
id = serializers.CharField()
type = serializers.CharField()
subtype = serializers.CharField(source="type")
timestamp = serializers.DateTimeField()
event = EventSerializer(
fields=[
"id",
"name",
"startTime",
"endTime",
"participantCount",
"illustration",
"schedule",
"location",
"rsvp",
"routes",
]
)
supportGroup = SupportGroupSerializer(source="supportgroup", fields=["name", "url"])
individual = PersonSerializer(fields=["fullName", "email"])
status = serializers.CharField()
|
from rest_framework import serializers
from agir.events.serializers import EventSerializer
from agir.groups.serializers import SupportGroupSerializer
from agir.lib.serializers import FlexibleFieldsMixin
from agir.people.serializers import PersonSerializer
class ActivitySerializer(FlexibleFieldsMixin, serializers.Serializer):
id = serializers.CharField()
type = serializers.CharField()
subtype = serializers.CharField(source="type")
timestamp = serializers.DateTimeField()
event = EventSerializer(
fields=[
"id",
"name",
"startTime",
"endTime",
"participantCount",
"illustration",
"schedule",
"location",
"rsvp",
"routes",
]
)
supportGroup = SupportGroupSerializer(source="supportgroup", fields=["name", "url"])
individual = PersonSerializer(fields=["fullName"])
status = serializers.CharField()
Add individual email field to activity serializerfrom rest_framework import serializers
from agir.events.serializers import EventSerializer
from agir.groups.serializers import SupportGroupSerializer
from agir.lib.serializers import FlexibleFieldsMixin
from agir.people.serializers import PersonSerializer
class ActivitySerializer(FlexibleFieldsMixin, serializers.Serializer):
id = serializers.CharField()
type = serializers.CharField()
subtype = serializers.CharField(source="type")
timestamp = serializers.DateTimeField()
event = EventSerializer(
fields=[
"id",
"name",
"startTime",
"endTime",
"participantCount",
"illustration",
"schedule",
"location",
"rsvp",
"routes",
]
)
supportGroup = SupportGroupSerializer(source="supportgroup", fields=["name", "url"])
individual = PersonSerializer(fields=["fullName", "email"])
status = serializers.CharField()
|
<commit_before>from rest_framework import serializers
from agir.events.serializers import EventSerializer
from agir.groups.serializers import SupportGroupSerializer
from agir.lib.serializers import FlexibleFieldsMixin
from agir.people.serializers import PersonSerializer
class ActivitySerializer(FlexibleFieldsMixin, serializers.Serializer):
id = serializers.CharField()
type = serializers.CharField()
subtype = serializers.CharField(source="type")
timestamp = serializers.DateTimeField()
event = EventSerializer(
fields=[
"id",
"name",
"startTime",
"endTime",
"participantCount",
"illustration",
"schedule",
"location",
"rsvp",
"routes",
]
)
supportGroup = SupportGroupSerializer(source="supportgroup", fields=["name", "url"])
individual = PersonSerializer(fields=["fullName"])
status = serializers.CharField()
<commit_msg>Add individual email field to activity serializer<commit_after>from rest_framework import serializers
from agir.events.serializers import EventSerializer
from agir.groups.serializers import SupportGroupSerializer
from agir.lib.serializers import FlexibleFieldsMixin
from agir.people.serializers import PersonSerializer
class ActivitySerializer(FlexibleFieldsMixin, serializers.Serializer):
id = serializers.CharField()
type = serializers.CharField()
subtype = serializers.CharField(source="type")
timestamp = serializers.DateTimeField()
event = EventSerializer(
fields=[
"id",
"name",
"startTime",
"endTime",
"participantCount",
"illustration",
"schedule",
"location",
"rsvp",
"routes",
]
)
supportGroup = SupportGroupSerializer(source="supportgroup", fields=["name", "url"])
individual = PersonSerializer(fields=["fullName", "email"])
status = serializers.CharField()
|
8e5c55a4710352d5f3b211c9df7d11c3cf9ef104
|
us_ignite/dummy/text.py
|
us_ignite/dummy/text.py
|
from random import choice
from django.conf import settings
words = open(settings.WORDS_PATH, "r").readlines()
def random_words(total):
return " ".join([choice(words).lower().rstrip() for i in range(total)])
def random_paragraphs(total, word_no=30):
return ".\n\n".join([random_words(word_no) for i in range(total)])
|
from random import choice
from django.conf import settings
from django.utils.encoding import smart_text
words = open(settings.WORDS_PATH, "r").readlines()
def random_words(total):
return u" ".join([smart_text(choice(words).lower().rstrip()) for i in range(total)])
def random_paragraphs(total, word_no=30):
return u".\n\n".join([random_words(word_no) for i in range(total)])
|
Handle encoding of the random words.
|
Handle encoding of the random words.
|
Python
|
bsd-3-clause
|
us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite
|
from random import choice
from django.conf import settings
words = open(settings.WORDS_PATH, "r").readlines()
def random_words(total):
return " ".join([choice(words).lower().rstrip() for i in range(total)])
def random_paragraphs(total, word_no=30):
return ".\n\n".join([random_words(word_no) for i in range(total)])
Handle encoding of the random words.
|
from random import choice
from django.conf import settings
from django.utils.encoding import smart_text
words = open(settings.WORDS_PATH, "r").readlines()
def random_words(total):
return u" ".join([smart_text(choice(words).lower().rstrip()) for i in range(total)])
def random_paragraphs(total, word_no=30):
return u".\n\n".join([random_words(word_no) for i in range(total)])
|
<commit_before>from random import choice
from django.conf import settings
words = open(settings.WORDS_PATH, "r").readlines()
def random_words(total):
return " ".join([choice(words).lower().rstrip() for i in range(total)])
def random_paragraphs(total, word_no=30):
return ".\n\n".join([random_words(word_no) for i in range(total)])
<commit_msg>Handle encoding of the random words.<commit_after>
|
from random import choice
from django.conf import settings
from django.utils.encoding import smart_text
words = open(settings.WORDS_PATH, "r").readlines()
def random_words(total):
return u" ".join([smart_text(choice(words).lower().rstrip()) for i in range(total)])
def random_paragraphs(total, word_no=30):
return u".\n\n".join([random_words(word_no) for i in range(total)])
|
from random import choice
from django.conf import settings
words = open(settings.WORDS_PATH, "r").readlines()
def random_words(total):
return " ".join([choice(words).lower().rstrip() for i in range(total)])
def random_paragraphs(total, word_no=30):
return ".\n\n".join([random_words(word_no) for i in range(total)])
Handle encoding of the random words.from random import choice
from django.conf import settings
from django.utils.encoding import smart_text
words = open(settings.WORDS_PATH, "r").readlines()
def random_words(total):
return u" ".join([smart_text(choice(words).lower().rstrip()) for i in range(total)])
def random_paragraphs(total, word_no=30):
return u".\n\n".join([random_words(word_no) for i in range(total)])
|
<commit_before>from random import choice
from django.conf import settings
words = open(settings.WORDS_PATH, "r").readlines()
def random_words(total):
return " ".join([choice(words).lower().rstrip() for i in range(total)])
def random_paragraphs(total, word_no=30):
return ".\n\n".join([random_words(word_no) for i in range(total)])
<commit_msg>Handle encoding of the random words.<commit_after>from random import choice
from django.conf import settings
from django.utils.encoding import smart_text
words = open(settings.WORDS_PATH, "r").readlines()
def random_words(total):
return u" ".join([smart_text(choice(words).lower().rstrip()) for i in range(total)])
def random_paragraphs(total, word_no=30):
return u".\n\n".join([random_words(word_no) for i in range(total)])
|
7d94abed2316c5ee6679f33d43c122b9bfcedab7
|
extra_countries/migrations/0001_initial.py
|
extra_countries/migrations/0001_initial.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('continents', '0001_initial'),
('currencies', '0001_initial'),
('cities', '0002_auto_20151112_1857'),
]
operations = [
migrations.CreateModel(
name='ExtraCountry',
fields=[
('code', models.CharField(serialize=False, primary_key=True, max_length=3)),
('country', models.OneToOneField(to='cities.Country')),
('extra_continent', models.ForeignKey(to='continents.Continent', null=True)),
('extra_currency', models.ForeignKey(to='currencies.Currency', null=True)),
],
),
]
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('continents', '0001_initial'),
('currencies', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='ExtraCountry',
fields=[
('code', models.CharField(serialize=False, primary_key=True, max_length=3)),
('country', models.OneToOneField(to='cities.Country')),
('extra_continent', models.ForeignKey(to='continents.Continent', null=True)),
('extra_currency', models.ForeignKey(to='currencies.Currency', null=True)),
],
),
]
|
Remove reference to nonexistent migration to fix tests
|
Remove reference to nonexistent migration to fix tests
|
Python
|
mit
|
openspending/cosmopolitan,kiote/cosmopolitan
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('continents', '0001_initial'),
('currencies', '0001_initial'),
('cities', '0002_auto_20151112_1857'),
]
operations = [
migrations.CreateModel(
name='ExtraCountry',
fields=[
('code', models.CharField(serialize=False, primary_key=True, max_length=3)),
('country', models.OneToOneField(to='cities.Country')),
('extra_continent', models.ForeignKey(to='continents.Continent', null=True)),
('extra_currency', models.ForeignKey(to='currencies.Currency', null=True)),
],
),
]
Remove reference to nonexistent migration to fix tests
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('continents', '0001_initial'),
('currencies', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='ExtraCountry',
fields=[
('code', models.CharField(serialize=False, primary_key=True, max_length=3)),
('country', models.OneToOneField(to='cities.Country')),
('extra_continent', models.ForeignKey(to='continents.Continent', null=True)),
('extra_currency', models.ForeignKey(to='currencies.Currency', null=True)),
],
),
]
|
<commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('continents', '0001_initial'),
('currencies', '0001_initial'),
('cities', '0002_auto_20151112_1857'),
]
operations = [
migrations.CreateModel(
name='ExtraCountry',
fields=[
('code', models.CharField(serialize=False, primary_key=True, max_length=3)),
('country', models.OneToOneField(to='cities.Country')),
('extra_continent', models.ForeignKey(to='continents.Continent', null=True)),
('extra_currency', models.ForeignKey(to='currencies.Currency', null=True)),
],
),
]
<commit_msg>Remove reference to nonexistent migration to fix tests<commit_after>
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('continents', '0001_initial'),
('currencies', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='ExtraCountry',
fields=[
('code', models.CharField(serialize=False, primary_key=True, max_length=3)),
('country', models.OneToOneField(to='cities.Country')),
('extra_continent', models.ForeignKey(to='continents.Continent', null=True)),
('extra_currency', models.ForeignKey(to='currencies.Currency', null=True)),
],
),
]
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('continents', '0001_initial'),
('currencies', '0001_initial'),
('cities', '0002_auto_20151112_1857'),
]
operations = [
migrations.CreateModel(
name='ExtraCountry',
fields=[
('code', models.CharField(serialize=False, primary_key=True, max_length=3)),
('country', models.OneToOneField(to='cities.Country')),
('extra_continent', models.ForeignKey(to='continents.Continent', null=True)),
('extra_currency', models.ForeignKey(to='currencies.Currency', null=True)),
],
),
]
Remove reference to nonexistent migration to fix tests# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('continents', '0001_initial'),
('currencies', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='ExtraCountry',
fields=[
('code', models.CharField(serialize=False, primary_key=True, max_length=3)),
('country', models.OneToOneField(to='cities.Country')),
('extra_continent', models.ForeignKey(to='continents.Continent', null=True)),
('extra_currency', models.ForeignKey(to='currencies.Currency', null=True)),
],
),
]
|
<commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('continents', '0001_initial'),
('currencies', '0001_initial'),
('cities', '0002_auto_20151112_1857'),
]
operations = [
migrations.CreateModel(
name='ExtraCountry',
fields=[
('code', models.CharField(serialize=False, primary_key=True, max_length=3)),
('country', models.OneToOneField(to='cities.Country')),
('extra_continent', models.ForeignKey(to='continents.Continent', null=True)),
('extra_currency', models.ForeignKey(to='currencies.Currency', null=True)),
],
),
]
<commit_msg>Remove reference to nonexistent migration to fix tests<commit_after># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('continents', '0001_initial'),
('currencies', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='ExtraCountry',
fields=[
('code', models.CharField(serialize=False, primary_key=True, max_length=3)),
('country', models.OneToOneField(to='cities.Country')),
('extra_continent', models.ForeignKey(to='continents.Continent', null=True)),
('extra_currency', models.ForeignKey(to='currencies.Currency', null=True)),
],
),
]
|
8a71fe98d50f7603742c60273502fb840e967c97
|
scalpel/event.py
|
scalpel/event.py
|
"""
Author: Thiago Marcos P. Santos
Created: August 28, 2008
Purpose: A signal/slot implementation
"""
from weakref import WeakValueDictionary
class Signal(object):
def __init__(self):
self.__slots = WeakValueDictionary()
def __call__(self, *args, **kargs):
for key in self.__slots:
func, _ = key
func(self.__slots[key], *args, **kargs)
def connect(self, slot):
key = (slot.im_func, id(slot.im_self))
self.__slots[key] = slot.im_self
def disconnect(self, slot):
key = (slot.im_func, id(slot.im_self))
if key in self.__slots:
self.__slots.pop(key)
def clear(self):
self.__slots.clear()
|
"""
Author: Thiago Marcos P. Santos
Created: August 28, 2008
Purpose: A signal/slot implementation
URL: http://code.activestate.com/recipes/576477/
Comment: Slightly modified with code from Patrick Chasco
(http://code.activestate.com/recipes/439356/) to support
connecting functions.
"""
from weakref import WeakValueDictionary
import inspect
class Signal(object):
def __init__(self):
self.__slots = WeakValueDictionary()
# For keeping references to _FuncHost objects.
self.__funchosts = {}
def __call__(self, *args, **kargs):
for key in self.__slots:
func, _ = key
func(self.__slots[key], *args, **kargs)
def connect(self, slot):
if inspect.ismethod(slot):
key = (slot.im_func, id(slot.im_self))
self.__slots[key] = slot.im_self
else:
host = _FuncHost(slot)
self.connect(host.meth)
# We stick a copy in here just to keep the instance alive.
self.__funchosts[slot] = host
def disconnect(self, slot):
if inspect.ismethod(slot):
key = (slot.im_func, id(slot.im_self))
if key in self.__slots:
self.__slots.pop(key)
else:
if slot in self.__funchosts:
self.disconnect(self.__funchosts[slot].meth)
self.__funchosts.pop(slot)
def clear(self):
self.__slots.clear()
class _FuncHost(object):
"""Turn a function into a method."""
def __init__(self, func):
self.func = func
def meth(self, *args, **kwargs):
self.func(*args, **kwargs)
if __name__ == '__main__':
a = 0
def test_func():
def foo():
global a
a = a + 1
s = Signal()
s()
s.connect(foo)
s()
s.disconnect(foo)
s()
assert a == 1
test_func()
|
Add support for connecting functions to Signal objects.
|
Add support for connecting functions to Signal objects.
Less elegant than the original recipe, but more functional.
|
Python
|
bsd-3-clause
|
stackp/Gum,stackp/Gum,stackp/Gum
|
"""
Author: Thiago Marcos P. Santos
Created: August 28, 2008
Purpose: A signal/slot implementation
"""
from weakref import WeakValueDictionary
class Signal(object):
def __init__(self):
self.__slots = WeakValueDictionary()
def __call__(self, *args, **kargs):
for key in self.__slots:
func, _ = key
func(self.__slots[key], *args, **kargs)
def connect(self, slot):
key = (slot.im_func, id(slot.im_self))
self.__slots[key] = slot.im_self
def disconnect(self, slot):
key = (slot.im_func, id(slot.im_self))
if key in self.__slots:
self.__slots.pop(key)
def clear(self):
self.__slots.clear()
Add support for connecting functions to Signal objects.
Less elegant than the original recipe, but more functional.
|
"""
Author: Thiago Marcos P. Santos
Created: August 28, 2008
Purpose: A signal/slot implementation
URL: http://code.activestate.com/recipes/576477/
Comment: Slightly modified with code from Patrick Chasco
(http://code.activestate.com/recipes/439356/) to support
connecting functions.
"""
from weakref import WeakValueDictionary
import inspect
class Signal(object):
def __init__(self):
self.__slots = WeakValueDictionary()
# For keeping references to _FuncHost objects.
self.__funchosts = {}
def __call__(self, *args, **kargs):
for key in self.__slots:
func, _ = key
func(self.__slots[key], *args, **kargs)
def connect(self, slot):
if inspect.ismethod(slot):
key = (slot.im_func, id(slot.im_self))
self.__slots[key] = slot.im_self
else:
host = _FuncHost(slot)
self.connect(host.meth)
# We stick a copy in here just to keep the instance alive.
self.__funchosts[slot] = host
def disconnect(self, slot):
if inspect.ismethod(slot):
key = (slot.im_func, id(slot.im_self))
if key in self.__slots:
self.__slots.pop(key)
else:
if slot in self.__funchosts:
self.disconnect(self.__funchosts[slot].meth)
self.__funchosts.pop(slot)
def clear(self):
self.__slots.clear()
class _FuncHost(object):
"""Turn a function into a method."""
def __init__(self, func):
self.func = func
def meth(self, *args, **kwargs):
self.func(*args, **kwargs)
if __name__ == '__main__':
a = 0
def test_func():
def foo():
global a
a = a + 1
s = Signal()
s()
s.connect(foo)
s()
s.disconnect(foo)
s()
assert a == 1
test_func()
|
<commit_before>"""
Author: Thiago Marcos P. Santos
Created: August 28, 2008
Purpose: A signal/slot implementation
"""
from weakref import WeakValueDictionary
class Signal(object):
def __init__(self):
self.__slots = WeakValueDictionary()
def __call__(self, *args, **kargs):
for key in self.__slots:
func, _ = key
func(self.__slots[key], *args, **kargs)
def connect(self, slot):
key = (slot.im_func, id(slot.im_self))
self.__slots[key] = slot.im_self
def disconnect(self, slot):
key = (slot.im_func, id(slot.im_self))
if key in self.__slots:
self.__slots.pop(key)
def clear(self):
self.__slots.clear()
<commit_msg>Add support for connecting functions to Signal objects.
Less elegant than the original recipe, but more functional.<commit_after>
|
"""
Author: Thiago Marcos P. Santos
Created: August 28, 2008
Purpose: A signal/slot implementation
URL: http://code.activestate.com/recipes/576477/
Comment: Slightly modified with code from Patrick Chasco
(http://code.activestate.com/recipes/439356/) to support
connecting functions.
"""
from weakref import WeakValueDictionary
import inspect
class Signal(object):
def __init__(self):
self.__slots = WeakValueDictionary()
# For keeping references to _FuncHost objects.
self.__funchosts = {}
def __call__(self, *args, **kargs):
for key in self.__slots:
func, _ = key
func(self.__slots[key], *args, **kargs)
def connect(self, slot):
if inspect.ismethod(slot):
key = (slot.im_func, id(slot.im_self))
self.__slots[key] = slot.im_self
else:
host = _FuncHost(slot)
self.connect(host.meth)
# We stick a copy in here just to keep the instance alive.
self.__funchosts[slot] = host
def disconnect(self, slot):
if inspect.ismethod(slot):
key = (slot.im_func, id(slot.im_self))
if key in self.__slots:
self.__slots.pop(key)
else:
if slot in self.__funchosts:
self.disconnect(self.__funchosts[slot].meth)
self.__funchosts.pop(slot)
def clear(self):
self.__slots.clear()
class _FuncHost(object):
"""Turn a function into a method."""
def __init__(self, func):
self.func = func
def meth(self, *args, **kwargs):
self.func(*args, **kwargs)
if __name__ == '__main__':
a = 0
def test_func():
def foo():
global a
a = a + 1
s = Signal()
s()
s.connect(foo)
s()
s.disconnect(foo)
s()
assert a == 1
test_func()
|
"""
Author: Thiago Marcos P. Santos
Created: August 28, 2008
Purpose: A signal/slot implementation
"""
from weakref import WeakValueDictionary
class Signal(object):
def __init__(self):
self.__slots = WeakValueDictionary()
def __call__(self, *args, **kargs):
for key in self.__slots:
func, _ = key
func(self.__slots[key], *args, **kargs)
def connect(self, slot):
key = (slot.im_func, id(slot.im_self))
self.__slots[key] = slot.im_self
def disconnect(self, slot):
key = (slot.im_func, id(slot.im_self))
if key in self.__slots:
self.__slots.pop(key)
def clear(self):
self.__slots.clear()
Add support for connecting functions to Signal objects.
Less elegant than the original recipe, but more functional."""
Author: Thiago Marcos P. Santos
Created: August 28, 2008
Purpose: A signal/slot implementation
URL: http://code.activestate.com/recipes/576477/
Comment: Slightly modified with code from Patrick Chasco
(http://code.activestate.com/recipes/439356/) to support
connecting functions.
"""
from weakref import WeakValueDictionary
import inspect
class Signal(object):
def __init__(self):
self.__slots = WeakValueDictionary()
# For keeping references to _FuncHost objects.
self.__funchosts = {}
def __call__(self, *args, **kargs):
for key in self.__slots:
func, _ = key
func(self.__slots[key], *args, **kargs)
def connect(self, slot):
if inspect.ismethod(slot):
key = (slot.im_func, id(slot.im_self))
self.__slots[key] = slot.im_self
else:
host = _FuncHost(slot)
self.connect(host.meth)
# We stick a copy in here just to keep the instance alive.
self.__funchosts[slot] = host
def disconnect(self, slot):
if inspect.ismethod(slot):
key = (slot.im_func, id(slot.im_self))
if key in self.__slots:
self.__slots.pop(key)
else:
if slot in self.__funchosts:
self.disconnect(self.__funchosts[slot].meth)
self.__funchosts.pop(slot)
def clear(self):
self.__slots.clear()
class _FuncHost(object):
"""Turn a function into a method."""
def __init__(self, func):
self.func = func
def meth(self, *args, **kwargs):
self.func(*args, **kwargs)
if __name__ == '__main__':
a = 0
def test_func():
def foo():
global a
a = a + 1
s = Signal()
s()
s.connect(foo)
s()
s.disconnect(foo)
s()
assert a == 1
test_func()
|
<commit_before>"""
Author: Thiago Marcos P. Santos
Created: August 28, 2008
Purpose: A signal/slot implementation
"""
from weakref import WeakValueDictionary
class Signal(object):
def __init__(self):
self.__slots = WeakValueDictionary()
def __call__(self, *args, **kargs):
for key in self.__slots:
func, _ = key
func(self.__slots[key], *args, **kargs)
def connect(self, slot):
key = (slot.im_func, id(slot.im_self))
self.__slots[key] = slot.im_self
def disconnect(self, slot):
key = (slot.im_func, id(slot.im_self))
if key in self.__slots:
self.__slots.pop(key)
def clear(self):
self.__slots.clear()
<commit_msg>Add support for connecting functions to Signal objects.
Less elegant than the original recipe, but more functional.<commit_after>"""
Author: Thiago Marcos P. Santos
Created: August 28, 2008
Purpose: A signal/slot implementation
URL: http://code.activestate.com/recipes/576477/
Comment: Slightly modified with code from Patrick Chasco
(http://code.activestate.com/recipes/439356/) to support
connecting functions.
"""
from weakref import WeakValueDictionary
import inspect
class Signal(object):
def __init__(self):
self.__slots = WeakValueDictionary()
# For keeping references to _FuncHost objects.
self.__funchosts = {}
def __call__(self, *args, **kargs):
for key in self.__slots:
func, _ = key
func(self.__slots[key], *args, **kargs)
def connect(self, slot):
if inspect.ismethod(slot):
key = (slot.im_func, id(slot.im_self))
self.__slots[key] = slot.im_self
else:
host = _FuncHost(slot)
self.connect(host.meth)
# We stick a copy in here just to keep the instance alive.
self.__funchosts[slot] = host
def disconnect(self, slot):
if inspect.ismethod(slot):
key = (slot.im_func, id(slot.im_self))
if key in self.__slots:
self.__slots.pop(key)
else:
if slot in self.__funchosts:
self.disconnect(self.__funchosts[slot].meth)
self.__funchosts.pop(slot)
def clear(self):
self.__slots.clear()
class _FuncHost(object):
"""Turn a function into a method."""
def __init__(self, func):
self.func = func
def meth(self, *args, **kwargs):
self.func(*args, **kwargs)
if __name__ == '__main__':
a = 0
def test_func():
def foo():
global a
a = a + 1
s = Signal()
s()
s.connect(foo)
s()
s.disconnect(foo)
s()
assert a == 1
test_func()
|
84a6aa05079940173e079e5c2f513b5bd8f8bcb7
|
api/locations/models.py
|
api/locations/models.py
|
# -*- coding: utf-8 -*-
# Copyright 2016 Steven Oud. All rights reserved.
# Use of this source code is governed by a MIT-style license that can be found
# in the LICENSE file.
from datetime import datetime
from api.models import JSONSerializer
from api import db
from api.visits.models import Visit
class Location(db.Model, JSONSerializer):
__tablename__ = 'locations'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String, nullable=False, unique=True)
occupied = db.Column(db.Boolean, nullable=False, default=False)
changed_at = db.Column(db.DateTime, default=None, onupdate=datetime.now())
average_duration = db.Column(db.Integer, default=0)
token = db.relationship('Token', backref='locations', uselist=False)
def __init__(self, name):
self.name = name
def __repr__(self):
return '<Location {}>'.format(self.name)
def calculate_average(self):
visits = Visit.query.with_entities(Visit.duration).all()
# Flatten list
visits = list(sum(visits, ()))
self.average_duration = sum(visits) / len(visits)
|
# -*- coding: utf-8 -*-
# Copyright 2016 Steven Oud. All rights reserved.
# Use of this source code is governed by a MIT-style license that can be found
# in the LICENSE file.
from datetime import datetime
from api.models import JSONSerializer
from api import db
from api.visits.models import Visit
class Location(db.Model, JSONSerializer):
__tablename__ = 'locations'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String, nullable=False, unique=True)
occupied = db.Column(db.Boolean, nullable=False, default=False)
changed_at = db.Column(db.DateTime, default=None, onupdate=datetime.now)
average_duration = db.Column(db.Integer, default=0)
token = db.relationship('Token', backref='locations', uselist=False)
def __init__(self, name):
self.name = name
def __repr__(self):
return '<Location {}>'.format(self.name)
def calculate_average(self):
visits = Visit.query.with_entities(Visit.duration).all()
# Flatten list
visits = list(sum(visits, ()))
self.average_duration = sum(visits) / len(visits)
|
Fix onupdate not using current time
|
Fix onupdate not using current time
|
Python
|
mit
|
Proj-P/project-p-api,Proj-P/project-p-api
|
# -*- coding: utf-8 -*-
# Copyright 2016 Steven Oud. All rights reserved.
# Use of this source code is governed by a MIT-style license that can be found
# in the LICENSE file.
from datetime import datetime
from api.models import JSONSerializer
from api import db
from api.visits.models import Visit
class Location(db.Model, JSONSerializer):
__tablename__ = 'locations'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String, nullable=False, unique=True)
occupied = db.Column(db.Boolean, nullable=False, default=False)
changed_at = db.Column(db.DateTime, default=None, onupdate=datetime.now())
average_duration = db.Column(db.Integer, default=0)
token = db.relationship('Token', backref='locations', uselist=False)
def __init__(self, name):
self.name = name
def __repr__(self):
return '<Location {}>'.format(self.name)
def calculate_average(self):
visits = Visit.query.with_entities(Visit.duration).all()
# Flatten list
visits = list(sum(visits, ()))
self.average_duration = sum(visits) / len(visits)
Fix onupdate not using current time
|
# -*- coding: utf-8 -*-
# Copyright 2016 Steven Oud. All rights reserved.
# Use of this source code is governed by a MIT-style license that can be found
# in the LICENSE file.
from datetime import datetime
from api.models import JSONSerializer
from api import db
from api.visits.models import Visit
class Location(db.Model, JSONSerializer):
__tablename__ = 'locations'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String, nullable=False, unique=True)
occupied = db.Column(db.Boolean, nullable=False, default=False)
changed_at = db.Column(db.DateTime, default=None, onupdate=datetime.now)
average_duration = db.Column(db.Integer, default=0)
token = db.relationship('Token', backref='locations', uselist=False)
def __init__(self, name):
self.name = name
def __repr__(self):
return '<Location {}>'.format(self.name)
def calculate_average(self):
visits = Visit.query.with_entities(Visit.duration).all()
# Flatten list
visits = list(sum(visits, ()))
self.average_duration = sum(visits) / len(visits)
|
<commit_before># -*- coding: utf-8 -*-
# Copyright 2016 Steven Oud. All rights reserved.
# Use of this source code is governed by a MIT-style license that can be found
# in the LICENSE file.
from datetime import datetime
from api.models import JSONSerializer
from api import db
from api.visits.models import Visit
class Location(db.Model, JSONSerializer):
__tablename__ = 'locations'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String, nullable=False, unique=True)
occupied = db.Column(db.Boolean, nullable=False, default=False)
changed_at = db.Column(db.DateTime, default=None, onupdate=datetime.now())
average_duration = db.Column(db.Integer, default=0)
token = db.relationship('Token', backref='locations', uselist=False)
def __init__(self, name):
self.name = name
def __repr__(self):
return '<Location {}>'.format(self.name)
def calculate_average(self):
visits = Visit.query.with_entities(Visit.duration).all()
# Flatten list
visits = list(sum(visits, ()))
self.average_duration = sum(visits) / len(visits)
<commit_msg>Fix onupdate not using current time<commit_after>
|
# -*- coding: utf-8 -*-
# Copyright 2016 Steven Oud. All rights reserved.
# Use of this source code is governed by a MIT-style license that can be found
# in the LICENSE file.
from datetime import datetime
from api.models import JSONSerializer
from api import db
from api.visits.models import Visit
class Location(db.Model, JSONSerializer):
__tablename__ = 'locations'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String, nullable=False, unique=True)
occupied = db.Column(db.Boolean, nullable=False, default=False)
changed_at = db.Column(db.DateTime, default=None, onupdate=datetime.now)
average_duration = db.Column(db.Integer, default=0)
token = db.relationship('Token', backref='locations', uselist=False)
def __init__(self, name):
self.name = name
def __repr__(self):
return '<Location {}>'.format(self.name)
def calculate_average(self):
visits = Visit.query.with_entities(Visit.duration).all()
# Flatten list
visits = list(sum(visits, ()))
self.average_duration = sum(visits) / len(visits)
|
# -*- coding: utf-8 -*-
# Copyright 2016 Steven Oud. All rights reserved.
# Use of this source code is governed by a MIT-style license that can be found
# in the LICENSE file.
from datetime import datetime
from api.models import JSONSerializer
from api import db
from api.visits.models import Visit
class Location(db.Model, JSONSerializer):
__tablename__ = 'locations'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String, nullable=False, unique=True)
occupied = db.Column(db.Boolean, nullable=False, default=False)
changed_at = db.Column(db.DateTime, default=None, onupdate=datetime.now())
average_duration = db.Column(db.Integer, default=0)
token = db.relationship('Token', backref='locations', uselist=False)
def __init__(self, name):
self.name = name
def __repr__(self):
return '<Location {}>'.format(self.name)
def calculate_average(self):
visits = Visit.query.with_entities(Visit.duration).all()
# Flatten list
visits = list(sum(visits, ()))
self.average_duration = sum(visits) / len(visits)
Fix onupdate not using current time# -*- coding: utf-8 -*-
# Copyright 2016 Steven Oud. All rights reserved.
# Use of this source code is governed by a MIT-style license that can be found
# in the LICENSE file.
from datetime import datetime
from api.models import JSONSerializer
from api import db
from api.visits.models import Visit
class Location(db.Model, JSONSerializer):
__tablename__ = 'locations'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String, nullable=False, unique=True)
occupied = db.Column(db.Boolean, nullable=False, default=False)
changed_at = db.Column(db.DateTime, default=None, onupdate=datetime.now)
average_duration = db.Column(db.Integer, default=0)
token = db.relationship('Token', backref='locations', uselist=False)
def __init__(self, name):
self.name = name
def __repr__(self):
return '<Location {}>'.format(self.name)
def calculate_average(self):
visits = Visit.query.with_entities(Visit.duration).all()
# Flatten list
visits = list(sum(visits, ()))
self.average_duration = sum(visits) / len(visits)
|
<commit_before># -*- coding: utf-8 -*-
# Copyright 2016 Steven Oud. All rights reserved.
# Use of this source code is governed by a MIT-style license that can be found
# in the LICENSE file.
from datetime import datetime
from api.models import JSONSerializer
from api import db
from api.visits.models import Visit
class Location(db.Model, JSONSerializer):
__tablename__ = 'locations'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String, nullable=False, unique=True)
occupied = db.Column(db.Boolean, nullable=False, default=False)
changed_at = db.Column(db.DateTime, default=None, onupdate=datetime.now())
average_duration = db.Column(db.Integer, default=0)
token = db.relationship('Token', backref='locations', uselist=False)
def __init__(self, name):
self.name = name
def __repr__(self):
return '<Location {}>'.format(self.name)
def calculate_average(self):
visits = Visit.query.with_entities(Visit.duration).all()
# Flatten list
visits = list(sum(visits, ()))
self.average_duration = sum(visits) / len(visits)
<commit_msg>Fix onupdate not using current time<commit_after># -*- coding: utf-8 -*-
# Copyright 2016 Steven Oud. All rights reserved.
# Use of this source code is governed by a MIT-style license that can be found
# in the LICENSE file.
from datetime import datetime
from api.models import JSONSerializer
from api import db
from api.visits.models import Visit
class Location(db.Model, JSONSerializer):
__tablename__ = 'locations'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String, nullable=False, unique=True)
occupied = db.Column(db.Boolean, nullable=False, default=False)
changed_at = db.Column(db.DateTime, default=None, onupdate=datetime.now)
average_duration = db.Column(db.Integer, default=0)
token = db.relationship('Token', backref='locations', uselist=False)
def __init__(self, name):
self.name = name
def __repr__(self):
return '<Location {}>'.format(self.name)
def calculate_average(self):
visits = Visit.query.with_entities(Visit.duration).all()
# Flatten list
visits = list(sum(visits, ()))
self.average_duration = sum(visits) / len(visits)
|
fec482c6b1655d7108386760a3e0297850da6e7b
|
editorsnotes/api/validators.py
|
editorsnotes/api/validators.py
|
from rest_framework.serializers import ValidationError
class UniqueToProjectValidator:
message = u'{model_name} with this {field_name} already exists.'
def __init__(self, field, message=None):
self.field_name = field
self.message = message or self.message
def set_context(self, serializer):
self.ModelClass = serializer.Meta.model
self.instance = getattr(serializer, 'instance', None)
def __call__(self, attrs):
# Assuming that the field is always required
if self.instance is not None:
value = attrs.get(self.field_name,
getattr(self.instance, self.field_name))
else:
value = attrs[self.field_name]
kwargs = {'project': attrs['project'], self.field_name: value}
qs = self.ModelClass.objects.filter(**kwargs)
if self.instance is not None:
qs = qs.exclude(id=self.instance.id)
if qs.exists():
opts = self.ModelClass._meta
raise ValidationError({
self.field_name: self.message.format(
model_name=opts.verbose_name.title(),
field_name=opts.get_field(self.field_name).verbose_name
)
})
|
from rest_framework.serializers import ValidationError
class UniqueToProjectValidator:
message = u'{model_name} with this {field_name} already exists.'
def __init__(self, field, message=None):
self.field_name = field
self.message = message or self.message
def set_context(self, serializer):
self.ModelClass = serializer.Meta.model
self.instance = getattr(serializer, 'instance', None)
self.project = serializer.context['request'].project
def __call__(self, attrs):
# Assuming that the field is always required
if self.instance is not None:
value = attrs.get(self.field_name,
getattr(self.instance, self.field_name))
else:
value = attrs[self.field_name]
kwargs = {'project': self.project, self.field_name: value}
qs = self.ModelClass.objects.filter(**kwargs)
if self.instance is not None:
qs = qs.exclude(id=self.instance.id)
if qs.exists():
opts = self.ModelClass._meta
raise ValidationError({
self.field_name: self.message.format(
model_name=opts.verbose_name.title(),
field_name=opts.get_field(self.field_name).verbose_name
)
})
|
Make sure a project is set for the project-specific validator
|
Make sure a project is set for the project-specific validator
|
Python
|
agpl-3.0
|
editorsnotes/editorsnotes,editorsnotes/editorsnotes
|
from rest_framework.serializers import ValidationError
class UniqueToProjectValidator:
message = u'{model_name} with this {field_name} already exists.'
def __init__(self, field, message=None):
self.field_name = field
self.message = message or self.message
def set_context(self, serializer):
self.ModelClass = serializer.Meta.model
self.instance = getattr(serializer, 'instance', None)
def __call__(self, attrs):
# Assuming that the field is always required
if self.instance is not None:
value = attrs.get(self.field_name,
getattr(self.instance, self.field_name))
else:
value = attrs[self.field_name]
kwargs = {'project': attrs['project'], self.field_name: value}
qs = self.ModelClass.objects.filter(**kwargs)
if self.instance is not None:
qs = qs.exclude(id=self.instance.id)
if qs.exists():
opts = self.ModelClass._meta
raise ValidationError({
self.field_name: self.message.format(
model_name=opts.verbose_name.title(),
field_name=opts.get_field(self.field_name).verbose_name
)
})
Make sure a project is set for the project-specific validator
|
from rest_framework.serializers import ValidationError
class UniqueToProjectValidator:
message = u'{model_name} with this {field_name} already exists.'
def __init__(self, field, message=None):
self.field_name = field
self.message = message or self.message
def set_context(self, serializer):
self.ModelClass = serializer.Meta.model
self.instance = getattr(serializer, 'instance', None)
self.project = serializer.context['request'].project
def __call__(self, attrs):
# Assuming that the field is always required
if self.instance is not None:
value = attrs.get(self.field_name,
getattr(self.instance, self.field_name))
else:
value = attrs[self.field_name]
kwargs = {'project': self.project, self.field_name: value}
qs = self.ModelClass.objects.filter(**kwargs)
if self.instance is not None:
qs = qs.exclude(id=self.instance.id)
if qs.exists():
opts = self.ModelClass._meta
raise ValidationError({
self.field_name: self.message.format(
model_name=opts.verbose_name.title(),
field_name=opts.get_field(self.field_name).verbose_name
)
})
|
<commit_before>from rest_framework.serializers import ValidationError
class UniqueToProjectValidator:
message = u'{model_name} with this {field_name} already exists.'
def __init__(self, field, message=None):
self.field_name = field
self.message = message or self.message
def set_context(self, serializer):
self.ModelClass = serializer.Meta.model
self.instance = getattr(serializer, 'instance', None)
def __call__(self, attrs):
# Assuming that the field is always required
if self.instance is not None:
value = attrs.get(self.field_name,
getattr(self.instance, self.field_name))
else:
value = attrs[self.field_name]
kwargs = {'project': attrs['project'], self.field_name: value}
qs = self.ModelClass.objects.filter(**kwargs)
if self.instance is not None:
qs = qs.exclude(id=self.instance.id)
if qs.exists():
opts = self.ModelClass._meta
raise ValidationError({
self.field_name: self.message.format(
model_name=opts.verbose_name.title(),
field_name=opts.get_field(self.field_name).verbose_name
)
})
<commit_msg>Make sure a project is set for the project-specific validator<commit_after>
|
from rest_framework.serializers import ValidationError
class UniqueToProjectValidator:
message = u'{model_name} with this {field_name} already exists.'
def __init__(self, field, message=None):
self.field_name = field
self.message = message or self.message
def set_context(self, serializer):
self.ModelClass = serializer.Meta.model
self.instance = getattr(serializer, 'instance', None)
self.project = serializer.context['request'].project
def __call__(self, attrs):
# Assuming that the field is always required
if self.instance is not None:
value = attrs.get(self.field_name,
getattr(self.instance, self.field_name))
else:
value = attrs[self.field_name]
kwargs = {'project': self.project, self.field_name: value}
qs = self.ModelClass.objects.filter(**kwargs)
if self.instance is not None:
qs = qs.exclude(id=self.instance.id)
if qs.exists():
opts = self.ModelClass._meta
raise ValidationError({
self.field_name: self.message.format(
model_name=opts.verbose_name.title(),
field_name=opts.get_field(self.field_name).verbose_name
)
})
|
from rest_framework.serializers import ValidationError
class UniqueToProjectValidator:
message = u'{model_name} with this {field_name} already exists.'
def __init__(self, field, message=None):
self.field_name = field
self.message = message or self.message
def set_context(self, serializer):
self.ModelClass = serializer.Meta.model
self.instance = getattr(serializer, 'instance', None)
def __call__(self, attrs):
# Assuming that the field is always required
if self.instance is not None:
value = attrs.get(self.field_name,
getattr(self.instance, self.field_name))
else:
value = attrs[self.field_name]
kwargs = {'project': attrs['project'], self.field_name: value}
qs = self.ModelClass.objects.filter(**kwargs)
if self.instance is not None:
qs = qs.exclude(id=self.instance.id)
if qs.exists():
opts = self.ModelClass._meta
raise ValidationError({
self.field_name: self.message.format(
model_name=opts.verbose_name.title(),
field_name=opts.get_field(self.field_name).verbose_name
)
})
Make sure a project is set for the project-specific validatorfrom rest_framework.serializers import ValidationError
class UniqueToProjectValidator:
message = u'{model_name} with this {field_name} already exists.'
def __init__(self, field, message=None):
self.field_name = field
self.message = message or self.message
def set_context(self, serializer):
self.ModelClass = serializer.Meta.model
self.instance = getattr(serializer, 'instance', None)
self.project = serializer.context['request'].project
def __call__(self, attrs):
# Assuming that the field is always required
if self.instance is not None:
value = attrs.get(self.field_name,
getattr(self.instance, self.field_name))
else:
value = attrs[self.field_name]
kwargs = {'project': self.project, self.field_name: value}
qs = self.ModelClass.objects.filter(**kwargs)
if self.instance is not None:
qs = qs.exclude(id=self.instance.id)
if qs.exists():
opts = self.ModelClass._meta
raise ValidationError({
self.field_name: self.message.format(
model_name=opts.verbose_name.title(),
field_name=opts.get_field(self.field_name).verbose_name
)
})
|
<commit_before>from rest_framework.serializers import ValidationError
class UniqueToProjectValidator:
message = u'{model_name} with this {field_name} already exists.'
def __init__(self, field, message=None):
self.field_name = field
self.message = message or self.message
def set_context(self, serializer):
self.ModelClass = serializer.Meta.model
self.instance = getattr(serializer, 'instance', None)
def __call__(self, attrs):
# Assuming that the field is always required
if self.instance is not None:
value = attrs.get(self.field_name,
getattr(self.instance, self.field_name))
else:
value = attrs[self.field_name]
kwargs = {'project': attrs['project'], self.field_name: value}
qs = self.ModelClass.objects.filter(**kwargs)
if self.instance is not None:
qs = qs.exclude(id=self.instance.id)
if qs.exists():
opts = self.ModelClass._meta
raise ValidationError({
self.field_name: self.message.format(
model_name=opts.verbose_name.title(),
field_name=opts.get_field(self.field_name).verbose_name
)
})
<commit_msg>Make sure a project is set for the project-specific validator<commit_after>from rest_framework.serializers import ValidationError
class UniqueToProjectValidator:
message = u'{model_name} with this {field_name} already exists.'
def __init__(self, field, message=None):
self.field_name = field
self.message = message or self.message
def set_context(self, serializer):
self.ModelClass = serializer.Meta.model
self.instance = getattr(serializer, 'instance', None)
self.project = serializer.context['request'].project
def __call__(self, attrs):
# Assuming that the field is always required
if self.instance is not None:
value = attrs.get(self.field_name,
getattr(self.instance, self.field_name))
else:
value = attrs[self.field_name]
kwargs = {'project': self.project, self.field_name: value}
qs = self.ModelClass.objects.filter(**kwargs)
if self.instance is not None:
qs = qs.exclude(id=self.instance.id)
if qs.exists():
opts = self.ModelClass._meta
raise ValidationError({
self.field_name: self.message.format(
model_name=opts.verbose_name.title(),
field_name=opts.get_field(self.field_name).verbose_name
)
})
|
57f131218ac7362fdf85389b73dcafb9d35897f4
|
TriangleSimilarityDistanceCalculator.py
|
TriangleSimilarityDistanceCalculator.py
|
# Calculate the distance to an object of known size.
# We need to know the perceived focal length for this to work.
#
# Known Focal Length values for calibrated cameras
# Logitech C920: H620 V?
# Microsoft Lifecam HD-3000: H652 V?
#
class TriangleSimilarityDistanceCalculator:
knownSize = 0
focalLength = 0;
def __init__(self, knownSize, perceivedFocalLength = None):
self.knownSize = knownSize
self.focalLength = perceivedFocalLength
# Call this to calibrate a camera and then use the calibrated focalLength value
# when using this class to calculate real distances.
def CalculatePerceivedFOVAtGivenDistance(self, perceivedSize, distance):
focalLength = perceivedSize * distance / float(self.knownSize)
return focalLength
# This will return the real world distance of the known object.
def CalcualteDistance(self, perceivedSize):
if self.focalLength == None:
raise ValueError("Did you forget to calibrate this camera and set the perceived focal length?")
distance = self.knownSize * self.focalLength / float(perceivedSize)
return distance
|
# Calculate the distance to an object of known size.
# We need to know the perceived focal length for this to work.
#
# Known Focal Length values for calibrated cameras
# Logitech C920: H622 V625
# Microsoft Lifecam HD-3000: H652 V?
#
PFL_H_C920 = 622
PFL_V_C920 = 625
PFL_H_LC3000 = 652
PFL_V_LC3000 = 652
class TriangleSimilarityDistanceCalculator:
knownSize = 0
focalLength = 0;
def __init__(self, knownSize, perceivedFocalLength = None):
self.knownSize = knownSize
self.focalLength = perceivedFocalLength
# Call this to calibrate a camera and then use the calibrated focalLength value
# when using this class to calculate real distances.
def CalculatePerceivedFocalLengthAtGivenDistance(self, perceivedSize, knownDistance):
focalLength = perceivedSize * knownDistance / float(self.knownSize)
return focalLength
# This will return the real world distance of the known object.
def CalcualteDistance(self, perceivedSize):
if self.focalLength == None:
raise ValueError("Did you forget to calibrate this camera and set the perceived focal length?")
distance = self.knownSize * self.focalLength / float(perceivedSize)
return distance
|
Update measured Focal Lengths for C920.
|
Update measured Focal Lengths for C920.
|
Python
|
mit
|
AluminatiFRC/Vision2016,AluminatiFRC/Vision2016
|
# Calculate the distance to an object of known size.
# We need to know the perceived focal length for this to work.
#
# Known Focal Length values for calibrated cameras
# Logitech C920: H620 V?
# Microsoft Lifecam HD-3000: H652 V?
#
class TriangleSimilarityDistanceCalculator:
knownSize = 0
focalLength = 0;
def __init__(self, knownSize, perceivedFocalLength = None):
self.knownSize = knownSize
self.focalLength = perceivedFocalLength
# Call this to calibrate a camera and then use the calibrated focalLength value
# when using this class to calculate real distances.
def CalculatePerceivedFOVAtGivenDistance(self, perceivedSize, distance):
focalLength = perceivedSize * distance / float(self.knownSize)
return focalLength
# This will return the real world distance of the known object.
def CalcualteDistance(self, perceivedSize):
if self.focalLength == None:
raise ValueError("Did you forget to calibrate this camera and set the perceived focal length?")
distance = self.knownSize * self.focalLength / float(perceivedSize)
return distance
Update measured Focal Lengths for C920.
|
# Calculate the distance to an object of known size.
# We need to know the perceived focal length for this to work.
#
# Known Focal Length values for calibrated cameras
# Logitech C920: H622 V625
# Microsoft Lifecam HD-3000: H652 V?
#
PFL_H_C920 = 622
PFL_V_C920 = 625
PFL_H_LC3000 = 652
PFL_V_LC3000 = 652
class TriangleSimilarityDistanceCalculator:
knownSize = 0
focalLength = 0;
def __init__(self, knownSize, perceivedFocalLength = None):
self.knownSize = knownSize
self.focalLength = perceivedFocalLength
# Call this to calibrate a camera and then use the calibrated focalLength value
# when using this class to calculate real distances.
def CalculatePerceivedFocalLengthAtGivenDistance(self, perceivedSize, knownDistance):
focalLength = perceivedSize * knownDistance / float(self.knownSize)
return focalLength
# This will return the real world distance of the known object.
def CalcualteDistance(self, perceivedSize):
if self.focalLength == None:
raise ValueError("Did you forget to calibrate this camera and set the perceived focal length?")
distance = self.knownSize * self.focalLength / float(perceivedSize)
return distance
|
<commit_before># Calculate the distance to an object of known size.
# We need to know the perceived focal length for this to work.
#
# Known Focal Length values for calibrated cameras
# Logitech C920: H620 V?
# Microsoft Lifecam HD-3000: H652 V?
#
class TriangleSimilarityDistanceCalculator:
knownSize = 0
focalLength = 0;
def __init__(self, knownSize, perceivedFocalLength = None):
self.knownSize = knownSize
self.focalLength = perceivedFocalLength
# Call this to calibrate a camera and then use the calibrated focalLength value
# when using this class to calculate real distances.
def CalculatePerceivedFOVAtGivenDistance(self, perceivedSize, distance):
focalLength = perceivedSize * distance / float(self.knownSize)
return focalLength
# This will return the real world distance of the known object.
def CalcualteDistance(self, perceivedSize):
if self.focalLength == None:
raise ValueError("Did you forget to calibrate this camera and set the perceived focal length?")
distance = self.knownSize * self.focalLength / float(perceivedSize)
return distance
<commit_msg>Update measured Focal Lengths for C920.<commit_after>
|
# Calculate the distance to an object of known size.
# We need to know the perceived focal length for this to work.
#
# Known Focal Length values for calibrated cameras
# Logitech C920: H622 V625
# Microsoft Lifecam HD-3000: H652 V?
#
PFL_H_C920 = 622
PFL_V_C920 = 625
PFL_H_LC3000 = 652
PFL_V_LC3000 = 652
class TriangleSimilarityDistanceCalculator:
knownSize = 0
focalLength = 0;
def __init__(self, knownSize, perceivedFocalLength = None):
self.knownSize = knownSize
self.focalLength = perceivedFocalLength
# Call this to calibrate a camera and then use the calibrated focalLength value
# when using this class to calculate real distances.
def CalculatePerceivedFocalLengthAtGivenDistance(self, perceivedSize, knownDistance):
focalLength = perceivedSize * knownDistance / float(self.knownSize)
return focalLength
# This will return the real world distance of the known object.
def CalcualteDistance(self, perceivedSize):
if self.focalLength == None:
raise ValueError("Did you forget to calibrate this camera and set the perceived focal length?")
distance = self.knownSize * self.focalLength / float(perceivedSize)
return distance
|
# Calculate the distance to an object of known size.
# We need to know the perceived focal length for this to work.
#
# Known Focal Length values for calibrated cameras
# Logitech C920: H620 V?
# Microsoft Lifecam HD-3000: H652 V?
#
class TriangleSimilarityDistanceCalculator:
knownSize = 0
focalLength = 0;
def __init__(self, knownSize, perceivedFocalLength = None):
self.knownSize = knownSize
self.focalLength = perceivedFocalLength
# Call this to calibrate a camera and then use the calibrated focalLength value
# when using this class to calculate real distances.
def CalculatePerceivedFOVAtGivenDistance(self, perceivedSize, distance):
focalLength = perceivedSize * distance / float(self.knownSize)
return focalLength
# This will return the real world distance of the known object.
def CalcualteDistance(self, perceivedSize):
if self.focalLength == None:
raise ValueError("Did you forget to calibrate this camera and set the perceived focal length?")
distance = self.knownSize * self.focalLength / float(perceivedSize)
return distance
Update measured Focal Lengths for C920.# Calculate the distance to an object of known size.
# We need to know the perceived focal length for this to work.
#
# Known Focal Length values for calibrated cameras
# Logitech C920: H622 V625
# Microsoft Lifecam HD-3000: H652 V?
#
PFL_H_C920 = 622
PFL_V_C920 = 625
PFL_H_LC3000 = 652
PFL_V_LC3000 = 652
class TriangleSimilarityDistanceCalculator:
knownSize = 0
focalLength = 0;
def __init__(self, knownSize, perceivedFocalLength = None):
self.knownSize = knownSize
self.focalLength = perceivedFocalLength
# Call this to calibrate a camera and then use the calibrated focalLength value
# when using this class to calculate real distances.
def CalculatePerceivedFocalLengthAtGivenDistance(self, perceivedSize, knownDistance):
focalLength = perceivedSize * knownDistance / float(self.knownSize)
return focalLength
# This will return the real world distance of the known object.
def CalcualteDistance(self, perceivedSize):
if self.focalLength == None:
raise ValueError("Did you forget to calibrate this camera and set the perceived focal length?")
distance = self.knownSize * self.focalLength / float(perceivedSize)
return distance
|
<commit_before># Calculate the distance to an object of known size.
# We need to know the perceived focal length for this to work.
#
# Known Focal Length values for calibrated cameras
# Logitech C920: H620 V?
# Microsoft Lifecam HD-3000: H652 V?
#
class TriangleSimilarityDistanceCalculator:
knownSize = 0
focalLength = 0;
def __init__(self, knownSize, perceivedFocalLength = None):
self.knownSize = knownSize
self.focalLength = perceivedFocalLength
# Call this to calibrate a camera and then use the calibrated focalLength value
# when using this class to calculate real distances.
def CalculatePerceivedFOVAtGivenDistance(self, perceivedSize, distance):
focalLength = perceivedSize * distance / float(self.knownSize)
return focalLength
# This will return the real world distance of the known object.
def CalcualteDistance(self, perceivedSize):
if self.focalLength == None:
raise ValueError("Did you forget to calibrate this camera and set the perceived focal length?")
distance = self.knownSize * self.focalLength / float(perceivedSize)
return distance
<commit_msg>Update measured Focal Lengths for C920.<commit_after># Calculate the distance to an object of known size.
# We need to know the perceived focal length for this to work.
#
# Known Focal Length values for calibrated cameras
# Logitech C920: H622 V625
# Microsoft Lifecam HD-3000: H652 V?
#
PFL_H_C920 = 622
PFL_V_C920 = 625
PFL_H_LC3000 = 652
PFL_V_LC3000 = 652
class TriangleSimilarityDistanceCalculator:
knownSize = 0
focalLength = 0;
def __init__(self, knownSize, perceivedFocalLength = None):
self.knownSize = knownSize
self.focalLength = perceivedFocalLength
# Call this to calibrate a camera and then use the calibrated focalLength value
# when using this class to calculate real distances.
def CalculatePerceivedFocalLengthAtGivenDistance(self, perceivedSize, knownDistance):
focalLength = perceivedSize * knownDistance / float(self.knownSize)
return focalLength
# This will return the real world distance of the known object.
def CalcualteDistance(self, perceivedSize):
if self.focalLength == None:
raise ValueError("Did you forget to calibrate this camera and set the perceived focal length?")
distance = self.knownSize * self.focalLength / float(perceivedSize)
return distance
|
70e71fea19abf898c0c6c7dc77f5757a07174093
|
script/yaml-to-plist.py
|
script/yaml-to-plist.py
|
#!/usr/bin/env python3
import sys
import yaml
from os import path
from plistlib import dumps
def generated_comment():
return "This file is auto-generated from %s, do not edit it by hand!" \
% path.basename(in_path)
def convert(yaml):
lines = dumps(yaml).decode('utf-8').splitlines()
lines.insert(3, "<!--\n |\t%s\n-->" % generated_comment())
lines.append('')
return "\n".join(lines)
if len(sys.argv) < 3:
print("Usage: yaml-to-plist <input-file> <output-file>")
sys.exit(1)
in_path = sys.argv[1]
out_path = sys.argv[2]
with open(in_path, 'r', encoding='utf-8') as in_file:
with open(out_path, 'w', encoding='utf-8') as out_file:
out_file.writelines(convert(yaml.load(in_file)))
|
#!/usr/bin/env python3
import sys
import yaml
from os import path
from plistlib import dumps
def generated_comment():
return "This file is auto-generated from %s, do not edit it by hand!" \
% path.basename(in_path)
def convert(yaml):
lines = dumps(yaml).decode('utf-8').splitlines()
lines.insert(3, "<!--\n |\t%s\n-->" % generated_comment())
lines.append('')
return "\n".join(lines)
if len(sys.argv) < 3:
print("Usage: yaml-to-plist <input-file> <output-file>")
sys.exit(1)
in_path = sys.argv[1]
out_path = sys.argv[2]
with open(in_path, 'r', encoding='utf-8') as in_file:
with open(out_path, 'w', encoding='utf-8') as out_file:
out_file.writelines(convert(yaml.safe_load(in_file)))
|
Use safe_load to avoid warning
|
Use safe_load to avoid warning
|
Python
|
mit
|
joaompinto/asciidoctor-vscode,joaompinto/asciidoctor-vscode,joaompinto/asciidoctor-vscode
|
#!/usr/bin/env python3
import sys
import yaml
from os import path
from plistlib import dumps
def generated_comment():
return "This file is auto-generated from %s, do not edit it by hand!" \
% path.basename(in_path)
def convert(yaml):
lines = dumps(yaml).decode('utf-8').splitlines()
lines.insert(3, "<!--\n |\t%s\n-->" % generated_comment())
lines.append('')
return "\n".join(lines)
if len(sys.argv) < 3:
print("Usage: yaml-to-plist <input-file> <output-file>")
sys.exit(1)
in_path = sys.argv[1]
out_path = sys.argv[2]
with open(in_path, 'r', encoding='utf-8') as in_file:
with open(out_path, 'w', encoding='utf-8') as out_file:
out_file.writelines(convert(yaml.load(in_file)))
Use safe_load to avoid warning
|
#!/usr/bin/env python3
import sys
import yaml
from os import path
from plistlib import dumps
def generated_comment():
return "This file is auto-generated from %s, do not edit it by hand!" \
% path.basename(in_path)
def convert(yaml):
lines = dumps(yaml).decode('utf-8').splitlines()
lines.insert(3, "<!--\n |\t%s\n-->" % generated_comment())
lines.append('')
return "\n".join(lines)
if len(sys.argv) < 3:
print("Usage: yaml-to-plist <input-file> <output-file>")
sys.exit(1)
in_path = sys.argv[1]
out_path = sys.argv[2]
with open(in_path, 'r', encoding='utf-8') as in_file:
with open(out_path, 'w', encoding='utf-8') as out_file:
out_file.writelines(convert(yaml.safe_load(in_file)))
|
<commit_before>#!/usr/bin/env python3
import sys
import yaml
from os import path
from plistlib import dumps
def generated_comment():
return "This file is auto-generated from %s, do not edit it by hand!" \
% path.basename(in_path)
def convert(yaml):
lines = dumps(yaml).decode('utf-8').splitlines()
lines.insert(3, "<!--\n |\t%s\n-->" % generated_comment())
lines.append('')
return "\n".join(lines)
if len(sys.argv) < 3:
print("Usage: yaml-to-plist <input-file> <output-file>")
sys.exit(1)
in_path = sys.argv[1]
out_path = sys.argv[2]
with open(in_path, 'r', encoding='utf-8') as in_file:
with open(out_path, 'w', encoding='utf-8') as out_file:
out_file.writelines(convert(yaml.load(in_file)))
<commit_msg>Use safe_load to avoid warning<commit_after>
|
#!/usr/bin/env python3
import sys
import yaml
from os import path
from plistlib import dumps
def generated_comment():
return "This file is auto-generated from %s, do not edit it by hand!" \
% path.basename(in_path)
def convert(yaml):
lines = dumps(yaml).decode('utf-8').splitlines()
lines.insert(3, "<!--\n |\t%s\n-->" % generated_comment())
lines.append('')
return "\n".join(lines)
if len(sys.argv) < 3:
print("Usage: yaml-to-plist <input-file> <output-file>")
sys.exit(1)
in_path = sys.argv[1]
out_path = sys.argv[2]
with open(in_path, 'r', encoding='utf-8') as in_file:
with open(out_path, 'w', encoding='utf-8') as out_file:
out_file.writelines(convert(yaml.safe_load(in_file)))
|
#!/usr/bin/env python3
import sys
import yaml
from os import path
from plistlib import dumps
def generated_comment():
return "This file is auto-generated from %s, do not edit it by hand!" \
% path.basename(in_path)
def convert(yaml):
lines = dumps(yaml).decode('utf-8').splitlines()
lines.insert(3, "<!--\n |\t%s\n-->" % generated_comment())
lines.append('')
return "\n".join(lines)
if len(sys.argv) < 3:
print("Usage: yaml-to-plist <input-file> <output-file>")
sys.exit(1)
in_path = sys.argv[1]
out_path = sys.argv[2]
with open(in_path, 'r', encoding='utf-8') as in_file:
with open(out_path, 'w', encoding='utf-8') as out_file:
out_file.writelines(convert(yaml.load(in_file)))
Use safe_load to avoid warning#!/usr/bin/env python3
import sys
import yaml
from os import path
from plistlib import dumps
def generated_comment():
return "This file is auto-generated from %s, do not edit it by hand!" \
% path.basename(in_path)
def convert(yaml):
lines = dumps(yaml).decode('utf-8').splitlines()
lines.insert(3, "<!--\n |\t%s\n-->" % generated_comment())
lines.append('')
return "\n".join(lines)
if len(sys.argv) < 3:
print("Usage: yaml-to-plist <input-file> <output-file>")
sys.exit(1)
in_path = sys.argv[1]
out_path = sys.argv[2]
with open(in_path, 'r', encoding='utf-8') as in_file:
with open(out_path, 'w', encoding='utf-8') as out_file:
out_file.writelines(convert(yaml.safe_load(in_file)))
|
<commit_before>#!/usr/bin/env python3
import sys
import yaml
from os import path
from plistlib import dumps
def generated_comment():
return "This file is auto-generated from %s, do not edit it by hand!" \
% path.basename(in_path)
def convert(yaml):
lines = dumps(yaml).decode('utf-8').splitlines()
lines.insert(3, "<!--\n |\t%s\n-->" % generated_comment())
lines.append('')
return "\n".join(lines)
if len(sys.argv) < 3:
print("Usage: yaml-to-plist <input-file> <output-file>")
sys.exit(1)
in_path = sys.argv[1]
out_path = sys.argv[2]
with open(in_path, 'r', encoding='utf-8') as in_file:
with open(out_path, 'w', encoding='utf-8') as out_file:
out_file.writelines(convert(yaml.load(in_file)))
<commit_msg>Use safe_load to avoid warning<commit_after>#!/usr/bin/env python3
import sys
import yaml
from os import path
from plistlib import dumps
def generated_comment():
return "This file is auto-generated from %s, do not edit it by hand!" \
% path.basename(in_path)
def convert(yaml):
lines = dumps(yaml).decode('utf-8').splitlines()
lines.insert(3, "<!--\n |\t%s\n-->" % generated_comment())
lines.append('')
return "\n".join(lines)
if len(sys.argv) < 3:
print("Usage: yaml-to-plist <input-file> <output-file>")
sys.exit(1)
in_path = sys.argv[1]
out_path = sys.argv[2]
with open(in_path, 'r', encoding='utf-8') as in_file:
with open(out_path, 'w', encoding='utf-8') as out_file:
out_file.writelines(convert(yaml.safe_load(in_file)))
|
693e02dd272af0d77b565e8d447bb3e72c43dd5f
|
apps/firefox/urls.py
|
apps/firefox/urls.py
|
from django.conf.urls.defaults import *
from django.conf import settings
from product_details import product_details
from mozorg.util import page
import views
urlpatterns = patterns('',
page('firefox/central', 'firefox/central.html'),
page('firefox/customize', 'firefox/customize'),
page('firefox/features', 'firefox/features.html'),
page('firefox/fx', 'firefox/fx.html'),
page('firefox/geolocation', 'firefox/geolocation.html',
gmap_api_key=settings.GMAP_API_KEY),
page('firefox/happy', 'firefox/happy.html'),
page('firefox/new', 'firefox/new.html'),
page('firefox/organizations/faq', 'firefox/organizations/faq.html'),
page('firefox/organizations', 'firefox/organizations.html'),
page('firefox/performance', 'firefox/performance.html'),
page('firefox/security', 'firefox/security.html'),
page('firefox/speed', 'firefox/speed.html',
latest_version=product_details.versions['LATEST_FIREFOX_DEVEL_VERSION']),
page('firefox/technology', 'firefox/technology.html'),
page('firefox/update', 'firefox/update.html'),
)
|
from django.conf.urls.defaults import *
from django.conf import settings
from product_details import product_details
from mozorg.util import page
import views
urlpatterns = patterns('',
page('firefox/central', 'firefox/central.html'),
page('firefox/customize', 'firefox/customize.html'),
page('firefox/features', 'firefox/features.html'),
page('firefox/fx', 'firefox/fx.html'),
page('firefox/geolocation', 'firefox/geolocation.html',
gmap_api_key=settings.GMAP_API_KEY),
page('firefox/happy', 'firefox/happy.html'),
page('firefox/new', 'firefox/new.html'),
page('firefox/organizations/faq', 'firefox/organizations/faq.html'),
page('firefox/organizations', 'firefox/organizations.html'),
page('firefox/performance', 'firefox/performance.html'),
page('firefox/security', 'firefox/security.html'),
page('firefox/speed', 'firefox/speed.html',
latest_version=product_details.versions['LATEST_FIREFOX_DEVEL_VERSION']),
page('firefox/technology', 'firefox/technology.html'),
page('firefox/update', 'firefox/update.html'),
)
|
Fix a typo in customize page url setup
|
Fix a typo in customize page url setup
|
Python
|
mpl-2.0
|
TheoChevalier/bedrock,SujaySKumar/bedrock,jpetto/bedrock,bensternthal/bedrock,gerv/bedrock,analytics-pros/mozilla-bedrock,flodolo/bedrock,TheoChevalier/bedrock,SujaySKumar/bedrock,mahinthjoe/bedrock,hoosteeno/bedrock,mahinthjoe/bedrock,ericawright/bedrock,mahinthjoe/bedrock,mmmavis/bedrock,gauthierm/bedrock,ckprice/bedrock,dudepare/bedrock,rishiloyola/bedrock,dudepare/bedrock,mozilla/mwc,pmclanahan/bedrock,davidwboswell/documentation_autoresponse,sylvestre/bedrock,craigcook/bedrock,rishiloyola/bedrock,Jobava/bedrock,ericawright/bedrock,sgarrity/bedrock,mermi/bedrock,elin-moco/bedrock,gauthierm/bedrock,gerv/bedrock,davidwboswell/documentation_autoresponse,mozilla/bedrock,l-hedgehog/bedrock,schalkneethling/bedrock,Sancus/bedrock,gauthierm/bedrock,jgmize/bedrock,amjadm61/bedrock,elin-moco/bedrock,andreadelrio/bedrock,davidwboswell/documentation_autoresponse,sylvestre/bedrock,mmmavis/lightbeam-bedrock-website,Sancus/bedrock,hoosteeno/bedrock,Jobava/bedrock,ckprice/bedrock,TheJJ100100/bedrock,craigcook/bedrock,jpetto/bedrock,petabyte/bedrock,yglazko/bedrock,malena/bedrock,pmclanahan/bedrock,alexgibson/bedrock,Jobava/bedrock,mmmavis/lightbeam-bedrock-website,MichaelKohler/bedrock,craigcook/bedrock,elin-moco/bedrock,pmclanahan/bedrock,glogiotatidis/bedrock,ckprice/bedrock,schalkneethling/bedrock,davehunt/bedrock,glogiotatidis/bedrock,jpetto/bedrock,jgmize/bedrock,sylvestre/bedrock,analytics-pros/mozilla-bedrock,kyoshino/bedrock,malena/bedrock,jacshfr/mozilla-bedrock,mahinthjoe/bedrock,yglazko/bedrock,mkmelin/bedrock,gauthierm/bedrock,flodolo/bedrock,MichaelKohler/bedrock,kyoshino/bedrock,Sancus/bedrock,craigcook/bedrock,alexgibson/bedrock,davidwboswell/documentation_autoresponse,mmmavis/bedrock,MichaelKohler/bedrock,rishiloyola/bedrock,TheoChevalier/bedrock,glogiotatidis/bedrock,rishiloyola/bedrock,mmmavis/lightbeam-bedrock-website,malena/bedrock,petabyte/bedrock,gerv/bedrock,gerv/bedrock,jgmize/bedrock,mozilla/bedrock,mermi/bedrock,petabyte/bedrock,l-hedgehog/bedrock,ericawright/bedrock,schalkneethling/bedrock,jacshfr/mozilla-bedrock,pascalchevrel/bedrock,l-hedgehog/bedrock,pascalchevrel/bedrock,mermi/bedrock,jacshfr/mozilla-bedrock,sylvestre/bedrock,jacshfr/mozilla-bedrock,alexgibson/bedrock,bensternthal/bedrock,SujaySKumar/bedrock,amjadm61/bedrock,flodolo/bedrock,petabyte/bedrock,pmclanahan/bedrock,davehunt/bedrock,andreadelrio/bedrock,davehunt/bedrock,mkmelin/bedrock,jacshfr/mozilla-bedrock,alexgibson/bedrock,bensternthal/bedrock,amjadm61/bedrock,mozilla/mwc,glogiotatidis/bedrock,CSCI-462-01-2017/bedrock,mozilla/mwc,chirilo/bedrock,sgarrity/bedrock,mmmavis/bedrock,amjadm61/bedrock,kyoshino/bedrock,davehunt/bedrock,ericawright/bedrock,mozilla/mwc,Jobava/bedrock,bensternthal/bedrock,malena/bedrock,hoosteeno/bedrock,marcoscaceres/bedrock,SujaySKumar/bedrock,chirilo/bedrock,MichaelKohler/bedrock,Sancus/bedrock,jpetto/bedrock,analytics-pros/mozilla-bedrock,TheJJ100100/bedrock,analytics-pros/mozilla-bedrock,chirilo/bedrock,amjadm61/bedrock,andreadelrio/bedrock,schalkneethling/bedrock,kyoshino/bedrock,chirilo/bedrock,marcoscaceres/bedrock,yglazko/bedrock,TheoChevalier/bedrock,pascalchevrel/bedrock,CSCI-462-01-2017/bedrock,sgarrity/bedrock,elin-moco/bedrock,jgmize/bedrock,mozilla/bedrock,mermi/bedrock,ckprice/bedrock,mmmavis/bedrock,CSCI-462-01-2017/bedrock,pascalchevrel/bedrock,TheJJ100100/bedrock,l-hedgehog/bedrock,mkmelin/bedrock,marcoscaceres/bedrock,mozilla/bedrock,dudepare/bedrock,dudepare/bedrock,TheJJ100100/bedrock,sgarrity/bedrock,CSCI-462-01-2017/bedrock,yglazko/bedrock,mkmelin/bedrock,marcoscaceres/bedrock,andreadelrio/bedrock,flodolo/bedrock,hoosteeno/bedrock
|
from django.conf.urls.defaults import *
from django.conf import settings
from product_details import product_details
from mozorg.util import page
import views
urlpatterns = patterns('',
page('firefox/central', 'firefox/central.html'),
page('firefox/customize', 'firefox/customize'),
page('firefox/features', 'firefox/features.html'),
page('firefox/fx', 'firefox/fx.html'),
page('firefox/geolocation', 'firefox/geolocation.html',
gmap_api_key=settings.GMAP_API_KEY),
page('firefox/happy', 'firefox/happy.html'),
page('firefox/new', 'firefox/new.html'),
page('firefox/organizations/faq', 'firefox/organizations/faq.html'),
page('firefox/organizations', 'firefox/organizations.html'),
page('firefox/performance', 'firefox/performance.html'),
page('firefox/security', 'firefox/security.html'),
page('firefox/speed', 'firefox/speed.html',
latest_version=product_details.versions['LATEST_FIREFOX_DEVEL_VERSION']),
page('firefox/technology', 'firefox/technology.html'),
page('firefox/update', 'firefox/update.html'),
)
Fix a typo in customize page url setup
|
from django.conf.urls.defaults import *
from django.conf import settings
from product_details import product_details
from mozorg.util import page
import views
urlpatterns = patterns('',
page('firefox/central', 'firefox/central.html'),
page('firefox/customize', 'firefox/customize.html'),
page('firefox/features', 'firefox/features.html'),
page('firefox/fx', 'firefox/fx.html'),
page('firefox/geolocation', 'firefox/geolocation.html',
gmap_api_key=settings.GMAP_API_KEY),
page('firefox/happy', 'firefox/happy.html'),
page('firefox/new', 'firefox/new.html'),
page('firefox/organizations/faq', 'firefox/organizations/faq.html'),
page('firefox/organizations', 'firefox/organizations.html'),
page('firefox/performance', 'firefox/performance.html'),
page('firefox/security', 'firefox/security.html'),
page('firefox/speed', 'firefox/speed.html',
latest_version=product_details.versions['LATEST_FIREFOX_DEVEL_VERSION']),
page('firefox/technology', 'firefox/technology.html'),
page('firefox/update', 'firefox/update.html'),
)
|
<commit_before>from django.conf.urls.defaults import *
from django.conf import settings
from product_details import product_details
from mozorg.util import page
import views
urlpatterns = patterns('',
page('firefox/central', 'firefox/central.html'),
page('firefox/customize', 'firefox/customize'),
page('firefox/features', 'firefox/features.html'),
page('firefox/fx', 'firefox/fx.html'),
page('firefox/geolocation', 'firefox/geolocation.html',
gmap_api_key=settings.GMAP_API_KEY),
page('firefox/happy', 'firefox/happy.html'),
page('firefox/new', 'firefox/new.html'),
page('firefox/organizations/faq', 'firefox/organizations/faq.html'),
page('firefox/organizations', 'firefox/organizations.html'),
page('firefox/performance', 'firefox/performance.html'),
page('firefox/security', 'firefox/security.html'),
page('firefox/speed', 'firefox/speed.html',
latest_version=product_details.versions['LATEST_FIREFOX_DEVEL_VERSION']),
page('firefox/technology', 'firefox/technology.html'),
page('firefox/update', 'firefox/update.html'),
)
<commit_msg>Fix a typo in customize page url setup<commit_after>
|
from django.conf.urls.defaults import *
from django.conf import settings
from product_details import product_details
from mozorg.util import page
import views
urlpatterns = patterns('',
page('firefox/central', 'firefox/central.html'),
page('firefox/customize', 'firefox/customize.html'),
page('firefox/features', 'firefox/features.html'),
page('firefox/fx', 'firefox/fx.html'),
page('firefox/geolocation', 'firefox/geolocation.html',
gmap_api_key=settings.GMAP_API_KEY),
page('firefox/happy', 'firefox/happy.html'),
page('firefox/new', 'firefox/new.html'),
page('firefox/organizations/faq', 'firefox/organizations/faq.html'),
page('firefox/organizations', 'firefox/organizations.html'),
page('firefox/performance', 'firefox/performance.html'),
page('firefox/security', 'firefox/security.html'),
page('firefox/speed', 'firefox/speed.html',
latest_version=product_details.versions['LATEST_FIREFOX_DEVEL_VERSION']),
page('firefox/technology', 'firefox/technology.html'),
page('firefox/update', 'firefox/update.html'),
)
|
from django.conf.urls.defaults import *
from django.conf import settings
from product_details import product_details
from mozorg.util import page
import views
urlpatterns = patterns('',
page('firefox/central', 'firefox/central.html'),
page('firefox/customize', 'firefox/customize'),
page('firefox/features', 'firefox/features.html'),
page('firefox/fx', 'firefox/fx.html'),
page('firefox/geolocation', 'firefox/geolocation.html',
gmap_api_key=settings.GMAP_API_KEY),
page('firefox/happy', 'firefox/happy.html'),
page('firefox/new', 'firefox/new.html'),
page('firefox/organizations/faq', 'firefox/organizations/faq.html'),
page('firefox/organizations', 'firefox/organizations.html'),
page('firefox/performance', 'firefox/performance.html'),
page('firefox/security', 'firefox/security.html'),
page('firefox/speed', 'firefox/speed.html',
latest_version=product_details.versions['LATEST_FIREFOX_DEVEL_VERSION']),
page('firefox/technology', 'firefox/technology.html'),
page('firefox/update', 'firefox/update.html'),
)
Fix a typo in customize page url setupfrom django.conf.urls.defaults import *
from django.conf import settings
from product_details import product_details
from mozorg.util import page
import views
urlpatterns = patterns('',
page('firefox/central', 'firefox/central.html'),
page('firefox/customize', 'firefox/customize.html'),
page('firefox/features', 'firefox/features.html'),
page('firefox/fx', 'firefox/fx.html'),
page('firefox/geolocation', 'firefox/geolocation.html',
gmap_api_key=settings.GMAP_API_KEY),
page('firefox/happy', 'firefox/happy.html'),
page('firefox/new', 'firefox/new.html'),
page('firefox/organizations/faq', 'firefox/organizations/faq.html'),
page('firefox/organizations', 'firefox/organizations.html'),
page('firefox/performance', 'firefox/performance.html'),
page('firefox/security', 'firefox/security.html'),
page('firefox/speed', 'firefox/speed.html',
latest_version=product_details.versions['LATEST_FIREFOX_DEVEL_VERSION']),
page('firefox/technology', 'firefox/technology.html'),
page('firefox/update', 'firefox/update.html'),
)
|
<commit_before>from django.conf.urls.defaults import *
from django.conf import settings
from product_details import product_details
from mozorg.util import page
import views
urlpatterns = patterns('',
page('firefox/central', 'firefox/central.html'),
page('firefox/customize', 'firefox/customize'),
page('firefox/features', 'firefox/features.html'),
page('firefox/fx', 'firefox/fx.html'),
page('firefox/geolocation', 'firefox/geolocation.html',
gmap_api_key=settings.GMAP_API_KEY),
page('firefox/happy', 'firefox/happy.html'),
page('firefox/new', 'firefox/new.html'),
page('firefox/organizations/faq', 'firefox/organizations/faq.html'),
page('firefox/organizations', 'firefox/organizations.html'),
page('firefox/performance', 'firefox/performance.html'),
page('firefox/security', 'firefox/security.html'),
page('firefox/speed', 'firefox/speed.html',
latest_version=product_details.versions['LATEST_FIREFOX_DEVEL_VERSION']),
page('firefox/technology', 'firefox/technology.html'),
page('firefox/update', 'firefox/update.html'),
)
<commit_msg>Fix a typo in customize page url setup<commit_after>from django.conf.urls.defaults import *
from django.conf import settings
from product_details import product_details
from mozorg.util import page
import views
urlpatterns = patterns('',
page('firefox/central', 'firefox/central.html'),
page('firefox/customize', 'firefox/customize.html'),
page('firefox/features', 'firefox/features.html'),
page('firefox/fx', 'firefox/fx.html'),
page('firefox/geolocation', 'firefox/geolocation.html',
gmap_api_key=settings.GMAP_API_KEY),
page('firefox/happy', 'firefox/happy.html'),
page('firefox/new', 'firefox/new.html'),
page('firefox/organizations/faq', 'firefox/organizations/faq.html'),
page('firefox/organizations', 'firefox/organizations.html'),
page('firefox/performance', 'firefox/performance.html'),
page('firefox/security', 'firefox/security.html'),
page('firefox/speed', 'firefox/speed.html',
latest_version=product_details.versions['LATEST_FIREFOX_DEVEL_VERSION']),
page('firefox/technology', 'firefox/technology.html'),
page('firefox/update', 'firefox/update.html'),
)
|
f4bce878530358ea7820b4f45f4d1defaa194a85
|
rabbitpy/__init__.py
|
rabbitpy/__init__.py
|
__version__ = '0.10.0'
from rabbitpy.connection import Connection
from rabbitpy.exchange import Exchange
from rabbitpy.message import Message
from rabbitpy.amqp_queue import Queue
from rabbitpy.tx import Tx
from rabbitpy.simple import consume
from rabbitpy.simple import get
from rabbitpy.simple import publish
from rabbitpy.simple import create_queue
from rabbitpy.simple import delete_queue
from rabbitpy.simple import create_direct_exchange
from rabbitpy.simple import create_fanout_exchange
from rabbitpy.simple import create_topic_exchange
from rabbitpy.simple import delete_exchange
import logging
try:
from logging import NullHandler
except ImportError:
# Python 2.6 does not have a NullHandler
class NullHandler(logging.Handler):
def emit(self, record):
pass
logging.getLogger('rabbitpy').addHandler(NullHandler())
|
__version__ = '0.10.0'
version = __version__
from rabbitpy.connection import Connection
from rabbitpy.exchange import Exchange
from rabbitpy.message import Message
from rabbitpy.amqp_queue import Queue
from rabbitpy.tx import Tx
from rabbitpy.simple import consume
from rabbitpy.simple import get
from rabbitpy.simple import publish
from rabbitpy.simple import create_queue
from rabbitpy.simple import delete_queue
from rabbitpy.simple import create_direct_exchange
from rabbitpy.simple import create_fanout_exchange
from rabbitpy.simple import create_topic_exchange
from rabbitpy.simple import delete_exchange
import logging
try:
from logging import NullHandler
except ImportError:
# Python 2.6 does not have a NullHandler
class NullHandler(logging.Handler):
def emit(self, record):
pass
logging.getLogger('rabbitpy').addHandler(NullHandler())
DEBUG = False
|
Add a DEBUG constant and the ability to more cleanly reference the version.
|
Add a DEBUG constant and the ability to more cleanly reference the version.
|
Python
|
bsd-3-clause
|
gmr/rabbitpy,gmr/rabbitpy,jonahbull/rabbitpy
|
__version__ = '0.10.0'
from rabbitpy.connection import Connection
from rabbitpy.exchange import Exchange
from rabbitpy.message import Message
from rabbitpy.amqp_queue import Queue
from rabbitpy.tx import Tx
from rabbitpy.simple import consume
from rabbitpy.simple import get
from rabbitpy.simple import publish
from rabbitpy.simple import create_queue
from rabbitpy.simple import delete_queue
from rabbitpy.simple import create_direct_exchange
from rabbitpy.simple import create_fanout_exchange
from rabbitpy.simple import create_topic_exchange
from rabbitpy.simple import delete_exchange
import logging
try:
from logging import NullHandler
except ImportError:
# Python 2.6 does not have a NullHandler
class NullHandler(logging.Handler):
def emit(self, record):
pass
logging.getLogger('rabbitpy').addHandler(NullHandler())
Add a DEBUG constant and the ability to more cleanly reference the version.
|
__version__ = '0.10.0'
version = __version__
from rabbitpy.connection import Connection
from rabbitpy.exchange import Exchange
from rabbitpy.message import Message
from rabbitpy.amqp_queue import Queue
from rabbitpy.tx import Tx
from rabbitpy.simple import consume
from rabbitpy.simple import get
from rabbitpy.simple import publish
from rabbitpy.simple import create_queue
from rabbitpy.simple import delete_queue
from rabbitpy.simple import create_direct_exchange
from rabbitpy.simple import create_fanout_exchange
from rabbitpy.simple import create_topic_exchange
from rabbitpy.simple import delete_exchange
import logging
try:
from logging import NullHandler
except ImportError:
# Python 2.6 does not have a NullHandler
class NullHandler(logging.Handler):
def emit(self, record):
pass
logging.getLogger('rabbitpy').addHandler(NullHandler())
DEBUG = False
|
<commit_before>__version__ = '0.10.0'
from rabbitpy.connection import Connection
from rabbitpy.exchange import Exchange
from rabbitpy.message import Message
from rabbitpy.amqp_queue import Queue
from rabbitpy.tx import Tx
from rabbitpy.simple import consume
from rabbitpy.simple import get
from rabbitpy.simple import publish
from rabbitpy.simple import create_queue
from rabbitpy.simple import delete_queue
from rabbitpy.simple import create_direct_exchange
from rabbitpy.simple import create_fanout_exchange
from rabbitpy.simple import create_topic_exchange
from rabbitpy.simple import delete_exchange
import logging
try:
from logging import NullHandler
except ImportError:
# Python 2.6 does not have a NullHandler
class NullHandler(logging.Handler):
def emit(self, record):
pass
logging.getLogger('rabbitpy').addHandler(NullHandler())
<commit_msg>Add a DEBUG constant and the ability to more cleanly reference the version.<commit_after>
|
__version__ = '0.10.0'
version = __version__
from rabbitpy.connection import Connection
from rabbitpy.exchange import Exchange
from rabbitpy.message import Message
from rabbitpy.amqp_queue import Queue
from rabbitpy.tx import Tx
from rabbitpy.simple import consume
from rabbitpy.simple import get
from rabbitpy.simple import publish
from rabbitpy.simple import create_queue
from rabbitpy.simple import delete_queue
from rabbitpy.simple import create_direct_exchange
from rabbitpy.simple import create_fanout_exchange
from rabbitpy.simple import create_topic_exchange
from rabbitpy.simple import delete_exchange
import logging
try:
from logging import NullHandler
except ImportError:
# Python 2.6 does not have a NullHandler
class NullHandler(logging.Handler):
def emit(self, record):
pass
logging.getLogger('rabbitpy').addHandler(NullHandler())
DEBUG = False
|
__version__ = '0.10.0'
from rabbitpy.connection import Connection
from rabbitpy.exchange import Exchange
from rabbitpy.message import Message
from rabbitpy.amqp_queue import Queue
from rabbitpy.tx import Tx
from rabbitpy.simple import consume
from rabbitpy.simple import get
from rabbitpy.simple import publish
from rabbitpy.simple import create_queue
from rabbitpy.simple import delete_queue
from rabbitpy.simple import create_direct_exchange
from rabbitpy.simple import create_fanout_exchange
from rabbitpy.simple import create_topic_exchange
from rabbitpy.simple import delete_exchange
import logging
try:
from logging import NullHandler
except ImportError:
# Python 2.6 does not have a NullHandler
class NullHandler(logging.Handler):
def emit(self, record):
pass
logging.getLogger('rabbitpy').addHandler(NullHandler())
Add a DEBUG constant and the ability to more cleanly reference the version.__version__ = '0.10.0'
version = __version__
from rabbitpy.connection import Connection
from rabbitpy.exchange import Exchange
from rabbitpy.message import Message
from rabbitpy.amqp_queue import Queue
from rabbitpy.tx import Tx
from rabbitpy.simple import consume
from rabbitpy.simple import get
from rabbitpy.simple import publish
from rabbitpy.simple import create_queue
from rabbitpy.simple import delete_queue
from rabbitpy.simple import create_direct_exchange
from rabbitpy.simple import create_fanout_exchange
from rabbitpy.simple import create_topic_exchange
from rabbitpy.simple import delete_exchange
import logging
try:
from logging import NullHandler
except ImportError:
# Python 2.6 does not have a NullHandler
class NullHandler(logging.Handler):
def emit(self, record):
pass
logging.getLogger('rabbitpy').addHandler(NullHandler())
DEBUG = False
|
<commit_before>__version__ = '0.10.0'
from rabbitpy.connection import Connection
from rabbitpy.exchange import Exchange
from rabbitpy.message import Message
from rabbitpy.amqp_queue import Queue
from rabbitpy.tx import Tx
from rabbitpy.simple import consume
from rabbitpy.simple import get
from rabbitpy.simple import publish
from rabbitpy.simple import create_queue
from rabbitpy.simple import delete_queue
from rabbitpy.simple import create_direct_exchange
from rabbitpy.simple import create_fanout_exchange
from rabbitpy.simple import create_topic_exchange
from rabbitpy.simple import delete_exchange
import logging
try:
from logging import NullHandler
except ImportError:
# Python 2.6 does not have a NullHandler
class NullHandler(logging.Handler):
def emit(self, record):
pass
logging.getLogger('rabbitpy').addHandler(NullHandler())
<commit_msg>Add a DEBUG constant and the ability to more cleanly reference the version.<commit_after>__version__ = '0.10.0'
version = __version__
from rabbitpy.connection import Connection
from rabbitpy.exchange import Exchange
from rabbitpy.message import Message
from rabbitpy.amqp_queue import Queue
from rabbitpy.tx import Tx
from rabbitpy.simple import consume
from rabbitpy.simple import get
from rabbitpy.simple import publish
from rabbitpy.simple import create_queue
from rabbitpy.simple import delete_queue
from rabbitpy.simple import create_direct_exchange
from rabbitpy.simple import create_fanout_exchange
from rabbitpy.simple import create_topic_exchange
from rabbitpy.simple import delete_exchange
import logging
try:
from logging import NullHandler
except ImportError:
# Python 2.6 does not have a NullHandler
class NullHandler(logging.Handler):
def emit(self, record):
pass
logging.getLogger('rabbitpy').addHandler(NullHandler())
DEBUG = False
|
e82474c0281aebe3b623a5be9adc0adf14fa58d5
|
ann_util.py
|
ann_util.py
|
import math
import random
def logistic(x):
return 1.0 / (1 + math.exp(-x))
def deriv_logistic(x):
lgst = logistic(x)
return (1 - lgst) * lgst
def hyperbolic_tangent(x):
return math.tanh(x)
def deriv_hyperbolic_tangent(x):
th = math.tanh(x)
return 1 - th * th
def between(min, max):
"""
Return a real random value between min and max.
"""
return random.random() * (max - min) + min
def make_matrix(N, M):
"""
Make an N rows by M columns matrix.
"""
return [[0 for i in range(M)] for i in range(N)]
|
import math
import pickle
import random
def logistic(x):
return 1.0 / (1 + math.exp(-x))
def deriv_logistic(x):
lgst = logistic(x)
return (1 - lgst) * lgst
def hyperbolic_tangent(x):
return math.tanh(x)
def deriv_hyperbolic_tangent(x):
th = math.tanh(x)
return 1 - th * th
def between(min, max):
"""
Return a real random value between min and max.
"""
return random.random() * (max - min) + min
def make_matrix(N, M):
"""
Make an N rows by M columns matrix.
"""
return [[0 for i in range(M)] for i in range(N)]
def serialize(nn, fname):
with open(fname, 'wb') as f:
pickle.dump(nn, f)
def deserialize(fname):
with open(fname, 'rb') as f:
nn = pickle.load(f)
return nn
|
Add pickle serialize and deserialize
|
Add pickle serialize and deserialize
|
Python
|
apache-2.0
|
Razvy000/ANN_Course
|
import math
import random
def logistic(x):
return 1.0 / (1 + math.exp(-x))
def deriv_logistic(x):
lgst = logistic(x)
return (1 - lgst) * lgst
def hyperbolic_tangent(x):
return math.tanh(x)
def deriv_hyperbolic_tangent(x):
th = math.tanh(x)
return 1 - th * th
def between(min, max):
"""
Return a real random value between min and max.
"""
return random.random() * (max - min) + min
def make_matrix(N, M):
"""
Make an N rows by M columns matrix.
"""
return [[0 for i in range(M)] for i in range(N)]
Add pickle serialize and deserialize
|
import math
import pickle
import random
def logistic(x):
return 1.0 / (1 + math.exp(-x))
def deriv_logistic(x):
lgst = logistic(x)
return (1 - lgst) * lgst
def hyperbolic_tangent(x):
return math.tanh(x)
def deriv_hyperbolic_tangent(x):
th = math.tanh(x)
return 1 - th * th
def between(min, max):
"""
Return a real random value between min and max.
"""
return random.random() * (max - min) + min
def make_matrix(N, M):
"""
Make an N rows by M columns matrix.
"""
return [[0 for i in range(M)] for i in range(N)]
def serialize(nn, fname):
with open(fname, 'wb') as f:
pickle.dump(nn, f)
def deserialize(fname):
with open(fname, 'rb') as f:
nn = pickle.load(f)
return nn
|
<commit_before>import math
import random
def logistic(x):
return 1.0 / (1 + math.exp(-x))
def deriv_logistic(x):
lgst = logistic(x)
return (1 - lgst) * lgst
def hyperbolic_tangent(x):
return math.tanh(x)
def deriv_hyperbolic_tangent(x):
th = math.tanh(x)
return 1 - th * th
def between(min, max):
"""
Return a real random value between min and max.
"""
return random.random() * (max - min) + min
def make_matrix(N, M):
"""
Make an N rows by M columns matrix.
"""
return [[0 for i in range(M)] for i in range(N)]
<commit_msg>Add pickle serialize and deserialize<commit_after>
|
import math
import pickle
import random
def logistic(x):
return 1.0 / (1 + math.exp(-x))
def deriv_logistic(x):
lgst = logistic(x)
return (1 - lgst) * lgst
def hyperbolic_tangent(x):
return math.tanh(x)
def deriv_hyperbolic_tangent(x):
th = math.tanh(x)
return 1 - th * th
def between(min, max):
"""
Return a real random value between min and max.
"""
return random.random() * (max - min) + min
def make_matrix(N, M):
"""
Make an N rows by M columns matrix.
"""
return [[0 for i in range(M)] for i in range(N)]
def serialize(nn, fname):
with open(fname, 'wb') as f:
pickle.dump(nn, f)
def deserialize(fname):
with open(fname, 'rb') as f:
nn = pickle.load(f)
return nn
|
import math
import random
def logistic(x):
return 1.0 / (1 + math.exp(-x))
def deriv_logistic(x):
lgst = logistic(x)
return (1 - lgst) * lgst
def hyperbolic_tangent(x):
return math.tanh(x)
def deriv_hyperbolic_tangent(x):
th = math.tanh(x)
return 1 - th * th
def between(min, max):
"""
Return a real random value between min and max.
"""
return random.random() * (max - min) + min
def make_matrix(N, M):
"""
Make an N rows by M columns matrix.
"""
return [[0 for i in range(M)] for i in range(N)]
Add pickle serialize and deserializeimport math
import pickle
import random
def logistic(x):
return 1.0 / (1 + math.exp(-x))
def deriv_logistic(x):
lgst = logistic(x)
return (1 - lgst) * lgst
def hyperbolic_tangent(x):
return math.tanh(x)
def deriv_hyperbolic_tangent(x):
th = math.tanh(x)
return 1 - th * th
def between(min, max):
"""
Return a real random value between min and max.
"""
return random.random() * (max - min) + min
def make_matrix(N, M):
"""
Make an N rows by M columns matrix.
"""
return [[0 for i in range(M)] for i in range(N)]
def serialize(nn, fname):
with open(fname, 'wb') as f:
pickle.dump(nn, f)
def deserialize(fname):
with open(fname, 'rb') as f:
nn = pickle.load(f)
return nn
|
<commit_before>import math
import random
def logistic(x):
return 1.0 / (1 + math.exp(-x))
def deriv_logistic(x):
lgst = logistic(x)
return (1 - lgst) * lgst
def hyperbolic_tangent(x):
return math.tanh(x)
def deriv_hyperbolic_tangent(x):
th = math.tanh(x)
return 1 - th * th
def between(min, max):
"""
Return a real random value between min and max.
"""
return random.random() * (max - min) + min
def make_matrix(N, M):
"""
Make an N rows by M columns matrix.
"""
return [[0 for i in range(M)] for i in range(N)]
<commit_msg>Add pickle serialize and deserialize<commit_after>import math
import pickle
import random
def logistic(x):
return 1.0 / (1 + math.exp(-x))
def deriv_logistic(x):
lgst = logistic(x)
return (1 - lgst) * lgst
def hyperbolic_tangent(x):
return math.tanh(x)
def deriv_hyperbolic_tangent(x):
th = math.tanh(x)
return 1 - th * th
def between(min, max):
"""
Return a real random value between min and max.
"""
return random.random() * (max - min) + min
def make_matrix(N, M):
"""
Make an N rows by M columns matrix.
"""
return [[0 for i in range(M)] for i in range(N)]
def serialize(nn, fname):
with open(fname, 'wb') as f:
pickle.dump(nn, f)
def deserialize(fname):
with open(fname, 'rb') as f:
nn = pickle.load(f)
return nn
|
ec7cbb256e7beab806fe5346c306f7ebc13b1578
|
src/googleclouddebugger/labels.py
|
src/googleclouddebugger/labels.py
|
# Copyright 2015 Google Inc. 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.
"""Defines the keys of the well known labels used by the cloud debugger.
DO NOT EDIT - This file is auto-generated
"""
class Debuggee(object):
MINOR_VERSION = 'minorversion'
PROJECT_ID = 'projectid'
MODULE = 'module'
DOMAIN = 'domain'
VERSION = 'version'
SET_ALL = frozenset([
'minorversion',
'projectid',
'module',
'domain',
'version',
])
class Breakpoint(object):
REQUEST_LOG_ID = 'requestlogid'
SET_ALL = frozenset([
'requestlogid',
])
|
# Copyright 2015 Google Inc. 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.
"""Defines the keys of the well known labels used by the cloud debugger.
DO NOT EDIT - This file is auto-generated
"""
class Breakpoint(object):
REQUEST_LOG_ID = 'requestlogid'
SET_ALL = frozenset([
'requestlogid',
])
class Debuggee(object):
DOMAIN = 'domain'
PROJECT_ID = 'projectid'
MODULE = 'module'
VERSION = 'version'
MINOR_VERSION = 'minorversion'
SET_ALL = frozenset([
'domain',
'projectid',
'module',
'version',
'minorversion',
])
|
Set compatible_with=appengine on targets depended on by App Engine apps or by the App Engine runtime itself.
|
Set compatible_with=appengine on targets depended on by App Engine apps or by the App Engine runtime itself.
This CL has no immediate impact on the targets, but it has two consequences moving forward:
- When google3 moves to Java 8, compatible_with=appengine targets will remain on Java 7. (If this target is a non-java_* target, you can ignore this bullet.)
- compatible_with=appengine targets can depend only on other compatible_with=appengine targets. (Fortunately, most common libraries will be compatible_with=appengine: http://gpaste/5720237664108544)
This CL is one of thousands in a migration on the critical path for Java 8, so please respond promptly, and, if you are the wrong reviewer, please reassign the CL.
More information:
http://go/compatible_with_appengine_lsc
Tested:
blaze build --nobuild
-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=127990496
|
Python
|
apache-2.0
|
GoogleCloudPlatform/cloud-debug-python,GoogleCloudPlatform/cloud-debug-python,GoogleCloudPlatform/cloud-debug-python
|
# Copyright 2015 Google Inc. 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.
"""Defines the keys of the well known labels used by the cloud debugger.
DO NOT EDIT - This file is auto-generated
"""
class Debuggee(object):
MINOR_VERSION = 'minorversion'
PROJECT_ID = 'projectid'
MODULE = 'module'
DOMAIN = 'domain'
VERSION = 'version'
SET_ALL = frozenset([
'minorversion',
'projectid',
'module',
'domain',
'version',
])
class Breakpoint(object):
REQUEST_LOG_ID = 'requestlogid'
SET_ALL = frozenset([
'requestlogid',
])
Set compatible_with=appengine on targets depended on by App Engine apps or by the App Engine runtime itself.
This CL has no immediate impact on the targets, but it has two consequences moving forward:
- When google3 moves to Java 8, compatible_with=appengine targets will remain on Java 7. (If this target is a non-java_* target, you can ignore this bullet.)
- compatible_with=appengine targets can depend only on other compatible_with=appengine targets. (Fortunately, most common libraries will be compatible_with=appengine: http://gpaste/5720237664108544)
This CL is one of thousands in a migration on the critical path for Java 8, so please respond promptly, and, if you are the wrong reviewer, please reassign the CL.
More information:
http://go/compatible_with_appengine_lsc
Tested:
blaze build --nobuild
-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=127990496
|
# Copyright 2015 Google Inc. 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.
"""Defines the keys of the well known labels used by the cloud debugger.
DO NOT EDIT - This file is auto-generated
"""
class Breakpoint(object):
REQUEST_LOG_ID = 'requestlogid'
SET_ALL = frozenset([
'requestlogid',
])
class Debuggee(object):
DOMAIN = 'domain'
PROJECT_ID = 'projectid'
MODULE = 'module'
VERSION = 'version'
MINOR_VERSION = 'minorversion'
SET_ALL = frozenset([
'domain',
'projectid',
'module',
'version',
'minorversion',
])
|
<commit_before># Copyright 2015 Google Inc. 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.
"""Defines the keys of the well known labels used by the cloud debugger.
DO NOT EDIT - This file is auto-generated
"""
class Debuggee(object):
MINOR_VERSION = 'minorversion'
PROJECT_ID = 'projectid'
MODULE = 'module'
DOMAIN = 'domain'
VERSION = 'version'
SET_ALL = frozenset([
'minorversion',
'projectid',
'module',
'domain',
'version',
])
class Breakpoint(object):
REQUEST_LOG_ID = 'requestlogid'
SET_ALL = frozenset([
'requestlogid',
])
<commit_msg>Set compatible_with=appengine on targets depended on by App Engine apps or by the App Engine runtime itself.
This CL has no immediate impact on the targets, but it has two consequences moving forward:
- When google3 moves to Java 8, compatible_with=appengine targets will remain on Java 7. (If this target is a non-java_* target, you can ignore this bullet.)
- compatible_with=appengine targets can depend only on other compatible_with=appengine targets. (Fortunately, most common libraries will be compatible_with=appengine: http://gpaste/5720237664108544)
This CL is one of thousands in a migration on the critical path for Java 8, so please respond promptly, and, if you are the wrong reviewer, please reassign the CL.
More information:
http://go/compatible_with_appengine_lsc
Tested:
blaze build --nobuild
-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=127990496<commit_after>
|
# Copyright 2015 Google Inc. 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.
"""Defines the keys of the well known labels used by the cloud debugger.
DO NOT EDIT - This file is auto-generated
"""
class Breakpoint(object):
REQUEST_LOG_ID = 'requestlogid'
SET_ALL = frozenset([
'requestlogid',
])
class Debuggee(object):
DOMAIN = 'domain'
PROJECT_ID = 'projectid'
MODULE = 'module'
VERSION = 'version'
MINOR_VERSION = 'minorversion'
SET_ALL = frozenset([
'domain',
'projectid',
'module',
'version',
'minorversion',
])
|
# Copyright 2015 Google Inc. 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.
"""Defines the keys of the well known labels used by the cloud debugger.
DO NOT EDIT - This file is auto-generated
"""
class Debuggee(object):
MINOR_VERSION = 'minorversion'
PROJECT_ID = 'projectid'
MODULE = 'module'
DOMAIN = 'domain'
VERSION = 'version'
SET_ALL = frozenset([
'minorversion',
'projectid',
'module',
'domain',
'version',
])
class Breakpoint(object):
REQUEST_LOG_ID = 'requestlogid'
SET_ALL = frozenset([
'requestlogid',
])
Set compatible_with=appengine on targets depended on by App Engine apps or by the App Engine runtime itself.
This CL has no immediate impact on the targets, but it has two consequences moving forward:
- When google3 moves to Java 8, compatible_with=appengine targets will remain on Java 7. (If this target is a non-java_* target, you can ignore this bullet.)
- compatible_with=appengine targets can depend only on other compatible_with=appengine targets. (Fortunately, most common libraries will be compatible_with=appengine: http://gpaste/5720237664108544)
This CL is one of thousands in a migration on the critical path for Java 8, so please respond promptly, and, if you are the wrong reviewer, please reassign the CL.
More information:
http://go/compatible_with_appengine_lsc
Tested:
blaze build --nobuild
-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=127990496# Copyright 2015 Google Inc. 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.
"""Defines the keys of the well known labels used by the cloud debugger.
DO NOT EDIT - This file is auto-generated
"""
class Breakpoint(object):
REQUEST_LOG_ID = 'requestlogid'
SET_ALL = frozenset([
'requestlogid',
])
class Debuggee(object):
DOMAIN = 'domain'
PROJECT_ID = 'projectid'
MODULE = 'module'
VERSION = 'version'
MINOR_VERSION = 'minorversion'
SET_ALL = frozenset([
'domain',
'projectid',
'module',
'version',
'minorversion',
])
|
<commit_before># Copyright 2015 Google Inc. 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.
"""Defines the keys of the well known labels used by the cloud debugger.
DO NOT EDIT - This file is auto-generated
"""
class Debuggee(object):
MINOR_VERSION = 'minorversion'
PROJECT_ID = 'projectid'
MODULE = 'module'
DOMAIN = 'domain'
VERSION = 'version'
SET_ALL = frozenset([
'minorversion',
'projectid',
'module',
'domain',
'version',
])
class Breakpoint(object):
REQUEST_LOG_ID = 'requestlogid'
SET_ALL = frozenset([
'requestlogid',
])
<commit_msg>Set compatible_with=appengine on targets depended on by App Engine apps or by the App Engine runtime itself.
This CL has no immediate impact on the targets, but it has two consequences moving forward:
- When google3 moves to Java 8, compatible_with=appengine targets will remain on Java 7. (If this target is a non-java_* target, you can ignore this bullet.)
- compatible_with=appengine targets can depend only on other compatible_with=appengine targets. (Fortunately, most common libraries will be compatible_with=appengine: http://gpaste/5720237664108544)
This CL is one of thousands in a migration on the critical path for Java 8, so please respond promptly, and, if you are the wrong reviewer, please reassign the CL.
More information:
http://go/compatible_with_appengine_lsc
Tested:
blaze build --nobuild
-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=127990496<commit_after># Copyright 2015 Google Inc. 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.
"""Defines the keys of the well known labels used by the cloud debugger.
DO NOT EDIT - This file is auto-generated
"""
class Breakpoint(object):
REQUEST_LOG_ID = 'requestlogid'
SET_ALL = frozenset([
'requestlogid',
])
class Debuggee(object):
DOMAIN = 'domain'
PROJECT_ID = 'projectid'
MODULE = 'module'
VERSION = 'version'
MINOR_VERSION = 'minorversion'
SET_ALL = frozenset([
'domain',
'projectid',
'module',
'version',
'minorversion',
])
|
6dd403ae88a11457c7930639781182afff892761
|
UM/__init__.py
|
UM/__init__.py
|
# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
#Shoopdawoop
## \package UM
# This is the main library for Uranium applications.
|
# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
#Shoopdawoop
## \package UM
# This is the main library for Uranium applications.
from .Application import Application
from .ColorGenerator import ColorGenerator
from .Controller import Controller
from .Event import Event, MouseEvent, WheelEvent, KeyEvent, ToolEvent, CallFunctionEvent, ViewEvent
from .Extension import Extension
from .InputDevice import InputDevice
from .Job import Job
from .JobQueue import JobQueue
from .Logger import Logger, LogOutput
from .Message import Message
from .MimeTypeDatabase import MimeType, MimeTypeDatabase, MimeTypeNotFoundError
from .Platform import Platform
from .PluginError import PluginError, PluginNotFoundError, InvalidMetaDataError
from .PluginObject import PluginObject
from .PluginRegistry import PluginRegistry
from .Preferences import Preferences
from .Resources import Resources
from .SaveFile import SaveFile
from .Signal import Signal, SignalEmitter
from .SortedList import SortedList, SortedListWithKey
from .Tool import Tool
from .Version import Version
|
Allow new import style for UM directory
|
Allow new import style for UM directory
This imports all public classes in the UM namespace rather than leaving them inside the modules in that namespace. For example, this allows directly importing UM.Logger and then using UM.Logger.log(...) to log a message.
Contributes to ALL ISSUES AT THE SAME TIME.
|
Python
|
agpl-3.0
|
onitake/Uranium,onitake/Uranium
|
# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
#Shoopdawoop
## \package UM
# This is the main library for Uranium applications.
Allow new import style for UM directory
This imports all public classes in the UM namespace rather than leaving them inside the modules in that namespace. For example, this allows directly importing UM.Logger and then using UM.Logger.log(...) to log a message.
Contributes to ALL ISSUES AT THE SAME TIME.
|
# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
#Shoopdawoop
## \package UM
# This is the main library for Uranium applications.
from .Application import Application
from .ColorGenerator import ColorGenerator
from .Controller import Controller
from .Event import Event, MouseEvent, WheelEvent, KeyEvent, ToolEvent, CallFunctionEvent, ViewEvent
from .Extension import Extension
from .InputDevice import InputDevice
from .Job import Job
from .JobQueue import JobQueue
from .Logger import Logger, LogOutput
from .Message import Message
from .MimeTypeDatabase import MimeType, MimeTypeDatabase, MimeTypeNotFoundError
from .Platform import Platform
from .PluginError import PluginError, PluginNotFoundError, InvalidMetaDataError
from .PluginObject import PluginObject
from .PluginRegistry import PluginRegistry
from .Preferences import Preferences
from .Resources import Resources
from .SaveFile import SaveFile
from .Signal import Signal, SignalEmitter
from .SortedList import SortedList, SortedListWithKey
from .Tool import Tool
from .Version import Version
|
<commit_before># Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
#Shoopdawoop
## \package UM
# This is the main library for Uranium applications.
<commit_msg>Allow new import style for UM directory
This imports all public classes in the UM namespace rather than leaving them inside the modules in that namespace. For example, this allows directly importing UM.Logger and then using UM.Logger.log(...) to log a message.
Contributes to ALL ISSUES AT THE SAME TIME.<commit_after>
|
# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
#Shoopdawoop
## \package UM
# This is the main library for Uranium applications.
from .Application import Application
from .ColorGenerator import ColorGenerator
from .Controller import Controller
from .Event import Event, MouseEvent, WheelEvent, KeyEvent, ToolEvent, CallFunctionEvent, ViewEvent
from .Extension import Extension
from .InputDevice import InputDevice
from .Job import Job
from .JobQueue import JobQueue
from .Logger import Logger, LogOutput
from .Message import Message
from .MimeTypeDatabase import MimeType, MimeTypeDatabase, MimeTypeNotFoundError
from .Platform import Platform
from .PluginError import PluginError, PluginNotFoundError, InvalidMetaDataError
from .PluginObject import PluginObject
from .PluginRegistry import PluginRegistry
from .Preferences import Preferences
from .Resources import Resources
from .SaveFile import SaveFile
from .Signal import Signal, SignalEmitter
from .SortedList import SortedList, SortedListWithKey
from .Tool import Tool
from .Version import Version
|
# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
#Shoopdawoop
## \package UM
# This is the main library for Uranium applications.
Allow new import style for UM directory
This imports all public classes in the UM namespace rather than leaving them inside the modules in that namespace. For example, this allows directly importing UM.Logger and then using UM.Logger.log(...) to log a message.
Contributes to ALL ISSUES AT THE SAME TIME.# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
#Shoopdawoop
## \package UM
# This is the main library for Uranium applications.
from .Application import Application
from .ColorGenerator import ColorGenerator
from .Controller import Controller
from .Event import Event, MouseEvent, WheelEvent, KeyEvent, ToolEvent, CallFunctionEvent, ViewEvent
from .Extension import Extension
from .InputDevice import InputDevice
from .Job import Job
from .JobQueue import JobQueue
from .Logger import Logger, LogOutput
from .Message import Message
from .MimeTypeDatabase import MimeType, MimeTypeDatabase, MimeTypeNotFoundError
from .Platform import Platform
from .PluginError import PluginError, PluginNotFoundError, InvalidMetaDataError
from .PluginObject import PluginObject
from .PluginRegistry import PluginRegistry
from .Preferences import Preferences
from .Resources import Resources
from .SaveFile import SaveFile
from .Signal import Signal, SignalEmitter
from .SortedList import SortedList, SortedListWithKey
from .Tool import Tool
from .Version import Version
|
<commit_before># Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
#Shoopdawoop
## \package UM
# This is the main library for Uranium applications.
<commit_msg>Allow new import style for UM directory
This imports all public classes in the UM namespace rather than leaving them inside the modules in that namespace. For example, this allows directly importing UM.Logger and then using UM.Logger.log(...) to log a message.
Contributes to ALL ISSUES AT THE SAME TIME.<commit_after># Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
#Shoopdawoop
## \package UM
# This is the main library for Uranium applications.
from .Application import Application
from .ColorGenerator import ColorGenerator
from .Controller import Controller
from .Event import Event, MouseEvent, WheelEvent, KeyEvent, ToolEvent, CallFunctionEvent, ViewEvent
from .Extension import Extension
from .InputDevice import InputDevice
from .Job import Job
from .JobQueue import JobQueue
from .Logger import Logger, LogOutput
from .Message import Message
from .MimeTypeDatabase import MimeType, MimeTypeDatabase, MimeTypeNotFoundError
from .Platform import Platform
from .PluginError import PluginError, PluginNotFoundError, InvalidMetaDataError
from .PluginObject import PluginObject
from .PluginRegistry import PluginRegistry
from .Preferences import Preferences
from .Resources import Resources
from .SaveFile import SaveFile
from .Signal import Signal, SignalEmitter
from .SortedList import SortedList, SortedListWithKey
from .Tool import Tool
from .Version import Version
|
556cd504dbbd4dfd1a537e8f3e4636f9ebb50327
|
src/scripts/get_arxiv.py
|
src/scripts/get_arxiv.py
|
import sys
import os
import bs4
import urllib2
import urllib
BASE_URL = "http://arxiv.org"
HEP_URL = 'http://arxiv.org/abs/hep-th/%d'
# TODO: Change prints to logs
def get_pdf(paper_id, save_dir):
try:
paper_page = urllib2.urlopen(HEP_URL % paper_id)
soup = bs4.BeautifulSoup(paper_page.read().decode('utf8'))
except:
print "Error"
else:
# TODO: Check if this pattern holds for all papers
file = soup.find("a", {"accesskey" : "f"})
if file:
file_url = file["href"]
print os.path.join(save_dir, str(paper_id) + ".pdf")
urllib.urlretrieve(BASE_URL + file_url, os.path.join(save_dir, str(paper_id) + ".pdf"))
else:
print "Unable to find PDF: %d" % paper_id
def main():
if len(sys.argv) > 2 and sys.argv[1].isdigit() and os.path.isdir(sys.argv[2]):
get_pdf(int(sys.argv[1]), sys.argv[2])
else:
print "Usage <paper id> <destination directory>"
if __name__ == "__main__": main()
|
import sys
import os
import bs4
import urllib2
import urllib
BASE_URL = "http://arxiv.org"
HEP_URL = 'http://arxiv.org/abs/hep-th/%d'
# TODO: Change prints to logs
def get_pdf(paper_id, save_dir):
file_path = os.path.join(save_dir, str(paper_id) + ".pdf")
if not os.path.isfile(file_path):
# Only try to download missing files
try:
paper_page = urllib2.urlopen(HEP_URL % paper_id)
soup = bs4.BeautifulSoup(paper_page.read().decode('utf8'))
except:
print "Error"
else:
# TODO: Check if this pattern holds for all papers
file = soup.find("a", {"accesskey" : "f"})
if file:
file_url = file["href"]
print os.path.join(save_dir, str(paper_id) + ".pdf")
urllib.urlretrieve(BASE_URL + file_url, os.path.join(save_dir, str(paper_id) + ".pdf"))
else:
print "Unable to find PDF: %d" % paper_id
def main():
if len(sys.argv) > 2 and sys.argv[1].isdigit() and os.path.isdir(sys.argv[2]):
get_pdf(int(sys.argv[1]), sys.argv[2])
else:
print "Usage <paper id> <destination directory>"
if __name__ == "__main__": main()
|
Update arxiv script to prevent dup downloads
|
Update arxiv script to prevent dup downloads
|
Python
|
mit
|
PinPinIre/Final-Year-Project,PinPinIre/Final-Year-Project,PinPinIre/Final-Year-Project
|
import sys
import os
import bs4
import urllib2
import urllib
BASE_URL = "http://arxiv.org"
HEP_URL = 'http://arxiv.org/abs/hep-th/%d'
# TODO: Change prints to logs
def get_pdf(paper_id, save_dir):
try:
paper_page = urllib2.urlopen(HEP_URL % paper_id)
soup = bs4.BeautifulSoup(paper_page.read().decode('utf8'))
except:
print "Error"
else:
# TODO: Check if this pattern holds for all papers
file = soup.find("a", {"accesskey" : "f"})
if file:
file_url = file["href"]
print os.path.join(save_dir, str(paper_id) + ".pdf")
urllib.urlretrieve(BASE_URL + file_url, os.path.join(save_dir, str(paper_id) + ".pdf"))
else:
print "Unable to find PDF: %d" % paper_id
def main():
if len(sys.argv) > 2 and sys.argv[1].isdigit() and os.path.isdir(sys.argv[2]):
get_pdf(int(sys.argv[1]), sys.argv[2])
else:
print "Usage <paper id> <destination directory>"
if __name__ == "__main__": main()
Update arxiv script to prevent dup downloads
|
import sys
import os
import bs4
import urllib2
import urllib
BASE_URL = "http://arxiv.org"
HEP_URL = 'http://arxiv.org/abs/hep-th/%d'
# TODO: Change prints to logs
def get_pdf(paper_id, save_dir):
file_path = os.path.join(save_dir, str(paper_id) + ".pdf")
if not os.path.isfile(file_path):
# Only try to download missing files
try:
paper_page = urllib2.urlopen(HEP_URL % paper_id)
soup = bs4.BeautifulSoup(paper_page.read().decode('utf8'))
except:
print "Error"
else:
# TODO: Check if this pattern holds for all papers
file = soup.find("a", {"accesskey" : "f"})
if file:
file_url = file["href"]
print os.path.join(save_dir, str(paper_id) + ".pdf")
urllib.urlretrieve(BASE_URL + file_url, os.path.join(save_dir, str(paper_id) + ".pdf"))
else:
print "Unable to find PDF: %d" % paper_id
def main():
if len(sys.argv) > 2 and sys.argv[1].isdigit() and os.path.isdir(sys.argv[2]):
get_pdf(int(sys.argv[1]), sys.argv[2])
else:
print "Usage <paper id> <destination directory>"
if __name__ == "__main__": main()
|
<commit_before>import sys
import os
import bs4
import urllib2
import urllib
BASE_URL = "http://arxiv.org"
HEP_URL = 'http://arxiv.org/abs/hep-th/%d'
# TODO: Change prints to logs
def get_pdf(paper_id, save_dir):
try:
paper_page = urllib2.urlopen(HEP_URL % paper_id)
soup = bs4.BeautifulSoup(paper_page.read().decode('utf8'))
except:
print "Error"
else:
# TODO: Check if this pattern holds for all papers
file = soup.find("a", {"accesskey" : "f"})
if file:
file_url = file["href"]
print os.path.join(save_dir, str(paper_id) + ".pdf")
urllib.urlretrieve(BASE_URL + file_url, os.path.join(save_dir, str(paper_id) + ".pdf"))
else:
print "Unable to find PDF: %d" % paper_id
def main():
if len(sys.argv) > 2 and sys.argv[1].isdigit() and os.path.isdir(sys.argv[2]):
get_pdf(int(sys.argv[1]), sys.argv[2])
else:
print "Usage <paper id> <destination directory>"
if __name__ == "__main__": main()
<commit_msg>Update arxiv script to prevent dup downloads<commit_after>
|
import sys
import os
import bs4
import urllib2
import urllib
BASE_URL = "http://arxiv.org"
HEP_URL = 'http://arxiv.org/abs/hep-th/%d'
# TODO: Change prints to logs
def get_pdf(paper_id, save_dir):
file_path = os.path.join(save_dir, str(paper_id) + ".pdf")
if not os.path.isfile(file_path):
# Only try to download missing files
try:
paper_page = urllib2.urlopen(HEP_URL % paper_id)
soup = bs4.BeautifulSoup(paper_page.read().decode('utf8'))
except:
print "Error"
else:
# TODO: Check if this pattern holds for all papers
file = soup.find("a", {"accesskey" : "f"})
if file:
file_url = file["href"]
print os.path.join(save_dir, str(paper_id) + ".pdf")
urllib.urlretrieve(BASE_URL + file_url, os.path.join(save_dir, str(paper_id) + ".pdf"))
else:
print "Unable to find PDF: %d" % paper_id
def main():
if len(sys.argv) > 2 and sys.argv[1].isdigit() and os.path.isdir(sys.argv[2]):
get_pdf(int(sys.argv[1]), sys.argv[2])
else:
print "Usage <paper id> <destination directory>"
if __name__ == "__main__": main()
|
import sys
import os
import bs4
import urllib2
import urllib
BASE_URL = "http://arxiv.org"
HEP_URL = 'http://arxiv.org/abs/hep-th/%d'
# TODO: Change prints to logs
def get_pdf(paper_id, save_dir):
try:
paper_page = urllib2.urlopen(HEP_URL % paper_id)
soup = bs4.BeautifulSoup(paper_page.read().decode('utf8'))
except:
print "Error"
else:
# TODO: Check if this pattern holds for all papers
file = soup.find("a", {"accesskey" : "f"})
if file:
file_url = file["href"]
print os.path.join(save_dir, str(paper_id) + ".pdf")
urllib.urlretrieve(BASE_URL + file_url, os.path.join(save_dir, str(paper_id) + ".pdf"))
else:
print "Unable to find PDF: %d" % paper_id
def main():
if len(sys.argv) > 2 and sys.argv[1].isdigit() and os.path.isdir(sys.argv[2]):
get_pdf(int(sys.argv[1]), sys.argv[2])
else:
print "Usage <paper id> <destination directory>"
if __name__ == "__main__": main()
Update arxiv script to prevent dup downloadsimport sys
import os
import bs4
import urllib2
import urllib
BASE_URL = "http://arxiv.org"
HEP_URL = 'http://arxiv.org/abs/hep-th/%d'
# TODO: Change prints to logs
def get_pdf(paper_id, save_dir):
file_path = os.path.join(save_dir, str(paper_id) + ".pdf")
if not os.path.isfile(file_path):
# Only try to download missing files
try:
paper_page = urllib2.urlopen(HEP_URL % paper_id)
soup = bs4.BeautifulSoup(paper_page.read().decode('utf8'))
except:
print "Error"
else:
# TODO: Check if this pattern holds for all papers
file = soup.find("a", {"accesskey" : "f"})
if file:
file_url = file["href"]
print os.path.join(save_dir, str(paper_id) + ".pdf")
urllib.urlretrieve(BASE_URL + file_url, os.path.join(save_dir, str(paper_id) + ".pdf"))
else:
print "Unable to find PDF: %d" % paper_id
def main():
if len(sys.argv) > 2 and sys.argv[1].isdigit() and os.path.isdir(sys.argv[2]):
get_pdf(int(sys.argv[1]), sys.argv[2])
else:
print "Usage <paper id> <destination directory>"
if __name__ == "__main__": main()
|
<commit_before>import sys
import os
import bs4
import urllib2
import urllib
BASE_URL = "http://arxiv.org"
HEP_URL = 'http://arxiv.org/abs/hep-th/%d'
# TODO: Change prints to logs
def get_pdf(paper_id, save_dir):
try:
paper_page = urllib2.urlopen(HEP_URL % paper_id)
soup = bs4.BeautifulSoup(paper_page.read().decode('utf8'))
except:
print "Error"
else:
# TODO: Check if this pattern holds for all papers
file = soup.find("a", {"accesskey" : "f"})
if file:
file_url = file["href"]
print os.path.join(save_dir, str(paper_id) + ".pdf")
urllib.urlretrieve(BASE_URL + file_url, os.path.join(save_dir, str(paper_id) + ".pdf"))
else:
print "Unable to find PDF: %d" % paper_id
def main():
if len(sys.argv) > 2 and sys.argv[1].isdigit() and os.path.isdir(sys.argv[2]):
get_pdf(int(sys.argv[1]), sys.argv[2])
else:
print "Usage <paper id> <destination directory>"
if __name__ == "__main__": main()
<commit_msg>Update arxiv script to prevent dup downloads<commit_after>import sys
import os
import bs4
import urllib2
import urllib
BASE_URL = "http://arxiv.org"
HEP_URL = 'http://arxiv.org/abs/hep-th/%d'
# TODO: Change prints to logs
def get_pdf(paper_id, save_dir):
file_path = os.path.join(save_dir, str(paper_id) + ".pdf")
if not os.path.isfile(file_path):
# Only try to download missing files
try:
paper_page = urllib2.urlopen(HEP_URL % paper_id)
soup = bs4.BeautifulSoup(paper_page.read().decode('utf8'))
except:
print "Error"
else:
# TODO: Check if this pattern holds for all papers
file = soup.find("a", {"accesskey" : "f"})
if file:
file_url = file["href"]
print os.path.join(save_dir, str(paper_id) + ".pdf")
urllib.urlretrieve(BASE_URL + file_url, os.path.join(save_dir, str(paper_id) + ".pdf"))
else:
print "Unable to find PDF: %d" % paper_id
def main():
if len(sys.argv) > 2 and sys.argv[1].isdigit() and os.path.isdir(sys.argv[2]):
get_pdf(int(sys.argv[1]), sys.argv[2])
else:
print "Usage <paper id> <destination directory>"
if __name__ == "__main__": main()
|
3ec2c5c7d30b69431d6703dafc4e9b0465b64ef9
|
lemur/migrations/versions/3097d57f3f0b_.py
|
lemur/migrations/versions/3097d57f3f0b_.py
|
"""Add new Indexes for faster searching
Revision ID: 3097d57f3f0b
Revises: 4fe230f7a26e
Create Date: 2021-06-19 20:18:55.332165
"""
# revision identifiers, used by Alembic.
revision = '3097d57f3f0b'
down_revision = '4fe230f7a26e'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_index(
'ix_root_authority_id',
'certificates',
['root_authority_id'],
unique=False,
postgresql_where=sqlalchemy.text("root_authority_id IS NOT NULL"))
op.create_index(
'certificate_associations_certificate_id_idx',
'certificate_associations',
['certificate_id'],
unique=False)
op.create_index(
'ix_certificates_serial',
'certificates',
['serial'],
unique=False)
def downgrade():
op.drop_index(
'ix_root_authority_id',
table_name='certificates')
op.drop_index(
'certificate_associations_certificate_id_idx',
table_name='certificate_associations')
op.drop_index(
'ix_certificates_serial',
table_name='certificates')
|
"""Add new Indexes for faster searching
Revision ID: 3097d57f3f0b
Revises: 4fe230f7a26e
Create Date: 2021-06-19 20:18:55.332165
"""
# revision identifiers, used by Alembic.
revision = '3097d57f3f0b'
down_revision = '4fe230f7a26e'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_index(
'ix_root_authority_id',
'certificates',
['root_authority_id'],
unique=False,
postgresql_where=sa.text("root_authority_id IS NOT NULL"))
op.create_index(
'certificate_associations_certificate_id_idx',
'certificate_associations',
['certificate_id'],
unique=False)
op.create_index(
'ix_certificates_serial',
'certificates',
['serial'],
unique=False)
def downgrade():
op.drop_index(
'ix_root_authority_id',
table_name='certificates')
op.drop_index(
'certificate_associations_certificate_id_idx',
table_name='certificate_associations')
op.drop_index(
'ix_certificates_serial',
table_name='certificates')
|
Fix sqlalchemy import alias in DB migration file
|
Fix sqlalchemy import alias in DB migration file
|
Python
|
apache-2.0
|
Netflix/lemur,Netflix/lemur,Netflix/lemur,Netflix/lemur
|
"""Add new Indexes for faster searching
Revision ID: 3097d57f3f0b
Revises: 4fe230f7a26e
Create Date: 2021-06-19 20:18:55.332165
"""
# revision identifiers, used by Alembic.
revision = '3097d57f3f0b'
down_revision = '4fe230f7a26e'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_index(
'ix_root_authority_id',
'certificates',
['root_authority_id'],
unique=False,
postgresql_where=sqlalchemy.text("root_authority_id IS NOT NULL"))
op.create_index(
'certificate_associations_certificate_id_idx',
'certificate_associations',
['certificate_id'],
unique=False)
op.create_index(
'ix_certificates_serial',
'certificates',
['serial'],
unique=False)
def downgrade():
op.drop_index(
'ix_root_authority_id',
table_name='certificates')
op.drop_index(
'certificate_associations_certificate_id_idx',
table_name='certificate_associations')
op.drop_index(
'ix_certificates_serial',
table_name='certificates')
Fix sqlalchemy import alias in DB migration file
|
"""Add new Indexes for faster searching
Revision ID: 3097d57f3f0b
Revises: 4fe230f7a26e
Create Date: 2021-06-19 20:18:55.332165
"""
# revision identifiers, used by Alembic.
revision = '3097d57f3f0b'
down_revision = '4fe230f7a26e'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_index(
'ix_root_authority_id',
'certificates',
['root_authority_id'],
unique=False,
postgresql_where=sa.text("root_authority_id IS NOT NULL"))
op.create_index(
'certificate_associations_certificate_id_idx',
'certificate_associations',
['certificate_id'],
unique=False)
op.create_index(
'ix_certificates_serial',
'certificates',
['serial'],
unique=False)
def downgrade():
op.drop_index(
'ix_root_authority_id',
table_name='certificates')
op.drop_index(
'certificate_associations_certificate_id_idx',
table_name='certificate_associations')
op.drop_index(
'ix_certificates_serial',
table_name='certificates')
|
<commit_before>"""Add new Indexes for faster searching
Revision ID: 3097d57f3f0b
Revises: 4fe230f7a26e
Create Date: 2021-06-19 20:18:55.332165
"""
# revision identifiers, used by Alembic.
revision = '3097d57f3f0b'
down_revision = '4fe230f7a26e'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_index(
'ix_root_authority_id',
'certificates',
['root_authority_id'],
unique=False,
postgresql_where=sqlalchemy.text("root_authority_id IS NOT NULL"))
op.create_index(
'certificate_associations_certificate_id_idx',
'certificate_associations',
['certificate_id'],
unique=False)
op.create_index(
'ix_certificates_serial',
'certificates',
['serial'],
unique=False)
def downgrade():
op.drop_index(
'ix_root_authority_id',
table_name='certificates')
op.drop_index(
'certificate_associations_certificate_id_idx',
table_name='certificate_associations')
op.drop_index(
'ix_certificates_serial',
table_name='certificates')
<commit_msg>Fix sqlalchemy import alias in DB migration file<commit_after>
|
"""Add new Indexes for faster searching
Revision ID: 3097d57f3f0b
Revises: 4fe230f7a26e
Create Date: 2021-06-19 20:18:55.332165
"""
# revision identifiers, used by Alembic.
revision = '3097d57f3f0b'
down_revision = '4fe230f7a26e'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_index(
'ix_root_authority_id',
'certificates',
['root_authority_id'],
unique=False,
postgresql_where=sa.text("root_authority_id IS NOT NULL"))
op.create_index(
'certificate_associations_certificate_id_idx',
'certificate_associations',
['certificate_id'],
unique=False)
op.create_index(
'ix_certificates_serial',
'certificates',
['serial'],
unique=False)
def downgrade():
op.drop_index(
'ix_root_authority_id',
table_name='certificates')
op.drop_index(
'certificate_associations_certificate_id_idx',
table_name='certificate_associations')
op.drop_index(
'ix_certificates_serial',
table_name='certificates')
|
"""Add new Indexes for faster searching
Revision ID: 3097d57f3f0b
Revises: 4fe230f7a26e
Create Date: 2021-06-19 20:18:55.332165
"""
# revision identifiers, used by Alembic.
revision = '3097d57f3f0b'
down_revision = '4fe230f7a26e'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_index(
'ix_root_authority_id',
'certificates',
['root_authority_id'],
unique=False,
postgresql_where=sqlalchemy.text("root_authority_id IS NOT NULL"))
op.create_index(
'certificate_associations_certificate_id_idx',
'certificate_associations',
['certificate_id'],
unique=False)
op.create_index(
'ix_certificates_serial',
'certificates',
['serial'],
unique=False)
def downgrade():
op.drop_index(
'ix_root_authority_id',
table_name='certificates')
op.drop_index(
'certificate_associations_certificate_id_idx',
table_name='certificate_associations')
op.drop_index(
'ix_certificates_serial',
table_name='certificates')
Fix sqlalchemy import alias in DB migration file"""Add new Indexes for faster searching
Revision ID: 3097d57f3f0b
Revises: 4fe230f7a26e
Create Date: 2021-06-19 20:18:55.332165
"""
# revision identifiers, used by Alembic.
revision = '3097d57f3f0b'
down_revision = '4fe230f7a26e'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_index(
'ix_root_authority_id',
'certificates',
['root_authority_id'],
unique=False,
postgresql_where=sa.text("root_authority_id IS NOT NULL"))
op.create_index(
'certificate_associations_certificate_id_idx',
'certificate_associations',
['certificate_id'],
unique=False)
op.create_index(
'ix_certificates_serial',
'certificates',
['serial'],
unique=False)
def downgrade():
op.drop_index(
'ix_root_authority_id',
table_name='certificates')
op.drop_index(
'certificate_associations_certificate_id_idx',
table_name='certificate_associations')
op.drop_index(
'ix_certificates_serial',
table_name='certificates')
|
<commit_before>"""Add new Indexes for faster searching
Revision ID: 3097d57f3f0b
Revises: 4fe230f7a26e
Create Date: 2021-06-19 20:18:55.332165
"""
# revision identifiers, used by Alembic.
revision = '3097d57f3f0b'
down_revision = '4fe230f7a26e'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_index(
'ix_root_authority_id',
'certificates',
['root_authority_id'],
unique=False,
postgresql_where=sqlalchemy.text("root_authority_id IS NOT NULL"))
op.create_index(
'certificate_associations_certificate_id_idx',
'certificate_associations',
['certificate_id'],
unique=False)
op.create_index(
'ix_certificates_serial',
'certificates',
['serial'],
unique=False)
def downgrade():
op.drop_index(
'ix_root_authority_id',
table_name='certificates')
op.drop_index(
'certificate_associations_certificate_id_idx',
table_name='certificate_associations')
op.drop_index(
'ix_certificates_serial',
table_name='certificates')
<commit_msg>Fix sqlalchemy import alias in DB migration file<commit_after>"""Add new Indexes for faster searching
Revision ID: 3097d57f3f0b
Revises: 4fe230f7a26e
Create Date: 2021-06-19 20:18:55.332165
"""
# revision identifiers, used by Alembic.
revision = '3097d57f3f0b'
down_revision = '4fe230f7a26e'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_index(
'ix_root_authority_id',
'certificates',
['root_authority_id'],
unique=False,
postgresql_where=sa.text("root_authority_id IS NOT NULL"))
op.create_index(
'certificate_associations_certificate_id_idx',
'certificate_associations',
['certificate_id'],
unique=False)
op.create_index(
'ix_certificates_serial',
'certificates',
['serial'],
unique=False)
def downgrade():
op.drop_index(
'ix_root_authority_id',
table_name='certificates')
op.drop_index(
'certificate_associations_certificate_id_idx',
table_name='certificate_associations')
op.drop_index(
'ix_certificates_serial',
table_name='certificates')
|
69f7490b6ed28c28784148295dec2144344f4ed8
|
config.py
|
config.py
|
import os
if os.environ.get('DATABASE_URL') is None:
SQLALCHEMY_DATABASE_URI = 'sqlite:///meetup.db'
else:
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
SQLALCHEMY_TRACK_MODIFICATIONS = False # supress deprecation warning
ACCESS_TOKEN = os.environ['ACCESS_TOKEN']
PAGE_ID = os.environ['PAGE_ID']
APP_ID = os.environ['APP_ID']
VERIFY_TOKEN = os.environ['VERIFY_TOKEN']
|
import os
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
SQLALCHEMY_TRACK_MODIFICATIONS = False # suppress deprecation warning
ACCESS_TOKEN = os.environ['ACCESS_TOKEN']
PAGE_ID = os.environ['PAGE_ID']
APP_ID = os.environ['APP_ID']
VERIFY_TOKEN = os.environ['VERIFY_TOKEN']
|
Remove automatic fallback to SQLite
|
Remove automatic fallback to SQLite
It's better to be explicit if there's no DATABASE_URL.
|
Python
|
mit
|
Stark-Mountain/meetup-facebook-bot,Stark-Mountain/meetup-facebook-bot
|
import os
if os.environ.get('DATABASE_URL') is None:
SQLALCHEMY_DATABASE_URI = 'sqlite:///meetup.db'
else:
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
SQLALCHEMY_TRACK_MODIFICATIONS = False # supress deprecation warning
ACCESS_TOKEN = os.environ['ACCESS_TOKEN']
PAGE_ID = os.environ['PAGE_ID']
APP_ID = os.environ['APP_ID']
VERIFY_TOKEN = os.environ['VERIFY_TOKEN']
Remove automatic fallback to SQLite
It's better to be explicit if there's no DATABASE_URL.
|
import os
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
SQLALCHEMY_TRACK_MODIFICATIONS = False # suppress deprecation warning
ACCESS_TOKEN = os.environ['ACCESS_TOKEN']
PAGE_ID = os.environ['PAGE_ID']
APP_ID = os.environ['APP_ID']
VERIFY_TOKEN = os.environ['VERIFY_TOKEN']
|
<commit_before>import os
if os.environ.get('DATABASE_URL') is None:
SQLALCHEMY_DATABASE_URI = 'sqlite:///meetup.db'
else:
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
SQLALCHEMY_TRACK_MODIFICATIONS = False # supress deprecation warning
ACCESS_TOKEN = os.environ['ACCESS_TOKEN']
PAGE_ID = os.environ['PAGE_ID']
APP_ID = os.environ['APP_ID']
VERIFY_TOKEN = os.environ['VERIFY_TOKEN']
<commit_msg>Remove automatic fallback to SQLite
It's better to be explicit if there's no DATABASE_URL.<commit_after>
|
import os
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
SQLALCHEMY_TRACK_MODIFICATIONS = False # suppress deprecation warning
ACCESS_TOKEN = os.environ['ACCESS_TOKEN']
PAGE_ID = os.environ['PAGE_ID']
APP_ID = os.environ['APP_ID']
VERIFY_TOKEN = os.environ['VERIFY_TOKEN']
|
import os
if os.environ.get('DATABASE_URL') is None:
SQLALCHEMY_DATABASE_URI = 'sqlite:///meetup.db'
else:
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
SQLALCHEMY_TRACK_MODIFICATIONS = False # supress deprecation warning
ACCESS_TOKEN = os.environ['ACCESS_TOKEN']
PAGE_ID = os.environ['PAGE_ID']
APP_ID = os.environ['APP_ID']
VERIFY_TOKEN = os.environ['VERIFY_TOKEN']
Remove automatic fallback to SQLite
It's better to be explicit if there's no DATABASE_URL.import os
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
SQLALCHEMY_TRACK_MODIFICATIONS = False # suppress deprecation warning
ACCESS_TOKEN = os.environ['ACCESS_TOKEN']
PAGE_ID = os.environ['PAGE_ID']
APP_ID = os.environ['APP_ID']
VERIFY_TOKEN = os.environ['VERIFY_TOKEN']
|
<commit_before>import os
if os.environ.get('DATABASE_URL') is None:
SQLALCHEMY_DATABASE_URI = 'sqlite:///meetup.db'
else:
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
SQLALCHEMY_TRACK_MODIFICATIONS = False # supress deprecation warning
ACCESS_TOKEN = os.environ['ACCESS_TOKEN']
PAGE_ID = os.environ['PAGE_ID']
APP_ID = os.environ['APP_ID']
VERIFY_TOKEN = os.environ['VERIFY_TOKEN']
<commit_msg>Remove automatic fallback to SQLite
It's better to be explicit if there's no DATABASE_URL.<commit_after>import os
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
SQLALCHEMY_TRACK_MODIFICATIONS = False # suppress deprecation warning
ACCESS_TOKEN = os.environ['ACCESS_TOKEN']
PAGE_ID = os.environ['PAGE_ID']
APP_ID = os.environ['APP_ID']
VERIFY_TOKEN = os.environ['VERIFY_TOKEN']
|
ab1a2982b6a44bfcfcaff5a3469f2d85f56a86a4
|
src/cli/_dbus/_manager.py
|
src/cli/_dbus/_manager.py
|
"""
Manager interface.
"""
class Manager(object):
"""
Manager interface.
"""
_INTERFACE_NAME = 'org.storage.stratis1.Manager'
def __init__(self, dbus_object):
"""
Initializer.
:param dbus_object: the dbus object
"""
self._dbus_object = dbus_object
def CreatePool(self, pool_name, devices, num_devices):
"""
Create a pool.
:param str pool_name: the pool name
:param devices: the component devices
:type devices: sequence of str
"""
return self._dbus_object.CreatePool(
pool_name,
devices,
num_devices,
dbus_interface=self._INTERFACE_NAME,
)
def DestroyPool(self, pool_name):
"""
Destroy a pool.
:param str pool_name: the name of the pool
"""
return self._dbus_object.DestroyPool(
pool_name,
dbus_interface=self._INTERFACE_NAME
)
def ListPools(self):
"""
List all pools.
"""
return self._dbus_object.ListPools(dbus_interface=self._INTERFACE_NAME)
|
"""
Manager interface.
"""
from ._properties import Properties
class Manager(object):
"""
Manager interface.
"""
_INTERFACE_NAME = 'org.storage.stratis1.Manager'
def __init__(self, dbus_object):
"""
Initializer.
:param dbus_object: the dbus object
"""
self._dbus_object = dbus_object
def CreatePool(self, pool_name, devices, num_devices):
"""
Create a pool.
:param str pool_name: the pool name
:param devices: the component devices
:type devices: sequence of str
"""
return self._dbus_object.CreatePool(
pool_name,
devices,
num_devices,
dbus_interface=self._INTERFACE_NAME,
)
def DestroyPool(self, pool_name):
"""
Destroy a pool.
:param str pool_name: the name of the pool
"""
return self._dbus_object.DestroyPool(
pool_name,
dbus_interface=self._INTERFACE_NAME
)
def ListPools(self):
"""
List all pools.
"""
return self._dbus_object.ListPools(dbus_interface=self._INTERFACE_NAME)
@property
def Version(self):
"""
Stratisd Version getter.
:rtype: String
"""
return Properties(self._dbus_object).Get(
self._INTERFACE_NAME,
'Version'
)
@property
def LogLevel(self):
"""
Stratisd LogLevel getter.
:rtype: String
"""
return Properties(self._dbus_object).Get(
self._INTERFACE_NAME,
'LogLevel'
)
@LogLevel.setter
def LogLevel(self, value):
"""
Stratisd LogLevel setter.
:param str value: the value to set
"""
return Properties(self._dbus_object).Set(
self._INTERFACE_NAME,
'LogLevel',
value
)
|
Use Properties interface to get Manager properties.
|
Use Properties interface to get Manager properties.
Signed-off-by: mulhern <7b51bcf507bcd7afb72bf8663752c0ddbeb517f6@redhat.com>
|
Python
|
apache-2.0
|
stratis-storage/stratis-cli,stratis-storage/stratis-cli
|
"""
Manager interface.
"""
class Manager(object):
"""
Manager interface.
"""
_INTERFACE_NAME = 'org.storage.stratis1.Manager'
def __init__(self, dbus_object):
"""
Initializer.
:param dbus_object: the dbus object
"""
self._dbus_object = dbus_object
def CreatePool(self, pool_name, devices, num_devices):
"""
Create a pool.
:param str pool_name: the pool name
:param devices: the component devices
:type devices: sequence of str
"""
return self._dbus_object.CreatePool(
pool_name,
devices,
num_devices,
dbus_interface=self._INTERFACE_NAME,
)
def DestroyPool(self, pool_name):
"""
Destroy a pool.
:param str pool_name: the name of the pool
"""
return self._dbus_object.DestroyPool(
pool_name,
dbus_interface=self._INTERFACE_NAME
)
def ListPools(self):
"""
List all pools.
"""
return self._dbus_object.ListPools(dbus_interface=self._INTERFACE_NAME)
Use Properties interface to get Manager properties.
Signed-off-by: mulhern <7b51bcf507bcd7afb72bf8663752c0ddbeb517f6@redhat.com>
|
"""
Manager interface.
"""
from ._properties import Properties
class Manager(object):
"""
Manager interface.
"""
_INTERFACE_NAME = 'org.storage.stratis1.Manager'
def __init__(self, dbus_object):
"""
Initializer.
:param dbus_object: the dbus object
"""
self._dbus_object = dbus_object
def CreatePool(self, pool_name, devices, num_devices):
"""
Create a pool.
:param str pool_name: the pool name
:param devices: the component devices
:type devices: sequence of str
"""
return self._dbus_object.CreatePool(
pool_name,
devices,
num_devices,
dbus_interface=self._INTERFACE_NAME,
)
def DestroyPool(self, pool_name):
"""
Destroy a pool.
:param str pool_name: the name of the pool
"""
return self._dbus_object.DestroyPool(
pool_name,
dbus_interface=self._INTERFACE_NAME
)
def ListPools(self):
"""
List all pools.
"""
return self._dbus_object.ListPools(dbus_interface=self._INTERFACE_NAME)
@property
def Version(self):
"""
Stratisd Version getter.
:rtype: String
"""
return Properties(self._dbus_object).Get(
self._INTERFACE_NAME,
'Version'
)
@property
def LogLevel(self):
"""
Stratisd LogLevel getter.
:rtype: String
"""
return Properties(self._dbus_object).Get(
self._INTERFACE_NAME,
'LogLevel'
)
@LogLevel.setter
def LogLevel(self, value):
"""
Stratisd LogLevel setter.
:param str value: the value to set
"""
return Properties(self._dbus_object).Set(
self._INTERFACE_NAME,
'LogLevel',
value
)
|
<commit_before>"""
Manager interface.
"""
class Manager(object):
"""
Manager interface.
"""
_INTERFACE_NAME = 'org.storage.stratis1.Manager'
def __init__(self, dbus_object):
"""
Initializer.
:param dbus_object: the dbus object
"""
self._dbus_object = dbus_object
def CreatePool(self, pool_name, devices, num_devices):
"""
Create a pool.
:param str pool_name: the pool name
:param devices: the component devices
:type devices: sequence of str
"""
return self._dbus_object.CreatePool(
pool_name,
devices,
num_devices,
dbus_interface=self._INTERFACE_NAME,
)
def DestroyPool(self, pool_name):
"""
Destroy a pool.
:param str pool_name: the name of the pool
"""
return self._dbus_object.DestroyPool(
pool_name,
dbus_interface=self._INTERFACE_NAME
)
def ListPools(self):
"""
List all pools.
"""
return self._dbus_object.ListPools(dbus_interface=self._INTERFACE_NAME)
<commit_msg>Use Properties interface to get Manager properties.
Signed-off-by: mulhern <7b51bcf507bcd7afb72bf8663752c0ddbeb517f6@redhat.com><commit_after>
|
"""
Manager interface.
"""
from ._properties import Properties
class Manager(object):
"""
Manager interface.
"""
_INTERFACE_NAME = 'org.storage.stratis1.Manager'
def __init__(self, dbus_object):
"""
Initializer.
:param dbus_object: the dbus object
"""
self._dbus_object = dbus_object
def CreatePool(self, pool_name, devices, num_devices):
"""
Create a pool.
:param str pool_name: the pool name
:param devices: the component devices
:type devices: sequence of str
"""
return self._dbus_object.CreatePool(
pool_name,
devices,
num_devices,
dbus_interface=self._INTERFACE_NAME,
)
def DestroyPool(self, pool_name):
"""
Destroy a pool.
:param str pool_name: the name of the pool
"""
return self._dbus_object.DestroyPool(
pool_name,
dbus_interface=self._INTERFACE_NAME
)
def ListPools(self):
"""
List all pools.
"""
return self._dbus_object.ListPools(dbus_interface=self._INTERFACE_NAME)
@property
def Version(self):
"""
Stratisd Version getter.
:rtype: String
"""
return Properties(self._dbus_object).Get(
self._INTERFACE_NAME,
'Version'
)
@property
def LogLevel(self):
"""
Stratisd LogLevel getter.
:rtype: String
"""
return Properties(self._dbus_object).Get(
self._INTERFACE_NAME,
'LogLevel'
)
@LogLevel.setter
def LogLevel(self, value):
"""
Stratisd LogLevel setter.
:param str value: the value to set
"""
return Properties(self._dbus_object).Set(
self._INTERFACE_NAME,
'LogLevel',
value
)
|
"""
Manager interface.
"""
class Manager(object):
"""
Manager interface.
"""
_INTERFACE_NAME = 'org.storage.stratis1.Manager'
def __init__(self, dbus_object):
"""
Initializer.
:param dbus_object: the dbus object
"""
self._dbus_object = dbus_object
def CreatePool(self, pool_name, devices, num_devices):
"""
Create a pool.
:param str pool_name: the pool name
:param devices: the component devices
:type devices: sequence of str
"""
return self._dbus_object.CreatePool(
pool_name,
devices,
num_devices,
dbus_interface=self._INTERFACE_NAME,
)
def DestroyPool(self, pool_name):
"""
Destroy a pool.
:param str pool_name: the name of the pool
"""
return self._dbus_object.DestroyPool(
pool_name,
dbus_interface=self._INTERFACE_NAME
)
def ListPools(self):
"""
List all pools.
"""
return self._dbus_object.ListPools(dbus_interface=self._INTERFACE_NAME)
Use Properties interface to get Manager properties.
Signed-off-by: mulhern <7b51bcf507bcd7afb72bf8663752c0ddbeb517f6@redhat.com>"""
Manager interface.
"""
from ._properties import Properties
class Manager(object):
"""
Manager interface.
"""
_INTERFACE_NAME = 'org.storage.stratis1.Manager'
def __init__(self, dbus_object):
"""
Initializer.
:param dbus_object: the dbus object
"""
self._dbus_object = dbus_object
def CreatePool(self, pool_name, devices, num_devices):
"""
Create a pool.
:param str pool_name: the pool name
:param devices: the component devices
:type devices: sequence of str
"""
return self._dbus_object.CreatePool(
pool_name,
devices,
num_devices,
dbus_interface=self._INTERFACE_NAME,
)
def DestroyPool(self, pool_name):
"""
Destroy a pool.
:param str pool_name: the name of the pool
"""
return self._dbus_object.DestroyPool(
pool_name,
dbus_interface=self._INTERFACE_NAME
)
def ListPools(self):
"""
List all pools.
"""
return self._dbus_object.ListPools(dbus_interface=self._INTERFACE_NAME)
@property
def Version(self):
"""
Stratisd Version getter.
:rtype: String
"""
return Properties(self._dbus_object).Get(
self._INTERFACE_NAME,
'Version'
)
@property
def LogLevel(self):
"""
Stratisd LogLevel getter.
:rtype: String
"""
return Properties(self._dbus_object).Get(
self._INTERFACE_NAME,
'LogLevel'
)
@LogLevel.setter
def LogLevel(self, value):
"""
Stratisd LogLevel setter.
:param str value: the value to set
"""
return Properties(self._dbus_object).Set(
self._INTERFACE_NAME,
'LogLevel',
value
)
|
<commit_before>"""
Manager interface.
"""
class Manager(object):
"""
Manager interface.
"""
_INTERFACE_NAME = 'org.storage.stratis1.Manager'
def __init__(self, dbus_object):
"""
Initializer.
:param dbus_object: the dbus object
"""
self._dbus_object = dbus_object
def CreatePool(self, pool_name, devices, num_devices):
"""
Create a pool.
:param str pool_name: the pool name
:param devices: the component devices
:type devices: sequence of str
"""
return self._dbus_object.CreatePool(
pool_name,
devices,
num_devices,
dbus_interface=self._INTERFACE_NAME,
)
def DestroyPool(self, pool_name):
"""
Destroy a pool.
:param str pool_name: the name of the pool
"""
return self._dbus_object.DestroyPool(
pool_name,
dbus_interface=self._INTERFACE_NAME
)
def ListPools(self):
"""
List all pools.
"""
return self._dbus_object.ListPools(dbus_interface=self._INTERFACE_NAME)
<commit_msg>Use Properties interface to get Manager properties.
Signed-off-by: mulhern <7b51bcf507bcd7afb72bf8663752c0ddbeb517f6@redhat.com><commit_after>"""
Manager interface.
"""
from ._properties import Properties
class Manager(object):
"""
Manager interface.
"""
_INTERFACE_NAME = 'org.storage.stratis1.Manager'
def __init__(self, dbus_object):
"""
Initializer.
:param dbus_object: the dbus object
"""
self._dbus_object = dbus_object
def CreatePool(self, pool_name, devices, num_devices):
"""
Create a pool.
:param str pool_name: the pool name
:param devices: the component devices
:type devices: sequence of str
"""
return self._dbus_object.CreatePool(
pool_name,
devices,
num_devices,
dbus_interface=self._INTERFACE_NAME,
)
def DestroyPool(self, pool_name):
"""
Destroy a pool.
:param str pool_name: the name of the pool
"""
return self._dbus_object.DestroyPool(
pool_name,
dbus_interface=self._INTERFACE_NAME
)
def ListPools(self):
"""
List all pools.
"""
return self._dbus_object.ListPools(dbus_interface=self._INTERFACE_NAME)
@property
def Version(self):
"""
Stratisd Version getter.
:rtype: String
"""
return Properties(self._dbus_object).Get(
self._INTERFACE_NAME,
'Version'
)
@property
def LogLevel(self):
"""
Stratisd LogLevel getter.
:rtype: String
"""
return Properties(self._dbus_object).Get(
self._INTERFACE_NAME,
'LogLevel'
)
@LogLevel.setter
def LogLevel(self, value):
"""
Stratisd LogLevel setter.
:param str value: the value to set
"""
return Properties(self._dbus_object).Set(
self._INTERFACE_NAME,
'LogLevel',
value
)
|
bdc554d18dc67cd4979bac3bc5d4b7d01b23b8b4
|
grako/rendering.py
|
grako/rendering.py
|
# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import, unicode_literals
import itertools
from .util import trim
def render(item, **fields):
""" Render the given item
"""
if item is None:
return ''
elif isinstance(item, Renderer):
return item.render(**fields)
elif isinstance(item, list):
return ''.join(render(e) for e in item)
else:
return str(item)
class Renderer(object):
template = ''
_counter = itertools.count()
def __init__(self, template=None):
if template is not None:
self.template = template
def counter(self):
return next(self._counter)
def render_fields(self, fields):
pass
def render(self, template=None, **fields):
fields.update({k:v for k, v in vars(self).items() if not k.startswith('_')})
self.render_fields(fields)
if template is None:
template = self.template
fields = {k:render(v) for k, v in fields.items()}
try:
return trim(template).format(**fields)
except KeyError as e:
raise KeyError(str(e), type(self))
|
# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import, unicode_literals
import itertools
from .util import trim
def render(item, **fields):
""" Render the given item
"""
if item is None:
return ''
elif isinstance(item, Renderer):
return item.render(**fields)
elif isinstance(item, list):
return ''.join(render(e) for e in item)
else:
return str(item)
class Renderer(object):
template = ''
_counter = itertools.count()
def __init__(self, template=None):
if template is not None:
self.template = template
def counter(self):
return next(self._counter)
def render_fields(self, fields):
pass
def render(self, template=None, **kwargs):
fields = ({k:v for k, v in vars(self).items() if not k.startswith('_')})
override = self.render_fields(fields)
if template is None:
if override is not None:
template = override
else:
template = self.template
fields.update(kwargs)
fields = {k:render(v) for k, v in fields.items()}
try:
return trim(template).format(**fields)
except KeyError as e:
raise KeyError(str(e), type(self))
|
Allow override of template through return value of render_fields.
|
Allow override of template through return value of render_fields.
|
Python
|
bsd-2-clause
|
swayf/grako,swayf/grako
|
# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import, unicode_literals
import itertools
from .util import trim
def render(item, **fields):
""" Render the given item
"""
if item is None:
return ''
elif isinstance(item, Renderer):
return item.render(**fields)
elif isinstance(item, list):
return ''.join(render(e) for e in item)
else:
return str(item)
class Renderer(object):
template = ''
_counter = itertools.count()
def __init__(self, template=None):
if template is not None:
self.template = template
def counter(self):
return next(self._counter)
def render_fields(self, fields):
pass
def render(self, template=None, **fields):
fields.update({k:v for k, v in vars(self).items() if not k.startswith('_')})
self.render_fields(fields)
if template is None:
template = self.template
fields = {k:render(v) for k, v in fields.items()}
try:
return trim(template).format(**fields)
except KeyError as e:
raise KeyError(str(e), type(self))
Allow override of template through return value of render_fields.
|
# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import, unicode_literals
import itertools
from .util import trim
def render(item, **fields):
""" Render the given item
"""
if item is None:
return ''
elif isinstance(item, Renderer):
return item.render(**fields)
elif isinstance(item, list):
return ''.join(render(e) for e in item)
else:
return str(item)
class Renderer(object):
template = ''
_counter = itertools.count()
def __init__(self, template=None):
if template is not None:
self.template = template
def counter(self):
return next(self._counter)
def render_fields(self, fields):
pass
def render(self, template=None, **kwargs):
fields = ({k:v for k, v in vars(self).items() if not k.startswith('_')})
override = self.render_fields(fields)
if template is None:
if override is not None:
template = override
else:
template = self.template
fields.update(kwargs)
fields = {k:render(v) for k, v in fields.items()}
try:
return trim(template).format(**fields)
except KeyError as e:
raise KeyError(str(e), type(self))
|
<commit_before># -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import, unicode_literals
import itertools
from .util import trim
def render(item, **fields):
""" Render the given item
"""
if item is None:
return ''
elif isinstance(item, Renderer):
return item.render(**fields)
elif isinstance(item, list):
return ''.join(render(e) for e in item)
else:
return str(item)
class Renderer(object):
template = ''
_counter = itertools.count()
def __init__(self, template=None):
if template is not None:
self.template = template
def counter(self):
return next(self._counter)
def render_fields(self, fields):
pass
def render(self, template=None, **fields):
fields.update({k:v for k, v in vars(self).items() if not k.startswith('_')})
self.render_fields(fields)
if template is None:
template = self.template
fields = {k:render(v) for k, v in fields.items()}
try:
return trim(template).format(**fields)
except KeyError as e:
raise KeyError(str(e), type(self))
<commit_msg>Allow override of template through return value of render_fields.<commit_after>
|
# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import, unicode_literals
import itertools
from .util import trim
def render(item, **fields):
""" Render the given item
"""
if item is None:
return ''
elif isinstance(item, Renderer):
return item.render(**fields)
elif isinstance(item, list):
return ''.join(render(e) for e in item)
else:
return str(item)
class Renderer(object):
template = ''
_counter = itertools.count()
def __init__(self, template=None):
if template is not None:
self.template = template
def counter(self):
return next(self._counter)
def render_fields(self, fields):
pass
def render(self, template=None, **kwargs):
fields = ({k:v for k, v in vars(self).items() if not k.startswith('_')})
override = self.render_fields(fields)
if template is None:
if override is not None:
template = override
else:
template = self.template
fields.update(kwargs)
fields = {k:render(v) for k, v in fields.items()}
try:
return trim(template).format(**fields)
except KeyError as e:
raise KeyError(str(e), type(self))
|
# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import, unicode_literals
import itertools
from .util import trim
def render(item, **fields):
""" Render the given item
"""
if item is None:
return ''
elif isinstance(item, Renderer):
return item.render(**fields)
elif isinstance(item, list):
return ''.join(render(e) for e in item)
else:
return str(item)
class Renderer(object):
template = ''
_counter = itertools.count()
def __init__(self, template=None):
if template is not None:
self.template = template
def counter(self):
return next(self._counter)
def render_fields(self, fields):
pass
def render(self, template=None, **fields):
fields.update({k:v for k, v in vars(self).items() if not k.startswith('_')})
self.render_fields(fields)
if template is None:
template = self.template
fields = {k:render(v) for k, v in fields.items()}
try:
return trim(template).format(**fields)
except KeyError as e:
raise KeyError(str(e), type(self))
Allow override of template through return value of render_fields.# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import, unicode_literals
import itertools
from .util import trim
def render(item, **fields):
""" Render the given item
"""
if item is None:
return ''
elif isinstance(item, Renderer):
return item.render(**fields)
elif isinstance(item, list):
return ''.join(render(e) for e in item)
else:
return str(item)
class Renderer(object):
template = ''
_counter = itertools.count()
def __init__(self, template=None):
if template is not None:
self.template = template
def counter(self):
return next(self._counter)
def render_fields(self, fields):
pass
def render(self, template=None, **kwargs):
fields = ({k:v for k, v in vars(self).items() if not k.startswith('_')})
override = self.render_fields(fields)
if template is None:
if override is not None:
template = override
else:
template = self.template
fields.update(kwargs)
fields = {k:render(v) for k, v in fields.items()}
try:
return trim(template).format(**fields)
except KeyError as e:
raise KeyError(str(e), type(self))
|
<commit_before># -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import, unicode_literals
import itertools
from .util import trim
def render(item, **fields):
""" Render the given item
"""
if item is None:
return ''
elif isinstance(item, Renderer):
return item.render(**fields)
elif isinstance(item, list):
return ''.join(render(e) for e in item)
else:
return str(item)
class Renderer(object):
template = ''
_counter = itertools.count()
def __init__(self, template=None):
if template is not None:
self.template = template
def counter(self):
return next(self._counter)
def render_fields(self, fields):
pass
def render(self, template=None, **fields):
fields.update({k:v for k, v in vars(self).items() if not k.startswith('_')})
self.render_fields(fields)
if template is None:
template = self.template
fields = {k:render(v) for k, v in fields.items()}
try:
return trim(template).format(**fields)
except KeyError as e:
raise KeyError(str(e), type(self))
<commit_msg>Allow override of template through return value of render_fields.<commit_after># -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import, unicode_literals
import itertools
from .util import trim
def render(item, **fields):
""" Render the given item
"""
if item is None:
return ''
elif isinstance(item, Renderer):
return item.render(**fields)
elif isinstance(item, list):
return ''.join(render(e) for e in item)
else:
return str(item)
class Renderer(object):
template = ''
_counter = itertools.count()
def __init__(self, template=None):
if template is not None:
self.template = template
def counter(self):
return next(self._counter)
def render_fields(self, fields):
pass
def render(self, template=None, **kwargs):
fields = ({k:v for k, v in vars(self).items() if not k.startswith('_')})
override = self.render_fields(fields)
if template is None:
if override is not None:
template = override
else:
template = self.template
fields.update(kwargs)
fields = {k:render(v) for k, v in fields.items()}
try:
return trim(template).format(**fields)
except KeyError as e:
raise KeyError(str(e), type(self))
|
f0984c9855a6283de27e717fad73bb4f1b6394ab
|
flatten-array/flatten_array.py
|
flatten-array/flatten_array.py
|
def flatten(lst):
"""Completely flatten an arbitrarily-deep list"""
return [*_flatten(lst)]
def _flatten(lst):
"""Generator for flattening arbitrarily-deep lists"""
if isinstance(lst, (list, tuple)):
for item in lst:
if item is None:
continue
else:
yield from _flatten(item)
else:
yield lst
|
def flatten(lst):
"""Completely flatten an arbitrarily-deep list"""
return [*_flatten(lst)]
def _flatten(lst):
"""Generator for flattening arbitrarily-deep lists"""
for item in lst:
if isinstance(item, (list, tuple)):
yield from _flatten(item)
elif item is not None:
yield item
|
Tidy and simplify generator code
|
Tidy and simplify generator code
|
Python
|
agpl-3.0
|
CubicComet/exercism-python-solutions
|
def flatten(lst):
"""Completely flatten an arbitrarily-deep list"""
return [*_flatten(lst)]
def _flatten(lst):
"""Generator for flattening arbitrarily-deep lists"""
if isinstance(lst, (list, tuple)):
for item in lst:
if item is None:
continue
else:
yield from _flatten(item)
else:
yield lst
Tidy and simplify generator code
|
def flatten(lst):
"""Completely flatten an arbitrarily-deep list"""
return [*_flatten(lst)]
def _flatten(lst):
"""Generator for flattening arbitrarily-deep lists"""
for item in lst:
if isinstance(item, (list, tuple)):
yield from _flatten(item)
elif item is not None:
yield item
|
<commit_before>def flatten(lst):
"""Completely flatten an arbitrarily-deep list"""
return [*_flatten(lst)]
def _flatten(lst):
"""Generator for flattening arbitrarily-deep lists"""
if isinstance(lst, (list, tuple)):
for item in lst:
if item is None:
continue
else:
yield from _flatten(item)
else:
yield lst
<commit_msg>Tidy and simplify generator code<commit_after>
|
def flatten(lst):
"""Completely flatten an arbitrarily-deep list"""
return [*_flatten(lst)]
def _flatten(lst):
"""Generator for flattening arbitrarily-deep lists"""
for item in lst:
if isinstance(item, (list, tuple)):
yield from _flatten(item)
elif item is not None:
yield item
|
def flatten(lst):
"""Completely flatten an arbitrarily-deep list"""
return [*_flatten(lst)]
def _flatten(lst):
"""Generator for flattening arbitrarily-deep lists"""
if isinstance(lst, (list, tuple)):
for item in lst:
if item is None:
continue
else:
yield from _flatten(item)
else:
yield lst
Tidy and simplify generator codedef flatten(lst):
"""Completely flatten an arbitrarily-deep list"""
return [*_flatten(lst)]
def _flatten(lst):
"""Generator for flattening arbitrarily-deep lists"""
for item in lst:
if isinstance(item, (list, tuple)):
yield from _flatten(item)
elif item is not None:
yield item
|
<commit_before>def flatten(lst):
"""Completely flatten an arbitrarily-deep list"""
return [*_flatten(lst)]
def _flatten(lst):
"""Generator for flattening arbitrarily-deep lists"""
if isinstance(lst, (list, tuple)):
for item in lst:
if item is None:
continue
else:
yield from _flatten(item)
else:
yield lst
<commit_msg>Tidy and simplify generator code<commit_after>def flatten(lst):
"""Completely flatten an arbitrarily-deep list"""
return [*_flatten(lst)]
def _flatten(lst):
"""Generator for flattening arbitrarily-deep lists"""
for item in lst:
if isinstance(item, (list, tuple)):
yield from _flatten(item)
elif item is not None:
yield item
|
8e6a835cf98212545d00f0967b6f6ce936143687
|
fluxghost/http_server_debug.py
|
fluxghost/http_server_debug.py
|
from multiprocessing import Process
import sys
from fluxghost.http_server_base import HttpServerBase, logger
def fork_entry(request, client, server):
from fluxghost.http_handler import HttpHandler
HttpHandler(request, client, server)
def check_autoreload():
if "fluxghost.http_handler" in sys.modules:
logger.error("Warning!! The fluxghost.http_handler has been "
"loaded before fork, auto-reload moudle function is"
" not work anymore.")
return
if "fluxclient" in sys.modules:
logger.error("Warning!! The fluxclient has been "
"loaded before fork, auto-reload moudle function is"
" not work anymore.")
return
class HttpServer(HttpServerBase):
def on_accept(self):
check_autoreload()
request, client = self.sock.accept()
w = Process(target=fork_entry, args=(request, client, self))
w.daemon = True
w.start()
|
from multiprocessing import Process
import sys
from fluxghost.http_server_base import HttpServerBase, logger
def fork_entry(request, client, server):
from fluxghost.http_handler import HttpHandler
HttpHandler(request, client, server)
def check_autoreload():
if "fluxghost.http_handler" in sys.modules:
logger.error("Warning!! The fluxghost.http_handler has been "
"loaded before fork, auto-reload moudle function is"
" not work anymore.")
return
if "fluxclient" in sys.modules:
logger.error("Warning!! The fluxclient has been "
"loaded before fork, auto-reload moudle function is"
" not work anymore.")
return
class HttpServer(HttpServerBase):
def on_accept(self):
check_autoreload()
request, client = self.sock.accept()
w = Process(target=fork_entry, args=(request, client, self))
w.daemon = True
w.start()
request.close()
|
Fix missing close socket error
|
Fix missing close socket error
|
Python
|
agpl-3.0
|
flux3dp/fluxghost,flux3dp/fluxghost,flux3dp/fluxghost,flux3dp/fluxghost
|
from multiprocessing import Process
import sys
from fluxghost.http_server_base import HttpServerBase, logger
def fork_entry(request, client, server):
from fluxghost.http_handler import HttpHandler
HttpHandler(request, client, server)
def check_autoreload():
if "fluxghost.http_handler" in sys.modules:
logger.error("Warning!! The fluxghost.http_handler has been "
"loaded before fork, auto-reload moudle function is"
" not work anymore.")
return
if "fluxclient" in sys.modules:
logger.error("Warning!! The fluxclient has been "
"loaded before fork, auto-reload moudle function is"
" not work anymore.")
return
class HttpServer(HttpServerBase):
def on_accept(self):
check_autoreload()
request, client = self.sock.accept()
w = Process(target=fork_entry, args=(request, client, self))
w.daemon = True
w.start()
Fix missing close socket error
|
from multiprocessing import Process
import sys
from fluxghost.http_server_base import HttpServerBase, logger
def fork_entry(request, client, server):
from fluxghost.http_handler import HttpHandler
HttpHandler(request, client, server)
def check_autoreload():
if "fluxghost.http_handler" in sys.modules:
logger.error("Warning!! The fluxghost.http_handler has been "
"loaded before fork, auto-reload moudle function is"
" not work anymore.")
return
if "fluxclient" in sys.modules:
logger.error("Warning!! The fluxclient has been "
"loaded before fork, auto-reload moudle function is"
" not work anymore.")
return
class HttpServer(HttpServerBase):
def on_accept(self):
check_autoreload()
request, client = self.sock.accept()
w = Process(target=fork_entry, args=(request, client, self))
w.daemon = True
w.start()
request.close()
|
<commit_before>
from multiprocessing import Process
import sys
from fluxghost.http_server_base import HttpServerBase, logger
def fork_entry(request, client, server):
from fluxghost.http_handler import HttpHandler
HttpHandler(request, client, server)
def check_autoreload():
if "fluxghost.http_handler" in sys.modules:
logger.error("Warning!! The fluxghost.http_handler has been "
"loaded before fork, auto-reload moudle function is"
" not work anymore.")
return
if "fluxclient" in sys.modules:
logger.error("Warning!! The fluxclient has been "
"loaded before fork, auto-reload moudle function is"
" not work anymore.")
return
class HttpServer(HttpServerBase):
def on_accept(self):
check_autoreload()
request, client = self.sock.accept()
w = Process(target=fork_entry, args=(request, client, self))
w.daemon = True
w.start()
<commit_msg>Fix missing close socket error<commit_after>
|
from multiprocessing import Process
import sys
from fluxghost.http_server_base import HttpServerBase, logger
def fork_entry(request, client, server):
from fluxghost.http_handler import HttpHandler
HttpHandler(request, client, server)
def check_autoreload():
if "fluxghost.http_handler" in sys.modules:
logger.error("Warning!! The fluxghost.http_handler has been "
"loaded before fork, auto-reload moudle function is"
" not work anymore.")
return
if "fluxclient" in sys.modules:
logger.error("Warning!! The fluxclient has been "
"loaded before fork, auto-reload moudle function is"
" not work anymore.")
return
class HttpServer(HttpServerBase):
def on_accept(self):
check_autoreload()
request, client = self.sock.accept()
w = Process(target=fork_entry, args=(request, client, self))
w.daemon = True
w.start()
request.close()
|
from multiprocessing import Process
import sys
from fluxghost.http_server_base import HttpServerBase, logger
def fork_entry(request, client, server):
from fluxghost.http_handler import HttpHandler
HttpHandler(request, client, server)
def check_autoreload():
if "fluxghost.http_handler" in sys.modules:
logger.error("Warning!! The fluxghost.http_handler has been "
"loaded before fork, auto-reload moudle function is"
" not work anymore.")
return
if "fluxclient" in sys.modules:
logger.error("Warning!! The fluxclient has been "
"loaded before fork, auto-reload moudle function is"
" not work anymore.")
return
class HttpServer(HttpServerBase):
def on_accept(self):
check_autoreload()
request, client = self.sock.accept()
w = Process(target=fork_entry, args=(request, client, self))
w.daemon = True
w.start()
Fix missing close socket error
from multiprocessing import Process
import sys
from fluxghost.http_server_base import HttpServerBase, logger
def fork_entry(request, client, server):
from fluxghost.http_handler import HttpHandler
HttpHandler(request, client, server)
def check_autoreload():
if "fluxghost.http_handler" in sys.modules:
logger.error("Warning!! The fluxghost.http_handler has been "
"loaded before fork, auto-reload moudle function is"
" not work anymore.")
return
if "fluxclient" in sys.modules:
logger.error("Warning!! The fluxclient has been "
"loaded before fork, auto-reload moudle function is"
" not work anymore.")
return
class HttpServer(HttpServerBase):
def on_accept(self):
check_autoreload()
request, client = self.sock.accept()
w = Process(target=fork_entry, args=(request, client, self))
w.daemon = True
w.start()
request.close()
|
<commit_before>
from multiprocessing import Process
import sys
from fluxghost.http_server_base import HttpServerBase, logger
def fork_entry(request, client, server):
from fluxghost.http_handler import HttpHandler
HttpHandler(request, client, server)
def check_autoreload():
if "fluxghost.http_handler" in sys.modules:
logger.error("Warning!! The fluxghost.http_handler has been "
"loaded before fork, auto-reload moudle function is"
" not work anymore.")
return
if "fluxclient" in sys.modules:
logger.error("Warning!! The fluxclient has been "
"loaded before fork, auto-reload moudle function is"
" not work anymore.")
return
class HttpServer(HttpServerBase):
def on_accept(self):
check_autoreload()
request, client = self.sock.accept()
w = Process(target=fork_entry, args=(request, client, self))
w.daemon = True
w.start()
<commit_msg>Fix missing close socket error<commit_after>
from multiprocessing import Process
import sys
from fluxghost.http_server_base import HttpServerBase, logger
def fork_entry(request, client, server):
from fluxghost.http_handler import HttpHandler
HttpHandler(request, client, server)
def check_autoreload():
if "fluxghost.http_handler" in sys.modules:
logger.error("Warning!! The fluxghost.http_handler has been "
"loaded before fork, auto-reload moudle function is"
" not work anymore.")
return
if "fluxclient" in sys.modules:
logger.error("Warning!! The fluxclient has been "
"loaded before fork, auto-reload moudle function is"
" not work anymore.")
return
class HttpServer(HttpServerBase):
def on_accept(self):
check_autoreload()
request, client = self.sock.accept()
w = Process(target=fork_entry, args=(request, client, self))
w.daemon = True
w.start()
request.close()
|
25746ab22ce7031e1bbee27bb04af73264525f4c
|
game/functional/test_input.py
|
game/functional/test_input.py
|
from twisted.trial.unittest import TestCase
from twisted.internet import reactor
from game.functional.test_view3d import SceneMixin
from game.player import Player
from game.vector import Vector
class StdoutReportingController(object):
# XXX Make an interface for the controller and verify this fake.
def __init__(self):
self.player = Player(Vector(0, 0, 0), 0, reactor.seconds)
def keyUp(self, key):
pass
def keyDown(self, key):
pass
def mouseMotion(self, pos, rel, buttons):
"""
Report to standard out the direction of the mouse movement.
"""
if rel[0] < 0:
print 'left',
elif rel[0] > 0:
print 'right',
if rel[1] < 0:
print 'up',
if rel[1] > 0:
print 'down',
print
class MouseInputTests(SceneMixin, TestCase):
"""
Tests for mouse input.
"""
def test_movement(self):
"""
When the mouse moves, the direction of movement is written to stdout.
"""
self.window.submitTo(StdoutReportingController())
reactor.callLater(2.0, self.window.stop)
return self.window.go()
|
from pygame import K_q
from twisted.trial.unittest import TestCase
from twisted.internet import reactor
from game.functional.test_view3d import SceneMixin
from game.player import Player
from game.vector import Vector
class QuittableController(object):
# XXX Make an interface for the controller and verify these fakes.
def __init__(self, reactor, window):
self.player = Player(Vector(0, 0, 0), 0, reactor.seconds)
self.window = window
def keyUp(self, key):
if key == K_q:
self.window.stop()
def keyDown(self, key):
pass
def mouseMotion(self, pos, rel, buttons):
pass
class StdoutReportingController(QuittableController):
def mouseMotion(self, pos, rel, buttons):
"""
Report to standard out the direction of the mouse movement.
"""
if rel[0] < 0:
print 'left',
elif rel[0] > 0:
print 'right',
if rel[1] < 0:
print 'up',
if rel[1] > 0:
print 'down',
print
class MouseInputTests(SceneMixin, TestCase):
"""
Tests for mouse input.
"""
def test_movement(self):
"""
When the mouse moves, the direction of movement is written to stdout.
"""
self.window.submitTo(StdoutReportingController(reactor, self.window))
return self.window.go()
def test_grab(self):
"""
Clicking on the window grabs the mouse. Clicking again releases it.
"""
self.window.submitTo(QuittableController(reactor, self.window))
return self.window.go()
|
Add a functional test for mouse grab.
|
Add a functional test for mouse grab.
|
Python
|
mit
|
eriknelson/gam3
|
from twisted.trial.unittest import TestCase
from twisted.internet import reactor
from game.functional.test_view3d import SceneMixin
from game.player import Player
from game.vector import Vector
class StdoutReportingController(object):
# XXX Make an interface for the controller and verify this fake.
def __init__(self):
self.player = Player(Vector(0, 0, 0), 0, reactor.seconds)
def keyUp(self, key):
pass
def keyDown(self, key):
pass
def mouseMotion(self, pos, rel, buttons):
"""
Report to standard out the direction of the mouse movement.
"""
if rel[0] < 0:
print 'left',
elif rel[0] > 0:
print 'right',
if rel[1] < 0:
print 'up',
if rel[1] > 0:
print 'down',
print
class MouseInputTests(SceneMixin, TestCase):
"""
Tests for mouse input.
"""
def test_movement(self):
"""
When the mouse moves, the direction of movement is written to stdout.
"""
self.window.submitTo(StdoutReportingController())
reactor.callLater(2.0, self.window.stop)
return self.window.go()
Add a functional test for mouse grab.
|
from pygame import K_q
from twisted.trial.unittest import TestCase
from twisted.internet import reactor
from game.functional.test_view3d import SceneMixin
from game.player import Player
from game.vector import Vector
class QuittableController(object):
# XXX Make an interface for the controller and verify these fakes.
def __init__(self, reactor, window):
self.player = Player(Vector(0, 0, 0), 0, reactor.seconds)
self.window = window
def keyUp(self, key):
if key == K_q:
self.window.stop()
def keyDown(self, key):
pass
def mouseMotion(self, pos, rel, buttons):
pass
class StdoutReportingController(QuittableController):
def mouseMotion(self, pos, rel, buttons):
"""
Report to standard out the direction of the mouse movement.
"""
if rel[0] < 0:
print 'left',
elif rel[0] > 0:
print 'right',
if rel[1] < 0:
print 'up',
if rel[1] > 0:
print 'down',
print
class MouseInputTests(SceneMixin, TestCase):
"""
Tests for mouse input.
"""
def test_movement(self):
"""
When the mouse moves, the direction of movement is written to stdout.
"""
self.window.submitTo(StdoutReportingController(reactor, self.window))
return self.window.go()
def test_grab(self):
"""
Clicking on the window grabs the mouse. Clicking again releases it.
"""
self.window.submitTo(QuittableController(reactor, self.window))
return self.window.go()
|
<commit_before>
from twisted.trial.unittest import TestCase
from twisted.internet import reactor
from game.functional.test_view3d import SceneMixin
from game.player import Player
from game.vector import Vector
class StdoutReportingController(object):
# XXX Make an interface for the controller and verify this fake.
def __init__(self):
self.player = Player(Vector(0, 0, 0), 0, reactor.seconds)
def keyUp(self, key):
pass
def keyDown(self, key):
pass
def mouseMotion(self, pos, rel, buttons):
"""
Report to standard out the direction of the mouse movement.
"""
if rel[0] < 0:
print 'left',
elif rel[0] > 0:
print 'right',
if rel[1] < 0:
print 'up',
if rel[1] > 0:
print 'down',
print
class MouseInputTests(SceneMixin, TestCase):
"""
Tests for mouse input.
"""
def test_movement(self):
"""
When the mouse moves, the direction of movement is written to stdout.
"""
self.window.submitTo(StdoutReportingController())
reactor.callLater(2.0, self.window.stop)
return self.window.go()
<commit_msg>Add a functional test for mouse grab.<commit_after>
|
from pygame import K_q
from twisted.trial.unittest import TestCase
from twisted.internet import reactor
from game.functional.test_view3d import SceneMixin
from game.player import Player
from game.vector import Vector
class QuittableController(object):
# XXX Make an interface for the controller and verify these fakes.
def __init__(self, reactor, window):
self.player = Player(Vector(0, 0, 0), 0, reactor.seconds)
self.window = window
def keyUp(self, key):
if key == K_q:
self.window.stop()
def keyDown(self, key):
pass
def mouseMotion(self, pos, rel, buttons):
pass
class StdoutReportingController(QuittableController):
def mouseMotion(self, pos, rel, buttons):
"""
Report to standard out the direction of the mouse movement.
"""
if rel[0] < 0:
print 'left',
elif rel[0] > 0:
print 'right',
if rel[1] < 0:
print 'up',
if rel[1] > 0:
print 'down',
print
class MouseInputTests(SceneMixin, TestCase):
"""
Tests for mouse input.
"""
def test_movement(self):
"""
When the mouse moves, the direction of movement is written to stdout.
"""
self.window.submitTo(StdoutReportingController(reactor, self.window))
return self.window.go()
def test_grab(self):
"""
Clicking on the window grabs the mouse. Clicking again releases it.
"""
self.window.submitTo(QuittableController(reactor, self.window))
return self.window.go()
|
from twisted.trial.unittest import TestCase
from twisted.internet import reactor
from game.functional.test_view3d import SceneMixin
from game.player import Player
from game.vector import Vector
class StdoutReportingController(object):
# XXX Make an interface for the controller and verify this fake.
def __init__(self):
self.player = Player(Vector(0, 0, 0), 0, reactor.seconds)
def keyUp(self, key):
pass
def keyDown(self, key):
pass
def mouseMotion(self, pos, rel, buttons):
"""
Report to standard out the direction of the mouse movement.
"""
if rel[0] < 0:
print 'left',
elif rel[0] > 0:
print 'right',
if rel[1] < 0:
print 'up',
if rel[1] > 0:
print 'down',
print
class MouseInputTests(SceneMixin, TestCase):
"""
Tests for mouse input.
"""
def test_movement(self):
"""
When the mouse moves, the direction of movement is written to stdout.
"""
self.window.submitTo(StdoutReportingController())
reactor.callLater(2.0, self.window.stop)
return self.window.go()
Add a functional test for mouse grab.
from pygame import K_q
from twisted.trial.unittest import TestCase
from twisted.internet import reactor
from game.functional.test_view3d import SceneMixin
from game.player import Player
from game.vector import Vector
class QuittableController(object):
# XXX Make an interface for the controller and verify these fakes.
def __init__(self, reactor, window):
self.player = Player(Vector(0, 0, 0), 0, reactor.seconds)
self.window = window
def keyUp(self, key):
if key == K_q:
self.window.stop()
def keyDown(self, key):
pass
def mouseMotion(self, pos, rel, buttons):
pass
class StdoutReportingController(QuittableController):
def mouseMotion(self, pos, rel, buttons):
"""
Report to standard out the direction of the mouse movement.
"""
if rel[0] < 0:
print 'left',
elif rel[0] > 0:
print 'right',
if rel[1] < 0:
print 'up',
if rel[1] > 0:
print 'down',
print
class MouseInputTests(SceneMixin, TestCase):
"""
Tests for mouse input.
"""
def test_movement(self):
"""
When the mouse moves, the direction of movement is written to stdout.
"""
self.window.submitTo(StdoutReportingController(reactor, self.window))
return self.window.go()
def test_grab(self):
"""
Clicking on the window grabs the mouse. Clicking again releases it.
"""
self.window.submitTo(QuittableController(reactor, self.window))
return self.window.go()
|
<commit_before>
from twisted.trial.unittest import TestCase
from twisted.internet import reactor
from game.functional.test_view3d import SceneMixin
from game.player import Player
from game.vector import Vector
class StdoutReportingController(object):
# XXX Make an interface for the controller and verify this fake.
def __init__(self):
self.player = Player(Vector(0, 0, 0), 0, reactor.seconds)
def keyUp(self, key):
pass
def keyDown(self, key):
pass
def mouseMotion(self, pos, rel, buttons):
"""
Report to standard out the direction of the mouse movement.
"""
if rel[0] < 0:
print 'left',
elif rel[0] > 0:
print 'right',
if rel[1] < 0:
print 'up',
if rel[1] > 0:
print 'down',
print
class MouseInputTests(SceneMixin, TestCase):
"""
Tests for mouse input.
"""
def test_movement(self):
"""
When the mouse moves, the direction of movement is written to stdout.
"""
self.window.submitTo(StdoutReportingController())
reactor.callLater(2.0, self.window.stop)
return self.window.go()
<commit_msg>Add a functional test for mouse grab.<commit_after>
from pygame import K_q
from twisted.trial.unittest import TestCase
from twisted.internet import reactor
from game.functional.test_view3d import SceneMixin
from game.player import Player
from game.vector import Vector
class QuittableController(object):
# XXX Make an interface for the controller and verify these fakes.
def __init__(self, reactor, window):
self.player = Player(Vector(0, 0, 0), 0, reactor.seconds)
self.window = window
def keyUp(self, key):
if key == K_q:
self.window.stop()
def keyDown(self, key):
pass
def mouseMotion(self, pos, rel, buttons):
pass
class StdoutReportingController(QuittableController):
def mouseMotion(self, pos, rel, buttons):
"""
Report to standard out the direction of the mouse movement.
"""
if rel[0] < 0:
print 'left',
elif rel[0] > 0:
print 'right',
if rel[1] < 0:
print 'up',
if rel[1] > 0:
print 'down',
print
class MouseInputTests(SceneMixin, TestCase):
"""
Tests for mouse input.
"""
def test_movement(self):
"""
When the mouse moves, the direction of movement is written to stdout.
"""
self.window.submitTo(StdoutReportingController(reactor, self.window))
return self.window.go()
def test_grab(self):
"""
Clicking on the window grabs the mouse. Clicking again releases it.
"""
self.window.submitTo(QuittableController(reactor, self.window))
return self.window.go()
|
ba523056c0ec42fe00aa0f23ff4933b773e03b46
|
config/__init__.py
|
config/__init__.py
|
class Config:
DEBUG = False
TESTING = False
REDIS = {
'host': 'localhost',
'port': 6379,
'db': 0,
'password': None
}
REDIS_KEY_EXPIRE = 604800 # a week in seconds
IMAGE_DIR = './resources'
LOG_FILE = 'app.log'
class DevelopmentConfig(Config):
DEBUG = True
def load_config(app, flags):
if 'dev' in flags:
app.config.from_object('config.DevelopmentConfig')
else:
app.config.from_object('config.Config')
def rotating_handler(filename):
if filename.startswith('~'):
filename = filename.replace('~', os.path.expanduser('~'))
handler = RotatingFileHandler(filename, maxBytes=5242880, backupCount=2)
formatter = Formatter('%(asctime)s [%(levelname)s] %(message)s', '%Y-%m-%d %H:%M:%S')
handler.setFormatter(formatter)
return handler
def setup_logging(app):
if not app.debug:
from logging import Formatter
from logging.handlers import RotatingFileHandler
import logging
filename = app.config['LOG_FILE']
handler = rotating_handler(filename)
handler.setLevel(logging.INFO)
app.logger.addHandler(handler)
|
from logging import Formatter
from logging.handlers import RotatingFileHandler
import logging
class Config:
DEBUG = False
TESTING = False
REDIS = {
'host': 'localhost',
'port': 6379,
'db': 0,
'password': None
}
REDIS_KEY_EXPIRE = 604800 # a week in seconds
IMAGE_DIR = './resources'
LOG_FILE = 'app.log'
class DevelopmentConfig(Config):
DEBUG = True
def load_config(app, flags):
if 'dev' in flags:
app.config.from_object('config.DevelopmentConfig')
else:
app.config.from_object('config.Config')
def rotating_handler(filename):
if filename.startswith('~'):
filename = filename.replace('~', os.path.expanduser('~'))
handler = RotatingFileHandler(filename, maxBytes=5242880, backupCount=2)
formatter = Formatter('%(asctime)s [%(levelname)s] %(message)s', '%Y-%m-%d %H:%M:%S')
handler.setFormatter(formatter)
return handler
def setup_logging(app):
if not app.debug:
filename = app.config['LOG_FILE']
handler = rotating_handler(filename)
handler.setLevel(logging.INFO)
app.logger.addHandler(handler)
|
Move imports to top of file
|
Move imports to top of file
|
Python
|
mit
|
Dinoshauer/img-resize
|
class Config:
DEBUG = False
TESTING = False
REDIS = {
'host': 'localhost',
'port': 6379,
'db': 0,
'password': None
}
REDIS_KEY_EXPIRE = 604800 # a week in seconds
IMAGE_DIR = './resources'
LOG_FILE = 'app.log'
class DevelopmentConfig(Config):
DEBUG = True
def load_config(app, flags):
if 'dev' in flags:
app.config.from_object('config.DevelopmentConfig')
else:
app.config.from_object('config.Config')
def rotating_handler(filename):
if filename.startswith('~'):
filename = filename.replace('~', os.path.expanduser('~'))
handler = RotatingFileHandler(filename, maxBytes=5242880, backupCount=2)
formatter = Formatter('%(asctime)s [%(levelname)s] %(message)s', '%Y-%m-%d %H:%M:%S')
handler.setFormatter(formatter)
return handler
def setup_logging(app):
if not app.debug:
from logging import Formatter
from logging.handlers import RotatingFileHandler
import logging
filename = app.config['LOG_FILE']
handler = rotating_handler(filename)
handler.setLevel(logging.INFO)
app.logger.addHandler(handler)
Move imports to top of file
|
from logging import Formatter
from logging.handlers import RotatingFileHandler
import logging
class Config:
DEBUG = False
TESTING = False
REDIS = {
'host': 'localhost',
'port': 6379,
'db': 0,
'password': None
}
REDIS_KEY_EXPIRE = 604800 # a week in seconds
IMAGE_DIR = './resources'
LOG_FILE = 'app.log'
class DevelopmentConfig(Config):
DEBUG = True
def load_config(app, flags):
if 'dev' in flags:
app.config.from_object('config.DevelopmentConfig')
else:
app.config.from_object('config.Config')
def rotating_handler(filename):
if filename.startswith('~'):
filename = filename.replace('~', os.path.expanduser('~'))
handler = RotatingFileHandler(filename, maxBytes=5242880, backupCount=2)
formatter = Formatter('%(asctime)s [%(levelname)s] %(message)s', '%Y-%m-%d %H:%M:%S')
handler.setFormatter(formatter)
return handler
def setup_logging(app):
if not app.debug:
filename = app.config['LOG_FILE']
handler = rotating_handler(filename)
handler.setLevel(logging.INFO)
app.logger.addHandler(handler)
|
<commit_before>class Config:
DEBUG = False
TESTING = False
REDIS = {
'host': 'localhost',
'port': 6379,
'db': 0,
'password': None
}
REDIS_KEY_EXPIRE = 604800 # a week in seconds
IMAGE_DIR = './resources'
LOG_FILE = 'app.log'
class DevelopmentConfig(Config):
DEBUG = True
def load_config(app, flags):
if 'dev' in flags:
app.config.from_object('config.DevelopmentConfig')
else:
app.config.from_object('config.Config')
def rotating_handler(filename):
if filename.startswith('~'):
filename = filename.replace('~', os.path.expanduser('~'))
handler = RotatingFileHandler(filename, maxBytes=5242880, backupCount=2)
formatter = Formatter('%(asctime)s [%(levelname)s] %(message)s', '%Y-%m-%d %H:%M:%S')
handler.setFormatter(formatter)
return handler
def setup_logging(app):
if not app.debug:
from logging import Formatter
from logging.handlers import RotatingFileHandler
import logging
filename = app.config['LOG_FILE']
handler = rotating_handler(filename)
handler.setLevel(logging.INFO)
app.logger.addHandler(handler)
<commit_msg>Move imports to top of file<commit_after>
|
from logging import Formatter
from logging.handlers import RotatingFileHandler
import logging
class Config:
DEBUG = False
TESTING = False
REDIS = {
'host': 'localhost',
'port': 6379,
'db': 0,
'password': None
}
REDIS_KEY_EXPIRE = 604800 # a week in seconds
IMAGE_DIR = './resources'
LOG_FILE = 'app.log'
class DevelopmentConfig(Config):
DEBUG = True
def load_config(app, flags):
if 'dev' in flags:
app.config.from_object('config.DevelopmentConfig')
else:
app.config.from_object('config.Config')
def rotating_handler(filename):
if filename.startswith('~'):
filename = filename.replace('~', os.path.expanduser('~'))
handler = RotatingFileHandler(filename, maxBytes=5242880, backupCount=2)
formatter = Formatter('%(asctime)s [%(levelname)s] %(message)s', '%Y-%m-%d %H:%M:%S')
handler.setFormatter(formatter)
return handler
def setup_logging(app):
if not app.debug:
filename = app.config['LOG_FILE']
handler = rotating_handler(filename)
handler.setLevel(logging.INFO)
app.logger.addHandler(handler)
|
class Config:
DEBUG = False
TESTING = False
REDIS = {
'host': 'localhost',
'port': 6379,
'db': 0,
'password': None
}
REDIS_KEY_EXPIRE = 604800 # a week in seconds
IMAGE_DIR = './resources'
LOG_FILE = 'app.log'
class DevelopmentConfig(Config):
DEBUG = True
def load_config(app, flags):
if 'dev' in flags:
app.config.from_object('config.DevelopmentConfig')
else:
app.config.from_object('config.Config')
def rotating_handler(filename):
if filename.startswith('~'):
filename = filename.replace('~', os.path.expanduser('~'))
handler = RotatingFileHandler(filename, maxBytes=5242880, backupCount=2)
formatter = Formatter('%(asctime)s [%(levelname)s] %(message)s', '%Y-%m-%d %H:%M:%S')
handler.setFormatter(formatter)
return handler
def setup_logging(app):
if not app.debug:
from logging import Formatter
from logging.handlers import RotatingFileHandler
import logging
filename = app.config['LOG_FILE']
handler = rotating_handler(filename)
handler.setLevel(logging.INFO)
app.logger.addHandler(handler)
Move imports to top of filefrom logging import Formatter
from logging.handlers import RotatingFileHandler
import logging
class Config:
DEBUG = False
TESTING = False
REDIS = {
'host': 'localhost',
'port': 6379,
'db': 0,
'password': None
}
REDIS_KEY_EXPIRE = 604800 # a week in seconds
IMAGE_DIR = './resources'
LOG_FILE = 'app.log'
class DevelopmentConfig(Config):
DEBUG = True
def load_config(app, flags):
if 'dev' in flags:
app.config.from_object('config.DevelopmentConfig')
else:
app.config.from_object('config.Config')
def rotating_handler(filename):
if filename.startswith('~'):
filename = filename.replace('~', os.path.expanduser('~'))
handler = RotatingFileHandler(filename, maxBytes=5242880, backupCount=2)
formatter = Formatter('%(asctime)s [%(levelname)s] %(message)s', '%Y-%m-%d %H:%M:%S')
handler.setFormatter(formatter)
return handler
def setup_logging(app):
if not app.debug:
filename = app.config['LOG_FILE']
handler = rotating_handler(filename)
handler.setLevel(logging.INFO)
app.logger.addHandler(handler)
|
<commit_before>class Config:
DEBUG = False
TESTING = False
REDIS = {
'host': 'localhost',
'port': 6379,
'db': 0,
'password': None
}
REDIS_KEY_EXPIRE = 604800 # a week in seconds
IMAGE_DIR = './resources'
LOG_FILE = 'app.log'
class DevelopmentConfig(Config):
DEBUG = True
def load_config(app, flags):
if 'dev' in flags:
app.config.from_object('config.DevelopmentConfig')
else:
app.config.from_object('config.Config')
def rotating_handler(filename):
if filename.startswith('~'):
filename = filename.replace('~', os.path.expanduser('~'))
handler = RotatingFileHandler(filename, maxBytes=5242880, backupCount=2)
formatter = Formatter('%(asctime)s [%(levelname)s] %(message)s', '%Y-%m-%d %H:%M:%S')
handler.setFormatter(formatter)
return handler
def setup_logging(app):
if not app.debug:
from logging import Formatter
from logging.handlers import RotatingFileHandler
import logging
filename = app.config['LOG_FILE']
handler = rotating_handler(filename)
handler.setLevel(logging.INFO)
app.logger.addHandler(handler)
<commit_msg>Move imports to top of file<commit_after>from logging import Formatter
from logging.handlers import RotatingFileHandler
import logging
class Config:
DEBUG = False
TESTING = False
REDIS = {
'host': 'localhost',
'port': 6379,
'db': 0,
'password': None
}
REDIS_KEY_EXPIRE = 604800 # a week in seconds
IMAGE_DIR = './resources'
LOG_FILE = 'app.log'
class DevelopmentConfig(Config):
DEBUG = True
def load_config(app, flags):
if 'dev' in flags:
app.config.from_object('config.DevelopmentConfig')
else:
app.config.from_object('config.Config')
def rotating_handler(filename):
if filename.startswith('~'):
filename = filename.replace('~', os.path.expanduser('~'))
handler = RotatingFileHandler(filename, maxBytes=5242880, backupCount=2)
formatter = Formatter('%(asctime)s [%(levelname)s] %(message)s', '%Y-%m-%d %H:%M:%S')
handler.setFormatter(formatter)
return handler
def setup_logging(app):
if not app.debug:
filename = app.config['LOG_FILE']
handler = rotating_handler(filename)
handler.setLevel(logging.INFO)
app.logger.addHandler(handler)
|
2c00876b60cdebfe1ed9ffd93b3064abaf3a20a0
|
rma/rule/GlobalKeySpace.py
|
rma/rule/GlobalKeySpace.py
|
from rma.redis import *
class GlobalKeySpace:
def __init__(self, redis):
"""
:param RmaRedis redis:
:return:
"""
self.redis = redis
def analyze(self, keys=[]):
total_keys = self.redis.total_keys()
return [
{
'headers': ['Stat', "Value"],
'data': [
["Total keys in db", total_keys],
["RedisDB key space overhead", dict_overhead(total_keys)]
]
}
]
|
from rma.redis import *
class GlobalKeySpace:
def __init__(self, redis):
"""
:param RmaRedis redis:
:return:
"""
self.redis = redis
def analyze(self, keys=[]):
total_keys = self.redis.total_keys()
keys_ = [
["Total keys in db", total_keys],
["RedisDB key space overhead", dict_overhead(total_keys)]
]
keys_ += [["Used `{0}`".format(key), value] for key, value in self.redis.config_get("*max-*-*").items()]
return [
{
'headers': ['Stat', "Value"],
'data': keys_
}
]
|
Add max config to globals
|
Add max config to globals
|
Python
|
mit
|
gamenet/redis-memory-analyzer
|
from rma.redis import *
class GlobalKeySpace:
def __init__(self, redis):
"""
:param RmaRedis redis:
:return:
"""
self.redis = redis
def analyze(self, keys=[]):
total_keys = self.redis.total_keys()
return [
{
'headers': ['Stat', "Value"],
'data': [
["Total keys in db", total_keys],
["RedisDB key space overhead", dict_overhead(total_keys)]
]
}
]
Add max config to globals
|
from rma.redis import *
class GlobalKeySpace:
def __init__(self, redis):
"""
:param RmaRedis redis:
:return:
"""
self.redis = redis
def analyze(self, keys=[]):
total_keys = self.redis.total_keys()
keys_ = [
["Total keys in db", total_keys],
["RedisDB key space overhead", dict_overhead(total_keys)]
]
keys_ += [["Used `{0}`".format(key), value] for key, value in self.redis.config_get("*max-*-*").items()]
return [
{
'headers': ['Stat', "Value"],
'data': keys_
}
]
|
<commit_before>from rma.redis import *
class GlobalKeySpace:
def __init__(self, redis):
"""
:param RmaRedis redis:
:return:
"""
self.redis = redis
def analyze(self, keys=[]):
total_keys = self.redis.total_keys()
return [
{
'headers': ['Stat', "Value"],
'data': [
["Total keys in db", total_keys],
["RedisDB key space overhead", dict_overhead(total_keys)]
]
}
]
<commit_msg>Add max config to globals<commit_after>
|
from rma.redis import *
class GlobalKeySpace:
def __init__(self, redis):
"""
:param RmaRedis redis:
:return:
"""
self.redis = redis
def analyze(self, keys=[]):
total_keys = self.redis.total_keys()
keys_ = [
["Total keys in db", total_keys],
["RedisDB key space overhead", dict_overhead(total_keys)]
]
keys_ += [["Used `{0}`".format(key), value] for key, value in self.redis.config_get("*max-*-*").items()]
return [
{
'headers': ['Stat', "Value"],
'data': keys_
}
]
|
from rma.redis import *
class GlobalKeySpace:
def __init__(self, redis):
"""
:param RmaRedis redis:
:return:
"""
self.redis = redis
def analyze(self, keys=[]):
total_keys = self.redis.total_keys()
return [
{
'headers': ['Stat', "Value"],
'data': [
["Total keys in db", total_keys],
["RedisDB key space overhead", dict_overhead(total_keys)]
]
}
]
Add max config to globalsfrom rma.redis import *
class GlobalKeySpace:
def __init__(self, redis):
"""
:param RmaRedis redis:
:return:
"""
self.redis = redis
def analyze(self, keys=[]):
total_keys = self.redis.total_keys()
keys_ = [
["Total keys in db", total_keys],
["RedisDB key space overhead", dict_overhead(total_keys)]
]
keys_ += [["Used `{0}`".format(key), value] for key, value in self.redis.config_get("*max-*-*").items()]
return [
{
'headers': ['Stat', "Value"],
'data': keys_
}
]
|
<commit_before>from rma.redis import *
class GlobalKeySpace:
def __init__(self, redis):
"""
:param RmaRedis redis:
:return:
"""
self.redis = redis
def analyze(self, keys=[]):
total_keys = self.redis.total_keys()
return [
{
'headers': ['Stat', "Value"],
'data': [
["Total keys in db", total_keys],
["RedisDB key space overhead", dict_overhead(total_keys)]
]
}
]
<commit_msg>Add max config to globals<commit_after>from rma.redis import *
class GlobalKeySpace:
def __init__(self, redis):
"""
:param RmaRedis redis:
:return:
"""
self.redis = redis
def analyze(self, keys=[]):
total_keys = self.redis.total_keys()
keys_ = [
["Total keys in db", total_keys],
["RedisDB key space overhead", dict_overhead(total_keys)]
]
keys_ += [["Used `{0}`".format(key), value] for key, value in self.redis.config_get("*max-*-*").items()]
return [
{
'headers': ['Stat', "Value"],
'data': keys_
}
]
|
7a71b2212bd71cb63b4708094a0cc3d409b820eb
|
bazaar/orders/models.py
|
bazaar/orders/models.py
|
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from bazaar.listings.models import Publishing, Store
@python_2_unicode_compatible
class Order(models.Model):
ORDER_PENDING = 0
ORDER_COMPLETED = 1
ORDER_STATUS_CHOICES = (
(ORDER_PENDING, "Pending"),
(ORDER_COMPLETED, "Completed"),
)
external_id = models.CharField(max_length=256)
store = models.ForeignKey(Store)
publishing = models.ForeignKey(Publishing, null=True, blank=True)
quantity = models.IntegerField(default=1)
status = models.CharField(max_length=50, choices=ORDER_STATUS_CHOICES, default=ORDER_PENDING)
def __str__(self):
return "Order %s from %s" % (self.external_id, self.store)
|
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from bazaar.listings.models import Publishing, Store
@python_2_unicode_compatible
class Order(models.Model):
ORDER_PENDING = 0
ORDER_COMPLETED = 1
ORDER_STATUS_CHOICES = (
(ORDER_PENDING, "Pending"),
(ORDER_COMPLETED, "Completed"),
)
external_id = models.CharField(max_length=256)
store = models.ForeignKey(Store)
publishing = models.ForeignKey(Publishing, null=True, blank=True)
quantity = models.IntegerField(default=1)
status = models.IntegerField(max_length=50, choices=ORDER_STATUS_CHOICES, default=ORDER_PENDING)
def __str__(self):
return "Order %s from %s" % (self.external_id, self.store)
|
Order status changed to integer
|
Order status changed to integer
|
Python
|
bsd-2-clause
|
evonove/django-bazaar,evonove/django-bazaar,meghabhoj/NEWBAZAAR,meghabhoj/NEWBAZAAR,evonove/django-bazaar,meghabhoj/NEWBAZAAR
|
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from bazaar.listings.models import Publishing, Store
@python_2_unicode_compatible
class Order(models.Model):
ORDER_PENDING = 0
ORDER_COMPLETED = 1
ORDER_STATUS_CHOICES = (
(ORDER_PENDING, "Pending"),
(ORDER_COMPLETED, "Completed"),
)
external_id = models.CharField(max_length=256)
store = models.ForeignKey(Store)
publishing = models.ForeignKey(Publishing, null=True, blank=True)
quantity = models.IntegerField(default=1)
status = models.CharField(max_length=50, choices=ORDER_STATUS_CHOICES, default=ORDER_PENDING)
def __str__(self):
return "Order %s from %s" % (self.external_id, self.store)
Order status changed to integer
|
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from bazaar.listings.models import Publishing, Store
@python_2_unicode_compatible
class Order(models.Model):
ORDER_PENDING = 0
ORDER_COMPLETED = 1
ORDER_STATUS_CHOICES = (
(ORDER_PENDING, "Pending"),
(ORDER_COMPLETED, "Completed"),
)
external_id = models.CharField(max_length=256)
store = models.ForeignKey(Store)
publishing = models.ForeignKey(Publishing, null=True, blank=True)
quantity = models.IntegerField(default=1)
status = models.IntegerField(max_length=50, choices=ORDER_STATUS_CHOICES, default=ORDER_PENDING)
def __str__(self):
return "Order %s from %s" % (self.external_id, self.store)
|
<commit_before>from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from bazaar.listings.models import Publishing, Store
@python_2_unicode_compatible
class Order(models.Model):
ORDER_PENDING = 0
ORDER_COMPLETED = 1
ORDER_STATUS_CHOICES = (
(ORDER_PENDING, "Pending"),
(ORDER_COMPLETED, "Completed"),
)
external_id = models.CharField(max_length=256)
store = models.ForeignKey(Store)
publishing = models.ForeignKey(Publishing, null=True, blank=True)
quantity = models.IntegerField(default=1)
status = models.CharField(max_length=50, choices=ORDER_STATUS_CHOICES, default=ORDER_PENDING)
def __str__(self):
return "Order %s from %s" % (self.external_id, self.store)
<commit_msg>Order status changed to integer<commit_after>
|
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from bazaar.listings.models import Publishing, Store
@python_2_unicode_compatible
class Order(models.Model):
ORDER_PENDING = 0
ORDER_COMPLETED = 1
ORDER_STATUS_CHOICES = (
(ORDER_PENDING, "Pending"),
(ORDER_COMPLETED, "Completed"),
)
external_id = models.CharField(max_length=256)
store = models.ForeignKey(Store)
publishing = models.ForeignKey(Publishing, null=True, blank=True)
quantity = models.IntegerField(default=1)
status = models.IntegerField(max_length=50, choices=ORDER_STATUS_CHOICES, default=ORDER_PENDING)
def __str__(self):
return "Order %s from %s" % (self.external_id, self.store)
|
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from bazaar.listings.models import Publishing, Store
@python_2_unicode_compatible
class Order(models.Model):
ORDER_PENDING = 0
ORDER_COMPLETED = 1
ORDER_STATUS_CHOICES = (
(ORDER_PENDING, "Pending"),
(ORDER_COMPLETED, "Completed"),
)
external_id = models.CharField(max_length=256)
store = models.ForeignKey(Store)
publishing = models.ForeignKey(Publishing, null=True, blank=True)
quantity = models.IntegerField(default=1)
status = models.CharField(max_length=50, choices=ORDER_STATUS_CHOICES, default=ORDER_PENDING)
def __str__(self):
return "Order %s from %s" % (self.external_id, self.store)
Order status changed to integerfrom __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from bazaar.listings.models import Publishing, Store
@python_2_unicode_compatible
class Order(models.Model):
ORDER_PENDING = 0
ORDER_COMPLETED = 1
ORDER_STATUS_CHOICES = (
(ORDER_PENDING, "Pending"),
(ORDER_COMPLETED, "Completed"),
)
external_id = models.CharField(max_length=256)
store = models.ForeignKey(Store)
publishing = models.ForeignKey(Publishing, null=True, blank=True)
quantity = models.IntegerField(default=1)
status = models.IntegerField(max_length=50, choices=ORDER_STATUS_CHOICES, default=ORDER_PENDING)
def __str__(self):
return "Order %s from %s" % (self.external_id, self.store)
|
<commit_before>from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from bazaar.listings.models import Publishing, Store
@python_2_unicode_compatible
class Order(models.Model):
ORDER_PENDING = 0
ORDER_COMPLETED = 1
ORDER_STATUS_CHOICES = (
(ORDER_PENDING, "Pending"),
(ORDER_COMPLETED, "Completed"),
)
external_id = models.CharField(max_length=256)
store = models.ForeignKey(Store)
publishing = models.ForeignKey(Publishing, null=True, blank=True)
quantity = models.IntegerField(default=1)
status = models.CharField(max_length=50, choices=ORDER_STATUS_CHOICES, default=ORDER_PENDING)
def __str__(self):
return "Order %s from %s" % (self.external_id, self.store)
<commit_msg>Order status changed to integer<commit_after>from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from bazaar.listings.models import Publishing, Store
@python_2_unicode_compatible
class Order(models.Model):
ORDER_PENDING = 0
ORDER_COMPLETED = 1
ORDER_STATUS_CHOICES = (
(ORDER_PENDING, "Pending"),
(ORDER_COMPLETED, "Completed"),
)
external_id = models.CharField(max_length=256)
store = models.ForeignKey(Store)
publishing = models.ForeignKey(Publishing, null=True, blank=True)
quantity = models.IntegerField(default=1)
status = models.IntegerField(max_length=50, choices=ORDER_STATUS_CHOICES, default=ORDER_PENDING)
def __str__(self):
return "Order %s from %s" % (self.external_id, self.store)
|
4c90c7445b0ccec8658fa71d50aa78a7de9c74b2
|
salt/defaults/exitcodes.py
|
salt/defaults/exitcodes.py
|
# -*- coding: utf-8 -*-
'''
Classification of Salt exit codes. These are intended to augment
universal exit codes (found in Python's `os` module with the `EX_`
prefix or in `sysexits.h`).
'''
# Too many situations use "exit 1" - try not to use it when something
# else is more appropriate.
EX_GENERIC = 1
# Salt SSH "Thin" deployment failures
EX_THIN_PYTHON_OLD = 10
EX_THIN_DEPLOY = 11
EX_THIN_CHECKSUM = 12
EX_MOD_DEPLOY = 13
# The os.EX_* exit codes are Unix only so in the interest of cross-platform
# compatiblility define them explicitly here.
#
# These constants are documented here:
# https://docs.python.org/2/library/os.html#os.EX_OK
EX_OK = 0
EX_NOUSER = 67
EX_UNAVAILABLE = 69
EX_CANTCREAT = 73
EX_SOFTWARE = 70
EX_USAGE = 64
|
# -*- coding: utf-8 -*-
'''
Classification of Salt exit codes. These are intended to augment
universal exit codes (found in Python's `os` module with the `EX_`
prefix or in `sysexits.h`).
'''
# Too many situations use "exit 1" - try not to use it when something
# else is more appropriate.
EX_GENERIC = 1
# Salt SSH "Thin" deployment failures
EX_THIN_PYTHON_OLD = 10
EX_THIN_DEPLOY = 11
EX_THIN_CHECKSUM = 12
EX_MOD_DEPLOY = 13
# The os.EX_* exit codes are Unix only so in the interest of cross-platform
# compatiblility define them explicitly here.
#
# These constants are documented here:
# https://docs.python.org/2/library/os.html#os.EX_OK
EX_OK = 0
EX_NOUSER = 67
EX_UNAVAILABLE = 69
EX_CANTCREAT = 73
EX_SOFTWARE = 70
EX_USAGE = 64
# The Salt specific exit codes are defined below:
# SALT_BUILD_FAIL is used when salt fails to build something, like a container
SALT_BUILD_FAIL = 101
|
Add Salt specific exit code
|
Add Salt specific exit code
|
Python
|
apache-2.0
|
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
|
# -*- coding: utf-8 -*-
'''
Classification of Salt exit codes. These are intended to augment
universal exit codes (found in Python's `os` module with the `EX_`
prefix or in `sysexits.h`).
'''
# Too many situations use "exit 1" - try not to use it when something
# else is more appropriate.
EX_GENERIC = 1
# Salt SSH "Thin" deployment failures
EX_THIN_PYTHON_OLD = 10
EX_THIN_DEPLOY = 11
EX_THIN_CHECKSUM = 12
EX_MOD_DEPLOY = 13
# The os.EX_* exit codes are Unix only so in the interest of cross-platform
# compatiblility define them explicitly here.
#
# These constants are documented here:
# https://docs.python.org/2/library/os.html#os.EX_OK
EX_OK = 0
EX_NOUSER = 67
EX_UNAVAILABLE = 69
EX_CANTCREAT = 73
EX_SOFTWARE = 70
EX_USAGE = 64
Add Salt specific exit code
|
# -*- coding: utf-8 -*-
'''
Classification of Salt exit codes. These are intended to augment
universal exit codes (found in Python's `os` module with the `EX_`
prefix or in `sysexits.h`).
'''
# Too many situations use "exit 1" - try not to use it when something
# else is more appropriate.
EX_GENERIC = 1
# Salt SSH "Thin" deployment failures
EX_THIN_PYTHON_OLD = 10
EX_THIN_DEPLOY = 11
EX_THIN_CHECKSUM = 12
EX_MOD_DEPLOY = 13
# The os.EX_* exit codes are Unix only so in the interest of cross-platform
# compatiblility define them explicitly here.
#
# These constants are documented here:
# https://docs.python.org/2/library/os.html#os.EX_OK
EX_OK = 0
EX_NOUSER = 67
EX_UNAVAILABLE = 69
EX_CANTCREAT = 73
EX_SOFTWARE = 70
EX_USAGE = 64
# The Salt specific exit codes are defined below:
# SALT_BUILD_FAIL is used when salt fails to build something, like a container
SALT_BUILD_FAIL = 101
|
<commit_before># -*- coding: utf-8 -*-
'''
Classification of Salt exit codes. These are intended to augment
universal exit codes (found in Python's `os` module with the `EX_`
prefix or in `sysexits.h`).
'''
# Too many situations use "exit 1" - try not to use it when something
# else is more appropriate.
EX_GENERIC = 1
# Salt SSH "Thin" deployment failures
EX_THIN_PYTHON_OLD = 10
EX_THIN_DEPLOY = 11
EX_THIN_CHECKSUM = 12
EX_MOD_DEPLOY = 13
# The os.EX_* exit codes are Unix only so in the interest of cross-platform
# compatiblility define them explicitly here.
#
# These constants are documented here:
# https://docs.python.org/2/library/os.html#os.EX_OK
EX_OK = 0
EX_NOUSER = 67
EX_UNAVAILABLE = 69
EX_CANTCREAT = 73
EX_SOFTWARE = 70
EX_USAGE = 64
<commit_msg>Add Salt specific exit code<commit_after>
|
# -*- coding: utf-8 -*-
'''
Classification of Salt exit codes. These are intended to augment
universal exit codes (found in Python's `os` module with the `EX_`
prefix or in `sysexits.h`).
'''
# Too many situations use "exit 1" - try not to use it when something
# else is more appropriate.
EX_GENERIC = 1
# Salt SSH "Thin" deployment failures
EX_THIN_PYTHON_OLD = 10
EX_THIN_DEPLOY = 11
EX_THIN_CHECKSUM = 12
EX_MOD_DEPLOY = 13
# The os.EX_* exit codes are Unix only so in the interest of cross-platform
# compatiblility define them explicitly here.
#
# These constants are documented here:
# https://docs.python.org/2/library/os.html#os.EX_OK
EX_OK = 0
EX_NOUSER = 67
EX_UNAVAILABLE = 69
EX_CANTCREAT = 73
EX_SOFTWARE = 70
EX_USAGE = 64
# The Salt specific exit codes are defined below:
# SALT_BUILD_FAIL is used when salt fails to build something, like a container
SALT_BUILD_FAIL = 101
|
# -*- coding: utf-8 -*-
'''
Classification of Salt exit codes. These are intended to augment
universal exit codes (found in Python's `os` module with the `EX_`
prefix or in `sysexits.h`).
'''
# Too many situations use "exit 1" - try not to use it when something
# else is more appropriate.
EX_GENERIC = 1
# Salt SSH "Thin" deployment failures
EX_THIN_PYTHON_OLD = 10
EX_THIN_DEPLOY = 11
EX_THIN_CHECKSUM = 12
EX_MOD_DEPLOY = 13
# The os.EX_* exit codes are Unix only so in the interest of cross-platform
# compatiblility define them explicitly here.
#
# These constants are documented here:
# https://docs.python.org/2/library/os.html#os.EX_OK
EX_OK = 0
EX_NOUSER = 67
EX_UNAVAILABLE = 69
EX_CANTCREAT = 73
EX_SOFTWARE = 70
EX_USAGE = 64
Add Salt specific exit code# -*- coding: utf-8 -*-
'''
Classification of Salt exit codes. These are intended to augment
universal exit codes (found in Python's `os` module with the `EX_`
prefix or in `sysexits.h`).
'''
# Too many situations use "exit 1" - try not to use it when something
# else is more appropriate.
EX_GENERIC = 1
# Salt SSH "Thin" deployment failures
EX_THIN_PYTHON_OLD = 10
EX_THIN_DEPLOY = 11
EX_THIN_CHECKSUM = 12
EX_MOD_DEPLOY = 13
# The os.EX_* exit codes are Unix only so in the interest of cross-platform
# compatiblility define them explicitly here.
#
# These constants are documented here:
# https://docs.python.org/2/library/os.html#os.EX_OK
EX_OK = 0
EX_NOUSER = 67
EX_UNAVAILABLE = 69
EX_CANTCREAT = 73
EX_SOFTWARE = 70
EX_USAGE = 64
# The Salt specific exit codes are defined below:
# SALT_BUILD_FAIL is used when salt fails to build something, like a container
SALT_BUILD_FAIL = 101
|
<commit_before># -*- coding: utf-8 -*-
'''
Classification of Salt exit codes. These are intended to augment
universal exit codes (found in Python's `os` module with the `EX_`
prefix or in `sysexits.h`).
'''
# Too many situations use "exit 1" - try not to use it when something
# else is more appropriate.
EX_GENERIC = 1
# Salt SSH "Thin" deployment failures
EX_THIN_PYTHON_OLD = 10
EX_THIN_DEPLOY = 11
EX_THIN_CHECKSUM = 12
EX_MOD_DEPLOY = 13
# The os.EX_* exit codes are Unix only so in the interest of cross-platform
# compatiblility define them explicitly here.
#
# These constants are documented here:
# https://docs.python.org/2/library/os.html#os.EX_OK
EX_OK = 0
EX_NOUSER = 67
EX_UNAVAILABLE = 69
EX_CANTCREAT = 73
EX_SOFTWARE = 70
EX_USAGE = 64
<commit_msg>Add Salt specific exit code<commit_after># -*- coding: utf-8 -*-
'''
Classification of Salt exit codes. These are intended to augment
universal exit codes (found in Python's `os` module with the `EX_`
prefix or in `sysexits.h`).
'''
# Too many situations use "exit 1" - try not to use it when something
# else is more appropriate.
EX_GENERIC = 1
# Salt SSH "Thin" deployment failures
EX_THIN_PYTHON_OLD = 10
EX_THIN_DEPLOY = 11
EX_THIN_CHECKSUM = 12
EX_MOD_DEPLOY = 13
# The os.EX_* exit codes are Unix only so in the interest of cross-platform
# compatiblility define them explicitly here.
#
# These constants are documented here:
# https://docs.python.org/2/library/os.html#os.EX_OK
EX_OK = 0
EX_NOUSER = 67
EX_UNAVAILABLE = 69
EX_CANTCREAT = 73
EX_SOFTWARE = 70
EX_USAGE = 64
# The Salt specific exit codes are defined below:
# SALT_BUILD_FAIL is used when salt fails to build something, like a container
SALT_BUILD_FAIL = 101
|
e94cb9d7277b2c9312f5b0526faded654d79abcb
|
tests/test_integration.py
|
tests/test_integration.py
|
import os
from unittest import TestCase
from yoconfigurator.base import read_config
from yoconfig import configure_services
from pycloudflare.services import CloudFlareService
app_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
conf = read_config(app_dir)
class ZonesTest(TestCase):
def setUp(self):
configure_services('cloudflare', ['cloudflare'], conf.common)
self.cloudflare = CloudFlareService()
def test_get_all_zones(self):
zones = self.cloudflare.get_zones()
self.assertIsInstance(zones, list)
def test_get_zone(self):
zone = self.cloudflare.get_zones()[0]
self.assertIsInstance(zone, dict)
|
import os
from unittest import TestCase
from yoconfigurator.base import read_config
from yoconfig import configure_services
from pycloudflare.services import CloudFlareService
app_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
conf = read_config(app_dir)
class ZonesTest(TestCase):
def setUp(self):
configure_services('cloudflare', ['cloudflare'], conf.common)
self.cloudflare = CloudFlareService()
def test_get_all_zones(self):
zones = self.cloudflare.get_zones()
self.assertIsInstance(zones, list)
def test_get_zone(self):
zone_id = self.cloudflare.get_zones()[0]['id']
zone = self.cloudflare.get_zone(zone_id)
self.assertIsInstance(zone, dict)
|
Test the actual get_zone call
|
Test the actual get_zone call
|
Python
|
mit
|
gnowxilef/pycloudflare,yola/pycloudflare
|
import os
from unittest import TestCase
from yoconfigurator.base import read_config
from yoconfig import configure_services
from pycloudflare.services import CloudFlareService
app_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
conf = read_config(app_dir)
class ZonesTest(TestCase):
def setUp(self):
configure_services('cloudflare', ['cloudflare'], conf.common)
self.cloudflare = CloudFlareService()
def test_get_all_zones(self):
zones = self.cloudflare.get_zones()
self.assertIsInstance(zones, list)
def test_get_zone(self):
zone = self.cloudflare.get_zones()[0]
self.assertIsInstance(zone, dict)
Test the actual get_zone call
|
import os
from unittest import TestCase
from yoconfigurator.base import read_config
from yoconfig import configure_services
from pycloudflare.services import CloudFlareService
app_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
conf = read_config(app_dir)
class ZonesTest(TestCase):
def setUp(self):
configure_services('cloudflare', ['cloudflare'], conf.common)
self.cloudflare = CloudFlareService()
def test_get_all_zones(self):
zones = self.cloudflare.get_zones()
self.assertIsInstance(zones, list)
def test_get_zone(self):
zone_id = self.cloudflare.get_zones()[0]['id']
zone = self.cloudflare.get_zone(zone_id)
self.assertIsInstance(zone, dict)
|
<commit_before>import os
from unittest import TestCase
from yoconfigurator.base import read_config
from yoconfig import configure_services
from pycloudflare.services import CloudFlareService
app_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
conf = read_config(app_dir)
class ZonesTest(TestCase):
def setUp(self):
configure_services('cloudflare', ['cloudflare'], conf.common)
self.cloudflare = CloudFlareService()
def test_get_all_zones(self):
zones = self.cloudflare.get_zones()
self.assertIsInstance(zones, list)
def test_get_zone(self):
zone = self.cloudflare.get_zones()[0]
self.assertIsInstance(zone, dict)
<commit_msg>Test the actual get_zone call<commit_after>
|
import os
from unittest import TestCase
from yoconfigurator.base import read_config
from yoconfig import configure_services
from pycloudflare.services import CloudFlareService
app_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
conf = read_config(app_dir)
class ZonesTest(TestCase):
def setUp(self):
configure_services('cloudflare', ['cloudflare'], conf.common)
self.cloudflare = CloudFlareService()
def test_get_all_zones(self):
zones = self.cloudflare.get_zones()
self.assertIsInstance(zones, list)
def test_get_zone(self):
zone_id = self.cloudflare.get_zones()[0]['id']
zone = self.cloudflare.get_zone(zone_id)
self.assertIsInstance(zone, dict)
|
import os
from unittest import TestCase
from yoconfigurator.base import read_config
from yoconfig import configure_services
from pycloudflare.services import CloudFlareService
app_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
conf = read_config(app_dir)
class ZonesTest(TestCase):
def setUp(self):
configure_services('cloudflare', ['cloudflare'], conf.common)
self.cloudflare = CloudFlareService()
def test_get_all_zones(self):
zones = self.cloudflare.get_zones()
self.assertIsInstance(zones, list)
def test_get_zone(self):
zone = self.cloudflare.get_zones()[0]
self.assertIsInstance(zone, dict)
Test the actual get_zone callimport os
from unittest import TestCase
from yoconfigurator.base import read_config
from yoconfig import configure_services
from pycloudflare.services import CloudFlareService
app_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
conf = read_config(app_dir)
class ZonesTest(TestCase):
def setUp(self):
configure_services('cloudflare', ['cloudflare'], conf.common)
self.cloudflare = CloudFlareService()
def test_get_all_zones(self):
zones = self.cloudflare.get_zones()
self.assertIsInstance(zones, list)
def test_get_zone(self):
zone_id = self.cloudflare.get_zones()[0]['id']
zone = self.cloudflare.get_zone(zone_id)
self.assertIsInstance(zone, dict)
|
<commit_before>import os
from unittest import TestCase
from yoconfigurator.base import read_config
from yoconfig import configure_services
from pycloudflare.services import CloudFlareService
app_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
conf = read_config(app_dir)
class ZonesTest(TestCase):
def setUp(self):
configure_services('cloudflare', ['cloudflare'], conf.common)
self.cloudflare = CloudFlareService()
def test_get_all_zones(self):
zones = self.cloudflare.get_zones()
self.assertIsInstance(zones, list)
def test_get_zone(self):
zone = self.cloudflare.get_zones()[0]
self.assertIsInstance(zone, dict)
<commit_msg>Test the actual get_zone call<commit_after>import os
from unittest import TestCase
from yoconfigurator.base import read_config
from yoconfig import configure_services
from pycloudflare.services import CloudFlareService
app_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
conf = read_config(app_dir)
class ZonesTest(TestCase):
def setUp(self):
configure_services('cloudflare', ['cloudflare'], conf.common)
self.cloudflare = CloudFlareService()
def test_get_all_zones(self):
zones = self.cloudflare.get_zones()
self.assertIsInstance(zones, list)
def test_get_zone(self):
zone_id = self.cloudflare.get_zones()[0]['id']
zone = self.cloudflare.get_zone(zone_id)
self.assertIsInstance(zone, dict)
|
54fdf3922615d5907a2e5344bf027df389572feb
|
byceps/services/user/transfer/models.py
|
byceps/services/user/transfer/models.py
|
"""
byceps.services.user.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import date
from typing import Any, Optional
from ....typing import UserID
@dataclass(frozen=True)
class User:
id: UserID
screen_name: Optional[str]
suspended: bool
deleted: bool
locale: Optional[str]
avatar_url: Optional[str]
is_orga: bool
@dataclass(frozen=True)
class UserDetail:
first_names: Optional[str]
last_name: Optional[str]
date_of_birth: Optional[date]
country: Optional[str]
zip_code: Optional[str]
city: Optional[str]
street: Optional[str]
phone_number: Optional[str]
internal_comment: Optional[str]
extras: dict[str, Any]
@dataclass(frozen=True)
class UserWithDetail(User):
detail: UserDetail
|
"""
byceps.services.user.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import date
from typing import Any, Optional
from ....typing import UserID
@dataclass(frozen=True)
class User:
id: UserID
screen_name: Optional[str]
suspended: bool
deleted: bool
locale: Optional[str]
avatar_url: Optional[str]
is_orga: bool
@dataclass(frozen=True)
class UserDetail:
first_names: Optional[str]
last_name: Optional[str]
date_of_birth: Optional[date]
country: Optional[str]
zip_code: Optional[str]
city: Optional[str]
street: Optional[str]
phone_number: Optional[str]
internal_comment: Optional[str]
extras: dict[str, Any]
@property
def full_name(self) -> Optional[str]:
names = [self.first_names, self.last_name]
return ' '.join(filter(None, names)) or None
@dataclass(frozen=True)
class UserWithDetail(User):
detail: UserDetail
|
Fix display of full user name at least on current user's settings page
|
Fix display of full user name at least on current user's settings page
|
Python
|
bsd-3-clause
|
homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps
|
"""
byceps.services.user.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import date
from typing import Any, Optional
from ....typing import UserID
@dataclass(frozen=True)
class User:
id: UserID
screen_name: Optional[str]
suspended: bool
deleted: bool
locale: Optional[str]
avatar_url: Optional[str]
is_orga: bool
@dataclass(frozen=True)
class UserDetail:
first_names: Optional[str]
last_name: Optional[str]
date_of_birth: Optional[date]
country: Optional[str]
zip_code: Optional[str]
city: Optional[str]
street: Optional[str]
phone_number: Optional[str]
internal_comment: Optional[str]
extras: dict[str, Any]
@dataclass(frozen=True)
class UserWithDetail(User):
detail: UserDetail
Fix display of full user name at least on current user's settings page
|
"""
byceps.services.user.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import date
from typing import Any, Optional
from ....typing import UserID
@dataclass(frozen=True)
class User:
id: UserID
screen_name: Optional[str]
suspended: bool
deleted: bool
locale: Optional[str]
avatar_url: Optional[str]
is_orga: bool
@dataclass(frozen=True)
class UserDetail:
first_names: Optional[str]
last_name: Optional[str]
date_of_birth: Optional[date]
country: Optional[str]
zip_code: Optional[str]
city: Optional[str]
street: Optional[str]
phone_number: Optional[str]
internal_comment: Optional[str]
extras: dict[str, Any]
@property
def full_name(self) -> Optional[str]:
names = [self.first_names, self.last_name]
return ' '.join(filter(None, names)) or None
@dataclass(frozen=True)
class UserWithDetail(User):
detail: UserDetail
|
<commit_before>"""
byceps.services.user.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import date
from typing import Any, Optional
from ....typing import UserID
@dataclass(frozen=True)
class User:
id: UserID
screen_name: Optional[str]
suspended: bool
deleted: bool
locale: Optional[str]
avatar_url: Optional[str]
is_orga: bool
@dataclass(frozen=True)
class UserDetail:
first_names: Optional[str]
last_name: Optional[str]
date_of_birth: Optional[date]
country: Optional[str]
zip_code: Optional[str]
city: Optional[str]
street: Optional[str]
phone_number: Optional[str]
internal_comment: Optional[str]
extras: dict[str, Any]
@dataclass(frozen=True)
class UserWithDetail(User):
detail: UserDetail
<commit_msg>Fix display of full user name at least on current user's settings page<commit_after>
|
"""
byceps.services.user.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import date
from typing import Any, Optional
from ....typing import UserID
@dataclass(frozen=True)
class User:
id: UserID
screen_name: Optional[str]
suspended: bool
deleted: bool
locale: Optional[str]
avatar_url: Optional[str]
is_orga: bool
@dataclass(frozen=True)
class UserDetail:
first_names: Optional[str]
last_name: Optional[str]
date_of_birth: Optional[date]
country: Optional[str]
zip_code: Optional[str]
city: Optional[str]
street: Optional[str]
phone_number: Optional[str]
internal_comment: Optional[str]
extras: dict[str, Any]
@property
def full_name(self) -> Optional[str]:
names = [self.first_names, self.last_name]
return ' '.join(filter(None, names)) or None
@dataclass(frozen=True)
class UserWithDetail(User):
detail: UserDetail
|
"""
byceps.services.user.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import date
from typing import Any, Optional
from ....typing import UserID
@dataclass(frozen=True)
class User:
id: UserID
screen_name: Optional[str]
suspended: bool
deleted: bool
locale: Optional[str]
avatar_url: Optional[str]
is_orga: bool
@dataclass(frozen=True)
class UserDetail:
first_names: Optional[str]
last_name: Optional[str]
date_of_birth: Optional[date]
country: Optional[str]
zip_code: Optional[str]
city: Optional[str]
street: Optional[str]
phone_number: Optional[str]
internal_comment: Optional[str]
extras: dict[str, Any]
@dataclass(frozen=True)
class UserWithDetail(User):
detail: UserDetail
Fix display of full user name at least on current user's settings page"""
byceps.services.user.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import date
from typing import Any, Optional
from ....typing import UserID
@dataclass(frozen=True)
class User:
id: UserID
screen_name: Optional[str]
suspended: bool
deleted: bool
locale: Optional[str]
avatar_url: Optional[str]
is_orga: bool
@dataclass(frozen=True)
class UserDetail:
first_names: Optional[str]
last_name: Optional[str]
date_of_birth: Optional[date]
country: Optional[str]
zip_code: Optional[str]
city: Optional[str]
street: Optional[str]
phone_number: Optional[str]
internal_comment: Optional[str]
extras: dict[str, Any]
@property
def full_name(self) -> Optional[str]:
names = [self.first_names, self.last_name]
return ' '.join(filter(None, names)) or None
@dataclass(frozen=True)
class UserWithDetail(User):
detail: UserDetail
|
<commit_before>"""
byceps.services.user.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import date
from typing import Any, Optional
from ....typing import UserID
@dataclass(frozen=True)
class User:
id: UserID
screen_name: Optional[str]
suspended: bool
deleted: bool
locale: Optional[str]
avatar_url: Optional[str]
is_orga: bool
@dataclass(frozen=True)
class UserDetail:
first_names: Optional[str]
last_name: Optional[str]
date_of_birth: Optional[date]
country: Optional[str]
zip_code: Optional[str]
city: Optional[str]
street: Optional[str]
phone_number: Optional[str]
internal_comment: Optional[str]
extras: dict[str, Any]
@dataclass(frozen=True)
class UserWithDetail(User):
detail: UserDetail
<commit_msg>Fix display of full user name at least on current user's settings page<commit_after>"""
byceps.services.user.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import date
from typing import Any, Optional
from ....typing import UserID
@dataclass(frozen=True)
class User:
id: UserID
screen_name: Optional[str]
suspended: bool
deleted: bool
locale: Optional[str]
avatar_url: Optional[str]
is_orga: bool
@dataclass(frozen=True)
class UserDetail:
first_names: Optional[str]
last_name: Optional[str]
date_of_birth: Optional[date]
country: Optional[str]
zip_code: Optional[str]
city: Optional[str]
street: Optional[str]
phone_number: Optional[str]
internal_comment: Optional[str]
extras: dict[str, Any]
@property
def full_name(self) -> Optional[str]:
names = [self.first_names, self.last_name]
return ' '.join(filter(None, names)) or None
@dataclass(frozen=True)
class UserWithDetail(User):
detail: UserDetail
|
8c8c0562e42ce789a283cec59771b1d1f3e95a2d
|
foreman/data_refinery_foreman/surveyor/management/commands/survey_sra.py
|
foreman/data_refinery_foreman/surveyor/management/commands/survey_sra.py
|
"""
This command will create and run survey jobs for each SRA run accession
in the range from start_accession to end_accession.
"""
from django.core.management.base import BaseCommand
from data_refinery_foreman.surveyor import surveyor
from data_refinery_common.logging import get_and_configure_logger
logger = get_and_configure_logger(__name__)
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
"--accession",
type=str,
help=("An SRA run accession. "))
parser.add_argument(
"--file",
type=str,
help=("An optional file listing accession codes.")
)
def handle(self, *args, **options):
if options["accession"] is None and options["file"] is None:
logger.error("You must specify accession or input file.")
return 1
if options["file"]:
with open(options["file"]) as file:
for acession in file:
try:
surveyor.survey_sra_experiment(accession.strip())
except Exception as e:
print(e)
else:
surveyor.survey_sra_experiment(options["accession"])
return 0
|
"""
This command will create and run survey jobs for each SRA run accession
in the range from start_accession to end_accession.
"""
import boto3
import botocore
import uuid
from django.core.management.base import BaseCommand
from data_refinery_foreman.surveyor import surveyor
from data_refinery_common.logging import get_and_configure_logger
from data_refinery_common.utils import parse_s3_url
logger = get_and_configure_logger(__name__)
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
"--accession",
type=str,
help=("An SRA run accession. "))
parser.add_argument(
"--file",
type=str,
help=("An optional file listing accession codes. s3:// URLs are also accepted.")
)
def handle(self, *args, **options):
if options["accession"] is None and options["file"] is None:
logger.error("You must specify accession or input file.")
return 1
if options["file"]:
if 's3://' in options["file"]:
bucket, key = parse_s3_url(options["file"])
s3 = boto3.resource('s3')
try:
filepath = "/tmp/input_" + str(uuid.uuid4()) + ".txt"
s3.Bucket(bucket).download_file(key, filepath)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == "404":
logger.error("The remote file does not exist.")
raise
else:
filepath = options["file"]
with open(filepath) as file:
for accession in file:
try:
surveyor.survey_sra_experiment(accession.strip())
except Exception as e:
print(e)
else:
surveyor.survey_sra_experiment(options["accession"])
return 0
|
Add support of s3 path
|
Add support of s3 path
|
Python
|
bsd-3-clause
|
data-refinery/data_refinery,data-refinery/data_refinery,data-refinery/data_refinery
|
"""
This command will create and run survey jobs for each SRA run accession
in the range from start_accession to end_accession.
"""
from django.core.management.base import BaseCommand
from data_refinery_foreman.surveyor import surveyor
from data_refinery_common.logging import get_and_configure_logger
logger = get_and_configure_logger(__name__)
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
"--accession",
type=str,
help=("An SRA run accession. "))
parser.add_argument(
"--file",
type=str,
help=("An optional file listing accession codes.")
)
def handle(self, *args, **options):
if options["accession"] is None and options["file"] is None:
logger.error("You must specify accession or input file.")
return 1
if options["file"]:
with open(options["file"]) as file:
for acession in file:
try:
surveyor.survey_sra_experiment(accession.strip())
except Exception as e:
print(e)
else:
surveyor.survey_sra_experiment(options["accession"])
return 0
Add support of s3 path
|
"""
This command will create and run survey jobs for each SRA run accession
in the range from start_accession to end_accession.
"""
import boto3
import botocore
import uuid
from django.core.management.base import BaseCommand
from data_refinery_foreman.surveyor import surveyor
from data_refinery_common.logging import get_and_configure_logger
from data_refinery_common.utils import parse_s3_url
logger = get_and_configure_logger(__name__)
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
"--accession",
type=str,
help=("An SRA run accession. "))
parser.add_argument(
"--file",
type=str,
help=("An optional file listing accession codes. s3:// URLs are also accepted.")
)
def handle(self, *args, **options):
if options["accession"] is None and options["file"] is None:
logger.error("You must specify accession or input file.")
return 1
if options["file"]:
if 's3://' in options["file"]:
bucket, key = parse_s3_url(options["file"])
s3 = boto3.resource('s3')
try:
filepath = "/tmp/input_" + str(uuid.uuid4()) + ".txt"
s3.Bucket(bucket).download_file(key, filepath)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == "404":
logger.error("The remote file does not exist.")
raise
else:
filepath = options["file"]
with open(filepath) as file:
for accession in file:
try:
surveyor.survey_sra_experiment(accession.strip())
except Exception as e:
print(e)
else:
surveyor.survey_sra_experiment(options["accession"])
return 0
|
<commit_before>"""
This command will create and run survey jobs for each SRA run accession
in the range from start_accession to end_accession.
"""
from django.core.management.base import BaseCommand
from data_refinery_foreman.surveyor import surveyor
from data_refinery_common.logging import get_and_configure_logger
logger = get_and_configure_logger(__name__)
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
"--accession",
type=str,
help=("An SRA run accession. "))
parser.add_argument(
"--file",
type=str,
help=("An optional file listing accession codes.")
)
def handle(self, *args, **options):
if options["accession"] is None and options["file"] is None:
logger.error("You must specify accession or input file.")
return 1
if options["file"]:
with open(options["file"]) as file:
for acession in file:
try:
surveyor.survey_sra_experiment(accession.strip())
except Exception as e:
print(e)
else:
surveyor.survey_sra_experiment(options["accession"])
return 0
<commit_msg>Add support of s3 path<commit_after>
|
"""
This command will create and run survey jobs for each SRA run accession
in the range from start_accession to end_accession.
"""
import boto3
import botocore
import uuid
from django.core.management.base import BaseCommand
from data_refinery_foreman.surveyor import surveyor
from data_refinery_common.logging import get_and_configure_logger
from data_refinery_common.utils import parse_s3_url
logger = get_and_configure_logger(__name__)
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
"--accession",
type=str,
help=("An SRA run accession. "))
parser.add_argument(
"--file",
type=str,
help=("An optional file listing accession codes. s3:// URLs are also accepted.")
)
def handle(self, *args, **options):
if options["accession"] is None and options["file"] is None:
logger.error("You must specify accession or input file.")
return 1
if options["file"]:
if 's3://' in options["file"]:
bucket, key = parse_s3_url(options["file"])
s3 = boto3.resource('s3')
try:
filepath = "/tmp/input_" + str(uuid.uuid4()) + ".txt"
s3.Bucket(bucket).download_file(key, filepath)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == "404":
logger.error("The remote file does not exist.")
raise
else:
filepath = options["file"]
with open(filepath) as file:
for accession in file:
try:
surveyor.survey_sra_experiment(accession.strip())
except Exception as e:
print(e)
else:
surveyor.survey_sra_experiment(options["accession"])
return 0
|
"""
This command will create and run survey jobs for each SRA run accession
in the range from start_accession to end_accession.
"""
from django.core.management.base import BaseCommand
from data_refinery_foreman.surveyor import surveyor
from data_refinery_common.logging import get_and_configure_logger
logger = get_and_configure_logger(__name__)
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
"--accession",
type=str,
help=("An SRA run accession. "))
parser.add_argument(
"--file",
type=str,
help=("An optional file listing accession codes.")
)
def handle(self, *args, **options):
if options["accession"] is None and options["file"] is None:
logger.error("You must specify accession or input file.")
return 1
if options["file"]:
with open(options["file"]) as file:
for acession in file:
try:
surveyor.survey_sra_experiment(accession.strip())
except Exception as e:
print(e)
else:
surveyor.survey_sra_experiment(options["accession"])
return 0
Add support of s3 path"""
This command will create and run survey jobs for each SRA run accession
in the range from start_accession to end_accession.
"""
import boto3
import botocore
import uuid
from django.core.management.base import BaseCommand
from data_refinery_foreman.surveyor import surveyor
from data_refinery_common.logging import get_and_configure_logger
from data_refinery_common.utils import parse_s3_url
logger = get_and_configure_logger(__name__)
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
"--accession",
type=str,
help=("An SRA run accession. "))
parser.add_argument(
"--file",
type=str,
help=("An optional file listing accession codes. s3:// URLs are also accepted.")
)
def handle(self, *args, **options):
if options["accession"] is None and options["file"] is None:
logger.error("You must specify accession or input file.")
return 1
if options["file"]:
if 's3://' in options["file"]:
bucket, key = parse_s3_url(options["file"])
s3 = boto3.resource('s3')
try:
filepath = "/tmp/input_" + str(uuid.uuid4()) + ".txt"
s3.Bucket(bucket).download_file(key, filepath)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == "404":
logger.error("The remote file does not exist.")
raise
else:
filepath = options["file"]
with open(filepath) as file:
for accession in file:
try:
surveyor.survey_sra_experiment(accession.strip())
except Exception as e:
print(e)
else:
surveyor.survey_sra_experiment(options["accession"])
return 0
|
<commit_before>"""
This command will create and run survey jobs for each SRA run accession
in the range from start_accession to end_accession.
"""
from django.core.management.base import BaseCommand
from data_refinery_foreman.surveyor import surveyor
from data_refinery_common.logging import get_and_configure_logger
logger = get_and_configure_logger(__name__)
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
"--accession",
type=str,
help=("An SRA run accession. "))
parser.add_argument(
"--file",
type=str,
help=("An optional file listing accession codes.")
)
def handle(self, *args, **options):
if options["accession"] is None and options["file"] is None:
logger.error("You must specify accession or input file.")
return 1
if options["file"]:
with open(options["file"]) as file:
for acession in file:
try:
surveyor.survey_sra_experiment(accession.strip())
except Exception as e:
print(e)
else:
surveyor.survey_sra_experiment(options["accession"])
return 0
<commit_msg>Add support of s3 path<commit_after>"""
This command will create and run survey jobs for each SRA run accession
in the range from start_accession to end_accession.
"""
import boto3
import botocore
import uuid
from django.core.management.base import BaseCommand
from data_refinery_foreman.surveyor import surveyor
from data_refinery_common.logging import get_and_configure_logger
from data_refinery_common.utils import parse_s3_url
logger = get_and_configure_logger(__name__)
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
"--accession",
type=str,
help=("An SRA run accession. "))
parser.add_argument(
"--file",
type=str,
help=("An optional file listing accession codes. s3:// URLs are also accepted.")
)
def handle(self, *args, **options):
if options["accession"] is None and options["file"] is None:
logger.error("You must specify accession or input file.")
return 1
if options["file"]:
if 's3://' in options["file"]:
bucket, key = parse_s3_url(options["file"])
s3 = boto3.resource('s3')
try:
filepath = "/tmp/input_" + str(uuid.uuid4()) + ".txt"
s3.Bucket(bucket).download_file(key, filepath)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == "404":
logger.error("The remote file does not exist.")
raise
else:
filepath = options["file"]
with open(filepath) as file:
for accession in file:
try:
surveyor.survey_sra_experiment(accession.strip())
except Exception as e:
print(e)
else:
surveyor.survey_sra_experiment(options["accession"])
return 0
|
3a96b839cbe8a2506f4a07a9b2be4acf4ca82e72
|
src/python/ipc-example.py
|
src/python/ipc-example.py
|
#!/usr/bin/env python3
# This file was developed by Thomáš Iser & Thomas Müller <thomas94@gmx.net>.
# It is published under the BSD 3-Clause License within the LICENSE file.
"""
Example usage of tev's Python IPC implementation.
"""
from ipc import TevIpc
import numpy as np
if __name__ == "__main__":
with TevIpc() as tev:
image_data = np.full((100,100,3), 1.0)
image_data[40:61,:,0] = 0.0
image_data[:,40:61,1] = 0.0
image_data[50:71,50:71,2] = 0.0
bonus_data = image_data[:,:,0] + image_data[:,:,1] + image_data[:,:,2]
tev.create_image("Test Image", width=100, height=100, channel_names=["R","G","B","Bonus"])
tev.update_image("Test Image", image_data, ["R", "G", "B"])
tev.update_image("Test Image", bonus_data, ["Bonus"])
|
#!/usr/bin/env python3
# This file was developed by Thomáš Iser & Thomas Müller <thomas94@gmx.net>.
# It is published under the BSD 3-Clause License within the LICENSE file.
"""
Example usage of tev's Python IPC implementation.
"""
from ipc import TevIpc
import numpy as np
if __name__ == "__main__":
with TevIpc() as tev:
image_data = np.full((300,200,3), 1.0)
image_data[40:61,:,0] = 0.0
image_data[:,40:61,1] = 0.0
image_data[50:71,50:71,2] = 0.0
bonus_data = image_data[:,:,0] + image_data[:,:,1] + image_data[:,:,2]
tev.create_image("Test Image", width=200, height=300, channel_names=["R","G","B","Bonus"])
tev.update_image("Test Image", image_data, ["R", "G", "B"])
tev.update_image("Test Image", bonus_data, ["Bonus"])
|
Use the example to verify tiled image updates are working
|
Use the example to verify tiled image updates are working
|
Python
|
bsd-3-clause
|
Tom94/tev,Tom94/tev,Tom94/tev,Tom94/tev
|
#!/usr/bin/env python3
# This file was developed by Thomáš Iser & Thomas Müller <thomas94@gmx.net>.
# It is published under the BSD 3-Clause License within the LICENSE file.
"""
Example usage of tev's Python IPC implementation.
"""
from ipc import TevIpc
import numpy as np
if __name__ == "__main__":
with TevIpc() as tev:
image_data = np.full((100,100,3), 1.0)
image_data[40:61,:,0] = 0.0
image_data[:,40:61,1] = 0.0
image_data[50:71,50:71,2] = 0.0
bonus_data = image_data[:,:,0] + image_data[:,:,1] + image_data[:,:,2]
tev.create_image("Test Image", width=100, height=100, channel_names=["R","G","B","Bonus"])
tev.update_image("Test Image", image_data, ["R", "G", "B"])
tev.update_image("Test Image", bonus_data, ["Bonus"])
Use the example to verify tiled image updates are working
|
#!/usr/bin/env python3
# This file was developed by Thomáš Iser & Thomas Müller <thomas94@gmx.net>.
# It is published under the BSD 3-Clause License within the LICENSE file.
"""
Example usage of tev's Python IPC implementation.
"""
from ipc import TevIpc
import numpy as np
if __name__ == "__main__":
with TevIpc() as tev:
image_data = np.full((300,200,3), 1.0)
image_data[40:61,:,0] = 0.0
image_data[:,40:61,1] = 0.0
image_data[50:71,50:71,2] = 0.0
bonus_data = image_data[:,:,0] + image_data[:,:,1] + image_data[:,:,2]
tev.create_image("Test Image", width=200, height=300, channel_names=["R","G","B","Bonus"])
tev.update_image("Test Image", image_data, ["R", "G", "B"])
tev.update_image("Test Image", bonus_data, ["Bonus"])
|
<commit_before>#!/usr/bin/env python3
# This file was developed by Thomáš Iser & Thomas Müller <thomas94@gmx.net>.
# It is published under the BSD 3-Clause License within the LICENSE file.
"""
Example usage of tev's Python IPC implementation.
"""
from ipc import TevIpc
import numpy as np
if __name__ == "__main__":
with TevIpc() as tev:
image_data = np.full((100,100,3), 1.0)
image_data[40:61,:,0] = 0.0
image_data[:,40:61,1] = 0.0
image_data[50:71,50:71,2] = 0.0
bonus_data = image_data[:,:,0] + image_data[:,:,1] + image_data[:,:,2]
tev.create_image("Test Image", width=100, height=100, channel_names=["R","G","B","Bonus"])
tev.update_image("Test Image", image_data, ["R", "G", "B"])
tev.update_image("Test Image", bonus_data, ["Bonus"])
<commit_msg>Use the example to verify tiled image updates are working<commit_after>
|
#!/usr/bin/env python3
# This file was developed by Thomáš Iser & Thomas Müller <thomas94@gmx.net>.
# It is published under the BSD 3-Clause License within the LICENSE file.
"""
Example usage of tev's Python IPC implementation.
"""
from ipc import TevIpc
import numpy as np
if __name__ == "__main__":
with TevIpc() as tev:
image_data = np.full((300,200,3), 1.0)
image_data[40:61,:,0] = 0.0
image_data[:,40:61,1] = 0.0
image_data[50:71,50:71,2] = 0.0
bonus_data = image_data[:,:,0] + image_data[:,:,1] + image_data[:,:,2]
tev.create_image("Test Image", width=200, height=300, channel_names=["R","G","B","Bonus"])
tev.update_image("Test Image", image_data, ["R", "G", "B"])
tev.update_image("Test Image", bonus_data, ["Bonus"])
|
#!/usr/bin/env python3
# This file was developed by Thomáš Iser & Thomas Müller <thomas94@gmx.net>.
# It is published under the BSD 3-Clause License within the LICENSE file.
"""
Example usage of tev's Python IPC implementation.
"""
from ipc import TevIpc
import numpy as np
if __name__ == "__main__":
with TevIpc() as tev:
image_data = np.full((100,100,3), 1.0)
image_data[40:61,:,0] = 0.0
image_data[:,40:61,1] = 0.0
image_data[50:71,50:71,2] = 0.0
bonus_data = image_data[:,:,0] + image_data[:,:,1] + image_data[:,:,2]
tev.create_image("Test Image", width=100, height=100, channel_names=["R","G","B","Bonus"])
tev.update_image("Test Image", image_data, ["R", "G", "B"])
tev.update_image("Test Image", bonus_data, ["Bonus"])
Use the example to verify tiled image updates are working#!/usr/bin/env python3
# This file was developed by Thomáš Iser & Thomas Müller <thomas94@gmx.net>.
# It is published under the BSD 3-Clause License within the LICENSE file.
"""
Example usage of tev's Python IPC implementation.
"""
from ipc import TevIpc
import numpy as np
if __name__ == "__main__":
with TevIpc() as tev:
image_data = np.full((300,200,3), 1.0)
image_data[40:61,:,0] = 0.0
image_data[:,40:61,1] = 0.0
image_data[50:71,50:71,2] = 0.0
bonus_data = image_data[:,:,0] + image_data[:,:,1] + image_data[:,:,2]
tev.create_image("Test Image", width=200, height=300, channel_names=["R","G","B","Bonus"])
tev.update_image("Test Image", image_data, ["R", "G", "B"])
tev.update_image("Test Image", bonus_data, ["Bonus"])
|
<commit_before>#!/usr/bin/env python3
# This file was developed by Thomáš Iser & Thomas Müller <thomas94@gmx.net>.
# It is published under the BSD 3-Clause License within the LICENSE file.
"""
Example usage of tev's Python IPC implementation.
"""
from ipc import TevIpc
import numpy as np
if __name__ == "__main__":
with TevIpc() as tev:
image_data = np.full((100,100,3), 1.0)
image_data[40:61,:,0] = 0.0
image_data[:,40:61,1] = 0.0
image_data[50:71,50:71,2] = 0.0
bonus_data = image_data[:,:,0] + image_data[:,:,1] + image_data[:,:,2]
tev.create_image("Test Image", width=100, height=100, channel_names=["R","G","B","Bonus"])
tev.update_image("Test Image", image_data, ["R", "G", "B"])
tev.update_image("Test Image", bonus_data, ["Bonus"])
<commit_msg>Use the example to verify tiled image updates are working<commit_after>#!/usr/bin/env python3
# This file was developed by Thomáš Iser & Thomas Müller <thomas94@gmx.net>.
# It is published under the BSD 3-Clause License within the LICENSE file.
"""
Example usage of tev's Python IPC implementation.
"""
from ipc import TevIpc
import numpy as np
if __name__ == "__main__":
with TevIpc() as tev:
image_data = np.full((300,200,3), 1.0)
image_data[40:61,:,0] = 0.0
image_data[:,40:61,1] = 0.0
image_data[50:71,50:71,2] = 0.0
bonus_data = image_data[:,:,0] + image_data[:,:,1] + image_data[:,:,2]
tev.create_image("Test Image", width=200, height=300, channel_names=["R","G","B","Bonus"])
tev.update_image("Test Image", image_data, ["R", "G", "B"])
tev.update_image("Test Image", bonus_data, ["Bonus"])
|
dbcd40d339968ece3ddb94d5fe9f6ddaab881967
|
zou/event_stream.py
|
zou/event_stream.py
|
import os
from flask import Flask
from flask_sse import sse
app = Flask(__name__)
redis_host = os.environ.get("KV_HOST", "localhost")
redis_port = os.environ.get("KV_PORT", "5379")
redis_url = "redis://%s:%s/2" % (redis_host, redis_port)
app.config["REDIS_URL"] = redis_url
app.register_blueprint(sse, url_prefix='/events')
|
import os
from flask import Flask
from flask_sse import sse
app = Flask(__name__)
redis_host = os.environ.get("KV_HOST", "localhost")
redis_port = os.environ.get("KV_PORT", "6379")
redis_url = "redis://%s:%s/2" % (redis_host, redis_port)
app.config["REDIS_URL"] = redis_url
app.register_blueprint(sse, url_prefix='/events')
|
Fix default port for Redis in event stream
|
Fix default port for Redis in event stream
|
Python
|
agpl-3.0
|
cgwire/zou
|
import os
from flask import Flask
from flask_sse import sse
app = Flask(__name__)
redis_host = os.environ.get("KV_HOST", "localhost")
redis_port = os.environ.get("KV_PORT", "5379")
redis_url = "redis://%s:%s/2" % (redis_host, redis_port)
app.config["REDIS_URL"] = redis_url
app.register_blueprint(sse, url_prefix='/events')
Fix default port for Redis in event stream
|
import os
from flask import Flask
from flask_sse import sse
app = Flask(__name__)
redis_host = os.environ.get("KV_HOST", "localhost")
redis_port = os.environ.get("KV_PORT", "6379")
redis_url = "redis://%s:%s/2" % (redis_host, redis_port)
app.config["REDIS_URL"] = redis_url
app.register_blueprint(sse, url_prefix='/events')
|
<commit_before>import os
from flask import Flask
from flask_sse import sse
app = Flask(__name__)
redis_host = os.environ.get("KV_HOST", "localhost")
redis_port = os.environ.get("KV_PORT", "5379")
redis_url = "redis://%s:%s/2" % (redis_host, redis_port)
app.config["REDIS_URL"] = redis_url
app.register_blueprint(sse, url_prefix='/events')
<commit_msg>Fix default port for Redis in event stream<commit_after>
|
import os
from flask import Flask
from flask_sse import sse
app = Flask(__name__)
redis_host = os.environ.get("KV_HOST", "localhost")
redis_port = os.environ.get("KV_PORT", "6379")
redis_url = "redis://%s:%s/2" % (redis_host, redis_port)
app.config["REDIS_URL"] = redis_url
app.register_blueprint(sse, url_prefix='/events')
|
import os
from flask import Flask
from flask_sse import sse
app = Flask(__name__)
redis_host = os.environ.get("KV_HOST", "localhost")
redis_port = os.environ.get("KV_PORT", "5379")
redis_url = "redis://%s:%s/2" % (redis_host, redis_port)
app.config["REDIS_URL"] = redis_url
app.register_blueprint(sse, url_prefix='/events')
Fix default port for Redis in event streamimport os
from flask import Flask
from flask_sse import sse
app = Flask(__name__)
redis_host = os.environ.get("KV_HOST", "localhost")
redis_port = os.environ.get("KV_PORT", "6379")
redis_url = "redis://%s:%s/2" % (redis_host, redis_port)
app.config["REDIS_URL"] = redis_url
app.register_blueprint(sse, url_prefix='/events')
|
<commit_before>import os
from flask import Flask
from flask_sse import sse
app = Flask(__name__)
redis_host = os.environ.get("KV_HOST", "localhost")
redis_port = os.environ.get("KV_PORT", "5379")
redis_url = "redis://%s:%s/2" % (redis_host, redis_port)
app.config["REDIS_URL"] = redis_url
app.register_blueprint(sse, url_prefix='/events')
<commit_msg>Fix default port for Redis in event stream<commit_after>import os
from flask import Flask
from flask_sse import sse
app = Flask(__name__)
redis_host = os.environ.get("KV_HOST", "localhost")
redis_port = os.environ.get("KV_PORT", "6379")
redis_url = "redis://%s:%s/2" % (redis_host, redis_port)
app.config["REDIS_URL"] = redis_url
app.register_blueprint(sse, url_prefix='/events')
|
0cc571d20bfab4f3820f287cac51c0e47093c5c9
|
website/addons/dropbox/settings/local-dist.py
|
website/addons/dropbox/settings/local-dist.py
|
# -*- coding: utf-8 -*-
"""Example Dropbox local settings file. Copy this file to local.py and change
these settings.
"""
# Get an app key and secret at https://www.dropbox.com/developers/apps
DROPBOX_KEY = 'changeme'
DROPBOX_SECRET = 'changeme'
|
# -*- coding: utf-8 -*-
"""Example Dropbox local settings file. Copy this file to local.py and change
these settings.
"""
# Get an app key and secret at https://www.dropbox.com/developers/apps
DROPBOX_KEY = 'changeme'
DROPBOX_SECRET = 'changeme'
|
Fix coding style for travis ci build.
|
Fix coding style for travis ci build.
|
Python
|
apache-2.0
|
RomanZWang/osf.io,acshi/osf.io,leb2dg/osf.io,cslzchen/osf.io,Johnetordoff/osf.io,amyshi188/osf.io,emetsger/osf.io,Nesiehr/osf.io,HalcyonChimera/osf.io,acshi/osf.io,aaxelb/osf.io,RomanZWang/osf.io,chrisseto/osf.io,hmoco/osf.io,zamattiac/osf.io,TomHeatwole/osf.io,asanfilippo7/osf.io,mluke93/osf.io,crcresearch/osf.io,abought/osf.io,crcresearch/osf.io,amyshi188/osf.io,laurenrevere/osf.io,acshi/osf.io,emetsger/osf.io,zachjanicki/osf.io,caseyrollins/osf.io,emetsger/osf.io,erinspace/osf.io,pattisdr/osf.io,kwierman/osf.io,felliott/osf.io,baylee-d/osf.io,rdhyee/osf.io,felliott/osf.io,CenterForOpenScience/osf.io,icereval/osf.io,samchrisinger/osf.io,crcresearch/osf.io,TomBaxter/osf.io,HalcyonChimera/osf.io,icereval/osf.io,samchrisinger/osf.io,TomBaxter/osf.io,caseyrollins/osf.io,kwierman/osf.io,caneruguz/osf.io,chrisseto/osf.io,sloria/osf.io,Johnetordoff/osf.io,mluo613/osf.io,monikagrabowska/osf.io,cslzchen/osf.io,laurenrevere/osf.io,asanfilippo7/osf.io,jnayak1/osf.io,zamattiac/osf.io,SSJohns/osf.io,caneruguz/osf.io,saradbowman/osf.io,alexschiller/osf.io,wearpants/osf.io,kch8qx/osf.io,mluke93/osf.io,DanielSBrown/osf.io,aaxelb/osf.io,aaxelb/osf.io,acshi/osf.io,cslzchen/osf.io,felliott/osf.io,Johnetordoff/osf.io,adlius/osf.io,kwierman/osf.io,erinspace/osf.io,doublebits/osf.io,mattclark/osf.io,TomBaxter/osf.io,doublebits/osf.io,kch8qx/osf.io,felliott/osf.io,mattclark/osf.io,alexschiller/osf.io,caneruguz/osf.io,pattisdr/osf.io,zachjanicki/osf.io,abought/osf.io,wearpants/osf.io,cslzchen/osf.io,hmoco/osf.io,sloria/osf.io,leb2dg/osf.io,mfraezz/osf.io,chennan47/osf.io,abought/osf.io,RomanZWang/osf.io,aaxelb/osf.io,binoculars/osf.io,emetsger/osf.io,rdhyee/osf.io,HalcyonChimera/osf.io,rdhyee/osf.io,zachjanicki/osf.io,adlius/osf.io,kch8qx/osf.io,cwisecarver/osf.io,jnayak1/osf.io,brianjgeiger/osf.io,CenterForOpenScience/osf.io,Nesiehr/osf.io,CenterForOpenScience/osf.io,mfraezz/osf.io,chennan47/osf.io,binoculars/osf.io,abought/osf.io,erinspace/osf.io,Johnetordoff/osf.io,brianjgeiger/osf.io,saradbowman/osf.io,DanielSBrown/osf.io,alexschiller/osf.io,baylee-d/osf.io,SSJohns/osf.io,mluke93/osf.io,SSJohns/osf.io,wearpants/osf.io,monikagrabowska/osf.io,chrisseto/osf.io,doublebits/osf.io,chrisseto/osf.io,CenterForOpenScience/osf.io,samchrisinger/osf.io,Nesiehr/osf.io,Nesiehr/osf.io,laurenrevere/osf.io,TomHeatwole/osf.io,monikagrabowska/osf.io,mluo613/osf.io,mfraezz/osf.io,kwierman/osf.io,monikagrabowska/osf.io,baylee-d/osf.io,mluo613/osf.io,mluke93/osf.io,kch8qx/osf.io,chennan47/osf.io,acshi/osf.io,mattclark/osf.io,TomHeatwole/osf.io,caneruguz/osf.io,rdhyee/osf.io,HalcyonChimera/osf.io,DanielSBrown/osf.io,jnayak1/osf.io,cwisecarver/osf.io,sloria/osf.io,doublebits/osf.io,zachjanicki/osf.io,SSJohns/osf.io,jnayak1/osf.io,RomanZWang/osf.io,alexschiller/osf.io,zamattiac/osf.io,hmoco/osf.io,adlius/osf.io,mluo613/osf.io,TomHeatwole/osf.io,asanfilippo7/osf.io,pattisdr/osf.io,asanfilippo7/osf.io,adlius/osf.io,wearpants/osf.io,cwisecarver/osf.io,monikagrabowska/osf.io,brianjgeiger/osf.io,alexschiller/osf.io,leb2dg/osf.io,hmoco/osf.io,amyshi188/osf.io,RomanZWang/osf.io,icereval/osf.io,samchrisinger/osf.io,zamattiac/osf.io,mfraezz/osf.io,mluo613/osf.io,binoculars/osf.io,DanielSBrown/osf.io,doublebits/osf.io,cwisecarver/osf.io,amyshi188/osf.io,caseyrollins/osf.io,kch8qx/osf.io,leb2dg/osf.io,brianjgeiger/osf.io
|
# -*- coding: utf-8 -*-
"""Example Dropbox local settings file. Copy this file to local.py and change
these settings.
"""
# Get an app key and secret at https://www.dropbox.com/developers/apps
DROPBOX_KEY = 'changeme'
DROPBOX_SECRET = 'changeme'Fix coding style for travis ci build.
|
# -*- coding: utf-8 -*-
"""Example Dropbox local settings file. Copy this file to local.py and change
these settings.
"""
# Get an app key and secret at https://www.dropbox.com/developers/apps
DROPBOX_KEY = 'changeme'
DROPBOX_SECRET = 'changeme'
|
<commit_before># -*- coding: utf-8 -*-
"""Example Dropbox local settings file. Copy this file to local.py and change
these settings.
"""
# Get an app key and secret at https://www.dropbox.com/developers/apps
DROPBOX_KEY = 'changeme'
DROPBOX_SECRET = 'changeme'<commit_msg>Fix coding style for travis ci build.<commit_after>
|
# -*- coding: utf-8 -*-
"""Example Dropbox local settings file. Copy this file to local.py and change
these settings.
"""
# Get an app key and secret at https://www.dropbox.com/developers/apps
DROPBOX_KEY = 'changeme'
DROPBOX_SECRET = 'changeme'
|
# -*- coding: utf-8 -*-
"""Example Dropbox local settings file. Copy this file to local.py and change
these settings.
"""
# Get an app key and secret at https://www.dropbox.com/developers/apps
DROPBOX_KEY = 'changeme'
DROPBOX_SECRET = 'changeme'Fix coding style for travis ci build.# -*- coding: utf-8 -*-
"""Example Dropbox local settings file. Copy this file to local.py and change
these settings.
"""
# Get an app key and secret at https://www.dropbox.com/developers/apps
DROPBOX_KEY = 'changeme'
DROPBOX_SECRET = 'changeme'
|
<commit_before># -*- coding: utf-8 -*-
"""Example Dropbox local settings file. Copy this file to local.py and change
these settings.
"""
# Get an app key and secret at https://www.dropbox.com/developers/apps
DROPBOX_KEY = 'changeme'
DROPBOX_SECRET = 'changeme'<commit_msg>Fix coding style for travis ci build.<commit_after># -*- coding: utf-8 -*-
"""Example Dropbox local settings file. Copy this file to local.py and change
these settings.
"""
# Get an app key and secret at https://www.dropbox.com/developers/apps
DROPBOX_KEY = 'changeme'
DROPBOX_SECRET = 'changeme'
|
1d652cac957f06afdad9fd64f617494e7f4821e4
|
application.py
|
application.py
|
#!/usr/bin/env python
# coding=utf-8
#
# Copyright 2015 cc98.org
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
import os.path
import re
import memcache
import torndb
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options
from jinja2 import Environment, FileSystemLoader
# Define a new command line option
define("port", default = 80, type = int, help = "run on the given port")
define("mysql_host", default = "mysql_host", help = "community database host")
define("mysql_database", default = "mysql_database", help = "community database name")
define("mysql_user", default = "mysql_db_user", help = "community database user")
define("mysql_pwd", default = "mysql_db_pwd", help = "community database pwd")
class Application(tornado.web.Application):
def __init__(self):
settings = dict(
)
handlers = [
(),
]
tornado.web.Application.__init__(self, handlers, settings)
# Have one global connection to the blog DB across all the handlers
self.db = torndb.Connection(
)
# Have one global session controller
# Have one global memcache controller
self.mc = memcache.Client(["127.0.0.1:11211"]])
def main():
tornado.options.parse_command_line()
httpserver = tornado.httpserver.HTTPServer(Application())
httpserver.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
if __name__ = "__main__":
main()
|
Add some necessary things to run the app
|
Add some necessary things to run the app
|
Python
|
mit
|
yiyangyi/cc98-tornado
|
Add some necessary things to run the app
|
#!/usr/bin/env python
# coding=utf-8
#
# Copyright 2015 cc98.org
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
import os.path
import re
import memcache
import torndb
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options
from jinja2 import Environment, FileSystemLoader
# Define a new command line option
define("port", default = 80, type = int, help = "run on the given port")
define("mysql_host", default = "mysql_host", help = "community database host")
define("mysql_database", default = "mysql_database", help = "community database name")
define("mysql_user", default = "mysql_db_user", help = "community database user")
define("mysql_pwd", default = "mysql_db_pwd", help = "community database pwd")
class Application(tornado.web.Application):
def __init__(self):
settings = dict(
)
handlers = [
(),
]
tornado.web.Application.__init__(self, handlers, settings)
# Have one global connection to the blog DB across all the handlers
self.db = torndb.Connection(
)
# Have one global session controller
# Have one global memcache controller
self.mc = memcache.Client(["127.0.0.1:11211"]])
def main():
tornado.options.parse_command_line()
httpserver = tornado.httpserver.HTTPServer(Application())
httpserver.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
if __name__ = "__main__":
main()
|
<commit_before><commit_msg>Add some necessary things to run the app<commit_after>
|
#!/usr/bin/env python
# coding=utf-8
#
# Copyright 2015 cc98.org
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
import os.path
import re
import memcache
import torndb
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options
from jinja2 import Environment, FileSystemLoader
# Define a new command line option
define("port", default = 80, type = int, help = "run on the given port")
define("mysql_host", default = "mysql_host", help = "community database host")
define("mysql_database", default = "mysql_database", help = "community database name")
define("mysql_user", default = "mysql_db_user", help = "community database user")
define("mysql_pwd", default = "mysql_db_pwd", help = "community database pwd")
class Application(tornado.web.Application):
def __init__(self):
settings = dict(
)
handlers = [
(),
]
tornado.web.Application.__init__(self, handlers, settings)
# Have one global connection to the blog DB across all the handlers
self.db = torndb.Connection(
)
# Have one global session controller
# Have one global memcache controller
self.mc = memcache.Client(["127.0.0.1:11211"]])
def main():
tornado.options.parse_command_line()
httpserver = tornado.httpserver.HTTPServer(Application())
httpserver.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
if __name__ = "__main__":
main()
|
Add some necessary things to run the app#!/usr/bin/env python
# coding=utf-8
#
# Copyright 2015 cc98.org
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
import os.path
import re
import memcache
import torndb
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options
from jinja2 import Environment, FileSystemLoader
# Define a new command line option
define("port", default = 80, type = int, help = "run on the given port")
define("mysql_host", default = "mysql_host", help = "community database host")
define("mysql_database", default = "mysql_database", help = "community database name")
define("mysql_user", default = "mysql_db_user", help = "community database user")
define("mysql_pwd", default = "mysql_db_pwd", help = "community database pwd")
class Application(tornado.web.Application):
def __init__(self):
settings = dict(
)
handlers = [
(),
]
tornado.web.Application.__init__(self, handlers, settings)
# Have one global connection to the blog DB across all the handlers
self.db = torndb.Connection(
)
# Have one global session controller
# Have one global memcache controller
self.mc = memcache.Client(["127.0.0.1:11211"]])
def main():
tornado.options.parse_command_line()
httpserver = tornado.httpserver.HTTPServer(Application())
httpserver.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
if __name__ = "__main__":
main()
|
<commit_before><commit_msg>Add some necessary things to run the app<commit_after>#!/usr/bin/env python
# coding=utf-8
#
# Copyright 2015 cc98.org
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
import os.path
import re
import memcache
import torndb
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options
from jinja2 import Environment, FileSystemLoader
# Define a new command line option
define("port", default = 80, type = int, help = "run on the given port")
define("mysql_host", default = "mysql_host", help = "community database host")
define("mysql_database", default = "mysql_database", help = "community database name")
define("mysql_user", default = "mysql_db_user", help = "community database user")
define("mysql_pwd", default = "mysql_db_pwd", help = "community database pwd")
class Application(tornado.web.Application):
def __init__(self):
settings = dict(
)
handlers = [
(),
]
tornado.web.Application.__init__(self, handlers, settings)
# Have one global connection to the blog DB across all the handlers
self.db = torndb.Connection(
)
# Have one global session controller
# Have one global memcache controller
self.mc = memcache.Client(["127.0.0.1:11211"]])
def main():
tornado.options.parse_command_line()
httpserver = tornado.httpserver.HTTPServer(Application())
httpserver.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
if __name__ = "__main__":
main()
|
|
6b365ae7d7ab01255643c48755590b8a1a0ae173
|
src/lib/constants/path.py
|
src/lib/constants/path.py
|
VIRTUALENV_DIR = "virtual_env/"
VIRTUALENV_ACTIVATE = VIRTUALENV_DIR + "bin/activate_this.py"
LOGS = "logs/"
YAML = "/etc/ggrc_test.yaml"
RESOURCES = "resources/"
REQUIREMENTS = RESOURCES + "requirements.txt"
SRC = "src/"
|
VIRTUALENV_DIR = "virtual_env/"
BIN_DIR = "bin/"
VIRTUALENV_ACTIVATE = "activate_this.py"
LOGS = "logs/"
YAML = "/etc/ggrc_test.yaml"
RESOURCES = "resources/"
REQUIREMENTS = RESOURCES + "requirements.txt"
SRC = "src/"
CHROME_DRIVER = "chromedriver"
|
Remove operations in module reserved for declaring constants.
|
Remove operations in module reserved for declaring constants.
|
Python
|
apache-2.0
|
NejcZupec/ggrc-core,plamut/ggrc-core,j0gurt/ggrc-core,NejcZupec/ggrc-core,jmakov/ggrc-core,jmakov/ggrc-core,j0gurt/ggrc-core,VinnieJohns/ggrc-core,jmakov/ggrc-core,kr41/ggrc-core,kr41/ggrc-core,kr41/ggrc-core,VinnieJohns/ggrc-core,andrei-karalionak/ggrc-core,AleksNeStu/ggrc-core,josthkko/ggrc-core,selahssea/ggrc-core,selahssea/ggrc-core,jmakov/ggrc-core,AleksNeStu/ggrc-core,selahssea/ggrc-core,VinnieJohns/ggrc-core,edofic/ggrc-core,NejcZupec/ggrc-core,NejcZupec/ggrc-core,AleksNeStu/ggrc-core,jmakov/ggrc-core,j0gurt/ggrc-core,andrei-karalionak/ggrc-core,andrei-karalionak/ggrc-core,plamut/ggrc-core,prasannav7/ggrc-core,j0gurt/ggrc-core,prasannav7/ggrc-core,edofic/ggrc-core,josthkko/ggrc-core,edofic/ggrc-core,kr41/ggrc-core,prasannav7/ggrc-core,prasannav7/ggrc-core,edofic/ggrc-core,plamut/ggrc-core,AleksNeStu/ggrc-core,josthkko/ggrc-core,VinnieJohns/ggrc-core,andrei-karalionak/ggrc-core,josthkko/ggrc-core,plamut/ggrc-core,selahssea/ggrc-core
|
VIRTUALENV_DIR = "virtual_env/"
VIRTUALENV_ACTIVATE = VIRTUALENV_DIR + "bin/activate_this.py"
LOGS = "logs/"
YAML = "/etc/ggrc_test.yaml"
RESOURCES = "resources/"
REQUIREMENTS = RESOURCES + "requirements.txt"
SRC = "src/"
Remove operations in module reserved for declaring constants.
|
VIRTUALENV_DIR = "virtual_env/"
BIN_DIR = "bin/"
VIRTUALENV_ACTIVATE = "activate_this.py"
LOGS = "logs/"
YAML = "/etc/ggrc_test.yaml"
RESOURCES = "resources/"
REQUIREMENTS = RESOURCES + "requirements.txt"
SRC = "src/"
CHROME_DRIVER = "chromedriver"
|
<commit_before>VIRTUALENV_DIR = "virtual_env/"
VIRTUALENV_ACTIVATE = VIRTUALENV_DIR + "bin/activate_this.py"
LOGS = "logs/"
YAML = "/etc/ggrc_test.yaml"
RESOURCES = "resources/"
REQUIREMENTS = RESOURCES + "requirements.txt"
SRC = "src/"
<commit_msg>Remove operations in module reserved for declaring constants.<commit_after>
|
VIRTUALENV_DIR = "virtual_env/"
BIN_DIR = "bin/"
VIRTUALENV_ACTIVATE = "activate_this.py"
LOGS = "logs/"
YAML = "/etc/ggrc_test.yaml"
RESOURCES = "resources/"
REQUIREMENTS = RESOURCES + "requirements.txt"
SRC = "src/"
CHROME_DRIVER = "chromedriver"
|
VIRTUALENV_DIR = "virtual_env/"
VIRTUALENV_ACTIVATE = VIRTUALENV_DIR + "bin/activate_this.py"
LOGS = "logs/"
YAML = "/etc/ggrc_test.yaml"
RESOURCES = "resources/"
REQUIREMENTS = RESOURCES + "requirements.txt"
SRC = "src/"
Remove operations in module reserved for declaring constants.VIRTUALENV_DIR = "virtual_env/"
BIN_DIR = "bin/"
VIRTUALENV_ACTIVATE = "activate_this.py"
LOGS = "logs/"
YAML = "/etc/ggrc_test.yaml"
RESOURCES = "resources/"
REQUIREMENTS = RESOURCES + "requirements.txt"
SRC = "src/"
CHROME_DRIVER = "chromedriver"
|
<commit_before>VIRTUALENV_DIR = "virtual_env/"
VIRTUALENV_ACTIVATE = VIRTUALENV_DIR + "bin/activate_this.py"
LOGS = "logs/"
YAML = "/etc/ggrc_test.yaml"
RESOURCES = "resources/"
REQUIREMENTS = RESOURCES + "requirements.txt"
SRC = "src/"
<commit_msg>Remove operations in module reserved for declaring constants.<commit_after>VIRTUALENV_DIR = "virtual_env/"
BIN_DIR = "bin/"
VIRTUALENV_ACTIVATE = "activate_this.py"
LOGS = "logs/"
YAML = "/etc/ggrc_test.yaml"
RESOURCES = "resources/"
REQUIREMENTS = RESOURCES + "requirements.txt"
SRC = "src/"
CHROME_DRIVER = "chromedriver"
|
5f6d994dfde18206e000537510b87f451234f1d3
|
installer/installer_config/forms.py
|
installer/installer_config/forms.py
|
from django import forms
from django.forms.models import ModelForm
from installer_config.models import EnvironmentProfile, Package, TerminalPrompt
class EnvironmentForm(ModelForm):
packages = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple,
queryset=Package.objects.all())
class Meta:
model = EnvironmentProfile
exclude = ('user',)
|
from django import forms
from django.forms.models import ModelForm
from installer_config.models import EnvironmentProfile, UserChoice
class EnvironmentForm(ModelForm):
packages = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple,
queryset=UserChoice.objects.all())
class Meta:
model = EnvironmentProfile
exclude = ('user',)
|
Fix form to query UserChoices, not Packages
|
Fix form to query UserChoices, not Packages
|
Python
|
mit
|
ezPy-co/ezpy,ezPy-co/ezpy,alibulota/Package_Installer,alibulota/Package_Installer
|
from django import forms
from django.forms.models import ModelForm
from installer_config.models import EnvironmentProfile, Package, TerminalPrompt
class EnvironmentForm(ModelForm):
packages = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple,
queryset=Package.objects.all())
class Meta:
model = EnvironmentProfile
exclude = ('user',)
Fix form to query UserChoices, not Packages
|
from django import forms
from django.forms.models import ModelForm
from installer_config.models import EnvironmentProfile, UserChoice
class EnvironmentForm(ModelForm):
packages = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple,
queryset=UserChoice.objects.all())
class Meta:
model = EnvironmentProfile
exclude = ('user',)
|
<commit_before>from django import forms
from django.forms.models import ModelForm
from installer_config.models import EnvironmentProfile, Package, TerminalPrompt
class EnvironmentForm(ModelForm):
packages = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple,
queryset=Package.objects.all())
class Meta:
model = EnvironmentProfile
exclude = ('user',)
<commit_msg>Fix form to query UserChoices, not Packages<commit_after>
|
from django import forms
from django.forms.models import ModelForm
from installer_config.models import EnvironmentProfile, UserChoice
class EnvironmentForm(ModelForm):
packages = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple,
queryset=UserChoice.objects.all())
class Meta:
model = EnvironmentProfile
exclude = ('user',)
|
from django import forms
from django.forms.models import ModelForm
from installer_config.models import EnvironmentProfile, Package, TerminalPrompt
class EnvironmentForm(ModelForm):
packages = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple,
queryset=Package.objects.all())
class Meta:
model = EnvironmentProfile
exclude = ('user',)
Fix form to query UserChoices, not Packagesfrom django import forms
from django.forms.models import ModelForm
from installer_config.models import EnvironmentProfile, UserChoice
class EnvironmentForm(ModelForm):
packages = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple,
queryset=UserChoice.objects.all())
class Meta:
model = EnvironmentProfile
exclude = ('user',)
|
<commit_before>from django import forms
from django.forms.models import ModelForm
from installer_config.models import EnvironmentProfile, Package, TerminalPrompt
class EnvironmentForm(ModelForm):
packages = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple,
queryset=Package.objects.all())
class Meta:
model = EnvironmentProfile
exclude = ('user',)
<commit_msg>Fix form to query UserChoices, not Packages<commit_after>from django import forms
from django.forms.models import ModelForm
from installer_config.models import EnvironmentProfile, UserChoice
class EnvironmentForm(ModelForm):
packages = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple,
queryset=UserChoice.objects.all())
class Meta:
model = EnvironmentProfile
exclude = ('user',)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.