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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e8caf759d9e120b08a2c7ec456c16245b1caf235
|
setup.py
|
setup.py
|
#!/usr/bin/env python
import os
import sys
import skosprovider
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
packages = [
'skosprovider',
]
requires = [
'language-tags',
'rfc3987',
'pyld',
'html5lib'
]
setup(
name='skosprovider',
version='0.7.1',
description='Abstraction layer for SKOS vocabularies.',
long_description=open('README.rst').read(),
author='Koen Van Daele',
author_email='koen_van_daele@telenet.be',
url='http://github.com/koenedaele/skosprovider',
packages=packages,
package_data={'': ['LICENSE']},
package_dir={'skosprovider': 'skosprovider'},
include_package_data=True,
install_requires=requires,
license='MIT',
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
],
test_suite='nose.collector'
)
|
#!/usr/bin/env python
import os
import sys
import skosprovider
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
packages = [
'skosprovider',
]
requires = [
'language-tags',
'rfc3987',
'pyld',
'html5lib'
]
setup(
name='skosprovider',
version='0.7.1',
description='Abstraction layer for SKOS vocabularies.',
long_description=open('README.rst').read(),
long_description_content_type='text/x-rst',
author='Koen Van Daele',
author_email='koen_van_daele@telenet.be',
url='http://github.com/koenedaele/skosprovider',
packages=packages,
package_data={'': ['LICENSE']},
package_dir={'skosprovider': 'skosprovider'},
include_package_data=True,
install_requires=requires,
license='MIT',
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
],
test_suite='nose.collector'
)
|
Add long description content type.
|
Add long description content type.
|
Python
|
mit
|
koenedaele/skosprovider
|
#!/usr/bin/env python
import os
import sys
import skosprovider
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
packages = [
'skosprovider',
]
requires = [
'language-tags',
'rfc3987',
'pyld',
'html5lib'
]
setup(
name='skosprovider',
version='0.7.1',
description='Abstraction layer for SKOS vocabularies.',
long_description=open('README.rst').read(),
author='Koen Van Daele',
author_email='koen_van_daele@telenet.be',
url='http://github.com/koenedaele/skosprovider',
packages=packages,
package_data={'': ['LICENSE']},
package_dir={'skosprovider': 'skosprovider'},
include_package_data=True,
install_requires=requires,
license='MIT',
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
],
test_suite='nose.collector'
)
Add long description content type.
|
#!/usr/bin/env python
import os
import sys
import skosprovider
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
packages = [
'skosprovider',
]
requires = [
'language-tags',
'rfc3987',
'pyld',
'html5lib'
]
setup(
name='skosprovider',
version='0.7.1',
description='Abstraction layer for SKOS vocabularies.',
long_description=open('README.rst').read(),
long_description_content_type='text/x-rst',
author='Koen Van Daele',
author_email='koen_van_daele@telenet.be',
url='http://github.com/koenedaele/skosprovider',
packages=packages,
package_data={'': ['LICENSE']},
package_dir={'skosprovider': 'skosprovider'},
include_package_data=True,
install_requires=requires,
license='MIT',
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
],
test_suite='nose.collector'
)
|
<commit_before>#!/usr/bin/env python
import os
import sys
import skosprovider
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
packages = [
'skosprovider',
]
requires = [
'language-tags',
'rfc3987',
'pyld',
'html5lib'
]
setup(
name='skosprovider',
version='0.7.1',
description='Abstraction layer for SKOS vocabularies.',
long_description=open('README.rst').read(),
author='Koen Van Daele',
author_email='koen_van_daele@telenet.be',
url='http://github.com/koenedaele/skosprovider',
packages=packages,
package_data={'': ['LICENSE']},
package_dir={'skosprovider': 'skosprovider'},
include_package_data=True,
install_requires=requires,
license='MIT',
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
],
test_suite='nose.collector'
)
<commit_msg>Add long description content type.<commit_after>
|
#!/usr/bin/env python
import os
import sys
import skosprovider
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
packages = [
'skosprovider',
]
requires = [
'language-tags',
'rfc3987',
'pyld',
'html5lib'
]
setup(
name='skosprovider',
version='0.7.1',
description='Abstraction layer for SKOS vocabularies.',
long_description=open('README.rst').read(),
long_description_content_type='text/x-rst',
author='Koen Van Daele',
author_email='koen_van_daele@telenet.be',
url='http://github.com/koenedaele/skosprovider',
packages=packages,
package_data={'': ['LICENSE']},
package_dir={'skosprovider': 'skosprovider'},
include_package_data=True,
install_requires=requires,
license='MIT',
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
],
test_suite='nose.collector'
)
|
#!/usr/bin/env python
import os
import sys
import skosprovider
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
packages = [
'skosprovider',
]
requires = [
'language-tags',
'rfc3987',
'pyld',
'html5lib'
]
setup(
name='skosprovider',
version='0.7.1',
description='Abstraction layer for SKOS vocabularies.',
long_description=open('README.rst').read(),
author='Koen Van Daele',
author_email='koen_van_daele@telenet.be',
url='http://github.com/koenedaele/skosprovider',
packages=packages,
package_data={'': ['LICENSE']},
package_dir={'skosprovider': 'skosprovider'},
include_package_data=True,
install_requires=requires,
license='MIT',
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
],
test_suite='nose.collector'
)
Add long description content type.#!/usr/bin/env python
import os
import sys
import skosprovider
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
packages = [
'skosprovider',
]
requires = [
'language-tags',
'rfc3987',
'pyld',
'html5lib'
]
setup(
name='skosprovider',
version='0.7.1',
description='Abstraction layer for SKOS vocabularies.',
long_description=open('README.rst').read(),
long_description_content_type='text/x-rst',
author='Koen Van Daele',
author_email='koen_van_daele@telenet.be',
url='http://github.com/koenedaele/skosprovider',
packages=packages,
package_data={'': ['LICENSE']},
package_dir={'skosprovider': 'skosprovider'},
include_package_data=True,
install_requires=requires,
license='MIT',
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
],
test_suite='nose.collector'
)
|
<commit_before>#!/usr/bin/env python
import os
import sys
import skosprovider
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
packages = [
'skosprovider',
]
requires = [
'language-tags',
'rfc3987',
'pyld',
'html5lib'
]
setup(
name='skosprovider',
version='0.7.1',
description='Abstraction layer for SKOS vocabularies.',
long_description=open('README.rst').read(),
author='Koen Van Daele',
author_email='koen_van_daele@telenet.be',
url='http://github.com/koenedaele/skosprovider',
packages=packages,
package_data={'': ['LICENSE']},
package_dir={'skosprovider': 'skosprovider'},
include_package_data=True,
install_requires=requires,
license='MIT',
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
],
test_suite='nose.collector'
)
<commit_msg>Add long description content type.<commit_after>#!/usr/bin/env python
import os
import sys
import skosprovider
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
packages = [
'skosprovider',
]
requires = [
'language-tags',
'rfc3987',
'pyld',
'html5lib'
]
setup(
name='skosprovider',
version='0.7.1',
description='Abstraction layer for SKOS vocabularies.',
long_description=open('README.rst').read(),
long_description_content_type='text/x-rst',
author='Koen Van Daele',
author_email='koen_van_daele@telenet.be',
url='http://github.com/koenedaele/skosprovider',
packages=packages,
package_data={'': ['LICENSE']},
package_dir={'skosprovider': 'skosprovider'},
include_package_data=True,
install_requires=requires,
license='MIT',
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
],
test_suite='nose.collector'
)
|
3016fa866ee2a3b9c9ba6ce6fcaf4d83e22c4ffe
|
setup.py
|
setup.py
|
from distutils.core import setup
with open('requirements.txt') as req_file:
requirements = req_file.read().splitlines()
setup(
name='fleet-py',
install_requires=requirements,
version='0.1.0',
description='Fleet SDK Wrapper for Python',
author='Sukrit Khera',
author_email='',
url='https://github.com/totem/fleet-py',
license='MIT',
platforms='Posix; MacOS X;',
packages=['fleet', 'fleet.client', 'fleet.deploy']
)
|
from distutils.core import setup
with open('requirements.txt') as req_file:
requirements = req_file.read().splitlines()
setup(
name='fleet-py',
install_requires=requirements,
version='0.1.1',
description='Fleet SDK Wrapper for Python',
author='Sukrit Khera',
author_email='',
url='https://github.com/totem/fleet-py',
license='MIT',
platforms='Posix; MacOS X;',
packages=['fleet', 'fleet.client', 'fleet.deploy']
)
|
Bump up version to 0.1.1
|
Bump up version to 0.1.1
|
Python
|
mit
|
totem/fleet-py
|
from distutils.core import setup
with open('requirements.txt') as req_file:
requirements = req_file.read().splitlines()
setup(
name='fleet-py',
install_requires=requirements,
version='0.1.0',
description='Fleet SDK Wrapper for Python',
author='Sukrit Khera',
author_email='',
url='https://github.com/totem/fleet-py',
license='MIT',
platforms='Posix; MacOS X;',
packages=['fleet', 'fleet.client', 'fleet.deploy']
)
Bump up version to 0.1.1
|
from distutils.core import setup
with open('requirements.txt') as req_file:
requirements = req_file.read().splitlines()
setup(
name='fleet-py',
install_requires=requirements,
version='0.1.1',
description='Fleet SDK Wrapper for Python',
author='Sukrit Khera',
author_email='',
url='https://github.com/totem/fleet-py',
license='MIT',
platforms='Posix; MacOS X;',
packages=['fleet', 'fleet.client', 'fleet.deploy']
)
|
<commit_before>from distutils.core import setup
with open('requirements.txt') as req_file:
requirements = req_file.read().splitlines()
setup(
name='fleet-py',
install_requires=requirements,
version='0.1.0',
description='Fleet SDK Wrapper for Python',
author='Sukrit Khera',
author_email='',
url='https://github.com/totem/fleet-py',
license='MIT',
platforms='Posix; MacOS X;',
packages=['fleet', 'fleet.client', 'fleet.deploy']
)
<commit_msg>Bump up version to 0.1.1<commit_after>
|
from distutils.core import setup
with open('requirements.txt') as req_file:
requirements = req_file.read().splitlines()
setup(
name='fleet-py',
install_requires=requirements,
version='0.1.1',
description='Fleet SDK Wrapper for Python',
author='Sukrit Khera',
author_email='',
url='https://github.com/totem/fleet-py',
license='MIT',
platforms='Posix; MacOS X;',
packages=['fleet', 'fleet.client', 'fleet.deploy']
)
|
from distutils.core import setup
with open('requirements.txt') as req_file:
requirements = req_file.read().splitlines()
setup(
name='fleet-py',
install_requires=requirements,
version='0.1.0',
description='Fleet SDK Wrapper for Python',
author='Sukrit Khera',
author_email='',
url='https://github.com/totem/fleet-py',
license='MIT',
platforms='Posix; MacOS X;',
packages=['fleet', 'fleet.client', 'fleet.deploy']
)
Bump up version to 0.1.1from distutils.core import setup
with open('requirements.txt') as req_file:
requirements = req_file.read().splitlines()
setup(
name='fleet-py',
install_requires=requirements,
version='0.1.1',
description='Fleet SDK Wrapper for Python',
author='Sukrit Khera',
author_email='',
url='https://github.com/totem/fleet-py',
license='MIT',
platforms='Posix; MacOS X;',
packages=['fleet', 'fleet.client', 'fleet.deploy']
)
|
<commit_before>from distutils.core import setup
with open('requirements.txt') as req_file:
requirements = req_file.read().splitlines()
setup(
name='fleet-py',
install_requires=requirements,
version='0.1.0',
description='Fleet SDK Wrapper for Python',
author='Sukrit Khera',
author_email='',
url='https://github.com/totem/fleet-py',
license='MIT',
platforms='Posix; MacOS X;',
packages=['fleet', 'fleet.client', 'fleet.deploy']
)
<commit_msg>Bump up version to 0.1.1<commit_after>from distutils.core import setup
with open('requirements.txt') as req_file:
requirements = req_file.read().splitlines()
setup(
name='fleet-py',
install_requires=requirements,
version='0.1.1',
description='Fleet SDK Wrapper for Python',
author='Sukrit Khera',
author_email='',
url='https://github.com/totem/fleet-py',
license='MIT',
platforms='Posix; MacOS X;',
packages=['fleet', 'fleet.client', 'fleet.deploy']
)
|
13eb0661c9025eed45d02dea93c622b87366b0c8
|
setup.py
|
setup.py
|
# -*- coding: utf-8 -*-
"""installer script for pywikibot 2.0 framework"""
#
# (C) Pywikipedia team, 2009-2012
#
__version__ = '$Id$'
#
# Distributed under the terms of the MIT license.
#
import sys
from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
if sys.version_info[0] != 2:
raise RuntimeError("ERROR: Pywikipediabot only runs under Python 2")
if sys.version_info[1] < 6:
raise RuntimeError("ERROR: Pywikipediabot only runs under Python 2.6 or higher")
else:
depend = ['httplib2>=0.6.0']
setup(name='Pywikipediabot',
version='2.0alpha',
description='Python Wikipedia Bot Framework',
license='MIT',
packages=find_packages(),
install_requires=depend,
test_suite="tests",
)
# automatically launch generate_user_files.py
import subprocess
python = sys.executable
python = python.replace("pythonw.exe", "python.exe") # for Windows
ignore = subprocess.call([python, "generate_user_files.py"])
|
# -*- coding: utf-8 -*-
"""installer script for pywikibot 2.0 framework"""
#
# (C) Pywikipedia team, 2009-2012
#
__version__ = '$Id$'
#
# Distributed under the terms of the MIT license.
#
import sys
from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
if sys.version_info[0] != 2:
raise RuntimeError("ERROR: Pywikipediabot only runs under Python 2")
if sys.version_info[1] < 6:
raise RuntimeError("ERROR: Pywikipediabot only runs under Python 2.6 or higher")
else:
depend = ['httplib2>=0.6.0', 'simplejson']
setup(name='Pywikipediabot',
version='2.0alpha',
description='Python Wikipedia Bot Framework',
license='MIT',
packages=find_packages(),
install_requires=depend,
test_suite="tests",
)
# automatically launch generate_user_files.py
import subprocess
python = sys.executable
python = python.replace("pythonw.exe", "python.exe") # for Windows
ignore = subprocess.call([python, "generate_user_files.py"])
|
Add simplejson as a required module
|
Add simplejson as a required module
git-svn-id: 9a050473c2aca1e14f53d73349e19b938c2cf203@11666 6a7f98fc-eeb0-4dc1-a6e2-c2c589a08aa6
|
Python
|
mit
|
legoktm/pywikipedia-rewrite
|
# -*- coding: utf-8 -*-
"""installer script for pywikibot 2.0 framework"""
#
# (C) Pywikipedia team, 2009-2012
#
__version__ = '$Id$'
#
# Distributed under the terms of the MIT license.
#
import sys
from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
if sys.version_info[0] != 2:
raise RuntimeError("ERROR: Pywikipediabot only runs under Python 2")
if sys.version_info[1] < 6:
raise RuntimeError("ERROR: Pywikipediabot only runs under Python 2.6 or higher")
else:
depend = ['httplib2>=0.6.0']
setup(name='Pywikipediabot',
version='2.0alpha',
description='Python Wikipedia Bot Framework',
license='MIT',
packages=find_packages(),
install_requires=depend,
test_suite="tests",
)
# automatically launch generate_user_files.py
import subprocess
python = sys.executable
python = python.replace("pythonw.exe", "python.exe") # for Windows
ignore = subprocess.call([python, "generate_user_files.py"])
Add simplejson as a required module
git-svn-id: 9a050473c2aca1e14f53d73349e19b938c2cf203@11666 6a7f98fc-eeb0-4dc1-a6e2-c2c589a08aa6
|
# -*- coding: utf-8 -*-
"""installer script for pywikibot 2.0 framework"""
#
# (C) Pywikipedia team, 2009-2012
#
__version__ = '$Id$'
#
# Distributed under the terms of the MIT license.
#
import sys
from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
if sys.version_info[0] != 2:
raise RuntimeError("ERROR: Pywikipediabot only runs under Python 2")
if sys.version_info[1] < 6:
raise RuntimeError("ERROR: Pywikipediabot only runs under Python 2.6 or higher")
else:
depend = ['httplib2>=0.6.0', 'simplejson']
setup(name='Pywikipediabot',
version='2.0alpha',
description='Python Wikipedia Bot Framework',
license='MIT',
packages=find_packages(),
install_requires=depend,
test_suite="tests",
)
# automatically launch generate_user_files.py
import subprocess
python = sys.executable
python = python.replace("pythonw.exe", "python.exe") # for Windows
ignore = subprocess.call([python, "generate_user_files.py"])
|
<commit_before># -*- coding: utf-8 -*-
"""installer script for pywikibot 2.0 framework"""
#
# (C) Pywikipedia team, 2009-2012
#
__version__ = '$Id$'
#
# Distributed under the terms of the MIT license.
#
import sys
from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
if sys.version_info[0] != 2:
raise RuntimeError("ERROR: Pywikipediabot only runs under Python 2")
if sys.version_info[1] < 6:
raise RuntimeError("ERROR: Pywikipediabot only runs under Python 2.6 or higher")
else:
depend = ['httplib2>=0.6.0']
setup(name='Pywikipediabot',
version='2.0alpha',
description='Python Wikipedia Bot Framework',
license='MIT',
packages=find_packages(),
install_requires=depend,
test_suite="tests",
)
# automatically launch generate_user_files.py
import subprocess
python = sys.executable
python = python.replace("pythonw.exe", "python.exe") # for Windows
ignore = subprocess.call([python, "generate_user_files.py"])
<commit_msg>Add simplejson as a required module
git-svn-id: 9a050473c2aca1e14f53d73349e19b938c2cf203@11666 6a7f98fc-eeb0-4dc1-a6e2-c2c589a08aa6<commit_after>
|
# -*- coding: utf-8 -*-
"""installer script for pywikibot 2.0 framework"""
#
# (C) Pywikipedia team, 2009-2012
#
__version__ = '$Id$'
#
# Distributed under the terms of the MIT license.
#
import sys
from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
if sys.version_info[0] != 2:
raise RuntimeError("ERROR: Pywikipediabot only runs under Python 2")
if sys.version_info[1] < 6:
raise RuntimeError("ERROR: Pywikipediabot only runs under Python 2.6 or higher")
else:
depend = ['httplib2>=0.6.0', 'simplejson']
setup(name='Pywikipediabot',
version='2.0alpha',
description='Python Wikipedia Bot Framework',
license='MIT',
packages=find_packages(),
install_requires=depend,
test_suite="tests",
)
# automatically launch generate_user_files.py
import subprocess
python = sys.executable
python = python.replace("pythonw.exe", "python.exe") # for Windows
ignore = subprocess.call([python, "generate_user_files.py"])
|
# -*- coding: utf-8 -*-
"""installer script for pywikibot 2.0 framework"""
#
# (C) Pywikipedia team, 2009-2012
#
__version__ = '$Id$'
#
# Distributed under the terms of the MIT license.
#
import sys
from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
if sys.version_info[0] != 2:
raise RuntimeError("ERROR: Pywikipediabot only runs under Python 2")
if sys.version_info[1] < 6:
raise RuntimeError("ERROR: Pywikipediabot only runs under Python 2.6 or higher")
else:
depend = ['httplib2>=0.6.0']
setup(name='Pywikipediabot',
version='2.0alpha',
description='Python Wikipedia Bot Framework',
license='MIT',
packages=find_packages(),
install_requires=depend,
test_suite="tests",
)
# automatically launch generate_user_files.py
import subprocess
python = sys.executable
python = python.replace("pythonw.exe", "python.exe") # for Windows
ignore = subprocess.call([python, "generate_user_files.py"])
Add simplejson as a required module
git-svn-id: 9a050473c2aca1e14f53d73349e19b938c2cf203@11666 6a7f98fc-eeb0-4dc1-a6e2-c2c589a08aa6# -*- coding: utf-8 -*-
"""installer script for pywikibot 2.0 framework"""
#
# (C) Pywikipedia team, 2009-2012
#
__version__ = '$Id$'
#
# Distributed under the terms of the MIT license.
#
import sys
from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
if sys.version_info[0] != 2:
raise RuntimeError("ERROR: Pywikipediabot only runs under Python 2")
if sys.version_info[1] < 6:
raise RuntimeError("ERROR: Pywikipediabot only runs under Python 2.6 or higher")
else:
depend = ['httplib2>=0.6.0', 'simplejson']
setup(name='Pywikipediabot',
version='2.0alpha',
description='Python Wikipedia Bot Framework',
license='MIT',
packages=find_packages(),
install_requires=depend,
test_suite="tests",
)
# automatically launch generate_user_files.py
import subprocess
python = sys.executable
python = python.replace("pythonw.exe", "python.exe") # for Windows
ignore = subprocess.call([python, "generate_user_files.py"])
|
<commit_before># -*- coding: utf-8 -*-
"""installer script for pywikibot 2.0 framework"""
#
# (C) Pywikipedia team, 2009-2012
#
__version__ = '$Id$'
#
# Distributed under the terms of the MIT license.
#
import sys
from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
if sys.version_info[0] != 2:
raise RuntimeError("ERROR: Pywikipediabot only runs under Python 2")
if sys.version_info[1] < 6:
raise RuntimeError("ERROR: Pywikipediabot only runs under Python 2.6 or higher")
else:
depend = ['httplib2>=0.6.0']
setup(name='Pywikipediabot',
version='2.0alpha',
description='Python Wikipedia Bot Framework',
license='MIT',
packages=find_packages(),
install_requires=depend,
test_suite="tests",
)
# automatically launch generate_user_files.py
import subprocess
python = sys.executable
python = python.replace("pythonw.exe", "python.exe") # for Windows
ignore = subprocess.call([python, "generate_user_files.py"])
<commit_msg>Add simplejson as a required module
git-svn-id: 9a050473c2aca1e14f53d73349e19b938c2cf203@11666 6a7f98fc-eeb0-4dc1-a6e2-c2c589a08aa6<commit_after># -*- coding: utf-8 -*-
"""installer script for pywikibot 2.0 framework"""
#
# (C) Pywikipedia team, 2009-2012
#
__version__ = '$Id$'
#
# Distributed under the terms of the MIT license.
#
import sys
from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
if sys.version_info[0] != 2:
raise RuntimeError("ERROR: Pywikipediabot only runs under Python 2")
if sys.version_info[1] < 6:
raise RuntimeError("ERROR: Pywikipediabot only runs under Python 2.6 or higher")
else:
depend = ['httplib2>=0.6.0', 'simplejson']
setup(name='Pywikipediabot',
version='2.0alpha',
description='Python Wikipedia Bot Framework',
license='MIT',
packages=find_packages(),
install_requires=depend,
test_suite="tests",
)
# automatically launch generate_user_files.py
import subprocess
python = sys.executable
python = python.replace("pythonw.exe", "python.exe") # for Windows
ignore = subprocess.call([python, "generate_user_files.py"])
|
d9ed64e66486905b53b020c0ae75cd3cffd232d2
|
setup.py
|
setup.py
|
from setuptools import find_packages, setup
from virtualenvapi import __version__
setup(
name='virtualenv-api',
version=__version__,
license='BSD',
author='Sam Kingston and AUTHORS',
author_email='sam@sjkwi.com.au',
description='An API for virtualenv/pip',
long_description=open('README.rst', 'r').read(),
url='https://github.com/sjkingo/virtualenv-api',
install_requires=['six',
'virtualenv'
],
packages=find_packages(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
from setuptools import find_packages, setup
from virtualenvapi import __version__
setup(
name='virtualenv-api',
version=__version__,
license='BSD',
author='Sam Kingston and AUTHORS',
author_email='sam@sjkwi.com.au',
description='An API for virtualenv/pip',
long_description=open('README.rst', 'r').read(),
url='https://github.com/sjkingo/virtualenv-api',
install_requires=['six',
'virtualenv'
],
packages=find_packages(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD 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.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
Add 3.6 to trove classifiers
|
Add 3.6 to trove classifiers [skipci]
|
Python
|
bsd-2-clause
|
sjkingo/virtualenv-api
|
from setuptools import find_packages, setup
from virtualenvapi import __version__
setup(
name='virtualenv-api',
version=__version__,
license='BSD',
author='Sam Kingston and AUTHORS',
author_email='sam@sjkwi.com.au',
description='An API for virtualenv/pip',
long_description=open('README.rst', 'r').read(),
url='https://github.com/sjkingo/virtualenv-api',
install_requires=['six',
'virtualenv'
],
packages=find_packages(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
Add 3.6 to trove classifiers [skipci]
|
from setuptools import find_packages, setup
from virtualenvapi import __version__
setup(
name='virtualenv-api',
version=__version__,
license='BSD',
author='Sam Kingston and AUTHORS',
author_email='sam@sjkwi.com.au',
description='An API for virtualenv/pip',
long_description=open('README.rst', 'r').read(),
url='https://github.com/sjkingo/virtualenv-api',
install_requires=['six',
'virtualenv'
],
packages=find_packages(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD 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.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
<commit_before>from setuptools import find_packages, setup
from virtualenvapi import __version__
setup(
name='virtualenv-api',
version=__version__,
license='BSD',
author='Sam Kingston and AUTHORS',
author_email='sam@sjkwi.com.au',
description='An API for virtualenv/pip',
long_description=open('README.rst', 'r').read(),
url='https://github.com/sjkingo/virtualenv-api',
install_requires=['six',
'virtualenv'
],
packages=find_packages(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
<commit_msg>Add 3.6 to trove classifiers [skipci]<commit_after>
|
from setuptools import find_packages, setup
from virtualenvapi import __version__
setup(
name='virtualenv-api',
version=__version__,
license='BSD',
author='Sam Kingston and AUTHORS',
author_email='sam@sjkwi.com.au',
description='An API for virtualenv/pip',
long_description=open('README.rst', 'r').read(),
url='https://github.com/sjkingo/virtualenv-api',
install_requires=['six',
'virtualenv'
],
packages=find_packages(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD 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.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
from setuptools import find_packages, setup
from virtualenvapi import __version__
setup(
name='virtualenv-api',
version=__version__,
license='BSD',
author='Sam Kingston and AUTHORS',
author_email='sam@sjkwi.com.au',
description='An API for virtualenv/pip',
long_description=open('README.rst', 'r').read(),
url='https://github.com/sjkingo/virtualenv-api',
install_requires=['six',
'virtualenv'
],
packages=find_packages(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
Add 3.6 to trove classifiers [skipci]from setuptools import find_packages, setup
from virtualenvapi import __version__
setup(
name='virtualenv-api',
version=__version__,
license='BSD',
author='Sam Kingston and AUTHORS',
author_email='sam@sjkwi.com.au',
description='An API for virtualenv/pip',
long_description=open('README.rst', 'r').read(),
url='https://github.com/sjkingo/virtualenv-api',
install_requires=['six',
'virtualenv'
],
packages=find_packages(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD 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.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
<commit_before>from setuptools import find_packages, setup
from virtualenvapi import __version__
setup(
name='virtualenv-api',
version=__version__,
license='BSD',
author='Sam Kingston and AUTHORS',
author_email='sam@sjkwi.com.au',
description='An API for virtualenv/pip',
long_description=open('README.rst', 'r').read(),
url='https://github.com/sjkingo/virtualenv-api',
install_requires=['six',
'virtualenv'
],
packages=find_packages(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
<commit_msg>Add 3.6 to trove classifiers [skipci]<commit_after>from setuptools import find_packages, setup
from virtualenvapi import __version__
setup(
name='virtualenv-api',
version=__version__,
license='BSD',
author='Sam Kingston and AUTHORS',
author_email='sam@sjkwi.com.au',
description='An API for virtualenv/pip',
long_description=open('README.rst', 'r').read(),
url='https://github.com/sjkingo/virtualenv-api',
install_requires=['six',
'virtualenv'
],
packages=find_packages(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD 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.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
98e88294f1648776f053985d445a16649bc41b6f
|
setup.py
|
setup.py
|
from setuptools import setup
with open("README.rst") as f:
readme = f.read()
setup(
name="rply",
description="A pure Python Lex/Yacc that works with RPython",
long_description=readme,
version="0.7.1",
author="Alex Gaynor",
author_email="alex.gaynor@gmail.com",
packages=["rply"],
)
|
from setuptools import setup
with open("README.rst") as f:
readme = f.read()
setup(
name="rply",
description="A pure Python Lex/Yacc that works with RPython",
long_description=readme,
version="0.7.2",
author="Alex Gaynor",
author_email="alex.gaynor@gmail.com",
packages=["rply"],
)
|
Bump version number for release
|
Bump version number for release
|
Python
|
bsd-3-clause
|
agamdua/rply,agamdua/rply
|
from setuptools import setup
with open("README.rst") as f:
readme = f.read()
setup(
name="rply",
description="A pure Python Lex/Yacc that works with RPython",
long_description=readme,
version="0.7.1",
author="Alex Gaynor",
author_email="alex.gaynor@gmail.com",
packages=["rply"],
)
Bump version number for release
|
from setuptools import setup
with open("README.rst") as f:
readme = f.read()
setup(
name="rply",
description="A pure Python Lex/Yacc that works with RPython",
long_description=readme,
version="0.7.2",
author="Alex Gaynor",
author_email="alex.gaynor@gmail.com",
packages=["rply"],
)
|
<commit_before>from setuptools import setup
with open("README.rst") as f:
readme = f.read()
setup(
name="rply",
description="A pure Python Lex/Yacc that works with RPython",
long_description=readme,
version="0.7.1",
author="Alex Gaynor",
author_email="alex.gaynor@gmail.com",
packages=["rply"],
)
<commit_msg>Bump version number for release<commit_after>
|
from setuptools import setup
with open("README.rst") as f:
readme = f.read()
setup(
name="rply",
description="A pure Python Lex/Yacc that works with RPython",
long_description=readme,
version="0.7.2",
author="Alex Gaynor",
author_email="alex.gaynor@gmail.com",
packages=["rply"],
)
|
from setuptools import setup
with open("README.rst") as f:
readme = f.read()
setup(
name="rply",
description="A pure Python Lex/Yacc that works with RPython",
long_description=readme,
version="0.7.1",
author="Alex Gaynor",
author_email="alex.gaynor@gmail.com",
packages=["rply"],
)
Bump version number for releasefrom setuptools import setup
with open("README.rst") as f:
readme = f.read()
setup(
name="rply",
description="A pure Python Lex/Yacc that works with RPython",
long_description=readme,
version="0.7.2",
author="Alex Gaynor",
author_email="alex.gaynor@gmail.com",
packages=["rply"],
)
|
<commit_before>from setuptools import setup
with open("README.rst") as f:
readme = f.read()
setup(
name="rply",
description="A pure Python Lex/Yacc that works with RPython",
long_description=readme,
version="0.7.1",
author="Alex Gaynor",
author_email="alex.gaynor@gmail.com",
packages=["rply"],
)
<commit_msg>Bump version number for release<commit_after>from setuptools import setup
with open("README.rst") as f:
readme = f.read()
setup(
name="rply",
description="A pure Python Lex/Yacc that works with RPython",
long_description=readme,
version="0.7.2",
author="Alex Gaynor",
author_email="alex.gaynor@gmail.com",
packages=["rply"],
)
|
c8aec8f354cc1166e2f9e6d8e1fc9be454708c36
|
setup.py
|
setup.py
|
#!/usr/bin/env python
from os.path import exists
from setuptools import setup
setup(name='cachey',
version='0.2.0',
description='Caching mindful of computation/storage costs',
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Topic :: Scientific/Engineering",
],
url='http://github.com/dask/cachey/',
maintainer='Matthew Rocklin',
maintainer_email='mrocklin@gmail.com',
license='BSD',
keywords='',
packages=['cachey'],
python_requires='>=3.6',
install_requires=list(open('requirements.txt').read().strip().split('\n')),
long_description=(open('README.md').read() if exists('README.md')
else ''),
zip_safe=False)
|
#!/usr/bin/env python
from os.path import exists
from setuptools import setup
setup(name='cachey',
version='0.2.0',
description='Caching mindful of computation/storage costs',
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Topic :: Scientific/Engineering",
],
url='http://github.com/dask/cachey/',
maintainer='Matthew Rocklin',
maintainer_email='mrocklin@gmail.com',
license='BSD',
keywords='',
packages=['cachey'],
python_requires='>=3.6',
install_requires=list(open('requirements.txt').read().strip().split('\n')),
long_description=(open('README.md').read() if exists('README.md')
else ''),
long_description_content_type='text/markdown',
zip_safe=False)
|
Update content type for description
|
DOC: Update content type for description
PyPI rejects uploads that fail to render.
|
Python
|
bsd-3-clause
|
blaze/cachey
|
#!/usr/bin/env python
from os.path import exists
from setuptools import setup
setup(name='cachey',
version='0.2.0',
description='Caching mindful of computation/storage costs',
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Topic :: Scientific/Engineering",
],
url='http://github.com/dask/cachey/',
maintainer='Matthew Rocklin',
maintainer_email='mrocklin@gmail.com',
license='BSD',
keywords='',
packages=['cachey'],
python_requires='>=3.6',
install_requires=list(open('requirements.txt').read().strip().split('\n')),
long_description=(open('README.md').read() if exists('README.md')
else ''),
zip_safe=False)
DOC: Update content type for description
PyPI rejects uploads that fail to render.
|
#!/usr/bin/env python
from os.path import exists
from setuptools import setup
setup(name='cachey',
version='0.2.0',
description='Caching mindful of computation/storage costs',
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Topic :: Scientific/Engineering",
],
url='http://github.com/dask/cachey/',
maintainer='Matthew Rocklin',
maintainer_email='mrocklin@gmail.com',
license='BSD',
keywords='',
packages=['cachey'],
python_requires='>=3.6',
install_requires=list(open('requirements.txt').read().strip().split('\n')),
long_description=(open('README.md').read() if exists('README.md')
else ''),
long_description_content_type='text/markdown',
zip_safe=False)
|
<commit_before>#!/usr/bin/env python
from os.path import exists
from setuptools import setup
setup(name='cachey',
version='0.2.0',
description='Caching mindful of computation/storage costs',
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Topic :: Scientific/Engineering",
],
url='http://github.com/dask/cachey/',
maintainer='Matthew Rocklin',
maintainer_email='mrocklin@gmail.com',
license='BSD',
keywords='',
packages=['cachey'],
python_requires='>=3.6',
install_requires=list(open('requirements.txt').read().strip().split('\n')),
long_description=(open('README.md').read() if exists('README.md')
else ''),
zip_safe=False)
<commit_msg>DOC: Update content type for description
PyPI rejects uploads that fail to render.<commit_after>
|
#!/usr/bin/env python
from os.path import exists
from setuptools import setup
setup(name='cachey',
version='0.2.0',
description='Caching mindful of computation/storage costs',
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Topic :: Scientific/Engineering",
],
url='http://github.com/dask/cachey/',
maintainer='Matthew Rocklin',
maintainer_email='mrocklin@gmail.com',
license='BSD',
keywords='',
packages=['cachey'],
python_requires='>=3.6',
install_requires=list(open('requirements.txt').read().strip().split('\n')),
long_description=(open('README.md').read() if exists('README.md')
else ''),
long_description_content_type='text/markdown',
zip_safe=False)
|
#!/usr/bin/env python
from os.path import exists
from setuptools import setup
setup(name='cachey',
version='0.2.0',
description='Caching mindful of computation/storage costs',
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Topic :: Scientific/Engineering",
],
url='http://github.com/dask/cachey/',
maintainer='Matthew Rocklin',
maintainer_email='mrocklin@gmail.com',
license='BSD',
keywords='',
packages=['cachey'],
python_requires='>=3.6',
install_requires=list(open('requirements.txt').read().strip().split('\n')),
long_description=(open('README.md').read() if exists('README.md')
else ''),
zip_safe=False)
DOC: Update content type for description
PyPI rejects uploads that fail to render.#!/usr/bin/env python
from os.path import exists
from setuptools import setup
setup(name='cachey',
version='0.2.0',
description='Caching mindful of computation/storage costs',
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Topic :: Scientific/Engineering",
],
url='http://github.com/dask/cachey/',
maintainer='Matthew Rocklin',
maintainer_email='mrocklin@gmail.com',
license='BSD',
keywords='',
packages=['cachey'],
python_requires='>=3.6',
install_requires=list(open('requirements.txt').read().strip().split('\n')),
long_description=(open('README.md').read() if exists('README.md')
else ''),
long_description_content_type='text/markdown',
zip_safe=False)
|
<commit_before>#!/usr/bin/env python
from os.path import exists
from setuptools import setup
setup(name='cachey',
version='0.2.0',
description='Caching mindful of computation/storage costs',
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Topic :: Scientific/Engineering",
],
url='http://github.com/dask/cachey/',
maintainer='Matthew Rocklin',
maintainer_email='mrocklin@gmail.com',
license='BSD',
keywords='',
packages=['cachey'],
python_requires='>=3.6',
install_requires=list(open('requirements.txt').read().strip().split('\n')),
long_description=(open('README.md').read() if exists('README.md')
else ''),
zip_safe=False)
<commit_msg>DOC: Update content type for description
PyPI rejects uploads that fail to render.<commit_after>#!/usr/bin/env python
from os.path import exists
from setuptools import setup
setup(name='cachey',
version='0.2.0',
description='Caching mindful of computation/storage costs',
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Topic :: Scientific/Engineering",
],
url='http://github.com/dask/cachey/',
maintainer='Matthew Rocklin',
maintainer_email='mrocklin@gmail.com',
license='BSD',
keywords='',
packages=['cachey'],
python_requires='>=3.6',
install_requires=list(open('requirements.txt').read().strip().split('\n')),
long_description=(open('README.md').read() if exists('README.md')
else ''),
long_description_content_type='text/markdown',
zip_safe=False)
|
e4a13b635367ed0100281be5f024f44588eb3a0b
|
setup.py
|
setup.py
|
from setuptools import setup, find_packages
__version__ = "0.0.13"
setup(
# package name in pypi
name='django-oscar-api',
# extract version from module.
version=__version__,
description="REST API module for django-oscar",
long_description=open('README.rst').read(),
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: Unix',
'Programming Language :: Python'
],
keywords='',
author='Lars van de Kerkhof, Martijn Jacobs',
author_email='lars@permanentmarkers.nl, martijn@devopsconsulting.nl',
url='https://github.com/tangentlabs/django-oscar-api',
license='BSD',
# include all packages in the egg, except the test package.
packages=find_packages(exclude=['ez_setup', 'examples', '*tests', '*fixtures', 'sandbox']),
# for avoiding conflict have one namespace for all apc related eggs.
namespace_packages=[],
# include non python files
include_package_data=True,
zip_safe=False,
# specify dependencies
install_requires=[
'setuptools',
'django-oscar>=0.6',
'djangorestframework<3.0.0'
],
# mark test target to require extras.
extras_require={
'test': ['django-nose',]
},
)
|
from setuptools import setup, find_packages
__version__ = "0.0.13"
setup(
# package name in pypi
name='django-oscar-api',
# extract version from module.
version=__version__,
description="REST API module for django-oscar",
long_description=open('README.rst').read(),
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: Unix',
'Programming Language :: Python'
],
keywords='',
author='Lars van de Kerkhof, Martijn Jacobs',
author_email='lars@permanentmarkers.nl, martijn@devopsconsulting.nl',
url='https://github.com/tangentlabs/django-oscar-api',
license='BSD',
# include all packages in the egg, except the test package.
packages=find_packages(exclude=['ez_setup', 'examples', '*tests', '*fixtures', 'sandbox']),
# for avoiding conflict have one namespace for all apc related eggs.
namespace_packages=[],
# include non python files
include_package_data=True,
zip_safe=False,
# specify dependencies
install_requires=[
'setuptools',
'django-oscar>=0.6',
'djangorestframework>=3.1.0'
],
# mark test target to require extras.
extras_require={
'test': ['django-nose',]
},
)
|
Use django rest framework > 3.1
|
Use django rest framework > 3.1
|
Python
|
bsd-3-clause
|
regulusweb/django-oscar-api,crgwbr/django-oscar-api
|
from setuptools import setup, find_packages
__version__ = "0.0.13"
setup(
# package name in pypi
name='django-oscar-api',
# extract version from module.
version=__version__,
description="REST API module for django-oscar",
long_description=open('README.rst').read(),
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: Unix',
'Programming Language :: Python'
],
keywords='',
author='Lars van de Kerkhof, Martijn Jacobs',
author_email='lars@permanentmarkers.nl, martijn@devopsconsulting.nl',
url='https://github.com/tangentlabs/django-oscar-api',
license='BSD',
# include all packages in the egg, except the test package.
packages=find_packages(exclude=['ez_setup', 'examples', '*tests', '*fixtures', 'sandbox']),
# for avoiding conflict have one namespace for all apc related eggs.
namespace_packages=[],
# include non python files
include_package_data=True,
zip_safe=False,
# specify dependencies
install_requires=[
'setuptools',
'django-oscar>=0.6',
'djangorestframework<3.0.0'
],
# mark test target to require extras.
extras_require={
'test': ['django-nose',]
},
)
Use django rest framework > 3.1
|
from setuptools import setup, find_packages
__version__ = "0.0.13"
setup(
# package name in pypi
name='django-oscar-api',
# extract version from module.
version=__version__,
description="REST API module for django-oscar",
long_description=open('README.rst').read(),
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: Unix',
'Programming Language :: Python'
],
keywords='',
author='Lars van de Kerkhof, Martijn Jacobs',
author_email='lars@permanentmarkers.nl, martijn@devopsconsulting.nl',
url='https://github.com/tangentlabs/django-oscar-api',
license='BSD',
# include all packages in the egg, except the test package.
packages=find_packages(exclude=['ez_setup', 'examples', '*tests', '*fixtures', 'sandbox']),
# for avoiding conflict have one namespace for all apc related eggs.
namespace_packages=[],
# include non python files
include_package_data=True,
zip_safe=False,
# specify dependencies
install_requires=[
'setuptools',
'django-oscar>=0.6',
'djangorestframework>=3.1.0'
],
# mark test target to require extras.
extras_require={
'test': ['django-nose',]
},
)
|
<commit_before>from setuptools import setup, find_packages
__version__ = "0.0.13"
setup(
# package name in pypi
name='django-oscar-api',
# extract version from module.
version=__version__,
description="REST API module for django-oscar",
long_description=open('README.rst').read(),
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: Unix',
'Programming Language :: Python'
],
keywords='',
author='Lars van de Kerkhof, Martijn Jacobs',
author_email='lars@permanentmarkers.nl, martijn@devopsconsulting.nl',
url='https://github.com/tangentlabs/django-oscar-api',
license='BSD',
# include all packages in the egg, except the test package.
packages=find_packages(exclude=['ez_setup', 'examples', '*tests', '*fixtures', 'sandbox']),
# for avoiding conflict have one namespace for all apc related eggs.
namespace_packages=[],
# include non python files
include_package_data=True,
zip_safe=False,
# specify dependencies
install_requires=[
'setuptools',
'django-oscar>=0.6',
'djangorestframework<3.0.0'
],
# mark test target to require extras.
extras_require={
'test': ['django-nose',]
},
)
<commit_msg>Use django rest framework > 3.1<commit_after>
|
from setuptools import setup, find_packages
__version__ = "0.0.13"
setup(
# package name in pypi
name='django-oscar-api',
# extract version from module.
version=__version__,
description="REST API module for django-oscar",
long_description=open('README.rst').read(),
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: Unix',
'Programming Language :: Python'
],
keywords='',
author='Lars van de Kerkhof, Martijn Jacobs',
author_email='lars@permanentmarkers.nl, martijn@devopsconsulting.nl',
url='https://github.com/tangentlabs/django-oscar-api',
license='BSD',
# include all packages in the egg, except the test package.
packages=find_packages(exclude=['ez_setup', 'examples', '*tests', '*fixtures', 'sandbox']),
# for avoiding conflict have one namespace for all apc related eggs.
namespace_packages=[],
# include non python files
include_package_data=True,
zip_safe=False,
# specify dependencies
install_requires=[
'setuptools',
'django-oscar>=0.6',
'djangorestframework>=3.1.0'
],
# mark test target to require extras.
extras_require={
'test': ['django-nose',]
},
)
|
from setuptools import setup, find_packages
__version__ = "0.0.13"
setup(
# package name in pypi
name='django-oscar-api',
# extract version from module.
version=__version__,
description="REST API module for django-oscar",
long_description=open('README.rst').read(),
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: Unix',
'Programming Language :: Python'
],
keywords='',
author='Lars van de Kerkhof, Martijn Jacobs',
author_email='lars@permanentmarkers.nl, martijn@devopsconsulting.nl',
url='https://github.com/tangentlabs/django-oscar-api',
license='BSD',
# include all packages in the egg, except the test package.
packages=find_packages(exclude=['ez_setup', 'examples', '*tests', '*fixtures', 'sandbox']),
# for avoiding conflict have one namespace for all apc related eggs.
namespace_packages=[],
# include non python files
include_package_data=True,
zip_safe=False,
# specify dependencies
install_requires=[
'setuptools',
'django-oscar>=0.6',
'djangorestframework<3.0.0'
],
# mark test target to require extras.
extras_require={
'test': ['django-nose',]
},
)
Use django rest framework > 3.1from setuptools import setup, find_packages
__version__ = "0.0.13"
setup(
# package name in pypi
name='django-oscar-api',
# extract version from module.
version=__version__,
description="REST API module for django-oscar",
long_description=open('README.rst').read(),
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: Unix',
'Programming Language :: Python'
],
keywords='',
author='Lars van de Kerkhof, Martijn Jacobs',
author_email='lars@permanentmarkers.nl, martijn@devopsconsulting.nl',
url='https://github.com/tangentlabs/django-oscar-api',
license='BSD',
# include all packages in the egg, except the test package.
packages=find_packages(exclude=['ez_setup', 'examples', '*tests', '*fixtures', 'sandbox']),
# for avoiding conflict have one namespace for all apc related eggs.
namespace_packages=[],
# include non python files
include_package_data=True,
zip_safe=False,
# specify dependencies
install_requires=[
'setuptools',
'django-oscar>=0.6',
'djangorestframework>=3.1.0'
],
# mark test target to require extras.
extras_require={
'test': ['django-nose',]
},
)
|
<commit_before>from setuptools import setup, find_packages
__version__ = "0.0.13"
setup(
# package name in pypi
name='django-oscar-api',
# extract version from module.
version=__version__,
description="REST API module for django-oscar",
long_description=open('README.rst').read(),
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: Unix',
'Programming Language :: Python'
],
keywords='',
author='Lars van de Kerkhof, Martijn Jacobs',
author_email='lars@permanentmarkers.nl, martijn@devopsconsulting.nl',
url='https://github.com/tangentlabs/django-oscar-api',
license='BSD',
# include all packages in the egg, except the test package.
packages=find_packages(exclude=['ez_setup', 'examples', '*tests', '*fixtures', 'sandbox']),
# for avoiding conflict have one namespace for all apc related eggs.
namespace_packages=[],
# include non python files
include_package_data=True,
zip_safe=False,
# specify dependencies
install_requires=[
'setuptools',
'django-oscar>=0.6',
'djangorestframework<3.0.0'
],
# mark test target to require extras.
extras_require={
'test': ['django-nose',]
},
)
<commit_msg>Use django rest framework > 3.1<commit_after>from setuptools import setup, find_packages
__version__ = "0.0.13"
setup(
# package name in pypi
name='django-oscar-api',
# extract version from module.
version=__version__,
description="REST API module for django-oscar",
long_description=open('README.rst').read(),
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: Unix',
'Programming Language :: Python'
],
keywords='',
author='Lars van de Kerkhof, Martijn Jacobs',
author_email='lars@permanentmarkers.nl, martijn@devopsconsulting.nl',
url='https://github.com/tangentlabs/django-oscar-api',
license='BSD',
# include all packages in the egg, except the test package.
packages=find_packages(exclude=['ez_setup', 'examples', '*tests', '*fixtures', 'sandbox']),
# for avoiding conflict have one namespace for all apc related eggs.
namespace_packages=[],
# include non python files
include_package_data=True,
zip_safe=False,
# specify dependencies
install_requires=[
'setuptools',
'django-oscar>=0.6',
'djangorestframework>=3.1.0'
],
# mark test target to require extras.
extras_require={
'test': ['django-nose',]
},
)
|
77dc80e60b252833940dc6b2a1c512684ed8decd
|
doc/conf.py
|
doc/conf.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Use sphinx-quickstart to create your own conf.py file!
# After that, you have to edit a few things. See below.
# Select nbsphinx and, if needed, add a math extension (mathjax or pngmath):
extensions = [
'nbsphinx',
'sphinx.ext.mathjax',
]
# Exclude build directory and Jupyter backup files:
exclude_patterns = ['_build', '**.ipynb_checkpoints']
# -- The settings below this line are not specific to nbsphinx ------------
master_doc = 'index'
project = 'nbsphinx'
author = 'Matthias Geier'
copyright = '2016, ' + author
# -- Get version information from Git -------------------------------------
try:
from subprocess import check_output
release = check_output(['git', 'describe', '--tags', '--always'])
release = release.decode().strip()
except Exception:
release = '<unknown>'
# -- Options for HTML output ----------------------------------------------
html_title = project + ' version ' + release
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
'papersize': 'a4paper',
'preamble': r'\setcounter{tocdepth}{3}',
}
latex_documents = [
(master_doc, 'nbsphinx.tex', project, author, 'howto'),
]
latex_show_urls = 'footnote'
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Use sphinx-quickstart to create your own conf.py file!
# After that, you have to edit a few things. See below.
# Select nbsphinx and, if needed, add a math extension (mathjax or pngmath):
extensions = [
'nbsphinx',
'sphinx.ext.mathjax',
]
# Exclude build directory and Jupyter backup files:
exclude_patterns = ['_build', '**.ipynb_checkpoints']
# Default language for syntax highlighting (e.g. in Markdown cells)
highlight_language = 'none'
# -- The settings below this line are not specific to nbsphinx ------------
master_doc = 'index'
project = 'nbsphinx'
author = 'Matthias Geier'
copyright = '2016, ' + author
# -- Get version information from Git -------------------------------------
try:
from subprocess import check_output
release = check_output(['git', 'describe', '--tags', '--always'])
release = release.decode().strip()
except Exception:
release = '<unknown>'
# -- Options for HTML output ----------------------------------------------
html_title = project + ' version ' + release
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
'papersize': 'a4paper',
'preamble': r'\setcounter{tocdepth}{3}',
}
latex_documents = [
(master_doc, 'nbsphinx.tex', project, author, 'howto'),
]
latex_show_urls = 'footnote'
|
Set default syntax highlighting language to 'none'
|
DOC: Set default syntax highlighting language to 'none'
|
Python
|
mit
|
spatialaudio/nbsphinx,spatialaudio/nbsphinx,spatialaudio/nbsphinx
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Use sphinx-quickstart to create your own conf.py file!
# After that, you have to edit a few things. See below.
# Select nbsphinx and, if needed, add a math extension (mathjax or pngmath):
extensions = [
'nbsphinx',
'sphinx.ext.mathjax',
]
# Exclude build directory and Jupyter backup files:
exclude_patterns = ['_build', '**.ipynb_checkpoints']
# -- The settings below this line are not specific to nbsphinx ------------
master_doc = 'index'
project = 'nbsphinx'
author = 'Matthias Geier'
copyright = '2016, ' + author
# -- Get version information from Git -------------------------------------
try:
from subprocess import check_output
release = check_output(['git', 'describe', '--tags', '--always'])
release = release.decode().strip()
except Exception:
release = '<unknown>'
# -- Options for HTML output ----------------------------------------------
html_title = project + ' version ' + release
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
'papersize': 'a4paper',
'preamble': r'\setcounter{tocdepth}{3}',
}
latex_documents = [
(master_doc, 'nbsphinx.tex', project, author, 'howto'),
]
latex_show_urls = 'footnote'
DOC: Set default syntax highlighting language to 'none'
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Use sphinx-quickstart to create your own conf.py file!
# After that, you have to edit a few things. See below.
# Select nbsphinx and, if needed, add a math extension (mathjax or pngmath):
extensions = [
'nbsphinx',
'sphinx.ext.mathjax',
]
# Exclude build directory and Jupyter backup files:
exclude_patterns = ['_build', '**.ipynb_checkpoints']
# Default language for syntax highlighting (e.g. in Markdown cells)
highlight_language = 'none'
# -- The settings below this line are not specific to nbsphinx ------------
master_doc = 'index'
project = 'nbsphinx'
author = 'Matthias Geier'
copyright = '2016, ' + author
# -- Get version information from Git -------------------------------------
try:
from subprocess import check_output
release = check_output(['git', 'describe', '--tags', '--always'])
release = release.decode().strip()
except Exception:
release = '<unknown>'
# -- Options for HTML output ----------------------------------------------
html_title = project + ' version ' + release
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
'papersize': 'a4paper',
'preamble': r'\setcounter{tocdepth}{3}',
}
latex_documents = [
(master_doc, 'nbsphinx.tex', project, author, 'howto'),
]
latex_show_urls = 'footnote'
|
<commit_before>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Use sphinx-quickstart to create your own conf.py file!
# After that, you have to edit a few things. See below.
# Select nbsphinx and, if needed, add a math extension (mathjax or pngmath):
extensions = [
'nbsphinx',
'sphinx.ext.mathjax',
]
# Exclude build directory and Jupyter backup files:
exclude_patterns = ['_build', '**.ipynb_checkpoints']
# -- The settings below this line are not specific to nbsphinx ------------
master_doc = 'index'
project = 'nbsphinx'
author = 'Matthias Geier'
copyright = '2016, ' + author
# -- Get version information from Git -------------------------------------
try:
from subprocess import check_output
release = check_output(['git', 'describe', '--tags', '--always'])
release = release.decode().strip()
except Exception:
release = '<unknown>'
# -- Options for HTML output ----------------------------------------------
html_title = project + ' version ' + release
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
'papersize': 'a4paper',
'preamble': r'\setcounter{tocdepth}{3}',
}
latex_documents = [
(master_doc, 'nbsphinx.tex', project, author, 'howto'),
]
latex_show_urls = 'footnote'
<commit_msg>DOC: Set default syntax highlighting language to 'none'<commit_after>
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Use sphinx-quickstart to create your own conf.py file!
# After that, you have to edit a few things. See below.
# Select nbsphinx and, if needed, add a math extension (mathjax or pngmath):
extensions = [
'nbsphinx',
'sphinx.ext.mathjax',
]
# Exclude build directory and Jupyter backup files:
exclude_patterns = ['_build', '**.ipynb_checkpoints']
# Default language for syntax highlighting (e.g. in Markdown cells)
highlight_language = 'none'
# -- The settings below this line are not specific to nbsphinx ------------
master_doc = 'index'
project = 'nbsphinx'
author = 'Matthias Geier'
copyright = '2016, ' + author
# -- Get version information from Git -------------------------------------
try:
from subprocess import check_output
release = check_output(['git', 'describe', '--tags', '--always'])
release = release.decode().strip()
except Exception:
release = '<unknown>'
# -- Options for HTML output ----------------------------------------------
html_title = project + ' version ' + release
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
'papersize': 'a4paper',
'preamble': r'\setcounter{tocdepth}{3}',
}
latex_documents = [
(master_doc, 'nbsphinx.tex', project, author, 'howto'),
]
latex_show_urls = 'footnote'
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Use sphinx-quickstart to create your own conf.py file!
# After that, you have to edit a few things. See below.
# Select nbsphinx and, if needed, add a math extension (mathjax or pngmath):
extensions = [
'nbsphinx',
'sphinx.ext.mathjax',
]
# Exclude build directory and Jupyter backup files:
exclude_patterns = ['_build', '**.ipynb_checkpoints']
# -- The settings below this line are not specific to nbsphinx ------------
master_doc = 'index'
project = 'nbsphinx'
author = 'Matthias Geier'
copyright = '2016, ' + author
# -- Get version information from Git -------------------------------------
try:
from subprocess import check_output
release = check_output(['git', 'describe', '--tags', '--always'])
release = release.decode().strip()
except Exception:
release = '<unknown>'
# -- Options for HTML output ----------------------------------------------
html_title = project + ' version ' + release
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
'papersize': 'a4paper',
'preamble': r'\setcounter{tocdepth}{3}',
}
latex_documents = [
(master_doc, 'nbsphinx.tex', project, author, 'howto'),
]
latex_show_urls = 'footnote'
DOC: Set default syntax highlighting language to 'none'#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Use sphinx-quickstart to create your own conf.py file!
# After that, you have to edit a few things. See below.
# Select nbsphinx and, if needed, add a math extension (mathjax or pngmath):
extensions = [
'nbsphinx',
'sphinx.ext.mathjax',
]
# Exclude build directory and Jupyter backup files:
exclude_patterns = ['_build', '**.ipynb_checkpoints']
# Default language for syntax highlighting (e.g. in Markdown cells)
highlight_language = 'none'
# -- The settings below this line are not specific to nbsphinx ------------
master_doc = 'index'
project = 'nbsphinx'
author = 'Matthias Geier'
copyright = '2016, ' + author
# -- Get version information from Git -------------------------------------
try:
from subprocess import check_output
release = check_output(['git', 'describe', '--tags', '--always'])
release = release.decode().strip()
except Exception:
release = '<unknown>'
# -- Options for HTML output ----------------------------------------------
html_title = project + ' version ' + release
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
'papersize': 'a4paper',
'preamble': r'\setcounter{tocdepth}{3}',
}
latex_documents = [
(master_doc, 'nbsphinx.tex', project, author, 'howto'),
]
latex_show_urls = 'footnote'
|
<commit_before>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Use sphinx-quickstart to create your own conf.py file!
# After that, you have to edit a few things. See below.
# Select nbsphinx and, if needed, add a math extension (mathjax or pngmath):
extensions = [
'nbsphinx',
'sphinx.ext.mathjax',
]
# Exclude build directory and Jupyter backup files:
exclude_patterns = ['_build', '**.ipynb_checkpoints']
# -- The settings below this line are not specific to nbsphinx ------------
master_doc = 'index'
project = 'nbsphinx'
author = 'Matthias Geier'
copyright = '2016, ' + author
# -- Get version information from Git -------------------------------------
try:
from subprocess import check_output
release = check_output(['git', 'describe', '--tags', '--always'])
release = release.decode().strip()
except Exception:
release = '<unknown>'
# -- Options for HTML output ----------------------------------------------
html_title = project + ' version ' + release
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
'papersize': 'a4paper',
'preamble': r'\setcounter{tocdepth}{3}',
}
latex_documents = [
(master_doc, 'nbsphinx.tex', project, author, 'howto'),
]
latex_show_urls = 'footnote'
<commit_msg>DOC: Set default syntax highlighting language to 'none'<commit_after>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Use sphinx-quickstart to create your own conf.py file!
# After that, you have to edit a few things. See below.
# Select nbsphinx and, if needed, add a math extension (mathjax or pngmath):
extensions = [
'nbsphinx',
'sphinx.ext.mathjax',
]
# Exclude build directory and Jupyter backup files:
exclude_patterns = ['_build', '**.ipynb_checkpoints']
# Default language for syntax highlighting (e.g. in Markdown cells)
highlight_language = 'none'
# -- The settings below this line are not specific to nbsphinx ------------
master_doc = 'index'
project = 'nbsphinx'
author = 'Matthias Geier'
copyright = '2016, ' + author
# -- Get version information from Git -------------------------------------
try:
from subprocess import check_output
release = check_output(['git', 'describe', '--tags', '--always'])
release = release.decode().strip()
except Exception:
release = '<unknown>'
# -- Options for HTML output ----------------------------------------------
html_title = project + ' version ' + release
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
'papersize': 'a4paper',
'preamble': r'\setcounter{tocdepth}{3}',
}
latex_documents = [
(master_doc, 'nbsphinx.tex', project, author, 'howto'),
]
latex_show_urls = 'footnote'
|
ca81dead53e199bc69fe6a5d0ffbaaa735a4367b
|
setup.py
|
setup.py
|
#!/usr/bin/env python
"""
Raven
======
Raven is a Python client for `Sentry <http://aboutsentry.com/>`_. It provides
full out-of-the-box support for many of the popular frameworks, including
Django, and Flask. Raven also includes drop-in support for any WSGI-compatible
web application.
"""
from setuptools import setup, find_packages
tests_require = [
'Django>=1.2,<1.4',
'django-celery',
'celery',
'blinker>=1.1',
'Flask>=0.8',
'django-sentry>=2.0.0',
'django-nose',
'nose',
'mock',
'unittest2',
]
install_requires = [
'simplejson',
]
setup(
name='raven',
version='2.0.0-Alpha1',
author='David Cramer',
author_email='dcramer@gmail.com',
url='http://github.com/dcramer/raven',
description='Raven is a client for Sentry',
long_description=__doc__,
packages=find_packages(exclude=("tests",)),
zip_safe=False,
install_requires=install_requires,
tests_require=tests_require,
extras_require={'test': tests_require},
test_suite='runtests.runtests',
include_package_data=True,
classifiers=[
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Operating System :: OS Independent',
'Topic :: Software Development'
],
)
|
#!/usr/bin/env python
"""
Raven
======
Raven is a Python client for `Sentry <http://aboutsentry.com/>`_. It provides
full out-of-the-box support for many of the popular frameworks, including
Django, and Flask. Raven also includes drop-in support for any WSGI-compatible
web application.
"""
from setuptools import setup, find_packages
tests_require = [
'Django>=1.2,<1.4',
'django-celery',
'celery',
'blinker>=1.1',
'Flask>=0.8',
'django-sentry>=2.0.0',
'django-nose',
'nose',
'mock',
'unittest2',
]
install_requires = [
'simplejson',
]
setup(
name='raven',
version='2.0.0',
author='David Cramer',
author_email='dcramer@gmail.com',
url='http://github.com/dcramer/raven',
description='Raven is a client for Sentry',
long_description=__doc__,
packages=find_packages(exclude=("tests",)),
zip_safe=False,
install_requires=install_requires,
tests_require=tests_require,
extras_require={'test': tests_require},
test_suite='runtests.runtests',
include_package_data=True,
classifiers=[
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Operating System :: OS Independent',
'Topic :: Software Development'
],
)
|
Drop alpha tag from package
|
Drop alpha tag from package
|
Python
|
bsd-3-clause
|
smarkets/raven-python,beniwohli/apm-agent-python,tarkatronic/opbeat_python,daikeren/opbeat_python,alex/raven,jmp0xf/raven-python,hzy/raven-python,nikolas/raven-python,beniwohli/apm-agent-python,inspirehep/raven-python,johansteffner/raven-python,someonehan/raven-python,smarkets/raven-python,recht/raven-python,smarkets/raven-python,akheron/raven-python,akalipetis/raven-python,patrys/opbeat_python,hzy/raven-python,patrys/opbeat_python,icereval/raven-python,getsentry/raven-python,dbravender/raven-python,danriti/raven-python,patrys/opbeat_python,lepture/raven-python,Goldmund-Wyldebeast-Wunderliebe/raven-python,Photonomie/raven-python,daikeren/opbeat_python,nikolas/raven-python,icereval/raven-python,tarkatronic/opbeat_python,jmagnusson/raven-python,ticosax/opbeat_python,jbarbuto/raven-python,ewdurbin/raven-python,inspirehep/raven-python,akalipetis/raven-python,patrys/opbeat_python,icereval/raven-python,ronaldevers/raven-python,jmagnusson/raven-python,jmagnusson/raven-python,jbarbuto/raven-python,smarkets/raven-python,ewdurbin/raven-python,ticosax/opbeat_python,someonehan/raven-python,jbarbuto/raven-python,nikolas/raven-python,jmp0xf/raven-python,percipient/raven-python,Goldmund-Wyldebeast-Wunderliebe/raven-python,getsentry/raven-python,lopter/raven-python-old,someonehan/raven-python,dirtycoder/opbeat_python,beniwohli/apm-agent-python,arthurlogilab/raven-python,jbarbuto/raven-python,Photonomie/raven-python,johansteffner/raven-python,ronaldevers/raven-python,arthurlogilab/raven-python,hzy/raven-python,percipient/raven-python,recht/raven-python,akheron/raven-python,nikolas/raven-python,inspirehep/raven-python,arthurlogilab/raven-python,ticosax/opbeat_python,tarkatronic/opbeat_python,johansteffner/raven-python,dbravender/raven-python,recht/raven-python,akalipetis/raven-python,Photonomie/raven-python,Goldmund-Wyldebeast-Wunderliebe/raven-python,openlabs/raven,akheron/raven-python,dirtycoder/opbeat_python,ewdurbin/raven-python,daikeren/opbeat_python,dirtycoder/opbeat_python,icereval/raven-python,danriti/raven-python,ronaldevers/raven-python,dbravender/raven-python,jmp0xf/raven-python,getsentry/raven-python,collective/mr.poe,lepture/raven-python,inspirehep/raven-python,percipient/raven-python,danriti/raven-python,beniwohli/apm-agent-python,arthurlogilab/raven-python,Goldmund-Wyldebeast-Wunderliebe/raven-python,lepture/raven-python
|
#!/usr/bin/env python
"""
Raven
======
Raven is a Python client for `Sentry <http://aboutsentry.com/>`_. It provides
full out-of-the-box support for many of the popular frameworks, including
Django, and Flask. Raven also includes drop-in support for any WSGI-compatible
web application.
"""
from setuptools import setup, find_packages
tests_require = [
'Django>=1.2,<1.4',
'django-celery',
'celery',
'blinker>=1.1',
'Flask>=0.8',
'django-sentry>=2.0.0',
'django-nose',
'nose',
'mock',
'unittest2',
]
install_requires = [
'simplejson',
]
setup(
name='raven',
version='2.0.0-Alpha1',
author='David Cramer',
author_email='dcramer@gmail.com',
url='http://github.com/dcramer/raven',
description='Raven is a client for Sentry',
long_description=__doc__,
packages=find_packages(exclude=("tests",)),
zip_safe=False,
install_requires=install_requires,
tests_require=tests_require,
extras_require={'test': tests_require},
test_suite='runtests.runtests',
include_package_data=True,
classifiers=[
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Operating System :: OS Independent',
'Topic :: Software Development'
],
)
Drop alpha tag from package
|
#!/usr/bin/env python
"""
Raven
======
Raven is a Python client for `Sentry <http://aboutsentry.com/>`_. It provides
full out-of-the-box support for many of the popular frameworks, including
Django, and Flask. Raven also includes drop-in support for any WSGI-compatible
web application.
"""
from setuptools import setup, find_packages
tests_require = [
'Django>=1.2,<1.4',
'django-celery',
'celery',
'blinker>=1.1',
'Flask>=0.8',
'django-sentry>=2.0.0',
'django-nose',
'nose',
'mock',
'unittest2',
]
install_requires = [
'simplejson',
]
setup(
name='raven',
version='2.0.0',
author='David Cramer',
author_email='dcramer@gmail.com',
url='http://github.com/dcramer/raven',
description='Raven is a client for Sentry',
long_description=__doc__,
packages=find_packages(exclude=("tests",)),
zip_safe=False,
install_requires=install_requires,
tests_require=tests_require,
extras_require={'test': tests_require},
test_suite='runtests.runtests',
include_package_data=True,
classifiers=[
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Operating System :: OS Independent',
'Topic :: Software Development'
],
)
|
<commit_before>#!/usr/bin/env python
"""
Raven
======
Raven is a Python client for `Sentry <http://aboutsentry.com/>`_. It provides
full out-of-the-box support for many of the popular frameworks, including
Django, and Flask. Raven also includes drop-in support for any WSGI-compatible
web application.
"""
from setuptools import setup, find_packages
tests_require = [
'Django>=1.2,<1.4',
'django-celery',
'celery',
'blinker>=1.1',
'Flask>=0.8',
'django-sentry>=2.0.0',
'django-nose',
'nose',
'mock',
'unittest2',
]
install_requires = [
'simplejson',
]
setup(
name='raven',
version='2.0.0-Alpha1',
author='David Cramer',
author_email='dcramer@gmail.com',
url='http://github.com/dcramer/raven',
description='Raven is a client for Sentry',
long_description=__doc__,
packages=find_packages(exclude=("tests",)),
zip_safe=False,
install_requires=install_requires,
tests_require=tests_require,
extras_require={'test': tests_require},
test_suite='runtests.runtests',
include_package_data=True,
classifiers=[
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Operating System :: OS Independent',
'Topic :: Software Development'
],
)
<commit_msg>Drop alpha tag from package<commit_after>
|
#!/usr/bin/env python
"""
Raven
======
Raven is a Python client for `Sentry <http://aboutsentry.com/>`_. It provides
full out-of-the-box support for many of the popular frameworks, including
Django, and Flask. Raven also includes drop-in support for any WSGI-compatible
web application.
"""
from setuptools import setup, find_packages
tests_require = [
'Django>=1.2,<1.4',
'django-celery',
'celery',
'blinker>=1.1',
'Flask>=0.8',
'django-sentry>=2.0.0',
'django-nose',
'nose',
'mock',
'unittest2',
]
install_requires = [
'simplejson',
]
setup(
name='raven',
version='2.0.0',
author='David Cramer',
author_email='dcramer@gmail.com',
url='http://github.com/dcramer/raven',
description='Raven is a client for Sentry',
long_description=__doc__,
packages=find_packages(exclude=("tests",)),
zip_safe=False,
install_requires=install_requires,
tests_require=tests_require,
extras_require={'test': tests_require},
test_suite='runtests.runtests',
include_package_data=True,
classifiers=[
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Operating System :: OS Independent',
'Topic :: Software Development'
],
)
|
#!/usr/bin/env python
"""
Raven
======
Raven is a Python client for `Sentry <http://aboutsentry.com/>`_. It provides
full out-of-the-box support for many of the popular frameworks, including
Django, and Flask. Raven also includes drop-in support for any WSGI-compatible
web application.
"""
from setuptools import setup, find_packages
tests_require = [
'Django>=1.2,<1.4',
'django-celery',
'celery',
'blinker>=1.1',
'Flask>=0.8',
'django-sentry>=2.0.0',
'django-nose',
'nose',
'mock',
'unittest2',
]
install_requires = [
'simplejson',
]
setup(
name='raven',
version='2.0.0-Alpha1',
author='David Cramer',
author_email='dcramer@gmail.com',
url='http://github.com/dcramer/raven',
description='Raven is a client for Sentry',
long_description=__doc__,
packages=find_packages(exclude=("tests",)),
zip_safe=False,
install_requires=install_requires,
tests_require=tests_require,
extras_require={'test': tests_require},
test_suite='runtests.runtests',
include_package_data=True,
classifiers=[
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Operating System :: OS Independent',
'Topic :: Software Development'
],
)
Drop alpha tag from package#!/usr/bin/env python
"""
Raven
======
Raven is a Python client for `Sentry <http://aboutsentry.com/>`_. It provides
full out-of-the-box support for many of the popular frameworks, including
Django, and Flask. Raven also includes drop-in support for any WSGI-compatible
web application.
"""
from setuptools import setup, find_packages
tests_require = [
'Django>=1.2,<1.4',
'django-celery',
'celery',
'blinker>=1.1',
'Flask>=0.8',
'django-sentry>=2.0.0',
'django-nose',
'nose',
'mock',
'unittest2',
]
install_requires = [
'simplejson',
]
setup(
name='raven',
version='2.0.0',
author='David Cramer',
author_email='dcramer@gmail.com',
url='http://github.com/dcramer/raven',
description='Raven is a client for Sentry',
long_description=__doc__,
packages=find_packages(exclude=("tests",)),
zip_safe=False,
install_requires=install_requires,
tests_require=tests_require,
extras_require={'test': tests_require},
test_suite='runtests.runtests',
include_package_data=True,
classifiers=[
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Operating System :: OS Independent',
'Topic :: Software Development'
],
)
|
<commit_before>#!/usr/bin/env python
"""
Raven
======
Raven is a Python client for `Sentry <http://aboutsentry.com/>`_. It provides
full out-of-the-box support for many of the popular frameworks, including
Django, and Flask. Raven also includes drop-in support for any WSGI-compatible
web application.
"""
from setuptools import setup, find_packages
tests_require = [
'Django>=1.2,<1.4',
'django-celery',
'celery',
'blinker>=1.1',
'Flask>=0.8',
'django-sentry>=2.0.0',
'django-nose',
'nose',
'mock',
'unittest2',
]
install_requires = [
'simplejson',
]
setup(
name='raven',
version='2.0.0-Alpha1',
author='David Cramer',
author_email='dcramer@gmail.com',
url='http://github.com/dcramer/raven',
description='Raven is a client for Sentry',
long_description=__doc__,
packages=find_packages(exclude=("tests",)),
zip_safe=False,
install_requires=install_requires,
tests_require=tests_require,
extras_require={'test': tests_require},
test_suite='runtests.runtests',
include_package_data=True,
classifiers=[
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Operating System :: OS Independent',
'Topic :: Software Development'
],
)
<commit_msg>Drop alpha tag from package<commit_after>#!/usr/bin/env python
"""
Raven
======
Raven is a Python client for `Sentry <http://aboutsentry.com/>`_. It provides
full out-of-the-box support for many of the popular frameworks, including
Django, and Flask. Raven also includes drop-in support for any WSGI-compatible
web application.
"""
from setuptools import setup, find_packages
tests_require = [
'Django>=1.2,<1.4',
'django-celery',
'celery',
'blinker>=1.1',
'Flask>=0.8',
'django-sentry>=2.0.0',
'django-nose',
'nose',
'mock',
'unittest2',
]
install_requires = [
'simplejson',
]
setup(
name='raven',
version='2.0.0',
author='David Cramer',
author_email='dcramer@gmail.com',
url='http://github.com/dcramer/raven',
description='Raven is a client for Sentry',
long_description=__doc__,
packages=find_packages(exclude=("tests",)),
zip_safe=False,
install_requires=install_requires,
tests_require=tests_require,
extras_require={'test': tests_require},
test_suite='runtests.runtests',
include_package_data=True,
classifiers=[
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Operating System :: OS Independent',
'Topic :: Software Development'
],
)
|
3803eae05013c04b4cf4516f40a851da048d939f
|
setup.py
|
setup.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
requires = ['pyrax==1.4.7',
'ipython==0.13.2',
'tornado==3.1',
]
setup(name='ipynb_swiftstore',
version='0.0.0',
description='IPython notebook storage for OpenStack Swift',
author='Kyle Kelley',
author_email='rgbkrk@gmail.com',
url='http://github.com/rgbkrk/ipynb-swiftstore',
py_modules=['ipynb_swiftstore'],
package_data={'': ['LICENSE']},
include_package_data=False,
install_requires=requires,
license=open('LICENSE').read(),
zip_safe=True,
classifiers=(
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'Environment :: OpenStack',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: System :: Distributed Computing',
),
)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
requires = ['pyrax==1.4.7',
'ipython==0.13.2',
'tornado==3.1',
'pyzmq==13.1.0'
]
setup(name='ipynb_swiftstore',
version='0.0.0',
description='IPython notebook storage for OpenStack Swift',
author='Kyle Kelley',
author_email='rgbkrk@gmail.com',
url='http://github.com/rgbkrk/ipynb-swiftstore',
py_modules=['ipynb_swiftstore'],
package_data={'': ['LICENSE']},
include_package_data=False,
install_requires=requires,
license=open('LICENSE').read(),
zip_safe=True,
classifiers=(
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'Environment :: OpenStack',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: System :: Distributed Computing',
),
)
|
Add pyzmq. Note: this package doesn't need it but IPython notebook does
|
Add pyzmq. Note: this package doesn't need it but IPython notebook does
|
Python
|
apache-2.0
|
rgbkrk/bookstore
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
requires = ['pyrax==1.4.7',
'ipython==0.13.2',
'tornado==3.1',
]
setup(name='ipynb_swiftstore',
version='0.0.0',
description='IPython notebook storage for OpenStack Swift',
author='Kyle Kelley',
author_email='rgbkrk@gmail.com',
url='http://github.com/rgbkrk/ipynb-swiftstore',
py_modules=['ipynb_swiftstore'],
package_data={'': ['LICENSE']},
include_package_data=False,
install_requires=requires,
license=open('LICENSE').read(),
zip_safe=True,
classifiers=(
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'Environment :: OpenStack',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: System :: Distributed Computing',
),
)
Add pyzmq. Note: this package doesn't need it but IPython notebook does
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
requires = ['pyrax==1.4.7',
'ipython==0.13.2',
'tornado==3.1',
'pyzmq==13.1.0'
]
setup(name='ipynb_swiftstore',
version='0.0.0',
description='IPython notebook storage for OpenStack Swift',
author='Kyle Kelley',
author_email='rgbkrk@gmail.com',
url='http://github.com/rgbkrk/ipynb-swiftstore',
py_modules=['ipynb_swiftstore'],
package_data={'': ['LICENSE']},
include_package_data=False,
install_requires=requires,
license=open('LICENSE').read(),
zip_safe=True,
classifiers=(
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'Environment :: OpenStack',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: System :: Distributed Computing',
),
)
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
requires = ['pyrax==1.4.7',
'ipython==0.13.2',
'tornado==3.1',
]
setup(name='ipynb_swiftstore',
version='0.0.0',
description='IPython notebook storage for OpenStack Swift',
author='Kyle Kelley',
author_email='rgbkrk@gmail.com',
url='http://github.com/rgbkrk/ipynb-swiftstore',
py_modules=['ipynb_swiftstore'],
package_data={'': ['LICENSE']},
include_package_data=False,
install_requires=requires,
license=open('LICENSE').read(),
zip_safe=True,
classifiers=(
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'Environment :: OpenStack',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: System :: Distributed Computing',
),
)
<commit_msg>Add pyzmq. Note: this package doesn't need it but IPython notebook does<commit_after>
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
requires = ['pyrax==1.4.7',
'ipython==0.13.2',
'tornado==3.1',
'pyzmq==13.1.0'
]
setup(name='ipynb_swiftstore',
version='0.0.0',
description='IPython notebook storage for OpenStack Swift',
author='Kyle Kelley',
author_email='rgbkrk@gmail.com',
url='http://github.com/rgbkrk/ipynb-swiftstore',
py_modules=['ipynb_swiftstore'],
package_data={'': ['LICENSE']},
include_package_data=False,
install_requires=requires,
license=open('LICENSE').read(),
zip_safe=True,
classifiers=(
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'Environment :: OpenStack',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: System :: Distributed Computing',
),
)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
requires = ['pyrax==1.4.7',
'ipython==0.13.2',
'tornado==3.1',
]
setup(name='ipynb_swiftstore',
version='0.0.0',
description='IPython notebook storage for OpenStack Swift',
author='Kyle Kelley',
author_email='rgbkrk@gmail.com',
url='http://github.com/rgbkrk/ipynb-swiftstore',
py_modules=['ipynb_swiftstore'],
package_data={'': ['LICENSE']},
include_package_data=False,
install_requires=requires,
license=open('LICENSE').read(),
zip_safe=True,
classifiers=(
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'Environment :: OpenStack',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: System :: Distributed Computing',
),
)
Add pyzmq. Note: this package doesn't need it but IPython notebook does#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
requires = ['pyrax==1.4.7',
'ipython==0.13.2',
'tornado==3.1',
'pyzmq==13.1.0'
]
setup(name='ipynb_swiftstore',
version='0.0.0',
description='IPython notebook storage for OpenStack Swift',
author='Kyle Kelley',
author_email='rgbkrk@gmail.com',
url='http://github.com/rgbkrk/ipynb-swiftstore',
py_modules=['ipynb_swiftstore'],
package_data={'': ['LICENSE']},
include_package_data=False,
install_requires=requires,
license=open('LICENSE').read(),
zip_safe=True,
classifiers=(
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'Environment :: OpenStack',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: System :: Distributed Computing',
),
)
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
requires = ['pyrax==1.4.7',
'ipython==0.13.2',
'tornado==3.1',
]
setup(name='ipynb_swiftstore',
version='0.0.0',
description='IPython notebook storage for OpenStack Swift',
author='Kyle Kelley',
author_email='rgbkrk@gmail.com',
url='http://github.com/rgbkrk/ipynb-swiftstore',
py_modules=['ipynb_swiftstore'],
package_data={'': ['LICENSE']},
include_package_data=False,
install_requires=requires,
license=open('LICENSE').read(),
zip_safe=True,
classifiers=(
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'Environment :: OpenStack',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: System :: Distributed Computing',
),
)
<commit_msg>Add pyzmq. Note: this package doesn't need it but IPython notebook does<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
requires = ['pyrax==1.4.7',
'ipython==0.13.2',
'tornado==3.1',
'pyzmq==13.1.0'
]
setup(name='ipynb_swiftstore',
version='0.0.0',
description='IPython notebook storage for OpenStack Swift',
author='Kyle Kelley',
author_email='rgbkrk@gmail.com',
url='http://github.com/rgbkrk/ipynb-swiftstore',
py_modules=['ipynb_swiftstore'],
package_data={'': ['LICENSE']},
include_package_data=False,
install_requires=requires,
license=open('LICENSE').read(),
zip_safe=True,
classifiers=(
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'Environment :: OpenStack',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: System :: Distributed Computing',
),
)
|
8da759ff201c9cc61783663edf4cd3cb8e5c694d
|
setup.py
|
setup.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
import glob
from spec_cleaner import __version__
test_requires = [
'mock',
'nose',
]
setup(
name='spec_cleaner',
description = 'RPM .spec files cleaner',
long_description = 'Command-line tool for cleaning various formatting' +
'errors in RPM .spec files',
url = 'https://github.com/openSUSE/spec-cleaner',
download_url = 'https://github.com/openSUSE/spec-cleaner',
version = __version__,
author = 'Tomáš Chvátal',
author_email = 'tchvatal@suse.cz',
maintainer = 'Tomáš Chvátal',
maintainer_email = 'tchvatal@suse.cz',
license = 'License :: OSI Approved :: BSD License',
platforms = ['Linux'],
keywords = ['SUSE', 'RPM', '.spec', 'cleaner'],
tests_require=test_requires,
test_suite="nose.collector",
packages = ['spec_cleaner'],
package_data = {'spec_cleaner' : [ "data/*.txt" ]},
data_files=[('/usr/libexec/obs/service/', glob.glob('obs/*'))],
entry_points = {
'console_scripts': ['spec-cleaner = spec_cleaner.main:main']},
)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
import glob
from spec_cleaner import __version__
test_requires = [
'mock',
'nose',
]
setup(
name='spec_cleaner',
description = 'RPM .spec files cleaner',
long_description = 'Command-line tool for cleaning various formatting' +
'errors in RPM .spec files',
url = 'https://github.com/openSUSE/spec-cleaner',
download_url = 'https://github.com/openSUSE/spec-cleaner',
version = __version__,
author = 'Tomáš Chvátal',
author_email = 'tchvatal@suse.cz',
maintainer = 'Tomáš Chvátal',
maintainer_email = 'tchvatal@suse.cz',
license = 'License :: OSI Approved :: BSD License',
platforms = ['Linux'],
keywords = ['SUSE', 'RPM', '.spec', 'cleaner'],
tests_require=test_requires,
test_suite="nose.collector",
packages = ['spec_cleaner'],
data_files=[('/usr/libexec/obs/service/', glob.glob('obs/*')),
('/usr/share/spec-cleaner/', glob.glob('data/*')),
],
entry_points = {
'console_scripts': ['spec-cleaner = spec_cleaner.main:main']},
)
|
Install the data files correctly too.
|
Install the data files correctly too.
|
Python
|
bsd-3-clause
|
plusky/spec-cleaner,plusky/spec-cleaner,plusky/spec-cleaner,plusky/spec-cleaner,plusky/spec-cleaner,pombredanne/spec-cleaner,pombredanne/spec-cleaner
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
import glob
from spec_cleaner import __version__
test_requires = [
'mock',
'nose',
]
setup(
name='spec_cleaner',
description = 'RPM .spec files cleaner',
long_description = 'Command-line tool for cleaning various formatting' +
'errors in RPM .spec files',
url = 'https://github.com/openSUSE/spec-cleaner',
download_url = 'https://github.com/openSUSE/spec-cleaner',
version = __version__,
author = 'Tomáš Chvátal',
author_email = 'tchvatal@suse.cz',
maintainer = 'Tomáš Chvátal',
maintainer_email = 'tchvatal@suse.cz',
license = 'License :: OSI Approved :: BSD License',
platforms = ['Linux'],
keywords = ['SUSE', 'RPM', '.spec', 'cleaner'],
tests_require=test_requires,
test_suite="nose.collector",
packages = ['spec_cleaner'],
package_data = {'spec_cleaner' : [ "data/*.txt" ]},
data_files=[('/usr/libexec/obs/service/', glob.glob('obs/*'))],
entry_points = {
'console_scripts': ['spec-cleaner = spec_cleaner.main:main']},
)
Install the data files correctly too.
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
import glob
from spec_cleaner import __version__
test_requires = [
'mock',
'nose',
]
setup(
name='spec_cleaner',
description = 'RPM .spec files cleaner',
long_description = 'Command-line tool for cleaning various formatting' +
'errors in RPM .spec files',
url = 'https://github.com/openSUSE/spec-cleaner',
download_url = 'https://github.com/openSUSE/spec-cleaner',
version = __version__,
author = 'Tomáš Chvátal',
author_email = 'tchvatal@suse.cz',
maintainer = 'Tomáš Chvátal',
maintainer_email = 'tchvatal@suse.cz',
license = 'License :: OSI Approved :: BSD License',
platforms = ['Linux'],
keywords = ['SUSE', 'RPM', '.spec', 'cleaner'],
tests_require=test_requires,
test_suite="nose.collector",
packages = ['spec_cleaner'],
data_files=[('/usr/libexec/obs/service/', glob.glob('obs/*')),
('/usr/share/spec-cleaner/', glob.glob('data/*')),
],
entry_points = {
'console_scripts': ['spec-cleaner = spec_cleaner.main:main']},
)
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
import glob
from spec_cleaner import __version__
test_requires = [
'mock',
'nose',
]
setup(
name='spec_cleaner',
description = 'RPM .spec files cleaner',
long_description = 'Command-line tool for cleaning various formatting' +
'errors in RPM .spec files',
url = 'https://github.com/openSUSE/spec-cleaner',
download_url = 'https://github.com/openSUSE/spec-cleaner',
version = __version__,
author = 'Tomáš Chvátal',
author_email = 'tchvatal@suse.cz',
maintainer = 'Tomáš Chvátal',
maintainer_email = 'tchvatal@suse.cz',
license = 'License :: OSI Approved :: BSD License',
platforms = ['Linux'],
keywords = ['SUSE', 'RPM', '.spec', 'cleaner'],
tests_require=test_requires,
test_suite="nose.collector",
packages = ['spec_cleaner'],
package_data = {'spec_cleaner' : [ "data/*.txt" ]},
data_files=[('/usr/libexec/obs/service/', glob.glob('obs/*'))],
entry_points = {
'console_scripts': ['spec-cleaner = spec_cleaner.main:main']},
)
<commit_msg>Install the data files correctly too.<commit_after>
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
import glob
from spec_cleaner import __version__
test_requires = [
'mock',
'nose',
]
setup(
name='spec_cleaner',
description = 'RPM .spec files cleaner',
long_description = 'Command-line tool for cleaning various formatting' +
'errors in RPM .spec files',
url = 'https://github.com/openSUSE/spec-cleaner',
download_url = 'https://github.com/openSUSE/spec-cleaner',
version = __version__,
author = 'Tomáš Chvátal',
author_email = 'tchvatal@suse.cz',
maintainer = 'Tomáš Chvátal',
maintainer_email = 'tchvatal@suse.cz',
license = 'License :: OSI Approved :: BSD License',
platforms = ['Linux'],
keywords = ['SUSE', 'RPM', '.spec', 'cleaner'],
tests_require=test_requires,
test_suite="nose.collector",
packages = ['spec_cleaner'],
data_files=[('/usr/libexec/obs/service/', glob.glob('obs/*')),
('/usr/share/spec-cleaner/', glob.glob('data/*')),
],
entry_points = {
'console_scripts': ['spec-cleaner = spec_cleaner.main:main']},
)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
import glob
from spec_cleaner import __version__
test_requires = [
'mock',
'nose',
]
setup(
name='spec_cleaner',
description = 'RPM .spec files cleaner',
long_description = 'Command-line tool for cleaning various formatting' +
'errors in RPM .spec files',
url = 'https://github.com/openSUSE/spec-cleaner',
download_url = 'https://github.com/openSUSE/spec-cleaner',
version = __version__,
author = 'Tomáš Chvátal',
author_email = 'tchvatal@suse.cz',
maintainer = 'Tomáš Chvátal',
maintainer_email = 'tchvatal@suse.cz',
license = 'License :: OSI Approved :: BSD License',
platforms = ['Linux'],
keywords = ['SUSE', 'RPM', '.spec', 'cleaner'],
tests_require=test_requires,
test_suite="nose.collector",
packages = ['spec_cleaner'],
package_data = {'spec_cleaner' : [ "data/*.txt" ]},
data_files=[('/usr/libexec/obs/service/', glob.glob('obs/*'))],
entry_points = {
'console_scripts': ['spec-cleaner = spec_cleaner.main:main']},
)
Install the data files correctly too.#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
import glob
from spec_cleaner import __version__
test_requires = [
'mock',
'nose',
]
setup(
name='spec_cleaner',
description = 'RPM .spec files cleaner',
long_description = 'Command-line tool for cleaning various formatting' +
'errors in RPM .spec files',
url = 'https://github.com/openSUSE/spec-cleaner',
download_url = 'https://github.com/openSUSE/spec-cleaner',
version = __version__,
author = 'Tomáš Chvátal',
author_email = 'tchvatal@suse.cz',
maintainer = 'Tomáš Chvátal',
maintainer_email = 'tchvatal@suse.cz',
license = 'License :: OSI Approved :: BSD License',
platforms = ['Linux'],
keywords = ['SUSE', 'RPM', '.spec', 'cleaner'],
tests_require=test_requires,
test_suite="nose.collector",
packages = ['spec_cleaner'],
data_files=[('/usr/libexec/obs/service/', glob.glob('obs/*')),
('/usr/share/spec-cleaner/', glob.glob('data/*')),
],
entry_points = {
'console_scripts': ['spec-cleaner = spec_cleaner.main:main']},
)
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
import glob
from spec_cleaner import __version__
test_requires = [
'mock',
'nose',
]
setup(
name='spec_cleaner',
description = 'RPM .spec files cleaner',
long_description = 'Command-line tool for cleaning various formatting' +
'errors in RPM .spec files',
url = 'https://github.com/openSUSE/spec-cleaner',
download_url = 'https://github.com/openSUSE/spec-cleaner',
version = __version__,
author = 'Tomáš Chvátal',
author_email = 'tchvatal@suse.cz',
maintainer = 'Tomáš Chvátal',
maintainer_email = 'tchvatal@suse.cz',
license = 'License :: OSI Approved :: BSD License',
platforms = ['Linux'],
keywords = ['SUSE', 'RPM', '.spec', 'cleaner'],
tests_require=test_requires,
test_suite="nose.collector",
packages = ['spec_cleaner'],
package_data = {'spec_cleaner' : [ "data/*.txt" ]},
data_files=[('/usr/libexec/obs/service/', glob.glob('obs/*'))],
entry_points = {
'console_scripts': ['spec-cleaner = spec_cleaner.main:main']},
)
<commit_msg>Install the data files correctly too.<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
import glob
from spec_cleaner import __version__
test_requires = [
'mock',
'nose',
]
setup(
name='spec_cleaner',
description = 'RPM .spec files cleaner',
long_description = 'Command-line tool for cleaning various formatting' +
'errors in RPM .spec files',
url = 'https://github.com/openSUSE/spec-cleaner',
download_url = 'https://github.com/openSUSE/spec-cleaner',
version = __version__,
author = 'Tomáš Chvátal',
author_email = 'tchvatal@suse.cz',
maintainer = 'Tomáš Chvátal',
maintainer_email = 'tchvatal@suse.cz',
license = 'License :: OSI Approved :: BSD License',
platforms = ['Linux'],
keywords = ['SUSE', 'RPM', '.spec', 'cleaner'],
tests_require=test_requires,
test_suite="nose.collector",
packages = ['spec_cleaner'],
data_files=[('/usr/libexec/obs/service/', glob.glob('obs/*')),
('/usr/share/spec-cleaner/', glob.glob('data/*')),
],
entry_points = {
'console_scripts': ['spec-cleaner = spec_cleaner.main:main']},
)
|
09474810b671f65ec4ce829bd345ddc94d038a63
|
setup.py
|
setup.py
|
from setuptools import setup
setup(
name='trac-github',
version='2.1.5',
author='Aymeric Augustin',
author_email='aymeric.augustin@m4x.org',
url='https://github.com/trac-hacks/trac-github',
description='Trac - GitHub integration',
download_url='http://pypi.python.org/pypi/trac-github',
packages=['tracext'],
platforms='all',
license='BSD',
extras_require={'oauth': ['requests_oauthlib >= 0.5']},
entry_points={'trac.plugins': [
'github.browser = tracext.github:GitHubBrowser',
'github.loginmodule = tracext.github:GitHubLoginModule[oauth]',
'github.postcommithook = tracext.github:GitHubPostCommitHook',
]},
)
|
from setuptools import setup
setup(
name='trac-github',
version='2.1.5',
author='Aymeric Augustin',
author_email='aymeric.augustin@m4x.org',
url='https://github.com/trac-hacks/trac-github',
description='Trac - GitHub integration',
download_url='https://pypi.python.org/pypi/trac-github',
packages=['tracext'],
platforms='all',
license='BSD',
extras_require={'oauth': ['requests_oauthlib >= 0.5']},
entry_points={'trac.plugins': [
'github.browser = tracext.github:GitHubBrowser',
'github.loginmodule = tracext.github:GitHubLoginModule[oauth]',
'github.postcommithook = tracext.github:GitHubPostCommitHook',
]},
)
|
Use HTTPS in download URL
|
Use HTTPS in download URL
It appears that PyPI is now HTTPS-only.
|
Python
|
bsd-3-clause
|
trac-hacks/trac-github
|
from setuptools import setup
setup(
name='trac-github',
version='2.1.5',
author='Aymeric Augustin',
author_email='aymeric.augustin@m4x.org',
url='https://github.com/trac-hacks/trac-github',
description='Trac - GitHub integration',
download_url='http://pypi.python.org/pypi/trac-github',
packages=['tracext'],
platforms='all',
license='BSD',
extras_require={'oauth': ['requests_oauthlib >= 0.5']},
entry_points={'trac.plugins': [
'github.browser = tracext.github:GitHubBrowser',
'github.loginmodule = tracext.github:GitHubLoginModule[oauth]',
'github.postcommithook = tracext.github:GitHubPostCommitHook',
]},
)
Use HTTPS in download URL
It appears that PyPI is now HTTPS-only.
|
from setuptools import setup
setup(
name='trac-github',
version='2.1.5',
author='Aymeric Augustin',
author_email='aymeric.augustin@m4x.org',
url='https://github.com/trac-hacks/trac-github',
description='Trac - GitHub integration',
download_url='https://pypi.python.org/pypi/trac-github',
packages=['tracext'],
platforms='all',
license='BSD',
extras_require={'oauth': ['requests_oauthlib >= 0.5']},
entry_points={'trac.plugins': [
'github.browser = tracext.github:GitHubBrowser',
'github.loginmodule = tracext.github:GitHubLoginModule[oauth]',
'github.postcommithook = tracext.github:GitHubPostCommitHook',
]},
)
|
<commit_before>from setuptools import setup
setup(
name='trac-github',
version='2.1.5',
author='Aymeric Augustin',
author_email='aymeric.augustin@m4x.org',
url='https://github.com/trac-hacks/trac-github',
description='Trac - GitHub integration',
download_url='http://pypi.python.org/pypi/trac-github',
packages=['tracext'],
platforms='all',
license='BSD',
extras_require={'oauth': ['requests_oauthlib >= 0.5']},
entry_points={'trac.plugins': [
'github.browser = tracext.github:GitHubBrowser',
'github.loginmodule = tracext.github:GitHubLoginModule[oauth]',
'github.postcommithook = tracext.github:GitHubPostCommitHook',
]},
)
<commit_msg>Use HTTPS in download URL
It appears that PyPI is now HTTPS-only.<commit_after>
|
from setuptools import setup
setup(
name='trac-github',
version='2.1.5',
author='Aymeric Augustin',
author_email='aymeric.augustin@m4x.org',
url='https://github.com/trac-hacks/trac-github',
description='Trac - GitHub integration',
download_url='https://pypi.python.org/pypi/trac-github',
packages=['tracext'],
platforms='all',
license='BSD',
extras_require={'oauth': ['requests_oauthlib >= 0.5']},
entry_points={'trac.plugins': [
'github.browser = tracext.github:GitHubBrowser',
'github.loginmodule = tracext.github:GitHubLoginModule[oauth]',
'github.postcommithook = tracext.github:GitHubPostCommitHook',
]},
)
|
from setuptools import setup
setup(
name='trac-github',
version='2.1.5',
author='Aymeric Augustin',
author_email='aymeric.augustin@m4x.org',
url='https://github.com/trac-hacks/trac-github',
description='Trac - GitHub integration',
download_url='http://pypi.python.org/pypi/trac-github',
packages=['tracext'],
platforms='all',
license='BSD',
extras_require={'oauth': ['requests_oauthlib >= 0.5']},
entry_points={'trac.plugins': [
'github.browser = tracext.github:GitHubBrowser',
'github.loginmodule = tracext.github:GitHubLoginModule[oauth]',
'github.postcommithook = tracext.github:GitHubPostCommitHook',
]},
)
Use HTTPS in download URL
It appears that PyPI is now HTTPS-only.from setuptools import setup
setup(
name='trac-github',
version='2.1.5',
author='Aymeric Augustin',
author_email='aymeric.augustin@m4x.org',
url='https://github.com/trac-hacks/trac-github',
description='Trac - GitHub integration',
download_url='https://pypi.python.org/pypi/trac-github',
packages=['tracext'],
platforms='all',
license='BSD',
extras_require={'oauth': ['requests_oauthlib >= 0.5']},
entry_points={'trac.plugins': [
'github.browser = tracext.github:GitHubBrowser',
'github.loginmodule = tracext.github:GitHubLoginModule[oauth]',
'github.postcommithook = tracext.github:GitHubPostCommitHook',
]},
)
|
<commit_before>from setuptools import setup
setup(
name='trac-github',
version='2.1.5',
author='Aymeric Augustin',
author_email='aymeric.augustin@m4x.org',
url='https://github.com/trac-hacks/trac-github',
description='Trac - GitHub integration',
download_url='http://pypi.python.org/pypi/trac-github',
packages=['tracext'],
platforms='all',
license='BSD',
extras_require={'oauth': ['requests_oauthlib >= 0.5']},
entry_points={'trac.plugins': [
'github.browser = tracext.github:GitHubBrowser',
'github.loginmodule = tracext.github:GitHubLoginModule[oauth]',
'github.postcommithook = tracext.github:GitHubPostCommitHook',
]},
)
<commit_msg>Use HTTPS in download URL
It appears that PyPI is now HTTPS-only.<commit_after>from setuptools import setup
setup(
name='trac-github',
version='2.1.5',
author='Aymeric Augustin',
author_email='aymeric.augustin@m4x.org',
url='https://github.com/trac-hacks/trac-github',
description='Trac - GitHub integration',
download_url='https://pypi.python.org/pypi/trac-github',
packages=['tracext'],
platforms='all',
license='BSD',
extras_require={'oauth': ['requests_oauthlib >= 0.5']},
entry_points={'trac.plugins': [
'github.browser = tracext.github:GitHubBrowser',
'github.loginmodule = tracext.github:GitHubLoginModule[oauth]',
'github.postcommithook = tracext.github:GitHubPostCommitHook',
]},
)
|
b254afaea67e08d83611423a3a1ec7afcee849b3
|
setup.py
|
setup.py
|
"""Install Wallace as a command line utility."""
from setuptools import setup
setup_args = dict(
name='wallace-platform',
packages=['wallace'],
version="0.11.2",
description='Wallace, a platform for experimental cultural evolution',
url='http://github.com/berkeley-cocosci/Wallace',
author='Berkeley CoCoSci',
author_email='wallace@cocosci.berkeley.edu',
license='MIT',
keywords=['science', 'cultural evolution', 'experiments', 'psychology'],
classifiers=[],
zip_safe=False,
entry_points={
'console_scripts': [
'wallace = wallace.command_line:wallace',
],
}
)
# Read in requirements.txt for dependencies.
setup_args['install_requires'] = install_requires = []
setup_args['dependency_links'] = dependency_links = []
with open('requirements.txt') as f:
for line in f.readlines():
req = line.strip()
if not req or req.startswith('#'):
continue
if req.startswith('-e '):
dependency_links.append(req[3:])
else:
install_requires.append(req)
setup(**setup_args)
|
"""Install Wallace as a command line utility."""
from setuptools import setup
setup_args = dict(
name='wallace-platform',
packages=['wallace'],
version="0.11.2",
description='Wallace, a platform for experimental cultural evolution',
url='http://github.com/berkeley-cocosci/Wallace',
author='Berkeley CoCoSci',
author_email='wallace@cocosci.berkeley.edu',
license='MIT',
keywords=['science', 'cultural evolution', 'experiments', 'psychology'],
classifiers=[],
zip_safe=False,
entry_points={
'console_scripts': [
'wallace = wallace.command_line:wallace',
],
},
dependency_links=['-e git+git://github.com/berkeley-cocosci/psiTurk.git@wallace3#egg=psiturk']
)
# Read in requirements.txt for dependencies.
setup_args['install_requires'] = install_requires = []
setup_args['dependency_links'] = dependency_links = []
with open('requirements.txt') as f:
for line in f.readlines():
req = line.strip()
if not req or req.startswith('#'):
continue
if req.startswith('-e '):
dependency_links.append(req[3:])
else:
install_requires.append(req)
setup(**setup_args)
|
Add custom psiTurk as dependency link
|
Add custom psiTurk as dependency link
|
Python
|
mit
|
jcpeterson/Dallinger,jcpeterson/Dallinger,berkeley-cocosci/Wallace,Dallinger/Dallinger,jcpeterson/Dallinger,suchow/Wallace,Dallinger/Dallinger,suchow/Wallace,Dallinger/Dallinger,berkeley-cocosci/Wallace,jcpeterson/Dallinger,Dallinger/Dallinger,suchow/Wallace,jcpeterson/Dallinger,Dallinger/Dallinger,berkeley-cocosci/Wallace
|
"""Install Wallace as a command line utility."""
from setuptools import setup
setup_args = dict(
name='wallace-platform',
packages=['wallace'],
version="0.11.2",
description='Wallace, a platform for experimental cultural evolution',
url='http://github.com/berkeley-cocosci/Wallace',
author='Berkeley CoCoSci',
author_email='wallace@cocosci.berkeley.edu',
license='MIT',
keywords=['science', 'cultural evolution', 'experiments', 'psychology'],
classifiers=[],
zip_safe=False,
entry_points={
'console_scripts': [
'wallace = wallace.command_line:wallace',
],
}
)
# Read in requirements.txt for dependencies.
setup_args['install_requires'] = install_requires = []
setup_args['dependency_links'] = dependency_links = []
with open('requirements.txt') as f:
for line in f.readlines():
req = line.strip()
if not req or req.startswith('#'):
continue
if req.startswith('-e '):
dependency_links.append(req[3:])
else:
install_requires.append(req)
setup(**setup_args)
Add custom psiTurk as dependency link
|
"""Install Wallace as a command line utility."""
from setuptools import setup
setup_args = dict(
name='wallace-platform',
packages=['wallace'],
version="0.11.2",
description='Wallace, a platform for experimental cultural evolution',
url='http://github.com/berkeley-cocosci/Wallace',
author='Berkeley CoCoSci',
author_email='wallace@cocosci.berkeley.edu',
license='MIT',
keywords=['science', 'cultural evolution', 'experiments', 'psychology'],
classifiers=[],
zip_safe=False,
entry_points={
'console_scripts': [
'wallace = wallace.command_line:wallace',
],
},
dependency_links=['-e git+git://github.com/berkeley-cocosci/psiTurk.git@wallace3#egg=psiturk']
)
# Read in requirements.txt for dependencies.
setup_args['install_requires'] = install_requires = []
setup_args['dependency_links'] = dependency_links = []
with open('requirements.txt') as f:
for line in f.readlines():
req = line.strip()
if not req or req.startswith('#'):
continue
if req.startswith('-e '):
dependency_links.append(req[3:])
else:
install_requires.append(req)
setup(**setup_args)
|
<commit_before>"""Install Wallace as a command line utility."""
from setuptools import setup
setup_args = dict(
name='wallace-platform',
packages=['wallace'],
version="0.11.2",
description='Wallace, a platform for experimental cultural evolution',
url='http://github.com/berkeley-cocosci/Wallace',
author='Berkeley CoCoSci',
author_email='wallace@cocosci.berkeley.edu',
license='MIT',
keywords=['science', 'cultural evolution', 'experiments', 'psychology'],
classifiers=[],
zip_safe=False,
entry_points={
'console_scripts': [
'wallace = wallace.command_line:wallace',
],
}
)
# Read in requirements.txt for dependencies.
setup_args['install_requires'] = install_requires = []
setup_args['dependency_links'] = dependency_links = []
with open('requirements.txt') as f:
for line in f.readlines():
req = line.strip()
if not req or req.startswith('#'):
continue
if req.startswith('-e '):
dependency_links.append(req[3:])
else:
install_requires.append(req)
setup(**setup_args)
<commit_msg>Add custom psiTurk as dependency link<commit_after>
|
"""Install Wallace as a command line utility."""
from setuptools import setup
setup_args = dict(
name='wallace-platform',
packages=['wallace'],
version="0.11.2",
description='Wallace, a platform for experimental cultural evolution',
url='http://github.com/berkeley-cocosci/Wallace',
author='Berkeley CoCoSci',
author_email='wallace@cocosci.berkeley.edu',
license='MIT',
keywords=['science', 'cultural evolution', 'experiments', 'psychology'],
classifiers=[],
zip_safe=False,
entry_points={
'console_scripts': [
'wallace = wallace.command_line:wallace',
],
},
dependency_links=['-e git+git://github.com/berkeley-cocosci/psiTurk.git@wallace3#egg=psiturk']
)
# Read in requirements.txt for dependencies.
setup_args['install_requires'] = install_requires = []
setup_args['dependency_links'] = dependency_links = []
with open('requirements.txt') as f:
for line in f.readlines():
req = line.strip()
if not req or req.startswith('#'):
continue
if req.startswith('-e '):
dependency_links.append(req[3:])
else:
install_requires.append(req)
setup(**setup_args)
|
"""Install Wallace as a command line utility."""
from setuptools import setup
setup_args = dict(
name='wallace-platform',
packages=['wallace'],
version="0.11.2",
description='Wallace, a platform for experimental cultural evolution',
url='http://github.com/berkeley-cocosci/Wallace',
author='Berkeley CoCoSci',
author_email='wallace@cocosci.berkeley.edu',
license='MIT',
keywords=['science', 'cultural evolution', 'experiments', 'psychology'],
classifiers=[],
zip_safe=False,
entry_points={
'console_scripts': [
'wallace = wallace.command_line:wallace',
],
}
)
# Read in requirements.txt for dependencies.
setup_args['install_requires'] = install_requires = []
setup_args['dependency_links'] = dependency_links = []
with open('requirements.txt') as f:
for line in f.readlines():
req = line.strip()
if not req or req.startswith('#'):
continue
if req.startswith('-e '):
dependency_links.append(req[3:])
else:
install_requires.append(req)
setup(**setup_args)
Add custom psiTurk as dependency link"""Install Wallace as a command line utility."""
from setuptools import setup
setup_args = dict(
name='wallace-platform',
packages=['wallace'],
version="0.11.2",
description='Wallace, a platform for experimental cultural evolution',
url='http://github.com/berkeley-cocosci/Wallace',
author='Berkeley CoCoSci',
author_email='wallace@cocosci.berkeley.edu',
license='MIT',
keywords=['science', 'cultural evolution', 'experiments', 'psychology'],
classifiers=[],
zip_safe=False,
entry_points={
'console_scripts': [
'wallace = wallace.command_line:wallace',
],
},
dependency_links=['-e git+git://github.com/berkeley-cocosci/psiTurk.git@wallace3#egg=psiturk']
)
# Read in requirements.txt for dependencies.
setup_args['install_requires'] = install_requires = []
setup_args['dependency_links'] = dependency_links = []
with open('requirements.txt') as f:
for line in f.readlines():
req = line.strip()
if not req or req.startswith('#'):
continue
if req.startswith('-e '):
dependency_links.append(req[3:])
else:
install_requires.append(req)
setup(**setup_args)
|
<commit_before>"""Install Wallace as a command line utility."""
from setuptools import setup
setup_args = dict(
name='wallace-platform',
packages=['wallace'],
version="0.11.2",
description='Wallace, a platform for experimental cultural evolution',
url='http://github.com/berkeley-cocosci/Wallace',
author='Berkeley CoCoSci',
author_email='wallace@cocosci.berkeley.edu',
license='MIT',
keywords=['science', 'cultural evolution', 'experiments', 'psychology'],
classifiers=[],
zip_safe=False,
entry_points={
'console_scripts': [
'wallace = wallace.command_line:wallace',
],
}
)
# Read in requirements.txt for dependencies.
setup_args['install_requires'] = install_requires = []
setup_args['dependency_links'] = dependency_links = []
with open('requirements.txt') as f:
for line in f.readlines():
req = line.strip()
if not req or req.startswith('#'):
continue
if req.startswith('-e '):
dependency_links.append(req[3:])
else:
install_requires.append(req)
setup(**setup_args)
<commit_msg>Add custom psiTurk as dependency link<commit_after>"""Install Wallace as a command line utility."""
from setuptools import setup
setup_args = dict(
name='wallace-platform',
packages=['wallace'],
version="0.11.2",
description='Wallace, a platform for experimental cultural evolution',
url='http://github.com/berkeley-cocosci/Wallace',
author='Berkeley CoCoSci',
author_email='wallace@cocosci.berkeley.edu',
license='MIT',
keywords=['science', 'cultural evolution', 'experiments', 'psychology'],
classifiers=[],
zip_safe=False,
entry_points={
'console_scripts': [
'wallace = wallace.command_line:wallace',
],
},
dependency_links=['-e git+git://github.com/berkeley-cocosci/psiTurk.git@wallace3#egg=psiturk']
)
# Read in requirements.txt for dependencies.
setup_args['install_requires'] = install_requires = []
setup_args['dependency_links'] = dependency_links = []
with open('requirements.txt') as f:
for line in f.readlines():
req = line.strip()
if not req or req.startswith('#'):
continue
if req.startswith('-e '):
dependency_links.append(req[3:])
else:
install_requires.append(req)
setup(**setup_args)
|
c0b2afcac4279f97bc110813549c389b125ca900
|
setup.py
|
setup.py
|
# -*- coding: utf-8 -*-
from setuptools import setup
setup(
name="mailroom",
description="The mailroom implementation tracks donations and send thank you letters.",
version='0.1.0',
author="Zach Rickert, Steven Than, David Smith",
author_email="zachrickert@gmail.com, steventhan11@gmail.com, dbsmith.dbs83@gmail.com",
license='MIT',
py_modules=['mailroom'],
package_dir={'': 'src'},
install_requires=[],
extras_require={'test': ['pytest']},
)
|
# -*- coding: utf-8 -*-
from setuptools import setup
setup(
name="mailroom",
description="The mailroom implementation tracks donations and send thank you letters.",
version='0.1.0',
author="Zach Rickert, Steven Than, David Smith",
author_email="zachrickert@gmail.com, steventhan11@gmail.com, dbsmith.dbs83@gmail.com",
license='MIT',
py_modules=['mailroom'],
package_dir={'': 'src'},
install_requires=[],
extras_require={'test': ['pytest']},
entry_points={'console_scripts': ["mailroom = mailroom:main_menu"]}
)
|
Add entry point to run mailroom from command line.
|
Add entry point to run mailroom from command line.
|
Python
|
mit
|
zachrickert/mailroom
|
# -*- coding: utf-8 -*-
from setuptools import setup
setup(
name="mailroom",
description="The mailroom implementation tracks donations and send thank you letters.",
version='0.1.0',
author="Zach Rickert, Steven Than, David Smith",
author_email="zachrickert@gmail.com, steventhan11@gmail.com, dbsmith.dbs83@gmail.com",
license='MIT',
py_modules=['mailroom'],
package_dir={'': 'src'},
install_requires=[],
extras_require={'test': ['pytest']},
)
Add entry point to run mailroom from command line.
|
# -*- coding: utf-8 -*-
from setuptools import setup
setup(
name="mailroom",
description="The mailroom implementation tracks donations and send thank you letters.",
version='0.1.0',
author="Zach Rickert, Steven Than, David Smith",
author_email="zachrickert@gmail.com, steventhan11@gmail.com, dbsmith.dbs83@gmail.com",
license='MIT',
py_modules=['mailroom'],
package_dir={'': 'src'},
install_requires=[],
extras_require={'test': ['pytest']},
entry_points={'console_scripts': ["mailroom = mailroom:main_menu"]}
)
|
<commit_before># -*- coding: utf-8 -*-
from setuptools import setup
setup(
name="mailroom",
description="The mailroom implementation tracks donations and send thank you letters.",
version='0.1.0',
author="Zach Rickert, Steven Than, David Smith",
author_email="zachrickert@gmail.com, steventhan11@gmail.com, dbsmith.dbs83@gmail.com",
license='MIT',
py_modules=['mailroom'],
package_dir={'': 'src'},
install_requires=[],
extras_require={'test': ['pytest']},
)
<commit_msg>Add entry point to run mailroom from command line.<commit_after>
|
# -*- coding: utf-8 -*-
from setuptools import setup
setup(
name="mailroom",
description="The mailroom implementation tracks donations and send thank you letters.",
version='0.1.0',
author="Zach Rickert, Steven Than, David Smith",
author_email="zachrickert@gmail.com, steventhan11@gmail.com, dbsmith.dbs83@gmail.com",
license='MIT',
py_modules=['mailroom'],
package_dir={'': 'src'},
install_requires=[],
extras_require={'test': ['pytest']},
entry_points={'console_scripts': ["mailroom = mailroom:main_menu"]}
)
|
# -*- coding: utf-8 -*-
from setuptools import setup
setup(
name="mailroom",
description="The mailroom implementation tracks donations and send thank you letters.",
version='0.1.0',
author="Zach Rickert, Steven Than, David Smith",
author_email="zachrickert@gmail.com, steventhan11@gmail.com, dbsmith.dbs83@gmail.com",
license='MIT',
py_modules=['mailroom'],
package_dir={'': 'src'},
install_requires=[],
extras_require={'test': ['pytest']},
)
Add entry point to run mailroom from command line.# -*- coding: utf-8 -*-
from setuptools import setup
setup(
name="mailroom",
description="The mailroom implementation tracks donations and send thank you letters.",
version='0.1.0',
author="Zach Rickert, Steven Than, David Smith",
author_email="zachrickert@gmail.com, steventhan11@gmail.com, dbsmith.dbs83@gmail.com",
license='MIT',
py_modules=['mailroom'],
package_dir={'': 'src'},
install_requires=[],
extras_require={'test': ['pytest']},
entry_points={'console_scripts': ["mailroom = mailroom:main_menu"]}
)
|
<commit_before># -*- coding: utf-8 -*-
from setuptools import setup
setup(
name="mailroom",
description="The mailroom implementation tracks donations and send thank you letters.",
version='0.1.0',
author="Zach Rickert, Steven Than, David Smith",
author_email="zachrickert@gmail.com, steventhan11@gmail.com, dbsmith.dbs83@gmail.com",
license='MIT',
py_modules=['mailroom'],
package_dir={'': 'src'},
install_requires=[],
extras_require={'test': ['pytest']},
)
<commit_msg>Add entry point to run mailroom from command line.<commit_after># -*- coding: utf-8 -*-
from setuptools import setup
setup(
name="mailroom",
description="The mailroom implementation tracks donations and send thank you letters.",
version='0.1.0',
author="Zach Rickert, Steven Than, David Smith",
author_email="zachrickert@gmail.com, steventhan11@gmail.com, dbsmith.dbs83@gmail.com",
license='MIT',
py_modules=['mailroom'],
package_dir={'': 'src'},
install_requires=[],
extras_require={'test': ['pytest']},
entry_points={'console_scripts': ["mailroom = mailroom:main_menu"]}
)
|
3064dd0fbddd24c5ca30bd39a90187991c3e0861
|
setup.py
|
setup.py
|
#!/usr/bin/env python
import io
from os import path
from setuptools import setup, find_packages
from pywind import __version__
# Get the long description from the relevant file
here = path.abspath(path.dirname(__file__))
with io.open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='pywind',
version=__version__,
description='Python Modules to access online information relating to renewable energy in the UK',
long_description=long_description,
author='David Reid',
author_email='zathrasorama@gmail.com',
url='https://github.com/zathras777/pywind',
packages=find_packages(exclude=['tests']),
install_requires=[
'lxml', 'xlrd', 'html5lib'
],
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Python Modules',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
],
test_suite='tests',
license='Unlicense',
)
|
#!/usr/bin/env python
import io
from os import path
from setuptools import setup, find_packages
from pywind import __version__
# Get the long description from the relevant file
here = path.abspath(path.dirname(__file__))
with io.open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='pywind',
version=__version__,
description='Python Modules to access online information relating to renewable energy in the UK',
long_description=long_description,
author='David Reid',
author_email='zathrasorama@gmail.com',
url='https://github.com/zathras777/pywind',
packages=find_packages(exclude=['tests']),
install_requires=[
'lxml', 'xlrd', 'html5lib', 'requests'
],
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Python Modules',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
],
test_suite='tests',
license='Unlicense',
)
|
Add requests as a requirement.
|
Add requests as a requirement.
|
Python
|
unlicense
|
zathras777/pywind,zathras777/pywind
|
#!/usr/bin/env python
import io
from os import path
from setuptools import setup, find_packages
from pywind import __version__
# Get the long description from the relevant file
here = path.abspath(path.dirname(__file__))
with io.open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='pywind',
version=__version__,
description='Python Modules to access online information relating to renewable energy in the UK',
long_description=long_description,
author='David Reid',
author_email='zathrasorama@gmail.com',
url='https://github.com/zathras777/pywind',
packages=find_packages(exclude=['tests']),
install_requires=[
'lxml', 'xlrd', 'html5lib'
],
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Python Modules',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
],
test_suite='tests',
license='Unlicense',
)
Add requests as a requirement.
|
#!/usr/bin/env python
import io
from os import path
from setuptools import setup, find_packages
from pywind import __version__
# Get the long description from the relevant file
here = path.abspath(path.dirname(__file__))
with io.open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='pywind',
version=__version__,
description='Python Modules to access online information relating to renewable energy in the UK',
long_description=long_description,
author='David Reid',
author_email='zathrasorama@gmail.com',
url='https://github.com/zathras777/pywind',
packages=find_packages(exclude=['tests']),
install_requires=[
'lxml', 'xlrd', 'html5lib', 'requests'
],
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Python Modules',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
],
test_suite='tests',
license='Unlicense',
)
|
<commit_before>#!/usr/bin/env python
import io
from os import path
from setuptools import setup, find_packages
from pywind import __version__
# Get the long description from the relevant file
here = path.abspath(path.dirname(__file__))
with io.open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='pywind',
version=__version__,
description='Python Modules to access online information relating to renewable energy in the UK',
long_description=long_description,
author='David Reid',
author_email='zathrasorama@gmail.com',
url='https://github.com/zathras777/pywind',
packages=find_packages(exclude=['tests']),
install_requires=[
'lxml', 'xlrd', 'html5lib'
],
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Python Modules',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
],
test_suite='tests',
license='Unlicense',
)
<commit_msg>Add requests as a requirement.<commit_after>
|
#!/usr/bin/env python
import io
from os import path
from setuptools import setup, find_packages
from pywind import __version__
# Get the long description from the relevant file
here = path.abspath(path.dirname(__file__))
with io.open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='pywind',
version=__version__,
description='Python Modules to access online information relating to renewable energy in the UK',
long_description=long_description,
author='David Reid',
author_email='zathrasorama@gmail.com',
url='https://github.com/zathras777/pywind',
packages=find_packages(exclude=['tests']),
install_requires=[
'lxml', 'xlrd', 'html5lib', 'requests'
],
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Python Modules',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
],
test_suite='tests',
license='Unlicense',
)
|
#!/usr/bin/env python
import io
from os import path
from setuptools import setup, find_packages
from pywind import __version__
# Get the long description from the relevant file
here = path.abspath(path.dirname(__file__))
with io.open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='pywind',
version=__version__,
description='Python Modules to access online information relating to renewable energy in the UK',
long_description=long_description,
author='David Reid',
author_email='zathrasorama@gmail.com',
url='https://github.com/zathras777/pywind',
packages=find_packages(exclude=['tests']),
install_requires=[
'lxml', 'xlrd', 'html5lib'
],
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Python Modules',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
],
test_suite='tests',
license='Unlicense',
)
Add requests as a requirement.#!/usr/bin/env python
import io
from os import path
from setuptools import setup, find_packages
from pywind import __version__
# Get the long description from the relevant file
here = path.abspath(path.dirname(__file__))
with io.open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='pywind',
version=__version__,
description='Python Modules to access online information relating to renewable energy in the UK',
long_description=long_description,
author='David Reid',
author_email='zathrasorama@gmail.com',
url='https://github.com/zathras777/pywind',
packages=find_packages(exclude=['tests']),
install_requires=[
'lxml', 'xlrd', 'html5lib', 'requests'
],
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Python Modules',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
],
test_suite='tests',
license='Unlicense',
)
|
<commit_before>#!/usr/bin/env python
import io
from os import path
from setuptools import setup, find_packages
from pywind import __version__
# Get the long description from the relevant file
here = path.abspath(path.dirname(__file__))
with io.open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='pywind',
version=__version__,
description='Python Modules to access online information relating to renewable energy in the UK',
long_description=long_description,
author='David Reid',
author_email='zathrasorama@gmail.com',
url='https://github.com/zathras777/pywind',
packages=find_packages(exclude=['tests']),
install_requires=[
'lxml', 'xlrd', 'html5lib'
],
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Python Modules',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
],
test_suite='tests',
license='Unlicense',
)
<commit_msg>Add requests as a requirement.<commit_after>#!/usr/bin/env python
import io
from os import path
from setuptools import setup, find_packages
from pywind import __version__
# Get the long description from the relevant file
here = path.abspath(path.dirname(__file__))
with io.open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='pywind',
version=__version__,
description='Python Modules to access online information relating to renewable energy in the UK',
long_description=long_description,
author='David Reid',
author_email='zathrasorama@gmail.com',
url='https://github.com/zathras777/pywind',
packages=find_packages(exclude=['tests']),
install_requires=[
'lxml', 'xlrd', 'html5lib', 'requests'
],
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Python Modules',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
],
test_suite='tests',
license='Unlicense',
)
|
b2ff1296b4e82da8dd8f8cf495ad4e837bf92b94
|
setup.py
|
setup.py
|
from setuptools import setup, find_packages
setup(
name='primestg',
version='1.1.0',
packages=find_packages(),
url='https://github.com/gisce/primestg',
license='GNU Affero General Public License v3',
author='GISCE-TI, S.L.',
author_email='devel@gisce.net',
install_requires=[
'lxml'
],
description='Prime STG-DC Interface Specification'
)
|
from setuptools import setup, find_packages
setup(
name='primestg',
version='1.1.0',
packages=find_packages(),
url='https://github.com/gisce/primestg',
license='GNU Affero General Public License v3',
author='GISCE-TI, S.L.',
author_email='devel@gisce.net',
install_requires=[
'lxml',
'zeep'
],
description='Prime STG-DC Interface Specification'
)
|
Add zeep library as requirement
|
Add zeep library as requirement
|
Python
|
agpl-3.0
|
gisce/primestg
|
from setuptools import setup, find_packages
setup(
name='primestg',
version='1.1.0',
packages=find_packages(),
url='https://github.com/gisce/primestg',
license='GNU Affero General Public License v3',
author='GISCE-TI, S.L.',
author_email='devel@gisce.net',
install_requires=[
'lxml'
],
description='Prime STG-DC Interface Specification'
)
Add zeep library as requirement
|
from setuptools import setup, find_packages
setup(
name='primestg',
version='1.1.0',
packages=find_packages(),
url='https://github.com/gisce/primestg',
license='GNU Affero General Public License v3',
author='GISCE-TI, S.L.',
author_email='devel@gisce.net',
install_requires=[
'lxml',
'zeep'
],
description='Prime STG-DC Interface Specification'
)
|
<commit_before>from setuptools import setup, find_packages
setup(
name='primestg',
version='1.1.0',
packages=find_packages(),
url='https://github.com/gisce/primestg',
license='GNU Affero General Public License v3',
author='GISCE-TI, S.L.',
author_email='devel@gisce.net',
install_requires=[
'lxml'
],
description='Prime STG-DC Interface Specification'
)
<commit_msg>Add zeep library as requirement<commit_after>
|
from setuptools import setup, find_packages
setup(
name='primestg',
version='1.1.0',
packages=find_packages(),
url='https://github.com/gisce/primestg',
license='GNU Affero General Public License v3',
author='GISCE-TI, S.L.',
author_email='devel@gisce.net',
install_requires=[
'lxml',
'zeep'
],
description='Prime STG-DC Interface Specification'
)
|
from setuptools import setup, find_packages
setup(
name='primestg',
version='1.1.0',
packages=find_packages(),
url='https://github.com/gisce/primestg',
license='GNU Affero General Public License v3',
author='GISCE-TI, S.L.',
author_email='devel@gisce.net',
install_requires=[
'lxml'
],
description='Prime STG-DC Interface Specification'
)
Add zeep library as requirementfrom setuptools import setup, find_packages
setup(
name='primestg',
version='1.1.0',
packages=find_packages(),
url='https://github.com/gisce/primestg',
license='GNU Affero General Public License v3',
author='GISCE-TI, S.L.',
author_email='devel@gisce.net',
install_requires=[
'lxml',
'zeep'
],
description='Prime STG-DC Interface Specification'
)
|
<commit_before>from setuptools import setup, find_packages
setup(
name='primestg',
version='1.1.0',
packages=find_packages(),
url='https://github.com/gisce/primestg',
license='GNU Affero General Public License v3',
author='GISCE-TI, S.L.',
author_email='devel@gisce.net',
install_requires=[
'lxml'
],
description='Prime STG-DC Interface Specification'
)
<commit_msg>Add zeep library as requirement<commit_after>from setuptools import setup, find_packages
setup(
name='primestg',
version='1.1.0',
packages=find_packages(),
url='https://github.com/gisce/primestg',
license='GNU Affero General Public License v3',
author='GISCE-TI, S.L.',
author_email='devel@gisce.net',
install_requires=[
'lxml',
'zeep'
],
description='Prime STG-DC Interface Specification'
)
|
e36c4a3f2fa54be390f8b0ae00f9151f95c49ed4
|
sqlobject/tests/test_schema.py
|
sqlobject/tests/test_schema.py
|
from sqlobject import *
from sqlobject.tests.dbtest import *
########################################
## Schema per connection
########################################
class Test(SQLObject):
foo = UnicodeCol(length=200)
def test_connection_schema():
if not supports('schema'):
return
conn = getConnection(schema=None)
conn.schema = None
conn.query('CREATE SCHEMA test')
setupClass(Test)
Test(foo='bar')
conn = Test._connection
assert conn.schema, \
"""To test a schema you need to give a connection uri that contains a schema."""
assert conn.queryAll("select * from %s.test" % conn.schema)
|
from sqlobject import *
from sqlobject.tests.dbtest import *
########################################
## Schema per connection
########################################
class Test(SQLObject):
foo = UnicodeCol(length=200)
def test_connection_schema():
if not supports('schema'):
return
conn = getConnection()
conn.schema = None
conn.query('CREATE SCHEMA test')
conn.schema = 'test'
conn.query('SET search_path TO test')
setupClass(Test)
Test(foo='bar')
assert conn.queryAll("SELECT * FROM test.test")
|
Allow the test to be run without 'schema=' parameter in the DB URI.
|
Allow the test to be run without 'schema=' parameter in the DB URI.
git-svn-id: 07e5abd2c6e244bc465bf007dc23a4c6bc1bee58@3524 95a46c32-92d2-0310-94a5-8d71aeb3d4b3
|
Python
|
lgpl-2.1
|
drnlm/sqlobject,drnlm/sqlobject,sqlobject/sqlobject,sqlobject/sqlobject
|
from sqlobject import *
from sqlobject.tests.dbtest import *
########################################
## Schema per connection
########################################
class Test(SQLObject):
foo = UnicodeCol(length=200)
def test_connection_schema():
if not supports('schema'):
return
conn = getConnection(schema=None)
conn.schema = None
conn.query('CREATE SCHEMA test')
setupClass(Test)
Test(foo='bar')
conn = Test._connection
assert conn.schema, \
"""To test a schema you need to give a connection uri that contains a schema."""
assert conn.queryAll("select * from %s.test" % conn.schema)
Allow the test to be run without 'schema=' parameter in the DB URI.
git-svn-id: 07e5abd2c6e244bc465bf007dc23a4c6bc1bee58@3524 95a46c32-92d2-0310-94a5-8d71aeb3d4b3
|
from sqlobject import *
from sqlobject.tests.dbtest import *
########################################
## Schema per connection
########################################
class Test(SQLObject):
foo = UnicodeCol(length=200)
def test_connection_schema():
if not supports('schema'):
return
conn = getConnection()
conn.schema = None
conn.query('CREATE SCHEMA test')
conn.schema = 'test'
conn.query('SET search_path TO test')
setupClass(Test)
Test(foo='bar')
assert conn.queryAll("SELECT * FROM test.test")
|
<commit_before>from sqlobject import *
from sqlobject.tests.dbtest import *
########################################
## Schema per connection
########################################
class Test(SQLObject):
foo = UnicodeCol(length=200)
def test_connection_schema():
if not supports('schema'):
return
conn = getConnection(schema=None)
conn.schema = None
conn.query('CREATE SCHEMA test')
setupClass(Test)
Test(foo='bar')
conn = Test._connection
assert conn.schema, \
"""To test a schema you need to give a connection uri that contains a schema."""
assert conn.queryAll("select * from %s.test" % conn.schema)
<commit_msg>Allow the test to be run without 'schema=' parameter in the DB URI.
git-svn-id: 07e5abd2c6e244bc465bf007dc23a4c6bc1bee58@3524 95a46c32-92d2-0310-94a5-8d71aeb3d4b3<commit_after>
|
from sqlobject import *
from sqlobject.tests.dbtest import *
########################################
## Schema per connection
########################################
class Test(SQLObject):
foo = UnicodeCol(length=200)
def test_connection_schema():
if not supports('schema'):
return
conn = getConnection()
conn.schema = None
conn.query('CREATE SCHEMA test')
conn.schema = 'test'
conn.query('SET search_path TO test')
setupClass(Test)
Test(foo='bar')
assert conn.queryAll("SELECT * FROM test.test")
|
from sqlobject import *
from sqlobject.tests.dbtest import *
########################################
## Schema per connection
########################################
class Test(SQLObject):
foo = UnicodeCol(length=200)
def test_connection_schema():
if not supports('schema'):
return
conn = getConnection(schema=None)
conn.schema = None
conn.query('CREATE SCHEMA test')
setupClass(Test)
Test(foo='bar')
conn = Test._connection
assert conn.schema, \
"""To test a schema you need to give a connection uri that contains a schema."""
assert conn.queryAll("select * from %s.test" % conn.schema)
Allow the test to be run without 'schema=' parameter in the DB URI.
git-svn-id: 07e5abd2c6e244bc465bf007dc23a4c6bc1bee58@3524 95a46c32-92d2-0310-94a5-8d71aeb3d4b3from sqlobject import *
from sqlobject.tests.dbtest import *
########################################
## Schema per connection
########################################
class Test(SQLObject):
foo = UnicodeCol(length=200)
def test_connection_schema():
if not supports('schema'):
return
conn = getConnection()
conn.schema = None
conn.query('CREATE SCHEMA test')
conn.schema = 'test'
conn.query('SET search_path TO test')
setupClass(Test)
Test(foo='bar')
assert conn.queryAll("SELECT * FROM test.test")
|
<commit_before>from sqlobject import *
from sqlobject.tests.dbtest import *
########################################
## Schema per connection
########################################
class Test(SQLObject):
foo = UnicodeCol(length=200)
def test_connection_schema():
if not supports('schema'):
return
conn = getConnection(schema=None)
conn.schema = None
conn.query('CREATE SCHEMA test')
setupClass(Test)
Test(foo='bar')
conn = Test._connection
assert conn.schema, \
"""To test a schema you need to give a connection uri that contains a schema."""
assert conn.queryAll("select * from %s.test" % conn.schema)
<commit_msg>Allow the test to be run without 'schema=' parameter in the DB URI.
git-svn-id: 07e5abd2c6e244bc465bf007dc23a4c6bc1bee58@3524 95a46c32-92d2-0310-94a5-8d71aeb3d4b3<commit_after>from sqlobject import *
from sqlobject.tests.dbtest import *
########################################
## Schema per connection
########################################
class Test(SQLObject):
foo = UnicodeCol(length=200)
def test_connection_schema():
if not supports('schema'):
return
conn = getConnection()
conn.schema = None
conn.query('CREATE SCHEMA test')
conn.schema = 'test'
conn.query('SET search_path TO test')
setupClass(Test)
Test(foo='bar')
assert conn.queryAll("SELECT * FROM test.test")
|
07c768ec9363a99ff2017ba8e2cccca42239e537
|
setup.py
|
setup.py
|
from setuptools import setup, find_packages
setup(
name='gdcdatamodel',
packages=find_packages(),
install_requires=[
'pytz==2016.4',
'graphviz==0.4.2',
'jsonschema==2.5.1',
'python-dateutil==2.4.2',
'psqlgraph',
'gdcdictionary',
'dictionaryutils>=2.0.0,<3.0.0',
'cdisutils',
],
package_data={
"gdcdatamodel": [
"xml_mappings/*.yaml",
]
},
dependency_links=[
'git+https://github.com/NCI-GDC/cdisutils.git@863ce13772116b51bcf5ce7e556f5df3cb9e6f63#egg=cdisutils',
'git+https://github.com/NCI-GDC/psqlgraph.git@1.2.0#egg=psqlgraph',
'git+https://github.com/NCI-GDC/gdcdictionary.git@1.15.0#egg=gdcdictionary',
],
entry_points={
'console_scripts': [
'gdc_postgres_admin=gdcdatamodel.gdc_postgres_admin:main'
]
},
)
|
from setuptools import setup, find_packages
setup(
name='gdcdatamodel',
packages=find_packages(),
install_requires=[
'pytz==2016.4',
'graphviz==0.4.2',
'jsonschema==2.5.1',
'python-dateutil==2.4.2',
'psqlgraph',
'gdcdictionary',
'dictionaryutils>=2.0.4,<3.0.0',
'cdisutils',
],
package_data={
"gdcdatamodel": [
"xml_mappings/*.yaml",
]
},
dependency_links=[
'git+https://github.com/NCI-GDC/cdisutils.git@863ce13772116b51bcf5ce7e556f5df3cb9e6f63#egg=cdisutils',
'git+https://github.com/NCI-GDC/psqlgraph.git@1.2.0#egg=psqlgraph',
'git+https://github.com/NCI-GDC/gdcdictionary.git@1.15.0#egg=gdcdictionary',
],
entry_points={
'console_scripts': [
'gdc_postgres_admin=gdcdatamodel.gdc_postgres_admin:main'
]
},
)
|
Update dictionaryutils pins to get latest
|
chore(pins): Update dictionaryutils pins to get latest
- Update dictionaryutils pins to get version with data release
changes
|
Python
|
apache-2.0
|
NCI-GDC/gdcdatamodel,NCI-GDC/gdcdatamodel
|
from setuptools import setup, find_packages
setup(
name='gdcdatamodel',
packages=find_packages(),
install_requires=[
'pytz==2016.4',
'graphviz==0.4.2',
'jsonschema==2.5.1',
'python-dateutil==2.4.2',
'psqlgraph',
'gdcdictionary',
'dictionaryutils>=2.0.0,<3.0.0',
'cdisutils',
],
package_data={
"gdcdatamodel": [
"xml_mappings/*.yaml",
]
},
dependency_links=[
'git+https://github.com/NCI-GDC/cdisutils.git@863ce13772116b51bcf5ce7e556f5df3cb9e6f63#egg=cdisutils',
'git+https://github.com/NCI-GDC/psqlgraph.git@1.2.0#egg=psqlgraph',
'git+https://github.com/NCI-GDC/gdcdictionary.git@1.15.0#egg=gdcdictionary',
],
entry_points={
'console_scripts': [
'gdc_postgres_admin=gdcdatamodel.gdc_postgres_admin:main'
]
},
)
chore(pins): Update dictionaryutils pins to get latest
- Update dictionaryutils pins to get version with data release
changes
|
from setuptools import setup, find_packages
setup(
name='gdcdatamodel',
packages=find_packages(),
install_requires=[
'pytz==2016.4',
'graphviz==0.4.2',
'jsonschema==2.5.1',
'python-dateutil==2.4.2',
'psqlgraph',
'gdcdictionary',
'dictionaryutils>=2.0.4,<3.0.0',
'cdisutils',
],
package_data={
"gdcdatamodel": [
"xml_mappings/*.yaml",
]
},
dependency_links=[
'git+https://github.com/NCI-GDC/cdisutils.git@863ce13772116b51bcf5ce7e556f5df3cb9e6f63#egg=cdisutils',
'git+https://github.com/NCI-GDC/psqlgraph.git@1.2.0#egg=psqlgraph',
'git+https://github.com/NCI-GDC/gdcdictionary.git@1.15.0#egg=gdcdictionary',
],
entry_points={
'console_scripts': [
'gdc_postgres_admin=gdcdatamodel.gdc_postgres_admin:main'
]
},
)
|
<commit_before>from setuptools import setup, find_packages
setup(
name='gdcdatamodel',
packages=find_packages(),
install_requires=[
'pytz==2016.4',
'graphviz==0.4.2',
'jsonschema==2.5.1',
'python-dateutil==2.4.2',
'psqlgraph',
'gdcdictionary',
'dictionaryutils>=2.0.0,<3.0.0',
'cdisutils',
],
package_data={
"gdcdatamodel": [
"xml_mappings/*.yaml",
]
},
dependency_links=[
'git+https://github.com/NCI-GDC/cdisutils.git@863ce13772116b51bcf5ce7e556f5df3cb9e6f63#egg=cdisutils',
'git+https://github.com/NCI-GDC/psqlgraph.git@1.2.0#egg=psqlgraph',
'git+https://github.com/NCI-GDC/gdcdictionary.git@1.15.0#egg=gdcdictionary',
],
entry_points={
'console_scripts': [
'gdc_postgres_admin=gdcdatamodel.gdc_postgres_admin:main'
]
},
)
<commit_msg>chore(pins): Update dictionaryutils pins to get latest
- Update dictionaryutils pins to get version with data release
changes<commit_after>
|
from setuptools import setup, find_packages
setup(
name='gdcdatamodel',
packages=find_packages(),
install_requires=[
'pytz==2016.4',
'graphviz==0.4.2',
'jsonschema==2.5.1',
'python-dateutil==2.4.2',
'psqlgraph',
'gdcdictionary',
'dictionaryutils>=2.0.4,<3.0.0',
'cdisutils',
],
package_data={
"gdcdatamodel": [
"xml_mappings/*.yaml",
]
},
dependency_links=[
'git+https://github.com/NCI-GDC/cdisutils.git@863ce13772116b51bcf5ce7e556f5df3cb9e6f63#egg=cdisutils',
'git+https://github.com/NCI-GDC/psqlgraph.git@1.2.0#egg=psqlgraph',
'git+https://github.com/NCI-GDC/gdcdictionary.git@1.15.0#egg=gdcdictionary',
],
entry_points={
'console_scripts': [
'gdc_postgres_admin=gdcdatamodel.gdc_postgres_admin:main'
]
},
)
|
from setuptools import setup, find_packages
setup(
name='gdcdatamodel',
packages=find_packages(),
install_requires=[
'pytz==2016.4',
'graphviz==0.4.2',
'jsonschema==2.5.1',
'python-dateutil==2.4.2',
'psqlgraph',
'gdcdictionary',
'dictionaryutils>=2.0.0,<3.0.0',
'cdisutils',
],
package_data={
"gdcdatamodel": [
"xml_mappings/*.yaml",
]
},
dependency_links=[
'git+https://github.com/NCI-GDC/cdisutils.git@863ce13772116b51bcf5ce7e556f5df3cb9e6f63#egg=cdisutils',
'git+https://github.com/NCI-GDC/psqlgraph.git@1.2.0#egg=psqlgraph',
'git+https://github.com/NCI-GDC/gdcdictionary.git@1.15.0#egg=gdcdictionary',
],
entry_points={
'console_scripts': [
'gdc_postgres_admin=gdcdatamodel.gdc_postgres_admin:main'
]
},
)
chore(pins): Update dictionaryutils pins to get latest
- Update dictionaryutils pins to get version with data release
changesfrom setuptools import setup, find_packages
setup(
name='gdcdatamodel',
packages=find_packages(),
install_requires=[
'pytz==2016.4',
'graphviz==0.4.2',
'jsonschema==2.5.1',
'python-dateutil==2.4.2',
'psqlgraph',
'gdcdictionary',
'dictionaryutils>=2.0.4,<3.0.0',
'cdisutils',
],
package_data={
"gdcdatamodel": [
"xml_mappings/*.yaml",
]
},
dependency_links=[
'git+https://github.com/NCI-GDC/cdisutils.git@863ce13772116b51bcf5ce7e556f5df3cb9e6f63#egg=cdisutils',
'git+https://github.com/NCI-GDC/psqlgraph.git@1.2.0#egg=psqlgraph',
'git+https://github.com/NCI-GDC/gdcdictionary.git@1.15.0#egg=gdcdictionary',
],
entry_points={
'console_scripts': [
'gdc_postgres_admin=gdcdatamodel.gdc_postgres_admin:main'
]
},
)
|
<commit_before>from setuptools import setup, find_packages
setup(
name='gdcdatamodel',
packages=find_packages(),
install_requires=[
'pytz==2016.4',
'graphviz==0.4.2',
'jsonschema==2.5.1',
'python-dateutil==2.4.2',
'psqlgraph',
'gdcdictionary',
'dictionaryutils>=2.0.0,<3.0.0',
'cdisutils',
],
package_data={
"gdcdatamodel": [
"xml_mappings/*.yaml",
]
},
dependency_links=[
'git+https://github.com/NCI-GDC/cdisutils.git@863ce13772116b51bcf5ce7e556f5df3cb9e6f63#egg=cdisutils',
'git+https://github.com/NCI-GDC/psqlgraph.git@1.2.0#egg=psqlgraph',
'git+https://github.com/NCI-GDC/gdcdictionary.git@1.15.0#egg=gdcdictionary',
],
entry_points={
'console_scripts': [
'gdc_postgres_admin=gdcdatamodel.gdc_postgres_admin:main'
]
},
)
<commit_msg>chore(pins): Update dictionaryutils pins to get latest
- Update dictionaryutils pins to get version with data release
changes<commit_after>from setuptools import setup, find_packages
setup(
name='gdcdatamodel',
packages=find_packages(),
install_requires=[
'pytz==2016.4',
'graphviz==0.4.2',
'jsonschema==2.5.1',
'python-dateutil==2.4.2',
'psqlgraph',
'gdcdictionary',
'dictionaryutils>=2.0.4,<3.0.0',
'cdisutils',
],
package_data={
"gdcdatamodel": [
"xml_mappings/*.yaml",
]
},
dependency_links=[
'git+https://github.com/NCI-GDC/cdisutils.git@863ce13772116b51bcf5ce7e556f5df3cb9e6f63#egg=cdisutils',
'git+https://github.com/NCI-GDC/psqlgraph.git@1.2.0#egg=psqlgraph',
'git+https://github.com/NCI-GDC/gdcdictionary.git@1.15.0#egg=gdcdictionary',
],
entry_points={
'console_scripts': [
'gdc_postgres_admin=gdcdatamodel.gdc_postgres_admin:main'
]
},
)
|
5709acf3c2effcdeef10323bbc956860c15f7ece
|
tasks.py
|
tasks.py
|
from arctasks import lint # noqa
from arctasks.release import * # noqa
|
from arctasks import lint # noqa
from arctasks.python import show_upgraded_packages # noqa
from arctasks.release import * # noqa
|
Include show_upgraded_packages task from ARCTasks
|
Include show_upgraded_packages task from ARCTasks
|
Python
|
mit
|
wylee/django-arcutils,PSU-OIT-ARC/django-arcutils,wylee/django-arcutils,PSU-OIT-ARC/django-arcutils
|
from arctasks import lint # noqa
from arctasks.release import * # noqa
Include show_upgraded_packages task from ARCTasks
|
from arctasks import lint # noqa
from arctasks.python import show_upgraded_packages # noqa
from arctasks.release import * # noqa
|
<commit_before>from arctasks import lint # noqa
from arctasks.release import * # noqa
<commit_msg>Include show_upgraded_packages task from ARCTasks<commit_after>
|
from arctasks import lint # noqa
from arctasks.python import show_upgraded_packages # noqa
from arctasks.release import * # noqa
|
from arctasks import lint # noqa
from arctasks.release import * # noqa
Include show_upgraded_packages task from ARCTasksfrom arctasks import lint # noqa
from arctasks.python import show_upgraded_packages # noqa
from arctasks.release import * # noqa
|
<commit_before>from arctasks import lint # noqa
from arctasks.release import * # noqa
<commit_msg>Include show_upgraded_packages task from ARCTasks<commit_after>from arctasks import lint # noqa
from arctasks.python import show_upgraded_packages # noqa
from arctasks.release import * # noqa
|
0c20b2194cd608551b1792f036de347bf7a36ddf
|
packages/QtInventor/__init__.py
|
packages/QtInventor/__init__.py
|
"""
Helper classes for creating 3D applications with PySide.
PySide is a binding to the Qt cross-platform application framework. This
package contains helper classes that integrate Open Inventor / Coin3D
into PySide based applications, namely:
- QIVWidget: Viewport widget for rendering and interacting with scene
graphs.
- QInspectorWidget: Scene graph inspector showing the scene structure in
a tree view and the fields of a node in a table view.
"""
from .QIVWidget import *
from .QInspectorWidget import *
from .QSceneGraphEditorWindow import *
from .QSceneGraphEditor import *
|
"""
Helper classes for creating 3D applications with PySide.
PySide is a binding to the Qt cross-platform application framework. This
package contains helper classes that integrate Open Inventor / Coin3D
into PySide based applications, namely:
- QIVWidget: Viewport widget for rendering and interacting with scene
graphs.
- QInspectorWidget: Scene graph inspector showing the scene structure in
a tree view and the fields of a node in a table view.
"""
from .QIVWidget import *
from .QInspectorWidget import *
from .QSceneGraphEditorWindow import *
from .QSceneGraphEditor import *
# load inventor extensions specified in IV_LIBS environment variable
import os
if os.environ.get('IV_LIBS') is not None:
import ctypes
import inventor
for lib in os.environ.get('IV_LIBS').split(";"):
ctypes.cdll.LoadLibrary(lib).initAllClasses()
inventor.create_classes()
|
Load extensions given in IV_LIBS variable.
|
Load extensions given in IV_LIBS variable.
|
Python
|
bsd-3-clause
|
TheHubbit/PyInventor,TheHubbit/PyInventor
|
"""
Helper classes for creating 3D applications with PySide.
PySide is a binding to the Qt cross-platform application framework. This
package contains helper classes that integrate Open Inventor / Coin3D
into PySide based applications, namely:
- QIVWidget: Viewport widget for rendering and interacting with scene
graphs.
- QInspectorWidget: Scene graph inspector showing the scene structure in
a tree view and the fields of a node in a table view.
"""
from .QIVWidget import *
from .QInspectorWidget import *
from .QSceneGraphEditorWindow import *
from .QSceneGraphEditor import *
Load extensions given in IV_LIBS variable.
|
"""
Helper classes for creating 3D applications with PySide.
PySide is a binding to the Qt cross-platform application framework. This
package contains helper classes that integrate Open Inventor / Coin3D
into PySide based applications, namely:
- QIVWidget: Viewport widget for rendering and interacting with scene
graphs.
- QInspectorWidget: Scene graph inspector showing the scene structure in
a tree view and the fields of a node in a table view.
"""
from .QIVWidget import *
from .QInspectorWidget import *
from .QSceneGraphEditorWindow import *
from .QSceneGraphEditor import *
# load inventor extensions specified in IV_LIBS environment variable
import os
if os.environ.get('IV_LIBS') is not None:
import ctypes
import inventor
for lib in os.environ.get('IV_LIBS').split(";"):
ctypes.cdll.LoadLibrary(lib).initAllClasses()
inventor.create_classes()
|
<commit_before>"""
Helper classes for creating 3D applications with PySide.
PySide is a binding to the Qt cross-platform application framework. This
package contains helper classes that integrate Open Inventor / Coin3D
into PySide based applications, namely:
- QIVWidget: Viewport widget for rendering and interacting with scene
graphs.
- QInspectorWidget: Scene graph inspector showing the scene structure in
a tree view and the fields of a node in a table view.
"""
from .QIVWidget import *
from .QInspectorWidget import *
from .QSceneGraphEditorWindow import *
from .QSceneGraphEditor import *
<commit_msg>Load extensions given in IV_LIBS variable.<commit_after>
|
"""
Helper classes for creating 3D applications with PySide.
PySide is a binding to the Qt cross-platform application framework. This
package contains helper classes that integrate Open Inventor / Coin3D
into PySide based applications, namely:
- QIVWidget: Viewport widget for rendering and interacting with scene
graphs.
- QInspectorWidget: Scene graph inspector showing the scene structure in
a tree view and the fields of a node in a table view.
"""
from .QIVWidget import *
from .QInspectorWidget import *
from .QSceneGraphEditorWindow import *
from .QSceneGraphEditor import *
# load inventor extensions specified in IV_LIBS environment variable
import os
if os.environ.get('IV_LIBS') is not None:
import ctypes
import inventor
for lib in os.environ.get('IV_LIBS').split(";"):
ctypes.cdll.LoadLibrary(lib).initAllClasses()
inventor.create_classes()
|
"""
Helper classes for creating 3D applications with PySide.
PySide is a binding to the Qt cross-platform application framework. This
package contains helper classes that integrate Open Inventor / Coin3D
into PySide based applications, namely:
- QIVWidget: Viewport widget for rendering and interacting with scene
graphs.
- QInspectorWidget: Scene graph inspector showing the scene structure in
a tree view and the fields of a node in a table view.
"""
from .QIVWidget import *
from .QInspectorWidget import *
from .QSceneGraphEditorWindow import *
from .QSceneGraphEditor import *
Load extensions given in IV_LIBS variable."""
Helper classes for creating 3D applications with PySide.
PySide is a binding to the Qt cross-platform application framework. This
package contains helper classes that integrate Open Inventor / Coin3D
into PySide based applications, namely:
- QIVWidget: Viewport widget for rendering and interacting with scene
graphs.
- QInspectorWidget: Scene graph inspector showing the scene structure in
a tree view and the fields of a node in a table view.
"""
from .QIVWidget import *
from .QInspectorWidget import *
from .QSceneGraphEditorWindow import *
from .QSceneGraphEditor import *
# load inventor extensions specified in IV_LIBS environment variable
import os
if os.environ.get('IV_LIBS') is not None:
import ctypes
import inventor
for lib in os.environ.get('IV_LIBS').split(";"):
ctypes.cdll.LoadLibrary(lib).initAllClasses()
inventor.create_classes()
|
<commit_before>"""
Helper classes for creating 3D applications with PySide.
PySide is a binding to the Qt cross-platform application framework. This
package contains helper classes that integrate Open Inventor / Coin3D
into PySide based applications, namely:
- QIVWidget: Viewport widget for rendering and interacting with scene
graphs.
- QInspectorWidget: Scene graph inspector showing the scene structure in
a tree view and the fields of a node in a table view.
"""
from .QIVWidget import *
from .QInspectorWidget import *
from .QSceneGraphEditorWindow import *
from .QSceneGraphEditor import *
<commit_msg>Load extensions given in IV_LIBS variable.<commit_after>"""
Helper classes for creating 3D applications with PySide.
PySide is a binding to the Qt cross-platform application framework. This
package contains helper classes that integrate Open Inventor / Coin3D
into PySide based applications, namely:
- QIVWidget: Viewport widget for rendering and interacting with scene
graphs.
- QInspectorWidget: Scene graph inspector showing the scene structure in
a tree view and the fields of a node in a table view.
"""
from .QIVWidget import *
from .QInspectorWidget import *
from .QSceneGraphEditorWindow import *
from .QSceneGraphEditor import *
# load inventor extensions specified in IV_LIBS environment variable
import os
if os.environ.get('IV_LIBS') is not None:
import ctypes
import inventor
for lib in os.environ.get('IV_LIBS').split(";"):
ctypes.cdll.LoadLibrary(lib).initAllClasses()
inventor.create_classes()
|
93228db226ce9082d5d3bf0e0b7de64ee8b07ca5
|
utils.py
|
utils.py
|
import os
import sys
import hashlib
def e(s):
if type(s) == str:
return str
return s.encode('utf-8')
def d(s):
if type(s) == unicode:
return s
return unicode(s, 'utf-8')
def mkid(s):
return hashlib.sha1(e(s)).hexdigest()[:2*4]
def running_in_tools_labs():
return os.path.exists('/etc/wmflabs-project')
class Logger(object):
def __init__(self):
self._mode = 'INFO'
def progress(self, message):
message = e(message)
if not sys.stderr.isatty():
return
if self._mode == 'PROGRESS':
print >>sys.stderr, '\r',
print >>sys.stderr, message,
self._mode = 'PROGRESS'
def info(self, message):
message = e(message)
if self._mode == 'PROGRESS':
print >>sys.stderr
print >>sys.stderr, message
self._mode = 'INFO'
|
import os
import sys
import hashlib
def e(s):
if type(s) == str:
return s
return s.encode('utf-8')
def d(s):
if type(s) == unicode:
return s
return unicode(s, 'utf-8')
def mkid(s):
return hashlib.sha1(e(s)).hexdigest()[:2*4]
def running_in_tools_labs():
return os.path.exists('/etc/wmflabs-project')
class Logger(object):
def __init__(self):
self._mode = 'INFO'
def progress(self, message):
message = e(message)
if not sys.stderr.isatty():
return
if self._mode == 'PROGRESS':
print >>sys.stderr, '\r',
print >>sys.stderr, message,
self._mode = 'PROGRESS'
def info(self, message):
message = e(message)
if self._mode == 'PROGRESS':
print >>sys.stderr
print >>sys.stderr, message
self._mode = 'INFO'
|
Fix string encoding when the argument is already a str().
|
Fix string encoding when the argument is already a str().
Former-commit-id: 812fd79675590659b3dc4251ed998f84c4bf2395
|
Python
|
mit
|
eggpi/citationhunt,eggpi/citationhunt,guilherme-pg/citationhunt,eggpi/citationhunt,guilherme-pg/citationhunt,guilherme-pg/citationhunt,guilherme-pg/citationhunt,eggpi/citationhunt
|
import os
import sys
import hashlib
def e(s):
if type(s) == str:
return str
return s.encode('utf-8')
def d(s):
if type(s) == unicode:
return s
return unicode(s, 'utf-8')
def mkid(s):
return hashlib.sha1(e(s)).hexdigest()[:2*4]
def running_in_tools_labs():
return os.path.exists('/etc/wmflabs-project')
class Logger(object):
def __init__(self):
self._mode = 'INFO'
def progress(self, message):
message = e(message)
if not sys.stderr.isatty():
return
if self._mode == 'PROGRESS':
print >>sys.stderr, '\r',
print >>sys.stderr, message,
self._mode = 'PROGRESS'
def info(self, message):
message = e(message)
if self._mode == 'PROGRESS':
print >>sys.stderr
print >>sys.stderr, message
self._mode = 'INFO'
Fix string encoding when the argument is already a str().
Former-commit-id: 812fd79675590659b3dc4251ed998f84c4bf2395
|
import os
import sys
import hashlib
def e(s):
if type(s) == str:
return s
return s.encode('utf-8')
def d(s):
if type(s) == unicode:
return s
return unicode(s, 'utf-8')
def mkid(s):
return hashlib.sha1(e(s)).hexdigest()[:2*4]
def running_in_tools_labs():
return os.path.exists('/etc/wmflabs-project')
class Logger(object):
def __init__(self):
self._mode = 'INFO'
def progress(self, message):
message = e(message)
if not sys.stderr.isatty():
return
if self._mode == 'PROGRESS':
print >>sys.stderr, '\r',
print >>sys.stderr, message,
self._mode = 'PROGRESS'
def info(self, message):
message = e(message)
if self._mode == 'PROGRESS':
print >>sys.stderr
print >>sys.stderr, message
self._mode = 'INFO'
|
<commit_before>import os
import sys
import hashlib
def e(s):
if type(s) == str:
return str
return s.encode('utf-8')
def d(s):
if type(s) == unicode:
return s
return unicode(s, 'utf-8')
def mkid(s):
return hashlib.sha1(e(s)).hexdigest()[:2*4]
def running_in_tools_labs():
return os.path.exists('/etc/wmflabs-project')
class Logger(object):
def __init__(self):
self._mode = 'INFO'
def progress(self, message):
message = e(message)
if not sys.stderr.isatty():
return
if self._mode == 'PROGRESS':
print >>sys.stderr, '\r',
print >>sys.stderr, message,
self._mode = 'PROGRESS'
def info(self, message):
message = e(message)
if self._mode == 'PROGRESS':
print >>sys.stderr
print >>sys.stderr, message
self._mode = 'INFO'
<commit_msg>Fix string encoding when the argument is already a str().
Former-commit-id: 812fd79675590659b3dc4251ed998f84c4bf2395<commit_after>
|
import os
import sys
import hashlib
def e(s):
if type(s) == str:
return s
return s.encode('utf-8')
def d(s):
if type(s) == unicode:
return s
return unicode(s, 'utf-8')
def mkid(s):
return hashlib.sha1(e(s)).hexdigest()[:2*4]
def running_in_tools_labs():
return os.path.exists('/etc/wmflabs-project')
class Logger(object):
def __init__(self):
self._mode = 'INFO'
def progress(self, message):
message = e(message)
if not sys.stderr.isatty():
return
if self._mode == 'PROGRESS':
print >>sys.stderr, '\r',
print >>sys.stderr, message,
self._mode = 'PROGRESS'
def info(self, message):
message = e(message)
if self._mode == 'PROGRESS':
print >>sys.stderr
print >>sys.stderr, message
self._mode = 'INFO'
|
import os
import sys
import hashlib
def e(s):
if type(s) == str:
return str
return s.encode('utf-8')
def d(s):
if type(s) == unicode:
return s
return unicode(s, 'utf-8')
def mkid(s):
return hashlib.sha1(e(s)).hexdigest()[:2*4]
def running_in_tools_labs():
return os.path.exists('/etc/wmflabs-project')
class Logger(object):
def __init__(self):
self._mode = 'INFO'
def progress(self, message):
message = e(message)
if not sys.stderr.isatty():
return
if self._mode == 'PROGRESS':
print >>sys.stderr, '\r',
print >>sys.stderr, message,
self._mode = 'PROGRESS'
def info(self, message):
message = e(message)
if self._mode == 'PROGRESS':
print >>sys.stderr
print >>sys.stderr, message
self._mode = 'INFO'
Fix string encoding when the argument is already a str().
Former-commit-id: 812fd79675590659b3dc4251ed998f84c4bf2395import os
import sys
import hashlib
def e(s):
if type(s) == str:
return s
return s.encode('utf-8')
def d(s):
if type(s) == unicode:
return s
return unicode(s, 'utf-8')
def mkid(s):
return hashlib.sha1(e(s)).hexdigest()[:2*4]
def running_in_tools_labs():
return os.path.exists('/etc/wmflabs-project')
class Logger(object):
def __init__(self):
self._mode = 'INFO'
def progress(self, message):
message = e(message)
if not sys.stderr.isatty():
return
if self._mode == 'PROGRESS':
print >>sys.stderr, '\r',
print >>sys.stderr, message,
self._mode = 'PROGRESS'
def info(self, message):
message = e(message)
if self._mode == 'PROGRESS':
print >>sys.stderr
print >>sys.stderr, message
self._mode = 'INFO'
|
<commit_before>import os
import sys
import hashlib
def e(s):
if type(s) == str:
return str
return s.encode('utf-8')
def d(s):
if type(s) == unicode:
return s
return unicode(s, 'utf-8')
def mkid(s):
return hashlib.sha1(e(s)).hexdigest()[:2*4]
def running_in_tools_labs():
return os.path.exists('/etc/wmflabs-project')
class Logger(object):
def __init__(self):
self._mode = 'INFO'
def progress(self, message):
message = e(message)
if not sys.stderr.isatty():
return
if self._mode == 'PROGRESS':
print >>sys.stderr, '\r',
print >>sys.stderr, message,
self._mode = 'PROGRESS'
def info(self, message):
message = e(message)
if self._mode == 'PROGRESS':
print >>sys.stderr
print >>sys.stderr, message
self._mode = 'INFO'
<commit_msg>Fix string encoding when the argument is already a str().
Former-commit-id: 812fd79675590659b3dc4251ed998f84c4bf2395<commit_after>import os
import sys
import hashlib
def e(s):
if type(s) == str:
return s
return s.encode('utf-8')
def d(s):
if type(s) == unicode:
return s
return unicode(s, 'utf-8')
def mkid(s):
return hashlib.sha1(e(s)).hexdigest()[:2*4]
def running_in_tools_labs():
return os.path.exists('/etc/wmflabs-project')
class Logger(object):
def __init__(self):
self._mode = 'INFO'
def progress(self, message):
message = e(message)
if not sys.stderr.isatty():
return
if self._mode == 'PROGRESS':
print >>sys.stderr, '\r',
print >>sys.stderr, message,
self._mode = 'PROGRESS'
def info(self, message):
message = e(message)
if self._mode == 'PROGRESS':
print >>sys.stderr
print >>sys.stderr, message
self._mode = 'INFO'
|
e1b2b35e36566e92bf789c4d5ab7c668d520f492
|
taca/illumina/NextSeq_Runs.py
|
taca/illumina/NextSeq_Runs.py
|
import os
import re
import csv
import glob
import shutil
import gzip
import operator
import subprocess
from datetime import datetime
from taca.utils.filesystem import chdir, control_fastq_filename
from taca.illumina.Runs import Run
from taca.illumina.HiSeqX_Runs import HiSeqX_Run
from taca.utils import misc
from flowcell_parser.classes import RunParametersParser, SampleSheetParser, RunParser, LaneBarcodeParser, DemuxSummaryParser
import logging
logger = logging.getLogger(__name__)
class NextSeq_Run(HiSeqX_Run):
def __init__(self, run_dir, samplesheet_folders):
super(NextSeq_Run, self).__init__(run_dir, samplesheet_folders)
self._set_sequencer_type()
self._set_run_type()
def _set_sequencer_type(self):
self.sequencer_type = "NextSeq"
def _set_run_type(self):
self.run_type = "NGI-RUN"
|
import os
import re
import csv
import glob
import shutil
import gzip
import operator
import subprocess
from datetime import datetime
from taca.utils.filesystem import chdir, control_fastq_filename
from taca.illumina.Runs import Run
from taca.illumina.HiSeqX_Runs import HiSeqX_Run
from taca.utils import misc
import logging
logger = logging.getLogger(__name__)
class NextSeq_Run(HiSeqX_Run):
def __init__(self, run_dir, samplesheet_folders):
super(NextSeq_Run, self).__init__(run_dir, samplesheet_folders)
self._set_sequencer_type()
self._set_run_type()
def _set_sequencer_type(self):
self.sequencer_type = "NextSeq"
def _set_run_type(self):
self.run_type = "NGI-RUN"
|
Clear samplesheet parser from header
|
Clear samplesheet parser from header
|
Python
|
mit
|
SciLifeLab/TACA,SciLifeLab/TACA,SciLifeLab/TACA
|
import os
import re
import csv
import glob
import shutil
import gzip
import operator
import subprocess
from datetime import datetime
from taca.utils.filesystem import chdir, control_fastq_filename
from taca.illumina.Runs import Run
from taca.illumina.HiSeqX_Runs import HiSeqX_Run
from taca.utils import misc
from flowcell_parser.classes import RunParametersParser, SampleSheetParser, RunParser, LaneBarcodeParser, DemuxSummaryParser
import logging
logger = logging.getLogger(__name__)
class NextSeq_Run(HiSeqX_Run):
def __init__(self, run_dir, samplesheet_folders):
super(NextSeq_Run, self).__init__(run_dir, samplesheet_folders)
self._set_sequencer_type()
self._set_run_type()
def _set_sequencer_type(self):
self.sequencer_type = "NextSeq"
def _set_run_type(self):
self.run_type = "NGI-RUN"
Clear samplesheet parser from header
|
import os
import re
import csv
import glob
import shutil
import gzip
import operator
import subprocess
from datetime import datetime
from taca.utils.filesystem import chdir, control_fastq_filename
from taca.illumina.Runs import Run
from taca.illumina.HiSeqX_Runs import HiSeqX_Run
from taca.utils import misc
import logging
logger = logging.getLogger(__name__)
class NextSeq_Run(HiSeqX_Run):
def __init__(self, run_dir, samplesheet_folders):
super(NextSeq_Run, self).__init__(run_dir, samplesheet_folders)
self._set_sequencer_type()
self._set_run_type()
def _set_sequencer_type(self):
self.sequencer_type = "NextSeq"
def _set_run_type(self):
self.run_type = "NGI-RUN"
|
<commit_before>import os
import re
import csv
import glob
import shutil
import gzip
import operator
import subprocess
from datetime import datetime
from taca.utils.filesystem import chdir, control_fastq_filename
from taca.illumina.Runs import Run
from taca.illumina.HiSeqX_Runs import HiSeqX_Run
from taca.utils import misc
from flowcell_parser.classes import RunParametersParser, SampleSheetParser, RunParser, LaneBarcodeParser, DemuxSummaryParser
import logging
logger = logging.getLogger(__name__)
class NextSeq_Run(HiSeqX_Run):
def __init__(self, run_dir, samplesheet_folders):
super(NextSeq_Run, self).__init__(run_dir, samplesheet_folders)
self._set_sequencer_type()
self._set_run_type()
def _set_sequencer_type(self):
self.sequencer_type = "NextSeq"
def _set_run_type(self):
self.run_type = "NGI-RUN"
<commit_msg>Clear samplesheet parser from header<commit_after>
|
import os
import re
import csv
import glob
import shutil
import gzip
import operator
import subprocess
from datetime import datetime
from taca.utils.filesystem import chdir, control_fastq_filename
from taca.illumina.Runs import Run
from taca.illumina.HiSeqX_Runs import HiSeqX_Run
from taca.utils import misc
import logging
logger = logging.getLogger(__name__)
class NextSeq_Run(HiSeqX_Run):
def __init__(self, run_dir, samplesheet_folders):
super(NextSeq_Run, self).__init__(run_dir, samplesheet_folders)
self._set_sequencer_type()
self._set_run_type()
def _set_sequencer_type(self):
self.sequencer_type = "NextSeq"
def _set_run_type(self):
self.run_type = "NGI-RUN"
|
import os
import re
import csv
import glob
import shutil
import gzip
import operator
import subprocess
from datetime import datetime
from taca.utils.filesystem import chdir, control_fastq_filename
from taca.illumina.Runs import Run
from taca.illumina.HiSeqX_Runs import HiSeqX_Run
from taca.utils import misc
from flowcell_parser.classes import RunParametersParser, SampleSheetParser, RunParser, LaneBarcodeParser, DemuxSummaryParser
import logging
logger = logging.getLogger(__name__)
class NextSeq_Run(HiSeqX_Run):
def __init__(self, run_dir, samplesheet_folders):
super(NextSeq_Run, self).__init__(run_dir, samplesheet_folders)
self._set_sequencer_type()
self._set_run_type()
def _set_sequencer_type(self):
self.sequencer_type = "NextSeq"
def _set_run_type(self):
self.run_type = "NGI-RUN"
Clear samplesheet parser from headerimport os
import re
import csv
import glob
import shutil
import gzip
import operator
import subprocess
from datetime import datetime
from taca.utils.filesystem import chdir, control_fastq_filename
from taca.illumina.Runs import Run
from taca.illumina.HiSeqX_Runs import HiSeqX_Run
from taca.utils import misc
import logging
logger = logging.getLogger(__name__)
class NextSeq_Run(HiSeqX_Run):
def __init__(self, run_dir, samplesheet_folders):
super(NextSeq_Run, self).__init__(run_dir, samplesheet_folders)
self._set_sequencer_type()
self._set_run_type()
def _set_sequencer_type(self):
self.sequencer_type = "NextSeq"
def _set_run_type(self):
self.run_type = "NGI-RUN"
|
<commit_before>import os
import re
import csv
import glob
import shutil
import gzip
import operator
import subprocess
from datetime import datetime
from taca.utils.filesystem import chdir, control_fastq_filename
from taca.illumina.Runs import Run
from taca.illumina.HiSeqX_Runs import HiSeqX_Run
from taca.utils import misc
from flowcell_parser.classes import RunParametersParser, SampleSheetParser, RunParser, LaneBarcodeParser, DemuxSummaryParser
import logging
logger = logging.getLogger(__name__)
class NextSeq_Run(HiSeqX_Run):
def __init__(self, run_dir, samplesheet_folders):
super(NextSeq_Run, self).__init__(run_dir, samplesheet_folders)
self._set_sequencer_type()
self._set_run_type()
def _set_sequencer_type(self):
self.sequencer_type = "NextSeq"
def _set_run_type(self):
self.run_type = "NGI-RUN"
<commit_msg>Clear samplesheet parser from header<commit_after>import os
import re
import csv
import glob
import shutil
import gzip
import operator
import subprocess
from datetime import datetime
from taca.utils.filesystem import chdir, control_fastq_filename
from taca.illumina.Runs import Run
from taca.illumina.HiSeqX_Runs import HiSeqX_Run
from taca.utils import misc
import logging
logger = logging.getLogger(__name__)
class NextSeq_Run(HiSeqX_Run):
def __init__(self, run_dir, samplesheet_folders):
super(NextSeq_Run, self).__init__(run_dir, samplesheet_folders)
self._set_sequencer_type()
self._set_run_type()
def _set_sequencer_type(self):
self.sequencer_type = "NextSeq"
def _set_run_type(self):
self.run_type = "NGI-RUN"
|
e17fab647a7840bbe56f5c37fbe32c73557d98b2
|
workers/subscriptions.py
|
workers/subscriptions.py
|
import os
import telegram
from leonard import Leonard
if __name__ == '__main__':
os.chdir('../')
telegram_client = telegram.Bot(os.environ['BOT_TOKEN'])
bot = Leonard(telegram_client)
i = 0
while True:
if i % 10 == 0:
bot.collect_plugins()
for name, check, send in bot.subscriptions:
send(bot, check(bot))
i += 1
|
import os
import time
import telegram
from leonard import Leonard
if __name__ == '__main__':
os.chdir('../')
telegram_client = telegram.Bot(os.environ['BOT_TOKEN'])
bot = Leonard(telegram_client)
bot.collect_plugins()
while True:
for name, check, send in bot.subscriptions:
send(bot, check(bot))
time.sleep(60)
|
Remove collecting plugins every second
|
Remove collecting plugins every second
|
Python
|
mit
|
sevazhidkov/leonard
|
import os
import telegram
from leonard import Leonard
if __name__ == '__main__':
os.chdir('../')
telegram_client = telegram.Bot(os.environ['BOT_TOKEN'])
bot = Leonard(telegram_client)
i = 0
while True:
if i % 10 == 0:
bot.collect_plugins()
for name, check, send in bot.subscriptions:
send(bot, check(bot))
i += 1
Remove collecting plugins every second
|
import os
import time
import telegram
from leonard import Leonard
if __name__ == '__main__':
os.chdir('../')
telegram_client = telegram.Bot(os.environ['BOT_TOKEN'])
bot = Leonard(telegram_client)
bot.collect_plugins()
while True:
for name, check, send in bot.subscriptions:
send(bot, check(bot))
time.sleep(60)
|
<commit_before>import os
import telegram
from leonard import Leonard
if __name__ == '__main__':
os.chdir('../')
telegram_client = telegram.Bot(os.environ['BOT_TOKEN'])
bot = Leonard(telegram_client)
i = 0
while True:
if i % 10 == 0:
bot.collect_plugins()
for name, check, send in bot.subscriptions:
send(bot, check(bot))
i += 1
<commit_msg>Remove collecting plugins every second<commit_after>
|
import os
import time
import telegram
from leonard import Leonard
if __name__ == '__main__':
os.chdir('../')
telegram_client = telegram.Bot(os.environ['BOT_TOKEN'])
bot = Leonard(telegram_client)
bot.collect_plugins()
while True:
for name, check, send in bot.subscriptions:
send(bot, check(bot))
time.sleep(60)
|
import os
import telegram
from leonard import Leonard
if __name__ == '__main__':
os.chdir('../')
telegram_client = telegram.Bot(os.environ['BOT_TOKEN'])
bot = Leonard(telegram_client)
i = 0
while True:
if i % 10 == 0:
bot.collect_plugins()
for name, check, send in bot.subscriptions:
send(bot, check(bot))
i += 1
Remove collecting plugins every secondimport os
import time
import telegram
from leonard import Leonard
if __name__ == '__main__':
os.chdir('../')
telegram_client = telegram.Bot(os.environ['BOT_TOKEN'])
bot = Leonard(telegram_client)
bot.collect_plugins()
while True:
for name, check, send in bot.subscriptions:
send(bot, check(bot))
time.sleep(60)
|
<commit_before>import os
import telegram
from leonard import Leonard
if __name__ == '__main__':
os.chdir('../')
telegram_client = telegram.Bot(os.environ['BOT_TOKEN'])
bot = Leonard(telegram_client)
i = 0
while True:
if i % 10 == 0:
bot.collect_plugins()
for name, check, send in bot.subscriptions:
send(bot, check(bot))
i += 1
<commit_msg>Remove collecting plugins every second<commit_after>import os
import time
import telegram
from leonard import Leonard
if __name__ == '__main__':
os.chdir('../')
telegram_client = telegram.Bot(os.environ['BOT_TOKEN'])
bot = Leonard(telegram_client)
bot.collect_plugins()
while True:
for name, check, send in bot.subscriptions:
send(bot, check(bot))
time.sleep(60)
|
657f88cb6e65731ca1d39067094cbe0f5d18e2fc
|
sample-functions/SentimentAnalysis/handler.py
|
sample-functions/SentimentAnalysis/handler.py
|
import sys
import json
from textblob import TextBlob
# set default encoding to UTF-8 to eliminate decoding errors
reload(sys)
sys.setdefaultencoding('utf8')
def get_stdin():
buf = ""
for line in sys.stdin:
buf = buf + line
return buf
if(__name__ == "__main__"):
st = get_stdin()
blob = TextBlob(st)
res = {
"polarity": 0,
"subjectivity": 0
}
for sentence in blob.sentences:
res["subjectivity"] = res["subjectivity"] + sentence.sentiment.subjectivity
res["polarity"] = res["polarity"] + sentence.sentiment.polarity
total = len(blob.sentences)
res["sentence_count"] = total
res["polarity"] = res["polarity"] / total
res["subjectivity"] = res["subjectivity"] / total
print(json.dumps(res))
|
import sys
import json
from textblob import TextBlob
# Set encoding to UTF-8 (vs ASCII to eliminate potential errors).
reload(sys)
sys.setdefaultencoding('utf8')
def get_stdin():
buf = ""
for line in sys.stdin:
buf = buf + line
return buf
if(__name__ == "__main__"):
st = get_stdin()
blob = TextBlob(st)
res = {
"polarity": 0,
"subjectivity": 0
}
for sentence in blob.sentences:
res["subjectivity"] = res["subjectivity"] + sentence.sentiment.subjectivity
res["polarity"] = res["polarity"] + sentence.sentiment.polarity
total = len(blob.sentences)
res["sentence_count"] = total
res["polarity"] = res["polarity"] / total
res["subjectivity"] = res["subjectivity"] / total
print(json.dumps(res))
|
Correct identation error in sample.
|
Correct identation error in sample.
|
Python
|
mit
|
openfaas/faas,rgee0/faas,alexellis/faas,rgee0/faas,alexellis/faas,alexellis/faas,haru01/faas,openfaas/faas,haru01/faas,rgee0/faas,alexellis/faas,haru01/faas,rgee0/faas,rgee0/faas,haru01/faas,haru01/faas,alexellis/faas,rgee0/faas,rgee0/faas,rgee0/faas,openfaas/faas,alexellis/faas,alexellis/faas,haru01/faas,rgee0/faas,haru01/faas,rgee0/faas,alexellis/faas,haru01/faas,alexellis/faas,haru01/faas
|
import sys
import json
from textblob import TextBlob
# set default encoding to UTF-8 to eliminate decoding errors
reload(sys)
sys.setdefaultencoding('utf8')
def get_stdin():
buf = ""
for line in sys.stdin:
buf = buf + line
return buf
if(__name__ == "__main__"):
st = get_stdin()
blob = TextBlob(st)
res = {
"polarity": 0,
"subjectivity": 0
}
for sentence in blob.sentences:
res["subjectivity"] = res["subjectivity"] + sentence.sentiment.subjectivity
res["polarity"] = res["polarity"] + sentence.sentiment.polarity
total = len(blob.sentences)
res["sentence_count"] = total
res["polarity"] = res["polarity"] / total
res["subjectivity"] = res["subjectivity"] / total
print(json.dumps(res))
Correct identation error in sample.
|
import sys
import json
from textblob import TextBlob
# Set encoding to UTF-8 (vs ASCII to eliminate potential errors).
reload(sys)
sys.setdefaultencoding('utf8')
def get_stdin():
buf = ""
for line in sys.stdin:
buf = buf + line
return buf
if(__name__ == "__main__"):
st = get_stdin()
blob = TextBlob(st)
res = {
"polarity": 0,
"subjectivity": 0
}
for sentence in blob.sentences:
res["subjectivity"] = res["subjectivity"] + sentence.sentiment.subjectivity
res["polarity"] = res["polarity"] + sentence.sentiment.polarity
total = len(blob.sentences)
res["sentence_count"] = total
res["polarity"] = res["polarity"] / total
res["subjectivity"] = res["subjectivity"] / total
print(json.dumps(res))
|
<commit_before>import sys
import json
from textblob import TextBlob
# set default encoding to UTF-8 to eliminate decoding errors
reload(sys)
sys.setdefaultencoding('utf8')
def get_stdin():
buf = ""
for line in sys.stdin:
buf = buf + line
return buf
if(__name__ == "__main__"):
st = get_stdin()
blob = TextBlob(st)
res = {
"polarity": 0,
"subjectivity": 0
}
for sentence in blob.sentences:
res["subjectivity"] = res["subjectivity"] + sentence.sentiment.subjectivity
res["polarity"] = res["polarity"] + sentence.sentiment.polarity
total = len(blob.sentences)
res["sentence_count"] = total
res["polarity"] = res["polarity"] / total
res["subjectivity"] = res["subjectivity"] / total
print(json.dumps(res))
<commit_msg>Correct identation error in sample.<commit_after>
|
import sys
import json
from textblob import TextBlob
# Set encoding to UTF-8 (vs ASCII to eliminate potential errors).
reload(sys)
sys.setdefaultencoding('utf8')
def get_stdin():
buf = ""
for line in sys.stdin:
buf = buf + line
return buf
if(__name__ == "__main__"):
st = get_stdin()
blob = TextBlob(st)
res = {
"polarity": 0,
"subjectivity": 0
}
for sentence in blob.sentences:
res["subjectivity"] = res["subjectivity"] + sentence.sentiment.subjectivity
res["polarity"] = res["polarity"] + sentence.sentiment.polarity
total = len(blob.sentences)
res["sentence_count"] = total
res["polarity"] = res["polarity"] / total
res["subjectivity"] = res["subjectivity"] / total
print(json.dumps(res))
|
import sys
import json
from textblob import TextBlob
# set default encoding to UTF-8 to eliminate decoding errors
reload(sys)
sys.setdefaultencoding('utf8')
def get_stdin():
buf = ""
for line in sys.stdin:
buf = buf + line
return buf
if(__name__ == "__main__"):
st = get_stdin()
blob = TextBlob(st)
res = {
"polarity": 0,
"subjectivity": 0
}
for sentence in blob.sentences:
res["subjectivity"] = res["subjectivity"] + sentence.sentiment.subjectivity
res["polarity"] = res["polarity"] + sentence.sentiment.polarity
total = len(blob.sentences)
res["sentence_count"] = total
res["polarity"] = res["polarity"] / total
res["subjectivity"] = res["subjectivity"] / total
print(json.dumps(res))
Correct identation error in sample.import sys
import json
from textblob import TextBlob
# Set encoding to UTF-8 (vs ASCII to eliminate potential errors).
reload(sys)
sys.setdefaultencoding('utf8')
def get_stdin():
buf = ""
for line in sys.stdin:
buf = buf + line
return buf
if(__name__ == "__main__"):
st = get_stdin()
blob = TextBlob(st)
res = {
"polarity": 0,
"subjectivity": 0
}
for sentence in blob.sentences:
res["subjectivity"] = res["subjectivity"] + sentence.sentiment.subjectivity
res["polarity"] = res["polarity"] + sentence.sentiment.polarity
total = len(blob.sentences)
res["sentence_count"] = total
res["polarity"] = res["polarity"] / total
res["subjectivity"] = res["subjectivity"] / total
print(json.dumps(res))
|
<commit_before>import sys
import json
from textblob import TextBlob
# set default encoding to UTF-8 to eliminate decoding errors
reload(sys)
sys.setdefaultencoding('utf8')
def get_stdin():
buf = ""
for line in sys.stdin:
buf = buf + line
return buf
if(__name__ == "__main__"):
st = get_stdin()
blob = TextBlob(st)
res = {
"polarity": 0,
"subjectivity": 0
}
for sentence in blob.sentences:
res["subjectivity"] = res["subjectivity"] + sentence.sentiment.subjectivity
res["polarity"] = res["polarity"] + sentence.sentiment.polarity
total = len(blob.sentences)
res["sentence_count"] = total
res["polarity"] = res["polarity"] / total
res["subjectivity"] = res["subjectivity"] / total
print(json.dumps(res))
<commit_msg>Correct identation error in sample.<commit_after>import sys
import json
from textblob import TextBlob
# Set encoding to UTF-8 (vs ASCII to eliminate potential errors).
reload(sys)
sys.setdefaultencoding('utf8')
def get_stdin():
buf = ""
for line in sys.stdin:
buf = buf + line
return buf
if(__name__ == "__main__"):
st = get_stdin()
blob = TextBlob(st)
res = {
"polarity": 0,
"subjectivity": 0
}
for sentence in blob.sentences:
res["subjectivity"] = res["subjectivity"] + sentence.sentiment.subjectivity
res["polarity"] = res["polarity"] + sentence.sentiment.polarity
total = len(blob.sentences)
res["sentence_count"] = total
res["polarity"] = res["polarity"] / total
res["subjectivity"] = res["subjectivity"] / total
print(json.dumps(res))
|
b60f9f22703d97cfaeaa69e36fe283d1ef5d2f5d
|
download_data.py
|
download_data.py
|
import bz2
import urllib.request
OPEN_CORPORA_URL = 'http://opencorpora.org/files/export/annot/annot.opcorpora.no_ambig.xml.bz2'
OPEN_CORPORA_DEST_FILE = 'data/annot.opcorpora.no_ambig.xml'
CHUNK = 16 * 1024
def download_and_unbzip(url, dest_file):
source = urllib.request.urlopen(url)
decompressor = bz2.BZ2Decompressor()
with open(dest_file, 'wb') as dest_file:
while True:
data = source.read(CHUNK)
if not data:
break
dest_file.write(decompressor.decompress(data))
if __name__ == '__main__':
download_and_unbzip(OPEN_CORPORA_URL, OPEN_CORPORA_DEST_FILE)
|
import bz2
import urllib.request
import os
import os.path
DATA_DIR = 'data'
OPEN_CORPORA_URL = 'http://opencorpora.org/files/export/annot/annot.opcorpora.no_ambig.xml.bz2'
OPEN_CORPORA_DEST_FILE = 'data/annot.opcorpora.no_ambig.xml'
CHUNK = 16 * 1024
def download_and_unbzip(url, dest_file):
source = urllib.request.urlopen(url)
decompressor = bz2.BZ2Decompressor()
with open(dest_file, 'wb') as dest_file:
while True:
data = source.read(CHUNK)
if not data:
break
dest_file.write(decompressor.decompress(data))
if __name__ == '__main__':
if not os.path.isdir(DATA_DIR):
os.mkdir(DATA_DIR)
download_and_unbzip(OPEN_CORPORA_URL, OPEN_CORPORA_DEST_FILE)
|
Create dir before data downloading
|
Create dir before data downloading
|
Python
|
mit
|
Nizametdinov/cnn-pos-tagger
|
import bz2
import urllib.request
OPEN_CORPORA_URL = 'http://opencorpora.org/files/export/annot/annot.opcorpora.no_ambig.xml.bz2'
OPEN_CORPORA_DEST_FILE = 'data/annot.opcorpora.no_ambig.xml'
CHUNK = 16 * 1024
def download_and_unbzip(url, dest_file):
source = urllib.request.urlopen(url)
decompressor = bz2.BZ2Decompressor()
with open(dest_file, 'wb') as dest_file:
while True:
data = source.read(CHUNK)
if not data:
break
dest_file.write(decompressor.decompress(data))
if __name__ == '__main__':
download_and_unbzip(OPEN_CORPORA_URL, OPEN_CORPORA_DEST_FILE)
Create dir before data downloading
|
import bz2
import urllib.request
import os
import os.path
DATA_DIR = 'data'
OPEN_CORPORA_URL = 'http://opencorpora.org/files/export/annot/annot.opcorpora.no_ambig.xml.bz2'
OPEN_CORPORA_DEST_FILE = 'data/annot.opcorpora.no_ambig.xml'
CHUNK = 16 * 1024
def download_and_unbzip(url, dest_file):
source = urllib.request.urlopen(url)
decompressor = bz2.BZ2Decompressor()
with open(dest_file, 'wb') as dest_file:
while True:
data = source.read(CHUNK)
if not data:
break
dest_file.write(decompressor.decompress(data))
if __name__ == '__main__':
if not os.path.isdir(DATA_DIR):
os.mkdir(DATA_DIR)
download_and_unbzip(OPEN_CORPORA_URL, OPEN_CORPORA_DEST_FILE)
|
<commit_before>import bz2
import urllib.request
OPEN_CORPORA_URL = 'http://opencorpora.org/files/export/annot/annot.opcorpora.no_ambig.xml.bz2'
OPEN_CORPORA_DEST_FILE = 'data/annot.opcorpora.no_ambig.xml'
CHUNK = 16 * 1024
def download_and_unbzip(url, dest_file):
source = urllib.request.urlopen(url)
decompressor = bz2.BZ2Decompressor()
with open(dest_file, 'wb') as dest_file:
while True:
data = source.read(CHUNK)
if not data:
break
dest_file.write(decompressor.decompress(data))
if __name__ == '__main__':
download_and_unbzip(OPEN_CORPORA_URL, OPEN_CORPORA_DEST_FILE)
<commit_msg>Create dir before data downloading<commit_after>
|
import bz2
import urllib.request
import os
import os.path
DATA_DIR = 'data'
OPEN_CORPORA_URL = 'http://opencorpora.org/files/export/annot/annot.opcorpora.no_ambig.xml.bz2'
OPEN_CORPORA_DEST_FILE = 'data/annot.opcorpora.no_ambig.xml'
CHUNK = 16 * 1024
def download_and_unbzip(url, dest_file):
source = urllib.request.urlopen(url)
decompressor = bz2.BZ2Decompressor()
with open(dest_file, 'wb') as dest_file:
while True:
data = source.read(CHUNK)
if not data:
break
dest_file.write(decompressor.decompress(data))
if __name__ == '__main__':
if not os.path.isdir(DATA_DIR):
os.mkdir(DATA_DIR)
download_and_unbzip(OPEN_CORPORA_URL, OPEN_CORPORA_DEST_FILE)
|
import bz2
import urllib.request
OPEN_CORPORA_URL = 'http://opencorpora.org/files/export/annot/annot.opcorpora.no_ambig.xml.bz2'
OPEN_CORPORA_DEST_FILE = 'data/annot.opcorpora.no_ambig.xml'
CHUNK = 16 * 1024
def download_and_unbzip(url, dest_file):
source = urllib.request.urlopen(url)
decompressor = bz2.BZ2Decompressor()
with open(dest_file, 'wb') as dest_file:
while True:
data = source.read(CHUNK)
if not data:
break
dest_file.write(decompressor.decompress(data))
if __name__ == '__main__':
download_and_unbzip(OPEN_CORPORA_URL, OPEN_CORPORA_DEST_FILE)
Create dir before data downloadingimport bz2
import urllib.request
import os
import os.path
DATA_DIR = 'data'
OPEN_CORPORA_URL = 'http://opencorpora.org/files/export/annot/annot.opcorpora.no_ambig.xml.bz2'
OPEN_CORPORA_DEST_FILE = 'data/annot.opcorpora.no_ambig.xml'
CHUNK = 16 * 1024
def download_and_unbzip(url, dest_file):
source = urllib.request.urlopen(url)
decompressor = bz2.BZ2Decompressor()
with open(dest_file, 'wb') as dest_file:
while True:
data = source.read(CHUNK)
if not data:
break
dest_file.write(decompressor.decompress(data))
if __name__ == '__main__':
if not os.path.isdir(DATA_DIR):
os.mkdir(DATA_DIR)
download_and_unbzip(OPEN_CORPORA_URL, OPEN_CORPORA_DEST_FILE)
|
<commit_before>import bz2
import urllib.request
OPEN_CORPORA_URL = 'http://opencorpora.org/files/export/annot/annot.opcorpora.no_ambig.xml.bz2'
OPEN_CORPORA_DEST_FILE = 'data/annot.opcorpora.no_ambig.xml'
CHUNK = 16 * 1024
def download_and_unbzip(url, dest_file):
source = urllib.request.urlopen(url)
decompressor = bz2.BZ2Decompressor()
with open(dest_file, 'wb') as dest_file:
while True:
data = source.read(CHUNK)
if not data:
break
dest_file.write(decompressor.decompress(data))
if __name__ == '__main__':
download_and_unbzip(OPEN_CORPORA_URL, OPEN_CORPORA_DEST_FILE)
<commit_msg>Create dir before data downloading<commit_after>import bz2
import urllib.request
import os
import os.path
DATA_DIR = 'data'
OPEN_CORPORA_URL = 'http://opencorpora.org/files/export/annot/annot.opcorpora.no_ambig.xml.bz2'
OPEN_CORPORA_DEST_FILE = 'data/annot.opcorpora.no_ambig.xml'
CHUNK = 16 * 1024
def download_and_unbzip(url, dest_file):
source = urllib.request.urlopen(url)
decompressor = bz2.BZ2Decompressor()
with open(dest_file, 'wb') as dest_file:
while True:
data = source.read(CHUNK)
if not data:
break
dest_file.write(decompressor.decompress(data))
if __name__ == '__main__':
if not os.path.isdir(DATA_DIR):
os.mkdir(DATA_DIR)
download_and_unbzip(OPEN_CORPORA_URL, OPEN_CORPORA_DEST_FILE)
|
19a9ccb0b896c87ba04b47081c6b796cb37bd022
|
test/test_cypher.py
|
test/test_cypher.py
|
from neomodel import StructuredNode, StringProperty, CypherException
class User2(StructuredNode):
email = StringProperty()
def test_start_cypher():
jim = User2(email='jim@test.com').save()
email = jim.start_cypher("RETURN a.email")[0][0][0]
assert email == 'jim@test.com'
def test_cypher():
jim = User2(email='jim1@test.com').save()
email = jim.cypher("START a=node({self}) RETURN a.email")[0][0][0]
assert email == 'jim1@test.com'
def test_cypher_syntax_error():
jim = User2(email='jim1@test.com').save()
try:
jim.cypher("START a=node({self}) RETURN xx")
except CypherException as e:
assert hasattr(e, 'message')
assert hasattr(e, 'query')
assert hasattr(e, 'query_parameters')
assert hasattr(e, 'java_trace')
assert hasattr(e, 'java_exception')
else:
assert False
|
from neomodel import StructuredNode, StringProperty, CypherException
class User2(StructuredNode):
email = StringProperty()
def test_cypher():
jim = User2(email='jim1@test.com').save()
email = jim.cypher("START a=node({self}) RETURN a.email")[0][0][0]
assert email == 'jim1@test.com'
def test_cypher_syntax_error():
jim = User2(email='jim1@test.com').save()
try:
jim.cypher("START a=node({self}) RETURN xx")
except CypherException as e:
assert hasattr(e, 'message')
assert hasattr(e, 'query')
assert hasattr(e, 'query_parameters')
assert hasattr(e, 'java_trace')
assert hasattr(e, 'java_exception')
else:
assert False
|
Remove test of deprecated method
|
Remove test of deprecated method
|
Python
|
mit
|
bleib1dj/neomodel,robinedwards/neomodel,cristigociu/neomodel_dh,fpieper/neomodel,andrefsp/neomodel,wcooley/neomodel,robinedwards/neomodel,bleib1dj/neomodel,pombredanne/neomodel
|
from neomodel import StructuredNode, StringProperty, CypherException
class User2(StructuredNode):
email = StringProperty()
def test_start_cypher():
jim = User2(email='jim@test.com').save()
email = jim.start_cypher("RETURN a.email")[0][0][0]
assert email == 'jim@test.com'
def test_cypher():
jim = User2(email='jim1@test.com').save()
email = jim.cypher("START a=node({self}) RETURN a.email")[0][0][0]
assert email == 'jim1@test.com'
def test_cypher_syntax_error():
jim = User2(email='jim1@test.com').save()
try:
jim.cypher("START a=node({self}) RETURN xx")
except CypherException as e:
assert hasattr(e, 'message')
assert hasattr(e, 'query')
assert hasattr(e, 'query_parameters')
assert hasattr(e, 'java_trace')
assert hasattr(e, 'java_exception')
else:
assert False
Remove test of deprecated method
|
from neomodel import StructuredNode, StringProperty, CypherException
class User2(StructuredNode):
email = StringProperty()
def test_cypher():
jim = User2(email='jim1@test.com').save()
email = jim.cypher("START a=node({self}) RETURN a.email")[0][0][0]
assert email == 'jim1@test.com'
def test_cypher_syntax_error():
jim = User2(email='jim1@test.com').save()
try:
jim.cypher("START a=node({self}) RETURN xx")
except CypherException as e:
assert hasattr(e, 'message')
assert hasattr(e, 'query')
assert hasattr(e, 'query_parameters')
assert hasattr(e, 'java_trace')
assert hasattr(e, 'java_exception')
else:
assert False
|
<commit_before>from neomodel import StructuredNode, StringProperty, CypherException
class User2(StructuredNode):
email = StringProperty()
def test_start_cypher():
jim = User2(email='jim@test.com').save()
email = jim.start_cypher("RETURN a.email")[0][0][0]
assert email == 'jim@test.com'
def test_cypher():
jim = User2(email='jim1@test.com').save()
email = jim.cypher("START a=node({self}) RETURN a.email")[0][0][0]
assert email == 'jim1@test.com'
def test_cypher_syntax_error():
jim = User2(email='jim1@test.com').save()
try:
jim.cypher("START a=node({self}) RETURN xx")
except CypherException as e:
assert hasattr(e, 'message')
assert hasattr(e, 'query')
assert hasattr(e, 'query_parameters')
assert hasattr(e, 'java_trace')
assert hasattr(e, 'java_exception')
else:
assert False
<commit_msg>Remove test of deprecated method<commit_after>
|
from neomodel import StructuredNode, StringProperty, CypherException
class User2(StructuredNode):
email = StringProperty()
def test_cypher():
jim = User2(email='jim1@test.com').save()
email = jim.cypher("START a=node({self}) RETURN a.email")[0][0][0]
assert email == 'jim1@test.com'
def test_cypher_syntax_error():
jim = User2(email='jim1@test.com').save()
try:
jim.cypher("START a=node({self}) RETURN xx")
except CypherException as e:
assert hasattr(e, 'message')
assert hasattr(e, 'query')
assert hasattr(e, 'query_parameters')
assert hasattr(e, 'java_trace')
assert hasattr(e, 'java_exception')
else:
assert False
|
from neomodel import StructuredNode, StringProperty, CypherException
class User2(StructuredNode):
email = StringProperty()
def test_start_cypher():
jim = User2(email='jim@test.com').save()
email = jim.start_cypher("RETURN a.email")[0][0][0]
assert email == 'jim@test.com'
def test_cypher():
jim = User2(email='jim1@test.com').save()
email = jim.cypher("START a=node({self}) RETURN a.email")[0][0][0]
assert email == 'jim1@test.com'
def test_cypher_syntax_error():
jim = User2(email='jim1@test.com').save()
try:
jim.cypher("START a=node({self}) RETURN xx")
except CypherException as e:
assert hasattr(e, 'message')
assert hasattr(e, 'query')
assert hasattr(e, 'query_parameters')
assert hasattr(e, 'java_trace')
assert hasattr(e, 'java_exception')
else:
assert False
Remove test of deprecated methodfrom neomodel import StructuredNode, StringProperty, CypherException
class User2(StructuredNode):
email = StringProperty()
def test_cypher():
jim = User2(email='jim1@test.com').save()
email = jim.cypher("START a=node({self}) RETURN a.email")[0][0][0]
assert email == 'jim1@test.com'
def test_cypher_syntax_error():
jim = User2(email='jim1@test.com').save()
try:
jim.cypher("START a=node({self}) RETURN xx")
except CypherException as e:
assert hasattr(e, 'message')
assert hasattr(e, 'query')
assert hasattr(e, 'query_parameters')
assert hasattr(e, 'java_trace')
assert hasattr(e, 'java_exception')
else:
assert False
|
<commit_before>from neomodel import StructuredNode, StringProperty, CypherException
class User2(StructuredNode):
email = StringProperty()
def test_start_cypher():
jim = User2(email='jim@test.com').save()
email = jim.start_cypher("RETURN a.email")[0][0][0]
assert email == 'jim@test.com'
def test_cypher():
jim = User2(email='jim1@test.com').save()
email = jim.cypher("START a=node({self}) RETURN a.email")[0][0][0]
assert email == 'jim1@test.com'
def test_cypher_syntax_error():
jim = User2(email='jim1@test.com').save()
try:
jim.cypher("START a=node({self}) RETURN xx")
except CypherException as e:
assert hasattr(e, 'message')
assert hasattr(e, 'query')
assert hasattr(e, 'query_parameters')
assert hasattr(e, 'java_trace')
assert hasattr(e, 'java_exception')
else:
assert False
<commit_msg>Remove test of deprecated method<commit_after>from neomodel import StructuredNode, StringProperty, CypherException
class User2(StructuredNode):
email = StringProperty()
def test_cypher():
jim = User2(email='jim1@test.com').save()
email = jim.cypher("START a=node({self}) RETURN a.email")[0][0][0]
assert email == 'jim1@test.com'
def test_cypher_syntax_error():
jim = User2(email='jim1@test.com').save()
try:
jim.cypher("START a=node({self}) RETURN xx")
except CypherException as e:
assert hasattr(e, 'message')
assert hasattr(e, 'query')
assert hasattr(e, 'query_parameters')
assert hasattr(e, 'java_trace')
assert hasattr(e, 'java_exception')
else:
assert False
|
7dc239db20a5a0cb507644f1650e2d0fb752608a
|
migrations/versions/88d46e8e73ef_industry_index_remove_date.py
|
migrations/versions/88d46e8e73ef_industry_index_remove_date.py
|
"""industry index remove date
Revision ID: 88d46e8e73ef
Revises: 6543398f0773
Create Date: 2016-03-08 19:51:18.026000
"""
# revision identifiers, used by Alembic.
revision = '88d46e8e73ef'
down_revision = '6543398f0773'
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import mysql
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_column('industry_index', 'date')
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column('industry_index', sa.Column('date', mysql.DATETIME(), nullable=False))
### end Alembic commands ###
|
"""industry index remove date
Revision ID: 88d46e8e73ef
Revises: 6543398f0773
Create Date: 2016-03-08 19:51:18.026000
"""
# revision identifiers, used by Alembic.
revision = '88d46e8e73ef'
down_revision = '6543398f0773'
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import mysql
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_constraint(u'industry_index_ibfk_1', 'industry_index', type_='foreignkey')
op.drop_constraint('PRIMARY', 'industry_index', type_='primary')
op.drop_column('industry_index', 'date')
op.create_primary_key("industry_index_pk", "industry_index", ['solarsystem_id', 'activity'])
op.create_foreign_key("industry_index_ibfk_1", 'industry_index', 'solar_system', ['solarsystem_id'], ['id'])
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_constraint(u'industry_index_ibfk_1', 'industry_index', type_='foreignkey')
op.drop_constraint('PRIMARY', 'industry_index', type_='primary')
op.add_column('industry_index', sa.Column('date', mysql.DATETIME(), nullable=False))
op.create_primary_key("industry_index_pk", "industry_index", ['solarsystem_id', 'activity', 'date'])
op.create_foreign_key("industry_index_ibfk_1", 'industry_index', 'solar_system', ['solarsystem_id'], ['id'])
### end Alembic commands ###
|
Fix migration file that didn't work correctly
|
Fix migration file that didn't work correctly
|
Python
|
bsd-3-clause
|
Kyria/LazyBlacksmith,Kyria/LazyBlacksmith,Kyria/LazyBlacksmith,Kyria/LazyBlacksmith
|
"""industry index remove date
Revision ID: 88d46e8e73ef
Revises: 6543398f0773
Create Date: 2016-03-08 19:51:18.026000
"""
# revision identifiers, used by Alembic.
revision = '88d46e8e73ef'
down_revision = '6543398f0773'
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import mysql
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_column('industry_index', 'date')
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column('industry_index', sa.Column('date', mysql.DATETIME(), nullable=False))
### end Alembic commands ###
Fix migration file that didn't work correctly
|
"""industry index remove date
Revision ID: 88d46e8e73ef
Revises: 6543398f0773
Create Date: 2016-03-08 19:51:18.026000
"""
# revision identifiers, used by Alembic.
revision = '88d46e8e73ef'
down_revision = '6543398f0773'
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import mysql
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_constraint(u'industry_index_ibfk_1', 'industry_index', type_='foreignkey')
op.drop_constraint('PRIMARY', 'industry_index', type_='primary')
op.drop_column('industry_index', 'date')
op.create_primary_key("industry_index_pk", "industry_index", ['solarsystem_id', 'activity'])
op.create_foreign_key("industry_index_ibfk_1", 'industry_index', 'solar_system', ['solarsystem_id'], ['id'])
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_constraint(u'industry_index_ibfk_1', 'industry_index', type_='foreignkey')
op.drop_constraint('PRIMARY', 'industry_index', type_='primary')
op.add_column('industry_index', sa.Column('date', mysql.DATETIME(), nullable=False))
op.create_primary_key("industry_index_pk", "industry_index", ['solarsystem_id', 'activity', 'date'])
op.create_foreign_key("industry_index_ibfk_1", 'industry_index', 'solar_system', ['solarsystem_id'], ['id'])
### end Alembic commands ###
|
<commit_before>"""industry index remove date
Revision ID: 88d46e8e73ef
Revises: 6543398f0773
Create Date: 2016-03-08 19:51:18.026000
"""
# revision identifiers, used by Alembic.
revision = '88d46e8e73ef'
down_revision = '6543398f0773'
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import mysql
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_column('industry_index', 'date')
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column('industry_index', sa.Column('date', mysql.DATETIME(), nullable=False))
### end Alembic commands ###
<commit_msg>Fix migration file that didn't work correctly<commit_after>
|
"""industry index remove date
Revision ID: 88d46e8e73ef
Revises: 6543398f0773
Create Date: 2016-03-08 19:51:18.026000
"""
# revision identifiers, used by Alembic.
revision = '88d46e8e73ef'
down_revision = '6543398f0773'
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import mysql
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_constraint(u'industry_index_ibfk_1', 'industry_index', type_='foreignkey')
op.drop_constraint('PRIMARY', 'industry_index', type_='primary')
op.drop_column('industry_index', 'date')
op.create_primary_key("industry_index_pk", "industry_index", ['solarsystem_id', 'activity'])
op.create_foreign_key("industry_index_ibfk_1", 'industry_index', 'solar_system', ['solarsystem_id'], ['id'])
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_constraint(u'industry_index_ibfk_1', 'industry_index', type_='foreignkey')
op.drop_constraint('PRIMARY', 'industry_index', type_='primary')
op.add_column('industry_index', sa.Column('date', mysql.DATETIME(), nullable=False))
op.create_primary_key("industry_index_pk", "industry_index", ['solarsystem_id', 'activity', 'date'])
op.create_foreign_key("industry_index_ibfk_1", 'industry_index', 'solar_system', ['solarsystem_id'], ['id'])
### end Alembic commands ###
|
"""industry index remove date
Revision ID: 88d46e8e73ef
Revises: 6543398f0773
Create Date: 2016-03-08 19:51:18.026000
"""
# revision identifiers, used by Alembic.
revision = '88d46e8e73ef'
down_revision = '6543398f0773'
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import mysql
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_column('industry_index', 'date')
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column('industry_index', sa.Column('date', mysql.DATETIME(), nullable=False))
### end Alembic commands ###
Fix migration file that didn't work correctly"""industry index remove date
Revision ID: 88d46e8e73ef
Revises: 6543398f0773
Create Date: 2016-03-08 19:51:18.026000
"""
# revision identifiers, used by Alembic.
revision = '88d46e8e73ef'
down_revision = '6543398f0773'
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import mysql
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_constraint(u'industry_index_ibfk_1', 'industry_index', type_='foreignkey')
op.drop_constraint('PRIMARY', 'industry_index', type_='primary')
op.drop_column('industry_index', 'date')
op.create_primary_key("industry_index_pk", "industry_index", ['solarsystem_id', 'activity'])
op.create_foreign_key("industry_index_ibfk_1", 'industry_index', 'solar_system', ['solarsystem_id'], ['id'])
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_constraint(u'industry_index_ibfk_1', 'industry_index', type_='foreignkey')
op.drop_constraint('PRIMARY', 'industry_index', type_='primary')
op.add_column('industry_index', sa.Column('date', mysql.DATETIME(), nullable=False))
op.create_primary_key("industry_index_pk", "industry_index", ['solarsystem_id', 'activity', 'date'])
op.create_foreign_key("industry_index_ibfk_1", 'industry_index', 'solar_system', ['solarsystem_id'], ['id'])
### end Alembic commands ###
|
<commit_before>"""industry index remove date
Revision ID: 88d46e8e73ef
Revises: 6543398f0773
Create Date: 2016-03-08 19:51:18.026000
"""
# revision identifiers, used by Alembic.
revision = '88d46e8e73ef'
down_revision = '6543398f0773'
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import mysql
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_column('industry_index', 'date')
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column('industry_index', sa.Column('date', mysql.DATETIME(), nullable=False))
### end Alembic commands ###
<commit_msg>Fix migration file that didn't work correctly<commit_after>"""industry index remove date
Revision ID: 88d46e8e73ef
Revises: 6543398f0773
Create Date: 2016-03-08 19:51:18.026000
"""
# revision identifiers, used by Alembic.
revision = '88d46e8e73ef'
down_revision = '6543398f0773'
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import mysql
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_constraint(u'industry_index_ibfk_1', 'industry_index', type_='foreignkey')
op.drop_constraint('PRIMARY', 'industry_index', type_='primary')
op.drop_column('industry_index', 'date')
op.create_primary_key("industry_index_pk", "industry_index", ['solarsystem_id', 'activity'])
op.create_foreign_key("industry_index_ibfk_1", 'industry_index', 'solar_system', ['solarsystem_id'], ['id'])
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_constraint(u'industry_index_ibfk_1', 'industry_index', type_='foreignkey')
op.drop_constraint('PRIMARY', 'industry_index', type_='primary')
op.add_column('industry_index', sa.Column('date', mysql.DATETIME(), nullable=False))
op.create_primary_key("industry_index_pk", "industry_index", ['solarsystem_id', 'activity', 'date'])
op.create_foreign_key("industry_index_ibfk_1", 'industry_index', 'solar_system', ['solarsystem_id'], ['id'])
### end Alembic commands ###
|
62ca16d355716c3baaf7a661269e54a517fef25d
|
tests/test_hooks.py
|
tests/test_hooks.py
|
from io import BytesIO
from unittest.mock import MagicMock, patch
from isort import hooks
def test_git_hook():
"""Simple smoke level testing of git hooks"""
# Ensure correct subprocess command is called
with patch("subprocess.run", MagicMock()) as run_mock:
hooks.git_hook()
assert run_mock.called_with(
["git", "diff-index", "--cached", "--name-only", "--diff-filter=ACMRTUXB HEAD"]
)
# Test with incorrectly sorted file returned from git
with patch("isort.hooks.get_lines", MagicMock(return_value=["isort/isort.py"])) as run_mock:
class FakeProecssResponse(object):
stdout = b"import b\nimport a"
with patch("subprocess.run", MagicMock(return_value=FakeProecssResponse())) as run_mock:
with patch("isort.hooks.SortImports", MagicMock()):
hooks.git_hook(modify=True)
|
from io import BytesIO
from unittest.mock import MagicMock, patch
from isort import hooks
def test_git_hook():
"""Simple smoke level testing of git hooks"""
# Ensure correct subprocess command is called
with patch("subprocess.run", MagicMock()) as run_mock:
hooks.git_hook()
assert run_mock.called_with(
["git", "diff-index", "--cached", "--name-only", "--diff-filter=ACMRTUXB HEAD"]
)
# Test with incorrectly sorted file returned from git
with patch("isort.hooks.get_lines", MagicMock(return_value=["isort/isort.py"])) as run_mock:
class FakeProecssResponse(object):
stdout = b"import b\nimport a"
with patch("subprocess.run", MagicMock(return_value=FakeProecssResponse())) as run_mock:
with patch("isort.hooks.api", MagicMock()):
hooks.git_hook(modify=True)
|
Fix mock statement for new API
|
Fix mock statement for new API
|
Python
|
mit
|
PyCQA/isort,PyCQA/isort
|
from io import BytesIO
from unittest.mock import MagicMock, patch
from isort import hooks
def test_git_hook():
"""Simple smoke level testing of git hooks"""
# Ensure correct subprocess command is called
with patch("subprocess.run", MagicMock()) as run_mock:
hooks.git_hook()
assert run_mock.called_with(
["git", "diff-index", "--cached", "--name-only", "--diff-filter=ACMRTUXB HEAD"]
)
# Test with incorrectly sorted file returned from git
with patch("isort.hooks.get_lines", MagicMock(return_value=["isort/isort.py"])) as run_mock:
class FakeProecssResponse(object):
stdout = b"import b\nimport a"
with patch("subprocess.run", MagicMock(return_value=FakeProecssResponse())) as run_mock:
with patch("isort.hooks.SortImports", MagicMock()):
hooks.git_hook(modify=True)
Fix mock statement for new API
|
from io import BytesIO
from unittest.mock import MagicMock, patch
from isort import hooks
def test_git_hook():
"""Simple smoke level testing of git hooks"""
# Ensure correct subprocess command is called
with patch("subprocess.run", MagicMock()) as run_mock:
hooks.git_hook()
assert run_mock.called_with(
["git", "diff-index", "--cached", "--name-only", "--diff-filter=ACMRTUXB HEAD"]
)
# Test with incorrectly sorted file returned from git
with patch("isort.hooks.get_lines", MagicMock(return_value=["isort/isort.py"])) as run_mock:
class FakeProecssResponse(object):
stdout = b"import b\nimport a"
with patch("subprocess.run", MagicMock(return_value=FakeProecssResponse())) as run_mock:
with patch("isort.hooks.api", MagicMock()):
hooks.git_hook(modify=True)
|
<commit_before>from io import BytesIO
from unittest.mock import MagicMock, patch
from isort import hooks
def test_git_hook():
"""Simple smoke level testing of git hooks"""
# Ensure correct subprocess command is called
with patch("subprocess.run", MagicMock()) as run_mock:
hooks.git_hook()
assert run_mock.called_with(
["git", "diff-index", "--cached", "--name-only", "--diff-filter=ACMRTUXB HEAD"]
)
# Test with incorrectly sorted file returned from git
with patch("isort.hooks.get_lines", MagicMock(return_value=["isort/isort.py"])) as run_mock:
class FakeProecssResponse(object):
stdout = b"import b\nimport a"
with patch("subprocess.run", MagicMock(return_value=FakeProecssResponse())) as run_mock:
with patch("isort.hooks.SortImports", MagicMock()):
hooks.git_hook(modify=True)
<commit_msg>Fix mock statement for new API<commit_after>
|
from io import BytesIO
from unittest.mock import MagicMock, patch
from isort import hooks
def test_git_hook():
"""Simple smoke level testing of git hooks"""
# Ensure correct subprocess command is called
with patch("subprocess.run", MagicMock()) as run_mock:
hooks.git_hook()
assert run_mock.called_with(
["git", "diff-index", "--cached", "--name-only", "--diff-filter=ACMRTUXB HEAD"]
)
# Test with incorrectly sorted file returned from git
with patch("isort.hooks.get_lines", MagicMock(return_value=["isort/isort.py"])) as run_mock:
class FakeProecssResponse(object):
stdout = b"import b\nimport a"
with patch("subprocess.run", MagicMock(return_value=FakeProecssResponse())) as run_mock:
with patch("isort.hooks.api", MagicMock()):
hooks.git_hook(modify=True)
|
from io import BytesIO
from unittest.mock import MagicMock, patch
from isort import hooks
def test_git_hook():
"""Simple smoke level testing of git hooks"""
# Ensure correct subprocess command is called
with patch("subprocess.run", MagicMock()) as run_mock:
hooks.git_hook()
assert run_mock.called_with(
["git", "diff-index", "--cached", "--name-only", "--diff-filter=ACMRTUXB HEAD"]
)
# Test with incorrectly sorted file returned from git
with patch("isort.hooks.get_lines", MagicMock(return_value=["isort/isort.py"])) as run_mock:
class FakeProecssResponse(object):
stdout = b"import b\nimport a"
with patch("subprocess.run", MagicMock(return_value=FakeProecssResponse())) as run_mock:
with patch("isort.hooks.SortImports", MagicMock()):
hooks.git_hook(modify=True)
Fix mock statement for new APIfrom io import BytesIO
from unittest.mock import MagicMock, patch
from isort import hooks
def test_git_hook():
"""Simple smoke level testing of git hooks"""
# Ensure correct subprocess command is called
with patch("subprocess.run", MagicMock()) as run_mock:
hooks.git_hook()
assert run_mock.called_with(
["git", "diff-index", "--cached", "--name-only", "--diff-filter=ACMRTUXB HEAD"]
)
# Test with incorrectly sorted file returned from git
with patch("isort.hooks.get_lines", MagicMock(return_value=["isort/isort.py"])) as run_mock:
class FakeProecssResponse(object):
stdout = b"import b\nimport a"
with patch("subprocess.run", MagicMock(return_value=FakeProecssResponse())) as run_mock:
with patch("isort.hooks.api", MagicMock()):
hooks.git_hook(modify=True)
|
<commit_before>from io import BytesIO
from unittest.mock import MagicMock, patch
from isort import hooks
def test_git_hook():
"""Simple smoke level testing of git hooks"""
# Ensure correct subprocess command is called
with patch("subprocess.run", MagicMock()) as run_mock:
hooks.git_hook()
assert run_mock.called_with(
["git", "diff-index", "--cached", "--name-only", "--diff-filter=ACMRTUXB HEAD"]
)
# Test with incorrectly sorted file returned from git
with patch("isort.hooks.get_lines", MagicMock(return_value=["isort/isort.py"])) as run_mock:
class FakeProecssResponse(object):
stdout = b"import b\nimport a"
with patch("subprocess.run", MagicMock(return_value=FakeProecssResponse())) as run_mock:
with patch("isort.hooks.SortImports", MagicMock()):
hooks.git_hook(modify=True)
<commit_msg>Fix mock statement for new API<commit_after>from io import BytesIO
from unittest.mock import MagicMock, patch
from isort import hooks
def test_git_hook():
"""Simple smoke level testing of git hooks"""
# Ensure correct subprocess command is called
with patch("subprocess.run", MagicMock()) as run_mock:
hooks.git_hook()
assert run_mock.called_with(
["git", "diff-index", "--cached", "--name-only", "--diff-filter=ACMRTUXB HEAD"]
)
# Test with incorrectly sorted file returned from git
with patch("isort.hooks.get_lines", MagicMock(return_value=["isort/isort.py"])) as run_mock:
class FakeProecssResponse(object):
stdout = b"import b\nimport a"
with patch("subprocess.run", MagicMock(return_value=FakeProecssResponse())) as run_mock:
with patch("isort.hooks.api", MagicMock()):
hooks.git_hook(modify=True)
|
c70b6717ec69fbf235b89d34c668686ecf9b8c26
|
tests/test_utils.py
|
tests/test_utils.py
|
#!/usr/bin/python2.5
#
# Copyright 2008 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Common testing utilities.
"""
__authors__ = [
'"Augie Fackler" <durin42@gmail.com>',
]
class MockRequest(object):
"""Shared dummy request object to mock common aspects of a request.
"""
def __init__(self, path=None):
self.REQUEST = self.GET = self.POST = {}
self.path = path
|
#!/usr/bin/python2.5
#
# Copyright 2008 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Common testing utilities.
"""
__authors__ = [
'"Augie Fackler" <durin42@gmail.com>',
'"Sverre Rabbelier" <sverre@rabbelier.nl>',
]
from soc.modules import callback
class MockRequest(object):
"""Shared dummy request object to mock common aspects of a request.
Before using the object, start should be called, when done (and
before calling start on a new request), end should be called.
"""
def __init__(self, path=None):
"""Creates a new empty request object.
self.REQUEST, self.GET and self.POST are set to an empty
dictionary, and path to the value specified.
"""
self.REQUEST = {}
self.GET = {}
self.POST = {}
self.path = path
def start(self):
"""Readies the core for a new request.
"""
core = callback.getCore()
core.startNewRequest(self)
def end(self):
"""Finishes up the current request.
"""
core = callback.getCore()
core.endRequest(self, False)
|
Add a start and end method to MockRequest
|
Add a start and end method to MockRequest
|
Python
|
apache-2.0
|
rhyolight/nupic.son,rhyolight/nupic.son,rhyolight/nupic.son
|
#!/usr/bin/python2.5
#
# Copyright 2008 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Common testing utilities.
"""
__authors__ = [
'"Augie Fackler" <durin42@gmail.com>',
]
class MockRequest(object):
"""Shared dummy request object to mock common aspects of a request.
"""
def __init__(self, path=None):
self.REQUEST = self.GET = self.POST = {}
self.path = path
Add a start and end method to MockRequest
|
#!/usr/bin/python2.5
#
# Copyright 2008 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Common testing utilities.
"""
__authors__ = [
'"Augie Fackler" <durin42@gmail.com>',
'"Sverre Rabbelier" <sverre@rabbelier.nl>',
]
from soc.modules import callback
class MockRequest(object):
"""Shared dummy request object to mock common aspects of a request.
Before using the object, start should be called, when done (and
before calling start on a new request), end should be called.
"""
def __init__(self, path=None):
"""Creates a new empty request object.
self.REQUEST, self.GET and self.POST are set to an empty
dictionary, and path to the value specified.
"""
self.REQUEST = {}
self.GET = {}
self.POST = {}
self.path = path
def start(self):
"""Readies the core for a new request.
"""
core = callback.getCore()
core.startNewRequest(self)
def end(self):
"""Finishes up the current request.
"""
core = callback.getCore()
core.endRequest(self, False)
|
<commit_before>#!/usr/bin/python2.5
#
# Copyright 2008 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Common testing utilities.
"""
__authors__ = [
'"Augie Fackler" <durin42@gmail.com>',
]
class MockRequest(object):
"""Shared dummy request object to mock common aspects of a request.
"""
def __init__(self, path=None):
self.REQUEST = self.GET = self.POST = {}
self.path = path
<commit_msg>Add a start and end method to MockRequest<commit_after>
|
#!/usr/bin/python2.5
#
# Copyright 2008 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Common testing utilities.
"""
__authors__ = [
'"Augie Fackler" <durin42@gmail.com>',
'"Sverre Rabbelier" <sverre@rabbelier.nl>',
]
from soc.modules import callback
class MockRequest(object):
"""Shared dummy request object to mock common aspects of a request.
Before using the object, start should be called, when done (and
before calling start on a new request), end should be called.
"""
def __init__(self, path=None):
"""Creates a new empty request object.
self.REQUEST, self.GET and self.POST are set to an empty
dictionary, and path to the value specified.
"""
self.REQUEST = {}
self.GET = {}
self.POST = {}
self.path = path
def start(self):
"""Readies the core for a new request.
"""
core = callback.getCore()
core.startNewRequest(self)
def end(self):
"""Finishes up the current request.
"""
core = callback.getCore()
core.endRequest(self, False)
|
#!/usr/bin/python2.5
#
# Copyright 2008 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Common testing utilities.
"""
__authors__ = [
'"Augie Fackler" <durin42@gmail.com>',
]
class MockRequest(object):
"""Shared dummy request object to mock common aspects of a request.
"""
def __init__(self, path=None):
self.REQUEST = self.GET = self.POST = {}
self.path = path
Add a start and end method to MockRequest#!/usr/bin/python2.5
#
# Copyright 2008 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Common testing utilities.
"""
__authors__ = [
'"Augie Fackler" <durin42@gmail.com>',
'"Sverre Rabbelier" <sverre@rabbelier.nl>',
]
from soc.modules import callback
class MockRequest(object):
"""Shared dummy request object to mock common aspects of a request.
Before using the object, start should be called, when done (and
before calling start on a new request), end should be called.
"""
def __init__(self, path=None):
"""Creates a new empty request object.
self.REQUEST, self.GET and self.POST are set to an empty
dictionary, and path to the value specified.
"""
self.REQUEST = {}
self.GET = {}
self.POST = {}
self.path = path
def start(self):
"""Readies the core for a new request.
"""
core = callback.getCore()
core.startNewRequest(self)
def end(self):
"""Finishes up the current request.
"""
core = callback.getCore()
core.endRequest(self, False)
|
<commit_before>#!/usr/bin/python2.5
#
# Copyright 2008 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Common testing utilities.
"""
__authors__ = [
'"Augie Fackler" <durin42@gmail.com>',
]
class MockRequest(object):
"""Shared dummy request object to mock common aspects of a request.
"""
def __init__(self, path=None):
self.REQUEST = self.GET = self.POST = {}
self.path = path
<commit_msg>Add a start and end method to MockRequest<commit_after>#!/usr/bin/python2.5
#
# Copyright 2008 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Common testing utilities.
"""
__authors__ = [
'"Augie Fackler" <durin42@gmail.com>',
'"Sverre Rabbelier" <sverre@rabbelier.nl>',
]
from soc.modules import callback
class MockRequest(object):
"""Shared dummy request object to mock common aspects of a request.
Before using the object, start should be called, when done (and
before calling start on a new request), end should be called.
"""
def __init__(self, path=None):
"""Creates a new empty request object.
self.REQUEST, self.GET and self.POST are set to an empty
dictionary, and path to the value specified.
"""
self.REQUEST = {}
self.GET = {}
self.POST = {}
self.path = path
def start(self):
"""Readies the core for a new request.
"""
core = callback.getCore()
core.startNewRequest(self)
def end(self):
"""Finishes up the current request.
"""
core = callback.getCore()
core.endRequest(self, False)
|
118bbc7363dc83947bc74f94f720ef8ecb1705d2
|
quickstart/python/understand/example-2/create_joke_task.6.x.py
|
quickstart/python/understand/example-2/create_joke_task.6.x.py
|
# Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
# Create a new task named 'tell_a_joke'
# Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list
task = client.preview.understand \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.tasks \
.create(unique_name='tell-a-joke')
# Provide actions for the new task
joke_actions = {
'actions': [
{'say': 'I was going to look for my missing watch, but I could never find the time.'}
]
}
# Update the tell-a-joke task to use this 'say' action.
client.preview.understand \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.tasks(task.sid) \
.task_actions().update(joke_actions)
print(intent.sid)
|
# Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
# Create a new task named 'tell_a_joke'
# Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list
task = client.preview.understand \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.tasks \
.create(unique_name='tell-a-joke')
# Provide actions for the new task
joke_actions = {
'actions': [
{'say': 'I was going to look for my missing watch, but I could never find the time.'}
]
}
# Update the tell-a-joke task to use this 'say' action.
client.preview.understand \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.tasks(task.sid) \
.task_actions().update(joke_actions)
print(task.sid)
|
Print task SID in output
|
Print task SID in output
|
Python
|
mit
|
TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets
|
# Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
# Create a new task named 'tell_a_joke'
# Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list
task = client.preview.understand \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.tasks \
.create(unique_name='tell-a-joke')
# Provide actions for the new task
joke_actions = {
'actions': [
{'say': 'I was going to look for my missing watch, but I could never find the time.'}
]
}
# Update the tell-a-joke task to use this 'say' action.
client.preview.understand \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.tasks(task.sid) \
.task_actions().update(joke_actions)
print(intent.sid)
Print task SID in output
|
# Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
# Create a new task named 'tell_a_joke'
# Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list
task = client.preview.understand \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.tasks \
.create(unique_name='tell-a-joke')
# Provide actions for the new task
joke_actions = {
'actions': [
{'say': 'I was going to look for my missing watch, but I could never find the time.'}
]
}
# Update the tell-a-joke task to use this 'say' action.
client.preview.understand \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.tasks(task.sid) \
.task_actions().update(joke_actions)
print(task.sid)
|
<commit_before># Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
# Create a new task named 'tell_a_joke'
# Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list
task = client.preview.understand \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.tasks \
.create(unique_name='tell-a-joke')
# Provide actions for the new task
joke_actions = {
'actions': [
{'say': 'I was going to look for my missing watch, but I could never find the time.'}
]
}
# Update the tell-a-joke task to use this 'say' action.
client.preview.understand \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.tasks(task.sid) \
.task_actions().update(joke_actions)
print(intent.sid)
<commit_msg>Print task SID in output<commit_after>
|
# Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
# Create a new task named 'tell_a_joke'
# Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list
task = client.preview.understand \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.tasks \
.create(unique_name='tell-a-joke')
# Provide actions for the new task
joke_actions = {
'actions': [
{'say': 'I was going to look for my missing watch, but I could never find the time.'}
]
}
# Update the tell-a-joke task to use this 'say' action.
client.preview.understand \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.tasks(task.sid) \
.task_actions().update(joke_actions)
print(task.sid)
|
# Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
# Create a new task named 'tell_a_joke'
# Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list
task = client.preview.understand \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.tasks \
.create(unique_name='tell-a-joke')
# Provide actions for the new task
joke_actions = {
'actions': [
{'say': 'I was going to look for my missing watch, but I could never find the time.'}
]
}
# Update the tell-a-joke task to use this 'say' action.
client.preview.understand \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.tasks(task.sid) \
.task_actions().update(joke_actions)
print(intent.sid)
Print task SID in output# Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
# Create a new task named 'tell_a_joke'
# Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list
task = client.preview.understand \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.tasks \
.create(unique_name='tell-a-joke')
# Provide actions for the new task
joke_actions = {
'actions': [
{'say': 'I was going to look for my missing watch, but I could never find the time.'}
]
}
# Update the tell-a-joke task to use this 'say' action.
client.preview.understand \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.tasks(task.sid) \
.task_actions().update(joke_actions)
print(task.sid)
|
<commit_before># Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
# Create a new task named 'tell_a_joke'
# Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list
task = client.preview.understand \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.tasks \
.create(unique_name='tell-a-joke')
# Provide actions for the new task
joke_actions = {
'actions': [
{'say': 'I was going to look for my missing watch, but I could never find the time.'}
]
}
# Update the tell-a-joke task to use this 'say' action.
client.preview.understand \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.tasks(task.sid) \
.task_actions().update(joke_actions)
print(intent.sid)
<commit_msg>Print task SID in output<commit_after># Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
# Create a new task named 'tell_a_joke'
# Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list
task = client.preview.understand \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.tasks \
.create(unique_name='tell-a-joke')
# Provide actions for the new task
joke_actions = {
'actions': [
{'say': 'I was going to look for my missing watch, but I could never find the time.'}
]
}
# Update the tell-a-joke task to use this 'say' action.
client.preview.understand \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.tasks(task.sid) \
.task_actions().update(joke_actions)
print(task.sid)
|
55f787d653f1ee7b923a460f892a27a4143ec408
|
providers/moviedata/provider.py
|
providers/moviedata/provider.py
|
from __future__ import print_function
from providers.provider import BaseProvider
# Subclasses implement a way to get movie data for from a search string
#
# To implement a MoviedataProvider:
# - Create a new file in moviedata/ and call it provider_[your name].py
# - Add the path to your file in settings.py, under MOVIEDATA_PROVIDERS
# - In the new file, Subclass MoviedataProvider and provide a IDENTIFIER
# - Implement get_movie_data(), returning a dictionary with movie data
class MoviedataProvider(BaseProvider):
IDENTIFIER = None
def get_movie_data(self):
raise NotImplementedError("Subclasses must implement get_movie_data")
|
from __future__ import print_function
from providers.provider import BaseProvider
# Subclasses implement a way to get movie data for from a search string
#
# To implement a MoviedataProvider:
# - Create a new file in moviedata/ and call it provider_[your name].py
# - Add the path to your file in settings.py, under MOVIEDATA_PROVIDERS
# - In the new file, Subclass MoviedataProvider and provide a IDENTIFIER
# - Implement get_movie_data()
# - It returns a tuple of a imdb_id and a dictionary with movie data
# - Implement get_data_fields()
# - It returns a dictionary mapping db fields to data that
# this provider has added to data
class MoviedataProvider(BaseProvider):
IDENTIFIER = None
def get_movie_data(self, name):
raise NotImplementedError("Subclasses must implement get_movie_data")
def get_data_mapping(self):
raise NotImplementedError("Subclasses must implement get_data_mapping")
# ==== HELPER METHODS ====
def transform_data(self, data):
if not data:
return data
out_data = {}
mapping = self.get_data_mapping()
for to_field, from_field in mapping.items():
if callable(from_field):
out_data[to_field] = from_field(data)
elif isinstance(from_field, str):
out_data[to_field] = self.traverse_json(data, path=from_field)
else:
assert False, "Unknown type for: " + repr(from_field)
return out_data
|
Add docs for add transform_data helper method.
|
Add docs for add transform_data helper method.
|
Python
|
mit
|
EmilStenstrom/nephele
|
from __future__ import print_function
from providers.provider import BaseProvider
# Subclasses implement a way to get movie data for from a search string
#
# To implement a MoviedataProvider:
# - Create a new file in moviedata/ and call it provider_[your name].py
# - Add the path to your file in settings.py, under MOVIEDATA_PROVIDERS
# - In the new file, Subclass MoviedataProvider and provide a IDENTIFIER
# - Implement get_movie_data(), returning a dictionary with movie data
class MoviedataProvider(BaseProvider):
IDENTIFIER = None
def get_movie_data(self):
raise NotImplementedError("Subclasses must implement get_movie_data")
Add docs for add transform_data helper method.
|
from __future__ import print_function
from providers.provider import BaseProvider
# Subclasses implement a way to get movie data for from a search string
#
# To implement a MoviedataProvider:
# - Create a new file in moviedata/ and call it provider_[your name].py
# - Add the path to your file in settings.py, under MOVIEDATA_PROVIDERS
# - In the new file, Subclass MoviedataProvider and provide a IDENTIFIER
# - Implement get_movie_data()
# - It returns a tuple of a imdb_id and a dictionary with movie data
# - Implement get_data_fields()
# - It returns a dictionary mapping db fields to data that
# this provider has added to data
class MoviedataProvider(BaseProvider):
IDENTIFIER = None
def get_movie_data(self, name):
raise NotImplementedError("Subclasses must implement get_movie_data")
def get_data_mapping(self):
raise NotImplementedError("Subclasses must implement get_data_mapping")
# ==== HELPER METHODS ====
def transform_data(self, data):
if not data:
return data
out_data = {}
mapping = self.get_data_mapping()
for to_field, from_field in mapping.items():
if callable(from_field):
out_data[to_field] = from_field(data)
elif isinstance(from_field, str):
out_data[to_field] = self.traverse_json(data, path=from_field)
else:
assert False, "Unknown type for: " + repr(from_field)
return out_data
|
<commit_before>from __future__ import print_function
from providers.provider import BaseProvider
# Subclasses implement a way to get movie data for from a search string
#
# To implement a MoviedataProvider:
# - Create a new file in moviedata/ and call it provider_[your name].py
# - Add the path to your file in settings.py, under MOVIEDATA_PROVIDERS
# - In the new file, Subclass MoviedataProvider and provide a IDENTIFIER
# - Implement get_movie_data(), returning a dictionary with movie data
class MoviedataProvider(BaseProvider):
IDENTIFIER = None
def get_movie_data(self):
raise NotImplementedError("Subclasses must implement get_movie_data")
<commit_msg>Add docs for add transform_data helper method.<commit_after>
|
from __future__ import print_function
from providers.provider import BaseProvider
# Subclasses implement a way to get movie data for from a search string
#
# To implement a MoviedataProvider:
# - Create a new file in moviedata/ and call it provider_[your name].py
# - Add the path to your file in settings.py, under MOVIEDATA_PROVIDERS
# - In the new file, Subclass MoviedataProvider and provide a IDENTIFIER
# - Implement get_movie_data()
# - It returns a tuple of a imdb_id and a dictionary with movie data
# - Implement get_data_fields()
# - It returns a dictionary mapping db fields to data that
# this provider has added to data
class MoviedataProvider(BaseProvider):
IDENTIFIER = None
def get_movie_data(self, name):
raise NotImplementedError("Subclasses must implement get_movie_data")
def get_data_mapping(self):
raise NotImplementedError("Subclasses must implement get_data_mapping")
# ==== HELPER METHODS ====
def transform_data(self, data):
if not data:
return data
out_data = {}
mapping = self.get_data_mapping()
for to_field, from_field in mapping.items():
if callable(from_field):
out_data[to_field] = from_field(data)
elif isinstance(from_field, str):
out_data[to_field] = self.traverse_json(data, path=from_field)
else:
assert False, "Unknown type for: " + repr(from_field)
return out_data
|
from __future__ import print_function
from providers.provider import BaseProvider
# Subclasses implement a way to get movie data for from a search string
#
# To implement a MoviedataProvider:
# - Create a new file in moviedata/ and call it provider_[your name].py
# - Add the path to your file in settings.py, under MOVIEDATA_PROVIDERS
# - In the new file, Subclass MoviedataProvider and provide a IDENTIFIER
# - Implement get_movie_data(), returning a dictionary with movie data
class MoviedataProvider(BaseProvider):
IDENTIFIER = None
def get_movie_data(self):
raise NotImplementedError("Subclasses must implement get_movie_data")
Add docs for add transform_data helper method.from __future__ import print_function
from providers.provider import BaseProvider
# Subclasses implement a way to get movie data for from a search string
#
# To implement a MoviedataProvider:
# - Create a new file in moviedata/ and call it provider_[your name].py
# - Add the path to your file in settings.py, under MOVIEDATA_PROVIDERS
# - In the new file, Subclass MoviedataProvider and provide a IDENTIFIER
# - Implement get_movie_data()
# - It returns a tuple of a imdb_id and a dictionary with movie data
# - Implement get_data_fields()
# - It returns a dictionary mapping db fields to data that
# this provider has added to data
class MoviedataProvider(BaseProvider):
IDENTIFIER = None
def get_movie_data(self, name):
raise NotImplementedError("Subclasses must implement get_movie_data")
def get_data_mapping(self):
raise NotImplementedError("Subclasses must implement get_data_mapping")
# ==== HELPER METHODS ====
def transform_data(self, data):
if not data:
return data
out_data = {}
mapping = self.get_data_mapping()
for to_field, from_field in mapping.items():
if callable(from_field):
out_data[to_field] = from_field(data)
elif isinstance(from_field, str):
out_data[to_field] = self.traverse_json(data, path=from_field)
else:
assert False, "Unknown type for: " + repr(from_field)
return out_data
|
<commit_before>from __future__ import print_function
from providers.provider import BaseProvider
# Subclasses implement a way to get movie data for from a search string
#
# To implement a MoviedataProvider:
# - Create a new file in moviedata/ and call it provider_[your name].py
# - Add the path to your file in settings.py, under MOVIEDATA_PROVIDERS
# - In the new file, Subclass MoviedataProvider and provide a IDENTIFIER
# - Implement get_movie_data(), returning a dictionary with movie data
class MoviedataProvider(BaseProvider):
IDENTIFIER = None
def get_movie_data(self):
raise NotImplementedError("Subclasses must implement get_movie_data")
<commit_msg>Add docs for add transform_data helper method.<commit_after>from __future__ import print_function
from providers.provider import BaseProvider
# Subclasses implement a way to get movie data for from a search string
#
# To implement a MoviedataProvider:
# - Create a new file in moviedata/ and call it provider_[your name].py
# - Add the path to your file in settings.py, under MOVIEDATA_PROVIDERS
# - In the new file, Subclass MoviedataProvider and provide a IDENTIFIER
# - Implement get_movie_data()
# - It returns a tuple of a imdb_id and a dictionary with movie data
# - Implement get_data_fields()
# - It returns a dictionary mapping db fields to data that
# this provider has added to data
class MoviedataProvider(BaseProvider):
IDENTIFIER = None
def get_movie_data(self, name):
raise NotImplementedError("Subclasses must implement get_movie_data")
def get_data_mapping(self):
raise NotImplementedError("Subclasses must implement get_data_mapping")
# ==== HELPER METHODS ====
def transform_data(self, data):
if not data:
return data
out_data = {}
mapping = self.get_data_mapping()
for to_field, from_field in mapping.items():
if callable(from_field):
out_data[to_field] = from_field(data)
elif isinstance(from_field, str):
out_data[to_field] = self.traverse_json(data, path=from_field)
else:
assert False, "Unknown type for: " + repr(from_field)
return out_data
|
458fb9b764cae3419b6513dcc1fedf2ea8949829
|
networkx/generators/tests/test_stochastic.py
|
networkx/generators/tests/test_stochastic.py
|
from nose.tools import assert_true, assert_equal,assert_raises
import networkx as nx
def test_stochastic():
G=nx.DiGraph()
G.add_edge(0,1)
G.add_edge(0,2)
S=nx.stochastic_graph(G)
assert_true(nx.is_isomorphic(G,S))
assert_equal(sorted(S.edges(data=True)),
[(0, 1, {'weight': 0.5}),
(0, 2, {'weight': 0.5})])
S=nx.stochastic_graph(G,copy=True)
assert_equal(sorted(S.edges(data=True)),
[(0, 1, {'weight': 0.5}),
(0, 2, {'weight': 0.5})])
def test_stochastic_error():
G=nx.Graph()
assert_raises(Exception,nx.stochastic_graph,G)
G=nx.MultiGraph()
assert_raises(Exception,nx.stochastic_graph,G)
|
from nose.tools import assert_true, assert_equal,assert_raises
import networkx as nx
def test_stochastic():
G=nx.DiGraph()
G.add_edge(0,1)
G.add_edge(0,2)
S=nx.stochastic_graph(G)
assert_true(nx.is_isomorphic(G,S))
assert_equal(sorted(S.edges(data=True)),
[(0, 1, {'weight': 0.5}),
(0, 2, {'weight': 0.5})])
S=nx.stochastic_graph(G,copy=True)
assert_equal(sorted(S.edges(data=True)),
[(0, 1, {'weight': 0.5}),
(0, 2, {'weight': 0.5})])
def test_stochastic_ints():
G=nx.DiGraph()
G.add_edge(0,1,weight=1)
G.add_edge(0,2,weight=1)
S=nx.stochastic_graph(G)
assert_equal(sorted(S.edges(data=True)),
[(0, 1, {'weight': 0.5}),
(0, 2, {'weight': 0.5})])
def test_stochastic_error():
G=nx.Graph()
assert_raises(Exception,nx.stochastic_graph,G)
G=nx.MultiGraph()
assert_raises(Exception,nx.stochastic_graph,G)
|
Test stochstic graph with ints
|
Test stochstic graph with ints
|
Python
|
bsd-3-clause
|
blublud/networkx,dhimmel/networkx,nathania/networkx,goulu/networkx,ltiao/networkx,ionanrozenfeld/networkx,bzero/networkx,dmoliveira/networkx,aureooms/networkx,yashu-seth/networkx,ghdk/networkx,ionanrozenfeld/networkx,nathania/networkx,harlowja/networkx,michaelpacer/networkx,ionanrozenfeld/networkx,aureooms/networkx,harlowja/networkx,bzero/networkx,beni55/networkx,OrkoHunter/networkx,jni/networkx,kernc/networkx,NvanAdrichem/networkx,jcurbelo/networkx,sharifulgeo/networkx,dhimmel/networkx,jakevdp/networkx,jfinkels/networkx,farhaanbukhsh/networkx,nathania/networkx,debsankha/networkx,farhaanbukhsh/networkx,sharifulgeo/networkx,RMKD/networkx,Sixshaman/networkx,RMKD/networkx,aureooms/networkx,blublud/networkx,jakevdp/networkx,kernc/networkx,chrisnatali/networkx,jni/networkx,debsankha/networkx,harlowja/networkx,dmoliveira/networkx,tmilicic/networkx,kernc/networkx,bzero/networkx,wasade/networkx,jni/networkx,blublud/networkx,ghdk/networkx,jakevdp/networkx,sharifulgeo/networkx,JamesClough/networkx,chrisnatali/networkx,farhaanbukhsh/networkx,dmoliveira/networkx,cmtm/networkx,ghdk/networkx,dhimmel/networkx,chrisnatali/networkx,RMKD/networkx,andnovar/networkx,SanketDG/networkx,debsankha/networkx
|
from nose.tools import assert_true, assert_equal,assert_raises
import networkx as nx
def test_stochastic():
G=nx.DiGraph()
G.add_edge(0,1)
G.add_edge(0,2)
S=nx.stochastic_graph(G)
assert_true(nx.is_isomorphic(G,S))
assert_equal(sorted(S.edges(data=True)),
[(0, 1, {'weight': 0.5}),
(0, 2, {'weight': 0.5})])
S=nx.stochastic_graph(G,copy=True)
assert_equal(sorted(S.edges(data=True)),
[(0, 1, {'weight': 0.5}),
(0, 2, {'weight': 0.5})])
def test_stochastic_error():
G=nx.Graph()
assert_raises(Exception,nx.stochastic_graph,G)
G=nx.MultiGraph()
assert_raises(Exception,nx.stochastic_graph,G)
Test stochstic graph with ints
|
from nose.tools import assert_true, assert_equal,assert_raises
import networkx as nx
def test_stochastic():
G=nx.DiGraph()
G.add_edge(0,1)
G.add_edge(0,2)
S=nx.stochastic_graph(G)
assert_true(nx.is_isomorphic(G,S))
assert_equal(sorted(S.edges(data=True)),
[(0, 1, {'weight': 0.5}),
(0, 2, {'weight': 0.5})])
S=nx.stochastic_graph(G,copy=True)
assert_equal(sorted(S.edges(data=True)),
[(0, 1, {'weight': 0.5}),
(0, 2, {'weight': 0.5})])
def test_stochastic_ints():
G=nx.DiGraph()
G.add_edge(0,1,weight=1)
G.add_edge(0,2,weight=1)
S=nx.stochastic_graph(G)
assert_equal(sorted(S.edges(data=True)),
[(0, 1, {'weight': 0.5}),
(0, 2, {'weight': 0.5})])
def test_stochastic_error():
G=nx.Graph()
assert_raises(Exception,nx.stochastic_graph,G)
G=nx.MultiGraph()
assert_raises(Exception,nx.stochastic_graph,G)
|
<commit_before>from nose.tools import assert_true, assert_equal,assert_raises
import networkx as nx
def test_stochastic():
G=nx.DiGraph()
G.add_edge(0,1)
G.add_edge(0,2)
S=nx.stochastic_graph(G)
assert_true(nx.is_isomorphic(G,S))
assert_equal(sorted(S.edges(data=True)),
[(0, 1, {'weight': 0.5}),
(0, 2, {'weight': 0.5})])
S=nx.stochastic_graph(G,copy=True)
assert_equal(sorted(S.edges(data=True)),
[(0, 1, {'weight': 0.5}),
(0, 2, {'weight': 0.5})])
def test_stochastic_error():
G=nx.Graph()
assert_raises(Exception,nx.stochastic_graph,G)
G=nx.MultiGraph()
assert_raises(Exception,nx.stochastic_graph,G)
<commit_msg>Test stochstic graph with ints<commit_after>
|
from nose.tools import assert_true, assert_equal,assert_raises
import networkx as nx
def test_stochastic():
G=nx.DiGraph()
G.add_edge(0,1)
G.add_edge(0,2)
S=nx.stochastic_graph(G)
assert_true(nx.is_isomorphic(G,S))
assert_equal(sorted(S.edges(data=True)),
[(0, 1, {'weight': 0.5}),
(0, 2, {'weight': 0.5})])
S=nx.stochastic_graph(G,copy=True)
assert_equal(sorted(S.edges(data=True)),
[(0, 1, {'weight': 0.5}),
(0, 2, {'weight': 0.5})])
def test_stochastic_ints():
G=nx.DiGraph()
G.add_edge(0,1,weight=1)
G.add_edge(0,2,weight=1)
S=nx.stochastic_graph(G)
assert_equal(sorted(S.edges(data=True)),
[(0, 1, {'weight': 0.5}),
(0, 2, {'weight': 0.5})])
def test_stochastic_error():
G=nx.Graph()
assert_raises(Exception,nx.stochastic_graph,G)
G=nx.MultiGraph()
assert_raises(Exception,nx.stochastic_graph,G)
|
from nose.tools import assert_true, assert_equal,assert_raises
import networkx as nx
def test_stochastic():
G=nx.DiGraph()
G.add_edge(0,1)
G.add_edge(0,2)
S=nx.stochastic_graph(G)
assert_true(nx.is_isomorphic(G,S))
assert_equal(sorted(S.edges(data=True)),
[(0, 1, {'weight': 0.5}),
(0, 2, {'weight': 0.5})])
S=nx.stochastic_graph(G,copy=True)
assert_equal(sorted(S.edges(data=True)),
[(0, 1, {'weight': 0.5}),
(0, 2, {'weight': 0.5})])
def test_stochastic_error():
G=nx.Graph()
assert_raises(Exception,nx.stochastic_graph,G)
G=nx.MultiGraph()
assert_raises(Exception,nx.stochastic_graph,G)
Test stochstic graph with intsfrom nose.tools import assert_true, assert_equal,assert_raises
import networkx as nx
def test_stochastic():
G=nx.DiGraph()
G.add_edge(0,1)
G.add_edge(0,2)
S=nx.stochastic_graph(G)
assert_true(nx.is_isomorphic(G,S))
assert_equal(sorted(S.edges(data=True)),
[(0, 1, {'weight': 0.5}),
(0, 2, {'weight': 0.5})])
S=nx.stochastic_graph(G,copy=True)
assert_equal(sorted(S.edges(data=True)),
[(0, 1, {'weight': 0.5}),
(0, 2, {'weight': 0.5})])
def test_stochastic_ints():
G=nx.DiGraph()
G.add_edge(0,1,weight=1)
G.add_edge(0,2,weight=1)
S=nx.stochastic_graph(G)
assert_equal(sorted(S.edges(data=True)),
[(0, 1, {'weight': 0.5}),
(0, 2, {'weight': 0.5})])
def test_stochastic_error():
G=nx.Graph()
assert_raises(Exception,nx.stochastic_graph,G)
G=nx.MultiGraph()
assert_raises(Exception,nx.stochastic_graph,G)
|
<commit_before>from nose.tools import assert_true, assert_equal,assert_raises
import networkx as nx
def test_stochastic():
G=nx.DiGraph()
G.add_edge(0,1)
G.add_edge(0,2)
S=nx.stochastic_graph(G)
assert_true(nx.is_isomorphic(G,S))
assert_equal(sorted(S.edges(data=True)),
[(0, 1, {'weight': 0.5}),
(0, 2, {'weight': 0.5})])
S=nx.stochastic_graph(G,copy=True)
assert_equal(sorted(S.edges(data=True)),
[(0, 1, {'weight': 0.5}),
(0, 2, {'weight': 0.5})])
def test_stochastic_error():
G=nx.Graph()
assert_raises(Exception,nx.stochastic_graph,G)
G=nx.MultiGraph()
assert_raises(Exception,nx.stochastic_graph,G)
<commit_msg>Test stochstic graph with ints<commit_after>from nose.tools import assert_true, assert_equal,assert_raises
import networkx as nx
def test_stochastic():
G=nx.DiGraph()
G.add_edge(0,1)
G.add_edge(0,2)
S=nx.stochastic_graph(G)
assert_true(nx.is_isomorphic(G,S))
assert_equal(sorted(S.edges(data=True)),
[(0, 1, {'weight': 0.5}),
(0, 2, {'weight': 0.5})])
S=nx.stochastic_graph(G,copy=True)
assert_equal(sorted(S.edges(data=True)),
[(0, 1, {'weight': 0.5}),
(0, 2, {'weight': 0.5})])
def test_stochastic_ints():
G=nx.DiGraph()
G.add_edge(0,1,weight=1)
G.add_edge(0,2,weight=1)
S=nx.stochastic_graph(G)
assert_equal(sorted(S.edges(data=True)),
[(0, 1, {'weight': 0.5}),
(0, 2, {'weight': 0.5})])
def test_stochastic_error():
G=nx.Graph()
assert_raises(Exception,nx.stochastic_graph,G)
G=nx.MultiGraph()
assert_raises(Exception,nx.stochastic_graph,G)
|
60cfe690ef44b87b0824fe33255abcd09806ae20
|
nn-patterns/utils/tests/networks/__init__.py
|
nn-patterns/utils/tests/networks/__init__.py
|
# Begin: Python 2/3 compatibility header small
# Get Python 3 functionality:
from __future__ import\
absolute_import, print_function, division, unicode_literals
from future.utils import raise_with_traceback, raise_from
# catch exception with: except Exception as e
from builtins import range, map, zip, filter
from io import open
import six
# End: Python 2/3 compatability header small
import theano.tensor as T
from . import mnist
from . import cifar10
from . import imagenet
def iterator():
"""
Iterator over various networks.
"""
default_nonlinearity = T.nnet.relu
def fetch_networks(module_name, module):
ret = [("%s.%s" % (module_name, name),
getattr(module, name)(default_nonlinearity))
for name in module.__all__]
for name, network in ret:
network["name"] = name
return [x[1] for x in sorted(ret)]
networks = (
fetch_networks("mnist", mnist) +
fetch_networks("cifar10", cifar10) +
fetch_networks("imagenet", imagenet)
)
for network in networks:
yield network
|
# Begin: Python 2/3 compatibility header small
# Get Python 3 functionality:
from __future__ import\
absolute_import, print_function, division, unicode_literals
from future.utils import raise_with_traceback, raise_from
# catch exception with: except Exception as e
from builtins import range, map, zip, filter
from io import open
import six
# End: Python 2/3 compatability header small
import fnmatch
import os
import theano.tensor as T
from . import mnist
from . import cifar10
from . import imagenet
def iterator():
"""
Iterator over various networks.
"""
default_nonlinearity = T.nnet.relu
# TODO: make this more transparent!
# Default test only for one network. To test all put "*"
name_filter = "mnist.cnn_2convb_2dense"
if "NNPATTERNS_TEST_FILTER" in os.environ:
name_filter = os.environ["NNPATTERNS_TEST_FILTER"]
def fetch_networks(module_name, module):
ret = [
("%s.%s" % (module_name, name),
getattr(module, name)(default_nonlinearity))
for name in module.__all__
if (fnmatch.fnmatch(name, name_filter) or
fnmatch.fnmatch("%s.%s" % (module_name, name), name_filter))
]
for name, network in ret:
network["name"] = name
return [x[1] for x in sorted(ret)]
networks = (
fetch_networks("mnist", mnist) +
fetch_networks("cifar10", cifar10) +
fetch_networks("imagenet", imagenet)
)
for network in networks:
yield network
|
Add filter to customize which networks to test.
|
Add filter to customize which networks to test.
|
Python
|
mit
|
pikinder/nn-patterns
|
# Begin: Python 2/3 compatibility header small
# Get Python 3 functionality:
from __future__ import\
absolute_import, print_function, division, unicode_literals
from future.utils import raise_with_traceback, raise_from
# catch exception with: except Exception as e
from builtins import range, map, zip, filter
from io import open
import six
# End: Python 2/3 compatability header small
import theano.tensor as T
from . import mnist
from . import cifar10
from . import imagenet
def iterator():
"""
Iterator over various networks.
"""
default_nonlinearity = T.nnet.relu
def fetch_networks(module_name, module):
ret = [("%s.%s" % (module_name, name),
getattr(module, name)(default_nonlinearity))
for name in module.__all__]
for name, network in ret:
network["name"] = name
return [x[1] for x in sorted(ret)]
networks = (
fetch_networks("mnist", mnist) +
fetch_networks("cifar10", cifar10) +
fetch_networks("imagenet", imagenet)
)
for network in networks:
yield network
Add filter to customize which networks to test.
|
# Begin: Python 2/3 compatibility header small
# Get Python 3 functionality:
from __future__ import\
absolute_import, print_function, division, unicode_literals
from future.utils import raise_with_traceback, raise_from
# catch exception with: except Exception as e
from builtins import range, map, zip, filter
from io import open
import six
# End: Python 2/3 compatability header small
import fnmatch
import os
import theano.tensor as T
from . import mnist
from . import cifar10
from . import imagenet
def iterator():
"""
Iterator over various networks.
"""
default_nonlinearity = T.nnet.relu
# TODO: make this more transparent!
# Default test only for one network. To test all put "*"
name_filter = "mnist.cnn_2convb_2dense"
if "NNPATTERNS_TEST_FILTER" in os.environ:
name_filter = os.environ["NNPATTERNS_TEST_FILTER"]
def fetch_networks(module_name, module):
ret = [
("%s.%s" % (module_name, name),
getattr(module, name)(default_nonlinearity))
for name in module.__all__
if (fnmatch.fnmatch(name, name_filter) or
fnmatch.fnmatch("%s.%s" % (module_name, name), name_filter))
]
for name, network in ret:
network["name"] = name
return [x[1] for x in sorted(ret)]
networks = (
fetch_networks("mnist", mnist) +
fetch_networks("cifar10", cifar10) +
fetch_networks("imagenet", imagenet)
)
for network in networks:
yield network
|
<commit_before># Begin: Python 2/3 compatibility header small
# Get Python 3 functionality:
from __future__ import\
absolute_import, print_function, division, unicode_literals
from future.utils import raise_with_traceback, raise_from
# catch exception with: except Exception as e
from builtins import range, map, zip, filter
from io import open
import six
# End: Python 2/3 compatability header small
import theano.tensor as T
from . import mnist
from . import cifar10
from . import imagenet
def iterator():
"""
Iterator over various networks.
"""
default_nonlinearity = T.nnet.relu
def fetch_networks(module_name, module):
ret = [("%s.%s" % (module_name, name),
getattr(module, name)(default_nonlinearity))
for name in module.__all__]
for name, network in ret:
network["name"] = name
return [x[1] for x in sorted(ret)]
networks = (
fetch_networks("mnist", mnist) +
fetch_networks("cifar10", cifar10) +
fetch_networks("imagenet", imagenet)
)
for network in networks:
yield network
<commit_msg>Add filter to customize which networks to test.<commit_after>
|
# Begin: Python 2/3 compatibility header small
# Get Python 3 functionality:
from __future__ import\
absolute_import, print_function, division, unicode_literals
from future.utils import raise_with_traceback, raise_from
# catch exception with: except Exception as e
from builtins import range, map, zip, filter
from io import open
import six
# End: Python 2/3 compatability header small
import fnmatch
import os
import theano.tensor as T
from . import mnist
from . import cifar10
from . import imagenet
def iterator():
"""
Iterator over various networks.
"""
default_nonlinearity = T.nnet.relu
# TODO: make this more transparent!
# Default test only for one network. To test all put "*"
name_filter = "mnist.cnn_2convb_2dense"
if "NNPATTERNS_TEST_FILTER" in os.environ:
name_filter = os.environ["NNPATTERNS_TEST_FILTER"]
def fetch_networks(module_name, module):
ret = [
("%s.%s" % (module_name, name),
getattr(module, name)(default_nonlinearity))
for name in module.__all__
if (fnmatch.fnmatch(name, name_filter) or
fnmatch.fnmatch("%s.%s" % (module_name, name), name_filter))
]
for name, network in ret:
network["name"] = name
return [x[1] for x in sorted(ret)]
networks = (
fetch_networks("mnist", mnist) +
fetch_networks("cifar10", cifar10) +
fetch_networks("imagenet", imagenet)
)
for network in networks:
yield network
|
# Begin: Python 2/3 compatibility header small
# Get Python 3 functionality:
from __future__ import\
absolute_import, print_function, division, unicode_literals
from future.utils import raise_with_traceback, raise_from
# catch exception with: except Exception as e
from builtins import range, map, zip, filter
from io import open
import six
# End: Python 2/3 compatability header small
import theano.tensor as T
from . import mnist
from . import cifar10
from . import imagenet
def iterator():
"""
Iterator over various networks.
"""
default_nonlinearity = T.nnet.relu
def fetch_networks(module_name, module):
ret = [("%s.%s" % (module_name, name),
getattr(module, name)(default_nonlinearity))
for name in module.__all__]
for name, network in ret:
network["name"] = name
return [x[1] for x in sorted(ret)]
networks = (
fetch_networks("mnist", mnist) +
fetch_networks("cifar10", cifar10) +
fetch_networks("imagenet", imagenet)
)
for network in networks:
yield network
Add filter to customize which networks to test.# Begin: Python 2/3 compatibility header small
# Get Python 3 functionality:
from __future__ import\
absolute_import, print_function, division, unicode_literals
from future.utils import raise_with_traceback, raise_from
# catch exception with: except Exception as e
from builtins import range, map, zip, filter
from io import open
import six
# End: Python 2/3 compatability header small
import fnmatch
import os
import theano.tensor as T
from . import mnist
from . import cifar10
from . import imagenet
def iterator():
"""
Iterator over various networks.
"""
default_nonlinearity = T.nnet.relu
# TODO: make this more transparent!
# Default test only for one network. To test all put "*"
name_filter = "mnist.cnn_2convb_2dense"
if "NNPATTERNS_TEST_FILTER" in os.environ:
name_filter = os.environ["NNPATTERNS_TEST_FILTER"]
def fetch_networks(module_name, module):
ret = [
("%s.%s" % (module_name, name),
getattr(module, name)(default_nonlinearity))
for name in module.__all__
if (fnmatch.fnmatch(name, name_filter) or
fnmatch.fnmatch("%s.%s" % (module_name, name), name_filter))
]
for name, network in ret:
network["name"] = name
return [x[1] for x in sorted(ret)]
networks = (
fetch_networks("mnist", mnist) +
fetch_networks("cifar10", cifar10) +
fetch_networks("imagenet", imagenet)
)
for network in networks:
yield network
|
<commit_before># Begin: Python 2/3 compatibility header small
# Get Python 3 functionality:
from __future__ import\
absolute_import, print_function, division, unicode_literals
from future.utils import raise_with_traceback, raise_from
# catch exception with: except Exception as e
from builtins import range, map, zip, filter
from io import open
import six
# End: Python 2/3 compatability header small
import theano.tensor as T
from . import mnist
from . import cifar10
from . import imagenet
def iterator():
"""
Iterator over various networks.
"""
default_nonlinearity = T.nnet.relu
def fetch_networks(module_name, module):
ret = [("%s.%s" % (module_name, name),
getattr(module, name)(default_nonlinearity))
for name in module.__all__]
for name, network in ret:
network["name"] = name
return [x[1] for x in sorted(ret)]
networks = (
fetch_networks("mnist", mnist) +
fetch_networks("cifar10", cifar10) +
fetch_networks("imagenet", imagenet)
)
for network in networks:
yield network
<commit_msg>Add filter to customize which networks to test.<commit_after># Begin: Python 2/3 compatibility header small
# Get Python 3 functionality:
from __future__ import\
absolute_import, print_function, division, unicode_literals
from future.utils import raise_with_traceback, raise_from
# catch exception with: except Exception as e
from builtins import range, map, zip, filter
from io import open
import six
# End: Python 2/3 compatability header small
import fnmatch
import os
import theano.tensor as T
from . import mnist
from . import cifar10
from . import imagenet
def iterator():
"""
Iterator over various networks.
"""
default_nonlinearity = T.nnet.relu
# TODO: make this more transparent!
# Default test only for one network. To test all put "*"
name_filter = "mnist.cnn_2convb_2dense"
if "NNPATTERNS_TEST_FILTER" in os.environ:
name_filter = os.environ["NNPATTERNS_TEST_FILTER"]
def fetch_networks(module_name, module):
ret = [
("%s.%s" % (module_name, name),
getattr(module, name)(default_nonlinearity))
for name in module.__all__
if (fnmatch.fnmatch(name, name_filter) or
fnmatch.fnmatch("%s.%s" % (module_name, name), name_filter))
]
for name, network in ret:
network["name"] = name
return [x[1] for x in sorted(ret)]
networks = (
fetch_networks("mnist", mnist) +
fetch_networks("cifar10", cifar10) +
fetch_networks("imagenet", imagenet)
)
for network in networks:
yield network
|
69d856b5b6ec9f87b55174ebbd414d9960bb626d
|
tests/offline/test_pricing.py
|
tests/offline/test_pricing.py
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2016 <>
#
# Distributed under terms of the MIT license.
# Python modules
from __future__ import unicode_literals
# Third-party modules
import pytest
# Project modules
from fnapy.exceptions import FnapyPricingError
from tests import make_requests_get_mock, fake_manager
from tests.offline import create_context_for_requests
def test_query_pricing(monkeypatch, fake_manager):
context = create_context_for_requests(monkeypatch, fake_manager,
'query_pricing', 'pricing_query')
with context:
fake_manager.query_pricing(ean='0886971942323')
# This time, we must also test the response because it may contain an error we
# want to catch and raise a FnapyPricingError
def test_query_pricing_with_invalid_ean(monkeypatch, fake_manager):
context = create_context_for_requests(monkeypatch, fake_manager,
'query_pricing_with_invalid_ean',
'pricing_query')
with context:
with pytest.raises(FnapyPricingError):
fake_manager.query_pricing(ean='007')
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2016 <>
#
# Distributed under terms of the MIT license.
# Python modules
from __future__ import unicode_literals
# Third-party modules
import pytest
# Project modules
from fnapy.exceptions import FnapyPricingError
from tests import make_requests_get_mock, fake_manager
from tests.offline import create_context_for_requests
def test_query_pricing(monkeypatch, fake_manager):
context = create_context_for_requests(monkeypatch, fake_manager,
'query_pricing', 'pricing_query')
with context:
eans = [7321900286480, 9780262510875, 5060314991222]
fake_manager.query_pricing(eans=eans)
# This time, we must also test the response because it may contain an error we
# want to catch and raise a FnapyPricingError
def test_query_pricing_with_invalid_ean(monkeypatch, fake_manager):
context = create_context_for_requests(monkeypatch, fake_manager,
'query_pricing_with_invalid_ean',
'pricing_query')
with context:
with pytest.raises(FnapyPricingError):
fake_manager.query_pricing(eans=['007'])
|
Update the tests for query_pricing
|
Update the tests for query_pricing
|
Python
|
mit
|
alexandriagroup/fnapy,alexandriagroup/fnapy
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2016 <>
#
# Distributed under terms of the MIT license.
# Python modules
from __future__ import unicode_literals
# Third-party modules
import pytest
# Project modules
from fnapy.exceptions import FnapyPricingError
from tests import make_requests_get_mock, fake_manager
from tests.offline import create_context_for_requests
def test_query_pricing(monkeypatch, fake_manager):
context = create_context_for_requests(monkeypatch, fake_manager,
'query_pricing', 'pricing_query')
with context:
fake_manager.query_pricing(ean='0886971942323')
# This time, we must also test the response because it may contain an error we
# want to catch and raise a FnapyPricingError
def test_query_pricing_with_invalid_ean(monkeypatch, fake_manager):
context = create_context_for_requests(monkeypatch, fake_manager,
'query_pricing_with_invalid_ean',
'pricing_query')
with context:
with pytest.raises(FnapyPricingError):
fake_manager.query_pricing(ean='007')
Update the tests for query_pricing
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2016 <>
#
# Distributed under terms of the MIT license.
# Python modules
from __future__ import unicode_literals
# Third-party modules
import pytest
# Project modules
from fnapy.exceptions import FnapyPricingError
from tests import make_requests_get_mock, fake_manager
from tests.offline import create_context_for_requests
def test_query_pricing(monkeypatch, fake_manager):
context = create_context_for_requests(monkeypatch, fake_manager,
'query_pricing', 'pricing_query')
with context:
eans = [7321900286480, 9780262510875, 5060314991222]
fake_manager.query_pricing(eans=eans)
# This time, we must also test the response because it may contain an error we
# want to catch and raise a FnapyPricingError
def test_query_pricing_with_invalid_ean(monkeypatch, fake_manager):
context = create_context_for_requests(monkeypatch, fake_manager,
'query_pricing_with_invalid_ean',
'pricing_query')
with context:
with pytest.raises(FnapyPricingError):
fake_manager.query_pricing(eans=['007'])
|
<commit_before>#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2016 <>
#
# Distributed under terms of the MIT license.
# Python modules
from __future__ import unicode_literals
# Third-party modules
import pytest
# Project modules
from fnapy.exceptions import FnapyPricingError
from tests import make_requests_get_mock, fake_manager
from tests.offline import create_context_for_requests
def test_query_pricing(monkeypatch, fake_manager):
context = create_context_for_requests(monkeypatch, fake_manager,
'query_pricing', 'pricing_query')
with context:
fake_manager.query_pricing(ean='0886971942323')
# This time, we must also test the response because it may contain an error we
# want to catch and raise a FnapyPricingError
def test_query_pricing_with_invalid_ean(monkeypatch, fake_manager):
context = create_context_for_requests(monkeypatch, fake_manager,
'query_pricing_with_invalid_ean',
'pricing_query')
with context:
with pytest.raises(FnapyPricingError):
fake_manager.query_pricing(ean='007')
<commit_msg>Update the tests for query_pricing<commit_after>
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2016 <>
#
# Distributed under terms of the MIT license.
# Python modules
from __future__ import unicode_literals
# Third-party modules
import pytest
# Project modules
from fnapy.exceptions import FnapyPricingError
from tests import make_requests_get_mock, fake_manager
from tests.offline import create_context_for_requests
def test_query_pricing(monkeypatch, fake_manager):
context = create_context_for_requests(monkeypatch, fake_manager,
'query_pricing', 'pricing_query')
with context:
eans = [7321900286480, 9780262510875, 5060314991222]
fake_manager.query_pricing(eans=eans)
# This time, we must also test the response because it may contain an error we
# want to catch and raise a FnapyPricingError
def test_query_pricing_with_invalid_ean(monkeypatch, fake_manager):
context = create_context_for_requests(monkeypatch, fake_manager,
'query_pricing_with_invalid_ean',
'pricing_query')
with context:
with pytest.raises(FnapyPricingError):
fake_manager.query_pricing(eans=['007'])
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2016 <>
#
# Distributed under terms of the MIT license.
# Python modules
from __future__ import unicode_literals
# Third-party modules
import pytest
# Project modules
from fnapy.exceptions import FnapyPricingError
from tests import make_requests_get_mock, fake_manager
from tests.offline import create_context_for_requests
def test_query_pricing(monkeypatch, fake_manager):
context = create_context_for_requests(monkeypatch, fake_manager,
'query_pricing', 'pricing_query')
with context:
fake_manager.query_pricing(ean='0886971942323')
# This time, we must also test the response because it may contain an error we
# want to catch and raise a FnapyPricingError
def test_query_pricing_with_invalid_ean(monkeypatch, fake_manager):
context = create_context_for_requests(monkeypatch, fake_manager,
'query_pricing_with_invalid_ean',
'pricing_query')
with context:
with pytest.raises(FnapyPricingError):
fake_manager.query_pricing(ean='007')
Update the tests for query_pricing#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2016 <>
#
# Distributed under terms of the MIT license.
# Python modules
from __future__ import unicode_literals
# Third-party modules
import pytest
# Project modules
from fnapy.exceptions import FnapyPricingError
from tests import make_requests_get_mock, fake_manager
from tests.offline import create_context_for_requests
def test_query_pricing(monkeypatch, fake_manager):
context = create_context_for_requests(monkeypatch, fake_manager,
'query_pricing', 'pricing_query')
with context:
eans = [7321900286480, 9780262510875, 5060314991222]
fake_manager.query_pricing(eans=eans)
# This time, we must also test the response because it may contain an error we
# want to catch and raise a FnapyPricingError
def test_query_pricing_with_invalid_ean(monkeypatch, fake_manager):
context = create_context_for_requests(monkeypatch, fake_manager,
'query_pricing_with_invalid_ean',
'pricing_query')
with context:
with pytest.raises(FnapyPricingError):
fake_manager.query_pricing(eans=['007'])
|
<commit_before>#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2016 <>
#
# Distributed under terms of the MIT license.
# Python modules
from __future__ import unicode_literals
# Third-party modules
import pytest
# Project modules
from fnapy.exceptions import FnapyPricingError
from tests import make_requests_get_mock, fake_manager
from tests.offline import create_context_for_requests
def test_query_pricing(monkeypatch, fake_manager):
context = create_context_for_requests(monkeypatch, fake_manager,
'query_pricing', 'pricing_query')
with context:
fake_manager.query_pricing(ean='0886971942323')
# This time, we must also test the response because it may contain an error we
# want to catch and raise a FnapyPricingError
def test_query_pricing_with_invalid_ean(monkeypatch, fake_manager):
context = create_context_for_requests(monkeypatch, fake_manager,
'query_pricing_with_invalid_ean',
'pricing_query')
with context:
with pytest.raises(FnapyPricingError):
fake_manager.query_pricing(ean='007')
<commit_msg>Update the tests for query_pricing<commit_after>#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2016 <>
#
# Distributed under terms of the MIT license.
# Python modules
from __future__ import unicode_literals
# Third-party modules
import pytest
# Project modules
from fnapy.exceptions import FnapyPricingError
from tests import make_requests_get_mock, fake_manager
from tests.offline import create_context_for_requests
def test_query_pricing(monkeypatch, fake_manager):
context = create_context_for_requests(monkeypatch, fake_manager,
'query_pricing', 'pricing_query')
with context:
eans = [7321900286480, 9780262510875, 5060314991222]
fake_manager.query_pricing(eans=eans)
# This time, we must also test the response because it may contain an error we
# want to catch and raise a FnapyPricingError
def test_query_pricing_with_invalid_ean(monkeypatch, fake_manager):
context = create_context_for_requests(monkeypatch, fake_manager,
'query_pricing_with_invalid_ean',
'pricing_query')
with context:
with pytest.raises(FnapyPricingError):
fake_manager.query_pricing(eans=['007'])
|
7d0f1c9cea6e71d5cc515ae3790226ae6badda79
|
Logger.py
|
Logger.py
|
import time
class Logger():
def __init__(self, name = "defaultLogFile"):
timestamp = time.strftime('%Y_%m_%d-%H_%M_%S')
self.name = "Logs/" + timestamp + "_" + name + ".txt"
try:
self.logfile = open(self.name, 'w')
self.opened = True
except:
self.opened = False
def save_line(self,data):
time_s = time.time()
time_ms = int(round((time_s - round(time_s))*1000))
timestamp = time.strftime(('%H_%M_%S'), time.localtime(time_s))+"_" +str(time_ms) + " : "
if(self.opened):
self.logfile.write(timestamp+data)
self.logfile.flush()
return 0,""
else:
return 1,str(timestamp+data)
def close(self):
if(self.opened):
self.logfile.flush()
self.logfile.close()
self.opened = False
return 0
else:
return 1
|
import time
class Logger():
def __init__(self, name = "defaultLogFile"):
timestamp = time.strftime('%Y_%m_%d-%H_%M_%S')
self.name = "Logs/" + timestamp + "_" + name + ".txt"
try:
self.logfile = open(self.name, 'w')
self.opened = True
except:
self.opened = False
def save_line(self,data):
time_s = time.time()
time_ms = int((time_s - int(time_s))*1000.0)
timestamp = time.strftime(('%H_%M_%S'), time.localtime(time_s))+"_" +str(time_ms) + " : "
if(self.opened):
self.logfile.write(timestamp+data)
self.logfile.flush()
return 0,""
else:
return 1,str(timestamp+data)
def close(self):
if(self.opened):
self.logfile.flush()
self.logfile.close()
self.opened = False
return 0
else:
return 1
|
Correct and simplify calculation of miliseconds
|
Correct and simplify calculation of miliseconds
Signed-off-by: TeaPackCZ <a78d8486eff6e2cb08b2d9907449b92187b8e215@gmail.com>
|
Python
|
mit
|
TeaPackCZ/RobotZed,TeaPackCZ/RobotZed
|
import time
class Logger():
def __init__(self, name = "defaultLogFile"):
timestamp = time.strftime('%Y_%m_%d-%H_%M_%S')
self.name = "Logs/" + timestamp + "_" + name + ".txt"
try:
self.logfile = open(self.name, 'w')
self.opened = True
except:
self.opened = False
def save_line(self,data):
time_s = time.time()
time_ms = int(round((time_s - round(time_s))*1000))
timestamp = time.strftime(('%H_%M_%S'), time.localtime(time_s))+"_" +str(time_ms) + " : "
if(self.opened):
self.logfile.write(timestamp+data)
self.logfile.flush()
return 0,""
else:
return 1,str(timestamp+data)
def close(self):
if(self.opened):
self.logfile.flush()
self.logfile.close()
self.opened = False
return 0
else:
return 1
Correct and simplify calculation of miliseconds
Signed-off-by: TeaPackCZ <a78d8486eff6e2cb08b2d9907449b92187b8e215@gmail.com>
|
import time
class Logger():
def __init__(self, name = "defaultLogFile"):
timestamp = time.strftime('%Y_%m_%d-%H_%M_%S')
self.name = "Logs/" + timestamp + "_" + name + ".txt"
try:
self.logfile = open(self.name, 'w')
self.opened = True
except:
self.opened = False
def save_line(self,data):
time_s = time.time()
time_ms = int((time_s - int(time_s))*1000.0)
timestamp = time.strftime(('%H_%M_%S'), time.localtime(time_s))+"_" +str(time_ms) + " : "
if(self.opened):
self.logfile.write(timestamp+data)
self.logfile.flush()
return 0,""
else:
return 1,str(timestamp+data)
def close(self):
if(self.opened):
self.logfile.flush()
self.logfile.close()
self.opened = False
return 0
else:
return 1
|
<commit_before>import time
class Logger():
def __init__(self, name = "defaultLogFile"):
timestamp = time.strftime('%Y_%m_%d-%H_%M_%S')
self.name = "Logs/" + timestamp + "_" + name + ".txt"
try:
self.logfile = open(self.name, 'w')
self.opened = True
except:
self.opened = False
def save_line(self,data):
time_s = time.time()
time_ms = int(round((time_s - round(time_s))*1000))
timestamp = time.strftime(('%H_%M_%S'), time.localtime(time_s))+"_" +str(time_ms) + " : "
if(self.opened):
self.logfile.write(timestamp+data)
self.logfile.flush()
return 0,""
else:
return 1,str(timestamp+data)
def close(self):
if(self.opened):
self.logfile.flush()
self.logfile.close()
self.opened = False
return 0
else:
return 1
<commit_msg>Correct and simplify calculation of miliseconds
Signed-off-by: TeaPackCZ <a78d8486eff6e2cb08b2d9907449b92187b8e215@gmail.com><commit_after>
|
import time
class Logger():
def __init__(self, name = "defaultLogFile"):
timestamp = time.strftime('%Y_%m_%d-%H_%M_%S')
self.name = "Logs/" + timestamp + "_" + name + ".txt"
try:
self.logfile = open(self.name, 'w')
self.opened = True
except:
self.opened = False
def save_line(self,data):
time_s = time.time()
time_ms = int((time_s - int(time_s))*1000.0)
timestamp = time.strftime(('%H_%M_%S'), time.localtime(time_s))+"_" +str(time_ms) + " : "
if(self.opened):
self.logfile.write(timestamp+data)
self.logfile.flush()
return 0,""
else:
return 1,str(timestamp+data)
def close(self):
if(self.opened):
self.logfile.flush()
self.logfile.close()
self.opened = False
return 0
else:
return 1
|
import time
class Logger():
def __init__(self, name = "defaultLogFile"):
timestamp = time.strftime('%Y_%m_%d-%H_%M_%S')
self.name = "Logs/" + timestamp + "_" + name + ".txt"
try:
self.logfile = open(self.name, 'w')
self.opened = True
except:
self.opened = False
def save_line(self,data):
time_s = time.time()
time_ms = int(round((time_s - round(time_s))*1000))
timestamp = time.strftime(('%H_%M_%S'), time.localtime(time_s))+"_" +str(time_ms) + " : "
if(self.opened):
self.logfile.write(timestamp+data)
self.logfile.flush()
return 0,""
else:
return 1,str(timestamp+data)
def close(self):
if(self.opened):
self.logfile.flush()
self.logfile.close()
self.opened = False
return 0
else:
return 1
Correct and simplify calculation of miliseconds
Signed-off-by: TeaPackCZ <a78d8486eff6e2cb08b2d9907449b92187b8e215@gmail.com>import time
class Logger():
def __init__(self, name = "defaultLogFile"):
timestamp = time.strftime('%Y_%m_%d-%H_%M_%S')
self.name = "Logs/" + timestamp + "_" + name + ".txt"
try:
self.logfile = open(self.name, 'w')
self.opened = True
except:
self.opened = False
def save_line(self,data):
time_s = time.time()
time_ms = int((time_s - int(time_s))*1000.0)
timestamp = time.strftime(('%H_%M_%S'), time.localtime(time_s))+"_" +str(time_ms) + " : "
if(self.opened):
self.logfile.write(timestamp+data)
self.logfile.flush()
return 0,""
else:
return 1,str(timestamp+data)
def close(self):
if(self.opened):
self.logfile.flush()
self.logfile.close()
self.opened = False
return 0
else:
return 1
|
<commit_before>import time
class Logger():
def __init__(self, name = "defaultLogFile"):
timestamp = time.strftime('%Y_%m_%d-%H_%M_%S')
self.name = "Logs/" + timestamp + "_" + name + ".txt"
try:
self.logfile = open(self.name, 'w')
self.opened = True
except:
self.opened = False
def save_line(self,data):
time_s = time.time()
time_ms = int(round((time_s - round(time_s))*1000))
timestamp = time.strftime(('%H_%M_%S'), time.localtime(time_s))+"_" +str(time_ms) + " : "
if(self.opened):
self.logfile.write(timestamp+data)
self.logfile.flush()
return 0,""
else:
return 1,str(timestamp+data)
def close(self):
if(self.opened):
self.logfile.flush()
self.logfile.close()
self.opened = False
return 0
else:
return 1
<commit_msg>Correct and simplify calculation of miliseconds
Signed-off-by: TeaPackCZ <a78d8486eff6e2cb08b2d9907449b92187b8e215@gmail.com><commit_after>import time
class Logger():
def __init__(self, name = "defaultLogFile"):
timestamp = time.strftime('%Y_%m_%d-%H_%M_%S')
self.name = "Logs/" + timestamp + "_" + name + ".txt"
try:
self.logfile = open(self.name, 'w')
self.opened = True
except:
self.opened = False
def save_line(self,data):
time_s = time.time()
time_ms = int((time_s - int(time_s))*1000.0)
timestamp = time.strftime(('%H_%M_%S'), time.localtime(time_s))+"_" +str(time_ms) + " : "
if(self.opened):
self.logfile.write(timestamp+data)
self.logfile.flush()
return 0,""
else:
return 1,str(timestamp+data)
def close(self):
if(self.opened):
self.logfile.flush()
self.logfile.close()
self.opened = False
return 0
else:
return 1
|
fc636b5ae0db4190e0499c6bec58d40ad0d0afe4
|
cms/management/commands/subcommands/moderator.py
|
cms/management/commands/subcommands/moderator.py
|
# -*- coding: utf-8 -*-
from cms.management.commands.subcommands.base import SubcommandsCommand
from cms.models import CMSPlugin
from cms.models.pagemodel import Page
from django.core.management.base import NoArgsCommand
class ModeratorOnCommand(NoArgsCommand):
help = 'Turn moderation on, run AFTER upgrading to 2.4'
def handle_noargs(self, **options):
"""
Ensure that the public pages look the same as their draft versions.
This is done by checking the content of the public pages, and reverting
the draft version to look the same.
The second stage is to go through the draft pages and publish the ones
marked as published.
The end result should be that the public pages and their draft versions
have the same plugins listed. If both versions exist and have content,
the public page has precedence. Otherwise, the draft version is used.
"""
for page in Page.objects.public():
if CMSPlugin.objects.filter(placeholder__page=page).count():
page.revert()
for page in Page.objects.drafts().filter(published=True):
page.publish()
class ModeratorCommand(SubcommandsCommand):
help = 'Moderator utilities'
subcommands = {
'on': ModeratorOnCommand,
}
|
# -*- coding: utf-8 -*-
from cms.management.commands.subcommands.base import SubcommandsCommand
from cms.models import CMSPlugin
from cms.models.pagemodel import Page
from django.core.management.base import NoArgsCommand
class ModeratorOnCommand(NoArgsCommand):
help = 'Turn moderation on, run AFTER upgrading to 2.4'
def handle_noargs(self, **options):
"""
Ensure that the public pages look the same as their draft versions.
This is done by checking the content of the public pages, and reverting
the draft version to look the same.
The second stage is to go through the draft pages and publish the ones
marked as published.
The end result should be that the public pages and their draft versions
have the same plugins listed. If both versions exist and have content,
the public page has precedence. Otherwise, the draft version is used.
"""
for page in Page.objects.public():
if CMSPlugin.objects.filter(placeholder__page=page).count():
page.publisher_draft.revert()
for page in Page.objects.drafts().filter(published=True):
page.publish()
class ModeratorCommand(SubcommandsCommand):
help = 'Moderator utilities'
subcommands = {
'on': ModeratorOnCommand,
}
|
Apply revert to the draft page.
|
Apply revert to the draft page.
|
Python
|
bsd-3-clause
|
keimlink/django-cms,mkoistinen/django-cms,foobacca/django-cms,FinalAngel/django-cms,nimbis/django-cms,Jaccorot/django-cms,memnonila/django-cms,nostalgiaz/django-cms,jproffitt/django-cms,adaptivelogic/django-cms,Livefyre/django-cms,sznekol/django-cms,MagicSolutions/django-cms,benzkji/django-cms,iddqd1/django-cms,SinnerSchraderMobileMirrors/django-cms,isotoma/django-cms,vxsx/django-cms,SofiaReis/django-cms,intgr/django-cms,cyberintruder/django-cms,sznekol/django-cms,ScholzVolkmer/django-cms,wyg3958/django-cms,SmithsonianEnterprises/django-cms,dhorelik/django-cms,jrief/django-cms,petecummings/django-cms,timgraham/django-cms,jeffreylu9/django-cms,chmberl/django-cms,vad/django-cms,foobacca/django-cms,intgr/django-cms,ScholzVolkmer/django-cms,frnhr/django-cms,ojii/django-cms,rsalmaso/django-cms,intip/django-cms,ojii/django-cms,sephii/django-cms,benzkji/django-cms,josjevv/django-cms,bittner/django-cms,rsalmaso/django-cms,selecsosi/django-cms,jproffitt/django-cms,Vegasvikk/django-cms,youprofit/django-cms,frnhr/django-cms,irudayarajisawa/django-cms,kk9599/django-cms,foobacca/django-cms,takeshineshiro/django-cms,FinalAngel/django-cms,Jaccorot/django-cms,AlexProfi/django-cms,SachaMPS/django-cms,wuzhihui1123/django-cms,stefanfoulis/django-cms,jrclaramunt/django-cms,chkir/django-cms,vstoykov/django-cms,andyzsf/django-cms,SofiaReis/django-cms,jsma/django-cms,owers19856/django-cms,frnhr/django-cms,11craft/django-cms,benzkji/django-cms,Vegasvikk/django-cms,yakky/django-cms,nimbis/django-cms,stefanfoulis/django-cms,intgr/django-cms,rscnt/django-cms,pancentric/django-cms,iddqd1/django-cms,qnub/django-cms,robmagee/django-cms,astagi/django-cms,vxsx/django-cms,intip/django-cms,selecsosi/django-cms,jeffreylu9/django-cms,josjevv/django-cms,astagi/django-cms,DylannCordel/django-cms,rscnt/django-cms,360youlun/django-cms,mkoistinen/django-cms,intip/django-cms,Livefyre/django-cms,isotoma/django-cms,360youlun/django-cms,divio/django-cms,rryan/django-cms,memnonila/django-cms,liuyisiyisi/django-cms,SinnerSchraderMobileMirrors/django-cms,iddqd1/django-cms,datakortet/django-cms,sznekol/django-cms,frnhr/django-cms,jrief/django-cms,evildmp/django-cms,owers19856/django-cms,Livefyre/django-cms,evildmp/django-cms,isotoma/django-cms,robmagee/django-cms,SachaMPS/django-cms,leture/django-cms,czpython/django-cms,jproffitt/django-cms,pixbuffer/django-cms,youprofit/django-cms,yakky/django-cms,bittner/django-cms,czpython/django-cms,webu/django-cms,datakortet/django-cms,SachaMPS/django-cms,nostalgiaz/django-cms,astagi/django-cms,vad/django-cms,cyberintruder/django-cms,adaptivelogic/django-cms,jeffreylu9/django-cms,webu/django-cms,petecummings/django-cms,jrief/django-cms,360youlun/django-cms,rryan/django-cms,pancentric/django-cms,AlexProfi/django-cms,divio/django-cms,leture/django-cms,jproffitt/django-cms,stefanw/django-cms,qnub/django-cms,ScholzVolkmer/django-cms,adaptivelogic/django-cms,wuzhihui1123/django-cms,pancentric/django-cms,sephii/django-cms,timgraham/django-cms,datakortet/django-cms,dhorelik/django-cms,yakky/django-cms,donce/django-cms,keimlink/django-cms,andyzsf/django-cms,saintbird/django-cms,chmberl/django-cms,wuzhihui1123/django-cms,FinalAngel/django-cms,wyg3958/django-cms,farhaadila/django-cms,vstoykov/django-cms,wyg3958/django-cms,Livefyre/django-cms,leture/django-cms,youprofit/django-cms,stefanfoulis/django-cms,saintbird/django-cms,irudayarajisawa/django-cms,rsalmaso/django-cms,selecsosi/django-cms,evildmp/django-cms,stefanw/django-cms,netzkolchose/django-cms,wuzhihui1123/django-cms,sephii/django-cms,intip/django-cms,pixbuffer/django-cms,cyberintruder/django-cms,SmithsonianEnterprises/django-cms,benzkji/django-cms,stefanw/django-cms,chkir/django-cms,11craft/django-cms,jeffreylu9/django-cms,jsma/django-cms,vad/django-cms,stefanfoulis/django-cms,netzkolchose/django-cms,qnub/django-cms,rscnt/django-cms,divio/django-cms,MagicSolutions/django-cms,datakortet/django-cms,11craft/django-cms,chkir/django-cms,bittner/django-cms,webu/django-cms,czpython/django-cms,FinalAngel/django-cms,timgraham/django-cms,nostalgiaz/django-cms,11craft/django-cms,AlexProfi/django-cms,jsma/django-cms,czpython/django-cms,SmithsonianEnterprises/django-cms,chmberl/django-cms,philippze/django-cms,jrclaramunt/django-cms,robmagee/django-cms,vad/django-cms,rsalmaso/django-cms,netzkolchose/django-cms,jrief/django-cms,jsma/django-cms,nimbis/django-cms,kk9599/django-cms,takeshineshiro/django-cms,nimbis/django-cms,SinnerSchraderMobileMirrors/django-cms,pixbuffer/django-cms,intgr/django-cms,farhaadila/django-cms,vxsx/django-cms,andyzsf/django-cms,netzkolchose/django-cms,liuyisiyisi/django-cms,josjevv/django-cms,bittner/django-cms,saintbird/django-cms,owers19856/django-cms,donce/django-cms,Jaccorot/django-cms,memnonila/django-cms,sephii/django-cms,nostalgiaz/django-cms,philippze/django-cms,yakky/django-cms,stefanw/django-cms,farhaadila/django-cms,SofiaReis/django-cms,vxsx/django-cms,petecummings/django-cms,takeshineshiro/django-cms,jrclaramunt/django-cms,rryan/django-cms,MagicSolutions/django-cms,liuyisiyisi/django-cms,ojii/django-cms,mkoistinen/django-cms,isotoma/django-cms,mkoistinen/django-cms,andyzsf/django-cms,keimlink/django-cms,rryan/django-cms,donce/django-cms,divio/django-cms,dhorelik/django-cms,irudayarajisawa/django-cms,DylannCordel/django-cms,kk9599/django-cms,foobacca/django-cms,vstoykov/django-cms,evildmp/django-cms,philippze/django-cms,Vegasvikk/django-cms,selecsosi/django-cms,DylannCordel/django-cms
|
# -*- coding: utf-8 -*-
from cms.management.commands.subcommands.base import SubcommandsCommand
from cms.models import CMSPlugin
from cms.models.pagemodel import Page
from django.core.management.base import NoArgsCommand
class ModeratorOnCommand(NoArgsCommand):
help = 'Turn moderation on, run AFTER upgrading to 2.4'
def handle_noargs(self, **options):
"""
Ensure that the public pages look the same as their draft versions.
This is done by checking the content of the public pages, and reverting
the draft version to look the same.
The second stage is to go through the draft pages and publish the ones
marked as published.
The end result should be that the public pages and their draft versions
have the same plugins listed. If both versions exist and have content,
the public page has precedence. Otherwise, the draft version is used.
"""
for page in Page.objects.public():
if CMSPlugin.objects.filter(placeholder__page=page).count():
page.revert()
for page in Page.objects.drafts().filter(published=True):
page.publish()
class ModeratorCommand(SubcommandsCommand):
help = 'Moderator utilities'
subcommands = {
'on': ModeratorOnCommand,
}
Apply revert to the draft page.
|
# -*- coding: utf-8 -*-
from cms.management.commands.subcommands.base import SubcommandsCommand
from cms.models import CMSPlugin
from cms.models.pagemodel import Page
from django.core.management.base import NoArgsCommand
class ModeratorOnCommand(NoArgsCommand):
help = 'Turn moderation on, run AFTER upgrading to 2.4'
def handle_noargs(self, **options):
"""
Ensure that the public pages look the same as their draft versions.
This is done by checking the content of the public pages, and reverting
the draft version to look the same.
The second stage is to go through the draft pages and publish the ones
marked as published.
The end result should be that the public pages and their draft versions
have the same plugins listed. If both versions exist and have content,
the public page has precedence. Otherwise, the draft version is used.
"""
for page in Page.objects.public():
if CMSPlugin.objects.filter(placeholder__page=page).count():
page.publisher_draft.revert()
for page in Page.objects.drafts().filter(published=True):
page.publish()
class ModeratorCommand(SubcommandsCommand):
help = 'Moderator utilities'
subcommands = {
'on': ModeratorOnCommand,
}
|
<commit_before># -*- coding: utf-8 -*-
from cms.management.commands.subcommands.base import SubcommandsCommand
from cms.models import CMSPlugin
from cms.models.pagemodel import Page
from django.core.management.base import NoArgsCommand
class ModeratorOnCommand(NoArgsCommand):
help = 'Turn moderation on, run AFTER upgrading to 2.4'
def handle_noargs(self, **options):
"""
Ensure that the public pages look the same as their draft versions.
This is done by checking the content of the public pages, and reverting
the draft version to look the same.
The second stage is to go through the draft pages and publish the ones
marked as published.
The end result should be that the public pages and their draft versions
have the same plugins listed. If both versions exist and have content,
the public page has precedence. Otherwise, the draft version is used.
"""
for page in Page.objects.public():
if CMSPlugin.objects.filter(placeholder__page=page).count():
page.revert()
for page in Page.objects.drafts().filter(published=True):
page.publish()
class ModeratorCommand(SubcommandsCommand):
help = 'Moderator utilities'
subcommands = {
'on': ModeratorOnCommand,
}
<commit_msg>Apply revert to the draft page.<commit_after>
|
# -*- coding: utf-8 -*-
from cms.management.commands.subcommands.base import SubcommandsCommand
from cms.models import CMSPlugin
from cms.models.pagemodel import Page
from django.core.management.base import NoArgsCommand
class ModeratorOnCommand(NoArgsCommand):
help = 'Turn moderation on, run AFTER upgrading to 2.4'
def handle_noargs(self, **options):
"""
Ensure that the public pages look the same as their draft versions.
This is done by checking the content of the public pages, and reverting
the draft version to look the same.
The second stage is to go through the draft pages and publish the ones
marked as published.
The end result should be that the public pages and their draft versions
have the same plugins listed. If both versions exist and have content,
the public page has precedence. Otherwise, the draft version is used.
"""
for page in Page.objects.public():
if CMSPlugin.objects.filter(placeholder__page=page).count():
page.publisher_draft.revert()
for page in Page.objects.drafts().filter(published=True):
page.publish()
class ModeratorCommand(SubcommandsCommand):
help = 'Moderator utilities'
subcommands = {
'on': ModeratorOnCommand,
}
|
# -*- coding: utf-8 -*-
from cms.management.commands.subcommands.base import SubcommandsCommand
from cms.models import CMSPlugin
from cms.models.pagemodel import Page
from django.core.management.base import NoArgsCommand
class ModeratorOnCommand(NoArgsCommand):
help = 'Turn moderation on, run AFTER upgrading to 2.4'
def handle_noargs(self, **options):
"""
Ensure that the public pages look the same as their draft versions.
This is done by checking the content of the public pages, and reverting
the draft version to look the same.
The second stage is to go through the draft pages and publish the ones
marked as published.
The end result should be that the public pages and their draft versions
have the same plugins listed. If both versions exist and have content,
the public page has precedence. Otherwise, the draft version is used.
"""
for page in Page.objects.public():
if CMSPlugin.objects.filter(placeholder__page=page).count():
page.revert()
for page in Page.objects.drafts().filter(published=True):
page.publish()
class ModeratorCommand(SubcommandsCommand):
help = 'Moderator utilities'
subcommands = {
'on': ModeratorOnCommand,
}
Apply revert to the draft page.# -*- coding: utf-8 -*-
from cms.management.commands.subcommands.base import SubcommandsCommand
from cms.models import CMSPlugin
from cms.models.pagemodel import Page
from django.core.management.base import NoArgsCommand
class ModeratorOnCommand(NoArgsCommand):
help = 'Turn moderation on, run AFTER upgrading to 2.4'
def handle_noargs(self, **options):
"""
Ensure that the public pages look the same as their draft versions.
This is done by checking the content of the public pages, and reverting
the draft version to look the same.
The second stage is to go through the draft pages and publish the ones
marked as published.
The end result should be that the public pages and their draft versions
have the same plugins listed. If both versions exist and have content,
the public page has precedence. Otherwise, the draft version is used.
"""
for page in Page.objects.public():
if CMSPlugin.objects.filter(placeholder__page=page).count():
page.publisher_draft.revert()
for page in Page.objects.drafts().filter(published=True):
page.publish()
class ModeratorCommand(SubcommandsCommand):
help = 'Moderator utilities'
subcommands = {
'on': ModeratorOnCommand,
}
|
<commit_before># -*- coding: utf-8 -*-
from cms.management.commands.subcommands.base import SubcommandsCommand
from cms.models import CMSPlugin
from cms.models.pagemodel import Page
from django.core.management.base import NoArgsCommand
class ModeratorOnCommand(NoArgsCommand):
help = 'Turn moderation on, run AFTER upgrading to 2.4'
def handle_noargs(self, **options):
"""
Ensure that the public pages look the same as their draft versions.
This is done by checking the content of the public pages, and reverting
the draft version to look the same.
The second stage is to go through the draft pages and publish the ones
marked as published.
The end result should be that the public pages and their draft versions
have the same plugins listed. If both versions exist and have content,
the public page has precedence. Otherwise, the draft version is used.
"""
for page in Page.objects.public():
if CMSPlugin.objects.filter(placeholder__page=page).count():
page.revert()
for page in Page.objects.drafts().filter(published=True):
page.publish()
class ModeratorCommand(SubcommandsCommand):
help = 'Moderator utilities'
subcommands = {
'on': ModeratorOnCommand,
}
<commit_msg>Apply revert to the draft page.<commit_after># -*- coding: utf-8 -*-
from cms.management.commands.subcommands.base import SubcommandsCommand
from cms.models import CMSPlugin
from cms.models.pagemodel import Page
from django.core.management.base import NoArgsCommand
class ModeratorOnCommand(NoArgsCommand):
help = 'Turn moderation on, run AFTER upgrading to 2.4'
def handle_noargs(self, **options):
"""
Ensure that the public pages look the same as their draft versions.
This is done by checking the content of the public pages, and reverting
the draft version to look the same.
The second stage is to go through the draft pages and publish the ones
marked as published.
The end result should be that the public pages and their draft versions
have the same plugins listed. If both versions exist and have content,
the public page has precedence. Otherwise, the draft version is used.
"""
for page in Page.objects.public():
if CMSPlugin.objects.filter(placeholder__page=page).count():
page.publisher_draft.revert()
for page in Page.objects.drafts().filter(published=True):
page.publish()
class ModeratorCommand(SubcommandsCommand):
help = 'Moderator utilities'
subcommands = {
'on': ModeratorOnCommand,
}
|
0fdaff5b0715722de7590aa2b57266291bafd000
|
umibukela/models.py
|
umibukela/models.py
|
import os
from django.db import models
# ------------------------------------------------------------------------------
# General utilities
# ------------------------------------------------------------------------------
def image_filename(instance, filename):
""" Make S3 image filenames
"""
return 'images/%s/%s' % (instance.id, os.path.basename(filename))
# ------------------------------------------------------------------------------
# Models
# ------------------------------------------------------------------------------
class Partner(models.Model):
short_name = models.CharField(max_length=200)
full_name = models.CharField(max_length=200)
physical_address = models.CharField(max_length=200)
contact_person = models.CharField(max_length=200)
telephone = models.CharField(max_length=200)
email_address = models.EmailField(max_length=200)
intro_title = models.CharField(max_length=200)
intro_statement = models.TextField(max_length=200)
intro_image = models.ImageField(upload_to=image_filename, blank=True, null=True)
context_quote = models.CharField(max_length=200)
context_statement = models.TextField(max_length=200)
context_image = models.ImageField(upload_to=image_filename, blank=True, null=True)
|
import os
import uuid
from django.db import models
# ------------------------------------------------------------------------------
# General utilities
# ------------------------------------------------------------------------------
def image_filename(instance, filename):
""" Make image filenames
"""
return 'images/%s_%s' % (uuid.uuid4(), os.path.basename(filename))
# ------------------------------------------------------------------------------
# Models
# ------------------------------------------------------------------------------
class Partner(models.Model):
short_name = models.CharField(max_length=200)
full_name = models.CharField(max_length=200)
physical_address = models.CharField(max_length=200)
contact_person = models.CharField(max_length=200)
telephone = models.CharField(max_length=200)
email_address = models.EmailField(max_length=200)
intro_title = models.CharField(max_length=200)
intro_statement = models.TextField(max_length=200)
intro_image = models.ImageField(upload_to=image_filename, blank=True, null=True)
context_quote = models.CharField(max_length=200)
context_statement = models.TextField(max_length=200)
context_image = models.ImageField(upload_to=image_filename, blank=True, null=True)
|
Remove image name dependency on object ID
|
Remove image name dependency on object ID
|
Python
|
mit
|
Code4SA/umibukela,Code4SA/umibukela,Code4SA/umibukela,Code4SA/umibukela
|
import os
from django.db import models
# ------------------------------------------------------------------------------
# General utilities
# ------------------------------------------------------------------------------
def image_filename(instance, filename):
""" Make S3 image filenames
"""
return 'images/%s/%s' % (instance.id, os.path.basename(filename))
# ------------------------------------------------------------------------------
# Models
# ------------------------------------------------------------------------------
class Partner(models.Model):
short_name = models.CharField(max_length=200)
full_name = models.CharField(max_length=200)
physical_address = models.CharField(max_length=200)
contact_person = models.CharField(max_length=200)
telephone = models.CharField(max_length=200)
email_address = models.EmailField(max_length=200)
intro_title = models.CharField(max_length=200)
intro_statement = models.TextField(max_length=200)
intro_image = models.ImageField(upload_to=image_filename, blank=True, null=True)
context_quote = models.CharField(max_length=200)
context_statement = models.TextField(max_length=200)
context_image = models.ImageField(upload_to=image_filename, blank=True, null=True)
Remove image name dependency on object ID
|
import os
import uuid
from django.db import models
# ------------------------------------------------------------------------------
# General utilities
# ------------------------------------------------------------------------------
def image_filename(instance, filename):
""" Make image filenames
"""
return 'images/%s_%s' % (uuid.uuid4(), os.path.basename(filename))
# ------------------------------------------------------------------------------
# Models
# ------------------------------------------------------------------------------
class Partner(models.Model):
short_name = models.CharField(max_length=200)
full_name = models.CharField(max_length=200)
physical_address = models.CharField(max_length=200)
contact_person = models.CharField(max_length=200)
telephone = models.CharField(max_length=200)
email_address = models.EmailField(max_length=200)
intro_title = models.CharField(max_length=200)
intro_statement = models.TextField(max_length=200)
intro_image = models.ImageField(upload_to=image_filename, blank=True, null=True)
context_quote = models.CharField(max_length=200)
context_statement = models.TextField(max_length=200)
context_image = models.ImageField(upload_to=image_filename, blank=True, null=True)
|
<commit_before>import os
from django.db import models
# ------------------------------------------------------------------------------
# General utilities
# ------------------------------------------------------------------------------
def image_filename(instance, filename):
""" Make S3 image filenames
"""
return 'images/%s/%s' % (instance.id, os.path.basename(filename))
# ------------------------------------------------------------------------------
# Models
# ------------------------------------------------------------------------------
class Partner(models.Model):
short_name = models.CharField(max_length=200)
full_name = models.CharField(max_length=200)
physical_address = models.CharField(max_length=200)
contact_person = models.CharField(max_length=200)
telephone = models.CharField(max_length=200)
email_address = models.EmailField(max_length=200)
intro_title = models.CharField(max_length=200)
intro_statement = models.TextField(max_length=200)
intro_image = models.ImageField(upload_to=image_filename, blank=True, null=True)
context_quote = models.CharField(max_length=200)
context_statement = models.TextField(max_length=200)
context_image = models.ImageField(upload_to=image_filename, blank=True, null=True)
<commit_msg>Remove image name dependency on object ID<commit_after>
|
import os
import uuid
from django.db import models
# ------------------------------------------------------------------------------
# General utilities
# ------------------------------------------------------------------------------
def image_filename(instance, filename):
""" Make image filenames
"""
return 'images/%s_%s' % (uuid.uuid4(), os.path.basename(filename))
# ------------------------------------------------------------------------------
# Models
# ------------------------------------------------------------------------------
class Partner(models.Model):
short_name = models.CharField(max_length=200)
full_name = models.CharField(max_length=200)
physical_address = models.CharField(max_length=200)
contact_person = models.CharField(max_length=200)
telephone = models.CharField(max_length=200)
email_address = models.EmailField(max_length=200)
intro_title = models.CharField(max_length=200)
intro_statement = models.TextField(max_length=200)
intro_image = models.ImageField(upload_to=image_filename, blank=True, null=True)
context_quote = models.CharField(max_length=200)
context_statement = models.TextField(max_length=200)
context_image = models.ImageField(upload_to=image_filename, blank=True, null=True)
|
import os
from django.db import models
# ------------------------------------------------------------------------------
# General utilities
# ------------------------------------------------------------------------------
def image_filename(instance, filename):
""" Make S3 image filenames
"""
return 'images/%s/%s' % (instance.id, os.path.basename(filename))
# ------------------------------------------------------------------------------
# Models
# ------------------------------------------------------------------------------
class Partner(models.Model):
short_name = models.CharField(max_length=200)
full_name = models.CharField(max_length=200)
physical_address = models.CharField(max_length=200)
contact_person = models.CharField(max_length=200)
telephone = models.CharField(max_length=200)
email_address = models.EmailField(max_length=200)
intro_title = models.CharField(max_length=200)
intro_statement = models.TextField(max_length=200)
intro_image = models.ImageField(upload_to=image_filename, blank=True, null=True)
context_quote = models.CharField(max_length=200)
context_statement = models.TextField(max_length=200)
context_image = models.ImageField(upload_to=image_filename, blank=True, null=True)
Remove image name dependency on object IDimport os
import uuid
from django.db import models
# ------------------------------------------------------------------------------
# General utilities
# ------------------------------------------------------------------------------
def image_filename(instance, filename):
""" Make image filenames
"""
return 'images/%s_%s' % (uuid.uuid4(), os.path.basename(filename))
# ------------------------------------------------------------------------------
# Models
# ------------------------------------------------------------------------------
class Partner(models.Model):
short_name = models.CharField(max_length=200)
full_name = models.CharField(max_length=200)
physical_address = models.CharField(max_length=200)
contact_person = models.CharField(max_length=200)
telephone = models.CharField(max_length=200)
email_address = models.EmailField(max_length=200)
intro_title = models.CharField(max_length=200)
intro_statement = models.TextField(max_length=200)
intro_image = models.ImageField(upload_to=image_filename, blank=True, null=True)
context_quote = models.CharField(max_length=200)
context_statement = models.TextField(max_length=200)
context_image = models.ImageField(upload_to=image_filename, blank=True, null=True)
|
<commit_before>import os
from django.db import models
# ------------------------------------------------------------------------------
# General utilities
# ------------------------------------------------------------------------------
def image_filename(instance, filename):
""" Make S3 image filenames
"""
return 'images/%s/%s' % (instance.id, os.path.basename(filename))
# ------------------------------------------------------------------------------
# Models
# ------------------------------------------------------------------------------
class Partner(models.Model):
short_name = models.CharField(max_length=200)
full_name = models.CharField(max_length=200)
physical_address = models.CharField(max_length=200)
contact_person = models.CharField(max_length=200)
telephone = models.CharField(max_length=200)
email_address = models.EmailField(max_length=200)
intro_title = models.CharField(max_length=200)
intro_statement = models.TextField(max_length=200)
intro_image = models.ImageField(upload_to=image_filename, blank=True, null=True)
context_quote = models.CharField(max_length=200)
context_statement = models.TextField(max_length=200)
context_image = models.ImageField(upload_to=image_filename, blank=True, null=True)
<commit_msg>Remove image name dependency on object ID<commit_after>import os
import uuid
from django.db import models
# ------------------------------------------------------------------------------
# General utilities
# ------------------------------------------------------------------------------
def image_filename(instance, filename):
""" Make image filenames
"""
return 'images/%s_%s' % (uuid.uuid4(), os.path.basename(filename))
# ------------------------------------------------------------------------------
# Models
# ------------------------------------------------------------------------------
class Partner(models.Model):
short_name = models.CharField(max_length=200)
full_name = models.CharField(max_length=200)
physical_address = models.CharField(max_length=200)
contact_person = models.CharField(max_length=200)
telephone = models.CharField(max_length=200)
email_address = models.EmailField(max_length=200)
intro_title = models.CharField(max_length=200)
intro_statement = models.TextField(max_length=200)
intro_image = models.ImageField(upload_to=image_filename, blank=True, null=True)
context_quote = models.CharField(max_length=200)
context_statement = models.TextField(max_length=200)
context_image = models.ImageField(upload_to=image_filename, blank=True, null=True)
|
5afe329b801d6442d3d645f8ba2e591a71e63f85
|
04.py
|
04.py
|
#! /usr/bin/env python3
def main():
pass
if __name__ == '__main__':
main()
|
#! /usr/bin/env python3
def main():
pass
if __name__ == '__main__':
main()
|
Test commit to see if commit signing on Windows works.
|
Test commit to see if commit signing on Windows works.
|
Python
|
mit
|
janhenke/project-euler
|
#! /usr/bin/env python3
def main():
pass
if __name__ == '__main__':
main()Test commit to see if commit signing on Windows works.
|
#! /usr/bin/env python3
def main():
pass
if __name__ == '__main__':
main()
|
<commit_before>#! /usr/bin/env python3
def main():
pass
if __name__ == '__main__':
main()<commit_msg>Test commit to see if commit signing on Windows works.<commit_after>
|
#! /usr/bin/env python3
def main():
pass
if __name__ == '__main__':
main()
|
#! /usr/bin/env python3
def main():
pass
if __name__ == '__main__':
main()Test commit to see if commit signing on Windows works.#! /usr/bin/env python3
def main():
pass
if __name__ == '__main__':
main()
|
<commit_before>#! /usr/bin/env python3
def main():
pass
if __name__ == '__main__':
main()<commit_msg>Test commit to see if commit signing on Windows works.<commit_after>#! /usr/bin/env python3
def main():
pass
if __name__ == '__main__':
main()
|
8897defe3b11a6518d3ad1148a5ee9321bfa176c
|
froniusLogger.py
|
froniusLogger.py
|
"""
Logs key data from a Fronius inverter to a CSV file for later analysis.
peter.marks@pobox.com
"""
import requests
import json
import datetime
import time
# Set this to the IP address of your inverter
host = "192.168.0.112"
sample_seconds = 60 # how many seconds between samples
def main():
print("started")
while True:
watts = watts_generated()
now = datetime.datetime.now()
line = "%s\t%s\n" % (now, watts)
#print(line)
write_to_logfile(line)
time.sleep(sample_seconds)
def write_to_logfile(line):
today = time.strftime("%Y_%m_%d")
file_name = today + ".csv"
out_file = open(file_name, "a")
out_file.write(line)
out_file.close()
def watts_generated():
url = "http://" + host + "/solar_api/v1/GetInverterRealtimeData.cgi?Scope=System"
r = requests.get(url, timeout=60)
json_data = r.json()
result = json_data["Body"]["Data"]["PAC"]["Values"]["1"]
return result
if __name__ == "__main__":
main()
|
"""
Logs key data from a Fronius inverter to a CSV file for later analysis.
peter.marks@pobox.com
"""
import requests
import json
import datetime
import time
# Set this to the IP address of your inverter
host = "192.168.0.112"
sample_seconds = 60 # how many seconds between samples, set to zero to run once and exit
def main():
print("started")
while True:
watts = watts_generated()
now = time.strftime("%H:%M:%S")
line = "%s\t%s\n" % (now, watts)
# print(line)
write_to_logfile(line)
if sample_seconds > 0:
time.sleep(sample_seconds)
else:
return
def write_to_logfile(line):
today = time.strftime("%Y_%m_%d")
file_name = today + ".csv"
out_file = open(file_name, "a")
out_file.write(line)
out_file.close()
def watts_generated():
url = "http://" + host + "/solar_api/v1/GetInverterRealtimeData.cgi?Scope=System"
r = requests.get(url, timeout=60)
json_data = r.json()
result = json_data["Body"]["Data"]["PAC"]["Values"]["1"]
return result
if __name__ == "__main__":
main()
|
Make the timestamp more sane. Add the ability to run once and exit for use with cron.
|
Make the timestamp more sane.
Add the ability to run once and exit for use with cron.
|
Python
|
apache-2.0
|
peterbmarks/froniusLogger,peterbmarks/froniusLogger
|
"""
Logs key data from a Fronius inverter to a CSV file for later analysis.
peter.marks@pobox.com
"""
import requests
import json
import datetime
import time
# Set this to the IP address of your inverter
host = "192.168.0.112"
sample_seconds = 60 # how many seconds between samples
def main():
print("started")
while True:
watts = watts_generated()
now = datetime.datetime.now()
line = "%s\t%s\n" % (now, watts)
#print(line)
write_to_logfile(line)
time.sleep(sample_seconds)
def write_to_logfile(line):
today = time.strftime("%Y_%m_%d")
file_name = today + ".csv"
out_file = open(file_name, "a")
out_file.write(line)
out_file.close()
def watts_generated():
url = "http://" + host + "/solar_api/v1/GetInverterRealtimeData.cgi?Scope=System"
r = requests.get(url, timeout=60)
json_data = r.json()
result = json_data["Body"]["Data"]["PAC"]["Values"]["1"]
return result
if __name__ == "__main__":
main()
Make the timestamp more sane.
Add the ability to run once and exit for use with cron.
|
"""
Logs key data from a Fronius inverter to a CSV file for later analysis.
peter.marks@pobox.com
"""
import requests
import json
import datetime
import time
# Set this to the IP address of your inverter
host = "192.168.0.112"
sample_seconds = 60 # how many seconds between samples, set to zero to run once and exit
def main():
print("started")
while True:
watts = watts_generated()
now = time.strftime("%H:%M:%S")
line = "%s\t%s\n" % (now, watts)
# print(line)
write_to_logfile(line)
if sample_seconds > 0:
time.sleep(sample_seconds)
else:
return
def write_to_logfile(line):
today = time.strftime("%Y_%m_%d")
file_name = today + ".csv"
out_file = open(file_name, "a")
out_file.write(line)
out_file.close()
def watts_generated():
url = "http://" + host + "/solar_api/v1/GetInverterRealtimeData.cgi?Scope=System"
r = requests.get(url, timeout=60)
json_data = r.json()
result = json_data["Body"]["Data"]["PAC"]["Values"]["1"]
return result
if __name__ == "__main__":
main()
|
<commit_before>"""
Logs key data from a Fronius inverter to a CSV file for later analysis.
peter.marks@pobox.com
"""
import requests
import json
import datetime
import time
# Set this to the IP address of your inverter
host = "192.168.0.112"
sample_seconds = 60 # how many seconds between samples
def main():
print("started")
while True:
watts = watts_generated()
now = datetime.datetime.now()
line = "%s\t%s\n" % (now, watts)
#print(line)
write_to_logfile(line)
time.sleep(sample_seconds)
def write_to_logfile(line):
today = time.strftime("%Y_%m_%d")
file_name = today + ".csv"
out_file = open(file_name, "a")
out_file.write(line)
out_file.close()
def watts_generated():
url = "http://" + host + "/solar_api/v1/GetInverterRealtimeData.cgi?Scope=System"
r = requests.get(url, timeout=60)
json_data = r.json()
result = json_data["Body"]["Data"]["PAC"]["Values"]["1"]
return result
if __name__ == "__main__":
main()
<commit_msg>Make the timestamp more sane.
Add the ability to run once and exit for use with cron.<commit_after>
|
"""
Logs key data from a Fronius inverter to a CSV file for later analysis.
peter.marks@pobox.com
"""
import requests
import json
import datetime
import time
# Set this to the IP address of your inverter
host = "192.168.0.112"
sample_seconds = 60 # how many seconds between samples, set to zero to run once and exit
def main():
print("started")
while True:
watts = watts_generated()
now = time.strftime("%H:%M:%S")
line = "%s\t%s\n" % (now, watts)
# print(line)
write_to_logfile(line)
if sample_seconds > 0:
time.sleep(sample_seconds)
else:
return
def write_to_logfile(line):
today = time.strftime("%Y_%m_%d")
file_name = today + ".csv"
out_file = open(file_name, "a")
out_file.write(line)
out_file.close()
def watts_generated():
url = "http://" + host + "/solar_api/v1/GetInverterRealtimeData.cgi?Scope=System"
r = requests.get(url, timeout=60)
json_data = r.json()
result = json_data["Body"]["Data"]["PAC"]["Values"]["1"]
return result
if __name__ == "__main__":
main()
|
"""
Logs key data from a Fronius inverter to a CSV file for later analysis.
peter.marks@pobox.com
"""
import requests
import json
import datetime
import time
# Set this to the IP address of your inverter
host = "192.168.0.112"
sample_seconds = 60 # how many seconds between samples
def main():
print("started")
while True:
watts = watts_generated()
now = datetime.datetime.now()
line = "%s\t%s\n" % (now, watts)
#print(line)
write_to_logfile(line)
time.sleep(sample_seconds)
def write_to_logfile(line):
today = time.strftime("%Y_%m_%d")
file_name = today + ".csv"
out_file = open(file_name, "a")
out_file.write(line)
out_file.close()
def watts_generated():
url = "http://" + host + "/solar_api/v1/GetInverterRealtimeData.cgi?Scope=System"
r = requests.get(url, timeout=60)
json_data = r.json()
result = json_data["Body"]["Data"]["PAC"]["Values"]["1"]
return result
if __name__ == "__main__":
main()
Make the timestamp more sane.
Add the ability to run once and exit for use with cron."""
Logs key data from a Fronius inverter to a CSV file for later analysis.
peter.marks@pobox.com
"""
import requests
import json
import datetime
import time
# Set this to the IP address of your inverter
host = "192.168.0.112"
sample_seconds = 60 # how many seconds between samples, set to zero to run once and exit
def main():
print("started")
while True:
watts = watts_generated()
now = time.strftime("%H:%M:%S")
line = "%s\t%s\n" % (now, watts)
# print(line)
write_to_logfile(line)
if sample_seconds > 0:
time.sleep(sample_seconds)
else:
return
def write_to_logfile(line):
today = time.strftime("%Y_%m_%d")
file_name = today + ".csv"
out_file = open(file_name, "a")
out_file.write(line)
out_file.close()
def watts_generated():
url = "http://" + host + "/solar_api/v1/GetInverterRealtimeData.cgi?Scope=System"
r = requests.get(url, timeout=60)
json_data = r.json()
result = json_data["Body"]["Data"]["PAC"]["Values"]["1"]
return result
if __name__ == "__main__":
main()
|
<commit_before>"""
Logs key data from a Fronius inverter to a CSV file for later analysis.
peter.marks@pobox.com
"""
import requests
import json
import datetime
import time
# Set this to the IP address of your inverter
host = "192.168.0.112"
sample_seconds = 60 # how many seconds between samples
def main():
print("started")
while True:
watts = watts_generated()
now = datetime.datetime.now()
line = "%s\t%s\n" % (now, watts)
#print(line)
write_to_logfile(line)
time.sleep(sample_seconds)
def write_to_logfile(line):
today = time.strftime("%Y_%m_%d")
file_name = today + ".csv"
out_file = open(file_name, "a")
out_file.write(line)
out_file.close()
def watts_generated():
url = "http://" + host + "/solar_api/v1/GetInverterRealtimeData.cgi?Scope=System"
r = requests.get(url, timeout=60)
json_data = r.json()
result = json_data["Body"]["Data"]["PAC"]["Values"]["1"]
return result
if __name__ == "__main__":
main()
<commit_msg>Make the timestamp more sane.
Add the ability to run once and exit for use with cron.<commit_after>"""
Logs key data from a Fronius inverter to a CSV file for later analysis.
peter.marks@pobox.com
"""
import requests
import json
import datetime
import time
# Set this to the IP address of your inverter
host = "192.168.0.112"
sample_seconds = 60 # how many seconds between samples, set to zero to run once and exit
def main():
print("started")
while True:
watts = watts_generated()
now = time.strftime("%H:%M:%S")
line = "%s\t%s\n" % (now, watts)
# print(line)
write_to_logfile(line)
if sample_seconds > 0:
time.sleep(sample_seconds)
else:
return
def write_to_logfile(line):
today = time.strftime("%Y_%m_%d")
file_name = today + ".csv"
out_file = open(file_name, "a")
out_file.write(line)
out_file.close()
def watts_generated():
url = "http://" + host + "/solar_api/v1/GetInverterRealtimeData.cgi?Scope=System"
r = requests.get(url, timeout=60)
json_data = r.json()
result = json_data["Body"]["Data"]["PAC"]["Values"]["1"]
return result
if __name__ == "__main__":
main()
|
ce644b55ee72790d111435b81fb76a2ea15913c5
|
gabbi/fixture.py
|
gabbi/fixture.py
|
"""Manage fixtures for gabbi at the test file level."""
def start_fixture(fixture_class):
"""Create the fixture class and start it."""
fixture = fixture_class()
fixture.start()
def stop_fixture(fixture_class):
"""Create the fixture class and stop it."""
fixture = fixture_class()
fixture.stop()
class GabbiFixture(object):
"""A singleton of a fixture."""
_instance = None
_started = False
_halted = False
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(GabbiFixture, cls).__new__(cls)
return cls._instance
def start(self):
if not self._started and not self._halted:
self._started = True
self.start_fixture()
def start_fixture(self):
pass
def stop(self):
if self._started:
self.stop_fixture()
self._started = False
self._halted = True
def stop_fixture(self):
pass
|
"""Manage fixtures for gabbi at the test file level."""
def start_fixture(fixture_class):
"""Create the fixture class and start it."""
fixture = fixture_class()
fixture.start()
def stop_fixture(fixture_class):
"""Re-Create the fixture class and stop it."""
fixture = fixture_class()
fixture.stop()
class GabbiFixtureError(Exception):
"""Generic exception for GabbiFixture."""
pass
class GabbiFixture(object):
"""A singleton of a fixture.
Subclasses must implement start_fixture and stop_fixture, each of which
contain the logic for stopping and starting whatever the fixture is.
What a fixture is is left as an exercise for the implementor.
A singleton is used so as to avoid in process duplication of the same
fixture. For environments where concurrent testing will be used, the
fixture should guard against collisions by uniquifying filenames,
database names and other external resources.
If calling code attempts to start an already started fixture, an Exception
will be raised: GabbiFixtureError.
"""
_instance = None
_started = False
def __new__(cls, *args, **kwargs):
"""Create the new instance or return an existing one."""
if not cls._instance:
cls._instance = super(GabbiFixture, cls).__new__(cls)
return cls._instance
def start(self):
"""Request that the fixture be started."""
if not self._started:
self.start_fixture()
self._started = True
else:
raise GabbiFixtureError('fixture %s already started' % self)
def start_fixture(self):
"""Implement the actual workings of starting the fixture here."""
pass
def stop(self):
"""Request that the fixture be stopped."""
if self._started:
self.stop_fixture()
self._started = False
def stop_fixture(self):
"""Implement the actual workings of stopping the fixture here."""
pass
|
Add some docs to GabbiFixture
|
Add some docs to GabbiFixture
|
Python
|
apache-2.0
|
FND/gabbi,jasonamyers/gabbi,jasonamyers/gabbi,FND/gabbi
|
"""Manage fixtures for gabbi at the test file level."""
def start_fixture(fixture_class):
"""Create the fixture class and start it."""
fixture = fixture_class()
fixture.start()
def stop_fixture(fixture_class):
"""Create the fixture class and stop it."""
fixture = fixture_class()
fixture.stop()
class GabbiFixture(object):
"""A singleton of a fixture."""
_instance = None
_started = False
_halted = False
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(GabbiFixture, cls).__new__(cls)
return cls._instance
def start(self):
if not self._started and not self._halted:
self._started = True
self.start_fixture()
def start_fixture(self):
pass
def stop(self):
if self._started:
self.stop_fixture()
self._started = False
self._halted = True
def stop_fixture(self):
pass
Add some docs to GabbiFixture
|
"""Manage fixtures for gabbi at the test file level."""
def start_fixture(fixture_class):
"""Create the fixture class and start it."""
fixture = fixture_class()
fixture.start()
def stop_fixture(fixture_class):
"""Re-Create the fixture class and stop it."""
fixture = fixture_class()
fixture.stop()
class GabbiFixtureError(Exception):
"""Generic exception for GabbiFixture."""
pass
class GabbiFixture(object):
"""A singleton of a fixture.
Subclasses must implement start_fixture and stop_fixture, each of which
contain the logic for stopping and starting whatever the fixture is.
What a fixture is is left as an exercise for the implementor.
A singleton is used so as to avoid in process duplication of the same
fixture. For environments where concurrent testing will be used, the
fixture should guard against collisions by uniquifying filenames,
database names and other external resources.
If calling code attempts to start an already started fixture, an Exception
will be raised: GabbiFixtureError.
"""
_instance = None
_started = False
def __new__(cls, *args, **kwargs):
"""Create the new instance or return an existing one."""
if not cls._instance:
cls._instance = super(GabbiFixture, cls).__new__(cls)
return cls._instance
def start(self):
"""Request that the fixture be started."""
if not self._started:
self.start_fixture()
self._started = True
else:
raise GabbiFixtureError('fixture %s already started' % self)
def start_fixture(self):
"""Implement the actual workings of starting the fixture here."""
pass
def stop(self):
"""Request that the fixture be stopped."""
if self._started:
self.stop_fixture()
self._started = False
def stop_fixture(self):
"""Implement the actual workings of stopping the fixture here."""
pass
|
<commit_before>"""Manage fixtures for gabbi at the test file level."""
def start_fixture(fixture_class):
"""Create the fixture class and start it."""
fixture = fixture_class()
fixture.start()
def stop_fixture(fixture_class):
"""Create the fixture class and stop it."""
fixture = fixture_class()
fixture.stop()
class GabbiFixture(object):
"""A singleton of a fixture."""
_instance = None
_started = False
_halted = False
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(GabbiFixture, cls).__new__(cls)
return cls._instance
def start(self):
if not self._started and not self._halted:
self._started = True
self.start_fixture()
def start_fixture(self):
pass
def stop(self):
if self._started:
self.stop_fixture()
self._started = False
self._halted = True
def stop_fixture(self):
pass
<commit_msg>Add some docs to GabbiFixture<commit_after>
|
"""Manage fixtures for gabbi at the test file level."""
def start_fixture(fixture_class):
"""Create the fixture class and start it."""
fixture = fixture_class()
fixture.start()
def stop_fixture(fixture_class):
"""Re-Create the fixture class and stop it."""
fixture = fixture_class()
fixture.stop()
class GabbiFixtureError(Exception):
"""Generic exception for GabbiFixture."""
pass
class GabbiFixture(object):
"""A singleton of a fixture.
Subclasses must implement start_fixture and stop_fixture, each of which
contain the logic for stopping and starting whatever the fixture is.
What a fixture is is left as an exercise for the implementor.
A singleton is used so as to avoid in process duplication of the same
fixture. For environments where concurrent testing will be used, the
fixture should guard against collisions by uniquifying filenames,
database names and other external resources.
If calling code attempts to start an already started fixture, an Exception
will be raised: GabbiFixtureError.
"""
_instance = None
_started = False
def __new__(cls, *args, **kwargs):
"""Create the new instance or return an existing one."""
if not cls._instance:
cls._instance = super(GabbiFixture, cls).__new__(cls)
return cls._instance
def start(self):
"""Request that the fixture be started."""
if not self._started:
self.start_fixture()
self._started = True
else:
raise GabbiFixtureError('fixture %s already started' % self)
def start_fixture(self):
"""Implement the actual workings of starting the fixture here."""
pass
def stop(self):
"""Request that the fixture be stopped."""
if self._started:
self.stop_fixture()
self._started = False
def stop_fixture(self):
"""Implement the actual workings of stopping the fixture here."""
pass
|
"""Manage fixtures for gabbi at the test file level."""
def start_fixture(fixture_class):
"""Create the fixture class and start it."""
fixture = fixture_class()
fixture.start()
def stop_fixture(fixture_class):
"""Create the fixture class and stop it."""
fixture = fixture_class()
fixture.stop()
class GabbiFixture(object):
"""A singleton of a fixture."""
_instance = None
_started = False
_halted = False
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(GabbiFixture, cls).__new__(cls)
return cls._instance
def start(self):
if not self._started and not self._halted:
self._started = True
self.start_fixture()
def start_fixture(self):
pass
def stop(self):
if self._started:
self.stop_fixture()
self._started = False
self._halted = True
def stop_fixture(self):
pass
Add some docs to GabbiFixture"""Manage fixtures for gabbi at the test file level."""
def start_fixture(fixture_class):
"""Create the fixture class and start it."""
fixture = fixture_class()
fixture.start()
def stop_fixture(fixture_class):
"""Re-Create the fixture class and stop it."""
fixture = fixture_class()
fixture.stop()
class GabbiFixtureError(Exception):
"""Generic exception for GabbiFixture."""
pass
class GabbiFixture(object):
"""A singleton of a fixture.
Subclasses must implement start_fixture and stop_fixture, each of which
contain the logic for stopping and starting whatever the fixture is.
What a fixture is is left as an exercise for the implementor.
A singleton is used so as to avoid in process duplication of the same
fixture. For environments where concurrent testing will be used, the
fixture should guard against collisions by uniquifying filenames,
database names and other external resources.
If calling code attempts to start an already started fixture, an Exception
will be raised: GabbiFixtureError.
"""
_instance = None
_started = False
def __new__(cls, *args, **kwargs):
"""Create the new instance or return an existing one."""
if not cls._instance:
cls._instance = super(GabbiFixture, cls).__new__(cls)
return cls._instance
def start(self):
"""Request that the fixture be started."""
if not self._started:
self.start_fixture()
self._started = True
else:
raise GabbiFixtureError('fixture %s already started' % self)
def start_fixture(self):
"""Implement the actual workings of starting the fixture here."""
pass
def stop(self):
"""Request that the fixture be stopped."""
if self._started:
self.stop_fixture()
self._started = False
def stop_fixture(self):
"""Implement the actual workings of stopping the fixture here."""
pass
|
<commit_before>"""Manage fixtures for gabbi at the test file level."""
def start_fixture(fixture_class):
"""Create the fixture class and start it."""
fixture = fixture_class()
fixture.start()
def stop_fixture(fixture_class):
"""Create the fixture class and stop it."""
fixture = fixture_class()
fixture.stop()
class GabbiFixture(object):
"""A singleton of a fixture."""
_instance = None
_started = False
_halted = False
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(GabbiFixture, cls).__new__(cls)
return cls._instance
def start(self):
if not self._started and not self._halted:
self._started = True
self.start_fixture()
def start_fixture(self):
pass
def stop(self):
if self._started:
self.stop_fixture()
self._started = False
self._halted = True
def stop_fixture(self):
pass
<commit_msg>Add some docs to GabbiFixture<commit_after>"""Manage fixtures for gabbi at the test file level."""
def start_fixture(fixture_class):
"""Create the fixture class and start it."""
fixture = fixture_class()
fixture.start()
def stop_fixture(fixture_class):
"""Re-Create the fixture class and stop it."""
fixture = fixture_class()
fixture.stop()
class GabbiFixtureError(Exception):
"""Generic exception for GabbiFixture."""
pass
class GabbiFixture(object):
"""A singleton of a fixture.
Subclasses must implement start_fixture and stop_fixture, each of which
contain the logic for stopping and starting whatever the fixture is.
What a fixture is is left as an exercise for the implementor.
A singleton is used so as to avoid in process duplication of the same
fixture. For environments where concurrent testing will be used, the
fixture should guard against collisions by uniquifying filenames,
database names and other external resources.
If calling code attempts to start an already started fixture, an Exception
will be raised: GabbiFixtureError.
"""
_instance = None
_started = False
def __new__(cls, *args, **kwargs):
"""Create the new instance or return an existing one."""
if not cls._instance:
cls._instance = super(GabbiFixture, cls).__new__(cls)
return cls._instance
def start(self):
"""Request that the fixture be started."""
if not self._started:
self.start_fixture()
self._started = True
else:
raise GabbiFixtureError('fixture %s already started' % self)
def start_fixture(self):
"""Implement the actual workings of starting the fixture here."""
pass
def stop(self):
"""Request that the fixture be stopped."""
if self._started:
self.stop_fixture()
self._started = False
def stop_fixture(self):
"""Implement the actual workings of stopping the fixture here."""
pass
|
02dec2f8fd426f5d01565bd358dd807e4d1c2d02
|
genes/apt/get.py
|
genes/apt/get.py
|
import os
from subprocess import call
from functools import partial
#TODO: stop using sudo or ensure it exists
#TODOE: specify user to run as
#TODO: utilize functools partial to handle some of the above functionality
class Config:
APT_GET = ['sudo', '-E', 'apt-get']
ENV = os.environ.copy()
ENV['DEBIAN_FRONTEND'] = "noninteractive"
ENV_CALL = partial(call, env=ENV)
def install(*packages):
if packages:
Config.ENV_CALL(Config.APT_GET + ['install'] + list(packages))
else:
#FIXME: need to output failure
pass
update = partial(Config.ENV_CALL, Config.APT_GET + ['update'])
upgrade = partial(Config.ENV_CALL, Config.APT_GET + ['upgrade'])
|
import os
from subprocess import call
from functools import partial
#TODO: stop using sudo or ensure it exists
#TODOE: specify user to run as
#TODO: utilize functools partial to handle some of the above functionality
class Config:
APT_GET = ['sudo', '-E', 'apt-get']
ENV = os.environ.copy()
ENV['DEBIAN_FRONTEND'] = "noninteractive"
ENV_CALL = partial(call, env=ENV)
#TODO: Split me out to key
RECV_KEY = ['sudo', '-E', 'apt-key', 'adv', '--keyserver', 'hkp://pgp.mit.edu:80', '--recv-keys']
def install(*packages):
if packages:
Config.ENV_CALL(Config.APT_GET + ['install'] + list(packages))
else:
#FIXME: need to output failure
pass
update = partial(Config.ENV_CALL, Config.APT_GET + ['update'])
upgrade = partial(Config.ENV_CALL, Config.APT_GET + ['upgrade'])
def recv_keys(*keys):
if keys:
Config.ENV_CALL(Config.RECV_KEY + list(keys))
else:
#FIXME: need to output failure
pass
def add_repo(filename, *line_items):
if filename and line_items:
#FIXME, open file and write lines to the end.
pass
else:
#FIXME: need to output failure
pass
|
Add recv_keys and add_repo to apt
|
Add recv_keys and add_repo to apt
|
Python
|
mit
|
hatchery/Genepool2,hatchery/genepool
|
import os
from subprocess import call
from functools import partial
#TODO: stop using sudo or ensure it exists
#TODOE: specify user to run as
#TODO: utilize functools partial to handle some of the above functionality
class Config:
APT_GET = ['sudo', '-E', 'apt-get']
ENV = os.environ.copy()
ENV['DEBIAN_FRONTEND'] = "noninteractive"
ENV_CALL = partial(call, env=ENV)
def install(*packages):
if packages:
Config.ENV_CALL(Config.APT_GET + ['install'] + list(packages))
else:
#FIXME: need to output failure
pass
update = partial(Config.ENV_CALL, Config.APT_GET + ['update'])
upgrade = partial(Config.ENV_CALL, Config.APT_GET + ['upgrade'])
Add recv_keys and add_repo to apt
|
import os
from subprocess import call
from functools import partial
#TODO: stop using sudo or ensure it exists
#TODOE: specify user to run as
#TODO: utilize functools partial to handle some of the above functionality
class Config:
APT_GET = ['sudo', '-E', 'apt-get']
ENV = os.environ.copy()
ENV['DEBIAN_FRONTEND'] = "noninteractive"
ENV_CALL = partial(call, env=ENV)
#TODO: Split me out to key
RECV_KEY = ['sudo', '-E', 'apt-key', 'adv', '--keyserver', 'hkp://pgp.mit.edu:80', '--recv-keys']
def install(*packages):
if packages:
Config.ENV_CALL(Config.APT_GET + ['install'] + list(packages))
else:
#FIXME: need to output failure
pass
update = partial(Config.ENV_CALL, Config.APT_GET + ['update'])
upgrade = partial(Config.ENV_CALL, Config.APT_GET + ['upgrade'])
def recv_keys(*keys):
if keys:
Config.ENV_CALL(Config.RECV_KEY + list(keys))
else:
#FIXME: need to output failure
pass
def add_repo(filename, *line_items):
if filename and line_items:
#FIXME, open file and write lines to the end.
pass
else:
#FIXME: need to output failure
pass
|
<commit_before>import os
from subprocess import call
from functools import partial
#TODO: stop using sudo or ensure it exists
#TODOE: specify user to run as
#TODO: utilize functools partial to handle some of the above functionality
class Config:
APT_GET = ['sudo', '-E', 'apt-get']
ENV = os.environ.copy()
ENV['DEBIAN_FRONTEND'] = "noninteractive"
ENV_CALL = partial(call, env=ENV)
def install(*packages):
if packages:
Config.ENV_CALL(Config.APT_GET + ['install'] + list(packages))
else:
#FIXME: need to output failure
pass
update = partial(Config.ENV_CALL, Config.APT_GET + ['update'])
upgrade = partial(Config.ENV_CALL, Config.APT_GET + ['upgrade'])
<commit_msg>Add recv_keys and add_repo to apt<commit_after>
|
import os
from subprocess import call
from functools import partial
#TODO: stop using sudo or ensure it exists
#TODOE: specify user to run as
#TODO: utilize functools partial to handle some of the above functionality
class Config:
APT_GET = ['sudo', '-E', 'apt-get']
ENV = os.environ.copy()
ENV['DEBIAN_FRONTEND'] = "noninteractive"
ENV_CALL = partial(call, env=ENV)
#TODO: Split me out to key
RECV_KEY = ['sudo', '-E', 'apt-key', 'adv', '--keyserver', 'hkp://pgp.mit.edu:80', '--recv-keys']
def install(*packages):
if packages:
Config.ENV_CALL(Config.APT_GET + ['install'] + list(packages))
else:
#FIXME: need to output failure
pass
update = partial(Config.ENV_CALL, Config.APT_GET + ['update'])
upgrade = partial(Config.ENV_CALL, Config.APT_GET + ['upgrade'])
def recv_keys(*keys):
if keys:
Config.ENV_CALL(Config.RECV_KEY + list(keys))
else:
#FIXME: need to output failure
pass
def add_repo(filename, *line_items):
if filename and line_items:
#FIXME, open file and write lines to the end.
pass
else:
#FIXME: need to output failure
pass
|
import os
from subprocess import call
from functools import partial
#TODO: stop using sudo or ensure it exists
#TODOE: specify user to run as
#TODO: utilize functools partial to handle some of the above functionality
class Config:
APT_GET = ['sudo', '-E', 'apt-get']
ENV = os.environ.copy()
ENV['DEBIAN_FRONTEND'] = "noninteractive"
ENV_CALL = partial(call, env=ENV)
def install(*packages):
if packages:
Config.ENV_CALL(Config.APT_GET + ['install'] + list(packages))
else:
#FIXME: need to output failure
pass
update = partial(Config.ENV_CALL, Config.APT_GET + ['update'])
upgrade = partial(Config.ENV_CALL, Config.APT_GET + ['upgrade'])
Add recv_keys and add_repo to aptimport os
from subprocess import call
from functools import partial
#TODO: stop using sudo or ensure it exists
#TODOE: specify user to run as
#TODO: utilize functools partial to handle some of the above functionality
class Config:
APT_GET = ['sudo', '-E', 'apt-get']
ENV = os.environ.copy()
ENV['DEBIAN_FRONTEND'] = "noninteractive"
ENV_CALL = partial(call, env=ENV)
#TODO: Split me out to key
RECV_KEY = ['sudo', '-E', 'apt-key', 'adv', '--keyserver', 'hkp://pgp.mit.edu:80', '--recv-keys']
def install(*packages):
if packages:
Config.ENV_CALL(Config.APT_GET + ['install'] + list(packages))
else:
#FIXME: need to output failure
pass
update = partial(Config.ENV_CALL, Config.APT_GET + ['update'])
upgrade = partial(Config.ENV_CALL, Config.APT_GET + ['upgrade'])
def recv_keys(*keys):
if keys:
Config.ENV_CALL(Config.RECV_KEY + list(keys))
else:
#FIXME: need to output failure
pass
def add_repo(filename, *line_items):
if filename and line_items:
#FIXME, open file and write lines to the end.
pass
else:
#FIXME: need to output failure
pass
|
<commit_before>import os
from subprocess import call
from functools import partial
#TODO: stop using sudo or ensure it exists
#TODOE: specify user to run as
#TODO: utilize functools partial to handle some of the above functionality
class Config:
APT_GET = ['sudo', '-E', 'apt-get']
ENV = os.environ.copy()
ENV['DEBIAN_FRONTEND'] = "noninteractive"
ENV_CALL = partial(call, env=ENV)
def install(*packages):
if packages:
Config.ENV_CALL(Config.APT_GET + ['install'] + list(packages))
else:
#FIXME: need to output failure
pass
update = partial(Config.ENV_CALL, Config.APT_GET + ['update'])
upgrade = partial(Config.ENV_CALL, Config.APT_GET + ['upgrade'])
<commit_msg>Add recv_keys and add_repo to apt<commit_after>import os
from subprocess import call
from functools import partial
#TODO: stop using sudo or ensure it exists
#TODOE: specify user to run as
#TODO: utilize functools partial to handle some of the above functionality
class Config:
APT_GET = ['sudo', '-E', 'apt-get']
ENV = os.environ.copy()
ENV['DEBIAN_FRONTEND'] = "noninteractive"
ENV_CALL = partial(call, env=ENV)
#TODO: Split me out to key
RECV_KEY = ['sudo', '-E', 'apt-key', 'adv', '--keyserver', 'hkp://pgp.mit.edu:80', '--recv-keys']
def install(*packages):
if packages:
Config.ENV_CALL(Config.APT_GET + ['install'] + list(packages))
else:
#FIXME: need to output failure
pass
update = partial(Config.ENV_CALL, Config.APT_GET + ['update'])
upgrade = partial(Config.ENV_CALL, Config.APT_GET + ['upgrade'])
def recv_keys(*keys):
if keys:
Config.ENV_CALL(Config.RECV_KEY + list(keys))
else:
#FIXME: need to output failure
pass
def add_repo(filename, *line_items):
if filename and line_items:
#FIXME, open file and write lines to the end.
pass
else:
#FIXME: need to output failure
pass
|
186eaeb5b5e8d7c7f06305566729bf36424c6e77
|
grab/__init__.py
|
grab/__init__.py
|
from base import (GrabError, DataNotFound, GrabNetworkError,
GrabMisuseError, UploadContent, UploadFile,
GrabTimeoutError)
from transport.curl import GrabCurl
#from transport.urllib import GrabUrllib
from transport.selenium import GrabSelenium
from transport.requests import GrabRequests
Grab = GrabCurl
version_info = (0, 3, 21)
__version__ = '.'.join(map(str, version_info))
|
from base import (GrabError, DataNotFound, GrabNetworkError,
GrabMisuseError, UploadContent, UploadFile,
GrabTimeoutError)
from transport.curl import GrabCurl
#from transport.urllib import GrabUrllib
from transport.selenium import GrabSelenium
from transport.requests import GrabRequests
from tools.logs import default_logging
Grab = GrabCurl
version_info = (0, 3, 21)
__version__ = '.'.join(map(str, version_info))
|
Add default_logging function to package namespace
|
Add default_logging function to package namespace
|
Python
|
mit
|
DDShadoww/grab,maurobaraldi/grab,DDShadoww/grab,liorvh/grab,SpaceAppsXploration/grab,huiyi1990/grab,subeax/grab,lorien/grab,pombredanne/grab-1,giserh/grab,alihalabyah/grab,kevinlondon/grab,shaunstanislaus/grab,subeax/grab,maurobaraldi/grab,kevinlondon/grab,SpaceAppsXploration/grab,shaunstanislaus/grab,pombredanne/grab-1,codevlabs/grab,istinspring/grab,istinspring/grab,huiyi1990/grab,codevlabs/grab,raybuhr/grab,giserh/grab,liorvh/grab,raybuhr/grab,lorien/grab,subeax/grab,alihalabyah/grab
|
from base import (GrabError, DataNotFound, GrabNetworkError,
GrabMisuseError, UploadContent, UploadFile,
GrabTimeoutError)
from transport.curl import GrabCurl
#from transport.urllib import GrabUrllib
from transport.selenium import GrabSelenium
from transport.requests import GrabRequests
Grab = GrabCurl
version_info = (0, 3, 21)
__version__ = '.'.join(map(str, version_info))
Add default_logging function to package namespace
|
from base import (GrabError, DataNotFound, GrabNetworkError,
GrabMisuseError, UploadContent, UploadFile,
GrabTimeoutError)
from transport.curl import GrabCurl
#from transport.urllib import GrabUrllib
from transport.selenium import GrabSelenium
from transport.requests import GrabRequests
from tools.logs import default_logging
Grab = GrabCurl
version_info = (0, 3, 21)
__version__ = '.'.join(map(str, version_info))
|
<commit_before>from base import (GrabError, DataNotFound, GrabNetworkError,
GrabMisuseError, UploadContent, UploadFile,
GrabTimeoutError)
from transport.curl import GrabCurl
#from transport.urllib import GrabUrllib
from transport.selenium import GrabSelenium
from transport.requests import GrabRequests
Grab = GrabCurl
version_info = (0, 3, 21)
__version__ = '.'.join(map(str, version_info))
<commit_msg>Add default_logging function to package namespace<commit_after>
|
from base import (GrabError, DataNotFound, GrabNetworkError,
GrabMisuseError, UploadContent, UploadFile,
GrabTimeoutError)
from transport.curl import GrabCurl
#from transport.urllib import GrabUrllib
from transport.selenium import GrabSelenium
from transport.requests import GrabRequests
from tools.logs import default_logging
Grab = GrabCurl
version_info = (0, 3, 21)
__version__ = '.'.join(map(str, version_info))
|
from base import (GrabError, DataNotFound, GrabNetworkError,
GrabMisuseError, UploadContent, UploadFile,
GrabTimeoutError)
from transport.curl import GrabCurl
#from transport.urllib import GrabUrllib
from transport.selenium import GrabSelenium
from transport.requests import GrabRequests
Grab = GrabCurl
version_info = (0, 3, 21)
__version__ = '.'.join(map(str, version_info))
Add default_logging function to package namespacefrom base import (GrabError, DataNotFound, GrabNetworkError,
GrabMisuseError, UploadContent, UploadFile,
GrabTimeoutError)
from transport.curl import GrabCurl
#from transport.urllib import GrabUrllib
from transport.selenium import GrabSelenium
from transport.requests import GrabRequests
from tools.logs import default_logging
Grab = GrabCurl
version_info = (0, 3, 21)
__version__ = '.'.join(map(str, version_info))
|
<commit_before>from base import (GrabError, DataNotFound, GrabNetworkError,
GrabMisuseError, UploadContent, UploadFile,
GrabTimeoutError)
from transport.curl import GrabCurl
#from transport.urllib import GrabUrllib
from transport.selenium import GrabSelenium
from transport.requests import GrabRequests
Grab = GrabCurl
version_info = (0, 3, 21)
__version__ = '.'.join(map(str, version_info))
<commit_msg>Add default_logging function to package namespace<commit_after>from base import (GrabError, DataNotFound, GrabNetworkError,
GrabMisuseError, UploadContent, UploadFile,
GrabTimeoutError)
from transport.curl import GrabCurl
#from transport.urllib import GrabUrllib
from transport.selenium import GrabSelenium
from transport.requests import GrabRequests
from tools.logs import default_logging
Grab = GrabCurl
version_info = (0, 3, 21)
__version__ = '.'.join(map(str, version_info))
|
1736fd6ec8a227adfeae6f6b0dbcb3c6af59377c
|
bokeh/sampledata/us_marriages_divorces.py
|
bokeh/sampledata/us_marriages_divorces.py
|
'''
This module provides U.S. marriage and divorce statistics between 1867 and 2014
Data from the CDC's National Center for Health Statistics (http://www.cdc.gov/nchs/) (NCHS) database
Data organized by Randal S. Olson (http://www.randalolson.com)
'''
from __future__ import absolute_import
from os.path import dirname, join
try:
import pandas as pd
except ImportError as e:
raise RuntimeError('us_marriages_divorces data requires pandas (http://pandas.pydata.org) to be installed')
data = pd.read_csv(
join(dirname(__file__), 'us_marriages_divorces.csv'))
# Fill in missing data with a simple linear interpolation
data = md_data.interpolate(method='linear', axis=0).ffill().bfill()
|
'''
This module provides U.S. marriage and divorce statistics between 1867 and 2014
Data from the CDC's National Center for Health Statistics (http://www.cdc.gov/nchs/) (NCHS) database
Data organized by Randal S. Olson (http://www.randalolson.com)
'''
from __future__ import absolute_import
from os.path import dirname, join
try:
import pandas as pd
except ImportError as e:
raise RuntimeError('us_marriages_divorces data requires pandas (http://pandas.pydata.org) to be installed')
data = pd.read_csv(
join(dirname(__file__), 'us_marriages_divorces.csv'))
# Fill in missing data with a simple linear interpolation
data = data.interpolate(method='linear', axis=0).ffill().bfill()
|
Fix reference to `md_data` in sample data
|
Fix reference to `md_data` in sample data
|
Python
|
bsd-3-clause
|
roxyboy/bokeh,josherick/bokeh,schoolie/bokeh,deeplook/bokeh,matbra/bokeh,htygithub/bokeh,ericmjl/bokeh,clairetang6/bokeh,rhiever/bokeh,xguse/bokeh,gpfreitas/bokeh,KasperPRasmussen/bokeh,philippjfr/bokeh,justacec/bokeh,gpfreitas/bokeh,timsnyder/bokeh,rothnic/bokeh,xguse/bokeh,matbra/bokeh,bokeh/bokeh,ptitjano/bokeh,muku42/bokeh,mindriot101/bokeh,josherick/bokeh,schoolie/bokeh,ericdill/bokeh,aavanian/bokeh,timsnyder/bokeh,draperjames/bokeh,KasperPRasmussen/bokeh,roxyboy/bokeh,jplourenco/bokeh,draperjames/bokeh,quasiben/bokeh,khkaminska/bokeh,DuCorey/bokeh,matbra/bokeh,DuCorey/bokeh,daodaoliang/bokeh,carlvlewis/bokeh,daodaoliang/bokeh,DuCorey/bokeh,paultcochrane/bokeh,ptitjano/bokeh,philippjfr/bokeh,percyfal/bokeh,ChinaQuants/bokeh,caseyclements/bokeh,saifrahmed/bokeh,clairetang6/bokeh,mindriot101/bokeh,carlvlewis/bokeh,dennisobrien/bokeh,azjps/bokeh,ptitjano/bokeh,ericmjl/bokeh,msarahan/bokeh,aavanian/bokeh,jakirkham/bokeh,paultcochrane/bokeh,Karel-van-de-Plassche/bokeh,ptitjano/bokeh,azjps/bokeh,dennisobrien/bokeh,CrazyGuo/bokeh,roxyboy/bokeh,KasperPRasmussen/bokeh,jplourenco/bokeh,evidation-health/bokeh,rs2/bokeh,aavanian/bokeh,DuCorey/bokeh,msarahan/bokeh,paultcochrane/bokeh,percyfal/bokeh,jakirkham/bokeh,ericmjl/bokeh,jakirkham/bokeh,justacec/bokeh,tacaswell/bokeh,tacaswell/bokeh,matbra/bokeh,Karel-van-de-Plassche/bokeh,rs2/bokeh,quasiben/bokeh,daodaoliang/bokeh,quasiben/bokeh,srinathv/bokeh,muku42/bokeh,josherick/bokeh,rhiever/bokeh,stonebig/bokeh,evidation-health/bokeh,Karel-van-de-Plassche/bokeh,josherick/bokeh,ericdill/bokeh,deeplook/bokeh,Karel-van-de-Plassche/bokeh,muku42/bokeh,schoolie/bokeh,bokeh/bokeh,draperjames/bokeh,daodaoliang/bokeh,DuCorey/bokeh,clairetang6/bokeh,schoolie/bokeh,jplourenco/bokeh,phobson/bokeh,stonebig/bokeh,caseyclements/bokeh,phobson/bokeh,dennisobrien/bokeh,schoolie/bokeh,gpfreitas/bokeh,xguse/bokeh,aiguofer/bokeh,srinathv/bokeh,phobson/bokeh,mindriot101/bokeh,ericmjl/bokeh,phobson/bokeh,maxalbert/bokeh,CrazyGuo/bokeh,maxalbert/bokeh,clairetang6/bokeh,mindriot101/bokeh,khkaminska/bokeh,aiguofer/bokeh,rhiever/bokeh,gpfreitas/bokeh,azjps/bokeh,aiguofer/bokeh,muku42/bokeh,dennisobrien/bokeh,khkaminska/bokeh,xguse/bokeh,Karel-van-de-Plassche/bokeh,aiguofer/bokeh,msarahan/bokeh,ptitjano/bokeh,draperjames/bokeh,rothnic/bokeh,phobson/bokeh,ericdill/bokeh,rhiever/bokeh,philippjfr/bokeh,rs2/bokeh,timsnyder/bokeh,maxalbert/bokeh,ChinaQuants/bokeh,azjps/bokeh,caseyclements/bokeh,carlvlewis/bokeh,khkaminska/bokeh,jakirkham/bokeh,rs2/bokeh,jplourenco/bokeh,aiguofer/bokeh,caseyclements/bokeh,timsnyder/bokeh,saifrahmed/bokeh,dennisobrien/bokeh,roxyboy/bokeh,CrazyGuo/bokeh,rothnic/bokeh,ericdill/bokeh,justacec/bokeh,msarahan/bokeh,deeplook/bokeh,htygithub/bokeh,jakirkham/bokeh,deeplook/bokeh,saifrahmed/bokeh,CrazyGuo/bokeh,percyfal/bokeh,draperjames/bokeh,rs2/bokeh,timsnyder/bokeh,percyfal/bokeh,KasperPRasmussen/bokeh,bokeh/bokeh,carlvlewis/bokeh,srinathv/bokeh,saifrahmed/bokeh,ericmjl/bokeh,evidation-health/bokeh,maxalbert/bokeh,evidation-health/bokeh,justacec/bokeh,htygithub/bokeh,philippjfr/bokeh,KasperPRasmussen/bokeh,aavanian/bokeh,rothnic/bokeh,tacaswell/bokeh,ChinaQuants/bokeh,stonebig/bokeh,percyfal/bokeh,htygithub/bokeh,aavanian/bokeh,azjps/bokeh,bokeh/bokeh,philippjfr/bokeh,stonebig/bokeh,tacaswell/bokeh,srinathv/bokeh,bokeh/bokeh,paultcochrane/bokeh,ChinaQuants/bokeh
|
'''
This module provides U.S. marriage and divorce statistics between 1867 and 2014
Data from the CDC's National Center for Health Statistics (http://www.cdc.gov/nchs/) (NCHS) database
Data organized by Randal S. Olson (http://www.randalolson.com)
'''
from __future__ import absolute_import
from os.path import dirname, join
try:
import pandas as pd
except ImportError as e:
raise RuntimeError('us_marriages_divorces data requires pandas (http://pandas.pydata.org) to be installed')
data = pd.read_csv(
join(dirname(__file__), 'us_marriages_divorces.csv'))
# Fill in missing data with a simple linear interpolation
data = md_data.interpolate(method='linear', axis=0).ffill().bfill()
Fix reference to `md_data` in sample data
|
'''
This module provides U.S. marriage and divorce statistics between 1867 and 2014
Data from the CDC's National Center for Health Statistics (http://www.cdc.gov/nchs/) (NCHS) database
Data organized by Randal S. Olson (http://www.randalolson.com)
'''
from __future__ import absolute_import
from os.path import dirname, join
try:
import pandas as pd
except ImportError as e:
raise RuntimeError('us_marriages_divorces data requires pandas (http://pandas.pydata.org) to be installed')
data = pd.read_csv(
join(dirname(__file__), 'us_marriages_divorces.csv'))
# Fill in missing data with a simple linear interpolation
data = data.interpolate(method='linear', axis=0).ffill().bfill()
|
<commit_before>'''
This module provides U.S. marriage and divorce statistics between 1867 and 2014
Data from the CDC's National Center for Health Statistics (http://www.cdc.gov/nchs/) (NCHS) database
Data organized by Randal S. Olson (http://www.randalolson.com)
'''
from __future__ import absolute_import
from os.path import dirname, join
try:
import pandas as pd
except ImportError as e:
raise RuntimeError('us_marriages_divorces data requires pandas (http://pandas.pydata.org) to be installed')
data = pd.read_csv(
join(dirname(__file__), 'us_marriages_divorces.csv'))
# Fill in missing data with a simple linear interpolation
data = md_data.interpolate(method='linear', axis=0).ffill().bfill()
<commit_msg>Fix reference to `md_data` in sample data<commit_after>
|
'''
This module provides U.S. marriage and divorce statistics between 1867 and 2014
Data from the CDC's National Center for Health Statistics (http://www.cdc.gov/nchs/) (NCHS) database
Data organized by Randal S. Olson (http://www.randalolson.com)
'''
from __future__ import absolute_import
from os.path import dirname, join
try:
import pandas as pd
except ImportError as e:
raise RuntimeError('us_marriages_divorces data requires pandas (http://pandas.pydata.org) to be installed')
data = pd.read_csv(
join(dirname(__file__), 'us_marriages_divorces.csv'))
# Fill in missing data with a simple linear interpolation
data = data.interpolate(method='linear', axis=0).ffill().bfill()
|
'''
This module provides U.S. marriage and divorce statistics between 1867 and 2014
Data from the CDC's National Center for Health Statistics (http://www.cdc.gov/nchs/) (NCHS) database
Data organized by Randal S. Olson (http://www.randalolson.com)
'''
from __future__ import absolute_import
from os.path import dirname, join
try:
import pandas as pd
except ImportError as e:
raise RuntimeError('us_marriages_divorces data requires pandas (http://pandas.pydata.org) to be installed')
data = pd.read_csv(
join(dirname(__file__), 'us_marriages_divorces.csv'))
# Fill in missing data with a simple linear interpolation
data = md_data.interpolate(method='linear', axis=0).ffill().bfill()
Fix reference to `md_data` in sample data'''
This module provides U.S. marriage and divorce statistics between 1867 and 2014
Data from the CDC's National Center for Health Statistics (http://www.cdc.gov/nchs/) (NCHS) database
Data organized by Randal S. Olson (http://www.randalolson.com)
'''
from __future__ import absolute_import
from os.path import dirname, join
try:
import pandas as pd
except ImportError as e:
raise RuntimeError('us_marriages_divorces data requires pandas (http://pandas.pydata.org) to be installed')
data = pd.read_csv(
join(dirname(__file__), 'us_marriages_divorces.csv'))
# Fill in missing data with a simple linear interpolation
data = data.interpolate(method='linear', axis=0).ffill().bfill()
|
<commit_before>'''
This module provides U.S. marriage and divorce statistics between 1867 and 2014
Data from the CDC's National Center for Health Statistics (http://www.cdc.gov/nchs/) (NCHS) database
Data organized by Randal S. Olson (http://www.randalolson.com)
'''
from __future__ import absolute_import
from os.path import dirname, join
try:
import pandas as pd
except ImportError as e:
raise RuntimeError('us_marriages_divorces data requires pandas (http://pandas.pydata.org) to be installed')
data = pd.read_csv(
join(dirname(__file__), 'us_marriages_divorces.csv'))
# Fill in missing data with a simple linear interpolation
data = md_data.interpolate(method='linear', axis=0).ffill().bfill()
<commit_msg>Fix reference to `md_data` in sample data<commit_after>'''
This module provides U.S. marriage and divorce statistics between 1867 and 2014
Data from the CDC's National Center for Health Statistics (http://www.cdc.gov/nchs/) (NCHS) database
Data organized by Randal S. Olson (http://www.randalolson.com)
'''
from __future__ import absolute_import
from os.path import dirname, join
try:
import pandas as pd
except ImportError as e:
raise RuntimeError('us_marriages_divorces data requires pandas (http://pandas.pydata.org) to be installed')
data = pd.read_csv(
join(dirname(__file__), 'us_marriages_divorces.csv'))
# Fill in missing data with a simple linear interpolation
data = data.interpolate(method='linear', axis=0).ffill().bfill()
|
b3ef68f209e014b624b8de26e53af5933e20aa9c
|
grako/rendering.py
|
grako/rendering.py
|
# -*- coding: utf-8 -*-
"""
The Renderer class provides the infrastructure for generating template-based
code. It's used by the .grammars module for parser generation.
"""
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 -*-
"""
The Renderer class provides the infrastructure for generating template-based
code. It's used by the .grammars module for parser generation.
"""
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 = ({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(fields)
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))
|
Use 'fields' instead of 'kwargs' to document intent.
|
Use 'fields' instead of 'kwargs' to document intent.
|
Python
|
bsd-2-clause
|
swayf/grako,swayf/grako
|
# -*- coding: utf-8 -*-
"""
The Renderer class provides the infrastructure for generating template-based
code. It's used by the .grammars module for parser generation.
"""
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))
Use 'fields' instead of 'kwargs' to document intent.
|
# -*- coding: utf-8 -*-
"""
The Renderer class provides the infrastructure for generating template-based
code. It's used by the .grammars module for parser generation.
"""
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 = ({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(fields)
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 -*-
"""
The Renderer class provides the infrastructure for generating template-based
code. It's used by the .grammars module for parser generation.
"""
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_msg>Use 'fields' instead of 'kwargs' to document intent.<commit_after>
|
# -*- coding: utf-8 -*-
"""
The Renderer class provides the infrastructure for generating template-based
code. It's used by the .grammars module for parser generation.
"""
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 = ({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(fields)
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 -*-
"""
The Renderer class provides the infrastructure for generating template-based
code. It's used by the .grammars module for parser generation.
"""
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))
Use 'fields' instead of 'kwargs' to document intent.# -*- coding: utf-8 -*-
"""
The Renderer class provides the infrastructure for generating template-based
code. It's used by the .grammars module for parser generation.
"""
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 = ({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(fields)
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 -*-
"""
The Renderer class provides the infrastructure for generating template-based
code. It's used by the .grammars module for parser generation.
"""
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_msg>Use 'fields' instead of 'kwargs' to document intent.<commit_after># -*- coding: utf-8 -*-
"""
The Renderer class provides the infrastructure for generating template-based
code. It's used by the .grammars module for parser generation.
"""
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 = ({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(fields)
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))
|
2277e8412fbd92c26cd822f389ecb7e099519da4
|
.conda/merge_dups.py
|
.conda/merge_dups.py
|
#!/usr/bin/env python
import yaml
linux = yaml.load(open('data_linux-64.yml'))
res = yaml.load(open('data_osx-.yml'))
res.extend(linux)
# Remove duplicates
unique_packages = {}
for package in res:
# This information is the unique portion, so we key on that
key = '|'.join([package[x] for x in ('url', 'version', 'name')])
# We turn the architecture item into a list.
if key in unique_packages:
unique_packages[key]['arch'].append(package['arch'])
else:
unique_packages[key] = package
unique_packages[key]['arch'] = [unique_packages[key]['arch']]
res = []
for item in unique_packages.values():
if len(item['arch']) == 1:
# If there is only one arch, then we have a platform specific URL,
# since otherwise we would have generated an arch that contains both
# linux + osx
item['arch'] = item['arch'][0]
res.append(item)
else:
# Here we have two or more archs (ideally. We don't check conditions
# like 0 arches)
item['arch'] = 'src'
res.append(item)
with open('data.yml', 'w') as outfile:
yaml.safe_dump(res, outfile, default_flow_style=False)
|
#!/usr/bin/env python
import yaml
linux = yaml.load(open('data_linux-64.yml', 'r'))
res = yaml.load(open('data_osx-.yml', 'r'))
res.extend(linux)
# Remove duplicates
unique_packages = {}
for package in res:
# This information is the unique portion, so we key on that
key_data = [
package['version'],
package['name']
]
if isinstance(package['url'], list):
key_data += package['url']
else:
key_data.append(package['url'])
key = '|'.join(key_data)
# We turn the architecture item into a list.
if key in unique_packages:
unique_packages[key]['arch'].append(package['arch'])
else:
unique_packages[key] = package
unique_packages[key]['arch'] = [unique_packages[key]['arch']]
res = []
for item in unique_packages.values():
if len(item['arch']) == 1:
# If there is only one arch, then we have a platform specific URL,
# since otherwise we would have generated an arch that contains both
# linux + osx
item['arch'] = item['arch'][0]
res.append(item)
else:
# Here we have two or more archs (ideally. We don't check conditions
# like 0 arches)
item['arch'] = 'src'
res.append(item)
with open('data.yml', 'w') as outfile:
yaml.safe_dump(res, outfile, default_flow_style=False)
|
Handle lists of URLs like in r-ada
|
Handle lists of URLs like in r-ada
|
Python
|
mit
|
galaxyproject/cargo-port,galaxyproject/cargo-port,erasche/community-package-cache,erasche/community-package-cache,erasche/community-package-cache
|
#!/usr/bin/env python
import yaml
linux = yaml.load(open('data_linux-64.yml'))
res = yaml.load(open('data_osx-.yml'))
res.extend(linux)
# Remove duplicates
unique_packages = {}
for package in res:
# This information is the unique portion, so we key on that
key = '|'.join([package[x] for x in ('url', 'version', 'name')])
# We turn the architecture item into a list.
if key in unique_packages:
unique_packages[key]['arch'].append(package['arch'])
else:
unique_packages[key] = package
unique_packages[key]['arch'] = [unique_packages[key]['arch']]
res = []
for item in unique_packages.values():
if len(item['arch']) == 1:
# If there is only one arch, then we have a platform specific URL,
# since otherwise we would have generated an arch that contains both
# linux + osx
item['arch'] = item['arch'][0]
res.append(item)
else:
# Here we have two or more archs (ideally. We don't check conditions
# like 0 arches)
item['arch'] = 'src'
res.append(item)
with open('data.yml', 'w') as outfile:
yaml.safe_dump(res, outfile, default_flow_style=False)
Handle lists of URLs like in r-ada
|
#!/usr/bin/env python
import yaml
linux = yaml.load(open('data_linux-64.yml', 'r'))
res = yaml.load(open('data_osx-.yml', 'r'))
res.extend(linux)
# Remove duplicates
unique_packages = {}
for package in res:
# This information is the unique portion, so we key on that
key_data = [
package['version'],
package['name']
]
if isinstance(package['url'], list):
key_data += package['url']
else:
key_data.append(package['url'])
key = '|'.join(key_data)
# We turn the architecture item into a list.
if key in unique_packages:
unique_packages[key]['arch'].append(package['arch'])
else:
unique_packages[key] = package
unique_packages[key]['arch'] = [unique_packages[key]['arch']]
res = []
for item in unique_packages.values():
if len(item['arch']) == 1:
# If there is only one arch, then we have a platform specific URL,
# since otherwise we would have generated an arch that contains both
# linux + osx
item['arch'] = item['arch'][0]
res.append(item)
else:
# Here we have two or more archs (ideally. We don't check conditions
# like 0 arches)
item['arch'] = 'src'
res.append(item)
with open('data.yml', 'w') as outfile:
yaml.safe_dump(res, outfile, default_flow_style=False)
|
<commit_before>#!/usr/bin/env python
import yaml
linux = yaml.load(open('data_linux-64.yml'))
res = yaml.load(open('data_osx-.yml'))
res.extend(linux)
# Remove duplicates
unique_packages = {}
for package in res:
# This information is the unique portion, so we key on that
key = '|'.join([package[x] for x in ('url', 'version', 'name')])
# We turn the architecture item into a list.
if key in unique_packages:
unique_packages[key]['arch'].append(package['arch'])
else:
unique_packages[key] = package
unique_packages[key]['arch'] = [unique_packages[key]['arch']]
res = []
for item in unique_packages.values():
if len(item['arch']) == 1:
# If there is only one arch, then we have a platform specific URL,
# since otherwise we would have generated an arch that contains both
# linux + osx
item['arch'] = item['arch'][0]
res.append(item)
else:
# Here we have two or more archs (ideally. We don't check conditions
# like 0 arches)
item['arch'] = 'src'
res.append(item)
with open('data.yml', 'w') as outfile:
yaml.safe_dump(res, outfile, default_flow_style=False)
<commit_msg>Handle lists of URLs like in r-ada<commit_after>
|
#!/usr/bin/env python
import yaml
linux = yaml.load(open('data_linux-64.yml', 'r'))
res = yaml.load(open('data_osx-.yml', 'r'))
res.extend(linux)
# Remove duplicates
unique_packages = {}
for package in res:
# This information is the unique portion, so we key on that
key_data = [
package['version'],
package['name']
]
if isinstance(package['url'], list):
key_data += package['url']
else:
key_data.append(package['url'])
key = '|'.join(key_data)
# We turn the architecture item into a list.
if key in unique_packages:
unique_packages[key]['arch'].append(package['arch'])
else:
unique_packages[key] = package
unique_packages[key]['arch'] = [unique_packages[key]['arch']]
res = []
for item in unique_packages.values():
if len(item['arch']) == 1:
# If there is only one arch, then we have a platform specific URL,
# since otherwise we would have generated an arch that contains both
# linux + osx
item['arch'] = item['arch'][0]
res.append(item)
else:
# Here we have two or more archs (ideally. We don't check conditions
# like 0 arches)
item['arch'] = 'src'
res.append(item)
with open('data.yml', 'w') as outfile:
yaml.safe_dump(res, outfile, default_flow_style=False)
|
#!/usr/bin/env python
import yaml
linux = yaml.load(open('data_linux-64.yml'))
res = yaml.load(open('data_osx-.yml'))
res.extend(linux)
# Remove duplicates
unique_packages = {}
for package in res:
# This information is the unique portion, so we key on that
key = '|'.join([package[x] for x in ('url', 'version', 'name')])
# We turn the architecture item into a list.
if key in unique_packages:
unique_packages[key]['arch'].append(package['arch'])
else:
unique_packages[key] = package
unique_packages[key]['arch'] = [unique_packages[key]['arch']]
res = []
for item in unique_packages.values():
if len(item['arch']) == 1:
# If there is only one arch, then we have a platform specific URL,
# since otherwise we would have generated an arch that contains both
# linux + osx
item['arch'] = item['arch'][0]
res.append(item)
else:
# Here we have two or more archs (ideally. We don't check conditions
# like 0 arches)
item['arch'] = 'src'
res.append(item)
with open('data.yml', 'w') as outfile:
yaml.safe_dump(res, outfile, default_flow_style=False)
Handle lists of URLs like in r-ada#!/usr/bin/env python
import yaml
linux = yaml.load(open('data_linux-64.yml', 'r'))
res = yaml.load(open('data_osx-.yml', 'r'))
res.extend(linux)
# Remove duplicates
unique_packages = {}
for package in res:
# This information is the unique portion, so we key on that
key_data = [
package['version'],
package['name']
]
if isinstance(package['url'], list):
key_data += package['url']
else:
key_data.append(package['url'])
key = '|'.join(key_data)
# We turn the architecture item into a list.
if key in unique_packages:
unique_packages[key]['arch'].append(package['arch'])
else:
unique_packages[key] = package
unique_packages[key]['arch'] = [unique_packages[key]['arch']]
res = []
for item in unique_packages.values():
if len(item['arch']) == 1:
# If there is only one arch, then we have a platform specific URL,
# since otherwise we would have generated an arch that contains both
# linux + osx
item['arch'] = item['arch'][0]
res.append(item)
else:
# Here we have two or more archs (ideally. We don't check conditions
# like 0 arches)
item['arch'] = 'src'
res.append(item)
with open('data.yml', 'w') as outfile:
yaml.safe_dump(res, outfile, default_flow_style=False)
|
<commit_before>#!/usr/bin/env python
import yaml
linux = yaml.load(open('data_linux-64.yml'))
res = yaml.load(open('data_osx-.yml'))
res.extend(linux)
# Remove duplicates
unique_packages = {}
for package in res:
# This information is the unique portion, so we key on that
key = '|'.join([package[x] for x in ('url', 'version', 'name')])
# We turn the architecture item into a list.
if key in unique_packages:
unique_packages[key]['arch'].append(package['arch'])
else:
unique_packages[key] = package
unique_packages[key]['arch'] = [unique_packages[key]['arch']]
res = []
for item in unique_packages.values():
if len(item['arch']) == 1:
# If there is only one arch, then we have a platform specific URL,
# since otherwise we would have generated an arch that contains both
# linux + osx
item['arch'] = item['arch'][0]
res.append(item)
else:
# Here we have two or more archs (ideally. We don't check conditions
# like 0 arches)
item['arch'] = 'src'
res.append(item)
with open('data.yml', 'w') as outfile:
yaml.safe_dump(res, outfile, default_flow_style=False)
<commit_msg>Handle lists of URLs like in r-ada<commit_after>#!/usr/bin/env python
import yaml
linux = yaml.load(open('data_linux-64.yml', 'r'))
res = yaml.load(open('data_osx-.yml', 'r'))
res.extend(linux)
# Remove duplicates
unique_packages = {}
for package in res:
# This information is the unique portion, so we key on that
key_data = [
package['version'],
package['name']
]
if isinstance(package['url'], list):
key_data += package['url']
else:
key_data.append(package['url'])
key = '|'.join(key_data)
# We turn the architecture item into a list.
if key in unique_packages:
unique_packages[key]['arch'].append(package['arch'])
else:
unique_packages[key] = package
unique_packages[key]['arch'] = [unique_packages[key]['arch']]
res = []
for item in unique_packages.values():
if len(item['arch']) == 1:
# If there is only one arch, then we have a platform specific URL,
# since otherwise we would have generated an arch that contains both
# linux + osx
item['arch'] = item['arch'][0]
res.append(item)
else:
# Here we have two or more archs (ideally. We don't check conditions
# like 0 arches)
item['arch'] = 'src'
res.append(item)
with open('data.yml', 'w') as outfile:
yaml.safe_dump(res, outfile, default_flow_style=False)
|
c3852dbfc14f5109a5b4ff399953142e4ea9c758
|
application.py
|
application.py
|
from flask import Flask
application = Flask(__name__)
@application.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == "__main__":
application.debug = True
application.run()
|
from flask import Flask
application = Flask(__name__)
@application.route('/')
def hello_world():
return 'Please use /api to use the DataNorth API.'
@application.route('/api')
def api_intro():
intro = \
"""
<h2> Welcome to the DataNorth API! </h2>
<h4> The following endpoints are available: </h4>
<ul>
<li>/api/crime</li>
<li>/api/energy</li>
<li>/api/housing</li>
</ul>
"""
return intro
if __name__ == "__main__":
application.debug = True
application.run()
|
Add /api endpoint and basic HTML
|
Add /api endpoint and basic HTML
|
Python
|
mit
|
data-north/datanorth-api
|
from flask import Flask
application = Flask(__name__)
@application.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == "__main__":
application.debug = True
application.run()Add /api endpoint and basic HTML
|
from flask import Flask
application = Flask(__name__)
@application.route('/')
def hello_world():
return 'Please use /api to use the DataNorth API.'
@application.route('/api')
def api_intro():
intro = \
"""
<h2> Welcome to the DataNorth API! </h2>
<h4> The following endpoints are available: </h4>
<ul>
<li>/api/crime</li>
<li>/api/energy</li>
<li>/api/housing</li>
</ul>
"""
return intro
if __name__ == "__main__":
application.debug = True
application.run()
|
<commit_before>from flask import Flask
application = Flask(__name__)
@application.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == "__main__":
application.debug = True
application.run()<commit_msg>Add /api endpoint and basic HTML<commit_after>
|
from flask import Flask
application = Flask(__name__)
@application.route('/')
def hello_world():
return 'Please use /api to use the DataNorth API.'
@application.route('/api')
def api_intro():
intro = \
"""
<h2> Welcome to the DataNorth API! </h2>
<h4> The following endpoints are available: </h4>
<ul>
<li>/api/crime</li>
<li>/api/energy</li>
<li>/api/housing</li>
</ul>
"""
return intro
if __name__ == "__main__":
application.debug = True
application.run()
|
from flask import Flask
application = Flask(__name__)
@application.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == "__main__":
application.debug = True
application.run()Add /api endpoint and basic HTMLfrom flask import Flask
application = Flask(__name__)
@application.route('/')
def hello_world():
return 'Please use /api to use the DataNorth API.'
@application.route('/api')
def api_intro():
intro = \
"""
<h2> Welcome to the DataNorth API! </h2>
<h4> The following endpoints are available: </h4>
<ul>
<li>/api/crime</li>
<li>/api/energy</li>
<li>/api/housing</li>
</ul>
"""
return intro
if __name__ == "__main__":
application.debug = True
application.run()
|
<commit_before>from flask import Flask
application = Flask(__name__)
@application.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == "__main__":
application.debug = True
application.run()<commit_msg>Add /api endpoint and basic HTML<commit_after>from flask import Flask
application = Flask(__name__)
@application.route('/')
def hello_world():
return 'Please use /api to use the DataNorth API.'
@application.route('/api')
def api_intro():
intro = \
"""
<h2> Welcome to the DataNorth API! </h2>
<h4> The following endpoints are available: </h4>
<ul>
<li>/api/crime</li>
<li>/api/energy</li>
<li>/api/housing</li>
</ul>
"""
return intro
if __name__ == "__main__":
application.debug = True
application.run()
|
8cc88e1f6e09e91f2ffc5bbf43b58b2d129a12c9
|
bnc.py
|
bnc.py
|
import nltk.corpus.reader.bnc
|
import nltk.corpus.reader.bnc
import time
start_time = time.perf_counter()
BNC_data = nltk.corpus.reader.bnc.BNCCorpusReader(root='/home/ubuntu/ug-d/bncbaby/',
fileids=r'aca/\w*\.xml', # r'aca/\w*\.xml', # r'[a-z]{3}/\w*\.xml')
lazy=False) # found here: https://github.com/nltk/nltk/issues/781 talk about how much more efficient it is
time_taken = time.perf_counter() - start_time
print('\n|| Successfully loaded the British National Corpus in {:.1f}'.format(time_taken), 'seconds. ||\n')
|
Load BNC into memory and time process.
|
Load BNC into memory and time process.
|
Python
|
mit
|
albertomh/ug-dissertation
|
import nltk.corpus.reader.bnc
Load BNC into memory and time process.
|
import nltk.corpus.reader.bnc
import time
start_time = time.perf_counter()
BNC_data = nltk.corpus.reader.bnc.BNCCorpusReader(root='/home/ubuntu/ug-d/bncbaby/',
fileids=r'aca/\w*\.xml', # r'aca/\w*\.xml', # r'[a-z]{3}/\w*\.xml')
lazy=False) # found here: https://github.com/nltk/nltk/issues/781 talk about how much more efficient it is
time_taken = time.perf_counter() - start_time
print('\n|| Successfully loaded the British National Corpus in {:.1f}'.format(time_taken), 'seconds. ||\n')
|
<commit_before>import nltk.corpus.reader.bnc
<commit_msg>Load BNC into memory and time process.<commit_after>
|
import nltk.corpus.reader.bnc
import time
start_time = time.perf_counter()
BNC_data = nltk.corpus.reader.bnc.BNCCorpusReader(root='/home/ubuntu/ug-d/bncbaby/',
fileids=r'aca/\w*\.xml', # r'aca/\w*\.xml', # r'[a-z]{3}/\w*\.xml')
lazy=False) # found here: https://github.com/nltk/nltk/issues/781 talk about how much more efficient it is
time_taken = time.perf_counter() - start_time
print('\n|| Successfully loaded the British National Corpus in {:.1f}'.format(time_taken), 'seconds. ||\n')
|
import nltk.corpus.reader.bnc
Load BNC into memory and time process.import nltk.corpus.reader.bnc
import time
start_time = time.perf_counter()
BNC_data = nltk.corpus.reader.bnc.BNCCorpusReader(root='/home/ubuntu/ug-d/bncbaby/',
fileids=r'aca/\w*\.xml', # r'aca/\w*\.xml', # r'[a-z]{3}/\w*\.xml')
lazy=False) # found here: https://github.com/nltk/nltk/issues/781 talk about how much more efficient it is
time_taken = time.perf_counter() - start_time
print('\n|| Successfully loaded the British National Corpus in {:.1f}'.format(time_taken), 'seconds. ||\n')
|
<commit_before>import nltk.corpus.reader.bnc
<commit_msg>Load BNC into memory and time process.<commit_after>import nltk.corpus.reader.bnc
import time
start_time = time.perf_counter()
BNC_data = nltk.corpus.reader.bnc.BNCCorpusReader(root='/home/ubuntu/ug-d/bncbaby/',
fileids=r'aca/\w*\.xml', # r'aca/\w*\.xml', # r'[a-z]{3}/\w*\.xml')
lazy=False) # found here: https://github.com/nltk/nltk/issues/781 talk about how much more efficient it is
time_taken = time.perf_counter() - start_time
print('\n|| Successfully loaded the British National Corpus in {:.1f}'.format(time_taken), 'seconds. ||\n')
|
bf155290d958e15cc16dc0093a570e33c038b397
|
bot.py
|
bot.py
|
#!/usr/bin/env python2.7
# coding: utf-8
import inspect
import logging
logging.basicConfig(level=logging.DEBUG)
import os
import time
import uuid
from comicsbot import ComicsBot
from dokuwiki import DokuWiki
from roomlogger import RoomLogger
execfile("config.py")
w = DokuWiki()
if w.dokuwiki.login(config["dokuwiki"]["username"],
config["dokuwiki"]["password"]):
welcome_message = "Hello! I've connected to wiki %s version %s, " \
"xmlrpc %s" % (w.dokuwiki.getTitle(), w.dokuwiki.getVersion(),
w.dokuwiki.getXMLRPCAPIVersion())
else:
welcome_message = "Hi! I cannot authorize to the wiki."
w = None
room_logger = RoomLogger(config["jabber"]["logdir"])
bot = ComicsBot(config["jabber"]["username"],
config["jabber"]["password"], wiki=w,
room_logger=room_logger, res=uuid.uuid1(),
debug=True, # log XMPP messages
markov_file=os.path.join(config["jabber"]["logdir"], "markov.json"))
bot.join_room(config["jabber"]["room"], config["jabber"]["nick"])
time.sleep(1)
#bot.send(config["jabber"]["room"], welcome_message, message_type="groupchat")
bot.serve_forever()
|
#!/usr/bin/env python2.7
# coding: utf-8
import inspect
import logging
logging.basicConfig(level=logging.DEBUG)
import os
import time
import uuid
from comicsbot import ComicsBot
from dokuwiki import DokuWiki
from roomlogger import RoomLogger
execfile("config.py")
w = DokuWiki()
if w.dokuwiki.login(config["dokuwiki"]["username"],
config["dokuwiki"]["password"]):
welcome_message = "Hello! I've connected to wiki %s version %s, " \
"xmlrpc %s" % (w.dokuwiki.getTitle(), w.dokuwiki.getVersion(),
w.dokuwiki.getXMLRPCAPIVersion())
else:
welcome_message = "Hi! I cannot authorize to the wiki."
w = None
room_logger = RoomLogger(config["jabber"]["logdir"])
bot = ComicsBot(config["jabber"]["username"],
config["jabber"]["password"], wiki=w,
room_logger=room_logger, res="ReplaceMe",
debug=True, # log XMPP messages
markov_file=os.path.join(config["jabber"]["logdir"], "markov.json"))
bot.join_room(config["jabber"]["room"], config["jabber"]["nick"])
time.sleep(1)
#bot.send(config["jabber"]["room"], welcome_message, message_type="groupchat")
bot.serve_forever()
|
Use constant resource to be replaced on reconnect
|
Use constant resource to be replaced on reconnect
Network failures may leave the "ghost" bot in the MUC, and unless
it receives a MUC stanza while a replacement is offline, it may
hang in the room forever. Messages are sent to the new resource in
that case.
https://xmpp.org/extensions/xep-0045.html#impl-service-ghosts
|
Python
|
mit
|
dotdoom/comicsbot,dotdoom/comicsbot
|
#!/usr/bin/env python2.7
# coding: utf-8
import inspect
import logging
logging.basicConfig(level=logging.DEBUG)
import os
import time
import uuid
from comicsbot import ComicsBot
from dokuwiki import DokuWiki
from roomlogger import RoomLogger
execfile("config.py")
w = DokuWiki()
if w.dokuwiki.login(config["dokuwiki"]["username"],
config["dokuwiki"]["password"]):
welcome_message = "Hello! I've connected to wiki %s version %s, " \
"xmlrpc %s" % (w.dokuwiki.getTitle(), w.dokuwiki.getVersion(),
w.dokuwiki.getXMLRPCAPIVersion())
else:
welcome_message = "Hi! I cannot authorize to the wiki."
w = None
room_logger = RoomLogger(config["jabber"]["logdir"])
bot = ComicsBot(config["jabber"]["username"],
config["jabber"]["password"], wiki=w,
room_logger=room_logger, res=uuid.uuid1(),
debug=True, # log XMPP messages
markov_file=os.path.join(config["jabber"]["logdir"], "markov.json"))
bot.join_room(config["jabber"]["room"], config["jabber"]["nick"])
time.sleep(1)
#bot.send(config["jabber"]["room"], welcome_message, message_type="groupchat")
bot.serve_forever()
Use constant resource to be replaced on reconnect
Network failures may leave the "ghost" bot in the MUC, and unless
it receives a MUC stanza while a replacement is offline, it may
hang in the room forever. Messages are sent to the new resource in
that case.
https://xmpp.org/extensions/xep-0045.html#impl-service-ghosts
|
#!/usr/bin/env python2.7
# coding: utf-8
import inspect
import logging
logging.basicConfig(level=logging.DEBUG)
import os
import time
import uuid
from comicsbot import ComicsBot
from dokuwiki import DokuWiki
from roomlogger import RoomLogger
execfile("config.py")
w = DokuWiki()
if w.dokuwiki.login(config["dokuwiki"]["username"],
config["dokuwiki"]["password"]):
welcome_message = "Hello! I've connected to wiki %s version %s, " \
"xmlrpc %s" % (w.dokuwiki.getTitle(), w.dokuwiki.getVersion(),
w.dokuwiki.getXMLRPCAPIVersion())
else:
welcome_message = "Hi! I cannot authorize to the wiki."
w = None
room_logger = RoomLogger(config["jabber"]["logdir"])
bot = ComicsBot(config["jabber"]["username"],
config["jabber"]["password"], wiki=w,
room_logger=room_logger, res="ReplaceMe",
debug=True, # log XMPP messages
markov_file=os.path.join(config["jabber"]["logdir"], "markov.json"))
bot.join_room(config["jabber"]["room"], config["jabber"]["nick"])
time.sleep(1)
#bot.send(config["jabber"]["room"], welcome_message, message_type="groupchat")
bot.serve_forever()
|
<commit_before>#!/usr/bin/env python2.7
# coding: utf-8
import inspect
import logging
logging.basicConfig(level=logging.DEBUG)
import os
import time
import uuid
from comicsbot import ComicsBot
from dokuwiki import DokuWiki
from roomlogger import RoomLogger
execfile("config.py")
w = DokuWiki()
if w.dokuwiki.login(config["dokuwiki"]["username"],
config["dokuwiki"]["password"]):
welcome_message = "Hello! I've connected to wiki %s version %s, " \
"xmlrpc %s" % (w.dokuwiki.getTitle(), w.dokuwiki.getVersion(),
w.dokuwiki.getXMLRPCAPIVersion())
else:
welcome_message = "Hi! I cannot authorize to the wiki."
w = None
room_logger = RoomLogger(config["jabber"]["logdir"])
bot = ComicsBot(config["jabber"]["username"],
config["jabber"]["password"], wiki=w,
room_logger=room_logger, res=uuid.uuid1(),
debug=True, # log XMPP messages
markov_file=os.path.join(config["jabber"]["logdir"], "markov.json"))
bot.join_room(config["jabber"]["room"], config["jabber"]["nick"])
time.sleep(1)
#bot.send(config["jabber"]["room"], welcome_message, message_type="groupchat")
bot.serve_forever()
<commit_msg>Use constant resource to be replaced on reconnect
Network failures may leave the "ghost" bot in the MUC, and unless
it receives a MUC stanza while a replacement is offline, it may
hang in the room forever. Messages are sent to the new resource in
that case.
https://xmpp.org/extensions/xep-0045.html#impl-service-ghosts<commit_after>
|
#!/usr/bin/env python2.7
# coding: utf-8
import inspect
import logging
logging.basicConfig(level=logging.DEBUG)
import os
import time
import uuid
from comicsbot import ComicsBot
from dokuwiki import DokuWiki
from roomlogger import RoomLogger
execfile("config.py")
w = DokuWiki()
if w.dokuwiki.login(config["dokuwiki"]["username"],
config["dokuwiki"]["password"]):
welcome_message = "Hello! I've connected to wiki %s version %s, " \
"xmlrpc %s" % (w.dokuwiki.getTitle(), w.dokuwiki.getVersion(),
w.dokuwiki.getXMLRPCAPIVersion())
else:
welcome_message = "Hi! I cannot authorize to the wiki."
w = None
room_logger = RoomLogger(config["jabber"]["logdir"])
bot = ComicsBot(config["jabber"]["username"],
config["jabber"]["password"], wiki=w,
room_logger=room_logger, res="ReplaceMe",
debug=True, # log XMPP messages
markov_file=os.path.join(config["jabber"]["logdir"], "markov.json"))
bot.join_room(config["jabber"]["room"], config["jabber"]["nick"])
time.sleep(1)
#bot.send(config["jabber"]["room"], welcome_message, message_type="groupchat")
bot.serve_forever()
|
#!/usr/bin/env python2.7
# coding: utf-8
import inspect
import logging
logging.basicConfig(level=logging.DEBUG)
import os
import time
import uuid
from comicsbot import ComicsBot
from dokuwiki import DokuWiki
from roomlogger import RoomLogger
execfile("config.py")
w = DokuWiki()
if w.dokuwiki.login(config["dokuwiki"]["username"],
config["dokuwiki"]["password"]):
welcome_message = "Hello! I've connected to wiki %s version %s, " \
"xmlrpc %s" % (w.dokuwiki.getTitle(), w.dokuwiki.getVersion(),
w.dokuwiki.getXMLRPCAPIVersion())
else:
welcome_message = "Hi! I cannot authorize to the wiki."
w = None
room_logger = RoomLogger(config["jabber"]["logdir"])
bot = ComicsBot(config["jabber"]["username"],
config["jabber"]["password"], wiki=w,
room_logger=room_logger, res=uuid.uuid1(),
debug=True, # log XMPP messages
markov_file=os.path.join(config["jabber"]["logdir"], "markov.json"))
bot.join_room(config["jabber"]["room"], config["jabber"]["nick"])
time.sleep(1)
#bot.send(config["jabber"]["room"], welcome_message, message_type="groupchat")
bot.serve_forever()
Use constant resource to be replaced on reconnect
Network failures may leave the "ghost" bot in the MUC, and unless
it receives a MUC stanza while a replacement is offline, it may
hang in the room forever. Messages are sent to the new resource in
that case.
https://xmpp.org/extensions/xep-0045.html#impl-service-ghosts#!/usr/bin/env python2.7
# coding: utf-8
import inspect
import logging
logging.basicConfig(level=logging.DEBUG)
import os
import time
import uuid
from comicsbot import ComicsBot
from dokuwiki import DokuWiki
from roomlogger import RoomLogger
execfile("config.py")
w = DokuWiki()
if w.dokuwiki.login(config["dokuwiki"]["username"],
config["dokuwiki"]["password"]):
welcome_message = "Hello! I've connected to wiki %s version %s, " \
"xmlrpc %s" % (w.dokuwiki.getTitle(), w.dokuwiki.getVersion(),
w.dokuwiki.getXMLRPCAPIVersion())
else:
welcome_message = "Hi! I cannot authorize to the wiki."
w = None
room_logger = RoomLogger(config["jabber"]["logdir"])
bot = ComicsBot(config["jabber"]["username"],
config["jabber"]["password"], wiki=w,
room_logger=room_logger, res="ReplaceMe",
debug=True, # log XMPP messages
markov_file=os.path.join(config["jabber"]["logdir"], "markov.json"))
bot.join_room(config["jabber"]["room"], config["jabber"]["nick"])
time.sleep(1)
#bot.send(config["jabber"]["room"], welcome_message, message_type="groupchat")
bot.serve_forever()
|
<commit_before>#!/usr/bin/env python2.7
# coding: utf-8
import inspect
import logging
logging.basicConfig(level=logging.DEBUG)
import os
import time
import uuid
from comicsbot import ComicsBot
from dokuwiki import DokuWiki
from roomlogger import RoomLogger
execfile("config.py")
w = DokuWiki()
if w.dokuwiki.login(config["dokuwiki"]["username"],
config["dokuwiki"]["password"]):
welcome_message = "Hello! I've connected to wiki %s version %s, " \
"xmlrpc %s" % (w.dokuwiki.getTitle(), w.dokuwiki.getVersion(),
w.dokuwiki.getXMLRPCAPIVersion())
else:
welcome_message = "Hi! I cannot authorize to the wiki."
w = None
room_logger = RoomLogger(config["jabber"]["logdir"])
bot = ComicsBot(config["jabber"]["username"],
config["jabber"]["password"], wiki=w,
room_logger=room_logger, res=uuid.uuid1(),
debug=True, # log XMPP messages
markov_file=os.path.join(config["jabber"]["logdir"], "markov.json"))
bot.join_room(config["jabber"]["room"], config["jabber"]["nick"])
time.sleep(1)
#bot.send(config["jabber"]["room"], welcome_message, message_type="groupchat")
bot.serve_forever()
<commit_msg>Use constant resource to be replaced on reconnect
Network failures may leave the "ghost" bot in the MUC, and unless
it receives a MUC stanza while a replacement is offline, it may
hang in the room forever. Messages are sent to the new resource in
that case.
https://xmpp.org/extensions/xep-0045.html#impl-service-ghosts<commit_after>#!/usr/bin/env python2.7
# coding: utf-8
import inspect
import logging
logging.basicConfig(level=logging.DEBUG)
import os
import time
import uuid
from comicsbot import ComicsBot
from dokuwiki import DokuWiki
from roomlogger import RoomLogger
execfile("config.py")
w = DokuWiki()
if w.dokuwiki.login(config["dokuwiki"]["username"],
config["dokuwiki"]["password"]):
welcome_message = "Hello! I've connected to wiki %s version %s, " \
"xmlrpc %s" % (w.dokuwiki.getTitle(), w.dokuwiki.getVersion(),
w.dokuwiki.getXMLRPCAPIVersion())
else:
welcome_message = "Hi! I cannot authorize to the wiki."
w = None
room_logger = RoomLogger(config["jabber"]["logdir"])
bot = ComicsBot(config["jabber"]["username"],
config["jabber"]["password"], wiki=w,
room_logger=room_logger, res="ReplaceMe",
debug=True, # log XMPP messages
markov_file=os.path.join(config["jabber"]["logdir"], "markov.json"))
bot.join_room(config["jabber"]["room"], config["jabber"]["nick"])
time.sleep(1)
#bot.send(config["jabber"]["room"], welcome_message, message_type="groupchat")
bot.serve_forever()
|
396c9128aa4d3bc7b31f5fb00363a7f52dba7476
|
indra/java_vm.py
|
indra/java_vm.py
|
"""Handles all imports from jnius to prevent conflicts resulting from attempts
to set JVM options while the VM is already running."""
import os
import warnings
import jnius_config
if '-Xmx4g' not in jnius_config.get_options():
if not jnius_config.vm_running:
jnius_config.add_options('-Xmx4g')
else:
warnings.warn("Couldn't set memory limit for Java VM because the VM "
"is already running.")
path_here = os.path.dirname(os.path.realpath(__file__))
cp = path_here + '/biopax/jars/paxtools.jar'
os.environ['CLASSPATH'] = cp + ':' + os.environ['CLASSPATH']
from jnius import autoclass, JavaException, cast
|
"""Handles all imports from jnius to prevent conflicts resulting from attempts
to set JVM options while the VM is already running."""
import os
import warnings
import jnius_config
if '-Xmx4g' not in jnius_config.get_options():
if not jnius_config.vm_running:
jnius_config.add_options('-Xmx4g')
else:
warnings.warn("Couldn't set memory limit for Java VM because the VM "
"is already running.")
path_here = os.path.dirname(os.path.realpath(__file__))
cp = path_here + '/biopax/jars/paxtools.jar'
cp_existing = os.environ.get('CLASSPATH')
if cp_existing is not None:
os.environ['CLASSPATH'] = cp + ':' + cp_existing
else:
os.environ['CLASSPATH'] = cp
from jnius import autoclass, JavaException, cast
|
Fix java VM starting when there is not classpath set
|
Fix java VM starting when there is not classpath set
|
Python
|
bsd-2-clause
|
johnbachman/belpy,sorgerlab/belpy,sorgerlab/belpy,bgyori/indra,johnbachman/belpy,johnbachman/indra,jmuhlich/indra,sorgerlab/indra,bgyori/indra,jmuhlich/indra,sorgerlab/indra,jmuhlich/indra,johnbachman/indra,sorgerlab/indra,bgyori/indra,pvtodorov/indra,johnbachman/belpy,sorgerlab/belpy,pvtodorov/indra,johnbachman/indra,pvtodorov/indra,pvtodorov/indra
|
"""Handles all imports from jnius to prevent conflicts resulting from attempts
to set JVM options while the VM is already running."""
import os
import warnings
import jnius_config
if '-Xmx4g' not in jnius_config.get_options():
if not jnius_config.vm_running:
jnius_config.add_options('-Xmx4g')
else:
warnings.warn("Couldn't set memory limit for Java VM because the VM "
"is already running.")
path_here = os.path.dirname(os.path.realpath(__file__))
cp = path_here + '/biopax/jars/paxtools.jar'
os.environ['CLASSPATH'] = cp + ':' + os.environ['CLASSPATH']
from jnius import autoclass, JavaException, cast
Fix java VM starting when there is not classpath set
|
"""Handles all imports from jnius to prevent conflicts resulting from attempts
to set JVM options while the VM is already running."""
import os
import warnings
import jnius_config
if '-Xmx4g' not in jnius_config.get_options():
if not jnius_config.vm_running:
jnius_config.add_options('-Xmx4g')
else:
warnings.warn("Couldn't set memory limit for Java VM because the VM "
"is already running.")
path_here = os.path.dirname(os.path.realpath(__file__))
cp = path_here + '/biopax/jars/paxtools.jar'
cp_existing = os.environ.get('CLASSPATH')
if cp_existing is not None:
os.environ['CLASSPATH'] = cp + ':' + cp_existing
else:
os.environ['CLASSPATH'] = cp
from jnius import autoclass, JavaException, cast
|
<commit_before>"""Handles all imports from jnius to prevent conflicts resulting from attempts
to set JVM options while the VM is already running."""
import os
import warnings
import jnius_config
if '-Xmx4g' not in jnius_config.get_options():
if not jnius_config.vm_running:
jnius_config.add_options('-Xmx4g')
else:
warnings.warn("Couldn't set memory limit for Java VM because the VM "
"is already running.")
path_here = os.path.dirname(os.path.realpath(__file__))
cp = path_here + '/biopax/jars/paxtools.jar'
os.environ['CLASSPATH'] = cp + ':' + os.environ['CLASSPATH']
from jnius import autoclass, JavaException, cast
<commit_msg>Fix java VM starting when there is not classpath set<commit_after>
|
"""Handles all imports from jnius to prevent conflicts resulting from attempts
to set JVM options while the VM is already running."""
import os
import warnings
import jnius_config
if '-Xmx4g' not in jnius_config.get_options():
if not jnius_config.vm_running:
jnius_config.add_options('-Xmx4g')
else:
warnings.warn("Couldn't set memory limit for Java VM because the VM "
"is already running.")
path_here = os.path.dirname(os.path.realpath(__file__))
cp = path_here + '/biopax/jars/paxtools.jar'
cp_existing = os.environ.get('CLASSPATH')
if cp_existing is not None:
os.environ['CLASSPATH'] = cp + ':' + cp_existing
else:
os.environ['CLASSPATH'] = cp
from jnius import autoclass, JavaException, cast
|
"""Handles all imports from jnius to prevent conflicts resulting from attempts
to set JVM options while the VM is already running."""
import os
import warnings
import jnius_config
if '-Xmx4g' not in jnius_config.get_options():
if not jnius_config.vm_running:
jnius_config.add_options('-Xmx4g')
else:
warnings.warn("Couldn't set memory limit for Java VM because the VM "
"is already running.")
path_here = os.path.dirname(os.path.realpath(__file__))
cp = path_here + '/biopax/jars/paxtools.jar'
os.environ['CLASSPATH'] = cp + ':' + os.environ['CLASSPATH']
from jnius import autoclass, JavaException, cast
Fix java VM starting when there is not classpath set"""Handles all imports from jnius to prevent conflicts resulting from attempts
to set JVM options while the VM is already running."""
import os
import warnings
import jnius_config
if '-Xmx4g' not in jnius_config.get_options():
if not jnius_config.vm_running:
jnius_config.add_options('-Xmx4g')
else:
warnings.warn("Couldn't set memory limit for Java VM because the VM "
"is already running.")
path_here = os.path.dirname(os.path.realpath(__file__))
cp = path_here + '/biopax/jars/paxtools.jar'
cp_existing = os.environ.get('CLASSPATH')
if cp_existing is not None:
os.environ['CLASSPATH'] = cp + ':' + cp_existing
else:
os.environ['CLASSPATH'] = cp
from jnius import autoclass, JavaException, cast
|
<commit_before>"""Handles all imports from jnius to prevent conflicts resulting from attempts
to set JVM options while the VM is already running."""
import os
import warnings
import jnius_config
if '-Xmx4g' not in jnius_config.get_options():
if not jnius_config.vm_running:
jnius_config.add_options('-Xmx4g')
else:
warnings.warn("Couldn't set memory limit for Java VM because the VM "
"is already running.")
path_here = os.path.dirname(os.path.realpath(__file__))
cp = path_here + '/biopax/jars/paxtools.jar'
os.environ['CLASSPATH'] = cp + ':' + os.environ['CLASSPATH']
from jnius import autoclass, JavaException, cast
<commit_msg>Fix java VM starting when there is not classpath set<commit_after>"""Handles all imports from jnius to prevent conflicts resulting from attempts
to set JVM options while the VM is already running."""
import os
import warnings
import jnius_config
if '-Xmx4g' not in jnius_config.get_options():
if not jnius_config.vm_running:
jnius_config.add_options('-Xmx4g')
else:
warnings.warn("Couldn't set memory limit for Java VM because the VM "
"is already running.")
path_here = os.path.dirname(os.path.realpath(__file__))
cp = path_here + '/biopax/jars/paxtools.jar'
cp_existing = os.environ.get('CLASSPATH')
if cp_existing is not None:
os.environ['CLASSPATH'] = cp + ':' + cp_existing
else:
os.environ['CLASSPATH'] = cp
from jnius import autoclass, JavaException, cast
|
dce014bc1b12bda7eb261b194acebe308ae7ff1b
|
pyQuantuccia/setup.py
|
pyQuantuccia/setup.py
|
import setuptools
qu_ext = setuptools.Extension(
'quantuccia',
sources=['src/pyQuantuccia.cpp']
)
setuptools.setup(
name='pyQuantuccia',
version='0.1.0',
packages=['pyQuantuccia'],
ext_modules=[qu_ext]
)
|
import setuptools
qu_ext = setuptools.Extension(
'quantuccia',
libraries=['ql'],
library_dirs=['src/Quantuccia'],
sources=['src/pyQuantuccia.cpp']
)
setuptools.setup(
name='pyQuantuccia',
version='0.1.0',
packages=['pyQuantuccia'],
ext_modules=[qu_ext]
)
|
Add the location of the ql library.
|
Add the location of the ql library.
|
Python
|
bsd-3-clause
|
jwg4/pyQuantuccia,jwg4/pyQuantuccia
|
import setuptools
qu_ext = setuptools.Extension(
'quantuccia',
sources=['src/pyQuantuccia.cpp']
)
setuptools.setup(
name='pyQuantuccia',
version='0.1.0',
packages=['pyQuantuccia'],
ext_modules=[qu_ext]
)
Add the location of the ql library.
|
import setuptools
qu_ext = setuptools.Extension(
'quantuccia',
libraries=['ql'],
library_dirs=['src/Quantuccia'],
sources=['src/pyQuantuccia.cpp']
)
setuptools.setup(
name='pyQuantuccia',
version='0.1.0',
packages=['pyQuantuccia'],
ext_modules=[qu_ext]
)
|
<commit_before>import setuptools
qu_ext = setuptools.Extension(
'quantuccia',
sources=['src/pyQuantuccia.cpp']
)
setuptools.setup(
name='pyQuantuccia',
version='0.1.0',
packages=['pyQuantuccia'],
ext_modules=[qu_ext]
)
<commit_msg>Add the location of the ql library.<commit_after>
|
import setuptools
qu_ext = setuptools.Extension(
'quantuccia',
libraries=['ql'],
library_dirs=['src/Quantuccia'],
sources=['src/pyQuantuccia.cpp']
)
setuptools.setup(
name='pyQuantuccia',
version='0.1.0',
packages=['pyQuantuccia'],
ext_modules=[qu_ext]
)
|
import setuptools
qu_ext = setuptools.Extension(
'quantuccia',
sources=['src/pyQuantuccia.cpp']
)
setuptools.setup(
name='pyQuantuccia',
version='0.1.0',
packages=['pyQuantuccia'],
ext_modules=[qu_ext]
)
Add the location of the ql library.import setuptools
qu_ext = setuptools.Extension(
'quantuccia',
libraries=['ql'],
library_dirs=['src/Quantuccia'],
sources=['src/pyQuantuccia.cpp']
)
setuptools.setup(
name='pyQuantuccia',
version='0.1.0',
packages=['pyQuantuccia'],
ext_modules=[qu_ext]
)
|
<commit_before>import setuptools
qu_ext = setuptools.Extension(
'quantuccia',
sources=['src/pyQuantuccia.cpp']
)
setuptools.setup(
name='pyQuantuccia',
version='0.1.0',
packages=['pyQuantuccia'],
ext_modules=[qu_ext]
)
<commit_msg>Add the location of the ql library.<commit_after>import setuptools
qu_ext = setuptools.Extension(
'quantuccia',
libraries=['ql'],
library_dirs=['src/Quantuccia'],
sources=['src/pyQuantuccia.cpp']
)
setuptools.setup(
name='pyQuantuccia',
version='0.1.0',
packages=['pyQuantuccia'],
ext_modules=[qu_ext]
)
|
da2e17366f83ebb1b95b80296e5d6376bc21b4eb
|
pyinapp/googleplay.py
|
pyinapp/googleplay.py
|
from pyinapp.errors import InAppValidationError
from pyinapp.purchase import Purchase
import base64
import json
import rsa
purchase_state_ok = 0
def make_pem(public_key):
return '\n'.join((
'-----BEGIN PUBLIC KEY-----',
'\n'.join(public_key[i:i+64] for i in range(0, len(public_key), 64)),
'-----END PUBLIC KEY-----'
))
class GooglePlayValidator(object):
def __init__(self, bundle_id, api_key):
self.bundle_id = bundle_id
pem = make_pem(api_key)
self.public_key = rsa.PublicKey.load_pkcs1_openssl_pem(pem)
def validate(self, receipt, signature):
ok = self._validate_signature(receipt, signature)
if not ok:
raise InAppValidationError('Bad signature')
try:
receipt_json = json.loads(receipt)
if receipt_json['packageName'] != self.bundle_id:
raise InAppValidationError('Bundle id mismatch')
if receipt_json['purchaseState'] != purchase_state_ok:
raise InAppValidationError('Item is not purchased')
return Purchase.from_google_play_receipt(receipt_json)
except (KeyError, ValueError):
raise InAppValidationError('Bad receipt')
def _validate_signature(self, receipt, signature):
try:
sig = base64.standard_b64decode(signature)
return rsa.verify(receipt.encode(), sig, self.public_key)
except rsa.VerificationError:
return False
|
from pyinapp.errors import InAppValidationError
from pyinapp.purchase import Purchase
import base64
import json
import rsa
purchase_state_ok = 0
def make_pem(public_key):
return '\n'.join((
'-----BEGIN PUBLIC KEY-----',
'\n'.join(public_key[i:i+64] for i in range(0, len(public_key), 64)),
'-----END PUBLIC KEY-----'
))
class GooglePlayValidator(object):
def __init__(self, bundle_id, api_key):
self.bundle_id = bundle_id
pem = make_pem(api_key)
self.public_key = rsa.PublicKey.load_pkcs1_openssl_pem(pem)
def validate(self, receipt, signature):
ok = self._validate_signature(receipt, signature)
if not ok:
raise InAppValidationError('Bad signature')
try:
receipt_json = json.loads(receipt)
if receipt_json['packageName'] != self.bundle_id:
raise InAppValidationError('Bundle id mismatch')
if receipt_json['purchaseState'] != purchase_state_ok:
raise InAppValidationError('Item is not purchased')
return Purchase.from_google_play_receipt(receipt_json)
except (KeyError, ValueError):
raise InAppValidationError('Bad receipt')
def _validate_signature(self, receipt, signature):
try:
sig = base64.standard_b64decode(signature)
return rsa.verify(receipt.encode(), sig, self.public_key)
except (rsa.VerificationError, TypeError):
return False
|
Add extra validation for Google Play signature
|
Add extra validation for Google Play signature
|
Python
|
mit
|
keeprocking/pyinapp
|
from pyinapp.errors import InAppValidationError
from pyinapp.purchase import Purchase
import base64
import json
import rsa
purchase_state_ok = 0
def make_pem(public_key):
return '\n'.join((
'-----BEGIN PUBLIC KEY-----',
'\n'.join(public_key[i:i+64] for i in range(0, len(public_key), 64)),
'-----END PUBLIC KEY-----'
))
class GooglePlayValidator(object):
def __init__(self, bundle_id, api_key):
self.bundle_id = bundle_id
pem = make_pem(api_key)
self.public_key = rsa.PublicKey.load_pkcs1_openssl_pem(pem)
def validate(self, receipt, signature):
ok = self._validate_signature(receipt, signature)
if not ok:
raise InAppValidationError('Bad signature')
try:
receipt_json = json.loads(receipt)
if receipt_json['packageName'] != self.bundle_id:
raise InAppValidationError('Bundle id mismatch')
if receipt_json['purchaseState'] != purchase_state_ok:
raise InAppValidationError('Item is not purchased')
return Purchase.from_google_play_receipt(receipt_json)
except (KeyError, ValueError):
raise InAppValidationError('Bad receipt')
def _validate_signature(self, receipt, signature):
try:
sig = base64.standard_b64decode(signature)
return rsa.verify(receipt.encode(), sig, self.public_key)
except rsa.VerificationError:
return False
Add extra validation for Google Play signature
|
from pyinapp.errors import InAppValidationError
from pyinapp.purchase import Purchase
import base64
import json
import rsa
purchase_state_ok = 0
def make_pem(public_key):
return '\n'.join((
'-----BEGIN PUBLIC KEY-----',
'\n'.join(public_key[i:i+64] for i in range(0, len(public_key), 64)),
'-----END PUBLIC KEY-----'
))
class GooglePlayValidator(object):
def __init__(self, bundle_id, api_key):
self.bundle_id = bundle_id
pem = make_pem(api_key)
self.public_key = rsa.PublicKey.load_pkcs1_openssl_pem(pem)
def validate(self, receipt, signature):
ok = self._validate_signature(receipt, signature)
if not ok:
raise InAppValidationError('Bad signature')
try:
receipt_json = json.loads(receipt)
if receipt_json['packageName'] != self.bundle_id:
raise InAppValidationError('Bundle id mismatch')
if receipt_json['purchaseState'] != purchase_state_ok:
raise InAppValidationError('Item is not purchased')
return Purchase.from_google_play_receipt(receipt_json)
except (KeyError, ValueError):
raise InAppValidationError('Bad receipt')
def _validate_signature(self, receipt, signature):
try:
sig = base64.standard_b64decode(signature)
return rsa.verify(receipt.encode(), sig, self.public_key)
except (rsa.VerificationError, TypeError):
return False
|
<commit_before>from pyinapp.errors import InAppValidationError
from pyinapp.purchase import Purchase
import base64
import json
import rsa
purchase_state_ok = 0
def make_pem(public_key):
return '\n'.join((
'-----BEGIN PUBLIC KEY-----',
'\n'.join(public_key[i:i+64] for i in range(0, len(public_key), 64)),
'-----END PUBLIC KEY-----'
))
class GooglePlayValidator(object):
def __init__(self, bundle_id, api_key):
self.bundle_id = bundle_id
pem = make_pem(api_key)
self.public_key = rsa.PublicKey.load_pkcs1_openssl_pem(pem)
def validate(self, receipt, signature):
ok = self._validate_signature(receipt, signature)
if not ok:
raise InAppValidationError('Bad signature')
try:
receipt_json = json.loads(receipt)
if receipt_json['packageName'] != self.bundle_id:
raise InAppValidationError('Bundle id mismatch')
if receipt_json['purchaseState'] != purchase_state_ok:
raise InAppValidationError('Item is not purchased')
return Purchase.from_google_play_receipt(receipt_json)
except (KeyError, ValueError):
raise InAppValidationError('Bad receipt')
def _validate_signature(self, receipt, signature):
try:
sig = base64.standard_b64decode(signature)
return rsa.verify(receipt.encode(), sig, self.public_key)
except rsa.VerificationError:
return False
<commit_msg>Add extra validation for Google Play signature<commit_after>
|
from pyinapp.errors import InAppValidationError
from pyinapp.purchase import Purchase
import base64
import json
import rsa
purchase_state_ok = 0
def make_pem(public_key):
return '\n'.join((
'-----BEGIN PUBLIC KEY-----',
'\n'.join(public_key[i:i+64] for i in range(0, len(public_key), 64)),
'-----END PUBLIC KEY-----'
))
class GooglePlayValidator(object):
def __init__(self, bundle_id, api_key):
self.bundle_id = bundle_id
pem = make_pem(api_key)
self.public_key = rsa.PublicKey.load_pkcs1_openssl_pem(pem)
def validate(self, receipt, signature):
ok = self._validate_signature(receipt, signature)
if not ok:
raise InAppValidationError('Bad signature')
try:
receipt_json = json.loads(receipt)
if receipt_json['packageName'] != self.bundle_id:
raise InAppValidationError('Bundle id mismatch')
if receipt_json['purchaseState'] != purchase_state_ok:
raise InAppValidationError('Item is not purchased')
return Purchase.from_google_play_receipt(receipt_json)
except (KeyError, ValueError):
raise InAppValidationError('Bad receipt')
def _validate_signature(self, receipt, signature):
try:
sig = base64.standard_b64decode(signature)
return rsa.verify(receipt.encode(), sig, self.public_key)
except (rsa.VerificationError, TypeError):
return False
|
from pyinapp.errors import InAppValidationError
from pyinapp.purchase import Purchase
import base64
import json
import rsa
purchase_state_ok = 0
def make_pem(public_key):
return '\n'.join((
'-----BEGIN PUBLIC KEY-----',
'\n'.join(public_key[i:i+64] for i in range(0, len(public_key), 64)),
'-----END PUBLIC KEY-----'
))
class GooglePlayValidator(object):
def __init__(self, bundle_id, api_key):
self.bundle_id = bundle_id
pem = make_pem(api_key)
self.public_key = rsa.PublicKey.load_pkcs1_openssl_pem(pem)
def validate(self, receipt, signature):
ok = self._validate_signature(receipt, signature)
if not ok:
raise InAppValidationError('Bad signature')
try:
receipt_json = json.loads(receipt)
if receipt_json['packageName'] != self.bundle_id:
raise InAppValidationError('Bundle id mismatch')
if receipt_json['purchaseState'] != purchase_state_ok:
raise InAppValidationError('Item is not purchased')
return Purchase.from_google_play_receipt(receipt_json)
except (KeyError, ValueError):
raise InAppValidationError('Bad receipt')
def _validate_signature(self, receipt, signature):
try:
sig = base64.standard_b64decode(signature)
return rsa.verify(receipt.encode(), sig, self.public_key)
except rsa.VerificationError:
return False
Add extra validation for Google Play signaturefrom pyinapp.errors import InAppValidationError
from pyinapp.purchase import Purchase
import base64
import json
import rsa
purchase_state_ok = 0
def make_pem(public_key):
return '\n'.join((
'-----BEGIN PUBLIC KEY-----',
'\n'.join(public_key[i:i+64] for i in range(0, len(public_key), 64)),
'-----END PUBLIC KEY-----'
))
class GooglePlayValidator(object):
def __init__(self, bundle_id, api_key):
self.bundle_id = bundle_id
pem = make_pem(api_key)
self.public_key = rsa.PublicKey.load_pkcs1_openssl_pem(pem)
def validate(self, receipt, signature):
ok = self._validate_signature(receipt, signature)
if not ok:
raise InAppValidationError('Bad signature')
try:
receipt_json = json.loads(receipt)
if receipt_json['packageName'] != self.bundle_id:
raise InAppValidationError('Bundle id mismatch')
if receipt_json['purchaseState'] != purchase_state_ok:
raise InAppValidationError('Item is not purchased')
return Purchase.from_google_play_receipt(receipt_json)
except (KeyError, ValueError):
raise InAppValidationError('Bad receipt')
def _validate_signature(self, receipt, signature):
try:
sig = base64.standard_b64decode(signature)
return rsa.verify(receipt.encode(), sig, self.public_key)
except (rsa.VerificationError, TypeError):
return False
|
<commit_before>from pyinapp.errors import InAppValidationError
from pyinapp.purchase import Purchase
import base64
import json
import rsa
purchase_state_ok = 0
def make_pem(public_key):
return '\n'.join((
'-----BEGIN PUBLIC KEY-----',
'\n'.join(public_key[i:i+64] for i in range(0, len(public_key), 64)),
'-----END PUBLIC KEY-----'
))
class GooglePlayValidator(object):
def __init__(self, bundle_id, api_key):
self.bundle_id = bundle_id
pem = make_pem(api_key)
self.public_key = rsa.PublicKey.load_pkcs1_openssl_pem(pem)
def validate(self, receipt, signature):
ok = self._validate_signature(receipt, signature)
if not ok:
raise InAppValidationError('Bad signature')
try:
receipt_json = json.loads(receipt)
if receipt_json['packageName'] != self.bundle_id:
raise InAppValidationError('Bundle id mismatch')
if receipt_json['purchaseState'] != purchase_state_ok:
raise InAppValidationError('Item is not purchased')
return Purchase.from_google_play_receipt(receipt_json)
except (KeyError, ValueError):
raise InAppValidationError('Bad receipt')
def _validate_signature(self, receipt, signature):
try:
sig = base64.standard_b64decode(signature)
return rsa.verify(receipt.encode(), sig, self.public_key)
except rsa.VerificationError:
return False
<commit_msg>Add extra validation for Google Play signature<commit_after>from pyinapp.errors import InAppValidationError
from pyinapp.purchase import Purchase
import base64
import json
import rsa
purchase_state_ok = 0
def make_pem(public_key):
return '\n'.join((
'-----BEGIN PUBLIC KEY-----',
'\n'.join(public_key[i:i+64] for i in range(0, len(public_key), 64)),
'-----END PUBLIC KEY-----'
))
class GooglePlayValidator(object):
def __init__(self, bundle_id, api_key):
self.bundle_id = bundle_id
pem = make_pem(api_key)
self.public_key = rsa.PublicKey.load_pkcs1_openssl_pem(pem)
def validate(self, receipt, signature):
ok = self._validate_signature(receipt, signature)
if not ok:
raise InAppValidationError('Bad signature')
try:
receipt_json = json.loads(receipt)
if receipt_json['packageName'] != self.bundle_id:
raise InAppValidationError('Bundle id mismatch')
if receipt_json['purchaseState'] != purchase_state_ok:
raise InAppValidationError('Item is not purchased')
return Purchase.from_google_play_receipt(receipt_json)
except (KeyError, ValueError):
raise InAppValidationError('Bad receipt')
def _validate_signature(self, receipt, signature):
try:
sig = base64.standard_b64decode(signature)
return rsa.verify(receipt.encode(), sig, self.public_key)
except (rsa.VerificationError, TypeError):
return False
|
0eec6519a54d066f253b2c62b2317962733de53d
|
rapidsms/log/tests.py
|
rapidsms/log/tests.py
|
#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
from nose.tools import assert_equals, assert_raises
from ..log.mixin import LoggerMixin
class LoggableStub(object, LoggerMixin):
pass
def test_logger_mixin():
obj = LoggableStub()
from logging.handlers import MemoryHandler
import logging
log = logging.getLogger()
handler = MemoryHandler(999)
log.setLevel(logging.DEBUG)
log.addHandler(handler)
obj.debug("This is a DEBUG message")
obj.info("This is an INFORMATIVE message")
obj.warning("This is a WARNING")
obj.error("This is an ERROR")
obj.critical("This is a CRITICAL error")
obj.exception("This is an exception")
obj.exception()
assert_equals(len(handler.buffer), 7)
assert_equals(handler.buffer[2].name, "loggablestub")
assert_equals(handler.buffer[2].msg, "This is a WARNING")
log.removeHandler(handler)
def test_logger_raises_on_invalid_name_type():
class BrokenLoggableStub(object, LoggerMixin):
def _logger_name(self):
return 123
broken_logger = BrokenLoggableStub()
assert_raises(
TypeError,
broken_logger.debug,
"This shouldn't work")
|
#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
from nose.tools import assert_equals, assert_raises
from ..log.mixin import LoggerMixin
class LoggableStub(object, LoggerMixin):
pass
def test_logger_mixin():
obj = LoggableStub()
from logging.handlers import MemoryHandler
import logging
log = logging.getLogger()
handler = MemoryHandler(999)
log.setLevel(logging.DEBUG)
log.addHandler(handler)
obj.debug("This is a DEBUG message")
obj.info("This is an INFORMATIVE message")
obj.warning("This is a WARNING")
obj.error("This is an ERROR")
obj.critical("This is a CRITICAL error")
obj.exception("This is an exception")
obj.exception()
# There should be 8 messages: 7 from above, plus
# one more for LoggerMixin's own deprecation warning
assert_equals(len(handler.buffer), 7 + 1)
assert_equals(handler.buffer[3].name, "loggablestub")
assert_equals(handler.buffer[3].msg, "This is a WARNING")
log.removeHandler(handler)
def test_logger_raises_on_invalid_name_type():
class BrokenLoggableStub(object, LoggerMixin):
def _logger_name(self):
return 123
broken_logger = BrokenLoggableStub()
assert_raises(
TypeError,
broken_logger.debug,
"This shouldn't work")
|
Fix LoggerMixin test Branch: feature/bulk-messaging-api
|
Fix LoggerMixin test
Branch: feature/bulk-messaging-api
|
Python
|
bsd-3-clause
|
ehealthafrica-ci/rapidsms,eHealthAfrica/rapidsms,peterayeni/rapidsms,peterayeni/rapidsms,eHealthAfrica/rapidsms,ehealthafrica-ci/rapidsms,peterayeni/rapidsms,lsgunth/rapidsms,caktus/rapidsms,lsgunth/rapidsms,caktus/rapidsms,catalpainternational/rapidsms,ehealthafrica-ci/rapidsms,catalpainternational/rapidsms,lsgunth/rapidsms,caktus/rapidsms,peterayeni/rapidsms,lsgunth/rapidsms,catalpainternational/rapidsms,eHealthAfrica/rapidsms,catalpainternational/rapidsms
|
#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
from nose.tools import assert_equals, assert_raises
from ..log.mixin import LoggerMixin
class LoggableStub(object, LoggerMixin):
pass
def test_logger_mixin():
obj = LoggableStub()
from logging.handlers import MemoryHandler
import logging
log = logging.getLogger()
handler = MemoryHandler(999)
log.setLevel(logging.DEBUG)
log.addHandler(handler)
obj.debug("This is a DEBUG message")
obj.info("This is an INFORMATIVE message")
obj.warning("This is a WARNING")
obj.error("This is an ERROR")
obj.critical("This is a CRITICAL error")
obj.exception("This is an exception")
obj.exception()
assert_equals(len(handler.buffer), 7)
assert_equals(handler.buffer[2].name, "loggablestub")
assert_equals(handler.buffer[2].msg, "This is a WARNING")
log.removeHandler(handler)
def test_logger_raises_on_invalid_name_type():
class BrokenLoggableStub(object, LoggerMixin):
def _logger_name(self):
return 123
broken_logger = BrokenLoggableStub()
assert_raises(
TypeError,
broken_logger.debug,
"This shouldn't work")
Fix LoggerMixin test
Branch: feature/bulk-messaging-api
|
#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
from nose.tools import assert_equals, assert_raises
from ..log.mixin import LoggerMixin
class LoggableStub(object, LoggerMixin):
pass
def test_logger_mixin():
obj = LoggableStub()
from logging.handlers import MemoryHandler
import logging
log = logging.getLogger()
handler = MemoryHandler(999)
log.setLevel(logging.DEBUG)
log.addHandler(handler)
obj.debug("This is a DEBUG message")
obj.info("This is an INFORMATIVE message")
obj.warning("This is a WARNING")
obj.error("This is an ERROR")
obj.critical("This is a CRITICAL error")
obj.exception("This is an exception")
obj.exception()
# There should be 8 messages: 7 from above, plus
# one more for LoggerMixin's own deprecation warning
assert_equals(len(handler.buffer), 7 + 1)
assert_equals(handler.buffer[3].name, "loggablestub")
assert_equals(handler.buffer[3].msg, "This is a WARNING")
log.removeHandler(handler)
def test_logger_raises_on_invalid_name_type():
class BrokenLoggableStub(object, LoggerMixin):
def _logger_name(self):
return 123
broken_logger = BrokenLoggableStub()
assert_raises(
TypeError,
broken_logger.debug,
"This shouldn't work")
|
<commit_before>#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
from nose.tools import assert_equals, assert_raises
from ..log.mixin import LoggerMixin
class LoggableStub(object, LoggerMixin):
pass
def test_logger_mixin():
obj = LoggableStub()
from logging.handlers import MemoryHandler
import logging
log = logging.getLogger()
handler = MemoryHandler(999)
log.setLevel(logging.DEBUG)
log.addHandler(handler)
obj.debug("This is a DEBUG message")
obj.info("This is an INFORMATIVE message")
obj.warning("This is a WARNING")
obj.error("This is an ERROR")
obj.critical("This is a CRITICAL error")
obj.exception("This is an exception")
obj.exception()
assert_equals(len(handler.buffer), 7)
assert_equals(handler.buffer[2].name, "loggablestub")
assert_equals(handler.buffer[2].msg, "This is a WARNING")
log.removeHandler(handler)
def test_logger_raises_on_invalid_name_type():
class BrokenLoggableStub(object, LoggerMixin):
def _logger_name(self):
return 123
broken_logger = BrokenLoggableStub()
assert_raises(
TypeError,
broken_logger.debug,
"This shouldn't work")
<commit_msg>Fix LoggerMixin test
Branch: feature/bulk-messaging-api<commit_after>
|
#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
from nose.tools import assert_equals, assert_raises
from ..log.mixin import LoggerMixin
class LoggableStub(object, LoggerMixin):
pass
def test_logger_mixin():
obj = LoggableStub()
from logging.handlers import MemoryHandler
import logging
log = logging.getLogger()
handler = MemoryHandler(999)
log.setLevel(logging.DEBUG)
log.addHandler(handler)
obj.debug("This is a DEBUG message")
obj.info("This is an INFORMATIVE message")
obj.warning("This is a WARNING")
obj.error("This is an ERROR")
obj.critical("This is a CRITICAL error")
obj.exception("This is an exception")
obj.exception()
# There should be 8 messages: 7 from above, plus
# one more for LoggerMixin's own deprecation warning
assert_equals(len(handler.buffer), 7 + 1)
assert_equals(handler.buffer[3].name, "loggablestub")
assert_equals(handler.buffer[3].msg, "This is a WARNING")
log.removeHandler(handler)
def test_logger_raises_on_invalid_name_type():
class BrokenLoggableStub(object, LoggerMixin):
def _logger_name(self):
return 123
broken_logger = BrokenLoggableStub()
assert_raises(
TypeError,
broken_logger.debug,
"This shouldn't work")
|
#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
from nose.tools import assert_equals, assert_raises
from ..log.mixin import LoggerMixin
class LoggableStub(object, LoggerMixin):
pass
def test_logger_mixin():
obj = LoggableStub()
from logging.handlers import MemoryHandler
import logging
log = logging.getLogger()
handler = MemoryHandler(999)
log.setLevel(logging.DEBUG)
log.addHandler(handler)
obj.debug("This is a DEBUG message")
obj.info("This is an INFORMATIVE message")
obj.warning("This is a WARNING")
obj.error("This is an ERROR")
obj.critical("This is a CRITICAL error")
obj.exception("This is an exception")
obj.exception()
assert_equals(len(handler.buffer), 7)
assert_equals(handler.buffer[2].name, "loggablestub")
assert_equals(handler.buffer[2].msg, "This is a WARNING")
log.removeHandler(handler)
def test_logger_raises_on_invalid_name_type():
class BrokenLoggableStub(object, LoggerMixin):
def _logger_name(self):
return 123
broken_logger = BrokenLoggableStub()
assert_raises(
TypeError,
broken_logger.debug,
"This shouldn't work")
Fix LoggerMixin test
Branch: feature/bulk-messaging-api#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
from nose.tools import assert_equals, assert_raises
from ..log.mixin import LoggerMixin
class LoggableStub(object, LoggerMixin):
pass
def test_logger_mixin():
obj = LoggableStub()
from logging.handlers import MemoryHandler
import logging
log = logging.getLogger()
handler = MemoryHandler(999)
log.setLevel(logging.DEBUG)
log.addHandler(handler)
obj.debug("This is a DEBUG message")
obj.info("This is an INFORMATIVE message")
obj.warning("This is a WARNING")
obj.error("This is an ERROR")
obj.critical("This is a CRITICAL error")
obj.exception("This is an exception")
obj.exception()
# There should be 8 messages: 7 from above, plus
# one more for LoggerMixin's own deprecation warning
assert_equals(len(handler.buffer), 7 + 1)
assert_equals(handler.buffer[3].name, "loggablestub")
assert_equals(handler.buffer[3].msg, "This is a WARNING")
log.removeHandler(handler)
def test_logger_raises_on_invalid_name_type():
class BrokenLoggableStub(object, LoggerMixin):
def _logger_name(self):
return 123
broken_logger = BrokenLoggableStub()
assert_raises(
TypeError,
broken_logger.debug,
"This shouldn't work")
|
<commit_before>#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
from nose.tools import assert_equals, assert_raises
from ..log.mixin import LoggerMixin
class LoggableStub(object, LoggerMixin):
pass
def test_logger_mixin():
obj = LoggableStub()
from logging.handlers import MemoryHandler
import logging
log = logging.getLogger()
handler = MemoryHandler(999)
log.setLevel(logging.DEBUG)
log.addHandler(handler)
obj.debug("This is a DEBUG message")
obj.info("This is an INFORMATIVE message")
obj.warning("This is a WARNING")
obj.error("This is an ERROR")
obj.critical("This is a CRITICAL error")
obj.exception("This is an exception")
obj.exception()
assert_equals(len(handler.buffer), 7)
assert_equals(handler.buffer[2].name, "loggablestub")
assert_equals(handler.buffer[2].msg, "This is a WARNING")
log.removeHandler(handler)
def test_logger_raises_on_invalid_name_type():
class BrokenLoggableStub(object, LoggerMixin):
def _logger_name(self):
return 123
broken_logger = BrokenLoggableStub()
assert_raises(
TypeError,
broken_logger.debug,
"This shouldn't work")
<commit_msg>Fix LoggerMixin test
Branch: feature/bulk-messaging-api<commit_after>#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
from nose.tools import assert_equals, assert_raises
from ..log.mixin import LoggerMixin
class LoggableStub(object, LoggerMixin):
pass
def test_logger_mixin():
obj = LoggableStub()
from logging.handlers import MemoryHandler
import logging
log = logging.getLogger()
handler = MemoryHandler(999)
log.setLevel(logging.DEBUG)
log.addHandler(handler)
obj.debug("This is a DEBUG message")
obj.info("This is an INFORMATIVE message")
obj.warning("This is a WARNING")
obj.error("This is an ERROR")
obj.critical("This is a CRITICAL error")
obj.exception("This is an exception")
obj.exception()
# There should be 8 messages: 7 from above, plus
# one more for LoggerMixin's own deprecation warning
assert_equals(len(handler.buffer), 7 + 1)
assert_equals(handler.buffer[3].name, "loggablestub")
assert_equals(handler.buffer[3].msg, "This is a WARNING")
log.removeHandler(handler)
def test_logger_raises_on_invalid_name_type():
class BrokenLoggableStub(object, LoggerMixin):
def _logger_name(self):
return 123
broken_logger = BrokenLoggableStub()
assert_raises(
TypeError,
broken_logger.debug,
"This shouldn't work")
|
cdfdfd7418f33cc38aa7db3e42e0050d4189ab77
|
webserver/utility/templatetags/active_tags.py
|
webserver/utility/templatetags/active_tags.py
|
import re
from django import template
from django.conf import settings
register = template.Library()
@register.simple_tag(takes_context=True)
def active(context, pattern):
print pattern
request = context['request']
if re.search(pattern, request.path):
return 'active'
return ''
|
import re
from django import template
from django.conf import settings
from django.template import Context, Template
register = template.Library()
@register.simple_tag(takes_context=True)
def active(context, pattern):
request = context['request']
template = Template(pattern)
context = Context(context)
if re.search(template.render(context), request.path):
return 'active'
return ''
|
Update active templatetag to accept more complex strings
|
Update active templatetag to accept more complex strings
|
Python
|
bsd-3-clause
|
siggame/webserver,siggame/webserver,siggame/webserver
|
import re
from django import template
from django.conf import settings
register = template.Library()
@register.simple_tag(takes_context=True)
def active(context, pattern):
print pattern
request = context['request']
if re.search(pattern, request.path):
return 'active'
return ''
Update active templatetag to accept more complex strings
|
import re
from django import template
from django.conf import settings
from django.template import Context, Template
register = template.Library()
@register.simple_tag(takes_context=True)
def active(context, pattern):
request = context['request']
template = Template(pattern)
context = Context(context)
if re.search(template.render(context), request.path):
return 'active'
return ''
|
<commit_before>import re
from django import template
from django.conf import settings
register = template.Library()
@register.simple_tag(takes_context=True)
def active(context, pattern):
print pattern
request = context['request']
if re.search(pattern, request.path):
return 'active'
return ''
<commit_msg>Update active templatetag to accept more complex strings<commit_after>
|
import re
from django import template
from django.conf import settings
from django.template import Context, Template
register = template.Library()
@register.simple_tag(takes_context=True)
def active(context, pattern):
request = context['request']
template = Template(pattern)
context = Context(context)
if re.search(template.render(context), request.path):
return 'active'
return ''
|
import re
from django import template
from django.conf import settings
register = template.Library()
@register.simple_tag(takes_context=True)
def active(context, pattern):
print pattern
request = context['request']
if re.search(pattern, request.path):
return 'active'
return ''
Update active templatetag to accept more complex stringsimport re
from django import template
from django.conf import settings
from django.template import Context, Template
register = template.Library()
@register.simple_tag(takes_context=True)
def active(context, pattern):
request = context['request']
template = Template(pattern)
context = Context(context)
if re.search(template.render(context), request.path):
return 'active'
return ''
|
<commit_before>import re
from django import template
from django.conf import settings
register = template.Library()
@register.simple_tag(takes_context=True)
def active(context, pattern):
print pattern
request = context['request']
if re.search(pattern, request.path):
return 'active'
return ''
<commit_msg>Update active templatetag to accept more complex strings<commit_after>import re
from django import template
from django.conf import settings
from django.template import Context, Template
register = template.Library()
@register.simple_tag(takes_context=True)
def active(context, pattern):
request = context['request']
template = Template(pattern)
context = Context(context)
if re.search(template.render(context), request.path):
return 'active'
return ''
|
fc6db503809e3e350081637ccb7b0f7e8eb67619
|
account_verification_flask/config/local.py
|
account_verification_flask/config/local.py
|
SECRET_KEY = '%^!@@*!&$8xdfdirunb52438#(&^874@#^&*($@*(@&^@)(&*)Y_)((+'
AUTHY_KEY = 'your_authy_key'
TWILIO_ACCOUNT_SID = 'your_twilio_account_sid'
TWILIO_AUTH_TOKEN = 'your_twilio_auth_token'
TWILIO_NUMBER = 'your_twilio_phone_number'
SQLALCHEMY_DATABASE_URI = 'sqlite:////Work/account_verification.db'
SQLALCHEMY_ECHO = True
|
SECRET_KEY = '%^!@@*!&$8xdfdirunb52438#(&^874@#^&*($@*(@&^@)(&*)Y_)((+'
AUTHY_KEY = 'your_authy_key'
TWILIO_ACCOUNT_SID = 'your_twilio_account_sid'
TWILIO_AUTH_TOKEN = 'your_twilio_auth_token'
TWILIO_NUMBER = 'your_twilio_phone_number'
SQLALCHEMY_DATABASE_URI = 'sqlite://'
SQLALCHEMY_ECHO = True
|
Switch the default config to use in memory sqlite
|
Switch the default config to use in memory sqlite
|
Python
|
mit
|
TwilioDevEd/account-verification-flask,TwilioDevEd/account-verification-flask,TwilioDevEd/account-verification-flask
|
SECRET_KEY = '%^!@@*!&$8xdfdirunb52438#(&^874@#^&*($@*(@&^@)(&*)Y_)((+'
AUTHY_KEY = 'your_authy_key'
TWILIO_ACCOUNT_SID = 'your_twilio_account_sid'
TWILIO_AUTH_TOKEN = 'your_twilio_auth_token'
TWILIO_NUMBER = 'your_twilio_phone_number'
SQLALCHEMY_DATABASE_URI = 'sqlite:////Work/account_verification.db'
SQLALCHEMY_ECHO = TrueSwitch the default config to use in memory sqlite
|
SECRET_KEY = '%^!@@*!&$8xdfdirunb52438#(&^874@#^&*($@*(@&^@)(&*)Y_)((+'
AUTHY_KEY = 'your_authy_key'
TWILIO_ACCOUNT_SID = 'your_twilio_account_sid'
TWILIO_AUTH_TOKEN = 'your_twilio_auth_token'
TWILIO_NUMBER = 'your_twilio_phone_number'
SQLALCHEMY_DATABASE_URI = 'sqlite://'
SQLALCHEMY_ECHO = True
|
<commit_before>SECRET_KEY = '%^!@@*!&$8xdfdirunb52438#(&^874@#^&*($@*(@&^@)(&*)Y_)((+'
AUTHY_KEY = 'your_authy_key'
TWILIO_ACCOUNT_SID = 'your_twilio_account_sid'
TWILIO_AUTH_TOKEN = 'your_twilio_auth_token'
TWILIO_NUMBER = 'your_twilio_phone_number'
SQLALCHEMY_DATABASE_URI = 'sqlite:////Work/account_verification.db'
SQLALCHEMY_ECHO = True<commit_msg>Switch the default config to use in memory sqlite<commit_after>
|
SECRET_KEY = '%^!@@*!&$8xdfdirunb52438#(&^874@#^&*($@*(@&^@)(&*)Y_)((+'
AUTHY_KEY = 'your_authy_key'
TWILIO_ACCOUNT_SID = 'your_twilio_account_sid'
TWILIO_AUTH_TOKEN = 'your_twilio_auth_token'
TWILIO_NUMBER = 'your_twilio_phone_number'
SQLALCHEMY_DATABASE_URI = 'sqlite://'
SQLALCHEMY_ECHO = True
|
SECRET_KEY = '%^!@@*!&$8xdfdirunb52438#(&^874@#^&*($@*(@&^@)(&*)Y_)((+'
AUTHY_KEY = 'your_authy_key'
TWILIO_ACCOUNT_SID = 'your_twilio_account_sid'
TWILIO_AUTH_TOKEN = 'your_twilio_auth_token'
TWILIO_NUMBER = 'your_twilio_phone_number'
SQLALCHEMY_DATABASE_URI = 'sqlite:////Work/account_verification.db'
SQLALCHEMY_ECHO = TrueSwitch the default config to use in memory sqliteSECRET_KEY = '%^!@@*!&$8xdfdirunb52438#(&^874@#^&*($@*(@&^@)(&*)Y_)((+'
AUTHY_KEY = 'your_authy_key'
TWILIO_ACCOUNT_SID = 'your_twilio_account_sid'
TWILIO_AUTH_TOKEN = 'your_twilio_auth_token'
TWILIO_NUMBER = 'your_twilio_phone_number'
SQLALCHEMY_DATABASE_URI = 'sqlite://'
SQLALCHEMY_ECHO = True
|
<commit_before>SECRET_KEY = '%^!@@*!&$8xdfdirunb52438#(&^874@#^&*($@*(@&^@)(&*)Y_)((+'
AUTHY_KEY = 'your_authy_key'
TWILIO_ACCOUNT_SID = 'your_twilio_account_sid'
TWILIO_AUTH_TOKEN = 'your_twilio_auth_token'
TWILIO_NUMBER = 'your_twilio_phone_number'
SQLALCHEMY_DATABASE_URI = 'sqlite:////Work/account_verification.db'
SQLALCHEMY_ECHO = True<commit_msg>Switch the default config to use in memory sqlite<commit_after>SECRET_KEY = '%^!@@*!&$8xdfdirunb52438#(&^874@#^&*($@*(@&^@)(&*)Y_)((+'
AUTHY_KEY = 'your_authy_key'
TWILIO_ACCOUNT_SID = 'your_twilio_account_sid'
TWILIO_AUTH_TOKEN = 'your_twilio_auth_token'
TWILIO_NUMBER = 'your_twilio_phone_number'
SQLALCHEMY_DATABASE_URI = 'sqlite://'
SQLALCHEMY_ECHO = True
|
4ee8cef54d21316c9490f49ee2b3f2f16ffdcfbb
|
python_scripts/solr_query_fetch_all.py
|
python_scripts/solr_query_fetch_all.py
|
#!/usr/bin/python
import requests
import ipdb
import time
import csv
import sys
import pysolr
def fetch_all( solr, query ) :
documents = []
num_matching_documents = solr.search( query ).hits
start = 0
rows = num_matching_documents
sys.stderr.write( ' starting fetch for ' + query )
while ( len( documents ) < num_matching_documents ) :
results = solr.search( query, **{
'start': start,
'rows': rows,
# 'fl' : 'media_id',
})
documents.extend( results.docs )
start += rows
assert len( documents ) <= num_matching_documents
assert len( documents ) == num_matching_documents
return documents
solr = pysolr.Solr('http://localhost:8983/solr/')
queries = [ '*:*',
]
for query in queries:
print query
results = fetch_all( solr, query )
print "got " + query
print results
|
#!/usr/bin/python
import requests
import ipdb
import time
import csv
import sys
import pysolr
def fetch_all( solr, query ) :
documents = []
num_matching_documents = solr.search( query ).hits
start = 0
rows = num_matching_documents
sys.stderr.write( ' starting fetch for ' + query )
sys.stderr.write( 'fetching {0} documents'.format( rows ) )
while ( len( documents ) < num_matching_documents ) :
results = solr.search( query, **{
'start': start,
'rows': rows,
# 'fl' : 'media_id',
})
documents.extend( results.docs )
start += rows
assert len( documents ) <= num_matching_documents
assert len( documents ) == num_matching_documents
return documents
solr = pysolr.Solr('http://localhost:8983/solr/')
queries = [ 'sentence:obama',
]
file=open('out.txt','wb')
for query in queries:
print query
results = fetch_all( solr, query )
print "got " + query
print len( results )
sentences = [ result['sentence'].encode('utf-8') for result in results ]
file.write("\n".join( sentences))
#file.writelines( sentences )
#ipdb.set_trace()
#file.writelines(str(results))
|
Save word counts to file.
|
Save word counts to file.
|
Python
|
agpl-3.0
|
AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,berkmancenter/mediacloud,AchyuthIIIT/mediacloud,berkmancenter/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,berkmancenter/mediacloud,AchyuthIIIT/mediacloud
|
#!/usr/bin/python
import requests
import ipdb
import time
import csv
import sys
import pysolr
def fetch_all( solr, query ) :
documents = []
num_matching_documents = solr.search( query ).hits
start = 0
rows = num_matching_documents
sys.stderr.write( ' starting fetch for ' + query )
while ( len( documents ) < num_matching_documents ) :
results = solr.search( query, **{
'start': start,
'rows': rows,
# 'fl' : 'media_id',
})
documents.extend( results.docs )
start += rows
assert len( documents ) <= num_matching_documents
assert len( documents ) == num_matching_documents
return documents
solr = pysolr.Solr('http://localhost:8983/solr/')
queries = [ '*:*',
]
for query in queries:
print query
results = fetch_all( solr, query )
print "got " + query
print results
Save word counts to file.
|
#!/usr/bin/python
import requests
import ipdb
import time
import csv
import sys
import pysolr
def fetch_all( solr, query ) :
documents = []
num_matching_documents = solr.search( query ).hits
start = 0
rows = num_matching_documents
sys.stderr.write( ' starting fetch for ' + query )
sys.stderr.write( 'fetching {0} documents'.format( rows ) )
while ( len( documents ) < num_matching_documents ) :
results = solr.search( query, **{
'start': start,
'rows': rows,
# 'fl' : 'media_id',
})
documents.extend( results.docs )
start += rows
assert len( documents ) <= num_matching_documents
assert len( documents ) == num_matching_documents
return documents
solr = pysolr.Solr('http://localhost:8983/solr/')
queries = [ 'sentence:obama',
]
file=open('out.txt','wb')
for query in queries:
print query
results = fetch_all( solr, query )
print "got " + query
print len( results )
sentences = [ result['sentence'].encode('utf-8') for result in results ]
file.write("\n".join( sentences))
#file.writelines( sentences )
#ipdb.set_trace()
#file.writelines(str(results))
|
<commit_before>#!/usr/bin/python
import requests
import ipdb
import time
import csv
import sys
import pysolr
def fetch_all( solr, query ) :
documents = []
num_matching_documents = solr.search( query ).hits
start = 0
rows = num_matching_documents
sys.stderr.write( ' starting fetch for ' + query )
while ( len( documents ) < num_matching_documents ) :
results = solr.search( query, **{
'start': start,
'rows': rows,
# 'fl' : 'media_id',
})
documents.extend( results.docs )
start += rows
assert len( documents ) <= num_matching_documents
assert len( documents ) == num_matching_documents
return documents
solr = pysolr.Solr('http://localhost:8983/solr/')
queries = [ '*:*',
]
for query in queries:
print query
results = fetch_all( solr, query )
print "got " + query
print results
<commit_msg>Save word counts to file.<commit_after>
|
#!/usr/bin/python
import requests
import ipdb
import time
import csv
import sys
import pysolr
def fetch_all( solr, query ) :
documents = []
num_matching_documents = solr.search( query ).hits
start = 0
rows = num_matching_documents
sys.stderr.write( ' starting fetch for ' + query )
sys.stderr.write( 'fetching {0} documents'.format( rows ) )
while ( len( documents ) < num_matching_documents ) :
results = solr.search( query, **{
'start': start,
'rows': rows,
# 'fl' : 'media_id',
})
documents.extend( results.docs )
start += rows
assert len( documents ) <= num_matching_documents
assert len( documents ) == num_matching_documents
return documents
solr = pysolr.Solr('http://localhost:8983/solr/')
queries = [ 'sentence:obama',
]
file=open('out.txt','wb')
for query in queries:
print query
results = fetch_all( solr, query )
print "got " + query
print len( results )
sentences = [ result['sentence'].encode('utf-8') for result in results ]
file.write("\n".join( sentences))
#file.writelines( sentences )
#ipdb.set_trace()
#file.writelines(str(results))
|
#!/usr/bin/python
import requests
import ipdb
import time
import csv
import sys
import pysolr
def fetch_all( solr, query ) :
documents = []
num_matching_documents = solr.search( query ).hits
start = 0
rows = num_matching_documents
sys.stderr.write( ' starting fetch for ' + query )
while ( len( documents ) < num_matching_documents ) :
results = solr.search( query, **{
'start': start,
'rows': rows,
# 'fl' : 'media_id',
})
documents.extend( results.docs )
start += rows
assert len( documents ) <= num_matching_documents
assert len( documents ) == num_matching_documents
return documents
solr = pysolr.Solr('http://localhost:8983/solr/')
queries = [ '*:*',
]
for query in queries:
print query
results = fetch_all( solr, query )
print "got " + query
print results
Save word counts to file.#!/usr/bin/python
import requests
import ipdb
import time
import csv
import sys
import pysolr
def fetch_all( solr, query ) :
documents = []
num_matching_documents = solr.search( query ).hits
start = 0
rows = num_matching_documents
sys.stderr.write( ' starting fetch for ' + query )
sys.stderr.write( 'fetching {0} documents'.format( rows ) )
while ( len( documents ) < num_matching_documents ) :
results = solr.search( query, **{
'start': start,
'rows': rows,
# 'fl' : 'media_id',
})
documents.extend( results.docs )
start += rows
assert len( documents ) <= num_matching_documents
assert len( documents ) == num_matching_documents
return documents
solr = pysolr.Solr('http://localhost:8983/solr/')
queries = [ 'sentence:obama',
]
file=open('out.txt','wb')
for query in queries:
print query
results = fetch_all( solr, query )
print "got " + query
print len( results )
sentences = [ result['sentence'].encode('utf-8') for result in results ]
file.write("\n".join( sentences))
#file.writelines( sentences )
#ipdb.set_trace()
#file.writelines(str(results))
|
<commit_before>#!/usr/bin/python
import requests
import ipdb
import time
import csv
import sys
import pysolr
def fetch_all( solr, query ) :
documents = []
num_matching_documents = solr.search( query ).hits
start = 0
rows = num_matching_documents
sys.stderr.write( ' starting fetch for ' + query )
while ( len( documents ) < num_matching_documents ) :
results = solr.search( query, **{
'start': start,
'rows': rows,
# 'fl' : 'media_id',
})
documents.extend( results.docs )
start += rows
assert len( documents ) <= num_matching_documents
assert len( documents ) == num_matching_documents
return documents
solr = pysolr.Solr('http://localhost:8983/solr/')
queries = [ '*:*',
]
for query in queries:
print query
results = fetch_all( solr, query )
print "got " + query
print results
<commit_msg>Save word counts to file.<commit_after>#!/usr/bin/python
import requests
import ipdb
import time
import csv
import sys
import pysolr
def fetch_all( solr, query ) :
documents = []
num_matching_documents = solr.search( query ).hits
start = 0
rows = num_matching_documents
sys.stderr.write( ' starting fetch for ' + query )
sys.stderr.write( 'fetching {0} documents'.format( rows ) )
while ( len( documents ) < num_matching_documents ) :
results = solr.search( query, **{
'start': start,
'rows': rows,
# 'fl' : 'media_id',
})
documents.extend( results.docs )
start += rows
assert len( documents ) <= num_matching_documents
assert len( documents ) == num_matching_documents
return documents
solr = pysolr.Solr('http://localhost:8983/solr/')
queries = [ 'sentence:obama',
]
file=open('out.txt','wb')
for query in queries:
print query
results = fetch_all( solr, query )
print "got " + query
print len( results )
sentences = [ result['sentence'].encode('utf-8') for result in results ]
file.write("\n".join( sentences))
#file.writelines( sentences )
#ipdb.set_trace()
#file.writelines(str(results))
|
bc02af25e3bbcb97de838eff1fc130f52258db2d
|
grammar/automator.py
|
grammar/automator.py
|
import os
class Automator:
def __init__(self, real = True):
self.xdo_list = []
self.real = real
def xdo(self, xdo):
self.xdo_list.append(xdo)
def flush(self):
if len(self.xdo_list) == 0: return
command = '/usr/bin/xdotool' + ' '
command += ' '.join(self.xdo_list)
self.execute(command)
self.xdo_list = []
def execute(self, command):
if command == '': return
print "`%s`" % command
if self.real:
os.system(command)
def raw_key(self, k):
self.xdo('key ' + k)
def key(self, k):
if(len(k) > 1): k = k.capitalize()
self.xdo('key ' + k)
|
import os
class Automator:
def __init__(self, real = True):
self.xdo_list = []
self.real = real
def xdo(self, xdo):
self.xdo_list.append(xdo)
def flush(self):
if len(self.xdo_list) == 0: return
command = '/usr/bin/xdotool' + ' '
command += ' '.join(self.xdo_list)
self.execute(command)
self.xdo_list = []
def execute(self, command):
if command == '': return
print "`%s`" % command
if self.real:
os.system(command)
def raw_key(self, k):
if(k == "'"): k = 'apostrophe'
elif(k == '.'): k = 'period'
elif(k == '-'): k = 'minus'
self.xdo('key ' + k)
def key(self, k):
if(len(k) > 1): k = k.capitalize()
self.xdo('key ' + k)
|
Support apostrophe and period in dictation (and minus, just in case).
|
Support apostrophe and period in dictation (and minus, just in case).
Example: "phrase don't like x. rays".
|
Python
|
bsd-2-clause
|
dwks/silvius,dwks/silvius
|
import os
class Automator:
def __init__(self, real = True):
self.xdo_list = []
self.real = real
def xdo(self, xdo):
self.xdo_list.append(xdo)
def flush(self):
if len(self.xdo_list) == 0: return
command = '/usr/bin/xdotool' + ' '
command += ' '.join(self.xdo_list)
self.execute(command)
self.xdo_list = []
def execute(self, command):
if command == '': return
print "`%s`" % command
if self.real:
os.system(command)
def raw_key(self, k):
self.xdo('key ' + k)
def key(self, k):
if(len(k) > 1): k = k.capitalize()
self.xdo('key ' + k)
Support apostrophe and period in dictation (and minus, just in case).
Example: "phrase don't like x. rays".
|
import os
class Automator:
def __init__(self, real = True):
self.xdo_list = []
self.real = real
def xdo(self, xdo):
self.xdo_list.append(xdo)
def flush(self):
if len(self.xdo_list) == 0: return
command = '/usr/bin/xdotool' + ' '
command += ' '.join(self.xdo_list)
self.execute(command)
self.xdo_list = []
def execute(self, command):
if command == '': return
print "`%s`" % command
if self.real:
os.system(command)
def raw_key(self, k):
if(k == "'"): k = 'apostrophe'
elif(k == '.'): k = 'period'
elif(k == '-'): k = 'minus'
self.xdo('key ' + k)
def key(self, k):
if(len(k) > 1): k = k.capitalize()
self.xdo('key ' + k)
|
<commit_before>import os
class Automator:
def __init__(self, real = True):
self.xdo_list = []
self.real = real
def xdo(self, xdo):
self.xdo_list.append(xdo)
def flush(self):
if len(self.xdo_list) == 0: return
command = '/usr/bin/xdotool' + ' '
command += ' '.join(self.xdo_list)
self.execute(command)
self.xdo_list = []
def execute(self, command):
if command == '': return
print "`%s`" % command
if self.real:
os.system(command)
def raw_key(self, k):
self.xdo('key ' + k)
def key(self, k):
if(len(k) > 1): k = k.capitalize()
self.xdo('key ' + k)
<commit_msg>Support apostrophe and period in dictation (and minus, just in case).
Example: "phrase don't like x. rays".<commit_after>
|
import os
class Automator:
def __init__(self, real = True):
self.xdo_list = []
self.real = real
def xdo(self, xdo):
self.xdo_list.append(xdo)
def flush(self):
if len(self.xdo_list) == 0: return
command = '/usr/bin/xdotool' + ' '
command += ' '.join(self.xdo_list)
self.execute(command)
self.xdo_list = []
def execute(self, command):
if command == '': return
print "`%s`" % command
if self.real:
os.system(command)
def raw_key(self, k):
if(k == "'"): k = 'apostrophe'
elif(k == '.'): k = 'period'
elif(k == '-'): k = 'minus'
self.xdo('key ' + k)
def key(self, k):
if(len(k) > 1): k = k.capitalize()
self.xdo('key ' + k)
|
import os
class Automator:
def __init__(self, real = True):
self.xdo_list = []
self.real = real
def xdo(self, xdo):
self.xdo_list.append(xdo)
def flush(self):
if len(self.xdo_list) == 0: return
command = '/usr/bin/xdotool' + ' '
command += ' '.join(self.xdo_list)
self.execute(command)
self.xdo_list = []
def execute(self, command):
if command == '': return
print "`%s`" % command
if self.real:
os.system(command)
def raw_key(self, k):
self.xdo('key ' + k)
def key(self, k):
if(len(k) > 1): k = k.capitalize()
self.xdo('key ' + k)
Support apostrophe and period in dictation (and minus, just in case).
Example: "phrase don't like x. rays".import os
class Automator:
def __init__(self, real = True):
self.xdo_list = []
self.real = real
def xdo(self, xdo):
self.xdo_list.append(xdo)
def flush(self):
if len(self.xdo_list) == 0: return
command = '/usr/bin/xdotool' + ' '
command += ' '.join(self.xdo_list)
self.execute(command)
self.xdo_list = []
def execute(self, command):
if command == '': return
print "`%s`" % command
if self.real:
os.system(command)
def raw_key(self, k):
if(k == "'"): k = 'apostrophe'
elif(k == '.'): k = 'period'
elif(k == '-'): k = 'minus'
self.xdo('key ' + k)
def key(self, k):
if(len(k) > 1): k = k.capitalize()
self.xdo('key ' + k)
|
<commit_before>import os
class Automator:
def __init__(self, real = True):
self.xdo_list = []
self.real = real
def xdo(self, xdo):
self.xdo_list.append(xdo)
def flush(self):
if len(self.xdo_list) == 0: return
command = '/usr/bin/xdotool' + ' '
command += ' '.join(self.xdo_list)
self.execute(command)
self.xdo_list = []
def execute(self, command):
if command == '': return
print "`%s`" % command
if self.real:
os.system(command)
def raw_key(self, k):
self.xdo('key ' + k)
def key(self, k):
if(len(k) > 1): k = k.capitalize()
self.xdo('key ' + k)
<commit_msg>Support apostrophe and period in dictation (and minus, just in case).
Example: "phrase don't like x. rays".<commit_after>import os
class Automator:
def __init__(self, real = True):
self.xdo_list = []
self.real = real
def xdo(self, xdo):
self.xdo_list.append(xdo)
def flush(self):
if len(self.xdo_list) == 0: return
command = '/usr/bin/xdotool' + ' '
command += ' '.join(self.xdo_list)
self.execute(command)
self.xdo_list = []
def execute(self, command):
if command == '': return
print "`%s`" % command
if self.real:
os.system(command)
def raw_key(self, k):
if(k == "'"): k = 'apostrophe'
elif(k == '.'): k = 'period'
elif(k == '-'): k = 'minus'
self.xdo('key ' + k)
def key(self, k):
if(len(k) > 1): k = k.capitalize()
self.xdo('key ' + k)
|
5f935bb952a616c3fe9ca24fa862621dfc1bda24
|
guv/hubs/watchers.py
|
guv/hubs/watchers.py
|
from guv.hubs.abc import AbstractListener
class FdListener(AbstractListener):
"""Default implementation of :cls:`AbstractListener`
"""
pass
class PollFdListener(AbstractListener):
def __init__(self, evtype, fd, cb):
"""
:param cb: Callable
:param args: tuple of arguments to be passed to cb
"""
super().__init__(evtype, fd)
self.cb = cb
class UvFdListener(AbstractListener):
def __init__(self, evtype, fd, handle):
"""
:param handle: underlying pyuv Handle object
:type handle: pyuv.Handle
"""
super().__init__(evtype, fd)
self.handle = handle
|
from guv.hubs.abc import AbstractListener
class PollFdListener(AbstractListener):
def __init__(self, evtype, fd, cb):
"""
:param cb: Callable
:param args: tuple of arguments to be passed to cb
"""
super().__init__(evtype, fd)
self.cb = cb
class UvFdListener(AbstractListener):
def __init__(self, evtype, fd, handle):
"""
:param handle: underlying pyuv Handle object
:type handle: pyuv.Handle
"""
super().__init__(evtype, fd)
self.handle = handle
|
Remove unneeded default Listener implementation
|
Remove unneeded default Listener implementation
|
Python
|
mit
|
veegee/guv,veegee/guv
|
from guv.hubs.abc import AbstractListener
class FdListener(AbstractListener):
"""Default implementation of :cls:`AbstractListener`
"""
pass
class PollFdListener(AbstractListener):
def __init__(self, evtype, fd, cb):
"""
:param cb: Callable
:param args: tuple of arguments to be passed to cb
"""
super().__init__(evtype, fd)
self.cb = cb
class UvFdListener(AbstractListener):
def __init__(self, evtype, fd, handle):
"""
:param handle: underlying pyuv Handle object
:type handle: pyuv.Handle
"""
super().__init__(evtype, fd)
self.handle = handle
Remove unneeded default Listener implementation
|
from guv.hubs.abc import AbstractListener
class PollFdListener(AbstractListener):
def __init__(self, evtype, fd, cb):
"""
:param cb: Callable
:param args: tuple of arguments to be passed to cb
"""
super().__init__(evtype, fd)
self.cb = cb
class UvFdListener(AbstractListener):
def __init__(self, evtype, fd, handle):
"""
:param handle: underlying pyuv Handle object
:type handle: pyuv.Handle
"""
super().__init__(evtype, fd)
self.handle = handle
|
<commit_before>from guv.hubs.abc import AbstractListener
class FdListener(AbstractListener):
"""Default implementation of :cls:`AbstractListener`
"""
pass
class PollFdListener(AbstractListener):
def __init__(self, evtype, fd, cb):
"""
:param cb: Callable
:param args: tuple of arguments to be passed to cb
"""
super().__init__(evtype, fd)
self.cb = cb
class UvFdListener(AbstractListener):
def __init__(self, evtype, fd, handle):
"""
:param handle: underlying pyuv Handle object
:type handle: pyuv.Handle
"""
super().__init__(evtype, fd)
self.handle = handle
<commit_msg>Remove unneeded default Listener implementation<commit_after>
|
from guv.hubs.abc import AbstractListener
class PollFdListener(AbstractListener):
def __init__(self, evtype, fd, cb):
"""
:param cb: Callable
:param args: tuple of arguments to be passed to cb
"""
super().__init__(evtype, fd)
self.cb = cb
class UvFdListener(AbstractListener):
def __init__(self, evtype, fd, handle):
"""
:param handle: underlying pyuv Handle object
:type handle: pyuv.Handle
"""
super().__init__(evtype, fd)
self.handle = handle
|
from guv.hubs.abc import AbstractListener
class FdListener(AbstractListener):
"""Default implementation of :cls:`AbstractListener`
"""
pass
class PollFdListener(AbstractListener):
def __init__(self, evtype, fd, cb):
"""
:param cb: Callable
:param args: tuple of arguments to be passed to cb
"""
super().__init__(evtype, fd)
self.cb = cb
class UvFdListener(AbstractListener):
def __init__(self, evtype, fd, handle):
"""
:param handle: underlying pyuv Handle object
:type handle: pyuv.Handle
"""
super().__init__(evtype, fd)
self.handle = handle
Remove unneeded default Listener implementationfrom guv.hubs.abc import AbstractListener
class PollFdListener(AbstractListener):
def __init__(self, evtype, fd, cb):
"""
:param cb: Callable
:param args: tuple of arguments to be passed to cb
"""
super().__init__(evtype, fd)
self.cb = cb
class UvFdListener(AbstractListener):
def __init__(self, evtype, fd, handle):
"""
:param handle: underlying pyuv Handle object
:type handle: pyuv.Handle
"""
super().__init__(evtype, fd)
self.handle = handle
|
<commit_before>from guv.hubs.abc import AbstractListener
class FdListener(AbstractListener):
"""Default implementation of :cls:`AbstractListener`
"""
pass
class PollFdListener(AbstractListener):
def __init__(self, evtype, fd, cb):
"""
:param cb: Callable
:param args: tuple of arguments to be passed to cb
"""
super().__init__(evtype, fd)
self.cb = cb
class UvFdListener(AbstractListener):
def __init__(self, evtype, fd, handle):
"""
:param handle: underlying pyuv Handle object
:type handle: pyuv.Handle
"""
super().__init__(evtype, fd)
self.handle = handle
<commit_msg>Remove unneeded default Listener implementation<commit_after>from guv.hubs.abc import AbstractListener
class PollFdListener(AbstractListener):
def __init__(self, evtype, fd, cb):
"""
:param cb: Callable
:param args: tuple of arguments to be passed to cb
"""
super().__init__(evtype, fd)
self.cb = cb
class UvFdListener(AbstractListener):
def __init__(self, evtype, fd, handle):
"""
:param handle: underlying pyuv Handle object
:type handle: pyuv.Handle
"""
super().__init__(evtype, fd)
self.handle = handle
|
93cebc0f0a99677f33005502217d83964de48478
|
notifications/templatetags/notifications_tags.py
|
notifications/templatetags/notifications_tags.py
|
# -*- coding: utf-8 -*-
from django.template import Library
from django.template.base import TemplateSyntaxError
from notifications.models import Notification
from django.template import Node
register = Library()
# TODO: Simplify this: it's a really simple tag!
class InboxCountNode(Node):
"For use in the notifications_unread tag"
def __init__(self, asvar=None):
self.asvar = asvar
def render(self, context):
"""
Return the count of unread messages for the user found in context,
(may be 0) or an empty string.
"""
try:
user = context['user']
if user.is_anonymous():
count = ''
else:
count = user.notifications.unread().count()
except (KeyError, AttributeError):
count = ''
if self.asvar:
context[self.asvar] = count
return ''
return count
@register.tag
def notifications_unread(parser, token):
"""
Give the number of unread notifications for a user,
or nothing (an empty string) for an anonymous user.
Storing the count in a variable for further processing is advised, such as::
{% notifications_unread as unread_count %}
...
{% if unread_count %}
You have <strong>{{ unread_count }}</strong> unread notifications.
{% endif %}
"""
bits = token.split_contents()
if len(bits) > 1:
if len(bits) != 3:
raise TemplateSyntaxError("'{0}' tag takes no argument or exactly two arguments".format(bits[0]))
if bits[1] != 'as':
raise TemplateSyntaxError("First argument to '{0}' tag must be 'as'".format(bits[0]))
return InboxCountNode(bits[2])
else:
return InboxCountNode()
|
# -*- coding: utf-8 -*-
from django.template import Library
from django.template.base import TemplateSyntaxError
from django.template import Node
register = Library()
@register.simple_tag(takes_context=True)
def notifications_unread(context):
if 'user' not in context:
return ''
user = context['user']
if user.is_anonymous():
return ''
return user.notifications.unread().count()
|
Simplify the notification tag. No longer can store the value in a variable.
|
Simplify the notification tag.
No longer can store the value in a variable.
|
Python
|
bsd-3-clause
|
iberben/django-notifications,django-notifications/django-notifications,iberben/django-notifications,Evidlo/django-notifications,iberben/django-notifications,brandonberney/basic-django-notifications,alazaro/django-notifications,Natgeoed/django-notifications,brandonberney/basic-django-notifications,philroche/django-notifications,lyoniionly/django-notifications,pebreo/django-notifications,LegoStormtroopr/django-notifications,error0608/django-notifications,zhang-z/django-notifications,django-notifications/django-notifications,lukeburden/django-notifications,letolab/django-notifications,alazaro/django-notifications,letolab/django-notifications,jimlyndon/django-notifications,philroche/django-notifications,brandonberney/basic-django-notifications,philroche/django-notifications,ganeshp-cuelogic/django-notifications,lyoniionly/django-notifications,pebreo/django-notifications,jimlyndon/django-notifications,natgeo/django-notifications,jimlyndon/django-notifications,zhang-z/django-notifications,ganeshp-cuelogic/django-notifications,zhang-z/django-notifications,LegoStormtroopr/django-notifications,alazaro/django-notifications,LegoStormtroopr/django-notifications,ganeshp-cuelogic/django-notifications,lukeburden/django-notifications,django-notifications/django-notifications,error0608/django-notifications,lukeburden/django-notifications,Evidlo/django-notifications,error0608/django-notifications,letolab/django-notifications,Evidlo/django-notifications,pebreo/django-notifications
|
# -*- coding: utf-8 -*-
from django.template import Library
from django.template.base import TemplateSyntaxError
from notifications.models import Notification
from django.template import Node
register = Library()
# TODO: Simplify this: it's a really simple tag!
class InboxCountNode(Node):
"For use in the notifications_unread tag"
def __init__(self, asvar=None):
self.asvar = asvar
def render(self, context):
"""
Return the count of unread messages for the user found in context,
(may be 0) or an empty string.
"""
try:
user = context['user']
if user.is_anonymous():
count = ''
else:
count = user.notifications.unread().count()
except (KeyError, AttributeError):
count = ''
if self.asvar:
context[self.asvar] = count
return ''
return count
@register.tag
def notifications_unread(parser, token):
"""
Give the number of unread notifications for a user,
or nothing (an empty string) for an anonymous user.
Storing the count in a variable for further processing is advised, such as::
{% notifications_unread as unread_count %}
...
{% if unread_count %}
You have <strong>{{ unread_count }}</strong> unread notifications.
{% endif %}
"""
bits = token.split_contents()
if len(bits) > 1:
if len(bits) != 3:
raise TemplateSyntaxError("'{0}' tag takes no argument or exactly two arguments".format(bits[0]))
if bits[1] != 'as':
raise TemplateSyntaxError("First argument to '{0}' tag must be 'as'".format(bits[0]))
return InboxCountNode(bits[2])
else:
return InboxCountNode()
Simplify the notification tag.
No longer can store the value in a variable.
|
# -*- coding: utf-8 -*-
from django.template import Library
from django.template.base import TemplateSyntaxError
from django.template import Node
register = Library()
@register.simple_tag(takes_context=True)
def notifications_unread(context):
if 'user' not in context:
return ''
user = context['user']
if user.is_anonymous():
return ''
return user.notifications.unread().count()
|
<commit_before># -*- coding: utf-8 -*-
from django.template import Library
from django.template.base import TemplateSyntaxError
from notifications.models import Notification
from django.template import Node
register = Library()
# TODO: Simplify this: it's a really simple tag!
class InboxCountNode(Node):
"For use in the notifications_unread tag"
def __init__(self, asvar=None):
self.asvar = asvar
def render(self, context):
"""
Return the count of unread messages for the user found in context,
(may be 0) or an empty string.
"""
try:
user = context['user']
if user.is_anonymous():
count = ''
else:
count = user.notifications.unread().count()
except (KeyError, AttributeError):
count = ''
if self.asvar:
context[self.asvar] = count
return ''
return count
@register.tag
def notifications_unread(parser, token):
"""
Give the number of unread notifications for a user,
or nothing (an empty string) for an anonymous user.
Storing the count in a variable for further processing is advised, such as::
{% notifications_unread as unread_count %}
...
{% if unread_count %}
You have <strong>{{ unread_count }}</strong> unread notifications.
{% endif %}
"""
bits = token.split_contents()
if len(bits) > 1:
if len(bits) != 3:
raise TemplateSyntaxError("'{0}' tag takes no argument or exactly two arguments".format(bits[0]))
if bits[1] != 'as':
raise TemplateSyntaxError("First argument to '{0}' tag must be 'as'".format(bits[0]))
return InboxCountNode(bits[2])
else:
return InboxCountNode()
<commit_msg>Simplify the notification tag.
No longer can store the value in a variable.<commit_after>
|
# -*- coding: utf-8 -*-
from django.template import Library
from django.template.base import TemplateSyntaxError
from django.template import Node
register = Library()
@register.simple_tag(takes_context=True)
def notifications_unread(context):
if 'user' not in context:
return ''
user = context['user']
if user.is_anonymous():
return ''
return user.notifications.unread().count()
|
# -*- coding: utf-8 -*-
from django.template import Library
from django.template.base import TemplateSyntaxError
from notifications.models import Notification
from django.template import Node
register = Library()
# TODO: Simplify this: it's a really simple tag!
class InboxCountNode(Node):
"For use in the notifications_unread tag"
def __init__(self, asvar=None):
self.asvar = asvar
def render(self, context):
"""
Return the count of unread messages for the user found in context,
(may be 0) or an empty string.
"""
try:
user = context['user']
if user.is_anonymous():
count = ''
else:
count = user.notifications.unread().count()
except (KeyError, AttributeError):
count = ''
if self.asvar:
context[self.asvar] = count
return ''
return count
@register.tag
def notifications_unread(parser, token):
"""
Give the number of unread notifications for a user,
or nothing (an empty string) for an anonymous user.
Storing the count in a variable for further processing is advised, such as::
{% notifications_unread as unread_count %}
...
{% if unread_count %}
You have <strong>{{ unread_count }}</strong> unread notifications.
{% endif %}
"""
bits = token.split_contents()
if len(bits) > 1:
if len(bits) != 3:
raise TemplateSyntaxError("'{0}' tag takes no argument or exactly two arguments".format(bits[0]))
if bits[1] != 'as':
raise TemplateSyntaxError("First argument to '{0}' tag must be 'as'".format(bits[0]))
return InboxCountNode(bits[2])
else:
return InboxCountNode()
Simplify the notification tag.
No longer can store the value in a variable.# -*- coding: utf-8 -*-
from django.template import Library
from django.template.base import TemplateSyntaxError
from django.template import Node
register = Library()
@register.simple_tag(takes_context=True)
def notifications_unread(context):
if 'user' not in context:
return ''
user = context['user']
if user.is_anonymous():
return ''
return user.notifications.unread().count()
|
<commit_before># -*- coding: utf-8 -*-
from django.template import Library
from django.template.base import TemplateSyntaxError
from notifications.models import Notification
from django.template import Node
register = Library()
# TODO: Simplify this: it's a really simple tag!
class InboxCountNode(Node):
"For use in the notifications_unread tag"
def __init__(self, asvar=None):
self.asvar = asvar
def render(self, context):
"""
Return the count of unread messages for the user found in context,
(may be 0) or an empty string.
"""
try:
user = context['user']
if user.is_anonymous():
count = ''
else:
count = user.notifications.unread().count()
except (KeyError, AttributeError):
count = ''
if self.asvar:
context[self.asvar] = count
return ''
return count
@register.tag
def notifications_unread(parser, token):
"""
Give the number of unread notifications for a user,
or nothing (an empty string) for an anonymous user.
Storing the count in a variable for further processing is advised, such as::
{% notifications_unread as unread_count %}
...
{% if unread_count %}
You have <strong>{{ unread_count }}</strong> unread notifications.
{% endif %}
"""
bits = token.split_contents()
if len(bits) > 1:
if len(bits) != 3:
raise TemplateSyntaxError("'{0}' tag takes no argument or exactly two arguments".format(bits[0]))
if bits[1] != 'as':
raise TemplateSyntaxError("First argument to '{0}' tag must be 'as'".format(bits[0]))
return InboxCountNode(bits[2])
else:
return InboxCountNode()
<commit_msg>Simplify the notification tag.
No longer can store the value in a variable.<commit_after># -*- coding: utf-8 -*-
from django.template import Library
from django.template.base import TemplateSyntaxError
from django.template import Node
register = Library()
@register.simple_tag(takes_context=True)
def notifications_unread(context):
if 'user' not in context:
return ''
user = context['user']
if user.is_anonymous():
return ''
return user.notifications.unread().count()
|
4d8b0fefa420efd60da0c6a29968f2fd441b9e09
|
openbox/configuration_builder/transformations.py
|
openbox/configuration_builder/transformations.py
|
def to_int(value):
return int(value)
def identity(value):
return value
|
def to_int(value, num=None):
return int(value)
def to_float(value, num=None):
return float(value)
def identity(value, num=None):
return value
|
Add to_float function and add num keyword
|
Transformations: Add to_float function and add num keyword
|
Python
|
apache-2.0
|
DeepnessLab/obsi,OpenBoxProject/obsi,DeepnessLab/obsi,pavel-lazar/obsi,pavel-lazar/obsi,OpenBoxProject/obsi,DeepnessLab/obsi,pavel-lazar/obsi,DeepnessLab/obsi,pavel-lazar/obsi,OpenBoxProject/obsi,OpenBoxProject/obsi
|
def to_int(value):
return int(value)
def identity(value):
return valueTransformations: Add to_float function and add num keyword
|
def to_int(value, num=None):
return int(value)
def to_float(value, num=None):
return float(value)
def identity(value, num=None):
return value
|
<commit_before>def to_int(value):
return int(value)
def identity(value):
return value<commit_msg>Transformations: Add to_float function and add num keyword<commit_after>
|
def to_int(value, num=None):
return int(value)
def to_float(value, num=None):
return float(value)
def identity(value, num=None):
return value
|
def to_int(value):
return int(value)
def identity(value):
return valueTransformations: Add to_float function and add num keyworddef to_int(value, num=None):
return int(value)
def to_float(value, num=None):
return float(value)
def identity(value, num=None):
return value
|
<commit_before>def to_int(value):
return int(value)
def identity(value):
return value<commit_msg>Transformations: Add to_float function and add num keyword<commit_after>def to_int(value, num=None):
return int(value)
def to_float(value, num=None):
return float(value)
def identity(value, num=None):
return value
|
aaf8ebb7b1b12b15ab96c2cd1d7cb053154e8d64
|
tests/lib/query_models/test_query_string_match.py
|
tests/lib/query_models/test_query_string_match.py
|
from positive_test_suite import PositiveTestSuite
from negative_test_suite import NegativeTestSuite
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../../lib"))
from query_models import QueryStringMatch
class TestQueryStringMatchPositiveTestSuite(PositiveTestSuite):
def query_tests(self):
tests = {
QueryStringMatch('summary: test'): [
{'summary': 'test'},
],
QueryStringMatch('summary: test conf'): [
{'summary': 'test'},
{'summary': 'conf'},
{'summary': 'test conf'},
],
}
return tests
class TestQueryStringMatchNegativeTestSuite(NegativeTestSuite):
def query_tests(self):
tests = {
QueryStringMatch('summary: test'): [
{'summary': 'example summary'},
{'summary': 'example summary tes'},
{'summary': 'testing'},
{'note': 'test'},
],
QueryStringMatch('summary: test conf'): [
{'summary': 'testing'},
{'summary': 'configuration'},
{'summary': 'testing configuration'},
],
}
return tests
|
from positive_test_suite import PositiveTestSuite
from negative_test_suite import NegativeTestSuite
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../../lib"))
from query_models import QueryStringMatch
hostname_test_regex = 'hostname: /(.*\.)*(sub|bus)+(\..*)*\.abc(\..*)*\.company\.com/'
class TestQueryStringMatchPositiveTestSuite(PositiveTestSuite):
def query_tests(self):
tests = {
QueryStringMatch('summary: test'): [
{'summary': 'test'},
],
QueryStringMatch('summary: test conf'): [
{'summary': 'test'},
{'summary': 'conf'},
{'summary': 'test conf'},
],
QueryStringMatch(hostname_test_regex): [
{'hostname': 'host1.sub.abc.company.com'},
{'hostname': 'host1.sub.test.abc.company.com'},
{'hostname': 'host1.sub.test.abc.domain.company.com'},
{'hostname': 'host1.sub.abc.domain.company.com'},
{'hostname': 'host2.bus.abc.domain.company.com'},
],
}
return tests
class TestQueryStringMatchNegativeTestSuite(NegativeTestSuite):
def query_tests(self):
tests = {
QueryStringMatch('summary: test'): [
{'summary': 'example summary'},
{'summary': 'example summary tes'},
{'summary': 'testing'},
{'note': 'test'},
],
QueryStringMatch('summary: test conf'): [
{'summary': 'testing'},
{'summary': 'configuration'},
{'summary': 'testing configuration'},
],
QueryStringMatch(hostname_test_regex): [
{'hostname': 'host1.sub.abcd.company.com'},
{'hostname': 'host1.sub.dabc.company.com'},
{'hostname': 'host1.suba.abc.company.com'},
{'hostname': 'host1.asub.abc.company.com'},
{'hostname': 'host1.sub.dabc.domain.companyabc.com'},
{'hostname': 'host2.bus.abc.domain.abcompany.com'},
],
}
return tests
|
Add extra tests to query string query model
|
Add extra tests to query string query model
|
Python
|
mpl-2.0
|
ameihm0912/MozDef,jeffbryner/MozDef,mpurzynski/MozDef,gdestuynder/MozDef,jeffbryner/MozDef,ameihm0912/MozDef,mpurzynski/MozDef,Phrozyn/MozDef,Phrozyn/MozDef,mpurzynski/MozDef,Phrozyn/MozDef,gdestuynder/MozDef,ameihm0912/MozDef,Phrozyn/MozDef,mozilla/MozDef,jeffbryner/MozDef,ameihm0912/MozDef,jeffbryner/MozDef,gdestuynder/MozDef,gdestuynder/MozDef,mpurzynski/MozDef,mozilla/MozDef,mozilla/MozDef,mozilla/MozDef
|
from positive_test_suite import PositiveTestSuite
from negative_test_suite import NegativeTestSuite
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../../lib"))
from query_models import QueryStringMatch
class TestQueryStringMatchPositiveTestSuite(PositiveTestSuite):
def query_tests(self):
tests = {
QueryStringMatch('summary: test'): [
{'summary': 'test'},
],
QueryStringMatch('summary: test conf'): [
{'summary': 'test'},
{'summary': 'conf'},
{'summary': 'test conf'},
],
}
return tests
class TestQueryStringMatchNegativeTestSuite(NegativeTestSuite):
def query_tests(self):
tests = {
QueryStringMatch('summary: test'): [
{'summary': 'example summary'},
{'summary': 'example summary tes'},
{'summary': 'testing'},
{'note': 'test'},
],
QueryStringMatch('summary: test conf'): [
{'summary': 'testing'},
{'summary': 'configuration'},
{'summary': 'testing configuration'},
],
}
return tests
Add extra tests to query string query model
|
from positive_test_suite import PositiveTestSuite
from negative_test_suite import NegativeTestSuite
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../../lib"))
from query_models import QueryStringMatch
hostname_test_regex = 'hostname: /(.*\.)*(sub|bus)+(\..*)*\.abc(\..*)*\.company\.com/'
class TestQueryStringMatchPositiveTestSuite(PositiveTestSuite):
def query_tests(self):
tests = {
QueryStringMatch('summary: test'): [
{'summary': 'test'},
],
QueryStringMatch('summary: test conf'): [
{'summary': 'test'},
{'summary': 'conf'},
{'summary': 'test conf'},
],
QueryStringMatch(hostname_test_regex): [
{'hostname': 'host1.sub.abc.company.com'},
{'hostname': 'host1.sub.test.abc.company.com'},
{'hostname': 'host1.sub.test.abc.domain.company.com'},
{'hostname': 'host1.sub.abc.domain.company.com'},
{'hostname': 'host2.bus.abc.domain.company.com'},
],
}
return tests
class TestQueryStringMatchNegativeTestSuite(NegativeTestSuite):
def query_tests(self):
tests = {
QueryStringMatch('summary: test'): [
{'summary': 'example summary'},
{'summary': 'example summary tes'},
{'summary': 'testing'},
{'note': 'test'},
],
QueryStringMatch('summary: test conf'): [
{'summary': 'testing'},
{'summary': 'configuration'},
{'summary': 'testing configuration'},
],
QueryStringMatch(hostname_test_regex): [
{'hostname': 'host1.sub.abcd.company.com'},
{'hostname': 'host1.sub.dabc.company.com'},
{'hostname': 'host1.suba.abc.company.com'},
{'hostname': 'host1.asub.abc.company.com'},
{'hostname': 'host1.sub.dabc.domain.companyabc.com'},
{'hostname': 'host2.bus.abc.domain.abcompany.com'},
],
}
return tests
|
<commit_before>from positive_test_suite import PositiveTestSuite
from negative_test_suite import NegativeTestSuite
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../../lib"))
from query_models import QueryStringMatch
class TestQueryStringMatchPositiveTestSuite(PositiveTestSuite):
def query_tests(self):
tests = {
QueryStringMatch('summary: test'): [
{'summary': 'test'},
],
QueryStringMatch('summary: test conf'): [
{'summary': 'test'},
{'summary': 'conf'},
{'summary': 'test conf'},
],
}
return tests
class TestQueryStringMatchNegativeTestSuite(NegativeTestSuite):
def query_tests(self):
tests = {
QueryStringMatch('summary: test'): [
{'summary': 'example summary'},
{'summary': 'example summary tes'},
{'summary': 'testing'},
{'note': 'test'},
],
QueryStringMatch('summary: test conf'): [
{'summary': 'testing'},
{'summary': 'configuration'},
{'summary': 'testing configuration'},
],
}
return tests
<commit_msg>Add extra tests to query string query model<commit_after>
|
from positive_test_suite import PositiveTestSuite
from negative_test_suite import NegativeTestSuite
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../../lib"))
from query_models import QueryStringMatch
hostname_test_regex = 'hostname: /(.*\.)*(sub|bus)+(\..*)*\.abc(\..*)*\.company\.com/'
class TestQueryStringMatchPositiveTestSuite(PositiveTestSuite):
def query_tests(self):
tests = {
QueryStringMatch('summary: test'): [
{'summary': 'test'},
],
QueryStringMatch('summary: test conf'): [
{'summary': 'test'},
{'summary': 'conf'},
{'summary': 'test conf'},
],
QueryStringMatch(hostname_test_regex): [
{'hostname': 'host1.sub.abc.company.com'},
{'hostname': 'host1.sub.test.abc.company.com'},
{'hostname': 'host1.sub.test.abc.domain.company.com'},
{'hostname': 'host1.sub.abc.domain.company.com'},
{'hostname': 'host2.bus.abc.domain.company.com'},
],
}
return tests
class TestQueryStringMatchNegativeTestSuite(NegativeTestSuite):
def query_tests(self):
tests = {
QueryStringMatch('summary: test'): [
{'summary': 'example summary'},
{'summary': 'example summary tes'},
{'summary': 'testing'},
{'note': 'test'},
],
QueryStringMatch('summary: test conf'): [
{'summary': 'testing'},
{'summary': 'configuration'},
{'summary': 'testing configuration'},
],
QueryStringMatch(hostname_test_regex): [
{'hostname': 'host1.sub.abcd.company.com'},
{'hostname': 'host1.sub.dabc.company.com'},
{'hostname': 'host1.suba.abc.company.com'},
{'hostname': 'host1.asub.abc.company.com'},
{'hostname': 'host1.sub.dabc.domain.companyabc.com'},
{'hostname': 'host2.bus.abc.domain.abcompany.com'},
],
}
return tests
|
from positive_test_suite import PositiveTestSuite
from negative_test_suite import NegativeTestSuite
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../../lib"))
from query_models import QueryStringMatch
class TestQueryStringMatchPositiveTestSuite(PositiveTestSuite):
def query_tests(self):
tests = {
QueryStringMatch('summary: test'): [
{'summary': 'test'},
],
QueryStringMatch('summary: test conf'): [
{'summary': 'test'},
{'summary': 'conf'},
{'summary': 'test conf'},
],
}
return tests
class TestQueryStringMatchNegativeTestSuite(NegativeTestSuite):
def query_tests(self):
tests = {
QueryStringMatch('summary: test'): [
{'summary': 'example summary'},
{'summary': 'example summary tes'},
{'summary': 'testing'},
{'note': 'test'},
],
QueryStringMatch('summary: test conf'): [
{'summary': 'testing'},
{'summary': 'configuration'},
{'summary': 'testing configuration'},
],
}
return tests
Add extra tests to query string query modelfrom positive_test_suite import PositiveTestSuite
from negative_test_suite import NegativeTestSuite
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../../lib"))
from query_models import QueryStringMatch
hostname_test_regex = 'hostname: /(.*\.)*(sub|bus)+(\..*)*\.abc(\..*)*\.company\.com/'
class TestQueryStringMatchPositiveTestSuite(PositiveTestSuite):
def query_tests(self):
tests = {
QueryStringMatch('summary: test'): [
{'summary': 'test'},
],
QueryStringMatch('summary: test conf'): [
{'summary': 'test'},
{'summary': 'conf'},
{'summary': 'test conf'},
],
QueryStringMatch(hostname_test_regex): [
{'hostname': 'host1.sub.abc.company.com'},
{'hostname': 'host1.sub.test.abc.company.com'},
{'hostname': 'host1.sub.test.abc.domain.company.com'},
{'hostname': 'host1.sub.abc.domain.company.com'},
{'hostname': 'host2.bus.abc.domain.company.com'},
],
}
return tests
class TestQueryStringMatchNegativeTestSuite(NegativeTestSuite):
def query_tests(self):
tests = {
QueryStringMatch('summary: test'): [
{'summary': 'example summary'},
{'summary': 'example summary tes'},
{'summary': 'testing'},
{'note': 'test'},
],
QueryStringMatch('summary: test conf'): [
{'summary': 'testing'},
{'summary': 'configuration'},
{'summary': 'testing configuration'},
],
QueryStringMatch(hostname_test_regex): [
{'hostname': 'host1.sub.abcd.company.com'},
{'hostname': 'host1.sub.dabc.company.com'},
{'hostname': 'host1.suba.abc.company.com'},
{'hostname': 'host1.asub.abc.company.com'},
{'hostname': 'host1.sub.dabc.domain.companyabc.com'},
{'hostname': 'host2.bus.abc.domain.abcompany.com'},
],
}
return tests
|
<commit_before>from positive_test_suite import PositiveTestSuite
from negative_test_suite import NegativeTestSuite
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../../lib"))
from query_models import QueryStringMatch
class TestQueryStringMatchPositiveTestSuite(PositiveTestSuite):
def query_tests(self):
tests = {
QueryStringMatch('summary: test'): [
{'summary': 'test'},
],
QueryStringMatch('summary: test conf'): [
{'summary': 'test'},
{'summary': 'conf'},
{'summary': 'test conf'},
],
}
return tests
class TestQueryStringMatchNegativeTestSuite(NegativeTestSuite):
def query_tests(self):
tests = {
QueryStringMatch('summary: test'): [
{'summary': 'example summary'},
{'summary': 'example summary tes'},
{'summary': 'testing'},
{'note': 'test'},
],
QueryStringMatch('summary: test conf'): [
{'summary': 'testing'},
{'summary': 'configuration'},
{'summary': 'testing configuration'},
],
}
return tests
<commit_msg>Add extra tests to query string query model<commit_after>from positive_test_suite import PositiveTestSuite
from negative_test_suite import NegativeTestSuite
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../../lib"))
from query_models import QueryStringMatch
hostname_test_regex = 'hostname: /(.*\.)*(sub|bus)+(\..*)*\.abc(\..*)*\.company\.com/'
class TestQueryStringMatchPositiveTestSuite(PositiveTestSuite):
def query_tests(self):
tests = {
QueryStringMatch('summary: test'): [
{'summary': 'test'},
],
QueryStringMatch('summary: test conf'): [
{'summary': 'test'},
{'summary': 'conf'},
{'summary': 'test conf'},
],
QueryStringMatch(hostname_test_regex): [
{'hostname': 'host1.sub.abc.company.com'},
{'hostname': 'host1.sub.test.abc.company.com'},
{'hostname': 'host1.sub.test.abc.domain.company.com'},
{'hostname': 'host1.sub.abc.domain.company.com'},
{'hostname': 'host2.bus.abc.domain.company.com'},
],
}
return tests
class TestQueryStringMatchNegativeTestSuite(NegativeTestSuite):
def query_tests(self):
tests = {
QueryStringMatch('summary: test'): [
{'summary': 'example summary'},
{'summary': 'example summary tes'},
{'summary': 'testing'},
{'note': 'test'},
],
QueryStringMatch('summary: test conf'): [
{'summary': 'testing'},
{'summary': 'configuration'},
{'summary': 'testing configuration'},
],
QueryStringMatch(hostname_test_regex): [
{'hostname': 'host1.sub.abcd.company.com'},
{'hostname': 'host1.sub.dabc.company.com'},
{'hostname': 'host1.suba.abc.company.com'},
{'hostname': 'host1.asub.abc.company.com'},
{'hostname': 'host1.sub.dabc.domain.companyabc.com'},
{'hostname': 'host2.bus.abc.domain.abcompany.com'},
],
}
return tests
|
ff2bf51f003fc5af1f62fc1aa181ca11a766c8f6
|
fs/archive/__init__.py
|
fs/archive/__init__.py
|
# coding: utf-8
from __future__ import absolute_import
from __future__ import unicode_literals
import contextlib
@contextlib.contextmanager
def open_archive(fs_url, archive):
from pkg_resources import iter_entry_points
from ..opener import open_fs
from ..opener._errors import Unsupported
it = iter_entry_points('fs.archive.open_archive')
entry_point = next((ep for ep in it if archive.endswith(ep.name)), None)
if entry_point is None:
raise Unsupported(
'unknown archive extension: {}'.format(archive))
archive_opener = entry_point.load()
# if not isinstance(archive_fs, base.ArchiveFS):
# raise TypeError('bad entry point')
try:
with open_fs(fs_url) as fs:
binfile = fs.openbin(archive, 'r+' if fs.isfile(archive) else 'w')
archive_fs = archive_opener(binfile)
yield archive_fs
finally:
archive_fs.close()
binfile.close()
__all__ = ['open_archive']
|
# coding: utf-8
from __future__ import absolute_import
from __future__ import unicode_literals
import contextlib
@contextlib.contextmanager
def open_archive(fs_url, archive):
from pkg_resources import iter_entry_points
from ..opener import open_fs
from ..opener._errors import Unsupported
it = iter_entry_points('fs.archive.open_archive')
entry_point = next((ep for ep in it if archive.endswith(ep.name)), None)
if entry_point is None:
raise Unsupported(
'unknown archive extension: {}'.format(archive))
archive_opener = entry_point.load()
# if not isinstance(archive_fs, base.ArchiveFS):
# raise TypeError('bad entry point')
try:
#with open_fs(fs_url) as fs:
fs = open_fs(fs_url)
binfile = fs.openbin(archive, 'r+' if fs.isfile(archive) else 'w')
archive_fs = archive_opener(binfile)
yield archive_fs
finally:
archive_fs.close()
binfile.close()
if fs is not fs_url: # close the fs if we opened it
fs.close()
__all__ = ['open_archive']
|
Make sure files and FS are properly closed in open_archive
|
Make sure files and FS are properly closed in open_archive
|
Python
|
mit
|
althonos/fs.archive
|
# coding: utf-8
from __future__ import absolute_import
from __future__ import unicode_literals
import contextlib
@contextlib.contextmanager
def open_archive(fs_url, archive):
from pkg_resources import iter_entry_points
from ..opener import open_fs
from ..opener._errors import Unsupported
it = iter_entry_points('fs.archive.open_archive')
entry_point = next((ep for ep in it if archive.endswith(ep.name)), None)
if entry_point is None:
raise Unsupported(
'unknown archive extension: {}'.format(archive))
archive_opener = entry_point.load()
# if not isinstance(archive_fs, base.ArchiveFS):
# raise TypeError('bad entry point')
try:
with open_fs(fs_url) as fs:
binfile = fs.openbin(archive, 'r+' if fs.isfile(archive) else 'w')
archive_fs = archive_opener(binfile)
yield archive_fs
finally:
archive_fs.close()
binfile.close()
__all__ = ['open_archive']
Make sure files and FS are properly closed in open_archive
|
# coding: utf-8
from __future__ import absolute_import
from __future__ import unicode_literals
import contextlib
@contextlib.contextmanager
def open_archive(fs_url, archive):
from pkg_resources import iter_entry_points
from ..opener import open_fs
from ..opener._errors import Unsupported
it = iter_entry_points('fs.archive.open_archive')
entry_point = next((ep for ep in it if archive.endswith(ep.name)), None)
if entry_point is None:
raise Unsupported(
'unknown archive extension: {}'.format(archive))
archive_opener = entry_point.load()
# if not isinstance(archive_fs, base.ArchiveFS):
# raise TypeError('bad entry point')
try:
#with open_fs(fs_url) as fs:
fs = open_fs(fs_url)
binfile = fs.openbin(archive, 'r+' if fs.isfile(archive) else 'w')
archive_fs = archive_opener(binfile)
yield archive_fs
finally:
archive_fs.close()
binfile.close()
if fs is not fs_url: # close the fs if we opened it
fs.close()
__all__ = ['open_archive']
|
<commit_before># coding: utf-8
from __future__ import absolute_import
from __future__ import unicode_literals
import contextlib
@contextlib.contextmanager
def open_archive(fs_url, archive):
from pkg_resources import iter_entry_points
from ..opener import open_fs
from ..opener._errors import Unsupported
it = iter_entry_points('fs.archive.open_archive')
entry_point = next((ep for ep in it if archive.endswith(ep.name)), None)
if entry_point is None:
raise Unsupported(
'unknown archive extension: {}'.format(archive))
archive_opener = entry_point.load()
# if not isinstance(archive_fs, base.ArchiveFS):
# raise TypeError('bad entry point')
try:
with open_fs(fs_url) as fs:
binfile = fs.openbin(archive, 'r+' if fs.isfile(archive) else 'w')
archive_fs = archive_opener(binfile)
yield archive_fs
finally:
archive_fs.close()
binfile.close()
__all__ = ['open_archive']
<commit_msg>Make sure files and FS are properly closed in open_archive<commit_after>
|
# coding: utf-8
from __future__ import absolute_import
from __future__ import unicode_literals
import contextlib
@contextlib.contextmanager
def open_archive(fs_url, archive):
from pkg_resources import iter_entry_points
from ..opener import open_fs
from ..opener._errors import Unsupported
it = iter_entry_points('fs.archive.open_archive')
entry_point = next((ep for ep in it if archive.endswith(ep.name)), None)
if entry_point is None:
raise Unsupported(
'unknown archive extension: {}'.format(archive))
archive_opener = entry_point.load()
# if not isinstance(archive_fs, base.ArchiveFS):
# raise TypeError('bad entry point')
try:
#with open_fs(fs_url) as fs:
fs = open_fs(fs_url)
binfile = fs.openbin(archive, 'r+' if fs.isfile(archive) else 'w')
archive_fs = archive_opener(binfile)
yield archive_fs
finally:
archive_fs.close()
binfile.close()
if fs is not fs_url: # close the fs if we opened it
fs.close()
__all__ = ['open_archive']
|
# coding: utf-8
from __future__ import absolute_import
from __future__ import unicode_literals
import contextlib
@contextlib.contextmanager
def open_archive(fs_url, archive):
from pkg_resources import iter_entry_points
from ..opener import open_fs
from ..opener._errors import Unsupported
it = iter_entry_points('fs.archive.open_archive')
entry_point = next((ep for ep in it if archive.endswith(ep.name)), None)
if entry_point is None:
raise Unsupported(
'unknown archive extension: {}'.format(archive))
archive_opener = entry_point.load()
# if not isinstance(archive_fs, base.ArchiveFS):
# raise TypeError('bad entry point')
try:
with open_fs(fs_url) as fs:
binfile = fs.openbin(archive, 'r+' if fs.isfile(archive) else 'w')
archive_fs = archive_opener(binfile)
yield archive_fs
finally:
archive_fs.close()
binfile.close()
__all__ = ['open_archive']
Make sure files and FS are properly closed in open_archive# coding: utf-8
from __future__ import absolute_import
from __future__ import unicode_literals
import contextlib
@contextlib.contextmanager
def open_archive(fs_url, archive):
from pkg_resources import iter_entry_points
from ..opener import open_fs
from ..opener._errors import Unsupported
it = iter_entry_points('fs.archive.open_archive')
entry_point = next((ep for ep in it if archive.endswith(ep.name)), None)
if entry_point is None:
raise Unsupported(
'unknown archive extension: {}'.format(archive))
archive_opener = entry_point.load()
# if not isinstance(archive_fs, base.ArchiveFS):
# raise TypeError('bad entry point')
try:
#with open_fs(fs_url) as fs:
fs = open_fs(fs_url)
binfile = fs.openbin(archive, 'r+' if fs.isfile(archive) else 'w')
archive_fs = archive_opener(binfile)
yield archive_fs
finally:
archive_fs.close()
binfile.close()
if fs is not fs_url: # close the fs if we opened it
fs.close()
__all__ = ['open_archive']
|
<commit_before># coding: utf-8
from __future__ import absolute_import
from __future__ import unicode_literals
import contextlib
@contextlib.contextmanager
def open_archive(fs_url, archive):
from pkg_resources import iter_entry_points
from ..opener import open_fs
from ..opener._errors import Unsupported
it = iter_entry_points('fs.archive.open_archive')
entry_point = next((ep for ep in it if archive.endswith(ep.name)), None)
if entry_point is None:
raise Unsupported(
'unknown archive extension: {}'.format(archive))
archive_opener = entry_point.load()
# if not isinstance(archive_fs, base.ArchiveFS):
# raise TypeError('bad entry point')
try:
with open_fs(fs_url) as fs:
binfile = fs.openbin(archive, 'r+' if fs.isfile(archive) else 'w')
archive_fs = archive_opener(binfile)
yield archive_fs
finally:
archive_fs.close()
binfile.close()
__all__ = ['open_archive']
<commit_msg>Make sure files and FS are properly closed in open_archive<commit_after># coding: utf-8
from __future__ import absolute_import
from __future__ import unicode_literals
import contextlib
@contextlib.contextmanager
def open_archive(fs_url, archive):
from pkg_resources import iter_entry_points
from ..opener import open_fs
from ..opener._errors import Unsupported
it = iter_entry_points('fs.archive.open_archive')
entry_point = next((ep for ep in it if archive.endswith(ep.name)), None)
if entry_point is None:
raise Unsupported(
'unknown archive extension: {}'.format(archive))
archive_opener = entry_point.load()
# if not isinstance(archive_fs, base.ArchiveFS):
# raise TypeError('bad entry point')
try:
#with open_fs(fs_url) as fs:
fs = open_fs(fs_url)
binfile = fs.openbin(archive, 'r+' if fs.isfile(archive) else 'w')
archive_fs = archive_opener(binfile)
yield archive_fs
finally:
archive_fs.close()
binfile.close()
if fs is not fs_url: # close the fs if we opened it
fs.close()
__all__ = ['open_archive']
|
12c1ee81843e3e163756a39b68671cf5c1842df2
|
scrapi/harvesters/mason_archival.py
|
scrapi/harvesters/mason_archival.py
|
"""
Harvester for Mason Archival Repository Service for the SHARE NS
"""
from __future__ import unicode_literals
from scrapi.base import OAIHarvester
class MasonArchival(OAIHarvester):
short_name = 'mason'
long_name = 'Mason Archival Repository Service'
url = 'http://mars.gmu.edu/'
base_url = 'http://mars.gmu.edu/oai/request'
timezone_granularity = True
property_list = [
'type', 'source', 'setSpec',
'format', 'identifier'
]
approved_sets = [
'col_1920_6102',
'col_1920_6039',
'com_1920_262',
'com_1920_466',
'com_1920_1320',
'com_1920_2852',
'com_1920_2869',
'com_1920_2883',
'com_1920_3011',
'com_1920_7520',
'com_1920_8132',
'com_1920_8138',
'col_1920_13'
]
|
"""
Harvester for Mason Archival Repository Service for the SHARE NS
"""
from __future__ import unicode_literals
from scrapi.base import OAIHarvester
class MasonArchival(OAIHarvester):
short_name = 'mason'
long_name = 'Mason Archival Repository Service'
url = 'http://mars.gmu.edu/'
base_url = 'http://mars.gmu.edu/oai/request'
timezone_granularity = True
property_list = [
'type', 'source', 'setSpec',
'format', 'identifier'
]
approved_sets = [
'col_1920_6102',
'col_1920_6039',
'com_1920_262',
'com_1920_466',
'com_1920_1320',
'com_1920_2852',
'com_1920_2869',
'com_1920_2883',
'com_1920_3011',
'com_1920_7520',
'com_1920_8132',
'com_1920_8138',
'col_1920_13',
'com_1920_2811'
]
|
Add approved set to gmu
|
Add approved set to gmu
|
Python
|
apache-2.0
|
CenterForOpenScience/scrapi,fabianvf/scrapi,CenterForOpenScience/scrapi,fabianvf/scrapi,erinspace/scrapi,erinspace/scrapi
|
"""
Harvester for Mason Archival Repository Service for the SHARE NS
"""
from __future__ import unicode_literals
from scrapi.base import OAIHarvester
class MasonArchival(OAIHarvester):
short_name = 'mason'
long_name = 'Mason Archival Repository Service'
url = 'http://mars.gmu.edu/'
base_url = 'http://mars.gmu.edu/oai/request'
timezone_granularity = True
property_list = [
'type', 'source', 'setSpec',
'format', 'identifier'
]
approved_sets = [
'col_1920_6102',
'col_1920_6039',
'com_1920_262',
'com_1920_466',
'com_1920_1320',
'com_1920_2852',
'com_1920_2869',
'com_1920_2883',
'com_1920_3011',
'com_1920_7520',
'com_1920_8132',
'com_1920_8138',
'col_1920_13'
]
Add approved set to gmu
|
"""
Harvester for Mason Archival Repository Service for the SHARE NS
"""
from __future__ import unicode_literals
from scrapi.base import OAIHarvester
class MasonArchival(OAIHarvester):
short_name = 'mason'
long_name = 'Mason Archival Repository Service'
url = 'http://mars.gmu.edu/'
base_url = 'http://mars.gmu.edu/oai/request'
timezone_granularity = True
property_list = [
'type', 'source', 'setSpec',
'format', 'identifier'
]
approved_sets = [
'col_1920_6102',
'col_1920_6039',
'com_1920_262',
'com_1920_466',
'com_1920_1320',
'com_1920_2852',
'com_1920_2869',
'com_1920_2883',
'com_1920_3011',
'com_1920_7520',
'com_1920_8132',
'com_1920_8138',
'col_1920_13',
'com_1920_2811'
]
|
<commit_before>"""
Harvester for Mason Archival Repository Service for the SHARE NS
"""
from __future__ import unicode_literals
from scrapi.base import OAIHarvester
class MasonArchival(OAIHarvester):
short_name = 'mason'
long_name = 'Mason Archival Repository Service'
url = 'http://mars.gmu.edu/'
base_url = 'http://mars.gmu.edu/oai/request'
timezone_granularity = True
property_list = [
'type', 'source', 'setSpec',
'format', 'identifier'
]
approved_sets = [
'col_1920_6102',
'col_1920_6039',
'com_1920_262',
'com_1920_466',
'com_1920_1320',
'com_1920_2852',
'com_1920_2869',
'com_1920_2883',
'com_1920_3011',
'com_1920_7520',
'com_1920_8132',
'com_1920_8138',
'col_1920_13'
]
<commit_msg>Add approved set to gmu<commit_after>
|
"""
Harvester for Mason Archival Repository Service for the SHARE NS
"""
from __future__ import unicode_literals
from scrapi.base import OAIHarvester
class MasonArchival(OAIHarvester):
short_name = 'mason'
long_name = 'Mason Archival Repository Service'
url = 'http://mars.gmu.edu/'
base_url = 'http://mars.gmu.edu/oai/request'
timezone_granularity = True
property_list = [
'type', 'source', 'setSpec',
'format', 'identifier'
]
approved_sets = [
'col_1920_6102',
'col_1920_6039',
'com_1920_262',
'com_1920_466',
'com_1920_1320',
'com_1920_2852',
'com_1920_2869',
'com_1920_2883',
'com_1920_3011',
'com_1920_7520',
'com_1920_8132',
'com_1920_8138',
'col_1920_13',
'com_1920_2811'
]
|
"""
Harvester for Mason Archival Repository Service for the SHARE NS
"""
from __future__ import unicode_literals
from scrapi.base import OAIHarvester
class MasonArchival(OAIHarvester):
short_name = 'mason'
long_name = 'Mason Archival Repository Service'
url = 'http://mars.gmu.edu/'
base_url = 'http://mars.gmu.edu/oai/request'
timezone_granularity = True
property_list = [
'type', 'source', 'setSpec',
'format', 'identifier'
]
approved_sets = [
'col_1920_6102',
'col_1920_6039',
'com_1920_262',
'com_1920_466',
'com_1920_1320',
'com_1920_2852',
'com_1920_2869',
'com_1920_2883',
'com_1920_3011',
'com_1920_7520',
'com_1920_8132',
'com_1920_8138',
'col_1920_13'
]
Add approved set to gmu"""
Harvester for Mason Archival Repository Service for the SHARE NS
"""
from __future__ import unicode_literals
from scrapi.base import OAIHarvester
class MasonArchival(OAIHarvester):
short_name = 'mason'
long_name = 'Mason Archival Repository Service'
url = 'http://mars.gmu.edu/'
base_url = 'http://mars.gmu.edu/oai/request'
timezone_granularity = True
property_list = [
'type', 'source', 'setSpec',
'format', 'identifier'
]
approved_sets = [
'col_1920_6102',
'col_1920_6039',
'com_1920_262',
'com_1920_466',
'com_1920_1320',
'com_1920_2852',
'com_1920_2869',
'com_1920_2883',
'com_1920_3011',
'com_1920_7520',
'com_1920_8132',
'com_1920_8138',
'col_1920_13',
'com_1920_2811'
]
|
<commit_before>"""
Harvester for Mason Archival Repository Service for the SHARE NS
"""
from __future__ import unicode_literals
from scrapi.base import OAIHarvester
class MasonArchival(OAIHarvester):
short_name = 'mason'
long_name = 'Mason Archival Repository Service'
url = 'http://mars.gmu.edu/'
base_url = 'http://mars.gmu.edu/oai/request'
timezone_granularity = True
property_list = [
'type', 'source', 'setSpec',
'format', 'identifier'
]
approved_sets = [
'col_1920_6102',
'col_1920_6039',
'com_1920_262',
'com_1920_466',
'com_1920_1320',
'com_1920_2852',
'com_1920_2869',
'com_1920_2883',
'com_1920_3011',
'com_1920_7520',
'com_1920_8132',
'com_1920_8138',
'col_1920_13'
]
<commit_msg>Add approved set to gmu<commit_after>"""
Harvester for Mason Archival Repository Service for the SHARE NS
"""
from __future__ import unicode_literals
from scrapi.base import OAIHarvester
class MasonArchival(OAIHarvester):
short_name = 'mason'
long_name = 'Mason Archival Repository Service'
url = 'http://mars.gmu.edu/'
base_url = 'http://mars.gmu.edu/oai/request'
timezone_granularity = True
property_list = [
'type', 'source', 'setSpec',
'format', 'identifier'
]
approved_sets = [
'col_1920_6102',
'col_1920_6039',
'com_1920_262',
'com_1920_466',
'com_1920_1320',
'com_1920_2852',
'com_1920_2869',
'com_1920_2883',
'com_1920_3011',
'com_1920_7520',
'com_1920_8132',
'com_1920_8138',
'col_1920_13',
'com_1920_2811'
]
|
82bca5898d753638536abdd965c799bd947163e5
|
scipy/ndimage/tests/test_regression.py
|
scipy/ndimage/tests/test_regression.py
|
import numpy as np
from numpy.testing import *
import scipy.ndimage as ndimage
def test_byte_order_median():
"""Regression test for #413: median_filter does not handle bytes orders."""
a = np.arange(9, dtype='<f4').reshape(3, 3)
ref = ndimage.filters.median_filter(a,(3, 3))
b = np.arange(9, dtype='>f4').reshape(3, 3)
t = ndimage.filters.median_filter(b, (3, 3))
assert_array_almost_equal(ref, t)
def test_zoom_output_shape():
"""Ticket #643"""
x = np.arange(12).reshape((3,4))
ndimage.zoom(x, 2, output=np.zeros((6,8)))
if __name__ == "__main__":
NumpyTest().run()
|
import numpy as np
from numpy.testing import *
import scipy.ndimage as ndimage
def test_byte_order_median():
"""Regression test for #413: median_filter does not handle bytes orders."""
a = np.arange(9, dtype='<f4').reshape(3, 3)
ref = ndimage.filters.median_filter(a,(3, 3))
b = np.arange(9, dtype='>f4').reshape(3, 3)
t = ndimage.filters.median_filter(b, (3, 3))
assert_array_almost_equal(ref, t)
def test_zoom_output_shape():
"""Ticket #643"""
x = np.arange(12).reshape((3,4))
ndimage.zoom(x, 2, output=np.zeros((6,8)))
if __name__ == "__main__":
run_module_suite()
|
Use run_module_suite instead of deprecated NumpyTest.
|
Use run_module_suite instead of deprecated NumpyTest.
|
Python
|
bsd-3-clause
|
teoliphant/scipy,gef756/scipy,ChanderG/scipy,raoulbq/scipy,petebachant/scipy,dch312/scipy,zaxliu/scipy,gertingold/scipy,ndchorley/scipy,zxsted/scipy,sonnyhu/scipy,ortylp/scipy,jsilter/scipy,rgommers/scipy,jseabold/scipy,surhudm/scipy,vhaasteren/scipy,jamestwebber/scipy,piyush0609/scipy,ales-erjavec/scipy,WillieMaddox/scipy,WillieMaddox/scipy,grlee77/scipy,matthew-brett/scipy,niknow/scipy,Dapid/scipy,endolith/scipy,scipy/scipy,nvoron23/scipy,Shaswat27/scipy,perimosocordiae/scipy,niknow/scipy,ChanderG/scipy,gef756/scipy,zerothi/scipy,person142/scipy,futurulus/scipy,mhogg/scipy,endolith/scipy,Gillu13/scipy,niknow/scipy,mingwpy/scipy,cpaulik/scipy,endolith/scipy,larsmans/scipy,anielsen001/scipy,fernand/scipy,larsmans/scipy,FRidh/scipy,vanpact/scipy,aeklant/scipy,larsmans/scipy,mdhaber/scipy,ales-erjavec/scipy,FRidh/scipy,niknow/scipy,mingwpy/scipy,jonycgn/scipy,ChanderG/scipy,Stefan-Endres/scipy,Stefan-Endres/scipy,aeklant/scipy,zxsted/scipy,fredrikw/scipy,woodscn/scipy,richardotis/scipy,richardotis/scipy,gfyoung/scipy,Eric89GXL/scipy,niknow/scipy,WillieMaddox/scipy,jamestwebber/scipy,Kamp9/scipy,vigna/scipy,chatcannon/scipy,petebachant/scipy,cpaulik/scipy,ndchorley/scipy,zerothi/scipy,befelix/scipy,Gillu13/scipy,e-q/scipy,maniteja123/scipy,anntzer/scipy,jakevdp/scipy,larsmans/scipy,Shaswat27/scipy,jsilter/scipy,fredrikw/scipy,josephcslater/scipy,arokem/scipy,Dapid/scipy,zaxliu/scipy,Newman101/scipy,surhudm/scipy,pbrod/scipy,kalvdans/scipy,perimosocordiae/scipy,Srisai85/scipy,njwilson23/scipy,jakevdp/scipy,sargas/scipy,Stefan-Endres/scipy,ndchorley/scipy,giorgiop/scipy,Shaswat27/scipy,Newman101/scipy,Kamp9/scipy,juliantaylor/scipy,gdooper/scipy,jor-/scipy,behzadnouri/scipy,gertingold/scipy,fredrikw/scipy,ales-erjavec/scipy,haudren/scipy,mhogg/scipy,gef756/scipy,jonycgn/scipy,kalvdans/scipy,Srisai85/scipy,aarchiba/scipy,ales-erjavec/scipy,sonnyhu/scipy,sauliusl/scipy,rmcgibbo/scipy,Srisai85/scipy,pnedunuri/scipy,felipebetancur/scipy,vigna/scipy,richardotis/scipy,vanpact/scipy,nvoron23/scipy,mhogg/scipy,minhlongdo/scipy,pyramania/scipy,WarrenWeckesser/scipy,grlee77/scipy,lukauskas/scipy,zerothi/scipy,cpaulik/scipy,tylerjereddy/scipy,maciejkula/scipy,tylerjereddy/scipy,maciejkula/scipy,vberaudi/scipy,nmayorov/scipy,ilayn/scipy,ortylp/scipy,nonhermitian/scipy,sauliusl/scipy,Dapid/scipy,witcxc/scipy,chatcannon/scipy,trankmichael/scipy,vhaasteren/scipy,ogrisel/scipy,apbard/scipy,jsilter/scipy,kalvdans/scipy,fernand/scipy,mingwpy/scipy,rgommers/scipy,Newman101/scipy,aeklant/scipy,vanpact/scipy,nvoron23/scipy,futurulus/scipy,zaxliu/scipy,sriki18/scipy,pyramania/scipy,jseabold/scipy,ndchorley/scipy,behzadnouri/scipy,gertingold/scipy,ogrisel/scipy,anielsen001/scipy,vhaasteren/scipy,befelix/scipy,rmcgibbo/scipy,mortada/scipy,efiring/scipy,jseabold/scipy,andim/scipy,haudren/scipy,raoulbq/scipy,sriki18/scipy,maniteja123/scipy,dch312/scipy,Dapid/scipy,vberaudi/scipy,mikebenfield/scipy,ogrisel/scipy,ales-erjavec/scipy,ndchorley/scipy,vhaasteren/scipy,mortada/scipy,bkendzior/scipy,jjhelmus/scipy,Stefan-Endres/scipy,chatcannon/scipy,perimosocordiae/scipy,scipy/scipy,nmayorov/scipy,kleskjr/scipy,lhilt/scipy,mdhaber/scipy,dch312/scipy,Gillu13/scipy,mhogg/scipy,vanpact/scipy,trankmichael/scipy,pnedunuri/scipy,witcxc/scipy,efiring/scipy,dch312/scipy,mtrbean/scipy,mdhaber/scipy,lukauskas/scipy,juliantaylor/scipy,hainm/scipy,jjhelmus/scipy,arokem/scipy,sriki18/scipy,ogrisel/scipy,njwilson23/scipy,kalvdans/scipy,tylerjereddy/scipy,WillieMaddox/scipy,aman-iitj/scipy,mgaitan/scipy,behzadnouri/scipy,anntzer/scipy,mgaitan/scipy,hainm/scipy,gfyoung/scipy,maniteja123/scipy,mortonjt/scipy,scipy/scipy,grlee77/scipy,Gillu13/scipy,pyramania/scipy,giorgiop/scipy,mortonjt/scipy,vberaudi/scipy,mortonjt/scipy,vigna/scipy,aman-iitj/scipy,mtrbean/scipy,lukauskas/scipy,fredrikw/scipy,woodscn/scipy,Newman101/scipy,minhlongdo/scipy,giorgiop/scipy,nmayorov/scipy,gertingold/scipy,person142/scipy,zxsted/scipy,fernand/scipy,hainm/scipy,mhogg/scipy,jjhelmus/scipy,vberaudi/scipy,Eric89GXL/scipy,WarrenWeckesser/scipy,woodscn/scipy,mhogg/scipy,felipebetancur/scipy,minhlongdo/scipy,pizzathief/scipy,anielsen001/scipy,Stefan-Endres/scipy,ortylp/scipy,matthew-brett/scipy,argriffing/scipy,jonycgn/scipy,argriffing/scipy,witcxc/scipy,chatcannon/scipy,aeklant/scipy,josephcslater/scipy,lukauskas/scipy,anntzer/scipy,ChanderG/scipy,hainm/scipy,maniteja123/scipy,gdooper/scipy,futurulus/scipy,behzadnouri/scipy,andim/scipy,apbard/scipy,petebachant/scipy,mgaitan/scipy,mdhaber/scipy,andyfaff/scipy,bkendzior/scipy,dominicelse/scipy,zxsted/scipy,aarchiba/scipy,felipebetancur/scipy,woodscn/scipy,FRidh/scipy,juliantaylor/scipy,anielsen001/scipy,WarrenWeckesser/scipy,perimosocordiae/scipy,vigna/scipy,dch312/scipy,jakevdp/scipy,larsmans/scipy,ndchorley/scipy,jakevdp/scipy,scipy/scipy,jor-/scipy,pyramania/scipy,FRidh/scipy,e-q/scipy,ortylp/scipy,hainm/scipy,josephcslater/scipy,vberaudi/scipy,mingwpy/scipy,raoulbq/scipy,chatcannon/scipy,endolith/scipy,richardotis/scipy,mingwpy/scipy,Srisai85/scipy,endolith/scipy,futurulus/scipy,gfyoung/scipy,jsilter/scipy,sauliusl/scipy,fredrikw/scipy,anielsen001/scipy,maniteja123/scipy,scipy/scipy,rgommers/scipy,matthewalbani/scipy,nonhermitian/scipy,jor-/scipy,ogrisel/scipy,mtrbean/scipy,mortada/scipy,matthewalbani/scipy,futurulus/scipy,Shaswat27/scipy,piyush0609/scipy,Eric89GXL/scipy,jseabold/scipy,pizzathief/scipy,Shaswat27/scipy,nvoron23/scipy,ales-erjavec/scipy,aarchiba/scipy,gdooper/scipy,jamestwebber/scipy,newemailjdm/scipy,cpaulik/scipy,nmayorov/scipy,lhilt/scipy,nonhermitian/scipy,zerothi/scipy,anielsen001/scipy,newemailjdm/scipy,cpaulik/scipy,gef756/scipy,matthewalbani/scipy,minhlongdo/scipy,mingwpy/scipy,trankmichael/scipy,apbard/scipy,vigna/scipy,teoliphant/scipy,zxsted/scipy,efiring/scipy,surhudm/scipy,ilayn/scipy,rmcgibbo/scipy,mikebenfield/scipy,njwilson23/scipy,pschella/scipy,aman-iitj/scipy,grlee77/scipy,gertingold/scipy,zaxliu/scipy,bkendzior/scipy,mikebenfield/scipy,vhaasteren/scipy,argriffing/scipy,ortylp/scipy,sargas/scipy,minhlongdo/scipy,pizzathief/scipy,mtrbean/scipy,rmcgibbo/scipy,Eric89GXL/scipy,mtrbean/scipy,giorgiop/scipy,andim/scipy,piyush0609/scipy,WarrenWeckesser/scipy,tylerjereddy/scipy,nonhermitian/scipy,endolith/scipy,person142/scipy,mortada/scipy,cpaulik/scipy,Srisai85/scipy,anntzer/scipy,jseabold/scipy,grlee77/scipy,piyush0609/scipy,pbrod/scipy,pschella/scipy,anntzer/scipy,jonycgn/scipy,kalvdans/scipy,dominicelse/scipy,maciejkula/scipy,trankmichael/scipy,Kamp9/scipy,andim/scipy,FRidh/scipy,WillieMaddox/scipy,fredrikw/scipy,aman-iitj/scipy,sauliusl/scipy,matthewalbani/scipy,bkendzior/scipy,jseabold/scipy,newemailjdm/scipy,nmayorov/scipy,rgommers/scipy,haudren/scipy,sauliusl/scipy,josephcslater/scipy,maniteja123/scipy,apbard/scipy,trankmichael/scipy,ortylp/scipy,maciejkula/scipy,behzadnouri/scipy,jjhelmus/scipy,jamestwebber/scipy,fernand/scipy,teoliphant/scipy,pbrod/scipy,Srisai85/scipy,pbrod/scipy,andim/scipy,pschella/scipy,woodscn/scipy,e-q/scipy,pbrod/scipy,pizzathief/scipy,argriffing/scipy,mikebenfield/scipy,pnedunuri/scipy,mgaitan/scipy,lhilt/scipy,felipebetancur/scipy,dominicelse/scipy,WillieMaddox/scipy,Dapid/scipy,juliantaylor/scipy,richardotis/scipy,perimosocordiae/scipy,jamestwebber/scipy,aeklant/scipy,felipebetancur/scipy,Kamp9/scipy,andyfaff/scipy,andyfaff/scipy,scipy/scipy,piyush0609/scipy,haudren/scipy,mtrbean/scipy,petebachant/scipy,sriki18/scipy,josephcslater/scipy,anntzer/scipy,petebachant/scipy,lhilt/scipy,gdooper/scipy,ilayn/scipy,giorgiop/scipy,gef756/scipy,matthew-brett/scipy,zaxliu/scipy,andyfaff/scipy,lhilt/scipy,mdhaber/scipy,pnedunuri/scipy,mgaitan/scipy,WarrenWeckesser/scipy,piyush0609/scipy,behzadnouri/scipy,njwilson23/scipy,mortada/scipy,andim/scipy,newemailjdm/scipy,Newman101/scipy,chatcannon/scipy,person142/scipy,mortonjt/scipy,jsilter/scipy,juliantaylor/scipy,zerothi/scipy,matthewalbani/scipy,surhudm/scipy,e-q/scipy,gfyoung/scipy,jjhelmus/scipy,Eric89GXL/scipy,dominicelse/scipy,mikebenfield/scipy,njwilson23/scipy,ilayn/scipy,perimosocordiae/scipy,andyfaff/scipy,matthew-brett/scipy,Eric89GXL/scipy,ChanderG/scipy,WarrenWeckesser/scipy,kleskjr/scipy,zxsted/scipy,Gillu13/scipy,sriki18/scipy,sriki18/scipy,efiring/scipy,befelix/scipy,gef756/scipy,kleskjr/scipy,petebachant/scipy,lukauskas/scipy,gdooper/scipy,ilayn/scipy,befelix/scipy,efiring/scipy,FRidh/scipy,raoulbq/scipy,sargas/scipy,e-q/scipy,vhaasteren/scipy,vanpact/scipy,mgaitan/scipy,Gillu13/scipy,sargas/scipy,fernand/scipy,jonycgn/scipy,argriffing/scipy,Dapid/scipy,teoliphant/scipy,sonnyhu/scipy,kleskjr/scipy,Newman101/scipy,zaxliu/scipy,mdhaber/scipy,witcxc/scipy,newemailjdm/scipy,Stefan-Endres/scipy,hainm/scipy,teoliphant/scipy,person142/scipy,haudren/scipy,nvoron23/scipy,Kamp9/scipy,tylerjereddy/scipy,vanpact/scipy,aarchiba/scipy,aarchiba/scipy,bkendzior/scipy,rmcgibbo/scipy,raoulbq/scipy,jor-/scipy,trankmichael/scipy,pschella/scipy,ilayn/scipy,vberaudi/scipy,larsmans/scipy,arokem/scipy,futurulus/scipy,newemailjdm/scipy,niknow/scipy,pnedunuri/scipy,surhudm/scipy,argriffing/scipy,pizzathief/scipy,fernand/scipy,mortada/scipy,mortonjt/scipy,jor-/scipy,surhudm/scipy,kleskjr/scipy,witcxc/scipy,andyfaff/scipy,sargas/scipy,giorgiop/scipy,nonhermitian/scipy,apbard/scipy,befelix/scipy,aman-iitj/scipy,rmcgibbo/scipy,ChanderG/scipy,haudren/scipy,sauliusl/scipy,sonnyhu/scipy,raoulbq/scipy,felipebetancur/scipy,arokem/scipy,pbrod/scipy,njwilson23/scipy,rgommers/scipy,efiring/scipy,aman-iitj/scipy,richardotis/scipy,matthew-brett/scipy,nvoron23/scipy,jakevdp/scipy,sonnyhu/scipy,dominicelse/scipy,pyramania/scipy,jonycgn/scipy,kleskjr/scipy,woodscn/scipy,pnedunuri/scipy,lukauskas/scipy,pschella/scipy,sonnyhu/scipy,minhlongdo/scipy,gfyoung/scipy,maciejkula/scipy,zerothi/scipy,Kamp9/scipy,Shaswat27/scipy,mortonjt/scipy,arokem/scipy
|
import numpy as np
from numpy.testing import *
import scipy.ndimage as ndimage
def test_byte_order_median():
"""Regression test for #413: median_filter does not handle bytes orders."""
a = np.arange(9, dtype='<f4').reshape(3, 3)
ref = ndimage.filters.median_filter(a,(3, 3))
b = np.arange(9, dtype='>f4').reshape(3, 3)
t = ndimage.filters.median_filter(b, (3, 3))
assert_array_almost_equal(ref, t)
def test_zoom_output_shape():
"""Ticket #643"""
x = np.arange(12).reshape((3,4))
ndimage.zoom(x, 2, output=np.zeros((6,8)))
if __name__ == "__main__":
NumpyTest().run()
Use run_module_suite instead of deprecated NumpyTest.
|
import numpy as np
from numpy.testing import *
import scipy.ndimage as ndimage
def test_byte_order_median():
"""Regression test for #413: median_filter does not handle bytes orders."""
a = np.arange(9, dtype='<f4').reshape(3, 3)
ref = ndimage.filters.median_filter(a,(3, 3))
b = np.arange(9, dtype='>f4').reshape(3, 3)
t = ndimage.filters.median_filter(b, (3, 3))
assert_array_almost_equal(ref, t)
def test_zoom_output_shape():
"""Ticket #643"""
x = np.arange(12).reshape((3,4))
ndimage.zoom(x, 2, output=np.zeros((6,8)))
if __name__ == "__main__":
run_module_suite()
|
<commit_before>import numpy as np
from numpy.testing import *
import scipy.ndimage as ndimage
def test_byte_order_median():
"""Regression test for #413: median_filter does not handle bytes orders."""
a = np.arange(9, dtype='<f4').reshape(3, 3)
ref = ndimage.filters.median_filter(a,(3, 3))
b = np.arange(9, dtype='>f4').reshape(3, 3)
t = ndimage.filters.median_filter(b, (3, 3))
assert_array_almost_equal(ref, t)
def test_zoom_output_shape():
"""Ticket #643"""
x = np.arange(12).reshape((3,4))
ndimage.zoom(x, 2, output=np.zeros((6,8)))
if __name__ == "__main__":
NumpyTest().run()
<commit_msg>Use run_module_suite instead of deprecated NumpyTest.<commit_after>
|
import numpy as np
from numpy.testing import *
import scipy.ndimage as ndimage
def test_byte_order_median():
"""Regression test for #413: median_filter does not handle bytes orders."""
a = np.arange(9, dtype='<f4').reshape(3, 3)
ref = ndimage.filters.median_filter(a,(3, 3))
b = np.arange(9, dtype='>f4').reshape(3, 3)
t = ndimage.filters.median_filter(b, (3, 3))
assert_array_almost_equal(ref, t)
def test_zoom_output_shape():
"""Ticket #643"""
x = np.arange(12).reshape((3,4))
ndimage.zoom(x, 2, output=np.zeros((6,8)))
if __name__ == "__main__":
run_module_suite()
|
import numpy as np
from numpy.testing import *
import scipy.ndimage as ndimage
def test_byte_order_median():
"""Regression test for #413: median_filter does not handle bytes orders."""
a = np.arange(9, dtype='<f4').reshape(3, 3)
ref = ndimage.filters.median_filter(a,(3, 3))
b = np.arange(9, dtype='>f4').reshape(3, 3)
t = ndimage.filters.median_filter(b, (3, 3))
assert_array_almost_equal(ref, t)
def test_zoom_output_shape():
"""Ticket #643"""
x = np.arange(12).reshape((3,4))
ndimage.zoom(x, 2, output=np.zeros((6,8)))
if __name__ == "__main__":
NumpyTest().run()
Use run_module_suite instead of deprecated NumpyTest.import numpy as np
from numpy.testing import *
import scipy.ndimage as ndimage
def test_byte_order_median():
"""Regression test for #413: median_filter does not handle bytes orders."""
a = np.arange(9, dtype='<f4').reshape(3, 3)
ref = ndimage.filters.median_filter(a,(3, 3))
b = np.arange(9, dtype='>f4').reshape(3, 3)
t = ndimage.filters.median_filter(b, (3, 3))
assert_array_almost_equal(ref, t)
def test_zoom_output_shape():
"""Ticket #643"""
x = np.arange(12).reshape((3,4))
ndimage.zoom(x, 2, output=np.zeros((6,8)))
if __name__ == "__main__":
run_module_suite()
|
<commit_before>import numpy as np
from numpy.testing import *
import scipy.ndimage as ndimage
def test_byte_order_median():
"""Regression test for #413: median_filter does not handle bytes orders."""
a = np.arange(9, dtype='<f4').reshape(3, 3)
ref = ndimage.filters.median_filter(a,(3, 3))
b = np.arange(9, dtype='>f4').reshape(3, 3)
t = ndimage.filters.median_filter(b, (3, 3))
assert_array_almost_equal(ref, t)
def test_zoom_output_shape():
"""Ticket #643"""
x = np.arange(12).reshape((3,4))
ndimage.zoom(x, 2, output=np.zeros((6,8)))
if __name__ == "__main__":
NumpyTest().run()
<commit_msg>Use run_module_suite instead of deprecated NumpyTest.<commit_after>import numpy as np
from numpy.testing import *
import scipy.ndimage as ndimage
def test_byte_order_median():
"""Regression test for #413: median_filter does not handle bytes orders."""
a = np.arange(9, dtype='<f4').reshape(3, 3)
ref = ndimage.filters.median_filter(a,(3, 3))
b = np.arange(9, dtype='>f4').reshape(3, 3)
t = ndimage.filters.median_filter(b, (3, 3))
assert_array_almost_equal(ref, t)
def test_zoom_output_shape():
"""Ticket #643"""
x = np.arange(12).reshape((3,4))
ndimage.zoom(x, 2, output=np.zeros((6,8)))
if __name__ == "__main__":
run_module_suite()
|
596b435e57275714b3d37529cc342cacc15a86bf
|
moto/s3/utils.py
|
moto/s3/utils.py
|
import re
import urllib2
import urlparse
bucket_name_regex = re.compile("(.+).s3.amazonaws.com")
def bucket_name_from_url(url):
domain = urlparse.urlparse(url).netloc
# If 'www' prefixed, strip it.
domain = domain.lstrip("www.")
if 'amazonaws.com' in domain:
bucket_result = bucket_name_regex.search(domain)
if bucket_result:
return bucket_result.groups()[0]
else:
if '.' in domain:
return domain.split(".")[0]
else:
# No subdomain found.
return None
def clean_key_name(key_name):
return urllib2.unquote(key_name)
|
import re
import urllib2
import urlparse
bucket_name_regex = re.compile("(.+).s3.amazonaws.com")
def bucket_name_from_url(url):
domain = urlparse.urlparse(url).netloc
# If 'www' prefixed, strip it.
domain = domain.replace("www.", "")
if 'amazonaws.com' in domain:
bucket_result = bucket_name_regex.search(domain)
if bucket_result:
return bucket_result.groups()[0]
else:
if '.' in domain:
return domain.split(".")[0]
else:
# No subdomain found.
return None
def clean_key_name(key_name):
return urllib2.unquote(key_name)
|
Fix the 'www.' strip changing the lstrip method by the replace
|
Fix the 'www.' strip changing the lstrip method by the replace
|
Python
|
apache-2.0
|
okomestudio/moto,william-richard/moto,araines/moto,william-richard/moto,whummer/moto,Affirm/moto,Brett55/moto,EarthmanT/moto,rocky4570/moto,andresriancho/moto,jszwedko/moto,riccardomc/moto,braintreeps/moto,ImmobilienScout24/moto,heddle317/moto,william-richard/moto,whummer/moto,heddle317/moto,heddle317/moto,ZuluPro/moto,spulec/moto,kefo/moto,rocky4570/moto,Affirm/moto,mrucci/moto,kefo/moto,william-richard/moto,Brett55/moto,behanceops/moto,rocky4570/moto,2rs2ts/moto,2rs2ts/moto,DataDog/moto,whummer/moto,jrydberg/moto,ludia/moto,whummer/moto,okomestudio/moto,2rs2ts/moto,Affirm/moto,gjtempleton/moto,botify-labs/moto,pior/moto,spulec/moto,botify-labs/moto,dbfr3qs/moto,ZuluPro/moto,whummer/moto,heddle317/moto,dbfr3qs/moto,rocky4570/moto,Brett55/moto,kefo/moto,botify-labs/moto,william-richard/moto,okomestudio/moto,kefo/moto,whummer/moto,okomestudio/moto,botify-labs/moto,im-auld/moto,2rs2ts/moto,ZuluPro/moto,Affirm/moto,tootedom/moto,Brett55/moto,spulec/moto,Affirm/moto,alexdebrie/moto,spulec/moto,2mf/moto,zonk1024/moto,kefo/moto,dbfr3qs/moto,ZuluPro/moto,gjtempleton/moto,2rs2ts/moto,Brett55/moto,gjtempleton/moto,IlyaSukhanov/moto,ZuluPro/moto,Brett55/moto,spulec/moto,jotes/moto,spulec/moto,rouge8/moto,dbfr3qs/moto,gjtempleton/moto,okomestudio/moto,dbfr3qs/moto,dbfr3qs/moto,gjtempleton/moto,botify-labs/moto,Affirm/moto,kennethd/moto,botify-labs/moto,ZuluPro/moto,william-richard/moto,okomestudio/moto,heddle317/moto,rocky4570/moto,silveregg/moto,rocky4570/moto
|
import re
import urllib2
import urlparse
bucket_name_regex = re.compile("(.+).s3.amazonaws.com")
def bucket_name_from_url(url):
domain = urlparse.urlparse(url).netloc
# If 'www' prefixed, strip it.
domain = domain.lstrip("www.")
if 'amazonaws.com' in domain:
bucket_result = bucket_name_regex.search(domain)
if bucket_result:
return bucket_result.groups()[0]
else:
if '.' in domain:
return domain.split(".")[0]
else:
# No subdomain found.
return None
def clean_key_name(key_name):
return urllib2.unquote(key_name)
Fix the 'www.' strip changing the lstrip method by the replace
|
import re
import urllib2
import urlparse
bucket_name_regex = re.compile("(.+).s3.amazonaws.com")
def bucket_name_from_url(url):
domain = urlparse.urlparse(url).netloc
# If 'www' prefixed, strip it.
domain = domain.replace("www.", "")
if 'amazonaws.com' in domain:
bucket_result = bucket_name_regex.search(domain)
if bucket_result:
return bucket_result.groups()[0]
else:
if '.' in domain:
return domain.split(".")[0]
else:
# No subdomain found.
return None
def clean_key_name(key_name):
return urllib2.unquote(key_name)
|
<commit_before>import re
import urllib2
import urlparse
bucket_name_regex = re.compile("(.+).s3.amazonaws.com")
def bucket_name_from_url(url):
domain = urlparse.urlparse(url).netloc
# If 'www' prefixed, strip it.
domain = domain.lstrip("www.")
if 'amazonaws.com' in domain:
bucket_result = bucket_name_regex.search(domain)
if bucket_result:
return bucket_result.groups()[0]
else:
if '.' in domain:
return domain.split(".")[0]
else:
# No subdomain found.
return None
def clean_key_name(key_name):
return urllib2.unquote(key_name)
<commit_msg>Fix the 'www.' strip changing the lstrip method by the replace<commit_after>
|
import re
import urllib2
import urlparse
bucket_name_regex = re.compile("(.+).s3.amazonaws.com")
def bucket_name_from_url(url):
domain = urlparse.urlparse(url).netloc
# If 'www' prefixed, strip it.
domain = domain.replace("www.", "")
if 'amazonaws.com' in domain:
bucket_result = bucket_name_regex.search(domain)
if bucket_result:
return bucket_result.groups()[0]
else:
if '.' in domain:
return domain.split(".")[0]
else:
# No subdomain found.
return None
def clean_key_name(key_name):
return urllib2.unquote(key_name)
|
import re
import urllib2
import urlparse
bucket_name_regex = re.compile("(.+).s3.amazonaws.com")
def bucket_name_from_url(url):
domain = urlparse.urlparse(url).netloc
# If 'www' prefixed, strip it.
domain = domain.lstrip("www.")
if 'amazonaws.com' in domain:
bucket_result = bucket_name_regex.search(domain)
if bucket_result:
return bucket_result.groups()[0]
else:
if '.' in domain:
return domain.split(".")[0]
else:
# No subdomain found.
return None
def clean_key_name(key_name):
return urllib2.unquote(key_name)
Fix the 'www.' strip changing the lstrip method by the replaceimport re
import urllib2
import urlparse
bucket_name_regex = re.compile("(.+).s3.amazonaws.com")
def bucket_name_from_url(url):
domain = urlparse.urlparse(url).netloc
# If 'www' prefixed, strip it.
domain = domain.replace("www.", "")
if 'amazonaws.com' in domain:
bucket_result = bucket_name_regex.search(domain)
if bucket_result:
return bucket_result.groups()[0]
else:
if '.' in domain:
return domain.split(".")[0]
else:
# No subdomain found.
return None
def clean_key_name(key_name):
return urllib2.unquote(key_name)
|
<commit_before>import re
import urllib2
import urlparse
bucket_name_regex = re.compile("(.+).s3.amazonaws.com")
def bucket_name_from_url(url):
domain = urlparse.urlparse(url).netloc
# If 'www' prefixed, strip it.
domain = domain.lstrip("www.")
if 'amazonaws.com' in domain:
bucket_result = bucket_name_regex.search(domain)
if bucket_result:
return bucket_result.groups()[0]
else:
if '.' in domain:
return domain.split(".")[0]
else:
# No subdomain found.
return None
def clean_key_name(key_name):
return urllib2.unquote(key_name)
<commit_msg>Fix the 'www.' strip changing the lstrip method by the replace<commit_after>import re
import urllib2
import urlparse
bucket_name_regex = re.compile("(.+).s3.amazonaws.com")
def bucket_name_from_url(url):
domain = urlparse.urlparse(url).netloc
# If 'www' prefixed, strip it.
domain = domain.replace("www.", "")
if 'amazonaws.com' in domain:
bucket_result = bucket_name_regex.search(domain)
if bucket_result:
return bucket_result.groups()[0]
else:
if '.' in domain:
return domain.split(".")[0]
else:
# No subdomain found.
return None
def clean_key_name(key_name):
return urllib2.unquote(key_name)
|
7fc5d07932587c87e8484190c84b6936a2b7247e
|
cms_genome_browser/urls.py
|
cms_genome_browser/urls.py
|
from django.conf.urls import patterns, url
from cms_genome_browser.views import BrowserListView, BrowserDetailView
urlpatterns = patterns('',
url(r'^$', BrowserListView.as_view(), name='browser_list'),
url(r'^(?P<slug>[^/]+)$', BrowserDetailView.as_view(), name='browser_detail'),
)
|
from django.conf.urls import patterns, url
from cms_genome_browser.views import BrowserListView, BrowserDetailView
urlpatterns = patterns('',
url(r'^$', BrowserListView.as_view(), name='browser_list'),
url(r'^(?P<slug>[^/]+)/$', BrowserDetailView.as_view(), name='browser_detail'),
)
|
Append trailing slash to detail URL
|
Append trailing slash to detail URL
|
Python
|
bsd-3-clause
|
mfcovington/djangocms-genome-browser,mfcovington/djangocms-genome-browser,mfcovington/djangocms-genome-browser
|
from django.conf.urls import patterns, url
from cms_genome_browser.views import BrowserListView, BrowserDetailView
urlpatterns = patterns('',
url(r'^$', BrowserListView.as_view(), name='browser_list'),
url(r'^(?P<slug>[^/]+)$', BrowserDetailView.as_view(), name='browser_detail'),
)
Append trailing slash to detail URL
|
from django.conf.urls import patterns, url
from cms_genome_browser.views import BrowserListView, BrowserDetailView
urlpatterns = patterns('',
url(r'^$', BrowserListView.as_view(), name='browser_list'),
url(r'^(?P<slug>[^/]+)/$', BrowserDetailView.as_view(), name='browser_detail'),
)
|
<commit_before>from django.conf.urls import patterns, url
from cms_genome_browser.views import BrowserListView, BrowserDetailView
urlpatterns = patterns('',
url(r'^$', BrowserListView.as_view(), name='browser_list'),
url(r'^(?P<slug>[^/]+)$', BrowserDetailView.as_view(), name='browser_detail'),
)
<commit_msg>Append trailing slash to detail URL<commit_after>
|
from django.conf.urls import patterns, url
from cms_genome_browser.views import BrowserListView, BrowserDetailView
urlpatterns = patterns('',
url(r'^$', BrowserListView.as_view(), name='browser_list'),
url(r'^(?P<slug>[^/]+)/$', BrowserDetailView.as_view(), name='browser_detail'),
)
|
from django.conf.urls import patterns, url
from cms_genome_browser.views import BrowserListView, BrowserDetailView
urlpatterns = patterns('',
url(r'^$', BrowserListView.as_view(), name='browser_list'),
url(r'^(?P<slug>[^/]+)$', BrowserDetailView.as_view(), name='browser_detail'),
)
Append trailing slash to detail URLfrom django.conf.urls import patterns, url
from cms_genome_browser.views import BrowserListView, BrowserDetailView
urlpatterns = patterns('',
url(r'^$', BrowserListView.as_view(), name='browser_list'),
url(r'^(?P<slug>[^/]+)/$', BrowserDetailView.as_view(), name='browser_detail'),
)
|
<commit_before>from django.conf.urls import patterns, url
from cms_genome_browser.views import BrowserListView, BrowserDetailView
urlpatterns = patterns('',
url(r'^$', BrowserListView.as_view(), name='browser_list'),
url(r'^(?P<slug>[^/]+)$', BrowserDetailView.as_view(), name='browser_detail'),
)
<commit_msg>Append trailing slash to detail URL<commit_after>from django.conf.urls import patterns, url
from cms_genome_browser.views import BrowserListView, BrowserDetailView
urlpatterns = patterns('',
url(r'^$', BrowserListView.as_view(), name='browser_list'),
url(r'^(?P<slug>[^/]+)/$', BrowserDetailView.as_view(), name='browser_detail'),
)
|
316dac037b8cef3086f5bdf6b9fd2afa0b2bfbd3
|
mama_cas/urls.py
|
mama_cas/urls.py
|
"""
URLconf for CAS server URIs as described in the CAS protocol.
"""
from django.conf.urls import patterns
from django.conf.urls import url
from mama_cas.views import LoginView
from mama_cas.views import LogoutView
from mama_cas.views import ValidateView
from mama_cas.views import ServiceValidateView
from mama_cas.views import ProxyValidateView
from mama_cas.views import ProxyView
from mama_cas.views import WarnView
from mama_cas.views import SamlValidateView
urlpatterns = patterns('',
url(r'^login/?$',
LoginView.as_view(),
name='cas_login'),
url(r'^logout/?$',
LogoutView.as_view(),
name='cas_logout'),
url(r'^validate/?$',
ValidateView.as_view(),
name='cas_validate'),
url(r'^serviceValidate/?$',
ServiceValidateView.as_view(),
name='cas_service_validate'),
url(r'^proxyValidate/?$',
ProxyValidateView.as_view(),
name='cas_proxy_validate'),
url(r'^proxy/?$',
ProxyView.as_view(),
name='cas_proxy'),
url(r'^warn/?$',
WarnView.as_view(),
name='cas_warn'),
url(r'^samlValidate/?$',
SamlValidateView.as_view(),
name='cas_saml_validate'),
)
|
"""
(2) CAS server URIs as described in the CAS protocol.
"""
from django.conf.urls import patterns
from django.conf.urls import url
from mama_cas.views import LoginView
from mama_cas.views import LogoutView
from mama_cas.views import ValidateView
from mama_cas.views import ServiceValidateView
from mama_cas.views import ProxyValidateView
from mama_cas.views import ProxyView
from mama_cas.views import WarnView
from mama_cas.views import SamlValidateView
urlpatterns = patterns('',
url(r'^login/?$',
LoginView.as_view(),
name='cas_login'),
url(r'^logout/?$',
LogoutView.as_view(),
name='cas_logout'),
url(r'^validate/?$',
ValidateView.as_view(),
name='cas_validate'),
url(r'^serviceValidate/?$',
ServiceValidateView.as_view(),
name='cas_service_validate'),
url(r'^proxyValidate/?$',
ProxyValidateView.as_view(),
name='cas_proxy_validate'),
url(r'^proxy/?$',
ProxyView.as_view(),
name='cas_proxy'),
url(r'^p3/serviceValidate/?$',
ServiceValidateView.as_view(),
name='cas_p3_service_validate'),
url(r'^p3/proxyValidate/?$',
ProxyValidateView.as_view(),
name='cas_p3_proxy_validate'),
url(r'^warn/?$',
WarnView.as_view(),
name='cas_warn'),
url(r'^samlValidate/?$',
SamlValidateView.as_view(),
name='cas_saml_validate'),
)
|
Add CAS 3.0 specific endpoints
|
Add CAS 3.0 specific endpoints
|
Python
|
bsd-3-clause
|
jbittel/django-mama-cas,jbittel/django-mama-cas,orbitvu/django-mama-cas,orbitvu/django-mama-cas
|
"""
URLconf for CAS server URIs as described in the CAS protocol.
"""
from django.conf.urls import patterns
from django.conf.urls import url
from mama_cas.views import LoginView
from mama_cas.views import LogoutView
from mama_cas.views import ValidateView
from mama_cas.views import ServiceValidateView
from mama_cas.views import ProxyValidateView
from mama_cas.views import ProxyView
from mama_cas.views import WarnView
from mama_cas.views import SamlValidateView
urlpatterns = patterns('',
url(r'^login/?$',
LoginView.as_view(),
name='cas_login'),
url(r'^logout/?$',
LogoutView.as_view(),
name='cas_logout'),
url(r'^validate/?$',
ValidateView.as_view(),
name='cas_validate'),
url(r'^serviceValidate/?$',
ServiceValidateView.as_view(),
name='cas_service_validate'),
url(r'^proxyValidate/?$',
ProxyValidateView.as_view(),
name='cas_proxy_validate'),
url(r'^proxy/?$',
ProxyView.as_view(),
name='cas_proxy'),
url(r'^warn/?$',
WarnView.as_view(),
name='cas_warn'),
url(r'^samlValidate/?$',
SamlValidateView.as_view(),
name='cas_saml_validate'),
)
Add CAS 3.0 specific endpoints
|
"""
(2) CAS server URIs as described in the CAS protocol.
"""
from django.conf.urls import patterns
from django.conf.urls import url
from mama_cas.views import LoginView
from mama_cas.views import LogoutView
from mama_cas.views import ValidateView
from mama_cas.views import ServiceValidateView
from mama_cas.views import ProxyValidateView
from mama_cas.views import ProxyView
from mama_cas.views import WarnView
from mama_cas.views import SamlValidateView
urlpatterns = patterns('',
url(r'^login/?$',
LoginView.as_view(),
name='cas_login'),
url(r'^logout/?$',
LogoutView.as_view(),
name='cas_logout'),
url(r'^validate/?$',
ValidateView.as_view(),
name='cas_validate'),
url(r'^serviceValidate/?$',
ServiceValidateView.as_view(),
name='cas_service_validate'),
url(r'^proxyValidate/?$',
ProxyValidateView.as_view(),
name='cas_proxy_validate'),
url(r'^proxy/?$',
ProxyView.as_view(),
name='cas_proxy'),
url(r'^p3/serviceValidate/?$',
ServiceValidateView.as_view(),
name='cas_p3_service_validate'),
url(r'^p3/proxyValidate/?$',
ProxyValidateView.as_view(),
name='cas_p3_proxy_validate'),
url(r'^warn/?$',
WarnView.as_view(),
name='cas_warn'),
url(r'^samlValidate/?$',
SamlValidateView.as_view(),
name='cas_saml_validate'),
)
|
<commit_before>"""
URLconf for CAS server URIs as described in the CAS protocol.
"""
from django.conf.urls import patterns
from django.conf.urls import url
from mama_cas.views import LoginView
from mama_cas.views import LogoutView
from mama_cas.views import ValidateView
from mama_cas.views import ServiceValidateView
from mama_cas.views import ProxyValidateView
from mama_cas.views import ProxyView
from mama_cas.views import WarnView
from mama_cas.views import SamlValidateView
urlpatterns = patterns('',
url(r'^login/?$',
LoginView.as_view(),
name='cas_login'),
url(r'^logout/?$',
LogoutView.as_view(),
name='cas_logout'),
url(r'^validate/?$',
ValidateView.as_view(),
name='cas_validate'),
url(r'^serviceValidate/?$',
ServiceValidateView.as_view(),
name='cas_service_validate'),
url(r'^proxyValidate/?$',
ProxyValidateView.as_view(),
name='cas_proxy_validate'),
url(r'^proxy/?$',
ProxyView.as_view(),
name='cas_proxy'),
url(r'^warn/?$',
WarnView.as_view(),
name='cas_warn'),
url(r'^samlValidate/?$',
SamlValidateView.as_view(),
name='cas_saml_validate'),
)
<commit_msg>Add CAS 3.0 specific endpoints<commit_after>
|
"""
(2) CAS server URIs as described in the CAS protocol.
"""
from django.conf.urls import patterns
from django.conf.urls import url
from mama_cas.views import LoginView
from mama_cas.views import LogoutView
from mama_cas.views import ValidateView
from mama_cas.views import ServiceValidateView
from mama_cas.views import ProxyValidateView
from mama_cas.views import ProxyView
from mama_cas.views import WarnView
from mama_cas.views import SamlValidateView
urlpatterns = patterns('',
url(r'^login/?$',
LoginView.as_view(),
name='cas_login'),
url(r'^logout/?$',
LogoutView.as_view(),
name='cas_logout'),
url(r'^validate/?$',
ValidateView.as_view(),
name='cas_validate'),
url(r'^serviceValidate/?$',
ServiceValidateView.as_view(),
name='cas_service_validate'),
url(r'^proxyValidate/?$',
ProxyValidateView.as_view(),
name='cas_proxy_validate'),
url(r'^proxy/?$',
ProxyView.as_view(),
name='cas_proxy'),
url(r'^p3/serviceValidate/?$',
ServiceValidateView.as_view(),
name='cas_p3_service_validate'),
url(r'^p3/proxyValidate/?$',
ProxyValidateView.as_view(),
name='cas_p3_proxy_validate'),
url(r'^warn/?$',
WarnView.as_view(),
name='cas_warn'),
url(r'^samlValidate/?$',
SamlValidateView.as_view(),
name='cas_saml_validate'),
)
|
"""
URLconf for CAS server URIs as described in the CAS protocol.
"""
from django.conf.urls import patterns
from django.conf.urls import url
from mama_cas.views import LoginView
from mama_cas.views import LogoutView
from mama_cas.views import ValidateView
from mama_cas.views import ServiceValidateView
from mama_cas.views import ProxyValidateView
from mama_cas.views import ProxyView
from mama_cas.views import WarnView
from mama_cas.views import SamlValidateView
urlpatterns = patterns('',
url(r'^login/?$',
LoginView.as_view(),
name='cas_login'),
url(r'^logout/?$',
LogoutView.as_view(),
name='cas_logout'),
url(r'^validate/?$',
ValidateView.as_view(),
name='cas_validate'),
url(r'^serviceValidate/?$',
ServiceValidateView.as_view(),
name='cas_service_validate'),
url(r'^proxyValidate/?$',
ProxyValidateView.as_view(),
name='cas_proxy_validate'),
url(r'^proxy/?$',
ProxyView.as_view(),
name='cas_proxy'),
url(r'^warn/?$',
WarnView.as_view(),
name='cas_warn'),
url(r'^samlValidate/?$',
SamlValidateView.as_view(),
name='cas_saml_validate'),
)
Add CAS 3.0 specific endpoints"""
(2) CAS server URIs as described in the CAS protocol.
"""
from django.conf.urls import patterns
from django.conf.urls import url
from mama_cas.views import LoginView
from mama_cas.views import LogoutView
from mama_cas.views import ValidateView
from mama_cas.views import ServiceValidateView
from mama_cas.views import ProxyValidateView
from mama_cas.views import ProxyView
from mama_cas.views import WarnView
from mama_cas.views import SamlValidateView
urlpatterns = patterns('',
url(r'^login/?$',
LoginView.as_view(),
name='cas_login'),
url(r'^logout/?$',
LogoutView.as_view(),
name='cas_logout'),
url(r'^validate/?$',
ValidateView.as_view(),
name='cas_validate'),
url(r'^serviceValidate/?$',
ServiceValidateView.as_view(),
name='cas_service_validate'),
url(r'^proxyValidate/?$',
ProxyValidateView.as_view(),
name='cas_proxy_validate'),
url(r'^proxy/?$',
ProxyView.as_view(),
name='cas_proxy'),
url(r'^p3/serviceValidate/?$',
ServiceValidateView.as_view(),
name='cas_p3_service_validate'),
url(r'^p3/proxyValidate/?$',
ProxyValidateView.as_view(),
name='cas_p3_proxy_validate'),
url(r'^warn/?$',
WarnView.as_view(),
name='cas_warn'),
url(r'^samlValidate/?$',
SamlValidateView.as_view(),
name='cas_saml_validate'),
)
|
<commit_before>"""
URLconf for CAS server URIs as described in the CAS protocol.
"""
from django.conf.urls import patterns
from django.conf.urls import url
from mama_cas.views import LoginView
from mama_cas.views import LogoutView
from mama_cas.views import ValidateView
from mama_cas.views import ServiceValidateView
from mama_cas.views import ProxyValidateView
from mama_cas.views import ProxyView
from mama_cas.views import WarnView
from mama_cas.views import SamlValidateView
urlpatterns = patterns('',
url(r'^login/?$',
LoginView.as_view(),
name='cas_login'),
url(r'^logout/?$',
LogoutView.as_view(),
name='cas_logout'),
url(r'^validate/?$',
ValidateView.as_view(),
name='cas_validate'),
url(r'^serviceValidate/?$',
ServiceValidateView.as_view(),
name='cas_service_validate'),
url(r'^proxyValidate/?$',
ProxyValidateView.as_view(),
name='cas_proxy_validate'),
url(r'^proxy/?$',
ProxyView.as_view(),
name='cas_proxy'),
url(r'^warn/?$',
WarnView.as_view(),
name='cas_warn'),
url(r'^samlValidate/?$',
SamlValidateView.as_view(),
name='cas_saml_validate'),
)
<commit_msg>Add CAS 3.0 specific endpoints<commit_after>"""
(2) CAS server URIs as described in the CAS protocol.
"""
from django.conf.urls import patterns
from django.conf.urls import url
from mama_cas.views import LoginView
from mama_cas.views import LogoutView
from mama_cas.views import ValidateView
from mama_cas.views import ServiceValidateView
from mama_cas.views import ProxyValidateView
from mama_cas.views import ProxyView
from mama_cas.views import WarnView
from mama_cas.views import SamlValidateView
urlpatterns = patterns('',
url(r'^login/?$',
LoginView.as_view(),
name='cas_login'),
url(r'^logout/?$',
LogoutView.as_view(),
name='cas_logout'),
url(r'^validate/?$',
ValidateView.as_view(),
name='cas_validate'),
url(r'^serviceValidate/?$',
ServiceValidateView.as_view(),
name='cas_service_validate'),
url(r'^proxyValidate/?$',
ProxyValidateView.as_view(),
name='cas_proxy_validate'),
url(r'^proxy/?$',
ProxyView.as_view(),
name='cas_proxy'),
url(r'^p3/serviceValidate/?$',
ServiceValidateView.as_view(),
name='cas_p3_service_validate'),
url(r'^p3/proxyValidate/?$',
ProxyValidateView.as_view(),
name='cas_p3_proxy_validate'),
url(r'^warn/?$',
WarnView.as_view(),
name='cas_warn'),
url(r'^samlValidate/?$',
SamlValidateView.as_view(),
name='cas_saml_validate'),
)
|
308f9d8e1d4083bb7cc6bca0cf021118502d141b
|
marble/common.py
|
marble/common.py
|
# -*- coding: utf-8 -*-
"""common.py
Contains basic functions that are shared thoughout the module
"""
def compute_totals(distribution, classes):
"Compute the number of individuals per class, per unit and in total"
N_unit = {au:sum([distribution[au][cl] for cl in classes]) for au in distribution}
N_class = {cl:sum([dist_a[cl] for dist_a in distribution.values()]) for cl in classes}
N_tot = sum(N_class.values())
return N_unit, N_class, N_tot
def regroup_per_class(distribution, classes):
"Return classes as they are presented in the data"
new_distribution = {au: {cl: sum([dist_au[c] for c in composition])
for cl,composition in classes.iteritems()}
for au, dist_au in distribution.iteritems()}
return new_distribution
def return_categories(distribution):
"Return the categories in the original data"
keys = next(distribution.itervalues()).keys()
return {k:[k] for k in keys}
|
# -*- coding: utf-8 -*-
"""common.py
Contains basic functions that are shared throughout the module
"""
def compute_totals(distribution, classes):
"Compute the number of individuals per class, per unit and in total"
N_unit = {au:sum([distribution[au][cl] for cl in classes]) for au in distribution}
N_class = {cl:sum([dist_a[cl] for dist_a in distribution.values()]) for cl in classes}
N_tot = sum(N_class.values())
return N_unit, N_class, N_tot
def regroup_per_class(distribution, classes):
"Return classes as they are presented in the data"
try:
new_distribution = {au: {cl: sum([dist_au[c] for c in composition])
for cl,composition in classes.iteritems()}
for au, dist_au in distribution.iteritems()}
except KeyError:
raise KeyError("Verify that the categories specified in the class"
" definitions exist in the original data.")
return new_distribution
def return_categories(distribution):
"Return the categories in the original data"
keys = next(distribution.itervalues()).keys()
return {k:[k] for k in keys}
|
Raise exception if faulty definition of classes inserted
|
Raise exception if faulty definition of classes inserted
|
Python
|
bsd-3-clause
|
scities/marble,walkerke/marble
|
# -*- coding: utf-8 -*-
"""common.py
Contains basic functions that are shared thoughout the module
"""
def compute_totals(distribution, classes):
"Compute the number of individuals per class, per unit and in total"
N_unit = {au:sum([distribution[au][cl] for cl in classes]) for au in distribution}
N_class = {cl:sum([dist_a[cl] for dist_a in distribution.values()]) for cl in classes}
N_tot = sum(N_class.values())
return N_unit, N_class, N_tot
def regroup_per_class(distribution, classes):
"Return classes as they are presented in the data"
new_distribution = {au: {cl: sum([dist_au[c] for c in composition])
for cl,composition in classes.iteritems()}
for au, dist_au in distribution.iteritems()}
return new_distribution
def return_categories(distribution):
"Return the categories in the original data"
keys = next(distribution.itervalues()).keys()
return {k:[k] for k in keys}
Raise exception if faulty definition of classes inserted
|
# -*- coding: utf-8 -*-
"""common.py
Contains basic functions that are shared throughout the module
"""
def compute_totals(distribution, classes):
"Compute the number of individuals per class, per unit and in total"
N_unit = {au:sum([distribution[au][cl] for cl in classes]) for au in distribution}
N_class = {cl:sum([dist_a[cl] for dist_a in distribution.values()]) for cl in classes}
N_tot = sum(N_class.values())
return N_unit, N_class, N_tot
def regroup_per_class(distribution, classes):
"Return classes as they are presented in the data"
try:
new_distribution = {au: {cl: sum([dist_au[c] for c in composition])
for cl,composition in classes.iteritems()}
for au, dist_au in distribution.iteritems()}
except KeyError:
raise KeyError("Verify that the categories specified in the class"
" definitions exist in the original data.")
return new_distribution
def return_categories(distribution):
"Return the categories in the original data"
keys = next(distribution.itervalues()).keys()
return {k:[k] for k in keys}
|
<commit_before># -*- coding: utf-8 -*-
"""common.py
Contains basic functions that are shared thoughout the module
"""
def compute_totals(distribution, classes):
"Compute the number of individuals per class, per unit and in total"
N_unit = {au:sum([distribution[au][cl] for cl in classes]) for au in distribution}
N_class = {cl:sum([dist_a[cl] for dist_a in distribution.values()]) for cl in classes}
N_tot = sum(N_class.values())
return N_unit, N_class, N_tot
def regroup_per_class(distribution, classes):
"Return classes as they are presented in the data"
new_distribution = {au: {cl: sum([dist_au[c] for c in composition])
for cl,composition in classes.iteritems()}
for au, dist_au in distribution.iteritems()}
return new_distribution
def return_categories(distribution):
"Return the categories in the original data"
keys = next(distribution.itervalues()).keys()
return {k:[k] for k in keys}
<commit_msg>Raise exception if faulty definition of classes inserted<commit_after>
|
# -*- coding: utf-8 -*-
"""common.py
Contains basic functions that are shared throughout the module
"""
def compute_totals(distribution, classes):
"Compute the number of individuals per class, per unit and in total"
N_unit = {au:sum([distribution[au][cl] for cl in classes]) for au in distribution}
N_class = {cl:sum([dist_a[cl] for dist_a in distribution.values()]) for cl in classes}
N_tot = sum(N_class.values())
return N_unit, N_class, N_tot
def regroup_per_class(distribution, classes):
"Return classes as they are presented in the data"
try:
new_distribution = {au: {cl: sum([dist_au[c] for c in composition])
for cl,composition in classes.iteritems()}
for au, dist_au in distribution.iteritems()}
except KeyError:
raise KeyError("Verify that the categories specified in the class"
" definitions exist in the original data.")
return new_distribution
def return_categories(distribution):
"Return the categories in the original data"
keys = next(distribution.itervalues()).keys()
return {k:[k] for k in keys}
|
# -*- coding: utf-8 -*-
"""common.py
Contains basic functions that are shared thoughout the module
"""
def compute_totals(distribution, classes):
"Compute the number of individuals per class, per unit and in total"
N_unit = {au:sum([distribution[au][cl] for cl in classes]) for au in distribution}
N_class = {cl:sum([dist_a[cl] for dist_a in distribution.values()]) for cl in classes}
N_tot = sum(N_class.values())
return N_unit, N_class, N_tot
def regroup_per_class(distribution, classes):
"Return classes as they are presented in the data"
new_distribution = {au: {cl: sum([dist_au[c] for c in composition])
for cl,composition in classes.iteritems()}
for au, dist_au in distribution.iteritems()}
return new_distribution
def return_categories(distribution):
"Return the categories in the original data"
keys = next(distribution.itervalues()).keys()
return {k:[k] for k in keys}
Raise exception if faulty definition of classes inserted# -*- coding: utf-8 -*-
"""common.py
Contains basic functions that are shared throughout the module
"""
def compute_totals(distribution, classes):
"Compute the number of individuals per class, per unit and in total"
N_unit = {au:sum([distribution[au][cl] for cl in classes]) for au in distribution}
N_class = {cl:sum([dist_a[cl] for dist_a in distribution.values()]) for cl in classes}
N_tot = sum(N_class.values())
return N_unit, N_class, N_tot
def regroup_per_class(distribution, classes):
"Return classes as they are presented in the data"
try:
new_distribution = {au: {cl: sum([dist_au[c] for c in composition])
for cl,composition in classes.iteritems()}
for au, dist_au in distribution.iteritems()}
except KeyError:
raise KeyError("Verify that the categories specified in the class"
" definitions exist in the original data.")
return new_distribution
def return_categories(distribution):
"Return the categories in the original data"
keys = next(distribution.itervalues()).keys()
return {k:[k] for k in keys}
|
<commit_before># -*- coding: utf-8 -*-
"""common.py
Contains basic functions that are shared thoughout the module
"""
def compute_totals(distribution, classes):
"Compute the number of individuals per class, per unit and in total"
N_unit = {au:sum([distribution[au][cl] for cl in classes]) for au in distribution}
N_class = {cl:sum([dist_a[cl] for dist_a in distribution.values()]) for cl in classes}
N_tot = sum(N_class.values())
return N_unit, N_class, N_tot
def regroup_per_class(distribution, classes):
"Return classes as they are presented in the data"
new_distribution = {au: {cl: sum([dist_au[c] for c in composition])
for cl,composition in classes.iteritems()}
for au, dist_au in distribution.iteritems()}
return new_distribution
def return_categories(distribution):
"Return the categories in the original data"
keys = next(distribution.itervalues()).keys()
return {k:[k] for k in keys}
<commit_msg>Raise exception if faulty definition of classes inserted<commit_after># -*- coding: utf-8 -*-
"""common.py
Contains basic functions that are shared throughout the module
"""
def compute_totals(distribution, classes):
"Compute the number of individuals per class, per unit and in total"
N_unit = {au:sum([distribution[au][cl] for cl in classes]) for au in distribution}
N_class = {cl:sum([dist_a[cl] for dist_a in distribution.values()]) for cl in classes}
N_tot = sum(N_class.values())
return N_unit, N_class, N_tot
def regroup_per_class(distribution, classes):
"Return classes as they are presented in the data"
try:
new_distribution = {au: {cl: sum([dist_au[c] for c in composition])
for cl,composition in classes.iteritems()}
for au, dist_au in distribution.iteritems()}
except KeyError:
raise KeyError("Verify that the categories specified in the class"
" definitions exist in the original data.")
return new_distribution
def return_categories(distribution):
"Return the categories in the original data"
keys = next(distribution.itervalues()).keys()
return {k:[k] for k in keys}
|
5bf441e34b672a5a369ad7e42cdc2fc7f7699476
|
publishers/base_publisher.py
|
publishers/base_publisher.py
|
from shared.base_component import BaseComponent
class BasePublisher(BaseComponent):
def __init__(self, conf):
BaseComponent.__init__(self, conf)
def publish(self, message):
pass
def __call__(self, message):
if self.query.match(message):
message = self.project.transform(message)
self.publish(message)
def close(self):
pass
|
from shared.base_component import BaseComponent
class BasePublisher(BaseComponent):
def __init__(self, conf):
BaseComponent.__init__(self, conf)
def publish(self, message):
pass
def __call__(self, message):
if self.query.match(message):
message = self.project.transform(message)
if message is not None:
self.publish(message)
def close(self):
pass
|
Discard None values in projections in publishers
|
Discard None values in projections in publishers
|
Python
|
mit
|
weapp/miner
|
from shared.base_component import BaseComponent
class BasePublisher(BaseComponent):
def __init__(self, conf):
BaseComponent.__init__(self, conf)
def publish(self, message):
pass
def __call__(self, message):
if self.query.match(message):
message = self.project.transform(message)
self.publish(message)
def close(self):
pass
Discard None values in projections in publishers
|
from shared.base_component import BaseComponent
class BasePublisher(BaseComponent):
def __init__(self, conf):
BaseComponent.__init__(self, conf)
def publish(self, message):
pass
def __call__(self, message):
if self.query.match(message):
message = self.project.transform(message)
if message is not None:
self.publish(message)
def close(self):
pass
|
<commit_before>from shared.base_component import BaseComponent
class BasePublisher(BaseComponent):
def __init__(self, conf):
BaseComponent.__init__(self, conf)
def publish(self, message):
pass
def __call__(self, message):
if self.query.match(message):
message = self.project.transform(message)
self.publish(message)
def close(self):
pass
<commit_msg>Discard None values in projections in publishers<commit_after>
|
from shared.base_component import BaseComponent
class BasePublisher(BaseComponent):
def __init__(self, conf):
BaseComponent.__init__(self, conf)
def publish(self, message):
pass
def __call__(self, message):
if self.query.match(message):
message = self.project.transform(message)
if message is not None:
self.publish(message)
def close(self):
pass
|
from shared.base_component import BaseComponent
class BasePublisher(BaseComponent):
def __init__(self, conf):
BaseComponent.__init__(self, conf)
def publish(self, message):
pass
def __call__(self, message):
if self.query.match(message):
message = self.project.transform(message)
self.publish(message)
def close(self):
pass
Discard None values in projections in publishersfrom shared.base_component import BaseComponent
class BasePublisher(BaseComponent):
def __init__(self, conf):
BaseComponent.__init__(self, conf)
def publish(self, message):
pass
def __call__(self, message):
if self.query.match(message):
message = self.project.transform(message)
if message is not None:
self.publish(message)
def close(self):
pass
|
<commit_before>from shared.base_component import BaseComponent
class BasePublisher(BaseComponent):
def __init__(self, conf):
BaseComponent.__init__(self, conf)
def publish(self, message):
pass
def __call__(self, message):
if self.query.match(message):
message = self.project.transform(message)
self.publish(message)
def close(self):
pass
<commit_msg>Discard None values in projections in publishers<commit_after>from shared.base_component import BaseComponent
class BasePublisher(BaseComponent):
def __init__(self, conf):
BaseComponent.__init__(self, conf)
def publish(self, message):
pass
def __call__(self, message):
if self.query.match(message):
message = self.project.transform(message)
if message is not None:
self.publish(message)
def close(self):
pass
|
14447e99f550d4b41ccee474fa89382bb0744eb3
|
bookmarks/forms.py
|
bookmarks/forms.py
|
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField
from wtforms.validators import (DataRequired, Length, EqualTo, Email, Regexp,
URL)
class BookmarkForm(FlaskForm):
b_id = StringField('Bookmark ID', [
Length(min=6,
max=6,
message='Bookmark ID must be 6 characters long'),
# Validate only lowercase letters and numbers
Regexp('^[0-9a-z]{1,6}$',
message='Can only include lowercase letters and digits')
])
link = StringField('Link', [
DataRequired(),
URL(message='Link must be a properly formatted URL')
])
follow_redirects = BooleanField('Follow Redirects?')
class RegisterForm(FlaskForm):
username = StringField('Username', [
Length(min=4,
max=25,
message='Username must be between 4 and 25 characters')
])
name = StringField('Name', [DataRequired()])
email = StringField('Email Address', [Email(), Length(min=6, max=35)])
password = PasswordField('New Password', [
Length(min=5, max=18),
EqualTo('confirm', message='Passwords must match')
])
confirm = PasswordField('Repeat Password')
accept_tos = BooleanField('I accept the TOS')
|
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField
from wtforms.validators import (DataRequired, Length, EqualTo, Email, Regexp,
URL)
class BookmarkForm(FlaskForm):
b_id = StringField('Bookmark ID', [
Length(min=6,
max=6,
message='Bookmark ID must be 6 characters long'),
# Validate only lowercase letters and numbers
Regexp('^[0-9a-z]{1,6}$',
message='Can only include lowercase letters and digits')
])
link = StringField('Link', [
DataRequired(),
URL(message='Link must be a properly formatted URL')
])
follow_redirects = BooleanField('Follow Redirects?')
class RegisterForm(FlaskForm):
username = StringField('Username', [
Length(min=4,
max=25,
message='Username must be between 4 and 25 characters')
])
name = StringField('Name', [DataRequired()])
email = StringField('Email Address', [Email(), Length(min=6, max=35)])
password = PasswordField('New Password', [
Length(min=5, max=18,
message='Password must be 5 to 18 characters long'),
# Check for 1 lower, 1 upper, and number
Regexp('^(?=.*[A-Z])(?=.*[0-9])(?=.*[a-z]).{5,18}$',
message='Password must include at least one lowercase letter, \
one uppercase letter, and one number.')
])
confirm = PasswordField('Repeat Password',[
EqualTo('password', message='You must confirm your password')
])
accept_tos = BooleanField('I accept the TOS')
|
Add regex password validation to register form
|
Add regex password validation to register form
Checks for password complexity on registartion
|
Python
|
apache-2.0
|
byanofsky/bookmarks,byanofsky/bookmarks,byanofsky/bookmarks
|
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField
from wtforms.validators import (DataRequired, Length, EqualTo, Email, Regexp,
URL)
class BookmarkForm(FlaskForm):
b_id = StringField('Bookmark ID', [
Length(min=6,
max=6,
message='Bookmark ID must be 6 characters long'),
# Validate only lowercase letters and numbers
Regexp('^[0-9a-z]{1,6}$',
message='Can only include lowercase letters and digits')
])
link = StringField('Link', [
DataRequired(),
URL(message='Link must be a properly formatted URL')
])
follow_redirects = BooleanField('Follow Redirects?')
class RegisterForm(FlaskForm):
username = StringField('Username', [
Length(min=4,
max=25,
message='Username must be between 4 and 25 characters')
])
name = StringField('Name', [DataRequired()])
email = StringField('Email Address', [Email(), Length(min=6, max=35)])
password = PasswordField('New Password', [
Length(min=5, max=18),
EqualTo('confirm', message='Passwords must match')
])
confirm = PasswordField('Repeat Password')
accept_tos = BooleanField('I accept the TOS')
Add regex password validation to register form
Checks for password complexity on registartion
|
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField
from wtforms.validators import (DataRequired, Length, EqualTo, Email, Regexp,
URL)
class BookmarkForm(FlaskForm):
b_id = StringField('Bookmark ID', [
Length(min=6,
max=6,
message='Bookmark ID must be 6 characters long'),
# Validate only lowercase letters and numbers
Regexp('^[0-9a-z]{1,6}$',
message='Can only include lowercase letters and digits')
])
link = StringField('Link', [
DataRequired(),
URL(message='Link must be a properly formatted URL')
])
follow_redirects = BooleanField('Follow Redirects?')
class RegisterForm(FlaskForm):
username = StringField('Username', [
Length(min=4,
max=25,
message='Username must be between 4 and 25 characters')
])
name = StringField('Name', [DataRequired()])
email = StringField('Email Address', [Email(), Length(min=6, max=35)])
password = PasswordField('New Password', [
Length(min=5, max=18,
message='Password must be 5 to 18 characters long'),
# Check for 1 lower, 1 upper, and number
Regexp('^(?=.*[A-Z])(?=.*[0-9])(?=.*[a-z]).{5,18}$',
message='Password must include at least one lowercase letter, \
one uppercase letter, and one number.')
])
confirm = PasswordField('Repeat Password',[
EqualTo('password', message='You must confirm your password')
])
accept_tos = BooleanField('I accept the TOS')
|
<commit_before>from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField
from wtforms.validators import (DataRequired, Length, EqualTo, Email, Regexp,
URL)
class BookmarkForm(FlaskForm):
b_id = StringField('Bookmark ID', [
Length(min=6,
max=6,
message='Bookmark ID must be 6 characters long'),
# Validate only lowercase letters and numbers
Regexp('^[0-9a-z]{1,6}$',
message='Can only include lowercase letters and digits')
])
link = StringField('Link', [
DataRequired(),
URL(message='Link must be a properly formatted URL')
])
follow_redirects = BooleanField('Follow Redirects?')
class RegisterForm(FlaskForm):
username = StringField('Username', [
Length(min=4,
max=25,
message='Username must be between 4 and 25 characters')
])
name = StringField('Name', [DataRequired()])
email = StringField('Email Address', [Email(), Length(min=6, max=35)])
password = PasswordField('New Password', [
Length(min=5, max=18),
EqualTo('confirm', message='Passwords must match')
])
confirm = PasswordField('Repeat Password')
accept_tos = BooleanField('I accept the TOS')
<commit_msg>Add regex password validation to register form
Checks for password complexity on registartion<commit_after>
|
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField
from wtforms.validators import (DataRequired, Length, EqualTo, Email, Regexp,
URL)
class BookmarkForm(FlaskForm):
b_id = StringField('Bookmark ID', [
Length(min=6,
max=6,
message='Bookmark ID must be 6 characters long'),
# Validate only lowercase letters and numbers
Regexp('^[0-9a-z]{1,6}$',
message='Can only include lowercase letters and digits')
])
link = StringField('Link', [
DataRequired(),
URL(message='Link must be a properly formatted URL')
])
follow_redirects = BooleanField('Follow Redirects?')
class RegisterForm(FlaskForm):
username = StringField('Username', [
Length(min=4,
max=25,
message='Username must be between 4 and 25 characters')
])
name = StringField('Name', [DataRequired()])
email = StringField('Email Address', [Email(), Length(min=6, max=35)])
password = PasswordField('New Password', [
Length(min=5, max=18,
message='Password must be 5 to 18 characters long'),
# Check for 1 lower, 1 upper, and number
Regexp('^(?=.*[A-Z])(?=.*[0-9])(?=.*[a-z]).{5,18}$',
message='Password must include at least one lowercase letter, \
one uppercase letter, and one number.')
])
confirm = PasswordField('Repeat Password',[
EqualTo('password', message='You must confirm your password')
])
accept_tos = BooleanField('I accept the TOS')
|
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField
from wtforms.validators import (DataRequired, Length, EqualTo, Email, Regexp,
URL)
class BookmarkForm(FlaskForm):
b_id = StringField('Bookmark ID', [
Length(min=6,
max=6,
message='Bookmark ID must be 6 characters long'),
# Validate only lowercase letters and numbers
Regexp('^[0-9a-z]{1,6}$',
message='Can only include lowercase letters and digits')
])
link = StringField('Link', [
DataRequired(),
URL(message='Link must be a properly formatted URL')
])
follow_redirects = BooleanField('Follow Redirects?')
class RegisterForm(FlaskForm):
username = StringField('Username', [
Length(min=4,
max=25,
message='Username must be between 4 and 25 characters')
])
name = StringField('Name', [DataRequired()])
email = StringField('Email Address', [Email(), Length(min=6, max=35)])
password = PasswordField('New Password', [
Length(min=5, max=18),
EqualTo('confirm', message='Passwords must match')
])
confirm = PasswordField('Repeat Password')
accept_tos = BooleanField('I accept the TOS')
Add regex password validation to register form
Checks for password complexity on registartionfrom flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField
from wtforms.validators import (DataRequired, Length, EqualTo, Email, Regexp,
URL)
class BookmarkForm(FlaskForm):
b_id = StringField('Bookmark ID', [
Length(min=6,
max=6,
message='Bookmark ID must be 6 characters long'),
# Validate only lowercase letters and numbers
Regexp('^[0-9a-z]{1,6}$',
message='Can only include lowercase letters and digits')
])
link = StringField('Link', [
DataRequired(),
URL(message='Link must be a properly formatted URL')
])
follow_redirects = BooleanField('Follow Redirects?')
class RegisterForm(FlaskForm):
username = StringField('Username', [
Length(min=4,
max=25,
message='Username must be between 4 and 25 characters')
])
name = StringField('Name', [DataRequired()])
email = StringField('Email Address', [Email(), Length(min=6, max=35)])
password = PasswordField('New Password', [
Length(min=5, max=18,
message='Password must be 5 to 18 characters long'),
# Check for 1 lower, 1 upper, and number
Regexp('^(?=.*[A-Z])(?=.*[0-9])(?=.*[a-z]).{5,18}$',
message='Password must include at least one lowercase letter, \
one uppercase letter, and one number.')
])
confirm = PasswordField('Repeat Password',[
EqualTo('password', message='You must confirm your password')
])
accept_tos = BooleanField('I accept the TOS')
|
<commit_before>from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField
from wtforms.validators import (DataRequired, Length, EqualTo, Email, Regexp,
URL)
class BookmarkForm(FlaskForm):
b_id = StringField('Bookmark ID', [
Length(min=6,
max=6,
message='Bookmark ID must be 6 characters long'),
# Validate only lowercase letters and numbers
Regexp('^[0-9a-z]{1,6}$',
message='Can only include lowercase letters and digits')
])
link = StringField('Link', [
DataRequired(),
URL(message='Link must be a properly formatted URL')
])
follow_redirects = BooleanField('Follow Redirects?')
class RegisterForm(FlaskForm):
username = StringField('Username', [
Length(min=4,
max=25,
message='Username must be between 4 and 25 characters')
])
name = StringField('Name', [DataRequired()])
email = StringField('Email Address', [Email(), Length(min=6, max=35)])
password = PasswordField('New Password', [
Length(min=5, max=18),
EqualTo('confirm', message='Passwords must match')
])
confirm = PasswordField('Repeat Password')
accept_tos = BooleanField('I accept the TOS')
<commit_msg>Add regex password validation to register form
Checks for password complexity on registartion<commit_after>from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField
from wtforms.validators import (DataRequired, Length, EqualTo, Email, Regexp,
URL)
class BookmarkForm(FlaskForm):
b_id = StringField('Bookmark ID', [
Length(min=6,
max=6,
message='Bookmark ID must be 6 characters long'),
# Validate only lowercase letters and numbers
Regexp('^[0-9a-z]{1,6}$',
message='Can only include lowercase letters and digits')
])
link = StringField('Link', [
DataRequired(),
URL(message='Link must be a properly formatted URL')
])
follow_redirects = BooleanField('Follow Redirects?')
class RegisterForm(FlaskForm):
username = StringField('Username', [
Length(min=4,
max=25,
message='Username must be between 4 and 25 characters')
])
name = StringField('Name', [DataRequired()])
email = StringField('Email Address', [Email(), Length(min=6, max=35)])
password = PasswordField('New Password', [
Length(min=5, max=18,
message='Password must be 5 to 18 characters long'),
# Check for 1 lower, 1 upper, and number
Regexp('^(?=.*[A-Z])(?=.*[0-9])(?=.*[a-z]).{5,18}$',
message='Password must include at least one lowercase letter, \
one uppercase letter, and one number.')
])
confirm = PasswordField('Repeat Password',[
EqualTo('password', message='You must confirm your password')
])
accept_tos = BooleanField('I accept the TOS')
|
c41115875ce46be3eacc1ec7c539010b430b0374
|
kegg_adapter/kegg.py
|
kegg_adapter/kegg.py
|
import urllib2
import json
#response = urllib2.urlopen('http://rest.kegg.jp/list/pathway/ath')
#html = response.read()
#lines = html.split('\n');
#data = {};
#for line in lines:
# parts = line.split('\t');
# if len(parts) >= 2:
# data[parts[0]] = parts[1]
#json_data = json.dumps(data)
#print json_data
def search(args):
if not 'operation' in args.keys():
exit(1);
if not 'argument' in args.keys():
exit(1);
url = 'http://rest.kegg.jp/'
operation = args['operation']
argument = args['argument']
url+= operation + '/' + argument
if 'argument2' in args.keys():
url+= '/' + args['argument2']
if 'option' in args.keys():
url+= '/' + args['option']
response = urllib2.urlopen(url)
html = response.read()
data = {}
if operation == 'find' or operation == 'list'\
or operation == 'link' or operation == 'conv':
print "jsonizing"
lines = html.split('\n')
for line in lines:
parts = line.split('\t');
if len(parts) >= 2:
data[parts[0]] = parts[1]
result = {}
result['results'] = data
result['args'] = args
print json.dumps(result);
|
import urllib2
import json
#response = urllib2.urlopen('http://rest.kegg.jp/list/pathway/ath')
#html = response.read()
#lines = html.split('\n');
#data = {};
#for line in lines:
# parts = line.split('\t');
# if len(parts) >= 2:
# data[parts[0]] = parts[1]
#json_data = json.dumps(data)
#print json_data
def search(args):
if not 'operation' in args.keys():
exit(0);
if not 'argument' in args.keys():
exit(0);
url = 'http://rest.kegg.jp/'
operation = args['operation']
argument = args['argument']
url+= operation + '/' + argument
if 'argument2' in args.keys():
url+= '/' + args['argument2']
if 'option' in args.keys():
url+= '/' + args['option']
response = urllib2.urlopen(url)
html = response.read()
data = {}
if operation == 'find' or operation == 'list'\
or operation == 'link' or operation == 'conv':
lines = html.split('\n')
for line in lines:
parts = line.split('\t');
if len(parts) >= 2:
data[parts[0]] = parts[1]
result = {}
result['results'] = data
result['args'] = args
print json.dumps(result);
|
Remove debugging print statements changed exit status from 1 to 0
|
Remove debugging print statements
changed exit status from 1 to 0
|
Python
|
artistic-2.0
|
Arabidopsis-Information-Portal/Intern-Hello-World,Arabidopsis-Information-Portal/KEGG-Pathway-API
|
import urllib2
import json
#response = urllib2.urlopen('http://rest.kegg.jp/list/pathway/ath')
#html = response.read()
#lines = html.split('\n');
#data = {};
#for line in lines:
# parts = line.split('\t');
# if len(parts) >= 2:
# data[parts[0]] = parts[1]
#json_data = json.dumps(data)
#print json_data
def search(args):
if not 'operation' in args.keys():
exit(1);
if not 'argument' in args.keys():
exit(1);
url = 'http://rest.kegg.jp/'
operation = args['operation']
argument = args['argument']
url+= operation + '/' + argument
if 'argument2' in args.keys():
url+= '/' + args['argument2']
if 'option' in args.keys():
url+= '/' + args['option']
response = urllib2.urlopen(url)
html = response.read()
data = {}
if operation == 'find' or operation == 'list'\
or operation == 'link' or operation == 'conv':
print "jsonizing"
lines = html.split('\n')
for line in lines:
parts = line.split('\t');
if len(parts) >= 2:
data[parts[0]] = parts[1]
result = {}
result['results'] = data
result['args'] = args
print json.dumps(result);
Remove debugging print statements
changed exit status from 1 to 0
|
import urllib2
import json
#response = urllib2.urlopen('http://rest.kegg.jp/list/pathway/ath')
#html = response.read()
#lines = html.split('\n');
#data = {};
#for line in lines:
# parts = line.split('\t');
# if len(parts) >= 2:
# data[parts[0]] = parts[1]
#json_data = json.dumps(data)
#print json_data
def search(args):
if not 'operation' in args.keys():
exit(0);
if not 'argument' in args.keys():
exit(0);
url = 'http://rest.kegg.jp/'
operation = args['operation']
argument = args['argument']
url+= operation + '/' + argument
if 'argument2' in args.keys():
url+= '/' + args['argument2']
if 'option' in args.keys():
url+= '/' + args['option']
response = urllib2.urlopen(url)
html = response.read()
data = {}
if operation == 'find' or operation == 'list'\
or operation == 'link' or operation == 'conv':
lines = html.split('\n')
for line in lines:
parts = line.split('\t');
if len(parts) >= 2:
data[parts[0]] = parts[1]
result = {}
result['results'] = data
result['args'] = args
print json.dumps(result);
|
<commit_before>import urllib2
import json
#response = urllib2.urlopen('http://rest.kegg.jp/list/pathway/ath')
#html = response.read()
#lines = html.split('\n');
#data = {};
#for line in lines:
# parts = line.split('\t');
# if len(parts) >= 2:
# data[parts[0]] = parts[1]
#json_data = json.dumps(data)
#print json_data
def search(args):
if not 'operation' in args.keys():
exit(1);
if not 'argument' in args.keys():
exit(1);
url = 'http://rest.kegg.jp/'
operation = args['operation']
argument = args['argument']
url+= operation + '/' + argument
if 'argument2' in args.keys():
url+= '/' + args['argument2']
if 'option' in args.keys():
url+= '/' + args['option']
response = urllib2.urlopen(url)
html = response.read()
data = {}
if operation == 'find' or operation == 'list'\
or operation == 'link' or operation == 'conv':
print "jsonizing"
lines = html.split('\n')
for line in lines:
parts = line.split('\t');
if len(parts) >= 2:
data[parts[0]] = parts[1]
result = {}
result['results'] = data
result['args'] = args
print json.dumps(result);
<commit_msg>Remove debugging print statements
changed exit status from 1 to 0<commit_after>
|
import urllib2
import json
#response = urllib2.urlopen('http://rest.kegg.jp/list/pathway/ath')
#html = response.read()
#lines = html.split('\n');
#data = {};
#for line in lines:
# parts = line.split('\t');
# if len(parts) >= 2:
# data[parts[0]] = parts[1]
#json_data = json.dumps(data)
#print json_data
def search(args):
if not 'operation' in args.keys():
exit(0);
if not 'argument' in args.keys():
exit(0);
url = 'http://rest.kegg.jp/'
operation = args['operation']
argument = args['argument']
url+= operation + '/' + argument
if 'argument2' in args.keys():
url+= '/' + args['argument2']
if 'option' in args.keys():
url+= '/' + args['option']
response = urllib2.urlopen(url)
html = response.read()
data = {}
if operation == 'find' or operation == 'list'\
or operation == 'link' or operation == 'conv':
lines = html.split('\n')
for line in lines:
parts = line.split('\t');
if len(parts) >= 2:
data[parts[0]] = parts[1]
result = {}
result['results'] = data
result['args'] = args
print json.dumps(result);
|
import urllib2
import json
#response = urllib2.urlopen('http://rest.kegg.jp/list/pathway/ath')
#html = response.read()
#lines = html.split('\n');
#data = {};
#for line in lines:
# parts = line.split('\t');
# if len(parts) >= 2:
# data[parts[0]] = parts[1]
#json_data = json.dumps(data)
#print json_data
def search(args):
if not 'operation' in args.keys():
exit(1);
if not 'argument' in args.keys():
exit(1);
url = 'http://rest.kegg.jp/'
operation = args['operation']
argument = args['argument']
url+= operation + '/' + argument
if 'argument2' in args.keys():
url+= '/' + args['argument2']
if 'option' in args.keys():
url+= '/' + args['option']
response = urllib2.urlopen(url)
html = response.read()
data = {}
if operation == 'find' or operation == 'list'\
or operation == 'link' or operation == 'conv':
print "jsonizing"
lines = html.split('\n')
for line in lines:
parts = line.split('\t');
if len(parts) >= 2:
data[parts[0]] = parts[1]
result = {}
result['results'] = data
result['args'] = args
print json.dumps(result);
Remove debugging print statements
changed exit status from 1 to 0import urllib2
import json
#response = urllib2.urlopen('http://rest.kegg.jp/list/pathway/ath')
#html = response.read()
#lines = html.split('\n');
#data = {};
#for line in lines:
# parts = line.split('\t');
# if len(parts) >= 2:
# data[parts[0]] = parts[1]
#json_data = json.dumps(data)
#print json_data
def search(args):
if not 'operation' in args.keys():
exit(0);
if not 'argument' in args.keys():
exit(0);
url = 'http://rest.kegg.jp/'
operation = args['operation']
argument = args['argument']
url+= operation + '/' + argument
if 'argument2' in args.keys():
url+= '/' + args['argument2']
if 'option' in args.keys():
url+= '/' + args['option']
response = urllib2.urlopen(url)
html = response.read()
data = {}
if operation == 'find' or operation == 'list'\
or operation == 'link' or operation == 'conv':
lines = html.split('\n')
for line in lines:
parts = line.split('\t');
if len(parts) >= 2:
data[parts[0]] = parts[1]
result = {}
result['results'] = data
result['args'] = args
print json.dumps(result);
|
<commit_before>import urllib2
import json
#response = urllib2.urlopen('http://rest.kegg.jp/list/pathway/ath')
#html = response.read()
#lines = html.split('\n');
#data = {};
#for line in lines:
# parts = line.split('\t');
# if len(parts) >= 2:
# data[parts[0]] = parts[1]
#json_data = json.dumps(data)
#print json_data
def search(args):
if not 'operation' in args.keys():
exit(1);
if not 'argument' in args.keys():
exit(1);
url = 'http://rest.kegg.jp/'
operation = args['operation']
argument = args['argument']
url+= operation + '/' + argument
if 'argument2' in args.keys():
url+= '/' + args['argument2']
if 'option' in args.keys():
url+= '/' + args['option']
response = urllib2.urlopen(url)
html = response.read()
data = {}
if operation == 'find' or operation == 'list'\
or operation == 'link' or operation == 'conv':
print "jsonizing"
lines = html.split('\n')
for line in lines:
parts = line.split('\t');
if len(parts) >= 2:
data[parts[0]] = parts[1]
result = {}
result['results'] = data
result['args'] = args
print json.dumps(result);
<commit_msg>Remove debugging print statements
changed exit status from 1 to 0<commit_after>import urllib2
import json
#response = urllib2.urlopen('http://rest.kegg.jp/list/pathway/ath')
#html = response.read()
#lines = html.split('\n');
#data = {};
#for line in lines:
# parts = line.split('\t');
# if len(parts) >= 2:
# data[parts[0]] = parts[1]
#json_data = json.dumps(data)
#print json_data
def search(args):
if not 'operation' in args.keys():
exit(0);
if not 'argument' in args.keys():
exit(0);
url = 'http://rest.kegg.jp/'
operation = args['operation']
argument = args['argument']
url+= operation + '/' + argument
if 'argument2' in args.keys():
url+= '/' + args['argument2']
if 'option' in args.keys():
url+= '/' + args['option']
response = urllib2.urlopen(url)
html = response.read()
data = {}
if operation == 'find' or operation == 'list'\
or operation == 'link' or operation == 'conv':
lines = html.split('\n')
for line in lines:
parts = line.split('\t');
if len(parts) >= 2:
data[parts[0]] = parts[1]
result = {}
result['results'] = data
result['args'] = args
print json.dumps(result);
|
b1c8ce6ac2658264a97983b185ebef31c0952b33
|
depot/tests.py
|
depot/tests.py
|
from django.test import TestCase
from .models import Depot
class DepotTestCase(TestCase):
def test_str(self):
depot = Depot(1, "My depot")
self.assertEqual(depot.__str__(), "Depot My depot")
|
from django.test import TestCase
from .models import Depot, Item
class DepotTestCase(TestCase):
def test_str(self):
depot = Depot(1, "My depot")
self.assertEqual(depot.__str__(), "Depot My depot")
class ItemTestCase(TestCase):
def test_str(self):
depot = Depot(2, "My depot")
item = Item(1, "My item", 5, 2, depot, "My shelf")
self.assertEqual(item.__str__(), "5 unit(s) of My item (visib.: 2) in My shelf")
|
Add test case for Item __str__ function
|
Add test case for Item __str__ function
|
Python
|
agpl-3.0
|
verleihtool/verleihtool,verleihtool/verleihtool,verleihtool/verleihtool,verleihtool/verleihtool
|
from django.test import TestCase
from .models import Depot
class DepotTestCase(TestCase):
def test_str(self):
depot = Depot(1, "My depot")
self.assertEqual(depot.__str__(), "Depot My depot")
Add test case for Item __str__ function
|
from django.test import TestCase
from .models import Depot, Item
class DepotTestCase(TestCase):
def test_str(self):
depot = Depot(1, "My depot")
self.assertEqual(depot.__str__(), "Depot My depot")
class ItemTestCase(TestCase):
def test_str(self):
depot = Depot(2, "My depot")
item = Item(1, "My item", 5, 2, depot, "My shelf")
self.assertEqual(item.__str__(), "5 unit(s) of My item (visib.: 2) in My shelf")
|
<commit_before>from django.test import TestCase
from .models import Depot
class DepotTestCase(TestCase):
def test_str(self):
depot = Depot(1, "My depot")
self.assertEqual(depot.__str__(), "Depot My depot")
<commit_msg>Add test case for Item __str__ function<commit_after>
|
from django.test import TestCase
from .models import Depot, Item
class DepotTestCase(TestCase):
def test_str(self):
depot = Depot(1, "My depot")
self.assertEqual(depot.__str__(), "Depot My depot")
class ItemTestCase(TestCase):
def test_str(self):
depot = Depot(2, "My depot")
item = Item(1, "My item", 5, 2, depot, "My shelf")
self.assertEqual(item.__str__(), "5 unit(s) of My item (visib.: 2) in My shelf")
|
from django.test import TestCase
from .models import Depot
class DepotTestCase(TestCase):
def test_str(self):
depot = Depot(1, "My depot")
self.assertEqual(depot.__str__(), "Depot My depot")
Add test case for Item __str__ functionfrom django.test import TestCase
from .models import Depot, Item
class DepotTestCase(TestCase):
def test_str(self):
depot = Depot(1, "My depot")
self.assertEqual(depot.__str__(), "Depot My depot")
class ItemTestCase(TestCase):
def test_str(self):
depot = Depot(2, "My depot")
item = Item(1, "My item", 5, 2, depot, "My shelf")
self.assertEqual(item.__str__(), "5 unit(s) of My item (visib.: 2) in My shelf")
|
<commit_before>from django.test import TestCase
from .models import Depot
class DepotTestCase(TestCase):
def test_str(self):
depot = Depot(1, "My depot")
self.assertEqual(depot.__str__(), "Depot My depot")
<commit_msg>Add test case for Item __str__ function<commit_after>from django.test import TestCase
from .models import Depot, Item
class DepotTestCase(TestCase):
def test_str(self):
depot = Depot(1, "My depot")
self.assertEqual(depot.__str__(), "Depot My depot")
class ItemTestCase(TestCase):
def test_str(self):
depot = Depot(2, "My depot")
item = Item(1, "My item", 5, 2, depot, "My shelf")
self.assertEqual(item.__str__(), "5 unit(s) of My item (visib.: 2) in My shelf")
|
c6e23473520a3b055896524663779fa582189763
|
datacats/tests/test_cli_pull.py
|
datacats/tests/test_cli_pull.py
|
from datacats.cli.pull import _retry_func
from datacats.error import DatacatsError
from unittest import TestCase
def raise_an_error(_):
raise DatacatsError('Hi')
class TestPullCli(TestCase):
def test_cli_pull_retry(self):
def count(*dummy, **_):
count.counter += 1
count.counter = 0
try:
_retry_func(raise_an_error, None, 5, count,
'Error! We wanted this to happen')
self.fail('Exception was not raised.')
except DatacatsError:
pass
finally:
self.assertEqual(count.counter, 4)
|
from datacats.cli.pull import _retry_func
from datacats.error import DatacatsError
from unittest import TestCase
def raise_an_error(_):
raise DatacatsError('Hi')
class TestPullCli(TestCase):
def test_cli_pull_retry(self):
def count(*dummy, **_):
count.counter += 1
count.counter = 0
try:
_retry_func(raise_an_error, None, 5, count,
'Error! We wanted this to happen')
self.fail('Exception was not raised.')
except DatacatsError as e:
self.assertEqual(count.counter, 4)
self.failIf('We wanted this to happen' not in str(e))
|
Move around assertions as Ian talked about
|
Move around assertions as Ian talked about
|
Python
|
agpl-3.0
|
datawagovau/datacats,JJediny/datacats,JackMc/datacats,reneenoble/datacats,wardi/datacats,deniszgonjanin/datacats,poguez/datacats,datawagovau/datacats,wardi/datacats,datacats/datacats,reneenoble/datacats,JackMc/datacats,poguez/datacats,deniszgonjanin/datacats,JJediny/datacats,datacats/datacats
|
from datacats.cli.pull import _retry_func
from datacats.error import DatacatsError
from unittest import TestCase
def raise_an_error(_):
raise DatacatsError('Hi')
class TestPullCli(TestCase):
def test_cli_pull_retry(self):
def count(*dummy, **_):
count.counter += 1
count.counter = 0
try:
_retry_func(raise_an_error, None, 5, count,
'Error! We wanted this to happen')
self.fail('Exception was not raised.')
except DatacatsError:
pass
finally:
self.assertEqual(count.counter, 4)
Move around assertions as Ian talked about
|
from datacats.cli.pull import _retry_func
from datacats.error import DatacatsError
from unittest import TestCase
def raise_an_error(_):
raise DatacatsError('Hi')
class TestPullCli(TestCase):
def test_cli_pull_retry(self):
def count(*dummy, **_):
count.counter += 1
count.counter = 0
try:
_retry_func(raise_an_error, None, 5, count,
'Error! We wanted this to happen')
self.fail('Exception was not raised.')
except DatacatsError as e:
self.assertEqual(count.counter, 4)
self.failIf('We wanted this to happen' not in str(e))
|
<commit_before>from datacats.cli.pull import _retry_func
from datacats.error import DatacatsError
from unittest import TestCase
def raise_an_error(_):
raise DatacatsError('Hi')
class TestPullCli(TestCase):
def test_cli_pull_retry(self):
def count(*dummy, **_):
count.counter += 1
count.counter = 0
try:
_retry_func(raise_an_error, None, 5, count,
'Error! We wanted this to happen')
self.fail('Exception was not raised.')
except DatacatsError:
pass
finally:
self.assertEqual(count.counter, 4)
<commit_msg>Move around assertions as Ian talked about<commit_after>
|
from datacats.cli.pull import _retry_func
from datacats.error import DatacatsError
from unittest import TestCase
def raise_an_error(_):
raise DatacatsError('Hi')
class TestPullCli(TestCase):
def test_cli_pull_retry(self):
def count(*dummy, **_):
count.counter += 1
count.counter = 0
try:
_retry_func(raise_an_error, None, 5, count,
'Error! We wanted this to happen')
self.fail('Exception was not raised.')
except DatacatsError as e:
self.assertEqual(count.counter, 4)
self.failIf('We wanted this to happen' not in str(e))
|
from datacats.cli.pull import _retry_func
from datacats.error import DatacatsError
from unittest import TestCase
def raise_an_error(_):
raise DatacatsError('Hi')
class TestPullCli(TestCase):
def test_cli_pull_retry(self):
def count(*dummy, **_):
count.counter += 1
count.counter = 0
try:
_retry_func(raise_an_error, None, 5, count,
'Error! We wanted this to happen')
self.fail('Exception was not raised.')
except DatacatsError:
pass
finally:
self.assertEqual(count.counter, 4)
Move around assertions as Ian talked aboutfrom datacats.cli.pull import _retry_func
from datacats.error import DatacatsError
from unittest import TestCase
def raise_an_error(_):
raise DatacatsError('Hi')
class TestPullCli(TestCase):
def test_cli_pull_retry(self):
def count(*dummy, **_):
count.counter += 1
count.counter = 0
try:
_retry_func(raise_an_error, None, 5, count,
'Error! We wanted this to happen')
self.fail('Exception was not raised.')
except DatacatsError as e:
self.assertEqual(count.counter, 4)
self.failIf('We wanted this to happen' not in str(e))
|
<commit_before>from datacats.cli.pull import _retry_func
from datacats.error import DatacatsError
from unittest import TestCase
def raise_an_error(_):
raise DatacatsError('Hi')
class TestPullCli(TestCase):
def test_cli_pull_retry(self):
def count(*dummy, **_):
count.counter += 1
count.counter = 0
try:
_retry_func(raise_an_error, None, 5, count,
'Error! We wanted this to happen')
self.fail('Exception was not raised.')
except DatacatsError:
pass
finally:
self.assertEqual(count.counter, 4)
<commit_msg>Move around assertions as Ian talked about<commit_after>from datacats.cli.pull import _retry_func
from datacats.error import DatacatsError
from unittest import TestCase
def raise_an_error(_):
raise DatacatsError('Hi')
class TestPullCli(TestCase):
def test_cli_pull_retry(self):
def count(*dummy, **_):
count.counter += 1
count.counter = 0
try:
_retry_func(raise_an_error, None, 5, count,
'Error! We wanted this to happen')
self.fail('Exception was not raised.')
except DatacatsError as e:
self.assertEqual(count.counter, 4)
self.failIf('We wanted this to happen' not in str(e))
|
2a550df5d9200deb6700fca4270526633811d592
|
osfclient/cli.py
|
osfclient/cli.py
|
"""Command line interface to the OSF"""
import os
from .api import OSF
CHUNK_SIZE = int(5e6)
def _setup_osf(args):
# command line argument overrides environment variable
username = os.getenv("OSF_USERNAME")
if args.username is not None:
username = args.username
password = os.getenv("OSF_PASSWORD")
return OSF(username=username, password=password)
def fetch(args):
osf = _setup_osf(args)
project = osf.project(args.project)
output_dir = args.project
if args.output is not None:
output_dir = args.output
for store in project.storages:
prefix = os.path.join(output_dir, store.name)
for file_ in store.files:
path = file_.path
if path.startswith('/'):
path = path[1:]
path = os.path.join(prefix, path)
directory, _ = os.path.split(path)
os.makedirs(directory, exist_ok=True)
with open(path, "wb") as f:
file_.write_to(f)
def list_(args):
osf = _setup_osf(args)
project = osf.project(args.project)
for store in project.storages:
prefix = store.name
for file_ in store.files:
path = file_.path
if path.startswith('/'):
path = path[1:]
print(os.path.join(prefix, path))
|
"""Command line interface to the OSF"""
import os
from .api import OSF
CHUNK_SIZE = int(5e6)
def _setup_osf(args):
# command line argument overrides environment variable
username = os.getenv("OSF_USERNAME")
if args.username is not None:
username = args.username
password = None
if username is not None:
password = os.getenv("OSF_PASSWORD")
return OSF(username=username, password=password)
def fetch(args):
osf = _setup_osf(args)
project = osf.project(args.project)
output_dir = args.project
if args.output is not None:
output_dir = args.output
for store in project.storages:
prefix = os.path.join(output_dir, store.name)
for file_ in store.files:
path = file_.path
if path.startswith('/'):
path = path[1:]
path = os.path.join(prefix, path)
directory, _ = os.path.split(path)
os.makedirs(directory, exist_ok=True)
with open(path, "wb") as f:
file_.write_to(f)
def list_(args):
osf = _setup_osf(args)
project = osf.project(args.project)
for store in project.storages:
prefix = store.name
for file_ in store.files:
path = file_.path
if path.startswith('/'):
path = path[1:]
print(os.path.join(prefix, path))
|
Stop grabbing password when there is no username
|
Stop grabbing password when there is no username
|
Python
|
bsd-3-clause
|
betatim/osf-cli,betatim/osf-cli
|
"""Command line interface to the OSF"""
import os
from .api import OSF
CHUNK_SIZE = int(5e6)
def _setup_osf(args):
# command line argument overrides environment variable
username = os.getenv("OSF_USERNAME")
if args.username is not None:
username = args.username
password = os.getenv("OSF_PASSWORD")
return OSF(username=username, password=password)
def fetch(args):
osf = _setup_osf(args)
project = osf.project(args.project)
output_dir = args.project
if args.output is not None:
output_dir = args.output
for store in project.storages:
prefix = os.path.join(output_dir, store.name)
for file_ in store.files:
path = file_.path
if path.startswith('/'):
path = path[1:]
path = os.path.join(prefix, path)
directory, _ = os.path.split(path)
os.makedirs(directory, exist_ok=True)
with open(path, "wb") as f:
file_.write_to(f)
def list_(args):
osf = _setup_osf(args)
project = osf.project(args.project)
for store in project.storages:
prefix = store.name
for file_ in store.files:
path = file_.path
if path.startswith('/'):
path = path[1:]
print(os.path.join(prefix, path))
Stop grabbing password when there is no username
|
"""Command line interface to the OSF"""
import os
from .api import OSF
CHUNK_SIZE = int(5e6)
def _setup_osf(args):
# command line argument overrides environment variable
username = os.getenv("OSF_USERNAME")
if args.username is not None:
username = args.username
password = None
if username is not None:
password = os.getenv("OSF_PASSWORD")
return OSF(username=username, password=password)
def fetch(args):
osf = _setup_osf(args)
project = osf.project(args.project)
output_dir = args.project
if args.output is not None:
output_dir = args.output
for store in project.storages:
prefix = os.path.join(output_dir, store.name)
for file_ in store.files:
path = file_.path
if path.startswith('/'):
path = path[1:]
path = os.path.join(prefix, path)
directory, _ = os.path.split(path)
os.makedirs(directory, exist_ok=True)
with open(path, "wb") as f:
file_.write_to(f)
def list_(args):
osf = _setup_osf(args)
project = osf.project(args.project)
for store in project.storages:
prefix = store.name
for file_ in store.files:
path = file_.path
if path.startswith('/'):
path = path[1:]
print(os.path.join(prefix, path))
|
<commit_before>"""Command line interface to the OSF"""
import os
from .api import OSF
CHUNK_SIZE = int(5e6)
def _setup_osf(args):
# command line argument overrides environment variable
username = os.getenv("OSF_USERNAME")
if args.username is not None:
username = args.username
password = os.getenv("OSF_PASSWORD")
return OSF(username=username, password=password)
def fetch(args):
osf = _setup_osf(args)
project = osf.project(args.project)
output_dir = args.project
if args.output is not None:
output_dir = args.output
for store in project.storages:
prefix = os.path.join(output_dir, store.name)
for file_ in store.files:
path = file_.path
if path.startswith('/'):
path = path[1:]
path = os.path.join(prefix, path)
directory, _ = os.path.split(path)
os.makedirs(directory, exist_ok=True)
with open(path, "wb") as f:
file_.write_to(f)
def list_(args):
osf = _setup_osf(args)
project = osf.project(args.project)
for store in project.storages:
prefix = store.name
for file_ in store.files:
path = file_.path
if path.startswith('/'):
path = path[1:]
print(os.path.join(prefix, path))
<commit_msg>Stop grabbing password when there is no username<commit_after>
|
"""Command line interface to the OSF"""
import os
from .api import OSF
CHUNK_SIZE = int(5e6)
def _setup_osf(args):
# command line argument overrides environment variable
username = os.getenv("OSF_USERNAME")
if args.username is not None:
username = args.username
password = None
if username is not None:
password = os.getenv("OSF_PASSWORD")
return OSF(username=username, password=password)
def fetch(args):
osf = _setup_osf(args)
project = osf.project(args.project)
output_dir = args.project
if args.output is not None:
output_dir = args.output
for store in project.storages:
prefix = os.path.join(output_dir, store.name)
for file_ in store.files:
path = file_.path
if path.startswith('/'):
path = path[1:]
path = os.path.join(prefix, path)
directory, _ = os.path.split(path)
os.makedirs(directory, exist_ok=True)
with open(path, "wb") as f:
file_.write_to(f)
def list_(args):
osf = _setup_osf(args)
project = osf.project(args.project)
for store in project.storages:
prefix = store.name
for file_ in store.files:
path = file_.path
if path.startswith('/'):
path = path[1:]
print(os.path.join(prefix, path))
|
"""Command line interface to the OSF"""
import os
from .api import OSF
CHUNK_SIZE = int(5e6)
def _setup_osf(args):
# command line argument overrides environment variable
username = os.getenv("OSF_USERNAME")
if args.username is not None:
username = args.username
password = os.getenv("OSF_PASSWORD")
return OSF(username=username, password=password)
def fetch(args):
osf = _setup_osf(args)
project = osf.project(args.project)
output_dir = args.project
if args.output is not None:
output_dir = args.output
for store in project.storages:
prefix = os.path.join(output_dir, store.name)
for file_ in store.files:
path = file_.path
if path.startswith('/'):
path = path[1:]
path = os.path.join(prefix, path)
directory, _ = os.path.split(path)
os.makedirs(directory, exist_ok=True)
with open(path, "wb") as f:
file_.write_to(f)
def list_(args):
osf = _setup_osf(args)
project = osf.project(args.project)
for store in project.storages:
prefix = store.name
for file_ in store.files:
path = file_.path
if path.startswith('/'):
path = path[1:]
print(os.path.join(prefix, path))
Stop grabbing password when there is no username"""Command line interface to the OSF"""
import os
from .api import OSF
CHUNK_SIZE = int(5e6)
def _setup_osf(args):
# command line argument overrides environment variable
username = os.getenv("OSF_USERNAME")
if args.username is not None:
username = args.username
password = None
if username is not None:
password = os.getenv("OSF_PASSWORD")
return OSF(username=username, password=password)
def fetch(args):
osf = _setup_osf(args)
project = osf.project(args.project)
output_dir = args.project
if args.output is not None:
output_dir = args.output
for store in project.storages:
prefix = os.path.join(output_dir, store.name)
for file_ in store.files:
path = file_.path
if path.startswith('/'):
path = path[1:]
path = os.path.join(prefix, path)
directory, _ = os.path.split(path)
os.makedirs(directory, exist_ok=True)
with open(path, "wb") as f:
file_.write_to(f)
def list_(args):
osf = _setup_osf(args)
project = osf.project(args.project)
for store in project.storages:
prefix = store.name
for file_ in store.files:
path = file_.path
if path.startswith('/'):
path = path[1:]
print(os.path.join(prefix, path))
|
<commit_before>"""Command line interface to the OSF"""
import os
from .api import OSF
CHUNK_SIZE = int(5e6)
def _setup_osf(args):
# command line argument overrides environment variable
username = os.getenv("OSF_USERNAME")
if args.username is not None:
username = args.username
password = os.getenv("OSF_PASSWORD")
return OSF(username=username, password=password)
def fetch(args):
osf = _setup_osf(args)
project = osf.project(args.project)
output_dir = args.project
if args.output is not None:
output_dir = args.output
for store in project.storages:
prefix = os.path.join(output_dir, store.name)
for file_ in store.files:
path = file_.path
if path.startswith('/'):
path = path[1:]
path = os.path.join(prefix, path)
directory, _ = os.path.split(path)
os.makedirs(directory, exist_ok=True)
with open(path, "wb") as f:
file_.write_to(f)
def list_(args):
osf = _setup_osf(args)
project = osf.project(args.project)
for store in project.storages:
prefix = store.name
for file_ in store.files:
path = file_.path
if path.startswith('/'):
path = path[1:]
print(os.path.join(prefix, path))
<commit_msg>Stop grabbing password when there is no username<commit_after>"""Command line interface to the OSF"""
import os
from .api import OSF
CHUNK_SIZE = int(5e6)
def _setup_osf(args):
# command line argument overrides environment variable
username = os.getenv("OSF_USERNAME")
if args.username is not None:
username = args.username
password = None
if username is not None:
password = os.getenv("OSF_PASSWORD")
return OSF(username=username, password=password)
def fetch(args):
osf = _setup_osf(args)
project = osf.project(args.project)
output_dir = args.project
if args.output is not None:
output_dir = args.output
for store in project.storages:
prefix = os.path.join(output_dir, store.name)
for file_ in store.files:
path = file_.path
if path.startswith('/'):
path = path[1:]
path = os.path.join(prefix, path)
directory, _ = os.path.split(path)
os.makedirs(directory, exist_ok=True)
with open(path, "wb") as f:
file_.write_to(f)
def list_(args):
osf = _setup_osf(args)
project = osf.project(args.project)
for store in project.storages:
prefix = store.name
for file_ in store.files:
path = file_.path
if path.startswith('/'):
path = path[1:]
print(os.path.join(prefix, path))
|
11906213015f03cfdb3f247a6dbcab0619be61e3
|
comrade/core/decorators.py
|
comrade/core/decorators.py
|
from django.shortcuts import get_object_or_404
from django.utils.decorators import available_attrs
from django.utils.http import urlquote
from django.http import HttpResponse
from django.template import loader, RequestContext
from functools import wraps
def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
def authorized(test_func, template_name='401.html'):
"""
Decorator for views that checks that the user passes the given test,
redirecting to the unauthorized page if it fails. The test should be a
callable that takes the user object and returns True if the user passes.
"""
def decorator(view_func):
def _wrapped_view(request, *args, **kwargs):
if test_func(request.user, *args, **kwargs):
return view_func(request, *args, **kwargs)
path = urlquote(request.get_full_path())
t = loader.get_template(template_name)
return HttpResponse(t.render(RequestContext(request)), status=401)
return wraps(view_func,
assigned=available_attrs(view_func))(_wrapped_view)
return decorator
def load_instance(model):
def decorator(view):
def _wrapper(request, object_id=None, *args, **kwargs):
if object_id:
instance = get_object_or_404(model, pk=object_id)
return view(request, instance, *args, **kwargs)
return view(request, *args, **kwargs)
return wraps(view)(_wrapper)
return decorator
|
from django.shortcuts import get_object_or_404
from django.utils.decorators import available_attrs
from comrade.views.simple import direct_to_template
from functools import wraps
def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
def authorized(test_func, template_name='401.html'):
"""
Decorator for views that checks that the user passes the given test,
redirecting to the unauthorized page if it fails. The test should be a
callable that takes the user object and returns True if the user passes.
"""
def decorator(view_func):
def _wrapped_view(request, *args, **kwargs):
if test_func(request.user, *args, **kwargs):
return view_func(request, *args, **kwargs)
return direct_to_template(template_name, status=401)
return wraps(view_func,
assigned=available_attrs(view_func))(_wrapped_view)
return decorator
def load_instance(model):
def decorator(view):
def _wrapper(request, object_id=None, *args, **kwargs):
if object_id:
instance = get_object_or_404(model, pk=object_id)
return view(request, instance, *args, **kwargs)
return view(request, *args, **kwargs)
return wraps(view)(_wrapper)
return decorator
|
Use our own code, when possible.
|
Use our own code, when possible.
|
Python
|
mit
|
bueda/django-comrade
|
from django.shortcuts import get_object_or_404
from django.utils.decorators import available_attrs
from django.utils.http import urlquote
from django.http import HttpResponse
from django.template import loader, RequestContext
from functools import wraps
def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
def authorized(test_func, template_name='401.html'):
"""
Decorator for views that checks that the user passes the given test,
redirecting to the unauthorized page if it fails. The test should be a
callable that takes the user object and returns True if the user passes.
"""
def decorator(view_func):
def _wrapped_view(request, *args, **kwargs):
if test_func(request.user, *args, **kwargs):
return view_func(request, *args, **kwargs)
path = urlquote(request.get_full_path())
t = loader.get_template(template_name)
return HttpResponse(t.render(RequestContext(request)), status=401)
return wraps(view_func,
assigned=available_attrs(view_func))(_wrapped_view)
return decorator
def load_instance(model):
def decorator(view):
def _wrapper(request, object_id=None, *args, **kwargs):
if object_id:
instance = get_object_or_404(model, pk=object_id)
return view(request, instance, *args, **kwargs)
return view(request, *args, **kwargs)
return wraps(view)(_wrapper)
return decorator
Use our own code, when possible.
|
from django.shortcuts import get_object_or_404
from django.utils.decorators import available_attrs
from comrade.views.simple import direct_to_template
from functools import wraps
def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
def authorized(test_func, template_name='401.html'):
"""
Decorator for views that checks that the user passes the given test,
redirecting to the unauthorized page if it fails. The test should be a
callable that takes the user object and returns True if the user passes.
"""
def decorator(view_func):
def _wrapped_view(request, *args, **kwargs):
if test_func(request.user, *args, **kwargs):
return view_func(request, *args, **kwargs)
return direct_to_template(template_name, status=401)
return wraps(view_func,
assigned=available_attrs(view_func))(_wrapped_view)
return decorator
def load_instance(model):
def decorator(view):
def _wrapper(request, object_id=None, *args, **kwargs):
if object_id:
instance = get_object_or_404(model, pk=object_id)
return view(request, instance, *args, **kwargs)
return view(request, *args, **kwargs)
return wraps(view)(_wrapper)
return decorator
|
<commit_before>from django.shortcuts import get_object_or_404
from django.utils.decorators import available_attrs
from django.utils.http import urlquote
from django.http import HttpResponse
from django.template import loader, RequestContext
from functools import wraps
def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
def authorized(test_func, template_name='401.html'):
"""
Decorator for views that checks that the user passes the given test,
redirecting to the unauthorized page if it fails. The test should be a
callable that takes the user object and returns True if the user passes.
"""
def decorator(view_func):
def _wrapped_view(request, *args, **kwargs):
if test_func(request.user, *args, **kwargs):
return view_func(request, *args, **kwargs)
path = urlquote(request.get_full_path())
t = loader.get_template(template_name)
return HttpResponse(t.render(RequestContext(request)), status=401)
return wraps(view_func,
assigned=available_attrs(view_func))(_wrapped_view)
return decorator
def load_instance(model):
def decorator(view):
def _wrapper(request, object_id=None, *args, **kwargs):
if object_id:
instance = get_object_or_404(model, pk=object_id)
return view(request, instance, *args, **kwargs)
return view(request, *args, **kwargs)
return wraps(view)(_wrapper)
return decorator
<commit_msg>Use our own code, when possible.<commit_after>
|
from django.shortcuts import get_object_or_404
from django.utils.decorators import available_attrs
from comrade.views.simple import direct_to_template
from functools import wraps
def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
def authorized(test_func, template_name='401.html'):
"""
Decorator for views that checks that the user passes the given test,
redirecting to the unauthorized page if it fails. The test should be a
callable that takes the user object and returns True if the user passes.
"""
def decorator(view_func):
def _wrapped_view(request, *args, **kwargs):
if test_func(request.user, *args, **kwargs):
return view_func(request, *args, **kwargs)
return direct_to_template(template_name, status=401)
return wraps(view_func,
assigned=available_attrs(view_func))(_wrapped_view)
return decorator
def load_instance(model):
def decorator(view):
def _wrapper(request, object_id=None, *args, **kwargs):
if object_id:
instance = get_object_or_404(model, pk=object_id)
return view(request, instance, *args, **kwargs)
return view(request, *args, **kwargs)
return wraps(view)(_wrapper)
return decorator
|
from django.shortcuts import get_object_or_404
from django.utils.decorators import available_attrs
from django.utils.http import urlquote
from django.http import HttpResponse
from django.template import loader, RequestContext
from functools import wraps
def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
def authorized(test_func, template_name='401.html'):
"""
Decorator for views that checks that the user passes the given test,
redirecting to the unauthorized page if it fails. The test should be a
callable that takes the user object and returns True if the user passes.
"""
def decorator(view_func):
def _wrapped_view(request, *args, **kwargs):
if test_func(request.user, *args, **kwargs):
return view_func(request, *args, **kwargs)
path = urlquote(request.get_full_path())
t = loader.get_template(template_name)
return HttpResponse(t.render(RequestContext(request)), status=401)
return wraps(view_func,
assigned=available_attrs(view_func))(_wrapped_view)
return decorator
def load_instance(model):
def decorator(view):
def _wrapper(request, object_id=None, *args, **kwargs):
if object_id:
instance = get_object_or_404(model, pk=object_id)
return view(request, instance, *args, **kwargs)
return view(request, *args, **kwargs)
return wraps(view)(_wrapper)
return decorator
Use our own code, when possible.from django.shortcuts import get_object_or_404
from django.utils.decorators import available_attrs
from comrade.views.simple import direct_to_template
from functools import wraps
def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
def authorized(test_func, template_name='401.html'):
"""
Decorator for views that checks that the user passes the given test,
redirecting to the unauthorized page if it fails. The test should be a
callable that takes the user object and returns True if the user passes.
"""
def decorator(view_func):
def _wrapped_view(request, *args, **kwargs):
if test_func(request.user, *args, **kwargs):
return view_func(request, *args, **kwargs)
return direct_to_template(template_name, status=401)
return wraps(view_func,
assigned=available_attrs(view_func))(_wrapped_view)
return decorator
def load_instance(model):
def decorator(view):
def _wrapper(request, object_id=None, *args, **kwargs):
if object_id:
instance = get_object_or_404(model, pk=object_id)
return view(request, instance, *args, **kwargs)
return view(request, *args, **kwargs)
return wraps(view)(_wrapper)
return decorator
|
<commit_before>from django.shortcuts import get_object_or_404
from django.utils.decorators import available_attrs
from django.utils.http import urlquote
from django.http import HttpResponse
from django.template import loader, RequestContext
from functools import wraps
def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
def authorized(test_func, template_name='401.html'):
"""
Decorator for views that checks that the user passes the given test,
redirecting to the unauthorized page if it fails. The test should be a
callable that takes the user object and returns True if the user passes.
"""
def decorator(view_func):
def _wrapped_view(request, *args, **kwargs):
if test_func(request.user, *args, **kwargs):
return view_func(request, *args, **kwargs)
path = urlquote(request.get_full_path())
t = loader.get_template(template_name)
return HttpResponse(t.render(RequestContext(request)), status=401)
return wraps(view_func,
assigned=available_attrs(view_func))(_wrapped_view)
return decorator
def load_instance(model):
def decorator(view):
def _wrapper(request, object_id=None, *args, **kwargs):
if object_id:
instance = get_object_or_404(model, pk=object_id)
return view(request, instance, *args, **kwargs)
return view(request, *args, **kwargs)
return wraps(view)(_wrapper)
return decorator
<commit_msg>Use our own code, when possible.<commit_after>from django.shortcuts import get_object_or_404
from django.utils.decorators import available_attrs
from comrade.views.simple import direct_to_template
from functools import wraps
def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
def authorized(test_func, template_name='401.html'):
"""
Decorator for views that checks that the user passes the given test,
redirecting to the unauthorized page if it fails. The test should be a
callable that takes the user object and returns True if the user passes.
"""
def decorator(view_func):
def _wrapped_view(request, *args, **kwargs):
if test_func(request.user, *args, **kwargs):
return view_func(request, *args, **kwargs)
return direct_to_template(template_name, status=401)
return wraps(view_func,
assigned=available_attrs(view_func))(_wrapped_view)
return decorator
def load_instance(model):
def decorator(view):
def _wrapper(request, object_id=None, *args, **kwargs):
if object_id:
instance = get_object_or_404(model, pk=object_id)
return view(request, instance, *args, **kwargs)
return view(request, *args, **kwargs)
return wraps(view)(_wrapper)
return decorator
|
03421e8eb4206299e869faa45e59d4c815965e6a
|
meshio/_files.py
|
meshio/_files.py
|
import os
import sys
from contextlib import contextmanager
def is_buffer(obj, mode):
return ("r" in mode and hasattr(obj, "read")) or (
"w" in mode and hasattr(obj, "write")
)
@contextmanager
def open_file(path_or_buf, mode="r"):
if is_buffer(path_or_buf, mode):
yield path_or_buf
elif sys.version_info < (3, 6) and isinstance(path_or_buf, os.PathLike):
# todo: remove when 3.5 is EoL
with open(str(path_or_buf), mode) as f:
yield f
else:
with open(path_or_buf, mode) as f:
yield f
|
import os
import sys
from contextlib import contextmanager
def is_buffer(obj, mode):
return ("r" in mode and hasattr(obj, "read")) or (
"w" in mode and hasattr(obj, "write")
)
@contextmanager
def open_file(path_or_buf, mode="r"):
if is_buffer(path_or_buf, mode):
yield path_or_buf
elif sys.version_info < (3, 6) and isinstance(path_or_buf, os.PathLike):
# TODO remove when python 3.5 is EoL (i.e. 2020-09-13)
# https://devguide.python.org/#status-of-python-branches
# https://www.python.org/dev/peps/pep-0478/
with open(str(path_or_buf), mode) as f:
yield f
else:
with open(path_or_buf, mode) as f:
yield f
|
Add more details to py35 EoL changes
|
Add more details to py35 EoL changes
|
Python
|
mit
|
nschloe/meshio
|
import os
import sys
from contextlib import contextmanager
def is_buffer(obj, mode):
return ("r" in mode and hasattr(obj, "read")) or (
"w" in mode and hasattr(obj, "write")
)
@contextmanager
def open_file(path_or_buf, mode="r"):
if is_buffer(path_or_buf, mode):
yield path_or_buf
elif sys.version_info < (3, 6) and isinstance(path_or_buf, os.PathLike):
# todo: remove when 3.5 is EoL
with open(str(path_or_buf), mode) as f:
yield f
else:
with open(path_or_buf, mode) as f:
yield f
Add more details to py35 EoL changes
|
import os
import sys
from contextlib import contextmanager
def is_buffer(obj, mode):
return ("r" in mode and hasattr(obj, "read")) or (
"w" in mode and hasattr(obj, "write")
)
@contextmanager
def open_file(path_or_buf, mode="r"):
if is_buffer(path_or_buf, mode):
yield path_or_buf
elif sys.version_info < (3, 6) and isinstance(path_or_buf, os.PathLike):
# TODO remove when python 3.5 is EoL (i.e. 2020-09-13)
# https://devguide.python.org/#status-of-python-branches
# https://www.python.org/dev/peps/pep-0478/
with open(str(path_or_buf), mode) as f:
yield f
else:
with open(path_or_buf, mode) as f:
yield f
|
<commit_before>import os
import sys
from contextlib import contextmanager
def is_buffer(obj, mode):
return ("r" in mode and hasattr(obj, "read")) or (
"w" in mode and hasattr(obj, "write")
)
@contextmanager
def open_file(path_or_buf, mode="r"):
if is_buffer(path_or_buf, mode):
yield path_or_buf
elif sys.version_info < (3, 6) and isinstance(path_or_buf, os.PathLike):
# todo: remove when 3.5 is EoL
with open(str(path_or_buf), mode) as f:
yield f
else:
with open(path_or_buf, mode) as f:
yield f
<commit_msg>Add more details to py35 EoL changes<commit_after>
|
import os
import sys
from contextlib import contextmanager
def is_buffer(obj, mode):
return ("r" in mode and hasattr(obj, "read")) or (
"w" in mode and hasattr(obj, "write")
)
@contextmanager
def open_file(path_or_buf, mode="r"):
if is_buffer(path_or_buf, mode):
yield path_or_buf
elif sys.version_info < (3, 6) and isinstance(path_or_buf, os.PathLike):
# TODO remove when python 3.5 is EoL (i.e. 2020-09-13)
# https://devguide.python.org/#status-of-python-branches
# https://www.python.org/dev/peps/pep-0478/
with open(str(path_or_buf), mode) as f:
yield f
else:
with open(path_or_buf, mode) as f:
yield f
|
import os
import sys
from contextlib import contextmanager
def is_buffer(obj, mode):
return ("r" in mode and hasattr(obj, "read")) or (
"w" in mode and hasattr(obj, "write")
)
@contextmanager
def open_file(path_or_buf, mode="r"):
if is_buffer(path_or_buf, mode):
yield path_or_buf
elif sys.version_info < (3, 6) and isinstance(path_or_buf, os.PathLike):
# todo: remove when 3.5 is EoL
with open(str(path_or_buf), mode) as f:
yield f
else:
with open(path_or_buf, mode) as f:
yield f
Add more details to py35 EoL changesimport os
import sys
from contextlib import contextmanager
def is_buffer(obj, mode):
return ("r" in mode and hasattr(obj, "read")) or (
"w" in mode and hasattr(obj, "write")
)
@contextmanager
def open_file(path_or_buf, mode="r"):
if is_buffer(path_or_buf, mode):
yield path_or_buf
elif sys.version_info < (3, 6) and isinstance(path_or_buf, os.PathLike):
# TODO remove when python 3.5 is EoL (i.e. 2020-09-13)
# https://devguide.python.org/#status-of-python-branches
# https://www.python.org/dev/peps/pep-0478/
with open(str(path_or_buf), mode) as f:
yield f
else:
with open(path_or_buf, mode) as f:
yield f
|
<commit_before>import os
import sys
from contextlib import contextmanager
def is_buffer(obj, mode):
return ("r" in mode and hasattr(obj, "read")) or (
"w" in mode and hasattr(obj, "write")
)
@contextmanager
def open_file(path_or_buf, mode="r"):
if is_buffer(path_or_buf, mode):
yield path_or_buf
elif sys.version_info < (3, 6) and isinstance(path_or_buf, os.PathLike):
# todo: remove when 3.5 is EoL
with open(str(path_or_buf), mode) as f:
yield f
else:
with open(path_or_buf, mode) as f:
yield f
<commit_msg>Add more details to py35 EoL changes<commit_after>import os
import sys
from contextlib import contextmanager
def is_buffer(obj, mode):
return ("r" in mode and hasattr(obj, "read")) or (
"w" in mode and hasattr(obj, "write")
)
@contextmanager
def open_file(path_or_buf, mode="r"):
if is_buffer(path_or_buf, mode):
yield path_or_buf
elif sys.version_info < (3, 6) and isinstance(path_or_buf, os.PathLike):
# TODO remove when python 3.5 is EoL (i.e. 2020-09-13)
# https://devguide.python.org/#status-of-python-branches
# https://www.python.org/dev/peps/pep-0478/
with open(str(path_or_buf), mode) as f:
yield f
else:
with open(path_or_buf, mode) as f:
yield f
|
6eee384ef75d119f5fbb3c6ff91fd2c49f9a5630
|
lib/authenticator.py
|
lib/authenticator.py
|
#
# HamperAuthenticator is the class to handle the authentication part of the provisioning portal.
# Instantiate with the email and password you want, it'll pass back the cookie jar if successful,
# or an error message on failure
#
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class HamperAuthenticator(object):
def __init__(self, driver, email, password):
super(HamperAuthenticator, self).__init__()
self.email = email
self.password = password
self.driver = webdriver.Firefox()
self.cookie_jar = self.driver.get_cookies()
def sign_in(self):
# Open the profile URL. This will forward to the sign in page if session is invalid
self.driver.get("https://developer.apple.com/account/ios/profile/")
email_element = self.driver.find_element_by_name("appleId")
email_element.send_keys(self.email)
password_element = self.driver.find_element_by_name("accountPassword")
password_element.send_keys(self.password)
self.driver.find_element_by_id("submitButton2").click()
self.cookie_jar = self.driver.get_cookies()
return self.cookie_jar
|
#
# HamperAuthenticator is the class to handle the authentication part of the provisioning portal.
# Instantiate with the email and password you want, it'll pass back the cookie jar if successful,
# or an error message on failure
#
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class HamperAuthenticator(object):
def __init__(self, email, password):
super(HamperAuthenticator, self).__init__()
self.email = email
self.password = password
def sign_in(self, driver):
# Open the profile URL. This will forward to the sign in page if session is invalid
driver.get("https://developer.apple.com/account/ios/profile/")
email_element = driver.find_element_by_name("appleId")
email_element.send_keys(self.email)
password_element = driver.find_element_by_name("accountPassword")
password_element.send_keys(self.password)
driver.find_element_by_id("submitButton2").click()
return driver
|
Use parameter to pass Webdriver object to share execution
|
Use parameter to pass Webdriver object to share execution
|
Python
|
mit
|
MobileXLabs/hamper
|
#
# HamperAuthenticator is the class to handle the authentication part of the provisioning portal.
# Instantiate with the email and password you want, it'll pass back the cookie jar if successful,
# or an error message on failure
#
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class HamperAuthenticator(object):
def __init__(self, driver, email, password):
super(HamperAuthenticator, self).__init__()
self.email = email
self.password = password
self.driver = webdriver.Firefox()
self.cookie_jar = self.driver.get_cookies()
def sign_in(self):
# Open the profile URL. This will forward to the sign in page if session is invalid
self.driver.get("https://developer.apple.com/account/ios/profile/")
email_element = self.driver.find_element_by_name("appleId")
email_element.send_keys(self.email)
password_element = self.driver.find_element_by_name("accountPassword")
password_element.send_keys(self.password)
self.driver.find_element_by_id("submitButton2").click()
self.cookie_jar = self.driver.get_cookies()
return self.cookie_jar
Use parameter to pass Webdriver object to share execution
|
#
# HamperAuthenticator is the class to handle the authentication part of the provisioning portal.
# Instantiate with the email and password you want, it'll pass back the cookie jar if successful,
# or an error message on failure
#
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class HamperAuthenticator(object):
def __init__(self, email, password):
super(HamperAuthenticator, self).__init__()
self.email = email
self.password = password
def sign_in(self, driver):
# Open the profile URL. This will forward to the sign in page if session is invalid
driver.get("https://developer.apple.com/account/ios/profile/")
email_element = driver.find_element_by_name("appleId")
email_element.send_keys(self.email)
password_element = driver.find_element_by_name("accountPassword")
password_element.send_keys(self.password)
driver.find_element_by_id("submitButton2").click()
return driver
|
<commit_before>#
# HamperAuthenticator is the class to handle the authentication part of the provisioning portal.
# Instantiate with the email and password you want, it'll pass back the cookie jar if successful,
# or an error message on failure
#
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class HamperAuthenticator(object):
def __init__(self, driver, email, password):
super(HamperAuthenticator, self).__init__()
self.email = email
self.password = password
self.driver = webdriver.Firefox()
self.cookie_jar = self.driver.get_cookies()
def sign_in(self):
# Open the profile URL. This will forward to the sign in page if session is invalid
self.driver.get("https://developer.apple.com/account/ios/profile/")
email_element = self.driver.find_element_by_name("appleId")
email_element.send_keys(self.email)
password_element = self.driver.find_element_by_name("accountPassword")
password_element.send_keys(self.password)
self.driver.find_element_by_id("submitButton2").click()
self.cookie_jar = self.driver.get_cookies()
return self.cookie_jar
<commit_msg>Use parameter to pass Webdriver object to share execution<commit_after>
|
#
# HamperAuthenticator is the class to handle the authentication part of the provisioning portal.
# Instantiate with the email and password you want, it'll pass back the cookie jar if successful,
# or an error message on failure
#
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class HamperAuthenticator(object):
def __init__(self, email, password):
super(HamperAuthenticator, self).__init__()
self.email = email
self.password = password
def sign_in(self, driver):
# Open the profile URL. This will forward to the sign in page if session is invalid
driver.get("https://developer.apple.com/account/ios/profile/")
email_element = driver.find_element_by_name("appleId")
email_element.send_keys(self.email)
password_element = driver.find_element_by_name("accountPassword")
password_element.send_keys(self.password)
driver.find_element_by_id("submitButton2").click()
return driver
|
#
# HamperAuthenticator is the class to handle the authentication part of the provisioning portal.
# Instantiate with the email and password you want, it'll pass back the cookie jar if successful,
# or an error message on failure
#
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class HamperAuthenticator(object):
def __init__(self, driver, email, password):
super(HamperAuthenticator, self).__init__()
self.email = email
self.password = password
self.driver = webdriver.Firefox()
self.cookie_jar = self.driver.get_cookies()
def sign_in(self):
# Open the profile URL. This will forward to the sign in page if session is invalid
self.driver.get("https://developer.apple.com/account/ios/profile/")
email_element = self.driver.find_element_by_name("appleId")
email_element.send_keys(self.email)
password_element = self.driver.find_element_by_name("accountPassword")
password_element.send_keys(self.password)
self.driver.find_element_by_id("submitButton2").click()
self.cookie_jar = self.driver.get_cookies()
return self.cookie_jar
Use parameter to pass Webdriver object to share execution#
# HamperAuthenticator is the class to handle the authentication part of the provisioning portal.
# Instantiate with the email and password you want, it'll pass back the cookie jar if successful,
# or an error message on failure
#
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class HamperAuthenticator(object):
def __init__(self, email, password):
super(HamperAuthenticator, self).__init__()
self.email = email
self.password = password
def sign_in(self, driver):
# Open the profile URL. This will forward to the sign in page if session is invalid
driver.get("https://developer.apple.com/account/ios/profile/")
email_element = driver.find_element_by_name("appleId")
email_element.send_keys(self.email)
password_element = driver.find_element_by_name("accountPassword")
password_element.send_keys(self.password)
driver.find_element_by_id("submitButton2").click()
return driver
|
<commit_before>#
# HamperAuthenticator is the class to handle the authentication part of the provisioning portal.
# Instantiate with the email and password you want, it'll pass back the cookie jar if successful,
# or an error message on failure
#
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class HamperAuthenticator(object):
def __init__(self, driver, email, password):
super(HamperAuthenticator, self).__init__()
self.email = email
self.password = password
self.driver = webdriver.Firefox()
self.cookie_jar = self.driver.get_cookies()
def sign_in(self):
# Open the profile URL. This will forward to the sign in page if session is invalid
self.driver.get("https://developer.apple.com/account/ios/profile/")
email_element = self.driver.find_element_by_name("appleId")
email_element.send_keys(self.email)
password_element = self.driver.find_element_by_name("accountPassword")
password_element.send_keys(self.password)
self.driver.find_element_by_id("submitButton2").click()
self.cookie_jar = self.driver.get_cookies()
return self.cookie_jar
<commit_msg>Use parameter to pass Webdriver object to share execution<commit_after>#
# HamperAuthenticator is the class to handle the authentication part of the provisioning portal.
# Instantiate with the email and password you want, it'll pass back the cookie jar if successful,
# or an error message on failure
#
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class HamperAuthenticator(object):
def __init__(self, email, password):
super(HamperAuthenticator, self).__init__()
self.email = email
self.password = password
def sign_in(self, driver):
# Open the profile URL. This will forward to the sign in page if session is invalid
driver.get("https://developer.apple.com/account/ios/profile/")
email_element = driver.find_element_by_name("appleId")
email_element.send_keys(self.email)
password_element = driver.find_element_by_name("accountPassword")
password_element.send_keys(self.password)
driver.find_element_by_id("submitButton2").click()
return driver
|
14230758fbdc0ab293f0179267768baf067dc33b
|
npc/__version__.py
|
npc/__version__.py
|
"""Current version string for NPC"""
__version__ = "1.3.1 beta 2"
|
"""Current version string for NPC"""
__version__ = "1.3.1 beta 3"
|
Bump version to beta 3
|
Bump version to beta 3
|
Python
|
mit
|
aurule/npc,aurule/npc
|
"""Current version string for NPC"""
__version__ = "1.3.1 beta 2"
Bump version to beta 3
|
"""Current version string for NPC"""
__version__ = "1.3.1 beta 3"
|
<commit_before>"""Current version string for NPC"""
__version__ = "1.3.1 beta 2"
<commit_msg>Bump version to beta 3<commit_after>
|
"""Current version string for NPC"""
__version__ = "1.3.1 beta 3"
|
"""Current version string for NPC"""
__version__ = "1.3.1 beta 2"
Bump version to beta 3"""Current version string for NPC"""
__version__ = "1.3.1 beta 3"
|
<commit_before>"""Current version string for NPC"""
__version__ = "1.3.1 beta 2"
<commit_msg>Bump version to beta 3<commit_after>"""Current version string for NPC"""
__version__ = "1.3.1 beta 3"
|
48b38ea71a79eaed81a4f83a46bf8bf3db8cfa18
|
txircd/modules/extra/listmodules.py
|
txircd/modules/extra/listmodules.py
|
from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from zope.interface import implements
class ModulesCommand(ModuleData):
implements(IPlugin, IModuleData)
name = "ModulesCommand"
def actions(self):
return [ ("statsruntype-modules", 1, self.listModules) ]
def listModules(self):
modules = {}
for modName in sorted(self.ircd.loadedModules.keys()):
modules[modName] = "*"
return modules
modulesCommand = ModulesCommand()
|
from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from zope.interface import implements
class ModulesList(ModuleData):
implements(IPlugin, IModuleData)
name = "ModulesList"
def actions(self):
return [ ("statsruntype-modules", 1, self.listModules) ]
def listModules(self):
modules = {}
for modName in sorted(self.ircd.loadedModules.keys()):
modules[modName] = "*"
return modules
modulesList = ModulesList()
|
Rename ModulesCommand to be more appropriate
|
Rename ModulesCommand to be more appropriate
|
Python
|
bsd-3-clause
|
Heufneutje/txircd
|
from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from zope.interface import implements
class ModulesCommand(ModuleData):
implements(IPlugin, IModuleData)
name = "ModulesCommand"
def actions(self):
return [ ("statsruntype-modules", 1, self.listModules) ]
def listModules(self):
modules = {}
for modName in sorted(self.ircd.loadedModules.keys()):
modules[modName] = "*"
return modules
modulesCommand = ModulesCommand()Rename ModulesCommand to be more appropriate
|
from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from zope.interface import implements
class ModulesList(ModuleData):
implements(IPlugin, IModuleData)
name = "ModulesList"
def actions(self):
return [ ("statsruntype-modules", 1, self.listModules) ]
def listModules(self):
modules = {}
for modName in sorted(self.ircd.loadedModules.keys()):
modules[modName] = "*"
return modules
modulesList = ModulesList()
|
<commit_before>from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from zope.interface import implements
class ModulesCommand(ModuleData):
implements(IPlugin, IModuleData)
name = "ModulesCommand"
def actions(self):
return [ ("statsruntype-modules", 1, self.listModules) ]
def listModules(self):
modules = {}
for modName in sorted(self.ircd.loadedModules.keys()):
modules[modName] = "*"
return modules
modulesCommand = ModulesCommand()<commit_msg>Rename ModulesCommand to be more appropriate<commit_after>
|
from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from zope.interface import implements
class ModulesList(ModuleData):
implements(IPlugin, IModuleData)
name = "ModulesList"
def actions(self):
return [ ("statsruntype-modules", 1, self.listModules) ]
def listModules(self):
modules = {}
for modName in sorted(self.ircd.loadedModules.keys()):
modules[modName] = "*"
return modules
modulesList = ModulesList()
|
from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from zope.interface import implements
class ModulesCommand(ModuleData):
implements(IPlugin, IModuleData)
name = "ModulesCommand"
def actions(self):
return [ ("statsruntype-modules", 1, self.listModules) ]
def listModules(self):
modules = {}
for modName in sorted(self.ircd.loadedModules.keys()):
modules[modName] = "*"
return modules
modulesCommand = ModulesCommand()Rename ModulesCommand to be more appropriatefrom twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from zope.interface import implements
class ModulesList(ModuleData):
implements(IPlugin, IModuleData)
name = "ModulesList"
def actions(self):
return [ ("statsruntype-modules", 1, self.listModules) ]
def listModules(self):
modules = {}
for modName in sorted(self.ircd.loadedModules.keys()):
modules[modName] = "*"
return modules
modulesList = ModulesList()
|
<commit_before>from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from zope.interface import implements
class ModulesCommand(ModuleData):
implements(IPlugin, IModuleData)
name = "ModulesCommand"
def actions(self):
return [ ("statsruntype-modules", 1, self.listModules) ]
def listModules(self):
modules = {}
for modName in sorted(self.ircd.loadedModules.keys()):
modules[modName] = "*"
return modules
modulesCommand = ModulesCommand()<commit_msg>Rename ModulesCommand to be more appropriate<commit_after>from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from zope.interface import implements
class ModulesList(ModuleData):
implements(IPlugin, IModuleData)
name = "ModulesList"
def actions(self):
return [ ("statsruntype-modules", 1, self.listModules) ]
def listModules(self):
modules = {}
for modName in sorted(self.ircd.loadedModules.keys()):
modules[modName] = "*"
return modules
modulesList = ModulesList()
|
d7fa7d2bacd45a50f14e4e1aeae57cfc56a315db
|
__init__.py
|
__init__.py
|
from openedoo_project import db
from openedoo.core.libs import Blueprint
from .controllers.employee import EmployeeLogin, EmployeeLogout, AddEmployee, \
AssignEmployeeAsTeacher, EmployeeDashboard, EditEmployee, DeleteEmployee, \
SearchEmployee, AddSubject
module_employee = Blueprint('module_employee', __name__,
template_folder='templates',
static_folder='static')
module_employee.add_url_rule('/admin/dashboard',
view_func=EmployeeDashboard.as_view('dashboard'))
module_employee.add_url_rule('/admin/login',
view_func=EmployeeLogin.as_view('login'))
module_employee.add_url_rule('/admin/logout',
view_func=EmployeeLogout.as_view('logout'))
module_employee.add_url_rule('/admin/add',
view_func=AddEmployee.as_view('add'))
module_employee.add_url_rule('/admin/edit',
view_func=EditEmployee.as_view('edit'))
assignEmployeeAsTeacherView = AssignEmployeeAsTeacher.as_view('assign')
module_employee.add_url_rule('/admin/assign',
view_func=assignEmployeeAsTeacherView)
module_employee.add_url_rule('/admin/delete',
view_func=DeleteEmployee.as_view('delete'))
module_employee.add_url_rule('/search',
view_func=SearchEmployee.as_view('search'))
module_employee.add_url_rule('/admin/subject/add',
view_func=AddSubject.as_view('add_subject'))
|
from openedoo_project import db
from openedoo.core.libs import Blueprint
from .controllers.employee import EmployeeLogin, EmployeeLogout, AddEmployee, \
AssignEmployeeAsTeacher, EmployeeDashboard, EditEmployee, DeleteEmployee, \
SearchEmployee, AddSubject
module_employee = Blueprint('module_employee', __name__,
template_folder='templates',
static_folder='static')
module_employee.add_url_rule('/admin',
view_func=EmployeeDashboard.as_view('dashboard'))
module_employee.add_url_rule('/admin/login',
view_func=EmployeeLogin.as_view('login'))
module_employee.add_url_rule('/admin/logout',
view_func=EmployeeLogout.as_view('logout'))
module_employee.add_url_rule('/admin/add',
view_func=AddEmployee.as_view('add'))
module_employee.add_url_rule('/admin/edit',
view_func=EditEmployee.as_view('edit'))
assignEmployeeAsTeacherView = AssignEmployeeAsTeacher.as_view('assign')
module_employee.add_url_rule('/admin/assign',
view_func=assignEmployeeAsTeacherView)
module_employee.add_url_rule('/admin/delete',
view_func=DeleteEmployee.as_view('delete'))
module_employee.add_url_rule('/search',
view_func=SearchEmployee.as_view('search'))
module_employee.add_url_rule('/admin/subject/add',
view_func=AddSubject.as_view('add_subject'))
|
Make dashboard route become admin's default
|
Make dashboard route become admin's default
|
Python
|
mit
|
openedoo/module_employee,openedoo/module_employee,openedoo/module_employee
|
from openedoo_project import db
from openedoo.core.libs import Blueprint
from .controllers.employee import EmployeeLogin, EmployeeLogout, AddEmployee, \
AssignEmployeeAsTeacher, EmployeeDashboard, EditEmployee, DeleteEmployee, \
SearchEmployee, AddSubject
module_employee = Blueprint('module_employee', __name__,
template_folder='templates',
static_folder='static')
module_employee.add_url_rule('/admin/dashboard',
view_func=EmployeeDashboard.as_view('dashboard'))
module_employee.add_url_rule('/admin/login',
view_func=EmployeeLogin.as_view('login'))
module_employee.add_url_rule('/admin/logout',
view_func=EmployeeLogout.as_view('logout'))
module_employee.add_url_rule('/admin/add',
view_func=AddEmployee.as_view('add'))
module_employee.add_url_rule('/admin/edit',
view_func=EditEmployee.as_view('edit'))
assignEmployeeAsTeacherView = AssignEmployeeAsTeacher.as_view('assign')
module_employee.add_url_rule('/admin/assign',
view_func=assignEmployeeAsTeacherView)
module_employee.add_url_rule('/admin/delete',
view_func=DeleteEmployee.as_view('delete'))
module_employee.add_url_rule('/search',
view_func=SearchEmployee.as_view('search'))
module_employee.add_url_rule('/admin/subject/add',
view_func=AddSubject.as_view('add_subject'))
Make dashboard route become admin's default
|
from openedoo_project import db
from openedoo.core.libs import Blueprint
from .controllers.employee import EmployeeLogin, EmployeeLogout, AddEmployee, \
AssignEmployeeAsTeacher, EmployeeDashboard, EditEmployee, DeleteEmployee, \
SearchEmployee, AddSubject
module_employee = Blueprint('module_employee', __name__,
template_folder='templates',
static_folder='static')
module_employee.add_url_rule('/admin',
view_func=EmployeeDashboard.as_view('dashboard'))
module_employee.add_url_rule('/admin/login',
view_func=EmployeeLogin.as_view('login'))
module_employee.add_url_rule('/admin/logout',
view_func=EmployeeLogout.as_view('logout'))
module_employee.add_url_rule('/admin/add',
view_func=AddEmployee.as_view('add'))
module_employee.add_url_rule('/admin/edit',
view_func=EditEmployee.as_view('edit'))
assignEmployeeAsTeacherView = AssignEmployeeAsTeacher.as_view('assign')
module_employee.add_url_rule('/admin/assign',
view_func=assignEmployeeAsTeacherView)
module_employee.add_url_rule('/admin/delete',
view_func=DeleteEmployee.as_view('delete'))
module_employee.add_url_rule('/search',
view_func=SearchEmployee.as_view('search'))
module_employee.add_url_rule('/admin/subject/add',
view_func=AddSubject.as_view('add_subject'))
|
<commit_before>from openedoo_project import db
from openedoo.core.libs import Blueprint
from .controllers.employee import EmployeeLogin, EmployeeLogout, AddEmployee, \
AssignEmployeeAsTeacher, EmployeeDashboard, EditEmployee, DeleteEmployee, \
SearchEmployee, AddSubject
module_employee = Blueprint('module_employee', __name__,
template_folder='templates',
static_folder='static')
module_employee.add_url_rule('/admin/dashboard',
view_func=EmployeeDashboard.as_view('dashboard'))
module_employee.add_url_rule('/admin/login',
view_func=EmployeeLogin.as_view('login'))
module_employee.add_url_rule('/admin/logout',
view_func=EmployeeLogout.as_view('logout'))
module_employee.add_url_rule('/admin/add',
view_func=AddEmployee.as_view('add'))
module_employee.add_url_rule('/admin/edit',
view_func=EditEmployee.as_view('edit'))
assignEmployeeAsTeacherView = AssignEmployeeAsTeacher.as_view('assign')
module_employee.add_url_rule('/admin/assign',
view_func=assignEmployeeAsTeacherView)
module_employee.add_url_rule('/admin/delete',
view_func=DeleteEmployee.as_view('delete'))
module_employee.add_url_rule('/search',
view_func=SearchEmployee.as_view('search'))
module_employee.add_url_rule('/admin/subject/add',
view_func=AddSubject.as_view('add_subject'))
<commit_msg>Make dashboard route become admin's default<commit_after>
|
from openedoo_project import db
from openedoo.core.libs import Blueprint
from .controllers.employee import EmployeeLogin, EmployeeLogout, AddEmployee, \
AssignEmployeeAsTeacher, EmployeeDashboard, EditEmployee, DeleteEmployee, \
SearchEmployee, AddSubject
module_employee = Blueprint('module_employee', __name__,
template_folder='templates',
static_folder='static')
module_employee.add_url_rule('/admin',
view_func=EmployeeDashboard.as_view('dashboard'))
module_employee.add_url_rule('/admin/login',
view_func=EmployeeLogin.as_view('login'))
module_employee.add_url_rule('/admin/logout',
view_func=EmployeeLogout.as_view('logout'))
module_employee.add_url_rule('/admin/add',
view_func=AddEmployee.as_view('add'))
module_employee.add_url_rule('/admin/edit',
view_func=EditEmployee.as_view('edit'))
assignEmployeeAsTeacherView = AssignEmployeeAsTeacher.as_view('assign')
module_employee.add_url_rule('/admin/assign',
view_func=assignEmployeeAsTeacherView)
module_employee.add_url_rule('/admin/delete',
view_func=DeleteEmployee.as_view('delete'))
module_employee.add_url_rule('/search',
view_func=SearchEmployee.as_view('search'))
module_employee.add_url_rule('/admin/subject/add',
view_func=AddSubject.as_view('add_subject'))
|
from openedoo_project import db
from openedoo.core.libs import Blueprint
from .controllers.employee import EmployeeLogin, EmployeeLogout, AddEmployee, \
AssignEmployeeAsTeacher, EmployeeDashboard, EditEmployee, DeleteEmployee, \
SearchEmployee, AddSubject
module_employee = Blueprint('module_employee', __name__,
template_folder='templates',
static_folder='static')
module_employee.add_url_rule('/admin/dashboard',
view_func=EmployeeDashboard.as_view('dashboard'))
module_employee.add_url_rule('/admin/login',
view_func=EmployeeLogin.as_view('login'))
module_employee.add_url_rule('/admin/logout',
view_func=EmployeeLogout.as_view('logout'))
module_employee.add_url_rule('/admin/add',
view_func=AddEmployee.as_view('add'))
module_employee.add_url_rule('/admin/edit',
view_func=EditEmployee.as_view('edit'))
assignEmployeeAsTeacherView = AssignEmployeeAsTeacher.as_view('assign')
module_employee.add_url_rule('/admin/assign',
view_func=assignEmployeeAsTeacherView)
module_employee.add_url_rule('/admin/delete',
view_func=DeleteEmployee.as_view('delete'))
module_employee.add_url_rule('/search',
view_func=SearchEmployee.as_view('search'))
module_employee.add_url_rule('/admin/subject/add',
view_func=AddSubject.as_view('add_subject'))
Make dashboard route become admin's defaultfrom openedoo_project import db
from openedoo.core.libs import Blueprint
from .controllers.employee import EmployeeLogin, EmployeeLogout, AddEmployee, \
AssignEmployeeAsTeacher, EmployeeDashboard, EditEmployee, DeleteEmployee, \
SearchEmployee, AddSubject
module_employee = Blueprint('module_employee', __name__,
template_folder='templates',
static_folder='static')
module_employee.add_url_rule('/admin',
view_func=EmployeeDashboard.as_view('dashboard'))
module_employee.add_url_rule('/admin/login',
view_func=EmployeeLogin.as_view('login'))
module_employee.add_url_rule('/admin/logout',
view_func=EmployeeLogout.as_view('logout'))
module_employee.add_url_rule('/admin/add',
view_func=AddEmployee.as_view('add'))
module_employee.add_url_rule('/admin/edit',
view_func=EditEmployee.as_view('edit'))
assignEmployeeAsTeacherView = AssignEmployeeAsTeacher.as_view('assign')
module_employee.add_url_rule('/admin/assign',
view_func=assignEmployeeAsTeacherView)
module_employee.add_url_rule('/admin/delete',
view_func=DeleteEmployee.as_view('delete'))
module_employee.add_url_rule('/search',
view_func=SearchEmployee.as_view('search'))
module_employee.add_url_rule('/admin/subject/add',
view_func=AddSubject.as_view('add_subject'))
|
<commit_before>from openedoo_project import db
from openedoo.core.libs import Blueprint
from .controllers.employee import EmployeeLogin, EmployeeLogout, AddEmployee, \
AssignEmployeeAsTeacher, EmployeeDashboard, EditEmployee, DeleteEmployee, \
SearchEmployee, AddSubject
module_employee = Blueprint('module_employee', __name__,
template_folder='templates',
static_folder='static')
module_employee.add_url_rule('/admin/dashboard',
view_func=EmployeeDashboard.as_view('dashboard'))
module_employee.add_url_rule('/admin/login',
view_func=EmployeeLogin.as_view('login'))
module_employee.add_url_rule('/admin/logout',
view_func=EmployeeLogout.as_view('logout'))
module_employee.add_url_rule('/admin/add',
view_func=AddEmployee.as_view('add'))
module_employee.add_url_rule('/admin/edit',
view_func=EditEmployee.as_view('edit'))
assignEmployeeAsTeacherView = AssignEmployeeAsTeacher.as_view('assign')
module_employee.add_url_rule('/admin/assign',
view_func=assignEmployeeAsTeacherView)
module_employee.add_url_rule('/admin/delete',
view_func=DeleteEmployee.as_view('delete'))
module_employee.add_url_rule('/search',
view_func=SearchEmployee.as_view('search'))
module_employee.add_url_rule('/admin/subject/add',
view_func=AddSubject.as_view('add_subject'))
<commit_msg>Make dashboard route become admin's default<commit_after>from openedoo_project import db
from openedoo.core.libs import Blueprint
from .controllers.employee import EmployeeLogin, EmployeeLogout, AddEmployee, \
AssignEmployeeAsTeacher, EmployeeDashboard, EditEmployee, DeleteEmployee, \
SearchEmployee, AddSubject
module_employee = Blueprint('module_employee', __name__,
template_folder='templates',
static_folder='static')
module_employee.add_url_rule('/admin',
view_func=EmployeeDashboard.as_view('dashboard'))
module_employee.add_url_rule('/admin/login',
view_func=EmployeeLogin.as_view('login'))
module_employee.add_url_rule('/admin/logout',
view_func=EmployeeLogout.as_view('logout'))
module_employee.add_url_rule('/admin/add',
view_func=AddEmployee.as_view('add'))
module_employee.add_url_rule('/admin/edit',
view_func=EditEmployee.as_view('edit'))
assignEmployeeAsTeacherView = AssignEmployeeAsTeacher.as_view('assign')
module_employee.add_url_rule('/admin/assign',
view_func=assignEmployeeAsTeacherView)
module_employee.add_url_rule('/admin/delete',
view_func=DeleteEmployee.as_view('delete'))
module_employee.add_url_rule('/search',
view_func=SearchEmployee.as_view('search'))
module_employee.add_url_rule('/admin/subject/add',
view_func=AddSubject.as_view('add_subject'))
|
64d75740c485b8e3ac3108b916cdf72ad41b0611
|
nacl/__init__.py
|
nacl/__init__.py
|
from . import hash # pylint: disable=W0622
|
from . import __about__
from . import hash # pylint: disable=W0622
__all__ = ["hash"] + __about__.__all__
# - Meta Information -
# This is pretty ugly
for attr in __about__.__all__:
if hasattr(__about__, attr):
globals()[attr] = getattr(__about__, attr)
# - End Meta Information -
|
Add meta information to the nacl package
|
Add meta information to the nacl package
|
Python
|
mit
|
dstufft/pynacl,ucoin-bot/cutecoin,hoffmabc/pynacl,Insoleet/cutecoin,xueyumusic/pynacl,scholarly/pynacl,ucoin-io/cutecoin,dstufft/pynacl,lmctv/pynacl,JackWink/pynacl,JackWink/pynacl,xueyumusic/pynacl,pyca/pynacl,reaperhulk/pynacl,scholarly/pynacl,lmctv/pynacl,ucoin-io/cutecoin,alex/pynacl,pyca/pynacl,xueyumusic/pynacl,alex/pynacl,pyca/pynacl,pyca/pynacl,dstufft/pynacl,alex/pynacl,reaperhulk/pynacl,hoffmabc/pynacl,JackWink/pynacl,lmctv/pynacl,hoffmabc/pynacl,pyca/pynacl,reaperhulk/pynacl,lmctv/pynacl,scholarly/pynacl,scholarly/pynacl,reaperhulk/pynacl,alex/pynacl,reaperhulk/pynacl,JackWink/pynacl,ucoin-io/cutecoin,xueyumusic/pynacl,dstufft/pynacl,lmctv/pynacl
|
from . import hash # pylint: disable=W0622
Add meta information to the nacl package
|
from . import __about__
from . import hash # pylint: disable=W0622
__all__ = ["hash"] + __about__.__all__
# - Meta Information -
# This is pretty ugly
for attr in __about__.__all__:
if hasattr(__about__, attr):
globals()[attr] = getattr(__about__, attr)
# - End Meta Information -
|
<commit_before>from . import hash # pylint: disable=W0622
<commit_msg>Add meta information to the nacl package<commit_after>
|
from . import __about__
from . import hash # pylint: disable=W0622
__all__ = ["hash"] + __about__.__all__
# - Meta Information -
# This is pretty ugly
for attr in __about__.__all__:
if hasattr(__about__, attr):
globals()[attr] = getattr(__about__, attr)
# - End Meta Information -
|
from . import hash # pylint: disable=W0622
Add meta information to the nacl packagefrom . import __about__
from . import hash # pylint: disable=W0622
__all__ = ["hash"] + __about__.__all__
# - Meta Information -
# This is pretty ugly
for attr in __about__.__all__:
if hasattr(__about__, attr):
globals()[attr] = getattr(__about__, attr)
# - End Meta Information -
|
<commit_before>from . import hash # pylint: disable=W0622
<commit_msg>Add meta information to the nacl package<commit_after>from . import __about__
from . import hash # pylint: disable=W0622
__all__ = ["hash"] + __about__.__all__
# - Meta Information -
# This is pretty ugly
for attr in __about__.__all__:
if hasattr(__about__, attr):
globals()[attr] = getattr(__about__, attr)
# - End Meta Information -
|
69ff671582bb343bd2ac9515964a3913e29f3d72
|
oabutton/wsgi.py
|
oabutton/wsgi.py
|
"""
WSGI config for oabutton project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "oabutton.settings")
from django.core.wsgi import get_wsgi_application
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from dj_static import Cling
application = Cling(get_wsgi_application())
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
|
"""
WSGI config for oabutton project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "oabutton.settings")
# Enable Django secure mode (see http://security.stackexchange.com/a/8970)
os.environ["HTTPS"] = "on"
from django.core.wsgi import get_wsgi_application
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from dj_static import Cling
application = Cling(get_wsgi_application())
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
|
Enable Django secure mode in WSGI module
|
Enable Django secure mode in WSGI module
|
Python
|
mit
|
OAButton/OAButton_old,OAButton/OAButton_old,OAButton/OAButton_old
|
"""
WSGI config for oabutton project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "oabutton.settings")
from django.core.wsgi import get_wsgi_application
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from dj_static import Cling
application = Cling(get_wsgi_application())
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
Enable Django secure mode in WSGI module
|
"""
WSGI config for oabutton project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "oabutton.settings")
# Enable Django secure mode (see http://security.stackexchange.com/a/8970)
os.environ["HTTPS"] = "on"
from django.core.wsgi import get_wsgi_application
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from dj_static import Cling
application = Cling(get_wsgi_application())
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
|
<commit_before>"""
WSGI config for oabutton project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "oabutton.settings")
from django.core.wsgi import get_wsgi_application
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from dj_static import Cling
application = Cling(get_wsgi_application())
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
<commit_msg>Enable Django secure mode in WSGI module<commit_after>
|
"""
WSGI config for oabutton project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "oabutton.settings")
# Enable Django secure mode (see http://security.stackexchange.com/a/8970)
os.environ["HTTPS"] = "on"
from django.core.wsgi import get_wsgi_application
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from dj_static import Cling
application = Cling(get_wsgi_application())
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
|
"""
WSGI config for oabutton project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "oabutton.settings")
from django.core.wsgi import get_wsgi_application
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from dj_static import Cling
application = Cling(get_wsgi_application())
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
Enable Django secure mode in WSGI module"""
WSGI config for oabutton project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "oabutton.settings")
# Enable Django secure mode (see http://security.stackexchange.com/a/8970)
os.environ["HTTPS"] = "on"
from django.core.wsgi import get_wsgi_application
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from dj_static import Cling
application = Cling(get_wsgi_application())
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
|
<commit_before>"""
WSGI config for oabutton project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "oabutton.settings")
from django.core.wsgi import get_wsgi_application
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from dj_static import Cling
application = Cling(get_wsgi_application())
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
<commit_msg>Enable Django secure mode in WSGI module<commit_after>"""
WSGI config for oabutton project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "oabutton.settings")
# Enable Django secure mode (see http://security.stackexchange.com/a/8970)
os.environ["HTTPS"] = "on"
from django.core.wsgi import get_wsgi_application
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from dj_static import Cling
application = Cling(get_wsgi_application())
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
|
65ef07040e8b0e34ce6dae42850789bdd8f4806a
|
cmsplugin_filer_file/models.py
|
cmsplugin_filer_file/models.py
|
from posixpath import exists
from cms.models import CMSPlugin
from django.db import models
from django.utils.translation import ugettext_lazy as _
from filer.fields.file import FilerFileField
from cmsplugin_filer_utils import FilerPluginManager
class FilerFile(CMSPlugin):
"""
Plugin for storing any type of file.
Default template displays download link with icon (if available) and file size.
This could be updated to use the mimetypes library to determine the type of file rather than
storing a separate icon for each different extension.
The icon search is currently performed within get_icon_url; this is probably a performance concern.
"""
title = models.CharField(_("title"), max_length=255, null=True, blank=True)
file = FilerFileField(verbose_name=_('file'))
target_blank = models.BooleanField(_('Open link in new window'), default=False)
objects = FilerPluginManager(select_related=('file',))
def get_icon_url(self):
return self.file.icons['32']
def file_exists(self):
return exists(self.file.path)
def get_file_name(self):
return self.file.name
def get_ext(self):
return self.file.extension
def __unicode__(self):
if self.title:
return self.title
elif self.file:
# added if, because it raised attribute error when file wasnt defined
return self.get_file_name()
return "<empty>"
search_fields = ('title',)
|
from cms.models import CMSPlugin
from django.db import models
from django.utils.translation import ugettext_lazy as _
from filer.fields.file import FilerFileField
from cmsplugin_filer_utils import FilerPluginManager
class FilerFile(CMSPlugin):
"""
Plugin for storing any type of file.
Default template displays download link with icon (if available) and file size.
This could be updated to use the mimetypes library to determine the type of file rather than
storing a separate icon for each different extension.
The icon search is currently performed within get_icon_url; this is probably a performance concern.
"""
title = models.CharField(_("title"), max_length=255, null=True, blank=True)
file = FilerFileField(verbose_name=_('file'))
target_blank = models.BooleanField(_('Open link in new window'), default=False)
objects = FilerPluginManager(select_related=('file',))
def get_icon_url(self):
return self.file.icons['32']
def file_exists(self):
return self.file.file.storage.exists(self.file.path)
def get_file_name(self):
if self.file.name in ('', None):
name = u"%s" % (self.file.original_filename,)
else:
name = u"%s" % (self.file.name,)
return name
def get_ext(self):
return self.file.extension
def __unicode__(self):
if self.title:
return self.title
elif self.file:
# added if, because it raised attribute error when file wasnt defined
return self.get_file_name()
return "<empty>"
search_fields = ('title',)
|
Use the file's storage to determine whether the file exists or not. The existing implementation that uses posixpath.exists only works if the storage backend is the default FileSystemStorage
|
Use the file's storage to determine whether the file exists or not.
The existing implementation that uses posixpath.exists only works if the storage backend is the default FileSystemStorage
|
Python
|
bsd-3-clause
|
nephila/cmsplugin-filer,stefanfoulis/cmsplugin-filer,centralniak/cmsplugin-filer,creimers/cmsplugin-filer,stefanfoulis/cmsplugin-filer,yvess/cmsplugin-filer,alsoicode/cmsplugin-filer,yvess/cmsplugin-filer,jrutila/cmsplugin-filer,brightinteractive/cmsplugin-filer,wlanslovenija/cmsplugin-filer,sephii/cmsplugin-filer,eliasp/cmsplugin-filer,ImaginaryLandscape/cmsplugin-filer,brightinteractive/cmsplugin-filer,divio/cmsplugin-filer,douwevandermeij/cmsplugin-filer,grigoryk/cmsplugin-filer,grigoryk/cmsplugin-filer,dreipol/cmsplugin-filer,skirsdeda/cmsplugin-filer,brightinteractive/cmsplugin-filer,nephila/cmsplugin-filer,yakky/cmsplugin-filer,isotoma/cmsplugin-filer,douwevandermeij/cmsplugin-filer,nephila/cmsplugin-filer,jrutila/cmsplugin-filer,jschneier/cmsplugin-filer,pbs/cmsplugin-filer,sephii/cmsplugin-filer,creimers/cmsplugin-filer,wlanslovenija/cmsplugin-filer,NB-Dev/cmsplugin-filer,divio/cmsplugin-filer,divio/cmsplugin-filer,yakky/cmsplugin-filer,alsoicode/cmsplugin-filer,alsoicode/cmsplugin-filer,eliasp/cmsplugin-filer,stefanfoulis/cmsplugin-filer,isotoma/cmsplugin-filer,dreipol/cmsplugin-filer,douwevandermeij/cmsplugin-filer,sephii/cmsplugin-filer,pbs/cmsplugin-filer,skirsdeda/cmsplugin-filer,centralniak/cmsplugin-filer,jschneier/cmsplugin-filer,yvess/cmsplugin-filer,wlanslovenija/cmsplugin-filer,eliasp/cmsplugin-filer,stefanfoulis/cmsplugin-filer,divio/cmsplugin-filer,creimers/cmsplugin-filer,jschneier/cmsplugin-filer,skirsdeda/cmsplugin-filer,yvess/cmsplugin-filer,pbs/cmsplugin-filer,ImaginaryLandscape/cmsplugin-filer,pbs/cmsplugin-filer,isotoma/cmsplugin-filer,NB-Dev/cmsplugin-filer
|
from posixpath import exists
from cms.models import CMSPlugin
from django.db import models
from django.utils.translation import ugettext_lazy as _
from filer.fields.file import FilerFileField
from cmsplugin_filer_utils import FilerPluginManager
class FilerFile(CMSPlugin):
"""
Plugin for storing any type of file.
Default template displays download link with icon (if available) and file size.
This could be updated to use the mimetypes library to determine the type of file rather than
storing a separate icon for each different extension.
The icon search is currently performed within get_icon_url; this is probably a performance concern.
"""
title = models.CharField(_("title"), max_length=255, null=True, blank=True)
file = FilerFileField(verbose_name=_('file'))
target_blank = models.BooleanField(_('Open link in new window'), default=False)
objects = FilerPluginManager(select_related=('file',))
def get_icon_url(self):
return self.file.icons['32']
def file_exists(self):
return exists(self.file.path)
def get_file_name(self):
return self.file.name
def get_ext(self):
return self.file.extension
def __unicode__(self):
if self.title:
return self.title
elif self.file:
# added if, because it raised attribute error when file wasnt defined
return self.get_file_name()
return "<empty>"
search_fields = ('title',)
Use the file's storage to determine whether the file exists or not.
The existing implementation that uses posixpath.exists only works if the storage backend is the default FileSystemStorage
|
from cms.models import CMSPlugin
from django.db import models
from django.utils.translation import ugettext_lazy as _
from filer.fields.file import FilerFileField
from cmsplugin_filer_utils import FilerPluginManager
class FilerFile(CMSPlugin):
"""
Plugin for storing any type of file.
Default template displays download link with icon (if available) and file size.
This could be updated to use the mimetypes library to determine the type of file rather than
storing a separate icon for each different extension.
The icon search is currently performed within get_icon_url; this is probably a performance concern.
"""
title = models.CharField(_("title"), max_length=255, null=True, blank=True)
file = FilerFileField(verbose_name=_('file'))
target_blank = models.BooleanField(_('Open link in new window'), default=False)
objects = FilerPluginManager(select_related=('file',))
def get_icon_url(self):
return self.file.icons['32']
def file_exists(self):
return self.file.file.storage.exists(self.file.path)
def get_file_name(self):
if self.file.name in ('', None):
name = u"%s" % (self.file.original_filename,)
else:
name = u"%s" % (self.file.name,)
return name
def get_ext(self):
return self.file.extension
def __unicode__(self):
if self.title:
return self.title
elif self.file:
# added if, because it raised attribute error when file wasnt defined
return self.get_file_name()
return "<empty>"
search_fields = ('title',)
|
<commit_before>from posixpath import exists
from cms.models import CMSPlugin
from django.db import models
from django.utils.translation import ugettext_lazy as _
from filer.fields.file import FilerFileField
from cmsplugin_filer_utils import FilerPluginManager
class FilerFile(CMSPlugin):
"""
Plugin for storing any type of file.
Default template displays download link with icon (if available) and file size.
This could be updated to use the mimetypes library to determine the type of file rather than
storing a separate icon for each different extension.
The icon search is currently performed within get_icon_url; this is probably a performance concern.
"""
title = models.CharField(_("title"), max_length=255, null=True, blank=True)
file = FilerFileField(verbose_name=_('file'))
target_blank = models.BooleanField(_('Open link in new window'), default=False)
objects = FilerPluginManager(select_related=('file',))
def get_icon_url(self):
return self.file.icons['32']
def file_exists(self):
return exists(self.file.path)
def get_file_name(self):
return self.file.name
def get_ext(self):
return self.file.extension
def __unicode__(self):
if self.title:
return self.title
elif self.file:
# added if, because it raised attribute error when file wasnt defined
return self.get_file_name()
return "<empty>"
search_fields = ('title',)
<commit_msg>Use the file's storage to determine whether the file exists or not.
The existing implementation that uses posixpath.exists only works if the storage backend is the default FileSystemStorage<commit_after>
|
from cms.models import CMSPlugin
from django.db import models
from django.utils.translation import ugettext_lazy as _
from filer.fields.file import FilerFileField
from cmsplugin_filer_utils import FilerPluginManager
class FilerFile(CMSPlugin):
"""
Plugin for storing any type of file.
Default template displays download link with icon (if available) and file size.
This could be updated to use the mimetypes library to determine the type of file rather than
storing a separate icon for each different extension.
The icon search is currently performed within get_icon_url; this is probably a performance concern.
"""
title = models.CharField(_("title"), max_length=255, null=True, blank=True)
file = FilerFileField(verbose_name=_('file'))
target_blank = models.BooleanField(_('Open link in new window'), default=False)
objects = FilerPluginManager(select_related=('file',))
def get_icon_url(self):
return self.file.icons['32']
def file_exists(self):
return self.file.file.storage.exists(self.file.path)
def get_file_name(self):
if self.file.name in ('', None):
name = u"%s" % (self.file.original_filename,)
else:
name = u"%s" % (self.file.name,)
return name
def get_ext(self):
return self.file.extension
def __unicode__(self):
if self.title:
return self.title
elif self.file:
# added if, because it raised attribute error when file wasnt defined
return self.get_file_name()
return "<empty>"
search_fields = ('title',)
|
from posixpath import exists
from cms.models import CMSPlugin
from django.db import models
from django.utils.translation import ugettext_lazy as _
from filer.fields.file import FilerFileField
from cmsplugin_filer_utils import FilerPluginManager
class FilerFile(CMSPlugin):
"""
Plugin for storing any type of file.
Default template displays download link with icon (if available) and file size.
This could be updated to use the mimetypes library to determine the type of file rather than
storing a separate icon for each different extension.
The icon search is currently performed within get_icon_url; this is probably a performance concern.
"""
title = models.CharField(_("title"), max_length=255, null=True, blank=True)
file = FilerFileField(verbose_name=_('file'))
target_blank = models.BooleanField(_('Open link in new window'), default=False)
objects = FilerPluginManager(select_related=('file',))
def get_icon_url(self):
return self.file.icons['32']
def file_exists(self):
return exists(self.file.path)
def get_file_name(self):
return self.file.name
def get_ext(self):
return self.file.extension
def __unicode__(self):
if self.title:
return self.title
elif self.file:
# added if, because it raised attribute error when file wasnt defined
return self.get_file_name()
return "<empty>"
search_fields = ('title',)
Use the file's storage to determine whether the file exists or not.
The existing implementation that uses posixpath.exists only works if the storage backend is the default FileSystemStoragefrom cms.models import CMSPlugin
from django.db import models
from django.utils.translation import ugettext_lazy as _
from filer.fields.file import FilerFileField
from cmsplugin_filer_utils import FilerPluginManager
class FilerFile(CMSPlugin):
"""
Plugin for storing any type of file.
Default template displays download link with icon (if available) and file size.
This could be updated to use the mimetypes library to determine the type of file rather than
storing a separate icon for each different extension.
The icon search is currently performed within get_icon_url; this is probably a performance concern.
"""
title = models.CharField(_("title"), max_length=255, null=True, blank=True)
file = FilerFileField(verbose_name=_('file'))
target_blank = models.BooleanField(_('Open link in new window'), default=False)
objects = FilerPluginManager(select_related=('file',))
def get_icon_url(self):
return self.file.icons['32']
def file_exists(self):
return self.file.file.storage.exists(self.file.path)
def get_file_name(self):
if self.file.name in ('', None):
name = u"%s" % (self.file.original_filename,)
else:
name = u"%s" % (self.file.name,)
return name
def get_ext(self):
return self.file.extension
def __unicode__(self):
if self.title:
return self.title
elif self.file:
# added if, because it raised attribute error when file wasnt defined
return self.get_file_name()
return "<empty>"
search_fields = ('title',)
|
<commit_before>from posixpath import exists
from cms.models import CMSPlugin
from django.db import models
from django.utils.translation import ugettext_lazy as _
from filer.fields.file import FilerFileField
from cmsplugin_filer_utils import FilerPluginManager
class FilerFile(CMSPlugin):
"""
Plugin for storing any type of file.
Default template displays download link with icon (if available) and file size.
This could be updated to use the mimetypes library to determine the type of file rather than
storing a separate icon for each different extension.
The icon search is currently performed within get_icon_url; this is probably a performance concern.
"""
title = models.CharField(_("title"), max_length=255, null=True, blank=True)
file = FilerFileField(verbose_name=_('file'))
target_blank = models.BooleanField(_('Open link in new window'), default=False)
objects = FilerPluginManager(select_related=('file',))
def get_icon_url(self):
return self.file.icons['32']
def file_exists(self):
return exists(self.file.path)
def get_file_name(self):
return self.file.name
def get_ext(self):
return self.file.extension
def __unicode__(self):
if self.title:
return self.title
elif self.file:
# added if, because it raised attribute error when file wasnt defined
return self.get_file_name()
return "<empty>"
search_fields = ('title',)
<commit_msg>Use the file's storage to determine whether the file exists or not.
The existing implementation that uses posixpath.exists only works if the storage backend is the default FileSystemStorage<commit_after>from cms.models import CMSPlugin
from django.db import models
from django.utils.translation import ugettext_lazy as _
from filer.fields.file import FilerFileField
from cmsplugin_filer_utils import FilerPluginManager
class FilerFile(CMSPlugin):
"""
Plugin for storing any type of file.
Default template displays download link with icon (if available) and file size.
This could be updated to use the mimetypes library to determine the type of file rather than
storing a separate icon for each different extension.
The icon search is currently performed within get_icon_url; this is probably a performance concern.
"""
title = models.CharField(_("title"), max_length=255, null=True, blank=True)
file = FilerFileField(verbose_name=_('file'))
target_blank = models.BooleanField(_('Open link in new window'), default=False)
objects = FilerPluginManager(select_related=('file',))
def get_icon_url(self):
return self.file.icons['32']
def file_exists(self):
return self.file.file.storage.exists(self.file.path)
def get_file_name(self):
if self.file.name in ('', None):
name = u"%s" % (self.file.original_filename,)
else:
name = u"%s" % (self.file.name,)
return name
def get_ext(self):
return self.file.extension
def __unicode__(self):
if self.title:
return self.title
elif self.file:
# added if, because it raised attribute error when file wasnt defined
return self.get_file_name()
return "<empty>"
search_fields = ('title',)
|
7b3f1edc1e9ba120a2718d0001135aa45c7a6753
|
personnel/views.py
|
personnel/views.py
|
'''This app contains the views for the personnel app.
'''
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from personnel.models import Person, JobPosting
class LaboratoryPersonnelList(ListView):
'''This class generates the view for current laboratory personnel located at **/personnel**.
This is filtered based on whether the ::class:`Personnel` object is marked as current_lab_member = True.
'''
queryset = Person.objects.filter(current_lab_member=True)
template_name = "personnel_list.html"
context_object_name = 'personnel'
def get_context_data(self, **kwargs):
'''This method adds to the context the personnel-type = current.'''
context = super(LaboratoryPersonnelList, self).get_context_data(**kwargs)
context['personnel-type'] = "current"
context['postings'] = JobPosting.objects.filter(active=True)
return context
class LaboratoryPersonnelDetail(DetailView):
'''This class generates the view for personnel-details located at **/personnel/<name_slug>**.
'''
model = Person
slug_field = "name_slug"
slug_url_kwarg = "name_slug"
template_name = "personnel_detail.html"
context_object_name = 'person'
|
'''This app contains the views for the personnel app.
'''
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from personnel.models import Person, JobPosting
class LaboratoryPersonnelList(ListView):
'''This class generates the view for current laboratory personnel located at **/personnel**.
This is filtered based on whether the ::class:`Personnel` object is marked as current_lab_member = True.
'''
queryset = Person.objects.filter(current_lab_member=True).order_by('created')
template_name = "personnel_list.html"
context_object_name = 'personnel'
def get_context_data(self, **kwargs):
'''This method adds to the context the personnel-type = current.'''
context = super(LaboratoryPersonnelList, self).get_context_data(**kwargs)
context['personnel-type'] = "current"
context['postings'] = JobPosting.objects.filter(active=True)
return context
class LaboratoryPersonnelDetail(DetailView):
'''This class generates the view for personnel-details located at **/personnel/<name_slug>**.
'''
model = Person
slug_field = "name_slug"
slug_url_kwarg = "name_slug"
template_name = "personnel_detail.html"
context_object_name = 'person'
|
Reset personnel page back to ordering by creation date.
|
Reset personnel page back to ordering by creation date.
|
Python
|
mit
|
davebridges/Lab-Website,davebridges/Lab-Website,davebridges/Lab-Website
|
'''This app contains the views for the personnel app.
'''
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from personnel.models import Person, JobPosting
class LaboratoryPersonnelList(ListView):
'''This class generates the view for current laboratory personnel located at **/personnel**.
This is filtered based on whether the ::class:`Personnel` object is marked as current_lab_member = True.
'''
queryset = Person.objects.filter(current_lab_member=True)
template_name = "personnel_list.html"
context_object_name = 'personnel'
def get_context_data(self, **kwargs):
'''This method adds to the context the personnel-type = current.'''
context = super(LaboratoryPersonnelList, self).get_context_data(**kwargs)
context['personnel-type'] = "current"
context['postings'] = JobPosting.objects.filter(active=True)
return context
class LaboratoryPersonnelDetail(DetailView):
'''This class generates the view for personnel-details located at **/personnel/<name_slug>**.
'''
model = Person
slug_field = "name_slug"
slug_url_kwarg = "name_slug"
template_name = "personnel_detail.html"
context_object_name = 'person'
Reset personnel page back to ordering by creation date.
|
'''This app contains the views for the personnel app.
'''
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from personnel.models import Person, JobPosting
class LaboratoryPersonnelList(ListView):
'''This class generates the view for current laboratory personnel located at **/personnel**.
This is filtered based on whether the ::class:`Personnel` object is marked as current_lab_member = True.
'''
queryset = Person.objects.filter(current_lab_member=True).order_by('created')
template_name = "personnel_list.html"
context_object_name = 'personnel'
def get_context_data(self, **kwargs):
'''This method adds to the context the personnel-type = current.'''
context = super(LaboratoryPersonnelList, self).get_context_data(**kwargs)
context['personnel-type'] = "current"
context['postings'] = JobPosting.objects.filter(active=True)
return context
class LaboratoryPersonnelDetail(DetailView):
'''This class generates the view for personnel-details located at **/personnel/<name_slug>**.
'''
model = Person
slug_field = "name_slug"
slug_url_kwarg = "name_slug"
template_name = "personnel_detail.html"
context_object_name = 'person'
|
<commit_before>'''This app contains the views for the personnel app.
'''
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from personnel.models import Person, JobPosting
class LaboratoryPersonnelList(ListView):
'''This class generates the view for current laboratory personnel located at **/personnel**.
This is filtered based on whether the ::class:`Personnel` object is marked as current_lab_member = True.
'''
queryset = Person.objects.filter(current_lab_member=True)
template_name = "personnel_list.html"
context_object_name = 'personnel'
def get_context_data(self, **kwargs):
'''This method adds to the context the personnel-type = current.'''
context = super(LaboratoryPersonnelList, self).get_context_data(**kwargs)
context['personnel-type'] = "current"
context['postings'] = JobPosting.objects.filter(active=True)
return context
class LaboratoryPersonnelDetail(DetailView):
'''This class generates the view for personnel-details located at **/personnel/<name_slug>**.
'''
model = Person
slug_field = "name_slug"
slug_url_kwarg = "name_slug"
template_name = "personnel_detail.html"
context_object_name = 'person'
<commit_msg>Reset personnel page back to ordering by creation date.<commit_after>
|
'''This app contains the views for the personnel app.
'''
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from personnel.models import Person, JobPosting
class LaboratoryPersonnelList(ListView):
'''This class generates the view for current laboratory personnel located at **/personnel**.
This is filtered based on whether the ::class:`Personnel` object is marked as current_lab_member = True.
'''
queryset = Person.objects.filter(current_lab_member=True).order_by('created')
template_name = "personnel_list.html"
context_object_name = 'personnel'
def get_context_data(self, **kwargs):
'''This method adds to the context the personnel-type = current.'''
context = super(LaboratoryPersonnelList, self).get_context_data(**kwargs)
context['personnel-type'] = "current"
context['postings'] = JobPosting.objects.filter(active=True)
return context
class LaboratoryPersonnelDetail(DetailView):
'''This class generates the view for personnel-details located at **/personnel/<name_slug>**.
'''
model = Person
slug_field = "name_slug"
slug_url_kwarg = "name_slug"
template_name = "personnel_detail.html"
context_object_name = 'person'
|
'''This app contains the views for the personnel app.
'''
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from personnel.models import Person, JobPosting
class LaboratoryPersonnelList(ListView):
'''This class generates the view for current laboratory personnel located at **/personnel**.
This is filtered based on whether the ::class:`Personnel` object is marked as current_lab_member = True.
'''
queryset = Person.objects.filter(current_lab_member=True)
template_name = "personnel_list.html"
context_object_name = 'personnel'
def get_context_data(self, **kwargs):
'''This method adds to the context the personnel-type = current.'''
context = super(LaboratoryPersonnelList, self).get_context_data(**kwargs)
context['personnel-type'] = "current"
context['postings'] = JobPosting.objects.filter(active=True)
return context
class LaboratoryPersonnelDetail(DetailView):
'''This class generates the view for personnel-details located at **/personnel/<name_slug>**.
'''
model = Person
slug_field = "name_slug"
slug_url_kwarg = "name_slug"
template_name = "personnel_detail.html"
context_object_name = 'person'
Reset personnel page back to ordering by creation date.'''This app contains the views for the personnel app.
'''
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from personnel.models import Person, JobPosting
class LaboratoryPersonnelList(ListView):
'''This class generates the view for current laboratory personnel located at **/personnel**.
This is filtered based on whether the ::class:`Personnel` object is marked as current_lab_member = True.
'''
queryset = Person.objects.filter(current_lab_member=True).order_by('created')
template_name = "personnel_list.html"
context_object_name = 'personnel'
def get_context_data(self, **kwargs):
'''This method adds to the context the personnel-type = current.'''
context = super(LaboratoryPersonnelList, self).get_context_data(**kwargs)
context['personnel-type'] = "current"
context['postings'] = JobPosting.objects.filter(active=True)
return context
class LaboratoryPersonnelDetail(DetailView):
'''This class generates the view for personnel-details located at **/personnel/<name_slug>**.
'''
model = Person
slug_field = "name_slug"
slug_url_kwarg = "name_slug"
template_name = "personnel_detail.html"
context_object_name = 'person'
|
<commit_before>'''This app contains the views for the personnel app.
'''
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from personnel.models import Person, JobPosting
class LaboratoryPersonnelList(ListView):
'''This class generates the view for current laboratory personnel located at **/personnel**.
This is filtered based on whether the ::class:`Personnel` object is marked as current_lab_member = True.
'''
queryset = Person.objects.filter(current_lab_member=True)
template_name = "personnel_list.html"
context_object_name = 'personnel'
def get_context_data(self, **kwargs):
'''This method adds to the context the personnel-type = current.'''
context = super(LaboratoryPersonnelList, self).get_context_data(**kwargs)
context['personnel-type'] = "current"
context['postings'] = JobPosting.objects.filter(active=True)
return context
class LaboratoryPersonnelDetail(DetailView):
'''This class generates the view for personnel-details located at **/personnel/<name_slug>**.
'''
model = Person
slug_field = "name_slug"
slug_url_kwarg = "name_slug"
template_name = "personnel_detail.html"
context_object_name = 'person'
<commit_msg>Reset personnel page back to ordering by creation date.<commit_after>'''This app contains the views for the personnel app.
'''
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from personnel.models import Person, JobPosting
class LaboratoryPersonnelList(ListView):
'''This class generates the view for current laboratory personnel located at **/personnel**.
This is filtered based on whether the ::class:`Personnel` object is marked as current_lab_member = True.
'''
queryset = Person.objects.filter(current_lab_member=True).order_by('created')
template_name = "personnel_list.html"
context_object_name = 'personnel'
def get_context_data(self, **kwargs):
'''This method adds to the context the personnel-type = current.'''
context = super(LaboratoryPersonnelList, self).get_context_data(**kwargs)
context['personnel-type'] = "current"
context['postings'] = JobPosting.objects.filter(active=True)
return context
class LaboratoryPersonnelDetail(DetailView):
'''This class generates the view for personnel-details located at **/personnel/<name_slug>**.
'''
model = Person
slug_field = "name_slug"
slug_url_kwarg = "name_slug"
template_name = "personnel_detail.html"
context_object_name = 'person'
|
39d67ed57d5c944afb06da1db4a18320e9ebd758
|
bids/ext/__init__.py
|
bids/ext/__init__.py
|
__path__ = __import__('pkgutil').extend_path(__path__, __name__)
|
"""
The PyBIDS extension namespace package
``bids.ext`` is reserved as a namespace for extensions to install into.
To write such an extension, the following things are needed:
1) Create a new package with the following structure (assuming setuptools)::
package/
bids/
ext/
__init__.py
EXTENSION/
__init__.py
...
setup.cfg
setup.py
The important things to note are that the ``bids/`` directory must be
empty apart from ``ext/`` and ``bids/ext/`` must be empty except for
your extension and an ``__init__.py``.
2) Place the following (and nothing else) in ``__init__.py``::
__path__ = __import__('pkgutil').extend_path(__path__, __name__)
3) Include the following lines in ``setup.cfg``::
[options]
install_requires =
pybids >= 0.15
packages = find_namespace:
[options.packages.find]
include =
bids.ext.EXTENSION
bids.ext.EXTENSION.*
"""
__path__ = __import__('pkgutil').extend_path(__path__, __name__)
|
Add an explanation of how to set up a namespace package
|
DOC: Add an explanation of how to set up a namespace package
|
Python
|
mit
|
INCF/pybids
|
__path__ = __import__('pkgutil').extend_path(__path__, __name__)
DOC: Add an explanation of how to set up a namespace package
|
"""
The PyBIDS extension namespace package
``bids.ext`` is reserved as a namespace for extensions to install into.
To write such an extension, the following things are needed:
1) Create a new package with the following structure (assuming setuptools)::
package/
bids/
ext/
__init__.py
EXTENSION/
__init__.py
...
setup.cfg
setup.py
The important things to note are that the ``bids/`` directory must be
empty apart from ``ext/`` and ``bids/ext/`` must be empty except for
your extension and an ``__init__.py``.
2) Place the following (and nothing else) in ``__init__.py``::
__path__ = __import__('pkgutil').extend_path(__path__, __name__)
3) Include the following lines in ``setup.cfg``::
[options]
install_requires =
pybids >= 0.15
packages = find_namespace:
[options.packages.find]
include =
bids.ext.EXTENSION
bids.ext.EXTENSION.*
"""
__path__ = __import__('pkgutil').extend_path(__path__, __name__)
|
<commit_before>__path__ = __import__('pkgutil').extend_path(__path__, __name__)
<commit_msg>DOC: Add an explanation of how to set up a namespace package<commit_after>
|
"""
The PyBIDS extension namespace package
``bids.ext`` is reserved as a namespace for extensions to install into.
To write such an extension, the following things are needed:
1) Create a new package with the following structure (assuming setuptools)::
package/
bids/
ext/
__init__.py
EXTENSION/
__init__.py
...
setup.cfg
setup.py
The important things to note are that the ``bids/`` directory must be
empty apart from ``ext/`` and ``bids/ext/`` must be empty except for
your extension and an ``__init__.py``.
2) Place the following (and nothing else) in ``__init__.py``::
__path__ = __import__('pkgutil').extend_path(__path__, __name__)
3) Include the following lines in ``setup.cfg``::
[options]
install_requires =
pybids >= 0.15
packages = find_namespace:
[options.packages.find]
include =
bids.ext.EXTENSION
bids.ext.EXTENSION.*
"""
__path__ = __import__('pkgutil').extend_path(__path__, __name__)
|
__path__ = __import__('pkgutil').extend_path(__path__, __name__)
DOC: Add an explanation of how to set up a namespace package"""
The PyBIDS extension namespace package
``bids.ext`` is reserved as a namespace for extensions to install into.
To write such an extension, the following things are needed:
1) Create a new package with the following structure (assuming setuptools)::
package/
bids/
ext/
__init__.py
EXTENSION/
__init__.py
...
setup.cfg
setup.py
The important things to note are that the ``bids/`` directory must be
empty apart from ``ext/`` and ``bids/ext/`` must be empty except for
your extension and an ``__init__.py``.
2) Place the following (and nothing else) in ``__init__.py``::
__path__ = __import__('pkgutil').extend_path(__path__, __name__)
3) Include the following lines in ``setup.cfg``::
[options]
install_requires =
pybids >= 0.15
packages = find_namespace:
[options.packages.find]
include =
bids.ext.EXTENSION
bids.ext.EXTENSION.*
"""
__path__ = __import__('pkgutil').extend_path(__path__, __name__)
|
<commit_before>__path__ = __import__('pkgutil').extend_path(__path__, __name__)
<commit_msg>DOC: Add an explanation of how to set up a namespace package<commit_after>"""
The PyBIDS extension namespace package
``bids.ext`` is reserved as a namespace for extensions to install into.
To write such an extension, the following things are needed:
1) Create a new package with the following structure (assuming setuptools)::
package/
bids/
ext/
__init__.py
EXTENSION/
__init__.py
...
setup.cfg
setup.py
The important things to note are that the ``bids/`` directory must be
empty apart from ``ext/`` and ``bids/ext/`` must be empty except for
your extension and an ``__init__.py``.
2) Place the following (and nothing else) in ``__init__.py``::
__path__ = __import__('pkgutil').extend_path(__path__, __name__)
3) Include the following lines in ``setup.cfg``::
[options]
install_requires =
pybids >= 0.15
packages = find_namespace:
[options.packages.find]
include =
bids.ext.EXTENSION
bids.ext.EXTENSION.*
"""
__path__ = __import__('pkgutil').extend_path(__path__, __name__)
|
5d15ae493663b23d1554f4f285cf3d2044134878
|
pybossa_analyst/zip_builder.py
|
pybossa_analyst/zip_builder.py
|
# -*- coding: utf8 -*-
"""Zip builder module for pybossa-analyst."""
import requests
import zipstream
def _download(url):
"""Download data from a URL."""
yield requests.get(url).content
def _generate_zip(tasks, fn_key, url_key):
"""Generate a zip containing downloaded task data."""
z = zipstream.ZipFile(compression=zipstream.ZIP_DEFLATED)
for t in tasks:
fn = t.info[fn_key]
url = t.info[url_key]
z.write_iter(fn, _download(url))
for chunk in z:
yield chunk
def generate(tasks, importer):
"""Generate a zip file containing original task input."""
if importer == 'flickr':
return _generate_zip(tasks, "title", "url")
else:
raise ValueError("Unknown importer type")
|
# -*- coding: utf8 -*-
"""Zip builder module for pybossa-analyst."""
import requests
import zipstream
def _download(url):
"""Download data from a URL."""
yield requests.get(url).content
def _generate_zip(tasks, fn_key, url_key):
"""Generate a zip containing downloaded task data."""
z = zipstream.ZipFile(compression=zipstream.ZIP_DEFLATED)
for t in tasks:
fn = t.info[fn_key]
url = t.info[url_key]
z.write_iter(fn, _download(url))
for chunk in z:
yield chunk
def generate(tasks, importer):
"""Generate a zip file containing original task input."""
if importer == 'flickr':
for t in tasks:
t.info["title"] = "{0}.{1}".format(t.info["title"], "jpg")
return _generate_zip(tasks, "title", "url")
else:
raise ValueError("Unknown importer type")
|
Add jpg link for flickr downloads
|
Add jpg link for flickr downloads
|
Python
|
unknown
|
alexandermendes/pybossa-analyst,alexandermendes/pybossa-analyst,alexandermendes/pybossa-analyst,LibCrowds/libcrowds-analyst
|
# -*- coding: utf8 -*-
"""Zip builder module for pybossa-analyst."""
import requests
import zipstream
def _download(url):
"""Download data from a URL."""
yield requests.get(url).content
def _generate_zip(tasks, fn_key, url_key):
"""Generate a zip containing downloaded task data."""
z = zipstream.ZipFile(compression=zipstream.ZIP_DEFLATED)
for t in tasks:
fn = t.info[fn_key]
url = t.info[url_key]
z.write_iter(fn, _download(url))
for chunk in z:
yield chunk
def generate(tasks, importer):
"""Generate a zip file containing original task input."""
if importer == 'flickr':
return _generate_zip(tasks, "title", "url")
else:
raise ValueError("Unknown importer type")
Add jpg link for flickr downloads
|
# -*- coding: utf8 -*-
"""Zip builder module for pybossa-analyst."""
import requests
import zipstream
def _download(url):
"""Download data from a URL."""
yield requests.get(url).content
def _generate_zip(tasks, fn_key, url_key):
"""Generate a zip containing downloaded task data."""
z = zipstream.ZipFile(compression=zipstream.ZIP_DEFLATED)
for t in tasks:
fn = t.info[fn_key]
url = t.info[url_key]
z.write_iter(fn, _download(url))
for chunk in z:
yield chunk
def generate(tasks, importer):
"""Generate a zip file containing original task input."""
if importer == 'flickr':
for t in tasks:
t.info["title"] = "{0}.{1}".format(t.info["title"], "jpg")
return _generate_zip(tasks, "title", "url")
else:
raise ValueError("Unknown importer type")
|
<commit_before># -*- coding: utf8 -*-
"""Zip builder module for pybossa-analyst."""
import requests
import zipstream
def _download(url):
"""Download data from a URL."""
yield requests.get(url).content
def _generate_zip(tasks, fn_key, url_key):
"""Generate a zip containing downloaded task data."""
z = zipstream.ZipFile(compression=zipstream.ZIP_DEFLATED)
for t in tasks:
fn = t.info[fn_key]
url = t.info[url_key]
z.write_iter(fn, _download(url))
for chunk in z:
yield chunk
def generate(tasks, importer):
"""Generate a zip file containing original task input."""
if importer == 'flickr':
return _generate_zip(tasks, "title", "url")
else:
raise ValueError("Unknown importer type")
<commit_msg>Add jpg link for flickr downloads<commit_after>
|
# -*- coding: utf8 -*-
"""Zip builder module for pybossa-analyst."""
import requests
import zipstream
def _download(url):
"""Download data from a URL."""
yield requests.get(url).content
def _generate_zip(tasks, fn_key, url_key):
"""Generate a zip containing downloaded task data."""
z = zipstream.ZipFile(compression=zipstream.ZIP_DEFLATED)
for t in tasks:
fn = t.info[fn_key]
url = t.info[url_key]
z.write_iter(fn, _download(url))
for chunk in z:
yield chunk
def generate(tasks, importer):
"""Generate a zip file containing original task input."""
if importer == 'flickr':
for t in tasks:
t.info["title"] = "{0}.{1}".format(t.info["title"], "jpg")
return _generate_zip(tasks, "title", "url")
else:
raise ValueError("Unknown importer type")
|
# -*- coding: utf8 -*-
"""Zip builder module for pybossa-analyst."""
import requests
import zipstream
def _download(url):
"""Download data from a URL."""
yield requests.get(url).content
def _generate_zip(tasks, fn_key, url_key):
"""Generate a zip containing downloaded task data."""
z = zipstream.ZipFile(compression=zipstream.ZIP_DEFLATED)
for t in tasks:
fn = t.info[fn_key]
url = t.info[url_key]
z.write_iter(fn, _download(url))
for chunk in z:
yield chunk
def generate(tasks, importer):
"""Generate a zip file containing original task input."""
if importer == 'flickr':
return _generate_zip(tasks, "title", "url")
else:
raise ValueError("Unknown importer type")
Add jpg link for flickr downloads# -*- coding: utf8 -*-
"""Zip builder module for pybossa-analyst."""
import requests
import zipstream
def _download(url):
"""Download data from a URL."""
yield requests.get(url).content
def _generate_zip(tasks, fn_key, url_key):
"""Generate a zip containing downloaded task data."""
z = zipstream.ZipFile(compression=zipstream.ZIP_DEFLATED)
for t in tasks:
fn = t.info[fn_key]
url = t.info[url_key]
z.write_iter(fn, _download(url))
for chunk in z:
yield chunk
def generate(tasks, importer):
"""Generate a zip file containing original task input."""
if importer == 'flickr':
for t in tasks:
t.info["title"] = "{0}.{1}".format(t.info["title"], "jpg")
return _generate_zip(tasks, "title", "url")
else:
raise ValueError("Unknown importer type")
|
<commit_before># -*- coding: utf8 -*-
"""Zip builder module for pybossa-analyst."""
import requests
import zipstream
def _download(url):
"""Download data from a URL."""
yield requests.get(url).content
def _generate_zip(tasks, fn_key, url_key):
"""Generate a zip containing downloaded task data."""
z = zipstream.ZipFile(compression=zipstream.ZIP_DEFLATED)
for t in tasks:
fn = t.info[fn_key]
url = t.info[url_key]
z.write_iter(fn, _download(url))
for chunk in z:
yield chunk
def generate(tasks, importer):
"""Generate a zip file containing original task input."""
if importer == 'flickr':
return _generate_zip(tasks, "title", "url")
else:
raise ValueError("Unknown importer type")
<commit_msg>Add jpg link for flickr downloads<commit_after># -*- coding: utf8 -*-
"""Zip builder module for pybossa-analyst."""
import requests
import zipstream
def _download(url):
"""Download data from a URL."""
yield requests.get(url).content
def _generate_zip(tasks, fn_key, url_key):
"""Generate a zip containing downloaded task data."""
z = zipstream.ZipFile(compression=zipstream.ZIP_DEFLATED)
for t in tasks:
fn = t.info[fn_key]
url = t.info[url_key]
z.write_iter(fn, _download(url))
for chunk in z:
yield chunk
def generate(tasks, importer):
"""Generate a zip file containing original task input."""
if importer == 'flickr':
for t in tasks:
t.info["title"] = "{0}.{1}".format(t.info["title"], "jpg")
return _generate_zip(tasks, "title", "url")
else:
raise ValueError("Unknown importer type")
|
662f245ca6c3dbe50d92a73549715af7ec46015e
|
chainerrl/explorers/additive_gaussian.py
|
chainerrl/explorers/additive_gaussian.py
|
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from builtins import * # NOQA
from future import standard_library
standard_library.install_aliases() # NOQA
import numpy as np
from chainerrl import explorer
class AdditiveGaussian(explorer.Explorer):
"""Additive Gaussian noise to actions.
Each action must be numpy.ndarray.
Args:
scale (float or array_like of floats): Scale parameter.
"""
def __init__(self, scale):
self.scale = scale
def select_action(self, t, greedy_action_func, action_value=None):
a = greedy_action_func()
noise = np.random.normal(
scale=self.scale, size=a.shape).astype(np.float32)
return a + noise
def __repr__(self):
return 'AdditiveGaussian(scale={})'.format(self.scale)
|
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from builtins import * # NOQA
from future import standard_library
standard_library.install_aliases() # NOQA
import numpy as np
from chainerrl import explorer
class AdditiveGaussian(explorer.Explorer):
"""Additive Gaussian noise to actions.
Each action must be numpy.ndarray.
Args:
scale (float or array_like of floats): Scale parameter.
"""
def __init__(self, scale, low=None, high=None):
self.scale = scale
self.low = low
self.high = high
def select_action(self, t, greedy_action_func, action_value=None):
a = greedy_action_func()
noise = np.random.normal(
scale=self.scale, size=a.shape).astype(np.float32)
if self.low is not None or self.high is not None:
return np.clip(a + noise, self.low, self.high)
else:
return a + noise
def __repr__(self):
return 'AdditiveGaussian(scale={})'.format(self.scale)
|
Add low and high options to AdditiveGaussian
|
Add low and high options to AdditiveGaussian
|
Python
|
mit
|
toslunar/chainerrl,toslunar/chainerrl
|
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from builtins import * # NOQA
from future import standard_library
standard_library.install_aliases() # NOQA
import numpy as np
from chainerrl import explorer
class AdditiveGaussian(explorer.Explorer):
"""Additive Gaussian noise to actions.
Each action must be numpy.ndarray.
Args:
scale (float or array_like of floats): Scale parameter.
"""
def __init__(self, scale):
self.scale = scale
def select_action(self, t, greedy_action_func, action_value=None):
a = greedy_action_func()
noise = np.random.normal(
scale=self.scale, size=a.shape).astype(np.float32)
return a + noise
def __repr__(self):
return 'AdditiveGaussian(scale={})'.format(self.scale)
Add low and high options to AdditiveGaussian
|
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from builtins import * # NOQA
from future import standard_library
standard_library.install_aliases() # NOQA
import numpy as np
from chainerrl import explorer
class AdditiveGaussian(explorer.Explorer):
"""Additive Gaussian noise to actions.
Each action must be numpy.ndarray.
Args:
scale (float or array_like of floats): Scale parameter.
"""
def __init__(self, scale, low=None, high=None):
self.scale = scale
self.low = low
self.high = high
def select_action(self, t, greedy_action_func, action_value=None):
a = greedy_action_func()
noise = np.random.normal(
scale=self.scale, size=a.shape).astype(np.float32)
if self.low is not None or self.high is not None:
return np.clip(a + noise, self.low, self.high)
else:
return a + noise
def __repr__(self):
return 'AdditiveGaussian(scale={})'.format(self.scale)
|
<commit_before>from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from builtins import * # NOQA
from future import standard_library
standard_library.install_aliases() # NOQA
import numpy as np
from chainerrl import explorer
class AdditiveGaussian(explorer.Explorer):
"""Additive Gaussian noise to actions.
Each action must be numpy.ndarray.
Args:
scale (float or array_like of floats): Scale parameter.
"""
def __init__(self, scale):
self.scale = scale
def select_action(self, t, greedy_action_func, action_value=None):
a = greedy_action_func()
noise = np.random.normal(
scale=self.scale, size=a.shape).astype(np.float32)
return a + noise
def __repr__(self):
return 'AdditiveGaussian(scale={})'.format(self.scale)
<commit_msg>Add low and high options to AdditiveGaussian<commit_after>
|
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from builtins import * # NOQA
from future import standard_library
standard_library.install_aliases() # NOQA
import numpy as np
from chainerrl import explorer
class AdditiveGaussian(explorer.Explorer):
"""Additive Gaussian noise to actions.
Each action must be numpy.ndarray.
Args:
scale (float or array_like of floats): Scale parameter.
"""
def __init__(self, scale, low=None, high=None):
self.scale = scale
self.low = low
self.high = high
def select_action(self, t, greedy_action_func, action_value=None):
a = greedy_action_func()
noise = np.random.normal(
scale=self.scale, size=a.shape).astype(np.float32)
if self.low is not None or self.high is not None:
return np.clip(a + noise, self.low, self.high)
else:
return a + noise
def __repr__(self):
return 'AdditiveGaussian(scale={})'.format(self.scale)
|
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from builtins import * # NOQA
from future import standard_library
standard_library.install_aliases() # NOQA
import numpy as np
from chainerrl import explorer
class AdditiveGaussian(explorer.Explorer):
"""Additive Gaussian noise to actions.
Each action must be numpy.ndarray.
Args:
scale (float or array_like of floats): Scale parameter.
"""
def __init__(self, scale):
self.scale = scale
def select_action(self, t, greedy_action_func, action_value=None):
a = greedy_action_func()
noise = np.random.normal(
scale=self.scale, size=a.shape).astype(np.float32)
return a + noise
def __repr__(self):
return 'AdditiveGaussian(scale={})'.format(self.scale)
Add low and high options to AdditiveGaussianfrom __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from builtins import * # NOQA
from future import standard_library
standard_library.install_aliases() # NOQA
import numpy as np
from chainerrl import explorer
class AdditiveGaussian(explorer.Explorer):
"""Additive Gaussian noise to actions.
Each action must be numpy.ndarray.
Args:
scale (float or array_like of floats): Scale parameter.
"""
def __init__(self, scale, low=None, high=None):
self.scale = scale
self.low = low
self.high = high
def select_action(self, t, greedy_action_func, action_value=None):
a = greedy_action_func()
noise = np.random.normal(
scale=self.scale, size=a.shape).astype(np.float32)
if self.low is not None or self.high is not None:
return np.clip(a + noise, self.low, self.high)
else:
return a + noise
def __repr__(self):
return 'AdditiveGaussian(scale={})'.format(self.scale)
|
<commit_before>from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from builtins import * # NOQA
from future import standard_library
standard_library.install_aliases() # NOQA
import numpy as np
from chainerrl import explorer
class AdditiveGaussian(explorer.Explorer):
"""Additive Gaussian noise to actions.
Each action must be numpy.ndarray.
Args:
scale (float or array_like of floats): Scale parameter.
"""
def __init__(self, scale):
self.scale = scale
def select_action(self, t, greedy_action_func, action_value=None):
a = greedy_action_func()
noise = np.random.normal(
scale=self.scale, size=a.shape).astype(np.float32)
return a + noise
def __repr__(self):
return 'AdditiveGaussian(scale={})'.format(self.scale)
<commit_msg>Add low and high options to AdditiveGaussian<commit_after>from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from builtins import * # NOQA
from future import standard_library
standard_library.install_aliases() # NOQA
import numpy as np
from chainerrl import explorer
class AdditiveGaussian(explorer.Explorer):
"""Additive Gaussian noise to actions.
Each action must be numpy.ndarray.
Args:
scale (float or array_like of floats): Scale parameter.
"""
def __init__(self, scale, low=None, high=None):
self.scale = scale
self.low = low
self.high = high
def select_action(self, t, greedy_action_func, action_value=None):
a = greedy_action_func()
noise = np.random.normal(
scale=self.scale, size=a.shape).astype(np.float32)
if self.low is not None or self.high is not None:
return np.clip(a + noise, self.low, self.high)
else:
return a + noise
def __repr__(self):
return 'AdditiveGaussian(scale={})'.format(self.scale)
|
9e9d25aaebc22f47e93f688bf5025378b2102b45
|
dss/storage.py
|
dss/storage.py
|
import pymongo
from .config import config
from .tools import show
client = pymongo.MongoClient()
conf = config['database']
database_name = conf['name']
_db = client[database_name]
class KeyValueStorage(object):
def __init__(self, database_name):
self.__dict__['_db'] = _db[database_name]
def __getattr__(self, name):
obj = self._db.find_one({'key': name})
if obj is None:
raise AttributeError(name)
return obj['value']
def __setattr__(self, name, value):
self._db.update(
{'key': name},
{'$set': {'value': value}},
upsert=True,
)
def __delattr__(self, name):
self._db.remove({'key': name})
__getitem__ = __getattr__
__setitem__ = __setattr__
__delitem__ = __delattr__
class DB:
meta = KeyValueStorage('metadata')
providers = _db.providers
static = _db.static_streams
mobile = _db.mobile_streams
db = DB
def update_database():
if not hasattr(db.meta, 'version'):
db.meta.version = 0 # stub
db_version = conf.getint('version')
current_version = db.meta.version
if current_version != db_version:
show('Database content version is {}. Upgrading to version {}'.format(
current_version, db_version
))
# TODO: Do some actual updating, if it is possible
|
import pymongo
from .config import config
from .tools import show
client = pymongo.MongoClient()
conf = config['database']
database_name = conf['name']
_db = client[database_name]
class KeyValueStorage(object):
def __init__(self, database_name, db=_db):
self.__dict__['_db'] = db[database_name]
def __getattr__(self, name):
obj = self._db.find_one({'key': name})
if obj is None:
raise AttributeError(name)
return obj['value']
def __setattr__(self, name, value):
self._db.update(
{'key': name},
{'$set': {'value': value}},
upsert=True,
)
def __delattr__(self, name):
self._db.remove({'key': name})
__getitem__ = __getattr__
__setitem__ = __setattr__
__delitem__ = __delattr__
class DB:
meta = KeyValueStorage('metadata')
providers = _db.providers
static = _db.static_streams
mobile = _db.mobile_streams
db = DB
def update_database():
if not hasattr(db.meta, 'version'):
db.meta.version = 0 # stub
db_version = conf.getint('version')
current_version = db.meta.version
if current_version != db_version:
show('Database content version is {}. Upgrading to version {}'.format(
current_version, db_version
))
# TODO: Do some actual updating, if it is possible
|
Enable external database (non dss) suport for KeyValueStorage
|
Enable external database (non dss) suport for KeyValueStorage
|
Python
|
bsd-3-clause
|
terabit-software/dynamic-stream-server,terabit-software/dynamic-stream-server,hmoraes/dynamic-stream-server,hmoraes/dynamic-stream-server,terabit-software/dynamic-stream-server,terabit-software/dynamic-stream-server,hmoraes/dynamic-stream-server,hmoraes/dynamic-stream-server
|
import pymongo
from .config import config
from .tools import show
client = pymongo.MongoClient()
conf = config['database']
database_name = conf['name']
_db = client[database_name]
class KeyValueStorage(object):
def __init__(self, database_name):
self.__dict__['_db'] = _db[database_name]
def __getattr__(self, name):
obj = self._db.find_one({'key': name})
if obj is None:
raise AttributeError(name)
return obj['value']
def __setattr__(self, name, value):
self._db.update(
{'key': name},
{'$set': {'value': value}},
upsert=True,
)
def __delattr__(self, name):
self._db.remove({'key': name})
__getitem__ = __getattr__
__setitem__ = __setattr__
__delitem__ = __delattr__
class DB:
meta = KeyValueStorage('metadata')
providers = _db.providers
static = _db.static_streams
mobile = _db.mobile_streams
db = DB
def update_database():
if not hasattr(db.meta, 'version'):
db.meta.version = 0 # stub
db_version = conf.getint('version')
current_version = db.meta.version
if current_version != db_version:
show('Database content version is {}. Upgrading to version {}'.format(
current_version, db_version
))
# TODO: Do some actual updating, if it is possible
Enable external database (non dss) suport for KeyValueStorage
|
import pymongo
from .config import config
from .tools import show
client = pymongo.MongoClient()
conf = config['database']
database_name = conf['name']
_db = client[database_name]
class KeyValueStorage(object):
def __init__(self, database_name, db=_db):
self.__dict__['_db'] = db[database_name]
def __getattr__(self, name):
obj = self._db.find_one({'key': name})
if obj is None:
raise AttributeError(name)
return obj['value']
def __setattr__(self, name, value):
self._db.update(
{'key': name},
{'$set': {'value': value}},
upsert=True,
)
def __delattr__(self, name):
self._db.remove({'key': name})
__getitem__ = __getattr__
__setitem__ = __setattr__
__delitem__ = __delattr__
class DB:
meta = KeyValueStorage('metadata')
providers = _db.providers
static = _db.static_streams
mobile = _db.mobile_streams
db = DB
def update_database():
if not hasattr(db.meta, 'version'):
db.meta.version = 0 # stub
db_version = conf.getint('version')
current_version = db.meta.version
if current_version != db_version:
show('Database content version is {}. Upgrading to version {}'.format(
current_version, db_version
))
# TODO: Do some actual updating, if it is possible
|
<commit_before>
import pymongo
from .config import config
from .tools import show
client = pymongo.MongoClient()
conf = config['database']
database_name = conf['name']
_db = client[database_name]
class KeyValueStorage(object):
def __init__(self, database_name):
self.__dict__['_db'] = _db[database_name]
def __getattr__(self, name):
obj = self._db.find_one({'key': name})
if obj is None:
raise AttributeError(name)
return obj['value']
def __setattr__(self, name, value):
self._db.update(
{'key': name},
{'$set': {'value': value}},
upsert=True,
)
def __delattr__(self, name):
self._db.remove({'key': name})
__getitem__ = __getattr__
__setitem__ = __setattr__
__delitem__ = __delattr__
class DB:
meta = KeyValueStorage('metadata')
providers = _db.providers
static = _db.static_streams
mobile = _db.mobile_streams
db = DB
def update_database():
if not hasattr(db.meta, 'version'):
db.meta.version = 0 # stub
db_version = conf.getint('version')
current_version = db.meta.version
if current_version != db_version:
show('Database content version is {}. Upgrading to version {}'.format(
current_version, db_version
))
# TODO: Do some actual updating, if it is possible
<commit_msg>Enable external database (non dss) suport for KeyValueStorage<commit_after>
|
import pymongo
from .config import config
from .tools import show
client = pymongo.MongoClient()
conf = config['database']
database_name = conf['name']
_db = client[database_name]
class KeyValueStorage(object):
def __init__(self, database_name, db=_db):
self.__dict__['_db'] = db[database_name]
def __getattr__(self, name):
obj = self._db.find_one({'key': name})
if obj is None:
raise AttributeError(name)
return obj['value']
def __setattr__(self, name, value):
self._db.update(
{'key': name},
{'$set': {'value': value}},
upsert=True,
)
def __delattr__(self, name):
self._db.remove({'key': name})
__getitem__ = __getattr__
__setitem__ = __setattr__
__delitem__ = __delattr__
class DB:
meta = KeyValueStorage('metadata')
providers = _db.providers
static = _db.static_streams
mobile = _db.mobile_streams
db = DB
def update_database():
if not hasattr(db.meta, 'version'):
db.meta.version = 0 # stub
db_version = conf.getint('version')
current_version = db.meta.version
if current_version != db_version:
show('Database content version is {}. Upgrading to version {}'.format(
current_version, db_version
))
# TODO: Do some actual updating, if it is possible
|
import pymongo
from .config import config
from .tools import show
client = pymongo.MongoClient()
conf = config['database']
database_name = conf['name']
_db = client[database_name]
class KeyValueStorage(object):
def __init__(self, database_name):
self.__dict__['_db'] = _db[database_name]
def __getattr__(self, name):
obj = self._db.find_one({'key': name})
if obj is None:
raise AttributeError(name)
return obj['value']
def __setattr__(self, name, value):
self._db.update(
{'key': name},
{'$set': {'value': value}},
upsert=True,
)
def __delattr__(self, name):
self._db.remove({'key': name})
__getitem__ = __getattr__
__setitem__ = __setattr__
__delitem__ = __delattr__
class DB:
meta = KeyValueStorage('metadata')
providers = _db.providers
static = _db.static_streams
mobile = _db.mobile_streams
db = DB
def update_database():
if not hasattr(db.meta, 'version'):
db.meta.version = 0 # stub
db_version = conf.getint('version')
current_version = db.meta.version
if current_version != db_version:
show('Database content version is {}. Upgrading to version {}'.format(
current_version, db_version
))
# TODO: Do some actual updating, if it is possible
Enable external database (non dss) suport for KeyValueStorage
import pymongo
from .config import config
from .tools import show
client = pymongo.MongoClient()
conf = config['database']
database_name = conf['name']
_db = client[database_name]
class KeyValueStorage(object):
def __init__(self, database_name, db=_db):
self.__dict__['_db'] = db[database_name]
def __getattr__(self, name):
obj = self._db.find_one({'key': name})
if obj is None:
raise AttributeError(name)
return obj['value']
def __setattr__(self, name, value):
self._db.update(
{'key': name},
{'$set': {'value': value}},
upsert=True,
)
def __delattr__(self, name):
self._db.remove({'key': name})
__getitem__ = __getattr__
__setitem__ = __setattr__
__delitem__ = __delattr__
class DB:
meta = KeyValueStorage('metadata')
providers = _db.providers
static = _db.static_streams
mobile = _db.mobile_streams
db = DB
def update_database():
if not hasattr(db.meta, 'version'):
db.meta.version = 0 # stub
db_version = conf.getint('version')
current_version = db.meta.version
if current_version != db_version:
show('Database content version is {}. Upgrading to version {}'.format(
current_version, db_version
))
# TODO: Do some actual updating, if it is possible
|
<commit_before>
import pymongo
from .config import config
from .tools import show
client = pymongo.MongoClient()
conf = config['database']
database_name = conf['name']
_db = client[database_name]
class KeyValueStorage(object):
def __init__(self, database_name):
self.__dict__['_db'] = _db[database_name]
def __getattr__(self, name):
obj = self._db.find_one({'key': name})
if obj is None:
raise AttributeError(name)
return obj['value']
def __setattr__(self, name, value):
self._db.update(
{'key': name},
{'$set': {'value': value}},
upsert=True,
)
def __delattr__(self, name):
self._db.remove({'key': name})
__getitem__ = __getattr__
__setitem__ = __setattr__
__delitem__ = __delattr__
class DB:
meta = KeyValueStorage('metadata')
providers = _db.providers
static = _db.static_streams
mobile = _db.mobile_streams
db = DB
def update_database():
if not hasattr(db.meta, 'version'):
db.meta.version = 0 # stub
db_version = conf.getint('version')
current_version = db.meta.version
if current_version != db_version:
show('Database content version is {}. Upgrading to version {}'.format(
current_version, db_version
))
# TODO: Do some actual updating, if it is possible
<commit_msg>Enable external database (non dss) suport for KeyValueStorage<commit_after>
import pymongo
from .config import config
from .tools import show
client = pymongo.MongoClient()
conf = config['database']
database_name = conf['name']
_db = client[database_name]
class KeyValueStorage(object):
def __init__(self, database_name, db=_db):
self.__dict__['_db'] = db[database_name]
def __getattr__(self, name):
obj = self._db.find_one({'key': name})
if obj is None:
raise AttributeError(name)
return obj['value']
def __setattr__(self, name, value):
self._db.update(
{'key': name},
{'$set': {'value': value}},
upsert=True,
)
def __delattr__(self, name):
self._db.remove({'key': name})
__getitem__ = __getattr__
__setitem__ = __setattr__
__delitem__ = __delattr__
class DB:
meta = KeyValueStorage('metadata')
providers = _db.providers
static = _db.static_streams
mobile = _db.mobile_streams
db = DB
def update_database():
if not hasattr(db.meta, 'version'):
db.meta.version = 0 # stub
db_version = conf.getint('version')
current_version = db.meta.version
if current_version != db_version:
show('Database content version is {}. Upgrading to version {}'.format(
current_version, db_version
))
# TODO: Do some actual updating, if it is possible
|
bc6a7ddca30093fa469800c32690d77c4f443018
|
tests/unit/test_notes.py
|
tests/unit/test_notes.py
|
import unittest
import requests_mock
from alertaclient.api import Client
class NotesTestCase(unittest.TestCase):
def setUp(self):
self.client = Client()
self.note = """
{
"status": "ok"
}
"""
@requests_mock.mock()
def test_add_note(self, m):
m.put('http://localhost:8080/alert/e7020428-5dad-4a41-9bfe-78e9d55cda06/note', text=self.note)
r = self.client.alert_note(id='e7020428-5dad-4a41-9bfe-78e9d55cda06', text='this is a test note')
self.assertEqual(r['status'], 'ok')
|
import unittest
import requests_mock
from alertaclient.api import Client
class NotesTestCase(unittest.TestCase):
def setUp(self):
self.client = Client()
self.note = """
{
"id": "62b62c6c-fca3-4329-b517-fc47c2371e63",
"note": {
"attributes": {
"environment": "Production",
"event": "node_down",
"resource": "web01",
"severity": "major",
"status": "open"
},
"createTime": "2020-04-19T10:45:49.385Z",
"customer": null,
"href": "http://localhost:8080/note/62b62c6c-fca3-4329-b517-fc47c2371e63",
"id": "62b62c6c-fca3-4329-b517-fc47c2371e63",
"related": {
"alert": "e7020428-5dad-4a41-9bfe-78e9d55cda06"
},
"text": "this is a new note",
"type": "alert",
"updateTime": null,
"user": null
},
"status": "ok"
}
"""
@requests_mock.mock()
def test_add_note(self, m):
m.put('http://localhost:8080/alert/e7020428-5dad-4a41-9bfe-78e9d55cda06/note', text=self.note)
r = self.client.alert_note(id='e7020428-5dad-4a41-9bfe-78e9d55cda06', text='this is a new note')
self.assertEqual(r['status'], 'ok')
self.assertEqual(r['note']['text'], 'this is a new note')
|
Fix unit tests for notes
|
Fix unit tests for notes
|
Python
|
apache-2.0
|
alerta/python-alerta,alerta/python-alerta-client,alerta/python-alerta-client
|
import unittest
import requests_mock
from alertaclient.api import Client
class NotesTestCase(unittest.TestCase):
def setUp(self):
self.client = Client()
self.note = """
{
"status": "ok"
}
"""
@requests_mock.mock()
def test_add_note(self, m):
m.put('http://localhost:8080/alert/e7020428-5dad-4a41-9bfe-78e9d55cda06/note', text=self.note)
r = self.client.alert_note(id='e7020428-5dad-4a41-9bfe-78e9d55cda06', text='this is a test note')
self.assertEqual(r['status'], 'ok')
Fix unit tests for notes
|
import unittest
import requests_mock
from alertaclient.api import Client
class NotesTestCase(unittest.TestCase):
def setUp(self):
self.client = Client()
self.note = """
{
"id": "62b62c6c-fca3-4329-b517-fc47c2371e63",
"note": {
"attributes": {
"environment": "Production",
"event": "node_down",
"resource": "web01",
"severity": "major",
"status": "open"
},
"createTime": "2020-04-19T10:45:49.385Z",
"customer": null,
"href": "http://localhost:8080/note/62b62c6c-fca3-4329-b517-fc47c2371e63",
"id": "62b62c6c-fca3-4329-b517-fc47c2371e63",
"related": {
"alert": "e7020428-5dad-4a41-9bfe-78e9d55cda06"
},
"text": "this is a new note",
"type": "alert",
"updateTime": null,
"user": null
},
"status": "ok"
}
"""
@requests_mock.mock()
def test_add_note(self, m):
m.put('http://localhost:8080/alert/e7020428-5dad-4a41-9bfe-78e9d55cda06/note', text=self.note)
r = self.client.alert_note(id='e7020428-5dad-4a41-9bfe-78e9d55cda06', text='this is a new note')
self.assertEqual(r['status'], 'ok')
self.assertEqual(r['note']['text'], 'this is a new note')
|
<commit_before>import unittest
import requests_mock
from alertaclient.api import Client
class NotesTestCase(unittest.TestCase):
def setUp(self):
self.client = Client()
self.note = """
{
"status": "ok"
}
"""
@requests_mock.mock()
def test_add_note(self, m):
m.put('http://localhost:8080/alert/e7020428-5dad-4a41-9bfe-78e9d55cda06/note', text=self.note)
r = self.client.alert_note(id='e7020428-5dad-4a41-9bfe-78e9d55cda06', text='this is a test note')
self.assertEqual(r['status'], 'ok')
<commit_msg>Fix unit tests for notes<commit_after>
|
import unittest
import requests_mock
from alertaclient.api import Client
class NotesTestCase(unittest.TestCase):
def setUp(self):
self.client = Client()
self.note = """
{
"id": "62b62c6c-fca3-4329-b517-fc47c2371e63",
"note": {
"attributes": {
"environment": "Production",
"event": "node_down",
"resource": "web01",
"severity": "major",
"status": "open"
},
"createTime": "2020-04-19T10:45:49.385Z",
"customer": null,
"href": "http://localhost:8080/note/62b62c6c-fca3-4329-b517-fc47c2371e63",
"id": "62b62c6c-fca3-4329-b517-fc47c2371e63",
"related": {
"alert": "e7020428-5dad-4a41-9bfe-78e9d55cda06"
},
"text": "this is a new note",
"type": "alert",
"updateTime": null,
"user": null
},
"status": "ok"
}
"""
@requests_mock.mock()
def test_add_note(self, m):
m.put('http://localhost:8080/alert/e7020428-5dad-4a41-9bfe-78e9d55cda06/note', text=self.note)
r = self.client.alert_note(id='e7020428-5dad-4a41-9bfe-78e9d55cda06', text='this is a new note')
self.assertEqual(r['status'], 'ok')
self.assertEqual(r['note']['text'], 'this is a new note')
|
import unittest
import requests_mock
from alertaclient.api import Client
class NotesTestCase(unittest.TestCase):
def setUp(self):
self.client = Client()
self.note = """
{
"status": "ok"
}
"""
@requests_mock.mock()
def test_add_note(self, m):
m.put('http://localhost:8080/alert/e7020428-5dad-4a41-9bfe-78e9d55cda06/note', text=self.note)
r = self.client.alert_note(id='e7020428-5dad-4a41-9bfe-78e9d55cda06', text='this is a test note')
self.assertEqual(r['status'], 'ok')
Fix unit tests for notesimport unittest
import requests_mock
from alertaclient.api import Client
class NotesTestCase(unittest.TestCase):
def setUp(self):
self.client = Client()
self.note = """
{
"id": "62b62c6c-fca3-4329-b517-fc47c2371e63",
"note": {
"attributes": {
"environment": "Production",
"event": "node_down",
"resource": "web01",
"severity": "major",
"status": "open"
},
"createTime": "2020-04-19T10:45:49.385Z",
"customer": null,
"href": "http://localhost:8080/note/62b62c6c-fca3-4329-b517-fc47c2371e63",
"id": "62b62c6c-fca3-4329-b517-fc47c2371e63",
"related": {
"alert": "e7020428-5dad-4a41-9bfe-78e9d55cda06"
},
"text": "this is a new note",
"type": "alert",
"updateTime": null,
"user": null
},
"status": "ok"
}
"""
@requests_mock.mock()
def test_add_note(self, m):
m.put('http://localhost:8080/alert/e7020428-5dad-4a41-9bfe-78e9d55cda06/note', text=self.note)
r = self.client.alert_note(id='e7020428-5dad-4a41-9bfe-78e9d55cda06', text='this is a new note')
self.assertEqual(r['status'], 'ok')
self.assertEqual(r['note']['text'], 'this is a new note')
|
<commit_before>import unittest
import requests_mock
from alertaclient.api import Client
class NotesTestCase(unittest.TestCase):
def setUp(self):
self.client = Client()
self.note = """
{
"status": "ok"
}
"""
@requests_mock.mock()
def test_add_note(self, m):
m.put('http://localhost:8080/alert/e7020428-5dad-4a41-9bfe-78e9d55cda06/note', text=self.note)
r = self.client.alert_note(id='e7020428-5dad-4a41-9bfe-78e9d55cda06', text='this is a test note')
self.assertEqual(r['status'], 'ok')
<commit_msg>Fix unit tests for notes<commit_after>import unittest
import requests_mock
from alertaclient.api import Client
class NotesTestCase(unittest.TestCase):
def setUp(self):
self.client = Client()
self.note = """
{
"id": "62b62c6c-fca3-4329-b517-fc47c2371e63",
"note": {
"attributes": {
"environment": "Production",
"event": "node_down",
"resource": "web01",
"severity": "major",
"status": "open"
},
"createTime": "2020-04-19T10:45:49.385Z",
"customer": null,
"href": "http://localhost:8080/note/62b62c6c-fca3-4329-b517-fc47c2371e63",
"id": "62b62c6c-fca3-4329-b517-fc47c2371e63",
"related": {
"alert": "e7020428-5dad-4a41-9bfe-78e9d55cda06"
},
"text": "this is a new note",
"type": "alert",
"updateTime": null,
"user": null
},
"status": "ok"
}
"""
@requests_mock.mock()
def test_add_note(self, m):
m.put('http://localhost:8080/alert/e7020428-5dad-4a41-9bfe-78e9d55cda06/note', text=self.note)
r = self.client.alert_note(id='e7020428-5dad-4a41-9bfe-78e9d55cda06', text='this is a new note')
self.assertEqual(r['status'], 'ok')
self.assertEqual(r['note']['text'], 'this is a new note')
|
4520360a0bbf223805cc963d58409626be2bd728
|
capstone/mdp/fixed_game_mdp.py
|
capstone/mdp/fixed_game_mdp.py
|
from .mdp import MDP
from .game_mdp import GameMDP
from ..utils import utility
class FixedGameMDP(GameMDP):
def __init__(self, game, opp_player, opp_idx):
'''
opp_player: the opponent player
opp_idx: the idx of the opponent player in the game
'''
self._game = game
self._opp_player = opp_player
self._opp_idx = opp_idx
self._agent_idx = opp_idx ^ 1
self._states = {}
def reward(self, game, move, next_game):
return utility(next_game, self._agent_idx) if next_game.is_over() else 0
def start_state(self):
new_game = self._game.copy()
if not new_game.is_over() and new_game.cur_player() == self._opp_idx:
chosen_move = self._opp_player.choose_move(new_game)
new_game.make_move(chosen_move)
return new_game
def transitions(self, game, move):
if game.is_over():
return []
new_game = game.copy().make_move(move)
if not new_game.is_over() and new_game.cur_player() == self._opp_idx:
chosen_move = self._opp_player.choose_move(new_game)
new_game.make_move(chosen_move)
return [(new_game, 1.0)]
|
from .mdp import MDP
from .game_mdp import GameMDP
from ..utils import utility
class FixedGameMDP(GameMDP):
def __init__(self, game, opp_player, opp_idx):
'''
opp_player: the opponent player
opp_idx: the idx of the opponent player in the game
'''
super(FixedGameMDP, self).__init__(game)
self._opp_player = opp_player
self._opp_idx = opp_idx
self._agent_idx = opp_idx ^ 1
def reward(self, game, move, next_game):
return utility(next_game, self._agent_idx) if next_game.is_over() else 0
def start_state(self):
new_game = self._game.copy()
if not new_game.is_over() and new_game.cur_player() == self._opp_idx:
chosen_move = self._opp_player.choose_move(new_game)
new_game.make_move(chosen_move)
return new_game
def transitions(self, game, move):
if game.is_over():
return []
new_game = game.copy().make_move(move)
if not new_game.is_over() and new_game.cur_player() == self._opp_idx:
chosen_move = self._opp_player.choose_move(new_game)
new_game.make_move(chosen_move)
return [(new_game, 1.0)]
|
Call super __init__ in GameMDP
|
Call super __init__ in GameMDP
|
Python
|
mit
|
davidrobles/mlnd-capstone-code
|
from .mdp import MDP
from .game_mdp import GameMDP
from ..utils import utility
class FixedGameMDP(GameMDP):
def __init__(self, game, opp_player, opp_idx):
'''
opp_player: the opponent player
opp_idx: the idx of the opponent player in the game
'''
self._game = game
self._opp_player = opp_player
self._opp_idx = opp_idx
self._agent_idx = opp_idx ^ 1
self._states = {}
def reward(self, game, move, next_game):
return utility(next_game, self._agent_idx) if next_game.is_over() else 0
def start_state(self):
new_game = self._game.copy()
if not new_game.is_over() and new_game.cur_player() == self._opp_idx:
chosen_move = self._opp_player.choose_move(new_game)
new_game.make_move(chosen_move)
return new_game
def transitions(self, game, move):
if game.is_over():
return []
new_game = game.copy().make_move(move)
if not new_game.is_over() and new_game.cur_player() == self._opp_idx:
chosen_move = self._opp_player.choose_move(new_game)
new_game.make_move(chosen_move)
return [(new_game, 1.0)]
Call super __init__ in GameMDP
|
from .mdp import MDP
from .game_mdp import GameMDP
from ..utils import utility
class FixedGameMDP(GameMDP):
def __init__(self, game, opp_player, opp_idx):
'''
opp_player: the opponent player
opp_idx: the idx of the opponent player in the game
'''
super(FixedGameMDP, self).__init__(game)
self._opp_player = opp_player
self._opp_idx = opp_idx
self._agent_idx = opp_idx ^ 1
def reward(self, game, move, next_game):
return utility(next_game, self._agent_idx) if next_game.is_over() else 0
def start_state(self):
new_game = self._game.copy()
if not new_game.is_over() and new_game.cur_player() == self._opp_idx:
chosen_move = self._opp_player.choose_move(new_game)
new_game.make_move(chosen_move)
return new_game
def transitions(self, game, move):
if game.is_over():
return []
new_game = game.copy().make_move(move)
if not new_game.is_over() and new_game.cur_player() == self._opp_idx:
chosen_move = self._opp_player.choose_move(new_game)
new_game.make_move(chosen_move)
return [(new_game, 1.0)]
|
<commit_before>from .mdp import MDP
from .game_mdp import GameMDP
from ..utils import utility
class FixedGameMDP(GameMDP):
def __init__(self, game, opp_player, opp_idx):
'''
opp_player: the opponent player
opp_idx: the idx of the opponent player in the game
'''
self._game = game
self._opp_player = opp_player
self._opp_idx = opp_idx
self._agent_idx = opp_idx ^ 1
self._states = {}
def reward(self, game, move, next_game):
return utility(next_game, self._agent_idx) if next_game.is_over() else 0
def start_state(self):
new_game = self._game.copy()
if not new_game.is_over() and new_game.cur_player() == self._opp_idx:
chosen_move = self._opp_player.choose_move(new_game)
new_game.make_move(chosen_move)
return new_game
def transitions(self, game, move):
if game.is_over():
return []
new_game = game.copy().make_move(move)
if not new_game.is_over() and new_game.cur_player() == self._opp_idx:
chosen_move = self._opp_player.choose_move(new_game)
new_game.make_move(chosen_move)
return [(new_game, 1.0)]
<commit_msg>Call super __init__ in GameMDP<commit_after>
|
from .mdp import MDP
from .game_mdp import GameMDP
from ..utils import utility
class FixedGameMDP(GameMDP):
def __init__(self, game, opp_player, opp_idx):
'''
opp_player: the opponent player
opp_idx: the idx of the opponent player in the game
'''
super(FixedGameMDP, self).__init__(game)
self._opp_player = opp_player
self._opp_idx = opp_idx
self._agent_idx = opp_idx ^ 1
def reward(self, game, move, next_game):
return utility(next_game, self._agent_idx) if next_game.is_over() else 0
def start_state(self):
new_game = self._game.copy()
if not new_game.is_over() and new_game.cur_player() == self._opp_idx:
chosen_move = self._opp_player.choose_move(new_game)
new_game.make_move(chosen_move)
return new_game
def transitions(self, game, move):
if game.is_over():
return []
new_game = game.copy().make_move(move)
if not new_game.is_over() and new_game.cur_player() == self._opp_idx:
chosen_move = self._opp_player.choose_move(new_game)
new_game.make_move(chosen_move)
return [(new_game, 1.0)]
|
from .mdp import MDP
from .game_mdp import GameMDP
from ..utils import utility
class FixedGameMDP(GameMDP):
def __init__(self, game, opp_player, opp_idx):
'''
opp_player: the opponent player
opp_idx: the idx of the opponent player in the game
'''
self._game = game
self._opp_player = opp_player
self._opp_idx = opp_idx
self._agent_idx = opp_idx ^ 1
self._states = {}
def reward(self, game, move, next_game):
return utility(next_game, self._agent_idx) if next_game.is_over() else 0
def start_state(self):
new_game = self._game.copy()
if not new_game.is_over() and new_game.cur_player() == self._opp_idx:
chosen_move = self._opp_player.choose_move(new_game)
new_game.make_move(chosen_move)
return new_game
def transitions(self, game, move):
if game.is_over():
return []
new_game = game.copy().make_move(move)
if not new_game.is_over() and new_game.cur_player() == self._opp_idx:
chosen_move = self._opp_player.choose_move(new_game)
new_game.make_move(chosen_move)
return [(new_game, 1.0)]
Call super __init__ in GameMDPfrom .mdp import MDP
from .game_mdp import GameMDP
from ..utils import utility
class FixedGameMDP(GameMDP):
def __init__(self, game, opp_player, opp_idx):
'''
opp_player: the opponent player
opp_idx: the idx of the opponent player in the game
'''
super(FixedGameMDP, self).__init__(game)
self._opp_player = opp_player
self._opp_idx = opp_idx
self._agent_idx = opp_idx ^ 1
def reward(self, game, move, next_game):
return utility(next_game, self._agent_idx) if next_game.is_over() else 0
def start_state(self):
new_game = self._game.copy()
if not new_game.is_over() and new_game.cur_player() == self._opp_idx:
chosen_move = self._opp_player.choose_move(new_game)
new_game.make_move(chosen_move)
return new_game
def transitions(self, game, move):
if game.is_over():
return []
new_game = game.copy().make_move(move)
if not new_game.is_over() and new_game.cur_player() == self._opp_idx:
chosen_move = self._opp_player.choose_move(new_game)
new_game.make_move(chosen_move)
return [(new_game, 1.0)]
|
<commit_before>from .mdp import MDP
from .game_mdp import GameMDP
from ..utils import utility
class FixedGameMDP(GameMDP):
def __init__(self, game, opp_player, opp_idx):
'''
opp_player: the opponent player
opp_idx: the idx of the opponent player in the game
'''
self._game = game
self._opp_player = opp_player
self._opp_idx = opp_idx
self._agent_idx = opp_idx ^ 1
self._states = {}
def reward(self, game, move, next_game):
return utility(next_game, self._agent_idx) if next_game.is_over() else 0
def start_state(self):
new_game = self._game.copy()
if not new_game.is_over() and new_game.cur_player() == self._opp_idx:
chosen_move = self._opp_player.choose_move(new_game)
new_game.make_move(chosen_move)
return new_game
def transitions(self, game, move):
if game.is_over():
return []
new_game = game.copy().make_move(move)
if not new_game.is_over() and new_game.cur_player() == self._opp_idx:
chosen_move = self._opp_player.choose_move(new_game)
new_game.make_move(chosen_move)
return [(new_game, 1.0)]
<commit_msg>Call super __init__ in GameMDP<commit_after>from .mdp import MDP
from .game_mdp import GameMDP
from ..utils import utility
class FixedGameMDP(GameMDP):
def __init__(self, game, opp_player, opp_idx):
'''
opp_player: the opponent player
opp_idx: the idx of the opponent player in the game
'''
super(FixedGameMDP, self).__init__(game)
self._opp_player = opp_player
self._opp_idx = opp_idx
self._agent_idx = opp_idx ^ 1
def reward(self, game, move, next_game):
return utility(next_game, self._agent_idx) if next_game.is_over() else 0
def start_state(self):
new_game = self._game.copy()
if not new_game.is_over() and new_game.cur_player() == self._opp_idx:
chosen_move = self._opp_player.choose_move(new_game)
new_game.make_move(chosen_move)
return new_game
def transitions(self, game, move):
if game.is_over():
return []
new_game = game.copy().make_move(move)
if not new_game.is_over() and new_game.cur_player() == self._opp_idx:
chosen_move = self._opp_player.choose_move(new_game)
new_game.make_move(chosen_move)
return [(new_game, 1.0)]
|
cf1aa4c0e07e4049f6f41b43898047fb5a0893b2
|
towel/templatetags/modelview_detail.py
|
towel/templatetags/modelview_detail.py
|
from django import template
from django.db import models
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter
def model_details(instance):
"""
Returns a stream of ``verbose_name``, ``value`` pairs for the specified
model instance::
<table>
{% for verbose_name, value in object|model_details %}
<tr>
<th>{{ verbose_name }}</th>
<td>{{ value }}</td>
</tr>
{% endfor %}
</table>
"""
for f in instance._meta.fields:
if f.auto_created:
continue
if isinstance(f, models.ForeignKey):
fk = getattr(instance, f.name)
if hasattr(fk, 'get_absolute_url'):
value = mark_safe(u'<a href="%s">%s</a>' % (
fk.get_absolute_url(),
fk))
else:
value = unicode(fk)
elif f.choices:
value = getattr(instance, 'get_%s_display' % f.name)()
else:
value = unicode(getattr(instance, f.name))
yield (f.verbose_name, value)
|
from django import template
from django.db import models
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter
def model_details(instance, fields=None):
"""
Returns a stream of ``verbose_name``, ``value`` pairs for the specified
model instance::
<table>
{% for verbose_name, value in object|model_details %}
<tr>
<th>{{ verbose_name }}</th>
<td>{{ value }}</td>
</tr>
{% endfor %}
</table>
"""
if not fields:
_fields = instance._meta.fields
else:
_fields = [instance._meta.get_field_by_name(f)[0] for f in fields.split(',')]
for f in _fields:
if f.auto_created:
continue
if isinstance(f, models.ForeignKey):
fk = getattr(instance, f.name)
if hasattr(fk, 'get_absolute_url'):
value = mark_safe(u'<a href="%s">%s</a>' % (
fk.get_absolute_url(),
fk))
else:
value = unicode(fk)
elif f.choices:
value = getattr(instance, 'get_%s_display' % f.name)()
else:
value = unicode(getattr(instance, f.name))
yield (f.verbose_name, value)
|
Allow specifying fields for model_details
|
Allow specifying fields for model_details
|
Python
|
bsd-3-clause
|
matthiask/towel,matthiask/towel,matthiask/towel,matthiask/towel
|
from django import template
from django.db import models
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter
def model_details(instance):
"""
Returns a stream of ``verbose_name``, ``value`` pairs for the specified
model instance::
<table>
{% for verbose_name, value in object|model_details %}
<tr>
<th>{{ verbose_name }}</th>
<td>{{ value }}</td>
</tr>
{% endfor %}
</table>
"""
for f in instance._meta.fields:
if f.auto_created:
continue
if isinstance(f, models.ForeignKey):
fk = getattr(instance, f.name)
if hasattr(fk, 'get_absolute_url'):
value = mark_safe(u'<a href="%s">%s</a>' % (
fk.get_absolute_url(),
fk))
else:
value = unicode(fk)
elif f.choices:
value = getattr(instance, 'get_%s_display' % f.name)()
else:
value = unicode(getattr(instance, f.name))
yield (f.verbose_name, value)
Allow specifying fields for model_details
|
from django import template
from django.db import models
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter
def model_details(instance, fields=None):
"""
Returns a stream of ``verbose_name``, ``value`` pairs for the specified
model instance::
<table>
{% for verbose_name, value in object|model_details %}
<tr>
<th>{{ verbose_name }}</th>
<td>{{ value }}</td>
</tr>
{% endfor %}
</table>
"""
if not fields:
_fields = instance._meta.fields
else:
_fields = [instance._meta.get_field_by_name(f)[0] for f in fields.split(',')]
for f in _fields:
if f.auto_created:
continue
if isinstance(f, models.ForeignKey):
fk = getattr(instance, f.name)
if hasattr(fk, 'get_absolute_url'):
value = mark_safe(u'<a href="%s">%s</a>' % (
fk.get_absolute_url(),
fk))
else:
value = unicode(fk)
elif f.choices:
value = getattr(instance, 'get_%s_display' % f.name)()
else:
value = unicode(getattr(instance, f.name))
yield (f.verbose_name, value)
|
<commit_before>from django import template
from django.db import models
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter
def model_details(instance):
"""
Returns a stream of ``verbose_name``, ``value`` pairs for the specified
model instance::
<table>
{% for verbose_name, value in object|model_details %}
<tr>
<th>{{ verbose_name }}</th>
<td>{{ value }}</td>
</tr>
{% endfor %}
</table>
"""
for f in instance._meta.fields:
if f.auto_created:
continue
if isinstance(f, models.ForeignKey):
fk = getattr(instance, f.name)
if hasattr(fk, 'get_absolute_url'):
value = mark_safe(u'<a href="%s">%s</a>' % (
fk.get_absolute_url(),
fk))
else:
value = unicode(fk)
elif f.choices:
value = getattr(instance, 'get_%s_display' % f.name)()
else:
value = unicode(getattr(instance, f.name))
yield (f.verbose_name, value)
<commit_msg>Allow specifying fields for model_details<commit_after>
|
from django import template
from django.db import models
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter
def model_details(instance, fields=None):
"""
Returns a stream of ``verbose_name``, ``value`` pairs for the specified
model instance::
<table>
{% for verbose_name, value in object|model_details %}
<tr>
<th>{{ verbose_name }}</th>
<td>{{ value }}</td>
</tr>
{% endfor %}
</table>
"""
if not fields:
_fields = instance._meta.fields
else:
_fields = [instance._meta.get_field_by_name(f)[0] for f in fields.split(',')]
for f in _fields:
if f.auto_created:
continue
if isinstance(f, models.ForeignKey):
fk = getattr(instance, f.name)
if hasattr(fk, 'get_absolute_url'):
value = mark_safe(u'<a href="%s">%s</a>' % (
fk.get_absolute_url(),
fk))
else:
value = unicode(fk)
elif f.choices:
value = getattr(instance, 'get_%s_display' % f.name)()
else:
value = unicode(getattr(instance, f.name))
yield (f.verbose_name, value)
|
from django import template
from django.db import models
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter
def model_details(instance):
"""
Returns a stream of ``verbose_name``, ``value`` pairs for the specified
model instance::
<table>
{% for verbose_name, value in object|model_details %}
<tr>
<th>{{ verbose_name }}</th>
<td>{{ value }}</td>
</tr>
{% endfor %}
</table>
"""
for f in instance._meta.fields:
if f.auto_created:
continue
if isinstance(f, models.ForeignKey):
fk = getattr(instance, f.name)
if hasattr(fk, 'get_absolute_url'):
value = mark_safe(u'<a href="%s">%s</a>' % (
fk.get_absolute_url(),
fk))
else:
value = unicode(fk)
elif f.choices:
value = getattr(instance, 'get_%s_display' % f.name)()
else:
value = unicode(getattr(instance, f.name))
yield (f.verbose_name, value)
Allow specifying fields for model_detailsfrom django import template
from django.db import models
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter
def model_details(instance, fields=None):
"""
Returns a stream of ``verbose_name``, ``value`` pairs for the specified
model instance::
<table>
{% for verbose_name, value in object|model_details %}
<tr>
<th>{{ verbose_name }}</th>
<td>{{ value }}</td>
</tr>
{% endfor %}
</table>
"""
if not fields:
_fields = instance._meta.fields
else:
_fields = [instance._meta.get_field_by_name(f)[0] for f in fields.split(',')]
for f in _fields:
if f.auto_created:
continue
if isinstance(f, models.ForeignKey):
fk = getattr(instance, f.name)
if hasattr(fk, 'get_absolute_url'):
value = mark_safe(u'<a href="%s">%s</a>' % (
fk.get_absolute_url(),
fk))
else:
value = unicode(fk)
elif f.choices:
value = getattr(instance, 'get_%s_display' % f.name)()
else:
value = unicode(getattr(instance, f.name))
yield (f.verbose_name, value)
|
<commit_before>from django import template
from django.db import models
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter
def model_details(instance):
"""
Returns a stream of ``verbose_name``, ``value`` pairs for the specified
model instance::
<table>
{% for verbose_name, value in object|model_details %}
<tr>
<th>{{ verbose_name }}</th>
<td>{{ value }}</td>
</tr>
{% endfor %}
</table>
"""
for f in instance._meta.fields:
if f.auto_created:
continue
if isinstance(f, models.ForeignKey):
fk = getattr(instance, f.name)
if hasattr(fk, 'get_absolute_url'):
value = mark_safe(u'<a href="%s">%s</a>' % (
fk.get_absolute_url(),
fk))
else:
value = unicode(fk)
elif f.choices:
value = getattr(instance, 'get_%s_display' % f.name)()
else:
value = unicode(getattr(instance, f.name))
yield (f.verbose_name, value)
<commit_msg>Allow specifying fields for model_details<commit_after>from django import template
from django.db import models
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter
def model_details(instance, fields=None):
"""
Returns a stream of ``verbose_name``, ``value`` pairs for the specified
model instance::
<table>
{% for verbose_name, value in object|model_details %}
<tr>
<th>{{ verbose_name }}</th>
<td>{{ value }}</td>
</tr>
{% endfor %}
</table>
"""
if not fields:
_fields = instance._meta.fields
else:
_fields = [instance._meta.get_field_by_name(f)[0] for f in fields.split(',')]
for f in _fields:
if f.auto_created:
continue
if isinstance(f, models.ForeignKey):
fk = getattr(instance, f.name)
if hasattr(fk, 'get_absolute_url'):
value = mark_safe(u'<a href="%s">%s</a>' % (
fk.get_absolute_url(),
fk))
else:
value = unicode(fk)
elif f.choices:
value = getattr(instance, 'get_%s_display' % f.name)()
else:
value = unicode(getattr(instance, f.name))
yield (f.verbose_name, value)
|
d150299c4e3165dbaf83867ac9944f03611cd63b
|
tornado_json/__init__.py
|
tornado_json/__init__.py
|
__version__='0.01'
|
# As setup.py imports this module to get the version, try not to do anything
# with dependencies for the project here. If that happens, setup.py
# should not import tornado_json and instead use this find_version
# thing: https://github.com/jezdez/envdir/blob/a062497e4339d5eb11e8a95dc6186dea6231aeb1/setup.py#L24
# Alternatively, just put the version in a text file or something to avoid
# this.
__version__ = '0.01'
|
Add warning about setup.py import
|
Add warning about setup.py import
|
Python
|
mit
|
ktalik/tornado-json,hfaran/Tornado-JSON,Tarsbot/Tornado-JSON
|
__version__='0.01'
Add warning about setup.py import
|
# As setup.py imports this module to get the version, try not to do anything
# with dependencies for the project here. If that happens, setup.py
# should not import tornado_json and instead use this find_version
# thing: https://github.com/jezdez/envdir/blob/a062497e4339d5eb11e8a95dc6186dea6231aeb1/setup.py#L24
# Alternatively, just put the version in a text file or something to avoid
# this.
__version__ = '0.01'
|
<commit_before>__version__='0.01'
<commit_msg>Add warning about setup.py import<commit_after>
|
# As setup.py imports this module to get the version, try not to do anything
# with dependencies for the project here. If that happens, setup.py
# should not import tornado_json and instead use this find_version
# thing: https://github.com/jezdez/envdir/blob/a062497e4339d5eb11e8a95dc6186dea6231aeb1/setup.py#L24
# Alternatively, just put the version in a text file or something to avoid
# this.
__version__ = '0.01'
|
__version__='0.01'
Add warning about setup.py import# As setup.py imports this module to get the version, try not to do anything
# with dependencies for the project here. If that happens, setup.py
# should not import tornado_json and instead use this find_version
# thing: https://github.com/jezdez/envdir/blob/a062497e4339d5eb11e8a95dc6186dea6231aeb1/setup.py#L24
# Alternatively, just put the version in a text file or something to avoid
# this.
__version__ = '0.01'
|
<commit_before>__version__='0.01'
<commit_msg>Add warning about setup.py import<commit_after># As setup.py imports this module to get the version, try not to do anything
# with dependencies for the project here. If that happens, setup.py
# should not import tornado_json and instead use this find_version
# thing: https://github.com/jezdez/envdir/blob/a062497e4339d5eb11e8a95dc6186dea6231aeb1/setup.py#L24
# Alternatively, just put the version in a text file or something to avoid
# this.
__version__ = '0.01'
|
ca214643b2a93bd9362182134624a8641b44aba2
|
tree_stars/tree_stars.py
|
tree_stars/tree_stars.py
|
"""Output a tree of stars like so:
*
***
*
***
*****
*
***
*****
*******
Input argument is the number of levels to the tree (3 in this example)
"""
from sys import argv
def main(levels):
for level in xrange(levels):
for sub_level in xrange(level+2):
spaces = (levels+2-sub_level) * ' '
stars = ((2 * sub_level) + 1) * '*'
print '{spaces}{stars}'.format(spaces=spaces, stars=stars)
if __name__ == '__main__':
main(int(argv[1]))
|
"""Output a tree of stars like so:
*
***
*
***
*****
*
***
*****
*******
Input argument is the number of levels to the tree (3 in this example)
"""
from sys import argv
def main(levels):
for level in xrange(levels):
for sub_level in xrange(level+2):
stars = ((2 * sub_level) + 1) * '*'
print ('{:^' + str(2 * levels + 2) + '}').format(stars)
# alternate method without using format centering
# spaces = (levels+2-sub_level) * ' '
# print '{spaces}{stars}'.format(spaces=spaces, stars=stars)
if __name__ == '__main__':
main(int(argv[1]))
|
Add solution using format method for centering.
|
Add solution using format method for centering.
|
Python
|
mit
|
bm5w/codeeval
|
"""Output a tree of stars like so:
*
***
*
***
*****
*
***
*****
*******
Input argument is the number of levels to the tree (3 in this example)
"""
from sys import argv
def main(levels):
for level in xrange(levels):
for sub_level in xrange(level+2):
spaces = (levels+2-sub_level) * ' '
stars = ((2 * sub_level) + 1) * '*'
print '{spaces}{stars}'.format(spaces=spaces, stars=stars)
if __name__ == '__main__':
main(int(argv[1]))
Add solution using format method for centering.
|
"""Output a tree of stars like so:
*
***
*
***
*****
*
***
*****
*******
Input argument is the number of levels to the tree (3 in this example)
"""
from sys import argv
def main(levels):
for level in xrange(levels):
for sub_level in xrange(level+2):
stars = ((2 * sub_level) + 1) * '*'
print ('{:^' + str(2 * levels + 2) + '}').format(stars)
# alternate method without using format centering
# spaces = (levels+2-sub_level) * ' '
# print '{spaces}{stars}'.format(spaces=spaces, stars=stars)
if __name__ == '__main__':
main(int(argv[1]))
|
<commit_before>"""Output a tree of stars like so:
*
***
*
***
*****
*
***
*****
*******
Input argument is the number of levels to the tree (3 in this example)
"""
from sys import argv
def main(levels):
for level in xrange(levels):
for sub_level in xrange(level+2):
spaces = (levels+2-sub_level) * ' '
stars = ((2 * sub_level) + 1) * '*'
print '{spaces}{stars}'.format(spaces=spaces, stars=stars)
if __name__ == '__main__':
main(int(argv[1]))
<commit_msg>Add solution using format method for centering.<commit_after>
|
"""Output a tree of stars like so:
*
***
*
***
*****
*
***
*****
*******
Input argument is the number of levels to the tree (3 in this example)
"""
from sys import argv
def main(levels):
for level in xrange(levels):
for sub_level in xrange(level+2):
stars = ((2 * sub_level) + 1) * '*'
print ('{:^' + str(2 * levels + 2) + '}').format(stars)
# alternate method without using format centering
# spaces = (levels+2-sub_level) * ' '
# print '{spaces}{stars}'.format(spaces=spaces, stars=stars)
if __name__ == '__main__':
main(int(argv[1]))
|
"""Output a tree of stars like so:
*
***
*
***
*****
*
***
*****
*******
Input argument is the number of levels to the tree (3 in this example)
"""
from sys import argv
def main(levels):
for level in xrange(levels):
for sub_level in xrange(level+2):
spaces = (levels+2-sub_level) * ' '
stars = ((2 * sub_level) + 1) * '*'
print '{spaces}{stars}'.format(spaces=spaces, stars=stars)
if __name__ == '__main__':
main(int(argv[1]))
Add solution using format method for centering."""Output a tree of stars like so:
*
***
*
***
*****
*
***
*****
*******
Input argument is the number of levels to the tree (3 in this example)
"""
from sys import argv
def main(levels):
for level in xrange(levels):
for sub_level in xrange(level+2):
stars = ((2 * sub_level) + 1) * '*'
print ('{:^' + str(2 * levels + 2) + '}').format(stars)
# alternate method without using format centering
# spaces = (levels+2-sub_level) * ' '
# print '{spaces}{stars}'.format(spaces=spaces, stars=stars)
if __name__ == '__main__':
main(int(argv[1]))
|
<commit_before>"""Output a tree of stars like so:
*
***
*
***
*****
*
***
*****
*******
Input argument is the number of levels to the tree (3 in this example)
"""
from sys import argv
def main(levels):
for level in xrange(levels):
for sub_level in xrange(level+2):
spaces = (levels+2-sub_level) * ' '
stars = ((2 * sub_level) + 1) * '*'
print '{spaces}{stars}'.format(spaces=spaces, stars=stars)
if __name__ == '__main__':
main(int(argv[1]))
<commit_msg>Add solution using format method for centering.<commit_after>"""Output a tree of stars like so:
*
***
*
***
*****
*
***
*****
*******
Input argument is the number of levels to the tree (3 in this example)
"""
from sys import argv
def main(levels):
for level in xrange(levels):
for sub_level in xrange(level+2):
stars = ((2 * sub_level) + 1) * '*'
print ('{:^' + str(2 * levels + 2) + '}').format(stars)
# alternate method without using format centering
# spaces = (levels+2-sub_level) * ' '
# print '{spaces}{stars}'.format(spaces=spaces, stars=stars)
if __name__ == '__main__':
main(int(argv[1]))
|
9068a532bfc7ff2b6d6fb276efda669a5cd60b36
|
example.py
|
example.py
|
import os
import mmstats
import libgettid
class MyStats(mmstats.BaseMmStats):
pid = mmstats.StaticUIntField(label="sys.pid", value=os.getpid)
tid = mmstats.StaticInt64Field(label="sys.tid", value=libgettid.gettid)
uid = mmstats.StaticUInt64Field(label="sys.uid", value=os.getuid)
gid = mmstats.StaticUInt64Field(label="sys.gid", value=os.getgid)
errors = mmstats.UIntStat(label="com.urbanairship.app.errors")
warnings = mmstats.UIntStat(label="com.urbanairship.app.warnings")
queries = mmstats.UIntStat(label="com.urbanairship.app.queries")
cache_hits = mmstats.UIntStat(label="com.urbanairship.app.cache_hits")
cache_misses = mmstats.UIntStat(label="com.urbanairship.app.cache_misses")
degraded = mmstats.BoolStat(label="com.urbanairship.app.degraded")
stats = MyStats(filename="mmstats-test-mystats")
stats.degraded = True
stats.errors += 1
stats.cache_hits += 1000
stats.queries = 50
|
import os
import mmstats
import libgettid
class MyStats(mmstats.BaseMmStats):
pid = mmstats.StaticUIntField(label="sys.pid", value=os.getpid)
tid = mmstats.StaticInt64Field(label="sys.tid", value=libgettid.gettid)
uid = mmstats.StaticUInt64Field(label="sys.uid", value=os.getuid)
gid = mmstats.StaticUInt64Field(label="sys.gid", value=os.getgid)
errors = mmstats.UIntStat(label="com.urbanairship.app.errors")
warnings = mmstats.UIntStat(label="com.urbanairship.app.warnings")
queries = mmstats.UIntStat(label="com.urbanairship.app.queries")
cache_hits = mmstats.UIntStat(label="com.urbanairship.app.cache_hits")
cache_misses = mmstats.UIntStat(label="com.urbanairship.app.cache_misses")
degraded = mmstats.BoolStat(label="com.urbanairship.app.degraded")
stats = MyStats(filename="mmstats-test-mystats")
stats.degraded = True
stats.errors += 1
stats.cache_hits += 1000
assert stats.cache_hits == 1000
|
Make it more obvious that values initialize at 0
|
Make it more obvious that values initialize at 0
|
Python
|
bsd-3-clause
|
schmichael/mmstats,schmichael/mmstats,schmichael/mmstats,schmichael/mmstats
|
import os
import mmstats
import libgettid
class MyStats(mmstats.BaseMmStats):
pid = mmstats.StaticUIntField(label="sys.pid", value=os.getpid)
tid = mmstats.StaticInt64Field(label="sys.tid", value=libgettid.gettid)
uid = mmstats.StaticUInt64Field(label="sys.uid", value=os.getuid)
gid = mmstats.StaticUInt64Field(label="sys.gid", value=os.getgid)
errors = mmstats.UIntStat(label="com.urbanairship.app.errors")
warnings = mmstats.UIntStat(label="com.urbanairship.app.warnings")
queries = mmstats.UIntStat(label="com.urbanairship.app.queries")
cache_hits = mmstats.UIntStat(label="com.urbanairship.app.cache_hits")
cache_misses = mmstats.UIntStat(label="com.urbanairship.app.cache_misses")
degraded = mmstats.BoolStat(label="com.urbanairship.app.degraded")
stats = MyStats(filename="mmstats-test-mystats")
stats.degraded = True
stats.errors += 1
stats.cache_hits += 1000
stats.queries = 50
Make it more obvious that values initialize at 0
|
import os
import mmstats
import libgettid
class MyStats(mmstats.BaseMmStats):
pid = mmstats.StaticUIntField(label="sys.pid", value=os.getpid)
tid = mmstats.StaticInt64Field(label="sys.tid", value=libgettid.gettid)
uid = mmstats.StaticUInt64Field(label="sys.uid", value=os.getuid)
gid = mmstats.StaticUInt64Field(label="sys.gid", value=os.getgid)
errors = mmstats.UIntStat(label="com.urbanairship.app.errors")
warnings = mmstats.UIntStat(label="com.urbanairship.app.warnings")
queries = mmstats.UIntStat(label="com.urbanairship.app.queries")
cache_hits = mmstats.UIntStat(label="com.urbanairship.app.cache_hits")
cache_misses = mmstats.UIntStat(label="com.urbanairship.app.cache_misses")
degraded = mmstats.BoolStat(label="com.urbanairship.app.degraded")
stats = MyStats(filename="mmstats-test-mystats")
stats.degraded = True
stats.errors += 1
stats.cache_hits += 1000
assert stats.cache_hits == 1000
|
<commit_before>import os
import mmstats
import libgettid
class MyStats(mmstats.BaseMmStats):
pid = mmstats.StaticUIntField(label="sys.pid", value=os.getpid)
tid = mmstats.StaticInt64Field(label="sys.tid", value=libgettid.gettid)
uid = mmstats.StaticUInt64Field(label="sys.uid", value=os.getuid)
gid = mmstats.StaticUInt64Field(label="sys.gid", value=os.getgid)
errors = mmstats.UIntStat(label="com.urbanairship.app.errors")
warnings = mmstats.UIntStat(label="com.urbanairship.app.warnings")
queries = mmstats.UIntStat(label="com.urbanairship.app.queries")
cache_hits = mmstats.UIntStat(label="com.urbanairship.app.cache_hits")
cache_misses = mmstats.UIntStat(label="com.urbanairship.app.cache_misses")
degraded = mmstats.BoolStat(label="com.urbanairship.app.degraded")
stats = MyStats(filename="mmstats-test-mystats")
stats.degraded = True
stats.errors += 1
stats.cache_hits += 1000
stats.queries = 50
<commit_msg>Make it more obvious that values initialize at 0<commit_after>
|
import os
import mmstats
import libgettid
class MyStats(mmstats.BaseMmStats):
pid = mmstats.StaticUIntField(label="sys.pid", value=os.getpid)
tid = mmstats.StaticInt64Field(label="sys.tid", value=libgettid.gettid)
uid = mmstats.StaticUInt64Field(label="sys.uid", value=os.getuid)
gid = mmstats.StaticUInt64Field(label="sys.gid", value=os.getgid)
errors = mmstats.UIntStat(label="com.urbanairship.app.errors")
warnings = mmstats.UIntStat(label="com.urbanairship.app.warnings")
queries = mmstats.UIntStat(label="com.urbanairship.app.queries")
cache_hits = mmstats.UIntStat(label="com.urbanairship.app.cache_hits")
cache_misses = mmstats.UIntStat(label="com.urbanairship.app.cache_misses")
degraded = mmstats.BoolStat(label="com.urbanairship.app.degraded")
stats = MyStats(filename="mmstats-test-mystats")
stats.degraded = True
stats.errors += 1
stats.cache_hits += 1000
assert stats.cache_hits == 1000
|
import os
import mmstats
import libgettid
class MyStats(mmstats.BaseMmStats):
pid = mmstats.StaticUIntField(label="sys.pid", value=os.getpid)
tid = mmstats.StaticInt64Field(label="sys.tid", value=libgettid.gettid)
uid = mmstats.StaticUInt64Field(label="sys.uid", value=os.getuid)
gid = mmstats.StaticUInt64Field(label="sys.gid", value=os.getgid)
errors = mmstats.UIntStat(label="com.urbanairship.app.errors")
warnings = mmstats.UIntStat(label="com.urbanairship.app.warnings")
queries = mmstats.UIntStat(label="com.urbanairship.app.queries")
cache_hits = mmstats.UIntStat(label="com.urbanairship.app.cache_hits")
cache_misses = mmstats.UIntStat(label="com.urbanairship.app.cache_misses")
degraded = mmstats.BoolStat(label="com.urbanairship.app.degraded")
stats = MyStats(filename="mmstats-test-mystats")
stats.degraded = True
stats.errors += 1
stats.cache_hits += 1000
stats.queries = 50
Make it more obvious that values initialize at 0import os
import mmstats
import libgettid
class MyStats(mmstats.BaseMmStats):
pid = mmstats.StaticUIntField(label="sys.pid", value=os.getpid)
tid = mmstats.StaticInt64Field(label="sys.tid", value=libgettid.gettid)
uid = mmstats.StaticUInt64Field(label="sys.uid", value=os.getuid)
gid = mmstats.StaticUInt64Field(label="sys.gid", value=os.getgid)
errors = mmstats.UIntStat(label="com.urbanairship.app.errors")
warnings = mmstats.UIntStat(label="com.urbanairship.app.warnings")
queries = mmstats.UIntStat(label="com.urbanairship.app.queries")
cache_hits = mmstats.UIntStat(label="com.urbanairship.app.cache_hits")
cache_misses = mmstats.UIntStat(label="com.urbanairship.app.cache_misses")
degraded = mmstats.BoolStat(label="com.urbanairship.app.degraded")
stats = MyStats(filename="mmstats-test-mystats")
stats.degraded = True
stats.errors += 1
stats.cache_hits += 1000
assert stats.cache_hits == 1000
|
<commit_before>import os
import mmstats
import libgettid
class MyStats(mmstats.BaseMmStats):
pid = mmstats.StaticUIntField(label="sys.pid", value=os.getpid)
tid = mmstats.StaticInt64Field(label="sys.tid", value=libgettid.gettid)
uid = mmstats.StaticUInt64Field(label="sys.uid", value=os.getuid)
gid = mmstats.StaticUInt64Field(label="sys.gid", value=os.getgid)
errors = mmstats.UIntStat(label="com.urbanairship.app.errors")
warnings = mmstats.UIntStat(label="com.urbanairship.app.warnings")
queries = mmstats.UIntStat(label="com.urbanairship.app.queries")
cache_hits = mmstats.UIntStat(label="com.urbanairship.app.cache_hits")
cache_misses = mmstats.UIntStat(label="com.urbanairship.app.cache_misses")
degraded = mmstats.BoolStat(label="com.urbanairship.app.degraded")
stats = MyStats(filename="mmstats-test-mystats")
stats.degraded = True
stats.errors += 1
stats.cache_hits += 1000
stats.queries = 50
<commit_msg>Make it more obvious that values initialize at 0<commit_after>import os
import mmstats
import libgettid
class MyStats(mmstats.BaseMmStats):
pid = mmstats.StaticUIntField(label="sys.pid", value=os.getpid)
tid = mmstats.StaticInt64Field(label="sys.tid", value=libgettid.gettid)
uid = mmstats.StaticUInt64Field(label="sys.uid", value=os.getuid)
gid = mmstats.StaticUInt64Field(label="sys.gid", value=os.getgid)
errors = mmstats.UIntStat(label="com.urbanairship.app.errors")
warnings = mmstats.UIntStat(label="com.urbanairship.app.warnings")
queries = mmstats.UIntStat(label="com.urbanairship.app.queries")
cache_hits = mmstats.UIntStat(label="com.urbanairship.app.cache_hits")
cache_misses = mmstats.UIntStat(label="com.urbanairship.app.cache_misses")
degraded = mmstats.BoolStat(label="com.urbanairship.app.degraded")
stats = MyStats(filename="mmstats-test-mystats")
stats.degraded = True
stats.errors += 1
stats.cache_hits += 1000
assert stats.cache_hits == 1000
|
906a5ee2b6e20b09b12d36d61271cd63cac49418
|
py2pack/utils.py
|
py2pack/utils.py
|
# -*- coding: utf-8 -*-
#
# Copyright (c) 2016, Thomas Bechtold <tbechtold@suse.com>
#
# 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 typing import List # noqa: F401, pylint: disable=unused-import
import tarfile
import zipfile
def _get_archive_filelist(filename):
# type: (str) -> List[str]
names = [] # type: List[str]
if tarfile.is_tarfile(filename):
with tarfile.open(filename) as tar_file:
names = sorted(tar_file.getnames())
elif zipfile.is_zipfile(filename):
with zipfile.ZipFile(filename) as zip_file:
names = sorted(zip_file.namelist())
else:
raise Exception("Can not get filenames from '%s'. "
"Not a tar or zip file" % filename)
if "./" in names:
names.remove("./")
return names
|
# -*- coding: utf-8 -*-
#
# Copyright (c) 2016, Thomas Bechtold <tbechtold@suse.com>
#
# 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 typing import List # noqa: F401, pylint: disable=unused-import
import tarfile
import zipfile
def _get_archive_filelist(filename):
# type: (str) -> List[str]
names = [] # type: List[str]
if tarfile.is_tarfile(filename):
with tarfile.open(filename) as tar_file:
names = sorted(tar_file.getnames())
elif zipfile.is_zipfile(filename):
with zipfile.ZipFile(filename) as zip_file:
names = sorted(zip_file.namelist())
else:
raise ValueError("Can not get filenames from '{!s}'. "
"Not a tar or zip file".format(filename))
if "./" in names:
names.remove("./")
return names
|
Raise a ValueError from _get_archive_filelist instead of Exception
|
Raise a ValueError from _get_archive_filelist instead of Exception
Raising the Exception base class is considered bad style, as the more
specialized child classes carry more information about the kind of error that
occurred. And often no-one actually tries to catch the Exception class.
|
Python
|
apache-2.0
|
saschpe/py2pack
|
# -*- coding: utf-8 -*-
#
# Copyright (c) 2016, Thomas Bechtold <tbechtold@suse.com>
#
# 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 typing import List # noqa: F401, pylint: disable=unused-import
import tarfile
import zipfile
def _get_archive_filelist(filename):
# type: (str) -> List[str]
names = [] # type: List[str]
if tarfile.is_tarfile(filename):
with tarfile.open(filename) as tar_file:
names = sorted(tar_file.getnames())
elif zipfile.is_zipfile(filename):
with zipfile.ZipFile(filename) as zip_file:
names = sorted(zip_file.namelist())
else:
raise Exception("Can not get filenames from '%s'. "
"Not a tar or zip file" % filename)
if "./" in names:
names.remove("./")
return names
Raise a ValueError from _get_archive_filelist instead of Exception
Raising the Exception base class is considered bad style, as the more
specialized child classes carry more information about the kind of error that
occurred. And often no-one actually tries to catch the Exception class.
|
# -*- coding: utf-8 -*-
#
# Copyright (c) 2016, Thomas Bechtold <tbechtold@suse.com>
#
# 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 typing import List # noqa: F401, pylint: disable=unused-import
import tarfile
import zipfile
def _get_archive_filelist(filename):
# type: (str) -> List[str]
names = [] # type: List[str]
if tarfile.is_tarfile(filename):
with tarfile.open(filename) as tar_file:
names = sorted(tar_file.getnames())
elif zipfile.is_zipfile(filename):
with zipfile.ZipFile(filename) as zip_file:
names = sorted(zip_file.namelist())
else:
raise ValueError("Can not get filenames from '{!s}'. "
"Not a tar or zip file".format(filename))
if "./" in names:
names.remove("./")
return names
|
<commit_before># -*- coding: utf-8 -*-
#
# Copyright (c) 2016, Thomas Bechtold <tbechtold@suse.com>
#
# 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 typing import List # noqa: F401, pylint: disable=unused-import
import tarfile
import zipfile
def _get_archive_filelist(filename):
# type: (str) -> List[str]
names = [] # type: List[str]
if tarfile.is_tarfile(filename):
with tarfile.open(filename) as tar_file:
names = sorted(tar_file.getnames())
elif zipfile.is_zipfile(filename):
with zipfile.ZipFile(filename) as zip_file:
names = sorted(zip_file.namelist())
else:
raise Exception("Can not get filenames from '%s'. "
"Not a tar or zip file" % filename)
if "./" in names:
names.remove("./")
return names
<commit_msg>Raise a ValueError from _get_archive_filelist instead of Exception
Raising the Exception base class is considered bad style, as the more
specialized child classes carry more information about the kind of error that
occurred. And often no-one actually tries to catch the Exception class.<commit_after>
|
# -*- coding: utf-8 -*-
#
# Copyright (c) 2016, Thomas Bechtold <tbechtold@suse.com>
#
# 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 typing import List # noqa: F401, pylint: disable=unused-import
import tarfile
import zipfile
def _get_archive_filelist(filename):
# type: (str) -> List[str]
names = [] # type: List[str]
if tarfile.is_tarfile(filename):
with tarfile.open(filename) as tar_file:
names = sorted(tar_file.getnames())
elif zipfile.is_zipfile(filename):
with zipfile.ZipFile(filename) as zip_file:
names = sorted(zip_file.namelist())
else:
raise ValueError("Can not get filenames from '{!s}'. "
"Not a tar or zip file".format(filename))
if "./" in names:
names.remove("./")
return names
|
# -*- coding: utf-8 -*-
#
# Copyright (c) 2016, Thomas Bechtold <tbechtold@suse.com>
#
# 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 typing import List # noqa: F401, pylint: disable=unused-import
import tarfile
import zipfile
def _get_archive_filelist(filename):
# type: (str) -> List[str]
names = [] # type: List[str]
if tarfile.is_tarfile(filename):
with tarfile.open(filename) as tar_file:
names = sorted(tar_file.getnames())
elif zipfile.is_zipfile(filename):
with zipfile.ZipFile(filename) as zip_file:
names = sorted(zip_file.namelist())
else:
raise Exception("Can not get filenames from '%s'. "
"Not a tar or zip file" % filename)
if "./" in names:
names.remove("./")
return names
Raise a ValueError from _get_archive_filelist instead of Exception
Raising the Exception base class is considered bad style, as the more
specialized child classes carry more information about the kind of error that
occurred. And often no-one actually tries to catch the Exception class.# -*- coding: utf-8 -*-
#
# Copyright (c) 2016, Thomas Bechtold <tbechtold@suse.com>
#
# 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 typing import List # noqa: F401, pylint: disable=unused-import
import tarfile
import zipfile
def _get_archive_filelist(filename):
# type: (str) -> List[str]
names = [] # type: List[str]
if tarfile.is_tarfile(filename):
with tarfile.open(filename) as tar_file:
names = sorted(tar_file.getnames())
elif zipfile.is_zipfile(filename):
with zipfile.ZipFile(filename) as zip_file:
names = sorted(zip_file.namelist())
else:
raise ValueError("Can not get filenames from '{!s}'. "
"Not a tar or zip file".format(filename))
if "./" in names:
names.remove("./")
return names
|
<commit_before># -*- coding: utf-8 -*-
#
# Copyright (c) 2016, Thomas Bechtold <tbechtold@suse.com>
#
# 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 typing import List # noqa: F401, pylint: disable=unused-import
import tarfile
import zipfile
def _get_archive_filelist(filename):
# type: (str) -> List[str]
names = [] # type: List[str]
if tarfile.is_tarfile(filename):
with tarfile.open(filename) as tar_file:
names = sorted(tar_file.getnames())
elif zipfile.is_zipfile(filename):
with zipfile.ZipFile(filename) as zip_file:
names = sorted(zip_file.namelist())
else:
raise Exception("Can not get filenames from '%s'. "
"Not a tar or zip file" % filename)
if "./" in names:
names.remove("./")
return names
<commit_msg>Raise a ValueError from _get_archive_filelist instead of Exception
Raising the Exception base class is considered bad style, as the more
specialized child classes carry more information about the kind of error that
occurred. And often no-one actually tries to catch the Exception class.<commit_after># -*- coding: utf-8 -*-
#
# Copyright (c) 2016, Thomas Bechtold <tbechtold@suse.com>
#
# 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 typing import List # noqa: F401, pylint: disable=unused-import
import tarfile
import zipfile
def _get_archive_filelist(filename):
# type: (str) -> List[str]
names = [] # type: List[str]
if tarfile.is_tarfile(filename):
with tarfile.open(filename) as tar_file:
names = sorted(tar_file.getnames())
elif zipfile.is_zipfile(filename):
with zipfile.ZipFile(filename) as zip_file:
names = sorted(zip_file.namelist())
else:
raise ValueError("Can not get filenames from '{!s}'. "
"Not a tar or zip file".format(filename))
if "./" in names:
names.remove("./")
return names
|
e26e3572a81e7ea3fd9ac4b3fd7f7739aa6c5779
|
pymt/__init__.py
|
pymt/__init__.py
|
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
|
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
# See https://github.com/numpy/numpy/blob/master/doc/release/1.14.0-notes.rst#many-changes-to-array-printing-disableable-with-the-new-legacy-printing-mode
import numpy as np
np.set_printoptions(legacy='1.13')
|
Use legacy docstrings with numpy 1.14
|
Use legacy docstrings with numpy 1.14
For an explanation, see https://github.com/numpy/numpy/blob/master/doc/release/1.14.0-notes.rst#many-changes-to-array-printing-disableable-with-the-new-legacy-printing-mode.
|
Python
|
mit
|
csdms/pymt,csdms/coupling,csdms/coupling
|
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
Use legacy docstrings with numpy 1.14
For an explanation, see https://github.com/numpy/numpy/blob/master/doc/release/1.14.0-notes.rst#many-changes-to-array-printing-disableable-with-the-new-legacy-printing-mode.
|
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
# See https://github.com/numpy/numpy/blob/master/doc/release/1.14.0-notes.rst#many-changes-to-array-printing-disableable-with-the-new-legacy-printing-mode
import numpy as np
np.set_printoptions(legacy='1.13')
|
<commit_before>from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
<commit_msg>Use legacy docstrings with numpy 1.14
For an explanation, see https://github.com/numpy/numpy/blob/master/doc/release/1.14.0-notes.rst#many-changes-to-array-printing-disableable-with-the-new-legacy-printing-mode.<commit_after>
|
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
# See https://github.com/numpy/numpy/blob/master/doc/release/1.14.0-notes.rst#many-changes-to-array-printing-disableable-with-the-new-legacy-printing-mode
import numpy as np
np.set_printoptions(legacy='1.13')
|
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
Use legacy docstrings with numpy 1.14
For an explanation, see https://github.com/numpy/numpy/blob/master/doc/release/1.14.0-notes.rst#many-changes-to-array-printing-disableable-with-the-new-legacy-printing-mode.from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
# See https://github.com/numpy/numpy/blob/master/doc/release/1.14.0-notes.rst#many-changes-to-array-printing-disableable-with-the-new-legacy-printing-mode
import numpy as np
np.set_printoptions(legacy='1.13')
|
<commit_before>from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
<commit_msg>Use legacy docstrings with numpy 1.14
For an explanation, see https://github.com/numpy/numpy/blob/master/doc/release/1.14.0-notes.rst#many-changes-to-array-printing-disableable-with-the-new-legacy-printing-mode.<commit_after>from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
# See https://github.com/numpy/numpy/blob/master/doc/release/1.14.0-notes.rst#many-changes-to-array-printing-disableable-with-the-new-legacy-printing-mode
import numpy as np
np.set_printoptions(legacy='1.13')
|
53aa7104616944f6206f8e2cd3684b0084158a11
|
fabfile.py
|
fabfile.py
|
from fabric.api import env, cd, run, shell_env, sudo
env.hosts = ['134.213.147.235']
env.user = 'root'
env.key_filename = '~/.ssh/id_di'
env.forward_agent = True
def deploy():
with cd('/srv/venv/mysite'):
run('git pull')
with cd('mysite'), shell_env(DJANGO_CONFIGURATION='Production'):
sudo(' ../../bin/python manage.py collectstatic --noinput',
user="pydev")
run('apachectl graceful')
|
from fabric.api import env, cd, run, shell_env, sudo
env.hosts = ['134.213.147.235']
env.user = 'root'
env.key_filename = '~/.ssh/id_di'
env.forward_agent = True
def deploy():
with cd('/srv/venv/mysite'):
run('git pull')
with cd('mysite'), shell_env(DJANGO_CONFIGURATION='Production'):
sudo(' ../../bin/python manage.py collectstatic --noinput',
user="pydev")
run('apachectl graceful')
def builddb():
with cd('/srv/venv/mysite/mysite'):
with shell_env(DJANGO_CONFIGURATION='Production'):
sudo("echo 'drop database app_data;create database app_data' | ../../bin/python manage.py dbshell",
user="pydev")
sudo(' ../../bin/python manage.py migrate',
user="pydev")
sudo(' ../../bin/python manage.py runscript setup_test_data',
user="pydev")
|
Add fab task to rebuild production database
|
Add fab task to rebuild production database
|
Python
|
bsd-3-clause
|
Kvoti/ditto,Kvoti/ditto,Kvoti/ditto,Kvoti/ditto,Kvoti/ditto
|
from fabric.api import env, cd, run, shell_env, sudo
env.hosts = ['134.213.147.235']
env.user = 'root'
env.key_filename = '~/.ssh/id_di'
env.forward_agent = True
def deploy():
with cd('/srv/venv/mysite'):
run('git pull')
with cd('mysite'), shell_env(DJANGO_CONFIGURATION='Production'):
sudo(' ../../bin/python manage.py collectstatic --noinput',
user="pydev")
run('apachectl graceful')
Add fab task to rebuild production database
|
from fabric.api import env, cd, run, shell_env, sudo
env.hosts = ['134.213.147.235']
env.user = 'root'
env.key_filename = '~/.ssh/id_di'
env.forward_agent = True
def deploy():
with cd('/srv/venv/mysite'):
run('git pull')
with cd('mysite'), shell_env(DJANGO_CONFIGURATION='Production'):
sudo(' ../../bin/python manage.py collectstatic --noinput',
user="pydev")
run('apachectl graceful')
def builddb():
with cd('/srv/venv/mysite/mysite'):
with shell_env(DJANGO_CONFIGURATION='Production'):
sudo("echo 'drop database app_data;create database app_data' | ../../bin/python manage.py dbshell",
user="pydev")
sudo(' ../../bin/python manage.py migrate',
user="pydev")
sudo(' ../../bin/python manage.py runscript setup_test_data',
user="pydev")
|
<commit_before>from fabric.api import env, cd, run, shell_env, sudo
env.hosts = ['134.213.147.235']
env.user = 'root'
env.key_filename = '~/.ssh/id_di'
env.forward_agent = True
def deploy():
with cd('/srv/venv/mysite'):
run('git pull')
with cd('mysite'), shell_env(DJANGO_CONFIGURATION='Production'):
sudo(' ../../bin/python manage.py collectstatic --noinput',
user="pydev")
run('apachectl graceful')
<commit_msg>Add fab task to rebuild production database<commit_after>
|
from fabric.api import env, cd, run, shell_env, sudo
env.hosts = ['134.213.147.235']
env.user = 'root'
env.key_filename = '~/.ssh/id_di'
env.forward_agent = True
def deploy():
with cd('/srv/venv/mysite'):
run('git pull')
with cd('mysite'), shell_env(DJANGO_CONFIGURATION='Production'):
sudo(' ../../bin/python manage.py collectstatic --noinput',
user="pydev")
run('apachectl graceful')
def builddb():
with cd('/srv/venv/mysite/mysite'):
with shell_env(DJANGO_CONFIGURATION='Production'):
sudo("echo 'drop database app_data;create database app_data' | ../../bin/python manage.py dbshell",
user="pydev")
sudo(' ../../bin/python manage.py migrate',
user="pydev")
sudo(' ../../bin/python manage.py runscript setup_test_data',
user="pydev")
|
from fabric.api import env, cd, run, shell_env, sudo
env.hosts = ['134.213.147.235']
env.user = 'root'
env.key_filename = '~/.ssh/id_di'
env.forward_agent = True
def deploy():
with cd('/srv/venv/mysite'):
run('git pull')
with cd('mysite'), shell_env(DJANGO_CONFIGURATION='Production'):
sudo(' ../../bin/python manage.py collectstatic --noinput',
user="pydev")
run('apachectl graceful')
Add fab task to rebuild production databasefrom fabric.api import env, cd, run, shell_env, sudo
env.hosts = ['134.213.147.235']
env.user = 'root'
env.key_filename = '~/.ssh/id_di'
env.forward_agent = True
def deploy():
with cd('/srv/venv/mysite'):
run('git pull')
with cd('mysite'), shell_env(DJANGO_CONFIGURATION='Production'):
sudo(' ../../bin/python manage.py collectstatic --noinput',
user="pydev")
run('apachectl graceful')
def builddb():
with cd('/srv/venv/mysite/mysite'):
with shell_env(DJANGO_CONFIGURATION='Production'):
sudo("echo 'drop database app_data;create database app_data' | ../../bin/python manage.py dbshell",
user="pydev")
sudo(' ../../bin/python manage.py migrate',
user="pydev")
sudo(' ../../bin/python manage.py runscript setup_test_data',
user="pydev")
|
<commit_before>from fabric.api import env, cd, run, shell_env, sudo
env.hosts = ['134.213.147.235']
env.user = 'root'
env.key_filename = '~/.ssh/id_di'
env.forward_agent = True
def deploy():
with cd('/srv/venv/mysite'):
run('git pull')
with cd('mysite'), shell_env(DJANGO_CONFIGURATION='Production'):
sudo(' ../../bin/python manage.py collectstatic --noinput',
user="pydev")
run('apachectl graceful')
<commit_msg>Add fab task to rebuild production database<commit_after>from fabric.api import env, cd, run, shell_env, sudo
env.hosts = ['134.213.147.235']
env.user = 'root'
env.key_filename = '~/.ssh/id_di'
env.forward_agent = True
def deploy():
with cd('/srv/venv/mysite'):
run('git pull')
with cd('mysite'), shell_env(DJANGO_CONFIGURATION='Production'):
sudo(' ../../bin/python manage.py collectstatic --noinput',
user="pydev")
run('apachectl graceful')
def builddb():
with cd('/srv/venv/mysite/mysite'):
with shell_env(DJANGO_CONFIGURATION='Production'):
sudo("echo 'drop database app_data;create database app_data' | ../../bin/python manage.py dbshell",
user="pydev")
sudo(' ../../bin/python manage.py migrate',
user="pydev")
sudo(' ../../bin/python manage.py runscript setup_test_data',
user="pydev")
|
8dcf5b2c85430a09502649bb3bb95c7b56312c03
|
pysearch/urls.py
|
pysearch/urls.py
|
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'pysearch.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
)
|
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'pysearch.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^search/', include('search.urls')),
)
|
Connect search route to app
|
Connect search route to app
|
Python
|
mit
|
nh0815/PySearch,nh0815/PySearch
|
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'pysearch.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
)
Connect search route to app
|
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'pysearch.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^search/', include('search.urls')),
)
|
<commit_before>from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'pysearch.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
)
<commit_msg>Connect search route to app<commit_after>
|
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'pysearch.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^search/', include('search.urls')),
)
|
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'pysearch.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
)
Connect search route to appfrom django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'pysearch.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^search/', include('search.urls')),
)
|
<commit_before>from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'pysearch.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
)
<commit_msg>Connect search route to app<commit_after>from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'pysearch.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^search/', include('search.urls')),
)
|
8025b6cad403ace01eb71af05d284d5fa0fa4ff7
|
pandoc-figref.py
|
pandoc-figref.py
|
#! /usr/bin/env python3
"""Pandoc filter that replaces labels of format {#?:???}, where ? is a
single lower case character defining the type and ??? is an alphanumeric
label, with numbers. Different types are counted separately.
"""
from pandocfilters import toJSONFilter, Str
import re
REF_PAT = re.compile('(.*)\{#([a-z]):(\w*)\}(.*)')
known_labels = {}
def figref(key, val, fmt, meta):
if key == 'Str' and REF_PAT.match(val):
start, kind, label, end = REF_PAT.match(val).groups()
if kind in known_labels:
if label not in known_labels[kind]:
known_labels[kind][label] = str(len(known_labels[kind])\
+ 1)
else:
known_labels[kind] = {}
known_labels[kind][label] = "1"
return [Str(start)] + [Str(known_labels[kind][label])] + \
[Str(end)]
if __name__ == '__main__':
toJSONFilter(figref)
|
#! /usr/bin/env python3
"""Pandoc filter that replaces labels of format {#?:???}, where ? is a
single lower case character defining the type and ??? is an alphanumeric
label, with numbers. Different types are counted separately.
"""
from pandocfilters import toJSONFilter, Str
import re
REF_PAT = re.compile('(.*)\{#([a-z]):(\w*)\}(.*)')
known_labels = {}
def figref(key, val, fmt, meta):
if key == 'Str' and REF_PAT.match(val):
start, kind, label, end = REF_PAT.match(val).groups()
if kind in known_labels:
if label not in known_labels[kind]:
known_labels[kind][label] = str(len(known_labels[kind])\
+ 1)
else:
known_labels[kind] = {}
known_labels[kind][label] = "1"
return [Str(start)] + [Str(known_labels[kind][label])] + \
[Str(end)] + [Str(" ")]
if __name__ == '__main__':
toJSONFilter(figref)
|
Fix issue with missing space after replacement
|
Fix issue with missing space after replacement
|
Python
|
mit
|
scotthartley/pandoc-figref
|
#! /usr/bin/env python3
"""Pandoc filter that replaces labels of format {#?:???}, where ? is a
single lower case character defining the type and ??? is an alphanumeric
label, with numbers. Different types are counted separately.
"""
from pandocfilters import toJSONFilter, Str
import re
REF_PAT = re.compile('(.*)\{#([a-z]):(\w*)\}(.*)')
known_labels = {}
def figref(key, val, fmt, meta):
if key == 'Str' and REF_PAT.match(val):
start, kind, label, end = REF_PAT.match(val).groups()
if kind in known_labels:
if label not in known_labels[kind]:
known_labels[kind][label] = str(len(known_labels[kind])\
+ 1)
else:
known_labels[kind] = {}
known_labels[kind][label] = "1"
return [Str(start)] + [Str(known_labels[kind][label])] + \
[Str(end)]
if __name__ == '__main__':
toJSONFilter(figref)Fix issue with missing space after replacement
|
#! /usr/bin/env python3
"""Pandoc filter that replaces labels of format {#?:???}, where ? is a
single lower case character defining the type and ??? is an alphanumeric
label, with numbers. Different types are counted separately.
"""
from pandocfilters import toJSONFilter, Str
import re
REF_PAT = re.compile('(.*)\{#([a-z]):(\w*)\}(.*)')
known_labels = {}
def figref(key, val, fmt, meta):
if key == 'Str' and REF_PAT.match(val):
start, kind, label, end = REF_PAT.match(val).groups()
if kind in known_labels:
if label not in known_labels[kind]:
known_labels[kind][label] = str(len(known_labels[kind])\
+ 1)
else:
known_labels[kind] = {}
known_labels[kind][label] = "1"
return [Str(start)] + [Str(known_labels[kind][label])] + \
[Str(end)] + [Str(" ")]
if __name__ == '__main__':
toJSONFilter(figref)
|
<commit_before>#! /usr/bin/env python3
"""Pandoc filter that replaces labels of format {#?:???}, where ? is a
single lower case character defining the type and ??? is an alphanumeric
label, with numbers. Different types are counted separately.
"""
from pandocfilters import toJSONFilter, Str
import re
REF_PAT = re.compile('(.*)\{#([a-z]):(\w*)\}(.*)')
known_labels = {}
def figref(key, val, fmt, meta):
if key == 'Str' and REF_PAT.match(val):
start, kind, label, end = REF_PAT.match(val).groups()
if kind in known_labels:
if label not in known_labels[kind]:
known_labels[kind][label] = str(len(known_labels[kind])\
+ 1)
else:
known_labels[kind] = {}
known_labels[kind][label] = "1"
return [Str(start)] + [Str(known_labels[kind][label])] + \
[Str(end)]
if __name__ == '__main__':
toJSONFilter(figref)<commit_msg>Fix issue with missing space after replacement<commit_after>
|
#! /usr/bin/env python3
"""Pandoc filter that replaces labels of format {#?:???}, where ? is a
single lower case character defining the type and ??? is an alphanumeric
label, with numbers. Different types are counted separately.
"""
from pandocfilters import toJSONFilter, Str
import re
REF_PAT = re.compile('(.*)\{#([a-z]):(\w*)\}(.*)')
known_labels = {}
def figref(key, val, fmt, meta):
if key == 'Str' and REF_PAT.match(val):
start, kind, label, end = REF_PAT.match(val).groups()
if kind in known_labels:
if label not in known_labels[kind]:
known_labels[kind][label] = str(len(known_labels[kind])\
+ 1)
else:
known_labels[kind] = {}
known_labels[kind][label] = "1"
return [Str(start)] + [Str(known_labels[kind][label])] + \
[Str(end)] + [Str(" ")]
if __name__ == '__main__':
toJSONFilter(figref)
|
#! /usr/bin/env python3
"""Pandoc filter that replaces labels of format {#?:???}, where ? is a
single lower case character defining the type and ??? is an alphanumeric
label, with numbers. Different types are counted separately.
"""
from pandocfilters import toJSONFilter, Str
import re
REF_PAT = re.compile('(.*)\{#([a-z]):(\w*)\}(.*)')
known_labels = {}
def figref(key, val, fmt, meta):
if key == 'Str' and REF_PAT.match(val):
start, kind, label, end = REF_PAT.match(val).groups()
if kind in known_labels:
if label not in known_labels[kind]:
known_labels[kind][label] = str(len(known_labels[kind])\
+ 1)
else:
known_labels[kind] = {}
known_labels[kind][label] = "1"
return [Str(start)] + [Str(known_labels[kind][label])] + \
[Str(end)]
if __name__ == '__main__':
toJSONFilter(figref)Fix issue with missing space after replacement#! /usr/bin/env python3
"""Pandoc filter that replaces labels of format {#?:???}, where ? is a
single lower case character defining the type and ??? is an alphanumeric
label, with numbers. Different types are counted separately.
"""
from pandocfilters import toJSONFilter, Str
import re
REF_PAT = re.compile('(.*)\{#([a-z]):(\w*)\}(.*)')
known_labels = {}
def figref(key, val, fmt, meta):
if key == 'Str' and REF_PAT.match(val):
start, kind, label, end = REF_PAT.match(val).groups()
if kind in known_labels:
if label not in known_labels[kind]:
known_labels[kind][label] = str(len(known_labels[kind])\
+ 1)
else:
known_labels[kind] = {}
known_labels[kind][label] = "1"
return [Str(start)] + [Str(known_labels[kind][label])] + \
[Str(end)] + [Str(" ")]
if __name__ == '__main__':
toJSONFilter(figref)
|
<commit_before>#! /usr/bin/env python3
"""Pandoc filter that replaces labels of format {#?:???}, where ? is a
single lower case character defining the type and ??? is an alphanumeric
label, with numbers. Different types are counted separately.
"""
from pandocfilters import toJSONFilter, Str
import re
REF_PAT = re.compile('(.*)\{#([a-z]):(\w*)\}(.*)')
known_labels = {}
def figref(key, val, fmt, meta):
if key == 'Str' and REF_PAT.match(val):
start, kind, label, end = REF_PAT.match(val).groups()
if kind in known_labels:
if label not in known_labels[kind]:
known_labels[kind][label] = str(len(known_labels[kind])\
+ 1)
else:
known_labels[kind] = {}
known_labels[kind][label] = "1"
return [Str(start)] + [Str(known_labels[kind][label])] + \
[Str(end)]
if __name__ == '__main__':
toJSONFilter(figref)<commit_msg>Fix issue with missing space after replacement<commit_after>#! /usr/bin/env python3
"""Pandoc filter that replaces labels of format {#?:???}, where ? is a
single lower case character defining the type and ??? is an alphanumeric
label, with numbers. Different types are counted separately.
"""
from pandocfilters import toJSONFilter, Str
import re
REF_PAT = re.compile('(.*)\{#([a-z]):(\w*)\}(.*)')
known_labels = {}
def figref(key, val, fmt, meta):
if key == 'Str' and REF_PAT.match(val):
start, kind, label, end = REF_PAT.match(val).groups()
if kind in known_labels:
if label not in known_labels[kind]:
known_labels[kind][label] = str(len(known_labels[kind])\
+ 1)
else:
known_labels[kind] = {}
known_labels[kind][label] = "1"
return [Str(start)] + [Str(known_labels[kind][label])] + \
[Str(end)] + [Str(" ")]
if __name__ == '__main__':
toJSONFilter(figref)
|
43612c86a3040de857e73bcc8ba7d24bde5a6a43
|
pgcli/pgstyle.py
|
pgcli/pgstyle.py
|
from pygments.token import Token
from pygments.style import Style
from pygments.util import ClassNotFound
from prompt_toolkit.styles import default_style_extensions
import pygments.styles
def style_factory(name):
try:
style = pygments.styles.get_style_by_name(name)
except ClassNotFound:
style = pygments.styles.get_style_by_name('native')
class PGStyle(Style):
styles = {}
styles.update(style.styles)
styles.update(default_style_extensions)
styles.update({
Token.Menu.Completions.Completion.Current: 'bg:#00aaaa #000000',
Token.Menu.Completions.Completion: 'bg:#008888 #ffffff',
Token.Menu.Completions.ProgressButton: 'bg:#003333',
Token.Menu.Completions.ProgressBar: 'bg:#00aaaa',
Token.SelectedText: '#ffffff bg:#6666aa',
Token.IncrementalSearchMatch: '#ffffff bg:#4444aa',
Token.IncrementalSearchMatch.Current: '#ffffff bg:#44aa44',
Token.Toolbar: 'bg:#440044 #ffffff',
Token.Toolbar: 'bg:#222222 #aaaaaa',
Token.Toolbar.Off: 'bg:#222222 #888888',
Token.Toolbar.On: 'bg:#222222 #ffffff',
})
return PGStyle
|
from pygments.token import Token
from pygments.style import Style
from pygments.util import ClassNotFound
from prompt_toolkit.styles import default_style_extensions
import pygments.styles
def style_factory(name):
try:
style = pygments.styles.get_style_by_name(name)
except ClassNotFound:
style = pygments.styles.get_style_by_name('native')
class PGStyle(Style):
styles = {}
styles.update(style.styles)
styles.update(default_style_extensions)
styles.update({
Token.Menu.Completions.Completion.Current: 'bg:#00aaaa #000000',
Token.Menu.Completions.Completion: 'bg:#008888 #ffffff',
Token.Menu.Completions.Meta.Current: 'bg:#00aaaa #000000',
Token.Menu.Completions.Meta: 'bg:#008888 #ffffff',
Token.Menu.Completions.ProgressButton: 'bg:#003333',
Token.Menu.Completions.ProgressBar: 'bg:#00aaaa',
Token.SelectedText: '#ffffff bg:#6666aa',
Token.IncrementalSearchMatch: '#ffffff bg:#4444aa',
Token.IncrementalSearchMatch.Current: '#ffffff bg:#44aa44',
Token.Toolbar: 'bg:#440044 #ffffff',
Token.Toolbar: 'bg:#222222 #aaaaaa',
Token.Toolbar.Off: 'bg:#222222 #888888',
Token.Toolbar.On: 'bg:#222222 #ffffff',
})
return PGStyle
|
Set completions meta-text styling to match
|
Set completions meta-text styling to match
|
Python
|
bsd-3-clause
|
nosun/pgcli,TamasNo1/pgcli,zhiyuanshi/pgcli,dbcli/pgcli,nosun/pgcli,lk1ngaa7/pgcli,d33tah/pgcli,joewalnes/pgcli,joewalnes/pgcli,dbcli/vcli,janusnic/pgcli,suzukaze/pgcli,n-someya/pgcli,zhiyuanshi/pgcli,w4ngyi/pgcli,darikg/pgcli,d33tah/pgcli,janusnic/pgcli,w4ngyi/pgcli,koljonen/pgcli,koljonen/pgcli,suzukaze/pgcli,n-someya/pgcli,dbcli/pgcli,dbcli/vcli,johshoff/pgcli,yx91490/pgcli,TamasNo1/pgcli,lk1ngaa7/pgcli,darikg/pgcli,johshoff/pgcli,yx91490/pgcli
|
from pygments.token import Token
from pygments.style import Style
from pygments.util import ClassNotFound
from prompt_toolkit.styles import default_style_extensions
import pygments.styles
def style_factory(name):
try:
style = pygments.styles.get_style_by_name(name)
except ClassNotFound:
style = pygments.styles.get_style_by_name('native')
class PGStyle(Style):
styles = {}
styles.update(style.styles)
styles.update(default_style_extensions)
styles.update({
Token.Menu.Completions.Completion.Current: 'bg:#00aaaa #000000',
Token.Menu.Completions.Completion: 'bg:#008888 #ffffff',
Token.Menu.Completions.ProgressButton: 'bg:#003333',
Token.Menu.Completions.ProgressBar: 'bg:#00aaaa',
Token.SelectedText: '#ffffff bg:#6666aa',
Token.IncrementalSearchMatch: '#ffffff bg:#4444aa',
Token.IncrementalSearchMatch.Current: '#ffffff bg:#44aa44',
Token.Toolbar: 'bg:#440044 #ffffff',
Token.Toolbar: 'bg:#222222 #aaaaaa',
Token.Toolbar.Off: 'bg:#222222 #888888',
Token.Toolbar.On: 'bg:#222222 #ffffff',
})
return PGStyle
Set completions meta-text styling to match
|
from pygments.token import Token
from pygments.style import Style
from pygments.util import ClassNotFound
from prompt_toolkit.styles import default_style_extensions
import pygments.styles
def style_factory(name):
try:
style = pygments.styles.get_style_by_name(name)
except ClassNotFound:
style = pygments.styles.get_style_by_name('native')
class PGStyle(Style):
styles = {}
styles.update(style.styles)
styles.update(default_style_extensions)
styles.update({
Token.Menu.Completions.Completion.Current: 'bg:#00aaaa #000000',
Token.Menu.Completions.Completion: 'bg:#008888 #ffffff',
Token.Menu.Completions.Meta.Current: 'bg:#00aaaa #000000',
Token.Menu.Completions.Meta: 'bg:#008888 #ffffff',
Token.Menu.Completions.ProgressButton: 'bg:#003333',
Token.Menu.Completions.ProgressBar: 'bg:#00aaaa',
Token.SelectedText: '#ffffff bg:#6666aa',
Token.IncrementalSearchMatch: '#ffffff bg:#4444aa',
Token.IncrementalSearchMatch.Current: '#ffffff bg:#44aa44',
Token.Toolbar: 'bg:#440044 #ffffff',
Token.Toolbar: 'bg:#222222 #aaaaaa',
Token.Toolbar.Off: 'bg:#222222 #888888',
Token.Toolbar.On: 'bg:#222222 #ffffff',
})
return PGStyle
|
<commit_before>from pygments.token import Token
from pygments.style import Style
from pygments.util import ClassNotFound
from prompt_toolkit.styles import default_style_extensions
import pygments.styles
def style_factory(name):
try:
style = pygments.styles.get_style_by_name(name)
except ClassNotFound:
style = pygments.styles.get_style_by_name('native')
class PGStyle(Style):
styles = {}
styles.update(style.styles)
styles.update(default_style_extensions)
styles.update({
Token.Menu.Completions.Completion.Current: 'bg:#00aaaa #000000',
Token.Menu.Completions.Completion: 'bg:#008888 #ffffff',
Token.Menu.Completions.ProgressButton: 'bg:#003333',
Token.Menu.Completions.ProgressBar: 'bg:#00aaaa',
Token.SelectedText: '#ffffff bg:#6666aa',
Token.IncrementalSearchMatch: '#ffffff bg:#4444aa',
Token.IncrementalSearchMatch.Current: '#ffffff bg:#44aa44',
Token.Toolbar: 'bg:#440044 #ffffff',
Token.Toolbar: 'bg:#222222 #aaaaaa',
Token.Toolbar.Off: 'bg:#222222 #888888',
Token.Toolbar.On: 'bg:#222222 #ffffff',
})
return PGStyle
<commit_msg>Set completions meta-text styling to match<commit_after>
|
from pygments.token import Token
from pygments.style import Style
from pygments.util import ClassNotFound
from prompt_toolkit.styles import default_style_extensions
import pygments.styles
def style_factory(name):
try:
style = pygments.styles.get_style_by_name(name)
except ClassNotFound:
style = pygments.styles.get_style_by_name('native')
class PGStyle(Style):
styles = {}
styles.update(style.styles)
styles.update(default_style_extensions)
styles.update({
Token.Menu.Completions.Completion.Current: 'bg:#00aaaa #000000',
Token.Menu.Completions.Completion: 'bg:#008888 #ffffff',
Token.Menu.Completions.Meta.Current: 'bg:#00aaaa #000000',
Token.Menu.Completions.Meta: 'bg:#008888 #ffffff',
Token.Menu.Completions.ProgressButton: 'bg:#003333',
Token.Menu.Completions.ProgressBar: 'bg:#00aaaa',
Token.SelectedText: '#ffffff bg:#6666aa',
Token.IncrementalSearchMatch: '#ffffff bg:#4444aa',
Token.IncrementalSearchMatch.Current: '#ffffff bg:#44aa44',
Token.Toolbar: 'bg:#440044 #ffffff',
Token.Toolbar: 'bg:#222222 #aaaaaa',
Token.Toolbar.Off: 'bg:#222222 #888888',
Token.Toolbar.On: 'bg:#222222 #ffffff',
})
return PGStyle
|
from pygments.token import Token
from pygments.style import Style
from pygments.util import ClassNotFound
from prompt_toolkit.styles import default_style_extensions
import pygments.styles
def style_factory(name):
try:
style = pygments.styles.get_style_by_name(name)
except ClassNotFound:
style = pygments.styles.get_style_by_name('native')
class PGStyle(Style):
styles = {}
styles.update(style.styles)
styles.update(default_style_extensions)
styles.update({
Token.Menu.Completions.Completion.Current: 'bg:#00aaaa #000000',
Token.Menu.Completions.Completion: 'bg:#008888 #ffffff',
Token.Menu.Completions.ProgressButton: 'bg:#003333',
Token.Menu.Completions.ProgressBar: 'bg:#00aaaa',
Token.SelectedText: '#ffffff bg:#6666aa',
Token.IncrementalSearchMatch: '#ffffff bg:#4444aa',
Token.IncrementalSearchMatch.Current: '#ffffff bg:#44aa44',
Token.Toolbar: 'bg:#440044 #ffffff',
Token.Toolbar: 'bg:#222222 #aaaaaa',
Token.Toolbar.Off: 'bg:#222222 #888888',
Token.Toolbar.On: 'bg:#222222 #ffffff',
})
return PGStyle
Set completions meta-text styling to matchfrom pygments.token import Token
from pygments.style import Style
from pygments.util import ClassNotFound
from prompt_toolkit.styles import default_style_extensions
import pygments.styles
def style_factory(name):
try:
style = pygments.styles.get_style_by_name(name)
except ClassNotFound:
style = pygments.styles.get_style_by_name('native')
class PGStyle(Style):
styles = {}
styles.update(style.styles)
styles.update(default_style_extensions)
styles.update({
Token.Menu.Completions.Completion.Current: 'bg:#00aaaa #000000',
Token.Menu.Completions.Completion: 'bg:#008888 #ffffff',
Token.Menu.Completions.Meta.Current: 'bg:#00aaaa #000000',
Token.Menu.Completions.Meta: 'bg:#008888 #ffffff',
Token.Menu.Completions.ProgressButton: 'bg:#003333',
Token.Menu.Completions.ProgressBar: 'bg:#00aaaa',
Token.SelectedText: '#ffffff bg:#6666aa',
Token.IncrementalSearchMatch: '#ffffff bg:#4444aa',
Token.IncrementalSearchMatch.Current: '#ffffff bg:#44aa44',
Token.Toolbar: 'bg:#440044 #ffffff',
Token.Toolbar: 'bg:#222222 #aaaaaa',
Token.Toolbar.Off: 'bg:#222222 #888888',
Token.Toolbar.On: 'bg:#222222 #ffffff',
})
return PGStyle
|
<commit_before>from pygments.token import Token
from pygments.style import Style
from pygments.util import ClassNotFound
from prompt_toolkit.styles import default_style_extensions
import pygments.styles
def style_factory(name):
try:
style = pygments.styles.get_style_by_name(name)
except ClassNotFound:
style = pygments.styles.get_style_by_name('native')
class PGStyle(Style):
styles = {}
styles.update(style.styles)
styles.update(default_style_extensions)
styles.update({
Token.Menu.Completions.Completion.Current: 'bg:#00aaaa #000000',
Token.Menu.Completions.Completion: 'bg:#008888 #ffffff',
Token.Menu.Completions.ProgressButton: 'bg:#003333',
Token.Menu.Completions.ProgressBar: 'bg:#00aaaa',
Token.SelectedText: '#ffffff bg:#6666aa',
Token.IncrementalSearchMatch: '#ffffff bg:#4444aa',
Token.IncrementalSearchMatch.Current: '#ffffff bg:#44aa44',
Token.Toolbar: 'bg:#440044 #ffffff',
Token.Toolbar: 'bg:#222222 #aaaaaa',
Token.Toolbar.Off: 'bg:#222222 #888888',
Token.Toolbar.On: 'bg:#222222 #ffffff',
})
return PGStyle
<commit_msg>Set completions meta-text styling to match<commit_after>from pygments.token import Token
from pygments.style import Style
from pygments.util import ClassNotFound
from prompt_toolkit.styles import default_style_extensions
import pygments.styles
def style_factory(name):
try:
style = pygments.styles.get_style_by_name(name)
except ClassNotFound:
style = pygments.styles.get_style_by_name('native')
class PGStyle(Style):
styles = {}
styles.update(style.styles)
styles.update(default_style_extensions)
styles.update({
Token.Menu.Completions.Completion.Current: 'bg:#00aaaa #000000',
Token.Menu.Completions.Completion: 'bg:#008888 #ffffff',
Token.Menu.Completions.Meta.Current: 'bg:#00aaaa #000000',
Token.Menu.Completions.Meta: 'bg:#008888 #ffffff',
Token.Menu.Completions.ProgressButton: 'bg:#003333',
Token.Menu.Completions.ProgressBar: 'bg:#00aaaa',
Token.SelectedText: '#ffffff bg:#6666aa',
Token.IncrementalSearchMatch: '#ffffff bg:#4444aa',
Token.IncrementalSearchMatch.Current: '#ffffff bg:#44aa44',
Token.Toolbar: 'bg:#440044 #ffffff',
Token.Toolbar: 'bg:#222222 #aaaaaa',
Token.Toolbar.Off: 'bg:#222222 #888888',
Token.Toolbar.On: 'bg:#222222 #ffffff',
})
return PGStyle
|
8b33e63ab84e2da2168259d8ce17c8afac964500
|
cacheops/management/commands/cleanfilecache.py
|
cacheops/management/commands/cleanfilecache.py
|
import os
from django.core.management.base import BaseCommand
from cacheops.conf import settings
class Command(BaseCommand):
help = 'Clean filebased cache'
def handle(self, **options):
os.system('find %s -type f \! -iname "\." -mmin +0 -delete' % settings.FILE_CACHE_DIR)
|
import os
from django.core.management.base import BaseCommand
from cacheops.conf import settings
class Command(BaseCommand):
help = 'Clean filebased cache'
def add_arguments(self, parser):
parser.add_argument('path', nargs='*', default=['default'])
def handle(self, **options):
for path in options['path']:
if path == 'default':
path = settings.FILE_CACHE_DIR
os.system('find %s -type f \! -iname "\." -mmin +0 -delete' % path)
|
Allow cleaning file cache in non default place
|
Allow cleaning file cache in non default place
|
Python
|
bsd-3-clause
|
LPgenerator/django-cacheops,Suor/django-cacheops
|
import os
from django.core.management.base import BaseCommand
from cacheops.conf import settings
class Command(BaseCommand):
help = 'Clean filebased cache'
def handle(self, **options):
os.system('find %s -type f \! -iname "\." -mmin +0 -delete' % settings.FILE_CACHE_DIR)
Allow cleaning file cache in non default place
|
import os
from django.core.management.base import BaseCommand
from cacheops.conf import settings
class Command(BaseCommand):
help = 'Clean filebased cache'
def add_arguments(self, parser):
parser.add_argument('path', nargs='*', default=['default'])
def handle(self, **options):
for path in options['path']:
if path == 'default':
path = settings.FILE_CACHE_DIR
os.system('find %s -type f \! -iname "\." -mmin +0 -delete' % path)
|
<commit_before>import os
from django.core.management.base import BaseCommand
from cacheops.conf import settings
class Command(BaseCommand):
help = 'Clean filebased cache'
def handle(self, **options):
os.system('find %s -type f \! -iname "\." -mmin +0 -delete' % settings.FILE_CACHE_DIR)
<commit_msg>Allow cleaning file cache in non default place<commit_after>
|
import os
from django.core.management.base import BaseCommand
from cacheops.conf import settings
class Command(BaseCommand):
help = 'Clean filebased cache'
def add_arguments(self, parser):
parser.add_argument('path', nargs='*', default=['default'])
def handle(self, **options):
for path in options['path']:
if path == 'default':
path = settings.FILE_CACHE_DIR
os.system('find %s -type f \! -iname "\." -mmin +0 -delete' % path)
|
import os
from django.core.management.base import BaseCommand
from cacheops.conf import settings
class Command(BaseCommand):
help = 'Clean filebased cache'
def handle(self, **options):
os.system('find %s -type f \! -iname "\." -mmin +0 -delete' % settings.FILE_CACHE_DIR)
Allow cleaning file cache in non default placeimport os
from django.core.management.base import BaseCommand
from cacheops.conf import settings
class Command(BaseCommand):
help = 'Clean filebased cache'
def add_arguments(self, parser):
parser.add_argument('path', nargs='*', default=['default'])
def handle(self, **options):
for path in options['path']:
if path == 'default':
path = settings.FILE_CACHE_DIR
os.system('find %s -type f \! -iname "\." -mmin +0 -delete' % path)
|
<commit_before>import os
from django.core.management.base import BaseCommand
from cacheops.conf import settings
class Command(BaseCommand):
help = 'Clean filebased cache'
def handle(self, **options):
os.system('find %s -type f \! -iname "\." -mmin +0 -delete' % settings.FILE_CACHE_DIR)
<commit_msg>Allow cleaning file cache in non default place<commit_after>import os
from django.core.management.base import BaseCommand
from cacheops.conf import settings
class Command(BaseCommand):
help = 'Clean filebased cache'
def add_arguments(self, parser):
parser.add_argument('path', nargs='*', default=['default'])
def handle(self, **options):
for path in options['path']:
if path == 'default':
path = settings.FILE_CACHE_DIR
os.system('find %s -type f \! -iname "\." -mmin +0 -delete' % path)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.