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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fbeb7b6d400f813c4ed9d293c5525a7c36b44d7d
|
setup.py
|
setup.py
|
#!/usr/bin/python
from setuptools import setup
from distutils.extension import Extension
from Pyrex.Distutils import build_ext
setup(
name="PyHesiod",
version="0.2.0",
description="PyHesiod - Python bindings for the Heisod naming library",
author="Evan Broder",
author_email="broder@mit.edu",
license="MIT",
py_modules=['hesiod'],
ext_modules=[
Extension("_hesiod",
["_hesiod.pyx"],
libraries=["hesiod"])
],
cmdclass= {"build_ext": build_ext}
)
|
#!/usr/bin/python
from setuptools import setup
from distutils.extension import Extension
from Pyrex.Distutils import build_ext
setup(
name="PyHesiod",
version="0.2.1",
description="PyHesiod - Python bindings for the Heisod naming library",
author="Evan Broder",
author_email="broder@mit.edu",
url="http://ebroder.net/code/PyHesiod",
license="MIT",
py_modules=['hesiod'],
ext_modules=[
Extension("_hesiod",
["_hesiod.pyx"],
libraries=["hesiod"])
],
cmdclass= {"build_ext": build_ext}
)
|
Add a quick note about a homepage
|
Add a quick note about a homepage
|
Python
|
mit
|
ebroder/python-hesiod
|
#!/usr/bin/python
from setuptools import setup
from distutils.extension import Extension
from Pyrex.Distutils import build_ext
setup(
name="PyHesiod",
version="0.2.0",
description="PyHesiod - Python bindings for the Heisod naming library",
author="Evan Broder",
author_email="broder@mit.edu",
license="MIT",
py_modules=['hesiod'],
ext_modules=[
Extension("_hesiod",
["_hesiod.pyx"],
libraries=["hesiod"])
],
cmdclass= {"build_ext": build_ext}
)
Add a quick note about a homepage
|
#!/usr/bin/python
from setuptools import setup
from distutils.extension import Extension
from Pyrex.Distutils import build_ext
setup(
name="PyHesiod",
version="0.2.1",
description="PyHesiod - Python bindings for the Heisod naming library",
author="Evan Broder",
author_email="broder@mit.edu",
url="http://ebroder.net/code/PyHesiod",
license="MIT",
py_modules=['hesiod'],
ext_modules=[
Extension("_hesiod",
["_hesiod.pyx"],
libraries=["hesiod"])
],
cmdclass= {"build_ext": build_ext}
)
|
<commit_before>#!/usr/bin/python
from setuptools import setup
from distutils.extension import Extension
from Pyrex.Distutils import build_ext
setup(
name="PyHesiod",
version="0.2.0",
description="PyHesiod - Python bindings for the Heisod naming library",
author="Evan Broder",
author_email="broder@mit.edu",
license="MIT",
py_modules=['hesiod'],
ext_modules=[
Extension("_hesiod",
["_hesiod.pyx"],
libraries=["hesiod"])
],
cmdclass= {"build_ext": build_ext}
)
<commit_msg>Add a quick note about a homepage<commit_after>
|
#!/usr/bin/python
from setuptools import setup
from distutils.extension import Extension
from Pyrex.Distutils import build_ext
setup(
name="PyHesiod",
version="0.2.1",
description="PyHesiod - Python bindings for the Heisod naming library",
author="Evan Broder",
author_email="broder@mit.edu",
url="http://ebroder.net/code/PyHesiod",
license="MIT",
py_modules=['hesiod'],
ext_modules=[
Extension("_hesiod",
["_hesiod.pyx"],
libraries=["hesiod"])
],
cmdclass= {"build_ext": build_ext}
)
|
#!/usr/bin/python
from setuptools import setup
from distutils.extension import Extension
from Pyrex.Distutils import build_ext
setup(
name="PyHesiod",
version="0.2.0",
description="PyHesiod - Python bindings for the Heisod naming library",
author="Evan Broder",
author_email="broder@mit.edu",
license="MIT",
py_modules=['hesiod'],
ext_modules=[
Extension("_hesiod",
["_hesiod.pyx"],
libraries=["hesiod"])
],
cmdclass= {"build_ext": build_ext}
)
Add a quick note about a homepage#!/usr/bin/python
from setuptools import setup
from distutils.extension import Extension
from Pyrex.Distutils import build_ext
setup(
name="PyHesiod",
version="0.2.1",
description="PyHesiod - Python bindings for the Heisod naming library",
author="Evan Broder",
author_email="broder@mit.edu",
url="http://ebroder.net/code/PyHesiod",
license="MIT",
py_modules=['hesiod'],
ext_modules=[
Extension("_hesiod",
["_hesiod.pyx"],
libraries=["hesiod"])
],
cmdclass= {"build_ext": build_ext}
)
|
<commit_before>#!/usr/bin/python
from setuptools import setup
from distutils.extension import Extension
from Pyrex.Distutils import build_ext
setup(
name="PyHesiod",
version="0.2.0",
description="PyHesiod - Python bindings for the Heisod naming library",
author="Evan Broder",
author_email="broder@mit.edu",
license="MIT",
py_modules=['hesiod'],
ext_modules=[
Extension("_hesiod",
["_hesiod.pyx"],
libraries=["hesiod"])
],
cmdclass= {"build_ext": build_ext}
)
<commit_msg>Add a quick note about a homepage<commit_after>#!/usr/bin/python
from setuptools import setup
from distutils.extension import Extension
from Pyrex.Distutils import build_ext
setup(
name="PyHesiod",
version="0.2.1",
description="PyHesiod - Python bindings for the Heisod naming library",
author="Evan Broder",
author_email="broder@mit.edu",
url="http://ebroder.net/code/PyHesiod",
license="MIT",
py_modules=['hesiod'],
ext_modules=[
Extension("_hesiod",
["_hesiod.pyx"],
libraries=["hesiod"])
],
cmdclass= {"build_ext": build_ext}
)
|
9887e5fe0253f4e44acdb438bc769313985e1080
|
setup.py
|
setup.py
|
#!/usr/bin/env python
from setuptools import setup
setup(
name="segfault",
version="0.0.1",
author="Sean Kelly",
author_email="sean.kelly.2992@gmail.com",
description="A library that makes the Python interpreter segfault.",
license="MIT",
keywords="segfault",
py_modules=['segfault', 'satire'],
)
|
#!/usr/bin/env python
from setuptools import setup
setup(
name="segfault",
version="0.0.1",
author="Sean Kelly",
author_email="sean.kelly.2992@gmail.com",
description="A library that makes the Python interpreter segfault.",
license="MIT",
url='https://github.com/cbgbt/segfault',
download_url='https://github.com/cbgbt/segfault/archive/v0.0.1.tar.gz',
keywords="segfault",
py_modules=['segfault', 'satire'],
)
|
Add pypi url and download_url
|
Add pypi url and download_url
|
Python
|
mit
|
cbgbt/segfault,cbgbt/segfault
|
#!/usr/bin/env python
from setuptools import setup
setup(
name="segfault",
version="0.0.1",
author="Sean Kelly",
author_email="sean.kelly.2992@gmail.com",
description="A library that makes the Python interpreter segfault.",
license="MIT",
keywords="segfault",
py_modules=['segfault', 'satire'],
)
Add pypi url and download_url
|
#!/usr/bin/env python
from setuptools import setup
setup(
name="segfault",
version="0.0.1",
author="Sean Kelly",
author_email="sean.kelly.2992@gmail.com",
description="A library that makes the Python interpreter segfault.",
license="MIT",
url='https://github.com/cbgbt/segfault',
download_url='https://github.com/cbgbt/segfault/archive/v0.0.1.tar.gz',
keywords="segfault",
py_modules=['segfault', 'satire'],
)
|
<commit_before>#!/usr/bin/env python
from setuptools import setup
setup(
name="segfault",
version="0.0.1",
author="Sean Kelly",
author_email="sean.kelly.2992@gmail.com",
description="A library that makes the Python interpreter segfault.",
license="MIT",
keywords="segfault",
py_modules=['segfault', 'satire'],
)
<commit_msg>Add pypi url and download_url<commit_after>
|
#!/usr/bin/env python
from setuptools import setup
setup(
name="segfault",
version="0.0.1",
author="Sean Kelly",
author_email="sean.kelly.2992@gmail.com",
description="A library that makes the Python interpreter segfault.",
license="MIT",
url='https://github.com/cbgbt/segfault',
download_url='https://github.com/cbgbt/segfault/archive/v0.0.1.tar.gz',
keywords="segfault",
py_modules=['segfault', 'satire'],
)
|
#!/usr/bin/env python
from setuptools import setup
setup(
name="segfault",
version="0.0.1",
author="Sean Kelly",
author_email="sean.kelly.2992@gmail.com",
description="A library that makes the Python interpreter segfault.",
license="MIT",
keywords="segfault",
py_modules=['segfault', 'satire'],
)
Add pypi url and download_url#!/usr/bin/env python
from setuptools import setup
setup(
name="segfault",
version="0.0.1",
author="Sean Kelly",
author_email="sean.kelly.2992@gmail.com",
description="A library that makes the Python interpreter segfault.",
license="MIT",
url='https://github.com/cbgbt/segfault',
download_url='https://github.com/cbgbt/segfault/archive/v0.0.1.tar.gz',
keywords="segfault",
py_modules=['segfault', 'satire'],
)
|
<commit_before>#!/usr/bin/env python
from setuptools import setup
setup(
name="segfault",
version="0.0.1",
author="Sean Kelly",
author_email="sean.kelly.2992@gmail.com",
description="A library that makes the Python interpreter segfault.",
license="MIT",
keywords="segfault",
py_modules=['segfault', 'satire'],
)
<commit_msg>Add pypi url and download_url<commit_after>#!/usr/bin/env python
from setuptools import setup
setup(
name="segfault",
version="0.0.1",
author="Sean Kelly",
author_email="sean.kelly.2992@gmail.com",
description="A library that makes the Python interpreter segfault.",
license="MIT",
url='https://github.com/cbgbt/segfault',
download_url='https://github.com/cbgbt/segfault/archive/v0.0.1.tar.gz',
keywords="segfault",
py_modules=['segfault', 'satire'],
)
|
2aaa7e9a2c9ef40ad428293c2fa6a92711e75ee8
|
setup.py
|
setup.py
|
#!/usr/bin/env python3
from setuptools import setup
setup(
name='botbot',
version='0.5.0',
description='A meta-bot for Euphoria.',
author='Rishov Sarkar',
url='https://github.com/ArkaneMoose/BotBot',
license='MIT',
packages=['botbot'],
package_dir={'botbot': 'source'},
install_requires=['eupy >=1.0, <2.0', 'simpleeval >=0.9, <0.10'],
dependency_links=['git+https://github.com/ArkaneMoose/EuPy.git@a569c35ea76a40b241a57669054b3247c3b4f960#egg=eupy-1.1', 'git+https://github.com/ArkaneMoose/simpleeval.git@ac33b805645ca616f11e64bb3330a12bc5fba658#egg=simpleeval-0.9.2'],
entry_points={
'console_scripts': [
'botbot = botbot.__main__:main'
]
}
)
|
#!/usr/bin/env python3
from setuptools import setup
setup(
name='botbot',
version='0.5.1',
description='A meta-bot for Euphoria.',
author='Rishov Sarkar',
url='https://github.com/ArkaneMoose/BotBot',
license='MIT',
packages=['botbot'],
package_dir={'botbot': 'source'},
install_requires=['eupy >=1.2, <2.0', 'simpleeval >=0.9, <0.10'],
dependency_links=['git+https://github.com/ArkaneMoose/EuPy.git@75777c49503acb32e09f4c36f6f65cc35157694a#egg=eupy-1.2', 'git+https://github.com/ArkaneMoose/simpleeval.git@ac33b805645ca616f11e64bb3330a12bc5fba658#egg=simpleeval-0.9.2'],
entry_points={
'console_scripts': [
'botbot = botbot.__main__:main'
]
}
)
|
Use latest version of EuPy
|
Use latest version of EuPy
The latest version of EuPy has better connection handling and improved
exponential backoff behavior.
|
Python
|
mit
|
ArkaneMoose/BotBot
|
#!/usr/bin/env python3
from setuptools import setup
setup(
name='botbot',
version='0.5.0',
description='A meta-bot for Euphoria.',
author='Rishov Sarkar',
url='https://github.com/ArkaneMoose/BotBot',
license='MIT',
packages=['botbot'],
package_dir={'botbot': 'source'},
install_requires=['eupy >=1.0, <2.0', 'simpleeval >=0.9, <0.10'],
dependency_links=['git+https://github.com/ArkaneMoose/EuPy.git@a569c35ea76a40b241a57669054b3247c3b4f960#egg=eupy-1.1', 'git+https://github.com/ArkaneMoose/simpleeval.git@ac33b805645ca616f11e64bb3330a12bc5fba658#egg=simpleeval-0.9.2'],
entry_points={
'console_scripts': [
'botbot = botbot.__main__:main'
]
}
)
Use latest version of EuPy
The latest version of EuPy has better connection handling and improved
exponential backoff behavior.
|
#!/usr/bin/env python3
from setuptools import setup
setup(
name='botbot',
version='0.5.1',
description='A meta-bot for Euphoria.',
author='Rishov Sarkar',
url='https://github.com/ArkaneMoose/BotBot',
license='MIT',
packages=['botbot'],
package_dir={'botbot': 'source'},
install_requires=['eupy >=1.2, <2.0', 'simpleeval >=0.9, <0.10'],
dependency_links=['git+https://github.com/ArkaneMoose/EuPy.git@75777c49503acb32e09f4c36f6f65cc35157694a#egg=eupy-1.2', 'git+https://github.com/ArkaneMoose/simpleeval.git@ac33b805645ca616f11e64bb3330a12bc5fba658#egg=simpleeval-0.9.2'],
entry_points={
'console_scripts': [
'botbot = botbot.__main__:main'
]
}
)
|
<commit_before>#!/usr/bin/env python3
from setuptools import setup
setup(
name='botbot',
version='0.5.0',
description='A meta-bot for Euphoria.',
author='Rishov Sarkar',
url='https://github.com/ArkaneMoose/BotBot',
license='MIT',
packages=['botbot'],
package_dir={'botbot': 'source'},
install_requires=['eupy >=1.0, <2.0', 'simpleeval >=0.9, <0.10'],
dependency_links=['git+https://github.com/ArkaneMoose/EuPy.git@a569c35ea76a40b241a57669054b3247c3b4f960#egg=eupy-1.1', 'git+https://github.com/ArkaneMoose/simpleeval.git@ac33b805645ca616f11e64bb3330a12bc5fba658#egg=simpleeval-0.9.2'],
entry_points={
'console_scripts': [
'botbot = botbot.__main__:main'
]
}
)
<commit_msg>Use latest version of EuPy
The latest version of EuPy has better connection handling and improved
exponential backoff behavior.<commit_after>
|
#!/usr/bin/env python3
from setuptools import setup
setup(
name='botbot',
version='0.5.1',
description='A meta-bot for Euphoria.',
author='Rishov Sarkar',
url='https://github.com/ArkaneMoose/BotBot',
license='MIT',
packages=['botbot'],
package_dir={'botbot': 'source'},
install_requires=['eupy >=1.2, <2.0', 'simpleeval >=0.9, <0.10'],
dependency_links=['git+https://github.com/ArkaneMoose/EuPy.git@75777c49503acb32e09f4c36f6f65cc35157694a#egg=eupy-1.2', 'git+https://github.com/ArkaneMoose/simpleeval.git@ac33b805645ca616f11e64bb3330a12bc5fba658#egg=simpleeval-0.9.2'],
entry_points={
'console_scripts': [
'botbot = botbot.__main__:main'
]
}
)
|
#!/usr/bin/env python3
from setuptools import setup
setup(
name='botbot',
version='0.5.0',
description='A meta-bot for Euphoria.',
author='Rishov Sarkar',
url='https://github.com/ArkaneMoose/BotBot',
license='MIT',
packages=['botbot'],
package_dir={'botbot': 'source'},
install_requires=['eupy >=1.0, <2.0', 'simpleeval >=0.9, <0.10'],
dependency_links=['git+https://github.com/ArkaneMoose/EuPy.git@a569c35ea76a40b241a57669054b3247c3b4f960#egg=eupy-1.1', 'git+https://github.com/ArkaneMoose/simpleeval.git@ac33b805645ca616f11e64bb3330a12bc5fba658#egg=simpleeval-0.9.2'],
entry_points={
'console_scripts': [
'botbot = botbot.__main__:main'
]
}
)
Use latest version of EuPy
The latest version of EuPy has better connection handling and improved
exponential backoff behavior.#!/usr/bin/env python3
from setuptools import setup
setup(
name='botbot',
version='0.5.1',
description='A meta-bot for Euphoria.',
author='Rishov Sarkar',
url='https://github.com/ArkaneMoose/BotBot',
license='MIT',
packages=['botbot'],
package_dir={'botbot': 'source'},
install_requires=['eupy >=1.2, <2.0', 'simpleeval >=0.9, <0.10'],
dependency_links=['git+https://github.com/ArkaneMoose/EuPy.git@75777c49503acb32e09f4c36f6f65cc35157694a#egg=eupy-1.2', 'git+https://github.com/ArkaneMoose/simpleeval.git@ac33b805645ca616f11e64bb3330a12bc5fba658#egg=simpleeval-0.9.2'],
entry_points={
'console_scripts': [
'botbot = botbot.__main__:main'
]
}
)
|
<commit_before>#!/usr/bin/env python3
from setuptools import setup
setup(
name='botbot',
version='0.5.0',
description='A meta-bot for Euphoria.',
author='Rishov Sarkar',
url='https://github.com/ArkaneMoose/BotBot',
license='MIT',
packages=['botbot'],
package_dir={'botbot': 'source'},
install_requires=['eupy >=1.0, <2.0', 'simpleeval >=0.9, <0.10'],
dependency_links=['git+https://github.com/ArkaneMoose/EuPy.git@a569c35ea76a40b241a57669054b3247c3b4f960#egg=eupy-1.1', 'git+https://github.com/ArkaneMoose/simpleeval.git@ac33b805645ca616f11e64bb3330a12bc5fba658#egg=simpleeval-0.9.2'],
entry_points={
'console_scripts': [
'botbot = botbot.__main__:main'
]
}
)
<commit_msg>Use latest version of EuPy
The latest version of EuPy has better connection handling and improved
exponential backoff behavior.<commit_after>#!/usr/bin/env python3
from setuptools import setup
setup(
name='botbot',
version='0.5.1',
description='A meta-bot for Euphoria.',
author='Rishov Sarkar',
url='https://github.com/ArkaneMoose/BotBot',
license='MIT',
packages=['botbot'],
package_dir={'botbot': 'source'},
install_requires=['eupy >=1.2, <2.0', 'simpleeval >=0.9, <0.10'],
dependency_links=['git+https://github.com/ArkaneMoose/EuPy.git@75777c49503acb32e09f4c36f6f65cc35157694a#egg=eupy-1.2', 'git+https://github.com/ArkaneMoose/simpleeval.git@ac33b805645ca616f11e64bb3330a12bc5fba658#egg=simpleeval-0.9.2'],
entry_points={
'console_scripts': [
'botbot = botbot.__main__:main'
]
}
)
|
26b1845419cd7ea55cf1f40f26812eb9c124299f
|
kolibri/core/content/signals.py
|
kolibri/core/content/signals.py
|
from django.db.models import F
from django.db.models.signals import pre_delete
from django.dispatch import receiver
from .models import ChannelMetadata
from .models import ContentNode
from kolibri.core.notifications.models import LearnerProgressNotification
@receiver(pre_delete, sender=ContentNode)
def cascade_delete_node(sender, instance=None, *args, **kwargs):
"""
For a given node, we delete all notifications
objects whose contentnode is the instance's node..
"""
LearnerProgressNotification.objects.filter(contentnode_id=instance.id).delete()
@receiver(pre_delete, sender=ChannelMetadata)
def reorder_channels_upon_deletion(sender, instance=None, *args, **kwargs):
"""
For a given channel, decrement the order of all channels that come after this channel.
"""
ChannelMetadata.objects.filter(order__gt=instance.order).update(order=F('order') - 1)
|
from django.db.models import F
from django.db.models.signals import pre_delete
from django.dispatch import receiver
from .models import ChannelMetadata
from .models import ContentNode
from kolibri.core.notifications.models import LearnerProgressNotification
from kolibri.core.lessons.models import Lesson
@receiver(pre_delete, sender=ContentNode)
def cascade_delete_node(sender, instance=None, *args, **kwargs):
"""
For a given node, we delete all notifications
objects whose contentnode is the instance's node..
"""
LearnerProgressNotification.objects.filter(contentnode_id=instance.id).delete()
@receiver(pre_delete, sender=ChannelMetadata)
def reorder_channels_upon_deletion(sender, instance=None, *args, **kwargs):
"""
For a given channel, decrement the order of all channels that come after this channel.
"""
ChannelMetadata.objects.filter(order__gt=instance.order).update(order=F('order') - 1)
@receiver(pre_delete, sender=ChannelMetadata)
def update_lesson_resources_before_delete(sender, instance=None, *args, **kwargs):
# Update the resources array of all lessons to ensure they don't have
# any deleted content
lessons = Lesson.objects.all()
for lesson in lessons:
updated_resources = [r for r in lesson.resources if r['channel_id'] != instance.id]
if len(updated_resources) < len(lesson.resources):
lesson.resources = updated_resources
lesson.save()
|
Add Channel deletion side-effect that updates affected lessons
|
Add Channel deletion side-effect that updates affected lessons
|
Python
|
mit
|
learningequality/kolibri,lyw07/kolibri,mrpau/kolibri,learningequality/kolibri,indirectlylit/kolibri,lyw07/kolibri,mrpau/kolibri,mrpau/kolibri,indirectlylit/kolibri,indirectlylit/kolibri,learningequality/kolibri,indirectlylit/kolibri,lyw07/kolibri,learningequality/kolibri,lyw07/kolibri,mrpau/kolibri
|
from django.db.models import F
from django.db.models.signals import pre_delete
from django.dispatch import receiver
from .models import ChannelMetadata
from .models import ContentNode
from kolibri.core.notifications.models import LearnerProgressNotification
@receiver(pre_delete, sender=ContentNode)
def cascade_delete_node(sender, instance=None, *args, **kwargs):
"""
For a given node, we delete all notifications
objects whose contentnode is the instance's node..
"""
LearnerProgressNotification.objects.filter(contentnode_id=instance.id).delete()
@receiver(pre_delete, sender=ChannelMetadata)
def reorder_channels_upon_deletion(sender, instance=None, *args, **kwargs):
"""
For a given channel, decrement the order of all channels that come after this channel.
"""
ChannelMetadata.objects.filter(order__gt=instance.order).update(order=F('order') - 1)
Add Channel deletion side-effect that updates affected lessons
|
from django.db.models import F
from django.db.models.signals import pre_delete
from django.dispatch import receiver
from .models import ChannelMetadata
from .models import ContentNode
from kolibri.core.notifications.models import LearnerProgressNotification
from kolibri.core.lessons.models import Lesson
@receiver(pre_delete, sender=ContentNode)
def cascade_delete_node(sender, instance=None, *args, **kwargs):
"""
For a given node, we delete all notifications
objects whose contentnode is the instance's node..
"""
LearnerProgressNotification.objects.filter(contentnode_id=instance.id).delete()
@receiver(pre_delete, sender=ChannelMetadata)
def reorder_channels_upon_deletion(sender, instance=None, *args, **kwargs):
"""
For a given channel, decrement the order of all channels that come after this channel.
"""
ChannelMetadata.objects.filter(order__gt=instance.order).update(order=F('order') - 1)
@receiver(pre_delete, sender=ChannelMetadata)
def update_lesson_resources_before_delete(sender, instance=None, *args, **kwargs):
# Update the resources array of all lessons to ensure they don't have
# any deleted content
lessons = Lesson.objects.all()
for lesson in lessons:
updated_resources = [r for r in lesson.resources if r['channel_id'] != instance.id]
if len(updated_resources) < len(lesson.resources):
lesson.resources = updated_resources
lesson.save()
|
<commit_before>from django.db.models import F
from django.db.models.signals import pre_delete
from django.dispatch import receiver
from .models import ChannelMetadata
from .models import ContentNode
from kolibri.core.notifications.models import LearnerProgressNotification
@receiver(pre_delete, sender=ContentNode)
def cascade_delete_node(sender, instance=None, *args, **kwargs):
"""
For a given node, we delete all notifications
objects whose contentnode is the instance's node..
"""
LearnerProgressNotification.objects.filter(contentnode_id=instance.id).delete()
@receiver(pre_delete, sender=ChannelMetadata)
def reorder_channels_upon_deletion(sender, instance=None, *args, **kwargs):
"""
For a given channel, decrement the order of all channels that come after this channel.
"""
ChannelMetadata.objects.filter(order__gt=instance.order).update(order=F('order') - 1)
<commit_msg>Add Channel deletion side-effect that updates affected lessons<commit_after>
|
from django.db.models import F
from django.db.models.signals import pre_delete
from django.dispatch import receiver
from .models import ChannelMetadata
from .models import ContentNode
from kolibri.core.notifications.models import LearnerProgressNotification
from kolibri.core.lessons.models import Lesson
@receiver(pre_delete, sender=ContentNode)
def cascade_delete_node(sender, instance=None, *args, **kwargs):
"""
For a given node, we delete all notifications
objects whose contentnode is the instance's node..
"""
LearnerProgressNotification.objects.filter(contentnode_id=instance.id).delete()
@receiver(pre_delete, sender=ChannelMetadata)
def reorder_channels_upon_deletion(sender, instance=None, *args, **kwargs):
"""
For a given channel, decrement the order of all channels that come after this channel.
"""
ChannelMetadata.objects.filter(order__gt=instance.order).update(order=F('order') - 1)
@receiver(pre_delete, sender=ChannelMetadata)
def update_lesson_resources_before_delete(sender, instance=None, *args, **kwargs):
# Update the resources array of all lessons to ensure they don't have
# any deleted content
lessons = Lesson.objects.all()
for lesson in lessons:
updated_resources = [r for r in lesson.resources if r['channel_id'] != instance.id]
if len(updated_resources) < len(lesson.resources):
lesson.resources = updated_resources
lesson.save()
|
from django.db.models import F
from django.db.models.signals import pre_delete
from django.dispatch import receiver
from .models import ChannelMetadata
from .models import ContentNode
from kolibri.core.notifications.models import LearnerProgressNotification
@receiver(pre_delete, sender=ContentNode)
def cascade_delete_node(sender, instance=None, *args, **kwargs):
"""
For a given node, we delete all notifications
objects whose contentnode is the instance's node..
"""
LearnerProgressNotification.objects.filter(contentnode_id=instance.id).delete()
@receiver(pre_delete, sender=ChannelMetadata)
def reorder_channels_upon_deletion(sender, instance=None, *args, **kwargs):
"""
For a given channel, decrement the order of all channels that come after this channel.
"""
ChannelMetadata.objects.filter(order__gt=instance.order).update(order=F('order') - 1)
Add Channel deletion side-effect that updates affected lessonsfrom django.db.models import F
from django.db.models.signals import pre_delete
from django.dispatch import receiver
from .models import ChannelMetadata
from .models import ContentNode
from kolibri.core.notifications.models import LearnerProgressNotification
from kolibri.core.lessons.models import Lesson
@receiver(pre_delete, sender=ContentNode)
def cascade_delete_node(sender, instance=None, *args, **kwargs):
"""
For a given node, we delete all notifications
objects whose contentnode is the instance's node..
"""
LearnerProgressNotification.objects.filter(contentnode_id=instance.id).delete()
@receiver(pre_delete, sender=ChannelMetadata)
def reorder_channels_upon_deletion(sender, instance=None, *args, **kwargs):
"""
For a given channel, decrement the order of all channels that come after this channel.
"""
ChannelMetadata.objects.filter(order__gt=instance.order).update(order=F('order') - 1)
@receiver(pre_delete, sender=ChannelMetadata)
def update_lesson_resources_before_delete(sender, instance=None, *args, **kwargs):
# Update the resources array of all lessons to ensure they don't have
# any deleted content
lessons = Lesson.objects.all()
for lesson in lessons:
updated_resources = [r for r in lesson.resources if r['channel_id'] != instance.id]
if len(updated_resources) < len(lesson.resources):
lesson.resources = updated_resources
lesson.save()
|
<commit_before>from django.db.models import F
from django.db.models.signals import pre_delete
from django.dispatch import receiver
from .models import ChannelMetadata
from .models import ContentNode
from kolibri.core.notifications.models import LearnerProgressNotification
@receiver(pre_delete, sender=ContentNode)
def cascade_delete_node(sender, instance=None, *args, **kwargs):
"""
For a given node, we delete all notifications
objects whose contentnode is the instance's node..
"""
LearnerProgressNotification.objects.filter(contentnode_id=instance.id).delete()
@receiver(pre_delete, sender=ChannelMetadata)
def reorder_channels_upon_deletion(sender, instance=None, *args, **kwargs):
"""
For a given channel, decrement the order of all channels that come after this channel.
"""
ChannelMetadata.objects.filter(order__gt=instance.order).update(order=F('order') - 1)
<commit_msg>Add Channel deletion side-effect that updates affected lessons<commit_after>from django.db.models import F
from django.db.models.signals import pre_delete
from django.dispatch import receiver
from .models import ChannelMetadata
from .models import ContentNode
from kolibri.core.notifications.models import LearnerProgressNotification
from kolibri.core.lessons.models import Lesson
@receiver(pre_delete, sender=ContentNode)
def cascade_delete_node(sender, instance=None, *args, **kwargs):
"""
For a given node, we delete all notifications
objects whose contentnode is the instance's node..
"""
LearnerProgressNotification.objects.filter(contentnode_id=instance.id).delete()
@receiver(pre_delete, sender=ChannelMetadata)
def reorder_channels_upon_deletion(sender, instance=None, *args, **kwargs):
"""
For a given channel, decrement the order of all channels that come after this channel.
"""
ChannelMetadata.objects.filter(order__gt=instance.order).update(order=F('order') - 1)
@receiver(pre_delete, sender=ChannelMetadata)
def update_lesson_resources_before_delete(sender, instance=None, *args, **kwargs):
# Update the resources array of all lessons to ensure they don't have
# any deleted content
lessons = Lesson.objects.all()
for lesson in lessons:
updated_resources = [r for r in lesson.resources if r['channel_id'] != instance.id]
if len(updated_resources) < len(lesson.resources):
lesson.resources = updated_resources
lesson.save()
|
81bebd21d7f88f042e538b73332d1727cd5117e2
|
setup.py
|
setup.py
|
import os
import re
from setuptools import setup
v = open(os.path.join(os.path.dirname(__file__), 'pynuodb', '__init__.py'))
VERSION = re.compile(r".*__version__ = '(.*?)'", re.S).match(v.read()).group(1)
v.close()
readme = os.path.join(os.path.dirname(__file__), 'README.rst')
setup(
name='pynuodb',
version=VERSION,
author='NuoDB',
author_email='info@nuodb.com',
description='NuoDB Python driver',
keywords='nuodb scalable cloud database',
packages=['pynuodb'],
package_dir={'pynuodb': 'pynuodb'},
url='https://github.com/nuodb/nuodb-python',
license='BSD Licence',
long_description=open(readme).read(),
install_requires=['pytz'],
)
|
import os
import re
from setuptools import setup
v = open(os.path.join(os.path.dirname(__file__), 'pynuodb', '__init__.py'))
VERSION = re.compile(r".*__version__ = '(.*?)'", re.S).match(v.read()).group(1)
v.close()
readme = os.path.join(os.path.dirname(__file__), 'README.rst')
setup(
name='pynuodb',
version=VERSION,
author='NuoDB',
author_email='info@nuodb.com',
description='NuoDB Python driver',
keywords='nuodb scalable cloud database',
packages=['pynuodb'],
package_dir={'pynuodb': 'pynuodb'},
url='https://github.com/nuodb/nuodb-python',
license='BSD License',
long_description=open(readme).read(),
install_requires=['pytz'],
)
|
Fix typo: licence to license
|
Fix typo: licence to license
|
Python
|
bsd-3-clause
|
tvincentNuoDB/nuodb-python
|
import os
import re
from setuptools import setup
v = open(os.path.join(os.path.dirname(__file__), 'pynuodb', '__init__.py'))
VERSION = re.compile(r".*__version__ = '(.*?)'", re.S).match(v.read()).group(1)
v.close()
readme = os.path.join(os.path.dirname(__file__), 'README.rst')
setup(
name='pynuodb',
version=VERSION,
author='NuoDB',
author_email='info@nuodb.com',
description='NuoDB Python driver',
keywords='nuodb scalable cloud database',
packages=['pynuodb'],
package_dir={'pynuodb': 'pynuodb'},
url='https://github.com/nuodb/nuodb-python',
license='BSD Licence',
long_description=open(readme).read(),
install_requires=['pytz'],
)
Fix typo: licence to license
|
import os
import re
from setuptools import setup
v = open(os.path.join(os.path.dirname(__file__), 'pynuodb', '__init__.py'))
VERSION = re.compile(r".*__version__ = '(.*?)'", re.S).match(v.read()).group(1)
v.close()
readme = os.path.join(os.path.dirname(__file__), 'README.rst')
setup(
name='pynuodb',
version=VERSION,
author='NuoDB',
author_email='info@nuodb.com',
description='NuoDB Python driver',
keywords='nuodb scalable cloud database',
packages=['pynuodb'],
package_dir={'pynuodb': 'pynuodb'},
url='https://github.com/nuodb/nuodb-python',
license='BSD License',
long_description=open(readme).read(),
install_requires=['pytz'],
)
|
<commit_before>import os
import re
from setuptools import setup
v = open(os.path.join(os.path.dirname(__file__), 'pynuodb', '__init__.py'))
VERSION = re.compile(r".*__version__ = '(.*?)'", re.S).match(v.read()).group(1)
v.close()
readme = os.path.join(os.path.dirname(__file__), 'README.rst')
setup(
name='pynuodb',
version=VERSION,
author='NuoDB',
author_email='info@nuodb.com',
description='NuoDB Python driver',
keywords='nuodb scalable cloud database',
packages=['pynuodb'],
package_dir={'pynuodb': 'pynuodb'},
url='https://github.com/nuodb/nuodb-python',
license='BSD Licence',
long_description=open(readme).read(),
install_requires=['pytz'],
)
<commit_msg>Fix typo: licence to license<commit_after>
|
import os
import re
from setuptools import setup
v = open(os.path.join(os.path.dirname(__file__), 'pynuodb', '__init__.py'))
VERSION = re.compile(r".*__version__ = '(.*?)'", re.S).match(v.read()).group(1)
v.close()
readme = os.path.join(os.path.dirname(__file__), 'README.rst')
setup(
name='pynuodb',
version=VERSION,
author='NuoDB',
author_email='info@nuodb.com',
description='NuoDB Python driver',
keywords='nuodb scalable cloud database',
packages=['pynuodb'],
package_dir={'pynuodb': 'pynuodb'},
url='https://github.com/nuodb/nuodb-python',
license='BSD License',
long_description=open(readme).read(),
install_requires=['pytz'],
)
|
import os
import re
from setuptools import setup
v = open(os.path.join(os.path.dirname(__file__), 'pynuodb', '__init__.py'))
VERSION = re.compile(r".*__version__ = '(.*?)'", re.S).match(v.read()).group(1)
v.close()
readme = os.path.join(os.path.dirname(__file__), 'README.rst')
setup(
name='pynuodb',
version=VERSION,
author='NuoDB',
author_email='info@nuodb.com',
description='NuoDB Python driver',
keywords='nuodb scalable cloud database',
packages=['pynuodb'],
package_dir={'pynuodb': 'pynuodb'},
url='https://github.com/nuodb/nuodb-python',
license='BSD Licence',
long_description=open(readme).read(),
install_requires=['pytz'],
)
Fix typo: licence to licenseimport os
import re
from setuptools import setup
v = open(os.path.join(os.path.dirname(__file__), 'pynuodb', '__init__.py'))
VERSION = re.compile(r".*__version__ = '(.*?)'", re.S).match(v.read()).group(1)
v.close()
readme = os.path.join(os.path.dirname(__file__), 'README.rst')
setup(
name='pynuodb',
version=VERSION,
author='NuoDB',
author_email='info@nuodb.com',
description='NuoDB Python driver',
keywords='nuodb scalable cloud database',
packages=['pynuodb'],
package_dir={'pynuodb': 'pynuodb'},
url='https://github.com/nuodb/nuodb-python',
license='BSD License',
long_description=open(readme).read(),
install_requires=['pytz'],
)
|
<commit_before>import os
import re
from setuptools import setup
v = open(os.path.join(os.path.dirname(__file__), 'pynuodb', '__init__.py'))
VERSION = re.compile(r".*__version__ = '(.*?)'", re.S).match(v.read()).group(1)
v.close()
readme = os.path.join(os.path.dirname(__file__), 'README.rst')
setup(
name='pynuodb',
version=VERSION,
author='NuoDB',
author_email='info@nuodb.com',
description='NuoDB Python driver',
keywords='nuodb scalable cloud database',
packages=['pynuodb'],
package_dir={'pynuodb': 'pynuodb'},
url='https://github.com/nuodb/nuodb-python',
license='BSD Licence',
long_description=open(readme).read(),
install_requires=['pytz'],
)
<commit_msg>Fix typo: licence to license<commit_after>import os
import re
from setuptools import setup
v = open(os.path.join(os.path.dirname(__file__), 'pynuodb', '__init__.py'))
VERSION = re.compile(r".*__version__ = '(.*?)'", re.S).match(v.read()).group(1)
v.close()
readme = os.path.join(os.path.dirname(__file__), 'README.rst')
setup(
name='pynuodb',
version=VERSION,
author='NuoDB',
author_email='info@nuodb.com',
description='NuoDB Python driver',
keywords='nuodb scalable cloud database',
packages=['pynuodb'],
package_dir={'pynuodb': 'pynuodb'},
url='https://github.com/nuodb/nuodb-python',
license='BSD License',
long_description=open(readme).read(),
install_requires=['pytz'],
)
|
a9eb6f7c9b23b0434aacfa601e0acb7fc72cb29b
|
setup.py
|
setup.py
|
import sys
import os
from os.path import join
from setuptools import setup
# Also in twarc.py
__version__ = '1.4.0'
if sys.version_info[0] < 3:
dependencies = open(join('requirements', 'python2.txt')).read().split()
else:
dependencies = open(join('requirements', 'python3.txt')).read().split()
if __name__ == "__main__":
setup(
name='twarc',
version=__version__,
url='https://github.com/docnow/twarc',
author='Ed Summers',
author_email='ehs@pobox.com',
packages=['twarc',],
description='Archive tweets from the command line',
install_requires=dependencies,
setup_requires=['pytest-runner'],
tests_require=['pytest'],
entry_points={'console_scripts': ['twarc = twarc:main']}
)
|
import sys
import os
from os.path import join
from setuptools import setup
# Also in twarc.py
__version__ = '1.4.0'
if sys.version_info[0] < 3:
dependencies = open(join('requirements', 'python2.txt')).read().split()
else:
dependencies = open(join('requirements', 'python3.txt')).read().split()
if __name__ == "__main__":
setup(
name='twarc',
version=__version__,
url='https://github.com/docnow/twarc',
author='Ed Summers',
author_email='ehs@pobox.com',
packages=['twarc',],
description='Archive tweets from the command line',
python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*',
install_requires=dependencies,
setup_requires=['pytest-runner'],
tests_require=['pytest'],
entry_points={'console_scripts': ['twarc = twarc:main']}
)
|
Add python_requires to help pip
|
Add python_requires to help pip
When old Python versions are dropped, this will help pip install the right version for people still running those old Python versions.
For more info on how this works:
* https://hackernoon.com/phasing-out-python-runtimes-gracefully-956f112f33c4
* https://github.com/pypa/python-packaging-user-guide/issues/450
|
Python
|
cc0-1.0
|
remagio/twarc,hugovk/twarc,DocNow/twarc,remagio/twarc,edsu/twarc
|
import sys
import os
from os.path import join
from setuptools import setup
# Also in twarc.py
__version__ = '1.4.0'
if sys.version_info[0] < 3:
dependencies = open(join('requirements', 'python2.txt')).read().split()
else:
dependencies = open(join('requirements', 'python3.txt')).read().split()
if __name__ == "__main__":
setup(
name='twarc',
version=__version__,
url='https://github.com/docnow/twarc',
author='Ed Summers',
author_email='ehs@pobox.com',
packages=['twarc',],
description='Archive tweets from the command line',
install_requires=dependencies,
setup_requires=['pytest-runner'],
tests_require=['pytest'],
entry_points={'console_scripts': ['twarc = twarc:main']}
)
Add python_requires to help pip
When old Python versions are dropped, this will help pip install the right version for people still running those old Python versions.
For more info on how this works:
* https://hackernoon.com/phasing-out-python-runtimes-gracefully-956f112f33c4
* https://github.com/pypa/python-packaging-user-guide/issues/450
|
import sys
import os
from os.path import join
from setuptools import setup
# Also in twarc.py
__version__ = '1.4.0'
if sys.version_info[0] < 3:
dependencies = open(join('requirements', 'python2.txt')).read().split()
else:
dependencies = open(join('requirements', 'python3.txt')).read().split()
if __name__ == "__main__":
setup(
name='twarc',
version=__version__,
url='https://github.com/docnow/twarc',
author='Ed Summers',
author_email='ehs@pobox.com',
packages=['twarc',],
description='Archive tweets from the command line',
python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*',
install_requires=dependencies,
setup_requires=['pytest-runner'],
tests_require=['pytest'],
entry_points={'console_scripts': ['twarc = twarc:main']}
)
|
<commit_before>import sys
import os
from os.path import join
from setuptools import setup
# Also in twarc.py
__version__ = '1.4.0'
if sys.version_info[0] < 3:
dependencies = open(join('requirements', 'python2.txt')).read().split()
else:
dependencies = open(join('requirements', 'python3.txt')).read().split()
if __name__ == "__main__":
setup(
name='twarc',
version=__version__,
url='https://github.com/docnow/twarc',
author='Ed Summers',
author_email='ehs@pobox.com',
packages=['twarc',],
description='Archive tweets from the command line',
install_requires=dependencies,
setup_requires=['pytest-runner'],
tests_require=['pytest'],
entry_points={'console_scripts': ['twarc = twarc:main']}
)
<commit_msg>Add python_requires to help pip
When old Python versions are dropped, this will help pip install the right version for people still running those old Python versions.
For more info on how this works:
* https://hackernoon.com/phasing-out-python-runtimes-gracefully-956f112f33c4
* https://github.com/pypa/python-packaging-user-guide/issues/450<commit_after>
|
import sys
import os
from os.path import join
from setuptools import setup
# Also in twarc.py
__version__ = '1.4.0'
if sys.version_info[0] < 3:
dependencies = open(join('requirements', 'python2.txt')).read().split()
else:
dependencies = open(join('requirements', 'python3.txt')).read().split()
if __name__ == "__main__":
setup(
name='twarc',
version=__version__,
url='https://github.com/docnow/twarc',
author='Ed Summers',
author_email='ehs@pobox.com',
packages=['twarc',],
description='Archive tweets from the command line',
python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*',
install_requires=dependencies,
setup_requires=['pytest-runner'],
tests_require=['pytest'],
entry_points={'console_scripts': ['twarc = twarc:main']}
)
|
import sys
import os
from os.path import join
from setuptools import setup
# Also in twarc.py
__version__ = '1.4.0'
if sys.version_info[0] < 3:
dependencies = open(join('requirements', 'python2.txt')).read().split()
else:
dependencies = open(join('requirements', 'python3.txt')).read().split()
if __name__ == "__main__":
setup(
name='twarc',
version=__version__,
url='https://github.com/docnow/twarc',
author='Ed Summers',
author_email='ehs@pobox.com',
packages=['twarc',],
description='Archive tweets from the command line',
install_requires=dependencies,
setup_requires=['pytest-runner'],
tests_require=['pytest'],
entry_points={'console_scripts': ['twarc = twarc:main']}
)
Add python_requires to help pip
When old Python versions are dropped, this will help pip install the right version for people still running those old Python versions.
For more info on how this works:
* https://hackernoon.com/phasing-out-python-runtimes-gracefully-956f112f33c4
* https://github.com/pypa/python-packaging-user-guide/issues/450import sys
import os
from os.path import join
from setuptools import setup
# Also in twarc.py
__version__ = '1.4.0'
if sys.version_info[0] < 3:
dependencies = open(join('requirements', 'python2.txt')).read().split()
else:
dependencies = open(join('requirements', 'python3.txt')).read().split()
if __name__ == "__main__":
setup(
name='twarc',
version=__version__,
url='https://github.com/docnow/twarc',
author='Ed Summers',
author_email='ehs@pobox.com',
packages=['twarc',],
description='Archive tweets from the command line',
python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*',
install_requires=dependencies,
setup_requires=['pytest-runner'],
tests_require=['pytest'],
entry_points={'console_scripts': ['twarc = twarc:main']}
)
|
<commit_before>import sys
import os
from os.path import join
from setuptools import setup
# Also in twarc.py
__version__ = '1.4.0'
if sys.version_info[0] < 3:
dependencies = open(join('requirements', 'python2.txt')).read().split()
else:
dependencies = open(join('requirements', 'python3.txt')).read().split()
if __name__ == "__main__":
setup(
name='twarc',
version=__version__,
url='https://github.com/docnow/twarc',
author='Ed Summers',
author_email='ehs@pobox.com',
packages=['twarc',],
description='Archive tweets from the command line',
install_requires=dependencies,
setup_requires=['pytest-runner'],
tests_require=['pytest'],
entry_points={'console_scripts': ['twarc = twarc:main']}
)
<commit_msg>Add python_requires to help pip
When old Python versions are dropped, this will help pip install the right version for people still running those old Python versions.
For more info on how this works:
* https://hackernoon.com/phasing-out-python-runtimes-gracefully-956f112f33c4
* https://github.com/pypa/python-packaging-user-guide/issues/450<commit_after>import sys
import os
from os.path import join
from setuptools import setup
# Also in twarc.py
__version__ = '1.4.0'
if sys.version_info[0] < 3:
dependencies = open(join('requirements', 'python2.txt')).read().split()
else:
dependencies = open(join('requirements', 'python3.txt')).read().split()
if __name__ == "__main__":
setup(
name='twarc',
version=__version__,
url='https://github.com/docnow/twarc',
author='Ed Summers',
author_email='ehs@pobox.com',
packages=['twarc',],
description='Archive tweets from the command line',
python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*',
install_requires=dependencies,
setup_requires=['pytest-runner'],
tests_require=['pytest'],
entry_points={'console_scripts': ['twarc = twarc:main']}
)
|
4e1fc34116003c431a2a5199f4620ffa07a3305e
|
setup.py
|
setup.py
|
#!/usr/bin/env python
import sys
from setuptools import setup, find_packages
if sys.version_info < (3, 3):
sys.exit('Sorry, Python < 3.3 is not supported')
setup(
name='pyecore',
version='0.5.5-dev',
description=('A Python(ic) Implementation of the Eclipse Modeling '
'Framework (EMF/Ecore)'),
long_description=open('README.rst').read(),
keywords='model metamodel EMF Ecore MDE',
url='https://github.com/pyecore/pyecore',
author='Vincent Aranega',
author_email='vincent.aranega@gmail.com',
packages=find_packages(exclude=['examples', 'tests']),
package_data={'': ['LICENSE',
'README.rst']},
include_package_data=True,
install_requires=['enum34;python_version<"3.4"',
'ordered-set',
'lxml'],
tests_require={'pytest'},
license='BSD 3-Clause',
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Operating System :: OS Independent',
'Intended Audience :: Developers',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries',
'License :: OSI Approved :: BSD License',
]
)
|
#!/usr/bin/env python
import sys
from setuptools import setup, find_packages
if sys.version_info < (3, 3):
sys.exit('Sorry, Python < 3.3 is not supported')
setup(
name='pyecore',
version='0.5.5-dev',
description=('A Python(ic) Implementation of the Eclipse Modeling '
'Framework (EMF/Ecore)'),
long_description=open('README.rst').read(),
keywords='model metamodel EMF Ecore MDE',
url='https://github.com/pyecore/pyecore',
author='Vincent Aranega',
author_email='vincent.aranega@gmail.com',
packages=find_packages(exclude=['examples', 'tests']),
data_files=[('', ['LICENSE', 'README.rst'])],
install_requires=['enum34;python_version<"3.4"',
'ordered-set',
'lxml'],
tests_require={'pytest'},
license='BSD 3-Clause',
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Operating System :: OS Independent',
'Intended Audience :: Developers',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries',
'License :: OSI Approved :: BSD License',
]
)
|
Fix missing LICENCE in dist package
|
Fix missing LICENCE in dist package
|
Python
|
bsd-3-clause
|
aranega/pyecore,pyecore/pyecore
|
#!/usr/bin/env python
import sys
from setuptools import setup, find_packages
if sys.version_info < (3, 3):
sys.exit('Sorry, Python < 3.3 is not supported')
setup(
name='pyecore',
version='0.5.5-dev',
description=('A Python(ic) Implementation of the Eclipse Modeling '
'Framework (EMF/Ecore)'),
long_description=open('README.rst').read(),
keywords='model metamodel EMF Ecore MDE',
url='https://github.com/pyecore/pyecore',
author='Vincent Aranega',
author_email='vincent.aranega@gmail.com',
packages=find_packages(exclude=['examples', 'tests']),
package_data={'': ['LICENSE',
'README.rst']},
include_package_data=True,
install_requires=['enum34;python_version<"3.4"',
'ordered-set',
'lxml'],
tests_require={'pytest'},
license='BSD 3-Clause',
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Operating System :: OS Independent',
'Intended Audience :: Developers',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries',
'License :: OSI Approved :: BSD License',
]
)
Fix missing LICENCE in dist package
|
#!/usr/bin/env python
import sys
from setuptools import setup, find_packages
if sys.version_info < (3, 3):
sys.exit('Sorry, Python < 3.3 is not supported')
setup(
name='pyecore',
version='0.5.5-dev',
description=('A Python(ic) Implementation of the Eclipse Modeling '
'Framework (EMF/Ecore)'),
long_description=open('README.rst').read(),
keywords='model metamodel EMF Ecore MDE',
url='https://github.com/pyecore/pyecore',
author='Vincent Aranega',
author_email='vincent.aranega@gmail.com',
packages=find_packages(exclude=['examples', 'tests']),
data_files=[('', ['LICENSE', 'README.rst'])],
install_requires=['enum34;python_version<"3.4"',
'ordered-set',
'lxml'],
tests_require={'pytest'},
license='BSD 3-Clause',
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Operating System :: OS Independent',
'Intended Audience :: Developers',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries',
'License :: OSI Approved :: BSD License',
]
)
|
<commit_before>#!/usr/bin/env python
import sys
from setuptools import setup, find_packages
if sys.version_info < (3, 3):
sys.exit('Sorry, Python < 3.3 is not supported')
setup(
name='pyecore',
version='0.5.5-dev',
description=('A Python(ic) Implementation of the Eclipse Modeling '
'Framework (EMF/Ecore)'),
long_description=open('README.rst').read(),
keywords='model metamodel EMF Ecore MDE',
url='https://github.com/pyecore/pyecore',
author='Vincent Aranega',
author_email='vincent.aranega@gmail.com',
packages=find_packages(exclude=['examples', 'tests']),
package_data={'': ['LICENSE',
'README.rst']},
include_package_data=True,
install_requires=['enum34;python_version<"3.4"',
'ordered-set',
'lxml'],
tests_require={'pytest'},
license='BSD 3-Clause',
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Operating System :: OS Independent',
'Intended Audience :: Developers',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries',
'License :: OSI Approved :: BSD License',
]
)
<commit_msg>Fix missing LICENCE in dist package<commit_after>
|
#!/usr/bin/env python
import sys
from setuptools import setup, find_packages
if sys.version_info < (3, 3):
sys.exit('Sorry, Python < 3.3 is not supported')
setup(
name='pyecore',
version='0.5.5-dev',
description=('A Python(ic) Implementation of the Eclipse Modeling '
'Framework (EMF/Ecore)'),
long_description=open('README.rst').read(),
keywords='model metamodel EMF Ecore MDE',
url='https://github.com/pyecore/pyecore',
author='Vincent Aranega',
author_email='vincent.aranega@gmail.com',
packages=find_packages(exclude=['examples', 'tests']),
data_files=[('', ['LICENSE', 'README.rst'])],
install_requires=['enum34;python_version<"3.4"',
'ordered-set',
'lxml'],
tests_require={'pytest'},
license='BSD 3-Clause',
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Operating System :: OS Independent',
'Intended Audience :: Developers',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries',
'License :: OSI Approved :: BSD License',
]
)
|
#!/usr/bin/env python
import sys
from setuptools import setup, find_packages
if sys.version_info < (3, 3):
sys.exit('Sorry, Python < 3.3 is not supported')
setup(
name='pyecore',
version='0.5.5-dev',
description=('A Python(ic) Implementation of the Eclipse Modeling '
'Framework (EMF/Ecore)'),
long_description=open('README.rst').read(),
keywords='model metamodel EMF Ecore MDE',
url='https://github.com/pyecore/pyecore',
author='Vincent Aranega',
author_email='vincent.aranega@gmail.com',
packages=find_packages(exclude=['examples', 'tests']),
package_data={'': ['LICENSE',
'README.rst']},
include_package_data=True,
install_requires=['enum34;python_version<"3.4"',
'ordered-set',
'lxml'],
tests_require={'pytest'},
license='BSD 3-Clause',
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Operating System :: OS Independent',
'Intended Audience :: Developers',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries',
'License :: OSI Approved :: BSD License',
]
)
Fix missing LICENCE in dist package#!/usr/bin/env python
import sys
from setuptools import setup, find_packages
if sys.version_info < (3, 3):
sys.exit('Sorry, Python < 3.3 is not supported')
setup(
name='pyecore',
version='0.5.5-dev',
description=('A Python(ic) Implementation of the Eclipse Modeling '
'Framework (EMF/Ecore)'),
long_description=open('README.rst').read(),
keywords='model metamodel EMF Ecore MDE',
url='https://github.com/pyecore/pyecore',
author='Vincent Aranega',
author_email='vincent.aranega@gmail.com',
packages=find_packages(exclude=['examples', 'tests']),
data_files=[('', ['LICENSE', 'README.rst'])],
install_requires=['enum34;python_version<"3.4"',
'ordered-set',
'lxml'],
tests_require={'pytest'},
license='BSD 3-Clause',
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Operating System :: OS Independent',
'Intended Audience :: Developers',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries',
'License :: OSI Approved :: BSD License',
]
)
|
<commit_before>#!/usr/bin/env python
import sys
from setuptools import setup, find_packages
if sys.version_info < (3, 3):
sys.exit('Sorry, Python < 3.3 is not supported')
setup(
name='pyecore',
version='0.5.5-dev',
description=('A Python(ic) Implementation of the Eclipse Modeling '
'Framework (EMF/Ecore)'),
long_description=open('README.rst').read(),
keywords='model metamodel EMF Ecore MDE',
url='https://github.com/pyecore/pyecore',
author='Vincent Aranega',
author_email='vincent.aranega@gmail.com',
packages=find_packages(exclude=['examples', 'tests']),
package_data={'': ['LICENSE',
'README.rst']},
include_package_data=True,
install_requires=['enum34;python_version<"3.4"',
'ordered-set',
'lxml'],
tests_require={'pytest'},
license='BSD 3-Clause',
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Operating System :: OS Independent',
'Intended Audience :: Developers',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries',
'License :: OSI Approved :: BSD License',
]
)
<commit_msg>Fix missing LICENCE in dist package<commit_after>#!/usr/bin/env python
import sys
from setuptools import setup, find_packages
if sys.version_info < (3, 3):
sys.exit('Sorry, Python < 3.3 is not supported')
setup(
name='pyecore',
version='0.5.5-dev',
description=('A Python(ic) Implementation of the Eclipse Modeling '
'Framework (EMF/Ecore)'),
long_description=open('README.rst').read(),
keywords='model metamodel EMF Ecore MDE',
url='https://github.com/pyecore/pyecore',
author='Vincent Aranega',
author_email='vincent.aranega@gmail.com',
packages=find_packages(exclude=['examples', 'tests']),
data_files=[('', ['LICENSE', 'README.rst'])],
install_requires=['enum34;python_version<"3.4"',
'ordered-set',
'lxml'],
tests_require={'pytest'},
license='BSD 3-Clause',
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Operating System :: OS Independent',
'Intended Audience :: Developers',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries',
'License :: OSI Approved :: BSD License',
]
)
|
6132f11d70f5b0a694d9b36caa2fc23561fb7722
|
setup.py
|
setup.py
|
import setuptools
import sys
requires = 'requires/python{0}.txt'.format(sys.version_info[0])
print(requires)
with open(requires) as handle:
requirements = [line.strip() for line in handle.readlines()]
setuptools.setup(
name='sprockets.mixins.avro-publisher',
version='1.0.0',
description='Mixin for publishing events to RabbitMQ as avro datums',
long_description=open('README.rst').read(),
url='https://github.com/sprockets/sprockets.mixins.avro-publisher',
author='AWeber Communications, Inc.',
author_email='api@aweber.com',
license='BSD',
classifiers=[
'Development Status :: 3 - Alpha', 'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License', 'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Libraries :: Python Modules'
],
packages=setuptools.find_packages(),
namespace_packages=['sprockets', 'sprockets.mixins'],
install_requires=requirements,
zip_safe=True)
|
import setuptools
import sys
requires = 'requires/python{0}.txt'.format(sys.version_info[0])
print(requires)
with open(requires) as handle:
requirements = [line.strip() for line in handle.readlines()]
setuptools.setup(
name='sprockets.mixins.avro-publisher',
version='1.0.0',
description='Mixin for publishing events to RabbitMQ as avro datums',
long_description=open('README.rst').read(),
url='https://github.com/sprockets/sprockets.mixins.avro-publisher',
author='AWeber Communications, Inc.',
author_email='api@aweber.com',
license='BSD',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: Implementation :: CPython',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Libraries :: Python Modules'
],
packages=setuptools.find_packages(),
namespace_packages=['sprockets', 'sprockets.mixins'],
install_requires=requirements,
zip_safe=True)
|
Adjust development status -> beta.
|
Adjust development status -> beta.
|
Python
|
bsd-3-clause
|
sprockets/sprockets.mixins.avro-publisher
|
import setuptools
import sys
requires = 'requires/python{0}.txt'.format(sys.version_info[0])
print(requires)
with open(requires) as handle:
requirements = [line.strip() for line in handle.readlines()]
setuptools.setup(
name='sprockets.mixins.avro-publisher',
version='1.0.0',
description='Mixin for publishing events to RabbitMQ as avro datums',
long_description=open('README.rst').read(),
url='https://github.com/sprockets/sprockets.mixins.avro-publisher',
author='AWeber Communications, Inc.',
author_email='api@aweber.com',
license='BSD',
classifiers=[
'Development Status :: 3 - Alpha', 'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License', 'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Libraries :: Python Modules'
],
packages=setuptools.find_packages(),
namespace_packages=['sprockets', 'sprockets.mixins'],
install_requires=requirements,
zip_safe=True)
Adjust development status -> beta.
|
import setuptools
import sys
requires = 'requires/python{0}.txt'.format(sys.version_info[0])
print(requires)
with open(requires) as handle:
requirements = [line.strip() for line in handle.readlines()]
setuptools.setup(
name='sprockets.mixins.avro-publisher',
version='1.0.0',
description='Mixin for publishing events to RabbitMQ as avro datums',
long_description=open('README.rst').read(),
url='https://github.com/sprockets/sprockets.mixins.avro-publisher',
author='AWeber Communications, Inc.',
author_email='api@aweber.com',
license='BSD',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: Implementation :: CPython',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Libraries :: Python Modules'
],
packages=setuptools.find_packages(),
namespace_packages=['sprockets', 'sprockets.mixins'],
install_requires=requirements,
zip_safe=True)
|
<commit_before>import setuptools
import sys
requires = 'requires/python{0}.txt'.format(sys.version_info[0])
print(requires)
with open(requires) as handle:
requirements = [line.strip() for line in handle.readlines()]
setuptools.setup(
name='sprockets.mixins.avro-publisher',
version='1.0.0',
description='Mixin for publishing events to RabbitMQ as avro datums',
long_description=open('README.rst').read(),
url='https://github.com/sprockets/sprockets.mixins.avro-publisher',
author='AWeber Communications, Inc.',
author_email='api@aweber.com',
license='BSD',
classifiers=[
'Development Status :: 3 - Alpha', 'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License', 'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Libraries :: Python Modules'
],
packages=setuptools.find_packages(),
namespace_packages=['sprockets', 'sprockets.mixins'],
install_requires=requirements,
zip_safe=True)
<commit_msg>Adjust development status -> beta.<commit_after>
|
import setuptools
import sys
requires = 'requires/python{0}.txt'.format(sys.version_info[0])
print(requires)
with open(requires) as handle:
requirements = [line.strip() for line in handle.readlines()]
setuptools.setup(
name='sprockets.mixins.avro-publisher',
version='1.0.0',
description='Mixin for publishing events to RabbitMQ as avro datums',
long_description=open('README.rst').read(),
url='https://github.com/sprockets/sprockets.mixins.avro-publisher',
author='AWeber Communications, Inc.',
author_email='api@aweber.com',
license='BSD',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: Implementation :: CPython',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Libraries :: Python Modules'
],
packages=setuptools.find_packages(),
namespace_packages=['sprockets', 'sprockets.mixins'],
install_requires=requirements,
zip_safe=True)
|
import setuptools
import sys
requires = 'requires/python{0}.txt'.format(sys.version_info[0])
print(requires)
with open(requires) as handle:
requirements = [line.strip() for line in handle.readlines()]
setuptools.setup(
name='sprockets.mixins.avro-publisher',
version='1.0.0',
description='Mixin for publishing events to RabbitMQ as avro datums',
long_description=open('README.rst').read(),
url='https://github.com/sprockets/sprockets.mixins.avro-publisher',
author='AWeber Communications, Inc.',
author_email='api@aweber.com',
license='BSD',
classifiers=[
'Development Status :: 3 - Alpha', 'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License', 'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Libraries :: Python Modules'
],
packages=setuptools.find_packages(),
namespace_packages=['sprockets', 'sprockets.mixins'],
install_requires=requirements,
zip_safe=True)
Adjust development status -> beta.import setuptools
import sys
requires = 'requires/python{0}.txt'.format(sys.version_info[0])
print(requires)
with open(requires) as handle:
requirements = [line.strip() for line in handle.readlines()]
setuptools.setup(
name='sprockets.mixins.avro-publisher',
version='1.0.0',
description='Mixin for publishing events to RabbitMQ as avro datums',
long_description=open('README.rst').read(),
url='https://github.com/sprockets/sprockets.mixins.avro-publisher',
author='AWeber Communications, Inc.',
author_email='api@aweber.com',
license='BSD',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: Implementation :: CPython',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Libraries :: Python Modules'
],
packages=setuptools.find_packages(),
namespace_packages=['sprockets', 'sprockets.mixins'],
install_requires=requirements,
zip_safe=True)
|
<commit_before>import setuptools
import sys
requires = 'requires/python{0}.txt'.format(sys.version_info[0])
print(requires)
with open(requires) as handle:
requirements = [line.strip() for line in handle.readlines()]
setuptools.setup(
name='sprockets.mixins.avro-publisher',
version='1.0.0',
description='Mixin for publishing events to RabbitMQ as avro datums',
long_description=open('README.rst').read(),
url='https://github.com/sprockets/sprockets.mixins.avro-publisher',
author='AWeber Communications, Inc.',
author_email='api@aweber.com',
license='BSD',
classifiers=[
'Development Status :: 3 - Alpha', 'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License', 'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Libraries :: Python Modules'
],
packages=setuptools.find_packages(),
namespace_packages=['sprockets', 'sprockets.mixins'],
install_requires=requirements,
zip_safe=True)
<commit_msg>Adjust development status -> beta.<commit_after>import setuptools
import sys
requires = 'requires/python{0}.txt'.format(sys.version_info[0])
print(requires)
with open(requires) as handle:
requirements = [line.strip() for line in handle.readlines()]
setuptools.setup(
name='sprockets.mixins.avro-publisher',
version='1.0.0',
description='Mixin for publishing events to RabbitMQ as avro datums',
long_description=open('README.rst').read(),
url='https://github.com/sprockets/sprockets.mixins.avro-publisher',
author='AWeber Communications, Inc.',
author_email='api@aweber.com',
license='BSD',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: Implementation :: CPython',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Libraries :: Python Modules'
],
packages=setuptools.find_packages(),
namespace_packages=['sprockets', 'sprockets.mixins'],
install_requires=requirements,
zip_safe=True)
|
d35330e9949833b37bfd56007e61ba65c63d6fd9
|
setup.py
|
setup.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from setuptools import setup
setup(name='githublabelscopy',
version='1.0.0',
description='A tool to copy labels between repositories using Github API',
url='http://github.com/fpietka/github-labels-copy',
author='François Pietka',
author_email='francois[at]]pietka[dot]fr',
license='MIT',
packages=['githublabelscopy'],
long_description=open('README.rst').read(),
install_requires=[
'PyGithub==1.32'
],
entry_points={
'console_scripts': [
'github-labels-copy = githublabelscopy.githublabelscopy:main'
],
},
classifiers=[
'Intended Audience :: Developers',
'Environment :: Console',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4'
],
zip_safe=True)
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from setuptools import setup
setup(name='githublabelscopy',
version='1.0.0',
description='A tool to copy labels between repositories using Github API',
url='http://github.com/fpietka/github-labels-copy',
author='François Pietka',
author_email='francois[at]]pietka[dot]fr',
license='MIT',
packages=['githublabelscopy'],
long_description=open('README.rst').read(),
install_requires=[
'PyGithub==1.32'
],
entry_points={
'console_scripts': [
'github-labels-copy = githublabelscopy.githublabelscopy:main'
],
},
classifiers=[
'Intended Audience :: Developers',
'Environment :: Console',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6'
],
zip_safe=True)
|
Add more python3 versions compatible
|
Add more python3 versions compatible
|
Python
|
mit
|
fpietka/github-labels-copy
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from setuptools import setup
setup(name='githublabelscopy',
version='1.0.0',
description='A tool to copy labels between repositories using Github API',
url='http://github.com/fpietka/github-labels-copy',
author='François Pietka',
author_email='francois[at]]pietka[dot]fr',
license='MIT',
packages=['githublabelscopy'],
long_description=open('README.rst').read(),
install_requires=[
'PyGithub==1.32'
],
entry_points={
'console_scripts': [
'github-labels-copy = githublabelscopy.githublabelscopy:main'
],
},
classifiers=[
'Intended Audience :: Developers',
'Environment :: Console',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4'
],
zip_safe=True)
Add more python3 versions compatible
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from setuptools import setup
setup(name='githublabelscopy',
version='1.0.0',
description='A tool to copy labels between repositories using Github API',
url='http://github.com/fpietka/github-labels-copy',
author='François Pietka',
author_email='francois[at]]pietka[dot]fr',
license='MIT',
packages=['githublabelscopy'],
long_description=open('README.rst').read(),
install_requires=[
'PyGithub==1.32'
],
entry_points={
'console_scripts': [
'github-labels-copy = githublabelscopy.githublabelscopy:main'
],
},
classifiers=[
'Intended Audience :: Developers',
'Environment :: Console',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6'
],
zip_safe=True)
|
<commit_before>#!/usr/bin/python
# -*- coding: utf-8 -*-
from setuptools import setup
setup(name='githublabelscopy',
version='1.0.0',
description='A tool to copy labels between repositories using Github API',
url='http://github.com/fpietka/github-labels-copy',
author='François Pietka',
author_email='francois[at]]pietka[dot]fr',
license='MIT',
packages=['githublabelscopy'],
long_description=open('README.rst').read(),
install_requires=[
'PyGithub==1.32'
],
entry_points={
'console_scripts': [
'github-labels-copy = githublabelscopy.githublabelscopy:main'
],
},
classifiers=[
'Intended Audience :: Developers',
'Environment :: Console',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4'
],
zip_safe=True)
<commit_msg>Add more python3 versions compatible<commit_after>
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from setuptools import setup
setup(name='githublabelscopy',
version='1.0.0',
description='A tool to copy labels between repositories using Github API',
url='http://github.com/fpietka/github-labels-copy',
author='François Pietka',
author_email='francois[at]]pietka[dot]fr',
license='MIT',
packages=['githublabelscopy'],
long_description=open('README.rst').read(),
install_requires=[
'PyGithub==1.32'
],
entry_points={
'console_scripts': [
'github-labels-copy = githublabelscopy.githublabelscopy:main'
],
},
classifiers=[
'Intended Audience :: Developers',
'Environment :: Console',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6'
],
zip_safe=True)
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from setuptools import setup
setup(name='githublabelscopy',
version='1.0.0',
description='A tool to copy labels between repositories using Github API',
url='http://github.com/fpietka/github-labels-copy',
author='François Pietka',
author_email='francois[at]]pietka[dot]fr',
license='MIT',
packages=['githublabelscopy'],
long_description=open('README.rst').read(),
install_requires=[
'PyGithub==1.32'
],
entry_points={
'console_scripts': [
'github-labels-copy = githublabelscopy.githublabelscopy:main'
],
},
classifiers=[
'Intended Audience :: Developers',
'Environment :: Console',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4'
],
zip_safe=True)
Add more python3 versions compatible#!/usr/bin/python
# -*- coding: utf-8 -*-
from setuptools import setup
setup(name='githublabelscopy',
version='1.0.0',
description='A tool to copy labels between repositories using Github API',
url='http://github.com/fpietka/github-labels-copy',
author='François Pietka',
author_email='francois[at]]pietka[dot]fr',
license='MIT',
packages=['githublabelscopy'],
long_description=open('README.rst').read(),
install_requires=[
'PyGithub==1.32'
],
entry_points={
'console_scripts': [
'github-labels-copy = githublabelscopy.githublabelscopy:main'
],
},
classifiers=[
'Intended Audience :: Developers',
'Environment :: Console',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6'
],
zip_safe=True)
|
<commit_before>#!/usr/bin/python
# -*- coding: utf-8 -*-
from setuptools import setup
setup(name='githublabelscopy',
version='1.0.0',
description='A tool to copy labels between repositories using Github API',
url='http://github.com/fpietka/github-labels-copy',
author='François Pietka',
author_email='francois[at]]pietka[dot]fr',
license='MIT',
packages=['githublabelscopy'],
long_description=open('README.rst').read(),
install_requires=[
'PyGithub==1.32'
],
entry_points={
'console_scripts': [
'github-labels-copy = githublabelscopy.githublabelscopy:main'
],
},
classifiers=[
'Intended Audience :: Developers',
'Environment :: Console',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4'
],
zip_safe=True)
<commit_msg>Add more python3 versions compatible<commit_after>#!/usr/bin/python
# -*- coding: utf-8 -*-
from setuptools import setup
setup(name='githublabelscopy',
version='1.0.0',
description='A tool to copy labels between repositories using Github API',
url='http://github.com/fpietka/github-labels-copy',
author='François Pietka',
author_email='francois[at]]pietka[dot]fr',
license='MIT',
packages=['githublabelscopy'],
long_description=open('README.rst').read(),
install_requires=[
'PyGithub==1.32'
],
entry_points={
'console_scripts': [
'github-labels-copy = githublabelscopy.githublabelscopy:main'
],
},
classifiers=[
'Intended Audience :: Developers',
'Environment :: Console',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6'
],
zip_safe=True)
|
11359d5b72af828635eb80e7c71e5a9bf92defd8
|
setup.py
|
setup.py
|
# import multiprocessing to avoid this bug (http://bugs.python.org/issue15881#msg170215)
import multiprocessing
assert multiprocessing
import re
from setuptools import setup, find_packages
def get_version():
"""
Extracts the version number from the version.py file.
"""
VERSION_FILE = '{{ project_name }}/version.py'
mo = re.search(r'^__version__ = [\'"]([^\'"]*)[\'"]', open(VERSION_FILE, 'rt').read(), re.M)
if mo:
return mo.group(1)
else:
raise RuntimeError('Unable to find version string in {0}.'.format(VERSION_FILE))
setup(
name='',
version=get_version(),
description='',
long_description=open('README.md').read(),
url='',
author='',
author_email='',
keywords='',
packages=find_packages(),
classifiers=[
'Programming Language :: Python',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Framework :: Django',
],
license='MIT',
install_requires=[
'django>=1.6',
],
tests_require=[
'psycopg2',
'django-nose',
'south',
],
test_suite='run_tests.run_tests',
include_package_data=True,
)
|
# import multiprocessing to avoid this bug (http://bugs.python.org/issue15881#msg170215)
import multiprocessing
assert multiprocessing
import re
from setuptools import setup, find_packages
def get_version():
"""
Extracts the version number from the version.py file.
"""
VERSION_FILE = '{{ project_name }}/version.py'
mo = re.search(r'^__version__ = [\'"]([^\'"]*)[\'"]', open(VERSION_FILE, 'rt').read(), re.M)
if mo:
return mo.group(1)
else:
raise RuntimeError('Unable to find version string in {0}.'.format(VERSION_FILE))
setup(
name='',
version=get_version(),
description='',
long_description=open('README.md').read(),
url='',
author='',
author_email='',
keywords='',
packages=find_packages(),
classifiers=[
'Programming Language :: Python',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Framework :: Django',
],
license='MIT',
install_requires=[
'django>=1.6',
],
tests_require=[
'psycopg2',
'django-nose',
'south',
'mock',
],
test_suite='run_tests.run_tests',
include_package_data=True,
)
|
Add mock to test requirements.
|
Add mock to test requirements.
|
Python
|
mit
|
ambitioninc/django-app-template
|
# import multiprocessing to avoid this bug (http://bugs.python.org/issue15881#msg170215)
import multiprocessing
assert multiprocessing
import re
from setuptools import setup, find_packages
def get_version():
"""
Extracts the version number from the version.py file.
"""
VERSION_FILE = '{{ project_name }}/version.py'
mo = re.search(r'^__version__ = [\'"]([^\'"]*)[\'"]', open(VERSION_FILE, 'rt').read(), re.M)
if mo:
return mo.group(1)
else:
raise RuntimeError('Unable to find version string in {0}.'.format(VERSION_FILE))
setup(
name='',
version=get_version(),
description='',
long_description=open('README.md').read(),
url='',
author='',
author_email='',
keywords='',
packages=find_packages(),
classifiers=[
'Programming Language :: Python',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Framework :: Django',
],
license='MIT',
install_requires=[
'django>=1.6',
],
tests_require=[
'psycopg2',
'django-nose',
'south',
],
test_suite='run_tests.run_tests',
include_package_data=True,
)
Add mock to test requirements.
|
# import multiprocessing to avoid this bug (http://bugs.python.org/issue15881#msg170215)
import multiprocessing
assert multiprocessing
import re
from setuptools import setup, find_packages
def get_version():
"""
Extracts the version number from the version.py file.
"""
VERSION_FILE = '{{ project_name }}/version.py'
mo = re.search(r'^__version__ = [\'"]([^\'"]*)[\'"]', open(VERSION_FILE, 'rt').read(), re.M)
if mo:
return mo.group(1)
else:
raise RuntimeError('Unable to find version string in {0}.'.format(VERSION_FILE))
setup(
name='',
version=get_version(),
description='',
long_description=open('README.md').read(),
url='',
author='',
author_email='',
keywords='',
packages=find_packages(),
classifiers=[
'Programming Language :: Python',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Framework :: Django',
],
license='MIT',
install_requires=[
'django>=1.6',
],
tests_require=[
'psycopg2',
'django-nose',
'south',
'mock',
],
test_suite='run_tests.run_tests',
include_package_data=True,
)
|
<commit_before># import multiprocessing to avoid this bug (http://bugs.python.org/issue15881#msg170215)
import multiprocessing
assert multiprocessing
import re
from setuptools import setup, find_packages
def get_version():
"""
Extracts the version number from the version.py file.
"""
VERSION_FILE = '{{ project_name }}/version.py'
mo = re.search(r'^__version__ = [\'"]([^\'"]*)[\'"]', open(VERSION_FILE, 'rt').read(), re.M)
if mo:
return mo.group(1)
else:
raise RuntimeError('Unable to find version string in {0}.'.format(VERSION_FILE))
setup(
name='',
version=get_version(),
description='',
long_description=open('README.md').read(),
url='',
author='',
author_email='',
keywords='',
packages=find_packages(),
classifiers=[
'Programming Language :: Python',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Framework :: Django',
],
license='MIT',
install_requires=[
'django>=1.6',
],
tests_require=[
'psycopg2',
'django-nose',
'south',
],
test_suite='run_tests.run_tests',
include_package_data=True,
)
<commit_msg>Add mock to test requirements.<commit_after>
|
# import multiprocessing to avoid this bug (http://bugs.python.org/issue15881#msg170215)
import multiprocessing
assert multiprocessing
import re
from setuptools import setup, find_packages
def get_version():
"""
Extracts the version number from the version.py file.
"""
VERSION_FILE = '{{ project_name }}/version.py'
mo = re.search(r'^__version__ = [\'"]([^\'"]*)[\'"]', open(VERSION_FILE, 'rt').read(), re.M)
if mo:
return mo.group(1)
else:
raise RuntimeError('Unable to find version string in {0}.'.format(VERSION_FILE))
setup(
name='',
version=get_version(),
description='',
long_description=open('README.md').read(),
url='',
author='',
author_email='',
keywords='',
packages=find_packages(),
classifiers=[
'Programming Language :: Python',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Framework :: Django',
],
license='MIT',
install_requires=[
'django>=1.6',
],
tests_require=[
'psycopg2',
'django-nose',
'south',
'mock',
],
test_suite='run_tests.run_tests',
include_package_data=True,
)
|
# import multiprocessing to avoid this bug (http://bugs.python.org/issue15881#msg170215)
import multiprocessing
assert multiprocessing
import re
from setuptools import setup, find_packages
def get_version():
"""
Extracts the version number from the version.py file.
"""
VERSION_FILE = '{{ project_name }}/version.py'
mo = re.search(r'^__version__ = [\'"]([^\'"]*)[\'"]', open(VERSION_FILE, 'rt').read(), re.M)
if mo:
return mo.group(1)
else:
raise RuntimeError('Unable to find version string in {0}.'.format(VERSION_FILE))
setup(
name='',
version=get_version(),
description='',
long_description=open('README.md').read(),
url='',
author='',
author_email='',
keywords='',
packages=find_packages(),
classifiers=[
'Programming Language :: Python',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Framework :: Django',
],
license='MIT',
install_requires=[
'django>=1.6',
],
tests_require=[
'psycopg2',
'django-nose',
'south',
],
test_suite='run_tests.run_tests',
include_package_data=True,
)
Add mock to test requirements.# import multiprocessing to avoid this bug (http://bugs.python.org/issue15881#msg170215)
import multiprocessing
assert multiprocessing
import re
from setuptools import setup, find_packages
def get_version():
"""
Extracts the version number from the version.py file.
"""
VERSION_FILE = '{{ project_name }}/version.py'
mo = re.search(r'^__version__ = [\'"]([^\'"]*)[\'"]', open(VERSION_FILE, 'rt').read(), re.M)
if mo:
return mo.group(1)
else:
raise RuntimeError('Unable to find version string in {0}.'.format(VERSION_FILE))
setup(
name='',
version=get_version(),
description='',
long_description=open('README.md').read(),
url='',
author='',
author_email='',
keywords='',
packages=find_packages(),
classifiers=[
'Programming Language :: Python',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Framework :: Django',
],
license='MIT',
install_requires=[
'django>=1.6',
],
tests_require=[
'psycopg2',
'django-nose',
'south',
'mock',
],
test_suite='run_tests.run_tests',
include_package_data=True,
)
|
<commit_before># import multiprocessing to avoid this bug (http://bugs.python.org/issue15881#msg170215)
import multiprocessing
assert multiprocessing
import re
from setuptools import setup, find_packages
def get_version():
"""
Extracts the version number from the version.py file.
"""
VERSION_FILE = '{{ project_name }}/version.py'
mo = re.search(r'^__version__ = [\'"]([^\'"]*)[\'"]', open(VERSION_FILE, 'rt').read(), re.M)
if mo:
return mo.group(1)
else:
raise RuntimeError('Unable to find version string in {0}.'.format(VERSION_FILE))
setup(
name='',
version=get_version(),
description='',
long_description=open('README.md').read(),
url='',
author='',
author_email='',
keywords='',
packages=find_packages(),
classifiers=[
'Programming Language :: Python',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Framework :: Django',
],
license='MIT',
install_requires=[
'django>=1.6',
],
tests_require=[
'psycopg2',
'django-nose',
'south',
],
test_suite='run_tests.run_tests',
include_package_data=True,
)
<commit_msg>Add mock to test requirements.<commit_after># import multiprocessing to avoid this bug (http://bugs.python.org/issue15881#msg170215)
import multiprocessing
assert multiprocessing
import re
from setuptools import setup, find_packages
def get_version():
"""
Extracts the version number from the version.py file.
"""
VERSION_FILE = '{{ project_name }}/version.py'
mo = re.search(r'^__version__ = [\'"]([^\'"]*)[\'"]', open(VERSION_FILE, 'rt').read(), re.M)
if mo:
return mo.group(1)
else:
raise RuntimeError('Unable to find version string in {0}.'.format(VERSION_FILE))
setup(
name='',
version=get_version(),
description='',
long_description=open('README.md').read(),
url='',
author='',
author_email='',
keywords='',
packages=find_packages(),
classifiers=[
'Programming Language :: Python',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Framework :: Django',
],
license='MIT',
install_requires=[
'django>=1.6',
],
tests_require=[
'psycopg2',
'django-nose',
'south',
'mock',
],
test_suite='run_tests.run_tests',
include_package_data=True,
)
|
2a4c13d46cb7168482985af4ab7eeaf251042a09
|
camera_filters.py
|
camera_filters.py
|
""" Apply different filters here """
import cv2 # import OpenCV 3 module
camera = cv2.VideoCapture(0) # get default camera
mode = 2 # default mode, apply Canny edge detection
while True:
ok, frame = camera.read() # read frame
if ok: # frame is read correctly
if mode == 2:
frame = cv2.Canny(frame, 100, 200) # Canny edge detection
cv2.imshow('My camera', frame) # show frame
key = cv2.waitKey(1) & 0xff # read keystroke
if key == 27: break # <Escape> key pressed, exit from cycle
if key == ord('1'): mode = 1 # show unchanged frame
if key == ord('2'): mode = 2 # apply Canny edge detection
camera.release() # release web camera
cv2.destroyAllWindows()
|
""" Apply different filters here """
import cv2 # import OpenCV 3 module
camera = cv2.VideoCapture(0) # get default camera
mode = 2 # default mode, apply Canny edge detection
while True:
ok, frame = camera.read() # read frame
if ok: # frame is read correctly
if mode == 2:
frame = cv2.Canny(frame, 100, 200) # Canny edge detection
if mode == 3:
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # convert to grayscale
frame = cv2.Canny(frame, 100, 200) # Canny edge detection
cv2.imshow('My camera', frame) # show frame
key = cv2.waitKey(1) & 0xff # read keystroke
if key == 27: break # <Escape> key pressed, exit from cycle
if key == ord('1'): mode = 1 # show unchanged frame
if key == ord('2'): mode = 2 # apply Canny edge detection
if key == ord('3'): mode = 3 # apply Canny to gray frame
camera.release() # release web camera
cv2.destroyAllWindows()
|
Apply Canny edge detection to grayscale. No big difference with colored Canny edge detection.
|
Apply Canny edge detection to grayscale. No big difference with colored Canny edge detection.
|
Python
|
mit
|
foobar167/junkyard,foobar167/junkyard,foobar167/junkyard,foobar167/junkyard,foobar167/junkyard,foobar167/junkyard
|
""" Apply different filters here """
import cv2 # import OpenCV 3 module
camera = cv2.VideoCapture(0) # get default camera
mode = 2 # default mode, apply Canny edge detection
while True:
ok, frame = camera.read() # read frame
if ok: # frame is read correctly
if mode == 2:
frame = cv2.Canny(frame, 100, 200) # Canny edge detection
cv2.imshow('My camera', frame) # show frame
key = cv2.waitKey(1) & 0xff # read keystroke
if key == 27: break # <Escape> key pressed, exit from cycle
if key == ord('1'): mode = 1 # show unchanged frame
if key == ord('2'): mode = 2 # apply Canny edge detection
camera.release() # release web camera
cv2.destroyAllWindows()
Apply Canny edge detection to grayscale. No big difference with colored Canny edge detection.
|
""" Apply different filters here """
import cv2 # import OpenCV 3 module
camera = cv2.VideoCapture(0) # get default camera
mode = 2 # default mode, apply Canny edge detection
while True:
ok, frame = camera.read() # read frame
if ok: # frame is read correctly
if mode == 2:
frame = cv2.Canny(frame, 100, 200) # Canny edge detection
if mode == 3:
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # convert to grayscale
frame = cv2.Canny(frame, 100, 200) # Canny edge detection
cv2.imshow('My camera', frame) # show frame
key = cv2.waitKey(1) & 0xff # read keystroke
if key == 27: break # <Escape> key pressed, exit from cycle
if key == ord('1'): mode = 1 # show unchanged frame
if key == ord('2'): mode = 2 # apply Canny edge detection
if key == ord('3'): mode = 3 # apply Canny to gray frame
camera.release() # release web camera
cv2.destroyAllWindows()
|
<commit_before>""" Apply different filters here """
import cv2 # import OpenCV 3 module
camera = cv2.VideoCapture(0) # get default camera
mode = 2 # default mode, apply Canny edge detection
while True:
ok, frame = camera.read() # read frame
if ok: # frame is read correctly
if mode == 2:
frame = cv2.Canny(frame, 100, 200) # Canny edge detection
cv2.imshow('My camera', frame) # show frame
key = cv2.waitKey(1) & 0xff # read keystroke
if key == 27: break # <Escape> key pressed, exit from cycle
if key == ord('1'): mode = 1 # show unchanged frame
if key == ord('2'): mode = 2 # apply Canny edge detection
camera.release() # release web camera
cv2.destroyAllWindows()
<commit_msg>Apply Canny edge detection to grayscale. No big difference with colored Canny edge detection.<commit_after>
|
""" Apply different filters here """
import cv2 # import OpenCV 3 module
camera = cv2.VideoCapture(0) # get default camera
mode = 2 # default mode, apply Canny edge detection
while True:
ok, frame = camera.read() # read frame
if ok: # frame is read correctly
if mode == 2:
frame = cv2.Canny(frame, 100, 200) # Canny edge detection
if mode == 3:
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # convert to grayscale
frame = cv2.Canny(frame, 100, 200) # Canny edge detection
cv2.imshow('My camera', frame) # show frame
key = cv2.waitKey(1) & 0xff # read keystroke
if key == 27: break # <Escape> key pressed, exit from cycle
if key == ord('1'): mode = 1 # show unchanged frame
if key == ord('2'): mode = 2 # apply Canny edge detection
if key == ord('3'): mode = 3 # apply Canny to gray frame
camera.release() # release web camera
cv2.destroyAllWindows()
|
""" Apply different filters here """
import cv2 # import OpenCV 3 module
camera = cv2.VideoCapture(0) # get default camera
mode = 2 # default mode, apply Canny edge detection
while True:
ok, frame = camera.read() # read frame
if ok: # frame is read correctly
if mode == 2:
frame = cv2.Canny(frame, 100, 200) # Canny edge detection
cv2.imshow('My camera', frame) # show frame
key = cv2.waitKey(1) & 0xff # read keystroke
if key == 27: break # <Escape> key pressed, exit from cycle
if key == ord('1'): mode = 1 # show unchanged frame
if key == ord('2'): mode = 2 # apply Canny edge detection
camera.release() # release web camera
cv2.destroyAllWindows()
Apply Canny edge detection to grayscale. No big difference with colored Canny edge detection.""" Apply different filters here """
import cv2 # import OpenCV 3 module
camera = cv2.VideoCapture(0) # get default camera
mode = 2 # default mode, apply Canny edge detection
while True:
ok, frame = camera.read() # read frame
if ok: # frame is read correctly
if mode == 2:
frame = cv2.Canny(frame, 100, 200) # Canny edge detection
if mode == 3:
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # convert to grayscale
frame = cv2.Canny(frame, 100, 200) # Canny edge detection
cv2.imshow('My camera', frame) # show frame
key = cv2.waitKey(1) & 0xff # read keystroke
if key == 27: break # <Escape> key pressed, exit from cycle
if key == ord('1'): mode = 1 # show unchanged frame
if key == ord('2'): mode = 2 # apply Canny edge detection
if key == ord('3'): mode = 3 # apply Canny to gray frame
camera.release() # release web camera
cv2.destroyAllWindows()
|
<commit_before>""" Apply different filters here """
import cv2 # import OpenCV 3 module
camera = cv2.VideoCapture(0) # get default camera
mode = 2 # default mode, apply Canny edge detection
while True:
ok, frame = camera.read() # read frame
if ok: # frame is read correctly
if mode == 2:
frame = cv2.Canny(frame, 100, 200) # Canny edge detection
cv2.imshow('My camera', frame) # show frame
key = cv2.waitKey(1) & 0xff # read keystroke
if key == 27: break # <Escape> key pressed, exit from cycle
if key == ord('1'): mode = 1 # show unchanged frame
if key == ord('2'): mode = 2 # apply Canny edge detection
camera.release() # release web camera
cv2.destroyAllWindows()
<commit_msg>Apply Canny edge detection to grayscale. No big difference with colored Canny edge detection.<commit_after>""" Apply different filters here """
import cv2 # import OpenCV 3 module
camera = cv2.VideoCapture(0) # get default camera
mode = 2 # default mode, apply Canny edge detection
while True:
ok, frame = camera.read() # read frame
if ok: # frame is read correctly
if mode == 2:
frame = cv2.Canny(frame, 100, 200) # Canny edge detection
if mode == 3:
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # convert to grayscale
frame = cv2.Canny(frame, 100, 200) # Canny edge detection
cv2.imshow('My camera', frame) # show frame
key = cv2.waitKey(1) & 0xff # read keystroke
if key == 27: break # <Escape> key pressed, exit from cycle
if key == ord('1'): mode = 1 # show unchanged frame
if key == ord('2'): mode = 2 # apply Canny edge detection
if key == ord('3'): mode = 3 # apply Canny to gray frame
camera.release() # release web camera
cv2.destroyAllWindows()
|
6571f2dab7ea94ffb86d054831b8b2abe21f861e
|
corehq/apps/accounting/migrations/0032_billingaccount_invoicing_plan.py
|
corehq/apps/accounting/migrations/0032_billingaccount_invoicing_plan.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-06-27 18:30
from __future__ import unicode_literals
from __future__ import absolute_import
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounting', '0031_billingaccount_billing_admin_emails'),
]
operations = [
migrations.AddField(
model_name='billingaccount',
name='invoicing_plan',
field=models.CharField(
choices=[('MONTHLY', 'Monthly'), ('QUARTERLY', 'Quarterly'), ('YEARLY', 'Yearly')],
default='MONTHLY', max_length=25
),
),
]
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-06-27 18:30
from __future__ import unicode_literals
from __future__ import absolute_import
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounting', '0031_billingaccount_billing_admin_emails'),
]
operations = [
migrations.AddField(
model_name='billingaccount',
name='invoicing_plan',
field=models.CharField(
choices=[('MONTHLY', 'Monthly'), ('QUARTERLY', 'Quarterly'), ('YEARLY', 'Yearly')],
default='MONTHLY', max_length=25
)
),
]
|
Add invoicing_plan with quarterly and yearly options
|
Add invoicing_plan with quarterly and yearly options
|
Python
|
bsd-3-clause
|
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-06-27 18:30
from __future__ import unicode_literals
from __future__ import absolute_import
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounting', '0031_billingaccount_billing_admin_emails'),
]
operations = [
migrations.AddField(
model_name='billingaccount',
name='invoicing_plan',
field=models.CharField(
choices=[('MONTHLY', 'Monthly'), ('QUARTERLY', 'Quarterly'), ('YEARLY', 'Yearly')],
default='MONTHLY', max_length=25
),
),
]
Add invoicing_plan with quarterly and yearly options
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-06-27 18:30
from __future__ import unicode_literals
from __future__ import absolute_import
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounting', '0031_billingaccount_billing_admin_emails'),
]
operations = [
migrations.AddField(
model_name='billingaccount',
name='invoicing_plan',
field=models.CharField(
choices=[('MONTHLY', 'Monthly'), ('QUARTERLY', 'Quarterly'), ('YEARLY', 'Yearly')],
default='MONTHLY', max_length=25
)
),
]
|
<commit_before># -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-06-27 18:30
from __future__ import unicode_literals
from __future__ import absolute_import
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounting', '0031_billingaccount_billing_admin_emails'),
]
operations = [
migrations.AddField(
model_name='billingaccount',
name='invoicing_plan',
field=models.CharField(
choices=[('MONTHLY', 'Monthly'), ('QUARTERLY', 'Quarterly'), ('YEARLY', 'Yearly')],
default='MONTHLY', max_length=25
),
),
]
<commit_msg>Add invoicing_plan with quarterly and yearly options<commit_after>
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-06-27 18:30
from __future__ import unicode_literals
from __future__ import absolute_import
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounting', '0031_billingaccount_billing_admin_emails'),
]
operations = [
migrations.AddField(
model_name='billingaccount',
name='invoicing_plan',
field=models.CharField(
choices=[('MONTHLY', 'Monthly'), ('QUARTERLY', 'Quarterly'), ('YEARLY', 'Yearly')],
default='MONTHLY', max_length=25
)
),
]
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-06-27 18:30
from __future__ import unicode_literals
from __future__ import absolute_import
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounting', '0031_billingaccount_billing_admin_emails'),
]
operations = [
migrations.AddField(
model_name='billingaccount',
name='invoicing_plan',
field=models.CharField(
choices=[('MONTHLY', 'Monthly'), ('QUARTERLY', 'Quarterly'), ('YEARLY', 'Yearly')],
default='MONTHLY', max_length=25
),
),
]
Add invoicing_plan with quarterly and yearly options# -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-06-27 18:30
from __future__ import unicode_literals
from __future__ import absolute_import
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounting', '0031_billingaccount_billing_admin_emails'),
]
operations = [
migrations.AddField(
model_name='billingaccount',
name='invoicing_plan',
field=models.CharField(
choices=[('MONTHLY', 'Monthly'), ('QUARTERLY', 'Quarterly'), ('YEARLY', 'Yearly')],
default='MONTHLY', max_length=25
)
),
]
|
<commit_before># -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-06-27 18:30
from __future__ import unicode_literals
from __future__ import absolute_import
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounting', '0031_billingaccount_billing_admin_emails'),
]
operations = [
migrations.AddField(
model_name='billingaccount',
name='invoicing_plan',
field=models.CharField(
choices=[('MONTHLY', 'Monthly'), ('QUARTERLY', 'Quarterly'), ('YEARLY', 'Yearly')],
default='MONTHLY', max_length=25
),
),
]
<commit_msg>Add invoicing_plan with quarterly and yearly options<commit_after># -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-06-27 18:30
from __future__ import unicode_literals
from __future__ import absolute_import
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounting', '0031_billingaccount_billing_admin_emails'),
]
operations = [
migrations.AddField(
model_name='billingaccount',
name='invoicing_plan',
field=models.CharField(
choices=[('MONTHLY', 'Monthly'), ('QUARTERLY', 'Quarterly'), ('YEARLY', 'Yearly')],
default='MONTHLY', max_length=25
)
),
]
|
695043ff82e80fdc3b0186dea268dd0eff79d642
|
webapp/tests/test_util.py
|
webapp/tests/test_util.py
|
from django.test import TestCase
from graphite import util
from graphite.wsgi import application # NOQA makes sure we have a working WSGI app
class UtilTest(TestCase):
def test_is_local_interface(self):
addresses = ['127.0.0.1', '127.0.0.1:8080', '8.8.8.8']
results = [ util.is_local_interface(a) for a in addresses ]
self.assertEqual( results, [True, True, False] )
|
from django.test import TestCase
from graphite import util
from graphite.wsgi import application # NOQA makes sure we have a working WSGI app
class UtilTest(TestCase):
def test_is_local_interface(self):
addresses = ['127.0.0.1', '127.0.0.1:8080', '8.8.8.8']
results = [ util.is_local_interface(a) for a in addresses ]
self.assertEqual( results, [True, True, False] )
addresses = ['::1', '[::1]:8080' ]
results = [ util.is_local_interface(a) for a in addresses ]
self.assertEqual( results, [True, True] )
with self.assertRaises(Exception):
addresses = ['::1:8080']
results = [ util.is_local_interface(a) for a in addresses ]
def test_write_index(self):
self.assertEqual(None, util.write_index() )
|
Add coverage to util.py for IPv6 and make_index
|
Add coverage to util.py for IPv6 and make_index
|
Python
|
apache-2.0
|
brutasse/graphite-web,DanCech/graphite-web,obfuscurity/graphite-web,deniszh/graphite-web,drax68/graphite-web,cbowman0/graphite-web,mcoolive/graphite-web,drax68/graphite-web,atnak/graphite-web,krux/graphite-web,johnseekins/graphite-web,brutasse/graphite-web,krux/graphite-web,drax68/graphite-web,bmhatfield/graphite-web,cosm0s/graphite-web,graphite-project/graphite-web,cosm0s/graphite-web,johnseekins/graphite-web,drax68/graphite-web,cosm0s/graphite-web,krux/graphite-web,atnak/graphite-web,deniszh/graphite-web,mcoolive/graphite-web,mcoolive/graphite-web,gwaldo/graphite-web,deniszh/graphite-web,mcoolive/graphite-web,gwaldo/graphite-web,johnseekins/graphite-web,graphite-project/graphite-web,bmhatfield/graphite-web,criteo-forks/graphite-web,drax68/graphite-web,brutasse/graphite-web,cbowman0/graphite-web,deniszh/graphite-web,atnak/graphite-web,cosm0s/graphite-web,drax68/graphite-web,DanCech/graphite-web,cosm0s/graphite-web,DanCech/graphite-web,graphite-project/graphite-web,cbowman0/graphite-web,gwaldo/graphite-web,obfuscurity/graphite-web,brutasse/graphite-web,krux/graphite-web,atnak/graphite-web,cbowman0/graphite-web,obfuscurity/graphite-web,DanCech/graphite-web,cbowman0/graphite-web,criteo-forks/graphite-web,graphite-project/graphite-web,mcoolive/graphite-web,atnak/graphite-web,deniszh/graphite-web,graphite-project/graphite-web,criteo-forks/graphite-web,criteo-forks/graphite-web,brutasse/graphite-web,bmhatfield/graphite-web,bmhatfield/graphite-web,criteo-forks/graphite-web,obfuscurity/graphite-web,bmhatfield/graphite-web,brutasse/graphite-web,johnseekins/graphite-web,krux/graphite-web,johnseekins/graphite-web,gwaldo/graphite-web,obfuscurity/graphite-web,DanCech/graphite-web,cosm0s/graphite-web,krux/graphite-web,atnak/graphite-web,deniszh/graphite-web,mcoolive/graphite-web,criteo-forks/graphite-web,gwaldo/graphite-web,johnseekins/graphite-web,graphite-project/graphite-web,DanCech/graphite-web,cbowman0/graphite-web,bmhatfield/graphite-web,obfuscurity/graphite-web,gwaldo/graphite-web
|
from django.test import TestCase
from graphite import util
from graphite.wsgi import application # NOQA makes sure we have a working WSGI app
class UtilTest(TestCase):
def test_is_local_interface(self):
addresses = ['127.0.0.1', '127.0.0.1:8080', '8.8.8.8']
results = [ util.is_local_interface(a) for a in addresses ]
self.assertEqual( results, [True, True, False] )
Add coverage to util.py for IPv6 and make_index
|
from django.test import TestCase
from graphite import util
from graphite.wsgi import application # NOQA makes sure we have a working WSGI app
class UtilTest(TestCase):
def test_is_local_interface(self):
addresses = ['127.0.0.1', '127.0.0.1:8080', '8.8.8.8']
results = [ util.is_local_interface(a) for a in addresses ]
self.assertEqual( results, [True, True, False] )
addresses = ['::1', '[::1]:8080' ]
results = [ util.is_local_interface(a) for a in addresses ]
self.assertEqual( results, [True, True] )
with self.assertRaises(Exception):
addresses = ['::1:8080']
results = [ util.is_local_interface(a) for a in addresses ]
def test_write_index(self):
self.assertEqual(None, util.write_index() )
|
<commit_before>from django.test import TestCase
from graphite import util
from graphite.wsgi import application # NOQA makes sure we have a working WSGI app
class UtilTest(TestCase):
def test_is_local_interface(self):
addresses = ['127.0.0.1', '127.0.0.1:8080', '8.8.8.8']
results = [ util.is_local_interface(a) for a in addresses ]
self.assertEqual( results, [True, True, False] )
<commit_msg>Add coverage to util.py for IPv6 and make_index<commit_after>
|
from django.test import TestCase
from graphite import util
from graphite.wsgi import application # NOQA makes sure we have a working WSGI app
class UtilTest(TestCase):
def test_is_local_interface(self):
addresses = ['127.0.0.1', '127.0.0.1:8080', '8.8.8.8']
results = [ util.is_local_interface(a) for a in addresses ]
self.assertEqual( results, [True, True, False] )
addresses = ['::1', '[::1]:8080' ]
results = [ util.is_local_interface(a) for a in addresses ]
self.assertEqual( results, [True, True] )
with self.assertRaises(Exception):
addresses = ['::1:8080']
results = [ util.is_local_interface(a) for a in addresses ]
def test_write_index(self):
self.assertEqual(None, util.write_index() )
|
from django.test import TestCase
from graphite import util
from graphite.wsgi import application # NOQA makes sure we have a working WSGI app
class UtilTest(TestCase):
def test_is_local_interface(self):
addresses = ['127.0.0.1', '127.0.0.1:8080', '8.8.8.8']
results = [ util.is_local_interface(a) for a in addresses ]
self.assertEqual( results, [True, True, False] )
Add coverage to util.py for IPv6 and make_indexfrom django.test import TestCase
from graphite import util
from graphite.wsgi import application # NOQA makes sure we have a working WSGI app
class UtilTest(TestCase):
def test_is_local_interface(self):
addresses = ['127.0.0.1', '127.0.0.1:8080', '8.8.8.8']
results = [ util.is_local_interface(a) for a in addresses ]
self.assertEqual( results, [True, True, False] )
addresses = ['::1', '[::1]:8080' ]
results = [ util.is_local_interface(a) for a in addresses ]
self.assertEqual( results, [True, True] )
with self.assertRaises(Exception):
addresses = ['::1:8080']
results = [ util.is_local_interface(a) for a in addresses ]
def test_write_index(self):
self.assertEqual(None, util.write_index() )
|
<commit_before>from django.test import TestCase
from graphite import util
from graphite.wsgi import application # NOQA makes sure we have a working WSGI app
class UtilTest(TestCase):
def test_is_local_interface(self):
addresses = ['127.0.0.1', '127.0.0.1:8080', '8.8.8.8']
results = [ util.is_local_interface(a) for a in addresses ]
self.assertEqual( results, [True, True, False] )
<commit_msg>Add coverage to util.py for IPv6 and make_index<commit_after>from django.test import TestCase
from graphite import util
from graphite.wsgi import application # NOQA makes sure we have a working WSGI app
class UtilTest(TestCase):
def test_is_local_interface(self):
addresses = ['127.0.0.1', '127.0.0.1:8080', '8.8.8.8']
results = [ util.is_local_interface(a) for a in addresses ]
self.assertEqual( results, [True, True, False] )
addresses = ['::1', '[::1]:8080' ]
results = [ util.is_local_interface(a) for a in addresses ]
self.assertEqual( results, [True, True] )
with self.assertRaises(Exception):
addresses = ['::1:8080']
results = [ util.is_local_interface(a) for a in addresses ]
def test_write_index(self):
self.assertEqual(None, util.write_index() )
|
c63391026fadc6f23ca7802e6ec706365ae4e117
|
daemon/daemon.py
|
daemon/daemon.py
|
#!/usr/bin/env python
import json
from objects.album import Album
from spotify_crawler import SpotifyCrawler
if __name__ == "__main__":
crawler = SpotifyCrawler()
artist = crawler.searchArtist("Ed Sheeran")
if artist:
albums = crawler.getAlbumsByArtist(artist.getArtistId())
for album in albums:
tracks = crawler.getTracksByAlbum(album.getAlbumId())
album.setTracks(tracks)
artist.setAlbums(albums)
print(artist.toJSON())
|
#!/usr/bin/env python
import json
from objects.album import Album
from spotify_crawler import SpotifyCrawler
if __name__ == "__main__":
crawler = SpotifyCrawler()
artist_name = "Ed Sheeran"
artist = crawler.searchArtist(artist_name)
if artist:
albums = crawler.getAlbumsByArtist(artist.getArtistId())
for album in albums:
tracks = crawler.getTracksByAlbum(album.getAlbumId())
album.setTracks(tracks)
artist.setAlbums(albums)
print(artist.toJSON())
else:
print("Cannot find " + artist_name)
|
Add the error handle if artist doesn't exist..
|
Add the error handle if artist doesn't exist..
|
Python
|
apache-2.0
|
rockers7414/xmusic,rockers7414/xmusic-crawler
|
#!/usr/bin/env python
import json
from objects.album import Album
from spotify_crawler import SpotifyCrawler
if __name__ == "__main__":
crawler = SpotifyCrawler()
artist = crawler.searchArtist("Ed Sheeran")
if artist:
albums = crawler.getAlbumsByArtist(artist.getArtistId())
for album in albums:
tracks = crawler.getTracksByAlbum(album.getAlbumId())
album.setTracks(tracks)
artist.setAlbums(albums)
print(artist.toJSON())
Add the error handle if artist doesn't exist..
|
#!/usr/bin/env python
import json
from objects.album import Album
from spotify_crawler import SpotifyCrawler
if __name__ == "__main__":
crawler = SpotifyCrawler()
artist_name = "Ed Sheeran"
artist = crawler.searchArtist(artist_name)
if artist:
albums = crawler.getAlbumsByArtist(artist.getArtistId())
for album in albums:
tracks = crawler.getTracksByAlbum(album.getAlbumId())
album.setTracks(tracks)
artist.setAlbums(albums)
print(artist.toJSON())
else:
print("Cannot find " + artist_name)
|
<commit_before>#!/usr/bin/env python
import json
from objects.album import Album
from spotify_crawler import SpotifyCrawler
if __name__ == "__main__":
crawler = SpotifyCrawler()
artist = crawler.searchArtist("Ed Sheeran")
if artist:
albums = crawler.getAlbumsByArtist(artist.getArtistId())
for album in albums:
tracks = crawler.getTracksByAlbum(album.getAlbumId())
album.setTracks(tracks)
artist.setAlbums(albums)
print(artist.toJSON())
<commit_msg>Add the error handle if artist doesn't exist..<commit_after>
|
#!/usr/bin/env python
import json
from objects.album import Album
from spotify_crawler import SpotifyCrawler
if __name__ == "__main__":
crawler = SpotifyCrawler()
artist_name = "Ed Sheeran"
artist = crawler.searchArtist(artist_name)
if artist:
albums = crawler.getAlbumsByArtist(artist.getArtistId())
for album in albums:
tracks = crawler.getTracksByAlbum(album.getAlbumId())
album.setTracks(tracks)
artist.setAlbums(albums)
print(artist.toJSON())
else:
print("Cannot find " + artist_name)
|
#!/usr/bin/env python
import json
from objects.album import Album
from spotify_crawler import SpotifyCrawler
if __name__ == "__main__":
crawler = SpotifyCrawler()
artist = crawler.searchArtist("Ed Sheeran")
if artist:
albums = crawler.getAlbumsByArtist(artist.getArtistId())
for album in albums:
tracks = crawler.getTracksByAlbum(album.getAlbumId())
album.setTracks(tracks)
artist.setAlbums(albums)
print(artist.toJSON())
Add the error handle if artist doesn't exist..#!/usr/bin/env python
import json
from objects.album import Album
from spotify_crawler import SpotifyCrawler
if __name__ == "__main__":
crawler = SpotifyCrawler()
artist_name = "Ed Sheeran"
artist = crawler.searchArtist(artist_name)
if artist:
albums = crawler.getAlbumsByArtist(artist.getArtistId())
for album in albums:
tracks = crawler.getTracksByAlbum(album.getAlbumId())
album.setTracks(tracks)
artist.setAlbums(albums)
print(artist.toJSON())
else:
print("Cannot find " + artist_name)
|
<commit_before>#!/usr/bin/env python
import json
from objects.album import Album
from spotify_crawler import SpotifyCrawler
if __name__ == "__main__":
crawler = SpotifyCrawler()
artist = crawler.searchArtist("Ed Sheeran")
if artist:
albums = crawler.getAlbumsByArtist(artist.getArtistId())
for album in albums:
tracks = crawler.getTracksByAlbum(album.getAlbumId())
album.setTracks(tracks)
artist.setAlbums(albums)
print(artist.toJSON())
<commit_msg>Add the error handle if artist doesn't exist..<commit_after>#!/usr/bin/env python
import json
from objects.album import Album
from spotify_crawler import SpotifyCrawler
if __name__ == "__main__":
crawler = SpotifyCrawler()
artist_name = "Ed Sheeran"
artist = crawler.searchArtist(artist_name)
if artist:
albums = crawler.getAlbumsByArtist(artist.getArtistId())
for album in albums:
tracks = crawler.getTracksByAlbum(album.getAlbumId())
album.setTracks(tracks)
artist.setAlbums(albums)
print(artist.toJSON())
else:
print("Cannot find " + artist_name)
|
42bc233ca11e6d5283fa760fa736585a7716afac
|
cvdb/urls.py
|
cvdb/urls.py
|
"""cvdb URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^accounts/', include('allauth.urls')),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^', include('django.contrib.auth.urls')),
url(r'^api/01/', include('api01.urls', namespace='api01')),
url(r'^', include('users.urls')),
url(r'^', include('viewcv.urls')),
]
|
"""cvdb URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^accounts/', include('allauth.urls')),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
# url(r'^', include('django.contrib.auth.urls')),
url(r'^api/01/', include('api01.urls', namespace='api01')),
url(r'^', include('users.urls')),
url(r'^', include('viewcv.urls')),
]
|
Disable default Django authorization URLs
|
Disable default Django authorization URLs
|
Python
|
mit
|
jarnoln/cvdb,jarnoln/cvdb
|
"""cvdb URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^accounts/', include('allauth.urls')),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^', include('django.contrib.auth.urls')),
url(r'^api/01/', include('api01.urls', namespace='api01')),
url(r'^', include('users.urls')),
url(r'^', include('viewcv.urls')),
]
Disable default Django authorization URLs
|
"""cvdb URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^accounts/', include('allauth.urls')),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
# url(r'^', include('django.contrib.auth.urls')),
url(r'^api/01/', include('api01.urls', namespace='api01')),
url(r'^', include('users.urls')),
url(r'^', include('viewcv.urls')),
]
|
<commit_before>"""cvdb URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^accounts/', include('allauth.urls')),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^', include('django.contrib.auth.urls')),
url(r'^api/01/', include('api01.urls', namespace='api01')),
url(r'^', include('users.urls')),
url(r'^', include('viewcv.urls')),
]
<commit_msg>Disable default Django authorization URLs<commit_after>
|
"""cvdb URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^accounts/', include('allauth.urls')),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
# url(r'^', include('django.contrib.auth.urls')),
url(r'^api/01/', include('api01.urls', namespace='api01')),
url(r'^', include('users.urls')),
url(r'^', include('viewcv.urls')),
]
|
"""cvdb URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^accounts/', include('allauth.urls')),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^', include('django.contrib.auth.urls')),
url(r'^api/01/', include('api01.urls', namespace='api01')),
url(r'^', include('users.urls')),
url(r'^', include('viewcv.urls')),
]
Disable default Django authorization URLs"""cvdb URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^accounts/', include('allauth.urls')),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
# url(r'^', include('django.contrib.auth.urls')),
url(r'^api/01/', include('api01.urls', namespace='api01')),
url(r'^', include('users.urls')),
url(r'^', include('viewcv.urls')),
]
|
<commit_before>"""cvdb URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^accounts/', include('allauth.urls')),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^', include('django.contrib.auth.urls')),
url(r'^api/01/', include('api01.urls', namespace='api01')),
url(r'^', include('users.urls')),
url(r'^', include('viewcv.urls')),
]
<commit_msg>Disable default Django authorization URLs<commit_after>"""cvdb URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^accounts/', include('allauth.urls')),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
# url(r'^', include('django.contrib.auth.urls')),
url(r'^api/01/', include('api01.urls', namespace='api01')),
url(r'^', include('users.urls')),
url(r'^', include('viewcv.urls')),
]
|
f735cd9f9cfdcfba54005151fee3deb7741282c3
|
show.py
|
show.py
|
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
def sweep(x, sweep_time, fs):
t = np.arange(0, sweep_time, 1 / fs)
p = 20 * np.log10(abs(sp.fft(x)))
f = np.linspace(0, fs / 2, len(p))
plt.figure(1)
plt.subplot(211)
plt.plot(t, x)
plt.grid()
plt.subplot(212)
plt.plot(f, p)
plt.xscale('log')
plt.grid()
plt.show()
|
import numpy as np
import matplotlib.pyplot as plt
def sweep(x, sweep_time, fs):
plt.subplots_adjust(hspace=0.4)
t = np.arange(0, sweep_time, 1 / fs)
p = 20 * np.log10(abs(np.fft.rfft(x)))
f = np.linspace(0, fs / 2, len(p))
plt.figure(1)
plt.subplot(211)
plt.plot(t, x)
plt.grid()
plt.xlabel('t / s')
plt.ylabel('x(t)')
plt.title('time domain')
plt.subplot(212)
plt.plot(f, p)
plt.xscale('log')
plt.grid()
plt.xlabel('f / Hz')
plt.ylabel('A / dB')
plt.title('frequency domain')
plt.show()
|
Add axis label and change import
|
Add axis label and change import
|
Python
|
mit
|
franzpl/sweep,spatialaudio/sweep
|
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
def sweep(x, sweep_time, fs):
t = np.arange(0, sweep_time, 1 / fs)
p = 20 * np.log10(abs(sp.fft(x)))
f = np.linspace(0, fs / 2, len(p))
plt.figure(1)
plt.subplot(211)
plt.plot(t, x)
plt.grid()
plt.subplot(212)
plt.plot(f, p)
plt.xscale('log')
plt.grid()
plt.show()
Add axis label and change import
|
import numpy as np
import matplotlib.pyplot as plt
def sweep(x, sweep_time, fs):
plt.subplots_adjust(hspace=0.4)
t = np.arange(0, sweep_time, 1 / fs)
p = 20 * np.log10(abs(np.fft.rfft(x)))
f = np.linspace(0, fs / 2, len(p))
plt.figure(1)
plt.subplot(211)
plt.plot(t, x)
plt.grid()
plt.xlabel('t / s')
plt.ylabel('x(t)')
plt.title('time domain')
plt.subplot(212)
plt.plot(f, p)
plt.xscale('log')
plt.grid()
plt.xlabel('f / Hz')
plt.ylabel('A / dB')
plt.title('frequency domain')
plt.show()
|
<commit_before>import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
def sweep(x, sweep_time, fs):
t = np.arange(0, sweep_time, 1 / fs)
p = 20 * np.log10(abs(sp.fft(x)))
f = np.linspace(0, fs / 2, len(p))
plt.figure(1)
plt.subplot(211)
plt.plot(t, x)
plt.grid()
plt.subplot(212)
plt.plot(f, p)
plt.xscale('log')
plt.grid()
plt.show()
<commit_msg>Add axis label and change import<commit_after>
|
import numpy as np
import matplotlib.pyplot as plt
def sweep(x, sweep_time, fs):
plt.subplots_adjust(hspace=0.4)
t = np.arange(0, sweep_time, 1 / fs)
p = 20 * np.log10(abs(np.fft.rfft(x)))
f = np.linspace(0, fs / 2, len(p))
plt.figure(1)
plt.subplot(211)
plt.plot(t, x)
plt.grid()
plt.xlabel('t / s')
plt.ylabel('x(t)')
plt.title('time domain')
plt.subplot(212)
plt.plot(f, p)
plt.xscale('log')
plt.grid()
plt.xlabel('f / Hz')
plt.ylabel('A / dB')
plt.title('frequency domain')
plt.show()
|
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
def sweep(x, sweep_time, fs):
t = np.arange(0, sweep_time, 1 / fs)
p = 20 * np.log10(abs(sp.fft(x)))
f = np.linspace(0, fs / 2, len(p))
plt.figure(1)
plt.subplot(211)
plt.plot(t, x)
plt.grid()
plt.subplot(212)
plt.plot(f, p)
plt.xscale('log')
plt.grid()
plt.show()
Add axis label and change importimport numpy as np
import matplotlib.pyplot as plt
def sweep(x, sweep_time, fs):
plt.subplots_adjust(hspace=0.4)
t = np.arange(0, sweep_time, 1 / fs)
p = 20 * np.log10(abs(np.fft.rfft(x)))
f = np.linspace(0, fs / 2, len(p))
plt.figure(1)
plt.subplot(211)
plt.plot(t, x)
plt.grid()
plt.xlabel('t / s')
plt.ylabel('x(t)')
plt.title('time domain')
plt.subplot(212)
plt.plot(f, p)
plt.xscale('log')
plt.grid()
plt.xlabel('f / Hz')
plt.ylabel('A / dB')
plt.title('frequency domain')
plt.show()
|
<commit_before>import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
def sweep(x, sweep_time, fs):
t = np.arange(0, sweep_time, 1 / fs)
p = 20 * np.log10(abs(sp.fft(x)))
f = np.linspace(0, fs / 2, len(p))
plt.figure(1)
plt.subplot(211)
plt.plot(t, x)
plt.grid()
plt.subplot(212)
plt.plot(f, p)
plt.xscale('log')
plt.grid()
plt.show()
<commit_msg>Add axis label and change import<commit_after>import numpy as np
import matplotlib.pyplot as plt
def sweep(x, sweep_time, fs):
plt.subplots_adjust(hspace=0.4)
t = np.arange(0, sweep_time, 1 / fs)
p = 20 * np.log10(abs(np.fft.rfft(x)))
f = np.linspace(0, fs / 2, len(p))
plt.figure(1)
plt.subplot(211)
plt.plot(t, x)
plt.grid()
plt.xlabel('t / s')
plt.ylabel('x(t)')
plt.title('time domain')
plt.subplot(212)
plt.plot(f, p)
plt.xscale('log')
plt.grid()
plt.xlabel('f / Hz')
plt.ylabel('A / dB')
plt.title('frequency domain')
plt.show()
|
8930337ef2402a9e5a6dfe3a336fc24b0ffbf87f
|
reviewboard/accounts/urls.py
|
reviewboard/accounts/urls.py
|
from __future__ import unicode_literals
from django.conf.urls import patterns, url
urlpatterns = patterns(
"reviewboard.accounts.views",
url(r'^register/$', 'account_register',
{'next_url': 'dashboard'}, name="register"),
url(r'^preferences/$', 'user_preferences', name="user-preferences"),
)
urlpatterns += patterns(
"django.contrib.auth.views",
url(r'^login/$', 'login',
{'template_name': 'accounts/login.html'},
name='login'),
url(r'^logout/$', 'logout_then_login', name='logout'),
url(r'^recover/$',
'password_reset',
{
'template_name': 'accounts/password_reset.html',
'email_template_name': 'accounts/password_reset_email.txt'
},
name='recover'),
url(r'^recover/done/$',
'password_reset_done',
{'template_name': 'accounts/password_reset_done.html'}),
url(r'^reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$',
'password_reset_confirm',
{'template_name': 'accounts/password_reset_confirm.html'},
name='password-reset-confirm'),
url(r'^reset/done/$',
'password_reset_complete',
{'template_name': 'accounts/password_reset_complete.html'}),
)
|
from __future__ import unicode_literals
from django.conf.urls import patterns, url
urlpatterns = patterns(
"reviewboard.accounts.views",
url(r'^register/$', 'account_register',
{'next_url': 'dashboard'}, name="register"),
url(r'^preferences/$', 'user_preferences', name="user-preferences"),
)
urlpatterns += patterns(
"django.contrib.auth.views",
url(r'^login/$', 'login',
{'template_name': 'accounts/login.html'},
name='login'),
url(r'^logout/$', 'logout_then_login', name='logout'),
url(r'^recover/$',
'password_reset',
{
'template_name': 'accounts/password_reset.html',
'email_template_name': 'accounts/password_reset_email.txt'
},
name='recover'),
url(r'^recover/done/$',
'password_reset_done',
{'template_name': 'accounts/password_reset_done.html'},
name='password_reset_done'),
url(r'^reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$',
'password_reset_confirm',
{'template_name': 'accounts/password_reset_confirm.html'},
name='password-reset-confirm'),
url(r'^reset/done/$',
'password_reset_complete',
{'template_name': 'accounts/password_reset_complete.html'}),
)
|
Fix internal server error at url /account/recover
|
Fix internal server error at url /account/recover
Fixed a 500 error at /account/recover when trying to reset password on the
login page.
Testing Done:
Verified that the server no longer returns a 500 error when loading the form.
Reviewed at https://reviews.reviewboard.org/r/5431/
|
Python
|
mit
|
beol/reviewboard,davidt/reviewboard,beol/reviewboard,1tush/reviewboard,custode/reviewboard,reviewboard/reviewboard,KnowNo/reviewboard,KnowNo/reviewboard,1tush/reviewboard,beol/reviewboard,1tush/reviewboard,beol/reviewboard,brennie/reviewboard,sgallagher/reviewboard,reviewboard/reviewboard,bkochendorfer/reviewboard,custode/reviewboard,brennie/reviewboard,bkochendorfer/reviewboard,custode/reviewboard,chipx86/reviewboard,chipx86/reviewboard,1tush/reviewboard,reviewboard/reviewboard,sgallagher/reviewboard,KnowNo/reviewboard,chipx86/reviewboard,1tush/reviewboard,davidt/reviewboard,brennie/reviewboard,chipx86/reviewboard,davidt/reviewboard,KnowNo/reviewboard,custode/reviewboard,sgallagher/reviewboard,brennie/reviewboard,1tush/reviewboard,bkochendorfer/reviewboard,davidt/reviewboard,1tush/reviewboard,reviewboard/reviewboard,bkochendorfer/reviewboard,1tush/reviewboard,1tush/reviewboard,sgallagher/reviewboard
|
from __future__ import unicode_literals
from django.conf.urls import patterns, url
urlpatterns = patterns(
"reviewboard.accounts.views",
url(r'^register/$', 'account_register',
{'next_url': 'dashboard'}, name="register"),
url(r'^preferences/$', 'user_preferences', name="user-preferences"),
)
urlpatterns += patterns(
"django.contrib.auth.views",
url(r'^login/$', 'login',
{'template_name': 'accounts/login.html'},
name='login'),
url(r'^logout/$', 'logout_then_login', name='logout'),
url(r'^recover/$',
'password_reset',
{
'template_name': 'accounts/password_reset.html',
'email_template_name': 'accounts/password_reset_email.txt'
},
name='recover'),
url(r'^recover/done/$',
'password_reset_done',
{'template_name': 'accounts/password_reset_done.html'}),
url(r'^reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$',
'password_reset_confirm',
{'template_name': 'accounts/password_reset_confirm.html'},
name='password-reset-confirm'),
url(r'^reset/done/$',
'password_reset_complete',
{'template_name': 'accounts/password_reset_complete.html'}),
)
Fix internal server error at url /account/recover
Fixed a 500 error at /account/recover when trying to reset password on the
login page.
Testing Done:
Verified that the server no longer returns a 500 error when loading the form.
Reviewed at https://reviews.reviewboard.org/r/5431/
|
from __future__ import unicode_literals
from django.conf.urls import patterns, url
urlpatterns = patterns(
"reviewboard.accounts.views",
url(r'^register/$', 'account_register',
{'next_url': 'dashboard'}, name="register"),
url(r'^preferences/$', 'user_preferences', name="user-preferences"),
)
urlpatterns += patterns(
"django.contrib.auth.views",
url(r'^login/$', 'login',
{'template_name': 'accounts/login.html'},
name='login'),
url(r'^logout/$', 'logout_then_login', name='logout'),
url(r'^recover/$',
'password_reset',
{
'template_name': 'accounts/password_reset.html',
'email_template_name': 'accounts/password_reset_email.txt'
},
name='recover'),
url(r'^recover/done/$',
'password_reset_done',
{'template_name': 'accounts/password_reset_done.html'},
name='password_reset_done'),
url(r'^reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$',
'password_reset_confirm',
{'template_name': 'accounts/password_reset_confirm.html'},
name='password-reset-confirm'),
url(r'^reset/done/$',
'password_reset_complete',
{'template_name': 'accounts/password_reset_complete.html'}),
)
|
<commit_before>from __future__ import unicode_literals
from django.conf.urls import patterns, url
urlpatterns = patterns(
"reviewboard.accounts.views",
url(r'^register/$', 'account_register',
{'next_url': 'dashboard'}, name="register"),
url(r'^preferences/$', 'user_preferences', name="user-preferences"),
)
urlpatterns += patterns(
"django.contrib.auth.views",
url(r'^login/$', 'login',
{'template_name': 'accounts/login.html'},
name='login'),
url(r'^logout/$', 'logout_then_login', name='logout'),
url(r'^recover/$',
'password_reset',
{
'template_name': 'accounts/password_reset.html',
'email_template_name': 'accounts/password_reset_email.txt'
},
name='recover'),
url(r'^recover/done/$',
'password_reset_done',
{'template_name': 'accounts/password_reset_done.html'}),
url(r'^reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$',
'password_reset_confirm',
{'template_name': 'accounts/password_reset_confirm.html'},
name='password-reset-confirm'),
url(r'^reset/done/$',
'password_reset_complete',
{'template_name': 'accounts/password_reset_complete.html'}),
)
<commit_msg>Fix internal server error at url /account/recover
Fixed a 500 error at /account/recover when trying to reset password on the
login page.
Testing Done:
Verified that the server no longer returns a 500 error when loading the form.
Reviewed at https://reviews.reviewboard.org/r/5431/<commit_after>
|
from __future__ import unicode_literals
from django.conf.urls import patterns, url
urlpatterns = patterns(
"reviewboard.accounts.views",
url(r'^register/$', 'account_register',
{'next_url': 'dashboard'}, name="register"),
url(r'^preferences/$', 'user_preferences', name="user-preferences"),
)
urlpatterns += patterns(
"django.contrib.auth.views",
url(r'^login/$', 'login',
{'template_name': 'accounts/login.html'},
name='login'),
url(r'^logout/$', 'logout_then_login', name='logout'),
url(r'^recover/$',
'password_reset',
{
'template_name': 'accounts/password_reset.html',
'email_template_name': 'accounts/password_reset_email.txt'
},
name='recover'),
url(r'^recover/done/$',
'password_reset_done',
{'template_name': 'accounts/password_reset_done.html'},
name='password_reset_done'),
url(r'^reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$',
'password_reset_confirm',
{'template_name': 'accounts/password_reset_confirm.html'},
name='password-reset-confirm'),
url(r'^reset/done/$',
'password_reset_complete',
{'template_name': 'accounts/password_reset_complete.html'}),
)
|
from __future__ import unicode_literals
from django.conf.urls import patterns, url
urlpatterns = patterns(
"reviewboard.accounts.views",
url(r'^register/$', 'account_register',
{'next_url': 'dashboard'}, name="register"),
url(r'^preferences/$', 'user_preferences', name="user-preferences"),
)
urlpatterns += patterns(
"django.contrib.auth.views",
url(r'^login/$', 'login',
{'template_name': 'accounts/login.html'},
name='login'),
url(r'^logout/$', 'logout_then_login', name='logout'),
url(r'^recover/$',
'password_reset',
{
'template_name': 'accounts/password_reset.html',
'email_template_name': 'accounts/password_reset_email.txt'
},
name='recover'),
url(r'^recover/done/$',
'password_reset_done',
{'template_name': 'accounts/password_reset_done.html'}),
url(r'^reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$',
'password_reset_confirm',
{'template_name': 'accounts/password_reset_confirm.html'},
name='password-reset-confirm'),
url(r'^reset/done/$',
'password_reset_complete',
{'template_name': 'accounts/password_reset_complete.html'}),
)
Fix internal server error at url /account/recover
Fixed a 500 error at /account/recover when trying to reset password on the
login page.
Testing Done:
Verified that the server no longer returns a 500 error when loading the form.
Reviewed at https://reviews.reviewboard.org/r/5431/from __future__ import unicode_literals
from django.conf.urls import patterns, url
urlpatterns = patterns(
"reviewboard.accounts.views",
url(r'^register/$', 'account_register',
{'next_url': 'dashboard'}, name="register"),
url(r'^preferences/$', 'user_preferences', name="user-preferences"),
)
urlpatterns += patterns(
"django.contrib.auth.views",
url(r'^login/$', 'login',
{'template_name': 'accounts/login.html'},
name='login'),
url(r'^logout/$', 'logout_then_login', name='logout'),
url(r'^recover/$',
'password_reset',
{
'template_name': 'accounts/password_reset.html',
'email_template_name': 'accounts/password_reset_email.txt'
},
name='recover'),
url(r'^recover/done/$',
'password_reset_done',
{'template_name': 'accounts/password_reset_done.html'},
name='password_reset_done'),
url(r'^reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$',
'password_reset_confirm',
{'template_name': 'accounts/password_reset_confirm.html'},
name='password-reset-confirm'),
url(r'^reset/done/$',
'password_reset_complete',
{'template_name': 'accounts/password_reset_complete.html'}),
)
|
<commit_before>from __future__ import unicode_literals
from django.conf.urls import patterns, url
urlpatterns = patterns(
"reviewboard.accounts.views",
url(r'^register/$', 'account_register',
{'next_url': 'dashboard'}, name="register"),
url(r'^preferences/$', 'user_preferences', name="user-preferences"),
)
urlpatterns += patterns(
"django.contrib.auth.views",
url(r'^login/$', 'login',
{'template_name': 'accounts/login.html'},
name='login'),
url(r'^logout/$', 'logout_then_login', name='logout'),
url(r'^recover/$',
'password_reset',
{
'template_name': 'accounts/password_reset.html',
'email_template_name': 'accounts/password_reset_email.txt'
},
name='recover'),
url(r'^recover/done/$',
'password_reset_done',
{'template_name': 'accounts/password_reset_done.html'}),
url(r'^reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$',
'password_reset_confirm',
{'template_name': 'accounts/password_reset_confirm.html'},
name='password-reset-confirm'),
url(r'^reset/done/$',
'password_reset_complete',
{'template_name': 'accounts/password_reset_complete.html'}),
)
<commit_msg>Fix internal server error at url /account/recover
Fixed a 500 error at /account/recover when trying to reset password on the
login page.
Testing Done:
Verified that the server no longer returns a 500 error when loading the form.
Reviewed at https://reviews.reviewboard.org/r/5431/<commit_after>from __future__ import unicode_literals
from django.conf.urls import patterns, url
urlpatterns = patterns(
"reviewboard.accounts.views",
url(r'^register/$', 'account_register',
{'next_url': 'dashboard'}, name="register"),
url(r'^preferences/$', 'user_preferences', name="user-preferences"),
)
urlpatterns += patterns(
"django.contrib.auth.views",
url(r'^login/$', 'login',
{'template_name': 'accounts/login.html'},
name='login'),
url(r'^logout/$', 'logout_then_login', name='logout'),
url(r'^recover/$',
'password_reset',
{
'template_name': 'accounts/password_reset.html',
'email_template_name': 'accounts/password_reset_email.txt'
},
name='recover'),
url(r'^recover/done/$',
'password_reset_done',
{'template_name': 'accounts/password_reset_done.html'},
name='password_reset_done'),
url(r'^reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$',
'password_reset_confirm',
{'template_name': 'accounts/password_reset_confirm.html'},
name='password-reset-confirm'),
url(r'^reset/done/$',
'password_reset_complete',
{'template_name': 'accounts/password_reset_complete.html'}),
)
|
50199aa8e270ff68f8d1026f88519609e2c97229
|
djgunicorn/config.py
|
djgunicorn/config.py
|
"""Gunicorn configuration file used by gunserver's Gunicorn subprocess.
This module is not designed to be imported directly, but provided as
Gunicorn's configuration file.
"""
import os
import sys
import django
import gunicorn
# General configs.
bind = os.environ['DJANGO_ADDRPORT']
logger_class = 'djgunicorn.logging.GunicornLogger'
def post_worker_init(worker):
"""Hook into Gunicorn to display message after launching.
This mimics the behaviour of Django's stock runserver command.
"""
quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-C'
sys.stdout.write(
"Django version {djangover}, Gunicorn version {gunicornver}, "
"using settings {settings!r}\n"
"Starting development server at http://{addrport}/\n"
"Quit the server with {quit_command}.\n".format(
djangover=django.get_version(),
gunicornver=gunicorn.__version__,
settings=os.environ.get('DJANGO_SETTINGS_MODULE'),
addrport=bind,
quit_command=quit_command,
),
)
def worker_exit(server, worker):
"""Hook into Gunicorn to display message after existing.
The purpose of this hook is purely cosmetic: we want a newline after the
worker reloads. This has an unintended side effect to display an extra
newline after the server quits, but it is relatively unimportant.
"""
sys.stdout.write('\n')
|
"""Gunicorn configuration file used by gunserver's Gunicorn subprocess.
This module is not designed to be imported directly, but provided as
Gunicorn's configuration file.
"""
import os
import sys
import django
import gunicorn
# General configs.
bind = os.environ['DJANGO_ADDRPORT']
logger_class = 'djgunicorn.logging.GunicornLogger'
def post_worker_init(worker):
"""Hook into Gunicorn to display message after launching.
This mimics the behaviour of Django's stock runserver command.
"""
quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-C'
sys.stdout.write(
"Django version {djangover}, Gunicorn version {gunicornver}, "
"using settings {settings!r}\n"
"Starting development server at http://{addrport}/\n"
"Quit the server with {quit_command}.\n".format(
djangover=django.get_version(),
gunicornver=gunicorn.__version__,
settings=os.environ.get('DJANGO_SETTINGS_MODULE'),
addrport=bind,
quit_command=quit_command,
),
)
def worker_int(worker):
"""Hook into Gunicorn to display message when worker gets an interruption.
The purpose of this hook is purely cosmetic: we want a newline when the
worker reloads. This has an unintended side effect to display an extra
newline after the server quits, but it is relatively unimportant.
"""
sys.stdout.write('\n')
|
Use worker_int to avoid \n being printed too late
|
Use worker_int to avoid \n being printed too late
|
Python
|
bsd-3-clause
|
uranusjr/django-gunicorn
|
"""Gunicorn configuration file used by gunserver's Gunicorn subprocess.
This module is not designed to be imported directly, but provided as
Gunicorn's configuration file.
"""
import os
import sys
import django
import gunicorn
# General configs.
bind = os.environ['DJANGO_ADDRPORT']
logger_class = 'djgunicorn.logging.GunicornLogger'
def post_worker_init(worker):
"""Hook into Gunicorn to display message after launching.
This mimics the behaviour of Django's stock runserver command.
"""
quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-C'
sys.stdout.write(
"Django version {djangover}, Gunicorn version {gunicornver}, "
"using settings {settings!r}\n"
"Starting development server at http://{addrport}/\n"
"Quit the server with {quit_command}.\n".format(
djangover=django.get_version(),
gunicornver=gunicorn.__version__,
settings=os.environ.get('DJANGO_SETTINGS_MODULE'),
addrport=bind,
quit_command=quit_command,
),
)
def worker_exit(server, worker):
"""Hook into Gunicorn to display message after existing.
The purpose of this hook is purely cosmetic: we want a newline after the
worker reloads. This has an unintended side effect to display an extra
newline after the server quits, but it is relatively unimportant.
"""
sys.stdout.write('\n')
Use worker_int to avoid \n being printed too late
|
"""Gunicorn configuration file used by gunserver's Gunicorn subprocess.
This module is not designed to be imported directly, but provided as
Gunicorn's configuration file.
"""
import os
import sys
import django
import gunicorn
# General configs.
bind = os.environ['DJANGO_ADDRPORT']
logger_class = 'djgunicorn.logging.GunicornLogger'
def post_worker_init(worker):
"""Hook into Gunicorn to display message after launching.
This mimics the behaviour of Django's stock runserver command.
"""
quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-C'
sys.stdout.write(
"Django version {djangover}, Gunicorn version {gunicornver}, "
"using settings {settings!r}\n"
"Starting development server at http://{addrport}/\n"
"Quit the server with {quit_command}.\n".format(
djangover=django.get_version(),
gunicornver=gunicorn.__version__,
settings=os.environ.get('DJANGO_SETTINGS_MODULE'),
addrport=bind,
quit_command=quit_command,
),
)
def worker_int(worker):
"""Hook into Gunicorn to display message when worker gets an interruption.
The purpose of this hook is purely cosmetic: we want a newline when the
worker reloads. This has an unintended side effect to display an extra
newline after the server quits, but it is relatively unimportant.
"""
sys.stdout.write('\n')
|
<commit_before>"""Gunicorn configuration file used by gunserver's Gunicorn subprocess.
This module is not designed to be imported directly, but provided as
Gunicorn's configuration file.
"""
import os
import sys
import django
import gunicorn
# General configs.
bind = os.environ['DJANGO_ADDRPORT']
logger_class = 'djgunicorn.logging.GunicornLogger'
def post_worker_init(worker):
"""Hook into Gunicorn to display message after launching.
This mimics the behaviour of Django's stock runserver command.
"""
quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-C'
sys.stdout.write(
"Django version {djangover}, Gunicorn version {gunicornver}, "
"using settings {settings!r}\n"
"Starting development server at http://{addrport}/\n"
"Quit the server with {quit_command}.\n".format(
djangover=django.get_version(),
gunicornver=gunicorn.__version__,
settings=os.environ.get('DJANGO_SETTINGS_MODULE'),
addrport=bind,
quit_command=quit_command,
),
)
def worker_exit(server, worker):
"""Hook into Gunicorn to display message after existing.
The purpose of this hook is purely cosmetic: we want a newline after the
worker reloads. This has an unintended side effect to display an extra
newline after the server quits, but it is relatively unimportant.
"""
sys.stdout.write('\n')
<commit_msg>Use worker_int to avoid \n being printed too late<commit_after>
|
"""Gunicorn configuration file used by gunserver's Gunicorn subprocess.
This module is not designed to be imported directly, but provided as
Gunicorn's configuration file.
"""
import os
import sys
import django
import gunicorn
# General configs.
bind = os.environ['DJANGO_ADDRPORT']
logger_class = 'djgunicorn.logging.GunicornLogger'
def post_worker_init(worker):
"""Hook into Gunicorn to display message after launching.
This mimics the behaviour of Django's stock runserver command.
"""
quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-C'
sys.stdout.write(
"Django version {djangover}, Gunicorn version {gunicornver}, "
"using settings {settings!r}\n"
"Starting development server at http://{addrport}/\n"
"Quit the server with {quit_command}.\n".format(
djangover=django.get_version(),
gunicornver=gunicorn.__version__,
settings=os.environ.get('DJANGO_SETTINGS_MODULE'),
addrport=bind,
quit_command=quit_command,
),
)
def worker_int(worker):
"""Hook into Gunicorn to display message when worker gets an interruption.
The purpose of this hook is purely cosmetic: we want a newline when the
worker reloads. This has an unintended side effect to display an extra
newline after the server quits, but it is relatively unimportant.
"""
sys.stdout.write('\n')
|
"""Gunicorn configuration file used by gunserver's Gunicorn subprocess.
This module is not designed to be imported directly, but provided as
Gunicorn's configuration file.
"""
import os
import sys
import django
import gunicorn
# General configs.
bind = os.environ['DJANGO_ADDRPORT']
logger_class = 'djgunicorn.logging.GunicornLogger'
def post_worker_init(worker):
"""Hook into Gunicorn to display message after launching.
This mimics the behaviour of Django's stock runserver command.
"""
quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-C'
sys.stdout.write(
"Django version {djangover}, Gunicorn version {gunicornver}, "
"using settings {settings!r}\n"
"Starting development server at http://{addrport}/\n"
"Quit the server with {quit_command}.\n".format(
djangover=django.get_version(),
gunicornver=gunicorn.__version__,
settings=os.environ.get('DJANGO_SETTINGS_MODULE'),
addrport=bind,
quit_command=quit_command,
),
)
def worker_exit(server, worker):
"""Hook into Gunicorn to display message after existing.
The purpose of this hook is purely cosmetic: we want a newline after the
worker reloads. This has an unintended side effect to display an extra
newline after the server quits, but it is relatively unimportant.
"""
sys.stdout.write('\n')
Use worker_int to avoid \n being printed too late"""Gunicorn configuration file used by gunserver's Gunicorn subprocess.
This module is not designed to be imported directly, but provided as
Gunicorn's configuration file.
"""
import os
import sys
import django
import gunicorn
# General configs.
bind = os.environ['DJANGO_ADDRPORT']
logger_class = 'djgunicorn.logging.GunicornLogger'
def post_worker_init(worker):
"""Hook into Gunicorn to display message after launching.
This mimics the behaviour of Django's stock runserver command.
"""
quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-C'
sys.stdout.write(
"Django version {djangover}, Gunicorn version {gunicornver}, "
"using settings {settings!r}\n"
"Starting development server at http://{addrport}/\n"
"Quit the server with {quit_command}.\n".format(
djangover=django.get_version(),
gunicornver=gunicorn.__version__,
settings=os.environ.get('DJANGO_SETTINGS_MODULE'),
addrport=bind,
quit_command=quit_command,
),
)
def worker_int(worker):
"""Hook into Gunicorn to display message when worker gets an interruption.
The purpose of this hook is purely cosmetic: we want a newline when the
worker reloads. This has an unintended side effect to display an extra
newline after the server quits, but it is relatively unimportant.
"""
sys.stdout.write('\n')
|
<commit_before>"""Gunicorn configuration file used by gunserver's Gunicorn subprocess.
This module is not designed to be imported directly, but provided as
Gunicorn's configuration file.
"""
import os
import sys
import django
import gunicorn
# General configs.
bind = os.environ['DJANGO_ADDRPORT']
logger_class = 'djgunicorn.logging.GunicornLogger'
def post_worker_init(worker):
"""Hook into Gunicorn to display message after launching.
This mimics the behaviour of Django's stock runserver command.
"""
quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-C'
sys.stdout.write(
"Django version {djangover}, Gunicorn version {gunicornver}, "
"using settings {settings!r}\n"
"Starting development server at http://{addrport}/\n"
"Quit the server with {quit_command}.\n".format(
djangover=django.get_version(),
gunicornver=gunicorn.__version__,
settings=os.environ.get('DJANGO_SETTINGS_MODULE'),
addrport=bind,
quit_command=quit_command,
),
)
def worker_exit(server, worker):
"""Hook into Gunicorn to display message after existing.
The purpose of this hook is purely cosmetic: we want a newline after the
worker reloads. This has an unintended side effect to display an extra
newline after the server quits, but it is relatively unimportant.
"""
sys.stdout.write('\n')
<commit_msg>Use worker_int to avoid \n being printed too late<commit_after>"""Gunicorn configuration file used by gunserver's Gunicorn subprocess.
This module is not designed to be imported directly, but provided as
Gunicorn's configuration file.
"""
import os
import sys
import django
import gunicorn
# General configs.
bind = os.environ['DJANGO_ADDRPORT']
logger_class = 'djgunicorn.logging.GunicornLogger'
def post_worker_init(worker):
"""Hook into Gunicorn to display message after launching.
This mimics the behaviour of Django's stock runserver command.
"""
quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-C'
sys.stdout.write(
"Django version {djangover}, Gunicorn version {gunicornver}, "
"using settings {settings!r}\n"
"Starting development server at http://{addrport}/\n"
"Quit the server with {quit_command}.\n".format(
djangover=django.get_version(),
gunicornver=gunicorn.__version__,
settings=os.environ.get('DJANGO_SETTINGS_MODULE'),
addrport=bind,
quit_command=quit_command,
),
)
def worker_int(worker):
"""Hook into Gunicorn to display message when worker gets an interruption.
The purpose of this hook is purely cosmetic: we want a newline when the
worker reloads. This has an unintended side effect to display an extra
newline after the server quits, but it is relatively unimportant.
"""
sys.stdout.write('\n')
|
a47b7ecc10f7aeff7b5897e30b608a313029c20d
|
checkmeout.py
|
checkmeout.py
|
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
if __name__ == '__main__':
app.run()
|
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
|
Change server to debug mode
|
Change server to debug mode
|
Python
|
mit
|
tomshen/checkmeout,tomshen/checkmeout
|
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
if __name__ == '__main__':
app.run()Change server to debug mode
|
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
|
<commit_before>from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
if __name__ == '__main__':
app.run()<commit_msg>Change server to debug mode<commit_after>
|
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
|
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
if __name__ == '__main__':
app.run()Change server to debug modefrom flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
|
<commit_before>from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
if __name__ == '__main__':
app.run()<commit_msg>Change server to debug mode<commit_after>from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
|
8741c1887b3d04e4e2dd3ef9df49a78d97df1d1b
|
hypermap/aggregator/urls.py
|
hypermap/aggregator/urls.py
|
from django.conf import settings
from django.conf.urls import include, patterns, url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^search', views.search, name='search'),
url(r'^service/(?P<service_id>\d+)/$', views.service_detail, name='service_detail'),
url(r'^service/(?P<service_id>\d+)/checks$', views.service_checks, name='service_checks'),
url(r'^layer/(?P<layer_id>\d+)/$', views.layer_detail, name='layer_detail'),
url(r'^layer/(?P<layer_id>\d+)/checks$', views.layer_checks, name='layer_checks'),
url(r'^celery_monitor/$', views.celery_monitor, name='celery_monitor'),
url(r'^update_progressbar/(?P<task_id>[^/]*)$', views.update_progressbar, name='update_progressbar'),
]
if settings.DEBUG:
import debug_toolbar
urlpatterns += patterns(
'',
url(r'^__debug__/', include(debug_toolbar.urls)),
)
|
from django.conf import settings
from django.conf.urls import include, patterns, url
from . import views
index = url(r'^', views.search, name='index')
if settings.SOLR_ENABLED:
index = url(r'^$', views.index, name='index')
urlpatterns = [
index,
url(r'^search', views.search, name='search'),
url(r'^service/(?P<service_id>\d+)/$', views.service_detail, name='service_detail'),
url(r'^service/(?P<service_id>\d+)/checks$', views.service_checks, name='service_checks'),
url(r'^layer/(?P<layer_id>\d+)/$', views.layer_detail, name='layer_detail'),
url(r'^layer/(?P<layer_id>\d+)/checks$', views.layer_checks, name='layer_checks'),
url(r'^celery_monitor/$', views.celery_monitor, name='celery_monitor'),
url(r'^update_progressbar/(?P<task_id>[^/]*)$', views.update_progressbar, name='update_progressbar'),
]
if settings.DEBUG:
import debug_toolbar
urlpatterns += patterns(
'',
url(r'^__debug__/', include(debug_toolbar.urls)),
)
|
Use old index view when SOLR is disabled
|
Use old index view when SOLR is disabled
|
Python
|
mit
|
cga-harvard/hypermap,cga-harvard/HHypermap,cga-harvard/HHypermap,cga-harvard/hypermap,jmwenda/hypermap,cga-harvard/HHypermap,jmwenda/hypermap,jmwenda/hypermap,cga-harvard/hypermap,jmwenda/hypermap,cga-harvard/hypermap,cga-harvard/HHypermap
|
from django.conf import settings
from django.conf.urls import include, patterns, url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^search', views.search, name='search'),
url(r'^service/(?P<service_id>\d+)/$', views.service_detail, name='service_detail'),
url(r'^service/(?P<service_id>\d+)/checks$', views.service_checks, name='service_checks'),
url(r'^layer/(?P<layer_id>\d+)/$', views.layer_detail, name='layer_detail'),
url(r'^layer/(?P<layer_id>\d+)/checks$', views.layer_checks, name='layer_checks'),
url(r'^celery_monitor/$', views.celery_monitor, name='celery_monitor'),
url(r'^update_progressbar/(?P<task_id>[^/]*)$', views.update_progressbar, name='update_progressbar'),
]
if settings.DEBUG:
import debug_toolbar
urlpatterns += patterns(
'',
url(r'^__debug__/', include(debug_toolbar.urls)),
)
Use old index view when SOLR is disabled
|
from django.conf import settings
from django.conf.urls import include, patterns, url
from . import views
index = url(r'^', views.search, name='index')
if settings.SOLR_ENABLED:
index = url(r'^$', views.index, name='index')
urlpatterns = [
index,
url(r'^search', views.search, name='search'),
url(r'^service/(?P<service_id>\d+)/$', views.service_detail, name='service_detail'),
url(r'^service/(?P<service_id>\d+)/checks$', views.service_checks, name='service_checks'),
url(r'^layer/(?P<layer_id>\d+)/$', views.layer_detail, name='layer_detail'),
url(r'^layer/(?P<layer_id>\d+)/checks$', views.layer_checks, name='layer_checks'),
url(r'^celery_monitor/$', views.celery_monitor, name='celery_monitor'),
url(r'^update_progressbar/(?P<task_id>[^/]*)$', views.update_progressbar, name='update_progressbar'),
]
if settings.DEBUG:
import debug_toolbar
urlpatterns += patterns(
'',
url(r'^__debug__/', include(debug_toolbar.urls)),
)
|
<commit_before>from django.conf import settings
from django.conf.urls import include, patterns, url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^search', views.search, name='search'),
url(r'^service/(?P<service_id>\d+)/$', views.service_detail, name='service_detail'),
url(r'^service/(?P<service_id>\d+)/checks$', views.service_checks, name='service_checks'),
url(r'^layer/(?P<layer_id>\d+)/$', views.layer_detail, name='layer_detail'),
url(r'^layer/(?P<layer_id>\d+)/checks$', views.layer_checks, name='layer_checks'),
url(r'^celery_monitor/$', views.celery_monitor, name='celery_monitor'),
url(r'^update_progressbar/(?P<task_id>[^/]*)$', views.update_progressbar, name='update_progressbar'),
]
if settings.DEBUG:
import debug_toolbar
urlpatterns += patterns(
'',
url(r'^__debug__/', include(debug_toolbar.urls)),
)
<commit_msg>Use old index view when SOLR is disabled<commit_after>
|
from django.conf import settings
from django.conf.urls import include, patterns, url
from . import views
index = url(r'^', views.search, name='index')
if settings.SOLR_ENABLED:
index = url(r'^$', views.index, name='index')
urlpatterns = [
index,
url(r'^search', views.search, name='search'),
url(r'^service/(?P<service_id>\d+)/$', views.service_detail, name='service_detail'),
url(r'^service/(?P<service_id>\d+)/checks$', views.service_checks, name='service_checks'),
url(r'^layer/(?P<layer_id>\d+)/$', views.layer_detail, name='layer_detail'),
url(r'^layer/(?P<layer_id>\d+)/checks$', views.layer_checks, name='layer_checks'),
url(r'^celery_monitor/$', views.celery_monitor, name='celery_monitor'),
url(r'^update_progressbar/(?P<task_id>[^/]*)$', views.update_progressbar, name='update_progressbar'),
]
if settings.DEBUG:
import debug_toolbar
urlpatterns += patterns(
'',
url(r'^__debug__/', include(debug_toolbar.urls)),
)
|
from django.conf import settings
from django.conf.urls import include, patterns, url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^search', views.search, name='search'),
url(r'^service/(?P<service_id>\d+)/$', views.service_detail, name='service_detail'),
url(r'^service/(?P<service_id>\d+)/checks$', views.service_checks, name='service_checks'),
url(r'^layer/(?P<layer_id>\d+)/$', views.layer_detail, name='layer_detail'),
url(r'^layer/(?P<layer_id>\d+)/checks$', views.layer_checks, name='layer_checks'),
url(r'^celery_monitor/$', views.celery_monitor, name='celery_monitor'),
url(r'^update_progressbar/(?P<task_id>[^/]*)$', views.update_progressbar, name='update_progressbar'),
]
if settings.DEBUG:
import debug_toolbar
urlpatterns += patterns(
'',
url(r'^__debug__/', include(debug_toolbar.urls)),
)
Use old index view when SOLR is disabledfrom django.conf import settings
from django.conf.urls import include, patterns, url
from . import views
index = url(r'^', views.search, name='index')
if settings.SOLR_ENABLED:
index = url(r'^$', views.index, name='index')
urlpatterns = [
index,
url(r'^search', views.search, name='search'),
url(r'^service/(?P<service_id>\d+)/$', views.service_detail, name='service_detail'),
url(r'^service/(?P<service_id>\d+)/checks$', views.service_checks, name='service_checks'),
url(r'^layer/(?P<layer_id>\d+)/$', views.layer_detail, name='layer_detail'),
url(r'^layer/(?P<layer_id>\d+)/checks$', views.layer_checks, name='layer_checks'),
url(r'^celery_monitor/$', views.celery_monitor, name='celery_monitor'),
url(r'^update_progressbar/(?P<task_id>[^/]*)$', views.update_progressbar, name='update_progressbar'),
]
if settings.DEBUG:
import debug_toolbar
urlpatterns += patterns(
'',
url(r'^__debug__/', include(debug_toolbar.urls)),
)
|
<commit_before>from django.conf import settings
from django.conf.urls import include, patterns, url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^search', views.search, name='search'),
url(r'^service/(?P<service_id>\d+)/$', views.service_detail, name='service_detail'),
url(r'^service/(?P<service_id>\d+)/checks$', views.service_checks, name='service_checks'),
url(r'^layer/(?P<layer_id>\d+)/$', views.layer_detail, name='layer_detail'),
url(r'^layer/(?P<layer_id>\d+)/checks$', views.layer_checks, name='layer_checks'),
url(r'^celery_monitor/$', views.celery_monitor, name='celery_monitor'),
url(r'^update_progressbar/(?P<task_id>[^/]*)$', views.update_progressbar, name='update_progressbar'),
]
if settings.DEBUG:
import debug_toolbar
urlpatterns += patterns(
'',
url(r'^__debug__/', include(debug_toolbar.urls)),
)
<commit_msg>Use old index view when SOLR is disabled<commit_after>from django.conf import settings
from django.conf.urls import include, patterns, url
from . import views
index = url(r'^', views.search, name='index')
if settings.SOLR_ENABLED:
index = url(r'^$', views.index, name='index')
urlpatterns = [
index,
url(r'^search', views.search, name='search'),
url(r'^service/(?P<service_id>\d+)/$', views.service_detail, name='service_detail'),
url(r'^service/(?P<service_id>\d+)/checks$', views.service_checks, name='service_checks'),
url(r'^layer/(?P<layer_id>\d+)/$', views.layer_detail, name='layer_detail'),
url(r'^layer/(?P<layer_id>\d+)/checks$', views.layer_checks, name='layer_checks'),
url(r'^celery_monitor/$', views.celery_monitor, name='celery_monitor'),
url(r'^update_progressbar/(?P<task_id>[^/]*)$', views.update_progressbar, name='update_progressbar'),
]
if settings.DEBUG:
import debug_toolbar
urlpatterns += patterns(
'',
url(r'^__debug__/', include(debug_toolbar.urls)),
)
|
01c7a5657078bff2670ec2913ad0b884598dbcbb
|
cde/types.py
|
cde/types.py
|
"""Types to make coding cde easier"""
import os
from pysyte.types import paths
from pysyte.types.lists import UniquelyTrues
class PossiblePaths(UniquelyTrues):
"""A unique list of possible paths"""
def predicate(self, item):
"""Exclude items which don't exist"""
return bool(item) and os.path.exists(item)
def paths(self):
return [paths.path(_) for _ in self if self.predicate(_)]
class UniquePaths(PossiblePaths):
def contains(self, item):
for path in self:
if path.same_path(item):
return True
return False
|
"""Types to make coding cde easier"""
import os
from typing import List
from pysyte.types import paths
from pysyte.types.lists import UniquelyTrues
class PossiblePaths(UniquelyTrues):
"""A unique list of possible paths"""
def convert(self, item: str) -> paths.StringPath:
return paths.path(item)
def predicate(self, item: str) -> bool:
"""Exclude items which don't exist"""
return bool(item) and os.path.exists(item)
def paths(self) -> List[paths.StringPath]:
return [_ for _ in self if self.predicate(_)]
class UniquePaths(PossiblePaths):
def __contains__(self, item: ):
for path in self:
if path.same_path(item):
return True
return False
class Roots(UniquePaths):
def predicate(self, item: str) -> bool:
path_ = paths.path(item)
if path_ in self:
return False
if path_.parent in self:
return False
for i, root in enumerate(self):
if root.parent.same_path(path_):
break
else:
self[i] = path_
|
Add Roots class to filter paths of children
|
Add Roots class to filter paths of children
Takes out python dirs like .../cde/cde
|
Python
|
mit
|
jalanb/kd,jalanb/kd
|
"""Types to make coding cde easier"""
import os
from pysyte.types import paths
from pysyte.types.lists import UniquelyTrues
class PossiblePaths(UniquelyTrues):
"""A unique list of possible paths"""
def predicate(self, item):
"""Exclude items which don't exist"""
return bool(item) and os.path.exists(item)
def paths(self):
return [paths.path(_) for _ in self if self.predicate(_)]
class UniquePaths(PossiblePaths):
def contains(self, item):
for path in self:
if path.same_path(item):
return True
return False
Add Roots class to filter paths of children
Takes out python dirs like .../cde/cde
|
"""Types to make coding cde easier"""
import os
from typing import List
from pysyte.types import paths
from pysyte.types.lists import UniquelyTrues
class PossiblePaths(UniquelyTrues):
"""A unique list of possible paths"""
def convert(self, item: str) -> paths.StringPath:
return paths.path(item)
def predicate(self, item: str) -> bool:
"""Exclude items which don't exist"""
return bool(item) and os.path.exists(item)
def paths(self) -> List[paths.StringPath]:
return [_ for _ in self if self.predicate(_)]
class UniquePaths(PossiblePaths):
def __contains__(self, item: ):
for path in self:
if path.same_path(item):
return True
return False
class Roots(UniquePaths):
def predicate(self, item: str) -> bool:
path_ = paths.path(item)
if path_ in self:
return False
if path_.parent in self:
return False
for i, root in enumerate(self):
if root.parent.same_path(path_):
break
else:
self[i] = path_
|
<commit_before>"""Types to make coding cde easier"""
import os
from pysyte.types import paths
from pysyte.types.lists import UniquelyTrues
class PossiblePaths(UniquelyTrues):
"""A unique list of possible paths"""
def predicate(self, item):
"""Exclude items which don't exist"""
return bool(item) and os.path.exists(item)
def paths(self):
return [paths.path(_) for _ in self if self.predicate(_)]
class UniquePaths(PossiblePaths):
def contains(self, item):
for path in self:
if path.same_path(item):
return True
return False
<commit_msg>Add Roots class to filter paths of children
Takes out python dirs like .../cde/cde<commit_after>
|
"""Types to make coding cde easier"""
import os
from typing import List
from pysyte.types import paths
from pysyte.types.lists import UniquelyTrues
class PossiblePaths(UniquelyTrues):
"""A unique list of possible paths"""
def convert(self, item: str) -> paths.StringPath:
return paths.path(item)
def predicate(self, item: str) -> bool:
"""Exclude items which don't exist"""
return bool(item) and os.path.exists(item)
def paths(self) -> List[paths.StringPath]:
return [_ for _ in self if self.predicate(_)]
class UniquePaths(PossiblePaths):
def __contains__(self, item: ):
for path in self:
if path.same_path(item):
return True
return False
class Roots(UniquePaths):
def predicate(self, item: str) -> bool:
path_ = paths.path(item)
if path_ in self:
return False
if path_.parent in self:
return False
for i, root in enumerate(self):
if root.parent.same_path(path_):
break
else:
self[i] = path_
|
"""Types to make coding cde easier"""
import os
from pysyte.types import paths
from pysyte.types.lists import UniquelyTrues
class PossiblePaths(UniquelyTrues):
"""A unique list of possible paths"""
def predicate(self, item):
"""Exclude items which don't exist"""
return bool(item) and os.path.exists(item)
def paths(self):
return [paths.path(_) for _ in self if self.predicate(_)]
class UniquePaths(PossiblePaths):
def contains(self, item):
for path in self:
if path.same_path(item):
return True
return False
Add Roots class to filter paths of children
Takes out python dirs like .../cde/cde"""Types to make coding cde easier"""
import os
from typing import List
from pysyte.types import paths
from pysyte.types.lists import UniquelyTrues
class PossiblePaths(UniquelyTrues):
"""A unique list of possible paths"""
def convert(self, item: str) -> paths.StringPath:
return paths.path(item)
def predicate(self, item: str) -> bool:
"""Exclude items which don't exist"""
return bool(item) and os.path.exists(item)
def paths(self) -> List[paths.StringPath]:
return [_ for _ in self if self.predicate(_)]
class UniquePaths(PossiblePaths):
def __contains__(self, item: ):
for path in self:
if path.same_path(item):
return True
return False
class Roots(UniquePaths):
def predicate(self, item: str) -> bool:
path_ = paths.path(item)
if path_ in self:
return False
if path_.parent in self:
return False
for i, root in enumerate(self):
if root.parent.same_path(path_):
break
else:
self[i] = path_
|
<commit_before>"""Types to make coding cde easier"""
import os
from pysyte.types import paths
from pysyte.types.lists import UniquelyTrues
class PossiblePaths(UniquelyTrues):
"""A unique list of possible paths"""
def predicate(self, item):
"""Exclude items which don't exist"""
return bool(item) and os.path.exists(item)
def paths(self):
return [paths.path(_) for _ in self if self.predicate(_)]
class UniquePaths(PossiblePaths):
def contains(self, item):
for path in self:
if path.same_path(item):
return True
return False
<commit_msg>Add Roots class to filter paths of children
Takes out python dirs like .../cde/cde<commit_after>"""Types to make coding cde easier"""
import os
from typing import List
from pysyte.types import paths
from pysyte.types.lists import UniquelyTrues
class PossiblePaths(UniquelyTrues):
"""A unique list of possible paths"""
def convert(self, item: str) -> paths.StringPath:
return paths.path(item)
def predicate(self, item: str) -> bool:
"""Exclude items which don't exist"""
return bool(item) and os.path.exists(item)
def paths(self) -> List[paths.StringPath]:
return [_ for _ in self if self.predicate(_)]
class UniquePaths(PossiblePaths):
def __contains__(self, item: ):
for path in self:
if path.same_path(item):
return True
return False
class Roots(UniquePaths):
def predicate(self, item: str) -> bool:
path_ = paths.path(item)
if path_ in self:
return False
if path_.parent in self:
return False
for i, root in enumerate(self):
if root.parent.same_path(path_):
break
else:
self[i] = path_
|
3d7ba9709b33982e6e65b24ee6f7d97cfa6ef22f
|
db/buyout.py
|
db/buyout.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from .common import Base, session_scope
from sqlalchemy import and_
class Buyout(Base):
__tablename__ = 'buyouts'
__autoload__ = True
STANDARD_ATTRS = [
'buyout_team_id', 'buyout_date', 'length', 'value',
'start_season', 'end_season'
]
def __init__(self, player_id, contract_id, buyout_data_dict):
self.player_id = player_id
self.contract_id = contract_id
for attr in self.STANDARD_ATTRS:
if attr in buyout_data_dict:
setattr(self, attr, buyout_data_dict[attr])
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from .common import Base, session_scope
class Buyout(Base):
__tablename__ = 'buyouts'
__autoload__ = True
STANDARD_ATTRS = [
'buyout_team_id', 'buyout_date', 'length', 'value',
'start_season', 'end_season'
]
def __init__(self, player_id, contract_id, buyout_data_dict):
self.player_id = player_id
self.contract_id = contract_id
for attr in self.STANDARD_ATTRS:
if attr in buyout_data_dict:
setattr(self, attr, buyout_data_dict[attr])
@classmethod
def find(self, contract_id):
with session_scope() as session:
try:
buyout = session.query(Buyout).filter(
Buyout.contract_id == contract_id
).one()
except:
buyout = None
return buyout
def update(self, other):
for attr in self.STANDARD_ATTRS:
if hasattr(other, attr):
setattr(self, attr, getattr(other, attr))
def __eq__(self, other):
return ((
self.contract_id, self.player_id, self.buyout_team_id,
self.buyout_date, self.length, self.value,
self.start_season, self.end_season
) == (
other.contract_id, other.player_id, other.buyout_team_id,
other.buyout_date, other.length, other.value,
other.start_season, other.end_season))
def __ne__(self, other):
return not self == other
|
Add find, update and comparison methods
|
Add find, update and comparison methods
|
Python
|
mit
|
leaffan/pynhldb
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from .common import Base, session_scope
from sqlalchemy import and_
class Buyout(Base):
__tablename__ = 'buyouts'
__autoload__ = True
STANDARD_ATTRS = [
'buyout_team_id', 'buyout_date', 'length', 'value',
'start_season', 'end_season'
]
def __init__(self, player_id, contract_id, buyout_data_dict):
self.player_id = player_id
self.contract_id = contract_id
for attr in self.STANDARD_ATTRS:
if attr in buyout_data_dict:
setattr(self, attr, buyout_data_dict[attr])
Add find, update and comparison methods
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from .common import Base, session_scope
class Buyout(Base):
__tablename__ = 'buyouts'
__autoload__ = True
STANDARD_ATTRS = [
'buyout_team_id', 'buyout_date', 'length', 'value',
'start_season', 'end_season'
]
def __init__(self, player_id, contract_id, buyout_data_dict):
self.player_id = player_id
self.contract_id = contract_id
for attr in self.STANDARD_ATTRS:
if attr in buyout_data_dict:
setattr(self, attr, buyout_data_dict[attr])
@classmethod
def find(self, contract_id):
with session_scope() as session:
try:
buyout = session.query(Buyout).filter(
Buyout.contract_id == contract_id
).one()
except:
buyout = None
return buyout
def update(self, other):
for attr in self.STANDARD_ATTRS:
if hasattr(other, attr):
setattr(self, attr, getattr(other, attr))
def __eq__(self, other):
return ((
self.contract_id, self.player_id, self.buyout_team_id,
self.buyout_date, self.length, self.value,
self.start_season, self.end_season
) == (
other.contract_id, other.player_id, other.buyout_team_id,
other.buyout_date, other.length, other.value,
other.start_season, other.end_season))
def __ne__(self, other):
return not self == other
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from .common import Base, session_scope
from sqlalchemy import and_
class Buyout(Base):
__tablename__ = 'buyouts'
__autoload__ = True
STANDARD_ATTRS = [
'buyout_team_id', 'buyout_date', 'length', 'value',
'start_season', 'end_season'
]
def __init__(self, player_id, contract_id, buyout_data_dict):
self.player_id = player_id
self.contract_id = contract_id
for attr in self.STANDARD_ATTRS:
if attr in buyout_data_dict:
setattr(self, attr, buyout_data_dict[attr])
<commit_msg>Add find, update and comparison methods<commit_after>
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from .common import Base, session_scope
class Buyout(Base):
__tablename__ = 'buyouts'
__autoload__ = True
STANDARD_ATTRS = [
'buyout_team_id', 'buyout_date', 'length', 'value',
'start_season', 'end_season'
]
def __init__(self, player_id, contract_id, buyout_data_dict):
self.player_id = player_id
self.contract_id = contract_id
for attr in self.STANDARD_ATTRS:
if attr in buyout_data_dict:
setattr(self, attr, buyout_data_dict[attr])
@classmethod
def find(self, contract_id):
with session_scope() as session:
try:
buyout = session.query(Buyout).filter(
Buyout.contract_id == contract_id
).one()
except:
buyout = None
return buyout
def update(self, other):
for attr in self.STANDARD_ATTRS:
if hasattr(other, attr):
setattr(self, attr, getattr(other, attr))
def __eq__(self, other):
return ((
self.contract_id, self.player_id, self.buyout_team_id,
self.buyout_date, self.length, self.value,
self.start_season, self.end_season
) == (
other.contract_id, other.player_id, other.buyout_team_id,
other.buyout_date, other.length, other.value,
other.start_season, other.end_season))
def __ne__(self, other):
return not self == other
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from .common import Base, session_scope
from sqlalchemy import and_
class Buyout(Base):
__tablename__ = 'buyouts'
__autoload__ = True
STANDARD_ATTRS = [
'buyout_team_id', 'buyout_date', 'length', 'value',
'start_season', 'end_season'
]
def __init__(self, player_id, contract_id, buyout_data_dict):
self.player_id = player_id
self.contract_id = contract_id
for attr in self.STANDARD_ATTRS:
if attr in buyout_data_dict:
setattr(self, attr, buyout_data_dict[attr])
Add find, update and comparison methods#!/usr/bin/env python
# -*- coding: utf-8 -*-
from .common import Base, session_scope
class Buyout(Base):
__tablename__ = 'buyouts'
__autoload__ = True
STANDARD_ATTRS = [
'buyout_team_id', 'buyout_date', 'length', 'value',
'start_season', 'end_season'
]
def __init__(self, player_id, contract_id, buyout_data_dict):
self.player_id = player_id
self.contract_id = contract_id
for attr in self.STANDARD_ATTRS:
if attr in buyout_data_dict:
setattr(self, attr, buyout_data_dict[attr])
@classmethod
def find(self, contract_id):
with session_scope() as session:
try:
buyout = session.query(Buyout).filter(
Buyout.contract_id == contract_id
).one()
except:
buyout = None
return buyout
def update(self, other):
for attr in self.STANDARD_ATTRS:
if hasattr(other, attr):
setattr(self, attr, getattr(other, attr))
def __eq__(self, other):
return ((
self.contract_id, self.player_id, self.buyout_team_id,
self.buyout_date, self.length, self.value,
self.start_season, self.end_season
) == (
other.contract_id, other.player_id, other.buyout_team_id,
other.buyout_date, other.length, other.value,
other.start_season, other.end_season))
def __ne__(self, other):
return not self == other
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from .common import Base, session_scope
from sqlalchemy import and_
class Buyout(Base):
__tablename__ = 'buyouts'
__autoload__ = True
STANDARD_ATTRS = [
'buyout_team_id', 'buyout_date', 'length', 'value',
'start_season', 'end_season'
]
def __init__(self, player_id, contract_id, buyout_data_dict):
self.player_id = player_id
self.contract_id = contract_id
for attr in self.STANDARD_ATTRS:
if attr in buyout_data_dict:
setattr(self, attr, buyout_data_dict[attr])
<commit_msg>Add find, update and comparison methods<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from .common import Base, session_scope
class Buyout(Base):
__tablename__ = 'buyouts'
__autoload__ = True
STANDARD_ATTRS = [
'buyout_team_id', 'buyout_date', 'length', 'value',
'start_season', 'end_season'
]
def __init__(self, player_id, contract_id, buyout_data_dict):
self.player_id = player_id
self.contract_id = contract_id
for attr in self.STANDARD_ATTRS:
if attr in buyout_data_dict:
setattr(self, attr, buyout_data_dict[attr])
@classmethod
def find(self, contract_id):
with session_scope() as session:
try:
buyout = session.query(Buyout).filter(
Buyout.contract_id == contract_id
).one()
except:
buyout = None
return buyout
def update(self, other):
for attr in self.STANDARD_ATTRS:
if hasattr(other, attr):
setattr(self, attr, getattr(other, attr))
def __eq__(self, other):
return ((
self.contract_id, self.player_id, self.buyout_team_id,
self.buyout_date, self.length, self.value,
self.start_season, self.end_season
) == (
other.contract_id, other.player_id, other.buyout_team_id,
other.buyout_date, other.length, other.value,
other.start_season, other.end_season))
def __ne__(self, other):
return not self == other
|
3feccc140c0371becccb3f80bef00d30b4bc15bf
|
corehq/sql_accessors/migrations/0056_add_hashlib_functions.py
|
corehq/sql_accessors/migrations/0056_add_hashlib_functions.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-12-04 08:36
from __future__ import absolute_import, unicode_literals
from django.db import migrations
from django.conf import settings
from corehq.sql_db.operations import HqRunSQL, noop_migration
class Migration(migrations.Migration):
dependencies = [
('sql_accessors', '0055_set_form_modified_on'),
]
operations = [
# this originally installed the hashlib extension in production as well
# but commcare-cloud does that where possible already
# and Amazon RDS doesn't allow it
HqRunSQL(
'CREATE EXTENSION IF NOT EXISTS hashlib',
'DROP EXTENSION hashlib'
)
if settings.UNIT_TESTING else noop_migration()
]
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-12-04 08:36
from __future__ import absolute_import, unicode_literals
from django.db import migrations
from django.conf import settings
from corehq.sql_db.operations import HqRunSQL, noop_migration
class Migration(migrations.Migration):
dependencies = [
('sql_accessors', '0055_set_form_modified_on'),
]
operations = [
# this originally installed the hashlib extension in production as well
# but commcare-cloud does that where possible already
# and Amazon RDS doesn't allow it
# Todo: Move this to testing harness, doesn't really belong here.
# See https://github.com/dimagi/commcare-hq/pull/21627#pullrequestreview-149807976
HqRunSQL(
'CREATE EXTENSION IF NOT EXISTS hashlib',
'DROP EXTENSION hashlib'
)
if settings.UNIT_TESTING else noop_migration()
]
|
Add comment about moving hashlib extention creation to test harness
|
Add comment about moving hashlib extention creation to test harness
|
Python
|
bsd-3-clause
|
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-12-04 08:36
from __future__ import absolute_import, unicode_literals
from django.db import migrations
from django.conf import settings
from corehq.sql_db.operations import HqRunSQL, noop_migration
class Migration(migrations.Migration):
dependencies = [
('sql_accessors', '0055_set_form_modified_on'),
]
operations = [
# this originally installed the hashlib extension in production as well
# but commcare-cloud does that where possible already
# and Amazon RDS doesn't allow it
HqRunSQL(
'CREATE EXTENSION IF NOT EXISTS hashlib',
'DROP EXTENSION hashlib'
)
if settings.UNIT_TESTING else noop_migration()
]
Add comment about moving hashlib extention creation to test harness
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-12-04 08:36
from __future__ import absolute_import, unicode_literals
from django.db import migrations
from django.conf import settings
from corehq.sql_db.operations import HqRunSQL, noop_migration
class Migration(migrations.Migration):
dependencies = [
('sql_accessors', '0055_set_form_modified_on'),
]
operations = [
# this originally installed the hashlib extension in production as well
# but commcare-cloud does that where possible already
# and Amazon RDS doesn't allow it
# Todo: Move this to testing harness, doesn't really belong here.
# See https://github.com/dimagi/commcare-hq/pull/21627#pullrequestreview-149807976
HqRunSQL(
'CREATE EXTENSION IF NOT EXISTS hashlib',
'DROP EXTENSION hashlib'
)
if settings.UNIT_TESTING else noop_migration()
]
|
<commit_before># -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-12-04 08:36
from __future__ import absolute_import, unicode_literals
from django.db import migrations
from django.conf import settings
from corehq.sql_db.operations import HqRunSQL, noop_migration
class Migration(migrations.Migration):
dependencies = [
('sql_accessors', '0055_set_form_modified_on'),
]
operations = [
# this originally installed the hashlib extension in production as well
# but commcare-cloud does that where possible already
# and Amazon RDS doesn't allow it
HqRunSQL(
'CREATE EXTENSION IF NOT EXISTS hashlib',
'DROP EXTENSION hashlib'
)
if settings.UNIT_TESTING else noop_migration()
]
<commit_msg>Add comment about moving hashlib extention creation to test harness<commit_after>
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-12-04 08:36
from __future__ import absolute_import, unicode_literals
from django.db import migrations
from django.conf import settings
from corehq.sql_db.operations import HqRunSQL, noop_migration
class Migration(migrations.Migration):
dependencies = [
('sql_accessors', '0055_set_form_modified_on'),
]
operations = [
# this originally installed the hashlib extension in production as well
# but commcare-cloud does that where possible already
# and Amazon RDS doesn't allow it
# Todo: Move this to testing harness, doesn't really belong here.
# See https://github.com/dimagi/commcare-hq/pull/21627#pullrequestreview-149807976
HqRunSQL(
'CREATE EXTENSION IF NOT EXISTS hashlib',
'DROP EXTENSION hashlib'
)
if settings.UNIT_TESTING else noop_migration()
]
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-12-04 08:36
from __future__ import absolute_import, unicode_literals
from django.db import migrations
from django.conf import settings
from corehq.sql_db.operations import HqRunSQL, noop_migration
class Migration(migrations.Migration):
dependencies = [
('sql_accessors', '0055_set_form_modified_on'),
]
operations = [
# this originally installed the hashlib extension in production as well
# but commcare-cloud does that where possible already
# and Amazon RDS doesn't allow it
HqRunSQL(
'CREATE EXTENSION IF NOT EXISTS hashlib',
'DROP EXTENSION hashlib'
)
if settings.UNIT_TESTING else noop_migration()
]
Add comment about moving hashlib extention creation to test harness# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-12-04 08:36
from __future__ import absolute_import, unicode_literals
from django.db import migrations
from django.conf import settings
from corehq.sql_db.operations import HqRunSQL, noop_migration
class Migration(migrations.Migration):
dependencies = [
('sql_accessors', '0055_set_form_modified_on'),
]
operations = [
# this originally installed the hashlib extension in production as well
# but commcare-cloud does that where possible already
# and Amazon RDS doesn't allow it
# Todo: Move this to testing harness, doesn't really belong here.
# See https://github.com/dimagi/commcare-hq/pull/21627#pullrequestreview-149807976
HqRunSQL(
'CREATE EXTENSION IF NOT EXISTS hashlib',
'DROP EXTENSION hashlib'
)
if settings.UNIT_TESTING else noop_migration()
]
|
<commit_before># -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-12-04 08:36
from __future__ import absolute_import, unicode_literals
from django.db import migrations
from django.conf import settings
from corehq.sql_db.operations import HqRunSQL, noop_migration
class Migration(migrations.Migration):
dependencies = [
('sql_accessors', '0055_set_form_modified_on'),
]
operations = [
# this originally installed the hashlib extension in production as well
# but commcare-cloud does that where possible already
# and Amazon RDS doesn't allow it
HqRunSQL(
'CREATE EXTENSION IF NOT EXISTS hashlib',
'DROP EXTENSION hashlib'
)
if settings.UNIT_TESTING else noop_migration()
]
<commit_msg>Add comment about moving hashlib extention creation to test harness<commit_after># -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-12-04 08:36
from __future__ import absolute_import, unicode_literals
from django.db import migrations
from django.conf import settings
from corehq.sql_db.operations import HqRunSQL, noop_migration
class Migration(migrations.Migration):
dependencies = [
('sql_accessors', '0055_set_form_modified_on'),
]
operations = [
# this originally installed the hashlib extension in production as well
# but commcare-cloud does that where possible already
# and Amazon RDS doesn't allow it
# Todo: Move this to testing harness, doesn't really belong here.
# See https://github.com/dimagi/commcare-hq/pull/21627#pullrequestreview-149807976
HqRunSQL(
'CREATE EXTENSION IF NOT EXISTS hashlib',
'DROP EXTENSION hashlib'
)
if settings.UNIT_TESTING else noop_migration()
]
|
f350e1dade6eff0aa82312dc9f66e98da19351eb
|
ec2_instance_types_list.py
|
ec2_instance_types_list.py
|
#!/usr/bin/env python
from bs4 import BeautifulSoup
import urllib
site_content = urllib.urlopen('https://aws.amazon.com/ec2/instance-types/').read()
soup = BeautifulSoup(site_content, 'lxml')
aws_tables = soup.find_all("div", {"class": "aws-table"});
for table_div in aws_tables:
trs = table_div.find('table').tbody.find_all('tr')
for tr in trs:
tds = tr.find_all('td')
rng = len(tds)
line = ''
if rng > 0:
for i in range(0, rng):
if i > 0:
line += ', '
line += tds[i].get_text().strip()
print(line)
print('\n')
|
#!/usr/bin/env python
from bs4 import BeautifulSoup
import urllib
import sys
import codecs
# Change encoding to fix a bug on windows
sys.stdout = codecs.getwriter("iso-8859-1")(sys.stdout, 'xmlcharrefreplace')
# Download a copy of the EC2 Instance Types from Amazon and scrape the content
site_content = urllib.urlopen('https://aws.amazon.com/ec2/instance-types/').read()
soup = BeautifulSoup(site_content, 'lxml')
aws_tables = soup.find_all("div", {"class": "aws-table"});
for table_div in aws_tables:
trs = table_div.find('table').tbody.find_all('tr')
for tr in trs:
tds = tr.find_all('td')
rng = len(tds)
line = ''
if rng > 0:
for i in range(0, rng):
if i > 0:
line += ', '
line += tds[i].get_text().strip()
print(line)
print('\n')
|
Fix a unicode bug when printing EC2 instance types on Windows machines
|
Fix a unicode bug when printing EC2 instance types on Windows machines
|
Python
|
mit
|
thinhpham/aws-tools
|
#!/usr/bin/env python
from bs4 import BeautifulSoup
import urllib
site_content = urllib.urlopen('https://aws.amazon.com/ec2/instance-types/').read()
soup = BeautifulSoup(site_content, 'lxml')
aws_tables = soup.find_all("div", {"class": "aws-table"});
for table_div in aws_tables:
trs = table_div.find('table').tbody.find_all('tr')
for tr in trs:
tds = tr.find_all('td')
rng = len(tds)
line = ''
if rng > 0:
for i in range(0, rng):
if i > 0:
line += ', '
line += tds[i].get_text().strip()
print(line)
print('\n')Fix a unicode bug when printing EC2 instance types on Windows machines
|
#!/usr/bin/env python
from bs4 import BeautifulSoup
import urllib
import sys
import codecs
# Change encoding to fix a bug on windows
sys.stdout = codecs.getwriter("iso-8859-1")(sys.stdout, 'xmlcharrefreplace')
# Download a copy of the EC2 Instance Types from Amazon and scrape the content
site_content = urllib.urlopen('https://aws.amazon.com/ec2/instance-types/').read()
soup = BeautifulSoup(site_content, 'lxml')
aws_tables = soup.find_all("div", {"class": "aws-table"});
for table_div in aws_tables:
trs = table_div.find('table').tbody.find_all('tr')
for tr in trs:
tds = tr.find_all('td')
rng = len(tds)
line = ''
if rng > 0:
for i in range(0, rng):
if i > 0:
line += ', '
line += tds[i].get_text().strip()
print(line)
print('\n')
|
<commit_before>#!/usr/bin/env python
from bs4 import BeautifulSoup
import urllib
site_content = urllib.urlopen('https://aws.amazon.com/ec2/instance-types/').read()
soup = BeautifulSoup(site_content, 'lxml')
aws_tables = soup.find_all("div", {"class": "aws-table"});
for table_div in aws_tables:
trs = table_div.find('table').tbody.find_all('tr')
for tr in trs:
tds = tr.find_all('td')
rng = len(tds)
line = ''
if rng > 0:
for i in range(0, rng):
if i > 0:
line += ', '
line += tds[i].get_text().strip()
print(line)
print('\n')<commit_msg>Fix a unicode bug when printing EC2 instance types on Windows machines<commit_after>
|
#!/usr/bin/env python
from bs4 import BeautifulSoup
import urllib
import sys
import codecs
# Change encoding to fix a bug on windows
sys.stdout = codecs.getwriter("iso-8859-1")(sys.stdout, 'xmlcharrefreplace')
# Download a copy of the EC2 Instance Types from Amazon and scrape the content
site_content = urllib.urlopen('https://aws.amazon.com/ec2/instance-types/').read()
soup = BeautifulSoup(site_content, 'lxml')
aws_tables = soup.find_all("div", {"class": "aws-table"});
for table_div in aws_tables:
trs = table_div.find('table').tbody.find_all('tr')
for tr in trs:
tds = tr.find_all('td')
rng = len(tds)
line = ''
if rng > 0:
for i in range(0, rng):
if i > 0:
line += ', '
line += tds[i].get_text().strip()
print(line)
print('\n')
|
#!/usr/bin/env python
from bs4 import BeautifulSoup
import urllib
site_content = urllib.urlopen('https://aws.amazon.com/ec2/instance-types/').read()
soup = BeautifulSoup(site_content, 'lxml')
aws_tables = soup.find_all("div", {"class": "aws-table"});
for table_div in aws_tables:
trs = table_div.find('table').tbody.find_all('tr')
for tr in trs:
tds = tr.find_all('td')
rng = len(tds)
line = ''
if rng > 0:
for i in range(0, rng):
if i > 0:
line += ', '
line += tds[i].get_text().strip()
print(line)
print('\n')Fix a unicode bug when printing EC2 instance types on Windows machines#!/usr/bin/env python
from bs4 import BeautifulSoup
import urllib
import sys
import codecs
# Change encoding to fix a bug on windows
sys.stdout = codecs.getwriter("iso-8859-1")(sys.stdout, 'xmlcharrefreplace')
# Download a copy of the EC2 Instance Types from Amazon and scrape the content
site_content = urllib.urlopen('https://aws.amazon.com/ec2/instance-types/').read()
soup = BeautifulSoup(site_content, 'lxml')
aws_tables = soup.find_all("div", {"class": "aws-table"});
for table_div in aws_tables:
trs = table_div.find('table').tbody.find_all('tr')
for tr in trs:
tds = tr.find_all('td')
rng = len(tds)
line = ''
if rng > 0:
for i in range(0, rng):
if i > 0:
line += ', '
line += tds[i].get_text().strip()
print(line)
print('\n')
|
<commit_before>#!/usr/bin/env python
from bs4 import BeautifulSoup
import urllib
site_content = urllib.urlopen('https://aws.amazon.com/ec2/instance-types/').read()
soup = BeautifulSoup(site_content, 'lxml')
aws_tables = soup.find_all("div", {"class": "aws-table"});
for table_div in aws_tables:
trs = table_div.find('table').tbody.find_all('tr')
for tr in trs:
tds = tr.find_all('td')
rng = len(tds)
line = ''
if rng > 0:
for i in range(0, rng):
if i > 0:
line += ', '
line += tds[i].get_text().strip()
print(line)
print('\n')<commit_msg>Fix a unicode bug when printing EC2 instance types on Windows machines<commit_after>#!/usr/bin/env python
from bs4 import BeautifulSoup
import urllib
import sys
import codecs
# Change encoding to fix a bug on windows
sys.stdout = codecs.getwriter("iso-8859-1")(sys.stdout, 'xmlcharrefreplace')
# Download a copy of the EC2 Instance Types from Amazon and scrape the content
site_content = urllib.urlopen('https://aws.amazon.com/ec2/instance-types/').read()
soup = BeautifulSoup(site_content, 'lxml')
aws_tables = soup.find_all("div", {"class": "aws-table"});
for table_div in aws_tables:
trs = table_div.find('table').tbody.find_all('tr')
for tr in trs:
tds = tr.find_all('td')
rng = len(tds)
line = ''
if rng > 0:
for i in range(0, rng):
if i > 0:
line += ', '
line += tds[i].get_text().strip()
print(line)
print('\n')
|
3ca4a7334a3a759762d309bcff94ddde62d5a48b
|
accounts/management/__init__.py
|
accounts/management/__init__.py
|
from django.db.models.signals import post_syncdb
from accounts import models, names
def ensure_core_accounts_exists(sender, **kwargs):
# We only create core accounts the first time syncdb is run
if models.Account.objects.all().count() > 0:
return
# Create asset accounts
assets = models.AccountType.add_root(name='Assets')
assets.accounts.create(name=names.REDEMPTIONS)
assets.accounts.create(name=names.LAPSED)
# Create liability accounts
liabilities = models.AccountType.add_root(name='Liabilities')
liabilities.accounts.create(name=names.MERCHANT_SOURCE,
credit_limit=None)
liabilities.add_child(name="Giftcards")
liabilities.add_child(name="User accounts")
post_syncdb.connect(ensure_core_accounts_exists, sender=models)
|
from accounts import models, names
def ensure_core_accounts_exists(sender, **kwargs):
# We only create core accounts the first time syncdb is run
if models.Account.objects.all().count() > 0:
return
# Create asset accounts
assets = models.AccountType.add_root(name='Assets')
assets.accounts.create(name=names.REDEMPTIONS)
assets.accounts.create(name=names.LAPSED)
# Create liability accounts
liabilities = models.AccountType.add_root(name='Liabilities')
liabilities.accounts.create(name=names.MERCHANT_SOURCE,
credit_limit=None)
liabilities.add_child(name="Giftcards")
liabilities.add_child(name="User accounts")
#post_syncdb.connect(ensure_core_accounts_exists, sender=models)
|
Remove syncdb signal - will move to migration shortly
|
Remove syncdb signal - will move to migration shortly
|
Python
|
bsd-3-clause
|
Jannes123/django-oscar-accounts,machtfit/django-oscar-accounts,michaelkuty/django-oscar-accounts,Mariana-Tek/django-oscar-accounts,amsys/django-account-balances,michaelkuty/django-oscar-accounts,Jannes123/django-oscar-accounts,carver/django-account-balances,Mariana-Tek/django-oscar-accounts,amsys/django-account-balances,machtfit/django-oscar-accounts,django-oscar/django-oscar-accounts,django-oscar/django-oscar-accounts
|
from django.db.models.signals import post_syncdb
from accounts import models, names
def ensure_core_accounts_exists(sender, **kwargs):
# We only create core accounts the first time syncdb is run
if models.Account.objects.all().count() > 0:
return
# Create asset accounts
assets = models.AccountType.add_root(name='Assets')
assets.accounts.create(name=names.REDEMPTIONS)
assets.accounts.create(name=names.LAPSED)
# Create liability accounts
liabilities = models.AccountType.add_root(name='Liabilities')
liabilities.accounts.create(name=names.MERCHANT_SOURCE,
credit_limit=None)
liabilities.add_child(name="Giftcards")
liabilities.add_child(name="User accounts")
post_syncdb.connect(ensure_core_accounts_exists, sender=models)
Remove syncdb signal - will move to migration shortly
|
from accounts import models, names
def ensure_core_accounts_exists(sender, **kwargs):
# We only create core accounts the first time syncdb is run
if models.Account.objects.all().count() > 0:
return
# Create asset accounts
assets = models.AccountType.add_root(name='Assets')
assets.accounts.create(name=names.REDEMPTIONS)
assets.accounts.create(name=names.LAPSED)
# Create liability accounts
liabilities = models.AccountType.add_root(name='Liabilities')
liabilities.accounts.create(name=names.MERCHANT_SOURCE,
credit_limit=None)
liabilities.add_child(name="Giftcards")
liabilities.add_child(name="User accounts")
#post_syncdb.connect(ensure_core_accounts_exists, sender=models)
|
<commit_before>from django.db.models.signals import post_syncdb
from accounts import models, names
def ensure_core_accounts_exists(sender, **kwargs):
# We only create core accounts the first time syncdb is run
if models.Account.objects.all().count() > 0:
return
# Create asset accounts
assets = models.AccountType.add_root(name='Assets')
assets.accounts.create(name=names.REDEMPTIONS)
assets.accounts.create(name=names.LAPSED)
# Create liability accounts
liabilities = models.AccountType.add_root(name='Liabilities')
liabilities.accounts.create(name=names.MERCHANT_SOURCE,
credit_limit=None)
liabilities.add_child(name="Giftcards")
liabilities.add_child(name="User accounts")
post_syncdb.connect(ensure_core_accounts_exists, sender=models)
<commit_msg>Remove syncdb signal - will move to migration shortly<commit_after>
|
from accounts import models, names
def ensure_core_accounts_exists(sender, **kwargs):
# We only create core accounts the first time syncdb is run
if models.Account.objects.all().count() > 0:
return
# Create asset accounts
assets = models.AccountType.add_root(name='Assets')
assets.accounts.create(name=names.REDEMPTIONS)
assets.accounts.create(name=names.LAPSED)
# Create liability accounts
liabilities = models.AccountType.add_root(name='Liabilities')
liabilities.accounts.create(name=names.MERCHANT_SOURCE,
credit_limit=None)
liabilities.add_child(name="Giftcards")
liabilities.add_child(name="User accounts")
#post_syncdb.connect(ensure_core_accounts_exists, sender=models)
|
from django.db.models.signals import post_syncdb
from accounts import models, names
def ensure_core_accounts_exists(sender, **kwargs):
# We only create core accounts the first time syncdb is run
if models.Account.objects.all().count() > 0:
return
# Create asset accounts
assets = models.AccountType.add_root(name='Assets')
assets.accounts.create(name=names.REDEMPTIONS)
assets.accounts.create(name=names.LAPSED)
# Create liability accounts
liabilities = models.AccountType.add_root(name='Liabilities')
liabilities.accounts.create(name=names.MERCHANT_SOURCE,
credit_limit=None)
liabilities.add_child(name="Giftcards")
liabilities.add_child(name="User accounts")
post_syncdb.connect(ensure_core_accounts_exists, sender=models)
Remove syncdb signal - will move to migration shortlyfrom accounts import models, names
def ensure_core_accounts_exists(sender, **kwargs):
# We only create core accounts the first time syncdb is run
if models.Account.objects.all().count() > 0:
return
# Create asset accounts
assets = models.AccountType.add_root(name='Assets')
assets.accounts.create(name=names.REDEMPTIONS)
assets.accounts.create(name=names.LAPSED)
# Create liability accounts
liabilities = models.AccountType.add_root(name='Liabilities')
liabilities.accounts.create(name=names.MERCHANT_SOURCE,
credit_limit=None)
liabilities.add_child(name="Giftcards")
liabilities.add_child(name="User accounts")
#post_syncdb.connect(ensure_core_accounts_exists, sender=models)
|
<commit_before>from django.db.models.signals import post_syncdb
from accounts import models, names
def ensure_core_accounts_exists(sender, **kwargs):
# We only create core accounts the first time syncdb is run
if models.Account.objects.all().count() > 0:
return
# Create asset accounts
assets = models.AccountType.add_root(name='Assets')
assets.accounts.create(name=names.REDEMPTIONS)
assets.accounts.create(name=names.LAPSED)
# Create liability accounts
liabilities = models.AccountType.add_root(name='Liabilities')
liabilities.accounts.create(name=names.MERCHANT_SOURCE,
credit_limit=None)
liabilities.add_child(name="Giftcards")
liabilities.add_child(name="User accounts")
post_syncdb.connect(ensure_core_accounts_exists, sender=models)
<commit_msg>Remove syncdb signal - will move to migration shortly<commit_after>from accounts import models, names
def ensure_core_accounts_exists(sender, **kwargs):
# We only create core accounts the first time syncdb is run
if models.Account.objects.all().count() > 0:
return
# Create asset accounts
assets = models.AccountType.add_root(name='Assets')
assets.accounts.create(name=names.REDEMPTIONS)
assets.accounts.create(name=names.LAPSED)
# Create liability accounts
liabilities = models.AccountType.add_root(name='Liabilities')
liabilities.accounts.create(name=names.MERCHANT_SOURCE,
credit_limit=None)
liabilities.add_child(name="Giftcards")
liabilities.add_child(name="User accounts")
#post_syncdb.connect(ensure_core_accounts_exists, sender=models)
|
a84c02b4369bf698c82be22b6231fe412ad67c63
|
Cauldron/ext/click/__init__.py
|
Cauldron/ext/click/__init__.py
|
# -*- coding: utf-8 -*-
try:
import click
except ImportError:
raise ImportError("Cauldron.ext.click requires the click package.")
from ...api import use
__all__ = ['backend', 'service']
def select_backend(ctx, param, value):
"""Callback to set the Cauldron backend."""
if not value or ctx.resilient_parsing:
return
use(str(value))
def backend(default=None):
"""Click options to set up a Cauldron backend."""
option = click.option("-k", "--backend", expose_value=False, is_eager=True,
callback=select_backend, help="Set the Cauldron backend.",
default=default)
def decorate(func):
return option(func)
return decorate
backend_option = backend
def construct_service(ctx, param, value):
"""Construct a service."""
if not value:
return
from Cauldron import ktl
return ktl.Service(str(value))
def service(default=None, backend=True):
"""Add a service argument which returns a ktl.Service class."""
option = click.option("-s", "--service", callback=construct_service,
help="KTL Service name to use.", default=default)
backend_default = None
if backend and isinstance(backend, str):
backend_default = backend
def decorate(func):
if backend:
func = backend_option(default=backend_default)(func)
return option(func)
|
# -*- coding: utf-8 -*-
try:
import click
except ImportError:
raise ImportError("Cauldron.ext.click requires the click package.")
from ...api import use
__all__ = ['backend', 'service']
def select_backend(ctx, param, value):
"""Callback to set the Cauldron backend."""
if not value or ctx.resilient_parsing:
return
use(str(value))
def backend(default=None):
"""Click options to set up a Cauldron backend."""
option = click.option("-k", "--backend", expose_value=False, is_eager=True,
callback=select_backend, help="Set the Cauldron backend.",
default=default)
def decorate(func):
return option(func)
return decorate
backend_option = backend
def construct_service(ctx, param, value):
"""Construct a service."""
if not value:
return
from Cauldron import ktl
return ktl.Service(str(value))
def service(default=None, backend=True):
"""Add a service argument which returns a ktl.Service class."""
option = click.option("-s", "--service", callback=construct_service,
help="KTL Service name to use.", default=default)
backend_default = None
if backend and isinstance(backend, str):
backend_default = backend
def decorate(func):
if backend:
func = backend_option(default=backend_default)(func)
return option(func)
return decorate
|
Fix a bug in Cauldron click extension
|
Fix a bug in Cauldron click extension
|
Python
|
bsd-3-clause
|
alexrudy/Cauldron
|
# -*- coding: utf-8 -*-
try:
import click
except ImportError:
raise ImportError("Cauldron.ext.click requires the click package.")
from ...api import use
__all__ = ['backend', 'service']
def select_backend(ctx, param, value):
"""Callback to set the Cauldron backend."""
if not value or ctx.resilient_parsing:
return
use(str(value))
def backend(default=None):
"""Click options to set up a Cauldron backend."""
option = click.option("-k", "--backend", expose_value=False, is_eager=True,
callback=select_backend, help="Set the Cauldron backend.",
default=default)
def decorate(func):
return option(func)
return decorate
backend_option = backend
def construct_service(ctx, param, value):
"""Construct a service."""
if not value:
return
from Cauldron import ktl
return ktl.Service(str(value))
def service(default=None, backend=True):
"""Add a service argument which returns a ktl.Service class."""
option = click.option("-s", "--service", callback=construct_service,
help="KTL Service name to use.", default=default)
backend_default = None
if backend and isinstance(backend, str):
backend_default = backend
def decorate(func):
if backend:
func = backend_option(default=backend_default)(func)
return option(func)
Fix a bug in Cauldron click extension
|
# -*- coding: utf-8 -*-
try:
import click
except ImportError:
raise ImportError("Cauldron.ext.click requires the click package.")
from ...api import use
__all__ = ['backend', 'service']
def select_backend(ctx, param, value):
"""Callback to set the Cauldron backend."""
if not value or ctx.resilient_parsing:
return
use(str(value))
def backend(default=None):
"""Click options to set up a Cauldron backend."""
option = click.option("-k", "--backend", expose_value=False, is_eager=True,
callback=select_backend, help="Set the Cauldron backend.",
default=default)
def decorate(func):
return option(func)
return decorate
backend_option = backend
def construct_service(ctx, param, value):
"""Construct a service."""
if not value:
return
from Cauldron import ktl
return ktl.Service(str(value))
def service(default=None, backend=True):
"""Add a service argument which returns a ktl.Service class."""
option = click.option("-s", "--service", callback=construct_service,
help="KTL Service name to use.", default=default)
backend_default = None
if backend and isinstance(backend, str):
backend_default = backend
def decorate(func):
if backend:
func = backend_option(default=backend_default)(func)
return option(func)
return decorate
|
<commit_before># -*- coding: utf-8 -*-
try:
import click
except ImportError:
raise ImportError("Cauldron.ext.click requires the click package.")
from ...api import use
__all__ = ['backend', 'service']
def select_backend(ctx, param, value):
"""Callback to set the Cauldron backend."""
if not value or ctx.resilient_parsing:
return
use(str(value))
def backend(default=None):
"""Click options to set up a Cauldron backend."""
option = click.option("-k", "--backend", expose_value=False, is_eager=True,
callback=select_backend, help="Set the Cauldron backend.",
default=default)
def decorate(func):
return option(func)
return decorate
backend_option = backend
def construct_service(ctx, param, value):
"""Construct a service."""
if not value:
return
from Cauldron import ktl
return ktl.Service(str(value))
def service(default=None, backend=True):
"""Add a service argument which returns a ktl.Service class."""
option = click.option("-s", "--service", callback=construct_service,
help="KTL Service name to use.", default=default)
backend_default = None
if backend and isinstance(backend, str):
backend_default = backend
def decorate(func):
if backend:
func = backend_option(default=backend_default)(func)
return option(func)
<commit_msg>Fix a bug in Cauldron click extension<commit_after>
|
# -*- coding: utf-8 -*-
try:
import click
except ImportError:
raise ImportError("Cauldron.ext.click requires the click package.")
from ...api import use
__all__ = ['backend', 'service']
def select_backend(ctx, param, value):
"""Callback to set the Cauldron backend."""
if not value or ctx.resilient_parsing:
return
use(str(value))
def backend(default=None):
"""Click options to set up a Cauldron backend."""
option = click.option("-k", "--backend", expose_value=False, is_eager=True,
callback=select_backend, help="Set the Cauldron backend.",
default=default)
def decorate(func):
return option(func)
return decorate
backend_option = backend
def construct_service(ctx, param, value):
"""Construct a service."""
if not value:
return
from Cauldron import ktl
return ktl.Service(str(value))
def service(default=None, backend=True):
"""Add a service argument which returns a ktl.Service class."""
option = click.option("-s", "--service", callback=construct_service,
help="KTL Service name to use.", default=default)
backend_default = None
if backend and isinstance(backend, str):
backend_default = backend
def decorate(func):
if backend:
func = backend_option(default=backend_default)(func)
return option(func)
return decorate
|
# -*- coding: utf-8 -*-
try:
import click
except ImportError:
raise ImportError("Cauldron.ext.click requires the click package.")
from ...api import use
__all__ = ['backend', 'service']
def select_backend(ctx, param, value):
"""Callback to set the Cauldron backend."""
if not value or ctx.resilient_parsing:
return
use(str(value))
def backend(default=None):
"""Click options to set up a Cauldron backend."""
option = click.option("-k", "--backend", expose_value=False, is_eager=True,
callback=select_backend, help="Set the Cauldron backend.",
default=default)
def decorate(func):
return option(func)
return decorate
backend_option = backend
def construct_service(ctx, param, value):
"""Construct a service."""
if not value:
return
from Cauldron import ktl
return ktl.Service(str(value))
def service(default=None, backend=True):
"""Add a service argument which returns a ktl.Service class."""
option = click.option("-s", "--service", callback=construct_service,
help="KTL Service name to use.", default=default)
backend_default = None
if backend and isinstance(backend, str):
backend_default = backend
def decorate(func):
if backend:
func = backend_option(default=backend_default)(func)
return option(func)
Fix a bug in Cauldron click extension# -*- coding: utf-8 -*-
try:
import click
except ImportError:
raise ImportError("Cauldron.ext.click requires the click package.")
from ...api import use
__all__ = ['backend', 'service']
def select_backend(ctx, param, value):
"""Callback to set the Cauldron backend."""
if not value or ctx.resilient_parsing:
return
use(str(value))
def backend(default=None):
"""Click options to set up a Cauldron backend."""
option = click.option("-k", "--backend", expose_value=False, is_eager=True,
callback=select_backend, help="Set the Cauldron backend.",
default=default)
def decorate(func):
return option(func)
return decorate
backend_option = backend
def construct_service(ctx, param, value):
"""Construct a service."""
if not value:
return
from Cauldron import ktl
return ktl.Service(str(value))
def service(default=None, backend=True):
"""Add a service argument which returns a ktl.Service class."""
option = click.option("-s", "--service", callback=construct_service,
help="KTL Service name to use.", default=default)
backend_default = None
if backend and isinstance(backend, str):
backend_default = backend
def decorate(func):
if backend:
func = backend_option(default=backend_default)(func)
return option(func)
return decorate
|
<commit_before># -*- coding: utf-8 -*-
try:
import click
except ImportError:
raise ImportError("Cauldron.ext.click requires the click package.")
from ...api import use
__all__ = ['backend', 'service']
def select_backend(ctx, param, value):
"""Callback to set the Cauldron backend."""
if not value or ctx.resilient_parsing:
return
use(str(value))
def backend(default=None):
"""Click options to set up a Cauldron backend."""
option = click.option("-k", "--backend", expose_value=False, is_eager=True,
callback=select_backend, help="Set the Cauldron backend.",
default=default)
def decorate(func):
return option(func)
return decorate
backend_option = backend
def construct_service(ctx, param, value):
"""Construct a service."""
if not value:
return
from Cauldron import ktl
return ktl.Service(str(value))
def service(default=None, backend=True):
"""Add a service argument which returns a ktl.Service class."""
option = click.option("-s", "--service", callback=construct_service,
help="KTL Service name to use.", default=default)
backend_default = None
if backend and isinstance(backend, str):
backend_default = backend
def decorate(func):
if backend:
func = backend_option(default=backend_default)(func)
return option(func)
<commit_msg>Fix a bug in Cauldron click extension<commit_after># -*- coding: utf-8 -*-
try:
import click
except ImportError:
raise ImportError("Cauldron.ext.click requires the click package.")
from ...api import use
__all__ = ['backend', 'service']
def select_backend(ctx, param, value):
"""Callback to set the Cauldron backend."""
if not value or ctx.resilient_parsing:
return
use(str(value))
def backend(default=None):
"""Click options to set up a Cauldron backend."""
option = click.option("-k", "--backend", expose_value=False, is_eager=True,
callback=select_backend, help="Set the Cauldron backend.",
default=default)
def decorate(func):
return option(func)
return decorate
backend_option = backend
def construct_service(ctx, param, value):
"""Construct a service."""
if not value:
return
from Cauldron import ktl
return ktl.Service(str(value))
def service(default=None, backend=True):
"""Add a service argument which returns a ktl.Service class."""
option = click.option("-s", "--service", callback=construct_service,
help="KTL Service name to use.", default=default)
backend_default = None
if backend and isinstance(backend, str):
backend_default = backend
def decorate(func):
if backend:
func = backend_option(default=backend_default)(func)
return option(func)
return decorate
|
5547e59360126baa20e1684a22e7f88fdacb530a
|
s2v2.py
|
s2v2.py
|
from s2v1 import *
def number_of_records(data_sample):
return len(data_sample)
number_of_ties = number_of_records(data_from_csv) - 1 # minus header row
# print(number_of_ties, "ties in our data sample")
def number_of_records2(data_sample):
return data_sample.size
number_of_ties_my_csv = number_of_records2(my_csv)
# print(number_of_ties_my_csv, "ties in our data sample")
|
from s2v1 import *
def number_of_records(data_sample):
return len(data_sample)
def number_of_records_ignore_header(data_sample, header=True):
if header:
return len(data_sample) - 1
else:
return len(data_sample)
number_of_ties = number_of_records(data_from_csv) - 1 # minus header row
# print(number_of_ties, "ties in our data sample")
def number_of_records2(data_sample):
return data_sample.size
number_of_ties_my_csv = number_of_records2(my_csv)
# print(number_of_ties_my_csv, "ties in our data sample")
|
Create new function for number of records and do a header check
|
Create new function for number of records and do a header check
|
Python
|
mit
|
alexmilesyounger/ds_basics
|
from s2v1 import *
def number_of_records(data_sample):
return len(data_sample)
number_of_ties = number_of_records(data_from_csv) - 1 # minus header row
# print(number_of_ties, "ties in our data sample")
def number_of_records2(data_sample):
return data_sample.size
number_of_ties_my_csv = number_of_records2(my_csv)
# print(number_of_ties_my_csv, "ties in our data sample")Create new function for number of records and do a header check
|
from s2v1 import *
def number_of_records(data_sample):
return len(data_sample)
def number_of_records_ignore_header(data_sample, header=True):
if header:
return len(data_sample) - 1
else:
return len(data_sample)
number_of_ties = number_of_records(data_from_csv) - 1 # minus header row
# print(number_of_ties, "ties in our data sample")
def number_of_records2(data_sample):
return data_sample.size
number_of_ties_my_csv = number_of_records2(my_csv)
# print(number_of_ties_my_csv, "ties in our data sample")
|
<commit_before>from s2v1 import *
def number_of_records(data_sample):
return len(data_sample)
number_of_ties = number_of_records(data_from_csv) - 1 # minus header row
# print(number_of_ties, "ties in our data sample")
def number_of_records2(data_sample):
return data_sample.size
number_of_ties_my_csv = number_of_records2(my_csv)
# print(number_of_ties_my_csv, "ties in our data sample")<commit_msg>Create new function for number of records and do a header check<commit_after>
|
from s2v1 import *
def number_of_records(data_sample):
return len(data_sample)
def number_of_records_ignore_header(data_sample, header=True):
if header:
return len(data_sample) - 1
else:
return len(data_sample)
number_of_ties = number_of_records(data_from_csv) - 1 # minus header row
# print(number_of_ties, "ties in our data sample")
def number_of_records2(data_sample):
return data_sample.size
number_of_ties_my_csv = number_of_records2(my_csv)
# print(number_of_ties_my_csv, "ties in our data sample")
|
from s2v1 import *
def number_of_records(data_sample):
return len(data_sample)
number_of_ties = number_of_records(data_from_csv) - 1 # minus header row
# print(number_of_ties, "ties in our data sample")
def number_of_records2(data_sample):
return data_sample.size
number_of_ties_my_csv = number_of_records2(my_csv)
# print(number_of_ties_my_csv, "ties in our data sample")Create new function for number of records and do a header checkfrom s2v1 import *
def number_of_records(data_sample):
return len(data_sample)
def number_of_records_ignore_header(data_sample, header=True):
if header:
return len(data_sample) - 1
else:
return len(data_sample)
number_of_ties = number_of_records(data_from_csv) - 1 # minus header row
# print(number_of_ties, "ties in our data sample")
def number_of_records2(data_sample):
return data_sample.size
number_of_ties_my_csv = number_of_records2(my_csv)
# print(number_of_ties_my_csv, "ties in our data sample")
|
<commit_before>from s2v1 import *
def number_of_records(data_sample):
return len(data_sample)
number_of_ties = number_of_records(data_from_csv) - 1 # minus header row
# print(number_of_ties, "ties in our data sample")
def number_of_records2(data_sample):
return data_sample.size
number_of_ties_my_csv = number_of_records2(my_csv)
# print(number_of_ties_my_csv, "ties in our data sample")<commit_msg>Create new function for number of records and do a header check<commit_after>from s2v1 import *
def number_of_records(data_sample):
return len(data_sample)
def number_of_records_ignore_header(data_sample, header=True):
if header:
return len(data_sample) - 1
else:
return len(data_sample)
number_of_ties = number_of_records(data_from_csv) - 1 # minus header row
# print(number_of_ties, "ties in our data sample")
def number_of_records2(data_sample):
return data_sample.size
number_of_ties_my_csv = number_of_records2(my_csv)
# print(number_of_ties_my_csv, "ties in our data sample")
|
2b88f8f458781bd88f559f1a5a966fd5050414a0
|
tests/merchandise/music/test_models.py
|
tests/merchandise/music/test_models.py
|
import pytest
from components.merchandise.music.models import Album, Single
from components.merchandise.music.factories import (AlbumFactory,
BaseFactory, SingleFactory)
@pytest.mark.django_db
class TestAlbums(object):
def test_album_factory(self):
album = AlbumFactory()
assert isinstance(album, Album)
assert 'album' in album.romanized_name
assert album.identifier == 'album'
@pytest.mark.django_db
class TestSingles(object):
def test_single_factory(self):
single = SingleFactory()
assert isinstance(single, Single)
assert 'single' in single.romanized_name
assert single.identifier == 'single'
|
import pytest
from components.merchandise.music.models import Album, Single
from components.merchandise.music.factories import (AlbumFactory,
BaseFactory, SingleFactory)
@pytest.mark.django_db
def test_album_factory():
factory = AlbumFactory()
assert isinstance(factory, Album)
assert 'album' in factory.romanized_name
assert factory.identifier == 'album'
@pytest.mark.django_db
def test_single_factory():
factory = SingleFactory()
assert isinstance(factory, Single)
assert 'single' in factory.romanized_name
assert factory.identifier == 'single'
|
Remove the class surrounding the music tests. Staying strictly functional.
|
Remove the class surrounding the music tests. Staying strictly functional.
|
Python
|
apache-2.0
|
hello-base/web,hello-base/web,hello-base/web,hello-base/web
|
import pytest
from components.merchandise.music.models import Album, Single
from components.merchandise.music.factories import (AlbumFactory,
BaseFactory, SingleFactory)
@pytest.mark.django_db
class TestAlbums(object):
def test_album_factory(self):
album = AlbumFactory()
assert isinstance(album, Album)
assert 'album' in album.romanized_name
assert album.identifier == 'album'
@pytest.mark.django_db
class TestSingles(object):
def test_single_factory(self):
single = SingleFactory()
assert isinstance(single, Single)
assert 'single' in single.romanized_name
assert single.identifier == 'single'
Remove the class surrounding the music tests. Staying strictly functional.
|
import pytest
from components.merchandise.music.models import Album, Single
from components.merchandise.music.factories import (AlbumFactory,
BaseFactory, SingleFactory)
@pytest.mark.django_db
def test_album_factory():
factory = AlbumFactory()
assert isinstance(factory, Album)
assert 'album' in factory.romanized_name
assert factory.identifier == 'album'
@pytest.mark.django_db
def test_single_factory():
factory = SingleFactory()
assert isinstance(factory, Single)
assert 'single' in factory.romanized_name
assert factory.identifier == 'single'
|
<commit_before>import pytest
from components.merchandise.music.models import Album, Single
from components.merchandise.music.factories import (AlbumFactory,
BaseFactory, SingleFactory)
@pytest.mark.django_db
class TestAlbums(object):
def test_album_factory(self):
album = AlbumFactory()
assert isinstance(album, Album)
assert 'album' in album.romanized_name
assert album.identifier == 'album'
@pytest.mark.django_db
class TestSingles(object):
def test_single_factory(self):
single = SingleFactory()
assert isinstance(single, Single)
assert 'single' in single.romanized_name
assert single.identifier == 'single'
<commit_msg>Remove the class surrounding the music tests. Staying strictly functional.<commit_after>
|
import pytest
from components.merchandise.music.models import Album, Single
from components.merchandise.music.factories import (AlbumFactory,
BaseFactory, SingleFactory)
@pytest.mark.django_db
def test_album_factory():
factory = AlbumFactory()
assert isinstance(factory, Album)
assert 'album' in factory.romanized_name
assert factory.identifier == 'album'
@pytest.mark.django_db
def test_single_factory():
factory = SingleFactory()
assert isinstance(factory, Single)
assert 'single' in factory.romanized_name
assert factory.identifier == 'single'
|
import pytest
from components.merchandise.music.models import Album, Single
from components.merchandise.music.factories import (AlbumFactory,
BaseFactory, SingleFactory)
@pytest.mark.django_db
class TestAlbums(object):
def test_album_factory(self):
album = AlbumFactory()
assert isinstance(album, Album)
assert 'album' in album.romanized_name
assert album.identifier == 'album'
@pytest.mark.django_db
class TestSingles(object):
def test_single_factory(self):
single = SingleFactory()
assert isinstance(single, Single)
assert 'single' in single.romanized_name
assert single.identifier == 'single'
Remove the class surrounding the music tests. Staying strictly functional.import pytest
from components.merchandise.music.models import Album, Single
from components.merchandise.music.factories import (AlbumFactory,
BaseFactory, SingleFactory)
@pytest.mark.django_db
def test_album_factory():
factory = AlbumFactory()
assert isinstance(factory, Album)
assert 'album' in factory.romanized_name
assert factory.identifier == 'album'
@pytest.mark.django_db
def test_single_factory():
factory = SingleFactory()
assert isinstance(factory, Single)
assert 'single' in factory.romanized_name
assert factory.identifier == 'single'
|
<commit_before>import pytest
from components.merchandise.music.models import Album, Single
from components.merchandise.music.factories import (AlbumFactory,
BaseFactory, SingleFactory)
@pytest.mark.django_db
class TestAlbums(object):
def test_album_factory(self):
album = AlbumFactory()
assert isinstance(album, Album)
assert 'album' in album.romanized_name
assert album.identifier == 'album'
@pytest.mark.django_db
class TestSingles(object):
def test_single_factory(self):
single = SingleFactory()
assert isinstance(single, Single)
assert 'single' in single.romanized_name
assert single.identifier == 'single'
<commit_msg>Remove the class surrounding the music tests. Staying strictly functional.<commit_after>import pytest
from components.merchandise.music.models import Album, Single
from components.merchandise.music.factories import (AlbumFactory,
BaseFactory, SingleFactory)
@pytest.mark.django_db
def test_album_factory():
factory = AlbumFactory()
assert isinstance(factory, Album)
assert 'album' in factory.romanized_name
assert factory.identifier == 'album'
@pytest.mark.django_db
def test_single_factory():
factory = SingleFactory()
assert isinstance(factory, Single)
assert 'single' in factory.romanized_name
assert factory.identifier == 'single'
|
b45193582f96853e0cb17a962a7e83aada529a10
|
DataLogger/SQLiteLogger.py
|
DataLogger/SQLiteLogger.py
|
import sqlite3
import time
class SQLiteLogger:
def __init__(self, filename="test.db"):
self.filename = filename
self.connection = None
def __enter__(self):
try:
with open(self.filename):
self.connection = sqlite3.connect(self.filename)
except IOError:
self.connection = sqlite3.connect(self.filename)
cursor = self.connection.cursor()
cursor.execute('''CREATE TABLE readings
(date real, device text, property text, value real)''')
self.connection.commit()
return self
def __exit__(self, type, value, traceback):
self.connection.close()
self.connection = None
def log(self, device, property, value):
now = time.time()
values = (now, device, property, value)
cursor = self.connection.cursor()
cursor.execute("INSERT INTO readings VALUES(?,?,?,?)", values)
self.connection.commit()
|
import sqlite3
import time
class SQLiteLogger:
def __init__(self, filename="test.db"):
self.filename = filename
self.connection = None
def __enter__(self):
try:
with open(self.filename):
self.connection = sqlite3.connect(self.filename)
except IOError:
self.connection = sqlite3.connect(self.filename)
cursor = self.connection.cursor()
cursor.execute('''CREATE TABLE readings
(date real, device text, property text, value real)''')
self.connection.commit()
return self
def __exit__(self, type, value, traceback):
self.connection.close()
self.connection = None
def log(self, device, property, value, t=None):
if t is None:
t = time.time()
values = (t, device, property, value)
cursor = self.connection.cursor()
cursor.execute("INSERT INTO readings VALUES(?,?,?,?)", values)
self.connection.commit()
|
Allow log time to be passed into logger
|
Allow log time to be passed into logger
|
Python
|
mit
|
thelonious/g2x,gizmo-cda/g2x,thelonious/g2x,gizmo-cda/g2x,gizmo-cda/g2x,gizmo-cda/g2x
|
import sqlite3
import time
class SQLiteLogger:
def __init__(self, filename="test.db"):
self.filename = filename
self.connection = None
def __enter__(self):
try:
with open(self.filename):
self.connection = sqlite3.connect(self.filename)
except IOError:
self.connection = sqlite3.connect(self.filename)
cursor = self.connection.cursor()
cursor.execute('''CREATE TABLE readings
(date real, device text, property text, value real)''')
self.connection.commit()
return self
def __exit__(self, type, value, traceback):
self.connection.close()
self.connection = None
def log(self, device, property, value):
now = time.time()
values = (now, device, property, value)
cursor = self.connection.cursor()
cursor.execute("INSERT INTO readings VALUES(?,?,?,?)", values)
self.connection.commit()
Allow log time to be passed into logger
|
import sqlite3
import time
class SQLiteLogger:
def __init__(self, filename="test.db"):
self.filename = filename
self.connection = None
def __enter__(self):
try:
with open(self.filename):
self.connection = sqlite3.connect(self.filename)
except IOError:
self.connection = sqlite3.connect(self.filename)
cursor = self.connection.cursor()
cursor.execute('''CREATE TABLE readings
(date real, device text, property text, value real)''')
self.connection.commit()
return self
def __exit__(self, type, value, traceback):
self.connection.close()
self.connection = None
def log(self, device, property, value, t=None):
if t is None:
t = time.time()
values = (t, device, property, value)
cursor = self.connection.cursor()
cursor.execute("INSERT INTO readings VALUES(?,?,?,?)", values)
self.connection.commit()
|
<commit_before>import sqlite3
import time
class SQLiteLogger:
def __init__(self, filename="test.db"):
self.filename = filename
self.connection = None
def __enter__(self):
try:
with open(self.filename):
self.connection = sqlite3.connect(self.filename)
except IOError:
self.connection = sqlite3.connect(self.filename)
cursor = self.connection.cursor()
cursor.execute('''CREATE TABLE readings
(date real, device text, property text, value real)''')
self.connection.commit()
return self
def __exit__(self, type, value, traceback):
self.connection.close()
self.connection = None
def log(self, device, property, value):
now = time.time()
values = (now, device, property, value)
cursor = self.connection.cursor()
cursor.execute("INSERT INTO readings VALUES(?,?,?,?)", values)
self.connection.commit()
<commit_msg>Allow log time to be passed into logger<commit_after>
|
import sqlite3
import time
class SQLiteLogger:
def __init__(self, filename="test.db"):
self.filename = filename
self.connection = None
def __enter__(self):
try:
with open(self.filename):
self.connection = sqlite3.connect(self.filename)
except IOError:
self.connection = sqlite3.connect(self.filename)
cursor = self.connection.cursor()
cursor.execute('''CREATE TABLE readings
(date real, device text, property text, value real)''')
self.connection.commit()
return self
def __exit__(self, type, value, traceback):
self.connection.close()
self.connection = None
def log(self, device, property, value, t=None):
if t is None:
t = time.time()
values = (t, device, property, value)
cursor = self.connection.cursor()
cursor.execute("INSERT INTO readings VALUES(?,?,?,?)", values)
self.connection.commit()
|
import sqlite3
import time
class SQLiteLogger:
def __init__(self, filename="test.db"):
self.filename = filename
self.connection = None
def __enter__(self):
try:
with open(self.filename):
self.connection = sqlite3.connect(self.filename)
except IOError:
self.connection = sqlite3.connect(self.filename)
cursor = self.connection.cursor()
cursor.execute('''CREATE TABLE readings
(date real, device text, property text, value real)''')
self.connection.commit()
return self
def __exit__(self, type, value, traceback):
self.connection.close()
self.connection = None
def log(self, device, property, value):
now = time.time()
values = (now, device, property, value)
cursor = self.connection.cursor()
cursor.execute("INSERT INTO readings VALUES(?,?,?,?)", values)
self.connection.commit()
Allow log time to be passed into loggerimport sqlite3
import time
class SQLiteLogger:
def __init__(self, filename="test.db"):
self.filename = filename
self.connection = None
def __enter__(self):
try:
with open(self.filename):
self.connection = sqlite3.connect(self.filename)
except IOError:
self.connection = sqlite3.connect(self.filename)
cursor = self.connection.cursor()
cursor.execute('''CREATE TABLE readings
(date real, device text, property text, value real)''')
self.connection.commit()
return self
def __exit__(self, type, value, traceback):
self.connection.close()
self.connection = None
def log(self, device, property, value, t=None):
if t is None:
t = time.time()
values = (t, device, property, value)
cursor = self.connection.cursor()
cursor.execute("INSERT INTO readings VALUES(?,?,?,?)", values)
self.connection.commit()
|
<commit_before>import sqlite3
import time
class SQLiteLogger:
def __init__(self, filename="test.db"):
self.filename = filename
self.connection = None
def __enter__(self):
try:
with open(self.filename):
self.connection = sqlite3.connect(self.filename)
except IOError:
self.connection = sqlite3.connect(self.filename)
cursor = self.connection.cursor()
cursor.execute('''CREATE TABLE readings
(date real, device text, property text, value real)''')
self.connection.commit()
return self
def __exit__(self, type, value, traceback):
self.connection.close()
self.connection = None
def log(self, device, property, value):
now = time.time()
values = (now, device, property, value)
cursor = self.connection.cursor()
cursor.execute("INSERT INTO readings VALUES(?,?,?,?)", values)
self.connection.commit()
<commit_msg>Allow log time to be passed into logger<commit_after>import sqlite3
import time
class SQLiteLogger:
def __init__(self, filename="test.db"):
self.filename = filename
self.connection = None
def __enter__(self):
try:
with open(self.filename):
self.connection = sqlite3.connect(self.filename)
except IOError:
self.connection = sqlite3.connect(self.filename)
cursor = self.connection.cursor()
cursor.execute('''CREATE TABLE readings
(date real, device text, property text, value real)''')
self.connection.commit()
return self
def __exit__(self, type, value, traceback):
self.connection.close()
self.connection = None
def log(self, device, property, value, t=None):
if t is None:
t = time.time()
values = (t, device, property, value)
cursor = self.connection.cursor()
cursor.execute("INSERT INTO readings VALUES(?,?,?,?)", values)
self.connection.commit()
|
c5049b9bf465aee93d4c87b9cd62608d338ede7f
|
robokassa/migrations/0003_load_source_type.py
|
robokassa/migrations/0003_load_source_type.py
|
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
class Migration(DataMigration):
def forwards(self, orm):
pass
def backwards(self, orm):
pass
models = {
u'robokassa.successnotification': {
'InvId': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}),
'Meta': {'object_name': 'SuccessNotification'},
'OutSum': ('django.db.models.fields.CharField', [], {'max_length': '15'}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
}
}
complete_apps = ['robokassa']
symmetrical = True
|
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
class Migration(DataMigration):
depends_on = (
('payment', '0003_auto__chg_field_sourcetype_code__add_unique_sourcetype_code'),
)
def forwards(self, orm):
orm['payment.SourceType'].objects.get_or_create(code='robokassa', defaults=dict(name=u'Робокасса'))
def backwards(self, orm):
pass
models = {
u'robokassa.successnotification': {
'InvId': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}),
'Meta': {'object_name': 'SuccessNotification'},
'OutSum': ('django.db.models.fields.CharField', [], {'max_length': '15'}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
u'payment.sourcetype': {
'Meta': {'object_name': 'SourceType'},
'code': ('oscar.models.fields.autoslugfield.AutoSlugField', [],
{'allow_duplicates': 'False', 'max_length': '128', 'separator': "u'-'", 'blank': 'True',
'unique': 'True', 'populate_from': "'name'", 'overwrite': 'False'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '128'})
}
}
complete_apps = ['robokassa']
symmetrical = True
|
Add the code that correctly adds the new payment source.
|
Add the code that correctly adds the new payment source.
|
Python
|
mit
|
a-iv/django-oscar-robokassa
|
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
class Migration(DataMigration):
def forwards(self, orm):
pass
def backwards(self, orm):
pass
models = {
u'robokassa.successnotification': {
'InvId': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}),
'Meta': {'object_name': 'SuccessNotification'},
'OutSum': ('django.db.models.fields.CharField', [], {'max_length': '15'}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
}
}
complete_apps = ['robokassa']
symmetrical = True
Add the code that correctly adds the new payment source.
|
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
class Migration(DataMigration):
depends_on = (
('payment', '0003_auto__chg_field_sourcetype_code__add_unique_sourcetype_code'),
)
def forwards(self, orm):
orm['payment.SourceType'].objects.get_or_create(code='robokassa', defaults=dict(name=u'Робокасса'))
def backwards(self, orm):
pass
models = {
u'robokassa.successnotification': {
'InvId': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}),
'Meta': {'object_name': 'SuccessNotification'},
'OutSum': ('django.db.models.fields.CharField', [], {'max_length': '15'}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
u'payment.sourcetype': {
'Meta': {'object_name': 'SourceType'},
'code': ('oscar.models.fields.autoslugfield.AutoSlugField', [],
{'allow_duplicates': 'False', 'max_length': '128', 'separator': "u'-'", 'blank': 'True',
'unique': 'True', 'populate_from': "'name'", 'overwrite': 'False'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '128'})
}
}
complete_apps = ['robokassa']
symmetrical = True
|
<commit_before># -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
class Migration(DataMigration):
def forwards(self, orm):
pass
def backwards(self, orm):
pass
models = {
u'robokassa.successnotification': {
'InvId': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}),
'Meta': {'object_name': 'SuccessNotification'},
'OutSum': ('django.db.models.fields.CharField', [], {'max_length': '15'}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
}
}
complete_apps = ['robokassa']
symmetrical = True
<commit_msg>Add the code that correctly adds the new payment source.<commit_after>
|
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
class Migration(DataMigration):
depends_on = (
('payment', '0003_auto__chg_field_sourcetype_code__add_unique_sourcetype_code'),
)
def forwards(self, orm):
orm['payment.SourceType'].objects.get_or_create(code='robokassa', defaults=dict(name=u'Робокасса'))
def backwards(self, orm):
pass
models = {
u'robokassa.successnotification': {
'InvId': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}),
'Meta': {'object_name': 'SuccessNotification'},
'OutSum': ('django.db.models.fields.CharField', [], {'max_length': '15'}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
u'payment.sourcetype': {
'Meta': {'object_name': 'SourceType'},
'code': ('oscar.models.fields.autoslugfield.AutoSlugField', [],
{'allow_duplicates': 'False', 'max_length': '128', 'separator': "u'-'", 'blank': 'True',
'unique': 'True', 'populate_from': "'name'", 'overwrite': 'False'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '128'})
}
}
complete_apps = ['robokassa']
symmetrical = True
|
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
class Migration(DataMigration):
def forwards(self, orm):
pass
def backwards(self, orm):
pass
models = {
u'robokassa.successnotification': {
'InvId': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}),
'Meta': {'object_name': 'SuccessNotification'},
'OutSum': ('django.db.models.fields.CharField', [], {'max_length': '15'}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
}
}
complete_apps = ['robokassa']
symmetrical = True
Add the code that correctly adds the new payment source.# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
class Migration(DataMigration):
depends_on = (
('payment', '0003_auto__chg_field_sourcetype_code__add_unique_sourcetype_code'),
)
def forwards(self, orm):
orm['payment.SourceType'].objects.get_or_create(code='robokassa', defaults=dict(name=u'Робокасса'))
def backwards(self, orm):
pass
models = {
u'robokassa.successnotification': {
'InvId': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}),
'Meta': {'object_name': 'SuccessNotification'},
'OutSum': ('django.db.models.fields.CharField', [], {'max_length': '15'}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
u'payment.sourcetype': {
'Meta': {'object_name': 'SourceType'},
'code': ('oscar.models.fields.autoslugfield.AutoSlugField', [],
{'allow_duplicates': 'False', 'max_length': '128', 'separator': "u'-'", 'blank': 'True',
'unique': 'True', 'populate_from': "'name'", 'overwrite': 'False'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '128'})
}
}
complete_apps = ['robokassa']
symmetrical = True
|
<commit_before># -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
class Migration(DataMigration):
def forwards(self, orm):
pass
def backwards(self, orm):
pass
models = {
u'robokassa.successnotification': {
'InvId': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}),
'Meta': {'object_name': 'SuccessNotification'},
'OutSum': ('django.db.models.fields.CharField', [], {'max_length': '15'}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
}
}
complete_apps = ['robokassa']
symmetrical = True
<commit_msg>Add the code that correctly adds the new payment source.<commit_after># -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
class Migration(DataMigration):
depends_on = (
('payment', '0003_auto__chg_field_sourcetype_code__add_unique_sourcetype_code'),
)
def forwards(self, orm):
orm['payment.SourceType'].objects.get_or_create(code='robokassa', defaults=dict(name=u'Робокасса'))
def backwards(self, orm):
pass
models = {
u'robokassa.successnotification': {
'InvId': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}),
'Meta': {'object_name': 'SuccessNotification'},
'OutSum': ('django.db.models.fields.CharField', [], {'max_length': '15'}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
u'payment.sourcetype': {
'Meta': {'object_name': 'SourceType'},
'code': ('oscar.models.fields.autoslugfield.AutoSlugField', [],
{'allow_duplicates': 'False', 'max_length': '128', 'separator': "u'-'", 'blank': 'True',
'unique': 'True', 'populate_from': "'name'", 'overwrite': 'False'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '128'})
}
}
complete_apps = ['robokassa']
symmetrical = True
|
c347b0ae40c39b5f48ca4c39abfa1e1491feec6d
|
core/urls.py
|
core/urls.py
|
from django.conf.urls import include, url
from django.contrib import admin
admin.site.site_header = 'Coworking space administration'
urlpatterns = [
url(r'^billjobs/', include('billjobs.urls')),
url(r'^admin/', include(admin.site.urls)),
]
|
from django.conf.urls import include, url
from django.contrib import admin
from core import settings
admin.site.site_header = 'Coworking space administration'
urlpatterns = [
url(r'^billjobs/', include('billjobs.urls')),
url(r'^admin/', include(admin.site.urls)),
]
if settings.DEBUG:
import debug_toolbar
urlpatterns = [
url(r'^__debug__/', include(debug_toolbar.urls)),
] + urlpatterns
|
Add url pattern for debug toolbar
|
Add url pattern for debug toolbar
|
Python
|
mit
|
ioO/billjobs
|
from django.conf.urls import include, url
from django.contrib import admin
admin.site.site_header = 'Coworking space administration'
urlpatterns = [
url(r'^billjobs/', include('billjobs.urls')),
url(r'^admin/', include(admin.site.urls)),
]
Add url pattern for debug toolbar
|
from django.conf.urls import include, url
from django.contrib import admin
from core import settings
admin.site.site_header = 'Coworking space administration'
urlpatterns = [
url(r'^billjobs/', include('billjobs.urls')),
url(r'^admin/', include(admin.site.urls)),
]
if settings.DEBUG:
import debug_toolbar
urlpatterns = [
url(r'^__debug__/', include(debug_toolbar.urls)),
] + urlpatterns
|
<commit_before>from django.conf.urls import include, url
from django.contrib import admin
admin.site.site_header = 'Coworking space administration'
urlpatterns = [
url(r'^billjobs/', include('billjobs.urls')),
url(r'^admin/', include(admin.site.urls)),
]
<commit_msg>Add url pattern for debug toolbar<commit_after>
|
from django.conf.urls import include, url
from django.contrib import admin
from core import settings
admin.site.site_header = 'Coworking space administration'
urlpatterns = [
url(r'^billjobs/', include('billjobs.urls')),
url(r'^admin/', include(admin.site.urls)),
]
if settings.DEBUG:
import debug_toolbar
urlpatterns = [
url(r'^__debug__/', include(debug_toolbar.urls)),
] + urlpatterns
|
from django.conf.urls import include, url
from django.contrib import admin
admin.site.site_header = 'Coworking space administration'
urlpatterns = [
url(r'^billjobs/', include('billjobs.urls')),
url(r'^admin/', include(admin.site.urls)),
]
Add url pattern for debug toolbarfrom django.conf.urls import include, url
from django.contrib import admin
from core import settings
admin.site.site_header = 'Coworking space administration'
urlpatterns = [
url(r'^billjobs/', include('billjobs.urls')),
url(r'^admin/', include(admin.site.urls)),
]
if settings.DEBUG:
import debug_toolbar
urlpatterns = [
url(r'^__debug__/', include(debug_toolbar.urls)),
] + urlpatterns
|
<commit_before>from django.conf.urls import include, url
from django.contrib import admin
admin.site.site_header = 'Coworking space administration'
urlpatterns = [
url(r'^billjobs/', include('billjobs.urls')),
url(r'^admin/', include(admin.site.urls)),
]
<commit_msg>Add url pattern for debug toolbar<commit_after>from django.conf.urls import include, url
from django.contrib import admin
from core import settings
admin.site.site_header = 'Coworking space administration'
urlpatterns = [
url(r'^billjobs/', include('billjobs.urls')),
url(r'^admin/', include(admin.site.urls)),
]
if settings.DEBUG:
import debug_toolbar
urlpatterns = [
url(r'^__debug__/', include(debug_toolbar.urls)),
] + urlpatterns
|
51c37e74da9fe2bfc068fd29a52422c84b13900d
|
froide/frontpage/models.py
|
froide/frontpage/models.py
|
from django.db import models
from django.utils.translation import ugettext as _
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.contrib.sites.managers import CurrentSiteManager
from foirequest.models import FoiRequest
class FeaturedRequestManager(CurrentSiteManager):
def getFeatured(self):
try:
return self.get_query_set().order_by("-timestamp").select_related('request', 'request__publicbody')[0]
except IndexError:
return None
class FeaturedRequest(models.Model):
request = models.ForeignKey(FoiRequest,
verbose_name=_("Featured Request"))
timestamp = models.DateTimeField()
title = models.CharField(max_length=255)
text = models.TextField()
url = models.CharField(max_length=255, blank=True)
user = models.ForeignKey(User, null=True,
on_delete=models.SET_NULL,
verbose_name=_("User"))
site = models.ForeignKey(Site, null=True,
on_delete=models.SET_NULL, verbose_name=_("Site"))
objects = FeaturedRequestManager()
|
from django.db import models
from django.utils.translation import ugettext as _
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.contrib.sites.managers import CurrentSiteManager
from foirequest.models import FoiRequest
class FeaturedRequestManager(CurrentSiteManager):
def getFeatured(self):
try:
return self.get_query_set().order_by("-timestamp").select_related('request', 'request__publicbody')[0]
except IndexError:
return None
class FeaturedRequest(models.Model):
request = models.ForeignKey(FoiRequest,
verbose_name=_("Featured Request"))
timestamp = models.DateTimeField()
title = models.CharField(max_length=255)
text = models.TextField()
url = models.CharField(max_length=255, blank=True)
user = models.ForeignKey(User, null=True,
on_delete=models.SET_NULL,
verbose_name=_("User"))
site = models.ForeignKey(Site, null=True,
on_delete=models.SET_NULL, verbose_name=_("Site"))
objects = FeaturedRequestManager()
class Meta:
ordering = ('-timestamp',)
get_latest_by = 'timestamp'
verbose_name = _('Featured Request')
verbose_name_plural = _('Featured Requests')
|
Add meta class to FeaturedRequest model
|
Add meta class to FeaturedRequest model
|
Python
|
mit
|
ryankanno/froide,fin/froide,okfse/froide,catcosmo/froide,catcosmo/froide,okfse/froide,CodeforHawaii/froide,CodeforHawaii/froide,LilithWittmann/froide,LilithWittmann/froide,fin/froide,catcosmo/froide,ryankanno/froide,stefanw/froide,stefanw/froide,CodeforHawaii/froide,fin/froide,ryankanno/froide,ryankanno/froide,LilithWittmann/froide,okfse/froide,CodeforHawaii/froide,fin/froide,catcosmo/froide,okfse/froide,ryankanno/froide,stefanw/froide,stefanw/froide,LilithWittmann/froide,catcosmo/froide,LilithWittmann/froide,okfse/froide,stefanw/froide,CodeforHawaii/froide
|
from django.db import models
from django.utils.translation import ugettext as _
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.contrib.sites.managers import CurrentSiteManager
from foirequest.models import FoiRequest
class FeaturedRequestManager(CurrentSiteManager):
def getFeatured(self):
try:
return self.get_query_set().order_by("-timestamp").select_related('request', 'request__publicbody')[0]
except IndexError:
return None
class FeaturedRequest(models.Model):
request = models.ForeignKey(FoiRequest,
verbose_name=_("Featured Request"))
timestamp = models.DateTimeField()
title = models.CharField(max_length=255)
text = models.TextField()
url = models.CharField(max_length=255, blank=True)
user = models.ForeignKey(User, null=True,
on_delete=models.SET_NULL,
verbose_name=_("User"))
site = models.ForeignKey(Site, null=True,
on_delete=models.SET_NULL, verbose_name=_("Site"))
objects = FeaturedRequestManager()
Add meta class to FeaturedRequest model
|
from django.db import models
from django.utils.translation import ugettext as _
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.contrib.sites.managers import CurrentSiteManager
from foirequest.models import FoiRequest
class FeaturedRequestManager(CurrentSiteManager):
def getFeatured(self):
try:
return self.get_query_set().order_by("-timestamp").select_related('request', 'request__publicbody')[0]
except IndexError:
return None
class FeaturedRequest(models.Model):
request = models.ForeignKey(FoiRequest,
verbose_name=_("Featured Request"))
timestamp = models.DateTimeField()
title = models.CharField(max_length=255)
text = models.TextField()
url = models.CharField(max_length=255, blank=True)
user = models.ForeignKey(User, null=True,
on_delete=models.SET_NULL,
verbose_name=_("User"))
site = models.ForeignKey(Site, null=True,
on_delete=models.SET_NULL, verbose_name=_("Site"))
objects = FeaturedRequestManager()
class Meta:
ordering = ('-timestamp',)
get_latest_by = 'timestamp'
verbose_name = _('Featured Request')
verbose_name_plural = _('Featured Requests')
|
<commit_before>from django.db import models
from django.utils.translation import ugettext as _
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.contrib.sites.managers import CurrentSiteManager
from foirequest.models import FoiRequest
class FeaturedRequestManager(CurrentSiteManager):
def getFeatured(self):
try:
return self.get_query_set().order_by("-timestamp").select_related('request', 'request__publicbody')[0]
except IndexError:
return None
class FeaturedRequest(models.Model):
request = models.ForeignKey(FoiRequest,
verbose_name=_("Featured Request"))
timestamp = models.DateTimeField()
title = models.CharField(max_length=255)
text = models.TextField()
url = models.CharField(max_length=255, blank=True)
user = models.ForeignKey(User, null=True,
on_delete=models.SET_NULL,
verbose_name=_("User"))
site = models.ForeignKey(Site, null=True,
on_delete=models.SET_NULL, verbose_name=_("Site"))
objects = FeaturedRequestManager()
<commit_msg>Add meta class to FeaturedRequest model<commit_after>
|
from django.db import models
from django.utils.translation import ugettext as _
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.contrib.sites.managers import CurrentSiteManager
from foirequest.models import FoiRequest
class FeaturedRequestManager(CurrentSiteManager):
def getFeatured(self):
try:
return self.get_query_set().order_by("-timestamp").select_related('request', 'request__publicbody')[0]
except IndexError:
return None
class FeaturedRequest(models.Model):
request = models.ForeignKey(FoiRequest,
verbose_name=_("Featured Request"))
timestamp = models.DateTimeField()
title = models.CharField(max_length=255)
text = models.TextField()
url = models.CharField(max_length=255, blank=True)
user = models.ForeignKey(User, null=True,
on_delete=models.SET_NULL,
verbose_name=_("User"))
site = models.ForeignKey(Site, null=True,
on_delete=models.SET_NULL, verbose_name=_("Site"))
objects = FeaturedRequestManager()
class Meta:
ordering = ('-timestamp',)
get_latest_by = 'timestamp'
verbose_name = _('Featured Request')
verbose_name_plural = _('Featured Requests')
|
from django.db import models
from django.utils.translation import ugettext as _
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.contrib.sites.managers import CurrentSiteManager
from foirequest.models import FoiRequest
class FeaturedRequestManager(CurrentSiteManager):
def getFeatured(self):
try:
return self.get_query_set().order_by("-timestamp").select_related('request', 'request__publicbody')[0]
except IndexError:
return None
class FeaturedRequest(models.Model):
request = models.ForeignKey(FoiRequest,
verbose_name=_("Featured Request"))
timestamp = models.DateTimeField()
title = models.CharField(max_length=255)
text = models.TextField()
url = models.CharField(max_length=255, blank=True)
user = models.ForeignKey(User, null=True,
on_delete=models.SET_NULL,
verbose_name=_("User"))
site = models.ForeignKey(Site, null=True,
on_delete=models.SET_NULL, verbose_name=_("Site"))
objects = FeaturedRequestManager()
Add meta class to FeaturedRequest modelfrom django.db import models
from django.utils.translation import ugettext as _
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.contrib.sites.managers import CurrentSiteManager
from foirequest.models import FoiRequest
class FeaturedRequestManager(CurrentSiteManager):
def getFeatured(self):
try:
return self.get_query_set().order_by("-timestamp").select_related('request', 'request__publicbody')[0]
except IndexError:
return None
class FeaturedRequest(models.Model):
request = models.ForeignKey(FoiRequest,
verbose_name=_("Featured Request"))
timestamp = models.DateTimeField()
title = models.CharField(max_length=255)
text = models.TextField()
url = models.CharField(max_length=255, blank=True)
user = models.ForeignKey(User, null=True,
on_delete=models.SET_NULL,
verbose_name=_("User"))
site = models.ForeignKey(Site, null=True,
on_delete=models.SET_NULL, verbose_name=_("Site"))
objects = FeaturedRequestManager()
class Meta:
ordering = ('-timestamp',)
get_latest_by = 'timestamp'
verbose_name = _('Featured Request')
verbose_name_plural = _('Featured Requests')
|
<commit_before>from django.db import models
from django.utils.translation import ugettext as _
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.contrib.sites.managers import CurrentSiteManager
from foirequest.models import FoiRequest
class FeaturedRequestManager(CurrentSiteManager):
def getFeatured(self):
try:
return self.get_query_set().order_by("-timestamp").select_related('request', 'request__publicbody')[0]
except IndexError:
return None
class FeaturedRequest(models.Model):
request = models.ForeignKey(FoiRequest,
verbose_name=_("Featured Request"))
timestamp = models.DateTimeField()
title = models.CharField(max_length=255)
text = models.TextField()
url = models.CharField(max_length=255, blank=True)
user = models.ForeignKey(User, null=True,
on_delete=models.SET_NULL,
verbose_name=_("User"))
site = models.ForeignKey(Site, null=True,
on_delete=models.SET_NULL, verbose_name=_("Site"))
objects = FeaturedRequestManager()
<commit_msg>Add meta class to FeaturedRequest model<commit_after>from django.db import models
from django.utils.translation import ugettext as _
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.contrib.sites.managers import CurrentSiteManager
from foirequest.models import FoiRequest
class FeaturedRequestManager(CurrentSiteManager):
def getFeatured(self):
try:
return self.get_query_set().order_by("-timestamp").select_related('request', 'request__publicbody')[0]
except IndexError:
return None
class FeaturedRequest(models.Model):
request = models.ForeignKey(FoiRequest,
verbose_name=_("Featured Request"))
timestamp = models.DateTimeField()
title = models.CharField(max_length=255)
text = models.TextField()
url = models.CharField(max_length=255, blank=True)
user = models.ForeignKey(User, null=True,
on_delete=models.SET_NULL,
verbose_name=_("User"))
site = models.ForeignKey(Site, null=True,
on_delete=models.SET_NULL, verbose_name=_("Site"))
objects = FeaturedRequestManager()
class Meta:
ordering = ('-timestamp',)
get_latest_by = 'timestamp'
verbose_name = _('Featured Request')
verbose_name_plural = _('Featured Requests')
|
fa7bd3247302407da423c38690b07b0917fadb80
|
core/urls.py
|
core/urls.py
|
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
]
|
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
]
# Use GeoJSON api
from djgeojson.views import GeoJSONLayerView
from .models import BookLocation
# GeoJSON book locations hook. Returns object with all BookLocation elements.
urlpatterns += [
url(r'^api/bookLocs.geojson$', GeoJSONLayerView.as_view(model=BookLocation, properties=('name','book_holding','time',)), name='bookLocs'),
]
|
Add a GeoJSON book locations hook
|
Add a GeoJSON book locations hook
Located at URL/api/bookLocs.geojson.
Returns all book locations.
|
Python
|
mit
|
edushifts/book-voyage,edushifts/book-voyage,edushifts/book-voyage,edushifts/book-voyage
|
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
]
Add a GeoJSON book locations hook
Located at URL/api/bookLocs.geojson.
Returns all book locations.
|
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
]
# Use GeoJSON api
from djgeojson.views import GeoJSONLayerView
from .models import BookLocation
# GeoJSON book locations hook. Returns object with all BookLocation elements.
urlpatterns += [
url(r'^api/bookLocs.geojson$', GeoJSONLayerView.as_view(model=BookLocation, properties=('name','book_holding','time',)), name='bookLocs'),
]
|
<commit_before>from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
]
<commit_msg>Add a GeoJSON book locations hook
Located at URL/api/bookLocs.geojson.
Returns all book locations.<commit_after>
|
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
]
# Use GeoJSON api
from djgeojson.views import GeoJSONLayerView
from .models import BookLocation
# GeoJSON book locations hook. Returns object with all BookLocation elements.
urlpatterns += [
url(r'^api/bookLocs.geojson$', GeoJSONLayerView.as_view(model=BookLocation, properties=('name','book_holding','time',)), name='bookLocs'),
]
|
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
]
Add a GeoJSON book locations hook
Located at URL/api/bookLocs.geojson.
Returns all book locations.from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
]
# Use GeoJSON api
from djgeojson.views import GeoJSONLayerView
from .models import BookLocation
# GeoJSON book locations hook. Returns object with all BookLocation elements.
urlpatterns += [
url(r'^api/bookLocs.geojson$', GeoJSONLayerView.as_view(model=BookLocation, properties=('name','book_holding','time',)), name='bookLocs'),
]
|
<commit_before>from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
]
<commit_msg>Add a GeoJSON book locations hook
Located at URL/api/bookLocs.geojson.
Returns all book locations.<commit_after>from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
]
# Use GeoJSON api
from djgeojson.views import GeoJSONLayerView
from .models import BookLocation
# GeoJSON book locations hook. Returns object with all BookLocation elements.
urlpatterns += [
url(r'^api/bookLocs.geojson$', GeoJSONLayerView.as_view(model=BookLocation, properties=('name','book_holding','time',)), name='bookLocs'),
]
|
25458e3664391566cbe416eba2b9885809ae157e
|
server/server.py
|
server/server.py
|
from flask import Flask, url_for
app = Flask(__name__)
@app.route('/')
def api_root():
return 'Welcome'
# Deprecated
# @app.route('/toggle')
# def api_toggle():
# # Toggle the state of the player
# return 'state changed'
# @app.route('/volume/<volume_value>')
# def api_volume(volume_value):
# # Adjusts volume of the player
# return 'Volume is now ' + volume_value
if __name__ == '__main__':
app.run(debug=True)
|
from flask import Flask, url_for
app = Flask(__name__)
@app.route('/')
def api_root():
return 'Welcome'
# Deprecated
# @app.route('/toggle')
# def api_toggle():
# # Toggle the state of the player
# return 'state changed'
# @app.route('/volume/<volume_value>')
# def api_volume(volume_value):
# # Adjusts volume of the player
# return 'Volume is now ' + volume_value
@app.route('/start/<tone_id>')
def api_start_tone(tone_id):
# Start the tone
return 'Started Playing ' + tone_id
@app.route('/stop/<tone_id>')
def api_stop_tone(tone_id):
# Stop the tone
return 'Stopped Playing ' + tone_id
if __name__ == '__main__':
app.run(debug=True)
|
Add methods to start and stop playing tone
|
Add methods to start and stop playing tone
|
Python
|
artistic-2.0
|
axay/eigen,axay/eigen
|
from flask import Flask, url_for
app = Flask(__name__)
@app.route('/')
def api_root():
return 'Welcome'
# Deprecated
# @app.route('/toggle')
# def api_toggle():
# # Toggle the state of the player
# return 'state changed'
# @app.route('/volume/<volume_value>')
# def api_volume(volume_value):
# # Adjusts volume of the player
# return 'Volume is now ' + volume_value
if __name__ == '__main__':
app.run(debug=True)Add methods to start and stop playing tone
|
from flask import Flask, url_for
app = Flask(__name__)
@app.route('/')
def api_root():
return 'Welcome'
# Deprecated
# @app.route('/toggle')
# def api_toggle():
# # Toggle the state of the player
# return 'state changed'
# @app.route('/volume/<volume_value>')
# def api_volume(volume_value):
# # Adjusts volume of the player
# return 'Volume is now ' + volume_value
@app.route('/start/<tone_id>')
def api_start_tone(tone_id):
# Start the tone
return 'Started Playing ' + tone_id
@app.route('/stop/<tone_id>')
def api_stop_tone(tone_id):
# Stop the tone
return 'Stopped Playing ' + tone_id
if __name__ == '__main__':
app.run(debug=True)
|
<commit_before>from flask import Flask, url_for
app = Flask(__name__)
@app.route('/')
def api_root():
return 'Welcome'
# Deprecated
# @app.route('/toggle')
# def api_toggle():
# # Toggle the state of the player
# return 'state changed'
# @app.route('/volume/<volume_value>')
# def api_volume(volume_value):
# # Adjusts volume of the player
# return 'Volume is now ' + volume_value
if __name__ == '__main__':
app.run(debug=True)<commit_msg>Add methods to start and stop playing tone<commit_after>
|
from flask import Flask, url_for
app = Flask(__name__)
@app.route('/')
def api_root():
return 'Welcome'
# Deprecated
# @app.route('/toggle')
# def api_toggle():
# # Toggle the state of the player
# return 'state changed'
# @app.route('/volume/<volume_value>')
# def api_volume(volume_value):
# # Adjusts volume of the player
# return 'Volume is now ' + volume_value
@app.route('/start/<tone_id>')
def api_start_tone(tone_id):
# Start the tone
return 'Started Playing ' + tone_id
@app.route('/stop/<tone_id>')
def api_stop_tone(tone_id):
# Stop the tone
return 'Stopped Playing ' + tone_id
if __name__ == '__main__':
app.run(debug=True)
|
from flask import Flask, url_for
app = Flask(__name__)
@app.route('/')
def api_root():
return 'Welcome'
# Deprecated
# @app.route('/toggle')
# def api_toggle():
# # Toggle the state of the player
# return 'state changed'
# @app.route('/volume/<volume_value>')
# def api_volume(volume_value):
# # Adjusts volume of the player
# return 'Volume is now ' + volume_value
if __name__ == '__main__':
app.run(debug=True)Add methods to start and stop playing tonefrom flask import Flask, url_for
app = Flask(__name__)
@app.route('/')
def api_root():
return 'Welcome'
# Deprecated
# @app.route('/toggle')
# def api_toggle():
# # Toggle the state of the player
# return 'state changed'
# @app.route('/volume/<volume_value>')
# def api_volume(volume_value):
# # Adjusts volume of the player
# return 'Volume is now ' + volume_value
@app.route('/start/<tone_id>')
def api_start_tone(tone_id):
# Start the tone
return 'Started Playing ' + tone_id
@app.route('/stop/<tone_id>')
def api_stop_tone(tone_id):
# Stop the tone
return 'Stopped Playing ' + tone_id
if __name__ == '__main__':
app.run(debug=True)
|
<commit_before>from flask import Flask, url_for
app = Flask(__name__)
@app.route('/')
def api_root():
return 'Welcome'
# Deprecated
# @app.route('/toggle')
# def api_toggle():
# # Toggle the state of the player
# return 'state changed'
# @app.route('/volume/<volume_value>')
# def api_volume(volume_value):
# # Adjusts volume of the player
# return 'Volume is now ' + volume_value
if __name__ == '__main__':
app.run(debug=True)<commit_msg>Add methods to start and stop playing tone<commit_after>from flask import Flask, url_for
app = Flask(__name__)
@app.route('/')
def api_root():
return 'Welcome'
# Deprecated
# @app.route('/toggle')
# def api_toggle():
# # Toggle the state of the player
# return 'state changed'
# @app.route('/volume/<volume_value>')
# def api_volume(volume_value):
# # Adjusts volume of the player
# return 'Volume is now ' + volume_value
@app.route('/start/<tone_id>')
def api_start_tone(tone_id):
# Start the tone
return 'Started Playing ' + tone_id
@app.route('/stop/<tone_id>')
def api_stop_tone(tone_id):
# Stop the tone
return 'Stopped Playing ' + tone_id
if __name__ == '__main__':
app.run(debug=True)
|
2063235c55bf359e284b2bd0fe83a6736d5a3a91
|
settings/prod.py
|
settings/prod.py
|
# -*- coding: utf-8 -*-
import os
import dj_database_url
from base import *
DEBUG = False
TEMPLATE_DEBUG = False
DATABASES = {
'default': dj_database_url.config()
}
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
GEOS_LIBRARY_PATH = '/app/.geodjango/geos/lib/libgeos_c.so'
GDAL_LIBRARY_PATH = '/app/.geodjango/gdal/lib/libgdal.so'
|
# -*- coding: utf-8 -*-
import os
import dj_database_url
from base import *
DEBUG = False
TEMPLATE_DEBUG = False
DATABASES = {
'default': dj_database_url.config()
}
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
|
Revert "Adding conf for geodjango buildpack"
|
Revert "Adding conf for geodjango buildpack"
This reverts commit 6d2528e8eae37751d66d3138e52042111e42e239.
gendjango buildpack messes with gunicorn
|
Python
|
agpl-3.0
|
datea/datea-api,lafactura/datea-api,lafactura/datea-api,datea/datea-api,datea/datea-api,lafactura/datea-api
|
# -*- coding: utf-8 -*-
import os
import dj_database_url
from base import *
DEBUG = False
TEMPLATE_DEBUG = False
DATABASES = {
'default': dj_database_url.config()
}
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
GEOS_LIBRARY_PATH = '/app/.geodjango/geos/lib/libgeos_c.so'
GDAL_LIBRARY_PATH = '/app/.geodjango/gdal/lib/libgdal.so'
Revert "Adding conf for geodjango buildpack"
This reverts commit 6d2528e8eae37751d66d3138e52042111e42e239.
gendjango buildpack messes with gunicorn
|
# -*- coding: utf-8 -*-
import os
import dj_database_url
from base import *
DEBUG = False
TEMPLATE_DEBUG = False
DATABASES = {
'default': dj_database_url.config()
}
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
|
<commit_before># -*- coding: utf-8 -*-
import os
import dj_database_url
from base import *
DEBUG = False
TEMPLATE_DEBUG = False
DATABASES = {
'default': dj_database_url.config()
}
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
GEOS_LIBRARY_PATH = '/app/.geodjango/geos/lib/libgeos_c.so'
GDAL_LIBRARY_PATH = '/app/.geodjango/gdal/lib/libgdal.so'
<commit_msg>Revert "Adding conf for geodjango buildpack"
This reverts commit 6d2528e8eae37751d66d3138e52042111e42e239.
gendjango buildpack messes with gunicorn<commit_after>
|
# -*- coding: utf-8 -*-
import os
import dj_database_url
from base import *
DEBUG = False
TEMPLATE_DEBUG = False
DATABASES = {
'default': dj_database_url.config()
}
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
|
# -*- coding: utf-8 -*-
import os
import dj_database_url
from base import *
DEBUG = False
TEMPLATE_DEBUG = False
DATABASES = {
'default': dj_database_url.config()
}
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
GEOS_LIBRARY_PATH = '/app/.geodjango/geos/lib/libgeos_c.so'
GDAL_LIBRARY_PATH = '/app/.geodjango/gdal/lib/libgdal.so'
Revert "Adding conf for geodjango buildpack"
This reverts commit 6d2528e8eae37751d66d3138e52042111e42e239.
gendjango buildpack messes with gunicorn# -*- coding: utf-8 -*-
import os
import dj_database_url
from base import *
DEBUG = False
TEMPLATE_DEBUG = False
DATABASES = {
'default': dj_database_url.config()
}
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
|
<commit_before># -*- coding: utf-8 -*-
import os
import dj_database_url
from base import *
DEBUG = False
TEMPLATE_DEBUG = False
DATABASES = {
'default': dj_database_url.config()
}
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
GEOS_LIBRARY_PATH = '/app/.geodjango/geos/lib/libgeos_c.so'
GDAL_LIBRARY_PATH = '/app/.geodjango/gdal/lib/libgdal.so'
<commit_msg>Revert "Adding conf for geodjango buildpack"
This reverts commit 6d2528e8eae37751d66d3138e52042111e42e239.
gendjango buildpack messes with gunicorn<commit_after># -*- coding: utf-8 -*-
import os
import dj_database_url
from base import *
DEBUG = False
TEMPLATE_DEBUG = False
DATABASES = {
'default': dj_database_url.config()
}
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
|
461ea32b927e35975c04b6b01679f4898ea490b6
|
shellReporter.py
|
shellReporter.py
|
#!/usr/bin/env python
class ShellReporter:
def send_status(self, timestamp, context, metric_value):
self._send(timestamp, context + '.STATUS', metric_value)
def send_duration(self, timestamp, context, metric_value):
self._send(timestamp, context + '.DURATION', metric_value)
def _send(self, timestamp, metric_name, metric_value):
print 'timestamp: %s - metric_name: %s - metric_value: %s' % (timestamp, metric_name, metric_value)
|
#!/usr/bin/env python
class ShellReporter:
def send_status(self, timestamp, context, metric_value):
self._send(timestamp, context + '.STATUS', metric_value + ' (%s)' % 'SUCCESS' if metric_value else 'FAILURE')
def send_duration(self, timestamp, context, metric_value):
self._send(timestamp, context + '.DURATION', metric_value)
def _send(self, timestamp, metric_name, metric_value):
print 'timestamp: %s - metric_name: %s - metric_value: %s' % (timestamp, metric_name, metric_value)
|
Add SUCCESS/FAILURE when reporting duration to shell
|
Add SUCCESS/FAILURE when reporting duration to shell
|
Python
|
mit
|
luigiberrettini/build-deploy-stats
|
#!/usr/bin/env python
class ShellReporter:
def send_status(self, timestamp, context, metric_value):
self._send(timestamp, context + '.STATUS', metric_value)
def send_duration(self, timestamp, context, metric_value):
self._send(timestamp, context + '.DURATION', metric_value)
def _send(self, timestamp, metric_name, metric_value):
print 'timestamp: %s - metric_name: %s - metric_value: %s' % (timestamp, metric_name, metric_value)Add SUCCESS/FAILURE when reporting duration to shell
|
#!/usr/bin/env python
class ShellReporter:
def send_status(self, timestamp, context, metric_value):
self._send(timestamp, context + '.STATUS', metric_value + ' (%s)' % 'SUCCESS' if metric_value else 'FAILURE')
def send_duration(self, timestamp, context, metric_value):
self._send(timestamp, context + '.DURATION', metric_value)
def _send(self, timestamp, metric_name, metric_value):
print 'timestamp: %s - metric_name: %s - metric_value: %s' % (timestamp, metric_name, metric_value)
|
<commit_before>#!/usr/bin/env python
class ShellReporter:
def send_status(self, timestamp, context, metric_value):
self._send(timestamp, context + '.STATUS', metric_value)
def send_duration(self, timestamp, context, metric_value):
self._send(timestamp, context + '.DURATION', metric_value)
def _send(self, timestamp, metric_name, metric_value):
print 'timestamp: %s - metric_name: %s - metric_value: %s' % (timestamp, metric_name, metric_value)<commit_msg>Add SUCCESS/FAILURE when reporting duration to shell<commit_after>
|
#!/usr/bin/env python
class ShellReporter:
def send_status(self, timestamp, context, metric_value):
self._send(timestamp, context + '.STATUS', metric_value + ' (%s)' % 'SUCCESS' if metric_value else 'FAILURE')
def send_duration(self, timestamp, context, metric_value):
self._send(timestamp, context + '.DURATION', metric_value)
def _send(self, timestamp, metric_name, metric_value):
print 'timestamp: %s - metric_name: %s - metric_value: %s' % (timestamp, metric_name, metric_value)
|
#!/usr/bin/env python
class ShellReporter:
def send_status(self, timestamp, context, metric_value):
self._send(timestamp, context + '.STATUS', metric_value)
def send_duration(self, timestamp, context, metric_value):
self._send(timestamp, context + '.DURATION', metric_value)
def _send(self, timestamp, metric_name, metric_value):
print 'timestamp: %s - metric_name: %s - metric_value: %s' % (timestamp, metric_name, metric_value)Add SUCCESS/FAILURE when reporting duration to shell#!/usr/bin/env python
class ShellReporter:
def send_status(self, timestamp, context, metric_value):
self._send(timestamp, context + '.STATUS', metric_value + ' (%s)' % 'SUCCESS' if metric_value else 'FAILURE')
def send_duration(self, timestamp, context, metric_value):
self._send(timestamp, context + '.DURATION', metric_value)
def _send(self, timestamp, metric_name, metric_value):
print 'timestamp: %s - metric_name: %s - metric_value: %s' % (timestamp, metric_name, metric_value)
|
<commit_before>#!/usr/bin/env python
class ShellReporter:
def send_status(self, timestamp, context, metric_value):
self._send(timestamp, context + '.STATUS', metric_value)
def send_duration(self, timestamp, context, metric_value):
self._send(timestamp, context + '.DURATION', metric_value)
def _send(self, timestamp, metric_name, metric_value):
print 'timestamp: %s - metric_name: %s - metric_value: %s' % (timestamp, metric_name, metric_value)<commit_msg>Add SUCCESS/FAILURE when reporting duration to shell<commit_after>#!/usr/bin/env python
class ShellReporter:
def send_status(self, timestamp, context, metric_value):
self._send(timestamp, context + '.STATUS', metric_value + ' (%s)' % 'SUCCESS' if metric_value else 'FAILURE')
def send_duration(self, timestamp, context, metric_value):
self._send(timestamp, context + '.DURATION', metric_value)
def _send(self, timestamp, metric_name, metric_value):
print 'timestamp: %s - metric_name: %s - metric_value: %s' % (timestamp, metric_name, metric_value)
|
4e7b8e0b03951faa0a43ce8b216b31c5bc4543a4
|
create_db.py
|
create_db.py
|
import os
import sys
import psycopg2
import sqlalchemy as sa
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
def main():
database = 'postgres'
user = 'postgres'
url = sa.engine.url.URL('postgresql', host=os.environ['PGHOST'],
database=database, username=user)
ddl_text = sa.text('CREATE DATABASE {};'.format(os.environ['PGDATABASE']))
engine = sa.create_engine(url)
engine.raw_connection().set_isolation_level(
ISOLATION_LEVEL_AUTOCOMMIT
)
try:
engine.execute(ddl_text)
sys.stdout.write('Creating environment successfully.\n')
except psycopg2.Error:
raise SystemExit('Could not connect to PostgreSQL.\n{0}'.format(sys.exc_info()))
if __name__ == '__main__':
main()
|
import os
import sys
import psycopg2
import sqlalchemy as sa
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
def main():
database = 'postgres'
user = 'postgres'
url = sa.engine.url.URL(
'postgresql', host=os.environ['PGHOST'], database=database,
username=user, password=os.environ.get('PGPASSWORD', None)
)
ddl_text = sa.DDL('CREATE DATABASE {};'.format(os.environ['PGDATABASE']))
engine = sa.create_engine(url)
engine.raw_connection().set_isolation_level(
ISOLATION_LEVEL_AUTOCOMMIT
)
try:
engine.execute(ddl_text)
sys.stdout.write('Creating environment successfully.\n')
except psycopg2.Error:
raise SystemExit('Could not connect to PostgreSQL.\n{0}'.format(sys.exc_info()))
if __name__ == '__main__':
main()
|
Add password envar for db creation.
|
Add password envar for db creation.
|
Python
|
mit
|
portfoliome/pgawedge
|
import os
import sys
import psycopg2
import sqlalchemy as sa
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
def main():
database = 'postgres'
user = 'postgres'
url = sa.engine.url.URL('postgresql', host=os.environ['PGHOST'],
database=database, username=user)
ddl_text = sa.text('CREATE DATABASE {};'.format(os.environ['PGDATABASE']))
engine = sa.create_engine(url)
engine.raw_connection().set_isolation_level(
ISOLATION_LEVEL_AUTOCOMMIT
)
try:
engine.execute(ddl_text)
sys.stdout.write('Creating environment successfully.\n')
except psycopg2.Error:
raise SystemExit('Could not connect to PostgreSQL.\n{0}'.format(sys.exc_info()))
if __name__ == '__main__':
main()
Add password envar for db creation.
|
import os
import sys
import psycopg2
import sqlalchemy as sa
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
def main():
database = 'postgres'
user = 'postgres'
url = sa.engine.url.URL(
'postgresql', host=os.environ['PGHOST'], database=database,
username=user, password=os.environ.get('PGPASSWORD', None)
)
ddl_text = sa.DDL('CREATE DATABASE {};'.format(os.environ['PGDATABASE']))
engine = sa.create_engine(url)
engine.raw_connection().set_isolation_level(
ISOLATION_LEVEL_AUTOCOMMIT
)
try:
engine.execute(ddl_text)
sys.stdout.write('Creating environment successfully.\n')
except psycopg2.Error:
raise SystemExit('Could not connect to PostgreSQL.\n{0}'.format(sys.exc_info()))
if __name__ == '__main__':
main()
|
<commit_before>import os
import sys
import psycopg2
import sqlalchemy as sa
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
def main():
database = 'postgres'
user = 'postgres'
url = sa.engine.url.URL('postgresql', host=os.environ['PGHOST'],
database=database, username=user)
ddl_text = sa.text('CREATE DATABASE {};'.format(os.environ['PGDATABASE']))
engine = sa.create_engine(url)
engine.raw_connection().set_isolation_level(
ISOLATION_LEVEL_AUTOCOMMIT
)
try:
engine.execute(ddl_text)
sys.stdout.write('Creating environment successfully.\n')
except psycopg2.Error:
raise SystemExit('Could not connect to PostgreSQL.\n{0}'.format(sys.exc_info()))
if __name__ == '__main__':
main()
<commit_msg>Add password envar for db creation.<commit_after>
|
import os
import sys
import psycopg2
import sqlalchemy as sa
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
def main():
database = 'postgres'
user = 'postgres'
url = sa.engine.url.URL(
'postgresql', host=os.environ['PGHOST'], database=database,
username=user, password=os.environ.get('PGPASSWORD', None)
)
ddl_text = sa.DDL('CREATE DATABASE {};'.format(os.environ['PGDATABASE']))
engine = sa.create_engine(url)
engine.raw_connection().set_isolation_level(
ISOLATION_LEVEL_AUTOCOMMIT
)
try:
engine.execute(ddl_text)
sys.stdout.write('Creating environment successfully.\n')
except psycopg2.Error:
raise SystemExit('Could not connect to PostgreSQL.\n{0}'.format(sys.exc_info()))
if __name__ == '__main__':
main()
|
import os
import sys
import psycopg2
import sqlalchemy as sa
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
def main():
database = 'postgres'
user = 'postgres'
url = sa.engine.url.URL('postgresql', host=os.environ['PGHOST'],
database=database, username=user)
ddl_text = sa.text('CREATE DATABASE {};'.format(os.environ['PGDATABASE']))
engine = sa.create_engine(url)
engine.raw_connection().set_isolation_level(
ISOLATION_LEVEL_AUTOCOMMIT
)
try:
engine.execute(ddl_text)
sys.stdout.write('Creating environment successfully.\n')
except psycopg2.Error:
raise SystemExit('Could not connect to PostgreSQL.\n{0}'.format(sys.exc_info()))
if __name__ == '__main__':
main()
Add password envar for db creation.import os
import sys
import psycopg2
import sqlalchemy as sa
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
def main():
database = 'postgres'
user = 'postgres'
url = sa.engine.url.URL(
'postgresql', host=os.environ['PGHOST'], database=database,
username=user, password=os.environ.get('PGPASSWORD', None)
)
ddl_text = sa.DDL('CREATE DATABASE {};'.format(os.environ['PGDATABASE']))
engine = sa.create_engine(url)
engine.raw_connection().set_isolation_level(
ISOLATION_LEVEL_AUTOCOMMIT
)
try:
engine.execute(ddl_text)
sys.stdout.write('Creating environment successfully.\n')
except psycopg2.Error:
raise SystemExit('Could not connect to PostgreSQL.\n{0}'.format(sys.exc_info()))
if __name__ == '__main__':
main()
|
<commit_before>import os
import sys
import psycopg2
import sqlalchemy as sa
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
def main():
database = 'postgres'
user = 'postgres'
url = sa.engine.url.URL('postgresql', host=os.environ['PGHOST'],
database=database, username=user)
ddl_text = sa.text('CREATE DATABASE {};'.format(os.environ['PGDATABASE']))
engine = sa.create_engine(url)
engine.raw_connection().set_isolation_level(
ISOLATION_LEVEL_AUTOCOMMIT
)
try:
engine.execute(ddl_text)
sys.stdout.write('Creating environment successfully.\n')
except psycopg2.Error:
raise SystemExit('Could not connect to PostgreSQL.\n{0}'.format(sys.exc_info()))
if __name__ == '__main__':
main()
<commit_msg>Add password envar for db creation.<commit_after>import os
import sys
import psycopg2
import sqlalchemy as sa
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
def main():
database = 'postgres'
user = 'postgres'
url = sa.engine.url.URL(
'postgresql', host=os.environ['PGHOST'], database=database,
username=user, password=os.environ.get('PGPASSWORD', None)
)
ddl_text = sa.DDL('CREATE DATABASE {};'.format(os.environ['PGDATABASE']))
engine = sa.create_engine(url)
engine.raw_connection().set_isolation_level(
ISOLATION_LEVEL_AUTOCOMMIT
)
try:
engine.execute(ddl_text)
sys.stdout.write('Creating environment successfully.\n')
except psycopg2.Error:
raise SystemExit('Could not connect to PostgreSQL.\n{0}'.format(sys.exc_info()))
if __name__ == '__main__':
main()
|
6f5e987b5a102b0c4b0bfcd88c17faab00655142
|
ctypeslib/test/test_toolchain.py
|
ctypeslib/test/test_toolchain.py
|
import unittest
import sys
from ctypeslib import h2xml, xml2py
class ToolchainTest(unittest.TestCase):
if sys.platform == "win32":
def test(self):
h2xml.main(["h2xml", "-q",
"-D WIN32_LEAN_AND_MEAN",
"-D _UNICODE", "-D UNICODE",
"-c", "windows.h",
"-o", "_windows_gen.xml"])
xml2py.main(["xml2py", "_windows_gen.xml", "-w", "-o", "_winapi_gen.py"])
import _winapi_gen
if __name__ == "__main__":
import unittest
unittest.main()
|
import unittest
import sys
from ctypeslib import h2xml, xml2py
class ToolchainTest(unittest.TestCase):
if sys.platform == "win32":
def test_windows(self):
h2xml.main(["h2xml", "-q",
"-D WIN32_LEAN_AND_MEAN",
"-D _UNICODE", "-D UNICODE",
"-c", "windows.h",
"-o", "_windows_gen.xml"])
xml2py.main(["xml2py", "_windows_gen.xml", "-w", "-o", "_winapi_gen.py"])
import _winapi_gen
def test(self):
h2xml.main(["h2xml", "-q",
"-D WIN32_LEAN_AND_MEAN",
"-D _UNICODE", "-D UNICODE",
"-c", "stdio.h",
"-o", "_stdio_gen.xml"])
xml2py.main(["xml2py", "_stdio_gen.xml", "-o", "_stdio_gen.py"])
import _stdio_gen
if __name__ == "__main__":
import unittest
unittest.main()
|
Add a test for stdio.h.
|
Add a test for stdio.h.
git-svn-id: ac2c3632cb6543e7ab5fafd132c7fe15057a1882@60472 6015fed2-1504-0410-9fe1-9d1591cc4771
|
Python
|
mit
|
trolldbois/ctypeslib,luzfcb/ctypeslib,trolldbois/ctypeslib,luzfcb/ctypeslib,luzfcb/ctypeslib,trolldbois/ctypeslib
|
import unittest
import sys
from ctypeslib import h2xml, xml2py
class ToolchainTest(unittest.TestCase):
if sys.platform == "win32":
def test(self):
h2xml.main(["h2xml", "-q",
"-D WIN32_LEAN_AND_MEAN",
"-D _UNICODE", "-D UNICODE",
"-c", "windows.h",
"-o", "_windows_gen.xml"])
xml2py.main(["xml2py", "_windows_gen.xml", "-w", "-o", "_winapi_gen.py"])
import _winapi_gen
if __name__ == "__main__":
import unittest
unittest.main()
Add a test for stdio.h.
git-svn-id: ac2c3632cb6543e7ab5fafd132c7fe15057a1882@60472 6015fed2-1504-0410-9fe1-9d1591cc4771
|
import unittest
import sys
from ctypeslib import h2xml, xml2py
class ToolchainTest(unittest.TestCase):
if sys.platform == "win32":
def test_windows(self):
h2xml.main(["h2xml", "-q",
"-D WIN32_LEAN_AND_MEAN",
"-D _UNICODE", "-D UNICODE",
"-c", "windows.h",
"-o", "_windows_gen.xml"])
xml2py.main(["xml2py", "_windows_gen.xml", "-w", "-o", "_winapi_gen.py"])
import _winapi_gen
def test(self):
h2xml.main(["h2xml", "-q",
"-D WIN32_LEAN_AND_MEAN",
"-D _UNICODE", "-D UNICODE",
"-c", "stdio.h",
"-o", "_stdio_gen.xml"])
xml2py.main(["xml2py", "_stdio_gen.xml", "-o", "_stdio_gen.py"])
import _stdio_gen
if __name__ == "__main__":
import unittest
unittest.main()
|
<commit_before>import unittest
import sys
from ctypeslib import h2xml, xml2py
class ToolchainTest(unittest.TestCase):
if sys.platform == "win32":
def test(self):
h2xml.main(["h2xml", "-q",
"-D WIN32_LEAN_AND_MEAN",
"-D _UNICODE", "-D UNICODE",
"-c", "windows.h",
"-o", "_windows_gen.xml"])
xml2py.main(["xml2py", "_windows_gen.xml", "-w", "-o", "_winapi_gen.py"])
import _winapi_gen
if __name__ == "__main__":
import unittest
unittest.main()
<commit_msg>Add a test for stdio.h.
git-svn-id: ac2c3632cb6543e7ab5fafd132c7fe15057a1882@60472 6015fed2-1504-0410-9fe1-9d1591cc4771<commit_after>
|
import unittest
import sys
from ctypeslib import h2xml, xml2py
class ToolchainTest(unittest.TestCase):
if sys.platform == "win32":
def test_windows(self):
h2xml.main(["h2xml", "-q",
"-D WIN32_LEAN_AND_MEAN",
"-D _UNICODE", "-D UNICODE",
"-c", "windows.h",
"-o", "_windows_gen.xml"])
xml2py.main(["xml2py", "_windows_gen.xml", "-w", "-o", "_winapi_gen.py"])
import _winapi_gen
def test(self):
h2xml.main(["h2xml", "-q",
"-D WIN32_LEAN_AND_MEAN",
"-D _UNICODE", "-D UNICODE",
"-c", "stdio.h",
"-o", "_stdio_gen.xml"])
xml2py.main(["xml2py", "_stdio_gen.xml", "-o", "_stdio_gen.py"])
import _stdio_gen
if __name__ == "__main__":
import unittest
unittest.main()
|
import unittest
import sys
from ctypeslib import h2xml, xml2py
class ToolchainTest(unittest.TestCase):
if sys.platform == "win32":
def test(self):
h2xml.main(["h2xml", "-q",
"-D WIN32_LEAN_AND_MEAN",
"-D _UNICODE", "-D UNICODE",
"-c", "windows.h",
"-o", "_windows_gen.xml"])
xml2py.main(["xml2py", "_windows_gen.xml", "-w", "-o", "_winapi_gen.py"])
import _winapi_gen
if __name__ == "__main__":
import unittest
unittest.main()
Add a test for stdio.h.
git-svn-id: ac2c3632cb6543e7ab5fafd132c7fe15057a1882@60472 6015fed2-1504-0410-9fe1-9d1591cc4771import unittest
import sys
from ctypeslib import h2xml, xml2py
class ToolchainTest(unittest.TestCase):
if sys.platform == "win32":
def test_windows(self):
h2xml.main(["h2xml", "-q",
"-D WIN32_LEAN_AND_MEAN",
"-D _UNICODE", "-D UNICODE",
"-c", "windows.h",
"-o", "_windows_gen.xml"])
xml2py.main(["xml2py", "_windows_gen.xml", "-w", "-o", "_winapi_gen.py"])
import _winapi_gen
def test(self):
h2xml.main(["h2xml", "-q",
"-D WIN32_LEAN_AND_MEAN",
"-D _UNICODE", "-D UNICODE",
"-c", "stdio.h",
"-o", "_stdio_gen.xml"])
xml2py.main(["xml2py", "_stdio_gen.xml", "-o", "_stdio_gen.py"])
import _stdio_gen
if __name__ == "__main__":
import unittest
unittest.main()
|
<commit_before>import unittest
import sys
from ctypeslib import h2xml, xml2py
class ToolchainTest(unittest.TestCase):
if sys.platform == "win32":
def test(self):
h2xml.main(["h2xml", "-q",
"-D WIN32_LEAN_AND_MEAN",
"-D _UNICODE", "-D UNICODE",
"-c", "windows.h",
"-o", "_windows_gen.xml"])
xml2py.main(["xml2py", "_windows_gen.xml", "-w", "-o", "_winapi_gen.py"])
import _winapi_gen
if __name__ == "__main__":
import unittest
unittest.main()
<commit_msg>Add a test for stdio.h.
git-svn-id: ac2c3632cb6543e7ab5fafd132c7fe15057a1882@60472 6015fed2-1504-0410-9fe1-9d1591cc4771<commit_after>import unittest
import sys
from ctypeslib import h2xml, xml2py
class ToolchainTest(unittest.TestCase):
if sys.platform == "win32":
def test_windows(self):
h2xml.main(["h2xml", "-q",
"-D WIN32_LEAN_AND_MEAN",
"-D _UNICODE", "-D UNICODE",
"-c", "windows.h",
"-o", "_windows_gen.xml"])
xml2py.main(["xml2py", "_windows_gen.xml", "-w", "-o", "_winapi_gen.py"])
import _winapi_gen
def test(self):
h2xml.main(["h2xml", "-q",
"-D WIN32_LEAN_AND_MEAN",
"-D _UNICODE", "-D UNICODE",
"-c", "stdio.h",
"-o", "_stdio_gen.xml"])
xml2py.main(["xml2py", "_stdio_gen.xml", "-o", "_stdio_gen.py"])
import _stdio_gen
if __name__ == "__main__":
import unittest
unittest.main()
|
73a9ba740d446e19c0428ffc29bf5bb5b033d7fe
|
PynamoDB/persistence_engine.py
|
PynamoDB/persistence_engine.py
|
"""
persistence_engine.py
~~~~~~~~~~~~
Implements put, get, delete methods for PersistenceStage. Using an actual persistence engine (i.e. MySQL, BDB), one would implement the three methods themselves.
"""
class PersistenceEngine(object):
""" Basic persistence engine implemented as a regular Python dict."""
def __init__(self):
self._persistence = dict()
def keys():
return self._persistence.keys()
def put(self, key, value):
""" Put key value pair into storage"""
self._persistence[key] = value
def get(self, key):
""" Get key's value """
return self._persistence[key]
def delete(self, key):
""" Delete key value pair """
del self._persistence[key]
|
"""
persistence_engine.py
~~~~~~~~~~~~
Implements put, get, delete methods for PersistenceStage. Using an actual persistence engine (i.e. MySQL, BDB), one would implement the three methods themselves.
"""
class PersistenceEngine(object):
""" Basic persistence engine implemented as a regular Python dict."""
def __init__(self):
self._persistence = dict()
def keys():
return self._persistence.keys()
def put(self, key, value, timestamp):
""" Put key value pair into storage"""
self._persistence[key] = {'value': value, 'timestamp': timestamp}
return True
def get(self, key):
""" Get key's value """
return self._persistence[key]['value'], self._persistence[key]['timestamp']
def delete(self, key):
""" Delete key value pair """
del self._persistence[key]
return True
|
Remove use of timestamped value.
|
Remove use of timestamped value.
Thought it was dumb/inelegant to have a Value() object floating around
with value and timestamp . Instead, now all messages are sent around
as json dicts.
The request enters the system as json, flows through to an endpoint
where it becomes a reply message, then flows back to the client.
|
Python
|
mit
|
samuelwu90/PynamoDB
|
"""
persistence_engine.py
~~~~~~~~~~~~
Implements put, get, delete methods for PersistenceStage. Using an actual persistence engine (i.e. MySQL, BDB), one would implement the three methods themselves.
"""
class PersistenceEngine(object):
""" Basic persistence engine implemented as a regular Python dict."""
def __init__(self):
self._persistence = dict()
def keys():
return self._persistence.keys()
def put(self, key, value):
""" Put key value pair into storage"""
self._persistence[key] = value
def get(self, key):
""" Get key's value """
return self._persistence[key]
def delete(self, key):
""" Delete key value pair """
del self._persistence[key]
Remove use of timestamped value.
Thought it was dumb/inelegant to have a Value() object floating around
with value and timestamp . Instead, now all messages are sent around
as json dicts.
The request enters the system as json, flows through to an endpoint
where it becomes a reply message, then flows back to the client.
|
"""
persistence_engine.py
~~~~~~~~~~~~
Implements put, get, delete methods for PersistenceStage. Using an actual persistence engine (i.e. MySQL, BDB), one would implement the three methods themselves.
"""
class PersistenceEngine(object):
""" Basic persistence engine implemented as a regular Python dict."""
def __init__(self):
self._persistence = dict()
def keys():
return self._persistence.keys()
def put(self, key, value, timestamp):
""" Put key value pair into storage"""
self._persistence[key] = {'value': value, 'timestamp': timestamp}
return True
def get(self, key):
""" Get key's value """
return self._persistence[key]['value'], self._persistence[key]['timestamp']
def delete(self, key):
""" Delete key value pair """
del self._persistence[key]
return True
|
<commit_before>"""
persistence_engine.py
~~~~~~~~~~~~
Implements put, get, delete methods for PersistenceStage. Using an actual persistence engine (i.e. MySQL, BDB), one would implement the three methods themselves.
"""
class PersistenceEngine(object):
""" Basic persistence engine implemented as a regular Python dict."""
def __init__(self):
self._persistence = dict()
def keys():
return self._persistence.keys()
def put(self, key, value):
""" Put key value pair into storage"""
self._persistence[key] = value
def get(self, key):
""" Get key's value """
return self._persistence[key]
def delete(self, key):
""" Delete key value pair """
del self._persistence[key]
<commit_msg>Remove use of timestamped value.
Thought it was dumb/inelegant to have a Value() object floating around
with value and timestamp . Instead, now all messages are sent around
as json dicts.
The request enters the system as json, flows through to an endpoint
where it becomes a reply message, then flows back to the client.<commit_after>
|
"""
persistence_engine.py
~~~~~~~~~~~~
Implements put, get, delete methods for PersistenceStage. Using an actual persistence engine (i.e. MySQL, BDB), one would implement the three methods themselves.
"""
class PersistenceEngine(object):
""" Basic persistence engine implemented as a regular Python dict."""
def __init__(self):
self._persistence = dict()
def keys():
return self._persistence.keys()
def put(self, key, value, timestamp):
""" Put key value pair into storage"""
self._persistence[key] = {'value': value, 'timestamp': timestamp}
return True
def get(self, key):
""" Get key's value """
return self._persistence[key]['value'], self._persistence[key]['timestamp']
def delete(self, key):
""" Delete key value pair """
del self._persistence[key]
return True
|
"""
persistence_engine.py
~~~~~~~~~~~~
Implements put, get, delete methods for PersistenceStage. Using an actual persistence engine (i.e. MySQL, BDB), one would implement the three methods themselves.
"""
class PersistenceEngine(object):
""" Basic persistence engine implemented as a regular Python dict."""
def __init__(self):
self._persistence = dict()
def keys():
return self._persistence.keys()
def put(self, key, value):
""" Put key value pair into storage"""
self._persistence[key] = value
def get(self, key):
""" Get key's value """
return self._persistence[key]
def delete(self, key):
""" Delete key value pair """
del self._persistence[key]
Remove use of timestamped value.
Thought it was dumb/inelegant to have a Value() object floating around
with value and timestamp . Instead, now all messages are sent around
as json dicts.
The request enters the system as json, flows through to an endpoint
where it becomes a reply message, then flows back to the client."""
persistence_engine.py
~~~~~~~~~~~~
Implements put, get, delete methods for PersistenceStage. Using an actual persistence engine (i.e. MySQL, BDB), one would implement the three methods themselves.
"""
class PersistenceEngine(object):
""" Basic persistence engine implemented as a regular Python dict."""
def __init__(self):
self._persistence = dict()
def keys():
return self._persistence.keys()
def put(self, key, value, timestamp):
""" Put key value pair into storage"""
self._persistence[key] = {'value': value, 'timestamp': timestamp}
return True
def get(self, key):
""" Get key's value """
return self._persistence[key]['value'], self._persistence[key]['timestamp']
def delete(self, key):
""" Delete key value pair """
del self._persistence[key]
return True
|
<commit_before>"""
persistence_engine.py
~~~~~~~~~~~~
Implements put, get, delete methods for PersistenceStage. Using an actual persistence engine (i.e. MySQL, BDB), one would implement the three methods themselves.
"""
class PersistenceEngine(object):
""" Basic persistence engine implemented as a regular Python dict."""
def __init__(self):
self._persistence = dict()
def keys():
return self._persistence.keys()
def put(self, key, value):
""" Put key value pair into storage"""
self._persistence[key] = value
def get(self, key):
""" Get key's value """
return self._persistence[key]
def delete(self, key):
""" Delete key value pair """
del self._persistence[key]
<commit_msg>Remove use of timestamped value.
Thought it was dumb/inelegant to have a Value() object floating around
with value and timestamp . Instead, now all messages are sent around
as json dicts.
The request enters the system as json, flows through to an endpoint
where it becomes a reply message, then flows back to the client.<commit_after>"""
persistence_engine.py
~~~~~~~~~~~~
Implements put, get, delete methods for PersistenceStage. Using an actual persistence engine (i.e. MySQL, BDB), one would implement the three methods themselves.
"""
class PersistenceEngine(object):
""" Basic persistence engine implemented as a regular Python dict."""
def __init__(self):
self._persistence = dict()
def keys():
return self._persistence.keys()
def put(self, key, value, timestamp):
""" Put key value pair into storage"""
self._persistence[key] = {'value': value, 'timestamp': timestamp}
return True
def get(self, key):
""" Get key's value """
return self._persistence[key]['value'], self._persistence[key]['timestamp']
def delete(self, key):
""" Delete key value pair """
del self._persistence[key]
return True
|
dcd2972bee896ea3c7885b1d6a8a6e132329d66b
|
apps/persona/urls.py
|
apps/persona/urls.py
|
from django.conf.urls.defaults import *
from mozorg.util import page
import views
urlpatterns = patterns('',
page('', 'persona/persona.html'),
page('about', 'persona/about.html'),
page('privacy-policy', 'persona/privacy-policy.html'),
page('terms-of-service', 'persona/terms-of-service.html'),
page('developer-faq', 'persona/developer-faq.html')
)
|
from django.conf.urls.defaults import *
from mozorg.util import page
urlpatterns = patterns('',
page('', 'persona/persona.html'),
page('about', 'persona/about.html'),
page('privacy-policy', 'persona/privacy-policy.html'),
page('terms-of-service', 'persona/terms-of-service.html'),
page('developer-faq', 'persona/developer-faq.html')
)
|
Remove unnecessary 'import views' line
|
Remove unnecessary 'import views' line
|
Python
|
mpl-2.0
|
jacshfr/mozilla-bedrock,marcoscaceres/bedrock,mmmavis/bedrock,sgarrity/bedrock,ericawright/bedrock,hoosteeno/bedrock,pascalchevrel/bedrock,schalkneethling/bedrock,alexgibson/bedrock,yglazko/bedrock,gauthierm/bedrock,sylvestre/bedrock,TheJJ100100/bedrock,dudepare/bedrock,davehunt/bedrock,bensternthal/bedrock,bensternthal/bedrock,craigcook/bedrock,mmmavis/bedrock,flodolo/bedrock,andreadelrio/bedrock,sylvestre/bedrock,davidwboswell/documentation_autoresponse,malena/bedrock,pascalchevrel/bedrock,glogiotatidis/bedrock,amjadm61/bedrock,Jobava/bedrock,l-hedgehog/bedrock,Jobava/bedrock,ericawright/bedrock,chirilo/bedrock,l-hedgehog/bedrock,pmclanahan/bedrock,davehunt/bedrock,mmmavis/lightbeam-bedrock-website,TheoChevalier/bedrock,CSCI-462-01-2017/bedrock,dudepare/bedrock,rishiloyola/bedrock,bensternthal/bedrock,schalkneethling/bedrock,andreadelrio/bedrock,TheJJ100100/bedrock,mkmelin/bedrock,TheoChevalier/bedrock,CSCI-462-01-2017/bedrock,glogiotatidis/bedrock,mozilla/bedrock,schalkneethling/bedrock,kyoshino/bedrock,TheoChevalier/bedrock,MichaelKohler/bedrock,analytics-pros/mozilla-bedrock,dudepare/bedrock,yglazko/bedrock,Sancus/bedrock,analytics-pros/mozilla-bedrock,jacshfr/mozilla-bedrock,rishiloyola/bedrock,gauthierm/bedrock,sgarrity/bedrock,alexgibson/bedrock,jacshfr/mozilla-bedrock,jgmize/bedrock,Sancus/bedrock,MichaelKohler/bedrock,SujaySKumar/bedrock,mozilla/mwc,ckprice/bedrock,jpetto/bedrock,MichaelKohler/bedrock,mahinthjoe/bedrock,marcoscaceres/bedrock,flodolo/bedrock,Sancus/bedrock,amjadm61/bedrock,TheoChevalier/bedrock,chirilo/bedrock,ericawright/bedrock,pascalchevrel/bedrock,sylvestre/bedrock,gerv/bedrock,alexgibson/bedrock,jpetto/bedrock,mmmavis/lightbeam-bedrock-website,chirilo/bedrock,gerv/bedrock,mozilla/bedrock,mermi/bedrock,l-hedgehog/bedrock,elin-moco/bedrock,mozilla/mwc,glogiotatidis/bedrock,gerv/bedrock,SujaySKumar/bedrock,elin-moco/bedrock,jacshfr/mozilla-bedrock,l-hedgehog/bedrock,alexgibson/bedrock,CSCI-462-01-2017/bedrock,elin-moco/bedrock,elin-moco/bedrock,sgarrity/bedrock,ckprice/bedrock,gauthierm/bedrock,davidwboswell/documentation_autoresponse,MichaelKohler/bedrock,mozilla/bedrock,chirilo/bedrock,malena/bedrock,petabyte/bedrock,amjadm61/bedrock,hoosteeno/bedrock,pmclanahan/bedrock,yglazko/bedrock,yglazko/bedrock,malena/bedrock,SujaySKumar/bedrock,craigcook/bedrock,amjadm61/bedrock,jpetto/bedrock,SujaySKumar/bedrock,andreadelrio/bedrock,davidwboswell/documentation_autoresponse,mozilla/mwc,kyoshino/bedrock,mmmavis/bedrock,petabyte/bedrock,hoosteeno/bedrock,jgmize/bedrock,rishiloyola/bedrock,craigcook/bedrock,andreadelrio/bedrock,schalkneethling/bedrock,TheJJ100100/bedrock,analytics-pros/mozilla-bedrock,mozilla/bedrock,mozilla/mwc,petabyte/bedrock,ericawright/bedrock,mermi/bedrock,ckprice/bedrock,mahinthjoe/bedrock,marcoscaceres/bedrock,sgarrity/bedrock,mermi/bedrock,pmclanahan/bedrock,petabyte/bedrock,pascalchevrel/bedrock,mermi/bedrock,jpetto/bedrock,gauthierm/bedrock,mahinthjoe/bedrock,ckprice/bedrock,glogiotatidis/bedrock,kyoshino/bedrock,mmmavis/lightbeam-bedrock-website,marcoscaceres/bedrock,mkmelin/bedrock,mkmelin/bedrock,CSCI-462-01-2017/bedrock,craigcook/bedrock,jacshfr/mozilla-bedrock,bensternthal/bedrock,malena/bedrock,Jobava/bedrock,flodolo/bedrock,Jobava/bedrock,jgmize/bedrock,davidwboswell/documentation_autoresponse,mkmelin/bedrock,mahinthjoe/bedrock,analytics-pros/mozilla-bedrock,Sancus/bedrock,davehunt/bedrock,flodolo/bedrock,amjadm61/bedrock,TheJJ100100/bedrock,pmclanahan/bedrock,rishiloyola/bedrock,mmmavis/bedrock,dudepare/bedrock,sylvestre/bedrock,jgmize/bedrock,hoosteeno/bedrock,kyoshino/bedrock,gerv/bedrock,davehunt/bedrock
|
from django.conf.urls.defaults import *
from mozorg.util import page
import views
urlpatterns = patterns('',
page('', 'persona/persona.html'),
page('about', 'persona/about.html'),
page('privacy-policy', 'persona/privacy-policy.html'),
page('terms-of-service', 'persona/terms-of-service.html'),
page('developer-faq', 'persona/developer-faq.html')
)
Remove unnecessary 'import views' line
|
from django.conf.urls.defaults import *
from mozorg.util import page
urlpatterns = patterns('',
page('', 'persona/persona.html'),
page('about', 'persona/about.html'),
page('privacy-policy', 'persona/privacy-policy.html'),
page('terms-of-service', 'persona/terms-of-service.html'),
page('developer-faq', 'persona/developer-faq.html')
)
|
<commit_before>from django.conf.urls.defaults import *
from mozorg.util import page
import views
urlpatterns = patterns('',
page('', 'persona/persona.html'),
page('about', 'persona/about.html'),
page('privacy-policy', 'persona/privacy-policy.html'),
page('terms-of-service', 'persona/terms-of-service.html'),
page('developer-faq', 'persona/developer-faq.html')
)
<commit_msg>Remove unnecessary 'import views' line<commit_after>
|
from django.conf.urls.defaults import *
from mozorg.util import page
urlpatterns = patterns('',
page('', 'persona/persona.html'),
page('about', 'persona/about.html'),
page('privacy-policy', 'persona/privacy-policy.html'),
page('terms-of-service', 'persona/terms-of-service.html'),
page('developer-faq', 'persona/developer-faq.html')
)
|
from django.conf.urls.defaults import *
from mozorg.util import page
import views
urlpatterns = patterns('',
page('', 'persona/persona.html'),
page('about', 'persona/about.html'),
page('privacy-policy', 'persona/privacy-policy.html'),
page('terms-of-service', 'persona/terms-of-service.html'),
page('developer-faq', 'persona/developer-faq.html')
)
Remove unnecessary 'import views' linefrom django.conf.urls.defaults import *
from mozorg.util import page
urlpatterns = patterns('',
page('', 'persona/persona.html'),
page('about', 'persona/about.html'),
page('privacy-policy', 'persona/privacy-policy.html'),
page('terms-of-service', 'persona/terms-of-service.html'),
page('developer-faq', 'persona/developer-faq.html')
)
|
<commit_before>from django.conf.urls.defaults import *
from mozorg.util import page
import views
urlpatterns = patterns('',
page('', 'persona/persona.html'),
page('about', 'persona/about.html'),
page('privacy-policy', 'persona/privacy-policy.html'),
page('terms-of-service', 'persona/terms-of-service.html'),
page('developer-faq', 'persona/developer-faq.html')
)
<commit_msg>Remove unnecessary 'import views' line<commit_after>from django.conf.urls.defaults import *
from mozorg.util import page
urlpatterns = patterns('',
page('', 'persona/persona.html'),
page('about', 'persona/about.html'),
page('privacy-policy', 'persona/privacy-policy.html'),
page('terms-of-service', 'persona/terms-of-service.html'),
page('developer-faq', 'persona/developer-faq.html')
)
|
414c8fa0a5576645831d58c8fa1285c9aef3610d
|
conditional/blueprints/intro_evals.py
|
conditional/blueprints/intro_evals.py
|
from flask import Blueprint
from flask import render_template
from flask import request
intro_evals_bp = Blueprint('intro_evals_bp', __name__)
@intro_evals_bp.route('/intro_evals/')
def display_intro_evals():
# get user data
user_name = request.headers.get('x-webauth-user')
members = [
{
'name': "Liam Middlebrook",
'packet_due': '2015-12-23',
'eval_date': '2016-02-13',
'signatures_missed': 3,
'committee_meetings': 24,
'committee_meetings_passed': False,
'house_meetings_missed': 0,
'house_meetings_comments': "",
'technical_seminars': "Seminar 1\nSeminar 2",
'techincal_seminars_passed': True,
'social_events': "",
'freshmen_project': False,
'comments': "please don't fail me",
'result': 'Pending'
}
]
# return names in 'first last (username)' format
return render_template('intro_evals.html',
username = user_name,
members = members)
|
from flask import Blueprint
from flask import render_template
from flask import request
intro_evals_bp = Blueprint('intro_evals_bp', __name__)
@intro_evals_bp.route('/intro_evals/')
def display_intro_evals():
# get user data
user_name = request.headers.get('x-webauth-user')
members = [
{
'name': "Liam Middlebrook",
'packet_due': '2015-12-23',
'eval_date': '2016-02-13',
'signatures_missed': 3,
'committee_meetings': 24,
'committee_meetings_passed': False,
'house_meetings_missed': [{'date': "aprial fools fayas ads", 'reason': "I was playing videogames"}],
'technical_seminars': [{'date': "halloween", 'name': 'how to play videogames with liam'}],
'social_events': "",
'freshmen_project': False,
'comments': "please don't fail me",
'result': 'Pending'
}
]
# return names in 'first last (username)' format
return render_template('intro_evals.html',
username = user_name,
members = members)
|
Edit intro evals data route
|
Edit intro evals data route
|
Python
|
mit
|
RamZallan/conditional,ComputerScienceHouse/conditional,RamZallan/conditional,RamZallan/conditional,ComputerScienceHouse/conditional,ComputerScienceHouse/conditional
|
from flask import Blueprint
from flask import render_template
from flask import request
intro_evals_bp = Blueprint('intro_evals_bp', __name__)
@intro_evals_bp.route('/intro_evals/')
def display_intro_evals():
# get user data
user_name = request.headers.get('x-webauth-user')
members = [
{
'name': "Liam Middlebrook",
'packet_due': '2015-12-23',
'eval_date': '2016-02-13',
'signatures_missed': 3,
'committee_meetings': 24,
'committee_meetings_passed': False,
'house_meetings_missed': 0,
'house_meetings_comments': "",
'technical_seminars': "Seminar 1\nSeminar 2",
'techincal_seminars_passed': True,
'social_events': "",
'freshmen_project': False,
'comments': "please don't fail me",
'result': 'Pending'
}
]
# return names in 'first last (username)' format
return render_template('intro_evals.html',
username = user_name,
members = members)
Edit intro evals data route
|
from flask import Blueprint
from flask import render_template
from flask import request
intro_evals_bp = Blueprint('intro_evals_bp', __name__)
@intro_evals_bp.route('/intro_evals/')
def display_intro_evals():
# get user data
user_name = request.headers.get('x-webauth-user')
members = [
{
'name': "Liam Middlebrook",
'packet_due': '2015-12-23',
'eval_date': '2016-02-13',
'signatures_missed': 3,
'committee_meetings': 24,
'committee_meetings_passed': False,
'house_meetings_missed': [{'date': "aprial fools fayas ads", 'reason': "I was playing videogames"}],
'technical_seminars': [{'date': "halloween", 'name': 'how to play videogames with liam'}],
'social_events': "",
'freshmen_project': False,
'comments': "please don't fail me",
'result': 'Pending'
}
]
# return names in 'first last (username)' format
return render_template('intro_evals.html',
username = user_name,
members = members)
|
<commit_before>from flask import Blueprint
from flask import render_template
from flask import request
intro_evals_bp = Blueprint('intro_evals_bp', __name__)
@intro_evals_bp.route('/intro_evals/')
def display_intro_evals():
# get user data
user_name = request.headers.get('x-webauth-user')
members = [
{
'name': "Liam Middlebrook",
'packet_due': '2015-12-23',
'eval_date': '2016-02-13',
'signatures_missed': 3,
'committee_meetings': 24,
'committee_meetings_passed': False,
'house_meetings_missed': 0,
'house_meetings_comments': "",
'technical_seminars': "Seminar 1\nSeminar 2",
'techincal_seminars_passed': True,
'social_events': "",
'freshmen_project': False,
'comments': "please don't fail me",
'result': 'Pending'
}
]
# return names in 'first last (username)' format
return render_template('intro_evals.html',
username = user_name,
members = members)
<commit_msg>Edit intro evals data route<commit_after>
|
from flask import Blueprint
from flask import render_template
from flask import request
intro_evals_bp = Blueprint('intro_evals_bp', __name__)
@intro_evals_bp.route('/intro_evals/')
def display_intro_evals():
# get user data
user_name = request.headers.get('x-webauth-user')
members = [
{
'name': "Liam Middlebrook",
'packet_due': '2015-12-23',
'eval_date': '2016-02-13',
'signatures_missed': 3,
'committee_meetings': 24,
'committee_meetings_passed': False,
'house_meetings_missed': [{'date': "aprial fools fayas ads", 'reason': "I was playing videogames"}],
'technical_seminars': [{'date': "halloween", 'name': 'how to play videogames with liam'}],
'social_events': "",
'freshmen_project': False,
'comments': "please don't fail me",
'result': 'Pending'
}
]
# return names in 'first last (username)' format
return render_template('intro_evals.html',
username = user_name,
members = members)
|
from flask import Blueprint
from flask import render_template
from flask import request
intro_evals_bp = Blueprint('intro_evals_bp', __name__)
@intro_evals_bp.route('/intro_evals/')
def display_intro_evals():
# get user data
user_name = request.headers.get('x-webauth-user')
members = [
{
'name': "Liam Middlebrook",
'packet_due': '2015-12-23',
'eval_date': '2016-02-13',
'signatures_missed': 3,
'committee_meetings': 24,
'committee_meetings_passed': False,
'house_meetings_missed': 0,
'house_meetings_comments': "",
'technical_seminars': "Seminar 1\nSeminar 2",
'techincal_seminars_passed': True,
'social_events': "",
'freshmen_project': False,
'comments': "please don't fail me",
'result': 'Pending'
}
]
# return names in 'first last (username)' format
return render_template('intro_evals.html',
username = user_name,
members = members)
Edit intro evals data routefrom flask import Blueprint
from flask import render_template
from flask import request
intro_evals_bp = Blueprint('intro_evals_bp', __name__)
@intro_evals_bp.route('/intro_evals/')
def display_intro_evals():
# get user data
user_name = request.headers.get('x-webauth-user')
members = [
{
'name': "Liam Middlebrook",
'packet_due': '2015-12-23',
'eval_date': '2016-02-13',
'signatures_missed': 3,
'committee_meetings': 24,
'committee_meetings_passed': False,
'house_meetings_missed': [{'date': "aprial fools fayas ads", 'reason': "I was playing videogames"}],
'technical_seminars': [{'date': "halloween", 'name': 'how to play videogames with liam'}],
'social_events': "",
'freshmen_project': False,
'comments': "please don't fail me",
'result': 'Pending'
}
]
# return names in 'first last (username)' format
return render_template('intro_evals.html',
username = user_name,
members = members)
|
<commit_before>from flask import Blueprint
from flask import render_template
from flask import request
intro_evals_bp = Blueprint('intro_evals_bp', __name__)
@intro_evals_bp.route('/intro_evals/')
def display_intro_evals():
# get user data
user_name = request.headers.get('x-webauth-user')
members = [
{
'name': "Liam Middlebrook",
'packet_due': '2015-12-23',
'eval_date': '2016-02-13',
'signatures_missed': 3,
'committee_meetings': 24,
'committee_meetings_passed': False,
'house_meetings_missed': 0,
'house_meetings_comments': "",
'technical_seminars': "Seminar 1\nSeminar 2",
'techincal_seminars_passed': True,
'social_events': "",
'freshmen_project': False,
'comments': "please don't fail me",
'result': 'Pending'
}
]
# return names in 'first last (username)' format
return render_template('intro_evals.html',
username = user_name,
members = members)
<commit_msg>Edit intro evals data route<commit_after>from flask import Blueprint
from flask import render_template
from flask import request
intro_evals_bp = Blueprint('intro_evals_bp', __name__)
@intro_evals_bp.route('/intro_evals/')
def display_intro_evals():
# get user data
user_name = request.headers.get('x-webauth-user')
members = [
{
'name': "Liam Middlebrook",
'packet_due': '2015-12-23',
'eval_date': '2016-02-13',
'signatures_missed': 3,
'committee_meetings': 24,
'committee_meetings_passed': False,
'house_meetings_missed': [{'date': "aprial fools fayas ads", 'reason': "I was playing videogames"}],
'technical_seminars': [{'date': "halloween", 'name': 'how to play videogames with liam'}],
'social_events': "",
'freshmen_project': False,
'comments': "please don't fail me",
'result': 'Pending'
}
]
# return names in 'first last (username)' format
return render_template('intro_evals.html',
username = user_name,
members = members)
|
3345d3d3d94fea39d6a670c5f92d87a1faadd8d7
|
tests/TestPluginManager.py
|
tests/TestPluginManager.py
|
import socket
import time
from threading import Event
from unittest import TestCase
from PluginManager import PluginManager
class TestPluginManager(TestCase):
def test_stop(self):
"""Test connecting to plugin's port, stopping PluginManager."""
class Plugin:
"""Mock plugin, uses random available port."""
def __init__(self):
sock = socket.socket()
sock.bind(('', 0)) # bind to any available port
self._port = sock.getsockname()[1]
sock.close()
self.run_called = Event()
def get_port(self):
return self._port
def run(self, sock, address, session):
self.run_called.set()
plugin = Plugin()
plugin_manager = PluginManager(plugin, lambda: None)
plugin_manager.start()
time.sleep(0.01)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost', plugin.get_port()))
sock.close()
time.sleep(0.01)
self.assertTrue(plugin.run_called.is_set())
plugin_manager.stop()
plugin_manager.join()
self.assertFalse(plugin_manager.is_alive())
|
import socket
import time
from threading import Event
from unittest import TestCase
from honeypot.PluginManager import PluginManager
class TestPluginManager(TestCase):
def test_stop(self):
"""Test connecting to plugin's port, stopping PluginManager."""
class Plugin:
"""Mock plugin, uses random available port."""
def __init__(self):
sock = socket.socket()
sock.bind(('', 0)) # bind to any available port
self._port = sock.getsockname()[1]
sock.close()
self.run_called = Event()
def get_port(self):
return self._port
def run(self, sock, address, session):
self.run_called.set()
plugin = Plugin()
plugin_manager = PluginManager(plugin, lambda: None)
plugin_manager.start()
time.sleep(0.01)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost', plugin.get_port()))
sock.close()
time.sleep(0.01)
self.assertTrue(plugin.run_called.is_set())
plugin_manager.stop()
plugin_manager.join()
self.assertFalse(plugin_manager.is_alive())
|
Fix imports in plugin manager test to work with nosetests
|
Fix imports in plugin manager test to work with nosetests
|
Python
|
mit
|
theplue/honeypot,ckaz18/honeypot,coyle5280/honeypot,coyle5280/honeypot,laurenmalone/honeypot,theplue/honeypot,laurenmalone/honeypot,laurenmalone/honeypot,coyle5280/honeypot,theplue/honeypot,coyle5280/honeypot,ckaz18/honeypot,ckaz18/honeypot,laurenmalone/honeypot,theplue/honeypot,ckaz18/honeypot
|
import socket
import time
from threading import Event
from unittest import TestCase
from PluginManager import PluginManager
class TestPluginManager(TestCase):
def test_stop(self):
"""Test connecting to plugin's port, stopping PluginManager."""
class Plugin:
"""Mock plugin, uses random available port."""
def __init__(self):
sock = socket.socket()
sock.bind(('', 0)) # bind to any available port
self._port = sock.getsockname()[1]
sock.close()
self.run_called = Event()
def get_port(self):
return self._port
def run(self, sock, address, session):
self.run_called.set()
plugin = Plugin()
plugin_manager = PluginManager(plugin, lambda: None)
plugin_manager.start()
time.sleep(0.01)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost', plugin.get_port()))
sock.close()
time.sleep(0.01)
self.assertTrue(plugin.run_called.is_set())
plugin_manager.stop()
plugin_manager.join()
self.assertFalse(plugin_manager.is_alive())
Fix imports in plugin manager test to work with nosetests
|
import socket
import time
from threading import Event
from unittest import TestCase
from honeypot.PluginManager import PluginManager
class TestPluginManager(TestCase):
def test_stop(self):
"""Test connecting to plugin's port, stopping PluginManager."""
class Plugin:
"""Mock plugin, uses random available port."""
def __init__(self):
sock = socket.socket()
sock.bind(('', 0)) # bind to any available port
self._port = sock.getsockname()[1]
sock.close()
self.run_called = Event()
def get_port(self):
return self._port
def run(self, sock, address, session):
self.run_called.set()
plugin = Plugin()
plugin_manager = PluginManager(plugin, lambda: None)
plugin_manager.start()
time.sleep(0.01)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost', plugin.get_port()))
sock.close()
time.sleep(0.01)
self.assertTrue(plugin.run_called.is_set())
plugin_manager.stop()
plugin_manager.join()
self.assertFalse(plugin_manager.is_alive())
|
<commit_before>import socket
import time
from threading import Event
from unittest import TestCase
from PluginManager import PluginManager
class TestPluginManager(TestCase):
def test_stop(self):
"""Test connecting to plugin's port, stopping PluginManager."""
class Plugin:
"""Mock plugin, uses random available port."""
def __init__(self):
sock = socket.socket()
sock.bind(('', 0)) # bind to any available port
self._port = sock.getsockname()[1]
sock.close()
self.run_called = Event()
def get_port(self):
return self._port
def run(self, sock, address, session):
self.run_called.set()
plugin = Plugin()
plugin_manager = PluginManager(plugin, lambda: None)
plugin_manager.start()
time.sleep(0.01)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost', plugin.get_port()))
sock.close()
time.sleep(0.01)
self.assertTrue(plugin.run_called.is_set())
plugin_manager.stop()
plugin_manager.join()
self.assertFalse(plugin_manager.is_alive())
<commit_msg>Fix imports in plugin manager test to work with nosetests<commit_after>
|
import socket
import time
from threading import Event
from unittest import TestCase
from honeypot.PluginManager import PluginManager
class TestPluginManager(TestCase):
def test_stop(self):
"""Test connecting to plugin's port, stopping PluginManager."""
class Plugin:
"""Mock plugin, uses random available port."""
def __init__(self):
sock = socket.socket()
sock.bind(('', 0)) # bind to any available port
self._port = sock.getsockname()[1]
sock.close()
self.run_called = Event()
def get_port(self):
return self._port
def run(self, sock, address, session):
self.run_called.set()
plugin = Plugin()
plugin_manager = PluginManager(plugin, lambda: None)
plugin_manager.start()
time.sleep(0.01)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost', plugin.get_port()))
sock.close()
time.sleep(0.01)
self.assertTrue(plugin.run_called.is_set())
plugin_manager.stop()
plugin_manager.join()
self.assertFalse(plugin_manager.is_alive())
|
import socket
import time
from threading import Event
from unittest import TestCase
from PluginManager import PluginManager
class TestPluginManager(TestCase):
def test_stop(self):
"""Test connecting to plugin's port, stopping PluginManager."""
class Plugin:
"""Mock plugin, uses random available port."""
def __init__(self):
sock = socket.socket()
sock.bind(('', 0)) # bind to any available port
self._port = sock.getsockname()[1]
sock.close()
self.run_called = Event()
def get_port(self):
return self._port
def run(self, sock, address, session):
self.run_called.set()
plugin = Plugin()
plugin_manager = PluginManager(plugin, lambda: None)
plugin_manager.start()
time.sleep(0.01)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost', plugin.get_port()))
sock.close()
time.sleep(0.01)
self.assertTrue(plugin.run_called.is_set())
plugin_manager.stop()
plugin_manager.join()
self.assertFalse(plugin_manager.is_alive())
Fix imports in plugin manager test to work with nosetestsimport socket
import time
from threading import Event
from unittest import TestCase
from honeypot.PluginManager import PluginManager
class TestPluginManager(TestCase):
def test_stop(self):
"""Test connecting to plugin's port, stopping PluginManager."""
class Plugin:
"""Mock plugin, uses random available port."""
def __init__(self):
sock = socket.socket()
sock.bind(('', 0)) # bind to any available port
self._port = sock.getsockname()[1]
sock.close()
self.run_called = Event()
def get_port(self):
return self._port
def run(self, sock, address, session):
self.run_called.set()
plugin = Plugin()
plugin_manager = PluginManager(plugin, lambda: None)
plugin_manager.start()
time.sleep(0.01)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost', plugin.get_port()))
sock.close()
time.sleep(0.01)
self.assertTrue(plugin.run_called.is_set())
plugin_manager.stop()
plugin_manager.join()
self.assertFalse(plugin_manager.is_alive())
|
<commit_before>import socket
import time
from threading import Event
from unittest import TestCase
from PluginManager import PluginManager
class TestPluginManager(TestCase):
def test_stop(self):
"""Test connecting to plugin's port, stopping PluginManager."""
class Plugin:
"""Mock plugin, uses random available port."""
def __init__(self):
sock = socket.socket()
sock.bind(('', 0)) # bind to any available port
self._port = sock.getsockname()[1]
sock.close()
self.run_called = Event()
def get_port(self):
return self._port
def run(self, sock, address, session):
self.run_called.set()
plugin = Plugin()
plugin_manager = PluginManager(plugin, lambda: None)
plugin_manager.start()
time.sleep(0.01)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost', plugin.get_port()))
sock.close()
time.sleep(0.01)
self.assertTrue(plugin.run_called.is_set())
plugin_manager.stop()
plugin_manager.join()
self.assertFalse(plugin_manager.is_alive())
<commit_msg>Fix imports in plugin manager test to work with nosetests<commit_after>import socket
import time
from threading import Event
from unittest import TestCase
from honeypot.PluginManager import PluginManager
class TestPluginManager(TestCase):
def test_stop(self):
"""Test connecting to plugin's port, stopping PluginManager."""
class Plugin:
"""Mock plugin, uses random available port."""
def __init__(self):
sock = socket.socket()
sock.bind(('', 0)) # bind to any available port
self._port = sock.getsockname()[1]
sock.close()
self.run_called = Event()
def get_port(self):
return self._port
def run(self, sock, address, session):
self.run_called.set()
plugin = Plugin()
plugin_manager = PluginManager(plugin, lambda: None)
plugin_manager.start()
time.sleep(0.01)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost', plugin.get_port()))
sock.close()
time.sleep(0.01)
self.assertTrue(plugin.run_called.is_set())
plugin_manager.stop()
plugin_manager.join()
self.assertFalse(plugin_manager.is_alive())
|
1be4fcb077d63155e6c0beed9e4138fa377fa067
|
ColorHistograms-python/color_histogram.py
|
ColorHistograms-python/color_histogram.py
|
from color_histogram_cuda import histogram
print histogram('../data/spotted_ball_3500.png', 16)
|
import sys
from color_histogram_cuda import histogram
print histogram(sys.argv[1], 16)
|
Read file name from command line in python wrapper
|
Read file name from command line in python wrapper
|
Python
|
bsd-3-clause
|
kwadraterry/GPGPU-LUT,kwadraterry/GPGPU-LUT,kwadraterry/GPGPU-LUT,kwadraterry/GPGPU-LUT,kwadraterry/GPGPU-LUT
|
from color_histogram_cuda import histogram
print histogram('../data/spotted_ball_3500.png', 16)Read file name from command line in python wrapper
|
import sys
from color_histogram_cuda import histogram
print histogram(sys.argv[1], 16)
|
<commit_before>from color_histogram_cuda import histogram
print histogram('../data/spotted_ball_3500.png', 16)<commit_msg>Read file name from command line in python wrapper<commit_after>
|
import sys
from color_histogram_cuda import histogram
print histogram(sys.argv[1], 16)
|
from color_histogram_cuda import histogram
print histogram('../data/spotted_ball_3500.png', 16)Read file name from command line in python wrapperimport sys
from color_histogram_cuda import histogram
print histogram(sys.argv[1], 16)
|
<commit_before>from color_histogram_cuda import histogram
print histogram('../data/spotted_ball_3500.png', 16)<commit_msg>Read file name from command line in python wrapper<commit_after>import sys
from color_histogram_cuda import histogram
print histogram(sys.argv[1], 16)
|
9faf0d224c19b888aa63267adf26a4937b9c60c3
|
tempest/api/compute/servers/test_availability_zone.py
|
tempest/api/compute/servers/test_availability_zone.py
|
# Copyright 2014 NEC Corporation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from tempest.api.compute import base
from tempest import test
class AZV2TestJSON(base.BaseV2ComputeTest):
"""Tests Availability Zone API List"""
@classmethod
def setup_clients(cls):
super(AZV2TestJSON, cls).setup_clients()
cls.client = cls.availability_zone_client
@test.idempotent_id('a8333aa2-205c-449f-a828-d38c2489bf25')
def test_get_availability_zone_list_with_non_admin_user(self):
# List of availability zone with non-administrator user
availability_zone = self.client.list_availability_zones()
self.assertTrue(len(availability_zone['availabilityZoneInfo']) > 0)
|
# Copyright 2014 NEC Corporation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from tempest.api.compute import base
from tempest import test
class AZV2TestJSON(base.BaseV2ComputeTest):
"""Tests Availability Zone API List"""
@classmethod
def setup_clients(cls):
super(AZV2TestJSON, cls).setup_clients()
cls.client = cls.availability_zone_client
@test.idempotent_id('a8333aa2-205c-449f-a828-d38c2489bf25')
def test_get_availability_zone_list_with_non_admin_user(self):
# List of availability zone with non-administrator user
availability_zone = self.client.list_availability_zones()
self.assertGreater(len(availability_zone['availabilityZoneInfo']), 0)
|
Use assertGreater(len(x), 0) over assertTrue(len(x) > 0)
|
Use assertGreater(len(x), 0) over assertTrue(len(x) > 0)
assertGreater provides a nicer error message if it fails.
Change-Id: I2c13d28c54ae3a9ff562448e7a16ab54d71b29b5
|
Python
|
apache-2.0
|
masayukig/tempest,vedujoshi/tempest,cisco-openstack/tempest,Tesora/tesora-tempest,openstack/tempest,sebrandon1/tempest,Tesora/tesora-tempest,sebrandon1/tempest,Juniper/tempest,Juniper/tempest,cisco-openstack/tempest,vedujoshi/tempest,masayukig/tempest,openstack/tempest
|
# Copyright 2014 NEC Corporation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from tempest.api.compute import base
from tempest import test
class AZV2TestJSON(base.BaseV2ComputeTest):
"""Tests Availability Zone API List"""
@classmethod
def setup_clients(cls):
super(AZV2TestJSON, cls).setup_clients()
cls.client = cls.availability_zone_client
@test.idempotent_id('a8333aa2-205c-449f-a828-d38c2489bf25')
def test_get_availability_zone_list_with_non_admin_user(self):
# List of availability zone with non-administrator user
availability_zone = self.client.list_availability_zones()
self.assertTrue(len(availability_zone['availabilityZoneInfo']) > 0)
Use assertGreater(len(x), 0) over assertTrue(len(x) > 0)
assertGreater provides a nicer error message if it fails.
Change-Id: I2c13d28c54ae3a9ff562448e7a16ab54d71b29b5
|
# Copyright 2014 NEC Corporation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from tempest.api.compute import base
from tempest import test
class AZV2TestJSON(base.BaseV2ComputeTest):
"""Tests Availability Zone API List"""
@classmethod
def setup_clients(cls):
super(AZV2TestJSON, cls).setup_clients()
cls.client = cls.availability_zone_client
@test.idempotent_id('a8333aa2-205c-449f-a828-d38c2489bf25')
def test_get_availability_zone_list_with_non_admin_user(self):
# List of availability zone with non-administrator user
availability_zone = self.client.list_availability_zones()
self.assertGreater(len(availability_zone['availabilityZoneInfo']), 0)
|
<commit_before># Copyright 2014 NEC Corporation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from tempest.api.compute import base
from tempest import test
class AZV2TestJSON(base.BaseV2ComputeTest):
"""Tests Availability Zone API List"""
@classmethod
def setup_clients(cls):
super(AZV2TestJSON, cls).setup_clients()
cls.client = cls.availability_zone_client
@test.idempotent_id('a8333aa2-205c-449f-a828-d38c2489bf25')
def test_get_availability_zone_list_with_non_admin_user(self):
# List of availability zone with non-administrator user
availability_zone = self.client.list_availability_zones()
self.assertTrue(len(availability_zone['availabilityZoneInfo']) > 0)
<commit_msg>Use assertGreater(len(x), 0) over assertTrue(len(x) > 0)
assertGreater provides a nicer error message if it fails.
Change-Id: I2c13d28c54ae3a9ff562448e7a16ab54d71b29b5<commit_after>
|
# Copyright 2014 NEC Corporation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from tempest.api.compute import base
from tempest import test
class AZV2TestJSON(base.BaseV2ComputeTest):
"""Tests Availability Zone API List"""
@classmethod
def setup_clients(cls):
super(AZV2TestJSON, cls).setup_clients()
cls.client = cls.availability_zone_client
@test.idempotent_id('a8333aa2-205c-449f-a828-d38c2489bf25')
def test_get_availability_zone_list_with_non_admin_user(self):
# List of availability zone with non-administrator user
availability_zone = self.client.list_availability_zones()
self.assertGreater(len(availability_zone['availabilityZoneInfo']), 0)
|
# Copyright 2014 NEC Corporation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from tempest.api.compute import base
from tempest import test
class AZV2TestJSON(base.BaseV2ComputeTest):
"""Tests Availability Zone API List"""
@classmethod
def setup_clients(cls):
super(AZV2TestJSON, cls).setup_clients()
cls.client = cls.availability_zone_client
@test.idempotent_id('a8333aa2-205c-449f-a828-d38c2489bf25')
def test_get_availability_zone_list_with_non_admin_user(self):
# List of availability zone with non-administrator user
availability_zone = self.client.list_availability_zones()
self.assertTrue(len(availability_zone['availabilityZoneInfo']) > 0)
Use assertGreater(len(x), 0) over assertTrue(len(x) > 0)
assertGreater provides a nicer error message if it fails.
Change-Id: I2c13d28c54ae3a9ff562448e7a16ab54d71b29b5# Copyright 2014 NEC Corporation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from tempest.api.compute import base
from tempest import test
class AZV2TestJSON(base.BaseV2ComputeTest):
"""Tests Availability Zone API List"""
@classmethod
def setup_clients(cls):
super(AZV2TestJSON, cls).setup_clients()
cls.client = cls.availability_zone_client
@test.idempotent_id('a8333aa2-205c-449f-a828-d38c2489bf25')
def test_get_availability_zone_list_with_non_admin_user(self):
# List of availability zone with non-administrator user
availability_zone = self.client.list_availability_zones()
self.assertGreater(len(availability_zone['availabilityZoneInfo']), 0)
|
<commit_before># Copyright 2014 NEC Corporation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from tempest.api.compute import base
from tempest import test
class AZV2TestJSON(base.BaseV2ComputeTest):
"""Tests Availability Zone API List"""
@classmethod
def setup_clients(cls):
super(AZV2TestJSON, cls).setup_clients()
cls.client = cls.availability_zone_client
@test.idempotent_id('a8333aa2-205c-449f-a828-d38c2489bf25')
def test_get_availability_zone_list_with_non_admin_user(self):
# List of availability zone with non-administrator user
availability_zone = self.client.list_availability_zones()
self.assertTrue(len(availability_zone['availabilityZoneInfo']) > 0)
<commit_msg>Use assertGreater(len(x), 0) over assertTrue(len(x) > 0)
assertGreater provides a nicer error message if it fails.
Change-Id: I2c13d28c54ae3a9ff562448e7a16ab54d71b29b5<commit_after># Copyright 2014 NEC Corporation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from tempest.api.compute import base
from tempest import test
class AZV2TestJSON(base.BaseV2ComputeTest):
"""Tests Availability Zone API List"""
@classmethod
def setup_clients(cls):
super(AZV2TestJSON, cls).setup_clients()
cls.client = cls.availability_zone_client
@test.idempotent_id('a8333aa2-205c-449f-a828-d38c2489bf25')
def test_get_availability_zone_list_with_non_admin_user(self):
# List of availability zone with non-administrator user
availability_zone = self.client.list_availability_zones()
self.assertGreater(len(availability_zone['availabilityZoneInfo']), 0)
|
d1b28ef809dbe18c79f296e6fc17c4ee9b3d153b
|
docs/conf.py
|
docs/conf.py
|
# -*- coding: utf-8 -*-
#
# This file is execfile()d with the current directory set to its containing
# directory.
import sys, os
sys.path.append(os.path.join(os.path.abspath('.'), '_ext'))
sys.path.append(os.path.dirname(os.path.abspath('.')))
import analytical
# -- General configuration -----------------------------------------------------
project = u'django-analytical'
copyright = u'2011, Joost Cassee <joost@cassee.net>'
release = analytical.__version__
# The short X.Y version.
version = release.rsplit('.', 1)[0]
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'local']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
add_function_parentheses = True
pygments_style = 'sphinx'
intersphinx_mapping = {
'http://docs.python.org/2.7': None,
'http://docs.djangoproject.com/en/1.6': 'http://docs.djangoproject.com/en/1.6/_objects/',
}
# -- Options for HTML output ---------------------------------------------------
html_theme = 'default'
htmlhelp_basename = 'analyticaldoc'
# -- Options for LaTeX output --------------------------------------------------
latex_documents = [
('index', 'django-analytical.tex', u'Documentation for django-analytical',
u'Joost Cassee', 'manual'),
]
|
# -*- coding: utf-8 -*-
#
# This file is execfile()d with the current directory set to its containing
# directory.
import sys, os
sys.path.append(os.path.join(os.path.abspath('.'), '_ext'))
sys.path.append(os.path.dirname(os.path.abspath('.')))
import analytical
# -- General configuration -----------------------------------------------------
project = u'django-analytical'
copyright = u'2011, Joost Cassee <joost@cassee.net>'
release = analytical.__version__
# The short X.Y version.
version = release.rsplit('.', 1)[0]
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'local']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
add_function_parentheses = True
pygments_style = 'sphinx'
intersphinx_mapping = {
'http://docs.python.org/2.7': None,
'http://docs.djangoproject.com/en/1.7': 'http://docs.djangoproject.com/en/1.7/_objects/',
}
# -- Options for HTML output ---------------------------------------------------
html_theme = 'default'
htmlhelp_basename = 'analyticaldoc'
# -- Options for LaTeX output --------------------------------------------------
latex_documents = [
('index', 'django-analytical.tex', u'Documentation for django-analytical',
u'Joost Cassee', 'manual'),
]
|
Update intersphinx links to Django 1.7
|
Update intersphinx links to Django 1.7
|
Python
|
mit
|
apocquet/django-analytical,ChristosChristofidis/django-analytical,bittner/django-analytical,ericdwang/django-analytical,machtfit/django-analytical,jcassee/django-analytical,pjdelport/django-analytical
|
# -*- coding: utf-8 -*-
#
# This file is execfile()d with the current directory set to its containing
# directory.
import sys, os
sys.path.append(os.path.join(os.path.abspath('.'), '_ext'))
sys.path.append(os.path.dirname(os.path.abspath('.')))
import analytical
# -- General configuration -----------------------------------------------------
project = u'django-analytical'
copyright = u'2011, Joost Cassee <joost@cassee.net>'
release = analytical.__version__
# The short X.Y version.
version = release.rsplit('.', 1)[0]
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'local']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
add_function_parentheses = True
pygments_style = 'sphinx'
intersphinx_mapping = {
'http://docs.python.org/2.7': None,
'http://docs.djangoproject.com/en/1.6': 'http://docs.djangoproject.com/en/1.6/_objects/',
}
# -- Options for HTML output ---------------------------------------------------
html_theme = 'default'
htmlhelp_basename = 'analyticaldoc'
# -- Options for LaTeX output --------------------------------------------------
latex_documents = [
('index', 'django-analytical.tex', u'Documentation for django-analytical',
u'Joost Cassee', 'manual'),
]
Update intersphinx links to Django 1.7
|
# -*- coding: utf-8 -*-
#
# This file is execfile()d with the current directory set to its containing
# directory.
import sys, os
sys.path.append(os.path.join(os.path.abspath('.'), '_ext'))
sys.path.append(os.path.dirname(os.path.abspath('.')))
import analytical
# -- General configuration -----------------------------------------------------
project = u'django-analytical'
copyright = u'2011, Joost Cassee <joost@cassee.net>'
release = analytical.__version__
# The short X.Y version.
version = release.rsplit('.', 1)[0]
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'local']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
add_function_parentheses = True
pygments_style = 'sphinx'
intersphinx_mapping = {
'http://docs.python.org/2.7': None,
'http://docs.djangoproject.com/en/1.7': 'http://docs.djangoproject.com/en/1.7/_objects/',
}
# -- Options for HTML output ---------------------------------------------------
html_theme = 'default'
htmlhelp_basename = 'analyticaldoc'
# -- Options for LaTeX output --------------------------------------------------
latex_documents = [
('index', 'django-analytical.tex', u'Documentation for django-analytical',
u'Joost Cassee', 'manual'),
]
|
<commit_before># -*- coding: utf-8 -*-
#
# This file is execfile()d with the current directory set to its containing
# directory.
import sys, os
sys.path.append(os.path.join(os.path.abspath('.'), '_ext'))
sys.path.append(os.path.dirname(os.path.abspath('.')))
import analytical
# -- General configuration -----------------------------------------------------
project = u'django-analytical'
copyright = u'2011, Joost Cassee <joost@cassee.net>'
release = analytical.__version__
# The short X.Y version.
version = release.rsplit('.', 1)[0]
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'local']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
add_function_parentheses = True
pygments_style = 'sphinx'
intersphinx_mapping = {
'http://docs.python.org/2.7': None,
'http://docs.djangoproject.com/en/1.6': 'http://docs.djangoproject.com/en/1.6/_objects/',
}
# -- Options for HTML output ---------------------------------------------------
html_theme = 'default'
htmlhelp_basename = 'analyticaldoc'
# -- Options for LaTeX output --------------------------------------------------
latex_documents = [
('index', 'django-analytical.tex', u'Documentation for django-analytical',
u'Joost Cassee', 'manual'),
]
<commit_msg>Update intersphinx links to Django 1.7<commit_after>
|
# -*- coding: utf-8 -*-
#
# This file is execfile()d with the current directory set to its containing
# directory.
import sys, os
sys.path.append(os.path.join(os.path.abspath('.'), '_ext'))
sys.path.append(os.path.dirname(os.path.abspath('.')))
import analytical
# -- General configuration -----------------------------------------------------
project = u'django-analytical'
copyright = u'2011, Joost Cassee <joost@cassee.net>'
release = analytical.__version__
# The short X.Y version.
version = release.rsplit('.', 1)[0]
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'local']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
add_function_parentheses = True
pygments_style = 'sphinx'
intersphinx_mapping = {
'http://docs.python.org/2.7': None,
'http://docs.djangoproject.com/en/1.7': 'http://docs.djangoproject.com/en/1.7/_objects/',
}
# -- Options for HTML output ---------------------------------------------------
html_theme = 'default'
htmlhelp_basename = 'analyticaldoc'
# -- Options for LaTeX output --------------------------------------------------
latex_documents = [
('index', 'django-analytical.tex', u'Documentation for django-analytical',
u'Joost Cassee', 'manual'),
]
|
# -*- coding: utf-8 -*-
#
# This file is execfile()d with the current directory set to its containing
# directory.
import sys, os
sys.path.append(os.path.join(os.path.abspath('.'), '_ext'))
sys.path.append(os.path.dirname(os.path.abspath('.')))
import analytical
# -- General configuration -----------------------------------------------------
project = u'django-analytical'
copyright = u'2011, Joost Cassee <joost@cassee.net>'
release = analytical.__version__
# The short X.Y version.
version = release.rsplit('.', 1)[0]
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'local']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
add_function_parentheses = True
pygments_style = 'sphinx'
intersphinx_mapping = {
'http://docs.python.org/2.7': None,
'http://docs.djangoproject.com/en/1.6': 'http://docs.djangoproject.com/en/1.6/_objects/',
}
# -- Options for HTML output ---------------------------------------------------
html_theme = 'default'
htmlhelp_basename = 'analyticaldoc'
# -- Options for LaTeX output --------------------------------------------------
latex_documents = [
('index', 'django-analytical.tex', u'Documentation for django-analytical',
u'Joost Cassee', 'manual'),
]
Update intersphinx links to Django 1.7# -*- coding: utf-8 -*-
#
# This file is execfile()d with the current directory set to its containing
# directory.
import sys, os
sys.path.append(os.path.join(os.path.abspath('.'), '_ext'))
sys.path.append(os.path.dirname(os.path.abspath('.')))
import analytical
# -- General configuration -----------------------------------------------------
project = u'django-analytical'
copyright = u'2011, Joost Cassee <joost@cassee.net>'
release = analytical.__version__
# The short X.Y version.
version = release.rsplit('.', 1)[0]
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'local']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
add_function_parentheses = True
pygments_style = 'sphinx'
intersphinx_mapping = {
'http://docs.python.org/2.7': None,
'http://docs.djangoproject.com/en/1.7': 'http://docs.djangoproject.com/en/1.7/_objects/',
}
# -- Options for HTML output ---------------------------------------------------
html_theme = 'default'
htmlhelp_basename = 'analyticaldoc'
# -- Options for LaTeX output --------------------------------------------------
latex_documents = [
('index', 'django-analytical.tex', u'Documentation for django-analytical',
u'Joost Cassee', 'manual'),
]
|
<commit_before># -*- coding: utf-8 -*-
#
# This file is execfile()d with the current directory set to its containing
# directory.
import sys, os
sys.path.append(os.path.join(os.path.abspath('.'), '_ext'))
sys.path.append(os.path.dirname(os.path.abspath('.')))
import analytical
# -- General configuration -----------------------------------------------------
project = u'django-analytical'
copyright = u'2011, Joost Cassee <joost@cassee.net>'
release = analytical.__version__
# The short X.Y version.
version = release.rsplit('.', 1)[0]
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'local']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
add_function_parentheses = True
pygments_style = 'sphinx'
intersphinx_mapping = {
'http://docs.python.org/2.7': None,
'http://docs.djangoproject.com/en/1.6': 'http://docs.djangoproject.com/en/1.6/_objects/',
}
# -- Options for HTML output ---------------------------------------------------
html_theme = 'default'
htmlhelp_basename = 'analyticaldoc'
# -- Options for LaTeX output --------------------------------------------------
latex_documents = [
('index', 'django-analytical.tex', u'Documentation for django-analytical',
u'Joost Cassee', 'manual'),
]
<commit_msg>Update intersphinx links to Django 1.7<commit_after># -*- coding: utf-8 -*-
#
# This file is execfile()d with the current directory set to its containing
# directory.
import sys, os
sys.path.append(os.path.join(os.path.abspath('.'), '_ext'))
sys.path.append(os.path.dirname(os.path.abspath('.')))
import analytical
# -- General configuration -----------------------------------------------------
project = u'django-analytical'
copyright = u'2011, Joost Cassee <joost@cassee.net>'
release = analytical.__version__
# The short X.Y version.
version = release.rsplit('.', 1)[0]
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'local']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
add_function_parentheses = True
pygments_style = 'sphinx'
intersphinx_mapping = {
'http://docs.python.org/2.7': None,
'http://docs.djangoproject.com/en/1.7': 'http://docs.djangoproject.com/en/1.7/_objects/',
}
# -- Options for HTML output ---------------------------------------------------
html_theme = 'default'
htmlhelp_basename = 'analyticaldoc'
# -- Options for LaTeX output --------------------------------------------------
latex_documents = [
('index', 'django-analytical.tex', u'Documentation for django-analytical',
u'Joost Cassee', 'manual'),
]
|
a1c570001e4214d1e2e2c4d34e2ee74721ecb2d5
|
xpserver_api/serializers.py
|
xpserver_api/serializers.py
|
from django.contrib.auth.models import User
from rest_framework import serializers, viewsets
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'email')
def create(self, validated_data):
user = User.objects.create(**validated_data)
user.username = validated_data['email']
user.save()
return user
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
|
from django.contrib.auth.models import User
from rest_framework import serializers, viewsets
from xpserver_api.services import generate_activation_code, EmailSender
from xpserver_web.models import Profile
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'email')
def create(self, validated_data):
user = User.objects.create(**validated_data)
email = validated_data['email']
user.username = email
user.is_active = False
user.save()
profile = Profile.objects.create(user=user, activation_code=generate_activation_code())
profile.save()
email_sender = EmailSender()
email_sender.send_activation_email_with(profile=profile)
return user
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
|
Add user profile when reg via api
|
Add user profile when reg via api
When user is registered via api it will create profile, activation link
and send it to given email just like a web registration flow.
|
Python
|
mit
|
xp2017-hackergarden/server,xp2017-hackergarden/server,xp2017-hackergarden/server,xp2017-hackergarden/server
|
from django.contrib.auth.models import User
from rest_framework import serializers, viewsets
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'email')
def create(self, validated_data):
user = User.objects.create(**validated_data)
user.username = validated_data['email']
user.save()
return user
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
Add user profile when reg via api
When user is registered via api it will create profile, activation link
and send it to given email just like a web registration flow.
|
from django.contrib.auth.models import User
from rest_framework import serializers, viewsets
from xpserver_api.services import generate_activation_code, EmailSender
from xpserver_web.models import Profile
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'email')
def create(self, validated_data):
user = User.objects.create(**validated_data)
email = validated_data['email']
user.username = email
user.is_active = False
user.save()
profile = Profile.objects.create(user=user, activation_code=generate_activation_code())
profile.save()
email_sender = EmailSender()
email_sender.send_activation_email_with(profile=profile)
return user
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
|
<commit_before>from django.contrib.auth.models import User
from rest_framework import serializers, viewsets
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'email')
def create(self, validated_data):
user = User.objects.create(**validated_data)
user.username = validated_data['email']
user.save()
return user
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
<commit_msg>Add user profile when reg via api
When user is registered via api it will create profile, activation link
and send it to given email just like a web registration flow.<commit_after>
|
from django.contrib.auth.models import User
from rest_framework import serializers, viewsets
from xpserver_api.services import generate_activation_code, EmailSender
from xpserver_web.models import Profile
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'email')
def create(self, validated_data):
user = User.objects.create(**validated_data)
email = validated_data['email']
user.username = email
user.is_active = False
user.save()
profile = Profile.objects.create(user=user, activation_code=generate_activation_code())
profile.save()
email_sender = EmailSender()
email_sender.send_activation_email_with(profile=profile)
return user
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
|
from django.contrib.auth.models import User
from rest_framework import serializers, viewsets
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'email')
def create(self, validated_data):
user = User.objects.create(**validated_data)
user.username = validated_data['email']
user.save()
return user
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
Add user profile when reg via api
When user is registered via api it will create profile, activation link
and send it to given email just like a web registration flow.from django.contrib.auth.models import User
from rest_framework import serializers, viewsets
from xpserver_api.services import generate_activation_code, EmailSender
from xpserver_web.models import Profile
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'email')
def create(self, validated_data):
user = User.objects.create(**validated_data)
email = validated_data['email']
user.username = email
user.is_active = False
user.save()
profile = Profile.objects.create(user=user, activation_code=generate_activation_code())
profile.save()
email_sender = EmailSender()
email_sender.send_activation_email_with(profile=profile)
return user
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
|
<commit_before>from django.contrib.auth.models import User
from rest_framework import serializers, viewsets
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'email')
def create(self, validated_data):
user = User.objects.create(**validated_data)
user.username = validated_data['email']
user.save()
return user
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
<commit_msg>Add user profile when reg via api
When user is registered via api it will create profile, activation link
and send it to given email just like a web registration flow.<commit_after>from django.contrib.auth.models import User
from rest_framework import serializers, viewsets
from xpserver_api.services import generate_activation_code, EmailSender
from xpserver_web.models import Profile
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'email')
def create(self, validated_data):
user = User.objects.create(**validated_data)
email = validated_data['email']
user.username = email
user.is_active = False
user.save()
profile = Profile.objects.create(user=user, activation_code=generate_activation_code())
profile.save()
email_sender = EmailSender()
email_sender.send_activation_email_with(profile=profile)
return user
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
|
0f497f4973317588c22044ea78da8a7147eeef19
|
docs/conf.py
|
docs/conf.py
|
import guzzle_sphinx_theme
project = "argcomplete"
copyright = "Andrey Kislyuk"
author = "Andrey Kislyuk"
version = ""
release = ""
language = None
master_doc = "index"
extensions = ["sphinx.ext.autodoc", "sphinx.ext.viewcode"]
source_suffix = [".rst", ".md"]
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
pygments_style = "sphinx"
html_theme_path = guzzle_sphinx_theme.html_theme_path()
html_theme = "guzzle_sphinx_theme"
html_theme_options = {
"project_nav_name": project,
"projectlink": "https://github.com/kislyuk/" + project,
}
html_sidebars = {
"**": [
"logo-text.html",
# "globaltoc.html",
"localtoc.html",
"searchbox.html"
]
}
|
import guzzle_sphinx_theme
project = "argcomplete"
copyright = "Andrey Kislyuk and argcomplete contributors"
author = "Andrey Kislyuk"
version = ""
release = ""
language = None
master_doc = "index"
extensions = ["sphinx.ext.autodoc", "sphinx.ext.viewcode"]
source_suffix = [".rst", ".md"]
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
pygments_style = "sphinx"
html_theme_path = guzzle_sphinx_theme.html_theme_path()
html_theme = "guzzle_sphinx_theme"
html_theme_options = {
"project_nav_name": project,
"projectlink": "https://github.com/kislyuk/" + project,
}
html_sidebars = {
"**": [
"logo-text.html",
# "globaltoc.html",
"localtoc.html",
"searchbox.html"
]
}
|
Adjust copyright line in docs
|
Adjust copyright line in docs
|
Python
|
apache-2.0
|
kislyuk/argcomplete,kislyuk/argcomplete
|
import guzzle_sphinx_theme
project = "argcomplete"
copyright = "Andrey Kislyuk"
author = "Andrey Kislyuk"
version = ""
release = ""
language = None
master_doc = "index"
extensions = ["sphinx.ext.autodoc", "sphinx.ext.viewcode"]
source_suffix = [".rst", ".md"]
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
pygments_style = "sphinx"
html_theme_path = guzzle_sphinx_theme.html_theme_path()
html_theme = "guzzle_sphinx_theme"
html_theme_options = {
"project_nav_name": project,
"projectlink": "https://github.com/kislyuk/" + project,
}
html_sidebars = {
"**": [
"logo-text.html",
# "globaltoc.html",
"localtoc.html",
"searchbox.html"
]
}
Adjust copyright line in docs
|
import guzzle_sphinx_theme
project = "argcomplete"
copyright = "Andrey Kislyuk and argcomplete contributors"
author = "Andrey Kislyuk"
version = ""
release = ""
language = None
master_doc = "index"
extensions = ["sphinx.ext.autodoc", "sphinx.ext.viewcode"]
source_suffix = [".rst", ".md"]
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
pygments_style = "sphinx"
html_theme_path = guzzle_sphinx_theme.html_theme_path()
html_theme = "guzzle_sphinx_theme"
html_theme_options = {
"project_nav_name": project,
"projectlink": "https://github.com/kislyuk/" + project,
}
html_sidebars = {
"**": [
"logo-text.html",
# "globaltoc.html",
"localtoc.html",
"searchbox.html"
]
}
|
<commit_before>import guzzle_sphinx_theme
project = "argcomplete"
copyright = "Andrey Kislyuk"
author = "Andrey Kislyuk"
version = ""
release = ""
language = None
master_doc = "index"
extensions = ["sphinx.ext.autodoc", "sphinx.ext.viewcode"]
source_suffix = [".rst", ".md"]
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
pygments_style = "sphinx"
html_theme_path = guzzle_sphinx_theme.html_theme_path()
html_theme = "guzzle_sphinx_theme"
html_theme_options = {
"project_nav_name": project,
"projectlink": "https://github.com/kislyuk/" + project,
}
html_sidebars = {
"**": [
"logo-text.html",
# "globaltoc.html",
"localtoc.html",
"searchbox.html"
]
}
<commit_msg>Adjust copyright line in docs<commit_after>
|
import guzzle_sphinx_theme
project = "argcomplete"
copyright = "Andrey Kislyuk and argcomplete contributors"
author = "Andrey Kislyuk"
version = ""
release = ""
language = None
master_doc = "index"
extensions = ["sphinx.ext.autodoc", "sphinx.ext.viewcode"]
source_suffix = [".rst", ".md"]
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
pygments_style = "sphinx"
html_theme_path = guzzle_sphinx_theme.html_theme_path()
html_theme = "guzzle_sphinx_theme"
html_theme_options = {
"project_nav_name": project,
"projectlink": "https://github.com/kislyuk/" + project,
}
html_sidebars = {
"**": [
"logo-text.html",
# "globaltoc.html",
"localtoc.html",
"searchbox.html"
]
}
|
import guzzle_sphinx_theme
project = "argcomplete"
copyright = "Andrey Kislyuk"
author = "Andrey Kislyuk"
version = ""
release = ""
language = None
master_doc = "index"
extensions = ["sphinx.ext.autodoc", "sphinx.ext.viewcode"]
source_suffix = [".rst", ".md"]
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
pygments_style = "sphinx"
html_theme_path = guzzle_sphinx_theme.html_theme_path()
html_theme = "guzzle_sphinx_theme"
html_theme_options = {
"project_nav_name": project,
"projectlink": "https://github.com/kislyuk/" + project,
}
html_sidebars = {
"**": [
"logo-text.html",
# "globaltoc.html",
"localtoc.html",
"searchbox.html"
]
}
Adjust copyright line in docsimport guzzle_sphinx_theme
project = "argcomplete"
copyright = "Andrey Kislyuk and argcomplete contributors"
author = "Andrey Kislyuk"
version = ""
release = ""
language = None
master_doc = "index"
extensions = ["sphinx.ext.autodoc", "sphinx.ext.viewcode"]
source_suffix = [".rst", ".md"]
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
pygments_style = "sphinx"
html_theme_path = guzzle_sphinx_theme.html_theme_path()
html_theme = "guzzle_sphinx_theme"
html_theme_options = {
"project_nav_name": project,
"projectlink": "https://github.com/kislyuk/" + project,
}
html_sidebars = {
"**": [
"logo-text.html",
# "globaltoc.html",
"localtoc.html",
"searchbox.html"
]
}
|
<commit_before>import guzzle_sphinx_theme
project = "argcomplete"
copyright = "Andrey Kislyuk"
author = "Andrey Kislyuk"
version = ""
release = ""
language = None
master_doc = "index"
extensions = ["sphinx.ext.autodoc", "sphinx.ext.viewcode"]
source_suffix = [".rst", ".md"]
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
pygments_style = "sphinx"
html_theme_path = guzzle_sphinx_theme.html_theme_path()
html_theme = "guzzle_sphinx_theme"
html_theme_options = {
"project_nav_name": project,
"projectlink": "https://github.com/kislyuk/" + project,
}
html_sidebars = {
"**": [
"logo-text.html",
# "globaltoc.html",
"localtoc.html",
"searchbox.html"
]
}
<commit_msg>Adjust copyright line in docs<commit_after>import guzzle_sphinx_theme
project = "argcomplete"
copyright = "Andrey Kislyuk and argcomplete contributors"
author = "Andrey Kislyuk"
version = ""
release = ""
language = None
master_doc = "index"
extensions = ["sphinx.ext.autodoc", "sphinx.ext.viewcode"]
source_suffix = [".rst", ".md"]
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
pygments_style = "sphinx"
html_theme_path = guzzle_sphinx_theme.html_theme_path()
html_theme = "guzzle_sphinx_theme"
html_theme_options = {
"project_nav_name": project,
"projectlink": "https://github.com/kislyuk/" + project,
}
html_sidebars = {
"**": [
"logo-text.html",
# "globaltoc.html",
"localtoc.html",
"searchbox.html"
]
}
|
a786079d5603eada9186180542096cc334d465f3
|
tests/fixtures/postgres.py
|
tests/fixtures/postgres.py
|
import pytest
from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
from sqlalchemy.ext.asyncio import AsyncSession
from virtool.models import Base
@pytest.fixture(scope="function")
async def engine():
engine = create_async_engine("postgresql+asyncpg://virtool:virtool@localhost/virtool", isolation_level="AUTOCOMMIT")
async with engine.connect() as conn:
try:
await conn.execute(text("CREATE DATABASE test"))
except ProgrammingError:
pass
return create_async_engine("postgresql+asyncpg://virtool:virtool@localhost/test")
@pytest.fixture(scope="function")
async def dbsession(engine, loop):
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await conn.run_sync(Base.metadata.create_all)
session = AsyncSession(bind=engine)
yield session
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await session.close()
|
import pytest
from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
from sqlalchemy.ext.asyncio import AsyncSession
from virtool.models import Base
@pytest.fixture(scope="function")
async def engine():
engine = create_async_engine("postgresql+asyncpg://virtool:virtool@postgres/virtool", isolation_level="AUTOCOMMIT")
async with engine.connect() as conn:
try:
await conn.execute(text("CREATE DATABASE test"))
except ProgrammingError:
pass
return create_async_engine("postgresql+asyncpg://virtool:virtool@postgres/test")
@pytest.fixture(scope="function")
async def dbsession(engine, loop):
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await conn.run_sync(Base.metadata.create_all)
session = AsyncSession(bind=engine)
yield session
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await session.close()
|
Update Postgres test connection string
|
Update Postgres test connection string
|
Python
|
mit
|
igboyes/virtool,virtool/virtool,igboyes/virtool,virtool/virtool
|
import pytest
from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
from sqlalchemy.ext.asyncio import AsyncSession
from virtool.models import Base
@pytest.fixture(scope="function")
async def engine():
engine = create_async_engine("postgresql+asyncpg://virtool:virtool@localhost/virtool", isolation_level="AUTOCOMMIT")
async with engine.connect() as conn:
try:
await conn.execute(text("CREATE DATABASE test"))
except ProgrammingError:
pass
return create_async_engine("postgresql+asyncpg://virtool:virtool@localhost/test")
@pytest.fixture(scope="function")
async def dbsession(engine, loop):
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await conn.run_sync(Base.metadata.create_all)
session = AsyncSession(bind=engine)
yield session
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await session.close()Update Postgres test connection string
|
import pytest
from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
from sqlalchemy.ext.asyncio import AsyncSession
from virtool.models import Base
@pytest.fixture(scope="function")
async def engine():
engine = create_async_engine("postgresql+asyncpg://virtool:virtool@postgres/virtool", isolation_level="AUTOCOMMIT")
async with engine.connect() as conn:
try:
await conn.execute(text("CREATE DATABASE test"))
except ProgrammingError:
pass
return create_async_engine("postgresql+asyncpg://virtool:virtool@postgres/test")
@pytest.fixture(scope="function")
async def dbsession(engine, loop):
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await conn.run_sync(Base.metadata.create_all)
session = AsyncSession(bind=engine)
yield session
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await session.close()
|
<commit_before>import pytest
from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
from sqlalchemy.ext.asyncio import AsyncSession
from virtool.models import Base
@pytest.fixture(scope="function")
async def engine():
engine = create_async_engine("postgresql+asyncpg://virtool:virtool@localhost/virtool", isolation_level="AUTOCOMMIT")
async with engine.connect() as conn:
try:
await conn.execute(text("CREATE DATABASE test"))
except ProgrammingError:
pass
return create_async_engine("postgresql+asyncpg://virtool:virtool@localhost/test")
@pytest.fixture(scope="function")
async def dbsession(engine, loop):
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await conn.run_sync(Base.metadata.create_all)
session = AsyncSession(bind=engine)
yield session
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await session.close()<commit_msg>Update Postgres test connection string<commit_after>
|
import pytest
from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
from sqlalchemy.ext.asyncio import AsyncSession
from virtool.models import Base
@pytest.fixture(scope="function")
async def engine():
engine = create_async_engine("postgresql+asyncpg://virtool:virtool@postgres/virtool", isolation_level="AUTOCOMMIT")
async with engine.connect() as conn:
try:
await conn.execute(text("CREATE DATABASE test"))
except ProgrammingError:
pass
return create_async_engine("postgresql+asyncpg://virtool:virtool@postgres/test")
@pytest.fixture(scope="function")
async def dbsession(engine, loop):
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await conn.run_sync(Base.metadata.create_all)
session = AsyncSession(bind=engine)
yield session
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await session.close()
|
import pytest
from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
from sqlalchemy.ext.asyncio import AsyncSession
from virtool.models import Base
@pytest.fixture(scope="function")
async def engine():
engine = create_async_engine("postgresql+asyncpg://virtool:virtool@localhost/virtool", isolation_level="AUTOCOMMIT")
async with engine.connect() as conn:
try:
await conn.execute(text("CREATE DATABASE test"))
except ProgrammingError:
pass
return create_async_engine("postgresql+asyncpg://virtool:virtool@localhost/test")
@pytest.fixture(scope="function")
async def dbsession(engine, loop):
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await conn.run_sync(Base.metadata.create_all)
session = AsyncSession(bind=engine)
yield session
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await session.close()Update Postgres test connection stringimport pytest
from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
from sqlalchemy.ext.asyncio import AsyncSession
from virtool.models import Base
@pytest.fixture(scope="function")
async def engine():
engine = create_async_engine("postgresql+asyncpg://virtool:virtool@postgres/virtool", isolation_level="AUTOCOMMIT")
async with engine.connect() as conn:
try:
await conn.execute(text("CREATE DATABASE test"))
except ProgrammingError:
pass
return create_async_engine("postgresql+asyncpg://virtool:virtool@postgres/test")
@pytest.fixture(scope="function")
async def dbsession(engine, loop):
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await conn.run_sync(Base.metadata.create_all)
session = AsyncSession(bind=engine)
yield session
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await session.close()
|
<commit_before>import pytest
from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
from sqlalchemy.ext.asyncio import AsyncSession
from virtool.models import Base
@pytest.fixture(scope="function")
async def engine():
engine = create_async_engine("postgresql+asyncpg://virtool:virtool@localhost/virtool", isolation_level="AUTOCOMMIT")
async with engine.connect() as conn:
try:
await conn.execute(text("CREATE DATABASE test"))
except ProgrammingError:
pass
return create_async_engine("postgresql+asyncpg://virtool:virtool@localhost/test")
@pytest.fixture(scope="function")
async def dbsession(engine, loop):
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await conn.run_sync(Base.metadata.create_all)
session = AsyncSession(bind=engine)
yield session
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await session.close()<commit_msg>Update Postgres test connection string<commit_after>import pytest
from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
from sqlalchemy.ext.asyncio import AsyncSession
from virtool.models import Base
@pytest.fixture(scope="function")
async def engine():
engine = create_async_engine("postgresql+asyncpg://virtool:virtool@postgres/virtool", isolation_level="AUTOCOMMIT")
async with engine.connect() as conn:
try:
await conn.execute(text("CREATE DATABASE test"))
except ProgrammingError:
pass
return create_async_engine("postgresql+asyncpg://virtool:virtool@postgres/test")
@pytest.fixture(scope="function")
async def dbsession(engine, loop):
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await conn.run_sync(Base.metadata.create_all)
session = AsyncSession(bind=engine)
yield session
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await session.close()
|
2d9e6d9ca46cdd58f5b811082f3fc40d62f3ead8
|
dev/__init__.py
|
dev/__init__.py
|
# coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
package_name = "certbuilder"
other_packages = []
package_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
build_root = os.path.abspath(os.path.join(package_root, '..'))
md_source_map = {
'docs/api.md': ['certbuilder/__init__.py'],
}
definition_replacements = {}
|
# coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
package_name = "certbuilder"
other_packages = []
task_keyword_args = []
requires_oscrypto = True
has_tests_package = False
package_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
build_root = os.path.abspath(os.path.join(package_root, '..'))
md_source_map = {
'docs/api.md': ['certbuilder/__init__.py'],
}
definition_replacements = {}
|
Add missing dev config values
|
Add missing dev config values
|
Python
|
mit
|
wbond/certbuilder
|
# coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
package_name = "certbuilder"
other_packages = []
package_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
build_root = os.path.abspath(os.path.join(package_root, '..'))
md_source_map = {
'docs/api.md': ['certbuilder/__init__.py'],
}
definition_replacements = {}
Add missing dev config values
|
# coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
package_name = "certbuilder"
other_packages = []
task_keyword_args = []
requires_oscrypto = True
has_tests_package = False
package_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
build_root = os.path.abspath(os.path.join(package_root, '..'))
md_source_map = {
'docs/api.md': ['certbuilder/__init__.py'],
}
definition_replacements = {}
|
<commit_before># coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
package_name = "certbuilder"
other_packages = []
package_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
build_root = os.path.abspath(os.path.join(package_root, '..'))
md_source_map = {
'docs/api.md': ['certbuilder/__init__.py'],
}
definition_replacements = {}
<commit_msg>Add missing dev config values<commit_after>
|
# coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
package_name = "certbuilder"
other_packages = []
task_keyword_args = []
requires_oscrypto = True
has_tests_package = False
package_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
build_root = os.path.abspath(os.path.join(package_root, '..'))
md_source_map = {
'docs/api.md': ['certbuilder/__init__.py'],
}
definition_replacements = {}
|
# coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
package_name = "certbuilder"
other_packages = []
package_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
build_root = os.path.abspath(os.path.join(package_root, '..'))
md_source_map = {
'docs/api.md': ['certbuilder/__init__.py'],
}
definition_replacements = {}
Add missing dev config values# coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
package_name = "certbuilder"
other_packages = []
task_keyword_args = []
requires_oscrypto = True
has_tests_package = False
package_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
build_root = os.path.abspath(os.path.join(package_root, '..'))
md_source_map = {
'docs/api.md': ['certbuilder/__init__.py'],
}
definition_replacements = {}
|
<commit_before># coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
package_name = "certbuilder"
other_packages = []
package_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
build_root = os.path.abspath(os.path.join(package_root, '..'))
md_source_map = {
'docs/api.md': ['certbuilder/__init__.py'],
}
definition_replacements = {}
<commit_msg>Add missing dev config values<commit_after># coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
package_name = "certbuilder"
other_packages = []
task_keyword_args = []
requires_oscrypto = True
has_tests_package = False
package_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
build_root = os.path.abspath(os.path.join(package_root, '..'))
md_source_map = {
'docs/api.md': ['certbuilder/__init__.py'],
}
definition_replacements = {}
|
1223726c081000ef42a580881c9f8d2002d91c0b
|
src/hireme/tasks/__init__.py
|
src/hireme/tasks/__init__.py
|
# -*- coding: utf-8 -*-
from flask import render_template
from flask import request
def render_task(func):
def rendered():
params = dict(title=func.__module__.split('.')[-1] or '')
if request.method == 'POST':
input_data = request.form.get('input')
params['input_data'] = input_data
params['solution'] = func(input_data)
return render_template('task.html', **params)
return rendered
|
# -*- coding: utf-8 -*-
from flask import render_template
from flask import request
def render_task(func):
"""Decorator for task solving functions. Provides raw form data from the
request and expects a string formatted return value."""
def rendered():
params = dict(title=func.__module__.split('.')[-1] or '')
if request.method == 'POST':
input_data = request.form.get('input')
params['input'] = input_data
params['solution'] = func(input_data)
return render_template('task.html', **params)
return rendered
|
Add docstring, fix template param name
|
Add docstring, fix template param name
|
Python
|
bsd-2-clause
|
cutoffthetop/hireme
|
# -*- coding: utf-8 -*-
from flask import render_template
from flask import request
def render_task(func):
def rendered():
params = dict(title=func.__module__.split('.')[-1] or '')
if request.method == 'POST':
input_data = request.form.get('input')
params['input_data'] = input_data
params['solution'] = func(input_data)
return render_template('task.html', **params)
return rendered
Add docstring, fix template param name
|
# -*- coding: utf-8 -*-
from flask import render_template
from flask import request
def render_task(func):
"""Decorator for task solving functions. Provides raw form data from the
request and expects a string formatted return value."""
def rendered():
params = dict(title=func.__module__.split('.')[-1] or '')
if request.method == 'POST':
input_data = request.form.get('input')
params['input'] = input_data
params['solution'] = func(input_data)
return render_template('task.html', **params)
return rendered
|
<commit_before># -*- coding: utf-8 -*-
from flask import render_template
from flask import request
def render_task(func):
def rendered():
params = dict(title=func.__module__.split('.')[-1] or '')
if request.method == 'POST':
input_data = request.form.get('input')
params['input_data'] = input_data
params['solution'] = func(input_data)
return render_template('task.html', **params)
return rendered
<commit_msg>Add docstring, fix template param name<commit_after>
|
# -*- coding: utf-8 -*-
from flask import render_template
from flask import request
def render_task(func):
"""Decorator for task solving functions. Provides raw form data from the
request and expects a string formatted return value."""
def rendered():
params = dict(title=func.__module__.split('.')[-1] or '')
if request.method == 'POST':
input_data = request.form.get('input')
params['input'] = input_data
params['solution'] = func(input_data)
return render_template('task.html', **params)
return rendered
|
# -*- coding: utf-8 -*-
from flask import render_template
from flask import request
def render_task(func):
def rendered():
params = dict(title=func.__module__.split('.')[-1] or '')
if request.method == 'POST':
input_data = request.form.get('input')
params['input_data'] = input_data
params['solution'] = func(input_data)
return render_template('task.html', **params)
return rendered
Add docstring, fix template param name# -*- coding: utf-8 -*-
from flask import render_template
from flask import request
def render_task(func):
"""Decorator for task solving functions. Provides raw form data from the
request and expects a string formatted return value."""
def rendered():
params = dict(title=func.__module__.split('.')[-1] or '')
if request.method == 'POST':
input_data = request.form.get('input')
params['input'] = input_data
params['solution'] = func(input_data)
return render_template('task.html', **params)
return rendered
|
<commit_before># -*- coding: utf-8 -*-
from flask import render_template
from flask import request
def render_task(func):
def rendered():
params = dict(title=func.__module__.split('.')[-1] or '')
if request.method == 'POST':
input_data = request.form.get('input')
params['input_data'] = input_data
params['solution'] = func(input_data)
return render_template('task.html', **params)
return rendered
<commit_msg>Add docstring, fix template param name<commit_after># -*- coding: utf-8 -*-
from flask import render_template
from flask import request
def render_task(func):
"""Decorator for task solving functions. Provides raw form data from the
request and expects a string formatted return value."""
def rendered():
params = dict(title=func.__module__.split('.')[-1] or '')
if request.method == 'POST':
input_data = request.form.get('input')
params['input'] = input_data
params['solution'] = func(input_data)
return render_template('task.html', **params)
return rendered
|
814d5b97c1b5238cc9b046762781b9e604a82353
|
dduplicated/fileManager.py
|
dduplicated/fileManager.py
|
#! /usr/bin/env python
import os
def managerFiles(paths, link):
first = True
src = ""
for path in paths:
if first:
first = False
src = path
print("PRESERVED: The file preserved is: \"" + path + "\"")
else:
os.remove(path)
print("DELETE: File deleted: \"" + path + "\"")
if link:
os.symlink(src, path)
print("LINK: Created link: \"" + path + "\" -> \"" + src + "\"")
# Try The Voight-Kampff if you not recognize if is a replicant or not, all is suspect
def manager(duplicates, createLink = False):
if len(duplicates) < 1:
print("No duplicates found")
print("Great! Bye!")
exit(0)
for filesByHash in duplicates.values():
managerFiles(filesByHash, link)
def delete(duplicates):
manager(duplicates)
def link(duplicates):
manager(duplicates, True)
|
#! /usr/bin/env python
import os
def managerFiles(paths, link):
first = True
src = ""
for path in paths:
if first:
first = False
src = path
print("PRESERVED: The file preserved is: \"" + path + "\"")
else:
os.remove(path)
print("DELETE: File deleted: \"" + path + "\"")
if link:
os.symlink(src, path)
print("LINK: Created link: \"" + path + "\" -> \"" + src + "\"")
# Try The Voight-Kampff if you not recognize if is a replicant or not, all is suspect
def manager(duplicates, createLink = False):
if len(duplicates) < 1:
print("No duplicates found")
print("Great! Bye!")
exit(0)
for filesByHash in duplicates.values():
managerFiles(filesByHash, createLink)
def delete(duplicates):
manager(duplicates)
def link(duplicates):
manager(duplicates, True)
|
Fix in action delete and not link
|
Fix in action delete and not link
Fix in case of user want only delete duplicates, the error is, when did they the delete only duplicates, the links was created anyway.
|
Python
|
mit
|
messiasthi/dduplicated-cli
|
#! /usr/bin/env python
import os
def managerFiles(paths, link):
first = True
src = ""
for path in paths:
if first:
first = False
src = path
print("PRESERVED: The file preserved is: \"" + path + "\"")
else:
os.remove(path)
print("DELETE: File deleted: \"" + path + "\"")
if link:
os.symlink(src, path)
print("LINK: Created link: \"" + path + "\" -> \"" + src + "\"")
# Try The Voight-Kampff if you not recognize if is a replicant or not, all is suspect
def manager(duplicates, createLink = False):
if len(duplicates) < 1:
print("No duplicates found")
print("Great! Bye!")
exit(0)
for filesByHash in duplicates.values():
managerFiles(filesByHash, link)
def delete(duplicates):
manager(duplicates)
def link(duplicates):
manager(duplicates, True)
Fix in action delete and not link
Fix in case of user want only delete duplicates, the error is, when did they the delete only duplicates, the links was created anyway.
|
#! /usr/bin/env python
import os
def managerFiles(paths, link):
first = True
src = ""
for path in paths:
if first:
first = False
src = path
print("PRESERVED: The file preserved is: \"" + path + "\"")
else:
os.remove(path)
print("DELETE: File deleted: \"" + path + "\"")
if link:
os.symlink(src, path)
print("LINK: Created link: \"" + path + "\" -> \"" + src + "\"")
# Try The Voight-Kampff if you not recognize if is a replicant or not, all is suspect
def manager(duplicates, createLink = False):
if len(duplicates) < 1:
print("No duplicates found")
print("Great! Bye!")
exit(0)
for filesByHash in duplicates.values():
managerFiles(filesByHash, createLink)
def delete(duplicates):
manager(duplicates)
def link(duplicates):
manager(duplicates, True)
|
<commit_before>#! /usr/bin/env python
import os
def managerFiles(paths, link):
first = True
src = ""
for path in paths:
if first:
first = False
src = path
print("PRESERVED: The file preserved is: \"" + path + "\"")
else:
os.remove(path)
print("DELETE: File deleted: \"" + path + "\"")
if link:
os.symlink(src, path)
print("LINK: Created link: \"" + path + "\" -> \"" + src + "\"")
# Try The Voight-Kampff if you not recognize if is a replicant or not, all is suspect
def manager(duplicates, createLink = False):
if len(duplicates) < 1:
print("No duplicates found")
print("Great! Bye!")
exit(0)
for filesByHash in duplicates.values():
managerFiles(filesByHash, link)
def delete(duplicates):
manager(duplicates)
def link(duplicates):
manager(duplicates, True)
<commit_msg>Fix in action delete and not link
Fix in case of user want only delete duplicates, the error is, when did they the delete only duplicates, the links was created anyway.<commit_after>
|
#! /usr/bin/env python
import os
def managerFiles(paths, link):
first = True
src = ""
for path in paths:
if first:
first = False
src = path
print("PRESERVED: The file preserved is: \"" + path + "\"")
else:
os.remove(path)
print("DELETE: File deleted: \"" + path + "\"")
if link:
os.symlink(src, path)
print("LINK: Created link: \"" + path + "\" -> \"" + src + "\"")
# Try The Voight-Kampff if you not recognize if is a replicant or not, all is suspect
def manager(duplicates, createLink = False):
if len(duplicates) < 1:
print("No duplicates found")
print("Great! Bye!")
exit(0)
for filesByHash in duplicates.values():
managerFiles(filesByHash, createLink)
def delete(duplicates):
manager(duplicates)
def link(duplicates):
manager(duplicates, True)
|
#! /usr/bin/env python
import os
def managerFiles(paths, link):
first = True
src = ""
for path in paths:
if first:
first = False
src = path
print("PRESERVED: The file preserved is: \"" + path + "\"")
else:
os.remove(path)
print("DELETE: File deleted: \"" + path + "\"")
if link:
os.symlink(src, path)
print("LINK: Created link: \"" + path + "\" -> \"" + src + "\"")
# Try The Voight-Kampff if you not recognize if is a replicant or not, all is suspect
def manager(duplicates, createLink = False):
if len(duplicates) < 1:
print("No duplicates found")
print("Great! Bye!")
exit(0)
for filesByHash in duplicates.values():
managerFiles(filesByHash, link)
def delete(duplicates):
manager(duplicates)
def link(duplicates):
manager(duplicates, True)
Fix in action delete and not link
Fix in case of user want only delete duplicates, the error is, when did they the delete only duplicates, the links was created anyway.#! /usr/bin/env python
import os
def managerFiles(paths, link):
first = True
src = ""
for path in paths:
if first:
first = False
src = path
print("PRESERVED: The file preserved is: \"" + path + "\"")
else:
os.remove(path)
print("DELETE: File deleted: \"" + path + "\"")
if link:
os.symlink(src, path)
print("LINK: Created link: \"" + path + "\" -> \"" + src + "\"")
# Try The Voight-Kampff if you not recognize if is a replicant or not, all is suspect
def manager(duplicates, createLink = False):
if len(duplicates) < 1:
print("No duplicates found")
print("Great! Bye!")
exit(0)
for filesByHash in duplicates.values():
managerFiles(filesByHash, createLink)
def delete(duplicates):
manager(duplicates)
def link(duplicates):
manager(duplicates, True)
|
<commit_before>#! /usr/bin/env python
import os
def managerFiles(paths, link):
first = True
src = ""
for path in paths:
if first:
first = False
src = path
print("PRESERVED: The file preserved is: \"" + path + "\"")
else:
os.remove(path)
print("DELETE: File deleted: \"" + path + "\"")
if link:
os.symlink(src, path)
print("LINK: Created link: \"" + path + "\" -> \"" + src + "\"")
# Try The Voight-Kampff if you not recognize if is a replicant or not, all is suspect
def manager(duplicates, createLink = False):
if len(duplicates) < 1:
print("No duplicates found")
print("Great! Bye!")
exit(0)
for filesByHash in duplicates.values():
managerFiles(filesByHash, link)
def delete(duplicates):
manager(duplicates)
def link(duplicates):
manager(duplicates, True)
<commit_msg>Fix in action delete and not link
Fix in case of user want only delete duplicates, the error is, when did they the delete only duplicates, the links was created anyway.<commit_after>#! /usr/bin/env python
import os
def managerFiles(paths, link):
first = True
src = ""
for path in paths:
if first:
first = False
src = path
print("PRESERVED: The file preserved is: \"" + path + "\"")
else:
os.remove(path)
print("DELETE: File deleted: \"" + path + "\"")
if link:
os.symlink(src, path)
print("LINK: Created link: \"" + path + "\" -> \"" + src + "\"")
# Try The Voight-Kampff if you not recognize if is a replicant or not, all is suspect
def manager(duplicates, createLink = False):
if len(duplicates) < 1:
print("No duplicates found")
print("Great! Bye!")
exit(0)
for filesByHash in duplicates.values():
managerFiles(filesByHash, createLink)
def delete(duplicates):
manager(duplicates)
def link(duplicates):
manager(duplicates, True)
|
d3a993b1f8ed7a682993c0472c362206fae2abcb
|
dodocs/profiles/remove.py
|
dodocs/profiles/remove.py
|
"""Create the profile.
Copyright (c) 2015 Francesco Montesano
MIT Licence
"""
import shutil
import dodocs.logger as dlog
import dodocs.utils as dutils
def remove(args):
"""Remove profile(s)
Parameters
----------
args : namespace
parsed command line arguments
"""
log = dlog.getLogger()
for name in args.name:
dlog.set_profile(name)
log.debug("Removing profile")
profile_dir = dutils.profile_dir(name)
if not profile_dir.exists():
log.warn("Profile does not exist")
continue
try:
if profile_dir.is_symlink():
realpath = profile_dir.resolve()
profile_dir.unlink()
shutil.rmtree(str(realpath))
else:
shutil.rmtree(str(profile_dir))
except FileNotFoundError:
log.error("The removal of profile failed", exc_info=True)
log.info("profile removed")
|
"""Remove the profiles.
Copyright (c) 2015 Francesco Montesano
MIT Licence
"""
import shutil
import dodocs.logger as dlog
import dodocs.utils as dutils
def remove(args):
"""Remove profile(s)
Parameters
----------
args : namespace
parsed command line arguments
"""
log = dlog.getLogger()
for name in args.name:
dlog.set_profile(name)
profile_dir = dutils.profile_dir(name)
if not profile_dir.exists():
log.warn("Profile does not exist")
continue
log.debug("Removing profile")
try:
if profile_dir.is_symlink():
realpath = profile_dir.resolve()
profile_dir.unlink()
shutil.rmtree(str(realpath))
else:
shutil.rmtree(str(profile_dir))
except FileNotFoundError:
log.error("The removal of profile failed", exc_info=True)
log.info("profile removed")
|
Adjust logging and fix module documentation
|
Adjust logging and fix module documentation
|
Python
|
mit
|
montefra/dodocs
|
"""Create the profile.
Copyright (c) 2015 Francesco Montesano
MIT Licence
"""
import shutil
import dodocs.logger as dlog
import dodocs.utils as dutils
def remove(args):
"""Remove profile(s)
Parameters
----------
args : namespace
parsed command line arguments
"""
log = dlog.getLogger()
for name in args.name:
dlog.set_profile(name)
log.debug("Removing profile")
profile_dir = dutils.profile_dir(name)
if not profile_dir.exists():
log.warn("Profile does not exist")
continue
try:
if profile_dir.is_symlink():
realpath = profile_dir.resolve()
profile_dir.unlink()
shutil.rmtree(str(realpath))
else:
shutil.rmtree(str(profile_dir))
except FileNotFoundError:
log.error("The removal of profile failed", exc_info=True)
log.info("profile removed")
Adjust logging and fix module documentation
|
"""Remove the profiles.
Copyright (c) 2015 Francesco Montesano
MIT Licence
"""
import shutil
import dodocs.logger as dlog
import dodocs.utils as dutils
def remove(args):
"""Remove profile(s)
Parameters
----------
args : namespace
parsed command line arguments
"""
log = dlog.getLogger()
for name in args.name:
dlog.set_profile(name)
profile_dir = dutils.profile_dir(name)
if not profile_dir.exists():
log.warn("Profile does not exist")
continue
log.debug("Removing profile")
try:
if profile_dir.is_symlink():
realpath = profile_dir.resolve()
profile_dir.unlink()
shutil.rmtree(str(realpath))
else:
shutil.rmtree(str(profile_dir))
except FileNotFoundError:
log.error("The removal of profile failed", exc_info=True)
log.info("profile removed")
|
<commit_before>"""Create the profile.
Copyright (c) 2015 Francesco Montesano
MIT Licence
"""
import shutil
import dodocs.logger as dlog
import dodocs.utils as dutils
def remove(args):
"""Remove profile(s)
Parameters
----------
args : namespace
parsed command line arguments
"""
log = dlog.getLogger()
for name in args.name:
dlog.set_profile(name)
log.debug("Removing profile")
profile_dir = dutils.profile_dir(name)
if not profile_dir.exists():
log.warn("Profile does not exist")
continue
try:
if profile_dir.is_symlink():
realpath = profile_dir.resolve()
profile_dir.unlink()
shutil.rmtree(str(realpath))
else:
shutil.rmtree(str(profile_dir))
except FileNotFoundError:
log.error("The removal of profile failed", exc_info=True)
log.info("profile removed")
<commit_msg>Adjust logging and fix module documentation<commit_after>
|
"""Remove the profiles.
Copyright (c) 2015 Francesco Montesano
MIT Licence
"""
import shutil
import dodocs.logger as dlog
import dodocs.utils as dutils
def remove(args):
"""Remove profile(s)
Parameters
----------
args : namespace
parsed command line arguments
"""
log = dlog.getLogger()
for name in args.name:
dlog.set_profile(name)
profile_dir = dutils.profile_dir(name)
if not profile_dir.exists():
log.warn("Profile does not exist")
continue
log.debug("Removing profile")
try:
if profile_dir.is_symlink():
realpath = profile_dir.resolve()
profile_dir.unlink()
shutil.rmtree(str(realpath))
else:
shutil.rmtree(str(profile_dir))
except FileNotFoundError:
log.error("The removal of profile failed", exc_info=True)
log.info("profile removed")
|
"""Create the profile.
Copyright (c) 2015 Francesco Montesano
MIT Licence
"""
import shutil
import dodocs.logger as dlog
import dodocs.utils as dutils
def remove(args):
"""Remove profile(s)
Parameters
----------
args : namespace
parsed command line arguments
"""
log = dlog.getLogger()
for name in args.name:
dlog.set_profile(name)
log.debug("Removing profile")
profile_dir = dutils.profile_dir(name)
if not profile_dir.exists():
log.warn("Profile does not exist")
continue
try:
if profile_dir.is_symlink():
realpath = profile_dir.resolve()
profile_dir.unlink()
shutil.rmtree(str(realpath))
else:
shutil.rmtree(str(profile_dir))
except FileNotFoundError:
log.error("The removal of profile failed", exc_info=True)
log.info("profile removed")
Adjust logging and fix module documentation"""Remove the profiles.
Copyright (c) 2015 Francesco Montesano
MIT Licence
"""
import shutil
import dodocs.logger as dlog
import dodocs.utils as dutils
def remove(args):
"""Remove profile(s)
Parameters
----------
args : namespace
parsed command line arguments
"""
log = dlog.getLogger()
for name in args.name:
dlog.set_profile(name)
profile_dir = dutils.profile_dir(name)
if not profile_dir.exists():
log.warn("Profile does not exist")
continue
log.debug("Removing profile")
try:
if profile_dir.is_symlink():
realpath = profile_dir.resolve()
profile_dir.unlink()
shutil.rmtree(str(realpath))
else:
shutil.rmtree(str(profile_dir))
except FileNotFoundError:
log.error("The removal of profile failed", exc_info=True)
log.info("profile removed")
|
<commit_before>"""Create the profile.
Copyright (c) 2015 Francesco Montesano
MIT Licence
"""
import shutil
import dodocs.logger as dlog
import dodocs.utils as dutils
def remove(args):
"""Remove profile(s)
Parameters
----------
args : namespace
parsed command line arguments
"""
log = dlog.getLogger()
for name in args.name:
dlog.set_profile(name)
log.debug("Removing profile")
profile_dir = dutils.profile_dir(name)
if not profile_dir.exists():
log.warn("Profile does not exist")
continue
try:
if profile_dir.is_symlink():
realpath = profile_dir.resolve()
profile_dir.unlink()
shutil.rmtree(str(realpath))
else:
shutil.rmtree(str(profile_dir))
except FileNotFoundError:
log.error("The removal of profile failed", exc_info=True)
log.info("profile removed")
<commit_msg>Adjust logging and fix module documentation<commit_after>"""Remove the profiles.
Copyright (c) 2015 Francesco Montesano
MIT Licence
"""
import shutil
import dodocs.logger as dlog
import dodocs.utils as dutils
def remove(args):
"""Remove profile(s)
Parameters
----------
args : namespace
parsed command line arguments
"""
log = dlog.getLogger()
for name in args.name:
dlog.set_profile(name)
profile_dir = dutils.profile_dir(name)
if not profile_dir.exists():
log.warn("Profile does not exist")
continue
log.debug("Removing profile")
try:
if profile_dir.is_symlink():
realpath = profile_dir.resolve()
profile_dir.unlink()
shutil.rmtree(str(realpath))
else:
shutil.rmtree(str(profile_dir))
except FileNotFoundError:
log.error("The removal of profile failed", exc_info=True)
log.info("profile removed")
|
1e76a9c7ee030875929a65d9f30194166dcd62ef
|
docs/reencode.py
|
docs/reencode.py
|
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://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.
"""Helper binary to reencode a text file from UTF-8 to ISO-8859-1."""
import argparse
import pathlib
def _main() -> None:
parser = argparse.ArgumentParser(allow_abbrev=False)
parser.add_argument('input', type=pathlib.Path)
parser.add_argument('output', type=pathlib.Path)
opts = parser.parse_args()
text = opts.input.read_text(encoding='utf-8')
with opts.output.open(mode='xt', encoding='latin-1', newline='\n') as file:
file.write(text)
if __name__ == '__main__':
_main()
|
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://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.
"""Helper binary to reencode a text file from UTF-8 to ISO-8859-1."""
import argparse
import pathlib
def _main() -> None:
parser = argparse.ArgumentParser(allow_abbrev=False)
parser.add_argument('input', type=pathlib.Path)
parser.add_argument('output', type=pathlib.Path)
opts = parser.parse_args()
text = opts.input.read_text(encoding='utf-8')
# Force Unix-style line endings for consistent results. See
# https://github.com/bazelbuild/stardoc/issues/110.
with opts.output.open(mode='xt', encoding='latin-1', newline='\n') as file:
file.write(text)
if __name__ == '__main__':
_main()
|
Add a comment about line endings in Stardoc files.
|
Add a comment about line endings in Stardoc files.
|
Python
|
apache-2.0
|
phst/rules_elisp,phst/rules_elisp,phst/rules_elisp,phst/rules_elisp,phst/rules_elisp
|
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://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.
"""Helper binary to reencode a text file from UTF-8 to ISO-8859-1."""
import argparse
import pathlib
def _main() -> None:
parser = argparse.ArgumentParser(allow_abbrev=False)
parser.add_argument('input', type=pathlib.Path)
parser.add_argument('output', type=pathlib.Path)
opts = parser.parse_args()
text = opts.input.read_text(encoding='utf-8')
with opts.output.open(mode='xt', encoding='latin-1', newline='\n') as file:
file.write(text)
if __name__ == '__main__':
_main()
Add a comment about line endings in Stardoc files.
|
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://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.
"""Helper binary to reencode a text file from UTF-8 to ISO-8859-1."""
import argparse
import pathlib
def _main() -> None:
parser = argparse.ArgumentParser(allow_abbrev=False)
parser.add_argument('input', type=pathlib.Path)
parser.add_argument('output', type=pathlib.Path)
opts = parser.parse_args()
text = opts.input.read_text(encoding='utf-8')
# Force Unix-style line endings for consistent results. See
# https://github.com/bazelbuild/stardoc/issues/110.
with opts.output.open(mode='xt', encoding='latin-1', newline='\n') as file:
file.write(text)
if __name__ == '__main__':
_main()
|
<commit_before># Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://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.
"""Helper binary to reencode a text file from UTF-8 to ISO-8859-1."""
import argparse
import pathlib
def _main() -> None:
parser = argparse.ArgumentParser(allow_abbrev=False)
parser.add_argument('input', type=pathlib.Path)
parser.add_argument('output', type=pathlib.Path)
opts = parser.parse_args()
text = opts.input.read_text(encoding='utf-8')
with opts.output.open(mode='xt', encoding='latin-1', newline='\n') as file:
file.write(text)
if __name__ == '__main__':
_main()
<commit_msg>Add a comment about line endings in Stardoc files.<commit_after>
|
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://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.
"""Helper binary to reencode a text file from UTF-8 to ISO-8859-1."""
import argparse
import pathlib
def _main() -> None:
parser = argparse.ArgumentParser(allow_abbrev=False)
parser.add_argument('input', type=pathlib.Path)
parser.add_argument('output', type=pathlib.Path)
opts = parser.parse_args()
text = opts.input.read_text(encoding='utf-8')
# Force Unix-style line endings for consistent results. See
# https://github.com/bazelbuild/stardoc/issues/110.
with opts.output.open(mode='xt', encoding='latin-1', newline='\n') as file:
file.write(text)
if __name__ == '__main__':
_main()
|
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://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.
"""Helper binary to reencode a text file from UTF-8 to ISO-8859-1."""
import argparse
import pathlib
def _main() -> None:
parser = argparse.ArgumentParser(allow_abbrev=False)
parser.add_argument('input', type=pathlib.Path)
parser.add_argument('output', type=pathlib.Path)
opts = parser.parse_args()
text = opts.input.read_text(encoding='utf-8')
with opts.output.open(mode='xt', encoding='latin-1', newline='\n') as file:
file.write(text)
if __name__ == '__main__':
_main()
Add a comment about line endings in Stardoc files.# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://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.
"""Helper binary to reencode a text file from UTF-8 to ISO-8859-1."""
import argparse
import pathlib
def _main() -> None:
parser = argparse.ArgumentParser(allow_abbrev=False)
parser.add_argument('input', type=pathlib.Path)
parser.add_argument('output', type=pathlib.Path)
opts = parser.parse_args()
text = opts.input.read_text(encoding='utf-8')
# Force Unix-style line endings for consistent results. See
# https://github.com/bazelbuild/stardoc/issues/110.
with opts.output.open(mode='xt', encoding='latin-1', newline='\n') as file:
file.write(text)
if __name__ == '__main__':
_main()
|
<commit_before># Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://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.
"""Helper binary to reencode a text file from UTF-8 to ISO-8859-1."""
import argparse
import pathlib
def _main() -> None:
parser = argparse.ArgumentParser(allow_abbrev=False)
parser.add_argument('input', type=pathlib.Path)
parser.add_argument('output', type=pathlib.Path)
opts = parser.parse_args()
text = opts.input.read_text(encoding='utf-8')
with opts.output.open(mode='xt', encoding='latin-1', newline='\n') as file:
file.write(text)
if __name__ == '__main__':
_main()
<commit_msg>Add a comment about line endings in Stardoc files.<commit_after># Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://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.
"""Helper binary to reencode a text file from UTF-8 to ISO-8859-1."""
import argparse
import pathlib
def _main() -> None:
parser = argparse.ArgumentParser(allow_abbrev=False)
parser.add_argument('input', type=pathlib.Path)
parser.add_argument('output', type=pathlib.Path)
opts = parser.parse_args()
text = opts.input.read_text(encoding='utf-8')
# Force Unix-style line endings for consistent results. See
# https://github.com/bazelbuild/stardoc/issues/110.
with opts.output.open(mode='xt', encoding='latin-1', newline='\n') as file:
file.write(text)
if __name__ == '__main__':
_main()
|
95ce6f33cc095df6d0a5f239e075a610eefbe262
|
docs/conf.py
|
docs/conf.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
extensions = ['sphinx.ext.autodoc', 'jaraco.packaging.sphinx', 'rst.linker']
master_doc = "index"
link_files = {
'../CHANGES.rst': dict(
using=dict(GH='https://github.com'),
replace=[
dict(
pattern=r'(Issue #|\B#)(?P<issue>\d+)',
url='{package_url}/issues/{issue}',
),
dict(
pattern=r'^(?m)((?P<scm_version>v?\d+(\.\d+){1,2}))\n[-=]+\n',
with_scm='{text}\n{rev[timestamp]:%d %b %Y}\n',
),
dict(
pattern=r'PEP[- ](?P<pep_number>\d+)',
url='https://www.python.org/dev/peps/pep-{pep_number:0>4}/',
),
],
)
}
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
extensions = ['sphinx.ext.autodoc', 'jaraco.packaging.sphinx', 'rst.linker']
master_doc = "index"
link_files = {
'../CHANGES.rst': dict(
using=dict(GH='https://github.com'),
replace=[
dict(
pattern=r'(Issue #|\B#)(?P<issue>\d+)',
url='{package_url}/issues/{issue}',
),
dict(
pattern=r'(?m:^((?P<scm_version>v?\d+(\.\d+){1,2}))\n[-=]+\n)',
with_scm='{text}\n{rev[timestamp]:%d %b %Y}\n',
),
dict(
pattern=r'PEP[- ](?P<pep_number>\d+)',
url='https://www.python.org/dev/peps/pep-{pep_number:0>4}/',
),
],
)
}
|
Use inline flags with local scope.
|
Use inline flags with local scope.
|
Python
|
mit
|
jaraco/jaraco.path,jaraco/hgtools,jazzband/inflect,yougov/pmxbot,jaraco/jaraco.classes,jaraco/jaraco.functools,jaraco/jaraco.collections,python/importlib_metadata,yougov/pmxbot,jaraco/irc,jaraco/jaraco.text,jaraco/tempora,jaraco/zipp,jaraco/portend,jaraco/backports.functools_lru_cache,jaraco/calendra,pwdyson/inflect.py,jaraco/jaraco.stream,jaraco/jaraco.context,yougov/pmxbot,jaraco/jaraco.logging,jaraco/jaraco.itertools,pytest-dev/pytest-runner,jaraco/keyring
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
extensions = ['sphinx.ext.autodoc', 'jaraco.packaging.sphinx', 'rst.linker']
master_doc = "index"
link_files = {
'../CHANGES.rst': dict(
using=dict(GH='https://github.com'),
replace=[
dict(
pattern=r'(Issue #|\B#)(?P<issue>\d+)',
url='{package_url}/issues/{issue}',
),
dict(
pattern=r'^(?m)((?P<scm_version>v?\d+(\.\d+){1,2}))\n[-=]+\n',
with_scm='{text}\n{rev[timestamp]:%d %b %Y}\n',
),
dict(
pattern=r'PEP[- ](?P<pep_number>\d+)',
url='https://www.python.org/dev/peps/pep-{pep_number:0>4}/',
),
],
)
}
Use inline flags with local scope.
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
extensions = ['sphinx.ext.autodoc', 'jaraco.packaging.sphinx', 'rst.linker']
master_doc = "index"
link_files = {
'../CHANGES.rst': dict(
using=dict(GH='https://github.com'),
replace=[
dict(
pattern=r'(Issue #|\B#)(?P<issue>\d+)',
url='{package_url}/issues/{issue}',
),
dict(
pattern=r'(?m:^((?P<scm_version>v?\d+(\.\d+){1,2}))\n[-=]+\n)',
with_scm='{text}\n{rev[timestamp]:%d %b %Y}\n',
),
dict(
pattern=r'PEP[- ](?P<pep_number>\d+)',
url='https://www.python.org/dev/peps/pep-{pep_number:0>4}/',
),
],
)
}
|
<commit_before>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
extensions = ['sphinx.ext.autodoc', 'jaraco.packaging.sphinx', 'rst.linker']
master_doc = "index"
link_files = {
'../CHANGES.rst': dict(
using=dict(GH='https://github.com'),
replace=[
dict(
pattern=r'(Issue #|\B#)(?P<issue>\d+)',
url='{package_url}/issues/{issue}',
),
dict(
pattern=r'^(?m)((?P<scm_version>v?\d+(\.\d+){1,2}))\n[-=]+\n',
with_scm='{text}\n{rev[timestamp]:%d %b %Y}\n',
),
dict(
pattern=r'PEP[- ](?P<pep_number>\d+)',
url='https://www.python.org/dev/peps/pep-{pep_number:0>4}/',
),
],
)
}
<commit_msg>Use inline flags with local scope.<commit_after>
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
extensions = ['sphinx.ext.autodoc', 'jaraco.packaging.sphinx', 'rst.linker']
master_doc = "index"
link_files = {
'../CHANGES.rst': dict(
using=dict(GH='https://github.com'),
replace=[
dict(
pattern=r'(Issue #|\B#)(?P<issue>\d+)',
url='{package_url}/issues/{issue}',
),
dict(
pattern=r'(?m:^((?P<scm_version>v?\d+(\.\d+){1,2}))\n[-=]+\n)',
with_scm='{text}\n{rev[timestamp]:%d %b %Y}\n',
),
dict(
pattern=r'PEP[- ](?P<pep_number>\d+)',
url='https://www.python.org/dev/peps/pep-{pep_number:0>4}/',
),
],
)
}
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
extensions = ['sphinx.ext.autodoc', 'jaraco.packaging.sphinx', 'rst.linker']
master_doc = "index"
link_files = {
'../CHANGES.rst': dict(
using=dict(GH='https://github.com'),
replace=[
dict(
pattern=r'(Issue #|\B#)(?P<issue>\d+)',
url='{package_url}/issues/{issue}',
),
dict(
pattern=r'^(?m)((?P<scm_version>v?\d+(\.\d+){1,2}))\n[-=]+\n',
with_scm='{text}\n{rev[timestamp]:%d %b %Y}\n',
),
dict(
pattern=r'PEP[- ](?P<pep_number>\d+)',
url='https://www.python.org/dev/peps/pep-{pep_number:0>4}/',
),
],
)
}
Use inline flags with local scope.#!/usr/bin/env python3
# -*- coding: utf-8 -*-
extensions = ['sphinx.ext.autodoc', 'jaraco.packaging.sphinx', 'rst.linker']
master_doc = "index"
link_files = {
'../CHANGES.rst': dict(
using=dict(GH='https://github.com'),
replace=[
dict(
pattern=r'(Issue #|\B#)(?P<issue>\d+)',
url='{package_url}/issues/{issue}',
),
dict(
pattern=r'(?m:^((?P<scm_version>v?\d+(\.\d+){1,2}))\n[-=]+\n)',
with_scm='{text}\n{rev[timestamp]:%d %b %Y}\n',
),
dict(
pattern=r'PEP[- ](?P<pep_number>\d+)',
url='https://www.python.org/dev/peps/pep-{pep_number:0>4}/',
),
],
)
}
|
<commit_before>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
extensions = ['sphinx.ext.autodoc', 'jaraco.packaging.sphinx', 'rst.linker']
master_doc = "index"
link_files = {
'../CHANGES.rst': dict(
using=dict(GH='https://github.com'),
replace=[
dict(
pattern=r'(Issue #|\B#)(?P<issue>\d+)',
url='{package_url}/issues/{issue}',
),
dict(
pattern=r'^(?m)((?P<scm_version>v?\d+(\.\d+){1,2}))\n[-=]+\n',
with_scm='{text}\n{rev[timestamp]:%d %b %Y}\n',
),
dict(
pattern=r'PEP[- ](?P<pep_number>\d+)',
url='https://www.python.org/dev/peps/pep-{pep_number:0>4}/',
),
],
)
}
<commit_msg>Use inline flags with local scope.<commit_after>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
extensions = ['sphinx.ext.autodoc', 'jaraco.packaging.sphinx', 'rst.linker']
master_doc = "index"
link_files = {
'../CHANGES.rst': dict(
using=dict(GH='https://github.com'),
replace=[
dict(
pattern=r'(Issue #|\B#)(?P<issue>\d+)',
url='{package_url}/issues/{issue}',
),
dict(
pattern=r'(?m:^((?P<scm_version>v?\d+(\.\d+){1,2}))\n[-=]+\n)',
with_scm='{text}\n{rev[timestamp]:%d %b %Y}\n',
),
dict(
pattern=r'PEP[- ](?P<pep_number>\d+)',
url='https://www.python.org/dev/peps/pep-{pep_number:0>4}/',
),
],
)
}
|
ab0ba3232c1a7a4b028abe6d371b3935ea0ab110
|
eve_api/tasks.py
|
eve_api/tasks.py
|
from celery.decorators import task
from eve_api.api_puller.accounts import import_eve_account
from eve_api.app_defines import *
from sso.tasks import update_user_access
@task()
def import_apikey(api_userid, api_key, user=None, force_cache=False):
log = import_apikey.get_logger()
l.info("Importing %s/%s" % (api_userid, api_key))
acc = import_eve_account(api_key, api_userid, force_cache=force_cache)
donecorps = []
if acc and acc.api_status == API_STATUS_OK:
if user and not acc.user:
acc.user = user
if acc.api_keytype == API_KEYTYPE_FULL and acc.characters.filter(director=1).count():
donecorps = []
for char in acc.characters.filter(director=1):
if not char.corporation.id in donecorps:
#pull_corp_members(acc.api_key, acc.api_user_id, char.id)
char.corporation.query_and_update_corp()
donecorps.append(char.corporation.id)
for char in acc.characters.all():
try:
if char.corporation.id not in donecorps:
char.corporation.query_and_update_corp()
donecorps.append(char.corporation.id)
except:
continue
acc.save()
if acc.user:
update_user_access.delay(user=acc.user)
return acc
|
from celery.decorators import task
from eve_api.api_puller.accounts import import_eve_account
from eve_api.app_defines import *
from sso.tasks import update_user_access
@task()
def import_apikey(api_userid, api_key, user=None, force_cache=False):
acc = import_eve_account(api_key, api_userid, force_cache=force_cache)
donecorps = []
if acc and acc.api_status == API_STATUS_OK:
if user and not acc.user:
acc.user = user
if acc.api_keytype == API_KEYTYPE_FULL and acc.characters.filter(director=1).count():
donecorps = []
for char in acc.characters.filter(director=1):
if not char.corporation.id in donecorps:
#pull_corp_members(acc.api_key, acc.api_user_id, char.id)
char.corporation.query_and_update_corp()
donecorps.append(char.corporation.id)
for char in acc.characters.all():
try:
if char.corporation.id not in donecorps:
char.corporation.query_and_update_corp()
donecorps.append(char.corporation.id)
except:
continue
acc.save()
if acc.user:
update_user_access.delay(user=acc.user)
return acc
|
Fix error in the apikey import task
|
Fix error in the apikey import task
|
Python
|
bsd-3-clause
|
nikdoof/test-auth
|
from celery.decorators import task
from eve_api.api_puller.accounts import import_eve_account
from eve_api.app_defines import *
from sso.tasks import update_user_access
@task()
def import_apikey(api_userid, api_key, user=None, force_cache=False):
log = import_apikey.get_logger()
l.info("Importing %s/%s" % (api_userid, api_key))
acc = import_eve_account(api_key, api_userid, force_cache=force_cache)
donecorps = []
if acc and acc.api_status == API_STATUS_OK:
if user and not acc.user:
acc.user = user
if acc.api_keytype == API_KEYTYPE_FULL and acc.characters.filter(director=1).count():
donecorps = []
for char in acc.characters.filter(director=1):
if not char.corporation.id in donecorps:
#pull_corp_members(acc.api_key, acc.api_user_id, char.id)
char.corporation.query_and_update_corp()
donecorps.append(char.corporation.id)
for char in acc.characters.all():
try:
if char.corporation.id not in donecorps:
char.corporation.query_and_update_corp()
donecorps.append(char.corporation.id)
except:
continue
acc.save()
if acc.user:
update_user_access.delay(user=acc.user)
return acc
Fix error in the apikey import task
|
from celery.decorators import task
from eve_api.api_puller.accounts import import_eve_account
from eve_api.app_defines import *
from sso.tasks import update_user_access
@task()
def import_apikey(api_userid, api_key, user=None, force_cache=False):
acc = import_eve_account(api_key, api_userid, force_cache=force_cache)
donecorps = []
if acc and acc.api_status == API_STATUS_OK:
if user and not acc.user:
acc.user = user
if acc.api_keytype == API_KEYTYPE_FULL and acc.characters.filter(director=1).count():
donecorps = []
for char in acc.characters.filter(director=1):
if not char.corporation.id in donecorps:
#pull_corp_members(acc.api_key, acc.api_user_id, char.id)
char.corporation.query_and_update_corp()
donecorps.append(char.corporation.id)
for char in acc.characters.all():
try:
if char.corporation.id not in donecorps:
char.corporation.query_and_update_corp()
donecorps.append(char.corporation.id)
except:
continue
acc.save()
if acc.user:
update_user_access.delay(user=acc.user)
return acc
|
<commit_before>from celery.decorators import task
from eve_api.api_puller.accounts import import_eve_account
from eve_api.app_defines import *
from sso.tasks import update_user_access
@task()
def import_apikey(api_userid, api_key, user=None, force_cache=False):
log = import_apikey.get_logger()
l.info("Importing %s/%s" % (api_userid, api_key))
acc = import_eve_account(api_key, api_userid, force_cache=force_cache)
donecorps = []
if acc and acc.api_status == API_STATUS_OK:
if user and not acc.user:
acc.user = user
if acc.api_keytype == API_KEYTYPE_FULL and acc.characters.filter(director=1).count():
donecorps = []
for char in acc.characters.filter(director=1):
if not char.corporation.id in donecorps:
#pull_corp_members(acc.api_key, acc.api_user_id, char.id)
char.corporation.query_and_update_corp()
donecorps.append(char.corporation.id)
for char in acc.characters.all():
try:
if char.corporation.id not in donecorps:
char.corporation.query_and_update_corp()
donecorps.append(char.corporation.id)
except:
continue
acc.save()
if acc.user:
update_user_access.delay(user=acc.user)
return acc
<commit_msg>Fix error in the apikey import task<commit_after>
|
from celery.decorators import task
from eve_api.api_puller.accounts import import_eve_account
from eve_api.app_defines import *
from sso.tasks import update_user_access
@task()
def import_apikey(api_userid, api_key, user=None, force_cache=False):
acc = import_eve_account(api_key, api_userid, force_cache=force_cache)
donecorps = []
if acc and acc.api_status == API_STATUS_OK:
if user and not acc.user:
acc.user = user
if acc.api_keytype == API_KEYTYPE_FULL and acc.characters.filter(director=1).count():
donecorps = []
for char in acc.characters.filter(director=1):
if not char.corporation.id in donecorps:
#pull_corp_members(acc.api_key, acc.api_user_id, char.id)
char.corporation.query_and_update_corp()
donecorps.append(char.corporation.id)
for char in acc.characters.all():
try:
if char.corporation.id not in donecorps:
char.corporation.query_and_update_corp()
donecorps.append(char.corporation.id)
except:
continue
acc.save()
if acc.user:
update_user_access.delay(user=acc.user)
return acc
|
from celery.decorators import task
from eve_api.api_puller.accounts import import_eve_account
from eve_api.app_defines import *
from sso.tasks import update_user_access
@task()
def import_apikey(api_userid, api_key, user=None, force_cache=False):
log = import_apikey.get_logger()
l.info("Importing %s/%s" % (api_userid, api_key))
acc = import_eve_account(api_key, api_userid, force_cache=force_cache)
donecorps = []
if acc and acc.api_status == API_STATUS_OK:
if user and not acc.user:
acc.user = user
if acc.api_keytype == API_KEYTYPE_FULL and acc.characters.filter(director=1).count():
donecorps = []
for char in acc.characters.filter(director=1):
if not char.corporation.id in donecorps:
#pull_corp_members(acc.api_key, acc.api_user_id, char.id)
char.corporation.query_and_update_corp()
donecorps.append(char.corporation.id)
for char in acc.characters.all():
try:
if char.corporation.id not in donecorps:
char.corporation.query_and_update_corp()
donecorps.append(char.corporation.id)
except:
continue
acc.save()
if acc.user:
update_user_access.delay(user=acc.user)
return acc
Fix error in the apikey import taskfrom celery.decorators import task
from eve_api.api_puller.accounts import import_eve_account
from eve_api.app_defines import *
from sso.tasks import update_user_access
@task()
def import_apikey(api_userid, api_key, user=None, force_cache=False):
acc = import_eve_account(api_key, api_userid, force_cache=force_cache)
donecorps = []
if acc and acc.api_status == API_STATUS_OK:
if user and not acc.user:
acc.user = user
if acc.api_keytype == API_KEYTYPE_FULL and acc.characters.filter(director=1).count():
donecorps = []
for char in acc.characters.filter(director=1):
if not char.corporation.id in donecorps:
#pull_corp_members(acc.api_key, acc.api_user_id, char.id)
char.corporation.query_and_update_corp()
donecorps.append(char.corporation.id)
for char in acc.characters.all():
try:
if char.corporation.id not in donecorps:
char.corporation.query_and_update_corp()
donecorps.append(char.corporation.id)
except:
continue
acc.save()
if acc.user:
update_user_access.delay(user=acc.user)
return acc
|
<commit_before>from celery.decorators import task
from eve_api.api_puller.accounts import import_eve_account
from eve_api.app_defines import *
from sso.tasks import update_user_access
@task()
def import_apikey(api_userid, api_key, user=None, force_cache=False):
log = import_apikey.get_logger()
l.info("Importing %s/%s" % (api_userid, api_key))
acc = import_eve_account(api_key, api_userid, force_cache=force_cache)
donecorps = []
if acc and acc.api_status == API_STATUS_OK:
if user and not acc.user:
acc.user = user
if acc.api_keytype == API_KEYTYPE_FULL and acc.characters.filter(director=1).count():
donecorps = []
for char in acc.characters.filter(director=1):
if not char.corporation.id in donecorps:
#pull_corp_members(acc.api_key, acc.api_user_id, char.id)
char.corporation.query_and_update_corp()
donecorps.append(char.corporation.id)
for char in acc.characters.all():
try:
if char.corporation.id not in donecorps:
char.corporation.query_and_update_corp()
donecorps.append(char.corporation.id)
except:
continue
acc.save()
if acc.user:
update_user_access.delay(user=acc.user)
return acc
<commit_msg>Fix error in the apikey import task<commit_after>from celery.decorators import task
from eve_api.api_puller.accounts import import_eve_account
from eve_api.app_defines import *
from sso.tasks import update_user_access
@task()
def import_apikey(api_userid, api_key, user=None, force_cache=False):
acc = import_eve_account(api_key, api_userid, force_cache=force_cache)
donecorps = []
if acc and acc.api_status == API_STATUS_OK:
if user and not acc.user:
acc.user = user
if acc.api_keytype == API_KEYTYPE_FULL and acc.characters.filter(director=1).count():
donecorps = []
for char in acc.characters.filter(director=1):
if not char.corporation.id in donecorps:
#pull_corp_members(acc.api_key, acc.api_user_id, char.id)
char.corporation.query_and_update_corp()
donecorps.append(char.corporation.id)
for char in acc.characters.all():
try:
if char.corporation.id not in donecorps:
char.corporation.query_and_update_corp()
donecorps.append(char.corporation.id)
except:
continue
acc.save()
if acc.user:
update_user_access.delay(user=acc.user)
return acc
|
fcde79c7743b621be31acc4bd4e5826b121d573d
|
nalaf/download_corpora.py
|
nalaf/download_corpora.py
|
"""
Downloads the necessary NLTK corpora for nalaf.
Usage: ::
$ python -m nalaf.download_corpora
"""
if __name__ == '__main__':
import nltk
CORPORA = ['punkt']
for corpus in CORPORA:
nltk.download(corpus)
|
"""
Downloads the necessary NLTK corpora for nalaf.
Usage: ::
$ python -m nalaf.download_corpora
"""
if __name__ == '__main__':
from nltk import download
CORPORA = ['punkt']
for corpus in CORPORA:
download(corpus)
|
Fix a build for travis-CI
|
Fix a build for travis-CI
|
Python
|
apache-2.0
|
Rostlab/nalaf
|
"""
Downloads the necessary NLTK corpora for nalaf.
Usage: ::
$ python -m nalaf.download_corpora
"""
if __name__ == '__main__':
import nltk
CORPORA = ['punkt']
for corpus in CORPORA:
nltk.download(corpus)Fix a build for travis-CI
|
"""
Downloads the necessary NLTK corpora for nalaf.
Usage: ::
$ python -m nalaf.download_corpora
"""
if __name__ == '__main__':
from nltk import download
CORPORA = ['punkt']
for corpus in CORPORA:
download(corpus)
|
<commit_before>"""
Downloads the necessary NLTK corpora for nalaf.
Usage: ::
$ python -m nalaf.download_corpora
"""
if __name__ == '__main__':
import nltk
CORPORA = ['punkt']
for corpus in CORPORA:
nltk.download(corpus)<commit_msg>Fix a build for travis-CI<commit_after>
|
"""
Downloads the necessary NLTK corpora for nalaf.
Usage: ::
$ python -m nalaf.download_corpora
"""
if __name__ == '__main__':
from nltk import download
CORPORA = ['punkt']
for corpus in CORPORA:
download(corpus)
|
"""
Downloads the necessary NLTK corpora for nalaf.
Usage: ::
$ python -m nalaf.download_corpora
"""
if __name__ == '__main__':
import nltk
CORPORA = ['punkt']
for corpus in CORPORA:
nltk.download(corpus)Fix a build for travis-CI"""
Downloads the necessary NLTK corpora for nalaf.
Usage: ::
$ python -m nalaf.download_corpora
"""
if __name__ == '__main__':
from nltk import download
CORPORA = ['punkt']
for corpus in CORPORA:
download(corpus)
|
<commit_before>"""
Downloads the necessary NLTK corpora for nalaf.
Usage: ::
$ python -m nalaf.download_corpora
"""
if __name__ == '__main__':
import nltk
CORPORA = ['punkt']
for corpus in CORPORA:
nltk.download(corpus)<commit_msg>Fix a build for travis-CI<commit_after>"""
Downloads the necessary NLTK corpora for nalaf.
Usage: ::
$ python -m nalaf.download_corpora
"""
if __name__ == '__main__':
from nltk import download
CORPORA = ['punkt']
for corpus in CORPORA:
download(corpus)
|
84f17b192c97212c7fdd963208f41085c85f08a5
|
examples/constant_liar.py
|
examples/constant_liar.py
|
"""
Example for parallel optimization with skopt.
The points to evaluate in parallel are selected according to the "constant lie" approach.
"""
import numpy as np
from multiprocessing.pool import ThreadPool
from skopt.space import Real
from skopt.learning import GaussianProcessRegressor
from skopt import Optimizer
# ThreadPool is used for parallel computations
pool = ThreadPool()
optimizer = Optimizer(
base_estimator=GaussianProcessRegressor(),
dimensions=[Real(-3.0, 3.0) for i in range(10)]
)
# configure number of threads to be used in parallel, and overall # of computations
n_points, n_steps, Y = 4, 20, []
for i in range(n_steps):
x = optimizer.ask(n_points)
# evaluate n_points in parallel
y = pool.map(lambda x: np.sum(np.array(x) ** 2), x)
# tell points and corresponding objectives to the optimizer
optimizer.tell(x, y)
# keep objectives history
Y.extend(y)
print min(Y)
|
"""
Example for parallel optimization with skopt.
The points to evaluate in parallel are selected according to the "constant lie" approach.
"""
import numpy as np
from sklearn.externals.joblib import Parallel, delayed
from skopt.space import Real
from skopt.learning import GaussianProcessRegressor
from skopt import Optimizer
optimizer = Optimizer(
base_estimator=GaussianProcessRegressor(),
dimensions=[Real(-3.0, 3.0) for i in range(10)]
)
# objective function to minimze
def objective(x):
return np.sum(np.array(x) ** 2)
# configure number of threads to be used in parallel, and overall # of computations
n_points, n_steps, Y = 4, 20, []
for i in range(n_steps):
x = optimizer.ask(n_points)
# evaluate n_points in parallel
y = Parallel()(delayed(objective)(v) for v in x)
# tell points and corresponding objectives to the optimizer
optimizer.tell(x, y)
# keep objectives history
Y.extend(y)
print min(Y)
|
Drop ThreadPool, use joblib instead
|
Drop ThreadPool, use joblib instead
|
Python
|
bsd-3-clause
|
scikit-optimize/scikit-optimize,betatim/BlackBox,betatim/BlackBox,scikit-optimize/scikit-optimize
|
"""
Example for parallel optimization with skopt.
The points to evaluate in parallel are selected according to the "constant lie" approach.
"""
import numpy as np
from multiprocessing.pool import ThreadPool
from skopt.space import Real
from skopt.learning import GaussianProcessRegressor
from skopt import Optimizer
# ThreadPool is used for parallel computations
pool = ThreadPool()
optimizer = Optimizer(
base_estimator=GaussianProcessRegressor(),
dimensions=[Real(-3.0, 3.0) for i in range(10)]
)
# configure number of threads to be used in parallel, and overall # of computations
n_points, n_steps, Y = 4, 20, []
for i in range(n_steps):
x = optimizer.ask(n_points)
# evaluate n_points in parallel
y = pool.map(lambda x: np.sum(np.array(x) ** 2), x)
# tell points and corresponding objectives to the optimizer
optimizer.tell(x, y)
# keep objectives history
Y.extend(y)
print min(Y)
Drop ThreadPool, use joblib instead
|
"""
Example for parallel optimization with skopt.
The points to evaluate in parallel are selected according to the "constant lie" approach.
"""
import numpy as np
from sklearn.externals.joblib import Parallel, delayed
from skopt.space import Real
from skopt.learning import GaussianProcessRegressor
from skopt import Optimizer
optimizer = Optimizer(
base_estimator=GaussianProcessRegressor(),
dimensions=[Real(-3.0, 3.0) for i in range(10)]
)
# objective function to minimze
def objective(x):
return np.sum(np.array(x) ** 2)
# configure number of threads to be used in parallel, and overall # of computations
n_points, n_steps, Y = 4, 20, []
for i in range(n_steps):
x = optimizer.ask(n_points)
# evaluate n_points in parallel
y = Parallel()(delayed(objective)(v) for v in x)
# tell points and corresponding objectives to the optimizer
optimizer.tell(x, y)
# keep objectives history
Y.extend(y)
print min(Y)
|
<commit_before>"""
Example for parallel optimization with skopt.
The points to evaluate in parallel are selected according to the "constant lie" approach.
"""
import numpy as np
from multiprocessing.pool import ThreadPool
from skopt.space import Real
from skopt.learning import GaussianProcessRegressor
from skopt import Optimizer
# ThreadPool is used for parallel computations
pool = ThreadPool()
optimizer = Optimizer(
base_estimator=GaussianProcessRegressor(),
dimensions=[Real(-3.0, 3.0) for i in range(10)]
)
# configure number of threads to be used in parallel, and overall # of computations
n_points, n_steps, Y = 4, 20, []
for i in range(n_steps):
x = optimizer.ask(n_points)
# evaluate n_points in parallel
y = pool.map(lambda x: np.sum(np.array(x) ** 2), x)
# tell points and corresponding objectives to the optimizer
optimizer.tell(x, y)
# keep objectives history
Y.extend(y)
print min(Y)
<commit_msg>Drop ThreadPool, use joblib instead<commit_after>
|
"""
Example for parallel optimization with skopt.
The points to evaluate in parallel are selected according to the "constant lie" approach.
"""
import numpy as np
from sklearn.externals.joblib import Parallel, delayed
from skopt.space import Real
from skopt.learning import GaussianProcessRegressor
from skopt import Optimizer
optimizer = Optimizer(
base_estimator=GaussianProcessRegressor(),
dimensions=[Real(-3.0, 3.0) for i in range(10)]
)
# objective function to minimze
def objective(x):
return np.sum(np.array(x) ** 2)
# configure number of threads to be used in parallel, and overall # of computations
n_points, n_steps, Y = 4, 20, []
for i in range(n_steps):
x = optimizer.ask(n_points)
# evaluate n_points in parallel
y = Parallel()(delayed(objective)(v) for v in x)
# tell points and corresponding objectives to the optimizer
optimizer.tell(x, y)
# keep objectives history
Y.extend(y)
print min(Y)
|
"""
Example for parallel optimization with skopt.
The points to evaluate in parallel are selected according to the "constant lie" approach.
"""
import numpy as np
from multiprocessing.pool import ThreadPool
from skopt.space import Real
from skopt.learning import GaussianProcessRegressor
from skopt import Optimizer
# ThreadPool is used for parallel computations
pool = ThreadPool()
optimizer = Optimizer(
base_estimator=GaussianProcessRegressor(),
dimensions=[Real(-3.0, 3.0) for i in range(10)]
)
# configure number of threads to be used in parallel, and overall # of computations
n_points, n_steps, Y = 4, 20, []
for i in range(n_steps):
x = optimizer.ask(n_points)
# evaluate n_points in parallel
y = pool.map(lambda x: np.sum(np.array(x) ** 2), x)
# tell points and corresponding objectives to the optimizer
optimizer.tell(x, y)
# keep objectives history
Y.extend(y)
print min(Y)
Drop ThreadPool, use joblib instead"""
Example for parallel optimization with skopt.
The points to evaluate in parallel are selected according to the "constant lie" approach.
"""
import numpy as np
from sklearn.externals.joblib import Parallel, delayed
from skopt.space import Real
from skopt.learning import GaussianProcessRegressor
from skopt import Optimizer
optimizer = Optimizer(
base_estimator=GaussianProcessRegressor(),
dimensions=[Real(-3.0, 3.0) for i in range(10)]
)
# objective function to minimze
def objective(x):
return np.sum(np.array(x) ** 2)
# configure number of threads to be used in parallel, and overall # of computations
n_points, n_steps, Y = 4, 20, []
for i in range(n_steps):
x = optimizer.ask(n_points)
# evaluate n_points in parallel
y = Parallel()(delayed(objective)(v) for v in x)
# tell points and corresponding objectives to the optimizer
optimizer.tell(x, y)
# keep objectives history
Y.extend(y)
print min(Y)
|
<commit_before>"""
Example for parallel optimization with skopt.
The points to evaluate in parallel are selected according to the "constant lie" approach.
"""
import numpy as np
from multiprocessing.pool import ThreadPool
from skopt.space import Real
from skopt.learning import GaussianProcessRegressor
from skopt import Optimizer
# ThreadPool is used for parallel computations
pool = ThreadPool()
optimizer = Optimizer(
base_estimator=GaussianProcessRegressor(),
dimensions=[Real(-3.0, 3.0) for i in range(10)]
)
# configure number of threads to be used in parallel, and overall # of computations
n_points, n_steps, Y = 4, 20, []
for i in range(n_steps):
x = optimizer.ask(n_points)
# evaluate n_points in parallel
y = pool.map(lambda x: np.sum(np.array(x) ** 2), x)
# tell points and corresponding objectives to the optimizer
optimizer.tell(x, y)
# keep objectives history
Y.extend(y)
print min(Y)
<commit_msg>Drop ThreadPool, use joblib instead<commit_after>"""
Example for parallel optimization with skopt.
The points to evaluate in parallel are selected according to the "constant lie" approach.
"""
import numpy as np
from sklearn.externals.joblib import Parallel, delayed
from skopt.space import Real
from skopt.learning import GaussianProcessRegressor
from skopt import Optimizer
optimizer = Optimizer(
base_estimator=GaussianProcessRegressor(),
dimensions=[Real(-3.0, 3.0) for i in range(10)]
)
# objective function to minimze
def objective(x):
return np.sum(np.array(x) ** 2)
# configure number of threads to be used in parallel, and overall # of computations
n_points, n_steps, Y = 4, 20, []
for i in range(n_steps):
x = optimizer.ask(n_points)
# evaluate n_points in parallel
y = Parallel()(delayed(objective)(v) for v in x)
# tell points and corresponding objectives to the optimizer
optimizer.tell(x, y)
# keep objectives history
Y.extend(y)
print min(Y)
|
4071adfe51a94376045fa31538f1ab94615ba962
|
escalator.py
|
escalator.py
|
"""Creates the escalator class"""
class Escalator:
"""
Each escalator is an instance of the escalator class.
Methods:
__init__: creates a new escalator
rate: calculates the rate people leave the escalator
"""
def __init__(self):
self.stand_time = None
self.stand_space = None
self.walk_time = None
self.walk_space = None
@property
def rate(self):
return (self.stand_time * self.stand_space) + self.walk_time * (self.walk_space)
|
"""Creates the escalator class"""
class Escalator:
"""
Each escalator is an instance of the escalator class.
Methods:
__init__: creates a new escalator
rate: calculates the rate people leave the escalator
"""
def __init__(self):
self.stand_time = eval(input("Enter a standing escalator transit time: "))
#testfunction() a function that will test if this is a positive number
self.stand_space = eval(input("Enter the number of stairs between standing people: "))
#testfuntion()
self.walk_time = eval(input("Enter a walking escalator transit time: "))
#testfuntion()
self.walk_space = eval(input("Enter the number of stairs between walking peopld: "))
#testfuntion()
@property
def rate(self):
return (self.stand_time * self.stand_space) + (self.walk_time * self.walk_space)
|
Add input statements and edit parentheses in rate
|
Add input statements and edit parentheses in rate
Attempted to add some input functions into the elevator constructor.
Ref #25 #23
|
Python
|
mit
|
ForestPride/rail-problem
|
"""Creates the escalator class"""
class Escalator:
"""
Each escalator is an instance of the escalator class.
Methods:
__init__: creates a new escalator
rate: calculates the rate people leave the escalator
"""
def __init__(self):
self.stand_time = None
self.stand_space = None
self.walk_time = None
self.walk_space = None
@property
def rate(self):
return (self.stand_time * self.stand_space) + self.walk_time * (self.walk_space)
Add input statements and edit parentheses in rate
Attempted to add some input functions into the elevator constructor.
Ref #25 #23
|
"""Creates the escalator class"""
class Escalator:
"""
Each escalator is an instance of the escalator class.
Methods:
__init__: creates a new escalator
rate: calculates the rate people leave the escalator
"""
def __init__(self):
self.stand_time = eval(input("Enter a standing escalator transit time: "))
#testfunction() a function that will test if this is a positive number
self.stand_space = eval(input("Enter the number of stairs between standing people: "))
#testfuntion()
self.walk_time = eval(input("Enter a walking escalator transit time: "))
#testfuntion()
self.walk_space = eval(input("Enter the number of stairs between walking peopld: "))
#testfuntion()
@property
def rate(self):
return (self.stand_time * self.stand_space) + (self.walk_time * self.walk_space)
|
<commit_before>"""Creates the escalator class"""
class Escalator:
"""
Each escalator is an instance of the escalator class.
Methods:
__init__: creates a new escalator
rate: calculates the rate people leave the escalator
"""
def __init__(self):
self.stand_time = None
self.stand_space = None
self.walk_time = None
self.walk_space = None
@property
def rate(self):
return (self.stand_time * self.stand_space) + self.walk_time * (self.walk_space)
<commit_msg>Add input statements and edit parentheses in rate
Attempted to add some input functions into the elevator constructor.
Ref #25 #23<commit_after>
|
"""Creates the escalator class"""
class Escalator:
"""
Each escalator is an instance of the escalator class.
Methods:
__init__: creates a new escalator
rate: calculates the rate people leave the escalator
"""
def __init__(self):
self.stand_time = eval(input("Enter a standing escalator transit time: "))
#testfunction() a function that will test if this is a positive number
self.stand_space = eval(input("Enter the number of stairs between standing people: "))
#testfuntion()
self.walk_time = eval(input("Enter a walking escalator transit time: "))
#testfuntion()
self.walk_space = eval(input("Enter the number of stairs between walking peopld: "))
#testfuntion()
@property
def rate(self):
return (self.stand_time * self.stand_space) + (self.walk_time * self.walk_space)
|
"""Creates the escalator class"""
class Escalator:
"""
Each escalator is an instance of the escalator class.
Methods:
__init__: creates a new escalator
rate: calculates the rate people leave the escalator
"""
def __init__(self):
self.stand_time = None
self.stand_space = None
self.walk_time = None
self.walk_space = None
@property
def rate(self):
return (self.stand_time * self.stand_space) + self.walk_time * (self.walk_space)
Add input statements and edit parentheses in rate
Attempted to add some input functions into the elevator constructor.
Ref #25 #23"""Creates the escalator class"""
class Escalator:
"""
Each escalator is an instance of the escalator class.
Methods:
__init__: creates a new escalator
rate: calculates the rate people leave the escalator
"""
def __init__(self):
self.stand_time = eval(input("Enter a standing escalator transit time: "))
#testfunction() a function that will test if this is a positive number
self.stand_space = eval(input("Enter the number of stairs between standing people: "))
#testfuntion()
self.walk_time = eval(input("Enter a walking escalator transit time: "))
#testfuntion()
self.walk_space = eval(input("Enter the number of stairs between walking peopld: "))
#testfuntion()
@property
def rate(self):
return (self.stand_time * self.stand_space) + (self.walk_time * self.walk_space)
|
<commit_before>"""Creates the escalator class"""
class Escalator:
"""
Each escalator is an instance of the escalator class.
Methods:
__init__: creates a new escalator
rate: calculates the rate people leave the escalator
"""
def __init__(self):
self.stand_time = None
self.stand_space = None
self.walk_time = None
self.walk_space = None
@property
def rate(self):
return (self.stand_time * self.stand_space) + self.walk_time * (self.walk_space)
<commit_msg>Add input statements and edit parentheses in rate
Attempted to add some input functions into the elevator constructor.
Ref #25 #23<commit_after>"""Creates the escalator class"""
class Escalator:
"""
Each escalator is an instance of the escalator class.
Methods:
__init__: creates a new escalator
rate: calculates the rate people leave the escalator
"""
def __init__(self):
self.stand_time = eval(input("Enter a standing escalator transit time: "))
#testfunction() a function that will test if this is a positive number
self.stand_space = eval(input("Enter the number of stairs between standing people: "))
#testfuntion()
self.walk_time = eval(input("Enter a walking escalator transit time: "))
#testfuntion()
self.walk_space = eval(input("Enter the number of stairs between walking peopld: "))
#testfuntion()
@property
def rate(self):
return (self.stand_time * self.stand_space) + (self.walk_time * self.walk_space)
|
92e1803a4c9e38a8672e00afbcfe0807ea808565
|
examples/reading/rtf15.py
|
examples/reading/rtf15.py
|
from pyth.plugins.rtf15.reader import Rtf15Reader
from pyth.plugins.xhtml.writer import XHTMLWriter
import sys
if len(sys.argv) > 1:
filename = sys.argv[1]
else:
filename = "sample.rtf"
doc = Rtf15Reader.read(open(filename))
print XHTMLWriter.write(doc, pretty=True).read()
|
from pyth.plugins.rtf15.reader import Rtf15Reader
from pyth.plugins.xhtml.writer import XHTMLWriter
import sys
if len(sys.argv) > 1:
filename = sys.argv[1]
else:
filename = "sample.rtf"
doc = Rtf15Reader.read(open(filename, "rb"))
print XHTMLWriter.write(doc, pretty=True).read()
|
Make RTF reader sample open in 'rb' mode explicitly
|
Make RTF reader sample open in 'rb' mode explicitly
|
Python
|
mit
|
kippr/pyth,kippr/pyth,prechelt/pyth,eriol/pyth,brendonh/pyth,prechelt/pyth,sheepeatingtaz/pyth,pombredanne/pyth
|
from pyth.plugins.rtf15.reader import Rtf15Reader
from pyth.plugins.xhtml.writer import XHTMLWriter
import sys
if len(sys.argv) > 1:
filename = sys.argv[1]
else:
filename = "sample.rtf"
doc = Rtf15Reader.read(open(filename))
print XHTMLWriter.write(doc, pretty=True).read()
Make RTF reader sample open in 'rb' mode explicitly
|
from pyth.plugins.rtf15.reader import Rtf15Reader
from pyth.plugins.xhtml.writer import XHTMLWriter
import sys
if len(sys.argv) > 1:
filename = sys.argv[1]
else:
filename = "sample.rtf"
doc = Rtf15Reader.read(open(filename, "rb"))
print XHTMLWriter.write(doc, pretty=True).read()
|
<commit_before>from pyth.plugins.rtf15.reader import Rtf15Reader
from pyth.plugins.xhtml.writer import XHTMLWriter
import sys
if len(sys.argv) > 1:
filename = sys.argv[1]
else:
filename = "sample.rtf"
doc = Rtf15Reader.read(open(filename))
print XHTMLWriter.write(doc, pretty=True).read()
<commit_msg>Make RTF reader sample open in 'rb' mode explicitly<commit_after>
|
from pyth.plugins.rtf15.reader import Rtf15Reader
from pyth.plugins.xhtml.writer import XHTMLWriter
import sys
if len(sys.argv) > 1:
filename = sys.argv[1]
else:
filename = "sample.rtf"
doc = Rtf15Reader.read(open(filename, "rb"))
print XHTMLWriter.write(doc, pretty=True).read()
|
from pyth.plugins.rtf15.reader import Rtf15Reader
from pyth.plugins.xhtml.writer import XHTMLWriter
import sys
if len(sys.argv) > 1:
filename = sys.argv[1]
else:
filename = "sample.rtf"
doc = Rtf15Reader.read(open(filename))
print XHTMLWriter.write(doc, pretty=True).read()
Make RTF reader sample open in 'rb' mode explicitlyfrom pyth.plugins.rtf15.reader import Rtf15Reader
from pyth.plugins.xhtml.writer import XHTMLWriter
import sys
if len(sys.argv) > 1:
filename = sys.argv[1]
else:
filename = "sample.rtf"
doc = Rtf15Reader.read(open(filename, "rb"))
print XHTMLWriter.write(doc, pretty=True).read()
|
<commit_before>from pyth.plugins.rtf15.reader import Rtf15Reader
from pyth.plugins.xhtml.writer import XHTMLWriter
import sys
if len(sys.argv) > 1:
filename = sys.argv[1]
else:
filename = "sample.rtf"
doc = Rtf15Reader.read(open(filename))
print XHTMLWriter.write(doc, pretty=True).read()
<commit_msg>Make RTF reader sample open in 'rb' mode explicitly<commit_after>from pyth.plugins.rtf15.reader import Rtf15Reader
from pyth.plugins.xhtml.writer import XHTMLWriter
import sys
if len(sys.argv) > 1:
filename = sys.argv[1]
else:
filename = "sample.rtf"
doc = Rtf15Reader.read(open(filename, "rb"))
print XHTMLWriter.write(doc, pretty=True).read()
|
65b418b8eaa8f57fdd3c8207168451da20b452bf
|
src/python/rgplot/RgChart.py
|
src/python/rgplot/RgChart.py
|
import matplotlib.pyplot as plt
#class RgChart(object):
#__metaclass__ = ABCMeta
class RgChart(object):
def with_grids(self):
self._ax.xaxis.grid(True)
self._ax.yaxis.grid(True)
return self
def save_as(self, filename):
self._create_plot()
self._fig.savefig(filename)
plt.close(self._fig) # close on save to avoid memory issues
def with_ygrid(self):
self._ax.yaxis.grid(True)
return self
def with_title(self, title = None):
if title is None:
plt.title(self._title)
else:
plt.title(title)
return self
def with_xlabel(self, xlabel = None):
if xlabel is None:
plt.xlabel(self._xlabel)
else:
plt.xlabel(xlabel)
return self
def with_ylabel(self, ylabel = None):
if ylabel is None:
plt.ylabel(self._ylabel)
else:
plt.ylabel(ylabel)
return self
def with_ylim(self, lim):
self._ax.set_ylim(lim)
return self
def wo_xticks(self):
self._ax.get_xaxis().set_ticks([])
return self
def wo_yticks(self):
self._ax.get_yaxis().set_ticks([])
return self
def _create_plot(self):
pass
|
import matplotlib.pyplot as plt
#class RgChart(object):
#__metaclass__ = ABCMeta
class RgChart(object):
TITLE_Y_OFFSET = 1.08
def with_grids(self):
self._ax.xaxis.grid(True)
self._ax.yaxis.grid(True)
return self
def save_as(self, filename):
self._create_plot()
self._fig.savefig(filename)
plt.close(self._fig) # close on save to avoid memory issues
def with_ygrid(self):
self._ax.yaxis.grid(True)
return self
def with_title(self, title = None, y_offset = RgChart.TITLE_Y_OFFSET):
if title is None:
plt.title(self._title, y = y_offset)
else:
plt.title(title, y = y_offset)
return self
def with_xlabel(self, xlabel = None):
if xlabel is None:
plt.xlabel(self._xlabel)
else:
plt.xlabel(xlabel)
return self
def with_ylabel(self, ylabel = None):
if ylabel is None:
plt.ylabel(self._ylabel)
else:
plt.ylabel(ylabel)
return self
def with_ylog(self):
self._ax.set_yscale('log')
return self
def with_ylim(self, lim):
self._ax.set_ylim(lim)
return self
def wo_xticks(self):
self._ax.get_xaxis().set_ticks([])
return self
def wo_yticks(self):
self._ax.get_yaxis().set_ticks([])
return self
def _create_plot(self):
pass
|
Add y log option and title offset
|
Add y log option and title offset
|
Python
|
mit
|
vjuranek/rg-offline-plotting,vjuranek/rg-offline-plotting
|
import matplotlib.pyplot as plt
#class RgChart(object):
#__metaclass__ = ABCMeta
class RgChart(object):
def with_grids(self):
self._ax.xaxis.grid(True)
self._ax.yaxis.grid(True)
return self
def save_as(self, filename):
self._create_plot()
self._fig.savefig(filename)
plt.close(self._fig) # close on save to avoid memory issues
def with_ygrid(self):
self._ax.yaxis.grid(True)
return self
def with_title(self, title = None):
if title is None:
plt.title(self._title)
else:
plt.title(title)
return self
def with_xlabel(self, xlabel = None):
if xlabel is None:
plt.xlabel(self._xlabel)
else:
plt.xlabel(xlabel)
return self
def with_ylabel(self, ylabel = None):
if ylabel is None:
plt.ylabel(self._ylabel)
else:
plt.ylabel(ylabel)
return self
def with_ylim(self, lim):
self._ax.set_ylim(lim)
return self
def wo_xticks(self):
self._ax.get_xaxis().set_ticks([])
return self
def wo_yticks(self):
self._ax.get_yaxis().set_ticks([])
return self
def _create_plot(self):
pass
Add y log option and title offset
|
import matplotlib.pyplot as plt
#class RgChart(object):
#__metaclass__ = ABCMeta
class RgChart(object):
TITLE_Y_OFFSET = 1.08
def with_grids(self):
self._ax.xaxis.grid(True)
self._ax.yaxis.grid(True)
return self
def save_as(self, filename):
self._create_plot()
self._fig.savefig(filename)
plt.close(self._fig) # close on save to avoid memory issues
def with_ygrid(self):
self._ax.yaxis.grid(True)
return self
def with_title(self, title = None, y_offset = RgChart.TITLE_Y_OFFSET):
if title is None:
plt.title(self._title, y = y_offset)
else:
plt.title(title, y = y_offset)
return self
def with_xlabel(self, xlabel = None):
if xlabel is None:
plt.xlabel(self._xlabel)
else:
plt.xlabel(xlabel)
return self
def with_ylabel(self, ylabel = None):
if ylabel is None:
plt.ylabel(self._ylabel)
else:
plt.ylabel(ylabel)
return self
def with_ylog(self):
self._ax.set_yscale('log')
return self
def with_ylim(self, lim):
self._ax.set_ylim(lim)
return self
def wo_xticks(self):
self._ax.get_xaxis().set_ticks([])
return self
def wo_yticks(self):
self._ax.get_yaxis().set_ticks([])
return self
def _create_plot(self):
pass
|
<commit_before>import matplotlib.pyplot as plt
#class RgChart(object):
#__metaclass__ = ABCMeta
class RgChart(object):
def with_grids(self):
self._ax.xaxis.grid(True)
self._ax.yaxis.grid(True)
return self
def save_as(self, filename):
self._create_plot()
self._fig.savefig(filename)
plt.close(self._fig) # close on save to avoid memory issues
def with_ygrid(self):
self._ax.yaxis.grid(True)
return self
def with_title(self, title = None):
if title is None:
plt.title(self._title)
else:
plt.title(title)
return self
def with_xlabel(self, xlabel = None):
if xlabel is None:
plt.xlabel(self._xlabel)
else:
plt.xlabel(xlabel)
return self
def with_ylabel(self, ylabel = None):
if ylabel is None:
plt.ylabel(self._ylabel)
else:
plt.ylabel(ylabel)
return self
def with_ylim(self, lim):
self._ax.set_ylim(lim)
return self
def wo_xticks(self):
self._ax.get_xaxis().set_ticks([])
return self
def wo_yticks(self):
self._ax.get_yaxis().set_ticks([])
return self
def _create_plot(self):
pass
<commit_msg>Add y log option and title offset<commit_after>
|
import matplotlib.pyplot as plt
#class RgChart(object):
#__metaclass__ = ABCMeta
class RgChart(object):
TITLE_Y_OFFSET = 1.08
def with_grids(self):
self._ax.xaxis.grid(True)
self._ax.yaxis.grid(True)
return self
def save_as(self, filename):
self._create_plot()
self._fig.savefig(filename)
plt.close(self._fig) # close on save to avoid memory issues
def with_ygrid(self):
self._ax.yaxis.grid(True)
return self
def with_title(self, title = None, y_offset = RgChart.TITLE_Y_OFFSET):
if title is None:
plt.title(self._title, y = y_offset)
else:
plt.title(title, y = y_offset)
return self
def with_xlabel(self, xlabel = None):
if xlabel is None:
plt.xlabel(self._xlabel)
else:
plt.xlabel(xlabel)
return self
def with_ylabel(self, ylabel = None):
if ylabel is None:
plt.ylabel(self._ylabel)
else:
plt.ylabel(ylabel)
return self
def with_ylog(self):
self._ax.set_yscale('log')
return self
def with_ylim(self, lim):
self._ax.set_ylim(lim)
return self
def wo_xticks(self):
self._ax.get_xaxis().set_ticks([])
return self
def wo_yticks(self):
self._ax.get_yaxis().set_ticks([])
return self
def _create_plot(self):
pass
|
import matplotlib.pyplot as plt
#class RgChart(object):
#__metaclass__ = ABCMeta
class RgChart(object):
def with_grids(self):
self._ax.xaxis.grid(True)
self._ax.yaxis.grid(True)
return self
def save_as(self, filename):
self._create_plot()
self._fig.savefig(filename)
plt.close(self._fig) # close on save to avoid memory issues
def with_ygrid(self):
self._ax.yaxis.grid(True)
return self
def with_title(self, title = None):
if title is None:
plt.title(self._title)
else:
plt.title(title)
return self
def with_xlabel(self, xlabel = None):
if xlabel is None:
plt.xlabel(self._xlabel)
else:
plt.xlabel(xlabel)
return self
def with_ylabel(self, ylabel = None):
if ylabel is None:
plt.ylabel(self._ylabel)
else:
plt.ylabel(ylabel)
return self
def with_ylim(self, lim):
self._ax.set_ylim(lim)
return self
def wo_xticks(self):
self._ax.get_xaxis().set_ticks([])
return self
def wo_yticks(self):
self._ax.get_yaxis().set_ticks([])
return self
def _create_plot(self):
pass
Add y log option and title offsetimport matplotlib.pyplot as plt
#class RgChart(object):
#__metaclass__ = ABCMeta
class RgChart(object):
TITLE_Y_OFFSET = 1.08
def with_grids(self):
self._ax.xaxis.grid(True)
self._ax.yaxis.grid(True)
return self
def save_as(self, filename):
self._create_plot()
self._fig.savefig(filename)
plt.close(self._fig) # close on save to avoid memory issues
def with_ygrid(self):
self._ax.yaxis.grid(True)
return self
def with_title(self, title = None, y_offset = RgChart.TITLE_Y_OFFSET):
if title is None:
plt.title(self._title, y = y_offset)
else:
plt.title(title, y = y_offset)
return self
def with_xlabel(self, xlabel = None):
if xlabel is None:
plt.xlabel(self._xlabel)
else:
plt.xlabel(xlabel)
return self
def with_ylabel(self, ylabel = None):
if ylabel is None:
plt.ylabel(self._ylabel)
else:
plt.ylabel(ylabel)
return self
def with_ylog(self):
self._ax.set_yscale('log')
return self
def with_ylim(self, lim):
self._ax.set_ylim(lim)
return self
def wo_xticks(self):
self._ax.get_xaxis().set_ticks([])
return self
def wo_yticks(self):
self._ax.get_yaxis().set_ticks([])
return self
def _create_plot(self):
pass
|
<commit_before>import matplotlib.pyplot as plt
#class RgChart(object):
#__metaclass__ = ABCMeta
class RgChart(object):
def with_grids(self):
self._ax.xaxis.grid(True)
self._ax.yaxis.grid(True)
return self
def save_as(self, filename):
self._create_plot()
self._fig.savefig(filename)
plt.close(self._fig) # close on save to avoid memory issues
def with_ygrid(self):
self._ax.yaxis.grid(True)
return self
def with_title(self, title = None):
if title is None:
plt.title(self._title)
else:
plt.title(title)
return self
def with_xlabel(self, xlabel = None):
if xlabel is None:
plt.xlabel(self._xlabel)
else:
plt.xlabel(xlabel)
return self
def with_ylabel(self, ylabel = None):
if ylabel is None:
plt.ylabel(self._ylabel)
else:
plt.ylabel(ylabel)
return self
def with_ylim(self, lim):
self._ax.set_ylim(lim)
return self
def wo_xticks(self):
self._ax.get_xaxis().set_ticks([])
return self
def wo_yticks(self):
self._ax.get_yaxis().set_ticks([])
return self
def _create_plot(self):
pass
<commit_msg>Add y log option and title offset<commit_after>import matplotlib.pyplot as plt
#class RgChart(object):
#__metaclass__ = ABCMeta
class RgChart(object):
TITLE_Y_OFFSET = 1.08
def with_grids(self):
self._ax.xaxis.grid(True)
self._ax.yaxis.grid(True)
return self
def save_as(self, filename):
self._create_plot()
self._fig.savefig(filename)
plt.close(self._fig) # close on save to avoid memory issues
def with_ygrid(self):
self._ax.yaxis.grid(True)
return self
def with_title(self, title = None, y_offset = RgChart.TITLE_Y_OFFSET):
if title is None:
plt.title(self._title, y = y_offset)
else:
plt.title(title, y = y_offset)
return self
def with_xlabel(self, xlabel = None):
if xlabel is None:
plt.xlabel(self._xlabel)
else:
plt.xlabel(xlabel)
return self
def with_ylabel(self, ylabel = None):
if ylabel is None:
plt.ylabel(self._ylabel)
else:
plt.ylabel(ylabel)
return self
def with_ylog(self):
self._ax.set_yscale('log')
return self
def with_ylim(self, lim):
self._ax.set_ylim(lim)
return self
def wo_xticks(self):
self._ax.get_xaxis().set_ticks([])
return self
def wo_yticks(self):
self._ax.get_yaxis().set_ticks([])
return self
def _create_plot(self):
pass
|
164891392f9a68abb0fa29a74787ef127849d0c0
|
benchexec/tools/avr.py
|
benchexec/tools/avr.py
|
# This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import benchexec.result as result
import benchexec.tools.template
class Tool(benchexec.tools.template.BaseTool2):
"""
Tool info for AVR -- Abstractly Verifying Reachability
URL: https://github.com/aman-goel/avr
"""
def executable(self, tool_locator):
return tool_locator.find_executable("avr.py")
def name(self):
return "AVR"
def cmdline(self, executable, options, task, rlimits):
return [executable] + options + [task.single_input_file]
def determine_result(self, run):
"""
@return: status of AVR after executing a run
"""
if run.was_timeout:
return result.RESULT_TIMEOUT
status = None
for line in run.output:
if "avr-h" in line:
status = result.RESULT_TRUE_PROP
if "avr-v" in line:
status = result.RESULT_FALSE_PROP
if not status:
status = result.RESULT_ERROR
return status
|
# This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import benchexec.result as result
import benchexec.tools.template
class Tool(benchexec.tools.template.BaseTool2):
"""
Tool info for AVR -- Abstractly Verifying Reachability
URL: https://github.com/aman-goel/avr
"""
def executable(self, tool_locator):
return tool_locator.find_executable("avr.py")
def name(self):
return "AVR"
def cmdline(self, executable, options, task, rlimits):
return [executable] + options + [task.single_input_file]
def determine_result(self, run):
"""
@return: status of AVR after executing a run
"""
if run.was_timeout:
return result.RESULT_TIMEOUT
status = None
for line in run.output:
# skip the lines that do not contain verification result
if not line.startswith("Verification result:"):
continue
if "avr-h" in line:
status = result.RESULT_TRUE_PROP
if "avr-v" in line:
status = result.RESULT_FALSE_PROP
if not status:
status = result.RESULT_ERROR
return status
|
Determine AVR's results more precisely
|
Determine AVR's results more precisely
|
Python
|
apache-2.0
|
sosy-lab/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,sosy-lab/benchexec
|
# This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import benchexec.result as result
import benchexec.tools.template
class Tool(benchexec.tools.template.BaseTool2):
"""
Tool info for AVR -- Abstractly Verifying Reachability
URL: https://github.com/aman-goel/avr
"""
def executable(self, tool_locator):
return tool_locator.find_executable("avr.py")
def name(self):
return "AVR"
def cmdline(self, executable, options, task, rlimits):
return [executable] + options + [task.single_input_file]
def determine_result(self, run):
"""
@return: status of AVR after executing a run
"""
if run.was_timeout:
return result.RESULT_TIMEOUT
status = None
for line in run.output:
if "avr-h" in line:
status = result.RESULT_TRUE_PROP
if "avr-v" in line:
status = result.RESULT_FALSE_PROP
if not status:
status = result.RESULT_ERROR
return status
Determine AVR's results more precisely
|
# This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import benchexec.result as result
import benchexec.tools.template
class Tool(benchexec.tools.template.BaseTool2):
"""
Tool info for AVR -- Abstractly Verifying Reachability
URL: https://github.com/aman-goel/avr
"""
def executable(self, tool_locator):
return tool_locator.find_executable("avr.py")
def name(self):
return "AVR"
def cmdline(self, executable, options, task, rlimits):
return [executable] + options + [task.single_input_file]
def determine_result(self, run):
"""
@return: status of AVR after executing a run
"""
if run.was_timeout:
return result.RESULT_TIMEOUT
status = None
for line in run.output:
# skip the lines that do not contain verification result
if not line.startswith("Verification result:"):
continue
if "avr-h" in line:
status = result.RESULT_TRUE_PROP
if "avr-v" in line:
status = result.RESULT_FALSE_PROP
if not status:
status = result.RESULT_ERROR
return status
|
<commit_before># This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import benchexec.result as result
import benchexec.tools.template
class Tool(benchexec.tools.template.BaseTool2):
"""
Tool info for AVR -- Abstractly Verifying Reachability
URL: https://github.com/aman-goel/avr
"""
def executable(self, tool_locator):
return tool_locator.find_executable("avr.py")
def name(self):
return "AVR"
def cmdline(self, executable, options, task, rlimits):
return [executable] + options + [task.single_input_file]
def determine_result(self, run):
"""
@return: status of AVR after executing a run
"""
if run.was_timeout:
return result.RESULT_TIMEOUT
status = None
for line in run.output:
if "avr-h" in line:
status = result.RESULT_TRUE_PROP
if "avr-v" in line:
status = result.RESULT_FALSE_PROP
if not status:
status = result.RESULT_ERROR
return status
<commit_msg>Determine AVR's results more precisely<commit_after>
|
# This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import benchexec.result as result
import benchexec.tools.template
class Tool(benchexec.tools.template.BaseTool2):
"""
Tool info for AVR -- Abstractly Verifying Reachability
URL: https://github.com/aman-goel/avr
"""
def executable(self, tool_locator):
return tool_locator.find_executable("avr.py")
def name(self):
return "AVR"
def cmdline(self, executable, options, task, rlimits):
return [executable] + options + [task.single_input_file]
def determine_result(self, run):
"""
@return: status of AVR after executing a run
"""
if run.was_timeout:
return result.RESULT_TIMEOUT
status = None
for line in run.output:
# skip the lines that do not contain verification result
if not line.startswith("Verification result:"):
continue
if "avr-h" in line:
status = result.RESULT_TRUE_PROP
if "avr-v" in line:
status = result.RESULT_FALSE_PROP
if not status:
status = result.RESULT_ERROR
return status
|
# This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import benchexec.result as result
import benchexec.tools.template
class Tool(benchexec.tools.template.BaseTool2):
"""
Tool info for AVR -- Abstractly Verifying Reachability
URL: https://github.com/aman-goel/avr
"""
def executable(self, tool_locator):
return tool_locator.find_executable("avr.py")
def name(self):
return "AVR"
def cmdline(self, executable, options, task, rlimits):
return [executable] + options + [task.single_input_file]
def determine_result(self, run):
"""
@return: status of AVR after executing a run
"""
if run.was_timeout:
return result.RESULT_TIMEOUT
status = None
for line in run.output:
if "avr-h" in line:
status = result.RESULT_TRUE_PROP
if "avr-v" in line:
status = result.RESULT_FALSE_PROP
if not status:
status = result.RESULT_ERROR
return status
Determine AVR's results more precisely# This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import benchexec.result as result
import benchexec.tools.template
class Tool(benchexec.tools.template.BaseTool2):
"""
Tool info for AVR -- Abstractly Verifying Reachability
URL: https://github.com/aman-goel/avr
"""
def executable(self, tool_locator):
return tool_locator.find_executable("avr.py")
def name(self):
return "AVR"
def cmdline(self, executable, options, task, rlimits):
return [executable] + options + [task.single_input_file]
def determine_result(self, run):
"""
@return: status of AVR after executing a run
"""
if run.was_timeout:
return result.RESULT_TIMEOUT
status = None
for line in run.output:
# skip the lines that do not contain verification result
if not line.startswith("Verification result:"):
continue
if "avr-h" in line:
status = result.RESULT_TRUE_PROP
if "avr-v" in line:
status = result.RESULT_FALSE_PROP
if not status:
status = result.RESULT_ERROR
return status
|
<commit_before># This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import benchexec.result as result
import benchexec.tools.template
class Tool(benchexec.tools.template.BaseTool2):
"""
Tool info for AVR -- Abstractly Verifying Reachability
URL: https://github.com/aman-goel/avr
"""
def executable(self, tool_locator):
return tool_locator.find_executable("avr.py")
def name(self):
return "AVR"
def cmdline(self, executable, options, task, rlimits):
return [executable] + options + [task.single_input_file]
def determine_result(self, run):
"""
@return: status of AVR after executing a run
"""
if run.was_timeout:
return result.RESULT_TIMEOUT
status = None
for line in run.output:
if "avr-h" in line:
status = result.RESULT_TRUE_PROP
if "avr-v" in line:
status = result.RESULT_FALSE_PROP
if not status:
status = result.RESULT_ERROR
return status
<commit_msg>Determine AVR's results more precisely<commit_after># This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import benchexec.result as result
import benchexec.tools.template
class Tool(benchexec.tools.template.BaseTool2):
"""
Tool info for AVR -- Abstractly Verifying Reachability
URL: https://github.com/aman-goel/avr
"""
def executable(self, tool_locator):
return tool_locator.find_executable("avr.py")
def name(self):
return "AVR"
def cmdline(self, executable, options, task, rlimits):
return [executable] + options + [task.single_input_file]
def determine_result(self, run):
"""
@return: status of AVR after executing a run
"""
if run.was_timeout:
return result.RESULT_TIMEOUT
status = None
for line in run.output:
# skip the lines that do not contain verification result
if not line.startswith("Verification result:"):
continue
if "avr-h" in line:
status = result.RESULT_TRUE_PROP
if "avr-v" in line:
status = result.RESULT_FALSE_PROP
if not status:
status = result.RESULT_ERROR
return status
|
e493d5403de51d8ee448e532d60204041aa88c19
|
jedihttp/handlers.py
|
jedihttp/handlers.py
|
import bottle
from bottle import response, request
import json
import jedi
import logging
app = bottle.Bottle( __name__ )
logger = logging.getLogger( __name__ )
@app.post( '/healthy' )
def healthy():
return _Json({})
@app.post( '/ready' )
def ready():
return _Json({})
@app.post( '/completions' )
def completion():
logger.info( 'received /completions request' )
script = _GetJediScript( request.json )
return _Json(
{
'completions': [ {
'name': completion.name,
'description': completion.description,
'docstring': completion.docstring(),
'module_path': completion.module_path,
'line': completion.line,
'column': completion.column
} for completion in script.completions() ]
} )
def _GetJediScript( request_data ):
source = request_data[ 'source' ]
line = request_data[ 'line' ]
col = request_data[ 'col' ]
path = request_data[ 'path' ]
return jedi.Script( source, line, col, path )
def _Json( data ):
response.content_type = 'application/json'
return json.dumps( data )
|
import bottle
from bottle import response, request
import json
import jedi
import logging
app = bottle.Bottle( __name__ )
logger = logging.getLogger( __name__ )
@app.post( '/healthy' )
def healthy():
return _Json({'healthy': True})
@app.post( '/ready' )
def ready():
return _Json({'ready': True})
@app.post( '/completions' )
def completion():
logger.info( 'received /completions request' )
script = _GetJediScript( request.json )
return _Json(
{
'completions': [ {
'name': completion.name,
'description': completion.description,
'docstring': completion.docstring(),
'module_path': completion.module_path,
'line': completion.line,
'column': completion.column
} for completion in script.completions() ]
} )
def _GetJediScript( request_data ):
source = request_data[ 'source' ]
line = request_data[ 'line' ]
col = request_data[ 'col' ]
path = request_data[ 'path' ]
return jedi.Script( source, line, col, path )
def _Json( data ):
response.content_type = 'application/json'
return json.dumps( data )
|
Send descriptive responses for /ready and /healthy
|
Send descriptive responses for /ready and /healthy
|
Python
|
apache-2.0
|
vheon/JediHTTP,micbou/JediHTTP,micbou/JediHTTP,vheon/JediHTTP
|
import bottle
from bottle import response, request
import json
import jedi
import logging
app = bottle.Bottle( __name__ )
logger = logging.getLogger( __name__ )
@app.post( '/healthy' )
def healthy():
return _Json({})
@app.post( '/ready' )
def ready():
return _Json({})
@app.post( '/completions' )
def completion():
logger.info( 'received /completions request' )
script = _GetJediScript( request.json )
return _Json(
{
'completions': [ {
'name': completion.name,
'description': completion.description,
'docstring': completion.docstring(),
'module_path': completion.module_path,
'line': completion.line,
'column': completion.column
} for completion in script.completions() ]
} )
def _GetJediScript( request_data ):
source = request_data[ 'source' ]
line = request_data[ 'line' ]
col = request_data[ 'col' ]
path = request_data[ 'path' ]
return jedi.Script( source, line, col, path )
def _Json( data ):
response.content_type = 'application/json'
return json.dumps( data )
Send descriptive responses for /ready and /healthy
|
import bottle
from bottle import response, request
import json
import jedi
import logging
app = bottle.Bottle( __name__ )
logger = logging.getLogger( __name__ )
@app.post( '/healthy' )
def healthy():
return _Json({'healthy': True})
@app.post( '/ready' )
def ready():
return _Json({'ready': True})
@app.post( '/completions' )
def completion():
logger.info( 'received /completions request' )
script = _GetJediScript( request.json )
return _Json(
{
'completions': [ {
'name': completion.name,
'description': completion.description,
'docstring': completion.docstring(),
'module_path': completion.module_path,
'line': completion.line,
'column': completion.column
} for completion in script.completions() ]
} )
def _GetJediScript( request_data ):
source = request_data[ 'source' ]
line = request_data[ 'line' ]
col = request_data[ 'col' ]
path = request_data[ 'path' ]
return jedi.Script( source, line, col, path )
def _Json( data ):
response.content_type = 'application/json'
return json.dumps( data )
|
<commit_before>import bottle
from bottle import response, request
import json
import jedi
import logging
app = bottle.Bottle( __name__ )
logger = logging.getLogger( __name__ )
@app.post( '/healthy' )
def healthy():
return _Json({})
@app.post( '/ready' )
def ready():
return _Json({})
@app.post( '/completions' )
def completion():
logger.info( 'received /completions request' )
script = _GetJediScript( request.json )
return _Json(
{
'completions': [ {
'name': completion.name,
'description': completion.description,
'docstring': completion.docstring(),
'module_path': completion.module_path,
'line': completion.line,
'column': completion.column
} for completion in script.completions() ]
} )
def _GetJediScript( request_data ):
source = request_data[ 'source' ]
line = request_data[ 'line' ]
col = request_data[ 'col' ]
path = request_data[ 'path' ]
return jedi.Script( source, line, col, path )
def _Json( data ):
response.content_type = 'application/json'
return json.dumps( data )
<commit_msg>Send descriptive responses for /ready and /healthy<commit_after>
|
import bottle
from bottle import response, request
import json
import jedi
import logging
app = bottle.Bottle( __name__ )
logger = logging.getLogger( __name__ )
@app.post( '/healthy' )
def healthy():
return _Json({'healthy': True})
@app.post( '/ready' )
def ready():
return _Json({'ready': True})
@app.post( '/completions' )
def completion():
logger.info( 'received /completions request' )
script = _GetJediScript( request.json )
return _Json(
{
'completions': [ {
'name': completion.name,
'description': completion.description,
'docstring': completion.docstring(),
'module_path': completion.module_path,
'line': completion.line,
'column': completion.column
} for completion in script.completions() ]
} )
def _GetJediScript( request_data ):
source = request_data[ 'source' ]
line = request_data[ 'line' ]
col = request_data[ 'col' ]
path = request_data[ 'path' ]
return jedi.Script( source, line, col, path )
def _Json( data ):
response.content_type = 'application/json'
return json.dumps( data )
|
import bottle
from bottle import response, request
import json
import jedi
import logging
app = bottle.Bottle( __name__ )
logger = logging.getLogger( __name__ )
@app.post( '/healthy' )
def healthy():
return _Json({})
@app.post( '/ready' )
def ready():
return _Json({})
@app.post( '/completions' )
def completion():
logger.info( 'received /completions request' )
script = _GetJediScript( request.json )
return _Json(
{
'completions': [ {
'name': completion.name,
'description': completion.description,
'docstring': completion.docstring(),
'module_path': completion.module_path,
'line': completion.line,
'column': completion.column
} for completion in script.completions() ]
} )
def _GetJediScript( request_data ):
source = request_data[ 'source' ]
line = request_data[ 'line' ]
col = request_data[ 'col' ]
path = request_data[ 'path' ]
return jedi.Script( source, line, col, path )
def _Json( data ):
response.content_type = 'application/json'
return json.dumps( data )
Send descriptive responses for /ready and /healthyimport bottle
from bottle import response, request
import json
import jedi
import logging
app = bottle.Bottle( __name__ )
logger = logging.getLogger( __name__ )
@app.post( '/healthy' )
def healthy():
return _Json({'healthy': True})
@app.post( '/ready' )
def ready():
return _Json({'ready': True})
@app.post( '/completions' )
def completion():
logger.info( 'received /completions request' )
script = _GetJediScript( request.json )
return _Json(
{
'completions': [ {
'name': completion.name,
'description': completion.description,
'docstring': completion.docstring(),
'module_path': completion.module_path,
'line': completion.line,
'column': completion.column
} for completion in script.completions() ]
} )
def _GetJediScript( request_data ):
source = request_data[ 'source' ]
line = request_data[ 'line' ]
col = request_data[ 'col' ]
path = request_data[ 'path' ]
return jedi.Script( source, line, col, path )
def _Json( data ):
response.content_type = 'application/json'
return json.dumps( data )
|
<commit_before>import bottle
from bottle import response, request
import json
import jedi
import logging
app = bottle.Bottle( __name__ )
logger = logging.getLogger( __name__ )
@app.post( '/healthy' )
def healthy():
return _Json({})
@app.post( '/ready' )
def ready():
return _Json({})
@app.post( '/completions' )
def completion():
logger.info( 'received /completions request' )
script = _GetJediScript( request.json )
return _Json(
{
'completions': [ {
'name': completion.name,
'description': completion.description,
'docstring': completion.docstring(),
'module_path': completion.module_path,
'line': completion.line,
'column': completion.column
} for completion in script.completions() ]
} )
def _GetJediScript( request_data ):
source = request_data[ 'source' ]
line = request_data[ 'line' ]
col = request_data[ 'col' ]
path = request_data[ 'path' ]
return jedi.Script( source, line, col, path )
def _Json( data ):
response.content_type = 'application/json'
return json.dumps( data )
<commit_msg>Send descriptive responses for /ready and /healthy<commit_after>import bottle
from bottle import response, request
import json
import jedi
import logging
app = bottle.Bottle( __name__ )
logger = logging.getLogger( __name__ )
@app.post( '/healthy' )
def healthy():
return _Json({'healthy': True})
@app.post( '/ready' )
def ready():
return _Json({'ready': True})
@app.post( '/completions' )
def completion():
logger.info( 'received /completions request' )
script = _GetJediScript( request.json )
return _Json(
{
'completions': [ {
'name': completion.name,
'description': completion.description,
'docstring': completion.docstring(),
'module_path': completion.module_path,
'line': completion.line,
'column': completion.column
} for completion in script.completions() ]
} )
def _GetJediScript( request_data ):
source = request_data[ 'source' ]
line = request_data[ 'line' ]
col = request_data[ 'col' ]
path = request_data[ 'path' ]
return jedi.Script( source, line, col, path )
def _Json( data ):
response.content_type = 'application/json'
return json.dumps( data )
|
647bfbff75f7356a974fdf3bc98612c12c47a151
|
angkot/geo/webapi/views.py
|
angkot/geo/webapi/views.py
|
from django.views.decorators.cache import cache_page
from ..models import Province, City
from angkot.common.decorators import wapi
def _province_to_dict(province):
data = dict(pid=province.id,
name=province.name,
code=province.code)
return (province.id, data)
def _city_to_dict(city):
data = dict(cid=city.id,
name=city.name,
pid=city.province.id)
return (city.id, data)
@cache_page(60 * 60 * 24)
@wapi.endpoint
def province_list(req):
provinces = Province.objects.filter(enabled=True)
ordering = [province.id for province in provinces]
provinces = dict(map(_province_to_dict, provinces))
last_update = Province.objects.filter(enabled=True) \
.order_by('-updated') \
.values_list('updated', flat=True)[0]
return dict(provinces=provinces,
ordering=ordering)
@wapi.endpoint
def city_list(req):
limit = 500
try:
page = int(req.GET.get('page', 0))
except ValueError:
page = 0
start = page * limit
end = start + limit
query = City.objects.filter(enabled=True) \
.order_by('pk')
cities = query[start:end]
cities = dict(map(_city_to_dict, cities))
total = len(query)
return dict(cities=cities,
page=page,
count=len(cities),
total=total)
|
from django.views.decorators.cache import cache_page
from ..models import Province, City
from angkot.common.decorators import wapi
def _province_to_dict(province):
return dict(pid=province.id,
name=province.name,
code=province.code)
def _city_to_dict(city):
data = dict(cid=city.id,
name=city.name,
pid=city.province.id)
return (city.id, data)
@cache_page(60 * 60 * 24)
@wapi.endpoint
def province_list(req):
provinces = Province.objects.filter(enabled=True) \
.order_by('order')
provinces = list(map(_province_to_dict, provinces))
return dict(provinces=provinces)
@wapi.endpoint
def city_list(req):
limit = 500
try:
page = int(req.GET.get('page', 0))
except ValueError:
page = 0
start = page * limit
end = start + limit
query = City.objects.filter(enabled=True) \
.order_by('pk')
cities = query[start:end]
cities = dict(map(_city_to_dict, cities))
total = len(query)
return dict(cities=cities,
page=page,
count=len(cities),
total=total)
|
Simplify the province list API
|
Simplify the province list API
It only contains province data as a list without the separate ordering
information. The order of the province data in the list is the order of
provinces.
|
Python
|
agpl-3.0
|
shirone/angkot,angkot/angkot,shirone/angkot,angkot/angkot,angkot/angkot,shirone/angkot,shirone/angkot,angkot/angkot
|
from django.views.decorators.cache import cache_page
from ..models import Province, City
from angkot.common.decorators import wapi
def _province_to_dict(province):
data = dict(pid=province.id,
name=province.name,
code=province.code)
return (province.id, data)
def _city_to_dict(city):
data = dict(cid=city.id,
name=city.name,
pid=city.province.id)
return (city.id, data)
@cache_page(60 * 60 * 24)
@wapi.endpoint
def province_list(req):
provinces = Province.objects.filter(enabled=True)
ordering = [province.id for province in provinces]
provinces = dict(map(_province_to_dict, provinces))
last_update = Province.objects.filter(enabled=True) \
.order_by('-updated') \
.values_list('updated', flat=True)[0]
return dict(provinces=provinces,
ordering=ordering)
@wapi.endpoint
def city_list(req):
limit = 500
try:
page = int(req.GET.get('page', 0))
except ValueError:
page = 0
start = page * limit
end = start + limit
query = City.objects.filter(enabled=True) \
.order_by('pk')
cities = query[start:end]
cities = dict(map(_city_to_dict, cities))
total = len(query)
return dict(cities=cities,
page=page,
count=len(cities),
total=total)
Simplify the province list API
It only contains province data as a list without the separate ordering
information. The order of the province data in the list is the order of
provinces.
|
from django.views.decorators.cache import cache_page
from ..models import Province, City
from angkot.common.decorators import wapi
def _province_to_dict(province):
return dict(pid=province.id,
name=province.name,
code=province.code)
def _city_to_dict(city):
data = dict(cid=city.id,
name=city.name,
pid=city.province.id)
return (city.id, data)
@cache_page(60 * 60 * 24)
@wapi.endpoint
def province_list(req):
provinces = Province.objects.filter(enabled=True) \
.order_by('order')
provinces = list(map(_province_to_dict, provinces))
return dict(provinces=provinces)
@wapi.endpoint
def city_list(req):
limit = 500
try:
page = int(req.GET.get('page', 0))
except ValueError:
page = 0
start = page * limit
end = start + limit
query = City.objects.filter(enabled=True) \
.order_by('pk')
cities = query[start:end]
cities = dict(map(_city_to_dict, cities))
total = len(query)
return dict(cities=cities,
page=page,
count=len(cities),
total=total)
|
<commit_before>from django.views.decorators.cache import cache_page
from ..models import Province, City
from angkot.common.decorators import wapi
def _province_to_dict(province):
data = dict(pid=province.id,
name=province.name,
code=province.code)
return (province.id, data)
def _city_to_dict(city):
data = dict(cid=city.id,
name=city.name,
pid=city.province.id)
return (city.id, data)
@cache_page(60 * 60 * 24)
@wapi.endpoint
def province_list(req):
provinces = Province.objects.filter(enabled=True)
ordering = [province.id for province in provinces]
provinces = dict(map(_province_to_dict, provinces))
last_update = Province.objects.filter(enabled=True) \
.order_by('-updated') \
.values_list('updated', flat=True)[0]
return dict(provinces=provinces,
ordering=ordering)
@wapi.endpoint
def city_list(req):
limit = 500
try:
page = int(req.GET.get('page', 0))
except ValueError:
page = 0
start = page * limit
end = start + limit
query = City.objects.filter(enabled=True) \
.order_by('pk')
cities = query[start:end]
cities = dict(map(_city_to_dict, cities))
total = len(query)
return dict(cities=cities,
page=page,
count=len(cities),
total=total)
<commit_msg>Simplify the province list API
It only contains province data as a list without the separate ordering
information. The order of the province data in the list is the order of
provinces.<commit_after>
|
from django.views.decorators.cache import cache_page
from ..models import Province, City
from angkot.common.decorators import wapi
def _province_to_dict(province):
return dict(pid=province.id,
name=province.name,
code=province.code)
def _city_to_dict(city):
data = dict(cid=city.id,
name=city.name,
pid=city.province.id)
return (city.id, data)
@cache_page(60 * 60 * 24)
@wapi.endpoint
def province_list(req):
provinces = Province.objects.filter(enabled=True) \
.order_by('order')
provinces = list(map(_province_to_dict, provinces))
return dict(provinces=provinces)
@wapi.endpoint
def city_list(req):
limit = 500
try:
page = int(req.GET.get('page', 0))
except ValueError:
page = 0
start = page * limit
end = start + limit
query = City.objects.filter(enabled=True) \
.order_by('pk')
cities = query[start:end]
cities = dict(map(_city_to_dict, cities))
total = len(query)
return dict(cities=cities,
page=page,
count=len(cities),
total=total)
|
from django.views.decorators.cache import cache_page
from ..models import Province, City
from angkot.common.decorators import wapi
def _province_to_dict(province):
data = dict(pid=province.id,
name=province.name,
code=province.code)
return (province.id, data)
def _city_to_dict(city):
data = dict(cid=city.id,
name=city.name,
pid=city.province.id)
return (city.id, data)
@cache_page(60 * 60 * 24)
@wapi.endpoint
def province_list(req):
provinces = Province.objects.filter(enabled=True)
ordering = [province.id for province in provinces]
provinces = dict(map(_province_to_dict, provinces))
last_update = Province.objects.filter(enabled=True) \
.order_by('-updated') \
.values_list('updated', flat=True)[0]
return dict(provinces=provinces,
ordering=ordering)
@wapi.endpoint
def city_list(req):
limit = 500
try:
page = int(req.GET.get('page', 0))
except ValueError:
page = 0
start = page * limit
end = start + limit
query = City.objects.filter(enabled=True) \
.order_by('pk')
cities = query[start:end]
cities = dict(map(_city_to_dict, cities))
total = len(query)
return dict(cities=cities,
page=page,
count=len(cities),
total=total)
Simplify the province list API
It only contains province data as a list without the separate ordering
information. The order of the province data in the list is the order of
provinces.from django.views.decorators.cache import cache_page
from ..models import Province, City
from angkot.common.decorators import wapi
def _province_to_dict(province):
return dict(pid=province.id,
name=province.name,
code=province.code)
def _city_to_dict(city):
data = dict(cid=city.id,
name=city.name,
pid=city.province.id)
return (city.id, data)
@cache_page(60 * 60 * 24)
@wapi.endpoint
def province_list(req):
provinces = Province.objects.filter(enabled=True) \
.order_by('order')
provinces = list(map(_province_to_dict, provinces))
return dict(provinces=provinces)
@wapi.endpoint
def city_list(req):
limit = 500
try:
page = int(req.GET.get('page', 0))
except ValueError:
page = 0
start = page * limit
end = start + limit
query = City.objects.filter(enabled=True) \
.order_by('pk')
cities = query[start:end]
cities = dict(map(_city_to_dict, cities))
total = len(query)
return dict(cities=cities,
page=page,
count=len(cities),
total=total)
|
<commit_before>from django.views.decorators.cache import cache_page
from ..models import Province, City
from angkot.common.decorators import wapi
def _province_to_dict(province):
data = dict(pid=province.id,
name=province.name,
code=province.code)
return (province.id, data)
def _city_to_dict(city):
data = dict(cid=city.id,
name=city.name,
pid=city.province.id)
return (city.id, data)
@cache_page(60 * 60 * 24)
@wapi.endpoint
def province_list(req):
provinces = Province.objects.filter(enabled=True)
ordering = [province.id for province in provinces]
provinces = dict(map(_province_to_dict, provinces))
last_update = Province.objects.filter(enabled=True) \
.order_by('-updated') \
.values_list('updated', flat=True)[0]
return dict(provinces=provinces,
ordering=ordering)
@wapi.endpoint
def city_list(req):
limit = 500
try:
page = int(req.GET.get('page', 0))
except ValueError:
page = 0
start = page * limit
end = start + limit
query = City.objects.filter(enabled=True) \
.order_by('pk')
cities = query[start:end]
cities = dict(map(_city_to_dict, cities))
total = len(query)
return dict(cities=cities,
page=page,
count=len(cities),
total=total)
<commit_msg>Simplify the province list API
It only contains province data as a list without the separate ordering
information. The order of the province data in the list is the order of
provinces.<commit_after>from django.views.decorators.cache import cache_page
from ..models import Province, City
from angkot.common.decorators import wapi
def _province_to_dict(province):
return dict(pid=province.id,
name=province.name,
code=province.code)
def _city_to_dict(city):
data = dict(cid=city.id,
name=city.name,
pid=city.province.id)
return (city.id, data)
@cache_page(60 * 60 * 24)
@wapi.endpoint
def province_list(req):
provinces = Province.objects.filter(enabled=True) \
.order_by('order')
provinces = list(map(_province_to_dict, provinces))
return dict(provinces=provinces)
@wapi.endpoint
def city_list(req):
limit = 500
try:
page = int(req.GET.get('page', 0))
except ValueError:
page = 0
start = page * limit
end = start + limit
query = City.objects.filter(enabled=True) \
.order_by('pk')
cities = query[start:end]
cities = dict(map(_city_to_dict, cities))
total = len(query)
return dict(cities=cities,
page=page,
count=len(cities),
total=total)
|
60f05c64d60d7db6f05a53548dd0434437bd0719
|
accelerator/migrations/0074_update_url_to_community.py
|
accelerator/migrations/0074_update_url_to_community.py
|
# Generated by Django 2.2.10 on 2021-11-05 12:29
from django.db import migrations
def update_url_to_community(apps, schema_editor):
people_url = "/people"
mentor_url = "/directory"
community_url = "/community"
SiteRedirectPage = apps.get_model('accelerator', 'SiteRedirectPage')
for siteredirectpage in SiteRedirectPage.objects.all():
has_old_url = siteredirectpage.objects.filter(new_url=people_url).filter(new_url=mentor_url)
if has_old_url.exists():
has_old_url.update(new_url=community_url)
class Migration(migrations.Migration):
dependencies = [
('accelerator', '0073_auto_20210909_1706'),
]
operations = [
migrations.RunPython(update_url_to_community,
migrations.RunPython.noop)
]
|
# Generated by Django 2.2.10 on 2021-11-05 12:29
from django.db import migrations
from django.db.models.query_utils import Q
def update_url_to_community(apps, schema_editor):
people_url = "/people"
mentor_url = "/directory"
community_url = "/community"
SiteRedirectPage = apps.get_model('accelerator', 'SiteRedirectPage')
for siteredirectpage in SiteRedirectPage.objects.all():
has_old_url = siteredirectpage.objects.filter(Q(new_url=people_url)| Q(new_url=mentor_url))
if has_old_url.exists():
has_old_url.update(new_url=community_url)
class Migration(migrations.Migration):
dependencies = [
('accelerator', '0073_auto_20210909_1706'),
]
operations = [
migrations.RunPython(update_url_to_community,
migrations.RunPython.noop)
]
|
Fix filter for people and mentor urls
|
[AC-9046] Fix filter for people and mentor urls
|
Python
|
mit
|
masschallenge/django-accelerator,masschallenge/django-accelerator
|
# Generated by Django 2.2.10 on 2021-11-05 12:29
from django.db import migrations
def update_url_to_community(apps, schema_editor):
people_url = "/people"
mentor_url = "/directory"
community_url = "/community"
SiteRedirectPage = apps.get_model('accelerator', 'SiteRedirectPage')
for siteredirectpage in SiteRedirectPage.objects.all():
has_old_url = siteredirectpage.objects.filter(new_url=people_url).filter(new_url=mentor_url)
if has_old_url.exists():
has_old_url.update(new_url=community_url)
class Migration(migrations.Migration):
dependencies = [
('accelerator', '0073_auto_20210909_1706'),
]
operations = [
migrations.RunPython(update_url_to_community,
migrations.RunPython.noop)
]
[AC-9046] Fix filter for people and mentor urls
|
# Generated by Django 2.2.10 on 2021-11-05 12:29
from django.db import migrations
from django.db.models.query_utils import Q
def update_url_to_community(apps, schema_editor):
people_url = "/people"
mentor_url = "/directory"
community_url = "/community"
SiteRedirectPage = apps.get_model('accelerator', 'SiteRedirectPage')
for siteredirectpage in SiteRedirectPage.objects.all():
has_old_url = siteredirectpage.objects.filter(Q(new_url=people_url)| Q(new_url=mentor_url))
if has_old_url.exists():
has_old_url.update(new_url=community_url)
class Migration(migrations.Migration):
dependencies = [
('accelerator', '0073_auto_20210909_1706'),
]
operations = [
migrations.RunPython(update_url_to_community,
migrations.RunPython.noop)
]
|
<commit_before># Generated by Django 2.2.10 on 2021-11-05 12:29
from django.db import migrations
def update_url_to_community(apps, schema_editor):
people_url = "/people"
mentor_url = "/directory"
community_url = "/community"
SiteRedirectPage = apps.get_model('accelerator', 'SiteRedirectPage')
for siteredirectpage in SiteRedirectPage.objects.all():
has_old_url = siteredirectpage.objects.filter(new_url=people_url).filter(new_url=mentor_url)
if has_old_url.exists():
has_old_url.update(new_url=community_url)
class Migration(migrations.Migration):
dependencies = [
('accelerator', '0073_auto_20210909_1706'),
]
operations = [
migrations.RunPython(update_url_to_community,
migrations.RunPython.noop)
]
<commit_msg>[AC-9046] Fix filter for people and mentor urls<commit_after>
|
# Generated by Django 2.2.10 on 2021-11-05 12:29
from django.db import migrations
from django.db.models.query_utils import Q
def update_url_to_community(apps, schema_editor):
people_url = "/people"
mentor_url = "/directory"
community_url = "/community"
SiteRedirectPage = apps.get_model('accelerator', 'SiteRedirectPage')
for siteredirectpage in SiteRedirectPage.objects.all():
has_old_url = siteredirectpage.objects.filter(Q(new_url=people_url)| Q(new_url=mentor_url))
if has_old_url.exists():
has_old_url.update(new_url=community_url)
class Migration(migrations.Migration):
dependencies = [
('accelerator', '0073_auto_20210909_1706'),
]
operations = [
migrations.RunPython(update_url_to_community,
migrations.RunPython.noop)
]
|
# Generated by Django 2.2.10 on 2021-11-05 12:29
from django.db import migrations
def update_url_to_community(apps, schema_editor):
people_url = "/people"
mentor_url = "/directory"
community_url = "/community"
SiteRedirectPage = apps.get_model('accelerator', 'SiteRedirectPage')
for siteredirectpage in SiteRedirectPage.objects.all():
has_old_url = siteredirectpage.objects.filter(new_url=people_url).filter(new_url=mentor_url)
if has_old_url.exists():
has_old_url.update(new_url=community_url)
class Migration(migrations.Migration):
dependencies = [
('accelerator', '0073_auto_20210909_1706'),
]
operations = [
migrations.RunPython(update_url_to_community,
migrations.RunPython.noop)
]
[AC-9046] Fix filter for people and mentor urls# Generated by Django 2.2.10 on 2021-11-05 12:29
from django.db import migrations
from django.db.models.query_utils import Q
def update_url_to_community(apps, schema_editor):
people_url = "/people"
mentor_url = "/directory"
community_url = "/community"
SiteRedirectPage = apps.get_model('accelerator', 'SiteRedirectPage')
for siteredirectpage in SiteRedirectPage.objects.all():
has_old_url = siteredirectpage.objects.filter(Q(new_url=people_url)| Q(new_url=mentor_url))
if has_old_url.exists():
has_old_url.update(new_url=community_url)
class Migration(migrations.Migration):
dependencies = [
('accelerator', '0073_auto_20210909_1706'),
]
operations = [
migrations.RunPython(update_url_to_community,
migrations.RunPython.noop)
]
|
<commit_before># Generated by Django 2.2.10 on 2021-11-05 12:29
from django.db import migrations
def update_url_to_community(apps, schema_editor):
people_url = "/people"
mentor_url = "/directory"
community_url = "/community"
SiteRedirectPage = apps.get_model('accelerator', 'SiteRedirectPage')
for siteredirectpage in SiteRedirectPage.objects.all():
has_old_url = siteredirectpage.objects.filter(new_url=people_url).filter(new_url=mentor_url)
if has_old_url.exists():
has_old_url.update(new_url=community_url)
class Migration(migrations.Migration):
dependencies = [
('accelerator', '0073_auto_20210909_1706'),
]
operations = [
migrations.RunPython(update_url_to_community,
migrations.RunPython.noop)
]
<commit_msg>[AC-9046] Fix filter for people and mentor urls<commit_after># Generated by Django 2.2.10 on 2021-11-05 12:29
from django.db import migrations
from django.db.models.query_utils import Q
def update_url_to_community(apps, schema_editor):
people_url = "/people"
mentor_url = "/directory"
community_url = "/community"
SiteRedirectPage = apps.get_model('accelerator', 'SiteRedirectPage')
for siteredirectpage in SiteRedirectPage.objects.all():
has_old_url = siteredirectpage.objects.filter(Q(new_url=people_url)| Q(new_url=mentor_url))
if has_old_url.exists():
has_old_url.update(new_url=community_url)
class Migration(migrations.Migration):
dependencies = [
('accelerator', '0073_auto_20210909_1706'),
]
operations = [
migrations.RunPython(update_url_to_community,
migrations.RunPython.noop)
]
|
6c2685fd6701600950d01b8f3ac3de08c0583ec9
|
indico/core/extpoint/location.py
|
indico/core/extpoint/location.py
|
# -*- coding: utf-8 -*-
##
##
## This file is part of Indico.
## Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN).
##
## Indico is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 3 of the
## License, or (at your option) any later version.
##
## Indico is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
## General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with Indico;if not, see <http://www.gnu.org/licenses/>.
from indico.core.extpoint import IListener, IContributor
class ILocationActionListener(IListener):
"""
Events that are related to rooms, locations, etc...
"""
def roomChanged(self, obj, oldLocation, newLocation):
pass
def locationChanged(self, obj, oldLocation, newLocation):
pass
def placeChanged(self, obj):
"""
Either the room or location changed
"""
|
# This file is part of Indico.
# Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# Indico is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Indico; if not, see <http://www.gnu.org/licenses/>.
from indico.core.extpoint import IListener
class ILocationActionListener(IListener):
"""
Events that are related to rooms, locations, etc...
"""
def roomChanged(self, obj, oldLocation, newLocation):
pass
def locationChanged(self, obj, oldLocation, newLocation):
pass
def placeChanged(self, obj):
"""
Either the room or location changed
"""
|
Update header missed by the script
|
Update header missed by the script
Really, who puts spaces in front of the comments of a file header?!
|
Python
|
mit
|
DirkHoffmann/indico,mic4ael/indico,DirkHoffmann/indico,ThiefMaster/indico,OmeGak/indico,indico/indico,mvidalgarcia/indico,indico/indico,DirkHoffmann/indico,mic4ael/indico,OmeGak/indico,pferreir/indico,pferreir/indico,mvidalgarcia/indico,indico/indico,indico/indico,ThiefMaster/indico,mvidalgarcia/indico,mic4ael/indico,pferreir/indico,mic4ael/indico,OmeGak/indico,DirkHoffmann/indico,OmeGak/indico,ThiefMaster/indico,ThiefMaster/indico,mvidalgarcia/indico,pferreir/indico
|
# -*- coding: utf-8 -*-
##
##
## This file is part of Indico.
## Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN).
##
## Indico is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 3 of the
## License, or (at your option) any later version.
##
## Indico is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
## General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with Indico;if not, see <http://www.gnu.org/licenses/>.
from indico.core.extpoint import IListener, IContributor
class ILocationActionListener(IListener):
"""
Events that are related to rooms, locations, etc...
"""
def roomChanged(self, obj, oldLocation, newLocation):
pass
def locationChanged(self, obj, oldLocation, newLocation):
pass
def placeChanged(self, obj):
"""
Either the room or location changed
"""
Update header missed by the script
Really, who puts spaces in front of the comments of a file header?!
|
# This file is part of Indico.
# Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# Indico is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Indico; if not, see <http://www.gnu.org/licenses/>.
from indico.core.extpoint import IListener
class ILocationActionListener(IListener):
"""
Events that are related to rooms, locations, etc...
"""
def roomChanged(self, obj, oldLocation, newLocation):
pass
def locationChanged(self, obj, oldLocation, newLocation):
pass
def placeChanged(self, obj):
"""
Either the room or location changed
"""
|
<commit_before> # -*- coding: utf-8 -*-
##
##
## This file is part of Indico.
## Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN).
##
## Indico is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 3 of the
## License, or (at your option) any later version.
##
## Indico is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
## General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with Indico;if not, see <http://www.gnu.org/licenses/>.
from indico.core.extpoint import IListener, IContributor
class ILocationActionListener(IListener):
"""
Events that are related to rooms, locations, etc...
"""
def roomChanged(self, obj, oldLocation, newLocation):
pass
def locationChanged(self, obj, oldLocation, newLocation):
pass
def placeChanged(self, obj):
"""
Either the room or location changed
"""
<commit_msg>Update header missed by the script
Really, who puts spaces in front of the comments of a file header?!<commit_after>
|
# This file is part of Indico.
# Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# Indico is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Indico; if not, see <http://www.gnu.org/licenses/>.
from indico.core.extpoint import IListener
class ILocationActionListener(IListener):
"""
Events that are related to rooms, locations, etc...
"""
def roomChanged(self, obj, oldLocation, newLocation):
pass
def locationChanged(self, obj, oldLocation, newLocation):
pass
def placeChanged(self, obj):
"""
Either the room or location changed
"""
|
# -*- coding: utf-8 -*-
##
##
## This file is part of Indico.
## Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN).
##
## Indico is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 3 of the
## License, or (at your option) any later version.
##
## Indico is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
## General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with Indico;if not, see <http://www.gnu.org/licenses/>.
from indico.core.extpoint import IListener, IContributor
class ILocationActionListener(IListener):
"""
Events that are related to rooms, locations, etc...
"""
def roomChanged(self, obj, oldLocation, newLocation):
pass
def locationChanged(self, obj, oldLocation, newLocation):
pass
def placeChanged(self, obj):
"""
Either the room or location changed
"""
Update header missed by the script
Really, who puts spaces in front of the comments of a file header?!# This file is part of Indico.
# Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# Indico is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Indico; if not, see <http://www.gnu.org/licenses/>.
from indico.core.extpoint import IListener
class ILocationActionListener(IListener):
"""
Events that are related to rooms, locations, etc...
"""
def roomChanged(self, obj, oldLocation, newLocation):
pass
def locationChanged(self, obj, oldLocation, newLocation):
pass
def placeChanged(self, obj):
"""
Either the room or location changed
"""
|
<commit_before> # -*- coding: utf-8 -*-
##
##
## This file is part of Indico.
## Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN).
##
## Indico is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 3 of the
## License, or (at your option) any later version.
##
## Indico is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
## General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with Indico;if not, see <http://www.gnu.org/licenses/>.
from indico.core.extpoint import IListener, IContributor
class ILocationActionListener(IListener):
"""
Events that are related to rooms, locations, etc...
"""
def roomChanged(self, obj, oldLocation, newLocation):
pass
def locationChanged(self, obj, oldLocation, newLocation):
pass
def placeChanged(self, obj):
"""
Either the room or location changed
"""
<commit_msg>Update header missed by the script
Really, who puts spaces in front of the comments of a file header?!<commit_after># This file is part of Indico.
# Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# Indico is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Indico; if not, see <http://www.gnu.org/licenses/>.
from indico.core.extpoint import IListener
class ILocationActionListener(IListener):
"""
Events that are related to rooms, locations, etc...
"""
def roomChanged(self, obj, oldLocation, newLocation):
pass
def locationChanged(self, obj, oldLocation, newLocation):
pass
def placeChanged(self, obj):
"""
Either the room or location changed
"""
|
3a2614034ba8b30d58b15f10947284fd487b3b61
|
get_lexer.py
|
get_lexer.py
|
#!/usr/bin/python
from pygments.lexers import (get_all_lexers)
for lexname, aliases, _, mimetypes in get_all_lexers():
print "%s" % (lexname)
|
#!/usr/bin/python
from pygments.lexers import (get_all_lexers)
for lexname, aliases, _, mimetypes in get_all_lexers():
print "%s" % (aliases[0])
|
Use first alias as languagename
|
Use first alias as languagename
|
Python
|
agpl-3.0
|
formorer/paste.pl,shlomif/paste.debian.net-paste.pl,formorer/paste.pl,shlomif/paste.debian.net-paste.pl,formorer/paste.pl
|
#!/usr/bin/python
from pygments.lexers import (get_all_lexers)
for lexname, aliases, _, mimetypes in get_all_lexers():
print "%s" % (lexname)
Use first alias as languagename
|
#!/usr/bin/python
from pygments.lexers import (get_all_lexers)
for lexname, aliases, _, mimetypes in get_all_lexers():
print "%s" % (aliases[0])
|
<commit_before>#!/usr/bin/python
from pygments.lexers import (get_all_lexers)
for lexname, aliases, _, mimetypes in get_all_lexers():
print "%s" % (lexname)
<commit_msg>Use first alias as languagename<commit_after>
|
#!/usr/bin/python
from pygments.lexers import (get_all_lexers)
for lexname, aliases, _, mimetypes in get_all_lexers():
print "%s" % (aliases[0])
|
#!/usr/bin/python
from pygments.lexers import (get_all_lexers)
for lexname, aliases, _, mimetypes in get_all_lexers():
print "%s" % (lexname)
Use first alias as languagename#!/usr/bin/python
from pygments.lexers import (get_all_lexers)
for lexname, aliases, _, mimetypes in get_all_lexers():
print "%s" % (aliases[0])
|
<commit_before>#!/usr/bin/python
from pygments.lexers import (get_all_lexers)
for lexname, aliases, _, mimetypes in get_all_lexers():
print "%s" % (lexname)
<commit_msg>Use first alias as languagename<commit_after>#!/usr/bin/python
from pygments.lexers import (get_all_lexers)
for lexname, aliases, _, mimetypes in get_all_lexers():
print "%s" % (aliases[0])
|
4d95e5cb938c43cacd14085bf752485334ab6f1a
|
prf/tests/test_mongodb.py
|
prf/tests/test_mongodb.py
|
from prf.tests.prf_testcase import PrfTestCase
from prf.mongodb import get_document_cls
class TestMongoDB(PrfTestCase):
def setUp(self):
super(TestMongoDB, self).setUp()
self.drop_databases()
self.unload_documents()
def test_get_document_cls(self):
cls = self.create_collection('default', 'col1')
cls2 = self.create_collection('prf-test2', 'col2')
cls3 = self.create_collection('default', 'col3')
cls4 = self.create_collection('prf-test2', 'col3')
dcls = get_document_cls('col1')
dcls2 = get_document_cls('col2')
dcls3 = get_document_cls('col3')
assert cls == dcls
assert cls2 == dcls2
assert dcls2._meta['db_alias'] == 'prf-test2'
# This is broken behavior with collision on collection names across dbs,
# get_document_cls will return the most recently defined class with that name.
assert dcls3 == cls4
|
import mock
from prf.tests.prf_testcase import PrfTestCase
from prf.mongodb import get_document_cls, connect_dataset_aliases
class TestMongoDB(PrfTestCase):
def setUp(self):
super(TestMongoDB, self).setUp()
self.drop_databases()
self.unload_documents()
def test_get_document_cls(self):
cls = self.create_collection('default', 'col1')
cls2 = self.create_collection('prf-test2', 'col2')
cls3 = self.create_collection('default', 'col3')
cls4 = self.create_collection('prf-test2', 'col3')
dcls = get_document_cls('col1')
dcls2 = get_document_cls('col2')
dcls3 = get_document_cls('col3')
assert cls == dcls
assert cls2 == dcls2
assert dcls2._meta['db_alias'] == 'prf-test2'
# This is broken behavior with collision on collection names across dbs,
# get_document_cls will return the most recently defined class with that name.
assert dcls3 == cls4
@mock.patch('prf.mongodb.mongo_connect')
def test_connect_dataset_aliases_missing_config(self, connect):
del self.conf.registry.settings['dataset.namespaces']
connect_dataset_aliases(self.conf, self.conf.prf_settings())
connect.assert_not_called()
|
Make sure no crashes happen when no namespaces are set
|
Make sure no crashes happen when no namespaces are set
|
Python
|
mit
|
vahana/prf
|
from prf.tests.prf_testcase import PrfTestCase
from prf.mongodb import get_document_cls
class TestMongoDB(PrfTestCase):
def setUp(self):
super(TestMongoDB, self).setUp()
self.drop_databases()
self.unload_documents()
def test_get_document_cls(self):
cls = self.create_collection('default', 'col1')
cls2 = self.create_collection('prf-test2', 'col2')
cls3 = self.create_collection('default', 'col3')
cls4 = self.create_collection('prf-test2', 'col3')
dcls = get_document_cls('col1')
dcls2 = get_document_cls('col2')
dcls3 = get_document_cls('col3')
assert cls == dcls
assert cls2 == dcls2
assert dcls2._meta['db_alias'] == 'prf-test2'
# This is broken behavior with collision on collection names across dbs,
# get_document_cls will return the most recently defined class with that name.
assert dcls3 == cls4
Make sure no crashes happen when no namespaces are set
|
import mock
from prf.tests.prf_testcase import PrfTestCase
from prf.mongodb import get_document_cls, connect_dataset_aliases
class TestMongoDB(PrfTestCase):
def setUp(self):
super(TestMongoDB, self).setUp()
self.drop_databases()
self.unload_documents()
def test_get_document_cls(self):
cls = self.create_collection('default', 'col1')
cls2 = self.create_collection('prf-test2', 'col2')
cls3 = self.create_collection('default', 'col3')
cls4 = self.create_collection('prf-test2', 'col3')
dcls = get_document_cls('col1')
dcls2 = get_document_cls('col2')
dcls3 = get_document_cls('col3')
assert cls == dcls
assert cls2 == dcls2
assert dcls2._meta['db_alias'] == 'prf-test2'
# This is broken behavior with collision on collection names across dbs,
# get_document_cls will return the most recently defined class with that name.
assert dcls3 == cls4
@mock.patch('prf.mongodb.mongo_connect')
def test_connect_dataset_aliases_missing_config(self, connect):
del self.conf.registry.settings['dataset.namespaces']
connect_dataset_aliases(self.conf, self.conf.prf_settings())
connect.assert_not_called()
|
<commit_before>from prf.tests.prf_testcase import PrfTestCase
from prf.mongodb import get_document_cls
class TestMongoDB(PrfTestCase):
def setUp(self):
super(TestMongoDB, self).setUp()
self.drop_databases()
self.unload_documents()
def test_get_document_cls(self):
cls = self.create_collection('default', 'col1')
cls2 = self.create_collection('prf-test2', 'col2')
cls3 = self.create_collection('default', 'col3')
cls4 = self.create_collection('prf-test2', 'col3')
dcls = get_document_cls('col1')
dcls2 = get_document_cls('col2')
dcls3 = get_document_cls('col3')
assert cls == dcls
assert cls2 == dcls2
assert dcls2._meta['db_alias'] == 'prf-test2'
# This is broken behavior with collision on collection names across dbs,
# get_document_cls will return the most recently defined class with that name.
assert dcls3 == cls4
<commit_msg>Make sure no crashes happen when no namespaces are set<commit_after>
|
import mock
from prf.tests.prf_testcase import PrfTestCase
from prf.mongodb import get_document_cls, connect_dataset_aliases
class TestMongoDB(PrfTestCase):
def setUp(self):
super(TestMongoDB, self).setUp()
self.drop_databases()
self.unload_documents()
def test_get_document_cls(self):
cls = self.create_collection('default', 'col1')
cls2 = self.create_collection('prf-test2', 'col2')
cls3 = self.create_collection('default', 'col3')
cls4 = self.create_collection('prf-test2', 'col3')
dcls = get_document_cls('col1')
dcls2 = get_document_cls('col2')
dcls3 = get_document_cls('col3')
assert cls == dcls
assert cls2 == dcls2
assert dcls2._meta['db_alias'] == 'prf-test2'
# This is broken behavior with collision on collection names across dbs,
# get_document_cls will return the most recently defined class with that name.
assert dcls3 == cls4
@mock.patch('prf.mongodb.mongo_connect')
def test_connect_dataset_aliases_missing_config(self, connect):
del self.conf.registry.settings['dataset.namespaces']
connect_dataset_aliases(self.conf, self.conf.prf_settings())
connect.assert_not_called()
|
from prf.tests.prf_testcase import PrfTestCase
from prf.mongodb import get_document_cls
class TestMongoDB(PrfTestCase):
def setUp(self):
super(TestMongoDB, self).setUp()
self.drop_databases()
self.unload_documents()
def test_get_document_cls(self):
cls = self.create_collection('default', 'col1')
cls2 = self.create_collection('prf-test2', 'col2')
cls3 = self.create_collection('default', 'col3')
cls4 = self.create_collection('prf-test2', 'col3')
dcls = get_document_cls('col1')
dcls2 = get_document_cls('col2')
dcls3 = get_document_cls('col3')
assert cls == dcls
assert cls2 == dcls2
assert dcls2._meta['db_alias'] == 'prf-test2'
# This is broken behavior with collision on collection names across dbs,
# get_document_cls will return the most recently defined class with that name.
assert dcls3 == cls4
Make sure no crashes happen when no namespaces are setimport mock
from prf.tests.prf_testcase import PrfTestCase
from prf.mongodb import get_document_cls, connect_dataset_aliases
class TestMongoDB(PrfTestCase):
def setUp(self):
super(TestMongoDB, self).setUp()
self.drop_databases()
self.unload_documents()
def test_get_document_cls(self):
cls = self.create_collection('default', 'col1')
cls2 = self.create_collection('prf-test2', 'col2')
cls3 = self.create_collection('default', 'col3')
cls4 = self.create_collection('prf-test2', 'col3')
dcls = get_document_cls('col1')
dcls2 = get_document_cls('col2')
dcls3 = get_document_cls('col3')
assert cls == dcls
assert cls2 == dcls2
assert dcls2._meta['db_alias'] == 'prf-test2'
# This is broken behavior with collision on collection names across dbs,
# get_document_cls will return the most recently defined class with that name.
assert dcls3 == cls4
@mock.patch('prf.mongodb.mongo_connect')
def test_connect_dataset_aliases_missing_config(self, connect):
del self.conf.registry.settings['dataset.namespaces']
connect_dataset_aliases(self.conf, self.conf.prf_settings())
connect.assert_not_called()
|
<commit_before>from prf.tests.prf_testcase import PrfTestCase
from prf.mongodb import get_document_cls
class TestMongoDB(PrfTestCase):
def setUp(self):
super(TestMongoDB, self).setUp()
self.drop_databases()
self.unload_documents()
def test_get_document_cls(self):
cls = self.create_collection('default', 'col1')
cls2 = self.create_collection('prf-test2', 'col2')
cls3 = self.create_collection('default', 'col3')
cls4 = self.create_collection('prf-test2', 'col3')
dcls = get_document_cls('col1')
dcls2 = get_document_cls('col2')
dcls3 = get_document_cls('col3')
assert cls == dcls
assert cls2 == dcls2
assert dcls2._meta['db_alias'] == 'prf-test2'
# This is broken behavior with collision on collection names across dbs,
# get_document_cls will return the most recently defined class with that name.
assert dcls3 == cls4
<commit_msg>Make sure no crashes happen when no namespaces are set<commit_after>import mock
from prf.tests.prf_testcase import PrfTestCase
from prf.mongodb import get_document_cls, connect_dataset_aliases
class TestMongoDB(PrfTestCase):
def setUp(self):
super(TestMongoDB, self).setUp()
self.drop_databases()
self.unload_documents()
def test_get_document_cls(self):
cls = self.create_collection('default', 'col1')
cls2 = self.create_collection('prf-test2', 'col2')
cls3 = self.create_collection('default', 'col3')
cls4 = self.create_collection('prf-test2', 'col3')
dcls = get_document_cls('col1')
dcls2 = get_document_cls('col2')
dcls3 = get_document_cls('col3')
assert cls == dcls
assert cls2 == dcls2
assert dcls2._meta['db_alias'] == 'prf-test2'
# This is broken behavior with collision on collection names across dbs,
# get_document_cls will return the most recently defined class with that name.
assert dcls3 == cls4
@mock.patch('prf.mongodb.mongo_connect')
def test_connect_dataset_aliases_missing_config(self, connect):
del self.conf.registry.settings['dataset.namespaces']
connect_dataset_aliases(self.conf, self.conf.prf_settings())
connect.assert_not_called()
|
8143d0735bce0b542b369d84bf9be02d3e6582b6
|
test_queue.py
|
test_queue.py
|
from queue import Queue
import pytest
def test_enqueue_first_item():
queue = Queue()
queue.enqueue("Bacon")
assert queue.last_item.data == "Bacon"
def test_enqueue_multi_last_item():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Steak")
queue.enqueue("Beer")
assert queue.first_item.data == "Beer"
def test_dequeue():
queue = Queue()
queue.enqueue("Bacon")
assert queue.dequeue() == "Bacon"
assert queue.size() == 0
def test_dequeue_multi():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Beer")
assert queue.dequeue() == "Bacon"
assert queue.last_item.data == "Beer"
assert queue.size() == 1
def test_size():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Beer")
assert queue.size() == 2
def test_size_with_remove():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Beer")
queue.enqueue("Cow")
queue.enqueue("Whiskey")
queue.dequeue()
assert queue.size() == 3
|
from queue import Queue
import pytest
def test_enqueue_first_item():
queue = Queue()
queue.enqueue("Bacon")
assert queue.last_item.data == "Bacon"
def test_enqueue_multi_last_item():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Steak")
queue.enqueue("Beer")
assert queue.first_item.data == "Beer"
def test_dequeue_empty():
queue = Queue()
with pytest.raises(ValueError):
queue.dequeue()
def test_dequeue():
queue = Queue()
queue.enqueue("Bacon")
assert queue.dequeue() == "Bacon"
assert queue.size() == 0
def test_dequeue_multi():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Beer")
assert queue.dequeue() == "Bacon"
assert queue.last_item.data == "Beer"
assert queue.size() == 1
def test_size():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Beer")
assert queue.size() == 2
def test_size_with_remove():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Beer")
queue.enqueue("Cow")
queue.enqueue("Whiskey")
queue.dequeue()
assert queue.size() == 3
|
Add test for dequeue from empty list
|
Add test for dequeue from empty list
|
Python
|
mit
|
jwarren116/data-structures
|
from queue import Queue
import pytest
def test_enqueue_first_item():
queue = Queue()
queue.enqueue("Bacon")
assert queue.last_item.data == "Bacon"
def test_enqueue_multi_last_item():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Steak")
queue.enqueue("Beer")
assert queue.first_item.data == "Beer"
def test_dequeue():
queue = Queue()
queue.enqueue("Bacon")
assert queue.dequeue() == "Bacon"
assert queue.size() == 0
def test_dequeue_multi():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Beer")
assert queue.dequeue() == "Bacon"
assert queue.last_item.data == "Beer"
assert queue.size() == 1
def test_size():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Beer")
assert queue.size() == 2
def test_size_with_remove():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Beer")
queue.enqueue("Cow")
queue.enqueue("Whiskey")
queue.dequeue()
assert queue.size() == 3
Add test for dequeue from empty list
|
from queue import Queue
import pytest
def test_enqueue_first_item():
queue = Queue()
queue.enqueue("Bacon")
assert queue.last_item.data == "Bacon"
def test_enqueue_multi_last_item():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Steak")
queue.enqueue("Beer")
assert queue.first_item.data == "Beer"
def test_dequeue_empty():
queue = Queue()
with pytest.raises(ValueError):
queue.dequeue()
def test_dequeue():
queue = Queue()
queue.enqueue("Bacon")
assert queue.dequeue() == "Bacon"
assert queue.size() == 0
def test_dequeue_multi():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Beer")
assert queue.dequeue() == "Bacon"
assert queue.last_item.data == "Beer"
assert queue.size() == 1
def test_size():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Beer")
assert queue.size() == 2
def test_size_with_remove():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Beer")
queue.enqueue("Cow")
queue.enqueue("Whiskey")
queue.dequeue()
assert queue.size() == 3
|
<commit_before>from queue import Queue
import pytest
def test_enqueue_first_item():
queue = Queue()
queue.enqueue("Bacon")
assert queue.last_item.data == "Bacon"
def test_enqueue_multi_last_item():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Steak")
queue.enqueue("Beer")
assert queue.first_item.data == "Beer"
def test_dequeue():
queue = Queue()
queue.enqueue("Bacon")
assert queue.dequeue() == "Bacon"
assert queue.size() == 0
def test_dequeue_multi():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Beer")
assert queue.dequeue() == "Bacon"
assert queue.last_item.data == "Beer"
assert queue.size() == 1
def test_size():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Beer")
assert queue.size() == 2
def test_size_with_remove():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Beer")
queue.enqueue("Cow")
queue.enqueue("Whiskey")
queue.dequeue()
assert queue.size() == 3
<commit_msg>Add test for dequeue from empty list<commit_after>
|
from queue import Queue
import pytest
def test_enqueue_first_item():
queue = Queue()
queue.enqueue("Bacon")
assert queue.last_item.data == "Bacon"
def test_enqueue_multi_last_item():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Steak")
queue.enqueue("Beer")
assert queue.first_item.data == "Beer"
def test_dequeue_empty():
queue = Queue()
with pytest.raises(ValueError):
queue.dequeue()
def test_dequeue():
queue = Queue()
queue.enqueue("Bacon")
assert queue.dequeue() == "Bacon"
assert queue.size() == 0
def test_dequeue_multi():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Beer")
assert queue.dequeue() == "Bacon"
assert queue.last_item.data == "Beer"
assert queue.size() == 1
def test_size():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Beer")
assert queue.size() == 2
def test_size_with_remove():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Beer")
queue.enqueue("Cow")
queue.enqueue("Whiskey")
queue.dequeue()
assert queue.size() == 3
|
from queue import Queue
import pytest
def test_enqueue_first_item():
queue = Queue()
queue.enqueue("Bacon")
assert queue.last_item.data == "Bacon"
def test_enqueue_multi_last_item():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Steak")
queue.enqueue("Beer")
assert queue.first_item.data == "Beer"
def test_dequeue():
queue = Queue()
queue.enqueue("Bacon")
assert queue.dequeue() == "Bacon"
assert queue.size() == 0
def test_dequeue_multi():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Beer")
assert queue.dequeue() == "Bacon"
assert queue.last_item.data == "Beer"
assert queue.size() == 1
def test_size():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Beer")
assert queue.size() == 2
def test_size_with_remove():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Beer")
queue.enqueue("Cow")
queue.enqueue("Whiskey")
queue.dequeue()
assert queue.size() == 3
Add test for dequeue from empty listfrom queue import Queue
import pytest
def test_enqueue_first_item():
queue = Queue()
queue.enqueue("Bacon")
assert queue.last_item.data == "Bacon"
def test_enqueue_multi_last_item():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Steak")
queue.enqueue("Beer")
assert queue.first_item.data == "Beer"
def test_dequeue_empty():
queue = Queue()
with pytest.raises(ValueError):
queue.dequeue()
def test_dequeue():
queue = Queue()
queue.enqueue("Bacon")
assert queue.dequeue() == "Bacon"
assert queue.size() == 0
def test_dequeue_multi():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Beer")
assert queue.dequeue() == "Bacon"
assert queue.last_item.data == "Beer"
assert queue.size() == 1
def test_size():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Beer")
assert queue.size() == 2
def test_size_with_remove():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Beer")
queue.enqueue("Cow")
queue.enqueue("Whiskey")
queue.dequeue()
assert queue.size() == 3
|
<commit_before>from queue import Queue
import pytest
def test_enqueue_first_item():
queue = Queue()
queue.enqueue("Bacon")
assert queue.last_item.data == "Bacon"
def test_enqueue_multi_last_item():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Steak")
queue.enqueue("Beer")
assert queue.first_item.data == "Beer"
def test_dequeue():
queue = Queue()
queue.enqueue("Bacon")
assert queue.dequeue() == "Bacon"
assert queue.size() == 0
def test_dequeue_multi():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Beer")
assert queue.dequeue() == "Bacon"
assert queue.last_item.data == "Beer"
assert queue.size() == 1
def test_size():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Beer")
assert queue.size() == 2
def test_size_with_remove():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Beer")
queue.enqueue("Cow")
queue.enqueue("Whiskey")
queue.dequeue()
assert queue.size() == 3
<commit_msg>Add test for dequeue from empty list<commit_after>from queue import Queue
import pytest
def test_enqueue_first_item():
queue = Queue()
queue.enqueue("Bacon")
assert queue.last_item.data == "Bacon"
def test_enqueue_multi_last_item():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Steak")
queue.enqueue("Beer")
assert queue.first_item.data == "Beer"
def test_dequeue_empty():
queue = Queue()
with pytest.raises(ValueError):
queue.dequeue()
def test_dequeue():
queue = Queue()
queue.enqueue("Bacon")
assert queue.dequeue() == "Bacon"
assert queue.size() == 0
def test_dequeue_multi():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Beer")
assert queue.dequeue() == "Bacon"
assert queue.last_item.data == "Beer"
assert queue.size() == 1
def test_size():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Beer")
assert queue.size() == 2
def test_size_with_remove():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Beer")
queue.enqueue("Cow")
queue.enqueue("Whiskey")
queue.dequeue()
assert queue.size() == 3
|
60ac75f10f7e74aea5636651de05b7bedd4f2be2
|
tests/main.py
|
tests/main.py
|
import json
import unittest
import requests
import validators
class DomainsTests(unittest.TestCase):
def test_json_is_valid(self):
with open("../world_universities_and_domains.json") as json_file:
valid_json = json.load(json_file)
for university in valid_json:
self.assertIn("name", university)
self.assertIn("domains", university)
self.assertIsInstance(university["domains"], list)
for domain in university["domains"]:
self.assertTrue(validators.domain(domain))
self.assertIn("web_pages", university)
self.assertIsInstance(university["web_pages"], list)
for web_page in university["web_pages"]:
self.assertTrue(validators.url(web_page))
self.assertIn("alpha_two_code", university)
self.assertIn("state-province", university)
self.assertIn("country", university)
def check_is_alive():
""" check url then if url isn't alive, add to file """
with open('../world_universities_and_domains.json') as json_raw:
universities = json.load(json_raw)
for university in universities[:]:
try:
for web_page in university["web_pages"]:
print(web_page)
requests.get(web_page, allow_redirects=False, timeout=10.0)
except requests.exceptions.ConnectionError as exc:
print('- Website doesn\'t exists: ', exc)
if __name__ == '__main__':
unittest.main(verbosity=2)
|
import json
import unittest
import requests
import validators
class DomainsTests(unittest.TestCase):
def test_json_is_valid(self):
with open("../world_universities_and_domains.json") as json_file:
valid_json = json.load(json_file)
for university in valid_json:
self.assertIn("name", university)
self.assertIn("domains", university)
self.assertIsInstance(university["domains"], list)
for domain in university["domains"]:
self.assertTrue(validators.domain(domain))
self.assertIn("web_pages", university)
self.assertIn("alpha_two_code", university)
self.assertIn("state-province", university)
self.assertIn("country", university)
def check_is_alive():
""" check url then if url isn't alive, add to file """
with open('../world_universities_and_domains.json') as json_raw:
universities = json.load(json_raw)
for university in universities[:]:
try:
for web_page in university["web_pages"]:
print(web_page)
requests.get(web_page, allow_redirects=False, timeout=10.0)
except requests.exceptions.ConnectionError as exc:
print('- Website doesn\'t exists: ', exc)
if __name__ == '__main__':
unittest.main(verbosity=2)
|
Remove URL test due to bad validator
|
Remove URL test due to bad validator
|
Python
|
mit
|
Hipo/university-domains-list
|
import json
import unittest
import requests
import validators
class DomainsTests(unittest.TestCase):
def test_json_is_valid(self):
with open("../world_universities_and_domains.json") as json_file:
valid_json = json.load(json_file)
for university in valid_json:
self.assertIn("name", university)
self.assertIn("domains", university)
self.assertIsInstance(university["domains"], list)
for domain in university["domains"]:
self.assertTrue(validators.domain(domain))
self.assertIn("web_pages", university)
self.assertIsInstance(university["web_pages"], list)
for web_page in university["web_pages"]:
self.assertTrue(validators.url(web_page))
self.assertIn("alpha_two_code", university)
self.assertIn("state-province", university)
self.assertIn("country", university)
def check_is_alive():
""" check url then if url isn't alive, add to file """
with open('../world_universities_and_domains.json') as json_raw:
universities = json.load(json_raw)
for university in universities[:]:
try:
for web_page in university["web_pages"]:
print(web_page)
requests.get(web_page, allow_redirects=False, timeout=10.0)
except requests.exceptions.ConnectionError as exc:
print('- Website doesn\'t exists: ', exc)
if __name__ == '__main__':
unittest.main(verbosity=2)
Remove URL test due to bad validator
|
import json
import unittest
import requests
import validators
class DomainsTests(unittest.TestCase):
def test_json_is_valid(self):
with open("../world_universities_and_domains.json") as json_file:
valid_json = json.load(json_file)
for university in valid_json:
self.assertIn("name", university)
self.assertIn("domains", university)
self.assertIsInstance(university["domains"], list)
for domain in university["domains"]:
self.assertTrue(validators.domain(domain))
self.assertIn("web_pages", university)
self.assertIn("alpha_two_code", university)
self.assertIn("state-province", university)
self.assertIn("country", university)
def check_is_alive():
""" check url then if url isn't alive, add to file """
with open('../world_universities_and_domains.json') as json_raw:
universities = json.load(json_raw)
for university in universities[:]:
try:
for web_page in university["web_pages"]:
print(web_page)
requests.get(web_page, allow_redirects=False, timeout=10.0)
except requests.exceptions.ConnectionError as exc:
print('- Website doesn\'t exists: ', exc)
if __name__ == '__main__':
unittest.main(verbosity=2)
|
<commit_before>import json
import unittest
import requests
import validators
class DomainsTests(unittest.TestCase):
def test_json_is_valid(self):
with open("../world_universities_and_domains.json") as json_file:
valid_json = json.load(json_file)
for university in valid_json:
self.assertIn("name", university)
self.assertIn("domains", university)
self.assertIsInstance(university["domains"], list)
for domain in university["domains"]:
self.assertTrue(validators.domain(domain))
self.assertIn("web_pages", university)
self.assertIsInstance(university["web_pages"], list)
for web_page in university["web_pages"]:
self.assertTrue(validators.url(web_page))
self.assertIn("alpha_two_code", university)
self.assertIn("state-province", university)
self.assertIn("country", university)
def check_is_alive():
""" check url then if url isn't alive, add to file """
with open('../world_universities_and_domains.json') as json_raw:
universities = json.load(json_raw)
for university in universities[:]:
try:
for web_page in university["web_pages"]:
print(web_page)
requests.get(web_page, allow_redirects=False, timeout=10.0)
except requests.exceptions.ConnectionError as exc:
print('- Website doesn\'t exists: ', exc)
if __name__ == '__main__':
unittest.main(verbosity=2)
<commit_msg>Remove URL test due to bad validator<commit_after>
|
import json
import unittest
import requests
import validators
class DomainsTests(unittest.TestCase):
def test_json_is_valid(self):
with open("../world_universities_and_domains.json") as json_file:
valid_json = json.load(json_file)
for university in valid_json:
self.assertIn("name", university)
self.assertIn("domains", university)
self.assertIsInstance(university["domains"], list)
for domain in university["domains"]:
self.assertTrue(validators.domain(domain))
self.assertIn("web_pages", university)
self.assertIn("alpha_two_code", university)
self.assertIn("state-province", university)
self.assertIn("country", university)
def check_is_alive():
""" check url then if url isn't alive, add to file """
with open('../world_universities_and_domains.json') as json_raw:
universities = json.load(json_raw)
for university in universities[:]:
try:
for web_page in university["web_pages"]:
print(web_page)
requests.get(web_page, allow_redirects=False, timeout=10.0)
except requests.exceptions.ConnectionError as exc:
print('- Website doesn\'t exists: ', exc)
if __name__ == '__main__':
unittest.main(verbosity=2)
|
import json
import unittest
import requests
import validators
class DomainsTests(unittest.TestCase):
def test_json_is_valid(self):
with open("../world_universities_and_domains.json") as json_file:
valid_json = json.load(json_file)
for university in valid_json:
self.assertIn("name", university)
self.assertIn("domains", university)
self.assertIsInstance(university["domains"], list)
for domain in university["domains"]:
self.assertTrue(validators.domain(domain))
self.assertIn("web_pages", university)
self.assertIsInstance(university["web_pages"], list)
for web_page in university["web_pages"]:
self.assertTrue(validators.url(web_page))
self.assertIn("alpha_two_code", university)
self.assertIn("state-province", university)
self.assertIn("country", university)
def check_is_alive():
""" check url then if url isn't alive, add to file """
with open('../world_universities_and_domains.json') as json_raw:
universities = json.load(json_raw)
for university in universities[:]:
try:
for web_page in university["web_pages"]:
print(web_page)
requests.get(web_page, allow_redirects=False, timeout=10.0)
except requests.exceptions.ConnectionError as exc:
print('- Website doesn\'t exists: ', exc)
if __name__ == '__main__':
unittest.main(verbosity=2)
Remove URL test due to bad validatorimport json
import unittest
import requests
import validators
class DomainsTests(unittest.TestCase):
def test_json_is_valid(self):
with open("../world_universities_and_domains.json") as json_file:
valid_json = json.load(json_file)
for university in valid_json:
self.assertIn("name", university)
self.assertIn("domains", university)
self.assertIsInstance(university["domains"], list)
for domain in university["domains"]:
self.assertTrue(validators.domain(domain))
self.assertIn("web_pages", university)
self.assertIn("alpha_two_code", university)
self.assertIn("state-province", university)
self.assertIn("country", university)
def check_is_alive():
""" check url then if url isn't alive, add to file """
with open('../world_universities_and_domains.json') as json_raw:
universities = json.load(json_raw)
for university in universities[:]:
try:
for web_page in university["web_pages"]:
print(web_page)
requests.get(web_page, allow_redirects=False, timeout=10.0)
except requests.exceptions.ConnectionError as exc:
print('- Website doesn\'t exists: ', exc)
if __name__ == '__main__':
unittest.main(verbosity=2)
|
<commit_before>import json
import unittest
import requests
import validators
class DomainsTests(unittest.TestCase):
def test_json_is_valid(self):
with open("../world_universities_and_domains.json") as json_file:
valid_json = json.load(json_file)
for university in valid_json:
self.assertIn("name", university)
self.assertIn("domains", university)
self.assertIsInstance(university["domains"], list)
for domain in university["domains"]:
self.assertTrue(validators.domain(domain))
self.assertIn("web_pages", university)
self.assertIsInstance(university["web_pages"], list)
for web_page in university["web_pages"]:
self.assertTrue(validators.url(web_page))
self.assertIn("alpha_two_code", university)
self.assertIn("state-province", university)
self.assertIn("country", university)
def check_is_alive():
""" check url then if url isn't alive, add to file """
with open('../world_universities_and_domains.json') as json_raw:
universities = json.load(json_raw)
for university in universities[:]:
try:
for web_page in university["web_pages"]:
print(web_page)
requests.get(web_page, allow_redirects=False, timeout=10.0)
except requests.exceptions.ConnectionError as exc:
print('- Website doesn\'t exists: ', exc)
if __name__ == '__main__':
unittest.main(verbosity=2)
<commit_msg>Remove URL test due to bad validator<commit_after>import json
import unittest
import requests
import validators
class DomainsTests(unittest.TestCase):
def test_json_is_valid(self):
with open("../world_universities_and_domains.json") as json_file:
valid_json = json.load(json_file)
for university in valid_json:
self.assertIn("name", university)
self.assertIn("domains", university)
self.assertIsInstance(university["domains"], list)
for domain in university["domains"]:
self.assertTrue(validators.domain(domain))
self.assertIn("web_pages", university)
self.assertIn("alpha_two_code", university)
self.assertIn("state-province", university)
self.assertIn("country", university)
def check_is_alive():
""" check url then if url isn't alive, add to file """
with open('../world_universities_and_domains.json') as json_raw:
universities = json.load(json_raw)
for university in universities[:]:
try:
for web_page in university["web_pages"]:
print(web_page)
requests.get(web_page, allow_redirects=False, timeout=10.0)
except requests.exceptions.ConnectionError as exc:
print('- Website doesn\'t exists: ', exc)
if __name__ == '__main__':
unittest.main(verbosity=2)
|
6a379b806dd1992ad3dd2b728878ed35e8d0ea3c
|
cdf/utils.py
|
cdf/utils.py
|
def get_major_dot_minor_version(version):
"""
Convert full VERSION Django tuple to
a dotted string containing MAJOR.MINOR.
For example, (1, 9, 3, 'final', 0) will result in '1.9'
"""
return '.'.join(version.split('.')[:2])
|
def get_major_dot_minor_version(version):
"""
Convert full VERSION Django tuple to
a dotted string containing MAJOR.MINOR.
For example, (1, 9, 3, 'final', 0) will result in '1.9'
"""
return '.'.join([str(v) for v in version[:2]])
|
Fix getting major.minor django version
|
Fix getting major.minor django version
|
Python
|
mit
|
ana-balica/classy-django-forms,ana-balica/classy-django-forms,ana-balica/classy-django-forms
|
def get_major_dot_minor_version(version):
"""
Convert full VERSION Django tuple to
a dotted string containing MAJOR.MINOR.
For example, (1, 9, 3, 'final', 0) will result in '1.9'
"""
return '.'.join(version.split('.')[:2])
Fix getting major.minor django version
|
def get_major_dot_minor_version(version):
"""
Convert full VERSION Django tuple to
a dotted string containing MAJOR.MINOR.
For example, (1, 9, 3, 'final', 0) will result in '1.9'
"""
return '.'.join([str(v) for v in version[:2]])
|
<commit_before>def get_major_dot_minor_version(version):
"""
Convert full VERSION Django tuple to
a dotted string containing MAJOR.MINOR.
For example, (1, 9, 3, 'final', 0) will result in '1.9'
"""
return '.'.join(version.split('.')[:2])
<commit_msg>Fix getting major.minor django version<commit_after>
|
def get_major_dot_minor_version(version):
"""
Convert full VERSION Django tuple to
a dotted string containing MAJOR.MINOR.
For example, (1, 9, 3, 'final', 0) will result in '1.9'
"""
return '.'.join([str(v) for v in version[:2]])
|
def get_major_dot_minor_version(version):
"""
Convert full VERSION Django tuple to
a dotted string containing MAJOR.MINOR.
For example, (1, 9, 3, 'final', 0) will result in '1.9'
"""
return '.'.join(version.split('.')[:2])
Fix getting major.minor django versiondef get_major_dot_minor_version(version):
"""
Convert full VERSION Django tuple to
a dotted string containing MAJOR.MINOR.
For example, (1, 9, 3, 'final', 0) will result in '1.9'
"""
return '.'.join([str(v) for v in version[:2]])
|
<commit_before>def get_major_dot_minor_version(version):
"""
Convert full VERSION Django tuple to
a dotted string containing MAJOR.MINOR.
For example, (1, 9, 3, 'final', 0) will result in '1.9'
"""
return '.'.join(version.split('.')[:2])
<commit_msg>Fix getting major.minor django version<commit_after>def get_major_dot_minor_version(version):
"""
Convert full VERSION Django tuple to
a dotted string containing MAJOR.MINOR.
For example, (1, 9, 3, 'final', 0) will result in '1.9'
"""
return '.'.join([str(v) for v in version[:2]])
|
8be84789d561c916b6d37e61537c4d957061a380
|
diceserver.py
|
diceserver.py
|
#!/usr/bin/env python
import random
from twisted.protocols import amp
port = 1234
_rand = random.Random()
class RollDice(amp.Command):
arguments = [('sides', amp.Integer())]
response = [('result', amp.Integer())]
class Dice(amp.AMP):
def roll(self, sides=6):
"""Return a random integer from 1 to sides"""
result = _rand.randint(1, sides)
return {'result': result}
RollDice.responder(roll)
def main():
from twisted.internet import reactor
from twisted.internet.protocol import Factory
pf = Factory()
pf.protocol = Dice
reactor.listenTCP(port, pf)
reactor.run()
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
import random
from twisted.protocols import amp
from twisted.internet import reactor
from twisted.internet.protocol import Factory
from twisted.python import usage
port = 1234
_rand = random.Random()
class Options(usage.Options):
optParameters = [
["port", "p", port, "server port"],
]
class RollDice(amp.Command):
arguments = [('sides', amp.Integer())]
response = [('result', amp.Integer())]
class Dice(amp.AMP):
def roll(self, sides=6):
"""Return a random integer from 1 to sides"""
result = _rand.randint(1, sides)
return {'result': result}
RollDice.responder(roll)
def main():
options = Options()
try:
options.parseOptions()
except usage.UsageError, err:
print "%s: %s" % (sys.argv[0], err)
print "%s: Try --help for usage details" % sys.argv[0]
sys.exit(1)
port = int(options["port"])
pf = Factory()
pf.protocol = Dice
reactor.listenTCP(port, pf)
reactor.run()
if __name__ == '__main__':
main()
|
Add command-line option to set port.
|
Add command-line option to set port.
|
Python
|
mit
|
dripton/ampchat
|
#!/usr/bin/env python
import random
from twisted.protocols import amp
port = 1234
_rand = random.Random()
class RollDice(amp.Command):
arguments = [('sides', amp.Integer())]
response = [('result', amp.Integer())]
class Dice(amp.AMP):
def roll(self, sides=6):
"""Return a random integer from 1 to sides"""
result = _rand.randint(1, sides)
return {'result': result}
RollDice.responder(roll)
def main():
from twisted.internet import reactor
from twisted.internet.protocol import Factory
pf = Factory()
pf.protocol = Dice
reactor.listenTCP(port, pf)
reactor.run()
if __name__ == '__main__':
main()
Add command-line option to set port.
|
#!/usr/bin/env python
import random
from twisted.protocols import amp
from twisted.internet import reactor
from twisted.internet.protocol import Factory
from twisted.python import usage
port = 1234
_rand = random.Random()
class Options(usage.Options):
optParameters = [
["port", "p", port, "server port"],
]
class RollDice(amp.Command):
arguments = [('sides', amp.Integer())]
response = [('result', amp.Integer())]
class Dice(amp.AMP):
def roll(self, sides=6):
"""Return a random integer from 1 to sides"""
result = _rand.randint(1, sides)
return {'result': result}
RollDice.responder(roll)
def main():
options = Options()
try:
options.parseOptions()
except usage.UsageError, err:
print "%s: %s" % (sys.argv[0], err)
print "%s: Try --help for usage details" % sys.argv[0]
sys.exit(1)
port = int(options["port"])
pf = Factory()
pf.protocol = Dice
reactor.listenTCP(port, pf)
reactor.run()
if __name__ == '__main__':
main()
|
<commit_before>#!/usr/bin/env python
import random
from twisted.protocols import amp
port = 1234
_rand = random.Random()
class RollDice(amp.Command):
arguments = [('sides', amp.Integer())]
response = [('result', amp.Integer())]
class Dice(amp.AMP):
def roll(self, sides=6):
"""Return a random integer from 1 to sides"""
result = _rand.randint(1, sides)
return {'result': result}
RollDice.responder(roll)
def main():
from twisted.internet import reactor
from twisted.internet.protocol import Factory
pf = Factory()
pf.protocol = Dice
reactor.listenTCP(port, pf)
reactor.run()
if __name__ == '__main__':
main()
<commit_msg>Add command-line option to set port.<commit_after>
|
#!/usr/bin/env python
import random
from twisted.protocols import amp
from twisted.internet import reactor
from twisted.internet.protocol import Factory
from twisted.python import usage
port = 1234
_rand = random.Random()
class Options(usage.Options):
optParameters = [
["port", "p", port, "server port"],
]
class RollDice(amp.Command):
arguments = [('sides', amp.Integer())]
response = [('result', amp.Integer())]
class Dice(amp.AMP):
def roll(self, sides=6):
"""Return a random integer from 1 to sides"""
result = _rand.randint(1, sides)
return {'result': result}
RollDice.responder(roll)
def main():
options = Options()
try:
options.parseOptions()
except usage.UsageError, err:
print "%s: %s" % (sys.argv[0], err)
print "%s: Try --help for usage details" % sys.argv[0]
sys.exit(1)
port = int(options["port"])
pf = Factory()
pf.protocol = Dice
reactor.listenTCP(port, pf)
reactor.run()
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
import random
from twisted.protocols import amp
port = 1234
_rand = random.Random()
class RollDice(amp.Command):
arguments = [('sides', amp.Integer())]
response = [('result', amp.Integer())]
class Dice(amp.AMP):
def roll(self, sides=6):
"""Return a random integer from 1 to sides"""
result = _rand.randint(1, sides)
return {'result': result}
RollDice.responder(roll)
def main():
from twisted.internet import reactor
from twisted.internet.protocol import Factory
pf = Factory()
pf.protocol = Dice
reactor.listenTCP(port, pf)
reactor.run()
if __name__ == '__main__':
main()
Add command-line option to set port.#!/usr/bin/env python
import random
from twisted.protocols import amp
from twisted.internet import reactor
from twisted.internet.protocol import Factory
from twisted.python import usage
port = 1234
_rand = random.Random()
class Options(usage.Options):
optParameters = [
["port", "p", port, "server port"],
]
class RollDice(amp.Command):
arguments = [('sides', amp.Integer())]
response = [('result', amp.Integer())]
class Dice(amp.AMP):
def roll(self, sides=6):
"""Return a random integer from 1 to sides"""
result = _rand.randint(1, sides)
return {'result': result}
RollDice.responder(roll)
def main():
options = Options()
try:
options.parseOptions()
except usage.UsageError, err:
print "%s: %s" % (sys.argv[0], err)
print "%s: Try --help for usage details" % sys.argv[0]
sys.exit(1)
port = int(options["port"])
pf = Factory()
pf.protocol = Dice
reactor.listenTCP(port, pf)
reactor.run()
if __name__ == '__main__':
main()
|
<commit_before>#!/usr/bin/env python
import random
from twisted.protocols import amp
port = 1234
_rand = random.Random()
class RollDice(amp.Command):
arguments = [('sides', amp.Integer())]
response = [('result', amp.Integer())]
class Dice(amp.AMP):
def roll(self, sides=6):
"""Return a random integer from 1 to sides"""
result = _rand.randint(1, sides)
return {'result': result}
RollDice.responder(roll)
def main():
from twisted.internet import reactor
from twisted.internet.protocol import Factory
pf = Factory()
pf.protocol = Dice
reactor.listenTCP(port, pf)
reactor.run()
if __name__ == '__main__':
main()
<commit_msg>Add command-line option to set port.<commit_after>#!/usr/bin/env python
import random
from twisted.protocols import amp
from twisted.internet import reactor
from twisted.internet.protocol import Factory
from twisted.python import usage
port = 1234
_rand = random.Random()
class Options(usage.Options):
optParameters = [
["port", "p", port, "server port"],
]
class RollDice(amp.Command):
arguments = [('sides', amp.Integer())]
response = [('result', amp.Integer())]
class Dice(amp.AMP):
def roll(self, sides=6):
"""Return a random integer from 1 to sides"""
result = _rand.randint(1, sides)
return {'result': result}
RollDice.responder(roll)
def main():
options = Options()
try:
options.parseOptions()
except usage.UsageError, err:
print "%s: %s" % (sys.argv[0], err)
print "%s: Try --help for usage details" % sys.argv[0]
sys.exit(1)
port = int(options["port"])
pf = Factory()
pf.protocol = Dice
reactor.listenTCP(port, pf)
reactor.run()
if __name__ == '__main__':
main()
|
7ec36c81c6437bf83c498661c07802500e3acaa6
|
gore/urls.py
|
gore/urls.py
|
import os
from django.conf.urls import include, url
from lepo.router import Router
from lepo.validate import validate_router
import gore.handlers.events
import gore.handlers.projects
import gore.handlers.store
router = Router.from_file(os.path.join(os.path.dirname(__file__), 'swagger.yaml'))
router.add_handlers(gore.handlers.events)
router.add_handlers(gore.handlers.store)
router.add_handlers(gore.handlers.projects)
validate_router(router)
urls = router.get_urls()
for u in urls: # TODO: This shouldn't be necessary :(
u.callback.csrf_exempt = True
urlpatterns = [
url(r'^api/', include(urls)),
]
|
import os
from django.conf.urls import include, url
from lepo.decorators import csrf_exempt
from lepo.router import Router
from lepo.validate import validate_router
import gore.handlers.events
import gore.handlers.projects
import gore.handlers.store
router = Router.from_file(os.path.join(os.path.dirname(__file__), 'swagger.yaml'))
router.add_handlers(gore.handlers.events)
router.add_handlers(gore.handlers.store)
router.add_handlers(gore.handlers.projects)
validate_router(router)
urls = router.get_urls(
optional_trailing_slash=True,
decorate=(csrf_exempt,),
)
urlpatterns = [
url(r'^api/', include(urls)),
]
|
Use Lepo 0.1.0's CSRF decorator
|
Gore: Use Lepo 0.1.0's CSRF decorator
|
Python
|
mit
|
akx/gentry,akx/gentry,akx/gentry,akx/gentry
|
import os
from django.conf.urls import include, url
from lepo.router import Router
from lepo.validate import validate_router
import gore.handlers.events
import gore.handlers.projects
import gore.handlers.store
router = Router.from_file(os.path.join(os.path.dirname(__file__), 'swagger.yaml'))
router.add_handlers(gore.handlers.events)
router.add_handlers(gore.handlers.store)
router.add_handlers(gore.handlers.projects)
validate_router(router)
urls = router.get_urls()
for u in urls: # TODO: This shouldn't be necessary :(
u.callback.csrf_exempt = True
urlpatterns = [
url(r'^api/', include(urls)),
]
Gore: Use Lepo 0.1.0's CSRF decorator
|
import os
from django.conf.urls import include, url
from lepo.decorators import csrf_exempt
from lepo.router import Router
from lepo.validate import validate_router
import gore.handlers.events
import gore.handlers.projects
import gore.handlers.store
router = Router.from_file(os.path.join(os.path.dirname(__file__), 'swagger.yaml'))
router.add_handlers(gore.handlers.events)
router.add_handlers(gore.handlers.store)
router.add_handlers(gore.handlers.projects)
validate_router(router)
urls = router.get_urls(
optional_trailing_slash=True,
decorate=(csrf_exempt,),
)
urlpatterns = [
url(r'^api/', include(urls)),
]
|
<commit_before>import os
from django.conf.urls import include, url
from lepo.router import Router
from lepo.validate import validate_router
import gore.handlers.events
import gore.handlers.projects
import gore.handlers.store
router = Router.from_file(os.path.join(os.path.dirname(__file__), 'swagger.yaml'))
router.add_handlers(gore.handlers.events)
router.add_handlers(gore.handlers.store)
router.add_handlers(gore.handlers.projects)
validate_router(router)
urls = router.get_urls()
for u in urls: # TODO: This shouldn't be necessary :(
u.callback.csrf_exempt = True
urlpatterns = [
url(r'^api/', include(urls)),
]
<commit_msg>Gore: Use Lepo 0.1.0's CSRF decorator<commit_after>
|
import os
from django.conf.urls import include, url
from lepo.decorators import csrf_exempt
from lepo.router import Router
from lepo.validate import validate_router
import gore.handlers.events
import gore.handlers.projects
import gore.handlers.store
router = Router.from_file(os.path.join(os.path.dirname(__file__), 'swagger.yaml'))
router.add_handlers(gore.handlers.events)
router.add_handlers(gore.handlers.store)
router.add_handlers(gore.handlers.projects)
validate_router(router)
urls = router.get_urls(
optional_trailing_slash=True,
decorate=(csrf_exempt,),
)
urlpatterns = [
url(r'^api/', include(urls)),
]
|
import os
from django.conf.urls import include, url
from lepo.router import Router
from lepo.validate import validate_router
import gore.handlers.events
import gore.handlers.projects
import gore.handlers.store
router = Router.from_file(os.path.join(os.path.dirname(__file__), 'swagger.yaml'))
router.add_handlers(gore.handlers.events)
router.add_handlers(gore.handlers.store)
router.add_handlers(gore.handlers.projects)
validate_router(router)
urls = router.get_urls()
for u in urls: # TODO: This shouldn't be necessary :(
u.callback.csrf_exempt = True
urlpatterns = [
url(r'^api/', include(urls)),
]
Gore: Use Lepo 0.1.0's CSRF decoratorimport os
from django.conf.urls import include, url
from lepo.decorators import csrf_exempt
from lepo.router import Router
from lepo.validate import validate_router
import gore.handlers.events
import gore.handlers.projects
import gore.handlers.store
router = Router.from_file(os.path.join(os.path.dirname(__file__), 'swagger.yaml'))
router.add_handlers(gore.handlers.events)
router.add_handlers(gore.handlers.store)
router.add_handlers(gore.handlers.projects)
validate_router(router)
urls = router.get_urls(
optional_trailing_slash=True,
decorate=(csrf_exempt,),
)
urlpatterns = [
url(r'^api/', include(urls)),
]
|
<commit_before>import os
from django.conf.urls import include, url
from lepo.router import Router
from lepo.validate import validate_router
import gore.handlers.events
import gore.handlers.projects
import gore.handlers.store
router = Router.from_file(os.path.join(os.path.dirname(__file__), 'swagger.yaml'))
router.add_handlers(gore.handlers.events)
router.add_handlers(gore.handlers.store)
router.add_handlers(gore.handlers.projects)
validate_router(router)
urls = router.get_urls()
for u in urls: # TODO: This shouldn't be necessary :(
u.callback.csrf_exempt = True
urlpatterns = [
url(r'^api/', include(urls)),
]
<commit_msg>Gore: Use Lepo 0.1.0's CSRF decorator<commit_after>import os
from django.conf.urls import include, url
from lepo.decorators import csrf_exempt
from lepo.router import Router
from lepo.validate import validate_router
import gore.handlers.events
import gore.handlers.projects
import gore.handlers.store
router = Router.from_file(os.path.join(os.path.dirname(__file__), 'swagger.yaml'))
router.add_handlers(gore.handlers.events)
router.add_handlers(gore.handlers.store)
router.add_handlers(gore.handlers.projects)
validate_router(router)
urls = router.get_urls(
optional_trailing_slash=True,
decorate=(csrf_exempt,),
)
urlpatterns = [
url(r'^api/', include(urls)),
]
|
50510c800e7510b0f918553f0c479a10b3a72deb
|
projections/simpleexpr.py
|
projections/simpleexpr.py
|
import numpy as np
import numpy.ma as ma
import projections.r2py.reval as reval
import projections.r2py.rparser as rparser
class SimpleExpr():
def __init__(self, name, expr):
self.name = name
self.tree = reval.make_inputs(rparser.parse(expr))
lokals = {}
exec(reval.to_py(self.tree, name), lokals)
self.func = lokals[name + '_st']
@property
def syms(self):
return reval.find_inputs(self.tree)
def eval(self, df):
try:
res = self.func(df)
except KeyError as e:
print("Error: input '%s' not defined" % e)
raise e
if not isinstance(res, np.ndarray):
arrays = filter(lambda v: isinstance(v, np.ndarray), df.values())
res = ma.masked_array(np.full(tuple(arrays)[0].shape, res,
dtype=np.float32))
return res
|
import numpy as np
import numpy.ma as ma
import projections.r2py.reval as reval
import projections.r2py.rparser as rparser
class SimpleExpr():
def __init__(self, name, expr):
self.name = name
self.tree = reval.make_inputs(rparser.parse(expr))
lokals = {}
exec(reval.to_py(self.tree, name), lokals)
self.func = lokals[name + '_st']
@property
def syms(self):
return reval.find_inputs(self.tree)
def eval(self, df):
try:
res = self.func(df)
except KeyError as e:
print("Error: input '%s' not defined" % e)
raise e
if not isinstance(res, np.ndarray):
res = ma.masked_array(np.full(tuple(df.values())[0].shape, res,
dtype=np.float32))
return res
|
Revert "Improve determination of array shape for constant expressions"
|
Revert "Improve determination of array shape for constant expressions"
This reverts commit c8c9c42f14c742c6fcb180b7a3cc1bab1655ac46.
|
Python
|
apache-2.0
|
ricardog/raster-project,ricardog/raster-project,ricardog/raster-project,ricardog/raster-project,ricardog/raster-project
|
import numpy as np
import numpy.ma as ma
import projections.r2py.reval as reval
import projections.r2py.rparser as rparser
class SimpleExpr():
def __init__(self, name, expr):
self.name = name
self.tree = reval.make_inputs(rparser.parse(expr))
lokals = {}
exec(reval.to_py(self.tree, name), lokals)
self.func = lokals[name + '_st']
@property
def syms(self):
return reval.find_inputs(self.tree)
def eval(self, df):
try:
res = self.func(df)
except KeyError as e:
print("Error: input '%s' not defined" % e)
raise e
if not isinstance(res, np.ndarray):
arrays = filter(lambda v: isinstance(v, np.ndarray), df.values())
res = ma.masked_array(np.full(tuple(arrays)[0].shape, res,
dtype=np.float32))
return res
Revert "Improve determination of array shape for constant expressions"
This reverts commit c8c9c42f14c742c6fcb180b7a3cc1bab1655ac46.
|
import numpy as np
import numpy.ma as ma
import projections.r2py.reval as reval
import projections.r2py.rparser as rparser
class SimpleExpr():
def __init__(self, name, expr):
self.name = name
self.tree = reval.make_inputs(rparser.parse(expr))
lokals = {}
exec(reval.to_py(self.tree, name), lokals)
self.func = lokals[name + '_st']
@property
def syms(self):
return reval.find_inputs(self.tree)
def eval(self, df):
try:
res = self.func(df)
except KeyError as e:
print("Error: input '%s' not defined" % e)
raise e
if not isinstance(res, np.ndarray):
res = ma.masked_array(np.full(tuple(df.values())[0].shape, res,
dtype=np.float32))
return res
|
<commit_before>
import numpy as np
import numpy.ma as ma
import projections.r2py.reval as reval
import projections.r2py.rparser as rparser
class SimpleExpr():
def __init__(self, name, expr):
self.name = name
self.tree = reval.make_inputs(rparser.parse(expr))
lokals = {}
exec(reval.to_py(self.tree, name), lokals)
self.func = lokals[name + '_st']
@property
def syms(self):
return reval.find_inputs(self.tree)
def eval(self, df):
try:
res = self.func(df)
except KeyError as e:
print("Error: input '%s' not defined" % e)
raise e
if not isinstance(res, np.ndarray):
arrays = filter(lambda v: isinstance(v, np.ndarray), df.values())
res = ma.masked_array(np.full(tuple(arrays)[0].shape, res,
dtype=np.float32))
return res
<commit_msg>Revert "Improve determination of array shape for constant expressions"
This reverts commit c8c9c42f14c742c6fcb180b7a3cc1bab1655ac46.<commit_after>
|
import numpy as np
import numpy.ma as ma
import projections.r2py.reval as reval
import projections.r2py.rparser as rparser
class SimpleExpr():
def __init__(self, name, expr):
self.name = name
self.tree = reval.make_inputs(rparser.parse(expr))
lokals = {}
exec(reval.to_py(self.tree, name), lokals)
self.func = lokals[name + '_st']
@property
def syms(self):
return reval.find_inputs(self.tree)
def eval(self, df):
try:
res = self.func(df)
except KeyError as e:
print("Error: input '%s' not defined" % e)
raise e
if not isinstance(res, np.ndarray):
res = ma.masked_array(np.full(tuple(df.values())[0].shape, res,
dtype=np.float32))
return res
|
import numpy as np
import numpy.ma as ma
import projections.r2py.reval as reval
import projections.r2py.rparser as rparser
class SimpleExpr():
def __init__(self, name, expr):
self.name = name
self.tree = reval.make_inputs(rparser.parse(expr))
lokals = {}
exec(reval.to_py(self.tree, name), lokals)
self.func = lokals[name + '_st']
@property
def syms(self):
return reval.find_inputs(self.tree)
def eval(self, df):
try:
res = self.func(df)
except KeyError as e:
print("Error: input '%s' not defined" % e)
raise e
if not isinstance(res, np.ndarray):
arrays = filter(lambda v: isinstance(v, np.ndarray), df.values())
res = ma.masked_array(np.full(tuple(arrays)[0].shape, res,
dtype=np.float32))
return res
Revert "Improve determination of array shape for constant expressions"
This reverts commit c8c9c42f14c742c6fcb180b7a3cc1bab1655ac46.
import numpy as np
import numpy.ma as ma
import projections.r2py.reval as reval
import projections.r2py.rparser as rparser
class SimpleExpr():
def __init__(self, name, expr):
self.name = name
self.tree = reval.make_inputs(rparser.parse(expr))
lokals = {}
exec(reval.to_py(self.tree, name), lokals)
self.func = lokals[name + '_st']
@property
def syms(self):
return reval.find_inputs(self.tree)
def eval(self, df):
try:
res = self.func(df)
except KeyError as e:
print("Error: input '%s' not defined" % e)
raise e
if not isinstance(res, np.ndarray):
res = ma.masked_array(np.full(tuple(df.values())[0].shape, res,
dtype=np.float32))
return res
|
<commit_before>
import numpy as np
import numpy.ma as ma
import projections.r2py.reval as reval
import projections.r2py.rparser as rparser
class SimpleExpr():
def __init__(self, name, expr):
self.name = name
self.tree = reval.make_inputs(rparser.parse(expr))
lokals = {}
exec(reval.to_py(self.tree, name), lokals)
self.func = lokals[name + '_st']
@property
def syms(self):
return reval.find_inputs(self.tree)
def eval(self, df):
try:
res = self.func(df)
except KeyError as e:
print("Error: input '%s' not defined" % e)
raise e
if not isinstance(res, np.ndarray):
arrays = filter(lambda v: isinstance(v, np.ndarray), df.values())
res = ma.masked_array(np.full(tuple(arrays)[0].shape, res,
dtype=np.float32))
return res
<commit_msg>Revert "Improve determination of array shape for constant expressions"
This reverts commit c8c9c42f14c742c6fcb180b7a3cc1bab1655ac46.<commit_after>
import numpy as np
import numpy.ma as ma
import projections.r2py.reval as reval
import projections.r2py.rparser as rparser
class SimpleExpr():
def __init__(self, name, expr):
self.name = name
self.tree = reval.make_inputs(rparser.parse(expr))
lokals = {}
exec(reval.to_py(self.tree, name), lokals)
self.func = lokals[name + '_st']
@property
def syms(self):
return reval.find_inputs(self.tree)
def eval(self, df):
try:
res = self.func(df)
except KeyError as e:
print("Error: input '%s' not defined" % e)
raise e
if not isinstance(res, np.ndarray):
res = ma.masked_array(np.full(tuple(df.values())[0].shape, res,
dtype=np.float32))
return res
|
cf170e9eb489680366d1608db8fd69d781ae65f5
|
thinc/loss.py
|
thinc/loss.py
|
import numpy
def categorical_crossentropy(scores, labels):
target = numpy.zeros(scores.shape, dtype='float32')
loss = 0.
for i in range(len(labels)):
target[i, int(labels[i])] = 1.
loss += (1.0-scores[i, int(labels[i])])**2
return scores - target, loss
|
import numpy
try:
from cupy import get_array_module
except ImportError:
def get_array_module(*a, **k):
return numpy
def categorical_crossentropy(scores, labels):
xp = get_array_module(scores)
target = xp.zeros(scores.shape, dtype='float32')
loss = 0.
for i in range(len(labels)):
target[i, int(labels[i])] = 1.
loss += (1.0-scores[i, int(labels[i])])**2
return scores - target, loss
|
Use one-hot representation in categorical cross-entropy
|
Use one-hot representation in categorical cross-entropy
|
Python
|
mit
|
explosion/thinc,explosion/thinc,spacy-io/thinc,spacy-io/thinc,explosion/thinc,explosion/thinc,spacy-io/thinc
|
import numpy
def categorical_crossentropy(scores, labels):
target = numpy.zeros(scores.shape, dtype='float32')
loss = 0.
for i in range(len(labels)):
target[i, int(labels[i])] = 1.
loss += (1.0-scores[i, int(labels[i])])**2
return scores - target, loss
Use one-hot representation in categorical cross-entropy
|
import numpy
try:
from cupy import get_array_module
except ImportError:
def get_array_module(*a, **k):
return numpy
def categorical_crossentropy(scores, labels):
xp = get_array_module(scores)
target = xp.zeros(scores.shape, dtype='float32')
loss = 0.
for i in range(len(labels)):
target[i, int(labels[i])] = 1.
loss += (1.0-scores[i, int(labels[i])])**2
return scores - target, loss
|
<commit_before>import numpy
def categorical_crossentropy(scores, labels):
target = numpy.zeros(scores.shape, dtype='float32')
loss = 0.
for i in range(len(labels)):
target[i, int(labels[i])] = 1.
loss += (1.0-scores[i, int(labels[i])])**2
return scores - target, loss
<commit_msg>Use one-hot representation in categorical cross-entropy<commit_after>
|
import numpy
try:
from cupy import get_array_module
except ImportError:
def get_array_module(*a, **k):
return numpy
def categorical_crossentropy(scores, labels):
xp = get_array_module(scores)
target = xp.zeros(scores.shape, dtype='float32')
loss = 0.
for i in range(len(labels)):
target[i, int(labels[i])] = 1.
loss += (1.0-scores[i, int(labels[i])])**2
return scores - target, loss
|
import numpy
def categorical_crossentropy(scores, labels):
target = numpy.zeros(scores.shape, dtype='float32')
loss = 0.
for i in range(len(labels)):
target[i, int(labels[i])] = 1.
loss += (1.0-scores[i, int(labels[i])])**2
return scores - target, loss
Use one-hot representation in categorical cross-entropyimport numpy
try:
from cupy import get_array_module
except ImportError:
def get_array_module(*a, **k):
return numpy
def categorical_crossentropy(scores, labels):
xp = get_array_module(scores)
target = xp.zeros(scores.shape, dtype='float32')
loss = 0.
for i in range(len(labels)):
target[i, int(labels[i])] = 1.
loss += (1.0-scores[i, int(labels[i])])**2
return scores - target, loss
|
<commit_before>import numpy
def categorical_crossentropy(scores, labels):
target = numpy.zeros(scores.shape, dtype='float32')
loss = 0.
for i in range(len(labels)):
target[i, int(labels[i])] = 1.
loss += (1.0-scores[i, int(labels[i])])**2
return scores - target, loss
<commit_msg>Use one-hot representation in categorical cross-entropy<commit_after>import numpy
try:
from cupy import get_array_module
except ImportError:
def get_array_module(*a, **k):
return numpy
def categorical_crossentropy(scores, labels):
xp = get_array_module(scores)
target = xp.zeros(scores.shape, dtype='float32')
loss = 0.
for i in range(len(labels)):
target[i, int(labels[i])] = 1.
loss += (1.0-scores[i, int(labels[i])])**2
return scores - target, loss
|
81112afb181e88a87b3399b8f7a1f0462ab382cc
|
kparcel/constants.py
|
kparcel/constants.py
|
PARSER_REQUEST_HEADER_USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0) Gecko/20100101 Firefox/4.0'
PARSER_RESULT_PARCEL = 'parcel'
PARSER_RESULT_TRACKS = 'tracks'
|
PARSER_REQUEST_HEADER_USER_AGENT = 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)'
PARSER_RESULT_PARCEL = 'parcel'
PARSER_RESULT_TRACKS = 'tracks'
|
Fix the default user-agent correctly
|
Constants: Fix the default user-agent correctly
|
Python
|
bsd-2-clause
|
iBluemind/armatis
|
PARSER_REQUEST_HEADER_USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0) Gecko/20100101 Firefox/4.0'
PARSER_RESULT_PARCEL = 'parcel'
PARSER_RESULT_TRACKS = 'tracks'
Constants: Fix the default user-agent correctly
|
PARSER_REQUEST_HEADER_USER_AGENT = 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)'
PARSER_RESULT_PARCEL = 'parcel'
PARSER_RESULT_TRACKS = 'tracks'
|
<commit_before>PARSER_REQUEST_HEADER_USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0) Gecko/20100101 Firefox/4.0'
PARSER_RESULT_PARCEL = 'parcel'
PARSER_RESULT_TRACKS = 'tracks'
<commit_msg>Constants: Fix the default user-agent correctly<commit_after>
|
PARSER_REQUEST_HEADER_USER_AGENT = 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)'
PARSER_RESULT_PARCEL = 'parcel'
PARSER_RESULT_TRACKS = 'tracks'
|
PARSER_REQUEST_HEADER_USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0) Gecko/20100101 Firefox/4.0'
PARSER_RESULT_PARCEL = 'parcel'
PARSER_RESULT_TRACKS = 'tracks'
Constants: Fix the default user-agent correctlyPARSER_REQUEST_HEADER_USER_AGENT = 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)'
PARSER_RESULT_PARCEL = 'parcel'
PARSER_RESULT_TRACKS = 'tracks'
|
<commit_before>PARSER_REQUEST_HEADER_USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0) Gecko/20100101 Firefox/4.0'
PARSER_RESULT_PARCEL = 'parcel'
PARSER_RESULT_TRACKS = 'tracks'
<commit_msg>Constants: Fix the default user-agent correctly<commit_after>PARSER_REQUEST_HEADER_USER_AGENT = 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)'
PARSER_RESULT_PARCEL = 'parcel'
PARSER_RESULT_TRACKS = 'tracks'
|
d81d17b3ef7819cf70c302f36afab32ae33e66a9
|
asyncmongo/__init__.py
|
asyncmongo/__init__.py
|
#!/bin/env python
#
# Copyright 2010 bit.ly
#
# 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.
"""
AsyncMongo is an asynchronous library for accessing mongo
http://github.com/bitly/asyncmongo
"""
try:
import bson
except ImportError:
raise ImportError("bson library not installed. Install pymongo >= 1.9 https://github.com/mongodb/mongo-python-driver")
# also update in setup.py
version = "1.3"
version_info = (1, 3)
ASCENDING = 1
"""Ascending sort order."""
DESCENDING = -1
"""Descending sort order."""
GEO2D = "2d"
"""Index specifier for a 2-dimensional `geospatial index`"""
TEXT = { $meta: "textScore" }
"""TEXT Index sort order."""
from errors import (Error, InterfaceError, AuthenticationError, DatabaseError, RSConnectionError,
DataError, IntegrityError, ProgrammingError, NotSupportedError)
from client import Client
|
#!/bin/env python
#
# Copyright 2010 bit.ly
#
# 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.
"""
AsyncMongo is an asynchronous library for accessing mongo
http://github.com/bitly/asyncmongo
"""
try:
import bson
except ImportError:
raise ImportError("bson library not installed. Install pymongo >= 1.9 https://github.com/mongodb/mongo-python-driver")
# also update in setup.py
version = "1.3"
version_info = (1, 3)
ASCENDING = 1
"""Ascending sort order."""
DESCENDING = -1
"""Descending sort order."""
GEO2D = "2d"
"""Index specifier for a 2-dimensional `geospatial index`"""
TEXT = { "$meta": "textScore" }
"""TEXT Index sort order."""
from errors import (Error, InterfaceError, AuthenticationError, DatabaseError, RSConnectionError,
DataError, IntegrityError, ProgrammingError, NotSupportedError)
from client import Client
|
Support Sort Order For TEXT Index
|
Support Sort Order For TEXT Index
|
Python
|
apache-2.0
|
RealGeeks/asyncmongo
|
#!/bin/env python
#
# Copyright 2010 bit.ly
#
# 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.
"""
AsyncMongo is an asynchronous library for accessing mongo
http://github.com/bitly/asyncmongo
"""
try:
import bson
except ImportError:
raise ImportError("bson library not installed. Install pymongo >= 1.9 https://github.com/mongodb/mongo-python-driver")
# also update in setup.py
version = "1.3"
version_info = (1, 3)
ASCENDING = 1
"""Ascending sort order."""
DESCENDING = -1
"""Descending sort order."""
GEO2D = "2d"
"""Index specifier for a 2-dimensional `geospatial index`"""
TEXT = { $meta: "textScore" }
"""TEXT Index sort order."""
from errors import (Error, InterfaceError, AuthenticationError, DatabaseError, RSConnectionError,
DataError, IntegrityError, ProgrammingError, NotSupportedError)
from client import Client
Support Sort Order For TEXT Index
|
#!/bin/env python
#
# Copyright 2010 bit.ly
#
# 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.
"""
AsyncMongo is an asynchronous library for accessing mongo
http://github.com/bitly/asyncmongo
"""
try:
import bson
except ImportError:
raise ImportError("bson library not installed. Install pymongo >= 1.9 https://github.com/mongodb/mongo-python-driver")
# also update in setup.py
version = "1.3"
version_info = (1, 3)
ASCENDING = 1
"""Ascending sort order."""
DESCENDING = -1
"""Descending sort order."""
GEO2D = "2d"
"""Index specifier for a 2-dimensional `geospatial index`"""
TEXT = { "$meta": "textScore" }
"""TEXT Index sort order."""
from errors import (Error, InterfaceError, AuthenticationError, DatabaseError, RSConnectionError,
DataError, IntegrityError, ProgrammingError, NotSupportedError)
from client import Client
|
<commit_before>#!/bin/env python
#
# Copyright 2010 bit.ly
#
# 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.
"""
AsyncMongo is an asynchronous library for accessing mongo
http://github.com/bitly/asyncmongo
"""
try:
import bson
except ImportError:
raise ImportError("bson library not installed. Install pymongo >= 1.9 https://github.com/mongodb/mongo-python-driver")
# also update in setup.py
version = "1.3"
version_info = (1, 3)
ASCENDING = 1
"""Ascending sort order."""
DESCENDING = -1
"""Descending sort order."""
GEO2D = "2d"
"""Index specifier for a 2-dimensional `geospatial index`"""
TEXT = { $meta: "textScore" }
"""TEXT Index sort order."""
from errors import (Error, InterfaceError, AuthenticationError, DatabaseError, RSConnectionError,
DataError, IntegrityError, ProgrammingError, NotSupportedError)
from client import Client
<commit_msg>Support Sort Order For TEXT Index<commit_after>
|
#!/bin/env python
#
# Copyright 2010 bit.ly
#
# 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.
"""
AsyncMongo is an asynchronous library for accessing mongo
http://github.com/bitly/asyncmongo
"""
try:
import bson
except ImportError:
raise ImportError("bson library not installed. Install pymongo >= 1.9 https://github.com/mongodb/mongo-python-driver")
# also update in setup.py
version = "1.3"
version_info = (1, 3)
ASCENDING = 1
"""Ascending sort order."""
DESCENDING = -1
"""Descending sort order."""
GEO2D = "2d"
"""Index specifier for a 2-dimensional `geospatial index`"""
TEXT = { "$meta": "textScore" }
"""TEXT Index sort order."""
from errors import (Error, InterfaceError, AuthenticationError, DatabaseError, RSConnectionError,
DataError, IntegrityError, ProgrammingError, NotSupportedError)
from client import Client
|
#!/bin/env python
#
# Copyright 2010 bit.ly
#
# 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.
"""
AsyncMongo is an asynchronous library for accessing mongo
http://github.com/bitly/asyncmongo
"""
try:
import bson
except ImportError:
raise ImportError("bson library not installed. Install pymongo >= 1.9 https://github.com/mongodb/mongo-python-driver")
# also update in setup.py
version = "1.3"
version_info = (1, 3)
ASCENDING = 1
"""Ascending sort order."""
DESCENDING = -1
"""Descending sort order."""
GEO2D = "2d"
"""Index specifier for a 2-dimensional `geospatial index`"""
TEXT = { $meta: "textScore" }
"""TEXT Index sort order."""
from errors import (Error, InterfaceError, AuthenticationError, DatabaseError, RSConnectionError,
DataError, IntegrityError, ProgrammingError, NotSupportedError)
from client import Client
Support Sort Order For TEXT Index#!/bin/env python
#
# Copyright 2010 bit.ly
#
# 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.
"""
AsyncMongo is an asynchronous library for accessing mongo
http://github.com/bitly/asyncmongo
"""
try:
import bson
except ImportError:
raise ImportError("bson library not installed. Install pymongo >= 1.9 https://github.com/mongodb/mongo-python-driver")
# also update in setup.py
version = "1.3"
version_info = (1, 3)
ASCENDING = 1
"""Ascending sort order."""
DESCENDING = -1
"""Descending sort order."""
GEO2D = "2d"
"""Index specifier for a 2-dimensional `geospatial index`"""
TEXT = { "$meta": "textScore" }
"""TEXT Index sort order."""
from errors import (Error, InterfaceError, AuthenticationError, DatabaseError, RSConnectionError,
DataError, IntegrityError, ProgrammingError, NotSupportedError)
from client import Client
|
<commit_before>#!/bin/env python
#
# Copyright 2010 bit.ly
#
# 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.
"""
AsyncMongo is an asynchronous library for accessing mongo
http://github.com/bitly/asyncmongo
"""
try:
import bson
except ImportError:
raise ImportError("bson library not installed. Install pymongo >= 1.9 https://github.com/mongodb/mongo-python-driver")
# also update in setup.py
version = "1.3"
version_info = (1, 3)
ASCENDING = 1
"""Ascending sort order."""
DESCENDING = -1
"""Descending sort order."""
GEO2D = "2d"
"""Index specifier for a 2-dimensional `geospatial index`"""
TEXT = { $meta: "textScore" }
"""TEXT Index sort order."""
from errors import (Error, InterfaceError, AuthenticationError, DatabaseError, RSConnectionError,
DataError, IntegrityError, ProgrammingError, NotSupportedError)
from client import Client
<commit_msg>Support Sort Order For TEXT Index<commit_after>#!/bin/env python
#
# Copyright 2010 bit.ly
#
# 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.
"""
AsyncMongo is an asynchronous library for accessing mongo
http://github.com/bitly/asyncmongo
"""
try:
import bson
except ImportError:
raise ImportError("bson library not installed. Install pymongo >= 1.9 https://github.com/mongodb/mongo-python-driver")
# also update in setup.py
version = "1.3"
version_info = (1, 3)
ASCENDING = 1
"""Ascending sort order."""
DESCENDING = -1
"""Descending sort order."""
GEO2D = "2d"
"""Index specifier for a 2-dimensional `geospatial index`"""
TEXT = { "$meta": "textScore" }
"""TEXT Index sort order."""
from errors import (Error, InterfaceError, AuthenticationError, DatabaseError, RSConnectionError,
DataError, IntegrityError, ProgrammingError, NotSupportedError)
from client import Client
|
b73dbb1a352f06092d8d0a869363eb8ddc0922e5
|
i3pystatus/updates/dnf.py
|
i3pystatus/updates/dnf.py
|
from i3pystatus.core.command import run_through_shell
from i3pystatus.updates import Backend
from re import split, sub
class Dnf(Backend):
"""
Gets updates for RPM-based distributions with `dnf check-update`.
The notification body consists of the status line followed by the package
name and version for each update.
https://dnf.readthedocs.org/en/latest/command_ref.html#check-update-command
"""
@property
def updates(self):
command = ["dnf", "check-update"]
dnf = run_through_shell(command)
raw = dnf.out
update_count = 0
if dnf.rc == 100:
lines = raw.splitlines()[2:]
lines = [l for l in lines if len(split("\s{2,}", l.rstrip())) == 3]
update_count = len(lines)
notif_body = sub(r"(\S+)\s+(\S+)\s+\S+\s*\n", r"\1: \2\n", raw)
return update_count, notif_body
Backend = Dnf
if __name__ == "__main__":
"""
Call this module directly; Print the update count and notification body.
"""
dnf = Dnf()
print("Updates: {}\n\n{}".format(*dnf.updates))
|
from i3pystatus.core.command import run_through_shell
from i3pystatus.updates import Backend
from re import split, sub
class Dnf(Backend):
"""
Gets updates for RPM-based distributions with `dnf check-update`.
The notification body consists of the status line followed by the package
name and version for each update.
https://dnf.readthedocs.org/en/latest/command_ref.html#check-update-command
"""
@property
def updates(self):
command = ["dnf", "check-update"]
dnf = run_through_shell(command)
if dnf.err:
return "?", dnf.err
raw = dnf.out
update_count = 0
if dnf.rc == 100:
lines = raw.splitlines()[2:]
lines = [l for l in lines if len(split("\s{2,}", l.rstrip())) == 3]
update_count = len(lines)
notif_body = sub(r"(\S+)\s+(\S+)\s+\S+\s*\n", r"\1: \2\n", raw)
return update_count, notif_body
Backend = Dnf
if __name__ == "__main__":
"""
Call this module directly; Print the update count and notification body.
"""
dnf = Dnf()
print("Updates: {}\n\n{}".format(*dnf.updates))
|
Return early if the check threw an error.
|
Return early if the check threw an error.
|
Python
|
mit
|
Arvedui/i3pystatus,yang-ling/i3pystatus,m45t3r/i3pystatus,Arvedui/i3pystatus,yang-ling/i3pystatus,m45t3r/i3pystatus,teto/i3pystatus,drwahl/i3pystatus,fmarchenko/i3pystatus,facetoe/i3pystatus,schroeji/i3pystatus,ncoop/i3pystatus,drwahl/i3pystatus,richese/i3pystatus,richese/i3pystatus,schroeji/i3pystatus,teto/i3pystatus,ncoop/i3pystatus,fmarchenko/i3pystatus,enkore/i3pystatus,facetoe/i3pystatus,enkore/i3pystatus
|
from i3pystatus.core.command import run_through_shell
from i3pystatus.updates import Backend
from re import split, sub
class Dnf(Backend):
"""
Gets updates for RPM-based distributions with `dnf check-update`.
The notification body consists of the status line followed by the package
name and version for each update.
https://dnf.readthedocs.org/en/latest/command_ref.html#check-update-command
"""
@property
def updates(self):
command = ["dnf", "check-update"]
dnf = run_through_shell(command)
raw = dnf.out
update_count = 0
if dnf.rc == 100:
lines = raw.splitlines()[2:]
lines = [l for l in lines if len(split("\s{2,}", l.rstrip())) == 3]
update_count = len(lines)
notif_body = sub(r"(\S+)\s+(\S+)\s+\S+\s*\n", r"\1: \2\n", raw)
return update_count, notif_body
Backend = Dnf
if __name__ == "__main__":
"""
Call this module directly; Print the update count and notification body.
"""
dnf = Dnf()
print("Updates: {}\n\n{}".format(*dnf.updates))
Return early if the check threw an error.
|
from i3pystatus.core.command import run_through_shell
from i3pystatus.updates import Backend
from re import split, sub
class Dnf(Backend):
"""
Gets updates for RPM-based distributions with `dnf check-update`.
The notification body consists of the status line followed by the package
name and version for each update.
https://dnf.readthedocs.org/en/latest/command_ref.html#check-update-command
"""
@property
def updates(self):
command = ["dnf", "check-update"]
dnf = run_through_shell(command)
if dnf.err:
return "?", dnf.err
raw = dnf.out
update_count = 0
if dnf.rc == 100:
lines = raw.splitlines()[2:]
lines = [l for l in lines if len(split("\s{2,}", l.rstrip())) == 3]
update_count = len(lines)
notif_body = sub(r"(\S+)\s+(\S+)\s+\S+\s*\n", r"\1: \2\n", raw)
return update_count, notif_body
Backend = Dnf
if __name__ == "__main__":
"""
Call this module directly; Print the update count and notification body.
"""
dnf = Dnf()
print("Updates: {}\n\n{}".format(*dnf.updates))
|
<commit_before>from i3pystatus.core.command import run_through_shell
from i3pystatus.updates import Backend
from re import split, sub
class Dnf(Backend):
"""
Gets updates for RPM-based distributions with `dnf check-update`.
The notification body consists of the status line followed by the package
name and version for each update.
https://dnf.readthedocs.org/en/latest/command_ref.html#check-update-command
"""
@property
def updates(self):
command = ["dnf", "check-update"]
dnf = run_through_shell(command)
raw = dnf.out
update_count = 0
if dnf.rc == 100:
lines = raw.splitlines()[2:]
lines = [l for l in lines if len(split("\s{2,}", l.rstrip())) == 3]
update_count = len(lines)
notif_body = sub(r"(\S+)\s+(\S+)\s+\S+\s*\n", r"\1: \2\n", raw)
return update_count, notif_body
Backend = Dnf
if __name__ == "__main__":
"""
Call this module directly; Print the update count and notification body.
"""
dnf = Dnf()
print("Updates: {}\n\n{}".format(*dnf.updates))
<commit_msg>Return early if the check threw an error.<commit_after>
|
from i3pystatus.core.command import run_through_shell
from i3pystatus.updates import Backend
from re import split, sub
class Dnf(Backend):
"""
Gets updates for RPM-based distributions with `dnf check-update`.
The notification body consists of the status line followed by the package
name and version for each update.
https://dnf.readthedocs.org/en/latest/command_ref.html#check-update-command
"""
@property
def updates(self):
command = ["dnf", "check-update"]
dnf = run_through_shell(command)
if dnf.err:
return "?", dnf.err
raw = dnf.out
update_count = 0
if dnf.rc == 100:
lines = raw.splitlines()[2:]
lines = [l for l in lines if len(split("\s{2,}", l.rstrip())) == 3]
update_count = len(lines)
notif_body = sub(r"(\S+)\s+(\S+)\s+\S+\s*\n", r"\1: \2\n", raw)
return update_count, notif_body
Backend = Dnf
if __name__ == "__main__":
"""
Call this module directly; Print the update count and notification body.
"""
dnf = Dnf()
print("Updates: {}\n\n{}".format(*dnf.updates))
|
from i3pystatus.core.command import run_through_shell
from i3pystatus.updates import Backend
from re import split, sub
class Dnf(Backend):
"""
Gets updates for RPM-based distributions with `dnf check-update`.
The notification body consists of the status line followed by the package
name and version for each update.
https://dnf.readthedocs.org/en/latest/command_ref.html#check-update-command
"""
@property
def updates(self):
command = ["dnf", "check-update"]
dnf = run_through_shell(command)
raw = dnf.out
update_count = 0
if dnf.rc == 100:
lines = raw.splitlines()[2:]
lines = [l for l in lines if len(split("\s{2,}", l.rstrip())) == 3]
update_count = len(lines)
notif_body = sub(r"(\S+)\s+(\S+)\s+\S+\s*\n", r"\1: \2\n", raw)
return update_count, notif_body
Backend = Dnf
if __name__ == "__main__":
"""
Call this module directly; Print the update count and notification body.
"""
dnf = Dnf()
print("Updates: {}\n\n{}".format(*dnf.updates))
Return early if the check threw an error.from i3pystatus.core.command import run_through_shell
from i3pystatus.updates import Backend
from re import split, sub
class Dnf(Backend):
"""
Gets updates for RPM-based distributions with `dnf check-update`.
The notification body consists of the status line followed by the package
name and version for each update.
https://dnf.readthedocs.org/en/latest/command_ref.html#check-update-command
"""
@property
def updates(self):
command = ["dnf", "check-update"]
dnf = run_through_shell(command)
if dnf.err:
return "?", dnf.err
raw = dnf.out
update_count = 0
if dnf.rc == 100:
lines = raw.splitlines()[2:]
lines = [l for l in lines if len(split("\s{2,}", l.rstrip())) == 3]
update_count = len(lines)
notif_body = sub(r"(\S+)\s+(\S+)\s+\S+\s*\n", r"\1: \2\n", raw)
return update_count, notif_body
Backend = Dnf
if __name__ == "__main__":
"""
Call this module directly; Print the update count and notification body.
"""
dnf = Dnf()
print("Updates: {}\n\n{}".format(*dnf.updates))
|
<commit_before>from i3pystatus.core.command import run_through_shell
from i3pystatus.updates import Backend
from re import split, sub
class Dnf(Backend):
"""
Gets updates for RPM-based distributions with `dnf check-update`.
The notification body consists of the status line followed by the package
name and version for each update.
https://dnf.readthedocs.org/en/latest/command_ref.html#check-update-command
"""
@property
def updates(self):
command = ["dnf", "check-update"]
dnf = run_through_shell(command)
raw = dnf.out
update_count = 0
if dnf.rc == 100:
lines = raw.splitlines()[2:]
lines = [l for l in lines if len(split("\s{2,}", l.rstrip())) == 3]
update_count = len(lines)
notif_body = sub(r"(\S+)\s+(\S+)\s+\S+\s*\n", r"\1: \2\n", raw)
return update_count, notif_body
Backend = Dnf
if __name__ == "__main__":
"""
Call this module directly; Print the update count and notification body.
"""
dnf = Dnf()
print("Updates: {}\n\n{}".format(*dnf.updates))
<commit_msg>Return early if the check threw an error.<commit_after>from i3pystatus.core.command import run_through_shell
from i3pystatus.updates import Backend
from re import split, sub
class Dnf(Backend):
"""
Gets updates for RPM-based distributions with `dnf check-update`.
The notification body consists of the status line followed by the package
name and version for each update.
https://dnf.readthedocs.org/en/latest/command_ref.html#check-update-command
"""
@property
def updates(self):
command = ["dnf", "check-update"]
dnf = run_through_shell(command)
if dnf.err:
return "?", dnf.err
raw = dnf.out
update_count = 0
if dnf.rc == 100:
lines = raw.splitlines()[2:]
lines = [l for l in lines if len(split("\s{2,}", l.rstrip())) == 3]
update_count = len(lines)
notif_body = sub(r"(\S+)\s+(\S+)\s+\S+\s*\n", r"\1: \2\n", raw)
return update_count, notif_body
Backend = Dnf
if __name__ == "__main__":
"""
Call this module directly; Print the update count and notification body.
"""
dnf = Dnf()
print("Updates: {}\n\n{}".format(*dnf.updates))
|
8571f61a20f9ef536040c3101e24c48640a72f6a
|
iss/admin.py
|
iss/admin.py
|
from django.contrib import admin
from .models import Organization
class OrganizationAdmin(admin.ModelAdmin):
list_display = ('account_num', 'org_name', 'city', 'state', 'country_iso')
search_fields = ('org_name', 'account_num')
admin.site.register(Organization, OrganizationAdmin)
|
from django.contrib import admin
from .models import Organization
class OrganizationAdmin(admin.ModelAdmin):
list_display = ('membersuite_id', 'account_num', 'org_name', 'city',
'state', 'country_iso')
search_fields = ('org_name', 'membersuite_id', 'account_num')
admin.site.register(Organization, OrganizationAdmin)
|
Add membersuite ID to display and search
|
Add membersuite ID to display and search
|
Python
|
mit
|
AASHE/iss
|
from django.contrib import admin
from .models import Organization
class OrganizationAdmin(admin.ModelAdmin):
list_display = ('account_num', 'org_name', 'city', 'state', 'country_iso')
search_fields = ('org_name', 'account_num')
admin.site.register(Organization, OrganizationAdmin)
Add membersuite ID to display and search
|
from django.contrib import admin
from .models import Organization
class OrganizationAdmin(admin.ModelAdmin):
list_display = ('membersuite_id', 'account_num', 'org_name', 'city',
'state', 'country_iso')
search_fields = ('org_name', 'membersuite_id', 'account_num')
admin.site.register(Organization, OrganizationAdmin)
|
<commit_before>from django.contrib import admin
from .models import Organization
class OrganizationAdmin(admin.ModelAdmin):
list_display = ('account_num', 'org_name', 'city', 'state', 'country_iso')
search_fields = ('org_name', 'account_num')
admin.site.register(Organization, OrganizationAdmin)
<commit_msg>Add membersuite ID to display and search<commit_after>
|
from django.contrib import admin
from .models import Organization
class OrganizationAdmin(admin.ModelAdmin):
list_display = ('membersuite_id', 'account_num', 'org_name', 'city',
'state', 'country_iso')
search_fields = ('org_name', 'membersuite_id', 'account_num')
admin.site.register(Organization, OrganizationAdmin)
|
from django.contrib import admin
from .models import Organization
class OrganizationAdmin(admin.ModelAdmin):
list_display = ('account_num', 'org_name', 'city', 'state', 'country_iso')
search_fields = ('org_name', 'account_num')
admin.site.register(Organization, OrganizationAdmin)
Add membersuite ID to display and searchfrom django.contrib import admin
from .models import Organization
class OrganizationAdmin(admin.ModelAdmin):
list_display = ('membersuite_id', 'account_num', 'org_name', 'city',
'state', 'country_iso')
search_fields = ('org_name', 'membersuite_id', 'account_num')
admin.site.register(Organization, OrganizationAdmin)
|
<commit_before>from django.contrib import admin
from .models import Organization
class OrganizationAdmin(admin.ModelAdmin):
list_display = ('account_num', 'org_name', 'city', 'state', 'country_iso')
search_fields = ('org_name', 'account_num')
admin.site.register(Organization, OrganizationAdmin)
<commit_msg>Add membersuite ID to display and search<commit_after>from django.contrib import admin
from .models import Organization
class OrganizationAdmin(admin.ModelAdmin):
list_display = ('membersuite_id', 'account_num', 'org_name', 'city',
'state', 'country_iso')
search_fields = ('org_name', 'membersuite_id', 'account_num')
admin.site.register(Organization, OrganizationAdmin)
|
e508bdfa034516cd3d9e530bc4a688c20cf65ea3
|
test/conftest.py
|
test/conftest.py
|
from os.path import dirname, join
import sys
import django
import django.conf
def pytest_configure():
example_path = join(dirname(dirname(__file__)), 'example')
if example_path not in sys.path:
sys.path.insert(0, example_path)
settings = {
'DEBUG': True,
'MIDDLEWARE_CLASSES': [
'django_httpolice.HTTPoliceMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
],
'ROOT_URLCONF': 'example_project.urls',
'LANGUAGE_CODE': 'en-us',
'USE_I18N': False,
'HTTPOLICE_ENABLE': True,
'HTTPOLICE_SILENCE': [1070, 1110],
}
if django.VERSION >= (1, 10): # pragma: no cover
settings['MIDDLEWARE'] = settings.pop('MIDDLEWARE_CLASSES')
django.conf.settings.configure(**settings)
|
from os.path import dirname, join
import sys
import django
import django.conf
def pytest_configure():
example_path = join(dirname(dirname(__file__)), 'example')
if example_path not in sys.path:
sys.path.insert(0, example_path)
settings = {
'ALLOWED_HOSTS': ['testserver'],
'DEBUG': True,
'MIDDLEWARE_CLASSES': [
'django_httpolice.HTTPoliceMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
],
'ROOT_URLCONF': 'example_project.urls',
'LANGUAGE_CODE': 'en-us',
'USE_I18N': False,
'HTTPOLICE_ENABLE': True,
'HTTPOLICE_SILENCE': [1070, 1110],
}
if django.VERSION >= (1, 10): # pragma: no cover
settings['MIDDLEWARE'] = settings.pop('MIDDLEWARE_CLASSES')
django.conf.settings.configure(**settings)
|
Fix tests under Django >= 1.10.3
|
Fix tests under Django >= 1.10.3
See "DNS rebinding vulnerability when DEBUG=True"
in Django 1.10.3 release notes:
https://docs.djangoproject.com/en/1.10/releases/1.10.3/
|
Python
|
mit
|
vfaronov/django-httpolice,vfaronov/django-httpolice
|
from os.path import dirname, join
import sys
import django
import django.conf
def pytest_configure():
example_path = join(dirname(dirname(__file__)), 'example')
if example_path not in sys.path:
sys.path.insert(0, example_path)
settings = {
'DEBUG': True,
'MIDDLEWARE_CLASSES': [
'django_httpolice.HTTPoliceMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
],
'ROOT_URLCONF': 'example_project.urls',
'LANGUAGE_CODE': 'en-us',
'USE_I18N': False,
'HTTPOLICE_ENABLE': True,
'HTTPOLICE_SILENCE': [1070, 1110],
}
if django.VERSION >= (1, 10): # pragma: no cover
settings['MIDDLEWARE'] = settings.pop('MIDDLEWARE_CLASSES')
django.conf.settings.configure(**settings)
Fix tests under Django >= 1.10.3
See "DNS rebinding vulnerability when DEBUG=True"
in Django 1.10.3 release notes:
https://docs.djangoproject.com/en/1.10/releases/1.10.3/
|
from os.path import dirname, join
import sys
import django
import django.conf
def pytest_configure():
example_path = join(dirname(dirname(__file__)), 'example')
if example_path not in sys.path:
sys.path.insert(0, example_path)
settings = {
'ALLOWED_HOSTS': ['testserver'],
'DEBUG': True,
'MIDDLEWARE_CLASSES': [
'django_httpolice.HTTPoliceMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
],
'ROOT_URLCONF': 'example_project.urls',
'LANGUAGE_CODE': 'en-us',
'USE_I18N': False,
'HTTPOLICE_ENABLE': True,
'HTTPOLICE_SILENCE': [1070, 1110],
}
if django.VERSION >= (1, 10): # pragma: no cover
settings['MIDDLEWARE'] = settings.pop('MIDDLEWARE_CLASSES')
django.conf.settings.configure(**settings)
|
<commit_before>from os.path import dirname, join
import sys
import django
import django.conf
def pytest_configure():
example_path = join(dirname(dirname(__file__)), 'example')
if example_path not in sys.path:
sys.path.insert(0, example_path)
settings = {
'DEBUG': True,
'MIDDLEWARE_CLASSES': [
'django_httpolice.HTTPoliceMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
],
'ROOT_URLCONF': 'example_project.urls',
'LANGUAGE_CODE': 'en-us',
'USE_I18N': False,
'HTTPOLICE_ENABLE': True,
'HTTPOLICE_SILENCE': [1070, 1110],
}
if django.VERSION >= (1, 10): # pragma: no cover
settings['MIDDLEWARE'] = settings.pop('MIDDLEWARE_CLASSES')
django.conf.settings.configure(**settings)
<commit_msg>Fix tests under Django >= 1.10.3
See "DNS rebinding vulnerability when DEBUG=True"
in Django 1.10.3 release notes:
https://docs.djangoproject.com/en/1.10/releases/1.10.3/<commit_after>
|
from os.path import dirname, join
import sys
import django
import django.conf
def pytest_configure():
example_path = join(dirname(dirname(__file__)), 'example')
if example_path not in sys.path:
sys.path.insert(0, example_path)
settings = {
'ALLOWED_HOSTS': ['testserver'],
'DEBUG': True,
'MIDDLEWARE_CLASSES': [
'django_httpolice.HTTPoliceMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
],
'ROOT_URLCONF': 'example_project.urls',
'LANGUAGE_CODE': 'en-us',
'USE_I18N': False,
'HTTPOLICE_ENABLE': True,
'HTTPOLICE_SILENCE': [1070, 1110],
}
if django.VERSION >= (1, 10): # pragma: no cover
settings['MIDDLEWARE'] = settings.pop('MIDDLEWARE_CLASSES')
django.conf.settings.configure(**settings)
|
from os.path import dirname, join
import sys
import django
import django.conf
def pytest_configure():
example_path = join(dirname(dirname(__file__)), 'example')
if example_path not in sys.path:
sys.path.insert(0, example_path)
settings = {
'DEBUG': True,
'MIDDLEWARE_CLASSES': [
'django_httpolice.HTTPoliceMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
],
'ROOT_URLCONF': 'example_project.urls',
'LANGUAGE_CODE': 'en-us',
'USE_I18N': False,
'HTTPOLICE_ENABLE': True,
'HTTPOLICE_SILENCE': [1070, 1110],
}
if django.VERSION >= (1, 10): # pragma: no cover
settings['MIDDLEWARE'] = settings.pop('MIDDLEWARE_CLASSES')
django.conf.settings.configure(**settings)
Fix tests under Django >= 1.10.3
See "DNS rebinding vulnerability when DEBUG=True"
in Django 1.10.3 release notes:
https://docs.djangoproject.com/en/1.10/releases/1.10.3/from os.path import dirname, join
import sys
import django
import django.conf
def pytest_configure():
example_path = join(dirname(dirname(__file__)), 'example')
if example_path not in sys.path:
sys.path.insert(0, example_path)
settings = {
'ALLOWED_HOSTS': ['testserver'],
'DEBUG': True,
'MIDDLEWARE_CLASSES': [
'django_httpolice.HTTPoliceMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
],
'ROOT_URLCONF': 'example_project.urls',
'LANGUAGE_CODE': 'en-us',
'USE_I18N': False,
'HTTPOLICE_ENABLE': True,
'HTTPOLICE_SILENCE': [1070, 1110],
}
if django.VERSION >= (1, 10): # pragma: no cover
settings['MIDDLEWARE'] = settings.pop('MIDDLEWARE_CLASSES')
django.conf.settings.configure(**settings)
|
<commit_before>from os.path import dirname, join
import sys
import django
import django.conf
def pytest_configure():
example_path = join(dirname(dirname(__file__)), 'example')
if example_path not in sys.path:
sys.path.insert(0, example_path)
settings = {
'DEBUG': True,
'MIDDLEWARE_CLASSES': [
'django_httpolice.HTTPoliceMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
],
'ROOT_URLCONF': 'example_project.urls',
'LANGUAGE_CODE': 'en-us',
'USE_I18N': False,
'HTTPOLICE_ENABLE': True,
'HTTPOLICE_SILENCE': [1070, 1110],
}
if django.VERSION >= (1, 10): # pragma: no cover
settings['MIDDLEWARE'] = settings.pop('MIDDLEWARE_CLASSES')
django.conf.settings.configure(**settings)
<commit_msg>Fix tests under Django >= 1.10.3
See "DNS rebinding vulnerability when DEBUG=True"
in Django 1.10.3 release notes:
https://docs.djangoproject.com/en/1.10/releases/1.10.3/<commit_after>from os.path import dirname, join
import sys
import django
import django.conf
def pytest_configure():
example_path = join(dirname(dirname(__file__)), 'example')
if example_path not in sys.path:
sys.path.insert(0, example_path)
settings = {
'ALLOWED_HOSTS': ['testserver'],
'DEBUG': True,
'MIDDLEWARE_CLASSES': [
'django_httpolice.HTTPoliceMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
],
'ROOT_URLCONF': 'example_project.urls',
'LANGUAGE_CODE': 'en-us',
'USE_I18N': False,
'HTTPOLICE_ENABLE': True,
'HTTPOLICE_SILENCE': [1070, 1110],
}
if django.VERSION >= (1, 10): # pragma: no cover
settings['MIDDLEWARE'] = settings.pop('MIDDLEWARE_CLASSES')
django.conf.settings.configure(**settings)
|
79ed8bdb4f328a0d9949e75f4aa5a4f60ab9305d
|
libqtile/widget/currentlayout.py
|
libqtile/widget/currentlayout.py
|
import base
from .. import manager, bar, hook
class CurrentLayout(base._TextBox):
defaults = manager.Defaults(
("font", "Arial", "Text font"),
("fontsize", None, "Font pixel size. Calculated if None."),
("padding", None, "Padding left and right. Calculated if None."),
("background", None, "Background colour."),
("foreground", "#ffffff", "Foreground colour.")
)
def __init__(self, width=bar.CALCULATED, **config):
base._TextBox.__init__(self, "", width, **config)
def _configure(self, qtile, bar):
base._TextBox._configure(self, qtile, bar)
self.text = self.bar.screen.group.layouts[0].name
self.setup_hooks()
def setup_hooks(self):
def hook_response(layout):
self.text = layout.name
self.bar.draw()
hook.subscribe.layout_change(hook_response)
|
import base
from .. import manager, bar, hook
class CurrentLayout(base._TextBox):
defaults = manager.Defaults(
("font", "Arial", "Text font"),
("fontsize", None, "Font pixel size. Calculated if None."),
("padding", None, "Padding left and right. Calculated if None."),
("background", None, "Background colour."),
("foreground", "#ffffff", "Foreground colour.")
)
def __init__(self, width=bar.CALCULATED, **config):
base._TextBox.__init__(self, "", width, **config)
def _configure(self, qtile, bar):
base._TextBox._configure(self, qtile, bar)
self.text = self.bar.screen.group.layouts[0].name
self.setup_hooks()
def setup_hooks(self):
def hook_response(layout):
self.text = layout.name
self.bar.draw()
hook.subscribe.layout_change(hook_response)
def click(self, x, y, button):
if button == 1:
self.qtile.cmd_nextlayout()
elif button == 2:
self.qtile.cmd_prevlayout()
|
Add click support on layout widget
|
Add click support on layout widget
|
Python
|
mit
|
w1ndy/qtile,kseistrup/qtile,soulchainer/qtile,jdowner/qtile,tych0/qtile,cortesi/qtile,kiniou/qtile,aniruddhkanojia/qtile,apinsard/qtile,de-vri-es/qtile,xplv/qtile,apinsard/qtile,jdowner/qtile,encukou/qtile,frostidaho/qtile,tych0/qtile,encukou/qtile,rxcomm/qtile,StephenBarnes/qtile,andrewyoung1991/qtile,rxcomm/qtile,ramnes/qtile,zordsdavini/qtile,kynikos/qtile,dequis/qtile,zordsdavini/qtile,flacjacket/qtile,aniruddhkanojia/qtile,EndPointCorp/qtile,kopchik/qtile,himaaaatti/qtile,farebord/qtile,kopchik/qtile,StephenBarnes/qtile,nxnfufunezn/qtile,EndPointCorp/qtile,kynikos/qtile,cortesi/qtile,andrewyoung1991/qtile,frostidaho/qtile,ramnes/qtile,himaaaatti/qtile,flacjacket/qtile,dequis/qtile,qtile/qtile,qtile/qtile,soulchainer/qtile,w1ndy/qtile,nxnfufunezn/qtile,farebord/qtile,xplv/qtile,kseistrup/qtile,kiniou/qtile,de-vri-es/qtile
|
import base
from .. import manager, bar, hook
class CurrentLayout(base._TextBox):
defaults = manager.Defaults(
("font", "Arial", "Text font"),
("fontsize", None, "Font pixel size. Calculated if None."),
("padding", None, "Padding left and right. Calculated if None."),
("background", None, "Background colour."),
("foreground", "#ffffff", "Foreground colour.")
)
def __init__(self, width=bar.CALCULATED, **config):
base._TextBox.__init__(self, "", width, **config)
def _configure(self, qtile, bar):
base._TextBox._configure(self, qtile, bar)
self.text = self.bar.screen.group.layouts[0].name
self.setup_hooks()
def setup_hooks(self):
def hook_response(layout):
self.text = layout.name
self.bar.draw()
hook.subscribe.layout_change(hook_response)
Add click support on layout widget
|
import base
from .. import manager, bar, hook
class CurrentLayout(base._TextBox):
defaults = manager.Defaults(
("font", "Arial", "Text font"),
("fontsize", None, "Font pixel size. Calculated if None."),
("padding", None, "Padding left and right. Calculated if None."),
("background", None, "Background colour."),
("foreground", "#ffffff", "Foreground colour.")
)
def __init__(self, width=bar.CALCULATED, **config):
base._TextBox.__init__(self, "", width, **config)
def _configure(self, qtile, bar):
base._TextBox._configure(self, qtile, bar)
self.text = self.bar.screen.group.layouts[0].name
self.setup_hooks()
def setup_hooks(self):
def hook_response(layout):
self.text = layout.name
self.bar.draw()
hook.subscribe.layout_change(hook_response)
def click(self, x, y, button):
if button == 1:
self.qtile.cmd_nextlayout()
elif button == 2:
self.qtile.cmd_prevlayout()
|
<commit_before>import base
from .. import manager, bar, hook
class CurrentLayout(base._TextBox):
defaults = manager.Defaults(
("font", "Arial", "Text font"),
("fontsize", None, "Font pixel size. Calculated if None."),
("padding", None, "Padding left and right. Calculated if None."),
("background", None, "Background colour."),
("foreground", "#ffffff", "Foreground colour.")
)
def __init__(self, width=bar.CALCULATED, **config):
base._TextBox.__init__(self, "", width, **config)
def _configure(self, qtile, bar):
base._TextBox._configure(self, qtile, bar)
self.text = self.bar.screen.group.layouts[0].name
self.setup_hooks()
def setup_hooks(self):
def hook_response(layout):
self.text = layout.name
self.bar.draw()
hook.subscribe.layout_change(hook_response)
<commit_msg>Add click support on layout widget<commit_after>
|
import base
from .. import manager, bar, hook
class CurrentLayout(base._TextBox):
defaults = manager.Defaults(
("font", "Arial", "Text font"),
("fontsize", None, "Font pixel size. Calculated if None."),
("padding", None, "Padding left and right. Calculated if None."),
("background", None, "Background colour."),
("foreground", "#ffffff", "Foreground colour.")
)
def __init__(self, width=bar.CALCULATED, **config):
base._TextBox.__init__(self, "", width, **config)
def _configure(self, qtile, bar):
base._TextBox._configure(self, qtile, bar)
self.text = self.bar.screen.group.layouts[0].name
self.setup_hooks()
def setup_hooks(self):
def hook_response(layout):
self.text = layout.name
self.bar.draw()
hook.subscribe.layout_change(hook_response)
def click(self, x, y, button):
if button == 1:
self.qtile.cmd_nextlayout()
elif button == 2:
self.qtile.cmd_prevlayout()
|
import base
from .. import manager, bar, hook
class CurrentLayout(base._TextBox):
defaults = manager.Defaults(
("font", "Arial", "Text font"),
("fontsize", None, "Font pixel size. Calculated if None."),
("padding", None, "Padding left and right. Calculated if None."),
("background", None, "Background colour."),
("foreground", "#ffffff", "Foreground colour.")
)
def __init__(self, width=bar.CALCULATED, **config):
base._TextBox.__init__(self, "", width, **config)
def _configure(self, qtile, bar):
base._TextBox._configure(self, qtile, bar)
self.text = self.bar.screen.group.layouts[0].name
self.setup_hooks()
def setup_hooks(self):
def hook_response(layout):
self.text = layout.name
self.bar.draw()
hook.subscribe.layout_change(hook_response)
Add click support on layout widgetimport base
from .. import manager, bar, hook
class CurrentLayout(base._TextBox):
defaults = manager.Defaults(
("font", "Arial", "Text font"),
("fontsize", None, "Font pixel size. Calculated if None."),
("padding", None, "Padding left and right. Calculated if None."),
("background", None, "Background colour."),
("foreground", "#ffffff", "Foreground colour.")
)
def __init__(self, width=bar.CALCULATED, **config):
base._TextBox.__init__(self, "", width, **config)
def _configure(self, qtile, bar):
base._TextBox._configure(self, qtile, bar)
self.text = self.bar.screen.group.layouts[0].name
self.setup_hooks()
def setup_hooks(self):
def hook_response(layout):
self.text = layout.name
self.bar.draw()
hook.subscribe.layout_change(hook_response)
def click(self, x, y, button):
if button == 1:
self.qtile.cmd_nextlayout()
elif button == 2:
self.qtile.cmd_prevlayout()
|
<commit_before>import base
from .. import manager, bar, hook
class CurrentLayout(base._TextBox):
defaults = manager.Defaults(
("font", "Arial", "Text font"),
("fontsize", None, "Font pixel size. Calculated if None."),
("padding", None, "Padding left and right. Calculated if None."),
("background", None, "Background colour."),
("foreground", "#ffffff", "Foreground colour.")
)
def __init__(self, width=bar.CALCULATED, **config):
base._TextBox.__init__(self, "", width, **config)
def _configure(self, qtile, bar):
base._TextBox._configure(self, qtile, bar)
self.text = self.bar.screen.group.layouts[0].name
self.setup_hooks()
def setup_hooks(self):
def hook_response(layout):
self.text = layout.name
self.bar.draw()
hook.subscribe.layout_change(hook_response)
<commit_msg>Add click support on layout widget<commit_after>import base
from .. import manager, bar, hook
class CurrentLayout(base._TextBox):
defaults = manager.Defaults(
("font", "Arial", "Text font"),
("fontsize", None, "Font pixel size. Calculated if None."),
("padding", None, "Padding left and right. Calculated if None."),
("background", None, "Background colour."),
("foreground", "#ffffff", "Foreground colour.")
)
def __init__(self, width=bar.CALCULATED, **config):
base._TextBox.__init__(self, "", width, **config)
def _configure(self, qtile, bar):
base._TextBox._configure(self, qtile, bar)
self.text = self.bar.screen.group.layouts[0].name
self.setup_hooks()
def setup_hooks(self):
def hook_response(layout):
self.text = layout.name
self.bar.draw()
hook.subscribe.layout_change(hook_response)
def click(self, x, y, button):
if button == 1:
self.qtile.cmd_nextlayout()
elif button == 2:
self.qtile.cmd_prevlayout()
|
893e52b16ea7998db1418dab8a10467a1f891289
|
forms.py
|
forms.py
|
from flask_wtf import Form
from flask_wtf.csrf import CsrfProtect
from wtforms import StringField, IntegerField, SelectField, BooleanField
csrf = CsrfProtect()
class Submission(Form):
submission = StringField('Submission URL')
comments = BooleanField('Include comments')
comments_style = SelectField('Comments style', choices=[('numbers', 'numbers'), ('quotes', 'quotes')])
email = StringField('Kindle email address')
kindle_address = SelectField('Kindle address', choices=[('normal', '@kindle.com'), ('free', '@free.kindle.com')])
class Subreddit(Form):
subreddit = StringField('Subreddit')
comments = BooleanField('Include comments')
comments_style = SelectField('Comments style', choices=[('numbers', 'numbers'), ('quotes', 'quotes')])
time = SelectField('Time period',
choices=[('all', 'all'), ('year', 'year'), ('month', 'month'), ('week', 'week'), ('day', 'day'),
('hour', 'hour')], default='week')
limit = IntegerField('Number of posts')
email = StringField('Kindle email address')
kindle_address = SelectField('Kindle address', choices=[('normal', '@kindle.com'), ('free', '@free.kindle.com')])
|
from flask_wtf import FlaskForm
from flask_wtf.csrf import CsrfProtect
from wtforms import StringField, IntegerField, SelectField, BooleanField
csrf = CsrfProtect()
class Submission(FlaskForm):
submission = StringField('Submission URL')
comments = BooleanField('Include comments')
comments_style = SelectField('Comments style', choices=[('numbers', 'numbers'), ('quotes', 'quotes')])
email = StringField('Kindle email address')
kindle_address = SelectField('Kindle address', choices=[('normal', '@kindle.com'), ('free', '@free.kindle.com')])
class Subreddit(FlaskForm):
subreddit = StringField('Subreddit')
comments = BooleanField('Include comments')
comments_style = SelectField('Comments style', choices=[('numbers', 'numbers'), ('quotes', 'quotes')])
time = SelectField('Time period',
choices=[('all', 'all'), ('year', 'year'), ('month', 'month'), ('week', 'week'), ('day', 'day'),
('hour', 'hour')], default='week')
limit = IntegerField('Number of posts')
email = StringField('Kindle email address')
kindle_address = SelectField('Kindle address', choices=[('normal', '@kindle.com'), ('free', '@free.kindle.com')])
|
Migrate from Form to FlaskForm
|
Migrate from Form to FlaskForm
|
Python
|
mit
|
JamieMagee/reddit2kindle,JamieMagee/reddit2kindle
|
from flask_wtf import Form
from flask_wtf.csrf import CsrfProtect
from wtforms import StringField, IntegerField, SelectField, BooleanField
csrf = CsrfProtect()
class Submission(Form):
submission = StringField('Submission URL')
comments = BooleanField('Include comments')
comments_style = SelectField('Comments style', choices=[('numbers', 'numbers'), ('quotes', 'quotes')])
email = StringField('Kindle email address')
kindle_address = SelectField('Kindle address', choices=[('normal', '@kindle.com'), ('free', '@free.kindle.com')])
class Subreddit(Form):
subreddit = StringField('Subreddit')
comments = BooleanField('Include comments')
comments_style = SelectField('Comments style', choices=[('numbers', 'numbers'), ('quotes', 'quotes')])
time = SelectField('Time period',
choices=[('all', 'all'), ('year', 'year'), ('month', 'month'), ('week', 'week'), ('day', 'day'),
('hour', 'hour')], default='week')
limit = IntegerField('Number of posts')
email = StringField('Kindle email address')
kindle_address = SelectField('Kindle address', choices=[('normal', '@kindle.com'), ('free', '@free.kindle.com')])
Migrate from Form to FlaskForm
|
from flask_wtf import FlaskForm
from flask_wtf.csrf import CsrfProtect
from wtforms import StringField, IntegerField, SelectField, BooleanField
csrf = CsrfProtect()
class Submission(FlaskForm):
submission = StringField('Submission URL')
comments = BooleanField('Include comments')
comments_style = SelectField('Comments style', choices=[('numbers', 'numbers'), ('quotes', 'quotes')])
email = StringField('Kindle email address')
kindle_address = SelectField('Kindle address', choices=[('normal', '@kindle.com'), ('free', '@free.kindle.com')])
class Subreddit(FlaskForm):
subreddit = StringField('Subreddit')
comments = BooleanField('Include comments')
comments_style = SelectField('Comments style', choices=[('numbers', 'numbers'), ('quotes', 'quotes')])
time = SelectField('Time period',
choices=[('all', 'all'), ('year', 'year'), ('month', 'month'), ('week', 'week'), ('day', 'day'),
('hour', 'hour')], default='week')
limit = IntegerField('Number of posts')
email = StringField('Kindle email address')
kindle_address = SelectField('Kindle address', choices=[('normal', '@kindle.com'), ('free', '@free.kindle.com')])
|
<commit_before>from flask_wtf import Form
from flask_wtf.csrf import CsrfProtect
from wtforms import StringField, IntegerField, SelectField, BooleanField
csrf = CsrfProtect()
class Submission(Form):
submission = StringField('Submission URL')
comments = BooleanField('Include comments')
comments_style = SelectField('Comments style', choices=[('numbers', 'numbers'), ('quotes', 'quotes')])
email = StringField('Kindle email address')
kindle_address = SelectField('Kindle address', choices=[('normal', '@kindle.com'), ('free', '@free.kindle.com')])
class Subreddit(Form):
subreddit = StringField('Subreddit')
comments = BooleanField('Include comments')
comments_style = SelectField('Comments style', choices=[('numbers', 'numbers'), ('quotes', 'quotes')])
time = SelectField('Time period',
choices=[('all', 'all'), ('year', 'year'), ('month', 'month'), ('week', 'week'), ('day', 'day'),
('hour', 'hour')], default='week')
limit = IntegerField('Number of posts')
email = StringField('Kindle email address')
kindle_address = SelectField('Kindle address', choices=[('normal', '@kindle.com'), ('free', '@free.kindle.com')])
<commit_msg>Migrate from Form to FlaskForm<commit_after>
|
from flask_wtf import FlaskForm
from flask_wtf.csrf import CsrfProtect
from wtforms import StringField, IntegerField, SelectField, BooleanField
csrf = CsrfProtect()
class Submission(FlaskForm):
submission = StringField('Submission URL')
comments = BooleanField('Include comments')
comments_style = SelectField('Comments style', choices=[('numbers', 'numbers'), ('quotes', 'quotes')])
email = StringField('Kindle email address')
kindle_address = SelectField('Kindle address', choices=[('normal', '@kindle.com'), ('free', '@free.kindle.com')])
class Subreddit(FlaskForm):
subreddit = StringField('Subreddit')
comments = BooleanField('Include comments')
comments_style = SelectField('Comments style', choices=[('numbers', 'numbers'), ('quotes', 'quotes')])
time = SelectField('Time period',
choices=[('all', 'all'), ('year', 'year'), ('month', 'month'), ('week', 'week'), ('day', 'day'),
('hour', 'hour')], default='week')
limit = IntegerField('Number of posts')
email = StringField('Kindle email address')
kindle_address = SelectField('Kindle address', choices=[('normal', '@kindle.com'), ('free', '@free.kindle.com')])
|
from flask_wtf import Form
from flask_wtf.csrf import CsrfProtect
from wtforms import StringField, IntegerField, SelectField, BooleanField
csrf = CsrfProtect()
class Submission(Form):
submission = StringField('Submission URL')
comments = BooleanField('Include comments')
comments_style = SelectField('Comments style', choices=[('numbers', 'numbers'), ('quotes', 'quotes')])
email = StringField('Kindle email address')
kindle_address = SelectField('Kindle address', choices=[('normal', '@kindle.com'), ('free', '@free.kindle.com')])
class Subreddit(Form):
subreddit = StringField('Subreddit')
comments = BooleanField('Include comments')
comments_style = SelectField('Comments style', choices=[('numbers', 'numbers'), ('quotes', 'quotes')])
time = SelectField('Time period',
choices=[('all', 'all'), ('year', 'year'), ('month', 'month'), ('week', 'week'), ('day', 'day'),
('hour', 'hour')], default='week')
limit = IntegerField('Number of posts')
email = StringField('Kindle email address')
kindle_address = SelectField('Kindle address', choices=[('normal', '@kindle.com'), ('free', '@free.kindle.com')])
Migrate from Form to FlaskFormfrom flask_wtf import FlaskForm
from flask_wtf.csrf import CsrfProtect
from wtforms import StringField, IntegerField, SelectField, BooleanField
csrf = CsrfProtect()
class Submission(FlaskForm):
submission = StringField('Submission URL')
comments = BooleanField('Include comments')
comments_style = SelectField('Comments style', choices=[('numbers', 'numbers'), ('quotes', 'quotes')])
email = StringField('Kindle email address')
kindle_address = SelectField('Kindle address', choices=[('normal', '@kindle.com'), ('free', '@free.kindle.com')])
class Subreddit(FlaskForm):
subreddit = StringField('Subreddit')
comments = BooleanField('Include comments')
comments_style = SelectField('Comments style', choices=[('numbers', 'numbers'), ('quotes', 'quotes')])
time = SelectField('Time period',
choices=[('all', 'all'), ('year', 'year'), ('month', 'month'), ('week', 'week'), ('day', 'day'),
('hour', 'hour')], default='week')
limit = IntegerField('Number of posts')
email = StringField('Kindle email address')
kindle_address = SelectField('Kindle address', choices=[('normal', '@kindle.com'), ('free', '@free.kindle.com')])
|
<commit_before>from flask_wtf import Form
from flask_wtf.csrf import CsrfProtect
from wtforms import StringField, IntegerField, SelectField, BooleanField
csrf = CsrfProtect()
class Submission(Form):
submission = StringField('Submission URL')
comments = BooleanField('Include comments')
comments_style = SelectField('Comments style', choices=[('numbers', 'numbers'), ('quotes', 'quotes')])
email = StringField('Kindle email address')
kindle_address = SelectField('Kindle address', choices=[('normal', '@kindle.com'), ('free', '@free.kindle.com')])
class Subreddit(Form):
subreddit = StringField('Subreddit')
comments = BooleanField('Include comments')
comments_style = SelectField('Comments style', choices=[('numbers', 'numbers'), ('quotes', 'quotes')])
time = SelectField('Time period',
choices=[('all', 'all'), ('year', 'year'), ('month', 'month'), ('week', 'week'), ('day', 'day'),
('hour', 'hour')], default='week')
limit = IntegerField('Number of posts')
email = StringField('Kindle email address')
kindle_address = SelectField('Kindle address', choices=[('normal', '@kindle.com'), ('free', '@free.kindle.com')])
<commit_msg>Migrate from Form to FlaskForm<commit_after>from flask_wtf import FlaskForm
from flask_wtf.csrf import CsrfProtect
from wtforms import StringField, IntegerField, SelectField, BooleanField
csrf = CsrfProtect()
class Submission(FlaskForm):
submission = StringField('Submission URL')
comments = BooleanField('Include comments')
comments_style = SelectField('Comments style', choices=[('numbers', 'numbers'), ('quotes', 'quotes')])
email = StringField('Kindle email address')
kindle_address = SelectField('Kindle address', choices=[('normal', '@kindle.com'), ('free', '@free.kindle.com')])
class Subreddit(FlaskForm):
subreddit = StringField('Subreddit')
comments = BooleanField('Include comments')
comments_style = SelectField('Comments style', choices=[('numbers', 'numbers'), ('quotes', 'quotes')])
time = SelectField('Time period',
choices=[('all', 'all'), ('year', 'year'), ('month', 'month'), ('week', 'week'), ('day', 'day'),
('hour', 'hour')], default='week')
limit = IntegerField('Number of posts')
email = StringField('Kindle email address')
kindle_address = SelectField('Kindle address', choices=[('normal', '@kindle.com'), ('free', '@free.kindle.com')])
|
18e3c3f716863b1cc259800592a07a89844d4bf8
|
appvalidator/testcases/scripting.py
|
appvalidator/testcases/scripting.py
|
import javascript.traverser as traverser
from javascript.spidermonkey import get_tree
from appvalidator.constants import SPIDERMONKEY_INSTALLATION
from ..contextgenerator import ContextGenerator
def test_js_file(err, filename, data, line=0, context=None):
"Tests a JS file by parsing and analyzing its tokens"
if (SPIDERMONKEY_INSTALLATION is None or
err.get_resource("SPIDERMONKEY") is None): # Default value is False
return
# Set the tier to 4 (Security Tests)
if err is not None:
before_tier = err.tier
err.set_tier(3)
tree = get_tree(data, err, filename,
err and err.get_resource("SPIDERMONKEY") or
SPIDERMONKEY_INSTALLATION)
if not tree:
if err is not None:
err.set_tier(before_tier)
return
trav = traverser.Traverser(
err, filename, line, context=context or ContextGenerator(data))
trav.run(tree)
# Reset the tier so we don't break the world
if err is not None:
err.set_tier(before_tier)
|
import javascript.traverser as traverser
from javascript.spidermonkey import get_tree
from appvalidator.constants import SPIDERMONKEY_INSTALLATION
from ..contextgenerator import ContextGenerator
def test_js_file(err, filename, data, line=0, context=None):
"Tests a JS file by parsing and analyzing its tokens"
if (SPIDERMONKEY_INSTALLATION is None or
err.get_resource("SPIDERMONKEY") is None): # Default value is False
return
# Set the tier to 4 (Security Tests)
if err is not None:
before_tier = err.tier
err.set_tier(3)
tree = get_tree(data, err, filename,
err and err.get_resource("SPIDERMONKEY") or
SPIDERMONKEY_INSTALLATION)
if not tree:
err.metadata.ran_js_tests = "no;missing ast"
if err is not None:
err.set_tier(before_tier)
return
trav = traverser.Traverser(
err, filename, line, context=context or ContextGenerator(data))
trav.run(tree)
err.metadata.ran_js_tests = "yes"
# Reset the tier so we don't break the world
if err is not None:
err.set_tier(before_tier)
|
Add information about JS test status to metadata
|
Add information about JS test status to metadata
|
Python
|
bsd-3-clause
|
mozilla/app-validator,stasm/app-validator,diox/app-validator,eviljeff/app-validator,eviljeff/app-validator,diox/app-validator,mstriemer/app-validator,diox/app-validator,eviljeff/app-validator,mstriemer/app-validator,mozilla/app-validator,diox/app-validator,mozilla/app-validator,stasm/app-validator,stasm/app-validator,eviljeff/app-validator,mstriemer/app-validator,mozilla/app-validator,stasm/app-validator
|
import javascript.traverser as traverser
from javascript.spidermonkey import get_tree
from appvalidator.constants import SPIDERMONKEY_INSTALLATION
from ..contextgenerator import ContextGenerator
def test_js_file(err, filename, data, line=0, context=None):
"Tests a JS file by parsing and analyzing its tokens"
if (SPIDERMONKEY_INSTALLATION is None or
err.get_resource("SPIDERMONKEY") is None): # Default value is False
return
# Set the tier to 4 (Security Tests)
if err is not None:
before_tier = err.tier
err.set_tier(3)
tree = get_tree(data, err, filename,
err and err.get_resource("SPIDERMONKEY") or
SPIDERMONKEY_INSTALLATION)
if not tree:
if err is not None:
err.set_tier(before_tier)
return
trav = traverser.Traverser(
err, filename, line, context=context or ContextGenerator(data))
trav.run(tree)
# Reset the tier so we don't break the world
if err is not None:
err.set_tier(before_tier)
Add information about JS test status to metadata
|
import javascript.traverser as traverser
from javascript.spidermonkey import get_tree
from appvalidator.constants import SPIDERMONKEY_INSTALLATION
from ..contextgenerator import ContextGenerator
def test_js_file(err, filename, data, line=0, context=None):
"Tests a JS file by parsing and analyzing its tokens"
if (SPIDERMONKEY_INSTALLATION is None or
err.get_resource("SPIDERMONKEY") is None): # Default value is False
return
# Set the tier to 4 (Security Tests)
if err is not None:
before_tier = err.tier
err.set_tier(3)
tree = get_tree(data, err, filename,
err and err.get_resource("SPIDERMONKEY") or
SPIDERMONKEY_INSTALLATION)
if not tree:
err.metadata.ran_js_tests = "no;missing ast"
if err is not None:
err.set_tier(before_tier)
return
trav = traverser.Traverser(
err, filename, line, context=context or ContextGenerator(data))
trav.run(tree)
err.metadata.ran_js_tests = "yes"
# Reset the tier so we don't break the world
if err is not None:
err.set_tier(before_tier)
|
<commit_before>import javascript.traverser as traverser
from javascript.spidermonkey import get_tree
from appvalidator.constants import SPIDERMONKEY_INSTALLATION
from ..contextgenerator import ContextGenerator
def test_js_file(err, filename, data, line=0, context=None):
"Tests a JS file by parsing and analyzing its tokens"
if (SPIDERMONKEY_INSTALLATION is None or
err.get_resource("SPIDERMONKEY") is None): # Default value is False
return
# Set the tier to 4 (Security Tests)
if err is not None:
before_tier = err.tier
err.set_tier(3)
tree = get_tree(data, err, filename,
err and err.get_resource("SPIDERMONKEY") or
SPIDERMONKEY_INSTALLATION)
if not tree:
if err is not None:
err.set_tier(before_tier)
return
trav = traverser.Traverser(
err, filename, line, context=context or ContextGenerator(data))
trav.run(tree)
# Reset the tier so we don't break the world
if err is not None:
err.set_tier(before_tier)
<commit_msg>Add information about JS test status to metadata<commit_after>
|
import javascript.traverser as traverser
from javascript.spidermonkey import get_tree
from appvalidator.constants import SPIDERMONKEY_INSTALLATION
from ..contextgenerator import ContextGenerator
def test_js_file(err, filename, data, line=0, context=None):
"Tests a JS file by parsing and analyzing its tokens"
if (SPIDERMONKEY_INSTALLATION is None or
err.get_resource("SPIDERMONKEY") is None): # Default value is False
return
# Set the tier to 4 (Security Tests)
if err is not None:
before_tier = err.tier
err.set_tier(3)
tree = get_tree(data, err, filename,
err and err.get_resource("SPIDERMONKEY") or
SPIDERMONKEY_INSTALLATION)
if not tree:
err.metadata.ran_js_tests = "no;missing ast"
if err is not None:
err.set_tier(before_tier)
return
trav = traverser.Traverser(
err, filename, line, context=context or ContextGenerator(data))
trav.run(tree)
err.metadata.ran_js_tests = "yes"
# Reset the tier so we don't break the world
if err is not None:
err.set_tier(before_tier)
|
import javascript.traverser as traverser
from javascript.spidermonkey import get_tree
from appvalidator.constants import SPIDERMONKEY_INSTALLATION
from ..contextgenerator import ContextGenerator
def test_js_file(err, filename, data, line=0, context=None):
"Tests a JS file by parsing and analyzing its tokens"
if (SPIDERMONKEY_INSTALLATION is None or
err.get_resource("SPIDERMONKEY") is None): # Default value is False
return
# Set the tier to 4 (Security Tests)
if err is not None:
before_tier = err.tier
err.set_tier(3)
tree = get_tree(data, err, filename,
err and err.get_resource("SPIDERMONKEY") or
SPIDERMONKEY_INSTALLATION)
if not tree:
if err is not None:
err.set_tier(before_tier)
return
trav = traverser.Traverser(
err, filename, line, context=context or ContextGenerator(data))
trav.run(tree)
# Reset the tier so we don't break the world
if err is not None:
err.set_tier(before_tier)
Add information about JS test status to metadataimport javascript.traverser as traverser
from javascript.spidermonkey import get_tree
from appvalidator.constants import SPIDERMONKEY_INSTALLATION
from ..contextgenerator import ContextGenerator
def test_js_file(err, filename, data, line=0, context=None):
"Tests a JS file by parsing and analyzing its tokens"
if (SPIDERMONKEY_INSTALLATION is None or
err.get_resource("SPIDERMONKEY") is None): # Default value is False
return
# Set the tier to 4 (Security Tests)
if err is not None:
before_tier = err.tier
err.set_tier(3)
tree = get_tree(data, err, filename,
err and err.get_resource("SPIDERMONKEY") or
SPIDERMONKEY_INSTALLATION)
if not tree:
err.metadata.ran_js_tests = "no;missing ast"
if err is not None:
err.set_tier(before_tier)
return
trav = traverser.Traverser(
err, filename, line, context=context or ContextGenerator(data))
trav.run(tree)
err.metadata.ran_js_tests = "yes"
# Reset the tier so we don't break the world
if err is not None:
err.set_tier(before_tier)
|
<commit_before>import javascript.traverser as traverser
from javascript.spidermonkey import get_tree
from appvalidator.constants import SPIDERMONKEY_INSTALLATION
from ..contextgenerator import ContextGenerator
def test_js_file(err, filename, data, line=0, context=None):
"Tests a JS file by parsing and analyzing its tokens"
if (SPIDERMONKEY_INSTALLATION is None or
err.get_resource("SPIDERMONKEY") is None): # Default value is False
return
# Set the tier to 4 (Security Tests)
if err is not None:
before_tier = err.tier
err.set_tier(3)
tree = get_tree(data, err, filename,
err and err.get_resource("SPIDERMONKEY") or
SPIDERMONKEY_INSTALLATION)
if not tree:
if err is not None:
err.set_tier(before_tier)
return
trav = traverser.Traverser(
err, filename, line, context=context or ContextGenerator(data))
trav.run(tree)
# Reset the tier so we don't break the world
if err is not None:
err.set_tier(before_tier)
<commit_msg>Add information about JS test status to metadata<commit_after>import javascript.traverser as traverser
from javascript.spidermonkey import get_tree
from appvalidator.constants import SPIDERMONKEY_INSTALLATION
from ..contextgenerator import ContextGenerator
def test_js_file(err, filename, data, line=0, context=None):
"Tests a JS file by parsing and analyzing its tokens"
if (SPIDERMONKEY_INSTALLATION is None or
err.get_resource("SPIDERMONKEY") is None): # Default value is False
return
# Set the tier to 4 (Security Tests)
if err is not None:
before_tier = err.tier
err.set_tier(3)
tree = get_tree(data, err, filename,
err and err.get_resource("SPIDERMONKEY") or
SPIDERMONKEY_INSTALLATION)
if not tree:
err.metadata.ran_js_tests = "no;missing ast"
if err is not None:
err.set_tier(before_tier)
return
trav = traverser.Traverser(
err, filename, line, context=context or ContextGenerator(data))
trav.run(tree)
err.metadata.ran_js_tests = "yes"
# Reset the tier so we don't break the world
if err is not None:
err.set_tier(before_tier)
|
0c55c9cbcf9af918abeaff0f7ea612373f1cfbbe
|
test_trigrams.py
|
test_trigrams.py
|
# -*- coding: utf-8 -*-
"""Trigram tests."""
import pytest
text = "az"
text_with_punct = "a.,/-z"
def test_read_file():
"""Assert the file imported and was split into lines."""
from trigrams import read_file
assert len(read_file()) > 0
@pytest.mark.parametrize('text, text_res', text_with_punct, text)
def test_strip_punct(text, text_res):
"""Assert no punctuation exists in the text."""
from trigrams import strip_punct
assert strip_punct(text) == text_res
|
# -*- coding: utf-8 -*-
"""Trigram tests."""
import pytest
text = "a z"
text_with_punct = "a.,/-z"
def test_read_file():
"""Assert the file imported and was split into lines."""
from trigrams import read_file
assert len(read_file()) > 0
def test_strip_punct():
"""Assert no punctuation exists in the text."""
from trigrams import strip_punct
assert strip_punct(text_with_punct) == text
|
Remove paramatrize, edit test so it passes
|
Remove paramatrize, edit test so it passes
|
Python
|
mit
|
bgarnaat/401_trigrams
|
# -*- coding: utf-8 -*-
"""Trigram tests."""
import pytest
text = "az"
text_with_punct = "a.,/-z"
def test_read_file():
"""Assert the file imported and was split into lines."""
from trigrams import read_file
assert len(read_file()) > 0
@pytest.mark.parametrize('text, text_res', text_with_punct, text)
def test_strip_punct(text, text_res):
"""Assert no punctuation exists in the text."""
from trigrams import strip_punct
assert strip_punct(text) == text_res
Remove paramatrize, edit test so it passes
|
# -*- coding: utf-8 -*-
"""Trigram tests."""
import pytest
text = "a z"
text_with_punct = "a.,/-z"
def test_read_file():
"""Assert the file imported and was split into lines."""
from trigrams import read_file
assert len(read_file()) > 0
def test_strip_punct():
"""Assert no punctuation exists in the text."""
from trigrams import strip_punct
assert strip_punct(text_with_punct) == text
|
<commit_before># -*- coding: utf-8 -*-
"""Trigram tests."""
import pytest
text = "az"
text_with_punct = "a.,/-z"
def test_read_file():
"""Assert the file imported and was split into lines."""
from trigrams import read_file
assert len(read_file()) > 0
@pytest.mark.parametrize('text, text_res', text_with_punct, text)
def test_strip_punct(text, text_res):
"""Assert no punctuation exists in the text."""
from trigrams import strip_punct
assert strip_punct(text) == text_res
<commit_msg>Remove paramatrize, edit test so it passes<commit_after>
|
# -*- coding: utf-8 -*-
"""Trigram tests."""
import pytest
text = "a z"
text_with_punct = "a.,/-z"
def test_read_file():
"""Assert the file imported and was split into lines."""
from trigrams import read_file
assert len(read_file()) > 0
def test_strip_punct():
"""Assert no punctuation exists in the text."""
from trigrams import strip_punct
assert strip_punct(text_with_punct) == text
|
# -*- coding: utf-8 -*-
"""Trigram tests."""
import pytest
text = "az"
text_with_punct = "a.,/-z"
def test_read_file():
"""Assert the file imported and was split into lines."""
from trigrams import read_file
assert len(read_file()) > 0
@pytest.mark.parametrize('text, text_res', text_with_punct, text)
def test_strip_punct(text, text_res):
"""Assert no punctuation exists in the text."""
from trigrams import strip_punct
assert strip_punct(text) == text_res
Remove paramatrize, edit test so it passes# -*- coding: utf-8 -*-
"""Trigram tests."""
import pytest
text = "a z"
text_with_punct = "a.,/-z"
def test_read_file():
"""Assert the file imported and was split into lines."""
from trigrams import read_file
assert len(read_file()) > 0
def test_strip_punct():
"""Assert no punctuation exists in the text."""
from trigrams import strip_punct
assert strip_punct(text_with_punct) == text
|
<commit_before># -*- coding: utf-8 -*-
"""Trigram tests."""
import pytest
text = "az"
text_with_punct = "a.,/-z"
def test_read_file():
"""Assert the file imported and was split into lines."""
from trigrams import read_file
assert len(read_file()) > 0
@pytest.mark.parametrize('text, text_res', text_with_punct, text)
def test_strip_punct(text, text_res):
"""Assert no punctuation exists in the text."""
from trigrams import strip_punct
assert strip_punct(text) == text_res
<commit_msg>Remove paramatrize, edit test so it passes<commit_after># -*- coding: utf-8 -*-
"""Trigram tests."""
import pytest
text = "a z"
text_with_punct = "a.,/-z"
def test_read_file():
"""Assert the file imported and was split into lines."""
from trigrams import read_file
assert len(read_file()) > 0
def test_strip_punct():
"""Assert no punctuation exists in the text."""
from trigrams import strip_punct
assert strip_punct(text_with_punct) == text
|
e53ecef685569dfad2c62cd38c53190a9b2012d0
|
metpy/gridding/__init__.py
|
metpy/gridding/__init__.py
|
# Copyright (c) 2008-2015 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
from .gridding_functions import * # noqa: F403
from .points import * # noqa: F403
from .triangles import * # noqa: F403
from .polygons import * # noqa: F403
from .interpolation import * # noqa: F403
__all__ = gridding_functions.__all__[:] # pylint: disable=undefined-variable
__all__.extend(interpolation.__all__) # pylint: disable=undefined-variable
|
# Copyright (c) 2008-2015 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
from .gridding_functions import * # noqa: F403
from .interpolation import * # noqa: F403
__all__ = gridding_functions.__all__[:] # pylint: disable=undefined-variable
__all__.extend(interpolation.__all__) # pylint: disable=undefined-variable
|
Remove some imported modules from gridding
|
MNT: Remove some imported modules from gridding
We never intended these to be part of the supported API. The fact that
these were available from metpy.gridding was revealed by the new
autosummary docs.
|
Python
|
bsd-3-clause
|
ShawnMurd/MetPy,dopplershift/MetPy,ahaberlie/MetPy,jrleeman/MetPy,ahaberlie/MetPy,dopplershift/MetPy,Unidata/MetPy,jrleeman/MetPy,Unidata/MetPy
|
# Copyright (c) 2008-2015 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
from .gridding_functions import * # noqa: F403
from .points import * # noqa: F403
from .triangles import * # noqa: F403
from .polygons import * # noqa: F403
from .interpolation import * # noqa: F403
__all__ = gridding_functions.__all__[:] # pylint: disable=undefined-variable
__all__.extend(interpolation.__all__) # pylint: disable=undefined-variable
MNT: Remove some imported modules from gridding
We never intended these to be part of the supported API. The fact that
these were available from metpy.gridding was revealed by the new
autosummary docs.
|
# Copyright (c) 2008-2015 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
from .gridding_functions import * # noqa: F403
from .interpolation import * # noqa: F403
__all__ = gridding_functions.__all__[:] # pylint: disable=undefined-variable
__all__.extend(interpolation.__all__) # pylint: disable=undefined-variable
|
<commit_before># Copyright (c) 2008-2015 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
from .gridding_functions import * # noqa: F403
from .points import * # noqa: F403
from .triangles import * # noqa: F403
from .polygons import * # noqa: F403
from .interpolation import * # noqa: F403
__all__ = gridding_functions.__all__[:] # pylint: disable=undefined-variable
__all__.extend(interpolation.__all__) # pylint: disable=undefined-variable
<commit_msg>MNT: Remove some imported modules from gridding
We never intended these to be part of the supported API. The fact that
these were available from metpy.gridding was revealed by the new
autosummary docs.<commit_after>
|
# Copyright (c) 2008-2015 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
from .gridding_functions import * # noqa: F403
from .interpolation import * # noqa: F403
__all__ = gridding_functions.__all__[:] # pylint: disable=undefined-variable
__all__.extend(interpolation.__all__) # pylint: disable=undefined-variable
|
# Copyright (c) 2008-2015 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
from .gridding_functions import * # noqa: F403
from .points import * # noqa: F403
from .triangles import * # noqa: F403
from .polygons import * # noqa: F403
from .interpolation import * # noqa: F403
__all__ = gridding_functions.__all__[:] # pylint: disable=undefined-variable
__all__.extend(interpolation.__all__) # pylint: disable=undefined-variable
MNT: Remove some imported modules from gridding
We never intended these to be part of the supported API. The fact that
these were available from metpy.gridding was revealed by the new
autosummary docs.# Copyright (c) 2008-2015 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
from .gridding_functions import * # noqa: F403
from .interpolation import * # noqa: F403
__all__ = gridding_functions.__all__[:] # pylint: disable=undefined-variable
__all__.extend(interpolation.__all__) # pylint: disable=undefined-variable
|
<commit_before># Copyright (c) 2008-2015 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
from .gridding_functions import * # noqa: F403
from .points import * # noqa: F403
from .triangles import * # noqa: F403
from .polygons import * # noqa: F403
from .interpolation import * # noqa: F403
__all__ = gridding_functions.__all__[:] # pylint: disable=undefined-variable
__all__.extend(interpolation.__all__) # pylint: disable=undefined-variable
<commit_msg>MNT: Remove some imported modules from gridding
We never intended these to be part of the supported API. The fact that
these were available from metpy.gridding was revealed by the new
autosummary docs.<commit_after># Copyright (c) 2008-2015 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
from .gridding_functions import * # noqa: F403
from .interpolation import * # noqa: F403
__all__ = gridding_functions.__all__[:] # pylint: disable=undefined-variable
__all__.extend(interpolation.__all__) # pylint: disable=undefined-variable
|
62d22972e3440092d479727b6120789d4724c15e
|
examples/redirects.py
|
examples/redirects.py
|
"""This example demonstrates how to perform different kinds of redirects using hug"""
import hug
@hug.get()
def sum_two_numbers(number_1: int, number_2: int):
"""I'll be redirecting to this using a variety of approaches below"""
return number_1 + number_2
@hug.post()
def internal_redirection_automatic(number_1: int, number_2: int):
"""This will redirect internally to the sum_two_numbers handler
passing along all passed in parameters.
Redirect happens within internally within hug, fully transparent to clients.
"""
print("Internal Redirection Automatic {}, {}".format(number_1, number_2))
return sum_two_numbers
@hug.post()
def internal_redirection_manual(number: int):
"""Instead of normal redirecting: You can manually call other handlers, with computed parameters
and return their results
"""
print("Internal Redirection Manual {}".format(number))
return sum_two_numbers(number, number)
@hug.post()
def redirect(redirect_type: hug.types.one_of((None, "permanent", "found", "see_other")) = None):
"""Hug also fully supports classical HTTP redirects,
providing built in convenience functions for the most common types.
"""
print("HTTP Redirect {}".format(redirect_type))
if not redirect_type:
hug.redirect.to("/sum_two_numbers")
else:
getattr(hug.redirect, redirect_type)("/sum_two_numbers")
|
"""This example demonstrates how to perform different kinds of redirects using hug"""
import hug
@hug.get()
def sum_two_numbers(number_1: int, number_2: int):
"""I'll be redirecting to this using a variety of approaches below"""
return number_1 + number_2
@hug.post()
def internal_redirection_automatic(number_1: int, number_2: int):
"""This will redirect internally to the sum_two_numbers handler
passing along all passed in parameters.
This kind of redirect happens internally within hug, fully transparent to clients.
"""
print("Internal Redirection Automatic {}, {}".format(number_1, number_2))
return sum_two_numbers
@hug.post()
def internal_redirection_manual(number: int):
"""Instead of normal redirecting: You can manually call other handlers, with computed parameters
and return their results
"""
print("Internal Redirection Manual {}".format(number))
return sum_two_numbers(number, number)
@hug.post()
def redirect(redirect_type: hug.types.one_of((None, "permanent", "found", "see_other")) = None):
"""Hug also fully supports classical HTTP redirects,
providing built in convenience functions for the most common types.
"""
print("HTTP Redirect {}".format(redirect_type))
if not redirect_type:
hug.redirect.to("/sum_two_numbers")
else:
getattr(hug.redirect, redirect_type)("/sum_two_numbers")
|
Fix grammer within doc string example
|
Fix grammer within doc string example
|
Python
|
mit
|
timothycrosley/hug,timothycrosley/hug,timothycrosley/hug
|
"""This example demonstrates how to perform different kinds of redirects using hug"""
import hug
@hug.get()
def sum_two_numbers(number_1: int, number_2: int):
"""I'll be redirecting to this using a variety of approaches below"""
return number_1 + number_2
@hug.post()
def internal_redirection_automatic(number_1: int, number_2: int):
"""This will redirect internally to the sum_two_numbers handler
passing along all passed in parameters.
Redirect happens within internally within hug, fully transparent to clients.
"""
print("Internal Redirection Automatic {}, {}".format(number_1, number_2))
return sum_two_numbers
@hug.post()
def internal_redirection_manual(number: int):
"""Instead of normal redirecting: You can manually call other handlers, with computed parameters
and return their results
"""
print("Internal Redirection Manual {}".format(number))
return sum_two_numbers(number, number)
@hug.post()
def redirect(redirect_type: hug.types.one_of((None, "permanent", "found", "see_other")) = None):
"""Hug also fully supports classical HTTP redirects,
providing built in convenience functions for the most common types.
"""
print("HTTP Redirect {}".format(redirect_type))
if not redirect_type:
hug.redirect.to("/sum_two_numbers")
else:
getattr(hug.redirect, redirect_type)("/sum_two_numbers")
Fix grammer within doc string example
|
"""This example demonstrates how to perform different kinds of redirects using hug"""
import hug
@hug.get()
def sum_two_numbers(number_1: int, number_2: int):
"""I'll be redirecting to this using a variety of approaches below"""
return number_1 + number_2
@hug.post()
def internal_redirection_automatic(number_1: int, number_2: int):
"""This will redirect internally to the sum_two_numbers handler
passing along all passed in parameters.
This kind of redirect happens internally within hug, fully transparent to clients.
"""
print("Internal Redirection Automatic {}, {}".format(number_1, number_2))
return sum_two_numbers
@hug.post()
def internal_redirection_manual(number: int):
"""Instead of normal redirecting: You can manually call other handlers, with computed parameters
and return their results
"""
print("Internal Redirection Manual {}".format(number))
return sum_two_numbers(number, number)
@hug.post()
def redirect(redirect_type: hug.types.one_of((None, "permanent", "found", "see_other")) = None):
"""Hug also fully supports classical HTTP redirects,
providing built in convenience functions for the most common types.
"""
print("HTTP Redirect {}".format(redirect_type))
if not redirect_type:
hug.redirect.to("/sum_two_numbers")
else:
getattr(hug.redirect, redirect_type)("/sum_two_numbers")
|
<commit_before>"""This example demonstrates how to perform different kinds of redirects using hug"""
import hug
@hug.get()
def sum_two_numbers(number_1: int, number_2: int):
"""I'll be redirecting to this using a variety of approaches below"""
return number_1 + number_2
@hug.post()
def internal_redirection_automatic(number_1: int, number_2: int):
"""This will redirect internally to the sum_two_numbers handler
passing along all passed in parameters.
Redirect happens within internally within hug, fully transparent to clients.
"""
print("Internal Redirection Automatic {}, {}".format(number_1, number_2))
return sum_two_numbers
@hug.post()
def internal_redirection_manual(number: int):
"""Instead of normal redirecting: You can manually call other handlers, with computed parameters
and return their results
"""
print("Internal Redirection Manual {}".format(number))
return sum_two_numbers(number, number)
@hug.post()
def redirect(redirect_type: hug.types.one_of((None, "permanent", "found", "see_other")) = None):
"""Hug also fully supports classical HTTP redirects,
providing built in convenience functions for the most common types.
"""
print("HTTP Redirect {}".format(redirect_type))
if not redirect_type:
hug.redirect.to("/sum_two_numbers")
else:
getattr(hug.redirect, redirect_type)("/sum_two_numbers")
<commit_msg>Fix grammer within doc string example<commit_after>
|
"""This example demonstrates how to perform different kinds of redirects using hug"""
import hug
@hug.get()
def sum_two_numbers(number_1: int, number_2: int):
"""I'll be redirecting to this using a variety of approaches below"""
return number_1 + number_2
@hug.post()
def internal_redirection_automatic(number_1: int, number_2: int):
"""This will redirect internally to the sum_two_numbers handler
passing along all passed in parameters.
This kind of redirect happens internally within hug, fully transparent to clients.
"""
print("Internal Redirection Automatic {}, {}".format(number_1, number_2))
return sum_two_numbers
@hug.post()
def internal_redirection_manual(number: int):
"""Instead of normal redirecting: You can manually call other handlers, with computed parameters
and return their results
"""
print("Internal Redirection Manual {}".format(number))
return sum_two_numbers(number, number)
@hug.post()
def redirect(redirect_type: hug.types.one_of((None, "permanent", "found", "see_other")) = None):
"""Hug also fully supports classical HTTP redirects,
providing built in convenience functions for the most common types.
"""
print("HTTP Redirect {}".format(redirect_type))
if not redirect_type:
hug.redirect.to("/sum_two_numbers")
else:
getattr(hug.redirect, redirect_type)("/sum_two_numbers")
|
"""This example demonstrates how to perform different kinds of redirects using hug"""
import hug
@hug.get()
def sum_two_numbers(number_1: int, number_2: int):
"""I'll be redirecting to this using a variety of approaches below"""
return number_1 + number_2
@hug.post()
def internal_redirection_automatic(number_1: int, number_2: int):
"""This will redirect internally to the sum_two_numbers handler
passing along all passed in parameters.
Redirect happens within internally within hug, fully transparent to clients.
"""
print("Internal Redirection Automatic {}, {}".format(number_1, number_2))
return sum_two_numbers
@hug.post()
def internal_redirection_manual(number: int):
"""Instead of normal redirecting: You can manually call other handlers, with computed parameters
and return their results
"""
print("Internal Redirection Manual {}".format(number))
return sum_two_numbers(number, number)
@hug.post()
def redirect(redirect_type: hug.types.one_of((None, "permanent", "found", "see_other")) = None):
"""Hug also fully supports classical HTTP redirects,
providing built in convenience functions for the most common types.
"""
print("HTTP Redirect {}".format(redirect_type))
if not redirect_type:
hug.redirect.to("/sum_two_numbers")
else:
getattr(hug.redirect, redirect_type)("/sum_two_numbers")
Fix grammer within doc string example"""This example demonstrates how to perform different kinds of redirects using hug"""
import hug
@hug.get()
def sum_two_numbers(number_1: int, number_2: int):
"""I'll be redirecting to this using a variety of approaches below"""
return number_1 + number_2
@hug.post()
def internal_redirection_automatic(number_1: int, number_2: int):
"""This will redirect internally to the sum_two_numbers handler
passing along all passed in parameters.
This kind of redirect happens internally within hug, fully transparent to clients.
"""
print("Internal Redirection Automatic {}, {}".format(number_1, number_2))
return sum_two_numbers
@hug.post()
def internal_redirection_manual(number: int):
"""Instead of normal redirecting: You can manually call other handlers, with computed parameters
and return their results
"""
print("Internal Redirection Manual {}".format(number))
return sum_two_numbers(number, number)
@hug.post()
def redirect(redirect_type: hug.types.one_of((None, "permanent", "found", "see_other")) = None):
"""Hug also fully supports classical HTTP redirects,
providing built in convenience functions for the most common types.
"""
print("HTTP Redirect {}".format(redirect_type))
if not redirect_type:
hug.redirect.to("/sum_two_numbers")
else:
getattr(hug.redirect, redirect_type)("/sum_two_numbers")
|
<commit_before>"""This example demonstrates how to perform different kinds of redirects using hug"""
import hug
@hug.get()
def sum_two_numbers(number_1: int, number_2: int):
"""I'll be redirecting to this using a variety of approaches below"""
return number_1 + number_2
@hug.post()
def internal_redirection_automatic(number_1: int, number_2: int):
"""This will redirect internally to the sum_two_numbers handler
passing along all passed in parameters.
Redirect happens within internally within hug, fully transparent to clients.
"""
print("Internal Redirection Automatic {}, {}".format(number_1, number_2))
return sum_two_numbers
@hug.post()
def internal_redirection_manual(number: int):
"""Instead of normal redirecting: You can manually call other handlers, with computed parameters
and return their results
"""
print("Internal Redirection Manual {}".format(number))
return sum_two_numbers(number, number)
@hug.post()
def redirect(redirect_type: hug.types.one_of((None, "permanent", "found", "see_other")) = None):
"""Hug also fully supports classical HTTP redirects,
providing built in convenience functions for the most common types.
"""
print("HTTP Redirect {}".format(redirect_type))
if not redirect_type:
hug.redirect.to("/sum_two_numbers")
else:
getattr(hug.redirect, redirect_type)("/sum_two_numbers")
<commit_msg>Fix grammer within doc string example<commit_after>"""This example demonstrates how to perform different kinds of redirects using hug"""
import hug
@hug.get()
def sum_two_numbers(number_1: int, number_2: int):
"""I'll be redirecting to this using a variety of approaches below"""
return number_1 + number_2
@hug.post()
def internal_redirection_automatic(number_1: int, number_2: int):
"""This will redirect internally to the sum_two_numbers handler
passing along all passed in parameters.
This kind of redirect happens internally within hug, fully transparent to clients.
"""
print("Internal Redirection Automatic {}, {}".format(number_1, number_2))
return sum_two_numbers
@hug.post()
def internal_redirection_manual(number: int):
"""Instead of normal redirecting: You can manually call other handlers, with computed parameters
and return their results
"""
print("Internal Redirection Manual {}".format(number))
return sum_two_numbers(number, number)
@hug.post()
def redirect(redirect_type: hug.types.one_of((None, "permanent", "found", "see_other")) = None):
"""Hug also fully supports classical HTTP redirects,
providing built in convenience functions for the most common types.
"""
print("HTTP Redirect {}".format(redirect_type))
if not redirect_type:
hug.redirect.to("/sum_two_numbers")
else:
getattr(hug.redirect, redirect_type)("/sum_two_numbers")
|
16aa9d35715e32e8455356f6c22e00d07aeefa90
|
jqsh/__main__.py
|
jqsh/__main__.py
|
#!/usr/bin/env python3
import sys
import jqsh.parser
import json
while True: # a simple repl
try:
for value in jqsh.parser.parse(input('jqsh> ')).start():
json.dump(value, sys.stdout, sort_keys=True, indent=4, separators=(',', ': '))
print() # add a newline because json.dump doesn't end its values with newlines
except EOFError:
print('^D')
break
except KeyboardInterrupt:
print() # add a newline after the Python-provided '^C'
continue
except SyntaxError as e:
print('jqsh: syntax error: ' + str(e))
|
#!/usr/bin/env python3
import sys
import jqsh.parser
import json
while True: # a simple repl
try:
for value in jqsh.parser.parse(input('jqsh> ')).start():
json.dump(value, sys.stdout, sort_keys=True, indent=2, separators=(',', ': '))
print() # add a newline because json.dump doesn't end its values with newlines
except EOFError:
print('^D')
break
except KeyboardInterrupt:
print() # add a newline after the Python-provided '^C'
continue
except SyntaxError as e:
print('jqsh: syntax error: ' + str(e))
|
Decrease indentation of JSON output
|
Decrease indentation of JSON output
|
Python
|
mit
|
jq-shell/python-jqsh
|
#!/usr/bin/env python3
import sys
import jqsh.parser
import json
while True: # a simple repl
try:
for value in jqsh.parser.parse(input('jqsh> ')).start():
json.dump(value, sys.stdout, sort_keys=True, indent=4, separators=(',', ': '))
print() # add a newline because json.dump doesn't end its values with newlines
except EOFError:
print('^D')
break
except KeyboardInterrupt:
print() # add a newline after the Python-provided '^C'
continue
except SyntaxError as e:
print('jqsh: syntax error: ' + str(e))
Decrease indentation of JSON output
|
#!/usr/bin/env python3
import sys
import jqsh.parser
import json
while True: # a simple repl
try:
for value in jqsh.parser.parse(input('jqsh> ')).start():
json.dump(value, sys.stdout, sort_keys=True, indent=2, separators=(',', ': '))
print() # add a newline because json.dump doesn't end its values with newlines
except EOFError:
print('^D')
break
except KeyboardInterrupt:
print() # add a newline after the Python-provided '^C'
continue
except SyntaxError as e:
print('jqsh: syntax error: ' + str(e))
|
<commit_before>#!/usr/bin/env python3
import sys
import jqsh.parser
import json
while True: # a simple repl
try:
for value in jqsh.parser.parse(input('jqsh> ')).start():
json.dump(value, sys.stdout, sort_keys=True, indent=4, separators=(',', ': '))
print() # add a newline because json.dump doesn't end its values with newlines
except EOFError:
print('^D')
break
except KeyboardInterrupt:
print() # add a newline after the Python-provided '^C'
continue
except SyntaxError as e:
print('jqsh: syntax error: ' + str(e))
<commit_msg>Decrease indentation of JSON output<commit_after>
|
#!/usr/bin/env python3
import sys
import jqsh.parser
import json
while True: # a simple repl
try:
for value in jqsh.parser.parse(input('jqsh> ')).start():
json.dump(value, sys.stdout, sort_keys=True, indent=2, separators=(',', ': '))
print() # add a newline because json.dump doesn't end its values with newlines
except EOFError:
print('^D')
break
except KeyboardInterrupt:
print() # add a newline after the Python-provided '^C'
continue
except SyntaxError as e:
print('jqsh: syntax error: ' + str(e))
|
#!/usr/bin/env python3
import sys
import jqsh.parser
import json
while True: # a simple repl
try:
for value in jqsh.parser.parse(input('jqsh> ')).start():
json.dump(value, sys.stdout, sort_keys=True, indent=4, separators=(',', ': '))
print() # add a newline because json.dump doesn't end its values with newlines
except EOFError:
print('^D')
break
except KeyboardInterrupt:
print() # add a newline after the Python-provided '^C'
continue
except SyntaxError as e:
print('jqsh: syntax error: ' + str(e))
Decrease indentation of JSON output#!/usr/bin/env python3
import sys
import jqsh.parser
import json
while True: # a simple repl
try:
for value in jqsh.parser.parse(input('jqsh> ')).start():
json.dump(value, sys.stdout, sort_keys=True, indent=2, separators=(',', ': '))
print() # add a newline because json.dump doesn't end its values with newlines
except EOFError:
print('^D')
break
except KeyboardInterrupt:
print() # add a newline after the Python-provided '^C'
continue
except SyntaxError as e:
print('jqsh: syntax error: ' + str(e))
|
<commit_before>#!/usr/bin/env python3
import sys
import jqsh.parser
import json
while True: # a simple repl
try:
for value in jqsh.parser.parse(input('jqsh> ')).start():
json.dump(value, sys.stdout, sort_keys=True, indent=4, separators=(',', ': '))
print() # add a newline because json.dump doesn't end its values with newlines
except EOFError:
print('^D')
break
except KeyboardInterrupt:
print() # add a newline after the Python-provided '^C'
continue
except SyntaxError as e:
print('jqsh: syntax error: ' + str(e))
<commit_msg>Decrease indentation of JSON output<commit_after>#!/usr/bin/env python3
import sys
import jqsh.parser
import json
while True: # a simple repl
try:
for value in jqsh.parser.parse(input('jqsh> ')).start():
json.dump(value, sys.stdout, sort_keys=True, indent=2, separators=(',', ': '))
print() # add a newline because json.dump doesn't end its values with newlines
except EOFError:
print('^D')
break
except KeyboardInterrupt:
print() # add a newline after the Python-provided '^C'
continue
except SyntaxError as e:
print('jqsh: syntax error: ' + str(e))
|
373297c6d7059344be67b44c7197998954db89b1
|
inboxen/app/handlers/in.py
|
inboxen/app/handlers/in.py
|
import logging
from lamson.routing import route, route_like, stateless
from config.settings import queue
from lamson import view
@route("(address)@(host)", address=".+")
@stateless
@nolocking
def START(message, address=None, host=None):
queue.push(message)
|
import logging
from lamson.routing import route, stateless, nolocking
from config.settings import accepted_queue
from lamson import view
@route("(address)@(host)", address=".+")
@stateless
@nolocking
def START(message, address=None, host=None):
accepted_queue.push(message)
|
Make the IN service actually deliver mail to the accepted queue
|
Make the IN service actually deliver mail to the accepted queue
|
Python
|
agpl-3.0
|
Inboxen/Inboxen,Inboxen/router,Inboxen/Inboxen,Inboxen/Inboxen,Inboxen/Inboxen
|
import logging
from lamson.routing import route, route_like, stateless
from config.settings import queue
from lamson import view
@route("(address)@(host)", address=".+")
@stateless
@nolocking
def START(message, address=None, host=None):
queue.push(message)
Make the IN service actually deliver mail to the accepted queue
|
import logging
from lamson.routing import route, stateless, nolocking
from config.settings import accepted_queue
from lamson import view
@route("(address)@(host)", address=".+")
@stateless
@nolocking
def START(message, address=None, host=None):
accepted_queue.push(message)
|
<commit_before>import logging
from lamson.routing import route, route_like, stateless
from config.settings import queue
from lamson import view
@route("(address)@(host)", address=".+")
@stateless
@nolocking
def START(message, address=None, host=None):
queue.push(message)
<commit_msg>Make the IN service actually deliver mail to the accepted queue<commit_after>
|
import logging
from lamson.routing import route, stateless, nolocking
from config.settings import accepted_queue
from lamson import view
@route("(address)@(host)", address=".+")
@stateless
@nolocking
def START(message, address=None, host=None):
accepted_queue.push(message)
|
import logging
from lamson.routing import route, route_like, stateless
from config.settings import queue
from lamson import view
@route("(address)@(host)", address=".+")
@stateless
@nolocking
def START(message, address=None, host=None):
queue.push(message)
Make the IN service actually deliver mail to the accepted queueimport logging
from lamson.routing import route, stateless, nolocking
from config.settings import accepted_queue
from lamson import view
@route("(address)@(host)", address=".+")
@stateless
@nolocking
def START(message, address=None, host=None):
accepted_queue.push(message)
|
<commit_before>import logging
from lamson.routing import route, route_like, stateless
from config.settings import queue
from lamson import view
@route("(address)@(host)", address=".+")
@stateless
@nolocking
def START(message, address=None, host=None):
queue.push(message)
<commit_msg>Make the IN service actually deliver mail to the accepted queue<commit_after>import logging
from lamson.routing import route, stateless, nolocking
from config.settings import accepted_queue
from lamson import view
@route("(address)@(host)", address=".+")
@stateless
@nolocking
def START(message, address=None, host=None):
accepted_queue.push(message)
|
6028b113ed37489d51a68dc5f1ae6ec4c9a14540
|
jsk_apc2016_common/node_scripts/visualize_pick_json.py
|
jsk_apc2016_common/node_scripts/visualize_pick_json.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import cv_bridge
import rospy
from sensor_msgs.msg import Image
import jsk_apc2016_common
def publish_cb(event):
imgmsg.header.stamp = rospy.Time.now()
pub.publish(imgmsg)
if __name__ == '__main__':
rospy.init_node('visualize_pick_json')
pub = rospy.Publisher('~output', Image, queue_size=10)
parser = argparse.ArgumentParser()
parser.add_argument('json',
help='JSON file with bin_contents and work_order')
args = parser.parse_args(rospy.myargv()[1:])
json = args.json
img = jsk_apc2016_common.visualize_pick_json(json)
br = cv_bridge.CvBridge()
imgmsg = br.cv2_to_imgmsg(img, encoding='bgr8')
timer = rospy.Timer(rospy.Duration(0.1), publish_cb)
rospy.spin()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import matplotlib.pyplot as plt
import cv_bridge
import rospy
from sensor_msgs.msg import Image
import jsk_apc2016_common
def visualize_cb(event):
if pub.get_num_connections() > 0:
imgmsg.header.stamp = rospy.Time.now()
pub.publish(imgmsg)
if display:
global displayed_img
img_rgb = img[:, :, ::-1]
plt.axis('off')
plt.tight_layout()
if displayed_img and displayed_img._imcache is None:
plt.close()
if displayed_img is None:
displayed_img = plt.imshow(img_rgb)
else:
displayed_img.set_data(img_rgb)
plt.pause(0.01)
if __name__ == '__main__':
rospy.init_node('visualize_pick_json')
pub = rospy.Publisher('~output', Image, queue_size=10)
parser = argparse.ArgumentParser()
parser.add_argument('json',
help='JSON file with bin_contents and work_order')
parser.add_argument('-d', '--display', action='store_true',
help='Display with a window')
args = parser.parse_args(rospy.myargv()[1:])
json = args.json
display = args.display
displayed_img = None
img = jsk_apc2016_common.visualize_pick_json(json)
br = cv_bridge.CvBridge()
imgmsg = br.cv2_to_imgmsg(img, encoding='bgr8')
timer = rospy.Timer(rospy.Duration(0.1), visualize_cb)
rospy.spin()
|
Add mode to display json with --display
|
Add mode to display json with --display
|
Python
|
bsd-3-clause
|
pazeshun/jsk_apc,pazeshun/jsk_apc,pazeshun/jsk_apc,pazeshun/jsk_apc,pazeshun/jsk_apc
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import cv_bridge
import rospy
from sensor_msgs.msg import Image
import jsk_apc2016_common
def publish_cb(event):
imgmsg.header.stamp = rospy.Time.now()
pub.publish(imgmsg)
if __name__ == '__main__':
rospy.init_node('visualize_pick_json')
pub = rospy.Publisher('~output', Image, queue_size=10)
parser = argparse.ArgumentParser()
parser.add_argument('json',
help='JSON file with bin_contents and work_order')
args = parser.parse_args(rospy.myargv()[1:])
json = args.json
img = jsk_apc2016_common.visualize_pick_json(json)
br = cv_bridge.CvBridge()
imgmsg = br.cv2_to_imgmsg(img, encoding='bgr8')
timer = rospy.Timer(rospy.Duration(0.1), publish_cb)
rospy.spin()
Add mode to display json with --display
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import matplotlib.pyplot as plt
import cv_bridge
import rospy
from sensor_msgs.msg import Image
import jsk_apc2016_common
def visualize_cb(event):
if pub.get_num_connections() > 0:
imgmsg.header.stamp = rospy.Time.now()
pub.publish(imgmsg)
if display:
global displayed_img
img_rgb = img[:, :, ::-1]
plt.axis('off')
plt.tight_layout()
if displayed_img and displayed_img._imcache is None:
plt.close()
if displayed_img is None:
displayed_img = plt.imshow(img_rgb)
else:
displayed_img.set_data(img_rgb)
plt.pause(0.01)
if __name__ == '__main__':
rospy.init_node('visualize_pick_json')
pub = rospy.Publisher('~output', Image, queue_size=10)
parser = argparse.ArgumentParser()
parser.add_argument('json',
help='JSON file with bin_contents and work_order')
parser.add_argument('-d', '--display', action='store_true',
help='Display with a window')
args = parser.parse_args(rospy.myargv()[1:])
json = args.json
display = args.display
displayed_img = None
img = jsk_apc2016_common.visualize_pick_json(json)
br = cv_bridge.CvBridge()
imgmsg = br.cv2_to_imgmsg(img, encoding='bgr8')
timer = rospy.Timer(rospy.Duration(0.1), visualize_cb)
rospy.spin()
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import cv_bridge
import rospy
from sensor_msgs.msg import Image
import jsk_apc2016_common
def publish_cb(event):
imgmsg.header.stamp = rospy.Time.now()
pub.publish(imgmsg)
if __name__ == '__main__':
rospy.init_node('visualize_pick_json')
pub = rospy.Publisher('~output', Image, queue_size=10)
parser = argparse.ArgumentParser()
parser.add_argument('json',
help='JSON file with bin_contents and work_order')
args = parser.parse_args(rospy.myargv()[1:])
json = args.json
img = jsk_apc2016_common.visualize_pick_json(json)
br = cv_bridge.CvBridge()
imgmsg = br.cv2_to_imgmsg(img, encoding='bgr8')
timer = rospy.Timer(rospy.Duration(0.1), publish_cb)
rospy.spin()
<commit_msg>Add mode to display json with --display<commit_after>
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import matplotlib.pyplot as plt
import cv_bridge
import rospy
from sensor_msgs.msg import Image
import jsk_apc2016_common
def visualize_cb(event):
if pub.get_num_connections() > 0:
imgmsg.header.stamp = rospy.Time.now()
pub.publish(imgmsg)
if display:
global displayed_img
img_rgb = img[:, :, ::-1]
plt.axis('off')
plt.tight_layout()
if displayed_img and displayed_img._imcache is None:
plt.close()
if displayed_img is None:
displayed_img = plt.imshow(img_rgb)
else:
displayed_img.set_data(img_rgb)
plt.pause(0.01)
if __name__ == '__main__':
rospy.init_node('visualize_pick_json')
pub = rospy.Publisher('~output', Image, queue_size=10)
parser = argparse.ArgumentParser()
parser.add_argument('json',
help='JSON file with bin_contents and work_order')
parser.add_argument('-d', '--display', action='store_true',
help='Display with a window')
args = parser.parse_args(rospy.myargv()[1:])
json = args.json
display = args.display
displayed_img = None
img = jsk_apc2016_common.visualize_pick_json(json)
br = cv_bridge.CvBridge()
imgmsg = br.cv2_to_imgmsg(img, encoding='bgr8')
timer = rospy.Timer(rospy.Duration(0.1), visualize_cb)
rospy.spin()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import cv_bridge
import rospy
from sensor_msgs.msg import Image
import jsk_apc2016_common
def publish_cb(event):
imgmsg.header.stamp = rospy.Time.now()
pub.publish(imgmsg)
if __name__ == '__main__':
rospy.init_node('visualize_pick_json')
pub = rospy.Publisher('~output', Image, queue_size=10)
parser = argparse.ArgumentParser()
parser.add_argument('json',
help='JSON file with bin_contents and work_order')
args = parser.parse_args(rospy.myargv()[1:])
json = args.json
img = jsk_apc2016_common.visualize_pick_json(json)
br = cv_bridge.CvBridge()
imgmsg = br.cv2_to_imgmsg(img, encoding='bgr8')
timer = rospy.Timer(rospy.Duration(0.1), publish_cb)
rospy.spin()
Add mode to display json with --display#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import matplotlib.pyplot as plt
import cv_bridge
import rospy
from sensor_msgs.msg import Image
import jsk_apc2016_common
def visualize_cb(event):
if pub.get_num_connections() > 0:
imgmsg.header.stamp = rospy.Time.now()
pub.publish(imgmsg)
if display:
global displayed_img
img_rgb = img[:, :, ::-1]
plt.axis('off')
plt.tight_layout()
if displayed_img and displayed_img._imcache is None:
plt.close()
if displayed_img is None:
displayed_img = plt.imshow(img_rgb)
else:
displayed_img.set_data(img_rgb)
plt.pause(0.01)
if __name__ == '__main__':
rospy.init_node('visualize_pick_json')
pub = rospy.Publisher('~output', Image, queue_size=10)
parser = argparse.ArgumentParser()
parser.add_argument('json',
help='JSON file with bin_contents and work_order')
parser.add_argument('-d', '--display', action='store_true',
help='Display with a window')
args = parser.parse_args(rospy.myargv()[1:])
json = args.json
display = args.display
displayed_img = None
img = jsk_apc2016_common.visualize_pick_json(json)
br = cv_bridge.CvBridge()
imgmsg = br.cv2_to_imgmsg(img, encoding='bgr8')
timer = rospy.Timer(rospy.Duration(0.1), visualize_cb)
rospy.spin()
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import cv_bridge
import rospy
from sensor_msgs.msg import Image
import jsk_apc2016_common
def publish_cb(event):
imgmsg.header.stamp = rospy.Time.now()
pub.publish(imgmsg)
if __name__ == '__main__':
rospy.init_node('visualize_pick_json')
pub = rospy.Publisher('~output', Image, queue_size=10)
parser = argparse.ArgumentParser()
parser.add_argument('json',
help='JSON file with bin_contents and work_order')
args = parser.parse_args(rospy.myargv()[1:])
json = args.json
img = jsk_apc2016_common.visualize_pick_json(json)
br = cv_bridge.CvBridge()
imgmsg = br.cv2_to_imgmsg(img, encoding='bgr8')
timer = rospy.Timer(rospy.Duration(0.1), publish_cb)
rospy.spin()
<commit_msg>Add mode to display json with --display<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import matplotlib.pyplot as plt
import cv_bridge
import rospy
from sensor_msgs.msg import Image
import jsk_apc2016_common
def visualize_cb(event):
if pub.get_num_connections() > 0:
imgmsg.header.stamp = rospy.Time.now()
pub.publish(imgmsg)
if display:
global displayed_img
img_rgb = img[:, :, ::-1]
plt.axis('off')
plt.tight_layout()
if displayed_img and displayed_img._imcache is None:
plt.close()
if displayed_img is None:
displayed_img = plt.imshow(img_rgb)
else:
displayed_img.set_data(img_rgb)
plt.pause(0.01)
if __name__ == '__main__':
rospy.init_node('visualize_pick_json')
pub = rospy.Publisher('~output', Image, queue_size=10)
parser = argparse.ArgumentParser()
parser.add_argument('json',
help='JSON file with bin_contents and work_order')
parser.add_argument('-d', '--display', action='store_true',
help='Display with a window')
args = parser.parse_args(rospy.myargv()[1:])
json = args.json
display = args.display
displayed_img = None
img = jsk_apc2016_common.visualize_pick_json(json)
br = cv_bridge.CvBridge()
imgmsg = br.cv2_to_imgmsg(img, encoding='bgr8')
timer = rospy.Timer(rospy.Duration(0.1), visualize_cb)
rospy.spin()
|
3d4a71f6bb84fe4e5c7f51b109a55a7560ebb673
|
test/test_absolute_import.py
|
test/test_absolute_import.py
|
import jedi
from jedi.parsing import Parser
from . import base
def test_explicit_absolute_imports():
"""
Detect modules with ``from __future__ import absolute_import``.
"""
parser = Parser("from __future__ import absolute_import", "test.py")
assert parser.scope.explicit_absolute_import
def test_no_explicit_absolute_imports():
"""
Detect modules without ``from __future__ import absolute_import``.
"""
parser = Parser("1", "test.py")
assert not parser.scope.explicit_absolute_import
def test_dont_break_imports_without_namespaces():
"""
The code checking for ``from __future__ import absolute_import`` shouldn't
assume that all imports have non-``None`` namespaces.
"""
src = "from __future__ import absolute_import\nimport xyzzy"
parser = Parser(src, "test.py")
assert parser.scope.explicit_absolute_import
@base.cwd_at("test/absolute_import")
def test_can_complete_when_shadowing():
filename = "unittest.py"
with open(filename) as f:
lines = f.readlines()
src = "".join(lines)
script = jedi.Script(src, len(lines), len(lines[1]), filename)
assert script.completions()
|
import jedi
from jedi.parsing import Parser
from . import base
def test_explicit_absolute_imports():
"""
Detect modules with ``from __future__ import absolute_import``.
"""
parser = Parser("from __future__ import absolute_import", "test.py")
assert parser.module.explicit_absolute_import
def test_no_explicit_absolute_imports():
"""
Detect modules without ``from __future__ import absolute_import``.
"""
parser = Parser("1", "test.py")
assert not parser.module.explicit_absolute_import
def test_dont_break_imports_without_namespaces():
"""
The code checking for ``from __future__ import absolute_import`` shouldn't
assume that all imports have non-``None`` namespaces.
"""
src = "from __future__ import absolute_import\nimport xyzzy"
parser = Parser(src, "test.py")
assert parser.module.explicit_absolute_import
@base.cwd_at("test/absolute_import")
def test_can_complete_when_shadowing():
filename = "unittest.py"
with open(filename) as f:
lines = f.readlines()
src = "".join(lines)
script = jedi.Script(src, len(lines), len(lines[1]), filename)
assert script.completions()
|
Use Parser.module instead of Parser.scope
|
Use Parser.module instead of Parser.scope
|
Python
|
mit
|
jonashaag/jedi,WoLpH/jedi,tjwei/jedi,mfussenegger/jedi,dwillmer/jedi,tjwei/jedi,mfussenegger/jedi,WoLpH/jedi,jonashaag/jedi,flurischt/jedi,flurischt/jedi,dwillmer/jedi
|
import jedi
from jedi.parsing import Parser
from . import base
def test_explicit_absolute_imports():
"""
Detect modules with ``from __future__ import absolute_import``.
"""
parser = Parser("from __future__ import absolute_import", "test.py")
assert parser.scope.explicit_absolute_import
def test_no_explicit_absolute_imports():
"""
Detect modules without ``from __future__ import absolute_import``.
"""
parser = Parser("1", "test.py")
assert not parser.scope.explicit_absolute_import
def test_dont_break_imports_without_namespaces():
"""
The code checking for ``from __future__ import absolute_import`` shouldn't
assume that all imports have non-``None`` namespaces.
"""
src = "from __future__ import absolute_import\nimport xyzzy"
parser = Parser(src, "test.py")
assert parser.scope.explicit_absolute_import
@base.cwd_at("test/absolute_import")
def test_can_complete_when_shadowing():
filename = "unittest.py"
with open(filename) as f:
lines = f.readlines()
src = "".join(lines)
script = jedi.Script(src, len(lines), len(lines[1]), filename)
assert script.completions()
Use Parser.module instead of Parser.scope
|
import jedi
from jedi.parsing import Parser
from . import base
def test_explicit_absolute_imports():
"""
Detect modules with ``from __future__ import absolute_import``.
"""
parser = Parser("from __future__ import absolute_import", "test.py")
assert parser.module.explicit_absolute_import
def test_no_explicit_absolute_imports():
"""
Detect modules without ``from __future__ import absolute_import``.
"""
parser = Parser("1", "test.py")
assert not parser.module.explicit_absolute_import
def test_dont_break_imports_without_namespaces():
"""
The code checking for ``from __future__ import absolute_import`` shouldn't
assume that all imports have non-``None`` namespaces.
"""
src = "from __future__ import absolute_import\nimport xyzzy"
parser = Parser(src, "test.py")
assert parser.module.explicit_absolute_import
@base.cwd_at("test/absolute_import")
def test_can_complete_when_shadowing():
filename = "unittest.py"
with open(filename) as f:
lines = f.readlines()
src = "".join(lines)
script = jedi.Script(src, len(lines), len(lines[1]), filename)
assert script.completions()
|
<commit_before>import jedi
from jedi.parsing import Parser
from . import base
def test_explicit_absolute_imports():
"""
Detect modules with ``from __future__ import absolute_import``.
"""
parser = Parser("from __future__ import absolute_import", "test.py")
assert parser.scope.explicit_absolute_import
def test_no_explicit_absolute_imports():
"""
Detect modules without ``from __future__ import absolute_import``.
"""
parser = Parser("1", "test.py")
assert not parser.scope.explicit_absolute_import
def test_dont_break_imports_without_namespaces():
"""
The code checking for ``from __future__ import absolute_import`` shouldn't
assume that all imports have non-``None`` namespaces.
"""
src = "from __future__ import absolute_import\nimport xyzzy"
parser = Parser(src, "test.py")
assert parser.scope.explicit_absolute_import
@base.cwd_at("test/absolute_import")
def test_can_complete_when_shadowing():
filename = "unittest.py"
with open(filename) as f:
lines = f.readlines()
src = "".join(lines)
script = jedi.Script(src, len(lines), len(lines[1]), filename)
assert script.completions()
<commit_msg>Use Parser.module instead of Parser.scope<commit_after>
|
import jedi
from jedi.parsing import Parser
from . import base
def test_explicit_absolute_imports():
"""
Detect modules with ``from __future__ import absolute_import``.
"""
parser = Parser("from __future__ import absolute_import", "test.py")
assert parser.module.explicit_absolute_import
def test_no_explicit_absolute_imports():
"""
Detect modules without ``from __future__ import absolute_import``.
"""
parser = Parser("1", "test.py")
assert not parser.module.explicit_absolute_import
def test_dont_break_imports_without_namespaces():
"""
The code checking for ``from __future__ import absolute_import`` shouldn't
assume that all imports have non-``None`` namespaces.
"""
src = "from __future__ import absolute_import\nimport xyzzy"
parser = Parser(src, "test.py")
assert parser.module.explicit_absolute_import
@base.cwd_at("test/absolute_import")
def test_can_complete_when_shadowing():
filename = "unittest.py"
with open(filename) as f:
lines = f.readlines()
src = "".join(lines)
script = jedi.Script(src, len(lines), len(lines[1]), filename)
assert script.completions()
|
import jedi
from jedi.parsing import Parser
from . import base
def test_explicit_absolute_imports():
"""
Detect modules with ``from __future__ import absolute_import``.
"""
parser = Parser("from __future__ import absolute_import", "test.py")
assert parser.scope.explicit_absolute_import
def test_no_explicit_absolute_imports():
"""
Detect modules without ``from __future__ import absolute_import``.
"""
parser = Parser("1", "test.py")
assert not parser.scope.explicit_absolute_import
def test_dont_break_imports_without_namespaces():
"""
The code checking for ``from __future__ import absolute_import`` shouldn't
assume that all imports have non-``None`` namespaces.
"""
src = "from __future__ import absolute_import\nimport xyzzy"
parser = Parser(src, "test.py")
assert parser.scope.explicit_absolute_import
@base.cwd_at("test/absolute_import")
def test_can_complete_when_shadowing():
filename = "unittest.py"
with open(filename) as f:
lines = f.readlines()
src = "".join(lines)
script = jedi.Script(src, len(lines), len(lines[1]), filename)
assert script.completions()
Use Parser.module instead of Parser.scopeimport jedi
from jedi.parsing import Parser
from . import base
def test_explicit_absolute_imports():
"""
Detect modules with ``from __future__ import absolute_import``.
"""
parser = Parser("from __future__ import absolute_import", "test.py")
assert parser.module.explicit_absolute_import
def test_no_explicit_absolute_imports():
"""
Detect modules without ``from __future__ import absolute_import``.
"""
parser = Parser("1", "test.py")
assert not parser.module.explicit_absolute_import
def test_dont_break_imports_without_namespaces():
"""
The code checking for ``from __future__ import absolute_import`` shouldn't
assume that all imports have non-``None`` namespaces.
"""
src = "from __future__ import absolute_import\nimport xyzzy"
parser = Parser(src, "test.py")
assert parser.module.explicit_absolute_import
@base.cwd_at("test/absolute_import")
def test_can_complete_when_shadowing():
filename = "unittest.py"
with open(filename) as f:
lines = f.readlines()
src = "".join(lines)
script = jedi.Script(src, len(lines), len(lines[1]), filename)
assert script.completions()
|
<commit_before>import jedi
from jedi.parsing import Parser
from . import base
def test_explicit_absolute_imports():
"""
Detect modules with ``from __future__ import absolute_import``.
"""
parser = Parser("from __future__ import absolute_import", "test.py")
assert parser.scope.explicit_absolute_import
def test_no_explicit_absolute_imports():
"""
Detect modules without ``from __future__ import absolute_import``.
"""
parser = Parser("1", "test.py")
assert not parser.scope.explicit_absolute_import
def test_dont_break_imports_without_namespaces():
"""
The code checking for ``from __future__ import absolute_import`` shouldn't
assume that all imports have non-``None`` namespaces.
"""
src = "from __future__ import absolute_import\nimport xyzzy"
parser = Parser(src, "test.py")
assert parser.scope.explicit_absolute_import
@base.cwd_at("test/absolute_import")
def test_can_complete_when_shadowing():
filename = "unittest.py"
with open(filename) as f:
lines = f.readlines()
src = "".join(lines)
script = jedi.Script(src, len(lines), len(lines[1]), filename)
assert script.completions()
<commit_msg>Use Parser.module instead of Parser.scope<commit_after>import jedi
from jedi.parsing import Parser
from . import base
def test_explicit_absolute_imports():
"""
Detect modules with ``from __future__ import absolute_import``.
"""
parser = Parser("from __future__ import absolute_import", "test.py")
assert parser.module.explicit_absolute_import
def test_no_explicit_absolute_imports():
"""
Detect modules without ``from __future__ import absolute_import``.
"""
parser = Parser("1", "test.py")
assert not parser.module.explicit_absolute_import
def test_dont_break_imports_without_namespaces():
"""
The code checking for ``from __future__ import absolute_import`` shouldn't
assume that all imports have non-``None`` namespaces.
"""
src = "from __future__ import absolute_import\nimport xyzzy"
parser = Parser(src, "test.py")
assert parser.module.explicit_absolute_import
@base.cwd_at("test/absolute_import")
def test_can_complete_when_shadowing():
filename = "unittest.py"
with open(filename) as f:
lines = f.readlines()
src = "".join(lines)
script = jedi.Script(src, len(lines), len(lines[1]), filename)
assert script.completions()
|
9968e526c00ee221940b30f435ecb866a4a1a608
|
tests/core/test_validator.py
|
tests/core/test_validator.py
|
import pytest
import asyncio
from rasa.core.validator import Validator
from tests.core.conftest import DEFAULT_DOMAIN_PATH, DEFAULT_STORIES_FILE, DEFAULT_NLU_DATA
from rasa.core.domain import Domain
from rasa.nlu.training_data import load_data, TrainingData
from rasa.core.training.dsl import StoryFileReader
@pytest.fixture
def validator():
domain = Domain.load(DEFAULT_DOMAIN_PATH)
stories = asyncio.run(
StoryFileReader.read_from_folder(DEFAULT_STORIES_FILE, domain)
)
intents = load_data(DEFAULT_NLU_DATA)
return Validator(domain=domain, intents=intents, stories=stories)
def test_validator_creation(validator):
assert isinstance(validator.domain, Domain)
assert isinstance(validator.intents, TrainingData)
assert isinstance(validator.stories, list)
def test_search(validator):
vec = ['a', 'b', 'c', 'd', 'e']
assert validator._search(vector=vec, searched_value='c')
def test_verify_intents(validator):
valid_intents = ['greet', 'goodbye', 'affirm']
validator.verify_intents()
assert validator.valid_intents == valid_intents
def test_verify_utters(validator):
valid_utterances = ['utter_greet', 'utter_goodbye', 'utter_default']
validator.verify_utterances()
assert validator.valid_utterances == valid_utterances
|
import pytest
import asyncio
from rasa.core.validator import Validator
from tests.core.conftest import (
DEFAULT_DOMAIN_PATH,
DEFAULT_STORIES_FILE,
DEFAULT_NLU_DATA,
)
from rasa.core.domain import Domain
from rasa.nlu.training_data import load_data, TrainingData
from rasa.core.training.dsl import StoryFileReader
@pytest.fixture
def validator():
domain = Domain.load(DEFAULT_DOMAIN_PATH)
stories = asyncio.run(
StoryFileReader.read_from_folder(DEFAULT_STORIES_FILE, domain)
)
intents = load_data(DEFAULT_NLU_DATA)
return Validator(domain=domain, intents=intents, stories=stories)
def test_validator_creation(validator):
assert isinstance(validator.domain, Domain)
assert isinstance(validator.intents, TrainingData)
assert isinstance(validator.stories, list)
def test_search(validator):
vec = ["a", "b", "c", "d", "e"]
assert validator._search(vector=vec, searched_value="c")
def test_verify_intents(validator):
valid_intents = ["greet", "goodbye", "affirm"]
validator.verify_intents()
assert validator.valid_intents == valid_intents
def test_verify_utters(validator):
valid_utterances = ["utter_greet", "utter_goodbye", "utter_default"]
validator.verify_utterances()
assert validator.valid_utterances == valid_utterances
|
Refactor validator tests with black
|
Refactor validator tests with black
Signed-off-by: Gabriela Barrozo Guedes <ef39217ba926e49eaea73efc4d3c11e5daab460c@gmail.com>
|
Python
|
apache-2.0
|
RasaHQ/rasa_nlu,RasaHQ/rasa_nlu,RasaHQ/rasa_nlu
|
import pytest
import asyncio
from rasa.core.validator import Validator
from tests.core.conftest import DEFAULT_DOMAIN_PATH, DEFAULT_STORIES_FILE, DEFAULT_NLU_DATA
from rasa.core.domain import Domain
from rasa.nlu.training_data import load_data, TrainingData
from rasa.core.training.dsl import StoryFileReader
@pytest.fixture
def validator():
domain = Domain.load(DEFAULT_DOMAIN_PATH)
stories = asyncio.run(
StoryFileReader.read_from_folder(DEFAULT_STORIES_FILE, domain)
)
intents = load_data(DEFAULT_NLU_DATA)
return Validator(domain=domain, intents=intents, stories=stories)
def test_validator_creation(validator):
assert isinstance(validator.domain, Domain)
assert isinstance(validator.intents, TrainingData)
assert isinstance(validator.stories, list)
def test_search(validator):
vec = ['a', 'b', 'c', 'd', 'e']
assert validator._search(vector=vec, searched_value='c')
def test_verify_intents(validator):
valid_intents = ['greet', 'goodbye', 'affirm']
validator.verify_intents()
assert validator.valid_intents == valid_intents
def test_verify_utters(validator):
valid_utterances = ['utter_greet', 'utter_goodbye', 'utter_default']
validator.verify_utterances()
assert validator.valid_utterances == valid_utterances
Refactor validator tests with black
Signed-off-by: Gabriela Barrozo Guedes <ef39217ba926e49eaea73efc4d3c11e5daab460c@gmail.com>
|
import pytest
import asyncio
from rasa.core.validator import Validator
from tests.core.conftest import (
DEFAULT_DOMAIN_PATH,
DEFAULT_STORIES_FILE,
DEFAULT_NLU_DATA,
)
from rasa.core.domain import Domain
from rasa.nlu.training_data import load_data, TrainingData
from rasa.core.training.dsl import StoryFileReader
@pytest.fixture
def validator():
domain = Domain.load(DEFAULT_DOMAIN_PATH)
stories = asyncio.run(
StoryFileReader.read_from_folder(DEFAULT_STORIES_FILE, domain)
)
intents = load_data(DEFAULT_NLU_DATA)
return Validator(domain=domain, intents=intents, stories=stories)
def test_validator_creation(validator):
assert isinstance(validator.domain, Domain)
assert isinstance(validator.intents, TrainingData)
assert isinstance(validator.stories, list)
def test_search(validator):
vec = ["a", "b", "c", "d", "e"]
assert validator._search(vector=vec, searched_value="c")
def test_verify_intents(validator):
valid_intents = ["greet", "goodbye", "affirm"]
validator.verify_intents()
assert validator.valid_intents == valid_intents
def test_verify_utters(validator):
valid_utterances = ["utter_greet", "utter_goodbye", "utter_default"]
validator.verify_utterances()
assert validator.valid_utterances == valid_utterances
|
<commit_before>import pytest
import asyncio
from rasa.core.validator import Validator
from tests.core.conftest import DEFAULT_DOMAIN_PATH, DEFAULT_STORIES_FILE, DEFAULT_NLU_DATA
from rasa.core.domain import Domain
from rasa.nlu.training_data import load_data, TrainingData
from rasa.core.training.dsl import StoryFileReader
@pytest.fixture
def validator():
domain = Domain.load(DEFAULT_DOMAIN_PATH)
stories = asyncio.run(
StoryFileReader.read_from_folder(DEFAULT_STORIES_FILE, domain)
)
intents = load_data(DEFAULT_NLU_DATA)
return Validator(domain=domain, intents=intents, stories=stories)
def test_validator_creation(validator):
assert isinstance(validator.domain, Domain)
assert isinstance(validator.intents, TrainingData)
assert isinstance(validator.stories, list)
def test_search(validator):
vec = ['a', 'b', 'c', 'd', 'e']
assert validator._search(vector=vec, searched_value='c')
def test_verify_intents(validator):
valid_intents = ['greet', 'goodbye', 'affirm']
validator.verify_intents()
assert validator.valid_intents == valid_intents
def test_verify_utters(validator):
valid_utterances = ['utter_greet', 'utter_goodbye', 'utter_default']
validator.verify_utterances()
assert validator.valid_utterances == valid_utterances
<commit_msg>Refactor validator tests with black
Signed-off-by: Gabriela Barrozo Guedes <ef39217ba926e49eaea73efc4d3c11e5daab460c@gmail.com><commit_after>
|
import pytest
import asyncio
from rasa.core.validator import Validator
from tests.core.conftest import (
DEFAULT_DOMAIN_PATH,
DEFAULT_STORIES_FILE,
DEFAULT_NLU_DATA,
)
from rasa.core.domain import Domain
from rasa.nlu.training_data import load_data, TrainingData
from rasa.core.training.dsl import StoryFileReader
@pytest.fixture
def validator():
domain = Domain.load(DEFAULT_DOMAIN_PATH)
stories = asyncio.run(
StoryFileReader.read_from_folder(DEFAULT_STORIES_FILE, domain)
)
intents = load_data(DEFAULT_NLU_DATA)
return Validator(domain=domain, intents=intents, stories=stories)
def test_validator_creation(validator):
assert isinstance(validator.domain, Domain)
assert isinstance(validator.intents, TrainingData)
assert isinstance(validator.stories, list)
def test_search(validator):
vec = ["a", "b", "c", "d", "e"]
assert validator._search(vector=vec, searched_value="c")
def test_verify_intents(validator):
valid_intents = ["greet", "goodbye", "affirm"]
validator.verify_intents()
assert validator.valid_intents == valid_intents
def test_verify_utters(validator):
valid_utterances = ["utter_greet", "utter_goodbye", "utter_default"]
validator.verify_utterances()
assert validator.valid_utterances == valid_utterances
|
import pytest
import asyncio
from rasa.core.validator import Validator
from tests.core.conftest import DEFAULT_DOMAIN_PATH, DEFAULT_STORIES_FILE, DEFAULT_NLU_DATA
from rasa.core.domain import Domain
from rasa.nlu.training_data import load_data, TrainingData
from rasa.core.training.dsl import StoryFileReader
@pytest.fixture
def validator():
domain = Domain.load(DEFAULT_DOMAIN_PATH)
stories = asyncio.run(
StoryFileReader.read_from_folder(DEFAULT_STORIES_FILE, domain)
)
intents = load_data(DEFAULT_NLU_DATA)
return Validator(domain=domain, intents=intents, stories=stories)
def test_validator_creation(validator):
assert isinstance(validator.domain, Domain)
assert isinstance(validator.intents, TrainingData)
assert isinstance(validator.stories, list)
def test_search(validator):
vec = ['a', 'b', 'c', 'd', 'e']
assert validator._search(vector=vec, searched_value='c')
def test_verify_intents(validator):
valid_intents = ['greet', 'goodbye', 'affirm']
validator.verify_intents()
assert validator.valid_intents == valid_intents
def test_verify_utters(validator):
valid_utterances = ['utter_greet', 'utter_goodbye', 'utter_default']
validator.verify_utterances()
assert validator.valid_utterances == valid_utterances
Refactor validator tests with black
Signed-off-by: Gabriela Barrozo Guedes <ef39217ba926e49eaea73efc4d3c11e5daab460c@gmail.com>import pytest
import asyncio
from rasa.core.validator import Validator
from tests.core.conftest import (
DEFAULT_DOMAIN_PATH,
DEFAULT_STORIES_FILE,
DEFAULT_NLU_DATA,
)
from rasa.core.domain import Domain
from rasa.nlu.training_data import load_data, TrainingData
from rasa.core.training.dsl import StoryFileReader
@pytest.fixture
def validator():
domain = Domain.load(DEFAULT_DOMAIN_PATH)
stories = asyncio.run(
StoryFileReader.read_from_folder(DEFAULT_STORIES_FILE, domain)
)
intents = load_data(DEFAULT_NLU_DATA)
return Validator(domain=domain, intents=intents, stories=stories)
def test_validator_creation(validator):
assert isinstance(validator.domain, Domain)
assert isinstance(validator.intents, TrainingData)
assert isinstance(validator.stories, list)
def test_search(validator):
vec = ["a", "b", "c", "d", "e"]
assert validator._search(vector=vec, searched_value="c")
def test_verify_intents(validator):
valid_intents = ["greet", "goodbye", "affirm"]
validator.verify_intents()
assert validator.valid_intents == valid_intents
def test_verify_utters(validator):
valid_utterances = ["utter_greet", "utter_goodbye", "utter_default"]
validator.verify_utterances()
assert validator.valid_utterances == valid_utterances
|
<commit_before>import pytest
import asyncio
from rasa.core.validator import Validator
from tests.core.conftest import DEFAULT_DOMAIN_PATH, DEFAULT_STORIES_FILE, DEFAULT_NLU_DATA
from rasa.core.domain import Domain
from rasa.nlu.training_data import load_data, TrainingData
from rasa.core.training.dsl import StoryFileReader
@pytest.fixture
def validator():
domain = Domain.load(DEFAULT_DOMAIN_PATH)
stories = asyncio.run(
StoryFileReader.read_from_folder(DEFAULT_STORIES_FILE, domain)
)
intents = load_data(DEFAULT_NLU_DATA)
return Validator(domain=domain, intents=intents, stories=stories)
def test_validator_creation(validator):
assert isinstance(validator.domain, Domain)
assert isinstance(validator.intents, TrainingData)
assert isinstance(validator.stories, list)
def test_search(validator):
vec = ['a', 'b', 'c', 'd', 'e']
assert validator._search(vector=vec, searched_value='c')
def test_verify_intents(validator):
valid_intents = ['greet', 'goodbye', 'affirm']
validator.verify_intents()
assert validator.valid_intents == valid_intents
def test_verify_utters(validator):
valid_utterances = ['utter_greet', 'utter_goodbye', 'utter_default']
validator.verify_utterances()
assert validator.valid_utterances == valid_utterances
<commit_msg>Refactor validator tests with black
Signed-off-by: Gabriela Barrozo Guedes <ef39217ba926e49eaea73efc4d3c11e5daab460c@gmail.com><commit_after>import pytest
import asyncio
from rasa.core.validator import Validator
from tests.core.conftest import (
DEFAULT_DOMAIN_PATH,
DEFAULT_STORIES_FILE,
DEFAULT_NLU_DATA,
)
from rasa.core.domain import Domain
from rasa.nlu.training_data import load_data, TrainingData
from rasa.core.training.dsl import StoryFileReader
@pytest.fixture
def validator():
domain = Domain.load(DEFAULT_DOMAIN_PATH)
stories = asyncio.run(
StoryFileReader.read_from_folder(DEFAULT_STORIES_FILE, domain)
)
intents = load_data(DEFAULT_NLU_DATA)
return Validator(domain=domain, intents=intents, stories=stories)
def test_validator_creation(validator):
assert isinstance(validator.domain, Domain)
assert isinstance(validator.intents, TrainingData)
assert isinstance(validator.stories, list)
def test_search(validator):
vec = ["a", "b", "c", "d", "e"]
assert validator._search(vector=vec, searched_value="c")
def test_verify_intents(validator):
valid_intents = ["greet", "goodbye", "affirm"]
validator.verify_intents()
assert validator.valid_intents == valid_intents
def test_verify_utters(validator):
valid_utterances = ["utter_greet", "utter_goodbye", "utter_default"]
validator.verify_utterances()
assert validator.valid_utterances == valid_utterances
|
37833caae3147f9c2f70b83f5b04becaa402a66e
|
httpDissec.py
|
httpDissec.py
|
# sudo apt-get install python-scapy
from scapy.all import *
# sudo pip install scapy_http
from scapy.layers import http
from scapy.layers.http import HTTPResponse
import sys
packets = rdpcap("task07_f1.pcap")
requests = {}
answers = {}
def has_http_header(packet):
return packet.haslayer(HTTPResponse)
for pkt in packets:
tcp = pkt['TCP']
# destination port must be 80
if tcp.dport == 80 and pkt.haslayer('HTTP'):
ip_id = pkt[IP].id
requests[ip_id] = pkt
for pkt in packets:
tcp = pkt['TCP']
# source port must be 80
if tcp.sport == 80 and pkt.haslayer('HTTP'):
ip_id = pkt['IP'].id
answers[ip_id] = pkt
print '=============== REQUESTS =================='
i = 0
for ip_id in requests:
print 'Packet: ', i, "\n"
i = i + 1
req = requests[ip_id]
req.show()
''' if req.haslayer('HTTP'):
# if 'HTTP Request' in req:
httpreq = req.getlayer('HTTP')
print '\o/\o/\o/\o/ HTTP REQUEST \o/\o/\o/\o/\o/\o/'
print httpreq
else:
print '/o\ /o\ /o\ NO HTTP REQUEST'
'''
print '=============== ANSWERS =================='
i = 0
for ip_id in answers:
print 'Packet: ', i, "\n"
i = i + 1
ans = answers[ip_id]
if has_http_header(ans):
print "HAS HEADER\n"
else:
print "NO HEADER\n"
ans.show()
|
# sudo apt-get install python-scapy
from scapy.all import *
# sudo pip install scapy_http
from scapy.layers import http
from scapy.layers.http import HTTPResponse
import sys
packets = rdpcap("task07_f1.pcap")
requests = []
answers = []
def has_http_header(packet):
return packet.haslayer(HTTPResponse)
for pkt in packets:
tcp = pkt['TCP']
# destination port must be 80
if tcp.dport == 80 and pkt.haslayer('HTTP'):
requests.append(pkt)
for pkt in packets:
tcp = pkt['TCP']
# source port must be 80
if tcp.sport == 80 and pkt.haslayer('HTTP'):
answers.append(pkt)
print '=============== REQUESTS =================='
i = 0
for req in requests:
print 'Packet: ', i, "\n"
i = i + 1
req.show()
print '=============== ANSWERS =================='
i = 0
for ans in answers:
print 'Packet: ', i, "\n"
i = i + 1
if has_http_header(ans):
print "HAS HEADER\n"
else:
print "NO HEADER\n"
ans.show()
|
Change from dic to list
|
Change from dic to list
|
Python
|
mit
|
alexst07/http_dissector
|
# sudo apt-get install python-scapy
from scapy.all import *
# sudo pip install scapy_http
from scapy.layers import http
from scapy.layers.http import HTTPResponse
import sys
packets = rdpcap("task07_f1.pcap")
requests = {}
answers = {}
def has_http_header(packet):
return packet.haslayer(HTTPResponse)
for pkt in packets:
tcp = pkt['TCP']
# destination port must be 80
if tcp.dport == 80 and pkt.haslayer('HTTP'):
ip_id = pkt[IP].id
requests[ip_id] = pkt
for pkt in packets:
tcp = pkt['TCP']
# source port must be 80
if tcp.sport == 80 and pkt.haslayer('HTTP'):
ip_id = pkt['IP'].id
answers[ip_id] = pkt
print '=============== REQUESTS =================='
i = 0
for ip_id in requests:
print 'Packet: ', i, "\n"
i = i + 1
req = requests[ip_id]
req.show()
''' if req.haslayer('HTTP'):
# if 'HTTP Request' in req:
httpreq = req.getlayer('HTTP')
print '\o/\o/\o/\o/ HTTP REQUEST \o/\o/\o/\o/\o/\o/'
print httpreq
else:
print '/o\ /o\ /o\ NO HTTP REQUEST'
'''
print '=============== ANSWERS =================='
i = 0
for ip_id in answers:
print 'Packet: ', i, "\n"
i = i + 1
ans = answers[ip_id]
if has_http_header(ans):
print "HAS HEADER\n"
else:
print "NO HEADER\n"
ans.show()
Change from dic to list
|
# sudo apt-get install python-scapy
from scapy.all import *
# sudo pip install scapy_http
from scapy.layers import http
from scapy.layers.http import HTTPResponse
import sys
packets = rdpcap("task07_f1.pcap")
requests = []
answers = []
def has_http_header(packet):
return packet.haslayer(HTTPResponse)
for pkt in packets:
tcp = pkt['TCP']
# destination port must be 80
if tcp.dport == 80 and pkt.haslayer('HTTP'):
requests.append(pkt)
for pkt in packets:
tcp = pkt['TCP']
# source port must be 80
if tcp.sport == 80 and pkt.haslayer('HTTP'):
answers.append(pkt)
print '=============== REQUESTS =================='
i = 0
for req in requests:
print 'Packet: ', i, "\n"
i = i + 1
req.show()
print '=============== ANSWERS =================='
i = 0
for ans in answers:
print 'Packet: ', i, "\n"
i = i + 1
if has_http_header(ans):
print "HAS HEADER\n"
else:
print "NO HEADER\n"
ans.show()
|
<commit_before># sudo apt-get install python-scapy
from scapy.all import *
# sudo pip install scapy_http
from scapy.layers import http
from scapy.layers.http import HTTPResponse
import sys
packets = rdpcap("task07_f1.pcap")
requests = {}
answers = {}
def has_http_header(packet):
return packet.haslayer(HTTPResponse)
for pkt in packets:
tcp = pkt['TCP']
# destination port must be 80
if tcp.dport == 80 and pkt.haslayer('HTTP'):
ip_id = pkt[IP].id
requests[ip_id] = pkt
for pkt in packets:
tcp = pkt['TCP']
# source port must be 80
if tcp.sport == 80 and pkt.haslayer('HTTP'):
ip_id = pkt['IP'].id
answers[ip_id] = pkt
print '=============== REQUESTS =================='
i = 0
for ip_id in requests:
print 'Packet: ', i, "\n"
i = i + 1
req = requests[ip_id]
req.show()
''' if req.haslayer('HTTP'):
# if 'HTTP Request' in req:
httpreq = req.getlayer('HTTP')
print '\o/\o/\o/\o/ HTTP REQUEST \o/\o/\o/\o/\o/\o/'
print httpreq
else:
print '/o\ /o\ /o\ NO HTTP REQUEST'
'''
print '=============== ANSWERS =================='
i = 0
for ip_id in answers:
print 'Packet: ', i, "\n"
i = i + 1
ans = answers[ip_id]
if has_http_header(ans):
print "HAS HEADER\n"
else:
print "NO HEADER\n"
ans.show()
<commit_msg>Change from dic to list<commit_after>
|
# sudo apt-get install python-scapy
from scapy.all import *
# sudo pip install scapy_http
from scapy.layers import http
from scapy.layers.http import HTTPResponse
import sys
packets = rdpcap("task07_f1.pcap")
requests = []
answers = []
def has_http_header(packet):
return packet.haslayer(HTTPResponse)
for pkt in packets:
tcp = pkt['TCP']
# destination port must be 80
if tcp.dport == 80 and pkt.haslayer('HTTP'):
requests.append(pkt)
for pkt in packets:
tcp = pkt['TCP']
# source port must be 80
if tcp.sport == 80 and pkt.haslayer('HTTP'):
answers.append(pkt)
print '=============== REQUESTS =================='
i = 0
for req in requests:
print 'Packet: ', i, "\n"
i = i + 1
req.show()
print '=============== ANSWERS =================='
i = 0
for ans in answers:
print 'Packet: ', i, "\n"
i = i + 1
if has_http_header(ans):
print "HAS HEADER\n"
else:
print "NO HEADER\n"
ans.show()
|
# sudo apt-get install python-scapy
from scapy.all import *
# sudo pip install scapy_http
from scapy.layers import http
from scapy.layers.http import HTTPResponse
import sys
packets = rdpcap("task07_f1.pcap")
requests = {}
answers = {}
def has_http_header(packet):
return packet.haslayer(HTTPResponse)
for pkt in packets:
tcp = pkt['TCP']
# destination port must be 80
if tcp.dport == 80 and pkt.haslayer('HTTP'):
ip_id = pkt[IP].id
requests[ip_id] = pkt
for pkt in packets:
tcp = pkt['TCP']
# source port must be 80
if tcp.sport == 80 and pkt.haslayer('HTTP'):
ip_id = pkt['IP'].id
answers[ip_id] = pkt
print '=============== REQUESTS =================='
i = 0
for ip_id in requests:
print 'Packet: ', i, "\n"
i = i + 1
req = requests[ip_id]
req.show()
''' if req.haslayer('HTTP'):
# if 'HTTP Request' in req:
httpreq = req.getlayer('HTTP')
print '\o/\o/\o/\o/ HTTP REQUEST \o/\o/\o/\o/\o/\o/'
print httpreq
else:
print '/o\ /o\ /o\ NO HTTP REQUEST'
'''
print '=============== ANSWERS =================='
i = 0
for ip_id in answers:
print 'Packet: ', i, "\n"
i = i + 1
ans = answers[ip_id]
if has_http_header(ans):
print "HAS HEADER\n"
else:
print "NO HEADER\n"
ans.show()
Change from dic to list# sudo apt-get install python-scapy
from scapy.all import *
# sudo pip install scapy_http
from scapy.layers import http
from scapy.layers.http import HTTPResponse
import sys
packets = rdpcap("task07_f1.pcap")
requests = []
answers = []
def has_http_header(packet):
return packet.haslayer(HTTPResponse)
for pkt in packets:
tcp = pkt['TCP']
# destination port must be 80
if tcp.dport == 80 and pkt.haslayer('HTTP'):
requests.append(pkt)
for pkt in packets:
tcp = pkt['TCP']
# source port must be 80
if tcp.sport == 80 and pkt.haslayer('HTTP'):
answers.append(pkt)
print '=============== REQUESTS =================='
i = 0
for req in requests:
print 'Packet: ', i, "\n"
i = i + 1
req.show()
print '=============== ANSWERS =================='
i = 0
for ans in answers:
print 'Packet: ', i, "\n"
i = i + 1
if has_http_header(ans):
print "HAS HEADER\n"
else:
print "NO HEADER\n"
ans.show()
|
<commit_before># sudo apt-get install python-scapy
from scapy.all import *
# sudo pip install scapy_http
from scapy.layers import http
from scapy.layers.http import HTTPResponse
import sys
packets = rdpcap("task07_f1.pcap")
requests = {}
answers = {}
def has_http_header(packet):
return packet.haslayer(HTTPResponse)
for pkt in packets:
tcp = pkt['TCP']
# destination port must be 80
if tcp.dport == 80 and pkt.haslayer('HTTP'):
ip_id = pkt[IP].id
requests[ip_id] = pkt
for pkt in packets:
tcp = pkt['TCP']
# source port must be 80
if tcp.sport == 80 and pkt.haslayer('HTTP'):
ip_id = pkt['IP'].id
answers[ip_id] = pkt
print '=============== REQUESTS =================='
i = 0
for ip_id in requests:
print 'Packet: ', i, "\n"
i = i + 1
req = requests[ip_id]
req.show()
''' if req.haslayer('HTTP'):
# if 'HTTP Request' in req:
httpreq = req.getlayer('HTTP')
print '\o/\o/\o/\o/ HTTP REQUEST \o/\o/\o/\o/\o/\o/'
print httpreq
else:
print '/o\ /o\ /o\ NO HTTP REQUEST'
'''
print '=============== ANSWERS =================='
i = 0
for ip_id in answers:
print 'Packet: ', i, "\n"
i = i + 1
ans = answers[ip_id]
if has_http_header(ans):
print "HAS HEADER\n"
else:
print "NO HEADER\n"
ans.show()
<commit_msg>Change from dic to list<commit_after># sudo apt-get install python-scapy
from scapy.all import *
# sudo pip install scapy_http
from scapy.layers import http
from scapy.layers.http import HTTPResponse
import sys
packets = rdpcap("task07_f1.pcap")
requests = []
answers = []
def has_http_header(packet):
return packet.haslayer(HTTPResponse)
for pkt in packets:
tcp = pkt['TCP']
# destination port must be 80
if tcp.dport == 80 and pkt.haslayer('HTTP'):
requests.append(pkt)
for pkt in packets:
tcp = pkt['TCP']
# source port must be 80
if tcp.sport == 80 and pkt.haslayer('HTTP'):
answers.append(pkt)
print '=============== REQUESTS =================='
i = 0
for req in requests:
print 'Packet: ', i, "\n"
i = i + 1
req.show()
print '=============== ANSWERS =================='
i = 0
for ans in answers:
print 'Packet: ', i, "\n"
i = i + 1
if has_http_header(ans):
print "HAS HEADER\n"
else:
print "NO HEADER\n"
ans.show()
|
0fa817e3efee4e9a539432d6e308534f82448c60
|
ReligiousPhraseMC/holy_twitter.py
|
ReligiousPhraseMC/holy_twitter.py
|
"""Coordinates the twitter api with the markov chain models"""
def main():
"""The main event loop for the holy twitter bot
It watches for twitter events, and posts randomly generated holy text to twitter.
"""
pass
if __name__ == '__main__':
main()
|
"""Coordinates the twitter api with the markov chain models"""
from tweepy import Stream, OAuthHandler, API
from tweepy.streaming import StreamListener
from twitter_secrets import api_tokens as at
class HolyListener(StreamListener):
def __init__(self):
self.tweetCount = 0
def on_connect(self):
print("Connection established!!")
def on_disconnect(self, notice):
print("Connection lost!! : ", notice)
def on_data(self, status):
print("Entered on_data()")
print(status, flush=True)
return True
def on_direct_message(self, status):
print("Entered on_direct_message()")
try:
print(status, flush=True)
return True
except BaseException as e:
print("Failed on_direct_message()", str(e))
def on_error(self, status):
print(status)
def main():
"""The main event loop for the holy twitter bot
It watches for twitter events, and posts randomly generated holy text to twitter.
"""
try:
auth = OAuthHandler(at['CONSUMER_KEY'], at['CONSUMER_SECRET'])
auth.secure = True
auth.set_access_token(at['ACCESS_KEY'], at['ACCESS_SECRET'])
api = API(auth)
# If the authentication was successful, you should
# see the name of the account print out
print(api.me().name)
stream.userstream()
except BaseException as e:
print("Error in main()", e)
if __name__ == '__main__':
main()
|
Add the twitter streaming solution as module
|
Add the twitter streaming solution as module
The streaming solution added here is the second one I tried in the
notebook. It seems like it will work well. Might mix them
|
Python
|
mit
|
salvor7/MarkovChainBibleBot
|
"""Coordinates the twitter api with the markov chain models"""
def main():
"""The main event loop for the holy twitter bot
It watches for twitter events, and posts randomly generated holy text to twitter.
"""
pass
if __name__ == '__main__':
main()
Add the twitter streaming solution as module
The streaming solution added here is the second one I tried in the
notebook. It seems like it will work well. Might mix them
|
"""Coordinates the twitter api with the markov chain models"""
from tweepy import Stream, OAuthHandler, API
from tweepy.streaming import StreamListener
from twitter_secrets import api_tokens as at
class HolyListener(StreamListener):
def __init__(self):
self.tweetCount = 0
def on_connect(self):
print("Connection established!!")
def on_disconnect(self, notice):
print("Connection lost!! : ", notice)
def on_data(self, status):
print("Entered on_data()")
print(status, flush=True)
return True
def on_direct_message(self, status):
print("Entered on_direct_message()")
try:
print(status, flush=True)
return True
except BaseException as e:
print("Failed on_direct_message()", str(e))
def on_error(self, status):
print(status)
def main():
"""The main event loop for the holy twitter bot
It watches for twitter events, and posts randomly generated holy text to twitter.
"""
try:
auth = OAuthHandler(at['CONSUMER_KEY'], at['CONSUMER_SECRET'])
auth.secure = True
auth.set_access_token(at['ACCESS_KEY'], at['ACCESS_SECRET'])
api = API(auth)
# If the authentication was successful, you should
# see the name of the account print out
print(api.me().name)
stream.userstream()
except BaseException as e:
print("Error in main()", e)
if __name__ == '__main__':
main()
|
<commit_before>"""Coordinates the twitter api with the markov chain models"""
def main():
"""The main event loop for the holy twitter bot
It watches for twitter events, and posts randomly generated holy text to twitter.
"""
pass
if __name__ == '__main__':
main()
<commit_msg>Add the twitter streaming solution as module
The streaming solution added here is the second one I tried in the
notebook. It seems like it will work well. Might mix them<commit_after>
|
"""Coordinates the twitter api with the markov chain models"""
from tweepy import Stream, OAuthHandler, API
from tweepy.streaming import StreamListener
from twitter_secrets import api_tokens as at
class HolyListener(StreamListener):
def __init__(self):
self.tweetCount = 0
def on_connect(self):
print("Connection established!!")
def on_disconnect(self, notice):
print("Connection lost!! : ", notice)
def on_data(self, status):
print("Entered on_data()")
print(status, flush=True)
return True
def on_direct_message(self, status):
print("Entered on_direct_message()")
try:
print(status, flush=True)
return True
except BaseException as e:
print("Failed on_direct_message()", str(e))
def on_error(self, status):
print(status)
def main():
"""The main event loop for the holy twitter bot
It watches for twitter events, and posts randomly generated holy text to twitter.
"""
try:
auth = OAuthHandler(at['CONSUMER_KEY'], at['CONSUMER_SECRET'])
auth.secure = True
auth.set_access_token(at['ACCESS_KEY'], at['ACCESS_SECRET'])
api = API(auth)
# If the authentication was successful, you should
# see the name of the account print out
print(api.me().name)
stream.userstream()
except BaseException as e:
print("Error in main()", e)
if __name__ == '__main__':
main()
|
"""Coordinates the twitter api with the markov chain models"""
def main():
"""The main event loop for the holy twitter bot
It watches for twitter events, and posts randomly generated holy text to twitter.
"""
pass
if __name__ == '__main__':
main()
Add the twitter streaming solution as module
The streaming solution added here is the second one I tried in the
notebook. It seems like it will work well. Might mix them"""Coordinates the twitter api with the markov chain models"""
from tweepy import Stream, OAuthHandler, API
from tweepy.streaming import StreamListener
from twitter_secrets import api_tokens as at
class HolyListener(StreamListener):
def __init__(self):
self.tweetCount = 0
def on_connect(self):
print("Connection established!!")
def on_disconnect(self, notice):
print("Connection lost!! : ", notice)
def on_data(self, status):
print("Entered on_data()")
print(status, flush=True)
return True
def on_direct_message(self, status):
print("Entered on_direct_message()")
try:
print(status, flush=True)
return True
except BaseException as e:
print("Failed on_direct_message()", str(e))
def on_error(self, status):
print(status)
def main():
"""The main event loop for the holy twitter bot
It watches for twitter events, and posts randomly generated holy text to twitter.
"""
try:
auth = OAuthHandler(at['CONSUMER_KEY'], at['CONSUMER_SECRET'])
auth.secure = True
auth.set_access_token(at['ACCESS_KEY'], at['ACCESS_SECRET'])
api = API(auth)
# If the authentication was successful, you should
# see the name of the account print out
print(api.me().name)
stream.userstream()
except BaseException as e:
print("Error in main()", e)
if __name__ == '__main__':
main()
|
<commit_before>"""Coordinates the twitter api with the markov chain models"""
def main():
"""The main event loop for the holy twitter bot
It watches for twitter events, and posts randomly generated holy text to twitter.
"""
pass
if __name__ == '__main__':
main()
<commit_msg>Add the twitter streaming solution as module
The streaming solution added here is the second one I tried in the
notebook. It seems like it will work well. Might mix them<commit_after>"""Coordinates the twitter api with the markov chain models"""
from tweepy import Stream, OAuthHandler, API
from tweepy.streaming import StreamListener
from twitter_secrets import api_tokens as at
class HolyListener(StreamListener):
def __init__(self):
self.tweetCount = 0
def on_connect(self):
print("Connection established!!")
def on_disconnect(self, notice):
print("Connection lost!! : ", notice)
def on_data(self, status):
print("Entered on_data()")
print(status, flush=True)
return True
def on_direct_message(self, status):
print("Entered on_direct_message()")
try:
print(status, flush=True)
return True
except BaseException as e:
print("Failed on_direct_message()", str(e))
def on_error(self, status):
print(status)
def main():
"""The main event loop for the holy twitter bot
It watches for twitter events, and posts randomly generated holy text to twitter.
"""
try:
auth = OAuthHandler(at['CONSUMER_KEY'], at['CONSUMER_SECRET'])
auth.secure = True
auth.set_access_token(at['ACCESS_KEY'], at['ACCESS_SECRET'])
api = API(auth)
# If the authentication was successful, you should
# see the name of the account print out
print(api.me().name)
stream.userstream()
except BaseException as e:
print("Error in main()", e)
if __name__ == '__main__':
main()
|
1b187ed85aede9ffe39ce52303694f852a8d02a2
|
vantage/shell.py
|
vantage/shell.py
|
import sys
import subprocess
from vantage import utils
from vantage.exceptions import VantageException
def shell_cmd(env, cmd, *args):
utils.loquacious(f"Running system defined '{cmd}' inside env", env)
utils.loquacious(f" With args: {args}", env)
try:
cmd = utils.find_executable(cmd)
if cmd is None:
raise FileNotFoundError()
completed = subprocess.run(
[cmd, *args],
env=env,
stdin=sys.stdin,
stdout=sys.stdout,
stderr=sys.stderr,
)
utils.loquacious(f" Exited with code {completed.returncode}", env)
return completed.returncode
except FileNotFoundError:
raise VantageException(f"Command '{cmd}' not found")
|
import sys
import subprocess
from vantage import utils
from vantage.exceptions import VantageException
def shell_cmd(env, cmd, *args):
utils.loquacious(f"Running system defined '{cmd}' inside env", env)
utils.loquacious(f" With args: {args}", env)
try:
cmd_path = utils.find_executable(cmd)
if cmd_path is None:
raise FileNotFoundError()
completed = subprocess.run(
[cmd_path, *args],
env=env,
stdin=sys.stdin,
stdout=sys.stdout,
stderr=sys.stderr,
)
utils.loquacious(f" Exited with code {completed.returncode}", env)
return completed.returncode
except FileNotFoundError:
raise VantageException(f"Command '{cmd}' not found")
|
Fix missing cmd name in error message
|
Fix missing cmd name in error message
|
Python
|
mit
|
vantage-org/vantage,vantage-org/vantage
|
import sys
import subprocess
from vantage import utils
from vantage.exceptions import VantageException
def shell_cmd(env, cmd, *args):
utils.loquacious(f"Running system defined '{cmd}' inside env", env)
utils.loquacious(f" With args: {args}", env)
try:
cmd = utils.find_executable(cmd)
if cmd is None:
raise FileNotFoundError()
completed = subprocess.run(
[cmd, *args],
env=env,
stdin=sys.stdin,
stdout=sys.stdout,
stderr=sys.stderr,
)
utils.loquacious(f" Exited with code {completed.returncode}", env)
return completed.returncode
except FileNotFoundError:
raise VantageException(f"Command '{cmd}' not found")
Fix missing cmd name in error message
|
import sys
import subprocess
from vantage import utils
from vantage.exceptions import VantageException
def shell_cmd(env, cmd, *args):
utils.loquacious(f"Running system defined '{cmd}' inside env", env)
utils.loquacious(f" With args: {args}", env)
try:
cmd_path = utils.find_executable(cmd)
if cmd_path is None:
raise FileNotFoundError()
completed = subprocess.run(
[cmd_path, *args],
env=env,
stdin=sys.stdin,
stdout=sys.stdout,
stderr=sys.stderr,
)
utils.loquacious(f" Exited with code {completed.returncode}", env)
return completed.returncode
except FileNotFoundError:
raise VantageException(f"Command '{cmd}' not found")
|
<commit_before>import sys
import subprocess
from vantage import utils
from vantage.exceptions import VantageException
def shell_cmd(env, cmd, *args):
utils.loquacious(f"Running system defined '{cmd}' inside env", env)
utils.loquacious(f" With args: {args}", env)
try:
cmd = utils.find_executable(cmd)
if cmd is None:
raise FileNotFoundError()
completed = subprocess.run(
[cmd, *args],
env=env,
stdin=sys.stdin,
stdout=sys.stdout,
stderr=sys.stderr,
)
utils.loquacious(f" Exited with code {completed.returncode}", env)
return completed.returncode
except FileNotFoundError:
raise VantageException(f"Command '{cmd}' not found")
<commit_msg>Fix missing cmd name in error message<commit_after>
|
import sys
import subprocess
from vantage import utils
from vantage.exceptions import VantageException
def shell_cmd(env, cmd, *args):
utils.loquacious(f"Running system defined '{cmd}' inside env", env)
utils.loquacious(f" With args: {args}", env)
try:
cmd_path = utils.find_executable(cmd)
if cmd_path is None:
raise FileNotFoundError()
completed = subprocess.run(
[cmd_path, *args],
env=env,
stdin=sys.stdin,
stdout=sys.stdout,
stderr=sys.stderr,
)
utils.loquacious(f" Exited with code {completed.returncode}", env)
return completed.returncode
except FileNotFoundError:
raise VantageException(f"Command '{cmd}' not found")
|
import sys
import subprocess
from vantage import utils
from vantage.exceptions import VantageException
def shell_cmd(env, cmd, *args):
utils.loquacious(f"Running system defined '{cmd}' inside env", env)
utils.loquacious(f" With args: {args}", env)
try:
cmd = utils.find_executable(cmd)
if cmd is None:
raise FileNotFoundError()
completed = subprocess.run(
[cmd, *args],
env=env,
stdin=sys.stdin,
stdout=sys.stdout,
stderr=sys.stderr,
)
utils.loquacious(f" Exited with code {completed.returncode}", env)
return completed.returncode
except FileNotFoundError:
raise VantageException(f"Command '{cmd}' not found")
Fix missing cmd name in error messageimport sys
import subprocess
from vantage import utils
from vantage.exceptions import VantageException
def shell_cmd(env, cmd, *args):
utils.loquacious(f"Running system defined '{cmd}' inside env", env)
utils.loquacious(f" With args: {args}", env)
try:
cmd_path = utils.find_executable(cmd)
if cmd_path is None:
raise FileNotFoundError()
completed = subprocess.run(
[cmd_path, *args],
env=env,
stdin=sys.stdin,
stdout=sys.stdout,
stderr=sys.stderr,
)
utils.loquacious(f" Exited with code {completed.returncode}", env)
return completed.returncode
except FileNotFoundError:
raise VantageException(f"Command '{cmd}' not found")
|
<commit_before>import sys
import subprocess
from vantage import utils
from vantage.exceptions import VantageException
def shell_cmd(env, cmd, *args):
utils.loquacious(f"Running system defined '{cmd}' inside env", env)
utils.loquacious(f" With args: {args}", env)
try:
cmd = utils.find_executable(cmd)
if cmd is None:
raise FileNotFoundError()
completed = subprocess.run(
[cmd, *args],
env=env,
stdin=sys.stdin,
stdout=sys.stdout,
stderr=sys.stderr,
)
utils.loquacious(f" Exited with code {completed.returncode}", env)
return completed.returncode
except FileNotFoundError:
raise VantageException(f"Command '{cmd}' not found")
<commit_msg>Fix missing cmd name in error message<commit_after>import sys
import subprocess
from vantage import utils
from vantage.exceptions import VantageException
def shell_cmd(env, cmd, *args):
utils.loquacious(f"Running system defined '{cmd}' inside env", env)
utils.loquacious(f" With args: {args}", env)
try:
cmd_path = utils.find_executable(cmd)
if cmd_path is None:
raise FileNotFoundError()
completed = subprocess.run(
[cmd_path, *args],
env=env,
stdin=sys.stdin,
stdout=sys.stdout,
stderr=sys.stderr,
)
utils.loquacious(f" Exited with code {completed.returncode}", env)
return completed.returncode
except FileNotFoundError:
raise VantageException(f"Command '{cmd}' not found")
|
c4109fadf0a66db5af0e579600a70e4b7e28493d
|
csdms/dakota/experiment.py
|
csdms/dakota/experiment.py
|
"""A template for describing a Dakota experiment."""
import os
import importlib
import inspect
blocks = ['environment', 'method', 'variables', 'interface', 'responses']
class Experiment(object):
"""Describe parameters to create an input file for a Dakota experiment."""
def __init__(self,
method='vector_parameter_study',
variables='continuous_design',
interface='direct',
responses='response_functions',
**kwargs):
"""Create a set of default experiment parameters."""
self.environment = self._import('environment', 'environment', **kwargs)
self.method = self._import('method', method, **kwargs)
self.variables = self._import('variables', variables, **kwargs)
self.interface = self._import('interface', interface, **kwargs)
self.responses = self._import('responses', responses, **kwargs)
def _get_subpackage_namespace(self, subpackage):
return os.path.splitext(self.__module__)[0] + '.' + subpackage
def _import(self, subpackage, module, **kwargs):
namespace = self._get_subpackage_namespace(subpackage) + '.' + module
module = importlib.import_module(namespace)
cls = getattr(module, module.classname)
return cls(**kwargs)
def __str__(self):
s = '# Dakota input file\n'
for section in blocks:
s += str(getattr(self, section))
return s
|
"""A template for describing a Dakota experiment."""
import os
import importlib
class Experiment(object):
"""Describe parameters to create an input file for a Dakota experiment."""
def __init__(self,
environment='environment',
method='vector_parameter_study',
variables='continuous_design',
interface='direct',
responses='response_functions',
**kwargs):
"""Create a set of default experiment parameters."""
self._blocks = ('environment', 'method', 'variables',
'interface', 'responses')
for section in self._blocks:
cls = self._import(section, eval(section), **kwargs)
setattr(self, section, cls)
def _get_subpackage_namespace(self, subpackage):
return os.path.splitext(self.__module__)[0] + '.' + subpackage
def _import(self, subpackage, module, **kwargs):
namespace = self._get_subpackage_namespace(subpackage) + '.' + module
module = importlib.import_module(namespace)
cls = getattr(module, module.classname)
return cls(**kwargs)
def __str__(self):
s = '# Dakota input file\n'
for section in self._blocks:
s += str(getattr(self, section))
return s
|
Refactor init method with _blocks attribute
|
Refactor init method with _blocks attribute
|
Python
|
mit
|
csdms/dakota,csdms/dakota
|
"""A template for describing a Dakota experiment."""
import os
import importlib
import inspect
blocks = ['environment', 'method', 'variables', 'interface', 'responses']
class Experiment(object):
"""Describe parameters to create an input file for a Dakota experiment."""
def __init__(self,
method='vector_parameter_study',
variables='continuous_design',
interface='direct',
responses='response_functions',
**kwargs):
"""Create a set of default experiment parameters."""
self.environment = self._import('environment', 'environment', **kwargs)
self.method = self._import('method', method, **kwargs)
self.variables = self._import('variables', variables, **kwargs)
self.interface = self._import('interface', interface, **kwargs)
self.responses = self._import('responses', responses, **kwargs)
def _get_subpackage_namespace(self, subpackage):
return os.path.splitext(self.__module__)[0] + '.' + subpackage
def _import(self, subpackage, module, **kwargs):
namespace = self._get_subpackage_namespace(subpackage) + '.' + module
module = importlib.import_module(namespace)
cls = getattr(module, module.classname)
return cls(**kwargs)
def __str__(self):
s = '# Dakota input file\n'
for section in blocks:
s += str(getattr(self, section))
return s
Refactor init method with _blocks attribute
|
"""A template for describing a Dakota experiment."""
import os
import importlib
class Experiment(object):
"""Describe parameters to create an input file for a Dakota experiment."""
def __init__(self,
environment='environment',
method='vector_parameter_study',
variables='continuous_design',
interface='direct',
responses='response_functions',
**kwargs):
"""Create a set of default experiment parameters."""
self._blocks = ('environment', 'method', 'variables',
'interface', 'responses')
for section in self._blocks:
cls = self._import(section, eval(section), **kwargs)
setattr(self, section, cls)
def _get_subpackage_namespace(self, subpackage):
return os.path.splitext(self.__module__)[0] + '.' + subpackage
def _import(self, subpackage, module, **kwargs):
namespace = self._get_subpackage_namespace(subpackage) + '.' + module
module = importlib.import_module(namespace)
cls = getattr(module, module.classname)
return cls(**kwargs)
def __str__(self):
s = '# Dakota input file\n'
for section in self._blocks:
s += str(getattr(self, section))
return s
|
<commit_before>"""A template for describing a Dakota experiment."""
import os
import importlib
import inspect
blocks = ['environment', 'method', 'variables', 'interface', 'responses']
class Experiment(object):
"""Describe parameters to create an input file for a Dakota experiment."""
def __init__(self,
method='vector_parameter_study',
variables='continuous_design',
interface='direct',
responses='response_functions',
**kwargs):
"""Create a set of default experiment parameters."""
self.environment = self._import('environment', 'environment', **kwargs)
self.method = self._import('method', method, **kwargs)
self.variables = self._import('variables', variables, **kwargs)
self.interface = self._import('interface', interface, **kwargs)
self.responses = self._import('responses', responses, **kwargs)
def _get_subpackage_namespace(self, subpackage):
return os.path.splitext(self.__module__)[0] + '.' + subpackage
def _import(self, subpackage, module, **kwargs):
namespace = self._get_subpackage_namespace(subpackage) + '.' + module
module = importlib.import_module(namespace)
cls = getattr(module, module.classname)
return cls(**kwargs)
def __str__(self):
s = '# Dakota input file\n'
for section in blocks:
s += str(getattr(self, section))
return s
<commit_msg>Refactor init method with _blocks attribute<commit_after>
|
"""A template for describing a Dakota experiment."""
import os
import importlib
class Experiment(object):
"""Describe parameters to create an input file for a Dakota experiment."""
def __init__(self,
environment='environment',
method='vector_parameter_study',
variables='continuous_design',
interface='direct',
responses='response_functions',
**kwargs):
"""Create a set of default experiment parameters."""
self._blocks = ('environment', 'method', 'variables',
'interface', 'responses')
for section in self._blocks:
cls = self._import(section, eval(section), **kwargs)
setattr(self, section, cls)
def _get_subpackage_namespace(self, subpackage):
return os.path.splitext(self.__module__)[0] + '.' + subpackage
def _import(self, subpackage, module, **kwargs):
namespace = self._get_subpackage_namespace(subpackage) + '.' + module
module = importlib.import_module(namespace)
cls = getattr(module, module.classname)
return cls(**kwargs)
def __str__(self):
s = '# Dakota input file\n'
for section in self._blocks:
s += str(getattr(self, section))
return s
|
"""A template for describing a Dakota experiment."""
import os
import importlib
import inspect
blocks = ['environment', 'method', 'variables', 'interface', 'responses']
class Experiment(object):
"""Describe parameters to create an input file for a Dakota experiment."""
def __init__(self,
method='vector_parameter_study',
variables='continuous_design',
interface='direct',
responses='response_functions',
**kwargs):
"""Create a set of default experiment parameters."""
self.environment = self._import('environment', 'environment', **kwargs)
self.method = self._import('method', method, **kwargs)
self.variables = self._import('variables', variables, **kwargs)
self.interface = self._import('interface', interface, **kwargs)
self.responses = self._import('responses', responses, **kwargs)
def _get_subpackage_namespace(self, subpackage):
return os.path.splitext(self.__module__)[0] + '.' + subpackage
def _import(self, subpackage, module, **kwargs):
namespace = self._get_subpackage_namespace(subpackage) + '.' + module
module = importlib.import_module(namespace)
cls = getattr(module, module.classname)
return cls(**kwargs)
def __str__(self):
s = '# Dakota input file\n'
for section in blocks:
s += str(getattr(self, section))
return s
Refactor init method with _blocks attribute"""A template for describing a Dakota experiment."""
import os
import importlib
class Experiment(object):
"""Describe parameters to create an input file for a Dakota experiment."""
def __init__(self,
environment='environment',
method='vector_parameter_study',
variables='continuous_design',
interface='direct',
responses='response_functions',
**kwargs):
"""Create a set of default experiment parameters."""
self._blocks = ('environment', 'method', 'variables',
'interface', 'responses')
for section in self._blocks:
cls = self._import(section, eval(section), **kwargs)
setattr(self, section, cls)
def _get_subpackage_namespace(self, subpackage):
return os.path.splitext(self.__module__)[0] + '.' + subpackage
def _import(self, subpackage, module, **kwargs):
namespace = self._get_subpackage_namespace(subpackage) + '.' + module
module = importlib.import_module(namespace)
cls = getattr(module, module.classname)
return cls(**kwargs)
def __str__(self):
s = '# Dakota input file\n'
for section in self._blocks:
s += str(getattr(self, section))
return s
|
<commit_before>"""A template for describing a Dakota experiment."""
import os
import importlib
import inspect
blocks = ['environment', 'method', 'variables', 'interface', 'responses']
class Experiment(object):
"""Describe parameters to create an input file for a Dakota experiment."""
def __init__(self,
method='vector_parameter_study',
variables='continuous_design',
interface='direct',
responses='response_functions',
**kwargs):
"""Create a set of default experiment parameters."""
self.environment = self._import('environment', 'environment', **kwargs)
self.method = self._import('method', method, **kwargs)
self.variables = self._import('variables', variables, **kwargs)
self.interface = self._import('interface', interface, **kwargs)
self.responses = self._import('responses', responses, **kwargs)
def _get_subpackage_namespace(self, subpackage):
return os.path.splitext(self.__module__)[0] + '.' + subpackage
def _import(self, subpackage, module, **kwargs):
namespace = self._get_subpackage_namespace(subpackage) + '.' + module
module = importlib.import_module(namespace)
cls = getattr(module, module.classname)
return cls(**kwargs)
def __str__(self):
s = '# Dakota input file\n'
for section in blocks:
s += str(getattr(self, section))
return s
<commit_msg>Refactor init method with _blocks attribute<commit_after>"""A template for describing a Dakota experiment."""
import os
import importlib
class Experiment(object):
"""Describe parameters to create an input file for a Dakota experiment."""
def __init__(self,
environment='environment',
method='vector_parameter_study',
variables='continuous_design',
interface='direct',
responses='response_functions',
**kwargs):
"""Create a set of default experiment parameters."""
self._blocks = ('environment', 'method', 'variables',
'interface', 'responses')
for section in self._blocks:
cls = self._import(section, eval(section), **kwargs)
setattr(self, section, cls)
def _get_subpackage_namespace(self, subpackage):
return os.path.splitext(self.__module__)[0] + '.' + subpackage
def _import(self, subpackage, module, **kwargs):
namespace = self._get_subpackage_namespace(subpackage) + '.' + module
module = importlib.import_module(namespace)
cls = getattr(module, module.classname)
return cls(**kwargs)
def __str__(self):
s = '# Dakota input file\n'
for section in self._blocks:
s += str(getattr(self, section))
return s
|
71bba7197f1e9faaa99cb54dfde452a7c8b1ff0f
|
nupic/research/frameworks/sigopt/common_experiments.py
|
nupic/research/frameworks/sigopt/common_experiments.py
|
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2020, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Affero Public License for more details.
#
# You should have received a copy of the GNU Affero Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
import mixins
from .sigopt_experiment import SigOptExperiment
class SigOptImagenetExperiment(SigOptExperiment, mixins.ImagenetParams):
"""
A subclass of SigOptExperiment used to sit between an experiment runner (such as
Ray) and the ImagenetExperiment class. update_config_with_suggestion() is specific
to our ImagenetExperiment config.
"""
pass
|
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2020, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Affero Public License for more details.
#
# You should have received a copy of the GNU Affero Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
import mixins
from .sigopt_experiment import SigOptExperiment
class SigOptImagenetExperiment(SigOptExperiment, mixins.ImagenetParams):
"""
A subclass of SigOptExperiment used to sit between an experiment runner (such as
Ray) and the ImagenetExperiment class. update_config_with_suggestion() is specific
to our ImagenetExperiment config.
"""
pass
class SigOptSDGOneCycleLRExperiment(SigOptExperiment,
mixins.SGDParams,
mixins.OneCycleLRParams):
"""Tune hyper-parameters using SDG and OneCycleLR."""
pass
class SigOptSDGStepLRExperiment(SigOptExperiment, mixins.SGDParams, mixins.StepLRParams):
"""Tune hyper-parameters using SDG and StepLR."""
pass
|
Add experiment classes for tuning hyper-parameters with SGD and either StepLR of OneCycleLR schedulers.
|
Add experiment classes for tuning hyper-parameters with SGD and either StepLR of OneCycleLR schedulers.
|
Python
|
agpl-3.0
|
numenta/nupic.research,mrcslws/nupic.research,subutai/nupic.research,numenta/nupic.research,subutai/nupic.research,mrcslws/nupic.research
|
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2020, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Affero Public License for more details.
#
# You should have received a copy of the GNU Affero Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
import mixins
from .sigopt_experiment import SigOptExperiment
class SigOptImagenetExperiment(SigOptExperiment, mixins.ImagenetParams):
"""
A subclass of SigOptExperiment used to sit between an experiment runner (such as
Ray) and the ImagenetExperiment class. update_config_with_suggestion() is specific
to our ImagenetExperiment config.
"""
pass
Add experiment classes for tuning hyper-parameters with SGD and either StepLR of OneCycleLR schedulers.
|
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2020, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Affero Public License for more details.
#
# You should have received a copy of the GNU Affero Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
import mixins
from .sigopt_experiment import SigOptExperiment
class SigOptImagenetExperiment(SigOptExperiment, mixins.ImagenetParams):
"""
A subclass of SigOptExperiment used to sit between an experiment runner (such as
Ray) and the ImagenetExperiment class. update_config_with_suggestion() is specific
to our ImagenetExperiment config.
"""
pass
class SigOptSDGOneCycleLRExperiment(SigOptExperiment,
mixins.SGDParams,
mixins.OneCycleLRParams):
"""Tune hyper-parameters using SDG and OneCycleLR."""
pass
class SigOptSDGStepLRExperiment(SigOptExperiment, mixins.SGDParams, mixins.StepLRParams):
"""Tune hyper-parameters using SDG and StepLR."""
pass
|
<commit_before># ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2020, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Affero Public License for more details.
#
# You should have received a copy of the GNU Affero Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
import mixins
from .sigopt_experiment import SigOptExperiment
class SigOptImagenetExperiment(SigOptExperiment, mixins.ImagenetParams):
"""
A subclass of SigOptExperiment used to sit between an experiment runner (such as
Ray) and the ImagenetExperiment class. update_config_with_suggestion() is specific
to our ImagenetExperiment config.
"""
pass
<commit_msg>Add experiment classes for tuning hyper-parameters with SGD and either StepLR of OneCycleLR schedulers.<commit_after>
|
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2020, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Affero Public License for more details.
#
# You should have received a copy of the GNU Affero Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
import mixins
from .sigopt_experiment import SigOptExperiment
class SigOptImagenetExperiment(SigOptExperiment, mixins.ImagenetParams):
"""
A subclass of SigOptExperiment used to sit between an experiment runner (such as
Ray) and the ImagenetExperiment class. update_config_with_suggestion() is specific
to our ImagenetExperiment config.
"""
pass
class SigOptSDGOneCycleLRExperiment(SigOptExperiment,
mixins.SGDParams,
mixins.OneCycleLRParams):
"""Tune hyper-parameters using SDG and OneCycleLR."""
pass
class SigOptSDGStepLRExperiment(SigOptExperiment, mixins.SGDParams, mixins.StepLRParams):
"""Tune hyper-parameters using SDG and StepLR."""
pass
|
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2020, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Affero Public License for more details.
#
# You should have received a copy of the GNU Affero Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
import mixins
from .sigopt_experiment import SigOptExperiment
class SigOptImagenetExperiment(SigOptExperiment, mixins.ImagenetParams):
"""
A subclass of SigOptExperiment used to sit between an experiment runner (such as
Ray) and the ImagenetExperiment class. update_config_with_suggestion() is specific
to our ImagenetExperiment config.
"""
pass
Add experiment classes for tuning hyper-parameters with SGD and either StepLR of OneCycleLR schedulers.# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2020, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Affero Public License for more details.
#
# You should have received a copy of the GNU Affero Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
import mixins
from .sigopt_experiment import SigOptExperiment
class SigOptImagenetExperiment(SigOptExperiment, mixins.ImagenetParams):
"""
A subclass of SigOptExperiment used to sit between an experiment runner (such as
Ray) and the ImagenetExperiment class. update_config_with_suggestion() is specific
to our ImagenetExperiment config.
"""
pass
class SigOptSDGOneCycleLRExperiment(SigOptExperiment,
mixins.SGDParams,
mixins.OneCycleLRParams):
"""Tune hyper-parameters using SDG and OneCycleLR."""
pass
class SigOptSDGStepLRExperiment(SigOptExperiment, mixins.SGDParams, mixins.StepLRParams):
"""Tune hyper-parameters using SDG and StepLR."""
pass
|
<commit_before># ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2020, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Affero Public License for more details.
#
# You should have received a copy of the GNU Affero Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
import mixins
from .sigopt_experiment import SigOptExperiment
class SigOptImagenetExperiment(SigOptExperiment, mixins.ImagenetParams):
"""
A subclass of SigOptExperiment used to sit between an experiment runner (such as
Ray) and the ImagenetExperiment class. update_config_with_suggestion() is specific
to our ImagenetExperiment config.
"""
pass
<commit_msg>Add experiment classes for tuning hyper-parameters with SGD and either StepLR of OneCycleLR schedulers.<commit_after># ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2020, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Affero Public License for more details.
#
# You should have received a copy of the GNU Affero Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
import mixins
from .sigopt_experiment import SigOptExperiment
class SigOptImagenetExperiment(SigOptExperiment, mixins.ImagenetParams):
"""
A subclass of SigOptExperiment used to sit between an experiment runner (such as
Ray) and the ImagenetExperiment class. update_config_with_suggestion() is specific
to our ImagenetExperiment config.
"""
pass
class SigOptSDGOneCycleLRExperiment(SigOptExperiment,
mixins.SGDParams,
mixins.OneCycleLRParams):
"""Tune hyper-parameters using SDG and OneCycleLR."""
pass
class SigOptSDGStepLRExperiment(SigOptExperiment, mixins.SGDParams, mixins.StepLRParams):
"""Tune hyper-parameters using SDG and StepLR."""
pass
|
c9ffe560879d6264eb4aed5b3dc96553f4ab2666
|
xudd/tools.py
|
xudd/tools.py
|
import base64
import uuid
from xudd import PY2
def base64_uuid4():
"""
Return a base64 encoded uuid4
"""
base64_encoded = base64.urlsafe_b64encode(uuid.uuid4().bytes)
if not PY2:
base64_encoded = base64_encoded.decode("utf-8")
return base64_encoded.rstrip("=")
def is_qualified_id(actor_id):
"""
See whether or not this actor id is fully qualified (has the
@hive-id attached) or not.
"""
return u"@" in actor_id
def split_id(actor_id):
"""
Split an actor id into ("actor-id", "hive-id")
If no hive-id, it will be None.
"""
components = actor_id.split(u"@", 1)
if len(components) == 1:
components.append(None)
return components
def possibly_qualify_id(actor_id, hive_id):
"""
If this actor doesn't already have a hive id assigned to it, assign it
"""
# it's already qualified, just return it
if is_qualified_id(actor_id):
return actor_id
return u"%s@%s" % (actor_id, hive_id)
|
import base64
import uuid
from xudd import PY2
def base64_uuid4():
"""
Return a base64 encoded uuid4
"""
base64_encoded = base64.urlsafe_b64encode(uuid.uuid4().bytes)
if not PY2:
base64_encoded = base64_encoded.decode("utf-8")
return base64_encoded.rstrip("=")
def is_qualified_id(actor_id):
"""
See whether or not this actor id is fully qualified (has the
@hive-id attached) or not.
"""
return u"@" in actor_id
def split_id(actor_id):
"""
Split an actor id into ("actor-id", "hive-id")
If no hive-id, it will be None.
"""
components = actor_id.split(u"@", 1)
if len(components) == 1:
components.append(None)
return components
def possibly_qualify_id(actor_id, hive_id):
"""If this actor doesn't already have a hive id assigned to it, assign it
Note that you can specify a hive_id here, and if there is already
a hive_id on the actor_id, it simply won't assign something. This
is useful if you want to declare an actor as local if it's not
assigned, but let it stay remote if it is.
"""
# it's already qualified, just return it
if is_qualified_id(actor_id):
return actor_id
return u"%s@%s" % (actor_id, hive_id)
|
Clarify that it's a-okay to use possibly_qualify_id to determine whether to declare an actor local.
|
Clarify that it's a-okay to use possibly_qualify_id to determine
whether to declare an actor local.
|
Python
|
apache-2.0
|
xudd/xudd
|
import base64
import uuid
from xudd import PY2
def base64_uuid4():
"""
Return a base64 encoded uuid4
"""
base64_encoded = base64.urlsafe_b64encode(uuid.uuid4().bytes)
if not PY2:
base64_encoded = base64_encoded.decode("utf-8")
return base64_encoded.rstrip("=")
def is_qualified_id(actor_id):
"""
See whether or not this actor id is fully qualified (has the
@hive-id attached) or not.
"""
return u"@" in actor_id
def split_id(actor_id):
"""
Split an actor id into ("actor-id", "hive-id")
If no hive-id, it will be None.
"""
components = actor_id.split(u"@", 1)
if len(components) == 1:
components.append(None)
return components
def possibly_qualify_id(actor_id, hive_id):
"""
If this actor doesn't already have a hive id assigned to it, assign it
"""
# it's already qualified, just return it
if is_qualified_id(actor_id):
return actor_id
return u"%s@%s" % (actor_id, hive_id)
Clarify that it's a-okay to use possibly_qualify_id to determine
whether to declare an actor local.
|
import base64
import uuid
from xudd import PY2
def base64_uuid4():
"""
Return a base64 encoded uuid4
"""
base64_encoded = base64.urlsafe_b64encode(uuid.uuid4().bytes)
if not PY2:
base64_encoded = base64_encoded.decode("utf-8")
return base64_encoded.rstrip("=")
def is_qualified_id(actor_id):
"""
See whether or not this actor id is fully qualified (has the
@hive-id attached) or not.
"""
return u"@" in actor_id
def split_id(actor_id):
"""
Split an actor id into ("actor-id", "hive-id")
If no hive-id, it will be None.
"""
components = actor_id.split(u"@", 1)
if len(components) == 1:
components.append(None)
return components
def possibly_qualify_id(actor_id, hive_id):
"""If this actor doesn't already have a hive id assigned to it, assign it
Note that you can specify a hive_id here, and if there is already
a hive_id on the actor_id, it simply won't assign something. This
is useful if you want to declare an actor as local if it's not
assigned, but let it stay remote if it is.
"""
# it's already qualified, just return it
if is_qualified_id(actor_id):
return actor_id
return u"%s@%s" % (actor_id, hive_id)
|
<commit_before>import base64
import uuid
from xudd import PY2
def base64_uuid4():
"""
Return a base64 encoded uuid4
"""
base64_encoded = base64.urlsafe_b64encode(uuid.uuid4().bytes)
if not PY2:
base64_encoded = base64_encoded.decode("utf-8")
return base64_encoded.rstrip("=")
def is_qualified_id(actor_id):
"""
See whether or not this actor id is fully qualified (has the
@hive-id attached) or not.
"""
return u"@" in actor_id
def split_id(actor_id):
"""
Split an actor id into ("actor-id", "hive-id")
If no hive-id, it will be None.
"""
components = actor_id.split(u"@", 1)
if len(components) == 1:
components.append(None)
return components
def possibly_qualify_id(actor_id, hive_id):
"""
If this actor doesn't already have a hive id assigned to it, assign it
"""
# it's already qualified, just return it
if is_qualified_id(actor_id):
return actor_id
return u"%s@%s" % (actor_id, hive_id)
<commit_msg>Clarify that it's a-okay to use possibly_qualify_id to determine
whether to declare an actor local.<commit_after>
|
import base64
import uuid
from xudd import PY2
def base64_uuid4():
"""
Return a base64 encoded uuid4
"""
base64_encoded = base64.urlsafe_b64encode(uuid.uuid4().bytes)
if not PY2:
base64_encoded = base64_encoded.decode("utf-8")
return base64_encoded.rstrip("=")
def is_qualified_id(actor_id):
"""
See whether or not this actor id is fully qualified (has the
@hive-id attached) or not.
"""
return u"@" in actor_id
def split_id(actor_id):
"""
Split an actor id into ("actor-id", "hive-id")
If no hive-id, it will be None.
"""
components = actor_id.split(u"@", 1)
if len(components) == 1:
components.append(None)
return components
def possibly_qualify_id(actor_id, hive_id):
"""If this actor doesn't already have a hive id assigned to it, assign it
Note that you can specify a hive_id here, and if there is already
a hive_id on the actor_id, it simply won't assign something. This
is useful if you want to declare an actor as local if it's not
assigned, but let it stay remote if it is.
"""
# it's already qualified, just return it
if is_qualified_id(actor_id):
return actor_id
return u"%s@%s" % (actor_id, hive_id)
|
import base64
import uuid
from xudd import PY2
def base64_uuid4():
"""
Return a base64 encoded uuid4
"""
base64_encoded = base64.urlsafe_b64encode(uuid.uuid4().bytes)
if not PY2:
base64_encoded = base64_encoded.decode("utf-8")
return base64_encoded.rstrip("=")
def is_qualified_id(actor_id):
"""
See whether or not this actor id is fully qualified (has the
@hive-id attached) or not.
"""
return u"@" in actor_id
def split_id(actor_id):
"""
Split an actor id into ("actor-id", "hive-id")
If no hive-id, it will be None.
"""
components = actor_id.split(u"@", 1)
if len(components) == 1:
components.append(None)
return components
def possibly_qualify_id(actor_id, hive_id):
"""
If this actor doesn't already have a hive id assigned to it, assign it
"""
# it's already qualified, just return it
if is_qualified_id(actor_id):
return actor_id
return u"%s@%s" % (actor_id, hive_id)
Clarify that it's a-okay to use possibly_qualify_id to determine
whether to declare an actor local.import base64
import uuid
from xudd import PY2
def base64_uuid4():
"""
Return a base64 encoded uuid4
"""
base64_encoded = base64.urlsafe_b64encode(uuid.uuid4().bytes)
if not PY2:
base64_encoded = base64_encoded.decode("utf-8")
return base64_encoded.rstrip("=")
def is_qualified_id(actor_id):
"""
See whether or not this actor id is fully qualified (has the
@hive-id attached) or not.
"""
return u"@" in actor_id
def split_id(actor_id):
"""
Split an actor id into ("actor-id", "hive-id")
If no hive-id, it will be None.
"""
components = actor_id.split(u"@", 1)
if len(components) == 1:
components.append(None)
return components
def possibly_qualify_id(actor_id, hive_id):
"""If this actor doesn't already have a hive id assigned to it, assign it
Note that you can specify a hive_id here, and if there is already
a hive_id on the actor_id, it simply won't assign something. This
is useful if you want to declare an actor as local if it's not
assigned, but let it stay remote if it is.
"""
# it's already qualified, just return it
if is_qualified_id(actor_id):
return actor_id
return u"%s@%s" % (actor_id, hive_id)
|
<commit_before>import base64
import uuid
from xudd import PY2
def base64_uuid4():
"""
Return a base64 encoded uuid4
"""
base64_encoded = base64.urlsafe_b64encode(uuid.uuid4().bytes)
if not PY2:
base64_encoded = base64_encoded.decode("utf-8")
return base64_encoded.rstrip("=")
def is_qualified_id(actor_id):
"""
See whether or not this actor id is fully qualified (has the
@hive-id attached) or not.
"""
return u"@" in actor_id
def split_id(actor_id):
"""
Split an actor id into ("actor-id", "hive-id")
If no hive-id, it will be None.
"""
components = actor_id.split(u"@", 1)
if len(components) == 1:
components.append(None)
return components
def possibly_qualify_id(actor_id, hive_id):
"""
If this actor doesn't already have a hive id assigned to it, assign it
"""
# it's already qualified, just return it
if is_qualified_id(actor_id):
return actor_id
return u"%s@%s" % (actor_id, hive_id)
<commit_msg>Clarify that it's a-okay to use possibly_qualify_id to determine
whether to declare an actor local.<commit_after>import base64
import uuid
from xudd import PY2
def base64_uuid4():
"""
Return a base64 encoded uuid4
"""
base64_encoded = base64.urlsafe_b64encode(uuid.uuid4().bytes)
if not PY2:
base64_encoded = base64_encoded.decode("utf-8")
return base64_encoded.rstrip("=")
def is_qualified_id(actor_id):
"""
See whether or not this actor id is fully qualified (has the
@hive-id attached) or not.
"""
return u"@" in actor_id
def split_id(actor_id):
"""
Split an actor id into ("actor-id", "hive-id")
If no hive-id, it will be None.
"""
components = actor_id.split(u"@", 1)
if len(components) == 1:
components.append(None)
return components
def possibly_qualify_id(actor_id, hive_id):
"""If this actor doesn't already have a hive id assigned to it, assign it
Note that you can specify a hive_id here, and if there is already
a hive_id on the actor_id, it simply won't assign something. This
is useful if you want to declare an actor as local if it's not
assigned, but let it stay remote if it is.
"""
# it's already qualified, just return it
if is_qualified_id(actor_id):
return actor_id
return u"%s@%s" % (actor_id, hive_id)
|
8a4295876a4e1059f46f8fadaa1562062bfe877e
|
tests/test_edge_cases.py
|
tests/test_edge_cases.py
|
from __future__ import with_statement
import unittest
from flask import Flask
import flask_featureflags as feature_flags
class TestOutsideRequestContext(unittest.TestCase):
def test_checking_is_active_outside_request_context_returns_false(self):
self.assertFalse(feature_flags.is_active("BOGUS_FEATURE_FLAG"))
def test_default_handler_returns_false_outside_request_context(self):
self.assertFalse(feature_flags.AppConfigFlagHandler("BOGUS_FEATURE_FLAG"))
class TestBadlyConfiguredApplication(unittest.TestCase):
def test_checking_is_active_on_an_app_that_was_never_set_up_raises_assertion(self):
# This simulates somebody calling is_active on a Flask app that was never
# set up with this extension. Since this is somebody likely trying to install it,
# make sure they get a nice, helpful error message
test_app = Flask(__name__)
with test_app.test_request_context("/"):
self.assertRaises(AssertionError, feature_flags.is_active, "BOGUS_FEATURE_FLAG")
def test_running_default_handler_on_app_that_was_never_set_up_returns_false(self):
# This case should only happen if somebody's being especially creative, but
# I want to make sure it's well-behaved anyways.
test_app = Flask(__name__)
with test_app.test_request_context("/"):
self.assertFalse(feature_flags.AppConfigFlagHandler("BOGUS_FEATURE_FLAG"))
|
from __future__ import with_statement
import unittest
from flask import Flask
import flask_featureflags as feature_flags
class TestOutsideRequestContext(unittest.TestCase):
def test_checking_is_active_outside_request_context_returns_false(self):
self.assertFalse(feature_flags.is_active("BOGUS_FEATURE_FLAG"))
def test_default_handler_returns_false_outside_request_context(self):
self.assertFalse(feature_flags.AppConfigFlagHandler("BOGUS_FEATURE_FLAG"))
class TestBadlyConfiguredApplication(unittest.TestCase):
def test_checking_is_active_on_an_app_that_was_never_set_up_raises_assertion(self):
# This simulates somebody calling is_active on a Flask app that was never
# set up with this extension. Since this is somebody likely trying to install it,
# make sure they get a nice, helpful error message
test_app = Flask(__name__)
with test_app.test_request_context("/"):
self.assertRaises(AssertionError, feature_flags.is_active, "BOGUS_FEATURE_FLAG")
def test_running_default_handler_on_app_that_was_never_set_up_returns_false(self):
# This case should only happen if somebody's being especially creative, but
# I want to make sure it's well-behaved anyways.
test_app = Flask(__name__)
with test_app.test_request_context("/"):
self.assertRaises(feature_flags.NoFeatureFlagFound,
feature_flags.AppConfigFlagHandler, "BOGUS_FEATURE_FLAG")
|
Fix test to support NoFeatureFlagFound.
|
Fix test to support NoFeatureFlagFound.
|
Python
|
apache-2.0
|
iromli/Flask-FeatureFlags,trustrachel/Flask-FeatureFlags,jskulski/Flask-FeatureFlags
|
from __future__ import with_statement
import unittest
from flask import Flask
import flask_featureflags as feature_flags
class TestOutsideRequestContext(unittest.TestCase):
def test_checking_is_active_outside_request_context_returns_false(self):
self.assertFalse(feature_flags.is_active("BOGUS_FEATURE_FLAG"))
def test_default_handler_returns_false_outside_request_context(self):
self.assertFalse(feature_flags.AppConfigFlagHandler("BOGUS_FEATURE_FLAG"))
class TestBadlyConfiguredApplication(unittest.TestCase):
def test_checking_is_active_on_an_app_that_was_never_set_up_raises_assertion(self):
# This simulates somebody calling is_active on a Flask app that was never
# set up with this extension. Since this is somebody likely trying to install it,
# make sure they get a nice, helpful error message
test_app = Flask(__name__)
with test_app.test_request_context("/"):
self.assertRaises(AssertionError, feature_flags.is_active, "BOGUS_FEATURE_FLAG")
def test_running_default_handler_on_app_that_was_never_set_up_returns_false(self):
# This case should only happen if somebody's being especially creative, but
# I want to make sure it's well-behaved anyways.
test_app = Flask(__name__)
with test_app.test_request_context("/"):
self.assertFalse(feature_flags.AppConfigFlagHandler("BOGUS_FEATURE_FLAG"))
Fix test to support NoFeatureFlagFound.
|
from __future__ import with_statement
import unittest
from flask import Flask
import flask_featureflags as feature_flags
class TestOutsideRequestContext(unittest.TestCase):
def test_checking_is_active_outside_request_context_returns_false(self):
self.assertFalse(feature_flags.is_active("BOGUS_FEATURE_FLAG"))
def test_default_handler_returns_false_outside_request_context(self):
self.assertFalse(feature_flags.AppConfigFlagHandler("BOGUS_FEATURE_FLAG"))
class TestBadlyConfiguredApplication(unittest.TestCase):
def test_checking_is_active_on_an_app_that_was_never_set_up_raises_assertion(self):
# This simulates somebody calling is_active on a Flask app that was never
# set up with this extension. Since this is somebody likely trying to install it,
# make sure they get a nice, helpful error message
test_app = Flask(__name__)
with test_app.test_request_context("/"):
self.assertRaises(AssertionError, feature_flags.is_active, "BOGUS_FEATURE_FLAG")
def test_running_default_handler_on_app_that_was_never_set_up_returns_false(self):
# This case should only happen if somebody's being especially creative, but
# I want to make sure it's well-behaved anyways.
test_app = Flask(__name__)
with test_app.test_request_context("/"):
self.assertRaises(feature_flags.NoFeatureFlagFound,
feature_flags.AppConfigFlagHandler, "BOGUS_FEATURE_FLAG")
|
<commit_before>from __future__ import with_statement
import unittest
from flask import Flask
import flask_featureflags as feature_flags
class TestOutsideRequestContext(unittest.TestCase):
def test_checking_is_active_outside_request_context_returns_false(self):
self.assertFalse(feature_flags.is_active("BOGUS_FEATURE_FLAG"))
def test_default_handler_returns_false_outside_request_context(self):
self.assertFalse(feature_flags.AppConfigFlagHandler("BOGUS_FEATURE_FLAG"))
class TestBadlyConfiguredApplication(unittest.TestCase):
def test_checking_is_active_on_an_app_that_was_never_set_up_raises_assertion(self):
# This simulates somebody calling is_active on a Flask app that was never
# set up with this extension. Since this is somebody likely trying to install it,
# make sure they get a nice, helpful error message
test_app = Flask(__name__)
with test_app.test_request_context("/"):
self.assertRaises(AssertionError, feature_flags.is_active, "BOGUS_FEATURE_FLAG")
def test_running_default_handler_on_app_that_was_never_set_up_returns_false(self):
# This case should only happen if somebody's being especially creative, but
# I want to make sure it's well-behaved anyways.
test_app = Flask(__name__)
with test_app.test_request_context("/"):
self.assertFalse(feature_flags.AppConfigFlagHandler("BOGUS_FEATURE_FLAG"))
<commit_msg>Fix test to support NoFeatureFlagFound.<commit_after>
|
from __future__ import with_statement
import unittest
from flask import Flask
import flask_featureflags as feature_flags
class TestOutsideRequestContext(unittest.TestCase):
def test_checking_is_active_outside_request_context_returns_false(self):
self.assertFalse(feature_flags.is_active("BOGUS_FEATURE_FLAG"))
def test_default_handler_returns_false_outside_request_context(self):
self.assertFalse(feature_flags.AppConfigFlagHandler("BOGUS_FEATURE_FLAG"))
class TestBadlyConfiguredApplication(unittest.TestCase):
def test_checking_is_active_on_an_app_that_was_never_set_up_raises_assertion(self):
# This simulates somebody calling is_active on a Flask app that was never
# set up with this extension. Since this is somebody likely trying to install it,
# make sure they get a nice, helpful error message
test_app = Flask(__name__)
with test_app.test_request_context("/"):
self.assertRaises(AssertionError, feature_flags.is_active, "BOGUS_FEATURE_FLAG")
def test_running_default_handler_on_app_that_was_never_set_up_returns_false(self):
# This case should only happen if somebody's being especially creative, but
# I want to make sure it's well-behaved anyways.
test_app = Flask(__name__)
with test_app.test_request_context("/"):
self.assertRaises(feature_flags.NoFeatureFlagFound,
feature_flags.AppConfigFlagHandler, "BOGUS_FEATURE_FLAG")
|
from __future__ import with_statement
import unittest
from flask import Flask
import flask_featureflags as feature_flags
class TestOutsideRequestContext(unittest.TestCase):
def test_checking_is_active_outside_request_context_returns_false(self):
self.assertFalse(feature_flags.is_active("BOGUS_FEATURE_FLAG"))
def test_default_handler_returns_false_outside_request_context(self):
self.assertFalse(feature_flags.AppConfigFlagHandler("BOGUS_FEATURE_FLAG"))
class TestBadlyConfiguredApplication(unittest.TestCase):
def test_checking_is_active_on_an_app_that_was_never_set_up_raises_assertion(self):
# This simulates somebody calling is_active on a Flask app that was never
# set up with this extension. Since this is somebody likely trying to install it,
# make sure they get a nice, helpful error message
test_app = Flask(__name__)
with test_app.test_request_context("/"):
self.assertRaises(AssertionError, feature_flags.is_active, "BOGUS_FEATURE_FLAG")
def test_running_default_handler_on_app_that_was_never_set_up_returns_false(self):
# This case should only happen if somebody's being especially creative, but
# I want to make sure it's well-behaved anyways.
test_app = Flask(__name__)
with test_app.test_request_context("/"):
self.assertFalse(feature_flags.AppConfigFlagHandler("BOGUS_FEATURE_FLAG"))
Fix test to support NoFeatureFlagFound.from __future__ import with_statement
import unittest
from flask import Flask
import flask_featureflags as feature_flags
class TestOutsideRequestContext(unittest.TestCase):
def test_checking_is_active_outside_request_context_returns_false(self):
self.assertFalse(feature_flags.is_active("BOGUS_FEATURE_FLAG"))
def test_default_handler_returns_false_outside_request_context(self):
self.assertFalse(feature_flags.AppConfigFlagHandler("BOGUS_FEATURE_FLAG"))
class TestBadlyConfiguredApplication(unittest.TestCase):
def test_checking_is_active_on_an_app_that_was_never_set_up_raises_assertion(self):
# This simulates somebody calling is_active on a Flask app that was never
# set up with this extension. Since this is somebody likely trying to install it,
# make sure they get a nice, helpful error message
test_app = Flask(__name__)
with test_app.test_request_context("/"):
self.assertRaises(AssertionError, feature_flags.is_active, "BOGUS_FEATURE_FLAG")
def test_running_default_handler_on_app_that_was_never_set_up_returns_false(self):
# This case should only happen if somebody's being especially creative, but
# I want to make sure it's well-behaved anyways.
test_app = Flask(__name__)
with test_app.test_request_context("/"):
self.assertRaises(feature_flags.NoFeatureFlagFound,
feature_flags.AppConfigFlagHandler, "BOGUS_FEATURE_FLAG")
|
<commit_before>from __future__ import with_statement
import unittest
from flask import Flask
import flask_featureflags as feature_flags
class TestOutsideRequestContext(unittest.TestCase):
def test_checking_is_active_outside_request_context_returns_false(self):
self.assertFalse(feature_flags.is_active("BOGUS_FEATURE_FLAG"))
def test_default_handler_returns_false_outside_request_context(self):
self.assertFalse(feature_flags.AppConfigFlagHandler("BOGUS_FEATURE_FLAG"))
class TestBadlyConfiguredApplication(unittest.TestCase):
def test_checking_is_active_on_an_app_that_was_never_set_up_raises_assertion(self):
# This simulates somebody calling is_active on a Flask app that was never
# set up with this extension. Since this is somebody likely trying to install it,
# make sure they get a nice, helpful error message
test_app = Flask(__name__)
with test_app.test_request_context("/"):
self.assertRaises(AssertionError, feature_flags.is_active, "BOGUS_FEATURE_FLAG")
def test_running_default_handler_on_app_that_was_never_set_up_returns_false(self):
# This case should only happen if somebody's being especially creative, but
# I want to make sure it's well-behaved anyways.
test_app = Flask(__name__)
with test_app.test_request_context("/"):
self.assertFalse(feature_flags.AppConfigFlagHandler("BOGUS_FEATURE_FLAG"))
<commit_msg>Fix test to support NoFeatureFlagFound.<commit_after>from __future__ import with_statement
import unittest
from flask import Flask
import flask_featureflags as feature_flags
class TestOutsideRequestContext(unittest.TestCase):
def test_checking_is_active_outside_request_context_returns_false(self):
self.assertFalse(feature_flags.is_active("BOGUS_FEATURE_FLAG"))
def test_default_handler_returns_false_outside_request_context(self):
self.assertFalse(feature_flags.AppConfigFlagHandler("BOGUS_FEATURE_FLAG"))
class TestBadlyConfiguredApplication(unittest.TestCase):
def test_checking_is_active_on_an_app_that_was_never_set_up_raises_assertion(self):
# This simulates somebody calling is_active on a Flask app that was never
# set up with this extension. Since this is somebody likely trying to install it,
# make sure they get a nice, helpful error message
test_app = Flask(__name__)
with test_app.test_request_context("/"):
self.assertRaises(AssertionError, feature_flags.is_active, "BOGUS_FEATURE_FLAG")
def test_running_default_handler_on_app_that_was_never_set_up_returns_false(self):
# This case should only happen if somebody's being especially creative, but
# I want to make sure it's well-behaved anyways.
test_app = Flask(__name__)
with test_app.test_request_context("/"):
self.assertRaises(feature_flags.NoFeatureFlagFound,
feature_flags.AppConfigFlagHandler, "BOGUS_FEATURE_FLAG")
|
640d5de356d58b80f4d6ebb1c503ce88e144ea90
|
core/models.py
|
core/models.py
|
from django.db import models
class Price(models.Model):
price = models.PositiveIntegerField()
datetime = models.DateTimeField()
|
from django.db import models
class Price(models.Model):
price = models.PositiveIntegerField()
datetime = models.DateTimeField()
@property
def price_float(self):
return self.price / 1000.0
@price_float.setter
def price_float(self, price):
self.price = round(price * 1000)
|
Add property for converting price float to integer
|
Add property for converting price float to integer
|
Python
|
unlicense
|
kvikshaug/btc.kvikshaug.no,kvikshaug/btc.kvikshaug.no,kvikshaug/btc.kvikshaug.no,kvikshaug/btc.kvikshaug.no
|
from django.db import models
class Price(models.Model):
price = models.PositiveIntegerField()
datetime = models.DateTimeField()
Add property for converting price float to integer
|
from django.db import models
class Price(models.Model):
price = models.PositiveIntegerField()
datetime = models.DateTimeField()
@property
def price_float(self):
return self.price / 1000.0
@price_float.setter
def price_float(self, price):
self.price = round(price * 1000)
|
<commit_before>from django.db import models
class Price(models.Model):
price = models.PositiveIntegerField()
datetime = models.DateTimeField()
<commit_msg>Add property for converting price float to integer<commit_after>
|
from django.db import models
class Price(models.Model):
price = models.PositiveIntegerField()
datetime = models.DateTimeField()
@property
def price_float(self):
return self.price / 1000.0
@price_float.setter
def price_float(self, price):
self.price = round(price * 1000)
|
from django.db import models
class Price(models.Model):
price = models.PositiveIntegerField()
datetime = models.DateTimeField()
Add property for converting price float to integerfrom django.db import models
class Price(models.Model):
price = models.PositiveIntegerField()
datetime = models.DateTimeField()
@property
def price_float(self):
return self.price / 1000.0
@price_float.setter
def price_float(self, price):
self.price = round(price * 1000)
|
<commit_before>from django.db import models
class Price(models.Model):
price = models.PositiveIntegerField()
datetime = models.DateTimeField()
<commit_msg>Add property for converting price float to integer<commit_after>from django.db import models
class Price(models.Model):
price = models.PositiveIntegerField()
datetime = models.DateTimeField()
@property
def price_float(self):
return self.price / 1000.0
@price_float.setter
def price_float(self, price):
self.price = round(price * 1000)
|
d720d58ef9e140460cad0dc90f7d43f384d031e1
|
djangosaml2/urls.py
|
djangosaml2/urls.py
|
# Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es)
# Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.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 django.conf.urls.defaults import patterns, handler500, url
urlpatterns = patterns(
'djangosaml2.views',
url(r'^login/$', 'login', name='saml2_login'),
url(r'^acs/$', 'assertion_consumer_service', name='saml2_acs'),
url(r'^logout/$', 'logout', name='saml2_logout'),
url(r'^ls/$', 'logout_service', name='saml2_ls'),
url(r'^metadata/$', 'metadata', name='saml2_metadata'),
)
handler500 = handler500
|
# Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es)
# Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.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.
try:
from django.conf.urls import patterns, handler500, url
# Fallback for Django versions < 1.4
except ImportError:
from django.conf.urls.defaults import patterns, handler500, url
urlpatterns = patterns(
'djangosaml2.views',
url(r'^login/$', 'login', name='saml2_login'),
url(r'^acs/$', 'assertion_consumer_service', name='saml2_acs'),
url(r'^logout/$', 'logout', name='saml2_logout'),
url(r'^ls/$', 'logout_service', name='saml2_ls'),
url(r'^metadata/$', 'metadata', name='saml2_metadata'),
)
handler500 = handler500
|
Fix imports for Django 1.6 and above
|
Fix imports for Django 1.6 and above
|
Python
|
apache-2.0
|
kradalby/djangosaml2,kradalby/djangosaml2
|
# Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es)
# Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.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 django.conf.urls.defaults import patterns, handler500, url
urlpatterns = patterns(
'djangosaml2.views',
url(r'^login/$', 'login', name='saml2_login'),
url(r'^acs/$', 'assertion_consumer_service', name='saml2_acs'),
url(r'^logout/$', 'logout', name='saml2_logout'),
url(r'^ls/$', 'logout_service', name='saml2_ls'),
url(r'^metadata/$', 'metadata', name='saml2_metadata'),
)
handler500 = handler500
Fix imports for Django 1.6 and above
|
# Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es)
# Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.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.
try:
from django.conf.urls import patterns, handler500, url
# Fallback for Django versions < 1.4
except ImportError:
from django.conf.urls.defaults import patterns, handler500, url
urlpatterns = patterns(
'djangosaml2.views',
url(r'^login/$', 'login', name='saml2_login'),
url(r'^acs/$', 'assertion_consumer_service', name='saml2_acs'),
url(r'^logout/$', 'logout', name='saml2_logout'),
url(r'^ls/$', 'logout_service', name='saml2_ls'),
url(r'^metadata/$', 'metadata', name='saml2_metadata'),
)
handler500 = handler500
|
<commit_before># Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es)
# Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.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 django.conf.urls.defaults import patterns, handler500, url
urlpatterns = patterns(
'djangosaml2.views',
url(r'^login/$', 'login', name='saml2_login'),
url(r'^acs/$', 'assertion_consumer_service', name='saml2_acs'),
url(r'^logout/$', 'logout', name='saml2_logout'),
url(r'^ls/$', 'logout_service', name='saml2_ls'),
url(r'^metadata/$', 'metadata', name='saml2_metadata'),
)
handler500 = handler500
<commit_msg>Fix imports for Django 1.6 and above<commit_after>
|
# Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es)
# Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.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.
try:
from django.conf.urls import patterns, handler500, url
# Fallback for Django versions < 1.4
except ImportError:
from django.conf.urls.defaults import patterns, handler500, url
urlpatterns = patterns(
'djangosaml2.views',
url(r'^login/$', 'login', name='saml2_login'),
url(r'^acs/$', 'assertion_consumer_service', name='saml2_acs'),
url(r'^logout/$', 'logout', name='saml2_logout'),
url(r'^ls/$', 'logout_service', name='saml2_ls'),
url(r'^metadata/$', 'metadata', name='saml2_metadata'),
)
handler500 = handler500
|
# Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es)
# Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.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 django.conf.urls.defaults import patterns, handler500, url
urlpatterns = patterns(
'djangosaml2.views',
url(r'^login/$', 'login', name='saml2_login'),
url(r'^acs/$', 'assertion_consumer_service', name='saml2_acs'),
url(r'^logout/$', 'logout', name='saml2_logout'),
url(r'^ls/$', 'logout_service', name='saml2_ls'),
url(r'^metadata/$', 'metadata', name='saml2_metadata'),
)
handler500 = handler500
Fix imports for Django 1.6 and above# Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es)
# Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.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.
try:
from django.conf.urls import patterns, handler500, url
# Fallback for Django versions < 1.4
except ImportError:
from django.conf.urls.defaults import patterns, handler500, url
urlpatterns = patterns(
'djangosaml2.views',
url(r'^login/$', 'login', name='saml2_login'),
url(r'^acs/$', 'assertion_consumer_service', name='saml2_acs'),
url(r'^logout/$', 'logout', name='saml2_logout'),
url(r'^ls/$', 'logout_service', name='saml2_ls'),
url(r'^metadata/$', 'metadata', name='saml2_metadata'),
)
handler500 = handler500
|
<commit_before># Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es)
# Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.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 django.conf.urls.defaults import patterns, handler500, url
urlpatterns = patterns(
'djangosaml2.views',
url(r'^login/$', 'login', name='saml2_login'),
url(r'^acs/$', 'assertion_consumer_service', name='saml2_acs'),
url(r'^logout/$', 'logout', name='saml2_logout'),
url(r'^ls/$', 'logout_service', name='saml2_ls'),
url(r'^metadata/$', 'metadata', name='saml2_metadata'),
)
handler500 = handler500
<commit_msg>Fix imports for Django 1.6 and above<commit_after># Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es)
# Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.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.
try:
from django.conf.urls import patterns, handler500, url
# Fallback for Django versions < 1.4
except ImportError:
from django.conf.urls.defaults import patterns, handler500, url
urlpatterns = patterns(
'djangosaml2.views',
url(r'^login/$', 'login', name='saml2_login'),
url(r'^acs/$', 'assertion_consumer_service', name='saml2_acs'),
url(r'^logout/$', 'logout', name='saml2_logout'),
url(r'^ls/$', 'logout_service', name='saml2_ls'),
url(r'^metadata/$', 'metadata', name='saml2_metadata'),
)
handler500 = handler500
|
63bb771df22c73d2e45e6577a01bf4e4a7c60dc6
|
bumblebee/modules/arch-update.py
|
bumblebee/modules/arch-update.py
|
"""Check updates to Arch Linux."""
import subprocess
import bumblebee.input
import bumblebee.output
import bumblebee.engine
class Module(bumblebee.engine.Module):
def __init__(self, engine, config):
widget = bumblebee.output.Widget(full_text=self.utilization)
super(Module, self).__init__(engine, config, widget)
self.packages = self.check_updates()
def check_updates(self):
p = subprocess.Popen(
"checkupdates", stdout=subprocess.PIPE, shell=True)
p_status = p.wait()
if p_status == 0:
(output, err) = p.communicate()
output = output.decode('utf-8')
packages = output.split('\n')
packages.pop()
return len(packages)
return '0'
def utilization(self, widget):
return f'Update Arch: {self.packages}'
def hidden(self):
return self.check_updates() == 0
def update(self, widgets):
self.packages = self.check_updates()
def state(self, widget):
return self.threshold_state(self.packages, 1, 100)
|
"""Check updates to Arch Linux."""
import subprocess
import bumblebee.input
import bumblebee.output
import bumblebee.engine
class Module(bumblebee.engine.Module):
def __init__(self, engine, config):
widget = bumblebee.output.Widget(full_text=self.utilization)
super(Module, self).__init__(engine, config, widget)
self.packages = self.check_updates()
def check_updates(self):
p = subprocess.Popen(
"checkupdates", stdout=subprocess.PIPE, shell=True)
p_status = p.wait()
if p_status == 0:
(output, err) = p.communicate()
output = output.decode('utf-8')
packages = output.split('\n')
packages.pop()
return len(packages)
return '0'
def utilization(self, widget):
return 'Update Arch: {}'.format(self.packages)
def hidden(self):
return self.check_updates() == 0
def update(self, widgets):
self.packages = self.check_updates()
def state(self, widget):
return self.threshold_state(self.packages, 1, 100)
|
Fix for previous versions of python
|
Fix for previous versions of python
|
Python
|
mit
|
tobi-wan-kenobi/bumblebee-status,tobi-wan-kenobi/bumblebee-status
|
"""Check updates to Arch Linux."""
import subprocess
import bumblebee.input
import bumblebee.output
import bumblebee.engine
class Module(bumblebee.engine.Module):
def __init__(self, engine, config):
widget = bumblebee.output.Widget(full_text=self.utilization)
super(Module, self).__init__(engine, config, widget)
self.packages = self.check_updates()
def check_updates(self):
p = subprocess.Popen(
"checkupdates", stdout=subprocess.PIPE, shell=True)
p_status = p.wait()
if p_status == 0:
(output, err) = p.communicate()
output = output.decode('utf-8')
packages = output.split('\n')
packages.pop()
return len(packages)
return '0'
def utilization(self, widget):
return f'Update Arch: {self.packages}'
def hidden(self):
return self.check_updates() == 0
def update(self, widgets):
self.packages = self.check_updates()
def state(self, widget):
return self.threshold_state(self.packages, 1, 100)
Fix for previous versions of python
|
"""Check updates to Arch Linux."""
import subprocess
import bumblebee.input
import bumblebee.output
import bumblebee.engine
class Module(bumblebee.engine.Module):
def __init__(self, engine, config):
widget = bumblebee.output.Widget(full_text=self.utilization)
super(Module, self).__init__(engine, config, widget)
self.packages = self.check_updates()
def check_updates(self):
p = subprocess.Popen(
"checkupdates", stdout=subprocess.PIPE, shell=True)
p_status = p.wait()
if p_status == 0:
(output, err) = p.communicate()
output = output.decode('utf-8')
packages = output.split('\n')
packages.pop()
return len(packages)
return '0'
def utilization(self, widget):
return 'Update Arch: {}'.format(self.packages)
def hidden(self):
return self.check_updates() == 0
def update(self, widgets):
self.packages = self.check_updates()
def state(self, widget):
return self.threshold_state(self.packages, 1, 100)
|
<commit_before>"""Check updates to Arch Linux."""
import subprocess
import bumblebee.input
import bumblebee.output
import bumblebee.engine
class Module(bumblebee.engine.Module):
def __init__(self, engine, config):
widget = bumblebee.output.Widget(full_text=self.utilization)
super(Module, self).__init__(engine, config, widget)
self.packages = self.check_updates()
def check_updates(self):
p = subprocess.Popen(
"checkupdates", stdout=subprocess.PIPE, shell=True)
p_status = p.wait()
if p_status == 0:
(output, err) = p.communicate()
output = output.decode('utf-8')
packages = output.split('\n')
packages.pop()
return len(packages)
return '0'
def utilization(self, widget):
return f'Update Arch: {self.packages}'
def hidden(self):
return self.check_updates() == 0
def update(self, widgets):
self.packages = self.check_updates()
def state(self, widget):
return self.threshold_state(self.packages, 1, 100)
<commit_msg>Fix for previous versions of python<commit_after>
|
"""Check updates to Arch Linux."""
import subprocess
import bumblebee.input
import bumblebee.output
import bumblebee.engine
class Module(bumblebee.engine.Module):
def __init__(self, engine, config):
widget = bumblebee.output.Widget(full_text=self.utilization)
super(Module, self).__init__(engine, config, widget)
self.packages = self.check_updates()
def check_updates(self):
p = subprocess.Popen(
"checkupdates", stdout=subprocess.PIPE, shell=True)
p_status = p.wait()
if p_status == 0:
(output, err) = p.communicate()
output = output.decode('utf-8')
packages = output.split('\n')
packages.pop()
return len(packages)
return '0'
def utilization(self, widget):
return 'Update Arch: {}'.format(self.packages)
def hidden(self):
return self.check_updates() == 0
def update(self, widgets):
self.packages = self.check_updates()
def state(self, widget):
return self.threshold_state(self.packages, 1, 100)
|
"""Check updates to Arch Linux."""
import subprocess
import bumblebee.input
import bumblebee.output
import bumblebee.engine
class Module(bumblebee.engine.Module):
def __init__(self, engine, config):
widget = bumblebee.output.Widget(full_text=self.utilization)
super(Module, self).__init__(engine, config, widget)
self.packages = self.check_updates()
def check_updates(self):
p = subprocess.Popen(
"checkupdates", stdout=subprocess.PIPE, shell=True)
p_status = p.wait()
if p_status == 0:
(output, err) = p.communicate()
output = output.decode('utf-8')
packages = output.split('\n')
packages.pop()
return len(packages)
return '0'
def utilization(self, widget):
return f'Update Arch: {self.packages}'
def hidden(self):
return self.check_updates() == 0
def update(self, widgets):
self.packages = self.check_updates()
def state(self, widget):
return self.threshold_state(self.packages, 1, 100)
Fix for previous versions of python"""Check updates to Arch Linux."""
import subprocess
import bumblebee.input
import bumblebee.output
import bumblebee.engine
class Module(bumblebee.engine.Module):
def __init__(self, engine, config):
widget = bumblebee.output.Widget(full_text=self.utilization)
super(Module, self).__init__(engine, config, widget)
self.packages = self.check_updates()
def check_updates(self):
p = subprocess.Popen(
"checkupdates", stdout=subprocess.PIPE, shell=True)
p_status = p.wait()
if p_status == 0:
(output, err) = p.communicate()
output = output.decode('utf-8')
packages = output.split('\n')
packages.pop()
return len(packages)
return '0'
def utilization(self, widget):
return 'Update Arch: {}'.format(self.packages)
def hidden(self):
return self.check_updates() == 0
def update(self, widgets):
self.packages = self.check_updates()
def state(self, widget):
return self.threshold_state(self.packages, 1, 100)
|
<commit_before>"""Check updates to Arch Linux."""
import subprocess
import bumblebee.input
import bumblebee.output
import bumblebee.engine
class Module(bumblebee.engine.Module):
def __init__(self, engine, config):
widget = bumblebee.output.Widget(full_text=self.utilization)
super(Module, self).__init__(engine, config, widget)
self.packages = self.check_updates()
def check_updates(self):
p = subprocess.Popen(
"checkupdates", stdout=subprocess.PIPE, shell=True)
p_status = p.wait()
if p_status == 0:
(output, err) = p.communicate()
output = output.decode('utf-8')
packages = output.split('\n')
packages.pop()
return len(packages)
return '0'
def utilization(self, widget):
return f'Update Arch: {self.packages}'
def hidden(self):
return self.check_updates() == 0
def update(self, widgets):
self.packages = self.check_updates()
def state(self, widget):
return self.threshold_state(self.packages, 1, 100)
<commit_msg>Fix for previous versions of python<commit_after>"""Check updates to Arch Linux."""
import subprocess
import bumblebee.input
import bumblebee.output
import bumblebee.engine
class Module(bumblebee.engine.Module):
def __init__(self, engine, config):
widget = bumblebee.output.Widget(full_text=self.utilization)
super(Module, self).__init__(engine, config, widget)
self.packages = self.check_updates()
def check_updates(self):
p = subprocess.Popen(
"checkupdates", stdout=subprocess.PIPE, shell=True)
p_status = p.wait()
if p_status == 0:
(output, err) = p.communicate()
output = output.decode('utf-8')
packages = output.split('\n')
packages.pop()
return len(packages)
return '0'
def utilization(self, widget):
return 'Update Arch: {}'.format(self.packages)
def hidden(self):
return self.check_updates() == 0
def update(self, widgets):
self.packages = self.check_updates()
def state(self, widget):
return self.threshold_state(self.packages, 1, 100)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.