commit stringlengths 40 40 | old_file stringlengths 4 150 | new_file stringlengths 4 150 | old_contents stringlengths 0 3.26k | new_contents stringlengths 1 4.43k | subject stringlengths 15 501 | message stringlengths 15 4.06k | lang stringclasses 4 values | license stringclasses 13 values | repos stringlengths 5 91.5k | diff stringlengths 0 4.35k |
|---|---|---|---|---|---|---|---|---|---|---|
b729b8bb5a3b65b6e8c09455b0db21e7df59dd8a | setup.py | setup.py | from setuptools import setup, find_packages
with open('README.rst') as readme:
description = readme.read()
setup(
name='mfl',
version='2.0.0',
description='Master falicity list',
long_description=(description),
author='Savannah Developers',
author_email='developers@savannahinformatics.com',
url='',
packages=find_packages(),
install_requires=[
"django>=1.8",
"Fabric>=1.10",
"coverage>=3.7",
"psycopg2>=2.5",
"djangorestframework>=3.1",
"django-filter>=0.9",
"flake8>=2.3",
"django-cors-headers>=1.0",
"virtualenv>=12.0",
"pip>=6.0",
"tox>=1.9",
"djangorestframework-xml>=1.0",
"djangorestframework-csv>=1.3",
"model_mommy>=1.2"
],
)
| from setuptools import setup, find_packages
with open('README.rst') as readme:
description = readme.read()
setup(
name='mfl',
version='2.0.0',
description='Master falicity list',
long_description=(description),
author='Savannah Developers',
author_email='developers@savannahinformatics.com',
url='',
packages=find_packages(),
install_requires=[
"model_mommy>=1.2",
"Fabric>=1.10",
"coverage>=3.7",
"psycopg2>=2.5",
"djangorestframework>=3.1",
"django-filter>=0.9",
"flake8>=2.3",
"django-cors-headers>=1.0",
"virtualenv>=12.0",
"pip>=6.0",
"tox>=1.9",
"djangorestframework-xml>=1.0",
"djangorestframework-csv>=1.3",
"django>=1.8",
],
)
| Fix model_mommy issues with django==1.8 | Fix model_mommy issues with django==1.8
| Python | mit | urandu/mfl_api,MasterFacilityList/mfl_api,urandu/mfl_api,urandu/mfl_api,MasterFacilityList/mfl_api,MasterFacilityList/mfl_api,MasterFacilityList/mfl_api,MasterFacilityList/mfl_api,urandu/mfl_api | ---
+++
@@ -14,7 +14,7 @@
url='',
packages=find_packages(),
install_requires=[
- "django>=1.8",
+ "model_mommy>=1.2",
"Fabric>=1.10",
"coverage>=3.7",
"psycopg2>=2.5",
@@ -27,6 +27,6 @@
"tox>=1.9",
"djangorestframework-xml>=1.0",
"djangorestframework-csv>=1.3",
- "model_mommy>=1.2"
+ "django>=1.8",
],
) |
dfb53cd63c908f13dafcc159ce337af653523748 | datasets/forms.py | datasets/forms.py | from django import forms
from datasets.models import DatasetRelease, CategoryComment
class DatasetReleaseForm(forms.ModelForm):
max_number_of_sounds = forms.IntegerField(required=False)
class Meta:
model = DatasetRelease
fields = ['release_tag', 'type']
class PresentNotPresentUnsureForm(forms.Form):
vote = forms.ChoiceField(
required=True,
widget=forms.RadioSelect,
choices=(
('1', 'Present and predominant',),
('0.5', 'Present but not predominant',),
('-1', 'Not Present',),
('0', 'Unsure',),
),
)
annotation_id = forms.IntegerField(
required=True,
widget=forms.HiddenInput,
)
visited_sound = forms.BooleanField(
required=False,
initial=False,
widget=forms.HiddenInput,
)
class CategoryCommentForm(forms.ModelForm):
class Meta:
model = CategoryComment
fields = ['comment', 'category_id', 'dataset']
widgets = {
'comment': forms.Textarea(attrs={
'cols': 80, 'rows': 3,
'placeholder': 'Add here any general comments you want to make about this category'}),
'category_id': forms.HiddenInput,
'dataset_id': forms.HiddenInput,
}
| from django import forms
from datasets.models import DatasetRelease, CategoryComment
class DatasetReleaseForm(forms.ModelForm):
max_number_of_sounds = forms.IntegerField(required=False)
class Meta:
model = DatasetRelease
fields = ['release_tag', 'type']
class PresentNotPresentUnsureForm(forms.Form):
vote = forms.ChoiceField(
required=True,
widget=forms.RadioSelect,
choices=(
('1', 'Present and predominant',),
('0.5', 'Present but not predominant',),
('-1', 'Not present',),
('0', 'Unsure',),
),
)
annotation_id = forms.IntegerField(
required=True,
widget=forms.HiddenInput,
)
visited_sound = forms.BooleanField(
required=False,
initial=False,
widget=forms.HiddenInput,
)
class CategoryCommentForm(forms.ModelForm):
class Meta:
model = CategoryComment
fields = ['comment', 'category_id', 'dataset']
widgets = {
'comment': forms.Textarea(attrs={
'cols': 80, 'rows': 3,
'placeholder': 'Add here any general comments you want to make about this category'}),
'category_id': forms.HiddenInput,
'dataset_id': forms.HiddenInput,
}
| Remove upper case Not Present | Remove upper case Not Present
| Python | agpl-3.0 | MTG/freesound-datasets,MTG/freesound-datasets,MTG/freesound-datasets,MTG/freesound-datasets | ---
+++
@@ -17,7 +17,7 @@
choices=(
('1', 'Present and predominant',),
('0.5', 'Present but not predominant',),
- ('-1', 'Not Present',),
+ ('-1', 'Not present',),
('0', 'Unsure',),
),
) |
bd7cab646b6ead140b62ed19b5378567c76bad9d | setup.py | setup.py | import os
from setuptools import setup
def read(name):
return open(os.path.join(os.path.dirname(__file__), name)).read()
setup(
name='python-dxf',
version='7.5.0',
description="Package for accessing a Docker v2 registry",
long_description=read('README.rst'),
keywords='docker registry',
author='David Halls',
author_email='dave@davedoesdev.com',
url='https://github.com/davedoesdev/dxf',
license='MIT',
packages=['dxf'],
entry_points={'console_scripts': ['dxf=dxf.main:main']},
install_requires=['www-authenticate>=0.9.2',
'requests>=2.18.4',
'jwcrypto>=0.4.2',
'tqdm>=4.19.4']
)
| import io
import os
from setuptools import setup
def read(name):
file_path = os.path.join(os.path.dirname(__file__), name)
return io.open(file_path, encoding='utf8').read()
setup(
name='python-dxf',
version='7.5.0',
description="Package for accessing a Docker v2 registry",
long_description=read('README.rst'),
keywords='docker registry',
author='David Halls',
author_email='dave@davedoesdev.com',
url='https://github.com/davedoesdev/dxf',
license='MIT',
packages=['dxf'],
entry_points={'console_scripts': ['dxf=dxf.main:main']},
install_requires=['www-authenticate>=0.9.2',
'requests>=2.18.4',
'jwcrypto>=0.4.2',
'tqdm>=4.19.4']
)
| Fix UnicodeDecodeError error when installing | Fix UnicodeDecodeError error when installing
Fix UnicodeDecodeError raised when attempting to install in non-English
systems (e.g. Windows 10 Korean).
| Python | mit | davedoesdev/dxf,davedoesdev/dxf,davedoesdev/dxf,davedoesdev/dxf | ---
+++
@@ -1,8 +1,10 @@
+import io
import os
from setuptools import setup
def read(name):
- return open(os.path.join(os.path.dirname(__file__), name)).read()
+ file_path = os.path.join(os.path.dirname(__file__), name)
+ return io.open(file_path, encoding='utf8').read()
setup(
name='python-dxf', |
816e77d6cb5321b57cbccfed56d01cbfbd058aa1 | setup.py | setup.py | # Uploading package to PyPi.
from setuptools import setup
setup(name='schoolopy',
version='0.1.0',
description='A Python wrapper for Schoology\'s API.',
url='https://github.com/ErikBoesen/schoolopy',
author='Erik Boesen',
author_email='me@erikboesen.com',
license='MIT',
packages=['schoolopy'],
install_requires=['requests', 'requests-oauthlib', 'oauthlib'],
zip_safe=False)
| # Uploading package to PyPi.
from setuptools import setup
setup(name='schoolopy',
version='0.2.0',
description='A Python wrapper for Schoology\'s API.',
url='https://github.com/ErikBoesen/schoolopy',
author='Erik Boesen',
author_email='me@erikboesen.com',
license='MIT',
packages=['schoolopy'],
install_requires=['requests', 'requests-oauthlib', 'oauthlib'],
zip_safe=False)
| Increment version for PyPI upload | Increment version for PyPI upload
| Python | mit | ErikBoesen/schoolopy | ---
+++
@@ -3,7 +3,7 @@
from setuptools import setup
setup(name='schoolopy',
- version='0.1.0',
+ version='0.2.0',
description='A Python wrapper for Schoology\'s API.',
url='https://github.com/ErikBoesen/schoolopy',
author='Erik Boesen', |
eb0ffe3da8b25a4d673b543faeef169279c63919 | python/hxActor/main.py | python/hxActor/main.py | #!/usr/bin/env python
import actorcore.ICC
class OurActor(actorcore.ICC.ICC):
def __init__(self, name,
productName=None, configFile=None,
modelNames=(),
debugLevel=30):
""" Setup an Actor instance. See help for actorcore.Actor for details. """
# This sets up the connections to/from the hub, the logger, and the twisted reactor.
#
actorcore.ICC.ICC.__init__(self, name,
productName=productName,
configFile=configFile,
modelNames=modelNames)
#
# To work
def main():
theActor = OurActor('hx', productName='hxActor')
theActor.run()
if __name__ == '__main__':
main()
| #!/usr/bin/env python
import actorcore.ICC
class OurActor(actorcore.ICC.ICC):
def __init__(self, name,
productName=None, configFile=None,
modelNames=('charis', 'hx'),
debugLevel=30):
""" Setup an Actor instance. See help for actorcore.Actor for details. """
# This sets up the connections to/from the hub, the logger, and the twisted reactor.
#
actorcore.ICC.ICC.__init__(self, name,
productName=productName,
configFile=configFile,
modelNames=modelNames)
#
# To work
def main():
theActor = OurActor('hx', productName='hxActor')
theActor.run()
if __name__ == '__main__':
main()
| Add model listeners for headers. | Add model listeners for headers.
| Python | mit | CraigLoomis/ics_hxActor,CraigLoomis/ics_hxActor | ---
+++
@@ -5,7 +5,7 @@
class OurActor(actorcore.ICC.ICC):
def __init__(self, name,
productName=None, configFile=None,
- modelNames=(),
+ modelNames=('charis', 'hx'),
debugLevel=30):
""" Setup an Actor instance. See help for actorcore.Actor for details. """ |
7f3f2802fb3c00baf440ebdc10920ad0b48118f9 | setup.py | setup.py | import codecs
from setuptools import find_packages
from setuptools import setup
import sys
install_requires = [
'cached-property',
'chainer>=2.0.0',
'future',
'gym>=0.9.7',
'numpy>=1.10.4',
'pillow',
'scipy',
]
test_requires = [
'pytest',
]
if sys.version_info < (3, 2):
install_requires.append('fastcache')
if sys.version_info < (3, 4):
install_requires.append('statistics')
if sys.version_info < (3, 5):
install_requires.append('funcsigs')
setup(name='chainerrl',
version='0.7.0',
description='ChainerRL, a deep reinforcement learning library',
long_description=codecs.open('README.md', 'r', encoding='utf-8').read(),
long_description_content_type='text/markdown',
author='Yasuhiro Fujita',
author_email='fujita@preferred.jp',
license='MIT License',
packages=find_packages(),
install_requires=install_requires,
test_requires=test_requires)
| import codecs
from setuptools import find_packages
from setuptools import setup
import sys
install_requires = [
'cached-property',
'chainer>=2.0.0',
'future',
'gym>=0.9.7',
'numpy>=1.10.4',
'pillow',
'scipy',
]
test_requires = [
'pytest',
'attrs<19.2.0', # pytest does not run with attrs==19.2.0 (https://github.com/pytest-dev/pytest/issues/3280) # NOQA
]
if sys.version_info < (3, 2):
install_requires.append('fastcache')
if sys.version_info < (3, 4):
install_requires.append('statistics')
if sys.version_info < (3, 5):
install_requires.append('funcsigs')
setup(name='chainerrl',
version='0.7.0',
description='ChainerRL, a deep reinforcement learning library',
long_description=codecs.open('README.md', 'r', encoding='utf-8').read(),
long_description_content_type='text/markdown',
author='Yasuhiro Fujita',
author_email='fujita@preferred.jp',
license='MIT License',
packages=find_packages(),
install_requires=install_requires,
test_requires=test_requires)
| Use attrs<19.2.0 to avoid pytest error | Use attrs<19.2.0 to avoid pytest error
| Python | mit | toslunar/chainerrl,toslunar/chainerrl | ---
+++
@@ -15,6 +15,7 @@
test_requires = [
'pytest',
+ 'attrs<19.2.0', # pytest does not run with attrs==19.2.0 (https://github.com/pytest-dev/pytest/issues/3280) # NOQA
]
if sys.version_info < (3, 2): |
ccd5dce9b4e2392abdf205d2913736a6ce47ae0b | setup.py | setup.py | #!/usr/bin/env python
"""
DJ-Database-URL
===============
This simple Django utility allows you to utilize the
`12factor <http://www.12factor.net/backing-services>`_ inspired
``REDIS_URL`` environment variable to configure your Django application.
Usage
-----
Configure your Redis database in ``settings.py`` from ``REDIS_URL``::
REDIS = {"default": dj_redis_url.config()}
Parse an arbitrary Database URL::
REDIS = {"default": dj_redis_url.parse("redis://..."")}
Installation
------------
Installation is simple too::
$ pip install dj-redis-url
"""
from setuptools import setup, find_packages
setup(
name="dj-redis-url",
version="0.1.2",
description="Use Redis URLs in your Django Application.",
long_description=__doc__,
url="https://github.com/dstufft/dj-redis-url",
author="Donald Stufft",
author_email="donald.stufft@gmail.com",
extras_require={
"tests": ["pytest"],
},
packages=find_packages(exclude=["tests"]),
package_data={"": ["LICENSE"]},
include_package_data=True,
zip_safe=False,
)
| #!/usr/bin/env python
"""
DJ-Database-URL
===============
This simple Django utility allows you to utilize the
`12factor <http://www.12factor.net/backing-services>`_ inspired
``REDIS_URL`` environment variable to configure your Django application.
Usage
-----
Configure your Redis database in ``settings.py`` from ``REDIS_URL``::
REDIS = {"default": dj_redis_url.config()}
Parse an arbitrary Database URL::
REDIS = {"default": dj_redis_url.parse("redis://..."")}
Installation
------------
Installation is simple too::
$ pip install dj-redis-url
"""
from setuptools import setup
setup(
name="dj-redis-url",
version="0.1.2",
description="Use Redis URLs in your Django Application.",
long_description=__doc__,
url="https://github.com/dstufft/dj-redis-url",
author="Donald Stufft",
author_email="donald.stufft@gmail.com",
extras_require={
"tests": ["pytest"],
},
py_modules=["dj_redis_url"],
include_package_data=True,
zip_safe=False,
)
| Switch from packages to modules | Switch from packages to modules
| Python | bsd-2-clause | dstufft/dj-redis-url | ---
+++
@@ -26,7 +26,7 @@
$ pip install dj-redis-url
"""
-from setuptools import setup, find_packages
+from setuptools import setup
setup(
name="dj-redis-url",
@@ -43,8 +43,7 @@
"tests": ["pytest"],
},
- packages=find_packages(exclude=["tests"]),
- package_data={"": ["LICENSE"]},
+ py_modules=["dj_redis_url"],
include_package_data=True,
zip_safe=False, |
df9379a370163ac0d9ca3daf99745c1d1fb7dc19 | setup.py | setup.py | from setuptools import setup, find_packages
from codecs import open
from os import path
_HERE = path.abspath(path.dirname(__file__))
def read(*names, **kwds):
return open(
path.join(_HERE, *names),
encoding=kwds.get('encoding', 'utf-8')
).read()
def find_version(*file_paths):
import re
version_file = read(*file_paths)
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find vresion string.")
setup(
name='wmtexe',
version=find_version("wmtexe/__init__.py"),
description='WMT execution server.',
long_description=read('README.md'),
url='https://github.com/csdms/wmt-exe',
author='Eric Hutton',
author_email='hutton.eric@gmail.com',
license='MIT',
packages=find_packages(),
entry_points={
'console_scripts': [
'wmt-slave=wmtexe.slave:main',
],
},
)
| from setuptools import setup, find_packages
from codecs import open
from os import path
_HERE = path.abspath(path.dirname(__file__))
def read(*names, **kwds):
return open(
path.join(_HERE, *names),
encoding=kwds.get('encoding', 'utf-8')
).read()
def find_version(*file_paths):
import re
version_file = read(*file_paths)
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find vresion string.")
setup(
name='wmtexe',
version=find_version("wmtexe/__init__.py"),
description='WMT execution server.',
long_description=read('README.md'),
url='https://github.com/csdms/wmt-exe',
author='Eric Hutton',
author_email='hutton.eric@gmail.com',
license='MIT',
packages=find_packages(),
entry_points={
'console_scripts': [
'wmt-slave=wmtexe.slave:main',
],
'distutils.commands': [
'configure = wmtexe.configure:Configure',
],
},
)
| Use the new configure command. | Use the new configure command.
| Python | mit | csdms/wmt-exe,csdms/wmt-exe,csdms/wmt-exe,csdms/wmt-exe | ---
+++
@@ -4,7 +4,6 @@
_HERE = path.abspath(path.dirname(__file__))
-
def read(*names, **kwds):
return open(
@@ -42,5 +41,8 @@
'console_scripts': [
'wmt-slave=wmtexe.slave:main',
],
+ 'distutils.commands': [
+ 'configure = wmtexe.configure:Configure',
+ ],
},
) |
8a8d5bfa1d091f2c701196f58fdf10bfb228d9b5 | setup.py | setup.py | """
Flask-Twilio
-------------
Make Twilio voice/SMS calls with Flask
"""
from setuptools import setup
exec(open('flask_twilio.py').readline())
setup(
name='Flask-Twilio',
version=__version__,
url='http://example.com/flask-twilio/',
license='BSD',
author='Leo Singer',
author_email='leo.singer@ligo.org',
description='Make Twilio voice/SMS calls with Flask',
long_description=__doc__,
py_modules=['flask_twilio'],
zip_safe=False,
include_package_data=True,
platforms='any',
install_requires=[
'itsdangerous',
'Flask',
'twilio'
],
setup_requires=[
'pytest-runner',
],
tests_require=[
'pytest',
],
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Communications :: Telephony'
]
) | """
Flask-Twilio
-------------
Make Twilio voice/SMS calls with Flask
"""
from setuptools import setup
exec(open('flask_twilio.py').readline())
setup(
name='Flask-Twilio',
version=__version__,
url='http://example.com/flask-twilio/',
license='BSD',
author='Leo Singer',
author_email='leo.singer@ligo.org',
description='Make Twilio voice/SMS calls with Flask',
long_description=__doc__,
py_modules=['flask_twilio'],
zip_safe=False,
include_package_data=True,
platforms='any',
install_requires=[
'itsdangerous',
'Flask',
'six',
'twilio'
],
setup_requires=[
'pytest-runner',
],
tests_require=[
'pytest',
],
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Communications :: Telephony'
]
) | Add missing dependency on six | Add missing dependency on six
| Python | bsd-3-clause | lpsinger/flask-twilio | ---
+++
@@ -24,6 +24,7 @@
install_requires=[
'itsdangerous',
'Flask',
+ 'six',
'twilio'
],
setup_requires=[ |
bff48b594f4714e0f2d52793a1a038ce1f436719 | setup.py | setup.py | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='edx-oauth2-provider',
version='0.5.4',
description='Provide OAuth2 access to edX installations',
author='edX',
url='https://github.com/edx/edx-oauth2-provider',
license='AGPL',
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU Affero General Public License v3',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
],
packages=find_packages(exclude=['tests', '*.tests']),
dependency_links=[
'git+https://github.com/edx/django-oauth2-provider@0.2.7-fork-edx-5#egg=django-oauth2-provider-0.2.7-fork-edx-5',
],
install_requires=[
'django-oauth2-provider==0.2.7-fork-edx-5',
'PyJWT==1.0.1'
]
)
| #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='edx-oauth2-provider',
version='0.5.5',
description='Provide OAuth2 access to edX installations',
author='edX',
url='https://github.com/edx/edx-oauth2-provider',
license='AGPL',
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU Affero General Public License v3',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
],
packages=find_packages(exclude=['tests']),
dependency_links=[
'git+https://github.com/edx/django-oauth2-provider@0.2.7-fork-edx-5#egg=django-oauth2-provider-0.2.7-fork-edx-5',
],
install_requires=[
'django-oauth2-provider==0.2.7-fork-edx-5',
'PyJWT==1.0.1'
]
)
| Include oauth2-provider's tests module in the installed package | Include oauth2-provider's tests module in the installed package
| Python | agpl-3.0 | edx/edx-oauth2-provider,edx/edx-oauth2-provider | ---
+++
@@ -4,7 +4,7 @@
setup(
name='edx-oauth2-provider',
- version='0.5.4',
+ version='0.5.5',
description='Provide OAuth2 access to edX installations',
author='edX',
url='https://github.com/edx/edx-oauth2-provider',
@@ -18,7 +18,7 @@
'Programming Language :: Python',
'Framework :: Django',
],
- packages=find_packages(exclude=['tests', '*.tests']),
+ packages=find_packages(exclude=['tests']),
dependency_links=[
'git+https://github.com/edx/django-oauth2-provider@0.2.7-fork-edx-5#egg=django-oauth2-provider-0.2.7-fork-edx-5',
], |
8dffe003fdb42cb9edd4fa0e720d6eceb9719381 | setup.py | setup.py | from setuptools import setup, find_packages
import thermochem
setup(
name="thermochem",
version=thermochem.__version__,
description="Python utilities for thermodynamics and thermochemistry",
author="Adel Qalieh",
author_email="adelq@sas.upenn.edu",
url="https://github.com/adelq/thermochem",
license="BSD",
packages=find_packages(),
include_package_data=True,
install_requires=['scipy>=0.6.0', 'numpy>=1.2.1', 'pandas>=0.17.0'],
zip_safe=False,
keywords='thermo chemistry physics',
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Console',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.5',
'Topic :: Scientific/Engineering :: Chemistry',
'Topic :: Scientific/Engineering :: Physics',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
| from setuptools import setup, find_packages
import thermochem
setup(
name="thermochem",
version=thermochem.__version__,
description="Python utilities for thermodynamics and thermochemistry",
long_description=open("README.rst").read(),
author="Adel Qalieh",
author_email="adelq@sas.upenn.edu",
url="https://github.com/adelq/thermochem",
license="BSD",
packages=find_packages(),
include_package_data=True,
install_requires=['scipy>=0.6.0', 'numpy>=1.2.1', 'pandas>=0.17.0'],
zip_safe=False,
keywords='thermo chemistry physics',
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Console',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.5',
'Topic :: Scientific/Engineering :: Chemistry',
'Topic :: Scientific/Engineering :: Physics',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
| Add README as long description | Add README as long description
| Python | bsd-3-clause | adelq/thermopy | ---
+++
@@ -5,6 +5,7 @@
name="thermochem",
version=thermochem.__version__,
description="Python utilities for thermodynamics and thermochemistry",
+ long_description=open("README.rst").read(),
author="Adel Qalieh",
author_email="adelq@sas.upenn.edu",
url="https://github.com/adelq/thermochem", |
3c33bc1a8cdc33b5519b7a0802b7b71d0193a6c6 | setup.py | setup.py | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='django-slack',
url="https://chris-lamb.co.uk/projects/django-slack",
version='5.2.0',
description="Provides easy-to-use integration between Django projects and "
"the Slack group chat and IM tool.",
author="Chris Lamb",
author_email="chris@chris-lamb.co.uk",
license="BSD",
packages=find_packages(),
include_package_data=True,
install_requires=(
'Django>=1.6.8',
'requests',
'six',
),
)
| #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='django-slack',
url="https://chris-lamb.co.uk/projects/django-slack",
version='5.2.0',
description="Provides easy-to-use integration between Django projects and "
"the Slack group chat and IM tool.",
author="Chris Lamb",
author_email="chris@chris-lamb.co.uk",
license="BSD",
packages=find_packages(),
include_package_data=True,
install_requires=(
'Django>=1.8.0',
'requests',
'six',
),
)
| Update Django requirement to latest LTS | Update Django requirement to latest LTS
| Python | bsd-3-clause | lamby/django-slack | ---
+++
@@ -17,7 +17,7 @@
packages=find_packages(),
include_package_data=True,
install_requires=(
- 'Django>=1.6.8',
+ 'Django>=1.8.0',
'requests',
'six',
), |
f994ab4a70a55706eeff133dd484dfd80a68e108 | bin/isy_showevents.py | bin/isy_showevents.py | #!/usr/local/bin/python2.7 -u
__author__ = "Peter Shipley"
import os
import keyring
import ConfigParser
from ISY.IsyEvent import ISYEvent
def main() :
config = ConfigParser.ConfigParser()
config.read(os.path.expanduser('~/isy.cfg'))
server = ISYEvent()
# you can subscribe to multiple devices
# server.subscribe('10.1.1.25')
isy_addr = config.get('isy', 'addr')
isy_user = config.get('isy', 'user')
server.subscribe(
addr=isy_addr,
userl=isy_user,
userp=keyring.get_password("isy", isy_user) )
server.set_process_func(ISYEvent.print_event, "")
try:
print('Use Control-C to exit')
server.events_loop() #no return
# for d in server.event_iter( ignorelist=["_0", "_11"] ):
# server.print_event(d, "")
except KeyboardInterrupt:
print('Exiting')
if __name__ == '__main__' :
main()
exit(0)
| #!/usr/local/bin/python2.7 -u
__author__ = "Peter Shipley"
import os
import ConfigParser
from ISY.IsyEvent import ISYEvent
def main() :
config = ConfigParser.ConfigParser()
config.read(os.path.expanduser('~/home.cfg'))
server = ISYEvent()
isy_addr = config.get('isy', 'addr')
isy_user = config.get('isy', 'user')
isy_pass = config.get('isy', 'pass')
server.subscribe(
addr=isy_addr,
userl=isy_user,
userp=isy_pass )
server.set_process_func(ISYEvent.print_event, "")
try:
print('Use Control-C to exit')
server.events_loop() #no return
except KeyboardInterrupt:
print('Exiting')
if __name__ == '__main__' :
main()
exit(0)
| Remove keyring and change to basic cfg file handling | Remove keyring and change to basic cfg file handling
| Python | bsd-2-clause | fxstein/ISYlib-python | ---
+++
@@ -3,7 +3,6 @@
import os
-import keyring
import ConfigParser
from ISY.IsyEvent import ISYEvent
@@ -11,28 +10,24 @@
def main() :
config = ConfigParser.ConfigParser()
- config.read(os.path.expanduser('~/isy.cfg'))
+ config.read(os.path.expanduser('~/home.cfg'))
server = ISYEvent()
- # you can subscribe to multiple devices
- # server.subscribe('10.1.1.25')
-
isy_addr = config.get('isy', 'addr')
isy_user = config.get('isy', 'user')
+ isy_pass = config.get('isy', 'pass')
server.subscribe(
addr=isy_addr,
userl=isy_user,
- userp=keyring.get_password("isy", isy_user) )
+ userp=isy_pass )
server.set_process_func(ISYEvent.print_event, "")
try:
print('Use Control-C to exit')
server.events_loop() #no return
- # for d in server.event_iter( ignorelist=["_0", "_11"] ):
- # server.print_event(d, "")
except KeyboardInterrupt:
print('Exiting')
|
ff9f64da2d43591cacfbec1a147fda4b82539c1d | serial_reader.py | serial_reader.py | #!/usr/bin/env python
from argparse import ArgumentParser
import serial
def run(device, baud):
with serial.Serial(device, baud, timeout=0.1) as ser:
while True:
line = ser.readline()
if line:
print line
if __name__ == '__main__':
parser = ArgumentParser()
parser.add_argument('device',
help='serial device, typically /dev/tty.usbserial-*')
parser.add_argument('--baud', dest='baud', type=int, default=74880)
args = parser.parse_args()
run(args.device, args.baud)
| #!/usr/bin/env python
from argparse import ArgumentParser
import sys
import serial
def run(device, baud):
with serial.Serial(device, baud, timeout=0.1) as ser:
while True:
line = ser.readline()
if line:
sys.stdout.write(line)
if __name__ == '__main__':
parser = ArgumentParser()
parser.add_argument('device',
help='serial device, typically /dev/tty.usbserial-*')
parser.add_argument('--baud', dest='baud', type=int, default=74880)
args = parser.parse_args()
run(args.device, args.baud)
| Use sys.stdout.write to get rid of extra newlines | Use sys.stdout.write to get rid of extra newlines
| Python | unlicense | recursify/serial-debug-tool | ---
+++
@@ -1,6 +1,7 @@
#!/usr/bin/env python
from argparse import ArgumentParser
+import sys
import serial
def run(device, baud):
@@ -8,7 +9,7 @@
while True:
line = ser.readline()
if line:
- print line
+ sys.stdout.write(line)
if __name__ == '__main__':
parser = ArgumentParser() |
8ffd26f4fddb0c367e61a46af6427eab6c244ea8 | south/signals.py | south/signals.py | """
South-specific signals
"""
from django.dispatch import Signal
# Sent at the start of the migration of an app
pre_migrate = Signal(providing_args=["app"])
# Sent after each successful migration of an app
post_migrate = Signal(providing_args=["app"])
# Sent after each run of a particular migration in a direction
ran_migration = Signal(providing_args=["app","migration","method"])
| """
South-specific signals
"""
from django.dispatch import Signal
from django.conf import settings
# Sent at the start of the migration of an app
pre_migrate = Signal(providing_args=["app"])
# Sent after each successful migration of an app
post_migrate = Signal(providing_args=["app"])
# Sent after each run of a particular migration in a direction
ran_migration = Signal(providing_args=["app","migration","method"])
# Compatibility code for django.contrib.auth
if 'django.contrib.auth' in settings.INSTALLED_APPS:
def create_permissions_compat(app, **kwargs):
from django.db.models import get_app
from django.contrib.auth.management import create_permissions
create_permissions(get_app(app), (), 0)
post_migrate.connect(create_permissions_compat)
| Add a compatibility hook to deal with creating django.contrib.auth permissions on migrated models. | Add a compatibility hook to deal with creating django.contrib.auth permissions on migrated models.
| Python | apache-2.0 | theatlantic/django-south,theatlantic/django-south | ---
+++
@@ -3,6 +3,7 @@
"""
from django.dispatch import Signal
+from django.conf import settings
# Sent at the start of the migration of an app
pre_migrate = Signal(providing_args=["app"])
@@ -12,3 +13,11 @@
# Sent after each run of a particular migration in a direction
ran_migration = Signal(providing_args=["app","migration","method"])
+
+# Compatibility code for django.contrib.auth
+if 'django.contrib.auth' in settings.INSTALLED_APPS:
+ def create_permissions_compat(app, **kwargs):
+ from django.db.models import get_app
+ from django.contrib.auth.management import create_permissions
+ create_permissions(get_app(app), (), 0)
+ post_migrate.connect(create_permissions_compat) |
46a568690a9a284ddc350519a15e092e1211d073 | reviewboard/site/urlresolvers.py | reviewboard/site/urlresolvers.py | from __future__ import unicode_literals
from django.core.urlresolvers import NoReverseMatch, reverse
def local_site_reverse(viewname, request=None, local_site_name=None,
args=None, kwargs=None, *func_args, **func_kwargs):
"""Reverses a URL name, returning a working URL.
This works much like Django's reverse(), but handles returning a
localsite version of a URL when invoked with a request within a localsite.
"""
if request or local_site_name:
if request and not local_site_name:
local_site_name = getattr(request, '_local_site_name', None)
if local_site_name:
if args:
new_args = [local_site_name] + args
new_kwargs = kwargs
else:
new_args = args
new_kwargs = {
'local_site_name': local_site_name,
}
if kwargs:
new_kwargs.update(kwargs)
try:
return reverse(viewname, args=new_args, kwargs=new_kwargs,
*func_args, **func_kwargs)
except NoReverseMatch:
# We'll try it again without those arguments.
pass
return reverse(viewname, args=args, kwargs=kwargs,
*func_args, **func_kwargs)
| from __future__ import unicode_literals
from django.core.urlresolvers import NoReverseMatch, reverse
def local_site_reverse(viewname, request=None, local_site_name=None,
local_site=None, args=None, kwargs=None,
*func_args, **func_kwargs):
"""Reverses a URL name, returning a working URL.
This works much like Django's reverse(), but handles returning a
localsite version of a URL when invoked with a request within a localsite.
"""
assert not (local_site_name and local_site)
if request or local_site_name or local_site:
if local_site:
local_site_name = local_site.name
elif request and not local_site_name:
local_site_name = getattr(request, '_local_site_name', None)
if local_site_name:
if args:
new_args = [local_site_name] + args
new_kwargs = kwargs
else:
new_args = args
new_kwargs = {
'local_site_name': local_site_name,
}
if kwargs:
new_kwargs.update(kwargs)
try:
return reverse(viewname, args=new_args, kwargs=new_kwargs,
*func_args, **func_kwargs)
except NoReverseMatch:
# We'll try it again without those arguments.
pass
return reverse(viewname, args=args, kwargs=kwargs,
*func_args, **func_kwargs)
| Allow local_site_reverse to take an actual LocalSite. | Allow local_site_reverse to take an actual LocalSite.
local_site_reverse was able to take a LocalSite's name, or a request
object, but if you actually had a LocalSite (or None), you'd have to
write your own conditional to extract the name and pass it.
Now, local_site_reverse can take a LocalSite. This saves a database
query, if one is already available, and simplifies calling code.
Reviewed at https://reviews.reviewboard.org/r/6302/
| Python | mit | custode/reviewboard,custode/reviewboard,bkochendorfer/reviewboard,custode/reviewboard,brennie/reviewboard,reviewboard/reviewboard,KnowNo/reviewboard,sgallagher/reviewboard,custode/reviewboard,sgallagher/reviewboard,brennie/reviewboard,davidt/reviewboard,chipx86/reviewboard,KnowNo/reviewboard,chipx86/reviewboard,KnowNo/reviewboard,beol/reviewboard,bkochendorfer/reviewboard,davidt/reviewboard,bkochendorfer/reviewboard,beol/reviewboard,chipx86/reviewboard,davidt/reviewboard,bkochendorfer/reviewboard,reviewboard/reviewboard,chipx86/reviewboard,davidt/reviewboard,brennie/reviewboard,reviewboard/reviewboard,brennie/reviewboard,beol/reviewboard,KnowNo/reviewboard,sgallagher/reviewboard,reviewboard/reviewboard,beol/reviewboard,sgallagher/reviewboard | ---
+++
@@ -4,14 +4,19 @@
def local_site_reverse(viewname, request=None, local_site_name=None,
- args=None, kwargs=None, *func_args, **func_kwargs):
+ local_site=None, args=None, kwargs=None,
+ *func_args, **func_kwargs):
"""Reverses a URL name, returning a working URL.
This works much like Django's reverse(), but handles returning a
localsite version of a URL when invoked with a request within a localsite.
"""
- if request or local_site_name:
- if request and not local_site_name:
+ assert not (local_site_name and local_site)
+
+ if request or local_site_name or local_site:
+ if local_site:
+ local_site_name = local_site.name
+ elif request and not local_site_name:
local_site_name = getattr(request, '_local_site_name', None)
if local_site_name: |
c488252462a2cb860111a4826f01883e7c16b3aa | numpy/distutils/setup.py | numpy/distutils/setup.py | #!/usr/bin/env python
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('distutils',parent_package,top_path)
config.add_subpackage('command')
config.add_subpackage('fcompiler')
config.add_data_dir('tests')
config.add_data_files('site.cfg')
config.make_config_py()
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(configuration=configuration)
| #!/usr/bin/env python
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('distutils',parent_package,top_path)
config.add_subpackage('command')
config.add_subpackage('fcompiler')
config.add_data_dir('tests')
config.add_data_files('site.cfg')
config.add_data_files('mingw/gfortran_vs2003_hack.c')
config.make_config_py()
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(configuration=configuration)
| Make the gfortran/vs2003 hack source file known to distutils. | Make the gfortran/vs2003 hack source file known to distutils.
git-svn-id: 77a43f9646713b91fea7788fad5dfbf67e151ece@6650 94b884b6-d6fd-0310-90d3-974f1d3f35e1
| Python | bsd-3-clause | chadnetzer/numpy-gaurdro,Ademan/NumPy-GSoC,Ademan/NumPy-GSoC,teoliphant/numpy-refactor,illume/numpy3k,Ademan/NumPy-GSoC,teoliphant/numpy-refactor,chadnetzer/numpy-gaurdro,Ademan/NumPy-GSoC,illume/numpy3k,jasonmccampbell/numpy-refactor-sprint,efiring/numpy-work,efiring/numpy-work,chadnetzer/numpy-gaurdro,efiring/numpy-work,teoliphant/numpy-refactor,teoliphant/numpy-refactor,efiring/numpy-work,teoliphant/numpy-refactor,jasonmccampbell/numpy-refactor-sprint,illume/numpy3k,jasonmccampbell/numpy-refactor-sprint,illume/numpy3k,jasonmccampbell/numpy-refactor-sprint,chadnetzer/numpy-gaurdro | ---
+++
@@ -7,6 +7,7 @@
config.add_subpackage('fcompiler')
config.add_data_dir('tests')
config.add_data_files('site.cfg')
+ config.add_data_files('mingw/gfortran_vs2003_hack.c')
config.make_config_py()
return config
|
56215f65ea1513adfd574cf6fc3d118121119290 | stestr/commands/__init__.py | stestr/commands/__init__.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from stestr.commands.failing import failing as failing_command
from stestr.commands.init import init as init_command
from stestr.commands.last import last as last_command
from stestr.commands.list import list_command
from stestr.commands.load import load as load_command
from stestr.commands.run import run_command
from stestr.commands.slowest import slowest as slowest_command
__all__ = [failing_command, init_command, last_command,
list_command, load_command, run_command, slowest_command]
| Allow to import commands APIs from a single module | Allow to import commands APIs from a single module
The APIs available to run various stestr commands are distributed
in multiple modules. For ease of use make them all accessible from
the commands module.
| Python | apache-2.0 | masayukig/stestr,mtreinish/stestr,mtreinish/stestr,masayukig/stestr | ---
+++
@@ -0,0 +1,22 @@
+# 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 stestr.commands.failing import failing as failing_command
+from stestr.commands.init import init as init_command
+from stestr.commands.last import last as last_command
+from stestr.commands.list import list_command
+from stestr.commands.load import load as load_command
+from stestr.commands.run import run_command
+from stestr.commands.slowest import slowest as slowest_command
+
+__all__ = [failing_command, init_command, last_command,
+ list_command, load_command, run_command, slowest_command] | |
a7f7d8ff9f8279ec2c1f3981b1507001f1f94394 | test/completion/docstring.py | test/completion/docstring.py | """ Test docstrings in functions and classes, which are used to infer types """
def f(a, b):
""" asdfasdf
:param a: blablabla
:type a: str
"""
#? str()
a
#?
b
def g(a, b):
""" asdfasdf
Arguments:
a (str): blablabla
"""
#? str()
a
#?
b
| """ Test docstrings in functions and classes, which are used to infer types """
def f(a, b):
""" asdfasdf
:param a: blablabla
:type a: str
"""
#? str()
a
#?
b
def g(a, b):
""" asdfasdf
Arguments:
a (str): blablabla
"""
#? str()
a
#?
b
def e(a, b):
""" asdfasdf
@type a: str
@param a: blablabla
"""
#? str()
a
#?
b
| Add tests for epydoc formated dosctring | Add tests for epydoc formated dosctring
| Python | mit | mfussenegger/jedi,flurischt/jedi,dwillmer/jedi,tjwei/jedi,WoLpH/jedi,jonashaag/jedi,mfussenegger/jedi,flurischt/jedi,jonashaag/jedi,tjwei/jedi,dwillmer/jedi,WoLpH/jedi | ---
+++
@@ -19,3 +19,13 @@
a
#?
b
+
+def e(a, b):
+ """ asdfasdf
+ @type a: str
+ @param a: blablabla
+ """
+ #? str()
+ a
+ #?
+ b |
92d5991a37c3f269e9a7e59ab5edd90b45699930 | test/style_test.py | test/style_test.py | import glob
import os
import pep8
class TestCodeFormat:
def test_pep8(self):
def match(*p):
s = list(p) + ['*.py']
return glob.glob(os.path.join(*s))
pep8style = pep8.StyleGuide(config_file='setup.cfg')
result = pep8style.check_files(
match('examples') +
match('test') +
match('pagoda'))
assert result.total_errors == 0
| import glob
import os
import pep8
class TestCodeFormat:
def test_pep8(self):
def match(*p):
s = list(p) + ['*.py']
return glob.glob(os.path.join(*s))
pep8style = pep8.StyleGuide(config_file='setup.cfg')
result = pep8style.check_files(
match('examples') +
match('scripts') +
match('test') +
match('pagoda'))
assert result.total_errors == 0
| Include scripts in style check. | Include scripts in style check.
| Python | mit | EmbodiedCognition/pagoda,EmbodiedCognition/pagoda | ---
+++
@@ -11,6 +11,7 @@
pep8style = pep8.StyleGuide(config_file='setup.cfg')
result = pep8style.check_files(
match('examples') +
+ match('scripts') +
match('test') +
match('pagoda'))
assert result.total_errors == 0 |
cfd710e0035c885fab926690d7ea450f3f9c3845 | setup.py | setup.py | from distutils.core import setup
import os, glob, string, shutil
# Packages
packages = ['neuroimaging', 'neuroimaging.statistics', 'neuroimaging.image', 'neuroimaging.reference', 'neuroimaging.data', 'neuroimaging.image.formats', 'neuroimaging.image.formats.analyze', 'neuroimaging.fmri', 'neuroimaging.fmri.fmristat', 'neuroimaging.visualization', 'neuroimaging.visualization.cmap']
def main():
setup (name = 'neuroimaging',
version = '0.01a',
description = 'This is a neuroimaging python package',
author = 'Various, one of whom is Jonathan Taylor',
author_email = 'jonathan.taylor@stanford.edu',
ext_package = 'neuroimaging',
packages=packages,
package_dir = {'neuroimaging': 'lib'},
url = 'http://neuroimaging.scipy.org',
long_description =
'''
''')
if __name__ == "__main__":
main()
| import os, glob, string, shutil
from distutils.core import setup
# Packages
packages = ['neuroimaging', 'neuroimaging.statistics', 'neuroimaging.image', 'neuroimaging.reference', 'neuroimaging.data', 'neuroimaging.image.formats', 'neuroimaging.image.formats.analyze', 'neuroimaging.fmri', 'neuroimaging.fmri.fmristat', 'neuroimaging.visualization', 'neuroimaging.visualization.cmap']
def main():
setup (name = 'neuroimaging',
version = '0.01a',
description = 'This is a neuroimaging python package',
author = 'Various, one of whom is Jonathan Taylor',
author_email = 'jonathan.taylor@stanford.edu',
ext_package = 'neuroimaging',
packages=packages,
package_dir = {'neuroimaging': 'lib'},
url = 'http://neuroimaging.scipy.org',
long_description =
'''
''')
if __name__ == "__main__":
main()
| Test edit - to check svn email hook | Test edit - to check svn email hook
| Python | bsd-3-clause | matthew-brett/draft-statsmodels,matthew-brett/draft-statsmodels | ---
+++
@@ -1,5 +1,5 @@
+import os, glob, string, shutil
from distutils.core import setup
-import os, glob, string, shutil
# Packages
|
a848ab0489b0419592dec6f2b5b728863bf0bebf | setup.py | setup.py | from distutils.core import setup
setup(
name = 'missingno',
packages = ['missingno'], # this must be the same as the name above
install_requires=['numpy', 'matplotlib'],
py_modules=['missingno'],
version = '0.1.1',
description = 'Missing data visualization module for Python.',
author = 'Aleksey Bilogur',
author_email = 'aleksey.bilogur@gmail.com',
url = 'https://github.com/ResidentMario/missingno',
download_url = 'https://github.com/ResidentMario/missingno/tarball/0.1.1',
keywords = ['data', 'data visualization', 'data analysis', 'missing data', 'data science', 'pandas', 'python',
'jupyter'],
classifiers = [],
) | from setuptools import setup
setup(
name = 'missingno',
packages = ['missingno'], # this must be the same as the name above
install_requires=['numpy', 'matplotlib'],
py_modules=['missingno'],
version = '0.1.1',
description = 'Missing data visualization module for Python.',
author = 'Aleksey Bilogur',
author_email = 'aleksey.bilogur@gmail.com',
url = 'https://github.com/ResidentMario/missingno',
download_url = 'https://github.com/ResidentMario/missingno/tarball/0.1.1',
keywords = ['data', 'data visualization', 'data analysis', 'missing data', 'data science', 'pandas', 'python',
'jupyter'],
classifiers = [],
) | Switch to 'more correct' distributor. | Switch to 'more correct' distributor.
| Python | mit | ResidentMario/missingno | ---
+++
@@ -1,4 +1,4 @@
-from distutils.core import setup
+from setuptools import setup
setup(
name = 'missingno',
packages = ['missingno'], # this must be the same as the name above |
a74ad2850521eea430c0144b433707e0e9d5bb88 | setup.py | setup.py | from setuptools import setup, find_packages
exec(open('keras_vggface/version.py').read())
setup(name='keras_vggface',
version=__version__,
description='VGGFace implementation with Keras framework',
url='https://github.com/rcmalli/keras-vggface',
author='Refik Can MALLI',
author_email = "mallir@itu.edu.tr",
license='MIT',
keywords = ['keras', 'vggface', 'deeplearning'],
packages=find_packages(exclude=["temp", "test", "data", "visualize"]),
zip_safe=False,
install_requires=['numpy>=1.9.1',
'scipy>=0.14',
'h5py',
'pillow',
'tensorflow',
'keras',
'six>=1.9.0',
'pyyaml'])
| from setuptools import setup, find_packages
exec(open('keras_vggface/version.py').read())
setup(
name='keras_vggface',
version=__version__,
description='VGGFace implementation with Keras framework',
url='https://github.com/rcmalli/keras-vggface',
author='Refik Can MALLI',
author_email="mallir@itu.edu.tr",
license='MIT',
keywords=['keras', 'vggface', 'deeplearning'],
packages=find_packages(exclude=["temp", "test", "data", "visualize"]),
zip_safe=False,
install_requires=[
'numpy>=1.9.1', 'scipy>=0.14', 'h5py', 'pillow', 'keras',
'six>=1.9.0', 'pyyaml'
],
extras_require={
"tf": ["tensorflow"],
"tf_gpu": ["tensorflow-gpu"],
})
| Make tensorflow be optional to allow using tensorflow-gpu | Make tensorflow be optional to allow using tensorflow-gpu
| Python | mit | rcmalli/keras-vggface | ---
+++
@@ -1,20 +1,21 @@
from setuptools import setup, find_packages
exec(open('keras_vggface/version.py').read())
-setup(name='keras_vggface',
- version=__version__,
- description='VGGFace implementation with Keras framework',
- url='https://github.com/rcmalli/keras-vggface',
- author='Refik Can MALLI',
- author_email = "mallir@itu.edu.tr",
- license='MIT',
- keywords = ['keras', 'vggface', 'deeplearning'],
- packages=find_packages(exclude=["temp", "test", "data", "visualize"]),
- zip_safe=False,
- install_requires=['numpy>=1.9.1',
- 'scipy>=0.14',
- 'h5py',
- 'pillow',
- 'tensorflow',
- 'keras',
- 'six>=1.9.0',
- 'pyyaml'])
+setup(
+ name='keras_vggface',
+ version=__version__,
+ description='VGGFace implementation with Keras framework',
+ url='https://github.com/rcmalli/keras-vggface',
+ author='Refik Can MALLI',
+ author_email="mallir@itu.edu.tr",
+ license='MIT',
+ keywords=['keras', 'vggface', 'deeplearning'],
+ packages=find_packages(exclude=["temp", "test", "data", "visualize"]),
+ zip_safe=False,
+ install_requires=[
+ 'numpy>=1.9.1', 'scipy>=0.14', 'h5py', 'pillow', 'keras',
+ 'six>=1.9.0', 'pyyaml'
+ ],
+ extras_require={
+ "tf": ["tensorflow"],
+ "tf_gpu": ["tensorflow-gpu"],
+ }) |
ce966cd73ff3dc37fd534fc7ae41e47b05782a4e | setup.py | setup.py | from setuptools import setup, find_packages
def read(fname):
with open(fname) as fp:
content = fp.read()
return content
setup(
name='munerator',
version="0.10.11",
description='Manager of OpenArena battles',
long_description=read("README.rst"),
author='Johan Bloemberg',
author_email='mail@ijohan.nl',
url='https://github.com/aequitas/munerator',
install_requires=[
'six',
'docopt',
'pyzmq',
'webcolors',
'python-Levenshtein',
'eve==0.3',
'flask',
'tornado',
'mongoengine',
'eve-mongoengine',
'python-dateutil',
'rcfile'
],
packages=find_packages(),
license=read("LICENSE"),
include_package_data=True,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Natural Language :: English',
"Programming Language :: Python :: 2",
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: Implementation :: CPython',
],
entry_points={
'console_scripts': [
"munerator = munerator:main",
]
},
)
| from setuptools import setup, find_packages
def read(fname):
with open(fname) as fp:
content = fp.read()
return content
setup(
name='munerator',
version="0.10.12",
description='Manager of OpenArena battles',
long_description=read("README.rst"),
author='Johan Bloemberg',
author_email='mail@ijohan.nl',
url='https://github.com/aequitas/munerator',
install_requires=[
'six',
'docopt',
'pyzmq',
'webcolors',
'python-Levenshtein',
'python-dateutil',
'rcfile'
],
extras_require={
'restapi': [
'mongoengine',
'eve-mongoengine',
'eve==0.3',
'flask',
],
'store': [
'mongoengine',
'eve-mongoengine',
'eve==0.3',
]
},
packages=find_packages(),
license=read("LICENSE"),
include_package_data=True,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Natural Language :: English',
"Programming Language :: Python :: 2",
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: Implementation :: CPython',
],
entry_points={
'console_scripts': [
"munerator = munerator:main",
]
},
)
| Split extra requires for store and restapi | Split extra requires for store and restapi
| Python | mit | aequitas/munerator,aequitas/munerator,aequitas/munerator,aequitas/munerator | ---
+++
@@ -8,7 +8,7 @@
setup(
name='munerator',
- version="0.10.11",
+ version="0.10.12",
description='Manager of OpenArena battles',
long_description=read("README.rst"),
author='Johan Bloemberg',
@@ -20,14 +20,22 @@
'pyzmq',
'webcolors',
'python-Levenshtein',
- 'eve==0.3',
- 'flask',
- 'tornado',
- 'mongoengine',
- 'eve-mongoengine',
'python-dateutil',
'rcfile'
],
+ extras_require={
+ 'restapi': [
+ 'mongoengine',
+ 'eve-mongoengine',
+ 'eve==0.3',
+ 'flask',
+ ],
+ 'store': [
+ 'mongoengine',
+ 'eve-mongoengine',
+ 'eve==0.3',
+ ]
+ },
packages=find_packages(),
license=read("LICENSE"),
include_package_data=True, |
4ffdbaf30c46ff886c7eb2e9e9686679a5045e49 | setup.py | setup.py | from setuptools import setup
PACKAGE = 'TracBacklog'
VERSION = '0.1'
setup(name=PACKAGE,
version=VERSION,
packages=['backlog'],
package_data={
'backlog': [
'htdocs/css/*.css',
'htdocs/img/*.png',
'htdocs/js/*.js',
'htdocs/js/dojo/*.js',
'htdocs/js/dojo/dnd/*.js',
'htdocs/js/dojo/date/*.js',
'templates/*.html',
'scripts/*'
]},
entry_points='''
[trac.plugins]
backlog = backlog.web_ui
''')
| from setuptools import setup
PACKAGE = 'TracBacklog'
VERSION = '0.1'
setup(name=PACKAGE,
version=VERSION,
packages=['backlog'],
package_data={
'backlog': [
'htdocs/css/*.css',
'htdocs/img/*.png',
'htdocs/js/*.js',
'htdocs/js/dojo/*.js',
'htdocs/js/dojo/dnd/*.js',
'htdocs/js/dojo/date/*.js',
'templates/*.html',
'scripts/*'
]},
entry_points={
'trac.plugins': ['backlog = backlog.web_ui']
}
)
| Use a different method of specifying the entry point. | Use a different method of specifying the entry point. | Python | bsd-3-clause | jszakmeister/trac-backlog,jszakmeister/trac-backlog | ---
+++
@@ -17,8 +17,8 @@
'templates/*.html',
'scripts/*'
]},
- entry_points='''
- [trac.plugins]
- backlog = backlog.web_ui
- ''')
+ entry_points={
+ 'trac.plugins': ['backlog = backlog.web_ui']
+ }
+ )
|
d1fb5fbef04fde818abd1eb6ac38805058addafb | setup.py | setup.py | import re
from setuptools import setup, find_packages
versionPattern = re.compile(r"""^__version__ = ['"](.*?)['"]$""", re.M)
with open("fusion_index/_version.py", "rt") as f:
version = versionPattern.search(f.read()).group(1)
setup(
name='fusion-index',
version=version,
description='Lookup/search index service for Fusion',
url='https://bitbucket.org/fusionapp/fusion-index',
install_requires=[
'Twisted[tls] >= 15.0.0',
'txspinneret >= 0.1.2',
'Axiom >= 0.7.4',
'eliot >= 0.8.0',
'testtools',
],
license='MIT',
packages=find_packages() + ['axiom.plugins'],
include_package_data=True)
| import re
from setuptools import setup, find_packages
versionPattern = re.compile(r"""^__version__ = ['"](.*?)['"]$""", re.M)
with open("fusion_index/_version.py", "rt") as f:
version = versionPattern.search(f.read()).group(1)
setup(
name='fusion-index',
version=version,
description='Lookup/search index service for Fusion',
url='https://bitbucket.org/fusionapp/fusion-index',
install_requires=[
'Twisted[tls] >= 15.0.0',
'txspinneret >= 0.1.2',
'Axiom >= 0.7.4',
'eliot >= 0.8.0',
'testtools',
'characteristic',
],
license='MIT',
packages=find_packages() + ['axiom.plugins'],
include_package_data=True)
| Add Characteristic to depends since we are using it directly now. | Add Characteristic to depends since we are using it directly now.
--HG--
branch : 1-lookup-index
| Python | mit | fusionapp/fusion-index | ---
+++
@@ -17,6 +17,7 @@
'Axiom >= 0.7.4',
'eliot >= 0.8.0',
'testtools',
+ 'characteristic',
],
license='MIT',
packages=find_packages() + ['axiom.plugins'], |
11d4763b093d0f1006051e892277d33ca273916c | setup.py | setup.py | from setuptools import setup, find_packages
import re
with open("README.rst", mode='r') as readme_file:
text=readme_file.read()
#below version code pulled from requests module
with open('__init__.py', 'r') as fd:
version_number = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]',
fd.read(), re.MULTILINE).group(1)
if not version_number:
raise RuntimeError('Cannot find version information')
setup(
name='pyautoupdate',
version=version_number,
packages=find_packages(),
description='Interface to allow python programs to automatically update',
long_description=text,
url='https://github.com/rlee287/pyautoupdate',
install_requires=['requests>=2.6'],
package_data={
'testing':['*.rst']},
license="LGPL 2.1"
)
| from setuptools import setup, find_packages
import re
with open("README.rst", mode='r') as readme_file:
text=readme_file.read()
#below version code pulled from requests module
with open('__init__.py', 'r') as fd:
version_number = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]',
fd.read(), re.MULTILINE).group(1)
if not version_number:
raise RuntimeError('Cannot find version information')
setup(
name='pyautoupdate',
version=version_number,
packages=find_packages(),
description='Interface to allow python programs to automatically update',
long_description=text,
url='https://github.com/rlee287/pyautoupdate',
install_requires=['requests'],
extras_require={
'testing': ['pytest','coverage']
},
package_data={
'testing':['*.rst']},
license="LGPL 2.1"
)
| Fix continuation whitespace and add extras_require | Fix continuation whitespace and add extras_require
| Python | lgpl-2.1 | rlee287/pyautoupdate,rlee287/pyautoupdate | ---
+++
@@ -8,7 +8,7 @@
#below version code pulled from requests module
with open('__init__.py', 'r') as fd:
version_number = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]',
- fd.read(), re.MULTILINE).group(1)
+ fd.read(), re.MULTILINE).group(1)
if not version_number:
raise RuntimeError('Cannot find version information')
@@ -19,7 +19,10 @@
description='Interface to allow python programs to automatically update',
long_description=text,
url='https://github.com/rlee287/pyautoupdate',
- install_requires=['requests>=2.6'],
+ install_requires=['requests'],
+ extras_require={
+ 'testing': ['pytest','coverage']
+ },
package_data={
'testing':['*.rst']},
license="LGPL 2.1" |
5958f80d456a43654c5013d38569554940e754f4 | tests/dojo_test.py | tests/dojo_test.py | import unittest
from src.dojo import Dojo
class TestCreateRoom (unittest.TestCase):
def setUp(self):
self.dojo = Dojo()
self.test_office = self.dojo.create_room("office", "test")
self.test_living_space = self.dojo.create_room("living_space", "test living space")
def test_create_room_successfully(self):
initial_room_count = len(self.dojo.all_rooms)
blue_office = self.dojo.create_room("office", "Blue")
self.assertTrue(blue_office)
new_room_count = len(self.dojo.all_rooms)
self.assertEqual(new_room_count - initial_room_count, 1)
def test_create_rooms_successfully(self):
my_class_instance = Dojo()
initial_room_count = len(my_class_instance.all_rooms)
offices = my_class_instance.create_room("office", "Blue", "Black", "Brown")
self.assertTrue(offices)
new_room_count = len(my_class_instance.all_rooms)
self.assertEqual(new_room_count - initial_room_count, 3) | import unittest
from src.dojo import Dojo
class TestCreateRoom (unittest.TestCase):
def setUp(self):
self.dojo = Dojo()
self.test_office = self.dojo.create_room("office", "test")
self.test_living_space = self.dojo.create_room("living_space", "test living space")
def test_create_room_successfully(self):
initial_room_count = len(self.dojo.all_rooms)
blue_office = self.dojo.create_room("office", "Blue")
self.assertTrue(blue_office)
new_room_count = len(self.dojo.all_rooms)
self.assertEqual(new_room_count - initial_room_count, 1)
def test_create_rooms_successfully(self):
initial_room_count = len(self.dojo.all_rooms)
offices = self.dojo.create_room("office", "Blue", "Black", "Brown")
self.assertTrue(offices)
new_room_count = len(self.dojo.all_rooms)
self.assertEqual(new_room_count - initial_room_count, 3) | Change test for multiple rooms to use test set-up | Change test for multiple rooms to use test set-up
| Python | mit | EdwinKato/Space-Allocator,EdwinKato/Space-Allocator | ---
+++
@@ -17,9 +17,8 @@
self.assertEqual(new_room_count - initial_room_count, 1)
def test_create_rooms_successfully(self):
- my_class_instance = Dojo()
- initial_room_count = len(my_class_instance.all_rooms)
- offices = my_class_instance.create_room("office", "Blue", "Black", "Brown")
+ initial_room_count = len(self.dojo.all_rooms)
+ offices = self.dojo.create_room("office", "Blue", "Black", "Brown")
self.assertTrue(offices)
- new_room_count = len(my_class_instance.all_rooms)
+ new_room_count = len(self.dojo.all_rooms)
self.assertEqual(new_room_count - initial_room_count, 3) |
2f75cf84d37869e49dd3820d00a2fa69ab57a219 | setup.py | setup.py | #!/usr/bin/env python
# encoding=utf-8
from __future__ import print_function
import os
import sys
from setuptools import setup
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.md')).read()
needs_pytest = set(['pytest', 'test', 'ptr']).intersection(sys.argv)
pytest_runner = ['pytest-runner'] if needs_pytest else []
setup(name='mwclient',
version='0.9.3', # Use bumpversion to update
description='MediaWiki API client',
long_description=README,
long_description_content_type='text/markdown',
classifiers=[
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
],
keywords='mediawiki wikipedia',
author='Bryan Tong Minh',
author_email='bryan.tongminh@gmail.com',
url='https://github.com/btongminh/mwclient',
license='MIT',
packages=['mwclient'],
install_requires=['requests_oauthlib', 'six'],
setup_requires=pytest_runner,
tests_require=['pytest', 'pytest-cov', 'flake8',
'responses>=0.3.0', 'responses!=0.6.0', 'mock'],
zip_safe=True
)
| #!/usr/bin/env python
# encoding=utf-8
from __future__ import print_function
import os
import sys
from setuptools import setup
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.md')).read()
needs_pytest = set(['pytest', 'test', 'ptr']).intersection(sys.argv)
pytest_runner = ['pytest-runner'] if needs_pytest else []
setup(name='mwclient',
version='0.9.3', # Use bumpversion to update
description='MediaWiki API client',
long_description=README,
long_description_content_type='text/markdown',
classifiers=[
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
],
keywords='mediawiki wikipedia',
author='Bryan Tong Minh',
author_email='bryan.tongminh@gmail.com',
url='https://github.com/btongminh/mwclient',
license='MIT',
packages=['mwclient'],
install_requires=['requests-oauthlib', 'six'],
setup_requires=pytest_runner,
tests_require=['pytest', 'pytest-cov', 'flake8',
'responses>=0.3.0', 'responses!=0.6.0', 'mock'],
zip_safe=True
)
| Update dependency to work on conda | Update dependency to work on conda
requests_oauthlib dependency name will only install from pip, requests-oauthlib works on both conda and pip | Python | mit | mwclient/mwclient | ---
+++
@@ -29,7 +29,7 @@
url='https://github.com/btongminh/mwclient',
license='MIT',
packages=['mwclient'],
- install_requires=['requests_oauthlib', 'six'],
+ install_requires=['requests-oauthlib', 'six'],
setup_requires=pytest_runner,
tests_require=['pytest', 'pytest-cov', 'flake8',
'responses>=0.3.0', 'responses!=0.6.0', 'mock'], |
2ee7bba787a29f715805b038fb98eda767534f10 | setup.py | setup.py | #!/usr/bin/env python
#-*- coding:utf-8 -*-
from setuptools import setup
setup(
name='pybreaker',
version='0.6.0',
description='Python implementation of the Circuit Breaker pattern',
long_description=open('README.rst', 'r').read(),
keywords=['design', 'pattern', 'circuit', 'breaker', 'integration'],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Libraries',
],
platforms=[
'Any',
],
license='BSD',
author='Daniel Fernandes Martins',
author_email='daniel.tritone@gmail.com',
url='http://github.com/danielfm/pybreaker',
package_dir={'': 'src'},
py_modules=['pybreaker'],
install_requires=[
'six',
],
include_package_data=True,
zip_safe=False,
test_suite='tests',
tests_require=['mock', 'fakeredis==0.16.0', 'redis==2.10.6', 'tornado'],
)
| #!/usr/bin/env python
#-*- coding:utf-8 -*-
from setuptools import setup
setup(
name='pybreaker',
version='0.6.0',
description='Python implementation of the Circuit Breaker pattern',
long_description=open('README.rst', 'r').read(),
keywords=['design', 'pattern', 'circuit', 'breaker', 'integration'],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Libraries',
],
platforms=[
'Any',
],
license='BSD',
author='Daniel Fernandes Martins',
author_email='daniel.tritone@gmail.com',
url='http://github.com/danielfm/pybreaker',
package_dir={'': 'src'},
py_modules=['pybreaker'],
install_requires=[
'six',
],
include_package_data=True,
zip_safe=False,
test_suite='tests',
tests_require=['mock', 'fakeredis==0.16.0', 'redis==2.10.6', 'tornado'],
)
| Update classifiers to drop support for Python 2.7 | Update classifiers to drop support for Python 2.7 | Python | bsd-3-clause | danielfm/pybreaker | ---
+++
@@ -14,7 +14,6 @@
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
- 'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Libraries',
], |
97f5bbf5c99a40b8204c1e818e3bc8d897f822f0 | setup.py | setup.py | import sys
from setuptools import setup
from betfairlightweight.__init__ import __version__
INSTALL_REQUIRES = [
'requests',
]
TEST_REQUIRES = [
'mock'
]
if sys.version_info < (3,4):
INSTALL_REQUIRES.extend([
'enum34',
])
setup(
name='betfairlightweight',
version=__version__,
packages=['betfairlightweight', 'betfairlightweight.endpoints',
'betfairlightweight.resources', 'betfairlightweight.streaming'],
package_dir={'betfairlightweight': 'betfairlightweight'},
install_requires=INSTALL_REQUIRES,
requires=['requests'],
url='https://github.com/liampauling/betfairlightweight',
license='MIT',
author='liampauling',
author_email='',
description='Lightweight python wrapper for Betfair API-NG',
classifiers=[
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
test_suite='tests'
)
| import sys
import re
from setuptools import setup
INSTALL_REQUIRES = [
'requests',
]
TEST_REQUIRES = [
'mock'
]
if sys.version_info < (3,4):
INSTALL_REQUIRES.extend([
'enum34',
])
with open('betfairlightweight/__init__.py', 'r') as f:
version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]',
f.read(), re.MULTILINE).group(1)
setup(
name='betfairlightweight',
version=version,
packages=['betfairlightweight', 'betfairlightweight.endpoints',
'betfairlightweight.resources', 'betfairlightweight.streaming'],
package_dir={'betfairlightweight': 'betfairlightweight'},
install_requires=INSTALL_REQUIRES,
requires=['requests'],
url='https://github.com/liampauling/betfairlightweight',
license='MIT',
author='liampauling',
author_email='',
description='Lightweight python wrapper for Betfair API-NG',
classifiers=[
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
test_suite='tests'
)
| Read __version__ with regex to avoid ImportError | Read __version__ with regex to avoid ImportError
| Python | mit | liampauling/betfairlightweight,liampauling/betfair | ---
+++
@@ -1,7 +1,7 @@
import sys
+import re
from setuptools import setup
-from betfairlightweight.__init__ import __version__
INSTALL_REQUIRES = [
@@ -16,9 +16,13 @@
'enum34',
])
+with open('betfairlightweight/__init__.py', 'r') as f:
+ version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]',
+ f.read(), re.MULTILINE).group(1)
+
setup(
name='betfairlightweight',
- version=__version__,
+ version=version,
packages=['betfairlightweight', 'betfairlightweight.endpoints',
'betfairlightweight.resources', 'betfairlightweight.streaming'],
package_dir={'betfairlightweight': 'betfairlightweight'}, |
67a12d44699e4bb8e3b6895ab10c9bb2477ed7fc | tests/fd_io.py | tests/fd_io.py | from filedes.test.base import BaseFDTestCase
from filedes import FD
import os
import errno
class TestFDIO(BaseFDTestCase):
def testReadWrite(self):
r, w = os.pipe()
self.assertEquals(FD(w).write("OK"), 2)
self.assertEquals(FD(r).read(2), "OK")
FD(r).close()
FD(w).close()
def testWriteAfterClose(self):
r, w = os.pipe()
fw = FD(w)
fw.close()
with self.assertRaises(OSError):
fw.write("oops")
FD(r).close()
def testNonblocking(self):
r, w = os.pipe()
fr = FD(r)
try:
fr.set_nonblocking()
with self.assertRaises(OSError) as ar:
fr.read(1)
self.assertEquals(ar.exception.errno, errno.EAGAIN)
finally:
fr.close()
FD(w).close()
| from filedes.test.base import BaseFDTestCase
from filedes import FD
import os
import errno
class TestFDIO(BaseFDTestCase):
def testReadWrite(self):
r, w = os.pipe()
self.assertEquals(FD(w).write("OK"), 2)
self.assertEquals(FD(r).read(2), "OK")
FD(r).close()
FD(w).close()
def testWriteAfterClose(self):
r, w = os.pipe()
fw = FD(w)
fw.close()
try:
with self.assertRaises(OSError) as ar:
fw.write("oops")
self.assertEquals(ar.exception.errno, errno.EBADF)
finally:
FD(r).close()
def testNonblocking(self):
r, w = os.pipe()
fr = FD(r)
try:
fr.set_nonblocking()
with self.assertRaises(OSError) as ar:
fr.read(1)
self.assertEquals(ar.exception.errno, errno.EAGAIN)
finally:
fr.close()
FD(w).close()
| Check for EBADF in write-to-closed fd test case | Check for EBADF in write-to-closed fd test case
| Python | isc | fmoo/python-filedes,fmoo/python-filedes | ---
+++
@@ -16,9 +16,12 @@
r, w = os.pipe()
fw = FD(w)
fw.close()
- with self.assertRaises(OSError):
- fw.write("oops")
- FD(r).close()
+ try:
+ with self.assertRaises(OSError) as ar:
+ fw.write("oops")
+ self.assertEquals(ar.exception.errno, errno.EBADF)
+ finally:
+ FD(r).close()
def testNonblocking(self):
r, w = os.pipe() |
912b8a90472fc39f7c5d3b8e1e44b57aa88c0b02 | setup.py | setup.py | #!/usr/bin/env python
from distutils.core import setup
setup(name='Numspell',
version='0.9',
description='A Python module for spelling numbers',
author='Alexei Sholik',
author_email='alcosholik@gmail.com',
url='https://github.com/alco/numspell',
license="MIT",
packages=['numspell'],
data_files=[('/usr/bin', ['spellnum'])],
)
| #!/usr/bin/env python
from distutils.core import setup
setup(name='Numspell',
version='0.9',
description='A Python module for spelling numbers',
author='Alexei Sholik',
author_email='alcosholik@gmail.com',
url='https://github.com/alco/numspell',
license="MIT",
packages=['numspell'],
scripts=['spellnum'],
)
| Add more idiomatic (and also portable) way to install `spellnum` script | Add more idiomatic (and also portable) way to install `spellnum` script
| Python | mit | alco/numspell,alco/numspell | ---
+++
@@ -10,5 +10,5 @@
url='https://github.com/alco/numspell',
license="MIT",
packages=['numspell'],
- data_files=[('/usr/bin', ['spellnum'])],
+ scripts=['spellnum'],
) |
7bbdd8b41e6cb2afb64a7b860e51553748a160bc | setup.py | setup.py | import setuptools
setuptools.setup(
name="Mongothon",
version="0.7.16",
author="Tom Leach",
author_email="tom@gc.io",
description="A MongoDB object-document mapping layer for Python",
license="BSD",
keywords="mongo mongodb database pymongo odm validation",
url="http://github.com/gamechanger/mongothon",
packages=["mongothon"],
long_description="Mongothon is a MongoDB object-document mapping " +
"API for Python, loosely based on the awesome " +
"mongoose.js library.",
install_requires=['pymongo>=2.5.0', 'inflection==0.2.0', 'schemer==0.2.4'],
tests_require=['mock', 'nose']
)
| import setuptools
setuptools.setup(
name="Mongothon",
version="0.7.17",
author="Tom Leach",
author_email="tom@gc.io",
description="A MongoDB object-document mapping layer for Python",
license="BSD",
keywords="mongo mongodb database pymongo odm validation",
url="http://github.com/gamechanger/mongothon",
packages=["mongothon"],
long_description="Mongothon is a MongoDB object-document mapping " +
"API for Python, loosely based on the awesome " +
"mongoose.js library.",
install_requires=['pymongo>=2.5.0', 'inflection==0.2.0', 'schemer>=0.2.0, <0.3.0'],
tests_require=['mock', 'nose']
)
| Use new version of Schemer and make the version float | Use new version of Schemer and make the version float
| Python | mit | gamechanger/mongothon | ---
+++
@@ -3,7 +3,7 @@
setuptools.setup(
name="Mongothon",
- version="0.7.16",
+ version="0.7.17",
author="Tom Leach",
author_email="tom@gc.io",
description="A MongoDB object-document mapping layer for Python",
@@ -14,6 +14,6 @@
long_description="Mongothon is a MongoDB object-document mapping " +
"API for Python, loosely based on the awesome " +
"mongoose.js library.",
- install_requires=['pymongo>=2.5.0', 'inflection==0.2.0', 'schemer==0.2.4'],
+ install_requires=['pymongo>=2.5.0', 'inflection==0.2.0', 'schemer>=0.2.0, <0.3.0'],
tests_require=['mock', 'nose']
) |
9dcd5a0f963a716e669d59429b3a8242cd65ffab | setup.py | setup.py | #!/usr/bin/env python
from setuptools import setup, find_packages
packages = find_packages()
desc = open("README.md").read(),
setup(name='cooperhewitt-swatchbook',
version='0.3',
description='Cooper Hewitt\'s Python tools for wrangling colours',
long_description=desc,
author='Cooper Hewitt Smithsonian Design Museum',
url='https://github.com/cooperhewitt/py-cooperhewitt-swatchbook',
requires=['colorsys', 'webcolors', 'colormath (<2.0)'],
packages=packages,
scripts=[],
download_url='https://github.com/cooperhewitt/py-cooperhewitt-swatchbook/releases/tag/v0.3',
license='BSD')
| #!/usr/bin/env python
from setuptools import setup, find_packages
packages = find_packages()
desc = open("README.md").read(),
setup(name='cooperhewitt-swatchbook',
version='0.3',
description='Cooper Hewitt\'s Python tools for wrangling colours',
long_description=desc,
author='Cooper Hewitt Smithsonian Design Museum',
url='https://github.com/cooperhewitt/py-cooperhewitt-swatchbook',
requires=['colorsys', 'webcolors', 'colormath (<2.0)'],
install_requires=['webcolors', 'colormath<2.0'],
packages=packages,
scripts=[],
download_url='https://github.com/cooperhewitt/py-cooperhewitt-swatchbook/releases/tag/v0.3',
license='BSD')
| Add pip requirements support with install_requires | Add pip requirements support with install_requires
| Python | bsd-3-clause | cooperhewitt/py-cooperhewitt-swatchbook | ---
+++
@@ -12,6 +12,7 @@
author='Cooper Hewitt Smithsonian Design Museum',
url='https://github.com/cooperhewitt/py-cooperhewitt-swatchbook',
requires=['colorsys', 'webcolors', 'colormath (<2.0)'],
+ install_requires=['webcolors', 'colormath<2.0'],
packages=packages,
scripts=[],
download_url='https://github.com/cooperhewitt/py-cooperhewitt-swatchbook/releases/tag/v0.3', |
3a34bed3e0fdcfdc1d13b50f0b16b367d1133609 | setup.py | setup.py | #!/usr/bin/env python
# -*- coding:utf-8 -*-
""" Setup script for csft """
import sys
from setuptools import find_packages, setup
import csft
requires = [
'argparse >= 1.2.1',
'pandas >= 0.20.1',
'pathlib >= 1.0.1',
]
if sys.version <= '3.5':
requires.append('scandir >= 1.5')
setup(
name=csft.__name__,
description=csft.__doc__,
version=csft.__version__,
author=csft.__author__,
license=csft.__license__,
author_email=csft.__email__,
url=csft.__url__,
packages=find_packages(),
entry_points={
'console_scripts': (
'csft = csft.__main__:main',
),
},
install_requires=requires,
)
| #!/usr/bin/env python
# -*- coding:utf-8 -*-
""" Setup script for csft """
import sys
from setuptools import find_packages, setup
import csft
requires = [
'argparse >= 1.2.1',
'pandas >= 0.20.1',
]
if sys.version < '3.4':
requires.append('pathlib >= 1.0.1')
if sys.version < '3.5':
requires.append('scandir >= 1.5')
setup(
name=csft.__name__,
description=csft.__doc__,
version=csft.__version__,
author=csft.__author__,
license=csft.__license__,
author_email=csft.__email__,
url=csft.__url__,
packages=find_packages(),
entry_points={
'console_scripts': (
'csft = csft.__main__:main',
),
},
install_requires=requires,
)
| Use the standard pathlib after Python 3.4 | Use the standard pathlib after Python 3.4
| Python | mit | yanqd0/csft | ---
+++
@@ -12,10 +12,12 @@
requires = [
'argparse >= 1.2.1',
'pandas >= 0.20.1',
- 'pathlib >= 1.0.1',
]
-if sys.version <= '3.5':
+if sys.version < '3.4':
+ requires.append('pathlib >= 1.0.1')
+
+if sys.version < '3.5':
requires.append('scandir >= 1.5')
setup( |
a3064f6feeabc47b01fb01e75771646400c80949 | setup.py | setup.py | from setuptools import setup
setup(name='uvp_adb',
version='1.0',
description='adb functions for uvp phone',
url='https://www.linkedin.com/in/sajjad-ziyaei-amiri-a1a16b9b',
author='Sajjad Ziyaei amiri',
author_email='szaforward@gmail.com',
license='MIT',
packages=['uvp_adb'],
zip_safe=False) | from setuptools import setup
setup(name='uvp_adb',
version='1.0',
description='adb functions for uvp phone',
url='https://github.com/inforfang/uvp_adb',
download_url = 'https://github.com/inforfang/uvp_adb/tarball/1.0',
author='inforfang',
author_email='szaforward2@gmail.com',
license='MIT',
packages=['uvp_adb'],
zip_safe=False)
| Correct urldownload and email address | Correct urldownload and email address
| Python | mit | inforfang/uvp_adb | ---
+++
@@ -3,9 +3,10 @@
setup(name='uvp_adb',
version='1.0',
description='adb functions for uvp phone',
- url='https://www.linkedin.com/in/sajjad-ziyaei-amiri-a1a16b9b',
- author='Sajjad Ziyaei amiri',
- author_email='szaforward@gmail.com',
+ url='https://github.com/inforfang/uvp_adb',
+ download_url = 'https://github.com/inforfang/uvp_adb/tarball/1.0',
+ author='inforfang',
+ author_email='szaforward2@gmail.com',
license='MIT',
packages=['uvp_adb'],
zip_safe=False) |
5004b500284ec1d0f709b3069867757770601c44 | mla_game/apps/transcript/management/commands/recalculate_phrase_game_mappings.py | mla_game/apps/transcript/management/commands/recalculate_phrase_game_mappings.py | from django.core.management.base import BaseCommand
from django.conf import settings
from ...models import TranscriptPhrase
from ...tasks import assign_current_game
phrase_positive_limit = settings.TRANSCRIPT_PHRASE_POSITIVE_CONFIDENCE_LIMIT
phrase_negative_limit = settings.TRANSCRIPT_PHRASE_NEGATIVE_CONFIDENCE_LIMIT
correction_lower_limit = settings.TRANSCRIPT_PHRASE_CORRECTION_LOWER_LIMIT
correction_upper_limit = settings.TRANSCRIPT_PHRASE_CORRECTION_UPPER_LIMIT
class Command(BaseCommand):
help = '''Recalculate game eligiblity for all phrases'''
def handle(self, *args, **options):
for phrase in TranscriptPhrase.objects.all():
assign_current_game(phrase)
| from django.core.management.base import BaseCommand
from django.conf import settings
from ...models import TranscriptPhraseVote
from ...tasks import assign_current_game
phrase_positive_limit = settings.TRANSCRIPT_PHRASE_POSITIVE_CONFIDENCE_LIMIT
phrase_negative_limit = settings.TRANSCRIPT_PHRASE_NEGATIVE_CONFIDENCE_LIMIT
correction_lower_limit = settings.TRANSCRIPT_PHRASE_CORRECTION_LOWER_LIMIT
correction_upper_limit = settings.TRANSCRIPT_PHRASE_CORRECTION_UPPER_LIMIT
class Command(BaseCommand):
help = '''Recalculate game eligiblity for all phrases'''
def handle(self, *args, **options):
to_assign = set()
for vote in TranscriptPhraseVote.objects.all():
to_assign.add(vote.transcript_phrase)
for phrase in to_assign:
assign_current_game(phrase)
| Update only phrases with user input | Update only phrases with user input
| Python | mit | WGBH/FixIt,WGBH/FixIt,WGBH/FixIt | ---
+++
@@ -1,7 +1,7 @@
from django.core.management.base import BaseCommand
from django.conf import settings
-from ...models import TranscriptPhrase
+from ...models import TranscriptPhraseVote
from ...tasks import assign_current_game
phrase_positive_limit = settings.TRANSCRIPT_PHRASE_POSITIVE_CONFIDENCE_LIMIT
@@ -14,5 +14,8 @@
help = '''Recalculate game eligiblity for all phrases'''
def handle(self, *args, **options):
- for phrase in TranscriptPhrase.objects.all():
+ to_assign = set()
+ for vote in TranscriptPhraseVote.objects.all():
+ to_assign.add(vote.transcript_phrase)
+ for phrase in to_assign:
assign_current_game(phrase) |
05b5a4390c7109bb8c0778c547883c41272769fb | examples/oauth.py | examples/oauth.py | import tweepy
# == OAuth Authentication ==
#
# This mode of authentication is the new preferred way
# of authenticating with Twitter.
# The consumer keys can be found on your application's Details
# page located at https://dev.twitter.com/apps (under "OAuth settings")
consumer_key=""
consumer_secret=""
# The access tokens can be found on your applications's Details
# page located at https://dev.twitter.com/apps (located
# under "Your access token")
access_token=""
access_token_secret=""
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
# If the authentication was successful, you should
# see the name of the account print out
print api.me().name
# If the application settings are set for "Read and Write" then
# this line should tweet out the message to your account's
# timeline. The "Read and Write" setting is on https://dev.twitter.com/apps
api.update_status('Updating using OAuth authentication via Tweepy!')
| import tweepy
# == OAuth Authentication ==
#
# This mode of authentication is the new preferred way
# of authenticating with Twitter.
# The consumer keys can be found on your application's Details
# page located at https://dev.twitter.com/apps (under "OAuth settings")
consumer_key=""
consumer_secret=""
# The access tokens can be found on your applications's Details
# page located at https://dev.twitter.com/apps (located
# under "Your access token")
access_token=""
access_token_secret=""
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.secure = True
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
# If the authentication was successful, you should
# see the name of the account print out
print api.me().name
# If the application settings are set for "Read and Write" then
# this line should tweet out the message to your account's
# timeline. The "Read and Write" setting is on https://dev.twitter.com/apps
api.update_status('Updating using OAuth authentication via Tweepy!')
| Change to make sure tweepy use SSL | Change to make sure tweepy use SSL
I had some problems using Tweepy and I realized it was because it didn't always use SSL. So I propose to add a line to make sure the connexion we use is secure. | Python | mit | vishnugonela/tweepy,iamjakob/tweepy,srimanthd/tweepy,sa8/tweepy,awangga/tweepy,zhenv5/tweepy,kcompher/tweepy,damchilly/tweepy,edsu/tweepy,cogniteev/tweepy,yared-bezum/tweepy,truekonrads/tweepy,tweepy/tweepy,Choko256/tweepy,elijah513/tweepy,tsablic/tweepy,hackebrot/tweepy,rudraksh125/tweepy,atomicjets/tweepy,IsaacHaze/tweepy,aleczadikian/tweepy,bconnelly/tweepy,LikeABird/tweepy,kylemanna/tweepy,conversocial/tweepy,vikasgorur/tweepy,arunxarun/tweepy,kskk02/tweepy,robbiewoods05/tweepy,sidewire/tweepy,aganzha/tweepy,obskyr/tweepy,raymondethan/tweepy,thelostscientist/tweepy,tuxos/tweepy,vivek8943/tweepy,techieshark/tweepy,svven/tweepy,wjt/tweepy,takeshineshiro/tweepy | ---
+++
@@ -17,6 +17,7 @@
access_token_secret=""
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
+auth.secure = True
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth) |
1d8f7d4a57b145fa3f8cce12a55b02eb0a754581 | crypto/envelope.py | crypto/envelope.py | """ Sealed envelope example from Princeton course
'Intro to Crypto and Cryptocurrencies'
https://www.youtube.com/watch?v=fOMVZXLjKYo
"""
import hashlib
def commit(key, msg):
m = hashlib.sha256()
m.update(key)
m.update(msg)
return {
"hash": m.hexdigest(),
"key": key
}
def verify(com, key, msg):
v = hashlib.sha256()
v.update(key)
v.update(msg)
try:
assert v.hexdigest() == com
return "Message has been verified"
except:
raise
sealed_msg = 'there'
msg = commit('hey', sealed_msg)
public_msg = msg.get('hash')
print(verify(public_msg, msg.get('key'), sealed_msg)) | """ Sealed envelope example from Princeton course
'Intro to Crypto and Cryptocurrencies'
https://www.youtube.com/watch?v=fOMVZXLjKYo
"""
import hashlib
def commit(key, msg):
m = hashlib.sha256()
m.update(key)
m.update(msg)
return {
"hash": m.hexdigest(),
"key": key
}
def verify(com, key, msg):
v = hashlib.sha256()
v.update(key)
v.update(msg)
try:
assert v.hexdigest() == com
return "Message has been verified"
except:
raise
sealed_msg = 'there'
key = hashlib.sha256().hexdigest()
msg = commit(key, sealed_msg)
public_msg = msg.get('hash')
print(verify(public_msg, msg.get('key'), sealed_msg)) | Make the key 'more secure' | Make the key 'more secure'
| Python | mit | b-ritter/python-notes,b-ritter/python-notes | ---
+++
@@ -26,7 +26,9 @@
sealed_msg = 'there'
-msg = commit('hey', sealed_msg)
+key = hashlib.sha256().hexdigest()
+
+msg = commit(key, sealed_msg)
public_msg = msg.get('hash')
|
2997b84a5ead65f6c17128baef3e3039957d97f8 | dduplicated/cli.py | dduplicated/cli.py | # The client of DDuplicated tool.
from os import path as opath, getcwd
from sys import argv
from dduplicated import commands
def get_paths(params):
paths = []
for param in params:
path = opath.join(getcwd(), param)
if opath.exists(path) and opath.isdir(path) and not opath.islink(path):
paths.append(path)
return paths
def main():
params = argv
processed_files = []
# Remove the command name
del params[0]
if len(params) == 0 or "help" in params:
commands.help()
elif "detect" in params:
processed_files = commands.detect(get_paths(params))
elif "delete" in params:
processed_files = commands.delete(commands.detect(get_paths(params)))
elif "link" in params:
processed_files = commands.link(commands.detect(get_paths(params)))
else:
commands.help()
if len(processed_files) > 0:
print(processed_files)
else:
print("No duplicates found")
print("Great! Bye!")
exit(0)
| # The client of DDuplicated tool.
from os import path as opath, getcwd
from pprint import pprint
from sys import argv
from dduplicated import commands
def get_paths(params):
paths = []
for param in params:
path = opath.join(getcwd(), param)
if opath.exists(path) and opath.isdir(path) and not opath.islink(path):
paths.append(path)
return paths
def main():
params = argv
processed_files = []
# Remove the command name
del params[0]
if len(params) == 0 or "help" in params:
commands.help()
elif "detect" in params:
processed_files = commands.detect(get_paths(params))
elif "delete" in params:
processed_files = commands.delete(commands.detect(get_paths(params)))
elif "link" in params:
processed_files = commands.link(commands.detect(get_paths(params)))
else:
commands.help()
if len(processed_files) > 0:
pprint(processed_files)
else:
print("No duplicates found")
print("Great! Bye!")
exit(0)
| Update in output to terminal. | Update in output to terminal.
Signed-off-by: messiasthi <8562fc1efba9a3c99753c749fdfb1b6932b70fbf@gmail.com>
| Python | mit | messiasthi/dduplicated-cli | ---
+++
@@ -1,5 +1,6 @@
# The client of DDuplicated tool.
from os import path as opath, getcwd
+from pprint import pprint
from sys import argv
from dduplicated import commands
@@ -35,7 +36,7 @@
commands.help()
if len(processed_files) > 0:
- print(processed_files)
+ pprint(processed_files)
else:
print("No duplicates found")
print("Great! Bye!") |
b1efc997c510fbdcaeb8d3ba9b4202ac810bb9ff | util/html_clean.py | util/html_clean.py | import bleach
DESCR_ALLOWED_TAGS = bleach.ALLOWED_TAGS + ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']
USER_DESCR_ALLOWED_TAGS = bleach.ALLOWED_TAGS + ['h2', 'h3', 'h4', 'h5', 'h6']
def clean_for_user_description(html):
"""
Removes dangerous tags, including h1.
"""
return bleach.clean(html, tags=USER_DESCR_ALLOWED_TAGS, strip=True)
def clean_for_description(html):
"""
Removes dangerous tags.
"""
return bleach.clean(html, tags=DESCR_ALLOWED_TAGS, strip=True)
def clean_all(html):
"""
Removes *all* html tags.
"""
return bleach.clean(html, tags=[], styles=[], attributes=[], strip=True)
| import bleach
DESCR_ALLOWED_TAGS = bleach.ALLOWED_TAGS + ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'br', 'p']
USER_DESCR_ALLOWED_TAGS = bleach.ALLOWED_TAGS + ['h2', 'h3', 'h4', 'h5', 'h6', 'br', 'p']
def clean_for_user_description(html):
"""
Removes dangerous tags, including h1.
"""
return bleach.clean(html, tags=USER_DESCR_ALLOWED_TAGS, strip=True)
def clean_for_description(html):
"""
Removes dangerous tags.
"""
return bleach.clean(html, tags=DESCR_ALLOWED_TAGS, strip=True)
def clean_all(html):
"""
Removes *all* html tags.
"""
return bleach.clean(html, tags=[], styles=[], attributes=[], strip=True)
| Allow <br /> and <p> in descriptions | Allow <br /> and <p> in descriptions
| Python | bsd-3-clause | fsr/course-management,fsr/course-management | ---
+++
@@ -1,8 +1,8 @@
import bleach
-DESCR_ALLOWED_TAGS = bleach.ALLOWED_TAGS + ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']
-USER_DESCR_ALLOWED_TAGS = bleach.ALLOWED_TAGS + ['h2', 'h3', 'h4', 'h5', 'h6']
+DESCR_ALLOWED_TAGS = bleach.ALLOWED_TAGS + ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'br', 'p']
+USER_DESCR_ALLOWED_TAGS = bleach.ALLOWED_TAGS + ['h2', 'h3', 'h4', 'h5', 'h6', 'br', 'p']
def clean_for_user_description(html): |
4673b980252f5fd4c490652d9af63eac02506614 | dimod/reference/composites/structure.py | dimod/reference/composites/structure.py | from dimod.core.sampler import Sampler
from dimod.core.composite import Composite
from dimod.core.structured import Structured
from dimod.decorators import bqm_structured
class StructureComposite(Sampler, Composite, Structured):
"""Creates a structured composed sampler from an unstructured sampler.
todo
"""
def __init__(self, sampler, nodelist, edgelist):
Sampler.__init__(self)
Composite.__init__(self, sampler)
Structured.__init__(self, nodelist, edgelist)
@bqm_structured
def sample(self, bqm, **sample_kwargs):
return self.child.sample(bqm, **sample_kwargs)
| from dimod.core.sampler import Sampler
from dimod.core.composite import Composite
from dimod.core.structured import Structured
from dimod.decorators import bqm_structured
class StructureComposite(Sampler, Composite, Structured):
"""Creates a structured composed sampler from an unstructured sampler.
"""
# we will override these in the __init__, but because they are abstract properties we need to
# signal that we are overriding them
edgelist = None
nodelist = None
children = None
def __init__(self, sampler, nodelist, edgelist):
self.children = [sampler]
self.nodelist = nodelist
self.edgelist = edgelist
@property
def parameters(self):
return self.child.parameters
@property
def properties(self):
return self.child.properties
@bqm_structured
def sample(self, bqm, **sample_kwargs):
return self.child.sample(bqm, **sample_kwargs)
| Update Structure composite to use the new abc | Update Structure composite to use the new abc
| Python | apache-2.0 | dwavesystems/dimod,dwavesystems/dimod | ---
+++
@@ -6,13 +6,25 @@
class StructureComposite(Sampler, Composite, Structured):
"""Creates a structured composed sampler from an unstructured sampler.
+ """
+ # we will override these in the __init__, but because they are abstract properties we need to
+ # signal that we are overriding them
+ edgelist = None
+ nodelist = None
+ children = None
- todo
- """
def __init__(self, sampler, nodelist, edgelist):
- Sampler.__init__(self)
- Composite.__init__(self, sampler)
- Structured.__init__(self, nodelist, edgelist)
+ self.children = [sampler]
+ self.nodelist = nodelist
+ self.edgelist = edgelist
+
+ @property
+ def parameters(self):
+ return self.child.parameters
+
+ @property
+ def properties(self):
+ return self.child.properties
@bqm_structured
def sample(self, bqm, **sample_kwargs): |
6d38920c1867921235c002b6ad411fd08378dd1f | fluent_contents/tests/test_models.py | fluent_contents/tests/test_models.py | from django.contrib.contenttypes.models import ContentType
from fluent_contents.models import ContentItem
from fluent_contents.tests.utils import AppTestCase
class ModelTests(AppTestCase):
"""
Testing the data model.
"""
def test_stale_model_str(self):
"""
No matter what, the ContentItem.__str__() should work.
This would break the admin delete screen otherwise.
"""
c = ContentType()
a = ContentItem(polymorphic_ctype=c)
self.assertEqual(str(a), "'(type deleted) 0' in 'None None'")
| from django.contrib.contenttypes.models import ContentType
from fluent_contents.models import ContentItem
from fluent_contents.tests.utils import AppTestCase
class ModelTests(AppTestCase):
"""
Testing the data model.
"""
def test_stale_model_str(self):
"""
No matter what, the ContentItem.__str__() should work.
This would break the admin delete screen otherwise.
"""
c = ContentType()
c.save()
a = ContentItem(polymorphic_ctype=c)
self.assertEqual(str(a), "'(type deleted) 0' in 'None None'")
| Fix Django 1.8+ tests for stale content type | Fix Django 1.8+ tests for stale content type
| Python | apache-2.0 | django-fluent/django-fluent-contents,edoburu/django-fluent-contents,edoburu/django-fluent-contents,django-fluent/django-fluent-contents,django-fluent/django-fluent-contents,edoburu/django-fluent-contents | ---
+++
@@ -15,5 +15,6 @@
This would break the admin delete screen otherwise.
"""
c = ContentType()
+ c.save()
a = ContentItem(polymorphic_ctype=c)
self.assertEqual(str(a), "'(type deleted) 0' in 'None None'") |
a16a822ede8ad987b2234f29a31f9fe79c27cbd5 | dbaas/workflow/steps/util/clone/clone_database.py | dbaas/workflow/steps/util/clone/clone_database.py | # -*- coding: utf-8 -*-
import logging
from util import full_stack
from util import call_script
from django.conf import settings
from drivers import factory_for
from system.models import Configuration
from notification.util import get_clone_args
from ...base import BaseStep
from ....exceptions.error_codes import DBAAS_0017
LOG = logging.getLogger(__name__)
class CloneDatabase(BaseStep):
def __unicode__(self):
return "Replicating database data..."
def do(self, workflow_dict):
try:
if 'databaseinfra' not in workflow_dict \
or 'clone' not in workflow_dict :
return False
args = get_clone_args(workflow_dict['clone'], workflow_dict['database'])
script_name = factory_for(workflow_dict['clone'].databaseinfra).clone()
python_bin= Configuration.get_by_name('python_venv_bin')
return_code, output = call_script(script_name, working_dir=settings.SCRIPTS_PATH
, args=args, split_lines=False, python_bin=python_bin)
LOG.info("Script Output: {}".format(output))
LOG.info("Return code: {}".format(return_code))
if return_code != 0:
return False
return True
except Exception:
traceback = full_stack()
workflow_dict['exceptions']['error_codes'].append(DBAAS_0017)
workflow_dict['exceptions']['traceback'].append(traceback)
return False
def undo(self, workflow_dict):
LOG.info("Nothing to do here...")
return True
| # -*- coding: utf-8 -*-
import logging
from util import full_stack
from util import call_script
from django.conf import settings
from drivers import factory_for
from system.models import Configuration
from notification.util import get_clone_args
from ...base import BaseStep
from ....exceptions.error_codes import DBAAS_0017
LOG = logging.getLogger(__name__)
class CloneDatabase(BaseStep):
def __unicode__(self):
return "Replicating database data..."
def do(self, workflow_dict):
try:
if 'databaseinfra' not in workflow_dict \
or 'clone' not in workflow_dict :
return False
args = get_clone_args(workflow_dict['clone'], workflow_dict['database'])
script_name = factory_for(workflow_dict['clone'].databaseinfra).clone()
python_bin= Configuration.get_by_name('python_venv_bin')
return_code, output = call_script(script_name, working_dir=settings.SCRIPTS_PATH
, args=args, split_lines=False, python_bin=python_bin)
LOG.info("Script Output: {}".format(output))
LOG.info("Return code: {}".format(return_code))
if return_code != 0:
workflow_dict['exceptions']['traceback'].append(output)
return False
return True
except Exception:
traceback = full_stack()
workflow_dict['exceptions']['error_codes'].append(DBAAS_0017)
workflow_dict['exceptions']['traceback'].append(traceback)
return False
def undo(self, workflow_dict):
LOG.info("Nothing to do here...")
return True
| Add call_script output to workflow_dict traceback | Add call_script output to workflow_dict traceback
| Python | bsd-3-clause | globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service | ---
+++
@@ -35,6 +35,7 @@
LOG.info("Return code: {}".format(return_code))
if return_code != 0:
+ workflow_dict['exceptions']['traceback'].append(output)
return False
return True |
870c89649032480587bdb03ae31f4eecf21eebf7 | tldr/parser.py | tldr/parser.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import click
def parse_page(page):
"""Parse the command man page."""
with open(page) as f:
lines = f.readlines()
for line in lines:
if line.startswith('#'):
continue
elif line.startswith('>'):
click.secho(line.replace('>', ' '), fg='blue', nl=False)
elif line.startswith('-'):
click.secho(line, fg='green', nl=False)
elif line.startswith('`'):
click.secho(' ' + line.replace('`', ''), fg='cyan', nl=False)
else:
click.secho(line, nl=False)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import click
from tldr.config import get_config
def parse_page(page):
"""Parse the command man page."""
colors = get_config()['colors']
with open(page) as f:
lines = f.readlines()
for line in lines:
if line.startswith('#'):
continue
elif line.startswith('>'):
click.secho(line.replace('>', ' '), fg=colors['description'],
nl=False)
elif line.startswith('-'):
click.secho(line, fg=colors['usage'], nl=False)
elif line.startswith('`'):
click.secho(' ' + line.replace('`', ''), fg=colors['command'],
nl=False)
else:
click.secho(line, nl=False)
| Use color configurations from config file | Use color configurations from config file
| Python | mit | lord63/tldr.py | ---
+++
@@ -5,19 +5,24 @@
import click
+from tldr.config import get_config
+
def parse_page(page):
"""Parse the command man page."""
+ colors = get_config()['colors']
with open(page) as f:
lines = f.readlines()
for line in lines:
if line.startswith('#'):
continue
elif line.startswith('>'):
- click.secho(line.replace('>', ' '), fg='blue', nl=False)
+ click.secho(line.replace('>', ' '), fg=colors['description'],
+ nl=False)
elif line.startswith('-'):
- click.secho(line, fg='green', nl=False)
+ click.secho(line, fg=colors['usage'], nl=False)
elif line.startswith('`'):
- click.secho(' ' + line.replace('`', ''), fg='cyan', nl=False)
+ click.secho(' ' + line.replace('`', ''), fg=colors['command'],
+ nl=False)
else:
click.secho(line, nl=False) |
9710589f34e50bdf2fa19b1fcd827b07d4248ab6 | dodo_commands/extra/dodo_standard_commands/commit-config.py | dodo_commands/extra/dodo_standard_commands/commit-config.py | from argparse import ArgumentParser
from dodo_commands.framework import Dodo
from dodo_commands.framework.config import Paths
import os
def _args():
parser = ArgumentParser()
parser.add_argument('-m', dest='message')
args = Dodo.parse_args(parser)
return args
if Dodo.is_main(__name__, safe=True):
args = _args()
if not os.path.exists(os.path.join(Paths().res_dir(), '.git')):
Dodo.run(['git', 'init'], cwd=Paths().res_dir())
Dodo.run(['git', 'add', '-A'], cwd=Paths().res_dir())
Dodo.run(
['git', 'commit', '-m', args.message or 'Update configuration'],
cwd=Paths().res_dir())
| from argparse import ArgumentParser
from dodo_commands.framework import Dodo
from dodo_commands.framework.config import Paths
import os
def _args():
parser = ArgumentParser()
parser.add_argument(
'--message', '-m', dest='message', help='The commit message')
args = Dodo.parse_args(parser)
return args
if Dodo.is_main(__name__, safe=True):
args = _args()
if not os.path.exists(os.path.join(Paths().res_dir(), '.git')):
Dodo.run(['git', 'init'], cwd=Paths().res_dir())
Dodo.run(['git', 'add', '-A'], cwd=Paths().res_dir())
Dodo.run(['git', 'commit', '-m', args.message or 'Update configuration'],
cwd=Paths().res_dir())
| Allow both -m and --message | Allow both -m and --message
| Python | mit | mnieber/dodo_commands | ---
+++
@@ -6,7 +6,8 @@
def _args():
parser = ArgumentParser()
- parser.add_argument('-m', dest='message')
+ parser.add_argument(
+ '--message', '-m', dest='message', help='The commit message')
args = Dodo.parse_args(parser)
return args
@@ -18,6 +19,5 @@
Dodo.run(['git', 'init'], cwd=Paths().res_dir())
Dodo.run(['git', 'add', '-A'], cwd=Paths().res_dir())
- Dodo.run(
- ['git', 'commit', '-m', args.message or 'Update configuration'],
- cwd=Paths().res_dir())
+ Dodo.run(['git', 'commit', '-m', args.message or 'Update configuration'],
+ cwd=Paths().res_dir()) |
2ea8ad7608f73fea2657e8e67a6c2bfef01b08d8 | uchicagohvz/users/backend.py | uchicagohvz/users/backend.py | from django.contrib.auth import get_user_model
import ldap
User = get_user_model()
class UChicagoLDAPBackend(object):
LDAP_SERVER = "ldaps://ldap.uchicago.edu:636"
def authenticate(self, cnetid=None, password=None):
if cnetid and password:
cnetid = ldap.filter.escape_filter_chars(cnetid)
try:
conn.simple_bind_s("uid=%s,ou=people,dc=uchicago,dc=edu" % cnetid, password)
except ldap.INVALID_CREDENTIALS:
return None
try:
user = User.objects.get(username=cnetid)
except User.DoesNotExist:
query = "(&(uid=%s)(objectclass=inetOrgPerson))" % (cnetid)
result = conn.search_ext_s("dc=uchicago,dc=edu", ldap.SCOPE_SUBTREE, query)
if result:
user_data = result[0]
user = User.objects.create_user(username=cnetid, email=user_data['email'], first_name=user_data['givenName'], last_name=user_data['sn'])
return user
return None
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None | from django.contrib.auth import get_user_model
import ldap
User = get_user_model()
class UChicagoLDAPBackend(object):
LDAP_SERVER = "ldaps://ldap.uchicago.edu:636"
def authenticate(self, cnetid=None, password=None):
if cnetid and password:
cnetid = ldap.filter.escape_filter_chars(cnetid)
try:
conn.simple_bind_s("uid=%s,ou=people,dc=uchicago,dc=edu" % cnetid, password)
except ldap.INVALID_CREDENTIALS:
return None
try:
user = User.objects.get(username=cnetid)
except User.DoesNotExist:
query = "(&(uid=%s)(objectclass=inetOrgPerson))" % (cnetid)
result = conn.search_ext_s("dc=uchicago,dc=edu", ldap.SCOPE_SUBTREE, query)
if result:
user_data = result[0]
user = User.objects.create_user(username=cnetid, email=user_data['mail'], first_name=user_data['givenName'], last_name=user_data['sn'])
return user
return None
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None | Change email to mail in LDAP | Change email to mail in LDAP
| Python | mit | kz26/uchicago-hvz,kz26/uchicago-hvz,kz26/uchicago-hvz | ---
+++
@@ -20,7 +20,7 @@
result = conn.search_ext_s("dc=uchicago,dc=edu", ldap.SCOPE_SUBTREE, query)
if result:
user_data = result[0]
- user = User.objects.create_user(username=cnetid, email=user_data['email'], first_name=user_data['givenName'], last_name=user_data['sn'])
+ user = User.objects.create_user(username=cnetid, email=user_data['mail'], first_name=user_data['givenName'], last_name=user_data['sn'])
return user
return None
|
52ffc2b264cbacaee56017cd4a67df4511d60392 | celery/managers.py | celery/managers.py | from django.db import models
from celery.registry import tasks
from datetime import datetime, timedelta
__all__ = ["TaskManager", "PeriodicTaskManager"]
class TaskManager(models.Manager):
def get_task(self, task_id):
task, created = self.get_or_create(task_id=task_id)
return task
def is_done(self, task_id):
return self.get_task(task_id).is_done
def get_all_expired(self):
return self.filter(date_done__lt=datetime.now() - timedelta(days=5))
def delete_expired(self):
self.get_all_expired().delete()
def mark_as_done(self, task_id):
task, created = self.get_or_create(task_id=task_id, defaults={
"is_done": True})
if not created:
task.is_done = True
task.save()
class PeriodicTaskManager(models.Manager):
def get_waiting_tasks(self):
periodic_tasks = tasks.get_all_periodic()
waiting = []
for task_name, task in periodic_tasks.items():
task_meta, created = self.get_or_create(name=task_name)
# task_run.every must be a timedelta object.
run_at = task_meta.last_run_at + task.run_every
if datetime.now() > run_at:
waiting.append(task_meta)
return waiting
| from django.db import models
from celery.registry import tasks
from datetime import datetime, timedelta
__all__ = ["TaskManager", "PeriodicTaskManager"]
class TaskManager(models.Manager):
def get_task(self, task_id):
task, created = self.get_or_create(task_id=task_id)
return task
def is_done(self, task_id):
return self.get_task(task_id).is_done
def get_all_expired(self):
return self.filter(date_done__lt=datetime.now() - timedelta(days=5),
is_done=True)
def delete_expired(self):
self.get_all_expired().delete()
def mark_as_done(self, task_id):
task, created = self.get_or_create(task_id=task_id, defaults={
"is_done": True})
if not created:
task.is_done = True
task.save()
class PeriodicTaskManager(models.Manager):
def get_waiting_tasks(self):
periodic_tasks = tasks.get_all_periodic()
waiting = []
for task_name, task in periodic_tasks.items():
task_meta, created = self.get_or_create(name=task_name)
# task_run.every must be a timedelta object.
run_at = task_meta.last_run_at + task.run_every
if datetime.now() > run_at:
waiting.append(task_meta)
return waiting
| Add is_done=True to get_all_expired filter. | Add is_done=True to get_all_expired filter.
| Python | bsd-3-clause | WoLpH/celery,cbrepo/celery,cbrepo/celery,ask/celery,frac/celery,WoLpH/celery,mitsuhiko/celery,ask/celery,mitsuhiko/celery,frac/celery | ---
+++
@@ -15,7 +15,8 @@
return self.get_task(task_id).is_done
def get_all_expired(self):
- return self.filter(date_done__lt=datetime.now() - timedelta(days=5))
+ return self.filter(date_done__lt=datetime.now() - timedelta(days=5),
+ is_done=True)
def delete_expired(self):
self.get_all_expired().delete() |
697fbacc04bc41dea056377e85ba6b29949d8feb | wars/device.py | wars/device.py | import pygame
from pygame.locals import *
from wars.block import Block
class Device(object):
# Static params
height = 60
# Object params
blocks = []
title = None
pos_y = None
def __init__(self, title, pos):
self.title = title
self.pos_y = pos
self.blocks = []
def move_blocks(self, amount):
for block in self.blocks:
block.move(amount)
if block.right_edge() <= 0:
self.blocks.remove(block)
def add_block(self, block):
block.pos_y = self.pos_y * self.height
self.blocks.append(block)
def reset(self):
del self.blocks[:]
def draw(self, surface):
# Do all the drawing of yourself ans such
# TODO: Implement this..
# Draw the blocks into yourself
for block in self.blocks:
block.draw(surface)
| import pygame
from pygame.locals import *
from wars.block import Block
class Device(object):
# Static params
height = 60
# Object params
blocks = []
title = None
pos_y = None
def __init__(self, title, pos):
self.title = title
self.pos_y = pos
self.blocks = []
def move_blocks(self, amount):
for block in self.blocks:
block.move(amount)
if block.right_edge() <= 0:
self.blocks.remove(block)
del block
def add_block(self, block):
block.pos_y = self.pos_y * self.height
self.blocks.append(block)
def reset(self):
del self.blocks[:]
def draw(self, surface):
# Do all the drawing of yourself and such.
# As there is currently only one ST, this is omitted
# Draw the blocks into yourself
for block in self.blocks:
block.draw(surface)
| Remove objects when they are not used | Remove objects when they are not used
| Python | mit | cmol/wifi-wars | ---
+++
@@ -21,6 +21,7 @@
block.move(amount)
if block.right_edge() <= 0:
self.blocks.remove(block)
+ del block
def add_block(self, block):
block.pos_y = self.pos_y * self.height
@@ -30,8 +31,8 @@
del self.blocks[:]
def draw(self, surface):
- # Do all the drawing of yourself ans such
- # TODO: Implement this..
+ # Do all the drawing of yourself and such.
+ # As there is currently only one ST, this is omitted
# Draw the blocks into yourself
for block in self.blocks: |
5fc1735082c001d81d9cded4c694c12b7afac8a0 | scripts/scrape-ecdc-list.py | scripts/scrape-ecdc-list.py | #!/usr/bin/env python
import requests
import lxml.html
import pandas as pd
import sys
URL = "http://ecdc.europa.eu/en/healthtopics/zika_virus_infection/zika-outbreak/Pages/Zika-countries-with-transmission.aspx"
columns = [
"country",
"current_zika_transmission",
]
def scrape():
html = requests.get(URL).content
dom = lxml.html.fromstring(html)
table = dom.cssselect(".ms-rteTable-1")[0]
rows = table.cssselect("tr")[1:]
data = [ [ td.text_content().strip()
for td in tr.cssselect("td, th") ]
for tr in rows ]
df = pd.DataFrame(data, columns=columns)[columns]
return df
if __name__ == "__main__":
df = scrape()
df.to_csv(sys.stdout, index=False, encoding="utf-8")
| #!/usr/bin/env python
import requests
import lxml.html
import pandas as pd
import sys
URL = "http://ecdc.europa.eu/en/healthtopics/zika_virus_infection/zika-outbreak/Pages/Zika-countries-with-transmission.aspx"
columns = [
"country",
"current_zika_transmission",
]
def scrape():
html = requests.get(URL).content
dom = lxml.html.fromstring(html)
table = dom.cssselect(".ms-rteTable-1")[-1]
rows = table.cssselect("tr")[1:]
data = [ [ td.text_content().strip()
for td in tr.cssselect("td, th") ]
for tr in rows ]
df = pd.DataFrame(data, columns=columns)[columns]
return df
if __name__ == "__main__":
df = scrape()
df.to_csv(sys.stdout, index=False, encoding="utf-8")
| Update ECDC scraper for tweaked page structure | Update ECDC scraper for tweaked page structure
| Python | mit | BuzzFeedNews/zika-data | ---
+++
@@ -14,7 +14,7 @@
def scrape():
html = requests.get(URL).content
dom = lxml.html.fromstring(html)
- table = dom.cssselect(".ms-rteTable-1")[0]
+ table = dom.cssselect(".ms-rteTable-1")[-1]
rows = table.cssselect("tr")[1:]
data = [ [ td.text_content().strip()
for td in tr.cssselect("td, th") ] |
5d901fddb0c863f811b0de40c063bb00b50e5394 | ion/processes/bootstrap/plugins/bootstrap_core.py | ion/processes/bootstrap/plugins/bootstrap_core.py | #!/usr/bin/env python
__author__ = 'Michael Meisinger'
from ion.core.bootstrap_process import BootstrapPlugin, AbortBootstrap
from pyon.public import IonObject, RT
from pyon.util.containers import get_safe
from interface.objects import ActorIdentity, Org
class BootstrapCore(BootstrapPlugin):
"""
Bootstrap plugin for core system resources.
No service dependency
"""
def on_initial_bootstrap(self, process, config, **kwargs):
# Detect if system has been started before by the presence of the ION system actor
system_actor, _ = process.container.resource_registry.find_resources(
restype=RT.ActorIdentity, id_only=True)
if system_actor:
raise AbortBootstrap("System already initialized. Start with bootmode=restart or force_clean!")
# Possibly start the event persister here
# Create ION actor
actor_name = get_safe(config, "system.system_actor", "ionsystem")
sys_actor = ActorIdentity(name=actor_name, description="ION System Agent")
process.container.resource_registry.create(sys_actor)
# Store all resource types
# Store all event types
def on_restart(self, process, config, **kwargs):
pass
| #!/usr/bin/env python
__author__ = 'Michael Meisinger'
from ion.core.bootstrap_process import BootstrapPlugin, AbortBootstrap
from pyon.public import IonObject, RT
from pyon.util.containers import get_safe
from interface.objects import ActorIdentity, Org
class BootstrapCore(BootstrapPlugin):
"""
Bootstrap plugin for core system resources.
No service dependency
"""
def on_initial_bootstrap(self, process, config, **kwargs):
# Detect if system has been started before by the presence of the ION system actor
system_actor, _ = process.container.resource_registry.find_resources(
restype=RT.ActorIdentity, id_only=True)
if system_actor:
raise AbortBootstrap("System already initialized. Start with bootmode=restart or force_clean!")
# Possibly start the event persister here
# Create ION actor
actor_name = get_safe(config, "system.system_actor", "ionsystem")
sys_actor = ActorIdentity(name=actor_name, description="ION System Agent")
process.container.resource_registry.create(sys_actor)
webauth_actor_name = get_safe(config, "system.web_authentication_actor", "web_authentication")
web_auth_actor = ActorIdentity(name=webauth_actor_name, description="Web Authentication Actor")
process.container.resource_registry.create(web_auth_actor)
# Store all resource types
# Store all event types
def on_restart(self, process, config, **kwargs):
pass
| Add web authentication actor on bootstrap | Add web authentication actor on bootstrap
| Python | bsd-2-clause | ooici/coi-services,ooici/coi-services,ooici/coi-services,ooici/coi-services,ooici/coi-services | ---
+++
@@ -30,6 +30,10 @@
sys_actor = ActorIdentity(name=actor_name, description="ION System Agent")
process.container.resource_registry.create(sys_actor)
+ webauth_actor_name = get_safe(config, "system.web_authentication_actor", "web_authentication")
+ web_auth_actor = ActorIdentity(name=webauth_actor_name, description="Web Authentication Actor")
+ process.container.resource_registry.create(web_auth_actor)
+
# Store all resource types
# Store all event types |
17457815b8eccabf137fdd91053796389d3c8de5 | EventParsers/ParserHelper.py | EventParsers/ParserHelper.py |
# The note off event contains no data, except for the least significant bits
# represening the polyphonic ID, so that all notes with that particular
# polyphonic ID can be turned off.
def parse_noteOff(bmsfile, read, strict, commandID):
return commandID & 0b111
# Several commands use three bytes of data and one byte for
# something else. Because Python's struct module does not have
# a way to parse three bytes at once, we need to do it as follows.
def parse_1Byte_1Tripplet(bmsfile, read, strict, commandID):
byte = read.byte()
tripplet = read.tripplet()
return (byte, tripplet)
# Variable-length delay
def parse_VL_delay(bmsfile, read, strict, commandID):
start = bmsfile.tell()
value = read.byte()
while (value >> 7) == 1:
value = read.byte()
dataLen = bmsfile.tell() - start
bmsfile.seek(start)
data = read.byteArray(dataLen)
return (data, )
|
# The note off event contains no data, except for the least significant bits
# represening the polyphonic ID, so that all notes with that particular
# polyphonic ID can be turned off.
def parse_noteOff(bmsfile, read, strict, commandID):
return (commandID & 0b111,)
# Several commands use three bytes of data and one byte for
# something else. Because Python's struct module does not have
# a way to parse three bytes at once, we need to do it as follows.
def parse_1Byte_1Tripplet(bmsfile, read, strict, commandID):
byte = read.byte()
tripplet = read.tripplet()
return (byte, tripplet)
# Variable-length delay
def parse_VL_delay(bmsfile, read, strict, commandID):
start = bmsfile.tell()
value = read.byte()
while (value >> 7) == 1:
value = read.byte()
dataLen = bmsfile.tell() - start
bmsfile.seek(start)
data = read.byteArray(dataLen)
return (data, )
| Make return value of function a tuple | Make return value of function a tuple
This should make the return value consistent with what struct.unpack would return.
| Python | bsd-3-clause | RenolY2/py-playBMS | ---
+++
@@ -4,7 +4,7 @@
# represening the polyphonic ID, so that all notes with that particular
# polyphonic ID can be turned off.
def parse_noteOff(bmsfile, read, strict, commandID):
- return commandID & 0b111
+ return (commandID & 0b111,)
# Several commands use three bytes of data and one byte for
# something else. Because Python's struct module does not have |
35974efcbae0c8a1b3009d7a2f38c73a52ff5790 | powerdns/admin.py | powerdns/admin.py | # -*- coding: utf-8 -*-
from django.contrib import admin
from powerdns.models import Domain, Record, Supermaster
class RecordAdmin(admin.ModelAdmin):
list_display = ('name', 'type', 'content', 'ttl', 'prio', 'change_date',)
list_filter = ['type', 'ttl',]
search_fields = ('name','content',)
class DomainAdmin(admin.ModelAdmin):
list_display = ('name', 'type', 'last_check', 'account',)
list_filter = ['type', 'last_check', 'account',]
search_fields = ('name',)
class SupermasterAdmin(admin.ModelAdmin):
list_display = ('ip', 'nameserver', 'account',)
list_filter = ['ip', 'account',]
search_fields = ('ip', 'nameserver',)
admin.site.register(Domain,DomainAdmin)
admin.site.register(Record,RecordAdmin)
admin.site.register(Supermaster,SupermasterAdmin)
| # -*- coding: utf-8 -*-
from django.contrib import admin
from powerdns.models import Domain, Record, Supermaster
class RecordAdmin(admin.ModelAdmin):
list_display = ('name', 'type', 'content', 'ttl', 'prio', 'change_date',)
list_filter = ['type', 'ttl',]
search_fields = ('name','content',)
readonly_fields = ('change_date',)
class DomainAdmin(admin.ModelAdmin):
list_display = ('name', 'type', 'last_check', 'account',)
list_filter = ['type', 'last_check', 'account',]
search_fields = ('name',)
readonly_fields = ('notified_serial',)
class SupermasterAdmin(admin.ModelAdmin):
list_display = ('ip', 'nameserver', 'account',)
list_filter = ['ip', 'account',]
search_fields = ('ip', 'nameserver',)
admin.site.register(Domain,DomainAdmin)
admin.site.register(Record,RecordAdmin)
admin.site.register(Supermaster,SupermasterAdmin)
| Mark some fields as readonly in the Admin panel as they are set by the server (Requires Django 1.2 or greater) | Mark some fields as readonly in the Admin panel as they are set by the server (Requires Django 1.2 or greater)
| Python | bsd-2-clause | dominikkowalski/django-powerdns-dnssec,zefciu/django-powerdns-dnssec,zefciu/django-powerdns-dnssec,dominikkowalski/django-powerdns-dnssec,dominikkowalski/django-powerdns-dnssec,allegro/django-powerdns-dnssec,allegro/django-powerdns-dnssec,dominikkowalski/django-powerdns-dnssec,allegro/django-powerdns-dnssec,allegro/django-powerdns-dnssec,dominikkowalski/django-powerdns-dnssec,zefciu/django-powerdns-dnssec | ---
+++
@@ -6,11 +6,13 @@
list_display = ('name', 'type', 'content', 'ttl', 'prio', 'change_date',)
list_filter = ['type', 'ttl',]
search_fields = ('name','content',)
+ readonly_fields = ('change_date',)
class DomainAdmin(admin.ModelAdmin):
list_display = ('name', 'type', 'last_check', 'account',)
list_filter = ['type', 'last_check', 'account',]
search_fields = ('name',)
+ readonly_fields = ('notified_serial',)
class SupermasterAdmin(admin.ModelAdmin):
list_display = ('ip', 'nameserver', 'account',) |
59854731162c25c75304798b62f6541bb9646eee | flask_boost/project/config/__init__.py | flask_boost/project/config/__init__.py | # coding: UTF-8
import os
def load_config():
"""Load config."""
mode = os.environ.get('MODE')
try:
if mode == 'PRODUCTION':
from .production import ProductionConfig
return ProductionConfig
elif mode == 'TESTING':
from .testing import TestingConfig
return TestingConfig
else:
from .development import DevelopmentConfig
return DevelopmentConfig
except ImportError, e:
from .default import Config
return Config | # coding: UTF-8
import os
def load_config():
"""Load config."""
mode = os.environ.get('MODE')
try:
if mode == 'PRODUCTION':
from .production import ProductionConfig
return ProductionConfig
elif mode == 'TESTING':
from .testing import TestingConfig
return TestingConfig
else:
from .development import DevelopmentConfig
return DevelopmentConfig
except ImportError:
from .default import Config
return Config | Update except statements to support Python3. | Update except statements to support Python3.
| Python | mit | hustlzp/Flask-Boost,hustlzp/Flask-Boost,hustlzp/Flask-Boost,1045347128/Flask-Boost,hustlzp/Flask-Boost,1045347128/Flask-Boost,1045347128/Flask-Boost,1045347128/Flask-Boost | ---
+++
@@ -15,6 +15,6 @@
else:
from .development import DevelopmentConfig
return DevelopmentConfig
- except ImportError, e:
+ except ImportError:
from .default import Config
return Config |
cda678a3ea9b01a684c6e2d3ed636834f41c96f8 | wkhtmltopdf/test_settings.py | wkhtmltopdf/test_settings.py | import os
DEBUG = True
DIRNAME = os.path.abspath(os.path.dirname(__file__))
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
# MEDIA_URL = '/media/'
# MEDIA_ROOT = '/tmp/media'
# STATIC_URL = '/static/'
# STATIC_ROOT = '/tmp/static'
MEDIA_ROOT = os.path.join(DIRNAME, 'media')
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(DIRNAME, 'static')
STATIC_URL = '/static/'
INSTALLED_APPS = (
'wkhtmltopdf.tests',
'wkhtmltopdf',
)
TEMPLATE_DIRS = [
os.path.join(DIRNAME, 'testproject', 'tests', 'templates'),
]
WKHTMLTOPDF_DEBUG = DEBUG
| import os
DEBUG = True
DIRNAME = os.path.abspath(os.path.dirname(__file__))
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
MEDIA_ROOT = os.path.join(DIRNAME, 'media')
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(DIRNAME, 'static')
STATIC_URL = '/static/'
INSTALLED_APPS = (
'wkhtmltopdf.tests',
'wkhtmltopdf',
)
TEMPLATE_DIRS = [
os.path.join(DIRNAME, 'testproject', 'tests', 'templates'),
]
WKHTMLTOPDF_DEBUG = DEBUG
| Remove unwanted settings vars from test project | Remove unwanted settings vars from test project
| Python | bsd-2-clause | powderflask/django-wkhtmltopdf,denisbalyko/django-wkhtmltopdf,halfnibble/django-wkhtmltopdf,halfnibble/django-wkhtmltopdf,denisbalyko/django-wkhtmltopdf,unrealsolver/django-wkhtmltopdf,tclancy/django-wkhtmltopdf,incuna/django-wkhtmltopdf,powderflask/django-wkhtmltopdf,unrealsolver/django-wkhtmltopdf,fankcoder/django-wkhtmltopdf,incuna/django-wkhtmltopdf,fankcoder/django-wkhtmltopdf,tclancy/django-wkhtmltopdf | ---
+++
@@ -11,10 +11,6 @@
}
}
-# MEDIA_URL = '/media/'
-# MEDIA_ROOT = '/tmp/media'
-# STATIC_URL = '/static/'
-# STATIC_ROOT = '/tmp/static'
MEDIA_ROOT = os.path.join(DIRNAME, 'media')
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(DIRNAME, 'static') |
bb3ffdea2a76a86c1911426ce030c29abbd1074f | tempo/django/forms.py | tempo/django/forms.py | #!/usr/bin/env python
# coding=utf-8
from decimal import Decimal
from django.utils.translation import ugettext_lazy as _
from django.forms.fields import Field, ValidationError
from tempo.django.widgets import ScheduleSetWidget
from tempo.schedule import Schedule
from tempo.scheduleset import ScheduleSet
class ScheduleSetField(Field):
widget = ScheduleSetWidget
def to_python(self, value):
if value is None:
return None
repeats = value['repeats']
if repeats == 'monthly':
return ScheduleSet(include=[
Schedule(days=[int(value['repeatOn'])])
])
elif repeats == 'weekly':
schedules = []
for repeat_on in value['repeatOn']:
if Decimal(repeat_on['from']) > Decimal(repeat_on['to']):
raise ValidationError(_('"From" is greater than "to".'),
code='invalid')
schedule = Schedule(
weekdays=[int(repeat_on['weekday'])],
days=[],
seconds_of_the_day=list(range(
int(Decimal(repeat_on['from']) * 60 * 60),
int(Decimal(repeat_on['to']) * 60 * 60) + 1)
),
seconds=[], minutes=[], hours=[]
)
schedules.append(schedule)
return ScheduleSet(include=schedules)
else:
raise ValueError
| #!/usr/bin/env python
# coding=utf-8
from decimal import Decimal
from django.utils.translation import ugettext_lazy as _
from django.forms.fields import Field, ValidationError
from tempo.django.widgets import ScheduleSetWidget
from tempo.schedule import Schedule
from tempo.scheduleset import ScheduleSet
class ScheduleSetField(Field):
widget = ScheduleSetWidget
def to_python(self, value):
if value is None:
return None
repeats = value['repeats']
if repeats == 'monthly':
return ScheduleSet(include=[
Schedule(days=[int(value['repeatOn'])])
])
elif repeats == 'weekly':
schedules = []
for repeat_on in value['repeatOn']:
if Decimal(repeat_on['from']) >= Decimal(repeat_on['to']):
raise ValidationError(_('"From" is greater than "to" '
'or equal to it.'),
code='invalid')
schedule = Schedule(
weekdays=[int(repeat_on['weekday'])],
days=[],
seconds_of_the_day=list(range(
int(Decimal(repeat_on['from']) * 60 * 60),
int(Decimal(repeat_on['to']) * 60 * 60))
),
seconds=[], minutes=[], hours=[]
)
schedules.append(schedule)
return ScheduleSet(include=schedules)
else:
raise ValueError
| Make "to" not inclusive in widget | Make "to" not inclusive in widget
To avoid exceeding possible values.
| Python | bsd-3-clause | AndrewPashkin/python-tempo,AndrewPashkin/python-tempo | ---
+++
@@ -26,8 +26,9 @@
elif repeats == 'weekly':
schedules = []
for repeat_on in value['repeatOn']:
- if Decimal(repeat_on['from']) > Decimal(repeat_on['to']):
- raise ValidationError(_('"From" is greater than "to".'),
+ if Decimal(repeat_on['from']) >= Decimal(repeat_on['to']):
+ raise ValidationError(_('"From" is greater than "to" '
+ 'or equal to it.'),
code='invalid')
schedule = Schedule(
@@ -35,7 +36,7 @@
days=[],
seconds_of_the_day=list(range(
int(Decimal(repeat_on['from']) * 60 * 60),
- int(Decimal(repeat_on['to']) * 60 * 60) + 1)
+ int(Decimal(repeat_on['to']) * 60 * 60))
),
seconds=[], minutes=[], hours=[]
) |
f58b24402d8d41778a45d4ce6e6080651c79d529 | scripts/common.py | scripts/common.py | #!/usr/bin/env python
#
# file: common.py
#
# author: Copyright (C) 2017-2018 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
#
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
# distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
import re
def sanitize(string, pattern = '[^0-9A-Za-z-]', replacement = '_'):
"""Sanitize and return provided string.
* `string` is the string that will be sanitized
* `pattern` is the pattern which will be replaced, default - `'[^0-9A-Za-z-]'`
* `replacement` is the replacement string, default - `'_'`
"""
regex = re.compile(pattern)
return regex.sub(replacement, string)
| #!/usr/bin/env python
#
# file: common.py
#
# author: Copyright (C) 2017-2018 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
#
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
# distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
import re
def sanitize(string, pattern = '[^0-9A-Za-z-]', replacement = '_'):
"""Sanitize and return provided string.
* `string` is the string that will be sanitized
* `pattern` is the pattern which will be replaced, default - `'[^0-9A-Za-z-]'`
* `replacement` is the replacement string, default - `'_'`
"""
regex = re.compile(pattern)
return regex.sub(replacement, str(string))
| Convert sanitize() argument to string | Convert sanitize() argument to string
This fixes the bug when the name of the node is an integer, in which
case it's not possible to do regex.sub() on it.
| Python | mpl-2.0 | CezaryGapinski/distortos,CezaryGapinski/distortos,jasmin-j/distortos,jasmin-j/distortos,jasmin-j/distortos,DISTORTEC/distortos,CezaryGapinski/distortos,DISTORTEC/distortos,CezaryGapinski/distortos,CezaryGapinski/distortos,DISTORTEC/distortos,jasmin-j/distortos,jasmin-j/distortos,DISTORTEC/distortos | ---
+++
@@ -19,4 +19,4 @@
* `replacement` is the replacement string, default - `'_'`
"""
regex = re.compile(pattern)
- return regex.sub(replacement, string)
+ return regex.sub(replacement, str(string)) |
d66355e4758b37be39d17d681ede1dbbd6b9b311 | setmagic/admin.py | setmagic/admin.py | from django import forms
from django.contrib import admin
from setmagic import settings
from setmagic.models import Setting
_denied = lambda *args: False
class SetMagicAdmin(admin.ModelAdmin):
list_display = 'label', 'current_value',
list_editable = 'current_value',
list_display_links = None
has_add_permission = _denied
has_delete_permission = _denied
# Make all fields read-only at the change form
def get_readonly_fields(self, *args, **kwargs):
return self.opts.get_all_field_names()
def changelist_view(self, *args, **kwargs):
settings._sync()
return super(SetMagicAdmin, self).changelist_view(*args, **kwargs)
def get_queryset(self, request):
return Setting.objects.filter(name__in=settings.defs)
def get_changelist_form(self, *args, **kwargs):
class Form(forms.ModelForm):
class Meta:
fields = self.list_editable
def __init__(self, *args, **kwargs):
super(Form, self).__init__(*args, **kwargs)
# Do nothing for empty forms
if not self.instance.pk:
return
# Set a custom field
custom_field = settings.defs[self.instance.name].get('field')
if custom_field:
self.fields['current_value'] = custom_field
return Form
admin.site.register(Setting, SetMagicAdmin)
| from django import forms
from django.contrib import admin
from django.utils.importlib import import_module
from setmagic import settings
from setmagic.models import Setting
_denied = lambda *args: False
class SetMagicAdmin(admin.ModelAdmin):
list_display = 'label', 'current_value',
list_editable = 'current_value',
list_display_links = None
has_add_permission = _denied
has_delete_permission = _denied
# Make all fields read-only at the change form
def get_readonly_fields(self, *args, **kwargs):
return self.opts.get_all_field_names()
def changelist_view(self, *args, **kwargs):
settings._sync()
return super(SetMagicAdmin, self).changelist_view(*args, **kwargs)
def get_queryset(self, request):
return Setting.objects.filter(name__in=settings.defs)
def get_changelist_form(self, *args, **kwargs):
class Form(forms.ModelForm):
class Meta:
fields = self.list_editable
def __init__(self, *args, **kwargs):
super(Form, self).__init__(*args, **kwargs)
# Do nothing for empty forms
if not self.instance.pk:
return
# Set a custom field
custom_field = settings.defs[self.instance.name].get('field')
if custom_field:
if isinstance(custom_field, str):
module, name = custom_field.rsplit('.', 1)
custom_field = getattr(import_module(module), name)()
self.fields['current_value'] = custom_field
return Form
admin.site.register(Setting, SetMagicAdmin)
| Use importlib to load custom fields by str | Use importlib to load custom fields by str
| Python | mit | 7ws/django-setmagic | ---
+++
@@ -1,5 +1,6 @@
from django import forms
from django.contrib import admin
+from django.utils.importlib import import_module
from setmagic import settings
from setmagic.models import Setting
@@ -43,6 +44,9 @@
# Set a custom field
custom_field = settings.defs[self.instance.name].get('field')
if custom_field:
+ if isinstance(custom_field, str):
+ module, name = custom_field.rsplit('.', 1)
+ custom_field = getattr(import_module(module), name)()
self.fields['current_value'] = custom_field
return Form |
65137b42bd5ebee37cba0fd462e8f7484a3f9aaa | pelops/etl/hog.py | pelops/etl/hog.py | from skimage.feature import hog
from skimage import colos
from pelops.etl.feature_producer import FeatureProducer
class HOGFeatureProducer(FeatureProducer):
def __init__(self, chip_producer):
super().__init__(chip_producer)
def produce_features(self, chip):
"""Takes a chip object and returns a feature vector of size
self.feat_size. """
img = PIL_Image.open(chip.filepath)
img = img.resize((256, 256), PIL_Image.BICUBIC)
img_x, img_y = img.size
img = color.rgb2gray(np.array(img))
features = hog(
img,
orientations=8,
pixels_per_cell=(int(img_x / 16), int(img_y / 16)),
cells_per_block=(16, 16), # Normalize over the whole image
)
return features
def set_variables(self):
"""Child classes should use this to set self.feat_size, and any other
needed variables. """
self.feat_size = 2048 # Set this in your inherited class
| from skimage.feature import hog
from skimage import colos
from pelops.etl.feature_producer import FeatureProducer
class HOGFeatureProducer(FeatureProducer):
def __init__(self, chip_producer, image_size=(256,256), cells=(16, 16), orientations=8):
super().__init__(chip_producer)
self.image_size = image_size
self.cells = cells
self.orientations = orientations
def produce_features(self, chip):
"""Takes a chip object and returns a feature vector of size
self.feat_size. """
img = PIL_Image.open(chip.filepath)
img = img.resize(self.image_size, PIL_Image.BICUBIC)
img_x, img_y = img.size
img = color.rgb2gray(np.array(img))
features = hog(
img,
orientations=self.orientations,
pixels_per_cell=(img_x / cells[0], img_y / cells[1]),
cells_per_block=cells, # Normalize over the whole image
)
return features
def set_variables(self):
self.feat_size = self.cells[0] * self.cells[1] * orientations
| Replace magic numbers in `HOGFeatureProducer` | Replace magic numbers in `HOGFeatureProducer`
| Python | apache-2.0 | d-grossman/pelops,d-grossman/pelops,dave-lab41/pelops,Lab41/pelops,dave-lab41/pelops,Lab41/pelops | ---
+++
@@ -6,25 +6,26 @@
class HOGFeatureProducer(FeatureProducer):
- def __init__(self, chip_producer):
+ def __init__(self, chip_producer, image_size=(256,256), cells=(16, 16), orientations=8):
super().__init__(chip_producer)
+ self.image_size = image_size
+ self.cells = cells
+ self.orientations = orientations
def produce_features(self, chip):
"""Takes a chip object and returns a feature vector of size
self.feat_size. """
img = PIL_Image.open(chip.filepath)
- img = img.resize((256, 256), PIL_Image.BICUBIC)
+ img = img.resize(self.image_size, PIL_Image.BICUBIC)
img_x, img_y = img.size
img = color.rgb2gray(np.array(img))
features = hog(
img,
- orientations=8,
- pixels_per_cell=(int(img_x / 16), int(img_y / 16)),
- cells_per_block=(16, 16), # Normalize over the whole image
+ orientations=self.orientations,
+ pixels_per_cell=(img_x / cells[0], img_y / cells[1]),
+ cells_per_block=cells, # Normalize over the whole image
)
return features
def set_variables(self):
- """Child classes should use this to set self.feat_size, and any other
- needed variables. """
- self.feat_size = 2048 # Set this in your inherited class
+ self.feat_size = self.cells[0] * self.cells[1] * orientations |
71c9b12056de1e1fdcc1effd2fda4c4dd284afab | froide/problem/utils.py | froide/problem/utils.py | from django.core.mail import mail_managers
from django.conf import settings
from django.template.loader import render_to_string
from django.utils.translation import ugettext_lazy as _
def inform_managers(report):
mail_managers(
_('New problem: {label} [#{reqid}]').format(
label=report.get_kind_display(),
reqid=report.message.request_id
),
'{}\n{}'.format(
report.description,
report.get_absolute_domain_url()
)
)
def inform_user_problem_resolved(report):
if report.auto_submitted or not report.user:
return False
foirequest = report.message.request
subject = _('Problem resolved on your request')
body = render_to_string("problem/email_problem_resolved.txt", {
"user": report.user,
"title": foirequest.title,
"report": report,
"url": report.user.get_autologin_url(
report.message.get_absolute_short_url()
),
"site_name": settings.SITE_NAME
})
report.user.send_mail(subject, body)
return True
| from django.core.mail import mail_managers
from django.conf import settings
from django.urls import reverse
from django.template.loader import render_to_string
from django.utils.translation import ugettext_lazy as _
def inform_managers(report):
admin_url = settings.SITE_URL + reverse(
'admin:problem_problemreport_change', args=(report.id,))
mail_managers(
_('New problem: {label} [#{reqid}]').format(
label=report.get_kind_display(),
reqid=report.message.request_id
),
'{}\n\n---\n\n{}\n'.format(
report.description,
report.get_absolute_domain_url(),
admin_url
)
)
def inform_user_problem_resolved(report):
if report.auto_submitted or not report.user:
return False
foirequest = report.message.request
subject = _('Problem resolved on your request')
body = render_to_string("problem/email_problem_resolved.txt", {
"user": report.user,
"title": foirequest.title,
"report": report,
"url": report.user.get_autologin_url(
report.message.get_absolute_short_url()
),
"site_name": settings.SITE_NAME
})
report.user.send_mail(subject, body)
return True
| Add link to report admin page to report info mail | Add link to report admin page to report info mail | Python | mit | stefanw/froide,stefanw/froide,stefanw/froide,fin/froide,stefanw/froide,fin/froide,stefanw/froide,fin/froide,fin/froide | ---
+++
@@ -1,18 +1,22 @@
from django.core.mail import mail_managers
from django.conf import settings
+from django.urls import reverse
from django.template.loader import render_to_string
from django.utils.translation import ugettext_lazy as _
def inform_managers(report):
+ admin_url = settings.SITE_URL + reverse(
+ 'admin:problem_problemreport_change', args=(report.id,))
mail_managers(
_('New problem: {label} [#{reqid}]').format(
label=report.get_kind_display(),
reqid=report.message.request_id
),
- '{}\n{}'.format(
+ '{}\n\n---\n\n{}\n'.format(
report.description,
- report.get_absolute_domain_url()
+ report.get_absolute_domain_url(),
+ admin_url
)
)
|
53e2ef4079bc191b0b88395cf23e7bac576033dc | mne/simulation/simulation_metrics.py | mne/simulation/simulation_metrics.py |
import numpy as np
def _check_stc(stc1, stc2):
# XXX What should we check? that the data is having the same size?
if stc1.data.shape != stc2.data.shape:
raise ValueError('Data in stcs must have the same size')
if stc1.times != stc2.times:
raise ValueError('Times of two stcs must match.')
def source_estimate_quantification(stc1, stc2, metric='rms'):
"""Helper function to calculate matrix similarities.
Parameters
----------
stc1 : SourceEstimate
First source estimate for comparison
stc2 : SourceEstimate
First source estimate for comparison
metric : str
Metric to calculate. 'rms', 'avg_corrcoef',
Returns
-------
"""
# TODO Add checks for source space
_check_stc(stc1, stc2)
score = _calc_metric(stc1.data, stc2.data, metric)
def _calc_metric(data1, data2, metric):
"""Calculate metric of choice"""
# Calculate root mean square difference between two matrices
if metric == 'rms':
return np.mean((stc1.data - stc2.data) ** 2)
# Calculate correlation coefficient between matrix elements
elif metric == 'avg_corrcoef':
return np.mean(np.corrcoeff(stc1.data, stc2.data))
| # Authors: Yousra Bekhti
# Mark Wronkiewicz <wronk.mark@gmail.com>
#
# License: BSD (3-clause)
import numpy as np
def _check_stc(stc1, stc2):
# XXX What should we check? that the data is having the same size?
if stc1.data.shape != stc2.data.shape:
raise ValueError('Data in stcs must have the same size')
if stc1.times != stc2.times:
raise ValueError('Times of two stcs must match.')
def source_estimate_quantification(stc1, stc2, metric='rms'):
"""Helper function to calculate matrix similarities.
Parameters
----------
stc1 : SourceEstimate
First source estimate for comparison
stc2 : SourceEstimate
First source estimate for comparison
metric : str
Metric to calculate. 'rms', 'avg_corrcoef',
Returns
-------
"""
# TODO Add checks for source space
_check_stc(stc1, stc2)
score = _calc_metric(stc1.data, stc2.data, metric)
def _calc_metric(data1, data2, metric):
"""Helper to calculate metric of choice.
Parameters
----------
data1 : ndarray, shape(n_sources, ntimes)
Second data matrix
data2 : ndarray, shape(n_sources, ntimes)
Second data matrix
metric : str
Metric to calculate. 'rms', 'corr',
Returns
-------
score : float
Calculated metric
"""
# Calculate root mean square difference between two matrices
if metric == 'rms':
return np.mean((stc1.data - stc2.data) ** 2)
# Calculate correlation coefficient between matrix elements
elif metric == 'corr':
return np.correlate(stc1.data.flatten(), stc2.data.flatten())
| Add documentation, tests, fix corr | Add documentation, tests, fix corr
| Python | bsd-3-clause | lorenzo-desantis/mne-python,wronk/mne-python,Teekuningas/mne-python,olafhauk/mne-python,mne-tools/mne-python,jaeilepp/mne-python,ARudiuk/mne-python,jmontoyam/mne-python,rkmaddox/mne-python,pravsripad/mne-python,larsoner/mne-python,wmvanvliet/mne-python,larsoner/mne-python,kingjr/mne-python,teonlamont/mne-python,kingjr/mne-python,adykstra/mne-python,yousrabk/mne-python,wmvanvliet/mne-python,rkmaddox/mne-python,bloyl/mne-python,pravsripad/mne-python,adykstra/mne-python,nicproulx/mne-python,Teekuningas/mne-python,jniediek/mne-python,kambysese/mne-python,Teekuningas/mne-python,ARudiuk/mne-python,kambysese/mne-python,drammock/mne-python,jniediek/mne-python,Eric89GXL/mne-python,wronk/mne-python,cmoutard/mne-python,mne-tools/mne-python,drammock/mne-python,pravsripad/mne-python,jaeilepp/mne-python,cjayb/mne-python,teonlamont/mne-python,cjayb/mne-python,mne-tools/mne-python,nicproulx/mne-python,alexandrebarachant/mne-python,drammock/mne-python,olafhauk/mne-python,olafhauk/mne-python,lorenzo-desantis/mne-python,jmontoyam/mne-python,leggitta/mne-python,kingjr/mne-python,bloyl/mne-python,cmoutard/mne-python,leggitta/mne-python,larsoner/mne-python,yousrabk/mne-python,alexandrebarachant/mne-python,Eric89GXL/mne-python,wmvanvliet/mne-python | ---
+++
@@ -1,3 +1,7 @@
+# Authors: Yousra Bekhti
+# Mark Wronkiewicz <wronk.mark@gmail.com>
+#
+# License: BSD (3-clause)
import numpy as np
@@ -34,13 +38,27 @@
score = _calc_metric(stc1.data, stc2.data, metric)
def _calc_metric(data1, data2, metric):
- """Calculate metric of choice"""
+ """Helper to calculate metric of choice.
+
+ Parameters
+ ----------
+ data1 : ndarray, shape(n_sources, ntimes)
+ Second data matrix
+ data2 : ndarray, shape(n_sources, ntimes)
+ Second data matrix
+ metric : str
+ Metric to calculate. 'rms', 'corr',
+
+ Returns
+ -------
+ score : float
+ Calculated metric
+ """
# Calculate root mean square difference between two matrices
if metric == 'rms':
return np.mean((stc1.data - stc2.data) ** 2)
# Calculate correlation coefficient between matrix elements
- elif metric == 'avg_corrcoef':
- return np.mean(np.corrcoeff(stc1.data, stc2.data))
-
+ elif metric == 'corr':
+ return np.correlate(stc1.data.flatten(), stc2.data.flatten()) |
8f3b6912ac7dd9fa63143a7e482d880658e69ac4 | pyeda/__init__.py | pyeda/__init__.py | """
Python EDA Package
common.py
boolfunc.py -- Boolean functions
expr.py -- Boolean logic expressions
vexpr.py -- Boolean vector logic expressions
table.py -- Boolean tables
"""
__copyright__ = "Copyright (c) 2012, Chris Drake"
__version__ = "0.3.1"
| """
Python EDA Package
common.py
boolfunc.py -- Boolean functions
constant.py -- Boolean constant functions
expr.py -- Boolean logic expressions
vexpr.py -- Boolean vector logic expressions
table.py -- Boolean tables
"""
__copyright__ = "Copyright (c) 2012, Chris Drake"
__version__ = "0.3.1"
| Add constant.py to package docstring | Add constant.py to package docstring
| Python | bsd-2-clause | sschnug/pyeda,pombredanne/pyeda,pombredanne/pyeda,GtTmy/pyeda,cjdrake/pyeda,pombredanne/pyeda,GtTmy/pyeda,cjdrake/pyeda,sschnug/pyeda,karissa/pyeda,sschnug/pyeda,karissa/pyeda,cjdrake/pyeda,GtTmy/pyeda,karissa/pyeda | ---
+++
@@ -3,6 +3,7 @@
common.py
boolfunc.py -- Boolean functions
+constant.py -- Boolean constant functions
expr.py -- Boolean logic expressions
vexpr.py -- Boolean vector logic expressions
table.py -- Boolean tables |
ac1dcd9f7acb8e8867996c70aa0a35eb45fcdc53 | generator/php_di_gen.py | generator/php_di_gen.py | #! /usr/bin/python
"""
This script accepts a string with the following syntax:
Get the list of classes that a PHP class depends on.
Generate PHP code that
defines the fields with corresponding
names ( same name as the class name but with the first letter
converted to lower case ).
defines the constructor.
Print out the code to the console.
"""
import sys
from generator.generator import Generator
from pyperclip.pyperclip import copy
def main():
"""
Parse arguments from command line
"""
argv = sys.argv
length = len(argv)
if length != 2:
print_help()
exit()
dependent_list_string = sys.argv[1]
statement = Generator.generate_statements(dependent_list_string)
copy(statement)
print statement
def print_help():
"""
Prints the help string for this script
"""
print "php-di-gen.py <dependent class list string>"
main()
| #! /usr/bin/python
"""
This script accepts a string with the following syntax:
Get the list of classes that a PHP class depends on.
Generate PHP code that
defines the fields with corresponding
names ( same name as the class name but with the first letter
converted to lower case ).
defines the constructor.
Print out the code to the console.
"""
import sys
from generator import Generator
from pyperclip.pyperclip import copy
def main():
"""
Parse arguments from command line
"""
argv = sys.argv
length = len(argv)
if length != 2:
print_help()
exit()
dependent_list_string = sys.argv[1]
statement = Generator.generate_statements(dependent_list_string)
copy(statement)
print statement
def print_help():
"""
Prints the help string for this script
"""
print "Run this script/executable with the following parameter <dependent class list string>."
main()
| Fix import and update help | Fix import and update help
Use relative module name
The script may be invoked from a single executable without py extension.
| Python | apache-2.0 | HappyRay/php-di-generator | ---
+++
@@ -16,7 +16,7 @@
"""
import sys
-from generator.generator import Generator
+from generator import Generator
from pyperclip.pyperclip import copy
def main():
@@ -37,7 +37,7 @@
"""
Prints the help string for this script
"""
- print "php-di-gen.py <dependent class list string>"
+ print "Run this script/executable with the following parameter <dependent class list string>."
main()
|
f029a204289abb91d57e117d45772d24372a1a43 | requests-RT/rt.py | requests-RT/rt.py | #!/usr/bin/python
import requests
class RT:
def __init__(self, apikey):
self.apikey = apikey
@staticmethod
def make_request(url, params=None):
req = requests.get(url, params=params)
return req.content
def search(self, query, page_limit=30, page=1):
url = 'http://api.rottentomatoes.com/api/public/v1.0/movies.json'
params = {
'q': query,
'page_limit': page_limit,
'page': page,
'apikey': self.apikey}
return make_request(url, params)
def box_office(self, limit=10, country='us'):
url = 'http://api.rottentomatoes.com/api/public/v1.0/lists/movies/box_office.json'
params = {
'limit': limit,
'country': country,
'apikey': self.apikey}
return make_request(url, params=params) | #!/usr/bin/python
__author__ = 'Mahmoud Hossam'
__version__ = '0.1'
import requests
class RT:
def __init__(self, apikey):
self.apikey = apikey
@staticmethod
def make_request(url, params=None):
req = requests.get(url, params=params)
return req.content
def search(self, query, page_limit=30, page=1):
url = 'http://api.rottentomatoes.com/api/public/v1.0/movies.json'
params = {
'q': query,
'page_limit': page_limit,
'page': page,
'apikey': self.apikey}
return make_request(url, params)
def box_office(self, limit=10, country='us'):
url = 'http://api.rottentomatoes.com/api/public/v1.0/lists/movies/box_office.json'
params = {
'limit': limit,
'country': country,
'apikey': self.apikey}
return make_request(url, params=params) | Add author and version number | Add author and version number
| Python | bsd-2-clause | mahmoudhossam/requests-RT | ---
+++
@@ -1,4 +1,7 @@
#!/usr/bin/python
+
+__author__ = 'Mahmoud Hossam'
+__version__ = '0.1'
import requests
|
6194aa67ce54ce5c2fb0de58bfb2d75607d7b882 | bin/combine_results.py | bin/combine_results.py | #!/usr/bin/env python
"""
Simple script to combine JUnit test results into a single XML file.
Useful for Jenkins.
TODO: Pretty indentation
"""
import os
from xml.etree import cElementTree as ET
def find_all(name, path):
result = []
for root, dirs, files in os.walk(path):
if name in files:
yield os.path.join(root, name)
def main(path, output):
testsuite = ET.Element("testsuite", name="all", package="all", tests="0")
for fname in find_all("results.xml", path):
tree = ET.parse(fname)
for element in tree.iter("testcase"):
testsuite.append(element)
result = ET.Element("testsuites", name="results")
result.append(testsuite)
ET.ElementTree(result).write(output, encoding="UTF-8")
if __name__ == "__main__":
main(".", "combined_results.xml")
| #!/usr/bin/env python
"""
Simple script to combine JUnit test results into a single XML file.
Useful for Jenkins.
TODO: Pretty indentation
"""
import os
from xml.etree import cElementTree as ET
def find_all(name, path):
result = []
for root, dirs, files in os.walk(path):
if name in files:
yield os.path.join(root, name)
def main(path, output):
testsuite = ET.Element("testsuite", name="all", package="all", tests="0")
for fname in find_all("results.xml", path):
tree = ET.parse(fname)
for element in tree.getiterator("testcase"):
testsuite.append(element)
result = ET.Element("testsuites", name="results")
result.append(testsuite)
ET.ElementTree(result).write(output, encoding="UTF-8")
if __name__ == "__main__":
main(".", "combined_results.xml")
| Enable regression run to work on python 2.6 | Cleanup: Enable regression run to work on python 2.6
| Python | bsd-3-clause | mkreider/cocotb2,stuarthodgson/cocotb,mkreider/cocotb2,mkreider/cocotb2,stuarthodgson/cocotb,stuarthodgson/cocotb | ---
+++
@@ -22,7 +22,7 @@
for fname in find_all("results.xml", path):
tree = ET.parse(fname)
- for element in tree.iter("testcase"):
+ for element in tree.getiterator("testcase"):
testsuite.append(element)
result = ET.Element("testsuites", name="results") |
e9ec19e68ccefaee9a975a6adc26cb6e5f1f7f33 | pymodels/middlelayer/devices/__init__.py | pymodels/middlelayer/devices/__init__.py | from .dcct import DCCT
from .li_llrf import LiLLRF
from .rf import RF
from .sofb import SOFB
from .kicker import Kicker
from .septum import Septum
from .screen import Screen
from .bpm import BPM
from .ict import ICT
from .ict import TranspEff
from .egun import Bias
from .egun import Filament
from .egun import HVPS
| from .dcct import DCCT
from .li_llrf import LiLLRF
from .rf import RF
from .sofb import SOFB
from .kicker import Kicker
from .septum import Septum
from .screen import Screen
from .bpm import BPM
from .ict import ICT
from .ict import TranspEff
from .egun import Bias
from .egun import Filament
from .egun import HVPS
from .timing import Timing
| Add timing in devices init | DEV.ENH: Add timing in devices init
| Python | mit | lnls-fac/sirius | ---
+++
@@ -11,3 +11,4 @@
from .egun import Bias
from .egun import Filament
from .egun import HVPS
+from .timing import Timing |
a9354124f4905f4befe9ff2ca8274406fbbb0dad | readux/annotations/migrations/0003_annotation_group_and_permissions.py | readux/annotations/migrations/0003_annotation_group_and_permissions.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('auth', '0006_require_contenttypes_0002'),
('annotations', '0002_add_volume_uri'),
]
operations = [
migrations.CreateModel(
name='AnnotationGroup',
fields=[
('group_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='auth.Group')),
('notes', models.TextField(blank=True)),
('created', models.DateTimeField(auto_now_add=True)),
('updated', models.DateTimeField(auto_now=True)),
],
bases=('auth.group',),
),
migrations.AlterModelOptions(
name='annotation',
options={'permissions': (('view_annotation', 'View annotation'),)},
),
migrations.AlterModelOptions(
name='annotation',
options={'permissions': (('view_annotation', 'View annotation'), ('admin_annotation', 'Manage annotation'))},
),
]
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('auth', '0006_require_contenttypes_0002'),
('annotations', '0002_add_volume_uri'),
]
operations = [
migrations.CreateModel(
name='AnnotationGroup',
fields=[
('group_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='auth.Group')),
('notes', models.TextField(blank=True)),
('created', models.DateTimeField(auto_now_add=True)),
('updated', models.DateTimeField(auto_now=True)),
],
bases=('auth.group',),
),
migrations.AlterModelOptions(
name='annotation',
options={'permissions': (('view_annotation', 'View annotation'), ('admin_annotation', 'Manage annotation'))},
),
]
| Fix migration that adds custom annotation permissions | Fix migration that adds custom annotation permissions
| Python | apache-2.0 | emory-libraries/readux,emory-libraries/readux,emory-libraries/readux | ---
+++
@@ -24,10 +24,6 @@
),
migrations.AlterModelOptions(
name='annotation',
- options={'permissions': (('view_annotation', 'View annotation'),)},
- ),
- migrations.AlterModelOptions(
- name='annotation',
options={'permissions': (('view_annotation', 'View annotation'), ('admin_annotation', 'Manage annotation'))},
),
] |
5531f188c7bf3030cb9fc3b46d92a1db60817b7c | confirmation/views.py | confirmation/views.py | # -*- coding: utf-8 -*-
# Copyright: (c) 2008, Jarek Zgoda <jarek.zgoda@gmail.com>
__revision__ = '$Id: views.py 21 2008-12-05 09:21:03Z jarek.zgoda $'
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.conf import settings
from confirmation.models import Confirmation
def confirm(request, confirmation_key):
confirmation_key = confirmation_key.lower()
obj = Confirmation.objects.confirm(confirmation_key)
confirmed = True
if not obj:
# confirmation failed
confirmed = False
try:
# try to get the object we was supposed to confirm
obj = Confirmation.objects.get(confirmation_key=confirmation_key)
except Confirmation.DoesNotExist:
pass
ctx = {
'object': obj,
'confirmed': confirmed,
'days': getattr(settings, 'EMAIL_CONFIRMATION_DAYS', 10),
}
templates = [
'confirmation/confirm.html',
]
if obj:
# if we have an object, we can use specific template
templates.insert(0, 'confirmation/confirm_%s.html' % obj._meta.module_name)
return render_to_response(templates, ctx,
context_instance=RequestContext(request))
| # -*- coding: utf-8 -*-
# Copyright: (c) 2008, Jarek Zgoda <jarek.zgoda@gmail.com>
__revision__ = '$Id: views.py 21 2008-12-05 09:21:03Z jarek.zgoda $'
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.conf import settings
from confirmation.models import Confirmation
def confirm(request, confirmation_key):
confirmation_key = confirmation_key.lower()
obj = Confirmation.objects.confirm(confirmation_key)
confirmed = True
if not obj:
# confirmation failed
confirmed = False
try:
# try to get the object we was supposed to confirm
obj = Confirmation.objects.get(confirmation_key=confirmation_key)
except Confirmation.DoesNotExist:
pass
ctx = {
'object': obj,
'confirmed': confirmed,
'days': getattr(settings, 'EMAIL_CONFIRMATION_DAYS', 10),
'key': confirmation_key,
}
templates = [
'confirmation/confirm.html',
]
if obj:
# if we have an object, we can use specific template
templates.insert(0, 'confirmation/confirm_%s.html' % obj._meta.module_name)
return render_to_response(templates, ctx,
context_instance=RequestContext(request))
| Include confirmation key in context object. | Include confirmation key in context object.
This way our templates can reference the confirmation key later.
(imported from commit 4d57e1309386f2236829b6fdf4e4ad43c5b125c8)
| Python | apache-2.0 | schatt/zulip,deer-hope/zulip,PaulPetring/zulip,adnanh/zulip,jeffcao/zulip,hafeez3000/zulip,fw1121/zulip,KJin99/zulip,ufosky-server/zulip,mahim97/zulip,dhcrzf/zulip,dawran6/zulip,firstblade/zulip,akuseru/zulip,eastlhu/zulip,showell/zulip,dawran6/zulip,vikas-parashar/zulip,esander91/zulip,eastlhu/zulip,so0k/zulip,johnny9/zulip,amallia/zulip,sharmaeklavya2/zulip,mansilladev/zulip,krtkmj/zulip,dawran6/zulip,proliming/zulip,rht/zulip,jackrzhang/zulip,noroot/zulip,eastlhu/zulip,deer-hope/zulip,firstblade/zulip,wweiradio/zulip,jackrzhang/zulip,punchagan/zulip,peiwei/zulip,showell/zulip,Cheppers/zulip,guiquanz/zulip,seapasulli/zulip,hackerkid/zulip,jrowan/zulip,ipernet/zulip,dotcool/zulip,esander91/zulip,kou/zulip,Galexrt/zulip,nicholasbs/zulip,PhilSk/zulip,zwily/zulip,mdavid/zulip,amanharitsh123/zulip,Drooids/zulip,kokoar/zulip,karamcnair/zulip,stamhe/zulip,easyfmxu/zulip,PaulPetring/zulip,sharmaeklavya2/zulip,ahmadassaf/zulip,saitodisse/zulip,levixie/zulip,arpith/zulip,Drooids/zulip,zwily/zulip,gigawhitlocks/zulip,Drooids/zulip,dxq-git/zulip,swinghu/zulip,jonesgithub/zulip,thomasboyt/zulip,itnihao/zulip,dwrpayne/zulip,ashwinirudrappa/zulip,armooo/zulip,jimmy54/zulip,jessedhillon/zulip,LeeRisk/zulip,samatdav/zulip,zorojean/zulip,proliming/zulip,jerryge/zulip,fw1121/zulip,Suninus/zulip,ryanbackman/zulip,andersk/zulip,luyifan/zulip,pradiptad/zulip,joshisa/zulip,swinghu/zulip,armooo/zulip,grave-w-grave/zulip,Suninus/zulip,udxxabp/zulip,firstblade/zulip,akuseru/zulip,shubhamdhama/zulip,atomic-labs/zulip,bluesea/zulip,AZtheAsian/zulip,rht/zulip,hayderimran7/zulip,akuseru/zulip,peiwei/zulip,codeKonami/zulip,jerryge/zulip,fw1121/zulip,kou/zulip,shaunstanislaus/zulip,johnnygaddarr/zulip,kokoar/zulip,Frouk/zulip,samatdav/zulip,hackerkid/zulip,Frouk/zulip,saitodisse/zulip,hackerkid/zulip,lfranchi/zulip,ApsOps/zulip,sonali0901/zulip,voidException/zulip,atomic-labs/zulip,zachallaun/zulip,wdaher/zulip,noroot/zulip,zulip/zulip,xuxiao/zulip,gigawhitlocks/zulip,hackerkid/zulip,Vallher/zulip,susansls/zulip,reyha/zulip,paxapy/zulip,ryansnowboarder/zulip,xuxiao/zulip,ahmadassaf/zulip,dattatreya303/zulip,rht/zulip,shubhamdhama/zulip,jainayush975/zulip,noroot/zulip,TigorC/zulip,vabs22/zulip,luyifan/zulip,synicalsyntax/zulip,lfranchi/zulip,dwrpayne/zulip,kaiyuanheshang/zulip,dnmfarrell/zulip,kokoar/zulip,moria/zulip,jainayush975/zulip,thomasboyt/zulip,j831/zulip,wangdeshui/zulip,timabbott/zulip,levixie/zulip,vakila/zulip,akuseru/zulip,m1ssou/zulip,luyifan/zulip,bssrdf/zulip,johnnygaddarr/zulip,punchagan/zulip,vabs22/zulip,sharmaeklavya2/zulip,amallia/zulip,schatt/zulip,qq1012803704/zulip,wweiradio/zulip,showell/zulip,deer-hope/zulip,zachallaun/zulip,christi3k/zulip,Qgap/zulip,christi3k/zulip,zwily/zulip,schatt/zulip,MariaFaBella85/zulip,peguin40/zulip,ryanbackman/zulip,babbage/zulip,natanovia/zulip,wdaher/zulip,jeffcao/zulip,noroot/zulip,he15his/zulip,TigorC/zulip,babbage/zulip,tbutter/zulip,wavelets/zulip,developerfm/zulip,hj3938/zulip,sup95/zulip,wdaher/zulip,samatdav/zulip,mohsenSy/zulip,jerryge/zulip,huangkebo/zulip,adnanh/zulip,mansilladev/zulip,shaunstanislaus/zulip,Frouk/zulip,Juanvulcano/zulip,hj3938/zulip,Drooids/zulip,levixie/zulip,qq1012803704/zulip,ryanbackman/zulip,TigorC/zulip,Gabriel0402/zulip,johnnygaddarr/zulip,stamhe/zulip,m1ssou/zulip,mahim97/zulip,mdavid/zulip,blaze225/zulip,glovebx/zulip,bluesea/zulip,jphilipsen05/zulip,nicholasbs/zulip,brockwhittaker/zulip,showell/zulip,sonali0901/zulip,sonali0901/zulip,bastianh/zulip,johnnygaddarr/zulip,udxxabp/zulip,Cheppers/zulip,amanharitsh123/zulip,deer-hope/zulip,alliejones/zulip,JPJPJPOPOP/zulip,lfranchi/zulip,Suninus/zulip,ryansnowboarder/zulip,babbage/zulip,KingxBanana/zulip,bitemyapp/zulip,shrikrishnaholla/zulip,sup95/zulip,so0k/zulip,dnmfarrell/zulip,Suninus/zulip,ikasumiwt/zulip,bowlofstew/zulip,tommyip/zulip,ApsOps/zulip,suxinde2009/zulip,suxinde2009/zulip,vaidap/zulip,akuseru/zulip,seapasulli/zulip,jeffcao/zulip,themass/zulip,Batterfii/zulip,zulip/zulip,ericzhou2008/zulip,vakila/zulip,Vallher/zulip,arpith/zulip,EasonYi/zulip,ryansnowboarder/zulip,willingc/zulip,eeshangarg/zulip,deer-hope/zulip,showell/zulip,itnihao/zulip,hayderimran7/zulip,shrikrishnaholla/zulip,technicalpickles/zulip,PhilSk/zulip,Qgap/zulip,kokoar/zulip,Qgap/zulip,sup95/zulip,tiansiyuan/zulip,aps-sids/zulip,karamcnair/zulip,Batterfii/zulip,bastianh/zulip,pradiptad/zulip,codeKonami/zulip,punchagan/zulip,dxq-git/zulip,ashwinirudrappa/zulip,samatdav/zulip,hackerkid/zulip,levixie/zulip,alliejones/zulip,stamhe/zulip,bluesea/zulip,DazWorrall/zulip,zachallaun/zulip,AZtheAsian/zulip,aliceriot/zulip,yuvipanda/zulip,Juanvulcano/zulip,shrikrishnaholla/zulip,arpith/zulip,ApsOps/zulip,zofuthan/zulip,zulip/zulip,zulip/zulip,seapasulli/zulip,arpitpanwar/zulip,ericzhou2008/zulip,thomasboyt/zulip,amyliu345/zulip,hayderimran7/zulip,willingc/zulip,hafeez3000/zulip,ashwinirudrappa/zulip,aps-sids/zulip,MayB/zulip,yocome/zulip,mahim97/zulip,ikasumiwt/zulip,tbutter/zulip,samatdav/zulip,blaze225/zulip,kou/zulip,cosmicAsymmetry/zulip,ipernet/zulip,ericzhou2008/zulip,MariaFaBella85/zulip,KJin99/zulip,joshisa/zulip,ufosky-server/zulip,seapasulli/zulip,andersk/zulip,niftynei/zulip,JanzTam/zulip,Suninus/zulip,suxinde2009/zulip,eeshangarg/zulip,vabs22/zulip,rishig/zulip,tommyip/zulip,dwrpayne/zulip,seapasulli/zulip,tommyip/zulip,bowlofstew/zulip,souravbadami/zulip,synicalsyntax/zulip,saitodisse/zulip,ikasumiwt/zulip,aakash-cr7/zulip,verma-varsha/zulip,timabbott/zulip,eeshangarg/zulip,seapasulli/zulip,pradiptad/zulip,timabbott/zulip,DazWorrall/zulip,vaidap/zulip,zacps/zulip,deer-hope/zulip,Cheppers/zulip,Galexrt/zulip,eastlhu/zulip,timabbott/zulip,glovebx/zulip,adnanh/zulip,vikas-parashar/zulip,ryansnowboarder/zulip,lfranchi/zulip,willingc/zulip,AZtheAsian/zulip,swinghu/zulip,fw1121/zulip,KingxBanana/zulip,wangdeshui/zulip,bitemyapp/zulip,verma-varsha/zulip,shrikrishnaholla/zulip,TigorC/zulip,Qgap/zulip,peguin40/zulip,nicholasbs/zulip,moria/zulip,firstblade/zulip,krtkmj/zulip,Juanvulcano/zulip,zachallaun/zulip,yuvipanda/zulip,natanovia/zulip,Juanvulcano/zulip,adnanh/zulip,suxinde2009/zulip,punchagan/zulip,j831/zulip,huangkebo/zulip,jeffcao/zulip,zhaoweigg/zulip,shrikrishnaholla/zulip,jeffcao/zulip,adnanh/zulip,eastlhu/zulip,firstblade/zulip,tommyip/zulip,huangkebo/zulip,bastianh/zulip,susansls/zulip,kaiyuanheshang/zulip,aps-sids/zulip,brainwane/zulip,zorojean/zulip,suxinde2009/zulip,niftynei/zulip,LeeRisk/zulip,MariaFaBella85/zulip,jerryge/zulip,developerfm/zulip,karamcnair/zulip,themass/zulip,MayB/zulip,hafeez3000/zulip,jackrzhang/zulip,so0k/zulip,gkotian/zulip,hengqujushi/zulip,itnihao/zulip,johnnygaddarr/zulip,LAndreas/zulip,rishig/zulip,amallia/zulip,avastu/zulip,yocome/zulip,proliming/zulip,Galexrt/zulip,stamhe/zulip,firstblade/zulip,dxq-git/zulip,bluesea/zulip,dxq-git/zulip,praveenaki/zulip,bluesea/zulip,xuanhan863/zulip,Frouk/zulip,ipernet/zulip,voidException/zulip,aps-sids/zulip,natanovia/zulip,karamcnair/zulip,peguin40/zulip,wavelets/zulip,bastianh/zulip,joshisa/zulip,jrowan/zulip,eeshangarg/zulip,huangkebo/zulip,Qgap/zulip,ufosky-server/zulip,DazWorrall/zulip,dawran6/zulip,proliming/zulip,avastu/zulip,PaulPetring/zulip,umkay/zulip,hafeez3000/zulip,zulip/zulip,susansls/zulip,jphilipsen05/zulip,vaidap/zulip,Frouk/zulip,proliming/zulip,souravbadami/zulip,amyliu345/zulip,Cheppers/zulip,verma-varsha/zulip,arpith/zulip,EasonYi/zulip,ashwinirudrappa/zulip,zachallaun/zulip,dwrpayne/zulip,zacps/zulip,johnny9/zulip,jimmy54/zulip,wdaher/zulip,cosmicAsymmetry/zulip,fw1121/zulip,ryansnowboarder/zulip,jonesgithub/zulip,mdavid/zulip,yuvipanda/zulip,johnny9/zulip,Cheppers/zulip,zorojean/zulip,tbutter/zulip,sonali0901/zulip,Juanvulcano/zulip,hustlzp/zulip,reyha/zulip,m1ssou/zulip,wavelets/zulip,wangdeshui/zulip,eeshangarg/zulip,guiquanz/zulip,schatt/zulip,saitodisse/zulip,JanzTam/zulip,verma-varsha/zulip,Jianchun1/zulip,esander91/zulip,johnny9/zulip,hengqujushi/zulip,yocome/zulip,vaidap/zulip,KingxBanana/zulip,natanovia/zulip,ikasumiwt/zulip,PaulPetring/zulip,AZtheAsian/zulip,aakash-cr7/zulip,j831/zulip,yuvipanda/zulip,armooo/zulip,hafeez3000/zulip,rishig/zulip,mohsenSy/zulip,mahim97/zulip,christi3k/zulip,Diptanshu8/zulip,littledogboy/zulip,he15his/zulip,dxq-git/zulip,guiquanz/zulip,peguin40/zulip,noroot/zulip,SmartPeople/zulip,technicalpickles/zulip,KJin99/zulip,umkay/zulip,wweiradio/zulip,hengqujushi/zulip,LAndreas/zulip,zulip/zulip,tiansiyuan/zulip,babbage/zulip,themass/zulip,Drooids/zulip,LeeRisk/zulip,jainayush975/zulip,TigorC/zulip,ikasumiwt/zulip,LAndreas/zulip,Cheppers/zulip,Gabriel0402/zulip,cosmicAsymmetry/zulip,joyhchen/zulip,mahim97/zulip,paxapy/zulip,kou/zulip,SmartPeople/zulip,zofuthan/zulip,AZtheAsian/zulip,wweiradio/zulip,dnmfarrell/zulip,vaidap/zulip,rishig/zulip,krtkmj/zulip,technicalpickles/zulip,brainwane/zulip,schatt/zulip,tdr130/zulip,andersk/zulip,amyliu345/zulip,karamcnair/zulip,jonesgithub/zulip,Vallher/zulip,ryanbackman/zulip,arpitpanwar/zulip,PaulPetring/zulip,synicalsyntax/zulip,akuseru/zulip,Suninus/zulip,EasonYi/zulip,umkay/zulip,joyhchen/zulip,alliejones/zulip,pradiptad/zulip,so0k/zulip,timabbott/zulip,arpith/zulip,hustlzp/zulip,blaze225/zulip,Vallher/zulip,johnny9/zulip,umkay/zulip,armooo/zulip,hayderimran7/zulip,aakash-cr7/zulip,littledogboy/zulip,punchagan/zulip,avastu/zulip,codeKonami/zulip,verma-varsha/zulip,PhilSk/zulip,dotcool/zulip,dattatreya303/zulip,tommyip/zulip,luyifan/zulip,rht/zulip,zhaoweigg/zulip,zacps/zulip,rht/zulip,joshisa/zulip,he15his/zulip,voidException/zulip,willingc/zulip,EasonYi/zulip,voidException/zulip,zwily/zulip,lfranchi/zulip,sonali0901/zulip,esander91/zulip,joshisa/zulip,souravbadami/zulip,esander91/zulip,RobotCaleb/zulip,praveenaki/zulip,Gabriel0402/zulip,amyliu345/zulip,zachallaun/zulip,swinghu/zulip,wangdeshui/zulip,synicalsyntax/zulip,brainwane/zulip,peiwei/zulip,arpitpanwar/zulip,punchagan/zulip,souravbadami/zulip,zorojean/zulip,AZtheAsian/zulip,zofuthan/zulip,xuanhan863/zulip,KingxBanana/zulip,saitodisse/zulip,Vallher/zulip,sup95/zulip,armooo/zulip,blaze225/zulip,showell/zulip,kaiyuanheshang/zulip,jessedhillon/zulip,ryanbackman/zulip,huangkebo/zulip,dhcrzf/zulip,arpitpanwar/zulip,ipernet/zulip,joyhchen/zulip,guiquanz/zulip,atomic-labs/zulip,amyliu345/zulip,KingxBanana/zulip,reyha/zulip,krtkmj/zulip,KJin99/zulip,johnny9/zulip,Cheppers/zulip,MayB/zulip,easyfmxu/zulip,esander91/zulip,themass/zulip,Juanvulcano/zulip,dotcool/zulip,so0k/zulip,amallia/zulip,souravbadami/zulip,voidException/zulip,DazWorrall/zulip,saitodisse/zulip,so0k/zulip,ApsOps/zulip,zhaoweigg/zulip,rishig/zulip,kou/zulip,tbutter/zulip,schatt/zulip,brockwhittaker/zulip,joshisa/zulip,hj3938/zulip,developerfm/zulip,aakash-cr7/zulip,ufosky-server/zulip,dxq-git/zulip,zacps/zulip,Qgap/zulip,grave-w-grave/zulip,fw1121/zulip,PhilSk/zulip,j831/zulip,christi3k/zulip,gigawhitlocks/zulip,hayderimran7/zulip,udxxabp/zulip,synicalsyntax/zulip,JPJPJPOPOP/zulip,paxapy/zulip,hustlzp/zulip,xuanhan863/zulip,ipernet/zulip,paxapy/zulip,glovebx/zulip,cosmicAsymmetry/zulip,grave-w-grave/zulip,amallia/zulip,mansilladev/zulip,mohsenSy/zulip,RobotCaleb/zulip,aakash-cr7/zulip,shaunstanislaus/zulip,Galexrt/zulip,jonesgithub/zulip,rht/zulip,easyfmxu/zulip,wangdeshui/zulip,eeshangarg/zulip,praveenaki/zulip,rishig/zulip,dnmfarrell/zulip,noroot/zulip,ApsOps/zulip,dwrpayne/zulip,zofuthan/zulip,xuxiao/zulip,zofuthan/zulip,yocome/zulip,guiquanz/zulip,mansilladev/zulip,easyfmxu/zulip,vikas-parashar/zulip,seapasulli/zulip,johnny9/zulip,ApsOps/zulip,ipernet/zulip,glovebx/zulip,thomasboyt/zulip,LeeRisk/zulip,sup95/zulip,reyha/zulip,eastlhu/zulip,he15his/zulip,amallia/zulip,zorojean/zulip,wweiradio/zulip,MariaFaBella85/zulip,mdavid/zulip,ufosky-server/zulip,zwily/zulip,JanzTam/zulip,jackrzhang/zulip,shaunstanislaus/zulip,JPJPJPOPOP/zulip,jonesgithub/zulip,tdr130/zulip,paxapy/zulip,jainayush975/zulip,kou/zulip,tdr130/zulip,hengqujushi/zulip,hj3938/zulip,dnmfarrell/zulip,shubhamdhama/zulip,ashwinirudrappa/zulip,synicalsyntax/zulip,bitemyapp/zulip,Gabriel0402/zulip,jimmy54/zulip,lfranchi/zulip,bitemyapp/zulip,Frouk/zulip,MayB/zulip,bastianh/zulip,technicalpickles/zulip,dotcool/zulip,voidException/zulip,ufosky-server/zulip,technicalpickles/zulip,Batterfii/zulip,willingc/zulip,reyha/zulip,ahmadassaf/zulip,gkotian/zulip,LAndreas/zulip,jessedhillon/zulip,EasonYi/zulip,ipernet/zulip,jrowan/zulip,vakila/zulip,gkotian/zulip,isht3/zulip,moria/zulip,dnmfarrell/zulip,gigawhitlocks/zulip,developerfm/zulip,bitemyapp/zulip,peiwei/zulip,ryanbackman/zulip,gigawhitlocks/zulip,niftynei/zulip,praveenaki/zulip,wweiradio/zulip,tbutter/zulip,nicholasbs/zulip,bssrdf/zulip,qq1012803704/zulip,ericzhou2008/zulip,wavelets/zulip,brainwane/zulip,ahmadassaf/zulip,RobotCaleb/zulip,huangkebo/zulip,isht3/zulip,calvinleenyc/zulip,stamhe/zulip,dhcrzf/zulip,udxxabp/zulip,sharmaeklavya2/zulip,calvinleenyc/zulip,thomasboyt/zulip,aliceriot/zulip,vikas-parashar/zulip,verma-varsha/zulip,hackerkid/zulip,andersk/zulip,itnihao/zulip,krtkmj/zulip,natanovia/zulip,qq1012803704/zulip,dotcool/zulip,jerryge/zulip,pradiptad/zulip,levixie/zulip,RobotCaleb/zulip,easyfmxu/zulip,Vallher/zulip,he15his/zulip,so0k/zulip,avastu/zulip,bowlofstew/zulip,EasonYi/zulip,Batterfii/zulip,brockwhittaker/zulip,dnmfarrell/zulip,ashwinirudrappa/zulip,stamhe/zulip,peiwei/zulip,shubhamdhama/zulip,xuanhan863/zulip,brainwane/zulip,ericzhou2008/zulip,vikas-parashar/zulip,jphilipsen05/zulip,amallia/zulip,aliceriot/zulip,wangdeshui/zulip,DazWorrall/zulip,bluesea/zulip,karamcnair/zulip,zachallaun/zulip,andersk/zulip,ikasumiwt/zulip,thomasboyt/zulip,grave-w-grave/zulip,DazWorrall/zulip,littledogboy/zulip,he15his/zulip,peiwei/zulip,aakash-cr7/zulip,udxxabp/zulip,hustlzp/zulip,praveenaki/zulip,umkay/zulip,MayB/zulip,jrowan/zulip,niftynei/zulip,mansilladev/zulip,jimmy54/zulip,andersk/zulip,reyha/zulip,dwrpayne/zulip,m1ssou/zulip,kaiyuanheshang/zulip,krtkmj/zulip,mansilladev/zulip,Gabriel0402/zulip,gigawhitlocks/zulip,SmartPeople/zulip,LeeRisk/zulip,joshisa/zulip,themass/zulip,aps-sids/zulip,aliceriot/zulip,jeffcao/zulip,alliejones/zulip,hj3938/zulip,showell/zulip,Diptanshu8/zulip,bssrdf/zulip,stamhe/zulip,codeKonami/zulip,esander91/zulip,littledogboy/zulip,schatt/zulip,gkotian/zulip,KJin99/zulip,zwily/zulip,jackrzhang/zulip,armooo/zulip,mohsenSy/zulip,ApsOps/zulip,luyifan/zulip,vakila/zulip,JPJPJPOPOP/zulip,RobotCaleb/zulip,zhaoweigg/zulip,tiansiyuan/zulip,mdavid/zulip,calvinleenyc/zulip,joyhchen/zulip,developerfm/zulip,shaunstanislaus/zulip,hafeez3000/zulip,hayderimran7/zulip,isht3/zulip,bssrdf/zulip,jackrzhang/zulip,umkay/zulip,xuanhan863/zulip,themass/zulip,kokoar/zulip,cosmicAsymmetry/zulip,vakila/zulip,zacps/zulip,noroot/zulip,SmartPeople/zulip,MariaFaBella85/zulip,KingxBanana/zulip,dotcool/zulip,LAndreas/zulip,johnnygaddarr/zulip,hustlzp/zulip,proliming/zulip,jessedhillon/zulip,Diptanshu8/zulip,hayderimran7/zulip,developerfm/zulip,arpith/zulip,ahmadassaf/zulip,Vallher/zulip,RobotCaleb/zulip,bowlofstew/zulip,shubhamdhama/zulip,jonesgithub/zulip,Jianchun1/zulip,bastianh/zulip,tdr130/zulip,aps-sids/zulip,qq1012803704/zulip,praveenaki/zulip,xuanhan863/zulip,Frouk/zulip,Drooids/zulip,xuxiao/zulip,willingc/zulip,MariaFaBella85/zulip,moria/zulip,krtkmj/zulip,moria/zulip,dattatreya303/zulip,Drooids/zulip,PhilSk/zulip,jimmy54/zulip,shaunstanislaus/zulip,Gabriel0402/zulip,hustlzp/zulip,shaunstanislaus/zulip,amyliu345/zulip,Diptanshu8/zulip,pradiptad/zulip,dhcrzf/zulip,jainayush975/zulip,timabbott/zulip,dhcrzf/zulip,babbage/zulip,PaulPetring/zulip,ahmadassaf/zulip,zwily/zulip,brainwane/zulip,samatdav/zulip,he15his/zulip,shrikrishnaholla/zulip,qq1012803704/zulip,qq1012803704/zulip,tdr130/zulip,kaiyuanheshang/zulip,peguin40/zulip,MariaFaBella85/zulip,Gabriel0402/zulip,PaulPetring/zulip,hj3938/zulip,zorojean/zulip,kaiyuanheshang/zulip,dhcrzf/zulip,amanharitsh123/zulip,dotcool/zulip,adnanh/zulip,aliceriot/zulip,technicalpickles/zulip,sonali0901/zulip,brockwhittaker/zulip,JanzTam/zulip,KJin99/zulip,hengqujushi/zulip,udxxabp/zulip,codeKonami/zulip,timabbott/zulip,SmartPeople/zulip,susansls/zulip,vakila/zulip,xuxiao/zulip,blaze225/zulip,hengqujushi/zulip,natanovia/zulip,jrowan/zulip,peiwei/zulip,aliceriot/zulip,nicholasbs/zulip,rht/zulip,amanharitsh123/zulip,vabs22/zulip,adnanh/zulip,m1ssou/zulip,Batterfii/zulip,yocome/zulip,tommyip/zulip,mdavid/zulip,yuvipanda/zulip,LAndreas/zulip,atomic-labs/zulip,ryansnowboarder/zulip,Jianchun1/zulip,bowlofstew/zulip,shubhamdhama/zulip,isht3/zulip,Diptanshu8/zulip,jphilipsen05/zulip,luyifan/zulip,yocome/zulip,vabs22/zulip,tiansiyuan/zulip,dxq-git/zulip,vakila/zulip,atomic-labs/zulip,hafeez3000/zulip,Diptanshu8/zulip,eeshangarg/zulip,MayB/zulip,mdavid/zulip,tiansiyuan/zulip,SmartPeople/zulip,ikasumiwt/zulip,udxxabp/zulip,brockwhittaker/zulip,blaze225/zulip,bitemyapp/zulip,suxinde2009/zulip,tiansiyuan/zulip,wweiradio/zulip,j831/zulip,mansilladev/zulip,susansls/zulip,ashwinirudrappa/zulip,luyifan/zulip,PhilSk/zulip,voidException/zulip,jonesgithub/zulip,aliceriot/zulip,calvinleenyc/zulip,avastu/zulip,zulip/zulip,synicalsyntax/zulip,bowlofstew/zulip,m1ssou/zulip,Jianchun1/zulip,codeKonami/zulip,dwrpayne/zulip,lfranchi/zulip,jphilipsen05/zulip,suxinde2009/zulip,babbage/zulip,vikas-parashar/zulip,kaiyuanheshang/zulip,JanzTam/zulip,jackrzhang/zulip,mohsenSy/zulip,niftynei/zulip,firstblade/zulip,yocome/zulip,jessedhillon/zulip,grave-w-grave/zulip,LeeRisk/zulip,jerryge/zulip,Batterfii/zulip,punchagan/zulip,avastu/zulip,sharmaeklavya2/zulip,bowlofstew/zulip,ericzhou2008/zulip,amanharitsh123/zulip,hustlzp/zulip,jessedhillon/zulip,JanzTam/zulip,saitodisse/zulip,bssrdf/zulip,shrikrishnaholla/zulip,sup95/zulip,gigawhitlocks/zulip,amanharitsh123/zulip,kokoar/zulip,tommyip/zulip,wdaher/zulip,brainwane/zulip,swinghu/zulip,xuanhan863/zulip,huangkebo/zulip,ufosky-server/zulip,brockwhittaker/zulip,atomic-labs/zulip,jimmy54/zulip,Suninus/zulip,zofuthan/zulip,jainayush975/zulip,littledogboy/zulip,wavelets/zulip,wavelets/zulip,yuvipanda/zulip,moria/zulip,alliejones/zulip,Batterfii/zulip,johnnygaddarr/zulip,TigorC/zulip,christi3k/zulip,glovebx/zulip,tiansiyuan/zulip,willingc/zulip,umkay/zulip,swinghu/zulip,jerryge/zulip,Galexrt/zulip,joyhchen/zulip,thomasboyt/zulip,Jianchun1/zulip,natanovia/zulip,DazWorrall/zulip,zorojean/zulip,nicholasbs/zulip,cosmicAsymmetry/zulip,gkotian/zulip,arpitpanwar/zulip,bssrdf/zulip,zofuthan/zulip,dawran6/zulip,itnihao/zulip,tdr130/zulip,mahim97/zulip,jeffcao/zulip,isht3/zulip,JPJPJPOPOP/zulip,bastianh/zulip,alliejones/zulip,m1ssou/zulip,vaidap/zulip,andersk/zulip,arpitpanwar/zulip,zhaoweigg/zulip,dattatreya303/zulip,littledogboy/zulip,calvinleenyc/zulip,xuxiao/zulip,akuseru/zulip,tdr130/zulip,isht3/zulip,dattatreya303/zulip,pradiptad/zulip,alliejones/zulip,themass/zulip,susansls/zulip,codeKonami/zulip,littledogboy/zulip,technicalpickles/zulip,dawran6/zulip,hengqujushi/zulip,developerfm/zulip,dhcrzf/zulip,hackerkid/zulip,kokoar/zulip,babbage/zulip,kou/zulip,itnihao/zulip,hj3938/zulip,vabs22/zulip,atomic-labs/zulip,fw1121/zulip,praveenaki/zulip,xuxiao/zulip,JPJPJPOPOP/zulip,rishig/zulip,moria/zulip,jphilipsen05/zulip,calvinleenyc/zulip,EasonYi/zulip,JanzTam/zulip,easyfmxu/zulip,zhaoweigg/zulip,grave-w-grave/zulip,swinghu/zulip,aps-sids/zulip,Jianchun1/zulip,joyhchen/zulip,Qgap/zulip,levixie/zulip,christi3k/zulip,wdaher/zulip,levixie/zulip,sharmaeklavya2/zulip,proliming/zulip,zacps/zulip,jessedhillon/zulip,tbutter/zulip,mohsenSy/zulip,ahmadassaf/zulip,bssrdf/zulip,arpitpanwar/zulip,wavelets/zulip,paxapy/zulip,bitemyapp/zulip,souravbadami/zulip,guiquanz/zulip,jimmy54/zulip,nicholasbs/zulip,bluesea/zulip,j831/zulip,jrowan/zulip,KJin99/zulip,Galexrt/zulip,gkotian/zulip,shubhamdhama/zulip,LAndreas/zulip,glovebx/zulip,easyfmxu/zulip,peguin40/zulip,dattatreya303/zulip,ericzhou2008/zulip,glovebx/zulip,deer-hope/zulip,wdaher/zulip,RobotCaleb/zulip,avastu/zulip,eastlhu/zulip,armooo/zulip,guiquanz/zulip,wangdeshui/zulip,MayB/zulip,gkotian/zulip,yuvipanda/zulip,zhaoweigg/zulip,LeeRisk/zulip,karamcnair/zulip,itnihao/zulip,tbutter/zulip,Galexrt/zulip,ryansnowboarder/zulip,niftynei/zulip | ---
+++
@@ -28,6 +28,7 @@
'object': obj,
'confirmed': confirmed,
'days': getattr(settings, 'EMAIL_CONFIRMATION_DAYS', 10),
+ 'key': confirmation_key,
}
templates = [
'confirmation/confirm.html', |
6ea9492ae32ad744da4803dcab3cf57334dd69e5 | script_helpers.py | script_helpers.py | """A set of functions to standardize some options for python scripts."""
def setup_parser_help(parser, additional_docs=None):
"""
Set formatting for parser to raw and add docstring to help output
Parameters
----------
parser : `ArgumentParser`
The parser to be modified.
additional_docs: str
Any documentation to be added to the documentation produced by
`argparse`
"""
from argparse import RawDescriptionHelpFormatter
parser.formatter_class = RawDescriptionHelpFormatter
if additional_docs is not None:
parser.epilog = additional_docs
def add_verbose(parser):
"""
Add a verbose option (--verbose or -v) to parser.
Parameters:
-----------
parser : `ArgumentParser`
"""
verbose_help = "provide more information during processing"
parser.add_argument("-v", "--verbose", help=verbose_help,
action="store_true")
| """A set of functions to standardize some options for python scripts."""
def setup_parser_help(parser, additional_docs=None):
"""
Set formatting for parser to raw and add docstring to help output
Parameters
----------
parser : `ArgumentParser`
The parser to be modified.
additional_docs: str
Any documentation to be added to the documentation produced by
`argparse`
"""
from argparse import RawDescriptionHelpFormatter
parser.formatter_class = RawDescriptionHelpFormatter
if additional_docs is not None:
parser.epilog = additional_docs
def add_verbose(parser):
"""
Add a verbose option (--verbose or -v) to parser.
Parameters:
-----------
parser : `ArgumentParser`
"""
verbose_help = "provide more information during processing"
parser.add_argument("-v", "--verbose", help=verbose_help,
action="store_true")
def add_directories(parser):
"""
Add a positional argument that is one or more directories.
Parameters
----------
parser : `ArgumentParser`
"""
parser.add_argument("dir", metavar='dir', nargs='+',
help="Directory to process")
| Change name of and add documentation to directory argument | Change name of and add documentation to directory argument
| Python | bsd-3-clause | mwcraig/msumastro | ---
+++
@@ -31,8 +31,24 @@
-----------
parser : `ArgumentParser`
+
"""
verbose_help = "provide more information during processing"
parser.add_argument("-v", "--verbose", help=verbose_help,
action="store_true")
+
+
+def add_directories(parser):
+ """
+ Add a positional argument that is one or more directories.
+
+ Parameters
+ ----------
+
+ parser : `ArgumentParser`
+
+ """
+
+ parser.add_argument("dir", metavar='dir', nargs='+',
+ help="Directory to process") |
07538222d07b0a565cadadd40df9bedeb12a4f60 | talk_timer.py | talk_timer.py | #!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
import argparse
from time import sleep
import pyttsx
parser = argparse.ArgumentParser(description='Presentation timer with spoken warnings.')
parser.add_argument('minutes', type=int, nargs=1, help='Length of talk in minutes')
args = parser.parse_args()
minutes = args.minutes[0]
print "Timing a {0}-minute talk.".format(minutes)
# Sleep for X-minute talk duration
sleep(minutes * 60)
# Text to speech
engine = pyttsx.init()
engine.say("Time is up")
engine.runAndWait()
print("Time is up")
| #!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
import argparse
from time import sleep
import pyttsx
parser = argparse.ArgumentParser(description='Presentation timer with spoken warnings.')
parser.add_argument('minutes', type=int, help='Length of talk in minutes')
args = parser.parse_args()
print "Timing a {0}-minute talk.".format(args.minutes)
# Sleep for X-minute talk duration
sleep(args.minutes * 60)
# Text to speech
engine = pyttsx.init()
engine.say("Time is up")
engine.runAndWait()
print("Time is up")
| Remove nargs param so that minutes is an int, not list. | Remove nargs param so that minutes is an int, not list.
| Python | bsd-3-clause | audreyr/useful | ---
+++
@@ -5,15 +5,13 @@
import pyttsx
parser = argparse.ArgumentParser(description='Presentation timer with spoken warnings.')
-parser.add_argument('minutes', type=int, nargs=1, help='Length of talk in minutes')
+parser.add_argument('minutes', type=int, help='Length of talk in minutes')
args = parser.parse_args()
-minutes = args.minutes[0]
-
-print "Timing a {0}-minute talk.".format(minutes)
+print "Timing a {0}-minute talk.".format(args.minutes)
# Sleep for X-minute talk duration
-sleep(minutes * 60)
+sleep(args.minutes * 60)
# Text to speech
engine = pyttsx.init() |
b06eb92ec878a06a2fa1ce9b7eb4d253d5481daa | tests/activity/test_activity_deposit_assets.py | tests/activity/test_activity_deposit_assets.py | import unittest
from activity.activity_DepositAssets import activity_DepositAssets
import settings_mock
from ddt import ddt, data, unpack
@ddt
class TestDepositAssets(unittest.TestCase):
def setUp(self):
self.depositassets = activity_DepositAssets(settings_mock, None, None, None, None)
@unpack
@data({'input': '.tif', 'expected': ['.tif']},
{'input': '.jpg, .tiff, .png', 'expected':['.jpg', '.tiff', '.png']})
def test_get_no_download_extensions(self, input, expected):
result = self.depositassets.get_no_download_extensions(input)
self.assertListEqual(result, expected)
@unpack
@data(
(None, None),
('image.jpg', 'image/jpeg'),
('/folder/file.pdf.zip', 'application/x-zip-compressed'),
('/folder/weird_file.wdl', 'binary/octet-stream'),
('a_file', 'binary/octet-stream')
)
def test_content_type_from_file_name(self, input, expected):
result = self.depositassets.content_type_from_file_name(input)
self.assertEqual(result, expected)
if __name__ == '__main__':
unittest.main()
| import unittest
from activity.activity_DepositAssets import activity_DepositAssets
import settings_mock
from ddt import ddt, data, unpack
@ddt
class TestDepositAssets(unittest.TestCase):
def setUp(self):
self.depositassets = activity_DepositAssets(settings_mock, None, None, None, None)
@unpack
@data({'input': '.tif', 'expected': ['.tif']},
{'input': '.jpg, .tiff, .png', 'expected':['.jpg', '.tiff', '.png']})
def test_get_no_download_extensions(self, input, expected):
result = self.depositassets.get_no_download_extensions(input)
self.assertListEqual(result, expected)
@unpack
@data(
(None, None),
('image.jpg', 'image/jpeg'),
('/folder/file.test.pdf', 'application/pdf'),
('/folder/weird_file.wdl', 'binary/octet-stream'),
('a_file', 'binary/octet-stream')
)
def test_content_type_from_file_name(self, input, expected):
result = self.depositassets.content_type_from_file_name(input)
self.assertEqual(result, expected)
if __name__ == '__main__':
unittest.main()
| Change test data for mimetype to content_type. | Change test data for mimetype to content_type.
| Python | mit | gnott/elife-bot,gnott/elife-bot,jhroot/elife-bot,gnott/elife-bot,jhroot/elife-bot,jhroot/elife-bot | ---
+++
@@ -20,7 +20,7 @@
@data(
(None, None),
('image.jpg', 'image/jpeg'),
- ('/folder/file.pdf.zip', 'application/x-zip-compressed'),
+ ('/folder/file.test.pdf', 'application/pdf'),
('/folder/weird_file.wdl', 'binary/octet-stream'),
('a_file', 'binary/octet-stream')
) |
a09274fbc9277de2cbd3336fca4922094b0db8d1 | crmapp/urls.py | crmapp/urls.py | from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'crmapp.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
)
| from django.conf.urls import patterns, include, url
from marketing.views import HomePage
urlpatterns = patterns('',
# Marketing pages
url(r'^$', HomePage.as_view(), name="home"),
# Subscriber related URLs
# Admin URL
# Login/Logout URLs
# Account related URLs
# Contact related URLS
# Communication related URLs
) | Create the Home Page > Create the URL Conf | Create the Home Page > Create the URL Conf
| Python | mit | tabdon/crmeasyapp,tabdon/crmeasyapp,deenaariff/Django | ---
+++
@@ -1,10 +1,27 @@
from django.conf.urls import patterns, include, url
-from django.contrib import admin
+
+from marketing.views import HomePage
urlpatterns = patterns('',
- # Examples:
- # url(r'^$', 'crmapp.views.home', name='home'),
- # url(r'^blog/', include('blog.urls')),
- url(r'^admin/', include(admin.site.urls)),
+ # Marketing pages
+ url(r'^$', HomePage.as_view(), name="home"),
+
+ # Subscriber related URLs
+
+
+ # Admin URL
+
+
+ # Login/Logout URLs
+
+
+ # Account related URLs
+
+
+ # Contact related URLS
+
+
+ # Communication related URLs
+
) |
f155c200dc6f8b7b9461f399a3d3642d23e64942 | snipsskills/templates/intent_template.py | snipsskills/templates/intent_template.py | # -*-: coding utf-8 -*-
""" Auto-generated intent class. """
# *****************************************************************************
# *****************************************************************************
# *****************************************************************************
#
# WARNING: THIS IS AN AUTO-GENERATED FILE
# DO NOT ATTEMPT TO EDIT IT, AS CHANGES WILL BE OVERWRITTEN.
#
# *****************************************************************************
# *****************************************************************************
# *****************************************************************************
# pylint: disable=line-too-long
from snipsskillscore.intent_parser import IntentParser
class {{to_camelcase_capitalized(intent.name)}}Intent:
intentName = "{{ intent.name }}"
{% if intent.slots is defined and intent.slots|length > 0 -%}
def __init__(self{% for slot in intent.slots -%}, {{slot.name}}=None{% endfor %}):
{% for slot in intent.slots -%}
self.{{slot.name}} = {{slot.name}}
{% endfor %}
{% endif -%}
@staticmethod
def parse(payload):
intentName = IntentParser.get_intent_name(payload)
if intentName != {{to_camelcase_capitalized(intent.name)}}Intent.intentName:
return None
return {{to_camelcase_capitalized(intent.name)}}Intent(
{% for slot in intent.slots -%}
IntentParser.get_slot_value(payload, "{{ slot.name}}"){{"," if not loop.last}}
{% endfor -%}
)
| # -*-: coding utf-8 -*-
""" Auto-generated intent class. """
# *****************************************************************************
# *****************************************************************************
# *****************************************************************************
#
# WARNING: THIS IS AN AUTO-GENERATED FILE
# DO NOT ATTEMPT TO EDIT IT, AS CHANGES WILL BE OVERWRITTEN.
#
# *****************************************************************************
# *****************************************************************************
# *****************************************************************************
# pylint: disable=line-too-long
from snipsskillscore.intent_parser import IntentParser
class {{to_camelcase_capitalized(intent.name)}}Intent:
intentName = "{{ intent.name }}"
{% if intent.slots is defined and intent.slots|length > 0 -%}
def __init__(self, sessionId, siteId, customData{% for slot in intent.slots -%}, {{slot.name}}=None{% endfor %}):
self.sessionId = sessionId
self.siteId = siteId
self.customData = customData
{% for slot in intent.slots -%}
self.{{slot.name}} = {{slot.name}}
{% endfor %}
{% endif -%}
@staticmethod
def parse(payload):
intentName = IntentParser.get_intent_name(payload)
if intentName != {{to_camelcase_capitalized(intent.name)}}Intent.intentName:
return None
return {{to_camelcase_capitalized(intent.name)}}Intent(
IntentParser.get_session_id(payload),
IntentParser.get_site_id(payload),
IntentParser.get_custom_data(payload),
{% for slot in intent.slots -%}
IntentParser.get_slot_value(payload, "{{ slot.name}}"){{"," if not loop.last}}
{% endfor -%}
)
| Add intent sessionId siteId & customData | Add intent sessionId siteId & customData
| Python | mit | snipsco/snipsskills,snipsco/snipsskills,snipsco/snipsskills,snipsco/snipsskills | ---
+++
@@ -21,7 +21,10 @@
intentName = "{{ intent.name }}"
{% if intent.slots is defined and intent.slots|length > 0 -%}
- def __init__(self{% for slot in intent.slots -%}, {{slot.name}}=None{% endfor %}):
+ def __init__(self, sessionId, siteId, customData{% for slot in intent.slots -%}, {{slot.name}}=None{% endfor %}):
+ self.sessionId = sessionId
+ self.siteId = siteId
+ self.customData = customData
{% for slot in intent.slots -%}
self.{{slot.name}} = {{slot.name}}
{% endfor %}
@@ -33,6 +36,9 @@
if intentName != {{to_camelcase_capitalized(intent.name)}}Intent.intentName:
return None
return {{to_camelcase_capitalized(intent.name)}}Intent(
+ IntentParser.get_session_id(payload),
+ IntentParser.get_site_id(payload),
+ IntentParser.get_custom_data(payload),
{% for slot in intent.slots -%}
IntentParser.get_slot_value(payload, "{{ slot.name}}"){{"," if not loop.last}}
{% endfor -%} |
a51d280ca7c7f487e6743e4f377f70641a8b4edd | turbustat/statistics/statistics_list.py | turbustat/statistics/statistics_list.py | # Licensed under an MIT open source license - see LICENSE
'''
Returns a list of all available distance metrics
'''
statistics_list = ["Wavelet", "MVC", "PSpec", "Bispectrum", "DeltaVariance",
"Genus", "VCS", "VCA", "Tsallis", "PCA", "SCF", "Cramer",
"Skewness", "Kurtosis", "VCS_Small_Scale", "VCS_Break",
"VCS_Large_Scale", "PDF_Hellinger", "PDF_KS", # "PDF_AD",
"Dendrogram_Hist", "Dendrogram_Num"]
twoD_statistics_list = \
["Wavelet", "MVC", "PSpec", "Bispectrum", "DeltaVariance",
"Genus", "Tsallis", "Skewness", "Kurtosis",
"PDF_Hellinger", "PDF_KS", # "PDF_AD",
"Dendrogram_Hist", "Dendrogram_Num"]
| # Licensed under an MIT open source license - see LICENSE
'''
Returns a list of all available distance metrics
'''
statistics_list = ["Wavelet", "MVC", "PSpec", "Bispectrum", "DeltaVariance",
"Genus", "VCS", "VCA", "Tsallis", "PCA", "SCF", "Cramer",
"Skewness", "Kurtosis", "VCS_Small_Scale", "VCS_Break",
"VCS_Large_Scale", "PDF_Hellinger", "PDF_KS",
"PDF_Lognormal", # "PDF_AD",
"Dendrogram_Hist", "Dendrogram_Num"]
twoD_statistics_list = \
["Wavelet", "MVC", "PSpec", "Bispectrum", "DeltaVariance",
"Genus", "Tsallis", "Skewness", "Kurtosis",
"PDF_Hellinger", "PDF_KS",
"PDF_Lognormal", # "PDF_AD",
"Dendrogram_Hist", "Dendrogram_Num"]
threeD_statistics_list = \
["VCS", "VCA", "PCA", "SCF", "Cramer", "VCS_Small_Scale",
"VCS_Large_Scale", "VCS_Break", "PDF_Hellinger", "PDF_KS",
"PDF_Lognormal", "Dendrogram_Hist", "Dendrogram_Num"]
| Update the stats lists and add a 3D only version | Update the stats lists and add a 3D only version
| Python | mit | Astroua/TurbuStat,e-koch/TurbuStat | ---
+++
@@ -7,11 +7,18 @@
statistics_list = ["Wavelet", "MVC", "PSpec", "Bispectrum", "DeltaVariance",
"Genus", "VCS", "VCA", "Tsallis", "PCA", "SCF", "Cramer",
"Skewness", "Kurtosis", "VCS_Small_Scale", "VCS_Break",
- "VCS_Large_Scale", "PDF_Hellinger", "PDF_KS", # "PDF_AD",
+ "VCS_Large_Scale", "PDF_Hellinger", "PDF_KS",
+ "PDF_Lognormal", # "PDF_AD",
"Dendrogram_Hist", "Dendrogram_Num"]
twoD_statistics_list = \
["Wavelet", "MVC", "PSpec", "Bispectrum", "DeltaVariance",
"Genus", "Tsallis", "Skewness", "Kurtosis",
- "PDF_Hellinger", "PDF_KS", # "PDF_AD",
+ "PDF_Hellinger", "PDF_KS",
+ "PDF_Lognormal", # "PDF_AD",
"Dendrogram_Hist", "Dendrogram_Num"]
+
+threeD_statistics_list = \
+ ["VCS", "VCA", "PCA", "SCF", "Cramer", "VCS_Small_Scale",
+ "VCS_Large_Scale", "VCS_Break", "PDF_Hellinger", "PDF_KS",
+ "PDF_Lognormal", "Dendrogram_Hist", "Dendrogram_Num"] |
50d69badbaeb41736269c99f7b301f09c9b24ecb | testing/test_models.py | testing/test_models.py | from k2catalogue import models
def test_safe_float_good():
assert models.safe_float("2") == 2.0
def test_safe_float_bad():
assert models.safe_float('this is not convertable to a float') is None
| from k2catalogue import models
def test_safe_float_good():
assert models.safe_float("2") == 2.0
def test_safe_float_bad():
assert models.safe_float('this is not convertable to a float') is None
def test_proposal_printing():
proposal = models.Proposal(proposal_id='abc')
assert repr(proposal) == '<Proposal: abc>'
| Add test for proposal printing | Add test for proposal printing
| Python | mit | mindriot101/k2catalogue | ---
+++
@@ -6,3 +6,6 @@
def test_safe_float_bad():
assert models.safe_float('this is not convertable to a float') is None
+def test_proposal_printing():
+ proposal = models.Proposal(proposal_id='abc')
+ assert repr(proposal) == '<Proposal: abc>' |
855cea2b603453ce7ed907fc153962596de31f00 | src/json.py | src/json.py | msg = 'This is not yet implemented'
def validate(sketch):
"""
- sketch: a `dict`
"""
raise NotImplementedError(msg)
def readsketch_iter(iterable):
"""
- iterable: as return by ijson.parser
Returns a `dict` with a sketch information
"""
raise NotImplementedError(msg)
def readjamschema(schema):
"""
Read a JAM definition schema
"""
raise NotImplementedError(msg)
| MSG = 'This is not yet implemented'
def validate(sketch):
"""
- sketch: a `dict`
"""
raise NotImplementedError(MSG)
def readsketch_iter(iterable):
"""
- iterable: as return by ijson.parser
Returns a `dict` with a sketch information
"""
raise NotImplementedError(MSG)
def readjamschema(schema):
"""
Read a JAM definition schema
"""
raise NotImplementedError(MSG)
| Rename msg -> MSG (since a constant). | Rename msg -> MSG (since a constant).
| Python | mit | lgautier/mashing-pumpkins,lgautier/mashing-pumpkins,lgautier/mashing-pumpkins | ---
+++
@@ -1,10 +1,12 @@
-msg = 'This is not yet implemented'
+MSG = 'This is not yet implemented'
+
def validate(sketch):
"""
- sketch: a `dict`
"""
- raise NotImplementedError(msg)
+ raise NotImplementedError(MSG)
+
def readsketch_iter(iterable):
"""
@@ -12,11 +14,12 @@
Returns a `dict` with a sketch information
"""
- raise NotImplementedError(msg)
+ raise NotImplementedError(MSG)
+
def readjamschema(schema):
"""
Read a JAM definition schema
"""
- raise NotImplementedError(msg)
+ raise NotImplementedError(MSG)
|
7cacf4f78f03e95eec51aac211779539954aee38 | pymanopt/manifolds/__init__.py | pymanopt/manifolds/__init__.py | from .grassmann import Grassmann
from .sphere import Sphere
from .stiefel import Stiefel
from .psd import PSDFixedRank, PSDFixedRankComplex, Elliptope, PositiveDefinite
from .oblique import Oblique
from .euclidean import Euclidean, Symmetric
from .product import Product
__all__ = ["Grassmann", "Sphere", "Stiefel", "PSDFixedRank",
"PSDFixedRankComplex", "Elliptope", "PositiveDefinite", "Oblique",
"Euclidean", "Product", "Symmetric"]
| from .grassmann import Grassmann
from .sphere import Sphere
from .stiefel import Stiefel
from .psd import PSDFixedRank, PSDFixedRankComplex, Elliptope, PositiveDefinite
from .oblique import Oblique
from .euclidean import Euclidean, Symmetric
from .product import Product
from .fixed_rank import FixedRankEmbedded
__all__ = ["Grassmann", "Sphere", "Stiefel", "PSDFixedRank",
"PSDFixedRankComplex", "Elliptope", "PositiveDefinite", "Oblique",
"Euclidean", "Product", "Symmetric", "FixedRankEmbedded"]
| Add FixedRankEmbedded to manifolds init. | Add FixedRankEmbedded to manifolds init.
Signed-off-by: Sebastian Weichwald <46f1a0bd5592a2f9244ca321b129902a06b53e03@sweichwald.de>
| Python | bsd-3-clause | j-towns/pymanopt,nkoep/pymanopt,tingelst/pymanopt,nkoep/pymanopt,pymanopt/pymanopt,nkoep/pymanopt,pymanopt/pymanopt | ---
+++
@@ -5,7 +5,8 @@
from .oblique import Oblique
from .euclidean import Euclidean, Symmetric
from .product import Product
+from .fixed_rank import FixedRankEmbedded
__all__ = ["Grassmann", "Sphere", "Stiefel", "PSDFixedRank",
"PSDFixedRankComplex", "Elliptope", "PositiveDefinite", "Oblique",
- "Euclidean", "Product", "Symmetric"]
+ "Euclidean", "Product", "Symmetric", "FixedRankEmbedded"] |
c2b9bcb5c931f89dcbbf473cefe8b238e01e5429 | vpr/tests/migrate/shell_migrate.py | vpr/tests/migrate/shell_migrate.py | from django.db import connection
from vpr_content import models
def removeDuplicatedTitleInMaterial():
cur = connection.cursor()
qr0 = 'select id from vpr_content_material'
qr1 = 'select text from vpr_content_material where id=%d'
qr2 = 'update vpr_content_material set text=\'%s\' where id=%d'
pt0 = '<div class="title">'
pt1 = '</div>'
cur.execute(qr0)
mids = cur.fetchall()
for mid in mids:
try:
mid = mid[0]
cur.execute(qr1 % mid)
text = cur.fetchone()[0]
p0 = text.find(pt0)
p1 = text.find(pt1, p0)
text = text[:p0] + text[p1+len(pt1)+1:]
material = models.Material.objects.get(pk=mid)
material.text = text
material.save()
print mid
except:
raise
print 'Updating failed at ' + str(mid)
| from django.db import connection
from vpr_content import models
def removeDuplicatedTitleInMaterial():
cur = connection.cursor()
qr0 = 'select id from vpr_content_material'
qr1 = 'select text from vpr_content_material where id=%d'
qr2 = 'update vpr_content_material set text=\'%s\' where id=%d'
pt0 = '<div class="title">'
pt1 = '</div>'
cur.execute(qr0)
mids = cur.fetchall()
for mid in mids:
try:
mid = mid[0]
cur.execute(qr1 % mid)
text = cur.fetchone()[0]
p0 = text.find(pt0)
p1 = text.find(pt1, p0)
text = text[:p0] + text[p1+len(pt1)+1:]
material = models.Material.objects.get(pk=mid)
material.text = text
material.save()
print mid
except:
raise
print 'Updating failed at ' + str(mid)
def determineLanguage(title, text):
VI_ELEMENTS_0 = (u'\u1ea1', u'\u1ebf', u'\u01b0')
VI_ELEMENTS_1 = ('â', 'ư', 'à')
for item in VI_ELEMENTS_0:
if item in title:
return 'vi'
for item in VI_ELEMENTS_1:
if item in text:
return 'vi'
return 'en'
def correctMaterialLanguage(material, dry=False):
if type(material) == str:
material = models.Material.objects.get(material_id=material)
new_lang = determineLanguage(material.title, material.text)
print str(material.language) + ' > ' + new_lang
if not dry:
material.language = new_lang
material.save()
def correctAllLanguages(dry=True):
targets = models.Material.objects.exclude(language='vi')
for material in targets:
correctMaterialLanguage(material, dry)
| Add script for correcting language | Add script for correcting language
| Python | agpl-3.0 | voer-platform/vp.repo,voer-platform/vp.repo,voer-platform/vp.repo,voer-platform/vp.repo | ---
+++
@@ -32,3 +32,32 @@
print 'Updating failed at ' + str(mid)
+
+def determineLanguage(title, text):
+ VI_ELEMENTS_0 = (u'\u1ea1', u'\u1ebf', u'\u01b0')
+ VI_ELEMENTS_1 = ('â', 'ư', 'à')
+ for item in VI_ELEMENTS_0:
+ if item in title:
+ return 'vi'
+ for item in VI_ELEMENTS_1:
+ if item in text:
+ return 'vi'
+ return 'en'
+
+
+def correctMaterialLanguage(material, dry=False):
+ if type(material) == str:
+ material = models.Material.objects.get(material_id=material)
+
+ new_lang = determineLanguage(material.title, material.text)
+ print str(material.language) + ' > ' + new_lang
+
+ if not dry:
+ material.language = new_lang
+ material.save()
+
+
+def correctAllLanguages(dry=True):
+ targets = models.Material.objects.exclude(language='vi')
+ for material in targets:
+ correctMaterialLanguage(material, dry) |
95c5b9c139bf69ac11338a4b2eaa9b8179d27284 | tests/test_async.py | tests/test_async.py | # -*- coding: utf-8 -*-
from asyncio import Future, gather, new_event_loop, sleep
from twisted.internet.defer import Deferred, ensureDeferred
from pyee import EventEmitter
def test_asyncio_emit():
"""Test that event_emitters can handle wrapping coroutines as used with
asyncio.
"""
loop = new_event_loop()
ee = EventEmitter(loop=loop)
should_call = Future(loop=loop)
@ee.on('event')
async def event_handler():
should_call.set_result(True)
async def create_timeout(loop=loop):
await sleep(0.1, loop=loop)
if not should_call.done():
raise Exception('should_call timed out!')
return should_call.cancel()
timeout = create_timeout(loop=loop)
@should_call.add_done_callback
def _done(result):
assert result
ee.emit('event')
loop.run_until_complete(gather(should_call, timeout, loop=loop))
loop.close()
def test_twisted_emit():
"""Test that event_emitters can handle wrapping coroutines when using
twisted and ensureDeferred.
"""
ee = EventEmitter(scheduler=ensureDeferred)
should_call = Deferred()
@ee.on('event')
async def event_handler():
should_call.callback(True)
@should_call.addCallback
def _done(result):
assert result
@should_call.addErrback
def _err(exc):
raise exc
ee.emit('event')
| # -*- coding: utf-8 -*-
from asyncio import Future, gather, new_event_loop, sleep
from mock import Mock
from twisted.internet.defer import ensureDeferred
from pyee import EventEmitter
def test_asyncio_emit():
"""Test that event_emitters can handle wrapping coroutines as used with
asyncio.
"""
loop = new_event_loop()
ee = EventEmitter(loop=loop)
should_call = Future(loop=loop)
@ee.on('event')
async def event_handler():
should_call.set_result(True)
async def create_timeout(loop=loop):
await sleep(0.1, loop=loop)
if not should_call.done():
raise Exception('should_call timed out!')
return should_call.cancel()
timeout = create_timeout(loop=loop)
@should_call.add_done_callback
def _done(result):
assert result
ee.emit('event')
loop.run_until_complete(gather(should_call, timeout, loop=loop))
loop.close()
def test_twisted_emit():
"""Test that event_emitters can handle wrapping coroutines when using
twisted and ensureDeferred.
"""
ee = EventEmitter(scheduler=ensureDeferred)
should_call = Mock()
@ee.on('event')
async def event_handler():
should_call(True)
ee.emit('event')
should_call.assert_called_once()
| Replace my deferred with a mock | Replace my deferred with a mock
| Python | mit | jfhbrook/pyee | ---
+++
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
from asyncio import Future, gather, new_event_loop, sleep
-from twisted.internet.defer import Deferred, ensureDeferred
+from mock import Mock
+from twisted.internet.defer import ensureDeferred
from pyee import EventEmitter
@@ -42,19 +43,13 @@
"""
ee = EventEmitter(scheduler=ensureDeferred)
- should_call = Deferred()
+ should_call = Mock()
@ee.on('event')
async def event_handler():
- should_call.callback(True)
-
- @should_call.addCallback
- def _done(result):
- assert result
-
- @should_call.addErrback
- def _err(exc):
- raise exc
+ should_call(True)
ee.emit('event')
+ should_call.assert_called_once()
+ |
7cde7a232a53138c2c199c16f55e0aecdcbf1aee | tests/test_basic.py | tests/test_basic.py | import sys
import pubrunner
import pubrunner.command_line
def test_countwords():
#pubrunner.pubrun('examples/CountWords/',True,True)
sys.argv = ['--test','examples/CountWords/']
pubrunner.command_line.main()
| import sys
import pubrunner
import pubrunner.command_line
def test_countwords():
#pubrunner.pubrun('examples/CountWords/',True,True)
sys.argv = ['pubrunner', '--test','examples/CountWords/']
pubrunner.command_line.main()
| Test wasn't using --test flag properly | Test wasn't using --test flag properly
| Python | mit | jakelever/pubrunner,jakelever/pubrunner | ---
+++
@@ -4,6 +4,6 @@
def test_countwords():
#pubrunner.pubrun('examples/CountWords/',True,True)
- sys.argv = ['--test','examples/CountWords/']
+ sys.argv = ['pubrunner', '--test','examples/CountWords/']
pubrunner.command_line.main()
|
711afeb0e01bc35b1f82588d814be4275f59f758 | spdx/tv_to_rdf.py | spdx/tv_to_rdf.py | #!/usr/bin/env python
# Copyright (C) 2017 BMW AG
# Author: Thomas Hafner
#
# 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.
import sys
import codecs
from spdx.parsers.tagvalue import Parser
from spdx.parsers.loggers import StandardLogger
from spdx.parsers.tagvaluebuilders import Builder
from spdx.writers.rdf import write_document
def tv_to_rdf(infile_name, outfile_name):
"""Converts a SPDX file from tag/value format to RDF format."""
parser = Parser(Builder(), StandardLogger())
parser.build()
with open(infile_name) as infile:
data = infile.read()
document, error = parser.parse(data)
if not error:
with open(outfile_name, mode='w') as outfile:
write_document(document, outfile)
else:
print 'Errors encountered while parsing RDF file.'
messages = []
document.validate(messages)
print '\n'.join(messages)
if __name__ == '__main__':
tv_to_rdf(*sys.argv[1:])
| #!/usr/bin/env python
# Copyright (C) 2017 BMW AG
# Author: Thomas Hafner
#
# 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.
import codecs
import sys
from spdx.parsers.tagvalue import Parser
from spdx.parsers.loggers import StandardLogger
from spdx.parsers.tagvaluebuilders import Builder
from spdx.writers.rdf import write_document
def tv_to_rdf(infile_name, outfile_name):
"""
Convert a SPDX file from tag/value format to RDF format.
"""
parser = Parser(Builder(), StandardLogger())
parser.build()
with open(infile_name) as infile:
data = infile.read()
document, error = parser.parse(data)
if not error:
with open(outfile_name, mode='w') as outfile:
write_document(document, outfile)
else:
print 'Errors encountered while parsing RDF file.'
messages = []
document.validate(messages)
print '\n'.join(messages)
if __name__ == '__main__':
tv_to_rdf(*sys.argv[1:])
| Normalize license header. Update format. | Normalize license header. Update format.
Signed-off-by: Philippe Ombredanne <ca95c4a6a4931f366cbdaf5878c5016609417d37@nexb.com> | Python | apache-2.0 | spdx/tools-python | ---
+++
@@ -1,29 +1,30 @@
#!/usr/bin/env python
# Copyright (C) 2017 BMW AG
-# Author: Thomas Hafner
+# Author: Thomas Hafner
+#
+# 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.
-#
-# 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
+import codecs
+import sys
-# 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.
-
-import sys
-import codecs
from spdx.parsers.tagvalue import Parser
from spdx.parsers.loggers import StandardLogger
from spdx.parsers.tagvaluebuilders import Builder
from spdx.writers.rdf import write_document
+
def tv_to_rdf(infile_name, outfile_name):
- """Converts a SPDX file from tag/value format to RDF format."""
+ """
+ Convert a SPDX file from tag/value format to RDF format.
+ """
parser = Parser(Builder(), StandardLogger())
parser.build()
with open(infile_name) as infile:
@@ -38,5 +39,6 @@
document.validate(messages)
print '\n'.join(messages)
+
if __name__ == '__main__':
tv_to_rdf(*sys.argv[1:]) |
fea76a8c9c03fef5c70e2fdd93d97cd3e096de7d | tests/test_mysql.py | tests/test_mysql.py | import unittest
from tests.common import load_check
import time
class TestMySql(unittest.TestCase):
def setUp(self):
# This should run on pre-2.7 python so no skiptest
self.skip = False
try:
import pymysql
except ImportError:
self.skip = True
def testChecks(self):
if not self.skip:
agentConfig = {
'version': '0.1',
'api_key': 'toto' }
conf = {'init_config': {}, 'instances': [{
'server': 'localhost',
'user': 'dog',
'pass': 'dog',
'options': {'replication': True},
}]}
# Initialize the check from checks.d
self.check = load_check('mysql', conf, agentConfig)
self.check.run()
metrics = self.check.get_metrics()
self.assertTrue(len(metrics) >= 8, metrics)
time.sleep(1)
self.check.run()
metrics = self.check.get_metrics()
self.assertTrue(len(metrics) >= 16, metrics)
if __name__ == '__main__':
unittest.main()
| import unittest
from tests.common import load_check
import time
class TestMySql(unittest.TestCase):
def setUp(self):
# This should run on pre-2.7 python so no skiptest
self.skip = False
try:
import pymysql
except ImportError:
self.skip = True
def testChecks(self):
if not self.skip:
agentConfig = {
'version': '0.1',
'api_key': 'toto' }
conf = {'init_config': {}, 'instances': [{
'server': 'localhost',
'user': 'dog',
'pass': 'dog',
'options': {'replication': True},
}]}
# Initialize the check from checks.d
self.check = load_check('mysql', conf, agentConfig)
self.check.run()
metrics = self.check.get_metrics()
self.assertTrue(len(metrics) >= 8, metrics)
# Service checks
service_checks = self.check.get_service_checks()
service_checks_count = len(service_checks)
self.assertTrue(type(service_checks) == type([]))
self.assertTrue(service_checks_count > 0)
self.assertEquals(len([sc for sc in service_checks if sc['check'] == "mysql.can_connect"]), 1, service_checks)
# Assert that all service checks have the proper tags: host and port
self.assertEquals(len([sc for sc in service_checks if "host:localhost" in sc['tags']]), service_checks_count, service_checks)
self.assertEquals(len([sc for sc in service_checks if "port:0" in sc['tags']]), service_checks_count, service_checks)
time.sleep(1)
self.check.run()
metrics = self.check.get_metrics()
self.assertTrue(len(metrics) >= 16, metrics)
if __name__ == '__main__':
unittest.main()
| Add test for Mysql sc | Add test for Mysql sc
| Python | bsd-3-clause | brettlangdon/dd-agent,truthbk/dd-agent,jraede/dd-agent,relateiq/dd-agent,cberry777/dd-agent,tebriel/dd-agent,urosgruber/dd-agent,jraede/dd-agent,ess/dd-agent,Shopify/dd-agent,joelvanvelden/dd-agent,jyogi/purvar-agent,eeroniemi/dd-agent,citrusleaf/dd-agent,indeedops/dd-agent,eeroniemi/dd-agent,Mashape/dd-agent,AniruddhaSAtre/dd-agent,c960657/dd-agent,lookout/dd-agent,pfmooney/dd-agent,truthbk/dd-agent,PagerDuty/dd-agent,c960657/dd-agent,jvassev/dd-agent,benmccann/dd-agent,pmav99/praktoras,relateiq/dd-agent,PagerDuty/dd-agent,gphat/dd-agent,citrusleaf/dd-agent,tebriel/dd-agent,AntoCard/powerdns-recursor_check,jvassev/dd-agent,darron/dd-agent,yuecong/dd-agent,yuecong/dd-agent,zendesk/dd-agent,mderomph-coolblue/dd-agent,benmccann/dd-agent,urosgruber/dd-agent,manolama/dd-agent,citrusleaf/dd-agent,cberry777/dd-agent,ess/dd-agent,cberry777/dd-agent,a20012251/dd-agent,tebriel/dd-agent,mderomph-coolblue/dd-agent,AntoCard/powerdns-recursor_check,jshum/dd-agent,JohnLZeller/dd-agent,AntoCard/powerdns-recursor_check,jshum/dd-agent,pfmooney/dd-agent,ess/dd-agent,PagerDuty/dd-agent,joelvanvelden/dd-agent,AntoCard/powerdns-recursor_check,packetloop/dd-agent,Shopify/dd-agent,pmav99/praktoras,PagerDuty/dd-agent,Shopify/dd-agent,takus/dd-agent,packetloop/dd-agent,relateiq/dd-agent,gphat/dd-agent,jraede/dd-agent,packetloop/dd-agent,gphat/dd-agent,yuecong/dd-agent,jamesandariese/dd-agent,guruxu/dd-agent,huhongbo/dd-agent,pmav99/praktoras,huhongbo/dd-agent,zendesk/dd-agent,brettlangdon/dd-agent,lookout/dd-agent,a20012251/dd-agent,Wattpad/dd-agent,urosgruber/dd-agent,indeedops/dd-agent,takus/dd-agent,GabrielNicolasAvellaneda/dd-agent,polynomial/dd-agent,AntoCard/powerdns-recursor_check,joelvanvelden/dd-agent,JohnLZeller/dd-agent,ess/dd-agent,mderomph-coolblue/dd-agent,Wattpad/dd-agent,yuecong/dd-agent,tebriel/dd-agent,Shopify/dd-agent,jraede/dd-agent,Mashape/dd-agent,oneandoneis2/dd-agent,eeroniemi/dd-agent,amalakar/dd-agent,benmccann/dd-agent,amalakar/dd-agent,takus/dd-agent,jshum/dd-agent,Wattpad/dd-agent,remh/dd-agent,GabrielNicolasAvellaneda/dd-agent,oneandoneis2/dd-agent,remh/dd-agent,indeedops/dd-agent,oneandoneis2/dd-agent,c960657/dd-agent,zendesk/dd-agent,amalakar/dd-agent,remh/dd-agent,truthbk/dd-agent,oneandoneis2/dd-agent,manolama/dd-agent,huhongbo/dd-agent,mderomph-coolblue/dd-agent,Mashape/dd-agent,Mashape/dd-agent,mderomph-coolblue/dd-agent,c960657/dd-agent,pfmooney/dd-agent,amalakar/dd-agent,indeedops/dd-agent,eeroniemi/dd-agent,guruxu/dd-agent,relateiq/dd-agent,JohnLZeller/dd-agent,polynomial/dd-agent,pfmooney/dd-agent,jamesandariese/dd-agent,manolama/dd-agent,truthbk/dd-agent,brettlangdon/dd-agent,jvassev/dd-agent,huhongbo/dd-agent,packetloop/dd-agent,AniruddhaSAtre/dd-agent,PagerDuty/dd-agent,urosgruber/dd-agent,lookout/dd-agent,pmav99/praktoras,jraede/dd-agent,jshum/dd-agent,Shopify/dd-agent,jvassev/dd-agent,polynomial/dd-agent,manolama/dd-agent,lookout/dd-agent,pfmooney/dd-agent,jyogi/purvar-agent,takus/dd-agent,huhongbo/dd-agent,GabrielNicolasAvellaneda/dd-agent,jamesandariese/dd-agent,guruxu/dd-agent,JohnLZeller/dd-agent,jamesandariese/dd-agent,cberry777/dd-agent,jyogi/purvar-agent,gphat/dd-agent,manolama/dd-agent,darron/dd-agent,AniruddhaSAtre/dd-agent,joelvanvelden/dd-agent,indeedops/dd-agent,Wattpad/dd-agent,a20012251/dd-agent,yuecong/dd-agent,amalakar/dd-agent,cberry777/dd-agent,lookout/dd-agent,citrusleaf/dd-agent,Mashape/dd-agent,GabrielNicolasAvellaneda/dd-agent,pmav99/praktoras,remh/dd-agent,brettlangdon/dd-agent,jamesandariese/dd-agent,tebriel/dd-agent,jshum/dd-agent,JohnLZeller/dd-agent,a20012251/dd-agent,benmccann/dd-agent,darron/dd-agent,urosgruber/dd-agent,guruxu/dd-agent,jyogi/purvar-agent,truthbk/dd-agent,joelvanvelden/dd-agent,Wattpad/dd-agent,AniruddhaSAtre/dd-agent,jyogi/purvar-agent,a20012251/dd-agent,eeroniemi/dd-agent,zendesk/dd-agent,guruxu/dd-agent,gphat/dd-agent,takus/dd-agent,packetloop/dd-agent,jvassev/dd-agent,darron/dd-agent,zendesk/dd-agent,GabrielNicolasAvellaneda/dd-agent,c960657/dd-agent,ess/dd-agent,relateiq/dd-agent,polynomial/dd-agent,darron/dd-agent,citrusleaf/dd-agent,benmccann/dd-agent,remh/dd-agent,AniruddhaSAtre/dd-agent,brettlangdon/dd-agent,oneandoneis2/dd-agent,polynomial/dd-agent | ---
+++
@@ -13,7 +13,7 @@
def testChecks(self):
if not self.skip:
- agentConfig = {
+ agentConfig = {
'version': '0.1',
'api_key': 'toto' }
@@ -29,10 +29,22 @@
self.check.run()
metrics = self.check.get_metrics()
self.assertTrue(len(metrics) >= 8, metrics)
+
+ # Service checks
+ service_checks = self.check.get_service_checks()
+ service_checks_count = len(service_checks)
+ self.assertTrue(type(service_checks) == type([]))
+ self.assertTrue(service_checks_count > 0)
+ self.assertEquals(len([sc for sc in service_checks if sc['check'] == "mysql.can_connect"]), 1, service_checks)
+ # Assert that all service checks have the proper tags: host and port
+ self.assertEquals(len([sc for sc in service_checks if "host:localhost" in sc['tags']]), service_checks_count, service_checks)
+ self.assertEquals(len([sc for sc in service_checks if "port:0" in sc['tags']]), service_checks_count, service_checks)
+
time.sleep(1)
self.check.run()
metrics = self.check.get_metrics()
self.assertTrue(len(metrics) >= 16, metrics)
-
+
+
if __name__ == '__main__':
unittest.main() |
42f49d19b3657c62208aacee0f2dd77081bb5aa2 | zerver/migrations/0189_userprofile_add_some_emojisets.py | zerver/migrations/0189_userprofile_add_some_emojisets.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-08-28 19:01
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0188_userprofile_enable_login_emails'),
]
operations = [
migrations.AlterField(
model_name='userprofile',
name='emojiset',
field=models.CharField(choices=[('google', 'Google modern'), ('google-blob', 'Google classic'), ('twitter', 'Twitter'), ('text', 'Plain text')], default='google-blob', max_length=20),
),
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-08-28 19:01
from __future__ import unicode_literals
from django.db import migrations, models
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def change_emojiset_choice(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
UserProfile = apps.get_model('zerver', 'UserProfile')
UserProfile.objects.filter(emojiset='google').update(emojiset='google-blob')
class Migration(migrations.Migration):
dependencies = [
('zerver', '0188_userprofile_enable_login_emails'),
]
operations = [
migrations.AlterField(
model_name='userprofile',
name='emojiset',
field=models.CharField(choices=[('google', 'Google modern'), ('google-blob', 'Google classic'), ('twitter', 'Twitter'), ('text', 'Plain text')], default='google-blob', max_length=20),
),
migrations.RunPython(
change_emojiset_choice,
reverse_code=migrations.RunPython.noop),
]
| Set default emoji to google-blob for existing users too. | emoji: Set default emoji to google-blob for existing users too.
This fixes an inconsistent test failure with test_users.py (that
depended on the ordering between this migration and the creation of
test database users like hamlet).
| Python | apache-2.0 | brainwane/zulip,brainwane/zulip,shubhamdhama/zulip,zulip/zulip,shubhamdhama/zulip,rht/zulip,showell/zulip,eeshangarg/zulip,punchagan/zulip,hackerkid/zulip,synicalsyntax/zulip,tommyip/zulip,showell/zulip,rishig/zulip,shubhamdhama/zulip,jackrzhang/zulip,synicalsyntax/zulip,dhcrzf/zulip,kou/zulip,andersk/zulip,dhcrzf/zulip,jackrzhang/zulip,rht/zulip,rishig/zulip,jackrzhang/zulip,tommyip/zulip,zulip/zulip,zulip/zulip,rishig/zulip,hackerkid/zulip,hackerkid/zulip,rht/zulip,timabbott/zulip,punchagan/zulip,timabbott/zulip,eeshangarg/zulip,jackrzhang/zulip,showell/zulip,tommyip/zulip,synicalsyntax/zulip,punchagan/zulip,rishig/zulip,dhcrzf/zulip,kou/zulip,showell/zulip,brainwane/zulip,andersk/zulip,hackerkid/zulip,tommyip/zulip,eeshangarg/zulip,eeshangarg/zulip,jackrzhang/zulip,punchagan/zulip,brainwane/zulip,rht/zulip,timabbott/zulip,zulip/zulip,andersk/zulip,timabbott/zulip,showell/zulip,punchagan/zulip,showell/zulip,shubhamdhama/zulip,zulip/zulip,shubhamdhama/zulip,punchagan/zulip,andersk/zulip,rht/zulip,jackrzhang/zulip,rishig/zulip,tommyip/zulip,andersk/zulip,showell/zulip,hackerkid/zulip,dhcrzf/zulip,timabbott/zulip,dhcrzf/zulip,brainwane/zulip,hackerkid/zulip,eeshangarg/zulip,hackerkid/zulip,eeshangarg/zulip,brainwane/zulip,kou/zulip,kou/zulip,shubhamdhama/zulip,kou/zulip,rht/zulip,kou/zulip,synicalsyntax/zulip,rishig/zulip,zulip/zulip,andersk/zulip,rishig/zulip,dhcrzf/zulip,rht/zulip,timabbott/zulip,dhcrzf/zulip,andersk/zulip,jackrzhang/zulip,synicalsyntax/zulip,shubhamdhama/zulip,tommyip/zulip,brainwane/zulip,synicalsyntax/zulip,zulip/zulip,eeshangarg/zulip,punchagan/zulip,tommyip/zulip,timabbott/zulip,synicalsyntax/zulip,kou/zulip | ---
+++
@@ -3,7 +3,12 @@
from __future__ import unicode_literals
from django.db import migrations, models
+from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
+from django.db.migrations.state import StateApps
+def change_emojiset_choice(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
+ UserProfile = apps.get_model('zerver', 'UserProfile')
+ UserProfile.objects.filter(emojiset='google').update(emojiset='google-blob')
class Migration(migrations.Migration):
@@ -17,4 +22,7 @@
name='emojiset',
field=models.CharField(choices=[('google', 'Google modern'), ('google-blob', 'Google classic'), ('twitter', 'Twitter'), ('text', 'Plain text')], default='google-blob', max_length=20),
),
+ migrations.RunPython(
+ change_emojiset_choice,
+ reverse_code=migrations.RunPython.noop),
] |
c46398091fbe591bbe79744ed4371fddcc454912 | IPython/html/terminal/handlers.py | IPython/html/terminal/handlers.py | """Tornado handlers for the terminal emulator."""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from tornado import web
import terminado
from ..base.handlers import IPythonHandler
class TerminalHandler(IPythonHandler):
"""Render the terminal interface."""
@web.authenticated
def get(self, term_name):
self.write(self.render_template('terminal.html',
ws_path="terminals/websocket/%s" % term_name))
class NewTerminalHandler(IPythonHandler):
"""Redirect to a new terminal."""
@web.authenticated
def get(self):
name, _ = self.application.terminal_manager.new_named_terminal()
self.redirect("/terminals/%s" % name, permanent=False)
class TermSocket(terminado.TermSocket, IPythonHandler):
def get(self, *args, **kwargs):
if not self.get_current_user():
raise web.HTTPError(403)
return super(TermSocket, self).get(*args, **kwargs)
| """Tornado handlers for the terminal emulator."""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from tornado import web
import terminado
from ..base.handlers import IPythonHandler
class TerminalHandler(IPythonHandler):
"""Render the terminal interface."""
@web.authenticated
def get(self, term_name):
self.write(self.render_template('terminal.html',
ws_path="terminals/websocket/%s" % term_name))
class NewTerminalHandler(IPythonHandler):
"""Redirect to a new terminal."""
@web.authenticated
def get(self):
name, _ = self.application.terminal_manager.new_named_terminal()
self.redirect(name, permanent=False)
class TermSocket(terminado.TermSocket, IPythonHandler):
def get(self, *args, **kwargs):
if not self.get_current_user():
raise web.HTTPError(403)
return super(TermSocket, self).get(*args, **kwargs)
| Use relative URL for redirect in NewTerminalHandler | Use relative URL for redirect in NewTerminalHandler
| Python | bsd-3-clause | ipython/ipython,ipython/ipython | ---
+++
@@ -19,7 +19,7 @@
@web.authenticated
def get(self):
name, _ = self.application.terminal_manager.new_named_terminal()
- self.redirect("/terminals/%s" % name, permanent=False)
+ self.redirect(name, permanent=False)
class TermSocket(terminado.TermSocket, IPythonHandler):
def get(self, *args, **kwargs): |
d04d56bdb79d6e6ac04af1642cb8c3ceff325d75 | dddp/test/__init__.py | dddp/test/__init__.py | # This file mainly exists to allow `python setup.py test` to work.
import os
import sys
import dddp
import django
from django.test.utils import get_runner
from django.conf import settings
def run_tests():
os.environ['DJANGO_SETTINGS_MODULE'] = 'dddp.test.test_project.settings'
dddp.greenify()
django.setup()
test_runner = get_runner(settings)()
failures = test_runner.run_tests(['dddp', 'dddp.test.django_todos'])
sys.exit(bool(failures))
| # This file mainly exists to allow `python setup.py test` to work.
import os
import sys
import dddp
def run_tests():
os.environ['DJANGO_SETTINGS_MODULE'] = 'dddp.test.test_project.settings'
dddp.greenify()
import django
from django.test.utils import get_runner
from django.conf import settings
django.setup()
test_runner = get_runner(settings)()
failures = test_runner.run_tests(['dddp', 'dddp.test.django_todos'])
sys.exit(bool(failures))
| Apply gevent monkey patching before importing django (which imports threading). | Apply gevent monkey patching before importing django (which imports threading).
| Python | mit | django-ddp/django-ddp,django-ddp/django-ddp,commoncode/django-ddp,commoncode/django-ddp,django-ddp/django-ddp,commoncode/django-ddp,django-ddp/django-ddp,commoncode/django-ddp | ---
+++
@@ -3,14 +3,14 @@
import sys
import dddp
-import django
-from django.test.utils import get_runner
-from django.conf import settings
def run_tests():
os.environ['DJANGO_SETTINGS_MODULE'] = 'dddp.test.test_project.settings'
dddp.greenify()
+ import django
+ from django.test.utils import get_runner
+ from django.conf import settings
django.setup()
test_runner = get_runner(settings)()
failures = test_runner.run_tests(['dddp', 'dddp.test.django_todos']) |
b2bc500c6a715493c4187e5b1c62e02717d8e31c | glue/plugins/dendro_viewer/__init__.py | glue/plugins/dendro_viewer/__init__.py | def setup():
from .qt_widget import DendroWidget
from glue.config import qt_client
qt_client.add(DendroWidget)
| def setup():
from glue.config import qt_client
from .qt_widget import DendroWidget
from .data_factory import load_dendro
qt_client.add(DendroWidget)
| Add missing import of dendrogram data factory | Add missing import of dendrogram data factory
| Python | bsd-3-clause | stscieisenhamer/glue,saimn/glue,saimn/glue,stscieisenhamer/glue | ---
+++
@@ -1,4 +1,5 @@
def setup():
+ from glue.config import qt_client
from .qt_widget import DendroWidget
- from glue.config import qt_client
+ from .data_factory import load_dendro
qt_client.add(DendroWidget) |
539c7a85a84fdb2fbe8ee3f5803778baf0c66841 | wmt/flask/__init__.py | wmt/flask/__init__.py | import os
from flask import Flask
from flask_login import LoginManager
from passlib.context import CryptContext
from .core import db
from .blueprints import register_blueprints
from .errors import ERROR_HANDLERS
class User(object):
def __init__(self, id):
self._id = id
def is_authenticated(self):
return True
def is_active(self):
return True
def is_anonymous(self):
return False
def get_id(self):
return self._id
def create_app(settings_override=None, register_security_blueprint=True):
app = Flask(__name__, instance_relative_config=True)
login_manager = LoginManager()
login_manager.init_app(app)
@login_manager.user_loader
def load_user(userid):
return User(userid)
@app.before_first_request
def create_database():
db.create_all()
app.config.from_object('wmt.flask.settings')
app.config.from_pyfile('settings.cfg', silent=True)
app.config.from_object(settings_override)
app.config['pw'] = CryptContext.from_string(
app.config['CRYPT_INI_CONTENTS'], section='passlib')
db.init_app(app)
register_blueprints(app, __name__, __path__)
for error, func in ERROR_HANDLERS:
app.errorhandler(error)(func)
return app
| import os
from flask import Flask
from flask_login import LoginManager
from passlib.context import CryptContext
from .settings import WmtSettings
from .core import db
from .blueprints import register_blueprints
from .errors import ERROR_HANDLERS
class User(object):
def __init__(self, id):
self._id = id
def is_authenticated(self):
return True
def is_active(self):
return True
def is_anonymous(self):
return False
def get_id(self):
return self._id
def create_app(settings_override=None, register_security_blueprint=True,
wmt_root_path=None):
app = Flask(__name__, instance_relative_config=True)
login_manager = LoginManager()
login_manager.init_app(app)
@login_manager.user_loader
def load_user(userid):
return User(userid)
@app.before_first_request
def create_database():
db.create_all()
app.config.from_object(WmtSettings(
os.path.join(wmt_root_path or app.root_path, 'db')))
#app.config.from_object(WmtSettings('/Users/huttone/git/wmt/db'))
app.config.from_pyfile('settings.cfg', silent=True)
app.config.from_object(settings_override)
app.config['pw'] = CryptContext.from_string(
app.config['CRYPT_INI_CONTENTS'], section='passlib')
db.init_app(app)
register_blueprints(app, __name__, __path__)
for error, func in ERROR_HANDLERS:
app.errorhandler(error)(func)
return app
| Use settings classes and set wmt_root_path. | Use settings classes and set wmt_root_path.
| Python | mit | mcflugen/wmt-rest,mcflugen/wmt-rest | ---
+++
@@ -5,6 +5,7 @@
from passlib.context import CryptContext
+from .settings import WmtSettings
from .core import db
from .blueprints import register_blueprints
from .errors import ERROR_HANDLERS
@@ -27,7 +28,8 @@
return self._id
-def create_app(settings_override=None, register_security_blueprint=True):
+def create_app(settings_override=None, register_security_blueprint=True,
+ wmt_root_path=None):
app = Flask(__name__, instance_relative_config=True)
login_manager = LoginManager()
@@ -41,7 +43,9 @@
def create_database():
db.create_all()
- app.config.from_object('wmt.flask.settings')
+ app.config.from_object(WmtSettings(
+ os.path.join(wmt_root_path or app.root_path, 'db')))
+ #app.config.from_object(WmtSettings('/Users/huttone/git/wmt/db'))
app.config.from_pyfile('settings.cfg', silent=True)
app.config.from_object(settings_override)
|
a479b445c18687827e7913e8b51abd5937848fe8 | anybox/buildbot/openerp/build_utils/analyze_oerp_tests.py | anybox/buildbot/openerp/build_utils/analyze_oerp_tests.py | """Analyse the tests log file given as argument.
Print a report and return status code 1 if failures are detected
"""
import sys
import re
FAILURE_REGEXPS = {
'Failure in Python block': re.compile(r'WARNING:tests[.].*AssertionError'),
'Errors during x/yml tests': re.compile(r'ERROR:tests[.]'),
'Errors or failures during unittest2 tests': re.compile(
r'at least one error occurred in a test'),
'Errors loading addons': re.compile(r'ERROR.*openerp: Failed to load'),
'Critical logs': re.compile(r'CRITICAL'),
'Error init db': re.compile(r'Failed to initialize database'),
'Tests failed to excute': re.compile(
r'openerp.modules.loading: Tests failed to execute'),
}
test_log = open(sys.argv[1], 'r')
failures = {} # label -> extracted line
for line in test_log.readlines():
for label, regexp in FAILURE_REGEXPS.items():
if regexp.search(line):
failures.setdefault(label, []).append(line)
if not failures:
print "No failure detected"
sys.exit(0)
total = 0
print 'FAILURES DETECTED'
print
for label, failed_lines in failures.items():
print label + ':'
for line in failed_lines:
print ' ' + line
print
total += len(failed_lines)
print "Total: %d failures " % total
sys.exit(1)
| """Analyse the tests log file given as argument.
Print a report and return status code 1 if failures are detected
"""
import sys
import re
FAILURE_REGEXPS = {
'Failure in Python block': re.compile(r'WARNING:tests[.].*AssertionError'),
'Errors during x/yml tests': re.compile(r'ERROR:tests[.]'),
'Errors or failures during unittest2 tests': re.compile(
r'at least one error occurred in a test'),
'Errors loading addons': re.compile(r'ERROR.*openerp: Failed to load'),
'Critical logs': re.compile(r'CRITICAL'),
'Error init db': re.compile(r'Failed to initialize database'),
'Tests failed to excute': re.compile(
r'openerp.modules.loading: Tests failed to execute'),
'WARNING no field in model': re.compile('No such field(s) in model'),
}
test_log = open(sys.argv[1], 'r')
failures = {} # label -> extracted line
for line in test_log.readlines():
for label, regexp in FAILURE_REGEXPS.items():
if regexp.search(line):
failures.setdefault(label, []).append(line)
if not failures:
print "No failure detected"
sys.exit(0)
total = 0
print 'FAILURES DETECTED'
print
for label, failed_lines in failures.items():
print label + ':'
for line in failed_lines:
print ' ' + line
print
total += len(failed_lines)
print "Total: %d failures " % total
sys.exit(1)
| Add regex to know if one field is use in a model where this field is not declared | Add regex to know if one field is use in a model where this field is not declared | Python | agpl-3.0 | anybox/anybox.buildbot.odoo | ---
+++
@@ -16,6 +16,7 @@
'Error init db': re.compile(r'Failed to initialize database'),
'Tests failed to excute': re.compile(
r'openerp.modules.loading: Tests failed to execute'),
+ 'WARNING no field in model': re.compile('No such field(s) in model'),
}
test_log = open(sys.argv[1], 'r') |
24f0c0d311886571cc0c5f8badca026a6c534a52 | dask/array/__init__.py | dask/array/__init__.py | from __future__ import absolute_import, division, print_function
from ..utils import ignoring
from .core import (Array, stack, concatenate, tensordot, transpose, from_array,
choose, where, coarsen, broadcast_to, constant, fromfunction, compute,
unique, store)
from .core import (arccos, arcsin, arctan, arctanh, arccosh, arcsinh, arctan2,
ceil, copysign, cos, cosh, degrees, exp, expm1, fabs, floor, fmod,
frexp, hypot, isinf, isnan, ldexp, log, log10, log1p, modf, radians,
sin, sinh, sqrt, tan, tanh, trunc, around, isnull, notnull, isclose)
from .reductions import (sum, prod, mean, std, var, any, all, min, max, vnorm,
argmin, argmax,
nansum, nanmean, nanstd, nanvar, nanmin,
nanmax, nanargmin, nanargmax)
from .percentile import percentile
with ignoring(ImportError):
from .reductions import nanprod
from . import random, linalg, ghost, creation
from .wrap import ones, zeros, empty
from .reblock import reblock
from ..context import set_options
from .optimization import optimize
| from __future__ import absolute_import, division, print_function
from ..utils import ignoring
from .core import (Array, stack, concatenate, tensordot, transpose, from_array,
choose, where, coarsen, broadcast_to, constant, fromfunction, compute,
unique, store)
from .core import (arccos, arcsin, arctan, arctanh, arccosh, arcsinh, arctan2,
ceil, copysign, cos, cosh, degrees, exp, expm1, fabs, floor, fmod,
frexp, hypot, isinf, isnan, ldexp, log, log10, log1p, modf, radians,
sin, sinh, sqrt, tan, tanh, trunc, around, isnull, notnull, isclose)
from .reductions import (sum, prod, mean, std, var, any, all, min, max, vnorm,
argmin, argmax,
nansum, nanmean, nanstd, nanvar, nanmin,
nanmax, nanargmin, nanargmax)
from .percentile import percentile
with ignoring(ImportError):
from .reductions import nanprod
from . import random, linalg, ghost
from .wrap import ones, zeros, empty
from .reblock import reblock
from ..context import set_options
from .optimization import optimize
from .creation import arange, linspace
| Move dask.array.creation.* into dask.array.* namespace | Move dask.array.creation.* into dask.array.* namespace
| Python | bsd-3-clause | mraspaud/dask,marianotepper/dask,minrk/dask,freeman-lab/dask,pombredanne/dask,ContinuumIO/dask,hainm/dask,ssanderson/dask,clarkfitzg/dask,jakirkham/dask,jakirkham/dask,PhE/dask,cowlicks/dask,ContinuumIO/dask,mikegraham/dask,cpcloud/dask,pombredanne/dask,hainm/dask,marianotepper/dask,simudream/dask,jcrist/dask,wiso/dask,blaze/dask,vikhyat/dask,blaze/dask,esc/dask,PhE/dask,minrk/dask,vikhyat/dask,wiso/dask,dask/dask,dask/dask,jayhetee/dask,freeman-lab/dask,mrocklin/dask,jcrist/dask,esc/dask,clarkfitzg/dask,ssanderson/dask,mrocklin/dask,simudream/dask,mraspaud/dask,chrisbarber/dask,jayhetee/dask,gameduell/dask | ---
+++
@@ -15,8 +15,9 @@
from .percentile import percentile
with ignoring(ImportError):
from .reductions import nanprod
-from . import random, linalg, ghost, creation
+from . import random, linalg, ghost
from .wrap import ones, zeros, empty
from .reblock import reblock
from ..context import set_options
from .optimization import optimize
+from .creation import arange, linspace |
36550f71f4161b0b5c7af872b78dd1e7d96b788a | scripts/patches/dynamodb.py | scripts/patches/dynamodb.py | patches = [
# duplicate GlobalSecondaryIndex
{
"op": "move",
"from": "/PropertyTypes/AWS::DynamoDB::GlobalTable.GlobalSecondaryIndex",
"path": "/PropertyTypes/AWS::DynamoDB::GlobalTable.GlobalTableGlobalSecondaryIndex",
},
{
"op": "replace",
"path": "/ResourceTypes/AWS::DynamoDB::GlobalTable/Properties/GlobalSecondaryIndexes/ItemType",
"value": "GlobalTableGlobalSecondaryIndex",
},
# duplicate SSESpecification
{
"op": "move",
"from": "/PropertyTypes/AWS::DynamoDB::GlobalTable.SSESpecification",
"path": "/PropertyTypes/AWS::DynamoDB::GlobalTable.GlobalTableSSESpecification",
},
{
"op": "replace",
"path": "/ResourceTypes/AWS::DynamoDB::GlobalTable/Properties/SSESpecification/Type",
"value": "GlobalTableSSESpecification",
},
]
| patches = [
# duplicate GlobalSecondaryIndex
{
"op": "move",
"from": "/PropertyTypes/AWS::DynamoDB::GlobalTable.GlobalSecondaryIndex",
"path": "/PropertyTypes/AWS::DynamoDB::GlobalTable.GlobalTableGlobalSecondaryIndex",
},
{
"op": "replace",
"path": "/ResourceTypes/AWS::DynamoDB::GlobalTable/Properties/GlobalSecondaryIndexes/ItemType",
"value": "GlobalTableGlobalSecondaryIndex",
},
# duplicate SSESpecification
{
"op": "move",
"from": "/PropertyTypes/AWS::DynamoDB::GlobalTable.SSESpecification",
"path": "/PropertyTypes/AWS::DynamoDB::GlobalTable.GlobalTableSSESpecification",
},
{
"op": "replace",
"path": "/ResourceTypes/AWS::DynamoDB::GlobalTable/Properties/SSESpecification/Type",
"value": "GlobalTableSSESpecification",
},
# Fix issue in spec 82.0.0 that changed Type to Json
{
"op": "replace",
"path": "/ResourceTypes/AWS::DynamoDB::Table/Properties/KeySchema/Type",
"value": "List",
},
{
"op": "add",
"path": "/ResourceTypes/AWS::DynamoDB::Table/Properties/KeySchema/ItemType",
"value": "KeySchema",
},
]
| Fix issue in spec 82.0.0 with DynamoDB KeySchema Type | Fix issue in spec 82.0.0 with DynamoDB KeySchema Type
| Python | bsd-2-clause | cloudtools/troposphere,cloudtools/troposphere | ---
+++
@@ -21,4 +21,15 @@
"path": "/ResourceTypes/AWS::DynamoDB::GlobalTable/Properties/SSESpecification/Type",
"value": "GlobalTableSSESpecification",
},
+ # Fix issue in spec 82.0.0 that changed Type to Json
+ {
+ "op": "replace",
+ "path": "/ResourceTypes/AWS::DynamoDB::Table/Properties/KeySchema/Type",
+ "value": "List",
+ },
+ {
+ "op": "add",
+ "path": "/ResourceTypes/AWS::DynamoDB::Table/Properties/KeySchema/ItemType",
+ "value": "KeySchema",
+ },
] |
8785f602900ab3bf3e297ee8f90ecf47c059cdde | sphinxcontrib/openstreetmap.py | sphinxcontrib/openstreetmap.py | # -*- coding: utf-8 -*-
"""
sphinxcontrib.openstreetmap
===========================
Embed OpenStreetMap on your documentation.
:copyright: Copyright 2015 HAYASHI Kentaro <kenhys@gmail.com>
:license: BSD, see LICENSE for details.
"""
from docutils import nodes
from docutils.parsers.rst import directives
from sphinx.util.compat import Directive
class openstreetmap(nodes.General, nodes.Element):
pass
class OpenStreetMapDirective(Directive):
"""Directive for embedding OpenStreetMap"""
has_content = False
option_spec = {
'id': directives.unchanged,
'label': directives.unchanged
}
def run(self):
node = openstreetmap()
return [node]
def visit_openstreetmap_node(self, node):
self.body.append("<div id='openstreetmap' style='color:red'>OpenStreetMap directive</div>")
def depart_openstreetmap_node(self, node):
pass
def setup(app):
app.add_node(openstreetmap,
html=(visit_openstreetmap_node, depart_openstreetmap_node))
app.add_directive('openstreetmap', OpenStreetMapDirective)
| # -*- coding: utf-8 -*-
"""
sphinxcontrib.openstreetmap
===========================
Embed OpenStreetMap on your documentation.
:copyright: Copyright 2015 HAYASHI Kentaro <kenhys@gmail.com>
:license: BSD, see LICENSE for details.
"""
from docutils import nodes
from docutils.parsers.rst import directives
from sphinx.util.compat import Directive
class openstreetmap(nodes.General, nodes.Element):
pass
class OpenStreetMapDirective(Directive):
"""Directive for embedding OpenStreetMap"""
has_content = False
option_spec = {
'id': directives.unchanged,
'label': directives.unchanged,
'marker': directives.unchanged,
}
def run(self):
node = openstreetmap()
return [node]
def visit_openstreetmap_node(self, node):
self.body.append("<div id='openstreetmap' style='color:red'>OpenStreetMap directive</div>")
def depart_openstreetmap_node(self, node):
pass
def setup(app):
app.add_node(openstreetmap,
html=(visit_openstreetmap_node, depart_openstreetmap_node))
app.add_directive('openstreetmap', OpenStreetMapDirective)
| Add marker as required parameter | Add marker as required parameter
| Python | bsd-2-clause | kenhys/sphinxcontrib-openstreetmap,kenhys/sphinxcontrib-openstreetmap | ---
+++
@@ -20,7 +20,8 @@
has_content = False
option_spec = {
'id': directives.unchanged,
- 'label': directives.unchanged
+ 'label': directives.unchanged,
+ 'marker': directives.unchanged,
}
def run(self): |
2ba3dd9bafddd4dfd1ab712c59c6efadd58b1f46 | skimage/feature/__init__.py | skimage/feature/__init__.py | from ._daisy import daisy
from ._hog import hog
from .texture import greycomatrix, greycoprops, local_binary_pattern
from .peak import peak_local_max
from .corner import (corner_kitchen_rosenfeld, corner_harris, corner_shi_tomasi,
corner_foerstner, corner_subpix, corner_peaks)
from .corner_cy import corner_moravec
from .template import match_template
| from ._daisy import daisy
from ._hog import hog
from .texture import greycomatrix, greycoprops, local_binary_pattern
from .peak import peak_local_max
from .corner import (corner_kitchen_rosenfeld, corner_harris, corner_shi_tomasi,
corner_foerstner, corner_subpix, corner_peaks)
from .corner_cy import corner_moravec
from .template import match_template
__all__ = ['daisy',
'hog',
'greycomatrix',
'greycoprops',
'local_binary_pattern',
'peak_local_max',
'corner_kitchen_rosenfeld',
'corner_harris',
'corner_shi_tomasi',
'corner_foerstner',
'corner_subpix',
'corner_peaks',
'corner_moravec',
'match_template']
| Add __all__ to feature package | Add __all__ to feature package
| Python | bsd-3-clause | WarrenWeckesser/scikits-image,michaelpacer/scikit-image,chintak/scikit-image,Midafi/scikit-image,bsipocz/scikit-image,almarklein/scikit-image,paalge/scikit-image,vighneshbirodkar/scikit-image,GaZ3ll3/scikit-image,ofgulban/scikit-image,GaZ3ll3/scikit-image,jwiggins/scikit-image,ClinicalGraphics/scikit-image,SamHames/scikit-image,youprofit/scikit-image,paalge/scikit-image,bsipocz/scikit-image,emon10005/scikit-image,almarklein/scikit-image,blink1073/scikit-image,chintak/scikit-image,warmspringwinds/scikit-image,chriscrosscutler/scikit-image,michaelaye/scikit-image,bennlich/scikit-image,keflavich/scikit-image,SamHames/scikit-image,chintak/scikit-image,michaelpacer/scikit-image,ajaybhat/scikit-image,blink1073/scikit-image,ofgulban/scikit-image,newville/scikit-image,newville/scikit-image,Hiyorimi/scikit-image,ClinicalGraphics/scikit-image,rjeli/scikit-image,dpshelio/scikit-image,oew1v07/scikit-image,michaelaye/scikit-image,jwiggins/scikit-image,chriscrosscutler/scikit-image,vighneshbirodkar/scikit-image,oew1v07/scikit-image,juliusbierk/scikit-image,bennlich/scikit-image,pratapvardhan/scikit-image,dpshelio/scikit-image,SamHames/scikit-image,rjeli/scikit-image,paalge/scikit-image,robintw/scikit-image,warmspringwinds/scikit-image,Britefury/scikit-image,WarrenWeckesser/scikits-image,juliusbierk/scikit-image,youprofit/scikit-image,Britefury/scikit-image,almarklein/scikit-image,Hiyorimi/scikit-image,keflavich/scikit-image,almarklein/scikit-image,SamHames/scikit-image,pratapvardhan/scikit-image,robintw/scikit-image,ofgulban/scikit-image,vighneshbirodkar/scikit-image,Midafi/scikit-image,rjeli/scikit-image,chintak/scikit-image,ajaybhat/scikit-image,emon10005/scikit-image | ---
+++
@@ -6,3 +6,19 @@
corner_foerstner, corner_subpix, corner_peaks)
from .corner_cy import corner_moravec
from .template import match_template
+
+
+__all__ = ['daisy',
+ 'hog',
+ 'greycomatrix',
+ 'greycoprops',
+ 'local_binary_pattern',
+ 'peak_local_max',
+ 'corner_kitchen_rosenfeld',
+ 'corner_harris',
+ 'corner_shi_tomasi',
+ 'corner_foerstner',
+ 'corner_subpix',
+ 'corner_peaks',
+ 'corner_moravec',
+ 'match_template'] |
5c89aa079d94fe70bb5627eb67404bc65b80212a | sympy/solvers/decompogen.py | sympy/solvers/decompogen.py | from sympy.core import Function, Pow, sympify
from sympy.polys import Poly
def decompogen(f, symbol):
"""
Computes General functional decomposition of ``f``.
Given an expression ``f``, returns a list ``[f_1, f_2, ..., f_n]``,
where::
f = f_1 o f_2 o ... f_n = f_1(f_2(... f_n))
Note: This is a General decomposition function. For Polynomial
decomposition see ``decompose`` in polys.
Examples
========
>>> from sympy.solvers.decompogen import decompogen
>>> from sympy.abc import x
>>> from sympy import sqrt, sin, cos
>>> decompogen(sin(cos(x)), x)
[sin(x), cos(x)]
>>> decompogen(sin(x)**2 + sin(x) + 1, x)
[x**2 + x + 1, sin(x)]
>>> decompogen(sqrt(6*x**2 - 5), x)
[sqrt(x), 6*x**2 - 5]
"""
f = sympify(f)
# ===== Simple Functions ===== #
if isinstance(f, (Function, Pow)):
return [f.subs(f.args[0], symbol), f.args[0]]
# ===== Convert to Polynomial ===== #
fp = Poly(f)
gens = fp.gens
if len(gens) == 1:
f1 = f.subs(gens[0], symbol)
f2 = gens[0]
return [f1, f2]
| from sympy.core import Function, Pow, sympify
from sympy.polys import Poly
def decompogen(f, symbol):
"""
Computes General functional decomposition of ``f``.
Given an expression ``f``, returns a list ``[f_1, f_2, ..., f_n]``,
where::
f = f_1 o f_2 o ... f_n = f_1(f_2(... f_n))
Note: This is a General decomposition function. For Polynomial
decomposition see ``decompose`` in polys.
Examples
========
>>> from sympy.solvers.decompogen import decompogen
>>> from sympy.abc import x
>>> from sympy import sqrt, sin, cos
>>> decompogen(sin(cos(x)), x)
[sin(x), cos(x)]
>>> decompogen(sin(x)**2 + sin(x) + 1, x)
[x**2 + x + 1, sin(x)]
>>> decompogen(sqrt(6*x**2 - 5), x)
[sqrt(x), 6*x**2 - 5]
"""
f = sympify(f)
# ===== Simple Functions ===== #
if isinstance(f, (Function, Pow)):
return [f.subs(f.args[0], symbol), f.args[0]]
# ===== Convert to Polynomial ===== #
fp = Poly(f)
gens = fp.gens
if len(gens) == 1:
f1 = f.subs(gens[0], symbol)
f2 = gens[0]
return [f1, f2]
return [f]
| Return `f` if no decomposition | Return `f` if no decomposition
Signed-off-by: AMiT Kumar <a9f82ad3e8c446d8f49d5b7e05ec2c64a9e15ea9@gmail.com>
| Python | bsd-3-clause | drufat/sympy,ChristinaZografou/sympy,chaffra/sympy,Vishluck/sympy,skidzo/sympy,ga7g08/sympy,wanglongqi/sympy,mafiya69/sympy,ga7g08/sympy,Davidjohnwilson/sympy,yashsharan/sympy,mcdaniel67/sympy,hargup/sympy,postvakje/sympy,Davidjohnwilson/sympy,VaibhavAgarwalVA/sympy,kaushik94/sympy,ChristinaZografou/sympy,MechCoder/sympy,MechCoder/sympy,Shaswat27/sympy,emon10005/sympy,kaichogami/sympy,jaimahajan1997/sympy,Shaswat27/sympy,kaushik94/sympy,Arafatk/sympy,Titan-C/sympy,kevalds51/sympy,jaimahajan1997/sympy,oliverlee/sympy,mafiya69/sympy,maniteja123/sympy,postvakje/sympy,drufat/sympy,AkademieOlympia/sympy,wanglongqi/sympy,madan96/sympy,abhiii5459/sympy,jerli/sympy,iamutkarshtiwari/sympy,Davidjohnwilson/sympy,lindsayad/sympy,madan96/sympy,ChristinaZografou/sympy,jerli/sympy,souravsingh/sympy,postvakje/sympy,rahuldan/sympy,saurabhjn76/sympy,ahhda/sympy,aktech/sympy,Titan-C/sympy,kaushik94/sympy,chaffra/sympy,madan96/sympy,lindsayad/sympy,wanglongqi/sympy,kevalds51/sympy,iamutkarshtiwari/sympy,jbbskinny/sympy,oliverlee/sympy,aktech/sympy,souravsingh/sympy,maniteja123/sympy,ahhda/sympy,iamutkarshtiwari/sympy,Curious72/sympy,emon10005/sympy,Titan-C/sympy,skidzo/sympy,Vishluck/sympy,ahhda/sympy,saurabhjn76/sympy,aktech/sympy,sampadsaha5/sympy,ga7g08/sympy,MechCoder/sympy,sampadsaha5/sympy,mcdaniel67/sympy,emon10005/sympy,jbbskinny/sympy,farhaanbukhsh/sympy,Curious72/sympy,VaibhavAgarwalVA/sympy,kevalds51/sympy,sahmed95/sympy,saurabhjn76/sympy,sahmed95/sympy,Arafatk/sympy,rahuldan/sympy,mcdaniel67/sympy,rahuldan/sympy,Shaswat27/sympy,yashsharan/sympy,abhiii5459/sympy,mafiya69/sympy,Vishluck/sympy,Arafatk/sympy,AkademieOlympia/sympy,skidzo/sympy,Curious72/sympy,souravsingh/sympy,AkademieOlympia/sympy,VaibhavAgarwalVA/sympy,sahmed95/sympy,jbbskinny/sympy,hargup/sympy,hargup/sympy,abhiii5459/sympy,farhaanbukhsh/sympy,kaichogami/sympy,chaffra/sympy,kaichogami/sympy,sampadsaha5/sympy,farhaanbukhsh/sympy,yashsharan/sympy,jerli/sympy,maniteja123/sympy,jaimahajan1997/sympy,oliverlee/sympy,lindsayad/sympy,drufat/sympy | ---
+++
@@ -40,3 +40,5 @@
f1 = f.subs(gens[0], symbol)
f2 = gens[0]
return [f1, f2]
+
+ return [f] |
6d3b191bd35f64b097ffac2a514d2400f2e07983 | tests/__main__.py | tests/__main__.py | #!/usr/bin/env python3
import os
import sys
import unittest
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
load = unittest.defaultTestLoader.loadTestsFromModule
suites = []
dirname = os.path.dirname(__file__)
sys.path.append(dirname)
filenames = os.listdir(dirname)
for filename in filenames:
if filename.startswith('test_') and filename.endswith('.py'):
name = filename[:-3]
plugin = __import__(name)
suites.append(load(plugin))
if __name__ == '__main__':
suite = unittest.TestSuite(suites)
runner = unittest.TextTestRunner(verbosity=2)
result = runner.run(suite)
| #!/usr/bin/env python3
import os
import sys
import unittest
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
load = unittest.defaultTestLoader.loadTestsFromModule
suites = []
dirname = os.path.dirname(__file__)
sys.path.append(dirname)
filenames = os.listdir(dirname)
for filename in filenames:
if filename.startswith('test_') and filename.endswith('.py'):
name = filename[:-3]
plugin = __import__(name)
suites.append(load(plugin))
if __name__ == '__main__':
suite = unittest.TestSuite(suites)
runner = unittest.TextTestRunner(verbosity=2)
result = runner.run(suite)
if result.wasSuccessful():
sys.exit(0)
else:
sys.exit(1)
| Fix return value of tests. | Fix return value of tests.
| Python | bsd-3-clause | ProgVal/Inceptoe,ProgVal/Inceptoe | ---
+++
@@ -22,3 +22,7 @@
suite = unittest.TestSuite(suites)
runner = unittest.TextTestRunner(verbosity=2)
result = runner.run(suite)
+ if result.wasSuccessful():
+ sys.exit(0)
+ else:
+ sys.exit(1) |
969c5129ec7c742985b7a3d09eb5ddd4b44b1743 | dothub/__main__.py | dothub/__main__.py | import logging
from . import config, cli
def main():
logging.basicConfig(levle=logging.INFO, format="%(message)s")
conf = config.load_config()
cli.dothub(obj={}, default_map=conf)
if __name__ == '__main__': # pragma: no cover
exit(main())
| import logging
from . import config, cli
def main():
logging.basicConfig(level=logging.INFO, format="%(message)s")
conf = config.load_config()
cli.dothub(obj={}, default_map=conf)
if __name__ == '__main__': # pragma: no cover
exit(main())
| Fix typo on logging configuration | Fix typo on logging configuration | Python | mit | Mariocj89/dothub | ---
+++
@@ -3,7 +3,7 @@
def main():
- logging.basicConfig(levle=logging.INFO, format="%(message)s")
+ logging.basicConfig(level=logging.INFO, format="%(message)s")
conf = config.load_config()
cli.dothub(obj={}, default_map=conf)
|
9fdd24ed20c553638cde7c67f994ea72da0ef149 | tests/conftest.py | tests/conftest.py | import shutil
from pathlib import Path
import pytest
from pandas_profiling.utils.cache import cache_file
@pytest.fixture(scope="function")
def get_data_file(tmpdir):
def getter(file_name, url):
source_file = cache_file(file_name, url)
# Move to temporary directory
test_path = Path(str(tmpdir))
shutil.copy(source_file, test_path / file_name)
return test_path / file_name
return getter
@pytest.fixture(scope="module")
def test_output_dir(tmpdir_factory):
test_path = Path(str(tmpdir_factory.mktemp("test")))
yield test_path
shutil.rmtree(str(test_path))
| import shutil
from pathlib import Path
import pytest
from pandas_profiling.utils.cache import cache_file
@pytest.fixture(scope="function")
def get_data_file(tmpdir):
def getter(file_name, url):
source_file = cache_file(file_name, url)
# Move to temporary directory
test_path = Path(str(tmpdir))
shutil.copy(str(source_file), str(test_path / file_name))
return str(test_path / file_name)
return getter
@pytest.fixture(scope="module")
def test_output_dir(tmpdir_factory):
test_path = Path(str(tmpdir_factory.mktemp("test")))
yield test_path
shutil.rmtree(str(test_path))
| Convert Path to str for Python 3.5 | Convert Path to str for Python 3.5
| Python | mit | JosPolfliet/pandas-profiling,JosPolfliet/pandas-profiling | ---
+++
@@ -12,8 +12,8 @@
source_file = cache_file(file_name, url)
# Move to temporary directory
test_path = Path(str(tmpdir))
- shutil.copy(source_file, test_path / file_name)
- return test_path / file_name
+ shutil.copy(str(source_file), str(test_path / file_name))
+ return str(test_path / file_name)
return getter
|
09fc5b3e37cc0bcaf764c540f32d1a3eab1b8cf2 | tests/som_test.py | tests/som_test.py | import unittest
from parameterized import parameterized
from som.vm.universe import Universe
class SomTest(unittest.TestCase):
@parameterized.expand([
("ClassStructure",),
("Array" ,),
("Block" ,),
("ClassLoading" ,),
("Closure" ,),
("Coercion" ,),
("CompilerReturn",),
("Double" ,),
("Empty" ,),
("Hash" ,),
("Integer" ,),
("ObjectSize" ,),
("Preliminary" ,),
("Reflection" ,),
("SelfBlock" ,),
("Super" ,),
("String" ,),
("Symbol" ,),
("System" ,),
("Vector" ,)])
def test_som_test(self, test_name):
args = ["-cp", "Smalltalk", "TestSuite/TestHarness.som", test_name]
u = Universe(True)
u.interpret(args)
self.assertEquals(0, u.last_exit_code())
import sys
if sys.modules.has_key('pytest'):
# hack to make pytest not to collect the unexpanded test method
delattr(SomTest, "test_som_test")
| import unittest
from parameterized import parameterized
from som.vm.universe import Universe
class SomTest(unittest.TestCase):
@parameterized.expand([
("ClassStructure",),
("Array" ,),
("Block" ,),
("ClassLoading" ,),
("Closure" ,),
("Coercion" ,),
("CompilerReturn",),
("Double" ,),
("Empty" ,),
("Hash" ,),
("Integer" ,),
("ObjectSize" ,),
("Preliminary" ,),
("Reflection" ,),
("SelfBlock" ,),
("Super" ,),
("String" ,),
("Symbol" ,),
("System" ,),
("Vector" ,)])
def test_som_test(self, test_name):
args = ["-cp", "Smalltalk", "TestSuite/TestHarness.som", test_name]
u = Universe(True)
u.interpret(args)
self.assertEquals(0, u.last_exit_code())
import sys
if 'pytest' in sys.modules:
# hack to make pytest not to collect the unexpanded test method
delattr(SomTest, "test_som_test")
| Use in, because has_key seems to be deprecated | Use in, because has_key seems to be deprecated
Signed-off-by: Stefan Marr <46f1a0bd5592a2f9244ca321b129902a06b53e03@stefan-marr.de>
| Python | mit | SOM-st/RTruffleSOM,SOM-st/PySOM,SOM-st/RPySOM,SOM-st/RPySOM,SOM-st/RTruffleSOM,smarr/RTruffleSOM,smarr/PySOM,smarr/RTruffleSOM,smarr/PySOM,SOM-st/PySOM | ---
+++
@@ -37,6 +37,7 @@
self.assertEquals(0, u.last_exit_code())
import sys
-if sys.modules.has_key('pytest'):
+
+if 'pytest' in sys.modules:
# hack to make pytest not to collect the unexpanded test method
delattr(SomTest, "test_som_test") |
e9e8428563545d00eda25a540a3621943bf34143 | tests/test_now.py | tests/test_now.py | # -*- coding: utf-8 -*-
import pytest
from freezegun import freeze_time
from jinja2 import Environment, exceptions
@pytest.fixture(scope='session')
def environment():
return Environment(extensions=['jinja2_time.TimeExtension'])
@pytest.yield_fixture(autouse=True)
def freeze():
freezer = freeze_time("2015-12-09 23:33:01")
freezer.start()
yield
freezer.stop()
def test_tz_is_required(environment):
with pytest.raises(exceptions.TemplateSyntaxError):
environment.from_string('{% now %}')
def test_utc_default_datetime_format(environment):
template = environment.from_string("{% now 'utc' %}")
assert template.render() == "2015-12-09"
@pytest.fixture(params=['utc', 'local', 'Europe/Berlin'])
def valid_tz(request):
return request.param
def test_accept_valid_timezones(environment, valid_tz):
template = environment.from_string(
"{% now '" + valid_tz + "', '%Y-%m' %}"
)
assert template.render() == '2015-12'
| # -*- coding: utf-8 -*-
import pytest
from freezegun import freeze_time
from jinja2 import Environment, exceptions
@pytest.fixture
def environment():
return Environment(extensions=['jinja2_time.TimeExtension'])
@pytest.yield_fixture(autouse=True)
def freeze():
freezer = freeze_time("2015-12-09 23:33:01")
freezer.start()
yield
freezer.stop()
def test_tz_is_required(environment):
with pytest.raises(exceptions.TemplateSyntaxError):
environment.from_string('{% now %}')
def test_utc_default_datetime_format(environment):
template = environment.from_string("{% now 'utc' %}")
assert template.render() == "2015-12-09"
@pytest.fixture(params=['utc', 'local', 'Europe/Berlin'])
def valid_tz(request):
return request.param
def test_accept_valid_timezones(environment, valid_tz):
template = environment.from_string(
"{% now '" + valid_tz + "', '%Y-%m' %}"
)
assert template.render() == '2015-12'
def test_environment_datetime_format(environment):
environment.datetime_format = '%a, %d %b %Y %H:%M:%S'
template = environment.from_string("{% now 'utc' %}")
assert template.render() == "Wed, 09 Dec 2015 23:33:01"
| Implement a test for environment.datetime_format | Implement a test for environment.datetime_format
| Python | mit | hackebrot/jinja2-time | ---
+++
@@ -6,7 +6,7 @@
from jinja2 import Environment, exceptions
-@pytest.fixture(scope='session')
+@pytest.fixture
def environment():
return Environment(extensions=['jinja2_time.TimeExtension'])
@@ -41,3 +41,11 @@
)
assert template.render() == '2015-12'
+
+
+def test_environment_datetime_format(environment):
+ environment.datetime_format = '%a, %d %b %Y %H:%M:%S'
+
+ template = environment.from_string("{% now 'utc' %}")
+
+ assert template.render() == "Wed, 09 Dec 2015 23:33:01" |
0147e9a6c9d61028781b55f4f8e068e576b653a0 | manage.py | manage.py | import os
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from api import create_app, db
application = create_app(os.getenv('FLASK_CONFIG') or 'default')
migrate = Migrate(application, db)
manager = Manager(application)
manager.add_command('db', MigrateCommand)
@manager.command
def test():
"""Run the unit tests."""
import unittest
tests = unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosity=2).run(tests)
@manager.command
def recreate_db():
"""
Recreates a local database. Drops and creates a new database
"""
db.drop_all()
db.create_all()
db.session.commit()
if __name__ == "__main__":
manager.run()
| import os
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from api import create_app, db
application = create_app(os.getenv('FLASK_CONFIG') or 'default')
migrate = Migrate(application, db)
manager = Manager(application)
manager.add_command('db', MigrateCommand)
@manager.command
def test():
"""Run the unit tests."""
import unittest
tests = unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosity=2).run(tests)
@manager.command
def recreate_db():
"""
Recreates a local database. Drops and creates a new database
"""
db.drop_all()
db.create_all()
db.session.commit()
@manager.command
def create_db():
db.create_all()
db.session.commit()
@manager.command
def drop_db():
db.drop_all()
db.session.commit()
if __name__ == "__main__":
manager.run()
| Add create and drop db tasks | Add create and drop db tasks
| Python | mit | EdwinKato/bucket-list,EdwinKato/bucket-list,EdwinKato/bucket-list,EdwinKato/bucket-list,EdwinKato/bucket-list | ---
+++
@@ -31,5 +31,16 @@
db.create_all()
db.session.commit()
+@manager.command
+def create_db():
+ db.create_all()
+ db.session.commit()
+
+@manager.command
+def drop_db():
+ db.drop_all()
+ db.session.commit()
+
+
if __name__ == "__main__":
manager.run() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.