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
8dd08da1b7578dccee0d64c236da9a87b911ce84
setup.py
setup.py
from setuptools import setup, find_packages setup( name='mock-django', version='0.4.0', description='', license='Apache License 2.0', author='David Cramer', author_email='dcramer@gmail.com', url='http://github.com/dcramer/mock-django', packages=find_packages(), install_requires=[ 'nose', 'unittest2', 'mock', ], tests_require=[ 'mock==dev', ], test_suite='nose.collector', zip_safe=False, include_package_data=True, )
from setuptools import setup, find_packages setup( name='mock-django', version='0.4.0', description='', license='Apache License 2.0', author='David Cramer', author_email='dcramer@gmail.com', url='http://github.com/dcramer/mock-django', packages=find_packages(), install_requires=[ 'nose', 'unittest2', 'mock', ], test_suite='nose.collector', zip_safe=False, include_package_data=True, )
Update reqs to not require mock==dev
Update reqs to not require mock==dev
Python
apache-2.0
bennylope/mock-django,dcramer/mock-django
--- +++ @@ -14,9 +14,6 @@ 'unittest2', 'mock', ], - tests_require=[ - 'mock==dev', - ], test_suite='nose.collector', zip_safe=False, include_package_data=True,
bed95f0c0da7bc81eaf35aab24865bc35f01513b
setup.py
setup.py
#!/usr/bin/env python3 # publish on pypi # --------------- # $ python3 setup.py sdist # $ twine upload dist/imagecluster-x.y.z.tar.gz import os from setuptools import setup here = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(here, 'README.rst')) as fd: long_description = fd.read() setup( name='imagecluster', version='0.3.0', description='cluster images based on image content using a pre-trained ' \ 'deep neural network and hierarchical clustering', long_description=long_description, url='https://github.com/elcorto/imagecluster', author='Steve Schmerler', author_email='git@elcorto.com', license='BSD 3-Clause', keywords='image cluster vgg16 deep-learning', packages=['imagecluster'], install_requires=open('requirements.txt').read().splitlines(), )
#!/usr/bin/env python3 # publish on pypi # --------------- # $ python3 setup.py sdist # $ twine upload dist/imagecluster-x.y.z.tar.gz import os from setuptools import setup here = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(here, 'README.rst'), encoding='utf-8') as fd: long_description = fd.read() setup( name='imagecluster', version='0.3.0', description='cluster images based on image content using a pre-trained ' \ 'deep neural network and hierarchical clustering', long_description=long_description, url='https://github.com/elcorto/imagecluster', author='Steve Schmerler', author_email='git@elcorto.com', license='BSD 3-Clause', keywords='image cluster vgg16 deep-learning', packages=['imagecluster'], install_requires=open('requirements.txt').read().splitlines(), )
Use utf-8 encoding when reading README.rst Avoid UnicodeDecodeErrors on some platforms that default to ascii encoding and fail to read the non-ascii characters.
MNT: Use utf-8 encoding when reading README.rst Avoid UnicodeDecodeErrors on some platforms that default to ascii encoding and fail to read the non-ascii characters.
Python
bsd-3-clause
elcorto/imagecluster
--- +++ @@ -9,7 +9,7 @@ from setuptools import setup here = os.path.abspath(os.path.dirname(__file__)) -with open(os.path.join(here, 'README.rst')) as fd: +with open(os.path.join(here, 'README.rst'), encoding='utf-8') as fd: long_description = fd.read()
66ac5502e689a404cf4372a3a9add75caa2473a6
setup.py
setup.py
from setuptools import setup, find_packages setup( name="virgil-sdk", version="4.0.1b", packages=find_packages(), install_requires=[ 'virgil-crypto', ], author="Virgil Security", author_email="support@virgilsecurity.com", url="https://virgilsecurity.com/", classifiers=[ "Development Status :: 4 - Beta", "License :: OSI Approved :: BSD License", "Natural Language :: English", "Programming Language :: Python :: 2.7", "Topic :: Security :: Cryptography", ], license="BSD", description="Virgil keys service SDK", long_description="Virgil keys service SDK", )
from setuptools import setup, find_packages setup( name="virgil-sdk", version="4.1.0", packages=find_packages(), install_requires=[ 'virgil-crypto', ], author="Virgil Security", author_email="support@virgilsecurity.com", url="https://virgilsecurity.com/", classifiers=[ "Development Status :: 5 Production/Stable", "License :: OSI Approved :: BSD License", "Natural Language :: English", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Topic :: Security :: Cryptography", ], license="BSD", description="Virgil keys service SDK", long_description="Virgil keys service SDK", )
Fix version for new release, change develpment status, add support for 3.3, 3.4, 3.5 version disabled early
Fix version for new release, change develpment status, add support for 3.3, 3.4, 3.5 version disabled early
Python
bsd-3-clause
VirgilSecurity/virgil-sdk-python
--- +++ @@ -2,7 +2,7 @@ setup( name="virgil-sdk", - version="4.0.1b", + version="4.1.0", packages=find_packages(), install_requires=[ 'virgil-crypto', @@ -11,10 +11,13 @@ author_email="support@virgilsecurity.com", url="https://virgilsecurity.com/", classifiers=[ - "Development Status :: 4 - Beta", + "Development Status :: 5 Production/Stable", "License :: OSI Approved :: BSD License", "Natural Language :: English", "Programming Language :: Python :: 2.7", + "Programming Language :: Python :: 3.3", + "Programming Language :: Python :: 3.4", + "Programming Language :: Python :: 3.5", "Topic :: Security :: Cryptography", ], license="BSD",
d5eff1a8770315a81c765f50a6d0cbe4ef0fced7
setup.py
setup.py
name, version = 'buildout.wheel', '0' install_requires = ['setuptools', 'wheel', 'humpty', 'six'] extras_require = dict(test=['manuel', 'mock', 'zope.testing']) entry_points = """ [zc.buildout.extension] wheel = buildout.wheel:load """ from setuptools import setup long_description = open('README.rst').read() + '\n' + open('CHANGES.rst').read() setup( author = 'Jim Fulton', author_email = 'jim@jimfulton.info', license = 'MIT', name = name, version = version, long_description = long_description, description = long_description.strip().split('\n')[1], packages = [name.split('.')[0], name], namespace_packages = [name.split('.')[0]], package_dir = {'': 'src'}, install_requires = install_requires, zip_safe = False, entry_points=entry_points, package_data = {name: ['*.txt', '*.test', '*.html']}, extras_require = extras_require, tests_require = extras_require['test'], test_suite = name+'.tests.test_suite', include_package_data = True, )
name = 'buildout.wheel' version = '0' install_requires = ['zc.buildout', 'setuptools', 'wheel', 'humpty', 'six'] extras_require = dict(test=[]) entry_points = """ [zc.buildout.extension] wheel = buildout.wheel:load """ from setuptools import setup long_description = open('README.rst').read() + '\n' + open('CHANGES.rst').read() setup( author = 'Jim Fulton', author_email = 'jim@jimfulton.info', license = 'MIT', name = name, version = version, long_description = long_description, description = long_description.strip().split('\n')[1], packages = [name.split('.')[0], name], namespace_packages = [name.split('.')[0]], package_dir = {'': 'src'}, install_requires = install_requires, zip_safe = False, entry_points=entry_points, package_data = {name: ['*.txt', '*.test', '*.html']}, extras_require = extras_require, tests_require = extras_require['test'], test_suite = name+'.tests.test_suite', include_package_data = True, keywords = "development build", classifiers = [ 'Development Status :: 5 - Production/Stable', 'Framework :: Buildout', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Topic :: Software Development :: Build Tools', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
Update meta data and no test deps
Update meta data and no test deps
Python
mit
buildout/buildout.wheel,leorochael/buildout.wheel,buildout/buildout.wheel,leorochael/buildout.wheel,buildout/wheel,buildout/wheel
--- +++ @@ -1,7 +1,8 @@ -name, version = 'buildout.wheel', '0' +name = 'buildout.wheel' +version = '0' -install_requires = ['setuptools', 'wheel', 'humpty', 'six'] -extras_require = dict(test=['manuel', 'mock', 'zope.testing']) +install_requires = ['zc.buildout', 'setuptools', 'wheel', 'humpty', 'six'] +extras_require = dict(test=[]) entry_points = """ [zc.buildout.extension] @@ -17,7 +18,8 @@ author_email = 'jim@jimfulton.info', license = 'MIT', - name = name, version = version, + name = name, + version = version, long_description = long_description, description = long_description.strip().split('\n')[1], packages = [name.split('.')[0], name], @@ -31,4 +33,22 @@ tests_require = extras_require['test'], test_suite = name+'.tests.test_suite', include_package_data = True, + + keywords = "development build", + classifiers = [ + 'Development Status :: 5 - Production/Stable', + 'Framework :: Buildout', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: MIT', + 'Programming Language :: Python', + 'Programming Language :: Python :: 2', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.4', + 'Programming Language :: Python :: 3.5', + 'Programming Language :: Python :: 3.6', + 'Topic :: Software Development :: Build Tools', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + )
c8609641a7cc0f7505b901eaa8e04e879b39b896
setup.py
setup.py
# -*- coding: utf-8 -*- from setuptools import setup, find_packages setup( name = "OpenFisca-Country-Template", version = "3.8.0", author = "OpenFisca Team", author_email = "contact@openfisca.org", classifiers=[ "Development Status :: 5 - Production/Stable", "License :: OSI Approved :: GNU Affero General Public License v3", "Operating System :: POSIX", "Programming Language :: Python", "Topic :: Scientific/Engineering :: Information Analysis", ], description = "OpenFisca tax and benefit system for Country-Template", keywords = "benefit microsimulation social tax", license ="http://www.fsf.org/licensing/licenses/agpl-3.0.html", url = "https://github.com/openfisca/country-template", include_package_data = True, # Will read MANIFEST.in data_files = [ ("share/openfisca/openfisca-country-template", ["CHANGELOG.md", "LICENSE", "README.md"]), ], install_requires = [ "OpenFisca-Core[web-api] >= 27.0, < 28.0", ], extras_require = { "dev": [ "autopep8 == 1.4.0", "flake8 >= 3.5.0, < 3.6.0", "flake8-print", "pycodestyle >= 2.3.0, < 2.4.0", # To avoid incompatibility with flake ] }, packages=find_packages(), )
# -*- coding: utf-8 -*- from setuptools import setup, find_packages setup( name = "OpenFisca-Country-Template", version = "3.8.0", author = "OpenFisca Team", author_email = "contact@openfisca.org", classifiers=[ "Development Status :: 5 - Production/Stable", "License :: OSI Approved :: GNU Affero General Public License v3", "Operating System :: POSIX", "Programming Language :: Python", "Topic :: Scientific/Engineering :: Information Analysis", ], description = "OpenFisca tax and benefit system for Country-Template", keywords = "benefit microsimulation social tax", license ="http://www.fsf.org/licensing/licenses/agpl-3.0.html", url = "https://github.com/openfisca/country-template", include_package_data = True, # Will read MANIFEST.in data_files = [ ("share/openfisca/openfisca-country-template", ["CHANGELOG.md", "LICENSE", "README.md"]), ], install_requires = [ "OpenFisca-Core[web-api] >=27.0,<32.0", ], extras_require = { "dev": [ "autopep8 == 1.4.0", "flake8 >= 3.5.0, < 3.6.0", "flake8-print", "pycodestyle >= 2.3.0, < 2.4.0", # To avoid incompatibility with flake ] }, packages=find_packages(), )
Update openfisca-core requirement from <28.0,>=27.0 to >=27.0,<32.0
Update openfisca-core requirement from <28.0,>=27.0 to >=27.0,<32.0 Updates the requirements on [openfisca-core](https://github.com/openfisca/openfisca-core) to permit the latest version. - [Release notes](https://github.com/openfisca/openfisca-core/releases) - [Changelog](https://github.com/openfisca/openfisca-core/blob/master/CHANGELOG.md) - [Commits](https://github.com/openfisca/openfisca-core/compare/27.0.0...31.0.0) Signed-off-by: dependabot[bot] <5bdcd3c0d4d24ae3e71b3b452a024c6324c7e4bb@dependabot.com>
Python
agpl-3.0
openfisca/country-template,openfisca/country-template
--- +++ @@ -23,7 +23,7 @@ ("share/openfisca/openfisca-country-template", ["CHANGELOG.md", "LICENSE", "README.md"]), ], install_requires = [ - "OpenFisca-Core[web-api] >= 27.0, < 28.0", + "OpenFisca-Core[web-api] >=27.0,<32.0", ], extras_require = { "dev": [
fc1bbf6972d8660f24aba0fa073991ca5847829a
setup.py
setup.py
from distutils.core import setup from jeni import __version__ CLASSIFIERS = [ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Utilities', 'Topic :: Software Development :: Libraries :: Python Modules'] setup( name='jeni', version=__version__, url='https://github.com/rduplain/jeni-python', license='BSD', author='Ron DuPlain', author_email='ron.duplain@gmail.com', description='dependency aggregation', py_modules=['jeni'], requires=[], classifiers=CLASSIFIERS)
from distutils.core import setup from os import path from jeni import __version__ CLASSIFIERS = [ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Utilities', 'Topic :: Software Development :: Libraries :: Python Modules'] with open(path.join(path.dirname(__file__), 'README.txt')) as fd: long_description = '\n' + fd.read() setup( name='jeni', version=__version__, url='https://github.com/rduplain/jeni-python', license='BSD', author='Ron DuPlain', author_email='ron.duplain@gmail.com', description='dependency aggregation', long_description=long_description, py_modules=['jeni'], requires=[], classifiers=CLASSIFIERS)
Read long description from README.
Read long description from README.
Python
bsd-2-clause
rduplain/jeni-python,groner/jeni-python
--- +++ @@ -1,4 +1,5 @@ from distutils.core import setup +from os import path from jeni import __version__ @@ -21,6 +22,10 @@ 'Topic :: Software Development :: Libraries :: Python Modules'] +with open(path.join(path.dirname(__file__), 'README.txt')) as fd: + long_description = '\n' + fd.read() + + setup( name='jeni', version=__version__, @@ -29,6 +34,7 @@ author='Ron DuPlain', author_email='ron.duplain@gmail.com', description='dependency aggregation', + long_description=long_description, py_modules=['jeni'], requires=[], classifiers=CLASSIFIERS)
dab5d49b71700d93b466dc9f9d377a08f7fe68db
setup.py
setup.py
#!/usr/bin/env python # Copyright 2011 Andrew Ryrie (amr66) from distutils.core import setup setup(name='django-pyroven', description='A Django authentication backend for Ucam-WebAuth / Raven', long_description=open('README.md').read(), url='https://github.com/pyroven/django-pyroven', version='0.9', license='MIT', author='Andrew Ryrie', author_email='smb314159@gmail.com', maintainer='Kristian Glass', maintainer_email='pyroven@doismellburning.co.uk', packages=['pyroven'], install_requires=[ 'Django<1.7', 'pyOpenSSL', ], classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Operating System :: OS Independent', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP', ], )
#!/usr/bin/env python # Copyright 2011 Andrew Ryrie (amr66) from distutils.core import setup setup(name='django-pyroven', description='A Django authentication backend for Ucam-WebAuth / Raven', long_description=open('README.md').read(), url='https://github.com/pyroven/django-pyroven', version='0.9', license='MIT', author='Andrew Ryrie', author_email='smb314159@gmail.com', maintainer='Kristian Glass', maintainer_email='pyroven@doismellburning.co.uk', packages=['pyroven'], install_requires=[ 'Django<1.7', 'pyOpenSSL', ], classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Operating System :: OS Independent', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP', ], )
Fix flake8 indentation issues with classifiers
Fix flake8 indentation issues with classifiers
Python
mit
pyroven/django-pyroven
--- +++ @@ -20,14 +20,14 @@ 'pyOpenSSL', ], classifiers=[ - 'Environment :: Web Environment', - 'Framework :: Django', - 'Operating System :: OS Independent', - 'Intended Audience :: Developers', - 'License :: OSI Approved :: MIT License', - 'Programming Language :: Python', - 'Programming Language :: Python :: 2.6', - 'Programming Language :: Python :: 2.7', - 'Topic :: Internet :: WWW/HTTP', + 'Environment :: Web Environment', + 'Framework :: Django', + 'Operating System :: OS Independent', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: MIT License', + 'Programming Language :: Python', + 'Programming Language :: Python :: 2.6', + 'Programming Language :: Python :: 2.7', + 'Topic :: Internet :: WWW/HTTP', ], )
6cefb1f71f05860ab1cf65fe29eb724a6349e493
setup.py
setup.py
from setuptools import setup url = "" version = "0.1.0" readme = open('README.rst').read() setup( name="dtool-create", packages=["dtool_create"], version=version, description="Dtool plugin for creating datasets and collections", long_description=readme, include_package_data=True, author="Tjelvar Olsson", author_email="tjelvar.olsson@jic.ac.uk", url=url, install_requires=[], download_url="{}/tarball/{}".format(url, version), license="MIT" )
from setuptools import setup url = "" version = "0.1.0" readme = open('README.rst').read() setup( name="dtool-create", packages=["dtool_create"], version=version, description="Dtool plugin for creating datasets and collections", long_description=readme, include_package_data=True, author="Tjelvar Olsson", author_email="tjelvar.olsson@jic.ac.uk", url=url, install_requires=[ "Click", "click-plugins", ], download_url="{}/tarball/{}".format(url, version), license="MIT" )
Add click and click-plugins dependencies
Add click and click-plugins dependencies
Python
mit
jic-dtool/dtool-create
--- +++ @@ -14,7 +14,10 @@ author="Tjelvar Olsson", author_email="tjelvar.olsson@jic.ac.uk", url=url, - install_requires=[], + install_requires=[ + "Click", + "click-plugins", + ], download_url="{}/tarball/{}".format(url, version), license="MIT" )
5ef6fe75ad8784381824d408a9178e076ddcc97e
setup.py
setup.py
from setuptools import setup, find_packages with open('requirements.txt') as f: required = f.read().splitlines() setup(name='hackr', version='0.1.1', url='https://github.com/pytorn/hackr', license='Apache 2.0', author='Ashwini Purohit', author_email='geek.ashwini@gmail.com', description='A unicorn for Hackathons', packages=find_packages(exclude=['tests']), long_description=open('README.rst').read(), zip_safe=False, classifiers=[ 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.6', ], install_requires=required, setup_requires=[])
from setuptools import setup, find_packages with open('requirements.txt') as f: required = f.read().splitlines() setup(name='hackr', version='0.1.2', url='https://github.com/pytorn/hackr', license='Apache 2.0', author='Ashwini Purohit', author_email='geek.ashwini@gmail.com', description='A unicorn for Hackathons', packages=find_packages(exclude=['tests']), long_description=open('README.rst').read(), zip_safe=False, classifiers=[ 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.6', ], install_requires=required, setup_requires=[])
Update package pip install hackr
Update package pip install hackr
Python
apache-2.0
pytorn/hackr
--- +++ @@ -5,7 +5,7 @@ setup(name='hackr', - version='0.1.1', + version='0.1.2', url='https://github.com/pytorn/hackr',
40a099f9f519f63695afb61a07a7c2d5b7f795af
setup.py
setup.py
#! /usr/bin/python from distutils.core import setup try: from distutils.command.build_py import build_py_2to3 as build_py except ImportError: # Python 2.x from distutils.command.build_py import build_py import photo import re DOCLINES = photo.__doc__.split("\n") DESCRIPTION = DOCLINES[0] LONG_DESCRIPTION = "\n".join(DOCLINES[2:]) VERSION = photo.__version__ AUTHOR = photo.__author__ m = re.match(r"^(.*?)\s*<(.*)>$", AUTHOR) (AUTHOR_NAME, AUTHOR_EMAIL) = m.groups() if m else (AUTHOR, None) setup( name = "photo", version = VERSION, description = DESCRIPTION, long_description = LONG_DESCRIPTION, author = AUTHOR_NAME, author_email = AUTHOR_EMAIL, license = "Apache-2.0", requires = ["yaml", "pyexiv2"], packages = ["photo", "photo.qt"], scripts = ["photoidx.py", "imageview.py"], classifiers = [ "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Development Status :: 3 - Alpha", "License :: OSI Approved :: Apache Software License", "Operating System :: OS Independent", ], cmdclass = {'build_py': build_py}, )
#! /usr/bin/python from distutils.core import setup try: from distutils.command.build_py import build_py_2to3 as build_py except ImportError: # Python 2.x from distutils.command.build_py import build_py import photo import re DOCLINES = photo.__doc__.split("\n") DESCRIPTION = DOCLINES[0] LONG_DESCRIPTION = "\n".join(DOCLINES[2:]) VERSION = photo.__version__ AUTHOR = photo.__author__ m = re.match(r"^(.*?)\s*<(.*)>$", AUTHOR) (AUTHOR_NAME, AUTHOR_EMAIL) = m.groups() if m else (AUTHOR, None) setup( name = "photo", version = VERSION, description = DESCRIPTION, long_description = LONG_DESCRIPTION, author = AUTHOR_NAME, author_email = AUTHOR_EMAIL, license = "Apache-2.0", requires = ["yaml"], packages = ["photo", "photo.qt"], scripts = ["photoidx.py", "imageview.py"], classifiers = [ "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Development Status :: 3 - Alpha", "License :: OSI Approved :: Apache Software License", "Operating System :: OS Independent", ], cmdclass = {'build_py': build_py}, )
Remove obsolete requirement of pyexiv2.
Remove obsolete requirement of pyexiv2.
Python
apache-2.0
RKrahl/photo-tools
--- +++ @@ -26,7 +26,7 @@ author = AUTHOR_NAME, author_email = AUTHOR_EMAIL, license = "Apache-2.0", - requires = ["yaml", "pyexiv2"], + requires = ["yaml"], packages = ["photo", "photo.qt"], scripts = ["photoidx.py", "imageview.py"], classifiers = [
42c064b71ebfce67bf83f4bc30cbf16cf8370ebb
setup.py
setup.py
import os import codecs #from distutils.core import setup from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name='django-messages-extends', version='0.6.1', description='A Django app for extends Django\'s messages framework, adds sticky messages and persistent messages', long_description=codecs.open('README.md', 'r', 'utf-8').read(), author='AliLozano', author_email='alilozanoc@gmail.com', #base-project = 'https://github.com/philomat/django-persistent-messages', #co-author='philomat', license='MIT', url='https://github.com/AliLozano/django-messages-extends/', keywords=['messages', 'django', 'persistent', 'sticky', ], packages=[ 'messages_extends', 'messages_extends.migrations', ], include_package_data=True, package_data={ 'messages_extends': [ 'templates/messages_extends/*/*.html', 'static/*', ], '': ['README.md', 'LICENSE.txt'] }, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], test_suite = 'runtests', py_modules=['messages_extends'], )
import os import codecs #from distutils.core import setup from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name='django-messages-extends', version='0.6.1', description='A Django app for extends Django\'s messages framework, adds sticky messages and persistent messages', long_description=codecs.open('README.md', 'r', 'utf-8').read(), author='AliLozano', author_email='alilozanoc@gmail.com', #base-project = 'https://github.com/philomat/django-persistent-messages', #co-author='philomat', license='MIT', url='https://github.com/AliLozano/django-messages-extends/', keywords=['messages', 'django', 'persistent', 'sticky', ], packages=[ 'messages_extends', 'messages_extends.migrations', ], include_package_data=True, package_data={ 'messages_extends': [ 'templates/messages_extends/*/*.html', 'static/*', ], '': ['README.md', 'LICENSE.txt'] }, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], test_suite = 'runtests', py_modules=['messages_extends'], python_requires='>=3', )
Add python_Requires, per @davidfischer suggestion
Add python_Requires, per @davidfischer suggestion
Python
mit
AliLozano/django-messages-extends,AliLozano/django-messages-extends,AliLozano/django-messages-extends
--- +++ @@ -42,4 +42,5 @@ ], test_suite = 'runtests', py_modules=['messages_extends'], + python_requires='>=3', )
f46e20c960ebd03eb8e8c194db649751407afb8b
setup.py
setup.py
from setuptools import setup setup( name='ploodood', version='0.1', description='Generates words that "sound like real words"', author = 'Matteo Giordano', author_email = 'ilmalteo@gmail.com', url = 'https://github.com/malteo/ploodood', download_url = 'https://github.com/malteo/ploodood/tarball/0.1', keywords = ['password', 'generator', 'cli', 'command line'], packages=['ploodood'], py_modules=['ploodood'], classifiers = [], install_requires=[ 'Click', 'Requests', 'untangle' ], entry_points=''' [console_scripts] ploodood=ploodood:ploodood ''', )
from setuptools import setup setup( name='ploodood', version='0.1', description='Generates words that "sound like real words"', author = 'Matteo Giordano', author_email = 'ilmalteo@gmail.com', url = 'https://github.com/malteo/ploodood', download_url = 'https://github.com/malteo/ploodood/tarball/0.1', keywords = ['password', 'generator', 'cli', 'command line'], py_modules=['ploodood'], classifiers = [], install_requires=[ 'Click', 'Requests', 'untangle' ], entry_points=''' [console_scripts] ploodood=ploodood:ploodood ''', )
Remove wrong directory and let it build
Remove wrong directory and let it build
Python
mit
malteo/ploodood
--- +++ @@ -9,7 +9,6 @@ url = 'https://github.com/malteo/ploodood', download_url = 'https://github.com/malteo/ploodood/tarball/0.1', keywords = ['password', 'generator', 'cli', 'command line'], - packages=['ploodood'], py_modules=['ploodood'], classifiers = [], install_requires=[
1dc919145219fde72e8b17e3dc93d675441d01e9
setup.py
setup.py
#!/usr/bin/python # -*-coding:UTF-8 -*- from setuptools import setup, find_packages from os import path import sys if sys.version_info[0] >= 3: install_requires = ["PyMySQL"] else: install_requires = ["MySQL-python"] here = path.abspath(path.dirname(__file__)) setup( name='dictmysqldb', version='0.3.4', description='A mysql package on the top of MySQL-python for more convenient database manipulations with Python dictionary.', author='Guangyang Li', author_email='mail@guangyangli.com', license='MIT', py_modules=['dictmysqldb'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: Software Development :: Build Tools', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3' ], keywords='mysql database', download_url = 'https://github.com/ligyxy/DictMySQLdb', install_requires=install_requires )
#!/usr/bin/python # -*-coding:UTF-8 -*- from setuptools import setup, find_packages from os import path import sys if sys.version_info[0] >= 3: install_requires = ["PyMySQL"] else: install_requires = ["MySQL-python"] here = path.abspath(path.dirname(__file__)) setup( name='dictmysqldb', version='0.3.5', description='A mysql package on the top of MySQL-python for more convenient database manipulations with Python dictionary.', author='Guangyang Li', author_email='mail@guangyangli.com', license='MIT', py_modules=['dictmysqldb'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: Software Development :: Build Tools', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.1', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5' ], keywords='mysql database', download_url = 'https://github.com/ligyxy/DictMySQLdb', install_requires=install_requires )
Fix the require Python version
Fix the require Python version
Python
mit
ligyxy/DictMySQLdb,ligyxy/DictMySQL
--- +++ @@ -15,7 +15,7 @@ setup( name='dictmysqldb', - version='0.3.4', + version='0.3.5', description='A mysql package on the top of MySQL-python for more convenient database manipulations with Python dictionary.', @@ -35,7 +35,12 @@ 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', - 'Programming Language :: Python :: 3' + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.1', + 'Programming Language :: Python :: 3.2', + 'Programming Language :: Python :: 3.3', + 'Programming Language :: Python :: 3.4', + 'Programming Language :: Python :: 3.5' ], keywords='mysql database',
fd1826588031bfe165cef1cfa8d8cdc9123e25c5
setup.py
setup.py
#!/usr/bin/env python from setuptools import setup setup( name='asset_bender', version='0.1.5', description="A django runtime implementation for Asset Bender", long_description=open('Readme.md').read(), author='HubSpot Dev Team', author_email='devteam+asset_bender_django@hubspot.com', url='https://github.com/HubSpot/asset_bender_django', # download_url='https://github.com/HubSpot/', license='LICENSE.txt', packages=['asset_bender'], include_package_data=True, install_requires=[ 'django>=1.3.0', 'hscacheutils<=1.0.0', ], )
#!/usr/bin/env python from setuptools import setup, find_packages setup( name='asset_bender', version='0.1.6', description="A django runtime implementation for Asset Bender", long_description=open('Readme.md').read(), author='HubSpot Dev Team', author_email='devteam+asset_bender_django@hubspot.com', url='https://github.com/HubSpot/asset_bender_django', # download_url='https://github.com/HubSpot/', license='LICENSE.txt', packages=find_packages(), include_package_data=True, install_requires=[ 'django>=1.3.0', 'hscacheutils<=1.0.0', ], )
Use find_packages instead of manually specifying modules.
Use find_packages instead of manually specifying modules.
Python
mit
HubSpot/asset_bender_django
--- +++ @@ -1,9 +1,9 @@ #!/usr/bin/env python -from setuptools import setup +from setuptools import setup, find_packages setup( name='asset_bender', - version='0.1.5', + version='0.1.6', description="A django runtime implementation for Asset Bender", long_description=open('Readme.md').read(), author='HubSpot Dev Team', @@ -11,7 +11,7 @@ url='https://github.com/HubSpot/asset_bender_django', # download_url='https://github.com/HubSpot/', license='LICENSE.txt', - packages=['asset_bender'], + packages=find_packages(), include_package_data=True, install_requires=[ 'django>=1.3.0',
9bc9232f2b2b95b7031afe3b0a8ec12f9d77384a
setup.py
setup.py
from setuptools import setup setup(name='biosignal', version='0.0.1', description='', url='http://github.com/EmlynC/python-biosignal', author='Emlyn Clay', author_email='eclay101@gmail.com', license='MIT', packages=['biosignal'], zip_safe=False)
from setuptools import setup setup(name='biosignal', version='0.0.2', description="""A library for processing and analysing physiological signals such as ECG, BP, EMG, EEG, Pulse and Sp02""", url='http://github.com/EmlynC/python-biosignal', author='Emlyn Clay', author_email='eclay101@gmail.com', license='MIT', packages=['biosignal'], zip_safe=False)
Add a description for PyPI
Add a description for PyPI
Python
mit
EmlynC/python-biosignal
--- +++ @@ -1,8 +1,9 @@ from setuptools import setup setup(name='biosignal', - version='0.0.1', - description='', + version='0.0.2', + description="""A library for processing and analysing physiological + signals such as ECG, BP, EMG, EEG, Pulse and Sp02""", url='http://github.com/EmlynC/python-biosignal', author='Emlyn Clay', author_email='eclay101@gmail.com',
34de3e7f3959c0fc05bf746e1bc6882f366bfa56
setup.py
setup.py
"""Mailmerge build and install configuration.""" import os try: from setuptools import setup except ImportError: from distutils.core import setup with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme_file: README = readme_file.read() setup( name="mailmerge", description="A simple, command line mail merge tool", long_description=README, version="1.9", author="Andrew DeOrio", author_email="awdeorio@umich.edu", url="https://github.com/awdeorio/mailmerge/", license="MIT", packages=["mailmerge"], keywords=["mail merge", "mailmerge", "email"], install_requires=[ "chardet", "click", "configparser", "jinja2", "future>0.18.0", "backports.csv;python_version<='2.7'", "markdown", "mock;python_version<='2.7'", ], extras_require={ 'dev': [ 'check-manifest', 'codecov>=1.4.0', 'pdbpp', 'pycodestyle', 'pydocstyle', 'pylint', 'pytest', 'pytest-cov', 'tox', ] }, # Python command line utilities will be installed in a PATH-accessible bin/ entry_points={ 'console_scripts': [ 'mailmerge = mailmerge.__main__:cli', ] }, )
"""Mailmerge build and install configuration.""" import os try: from setuptools import setup except ImportError: from distutils.core import setup with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme_file: README = readme_file.read() setup( name="mailmerge", description="A simple, command line mail merge tool", long_description=README, version="1.9", author="Andrew DeOrio", author_email="awdeorio@umich.edu", url="https://github.com/awdeorio/mailmerge/", license="MIT", packages=["mailmerge"], keywords=["mail merge", "mailmerge", "email"], install_requires=[ "chardet", "click", "configparser", "jinja2", # The attachments feature relies on a bug fix in the future library "future>0.18.0", "backports.csv;python_version<='2.7'", "markdown", "mock;python_version<='2.7'", ], extras_require={ 'dev': [ 'check-manifest', 'codecov>=1.4.0', 'pdbpp', 'pycodestyle', 'pydocstyle', 'pylint', 'pytest', 'pytest-cov', 'tox', ] }, # Python command line utilities will be installed in a PATH-accessible bin/ entry_points={ 'console_scripts': [ 'mailmerge = mailmerge.__main__:cli', ] }, )
Comment the new library requirement
Comment the new library requirement
Python
mit
awdeorio/mailmerge
--- +++ @@ -25,7 +25,10 @@ "click", "configparser", "jinja2", + + # The attachments feature relies on a bug fix in the future library "future>0.18.0", + "backports.csv;python_version<='2.7'", "markdown", "mock;python_version<='2.7'",
19b9695ae4ec14d813ad95f782a0c3486a53100c
setup.py
setup.py
""" Flask-CacheControl ------------------ A light-weight library to conveniently set Cache-Control headers on the response. Decorate view functions with cache_for, cache, or dont_cache decorators. Makes use of Flask response.cache_control. This extension does not provide any caching of its own. Its sole purpose is to set Cache-Control and related HTTP headers on the response, so that clients, intermediary proxies or reverse proxies in your jurisdiction which evaluate Cache-Control headers, such as Varnish Cache, do the caching for you. """ import ast import re from setuptools import setup _version_re = re.compile(r'__version__\s+=\s+(.*)') with open('src/flask_cachecontrol/__init__.py', 'rb') as f: version = str(ast.literal_eval(_version_re.search( f.read().decode('utf-8')).group(1))) setup( name='Flask-CacheControl', version=version, url='https://github.com/twiebe/Flask-CacheControl', license='BSD', author='Thomas Wiebe', author_email='code@heimblick.net', description='Set Cache-Control headers on the Flask response', long_description=__doc__, package_dir={'': 'src'}, packages=['flask_cachecontrol'], zip_safe=False, include_package_data=True, platforms='any', install_requires=[ 'Flask', ], 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', ] )
import ast import re from setuptools import setup _version_re = re.compile(r'__version__\s+=\s+(.*)') with open('src/flask_cachecontrol/__init__.py', 'rb') as f: version = str(ast.literal_eval(_version_re.search( f.read().decode('utf-8')).group(1))) setup( name='Flask-CacheControl', version=version, url='https://github.com/twiebe/Flask-CacheControl', license='BSD', author='Thomas Wiebe', author_email='code@heimblick.net', description='Set Cache-Control headers on the Flask response', long_description=open('README.md', 'r').read(), long_description_content_type="text/markdown", package_dir={'': 'src'}, packages=['flask_cachecontrol'], zip_safe=False, include_package_data=True, platforms='any', install_requires=[ 'Flask', ], 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', ] )
Use long description from README.md
Use long description from README.md
Python
bsd-3-clause
twiebe/Flask-CacheControl
--- +++ @@ -1,19 +1,3 @@ -""" -Flask-CacheControl ------------------- - -A light-weight library to conveniently set Cache-Control -headers on the response. Decorate view functions with -cache_for, cache, or dont_cache decorators. Makes use of -Flask response.cache_control. - -This extension does not provide any caching of its own. Its sole -purpose is to set Cache-Control and related HTTP headers on the -response, so that clients, intermediary proxies or reverse proxies -in your jurisdiction which evaluate Cache-Control headers, such as -Varnish Cache, do the caching for you. -""" - import ast import re from setuptools import setup @@ -24,7 +8,6 @@ version = str(ast.literal_eval(_version_re.search( f.read().decode('utf-8')).group(1))) - setup( name='Flask-CacheControl', version=version, @@ -33,7 +16,8 @@ author='Thomas Wiebe', author_email='code@heimblick.net', description='Set Cache-Control headers on the Flask response', - long_description=__doc__, + long_description=open('README.md', 'r').read(), + long_description_content_type="text/markdown", package_dir={'': 'src'}, packages=['flask_cachecontrol'], zip_safe=False,
9b745412a9b36dffe3ba5ad7304e202a500e77fb
tasks.py
tasks.py
from os import mkdir from os.path import join from shutil import rmtree, copytree from invoke import Collection, ctask as task from invocations.docs import docs, www from invocations.packaging import publish # Until we move to spec-based testing @task def test(ctx, coverage=False): runner = "python" if coverage: runner = "coverage run --source=paramiko" flags = "--verbose" ctx.run("{0} test.py {1}".format(runner, flags), pty=True) @task def coverage(ctx): ctx.run("coverage run --source=paramiko test.py --verbose") # Until we stop bundling docs w/ releases. Need to discover use cases first. @task def release(ctx): # Build docs first. Use terribad workaround pending invoke #146 ctx.run("inv docs") # Move the built docs into where Epydocs used to live target = 'docs' rmtree(target, ignore_errors=True) # TODO: make it easier to yank out this config val from the docs coll copytree('sites/docs/_build', target) # Publish publish(ctx) # Remind print("\n\nDon't forget to update RTD's versions page for new minor releases!") ns = Collection(test, coverage, release, docs, www)
from os import mkdir from os.path import join from shutil import rmtree, copytree from invoke import Collection, ctask as task from invocations.docs import docs, www from invocations.packaging import publish # Until we move to spec-based testing @task def test(ctx, coverage=False, flags=""): if "--verbose" not in flags.split(): flags += " --verbose" runner = "python" if coverage: runner = "coverage run --source=paramiko" ctx.run("{0} test.py {1}".format(runner, flags), pty=True) @task def coverage(ctx): ctx.run("coverage run --source=paramiko test.py --verbose") # Until we stop bundling docs w/ releases. Need to discover use cases first. @task def release(ctx): # Build docs first. Use terribad workaround pending invoke #146 ctx.run("inv docs") # Move the built docs into where Epydocs used to live target = 'docs' rmtree(target, ignore_errors=True) # TODO: make it easier to yank out this config val from the docs coll copytree('sites/docs/_build', target) # Publish publish(ctx) # Remind print("\n\nDon't forget to update RTD's versions page for new minor releases!") ns = Collection(test, coverage, release, docs, www)
Allow specifying test.py flags in 'inv test'
Allow specifying test.py flags in 'inv test'
Python
lgpl-2.1
mirrorcoder/paramiko,jaraco/paramiko,dorianpula/paramiko,ameily/paramiko,paramiko/paramiko,reaperhulk/paramiko,SebastianDeiss/paramiko
--- +++ @@ -9,11 +9,12 @@ # Until we move to spec-based testing @task -def test(ctx, coverage=False): +def test(ctx, coverage=False, flags=""): + if "--verbose" not in flags.split(): + flags += " --verbose" runner = "python" if coverage: runner = "coverage run --source=paramiko" - flags = "--verbose" ctx.run("{0} test.py {1}".format(runner, flags), pty=True)
96d2e3d47cf193046f68fef859244fd31be2ffa9
utils.py
utils.py
import vx def _expose(f=None, name=None): if name is None: name = f.__name__.lstrip('_') if getattr(vx, name, None) is not None: raise AttributeError("Cannot expose duplicate name: '{}'".format(name)) if f is None: def g(f): setattr(vx, name, f) return f return g setattr(vx, name, f) return f vx.expose = _expose @vx.expose def _repeat(c, times=4): for _ in range(times): c()
import vx from functools import partial def _expose(f=None, name=None): if f is None: return partial(_expose, name=name) if name is None: name = f.__name__.lstrip('_') if getattr(vx, name, None) is not None: raise AttributeError("Cannot expose duplicate name: '{}'".format(name)) setattr(vx, name, f) return f vx.expose = _expose @vx.expose def _repeat(c, times=4): for _ in range(times): c()
Fix vx.expose to not crash when None,None is passed
Fix vx.expose to not crash when None,None is passed Also reformat it using functools.partial
Python
mit
philipdexter/vx,philipdexter/vx
--- +++ @@ -1,15 +1,14 @@ import vx +from functools import partial + def _expose(f=None, name=None): + if f is None: + return partial(_expose, name=name) if name is None: name = f.__name__.lstrip('_') if getattr(vx, name, None) is not None: raise AttributeError("Cannot expose duplicate name: '{}'".format(name)) - if f is None: - def g(f): - setattr(vx, name, f) - return f - return g setattr(vx, name, f) return f vx.expose = _expose
8cba7a1af5b590639dbba429a4e9eba3fb5898d8
Tools/bmtest.py
Tools/bmtest.py
import chessmoves # Source: https://github.com/kervinck/floyd.git import floyd as engine import sys def parseEpd(rawLine): # 4-field FEN line = rawLine.strip().split(' ', 4) pos = ' '.join(line[0:4]) # EPD fields operations = {'bm': '', 'am': ''} fields = [op for op in line[4].split(';') if len(op) > 0] fields = [op.strip().split(' ', 1) for op in fields] operations.update(dict(fields)) return pos, operations nrPassed = 0 nrTests = 0 movetime = float(sys.argv[1]) for rawLine in sys.stdin: print rawLine, nrTests += 1 pos, operations = parseEpd(rawLine) bm = [chessmoves.move(pos, bm, notation='uci')[0] for bm in operations['bm'].split()] # best move am = [chessmoves.move(pos, am, notation='uci')[0] for am in operations['am'].split()] # avoid move score, move = engine.search(pos, movetime=movetime, info='uci') print 'bestmove', move print 'test', if (len(bm) == 0 or move in bm) and\ (len(am) == 0 or move not in am): print 'result OK', nrPassed += 1 else: print 'result FAILED', print 'passed %d total %d' % (nrPassed, nrTests) print
import chessmoves # Source: https://github.com/kervinck/chessmoves.git import floyd as engine import sys def parseEpd(rawLine): # 4-field FEN line = rawLine.strip().split(' ', 4) pos = ' '.join(line[0:4]) # EPD fields operations = {'bm': '', 'am': ''} fields = [op for op in line[4].split(';') if len(op) > 0] fields = [op.strip().split(' ', 1) for op in fields] operations.update(dict(fields)) return pos, operations nrPassed = 0 nrTests = 0 movetime = float(sys.argv[1]) for rawLine in sys.stdin: print rawLine, nrTests += 1 pos, operations = parseEpd(rawLine) bm = [chessmoves.move(pos, bm, notation='uci')[0] for bm in operations['bm'].split()] # best move am = [chessmoves.move(pos, am, notation='uci')[0] for am in operations['am'].split()] # avoid move score, move = engine.search(pos, movetime=movetime, info='uci') print 'bestmove', move print 'test', if (len(bm) == 0 or move in bm) and\ (len(am) == 0 or move not in am): print 'result OK', nrPassed += 1 else: print 'result FAILED', print 'passed %d total %d' % (nrPassed, nrTests) print
Correct github URL for chessmoves module
Correct github URL for chessmoves module
Python
bsd-2-clause
kervinck/floyd,kervinck/floyd,kervinck/floyd,kervinck/floyd
--- +++ @@ -1,5 +1,5 @@ -import chessmoves # Source: https://github.com/kervinck/floyd.git +import chessmoves # Source: https://github.com/kervinck/chessmoves.git import floyd as engine import sys
f40f951a52c6c19108224d306f0e173465d0054d
scripts/pycodestyle_on_repo.py
scripts/pycodestyle_on_repo.py
# Copyright 2016 Google Inc. # # 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. """Custom script to run pycodestyle on google-cloud codebase. This runs pycodestyle as a script via subprocess but only runs it on the .py files that are checked in to the repository. """ import os import subprocess import sys def main(): """Run pycodestyle on all Python files in the repository.""" git_root = subprocess.check_output( ['git', 'rev-parse', '--show-toplevel']).strip() os.chdir(git_root) python_files = subprocess.check_output(['git', 'ls-files', '*py']) python_files = python_files.strip().split() pycodestyle_command = ['pycodestyle'] + python_files status_code = subprocess.call(pycodestyle_command) sys.exit(status_code) if __name__ == '__main__': main()
# Copyright 2016 Google Inc. # # 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. """Custom script to run pycodestyle on google-cloud codebase. This runs pycodestyle as a script via subprocess but only runs it on the .py files that are checked in to the repository. """ import os import subprocess import sys from run_pylint import get_files_for_linting def main(): """Run pycodestyle on all Python files in the repository.""" git_root = subprocess.check_output( ['git', 'rev-parse', '--show-toplevel']).strip() os.chdir(git_root) candidates, _ = get_files_for_linting() python_files = [ candidate for candidate in candidates if candidate.endswith('.py')] pycodestyle_command = ['pycodestyle'] + python_files status_code = subprocess.call(pycodestyle_command) sys.exit(status_code) if __name__ == '__main__': main()
Use 'diff_base' for pycodestyle check, if set.
Use 'diff_base' for pycodestyle check, if set. Speeds it up, plus reduces spew when testing locally.
Python
apache-2.0
jonparrott/google-cloud-python,googleapis/google-cloud-python,tswast/google-cloud-python,Fkawala/gcloud-python,googleapis/google-cloud-python,tartavull/google-cloud-python,tseaver/google-cloud-python,Fkawala/gcloud-python,dhermes/google-cloud-python,calpeyser/google-cloud-python,calpeyser/google-cloud-python,quom/google-cloud-python,quom/google-cloud-python,tseaver/google-cloud-python,tseaver/google-cloud-python,jonparrott/gcloud-python,tseaver/gcloud-python,jgeewax/gcloud-python,tseaver/gcloud-python,tartavull/google-cloud-python,tswast/google-cloud-python,jgeewax/gcloud-python,jonparrott/google-cloud-python,dhermes/google-cloud-python,GoogleCloudPlatform/gcloud-python,dhermes/google-cloud-python,daspecster/google-cloud-python,dhermes/gcloud-python,tswast/google-cloud-python,jonparrott/gcloud-python,daspecster/google-cloud-python,GoogleCloudPlatform/gcloud-python,dhermes/gcloud-python
--- +++ @@ -23,14 +23,17 @@ import subprocess import sys +from run_pylint import get_files_for_linting + def main(): """Run pycodestyle on all Python files in the repository.""" git_root = subprocess.check_output( ['git', 'rev-parse', '--show-toplevel']).strip() os.chdir(git_root) - python_files = subprocess.check_output(['git', 'ls-files', '*py']) - python_files = python_files.strip().split() + candidates, _ = get_files_for_linting() + python_files = [ + candidate for candidate in candidates if candidate.endswith('.py')] pycodestyle_command = ['pycodestyle'] + python_files status_code = subprocess.call(pycodestyle_command)
24eb92088115a4cd583a3dc759083ff295db3135
website/jdpages/signals.py
website/jdpages/signals.py
import logging logger = logging.getLogger(__name__) from django.contrib.contenttypes.models import ContentType from django.db.models.signals import post_save from django.dispatch import receiver from mezzanine.blog.models import BlogCategory from website.jdpages.models import ColumnElement @receiver(post_save) def post_save_callback(sender, instance, created, **kwargs): """ Called after a model instance is saved. Created related database objects for some Arguments: sender -- the model class instance -- the actual instance being saved created -- a boolean; True if a new record was created """ if not created: return if sender == BlogCategory: if ColumnElement.objects.filter(object_id=instance.id, content_type=ContentType.objects.get_for_model(sender)): return blog_category = instance blog_category_element = ColumnElement() blog_category_element.title = blog_category.title blog_category_element.content_type = ContentType.objects.get_for_model(BlogCategory) blog_category_element.object_id = blog_category.id blog_category_element.save() blog_category_element.site_id = instance.site_id blog_category_element.save(update_site=False) return
import logging logger = logging.getLogger(__name__) from django.contrib.contenttypes.models import ContentType from django.db.models.signals import post_save, pre_delete from django.dispatch import receiver from mezzanine.blog.models import BlogCategory from website.jdpages.models import ColumnElement @receiver(post_save) def post_save_callback(sender, instance, created, **kwargs): """ Called after a model instance is saved. Create related models here. Arguments: sender -- the model class instance -- the actual instance being saved created -- a boolean; True if a new record was created """ if not created: return if sender == BlogCategory: if ColumnElement.objects.filter(object_id=instance.id, content_type=ContentType.objects.get_for_model(sender)): return blog_category = instance blog_category_element = ColumnElement() blog_category_element.title = blog_category.title blog_category_element.content_type = ContentType.objects.get_for_model(BlogCategory) blog_category_element.object_id = blog_category.id blog_category_element.save() blog_category_element.site_id = instance.site_id blog_category_element.save(update_site=False) return @receiver(pre_delete) def pre_delete_callback(sender, instance, **kwargs): """ Called just before a model is deleted. Delete related models here. Arguments: sender -- the model class instance -- the actual instance being saved """ if sender == BlogCategory: related_elements = ColumnElement.objects.filter(object_id=instance.id, content_type=ContentType.objects.get_for_model(sender)) if related_elements: for element in related_elements: element.delete() return
Delete the related ColumnElement when a BlogCategory is deleted.
Delete the related ColumnElement when a BlogCategory is deleted.
Python
mit
jonge-democraten/website,jonge-democraten/website,jonge-democraten/website,jonge-democraten/website
--- +++ @@ -2,7 +2,7 @@ logger = logging.getLogger(__name__) from django.contrib.contenttypes.models import ContentType -from django.db.models.signals import post_save +from django.db.models.signals import post_save, pre_delete from django.dispatch import receiver from mezzanine.blog.models import BlogCategory @@ -14,7 +14,7 @@ def post_save_callback(sender, instance, created, **kwargs): """ Called after a model instance is saved. - Created related database objects for some + Create related models here. Arguments: sender -- the model class instance -- the actual instance being saved @@ -34,3 +34,19 @@ blog_category_element.site_id = instance.site_id blog_category_element.save(update_site=False) return + +@receiver(pre_delete) +def pre_delete_callback(sender, instance, **kwargs): + """ + Called just before a model is deleted. + Delete related models here. + Arguments: + sender -- the model class + instance -- the actual instance being saved + """ + if sender == BlogCategory: + related_elements = ColumnElement.objects.filter(object_id=instance.id, content_type=ContentType.objects.get_for_model(sender)) + if related_elements: + for element in related_elements: + element.delete() + return
9afa5b8b2fe2a5236337346a6f677a04863b82c7
salt/output/__init__.py
salt/output/__init__.py
''' Used to manage the outputter system. This package is the modular system used for managing outputters. ''' # Import salt utils import salt.loader def display_output(data, out, opts=None): ''' Print the passed data using the desired output ''' if opts is None: opts = {} if not 'color' in opts: opts['color'] = not bool(opts.get('no_color', False)) outputters = salt.loader.outputters(opts) if not out in outputters: outputters['pprint'](data) outputters[out](data) def get_printout(out, opts=None, **kwargs): ''' Return a printer function ''' if opts is None: opts = {} opts.update(kwargs) if not 'color' in opts: opts['color'] = not bool(opts.get('no_color', False)) outputters = salt.loader.outputters(opts) if not out in outputters: return None return outputters[out]
''' Used to manage the outputter system. This package is the modular system used for managing outputters. ''' # Import salt utils import salt.loader def display_output(data, out, opts=None): ''' Print the passed data using the desired output ''' get_printout(out, opts)(data) def get_printout(out, opts=None, **kwargs): ''' Return a printer function ''' if out.endswith('_out'): out = out[:-4] if opts is None: opts = {} opts.update(kwargs) if not 'color' in opts: opts['color'] = not bool(opts.get('no_color', False)) outputters = salt.loader.outputters(opts) if not out in outputters: return None return outputters[out]
Fix issue where interfaces pass in _out
Fix issue where interfaces pass in _out
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
--- +++ @@ -11,20 +11,15 @@ ''' Print the passed data using the desired output ''' - if opts is None: - opts = {} - if not 'color' in opts: - opts['color'] = not bool(opts.get('no_color', False)) - outputters = salt.loader.outputters(opts) - if not out in outputters: - outputters['pprint'](data) - outputters[out](data) + get_printout(out, opts)(data) def get_printout(out, opts=None, **kwargs): ''' Return a printer function ''' + if out.endswith('_out'): + out = out[:-4] if opts is None: opts = {} opts.update(kwargs)
64bd4ea8a4b04ce1c65375ad3c7776a1583b7294
crypto-square/crypto_square.py
crypto-square/crypto_square.py
import math def encode(s): s = list(filter(str.isalnum, s.lower())) size = math.ceil(math.sqrt(len(s))) s += "." * (size**2 - len(s)) parts = [s[i*size:(i+1)*size] for i in range(size)] return " ".join(map("".join, zip(*parts))).replace(".", "")
import math def encode(s): s = "".join(filter(str.isalnum, s.lower())) size = math.ceil(math.sqrt(len(s))) return " ".join(s[i::size] for i in range(size))
Use string slices with a stride
Use string slices with a stride
Python
agpl-3.0
CubicComet/exercism-python-solutions
--- +++ @@ -2,8 +2,6 @@ def encode(s): - s = list(filter(str.isalnum, s.lower())) + s = "".join(filter(str.isalnum, s.lower())) size = math.ceil(math.sqrt(len(s))) - s += "." * (size**2 - len(s)) - parts = [s[i*size:(i+1)*size] for i in range(size)] - return " ".join(map("".join, zip(*parts))).replace(".", "") + return " ".join(s[i::size] for i in range(size))
c4f0f13892f1a1af73a94e6cbea95d30e676203c
xorgauth/accounts/views.py
xorgauth/accounts/views.py
from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.shortcuts import render from django.views.generic import TemplateView from oidc_provider.models import UserConsent, Client @login_required def list_consents(request): # if a revoke request was done, process it revoke = request.POST.get('revoke', None) if revoke is not None: consent = UserConsent.objects.filter(user=request.user, client__client_id=revoke) if consent: revoked_client = consent[0].client consent[0].delete() messages.success(request, "Successfully revoked consent for client \"{}\"".format(revoked_client.name)) else: client = Client.objects.filter(client_id=revoke) if client: messages.error(request, "You have no consent for client \"{}\".".format(client[0].name)) else: messages.error(request, "Unknown client.") # render the result consents = UserConsent.objects.filter(user=request.user) return render(request, 'list_consents.html', { 'consents': consents }) class ProfileView(TemplateView, LoginRequiredMixin): template_name = 'profile.html'
from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.shortcuts import render from django.views.generic import TemplateView from oidc_provider.models import UserConsent, Client @login_required def list_consents(request): # if a revoke request was done, process it revoke = request.POST.get('revoke', None) if revoke is not None: consent = UserConsent.objects.filter(user=request.user, client__client_id=revoke) if consent: revoked_client = consent[0].client consent[0].delete() messages.success(request, "Successfully revoked consent for client \"{}\"".format(revoked_client.name)) else: client = Client.objects.filter(client_id=revoke) if client: messages.error(request, "You have no consent for client \"{}\".".format(client[0].name)) else: messages.error(request, "Unknown client.") # render the result consents = UserConsent.objects.filter(user=request.user) return render(request, 'list_consents.html', { 'consents': consents }) class ProfileView(LoginRequiredMixin, TemplateView): template_name = 'profile.html'
Fix access restriction to /accounts/profile/
Fix access restriction to /accounts/profile/ LoginRequiredMixin needs to come first for it to be applied. Otherwise, /accounts/profile/ is accessible even when the user is not authenticated.
Python
agpl-3.0
Polytechnique-org/xorgauth,Polytechnique-org/xorgauth
--- +++ @@ -30,5 +30,5 @@ }) -class ProfileView(TemplateView, LoginRequiredMixin): +class ProfileView(LoginRequiredMixin, TemplateView): template_name = 'profile.html'
f0ceb7d9372766d9b1e55d619b8e05aee5950fb2
tests/matchers/test_boolean.py
tests/matchers/test_boolean.py
from robber import expect from robber.matchers.boolean import TrueMatcher, FalseMatcher class TestTrueMatcher: def test_matches(self): expect(TrueMatcher(True).matches()).to.eq(True) expect(TrueMatcher(False).matches()).to.eq(False) def test_failure_message(self): true = TrueMatcher(False) message = true.failure_message() expect(message) == 'Expected False to be True' def test_failure_message_with_not_to(self): true = TrueMatcher(True, is_negated=True) message = true.failure_message() expect(message) == 'Expected True not to be True' def test_register(self): expect(expect.matcher('true')) == TrueMatcher class TestFalseMatcher: def test_matches(self): expect(FalseMatcher(False).matches()).to.eq(True) expect(FalseMatcher(True).matches()).to.eq(False) def test_failure_message(self): false = FalseMatcher(True) message = false.failure_message() expect(message) == 'Expected True to be False' def test_failure_message_with_not_to(self): false = FalseMatcher(False, is_negated=True) message = false.failure_message() expect(message) == 'Expected False not to be False' def test_register(self): expect(expect.matcher('false')) == FalseMatcher
from robber import expect from robber.matchers.boolean import TrueMatcher, FalseMatcher class TestTrueMatcher: def test_matches(self): expect(TrueMatcher(True).matches()).to.eq(True) expect(TrueMatcher(False).matches()).to.eq(False) def test_failure_message(self): true = TrueMatcher(False) message = true.failure_message() expect(message) == 'Expected False to be True' def test_failure_message_with_not_to(self): true = TrueMatcher(True, is_negated=True) message = true.failure_message() expect(message) == 'Expected True not to be True' def test_failure_message_with_not_to(self): true = TrueMatcher(True, is_negated=True) message = true.failure_message() expect(message) == 'Expected True not to be True' def test_register(self): expect(expect.matcher('true')) == TrueMatcher class TestFalseMatcher: def test_matches(self): expect(FalseMatcher(False).matches()).to.eq(True) expect(FalseMatcher(True).matches()).to.eq(False) def test_failure_message(self): false = FalseMatcher(True) message = false.failure_message() expect(message) == 'Expected True to be False' def test_failure_message_with_not_to(self): false = FalseMatcher(False, is_negated=True) message = false.failure_message() expect(message) == 'Expected False not to be False' def test_register(self): expect(expect.matcher('false')) == FalseMatcher
Add failure message test for not_to.be.true()
[f] Add failure message test for not_to.be.true()
Python
mit
vesln/robber.py
--- +++ @@ -11,6 +11,11 @@ true = TrueMatcher(False) message = true.failure_message() expect(message) == 'Expected False to be True' + + def test_failure_message_with_not_to(self): + true = TrueMatcher(True, is_negated=True) + message = true.failure_message() + expect(message) == 'Expected True not to be True' def test_failure_message_with_not_to(self): true = TrueMatcher(True, is_negated=True)
c65e2b3bb2d43a5d12d50cf79636e94a6a1f1dc5
Algo.py
Algo.py
# # Copyright (c) 2016, Gabriel Linder <linder.gabriel@gmail.com> # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH # REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY # AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, # INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM # LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR # OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR # PERFORMANCE OF THIS SOFTWARE. # from abc import ABC, abstractmethod from Color import RandomColor class Algo(ABC): def __init__(self, population_size): self.population_size = population_size self.set_random_population() def set_random_population(self): self.population = [] for i in range(self.population_size): self.population.append(RandomColor()) def dump(self): for color in self.population: print('{} '.format(color), end='') print(flush=True) @abstractmethod def tick(self, deltas): pass
# # Copyright (c) 2016, Gabriel Linder <linder.gabriel@gmail.com> # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH # REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY # AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, # INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM # LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR # OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR # PERFORMANCE OF THIS SOFTWARE. # from abc import ABC, abstractmethod from Color import RandomColor class Algo(ABC): def __init__(self, population_size): assert population_size % 2 == 0 self.half_population_size = population_size // 2 self.population_size = population_size self.set_random_population() def set_random_population(self): self.population = [] for i in range(self.population_size): self.population.append(RandomColor()) def dump(self): for color in self.population: print('{} '.format(color), end='') print(flush=True) @abstractmethod def tick(self, deltas): pass
Check that population_size is even, and set half_population_size.
Check that population_size is even, and set half_population_size. This will be used by genetic algorithms.
Python
isc
dargor/python-guess-random-color,dargor/python-guess-random-color
--- +++ @@ -22,7 +22,12 @@ class Algo(ABC): def __init__(self, population_size): + + assert population_size % 2 == 0 + + self.half_population_size = population_size // 2 self.population_size = population_size + self.set_random_population() def set_random_population(self):
f80b9f42db599e0416bd4e28f69c81e0fda494d2
todoist/managers/generic.py
todoist/managers/generic.py
# -*- coding: utf-8 -*- class Manager(object): # should be re-defined in a subclass state_name = None object_type = None def __init__(self, api): self.api = api # shortcuts @property def state(self): return self.api.state @property def queue(self): return self.api.queue @property def token(self): return self.api.token class AllMixin(object): def all(self, filt=None): return list(filter(filt, self.state[self.state_name])) class GetByIdMixin(object): def get_by_id(self, obj_id, only_local=False): """ Finds and returns the object based on its id. """ for obj in self.state[self.state_name]: if obj['id'] == obj_id or obj.temp_id == str(obj_id): return obj if not only_local and self.object_type is not None: getter = getattr(eval('self.api.%ss' % self.object_type), 'get') return getter(obj_id) return None class SyncMixin(object): """ Syncs this specific type of objects. """ def sync(self): return self.api.sync()
# -*- coding: utf-8 -*- class Manager(object): # should be re-defined in a subclass state_name = None object_type = None def __init__(self, api): self.api = api # shortcuts @property def state(self): return self.api.state @property def queue(self): return self.api.queue @property def token(self): return self.api.token class AllMixin(object): def all(self, filt=None): return list(filter(filt, self.state[self.state_name])) class GetByIdMixin(object): def get_by_id(self, obj_id, only_local=False): """ Finds and returns the object based on its id. """ for obj in self.state[self.state_name]: if obj['id'] == obj_id or obj.temp_id == str(obj_id): return obj if not only_local and self.object_type is not None: getter = getattr(eval('self.api.%ss' % self.object_type), 'get') data = getter(obj_id) # retrieves from state, otherwise we return the raw data for obj in self.state[self.state_name]: if obj['id'] == obj_id or obj.temp_id == str(obj_id): return obj return data return None class SyncMixin(object): """ Syncs this specific type of objects. """ def sync(self): return self.api.sync()
Fix the case of using `get_by_id` when there's not state
Fix the case of using `get_by_id` when there's not state Previous to this commit, if there's no state we would return raw data, which would break object chaining. Now we check the state one last time before giving up and returning the raw data because it may have been populated by methods like `get_by_id` (instead of sync())
Python
mit
Doist/todoist-python
--- +++ @@ -38,7 +38,14 @@ if not only_local and self.object_type is not None: getter = getattr(eval('self.api.%ss' % self.object_type), 'get') - return getter(obj_id) + data = getter(obj_id) + + # retrieves from state, otherwise we return the raw data + for obj in self.state[self.state_name]: + if obj['id'] == obj_id or obj.temp_id == str(obj_id): + return obj + + return data return None
6a34e0adb5128e4a46be26e9afa08cc9cd691be7
actionizer.py
actionizer.py
#! /usr/bin/python import numpy as np import os from sklearn import datasets MESSAGES_DIR = "data/messages/" JUDGMENTS_PATH = "data/judgments/judgments.txt" def load_messages(): messages = [] for filename in os.listdir(MESSAGES_DIR): with open(MESSAGES_DIR + filename) as message_file: messages.append(message_file.read()) return messages def tfidf(documents): # TODO: Stub implementation return [[]] def load_judgments(): judgments = [] with open(JUDGMENTS_PATH) as judgments_file: for line in judgments_file: judgments.append(1 if len(line.split()) > 2 else 0) return judgments def main(): messages = load_messages() target = load_judgments() print target data = tfidf(messages) if __name__ == "__main__": main()
#! /usr/bin/python import numpy as np import os from sklearn import datasets from sklearn.naive_bayes import GaussianNB from sklearn.metrics import classification_report MESSAGES_DIR = "data/messages/" JUDGMENTS_PATH = "data/judgments/judgments.txt" def load_messages(): messages = [] for filename in os.listdir(MESSAGES_DIR): with open(MESSAGES_DIR + filename) as message_file: messages.append(message_file.read()) return messages def bag_of_words(documents): tokens = set() # Go through all the documents and collect all of the unique tokens for document in documents: for token in document.split(): tokens.add(token) # Create an empty dense matrix with one row for every document and one column for every token mat = np.zeros((len(documents), len(tokens))) # Convert tokens from a set to a list so that we can grab the index of a token from the set tokens = list(tokens) # Go through all the documents again and count the frequency of each token for row, document in enumerate(documents): for token in document.split(): col = tokens.index(token) mat[row][col] += 1 return mat def tfidf(data): # TODO: Stub implementation return data def load_judgments(): judgments = [] with open(JUDGMENTS_PATH) as judgments_file: for line in judgments_file: judgments.append(1 if len(line.split()) > 2 else 0) return judgments def main(): messages = load_messages() target = load_judgments() data = bag_of_words(messages) print data print target #data = tfidf(data) # Gaussian Naive Bayes Classifier gnb = GaussianNB() predictions = gnb.fit(data, target).predict(data) print classification_report(target, predictions, target_names=["No action", "Action"]) if __name__ == "__main__": main()
Add bag of words representation and simple naive bayes classification
Add bag of words representation and simple naive bayes classification
Python
mit
chiubaka/actionizer
--- +++ @@ -3,6 +3,8 @@ import numpy as np import os from sklearn import datasets +from sklearn.naive_bayes import GaussianNB +from sklearn.metrics import classification_report MESSAGES_DIR = "data/messages/" JUDGMENTS_PATH = "data/judgments/judgments.txt" @@ -15,9 +17,30 @@ return messages -def tfidf(documents): +def bag_of_words(documents): + tokens = set() + # Go through all the documents and collect all of the unique tokens + for document in documents: + for token in document.split(): + tokens.add(token) + + # Create an empty dense matrix with one row for every document and one column for every token + mat = np.zeros((len(documents), len(tokens))) + + # Convert tokens from a set to a list so that we can grab the index of a token from the set + tokens = list(tokens) + + # Go through all the documents again and count the frequency of each token + for row, document in enumerate(documents): + for token in document.split(): + col = tokens.index(token) + mat[row][col] += 1 + + return mat + +def tfidf(data): # TODO: Stub implementation - return [[]] + return data def load_judgments(): judgments = [] @@ -30,8 +53,15 @@ def main(): messages = load_messages() target = load_judgments() + data = bag_of_words(messages) + print data print target - data = tfidf(messages) + #data = tfidf(data) + + # Gaussian Naive Bayes Classifier + gnb = GaussianNB() + predictions = gnb.fit(data, target).predict(data) + print classification_report(target, predictions, target_names=["No action", "Action"]) if __name__ == "__main__": main()
9c923b8a94ea534c5b18983e81add7301a1dfa66
waterbutler/core/streams/file.py
waterbutler/core/streams/file.py
import os from waterbutler.core.streams import BaseStream class FileStreamReader(BaseStream): def __init__(self, file_pointer): super().__init__() self.file_gen = None self.file_pointer = file_pointer self.read_size = None self.content_type = 'application/octet-stream' @property def size(self): cursor = self.file_pointer.tell() self.file_pointer.seek(0, os.SEEK_END) ret = self.file_pointer.tell() self.file_pointer.seek(cursor) return ret def close(self): self.file_pointer.close() self.feed_eof() def read_as_gen(self): self.file_pointer.seek(0) while True: chunk = self.file_pointer.read(self.read_size) if not chunk: self.feed_eof() chunk = b'' yield chunk async def _read(self, size): self.file_gen = self.file_gen or self.read_as_gen() self.read_size = size return next(self.file_gen)
import os # import asyncio from waterbutler.core.streams import BaseStream class FileStreamReader(BaseStream): def __init__(self, file_pointer): super().__init__() self.file_gen = None self.file_pointer = file_pointer self.read_size = None self.content_type = 'application/octet-stream' @property def size(self): cursor = self.file_pointer.tell() self.file_pointer.seek(0, os.SEEK_END) ret = self.file_pointer.tell() self.file_pointer.seek(cursor) return ret def close(self): self.file_pointer.close() self.feed_eof() class read_chunks: def __init__(self, read_size, fp): self.done = False self.read_size = read_size self.fp = fp async def __aiter__(self): return self async def __anext__(self): if self.done: raise StopAsyncIteration return await self.get_chunk() async def get_chunk(self): while True: chunk = self.fp.read(self.read_size) if not chunk: chunk = b'' self.done = True return chunk async def _read(self, read_size): async for chunk in self.read_chunks(read_size, self.file_pointer): if chunk == b'': self.feed_eof() return chunk
Update FileStreamReader to use async generator
Update FileStreamReader to use async generator
Python
apache-2.0
RCOSDP/waterbutler,TomBaxter/waterbutler,rdhyee/waterbutler,CenterForOpenScience/waterbutler,felliott/waterbutler,Johnetordoff/waterbutler
--- +++ @@ -1,4 +1,5 @@ import os +# import asyncio from waterbutler.core.streams import BaseStream @@ -24,16 +25,30 @@ self.file_pointer.close() self.feed_eof() - def read_as_gen(self): - self.file_pointer.seek(0) - while True: - chunk = self.file_pointer.read(self.read_size) - if not chunk: + class read_chunks: + def __init__(self, read_size, fp): + self.done = False + self.read_size = read_size + self.fp = fp + + async def __aiter__(self): + return self + + async def __anext__(self): + if self.done: + raise StopAsyncIteration + return await self.get_chunk() + + async def get_chunk(self): + while True: + chunk = self.fp.read(self.read_size) + if not chunk: + chunk = b'' + self.done = True + return chunk + + async def _read(self, read_size): + async for chunk in self.read_chunks(read_size, self.file_pointer): + if chunk == b'': self.feed_eof() - chunk = b'' - yield chunk - - async def _read(self, size): - self.file_gen = self.file_gen or self.read_as_gen() - self.read_size = size - return next(self.file_gen) + return chunk
26b9bed4148cd4085009884df66c7bf9bd09ec00
topaz/tools/make_release.py
topaz/tools/make_release.py
import os import sys import tarfile PROJECT_ROOT = os.path.join(os.path.dirname(__file__), os.path.pardir, os.path.pardir) def main(argv): target = argv[0] t = tarfile.open(target, mode="w") for name in [ "bin/topaz", "lib-ruby", "AUTHORS.rst", "LICENSE", "README.rst" ]: t.add(os.path.join(PROJECT_ROOT, name), arcname="topaz/%s" % name) t.add( os.path.join(PROJECT_ROOT, "docs"), "topaz/docs", filter=lambda info: info if "_build" not in info.name else None ) t.close() if __name__ == "__main__": main(sys.argv[1:])
import os import sys import tarfile PROJECT_ROOT = os.path.join(os.path.dirname(__file__), os.path.pardir, os.path.pardir) def main(argv): target = argv[0] t = tarfile.open(target, mode="w:bz2") for name in [ "bin/topaz", "lib-ruby", "AUTHORS.rst", "LICENSE", "README.rst" ]: t.add(os.path.join(PROJECT_ROOT, name), arcname="topaz/%s" % name) t.add( os.path.join(PROJECT_ROOT, "docs"), "topaz/docs", filter=lambda info: info if "_build" not in info.name else None ) t.close() if __name__ == "__main__": main(sys.argv[1:])
Make a bz2 for the release.
Make a bz2 for the release.
Python
bsd-3-clause
topazproject/topaz,babelsberg/babelsberg-r,topazproject/topaz,topazproject/topaz,kachick/topaz,babelsberg/babelsberg-r,babelsberg/babelsberg-r,kachick/topaz,babelsberg/babelsberg-r,babelsberg/babelsberg-r,topazproject/topaz,kachick/topaz
--- +++ @@ -8,7 +8,7 @@ def main(argv): target = argv[0] - t = tarfile.open(target, mode="w") + t = tarfile.open(target, mode="w:bz2") for name in [ "bin/topaz", "lib-ruby",
cf89df9f0c45134b02879781223f9baff77c99d8
website/addons/forward/routes.py
website/addons/forward/routes.py
# -*- coding: utf-8 -*- """Forward addon routes.""" from framework.routing import Rule, json_renderer from website.routes import OsfWebRenderer from website.addons.forward import views api_routes = { 'rules': [ Rule( [ '/project/<pid>/forward/config/', '/project/<pid>/node/<nid>/forward/config/' ], 'get', views.config.forward_config_get, json_renderer, ), Rule( [ '/project/<pid>/forward/config/', '/project/<pid>/node/<nid>/forward/config/' ], 'put', views.config.forward_config_put, json_renderer, ), Rule( [ '/project/<pid>/forward/widget/', '/project/<pid>/node/<nid>forward/widget/', ], 'get', views.widget.forward_widget, OsfWebRenderer('../addons/forward/templates/forward_widget.mako'), ) ], 'prefix': '/api/v1', }
# -*- coding: utf-8 -*- """Forward addon routes.""" from framework.routing import Rule, json_renderer from website.routes import OsfWebRenderer from website.addons.forward import views api_routes = { 'rules': [ Rule( [ '/project/<pid>/forward/config/', '/project/<pid>/node/<nid>/forward/config/' ], 'get', views.config.forward_config_get, json_renderer, ), Rule( [ '/project/<pid>/forward/config/', '/project/<pid>/node/<nid>/forward/config/' ], 'put', views.config.forward_config_put, json_renderer, ), Rule( [ '/project/<pid>/forward/widget/', '/project/<pid>/node/<nid>/forward/widget/', ], 'get', views.widget.forward_widget, OsfWebRenderer('../addons/forward/templates/forward_widget.mako'), ) ], 'prefix': '/api/v1', }
Add missing slash so that Forward config error is rendered properly
Add missing slash so that Forward config error is rendered properly Closes centerforopenscience/openscienceframework.org#941
Python
apache-2.0
baylee-d/osf.io,himanshuo/osf.io,baylee-d/osf.io,felliott/osf.io,MerlinZhang/osf.io,HarryRybacki/osf.io,hmoco/osf.io,brianjgeiger/osf.io,caseyrygt/osf.io,ckc6cz/osf.io,petermalcolm/osf.io,adlius/osf.io,RomanZWang/osf.io,himanshuo/osf.io,mluo613/osf.io,chennan47/osf.io,Nesiehr/osf.io,emetsger/osf.io,sloria/osf.io,aaxelb/osf.io,GaryKriebel/osf.io,TomBaxter/osf.io,reinaH/osf.io,TomBaxter/osf.io,reinaH/osf.io,Nesiehr/osf.io,DanielSBrown/osf.io,leb2dg/osf.io,icereval/osf.io,chrisseto/osf.io,ticklemepierce/osf.io,TomHeatwole/osf.io,monikagrabowska/osf.io,GageGaskins/osf.io,jeffreyliu3230/osf.io,njantrania/osf.io,wearpants/osf.io,doublebits/osf.io,brandonPurvis/osf.io,pattisdr/osf.io,kwierman/osf.io,ZobairAlijan/osf.io,zamattiac/osf.io,zkraime/osf.io,mfraezz/osf.io,petermalcolm/osf.io,GageGaskins/osf.io,ckc6cz/osf.io,alexschiller/osf.io,haoyuchen1992/osf.io,chrisseto/osf.io,cwisecarver/osf.io,samchrisinger/osf.io,TomHeatwole/osf.io,reinaH/osf.io,KAsante95/osf.io,lyndsysimon/osf.io,revanthkolli/osf.io,MerlinZhang/osf.io,felliott/osf.io,jeffreyliu3230/osf.io,brandonPurvis/osf.io,jinluyuan/osf.io,caseyrollins/osf.io,laurenrevere/osf.io,HalcyonChimera/osf.io,zamattiac/osf.io,monikagrabowska/osf.io,brandonPurvis/osf.io,kwierman/osf.io,himanshuo/osf.io,hmoco/osf.io,danielneis/osf.io,ticklemepierce/osf.io,RomanZWang/osf.io,caseyrollins/osf.io,KAsante95/osf.io,erinspace/osf.io,brianjgeiger/osf.io,monikagrabowska/osf.io,mluo613/osf.io,zkraime/osf.io,KAsante95/osf.io,kch8qx/osf.io,adlius/osf.io,himanshuo/osf.io,mluke93/osf.io,baylee-d/osf.io,GageGaskins/osf.io,rdhyee/osf.io,CenterForOpenScience/osf.io,HalcyonChimera/osf.io,acshi/osf.io,Johnetordoff/osf.io,HarryRybacki/osf.io,RomanZWang/osf.io,abought/osf.io,HarryRybacki/osf.io,billyhunt/osf.io,mfraezz/osf.io,jnayak1/osf.io,sloria/osf.io,zachjanicki/osf.io,adlius/osf.io,samchrisinger/osf.io,brandonPurvis/osf.io,jeffreyliu3230/osf.io,danielneis/osf.io,GaryKriebel/osf.io,jmcarp/osf.io,arpitar/osf.io,danielneis/osf.io,abought/osf.io,KAsante95/osf.io,caneruguz/osf.io,aaxelb/osf.io,monikagrabowska/osf.io,samchrisinger/osf.io,fabianvf/osf.io,jmcarp/osf.io,laurenrevere/osf.io,TomHeatwole/osf.io,RomanZWang/osf.io,cldershem/osf.io,kwierman/osf.io,Nesiehr/osf.io,lamdnhan/osf.io,mluo613/osf.io,caseyrygt/osf.io,caseyrygt/osf.io,jinluyuan/osf.io,revanthkolli/osf.io,abought/osf.io,mfraezz/osf.io,cosenal/osf.io,samanehsan/osf.io,TomHeatwole/osf.io,samchrisinger/osf.io,kch8qx/osf.io,mluke93/osf.io,leb2dg/osf.io,acshi/osf.io,mluke93/osf.io,leb2dg/osf.io,kushG/osf.io,samanehsan/osf.io,ticklemepierce/osf.io,saradbowman/osf.io,HalcyonChimera/osf.io,zachjanicki/osf.io,ZobairAlijan/osf.io,felliott/osf.io,brianjgeiger/osf.io,acshi/osf.io,billyhunt/osf.io,bdyetton/prettychart,billyhunt/osf.io,lamdnhan/osf.io,crcresearch/osf.io,revanthkolli/osf.io,SSJohns/osf.io,ticklemepierce/osf.io,DanielSBrown/osf.io,Ghalko/osf.io,KAsante95/osf.io,arpitar/osf.io,haoyuchen1992/osf.io,kushG/osf.io,asanfilippo7/osf.io,arpitar/osf.io,zachjanicki/osf.io,alexschiller/osf.io,binoculars/osf.io,leb2dg/osf.io,jolene-esposito/osf.io,sbt9uc/osf.io,dplorimer/osf,dplorimer/osf,billyhunt/osf.io,zachjanicki/osf.io,ZobairAlijan/osf.io,mluo613/osf.io,emetsger/osf.io,chrisseto/osf.io,CenterForOpenScience/osf.io,Ghalko/osf.io,Ghalko/osf.io,AndrewSallans/osf.io,laurenrevere/osf.io,binoculars/osf.io,barbour-em/osf.io,abought/osf.io,barbour-em/osf.io,brandonPurvis/osf.io,hmoco/osf.io,rdhyee/osf.io,caseyrygt/osf.io,jnayak1/osf.io,fabianvf/osf.io,HalcyonChimera/osf.io,jnayak1/osf.io,reinaH/osf.io,sbt9uc/osf.io,kch8qx/osf.io,aaxelb/osf.io,icereval/osf.io,zamattiac/osf.io,danielneis/osf.io,monikagrabowska/osf.io,caseyrollins/osf.io,amyshi188/osf.io,fabianvf/osf.io,lyndsysimon/osf.io,erinspace/osf.io,doublebits/osf.io,billyhunt/osf.io,brianjgeiger/osf.io,chennan47/osf.io,erinspace/osf.io,SSJohns/osf.io,jolene-esposito/osf.io,mfraezz/osf.io,cwisecarver/osf.io,haoyuchen1992/osf.io,ckc6cz/osf.io,GaryKriebel/osf.io,kwierman/osf.io,sbt9uc/osf.io,jolene-esposito/osf.io,cosenal/osf.io,amyshi188/osf.io,kch8qx/osf.io,MerlinZhang/osf.io,TomBaxter/osf.io,acshi/osf.io,Nesiehr/osf.io,kch8qx/osf.io,ckc6cz/osf.io,hmoco/osf.io,petermalcolm/osf.io,caneruguz/osf.io,alexschiller/osf.io,GageGaskins/osf.io,njantrania/osf.io,Johnetordoff/osf.io,mluke93/osf.io,cwisecarver/osf.io,cwisecarver/osf.io,caneruguz/osf.io,felliott/osf.io,doublebits/osf.io,njantrania/osf.io,cosenal/osf.io,sloria/osf.io,revanthkolli/osf.io,lyndsysimon/osf.io,asanfilippo7/osf.io,mattclark/osf.io,CenterForOpenScience/osf.io,haoyuchen1992/osf.io,cslzchen/osf.io,Ghalko/osf.io,cldershem/osf.io,doublebits/osf.io,alexschiller/osf.io,SSJohns/osf.io,jinluyuan/osf.io,ZobairAlijan/osf.io,aaxelb/osf.io,sbt9uc/osf.io,pattisdr/osf.io,bdyetton/prettychart,lamdnhan/osf.io,amyshi188/osf.io,jnayak1/osf.io,mattclark/osf.io,acshi/osf.io,cslzchen/osf.io,adlius/osf.io,caneruguz/osf.io,jmcarp/osf.io,SSJohns/osf.io,cslzchen/osf.io,DanielSBrown/osf.io,wearpants/osf.io,petermalcolm/osf.io,dplorimer/osf,jinluyuan/osf.io,cldershem/osf.io,chrisseto/osf.io,GaryKriebel/osf.io,emetsger/osf.io,AndrewSallans/osf.io,dplorimer/osf,GageGaskins/osf.io,Johnetordoff/osf.io,DanielSBrown/osf.io,mattclark/osf.io,bdyetton/prettychart,MerlinZhang/osf.io,mluo613/osf.io,njantrania/osf.io,rdhyee/osf.io,doublebits/osf.io,samanehsan/osf.io,bdyetton/prettychart,amyshi188/osf.io,wearpants/osf.io,saradbowman/osf.io,CenterForOpenScience/osf.io,samanehsan/osf.io,alexschiller/osf.io,asanfilippo7/osf.io,barbour-em/osf.io,crcresearch/osf.io,lamdnhan/osf.io,zkraime/osf.io,cosenal/osf.io,pattisdr/osf.io,jolene-esposito/osf.io,Johnetordoff/osf.io,RomanZWang/osf.io,crcresearch/osf.io,jeffreyliu3230/osf.io,HarryRybacki/osf.io,arpitar/osf.io,cldershem/osf.io,cslzchen/osf.io,binoculars/osf.io,kushG/osf.io,jmcarp/osf.io,wearpants/osf.io,asanfilippo7/osf.io,zkraime/osf.io,emetsger/osf.io,chennan47/osf.io,icereval/osf.io,kushG/osf.io,lyndsysimon/osf.io,barbour-em/osf.io,rdhyee/osf.io,zamattiac/osf.io,fabianvf/osf.io
--- +++ @@ -32,7 +32,7 @@ Rule( [ '/project/<pid>/forward/widget/', - '/project/<pid>/node/<nid>forward/widget/', + '/project/<pid>/node/<nid>/forward/widget/', ], 'get', views.widget.forward_widget,
8e52298adf81e3ac718559a33f4db799e00e8d16
tests/test_scarplet.py
tests/test_scarplet.py
import unittest import dem import WindowedTemplate as wt import filecmp class TemplateMatchingTestCase(unittest.TestCase): def setUp(self): self.dem = dem.DEMGrid('tests/data/synthetic.tif') def test_match_template(self): test_amplitude = dem.BaseSpatialGrid('tests/results/synthetic_amplitude.tif') test_age = dem.BaseSpatialGrid('tests/results/synthetic_age.tif') test_alpha = dem.BaseSpatialGrid('tests/results/synthetic_alpha.tif') template_args = {'alpha' : 0, 'kt' : 1, 'd' : 100 } curv = self.dem._calculate_directional_lacpalcian(alpha) amplitude, age, alpha, snr = scarplet.match_template(curv, wt.Scarp.template_function, template_args) # TODO: refactor into separate tests? with self.subTest(param_grid=amplitude): self.assertTrue(np.equal(param_grid, test_amplitude), "Best-fit amplitudes incorrect") with self.subTest(param_grid=age): self.assertTrue(np.equal(param_grid, test_age), "Best-fit ages incorrect") with self.subTest(param_grid=alpha): self.assertTrue(np.equal(param_grid, test_alpha), "Best-fit orientations incorrect")
Write test for template matching of synthetic scarp
Write test for template matching of synthetic scarp
Python
mit
stgl/scarplet,rmsare/scarplet
--- +++ @@ -0,0 +1,34 @@ +import unittest +import dem +import WindowedTemplate as wt +import filecmp + +class TemplateMatchingTestCase(unittest.TestCase): + + + def setUp(self): + + self.dem = dem.DEMGrid('tests/data/synthetic.tif') + + def test_match_template(self): + + test_amplitude = dem.BaseSpatialGrid('tests/results/synthetic_amplitude.tif') + test_age = dem.BaseSpatialGrid('tests/results/synthetic_age.tif') + test_alpha = dem.BaseSpatialGrid('tests/results/synthetic_alpha.tif') + + template_args = {'alpha' : 0, + 'kt' : 1, + 'd' : 100 + } + + curv = self.dem._calculate_directional_lacpalcian(alpha) + + amplitude, age, alpha, snr = scarplet.match_template(curv, wt.Scarp.template_function, template_args) + + # TODO: refactor into separate tests? + with self.subTest(param_grid=amplitude): + self.assertTrue(np.equal(param_grid, test_amplitude), "Best-fit amplitudes incorrect") + with self.subTest(param_grid=age): + self.assertTrue(np.equal(param_grid, test_age), "Best-fit ages incorrect") + with self.subTest(param_grid=alpha): + self.assertTrue(np.equal(param_grid, test_alpha), "Best-fit orientations incorrect")
75c53cc811ae7f374df211b220c220f01d8b37e9
flocker/node/functional/test_script.py
flocker/node/functional/test_script.py
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ Functional tests for the ``flocker-changestate`` command line tool. """ from subprocess import check_output from unittest import skipUnless from twisted.python.procutils import which from twisted.trial.unittest import TestCase from ... import __version__ _require_installed = skipUnless(which("flocker-changestate"), "flocker-changestate not installed") class FlockerDeployTests(TestCase): """Tests for ``flocker-changestate``.""" @_require_installed def setUp(self): pass def test_version(self): """ ``flocker-changestate`` is a command available on the system path """ result = check_output([b"flocker-changestate"] + [b"--version"]) self.assertEqual(result, b"%s\n" % (__version__,))
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ Functional tests for the ``flocker-changestate`` command line tool. """ from subprocess import check_output from unittest import skipUnless from twisted.python.procutils import which from twisted.trial.unittest import TestCase from ... import __version__ _require_installed = skipUnless(which("flocker-changestate"), "flocker-changestate not installed") class FlockerChangeStateTests(TestCase): """Tests for ``flocker-changestate``.""" @_require_installed def setUp(self): pass def test_version(self): """ ``flocker-changestate`` is a command available on the system path """ result = check_output([b"flocker-changestate"] + [b"--version"]) self.assertEqual(result, b"%s\n" % (__version__,))
Fix the functional testcase name
Fix the functional testcase name
Python
apache-2.0
jml/flocker,agonzalezro/flocker,Azulinho/flocker,AndyHuu/flocker,adamtheturtle/flocker,wallnerryan/flocker-profiles,Azulinho/flocker,1d4Nf6/flocker,LaynePeng/flocker,beni55/flocker,LaynePeng/flocker,hackday-profilers/flocker,beni55/flocker,w4ngyi/flocker,runcom/flocker,jml/flocker,jml/flocker,mbrukman/flocker,hackday-profilers/flocker,adamtheturtle/flocker,1d4Nf6/flocker,agonzalezro/flocker,moypray/flocker,moypray/flocker,achanda/flocker,lukemarsden/flocker,Azulinho/flocker,mbrukman/flocker,runcom/flocker,adamtheturtle/flocker,lukemarsden/flocker,runcom/flocker,AndyHuu/flocker,achanda/flocker,agonzalezro/flocker,mbrukman/flocker,lukemarsden/flocker,w4ngyi/flocker,w4ngyi/flocker,1d4Nf6/flocker,wallnerryan/flocker-profiles,achanda/flocker,AndyHuu/flocker,hackday-profilers/flocker,LaynePeng/flocker,beni55/flocker,wallnerryan/flocker-profiles,moypray/flocker
--- +++ @@ -16,7 +16,7 @@ "flocker-changestate not installed") -class FlockerDeployTests(TestCase): +class FlockerChangeStateTests(TestCase): """Tests for ``flocker-changestate``.""" @_require_installed
c61b08475d82d57dae4349e1c4aa3e58fd7d8256
src/sentry/api/serializers/models/grouptagvalue.py
src/sentry/api/serializers/models/grouptagvalue.py
from __future__ import absolute_import from sentry.api.serializers import Serializer, register from sentry.models import GroupTagValue @register(GroupTagValue) class GroupTagValueSerializer(Serializer): def serialize(self, obj, attrs, user): d = { 'key': obj.key, 'value': obj.value, 'count': obj.times_seen, 'lastSeen': obj.last_seen, 'firstSeen': obj.first_seen, } return d
from __future__ import absolute_import from sentry.api.serializers import Serializer, register from sentry.models import GroupTagValue, TagValue @register(GroupTagValue) class GroupTagValueSerializer(Serializer): def get_attrs(self, item_list, user): assert len(set(i.key for i in item_list)) < 2 tagvalues = dict( (t.value, t) for t in TagValue.objects.filter( project=item_list[0].project, key=item_list[0].key, value__in=[i.value for i in item_list] ) ) result = {} for item in item_list: result[item] = { 'name': tagvalues[item.value].get_label(), } return result def serialize(self, obj, attrs, user): d = { 'name': attrs['name'], 'key': obj.key, 'value': obj.value, 'count': obj.times_seen, 'lastSeen': obj.last_seen, 'firstSeen': obj.first_seen, } return d
Implement labels on group tag values
Implement labels on group tag values
Python
bsd-3-clause
ngonzalvez/sentry,mvaled/sentry,daevaorn/sentry,kevinlondon/sentry,imankulov/sentry,gencer/sentry,korealerts1/sentry,Natim/sentry,felixbuenemann/sentry,JamesMura/sentry,JackDanger/sentry,fotinakis/sentry,JackDanger/sentry,jean/sentry,looker/sentry,gencer/sentry,looker/sentry,gencer/sentry,looker/sentry,ngonzalvez/sentry,looker/sentry,fotinakis/sentry,BuildingLink/sentry,gencer/sentry,hongliang5623/sentry,Kryz/sentry,zenefits/sentry,BayanGroup/sentry,JamesMura/sentry,wong2/sentry,JamesMura/sentry,jean/sentry,fuziontech/sentry,zenefits/sentry,JackDanger/sentry,nicholasserra/sentry,JamesMura/sentry,fotinakis/sentry,korealerts1/sentry,imankulov/sentry,daevaorn/sentry,mitsuhiko/sentry,ifduyue/sentry,mvaled/sentry,Natim/sentry,beeftornado/sentry,alexm92/sentry,nicholasserra/sentry,zenefits/sentry,BuildingLink/sentry,mitsuhiko/sentry,korealerts1/sentry,ifduyue/sentry,Kryz/sentry,hongliang5623/sentry,ifduyue/sentry,gencer/sentry,BayanGroup/sentry,Kryz/sentry,alexm92/sentry,Natim/sentry,mvaled/sentry,wong2/sentry,BayanGroup/sentry,ifduyue/sentry,BuildingLink/sentry,ifduyue/sentry,felixbuenemann/sentry,alexm92/sentry,daevaorn/sentry,BuildingLink/sentry,songyi199111/sentry,mvaled/sentry,wong2/sentry,fuziontech/sentry,ngonzalvez/sentry,looker/sentry,JamesMura/sentry,songyi199111/sentry,jean/sentry,nicholasserra/sentry,mvaled/sentry,BuildingLink/sentry,songyi199111/sentry,fotinakis/sentry,jean/sentry,hongliang5623/sentry,felixbuenemann/sentry,kevinlondon/sentry,mvaled/sentry,beeftornado/sentry,daevaorn/sentry,zenefits/sentry,fuziontech/sentry,imankulov/sentry,zenefits/sentry,kevinlondon/sentry,beeftornado/sentry,jean/sentry
--- +++ @@ -1,13 +1,33 @@ from __future__ import absolute_import from sentry.api.serializers import Serializer, register -from sentry.models import GroupTagValue +from sentry.models import GroupTagValue, TagValue @register(GroupTagValue) class GroupTagValueSerializer(Serializer): + def get_attrs(self, item_list, user): + assert len(set(i.key for i in item_list)) < 2 + + tagvalues = dict( + (t.value, t) + for t in TagValue.objects.filter( + project=item_list[0].project, + key=item_list[0].key, + value__in=[i.value for i in item_list] + ) + ) + + result = {} + for item in item_list: + result[item] = { + 'name': tagvalues[item.value].get_label(), + } + return result + def serialize(self, obj, attrs, user): d = { + 'name': attrs['name'], 'key': obj.key, 'value': obj.value, 'count': obj.times_seen,
6d87ef7420cdb544739340eb432a3e2ee68e734e
wordonhd/Letter.py
wordonhd/Letter.py
class Letter(object): _values = { '#': 0, # Wildcard 'ENIOA': 1, 'SDTR': 2, 'MLKPBG': 3, 'ZVUFJH': 4, 'CW': 5, 'XY': 8, 'Q': 10 } def __init__(self, letter): self.letter = letter[-1] self.wordon = letter[0] == '!' self.real = letter[-1] @property def weight(self): return self.value + self.wordon * 100 @property def value(self): return list(filter(lambda x: self.letter in x[0], self._values.items()))[0][1] @staticmethod def from_raw(data): data = data.split(',') return list(map(Letter, data)) def __str__(self): out = self.letter if self.wordon: out = '!' + out if self.letter != self.real: out += self.real return out def __repr__(self): return "<Letter '{}({})' val '{}'>".format(self.letter, self.real, self.value) def __cmp__(self, other): assert isinstance(other, Letter) return self.wordon == other.wordon and self.letter == other.letter
class Letter(object): _values = { '#': 0, # Wildcard 'ENIOA': 1, 'SDTR': 2, 'MLKPBG': 3, 'ZVUFJH': 4, 'CW': 5, 'XY': 8, 'Q': 10 } def __init__(self, letter): self.letter = letter[-1] self.wordon = letter[0] == '!' self.real = letter[-1] @property def weight(self): return self.value + self.wordon * 100 @property def value(self): return list(filter(lambda x: self.letter in x[0], self._values.items()))[0][1] @staticmethod def from_raw(data): data = data.split(',') return list(map(Letter, data)) def __str__(self): out = self.letter if self.wordon: out = '!' + out if self.letter != self.real: out += self.real return out def __repr__(self): return "<Letter '{}({})' val '{}'>".format(self.letter, self.real, self.value) def __eq__(self, other): assert isinstance(other, Letter) return self.wordon == other.wordon and self.letter == other.letter
Fix wordon filtering when calculating the value
Fix wordon filtering when calculating the value
Python
bsd-2-clause
Mechazawa/WordOn-HD-Bot
--- +++ @@ -40,6 +40,6 @@ def __repr__(self): return "<Letter '{}({})' val '{}'>".format(self.letter, self.real, self.value) - def __cmp__(self, other): + def __eq__(self, other): assert isinstance(other, Letter) return self.wordon == other.wordon and self.letter == other.letter
06ac40c2767e73890f9d68ddc2e5d3c7522118ae
levels/intro.py
levels/intro.py
import pyglet from pyglet.window.key import SPACE from .levels import Level class IntroScreen(Level): def __init__(self, window): self.welcome = pyglet.text.Label('WELCOME\n\tTO\nCLAIRE', x=100, y=window.height-80, width=window.width//2, font_size=40, multiline=True) scores = self.get_scores() self.scores = pyglet.text.Label("".join(scores), x=100, y=window.height-280, width=int(window.width * .8), font_size=30, multiline=True) super(IntroScreen, self).__init__(window) def reset(self): scores = self.get_scores() self.scores.text = "".join(scores) def get_scores(self): with open("scores.txt") as fp: lines = fp.readlines() lines = sorted(lines, reverse=True, key=lambda l: float(l.split(': ')[-1])) return ["{}. {}".format(i, line) for i, line in enumerate(lines[:5], 1)] def key(self, symbol, mod): if symbol == SPACE: self.container.next() def draw(self): self.window.clear() self.welcome.draw() self.scores.draw()
import pyglet from pyglet.window.key import SPACE from .levels import Level class IntroScreen(Level): def __init__(self, window): self.welcome = pyglet.text.Label('WELCOME\n\tTO\nCLAIRE', x=100, y=window.height-80, width=window.width//2, font_size=40, multiline=True) scores = self.get_scores() self.scores = pyglet.text.Label("".join(scores), x=100, y=window.height-280, width=int(window.width * .8), font_size=30, multiline=True) super(IntroScreen, self).__init__(window) def reset(self): scores = self.get_scores() self.scores.text = "".join(scores) def get_scores(self): with open("scores.txt") as fp: lines = fp.readlines() lines = sorted(lines, reverse=True, key=lambda l: float(l.split(': ')[-1])) return ["#{} - {}".format(i, line) for i, line in enumerate(lines[:5], 1)] def key(self, symbol, mod): if symbol == SPACE: self.container.next() def draw(self): self.window.clear() self.welcome.draw() self.scores.draw()
Change formate of top 5 list
Change formate of top 5 list
Python
mit
simeonf/claire
--- +++ @@ -24,7 +24,7 @@ with open("scores.txt") as fp: lines = fp.readlines() lines = sorted(lines, reverse=True, key=lambda l: float(l.split(': ')[-1])) - return ["{}. {}".format(i, line) for i, line in enumerate(lines[:5], 1)] + return ["#{} - {}".format(i, line) for i, line in enumerate(lines[:5], 1)] def key(self, symbol, mod): if symbol == SPACE:
c044c804633612608bbbf61621551d892483f179
yaspin/spinners.py
yaspin/spinners.py
# -*- coding: utf-8 -*- """ yaspin.spinners ~~~~~~~~~~~~~~~ A collection of cli spinners. """ import codecs import os from collections import namedtuple try: import simplejson as json except ImportError: import json THIS_DIR = os.path.dirname(os.path.realpath(__file__)) SPINNERS_PATH = os.path.join(THIS_DIR, "data/spinners.json") def _hook(dct): return namedtuple("Spinner", dct.keys())(*dct.values()) with codecs.open(SPINNERS_PATH, encoding="utf-8") as f: Spinners = json.load(f, object_hook=_hook)
# -*- coding: utf-8 -*- """ yaspin.spinners ~~~~~~~~~~~~~~~ A collection of cli spinners. """ import codecs import pkgutil from collections import namedtuple try: import simplejson as json except ImportError: import json THIS_DIR = os.path.dirname(os.path.realpath(__file__)) SPINNERS_DATA = pkgutil.get_data(__package__, "data/spinners.json").decode("utf-8") def _hook(dct): return namedtuple("Spinner", dct.keys())(*dct.values()) Spinners = json.loads(SPINNERS_DATA, object_hook=_hook)
Allow use inside zip bundled package
Allow use inside zip bundled package
Python
mit
pavdmyt/yaspin
--- +++ @@ -8,7 +8,7 @@ """ import codecs -import os +import pkgutil from collections import namedtuple try: @@ -18,12 +18,11 @@ THIS_DIR = os.path.dirname(os.path.realpath(__file__)) -SPINNERS_PATH = os.path.join(THIS_DIR, "data/spinners.json") +SPINNERS_DATA = pkgutil.get_data(__package__, "data/spinners.json").decode("utf-8") def _hook(dct): return namedtuple("Spinner", dct.keys())(*dct.values()) -with codecs.open(SPINNERS_PATH, encoding="utf-8") as f: - Spinners = json.load(f, object_hook=_hook) +Spinners = json.loads(SPINNERS_DATA, object_hook=_hook)
01331f37c629f0738c5517527a6e78be55334e04
democracy/views/utils.py
democracy/views/utils.py
# -*- coding: utf-8 -*- from functools import lru_cache from rest_framework import serializers class AbstractFieldSerializer(serializers.RelatedField): parent_serializer_class = serializers.ModelSerializer def to_representation(self, image): return self.parent_serializer_class(image, context=self.context).data class AbstractSerializerMixin(object): @classmethod @lru_cache() def get_field_serializer_class(cls): return type('%sFieldSerializer' % cls.Meta.model, (AbstractFieldSerializer,), { "parent_serializer_class": cls }) @classmethod def get_field_serializer(cls, **kwargs): return cls.get_field_serializer_class()(**kwargs)
# -*- coding: utf-8 -*- from functools import lru_cache from rest_framework import serializers from rest_framework.relations import ManyRelatedField, MANY_RELATION_KWARGS class AbstractFieldSerializer(serializers.RelatedField): parent_serializer_class = serializers.ModelSerializer many_field_class = ManyRelatedField def to_representation(self, image): return self.parent_serializer_class(image, context=self.context).data @classmethod def many_init(cls, *args, **kwargs): list_kwargs = {'child_relation': cls(*args, **kwargs)} for key in kwargs.keys(): if key in MANY_RELATION_KWARGS: list_kwargs[key] = kwargs[key] return cls.many_field_class(**list_kwargs) class AbstractSerializerMixin(object): @classmethod @lru_cache() def get_field_serializer_class(cls, many_field_class=ManyRelatedField): return type('%sFieldSerializer' % cls.Meta.model, (AbstractFieldSerializer,), { "parent_serializer_class": cls, "many_field_class": many_field_class, }) @classmethod def get_field_serializer(cls, **kwargs): many_field_class = kwargs.pop("many_field_class", ManyRelatedField) return cls.get_field_serializer_class(many_field_class=many_field_class)(**kwargs)
Allow overriding the ManyRelatedField for image fields
Allow overriding the ManyRelatedField for image fields
Python
mit
City-of-Helsinki/kerrokantasi,stephawe/kerrokantasi,City-of-Helsinki/kerrokantasi,City-of-Helsinki/kerrokantasi,stephawe/kerrokantasi,vikoivun/kerrokantasi,vikoivun/kerrokantasi,vikoivun/kerrokantasi,stephawe/kerrokantasi,City-of-Helsinki/kerrokantasi
--- +++ @@ -2,24 +2,36 @@ from functools import lru_cache from rest_framework import serializers +from rest_framework.relations import ManyRelatedField, MANY_RELATION_KWARGS class AbstractFieldSerializer(serializers.RelatedField): parent_serializer_class = serializers.ModelSerializer + many_field_class = ManyRelatedField def to_representation(self, image): return self.parent_serializer_class(image, context=self.context).data + + @classmethod + def many_init(cls, *args, **kwargs): + list_kwargs = {'child_relation': cls(*args, **kwargs)} + for key in kwargs.keys(): + if key in MANY_RELATION_KWARGS: + list_kwargs[key] = kwargs[key] + return cls.many_field_class(**list_kwargs) class AbstractSerializerMixin(object): @classmethod @lru_cache() - def get_field_serializer_class(cls): + def get_field_serializer_class(cls, many_field_class=ManyRelatedField): return type('%sFieldSerializer' % cls.Meta.model, (AbstractFieldSerializer,), { - "parent_serializer_class": cls + "parent_serializer_class": cls, + "many_field_class": many_field_class, }) @classmethod def get_field_serializer(cls, **kwargs): - return cls.get_field_serializer_class()(**kwargs) + many_field_class = kwargs.pop("many_field_class", ManyRelatedField) + return cls.get_field_serializer_class(many_field_class=many_field_class)(**kwargs)
d240faeec0dea1b9dbefe080b479276ea19d2a0b
apps/explorer/tests/test_views.py
apps/explorer/tests/test_views.py
from django.core.urlresolvers import reverse from apps.core.factories import PIXELER_PASSWORD, PixelerFactory from apps.core.tests import CoreFixturesTestCase from apps.core.management.commands.make_development_fixtures import ( make_development_fixtures ) class PixelSetListViewTestCase(CoreFixturesTestCase): def setUp(self): self.user = PixelerFactory( is_active=True, is_staff=True, is_superuser=True, ) self.client.login( username=self.user.username, password=PIXELER_PASSWORD, ) self.url = reverse('explorer:pixelset_list') def test_renders_pixelset_list_template(self): response = self.client.get(self.url) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'explorer/pixelset_list.html') def test_renders_empty_message(self): response = self.client.get(self.url) expected = ( '<td colspan="8" class="empty">' 'No pixel set has been submitted yet' '</td>' ) self.assertContains(response, expected, html=True) def test_renders_pixelset_list(self): make_development_fixtures(n_pixel_sets=12) response = self.client.get(self.url) self.assertContains( response, '<tr class="pixelset">', count=10 )
from django.core.urlresolvers import reverse from apps.core.factories import PIXELER_PASSWORD, PixelerFactory from apps.core.tests import CoreFixturesTestCase from apps.core.management.commands.make_development_fixtures import ( make_development_fixtures ) class PixelSetListViewTestCase(CoreFixturesTestCase): def setUp(self): self.user = PixelerFactory( is_active=True, is_staff=True, is_superuser=True, ) self.client.login( username=self.user.username, password=PIXELER_PASSWORD, ) self.url = reverse('explorer:pixelset_list') def test_renders_pixelset_list_template(self): response = self.client.get(self.url) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'explorer/pixelset_list.html') def test_renders_empty_message(self): response = self.client.get(self.url) expected = ( '<td colspan="8" class="empty">' 'No pixel set matches your query' '</td>' ) self.assertContains(response, expected, html=True) def test_renders_pixelset_list(self): make_development_fixtures(n_pixel_sets=12) response = self.client.get(self.url) self.assertContains( response, '<tr class="pixelset">', count=10 )
Fix empty pixel set list message
Fix empty pixel set list message
Python
bsd-3-clause
Candihub/pixel,Candihub/pixel,Candihub/pixel,Candihub/pixel,Candihub/pixel
--- +++ @@ -35,7 +35,7 @@ expected = ( '<td colspan="8" class="empty">' - 'No pixel set has been submitted yet' + 'No pixel set matches your query' '</td>' ) self.assertContains(response, expected, html=True)
e475fdcf1054d5942addd28ca2c543542fc8abc5
geoalchemy2/shape.py
geoalchemy2/shape.py
""" This module provides utility functions for integrating with Shapely. """ import shapely.wkb import shapely.wkt from .elements import WKBElement, WKTElement from .compat import buffer, bytes def to_shape(element): """ Function to convert a :class:`geoalchemy2.types.SpatialElement` to a Shapely geometry. Example:: lake = Session.query(Lake).get(1) polygon = to_shape(lake.geom) """ assert isinstance(element, (WKBElement, WKTElement)) if isinstance(element, WKBElement): return shapely.wkb.loads(bytes(element.data)) elif isinstance(element, WKTElement): return shapely.wkt.loads(element.data) def from_shape(shape, srid=-1): """ Function to convert a Shapely geometry to a :class:`geoalchemy2.types.WKBElement`. Additional arguments: ``srid`` An integer representing the spatial reference system. E.g. 4326. Default value is -1, which means no/unknown reference system. Example:: from shapely.geometry import Point wkb_element = from_shape(Point(5, 45), srid=4326) """ return WKBElement(buffer(shape.wkb), srid=srid)
""" This module provides utility functions for integrating with Shapely. .. note:: As GeoAlchemy 2 itself has no dependency on `Shapely`, applications using functions of this module have to ensure that `Shapely` is available. """ import shapely.wkb import shapely.wkt from .elements import WKBElement, WKTElement from .compat import buffer, bytes def to_shape(element): """ Function to convert a :class:`geoalchemy2.types.SpatialElement` to a Shapely geometry. Example:: lake = Session.query(Lake).get(1) polygon = to_shape(lake.geom) """ assert isinstance(element, (WKBElement, WKTElement)) if isinstance(element, WKBElement): return shapely.wkb.loads(bytes(element.data)) elif isinstance(element, WKTElement): return shapely.wkt.loads(element.data) def from_shape(shape, srid=-1): """ Function to convert a Shapely geometry to a :class:`geoalchemy2.types.WKBElement`. Additional arguments: ``srid`` An integer representing the spatial reference system. E.g. 4326. Default value is -1, which means no/unknown reference system. Example:: from shapely.geometry import Point wkb_element = from_shape(Point(5, 45), srid=4326) """ return WKBElement(buffer(shape.wkb), srid=srid)
Add note in docu about Shapely
Add note in docu about Shapely
Python
mit
geoalchemy/geoalchemy2
--- +++ @@ -1,5 +1,10 @@ """ This module provides utility functions for integrating with Shapely. + +.. note:: + + As GeoAlchemy 2 itself has no dependency on `Shapely`, applications using + functions of this module have to ensure that `Shapely` is available. """ import shapely.wkb
c656ac5231d85e5f6a07688d3d7c2f4f07b3e154
backstage/settings/development.py
backstage/settings/development.py
import os import dj_database_url from .base import * DATABASE_URL = os.environ.get('DATABASE_URL') DATABASES = { 'default': dj_database_url.config() } STATIC_ROOT = 'static_sources' STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), )
import os import dj_database_url from .base import * DATABASE_URL = os.environ.get('DATABASE_URL') DATABASES = { 'default': dj_database_url.config() } # Media handling MEDIA_ROOT = BASE_DIR.child("media") # Static file handling STATIC_ROOT = 'static_sources' STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), )
Add MEDIA_ROOT to dev settings
Add MEDIA_ROOT to dev settings
Python
mit
mhotwagner/backstage,mhotwagner/backstage,mhotwagner/backstage
--- +++ @@ -11,6 +11,10 @@ 'default': dj_database_url.config() } +# Media handling +MEDIA_ROOT = BASE_DIR.child("media") + +# Static file handling STATIC_ROOT = 'static_sources' STATIC_URL = '/static/'
76166f243b9f5f21582c95a843ddfa174ded8602
PyFVCOM/__init__.py
PyFVCOM/__init__.py
""" The FVCOM Python toolbox (PyFVCOM) """ __version__ = '1.6.2' __author__ = 'Pierre Cazenave' __credits__ = ['Pierre Cazenave'] __license__ = 'MIT' __maintainer__ = 'Pierre Cazenave' __email__ = 'pica@pml.ac.uk' import inspect from warnings import warn # Import everything! from PyFVCOM import buoy_tools from PyFVCOM import cst_tools from PyFVCOM import ctd_tools from PyFVCOM import current_tools from PyFVCOM import grid_tools from PyFVCOM import ll2utm from PyFVCOM import ll2utm as coordinate_tools from PyFVCOM import ocean_tools from PyFVCOM import stats_tools from PyFVCOM import tide_tools from PyFVCOM import tidal_ellipse from PyFVCOM import process_results from PyFVCOM import read_results from PyFVCOM import plot from PyFVCOM import utilities
""" The FVCOM Python toolbox (PyFVCOM) """ __version__ = '1.6.2' __author__ = 'Pierre Cazenave' __credits__ = ['Pierre Cazenave'] __license__ = 'MIT' __maintainer__ = 'Pierre Cazenave' __email__ = 'pica@pml.ac.uk' import inspect from warnings import warn # Import everything! from PyFVCOM import buoy_tools from PyFVCOM import cst_tools from PyFVCOM import ctd_tools from PyFVCOM import current_tools from PyFVCOM import grid_tools from PyFVCOM import ll2utm from PyFVCOM import ll2utm as coordinate_tools from PyFVCOM import ocean_tools from PyFVCOM import stats_tools from PyFVCOM import tidal_ellipse from PyFVCOM import tide_tools from PyFVCOM import process_results from PyFVCOM import read_results from PyFVCOM import plot from PyFVCOM import utilities
Put things in in alphabetical order.
Put things in in alphabetical order.
Python
mit
pwcazenave/PyFVCOM
--- +++ @@ -23,8 +23,8 @@ from PyFVCOM import ll2utm as coordinate_tools from PyFVCOM import ocean_tools from PyFVCOM import stats_tools +from PyFVCOM import tidal_ellipse from PyFVCOM import tide_tools -from PyFVCOM import tidal_ellipse from PyFVCOM import process_results from PyFVCOM import read_results from PyFVCOM import plot
b0a637ab19b3a5aca9e8c759fad2213ccde33e28
tests/chainer_tests/functions_tests/math_tests/test_sqrt.py
tests/chainer_tests/functions_tests/math_tests/test_sqrt.py
import unittest import numpy import chainer.functions as F from chainer import testing # # sqrt def make_data(shape, dtype): x = numpy.random.uniform(0.1, 5, shape).astype(dtype) gy = numpy.random.uniform(-1, 1, shape).astype(dtype) return x, gy @testing.unary_math_function_test(F.Sqrt(), make_data=make_data) class TestSqrt(unittest.TestCase): pass # # rsqrt def rsqrt(x): return numpy.reciprocal(numpy.sqrt(x)) class TestRsqrt(unittest.TestCase): def test_rsqrt(self): x = numpy.random.uniform(0.1, 5, (3, 2)).astype(numpy.float32) testing.assert_allclose(F.rsqrt(x).data, rsqrt(x)) testing.run_module(__name__, __file__)
import unittest import numpy import chainer.functions as F from chainer import testing # sqrt def make_data(shape, dtype): x = numpy.random.uniform(0.1, 5, shape).astype(dtype) gy = numpy.random.uniform(-1, 1, shape).astype(dtype) return x, gy @testing.unary_math_function_test(F.Sqrt(), make_data=make_data) class TestSqrt(unittest.TestCase): pass # rsqrt def rsqrt(x): return numpy.reciprocal(numpy.sqrt(x)) class TestRsqrt(unittest.TestCase): def test_rsqrt(self): x = numpy.random.uniform(0.1, 5, (3, 2)).astype(numpy.float32) testing.assert_allclose(F.rsqrt(x).data, rsqrt(x)) testing.run_module(__name__, __file__)
Remove empty lines in comments.
Remove empty lines in comments.
Python
mit
wkentaro/chainer,ysekky/chainer,chainer/chainer,hvy/chainer,okuta/chainer,chainer/chainer,keisuke-umezawa/chainer,wkentaro/chainer,wkentaro/chainer,cupy/cupy,kiyukuta/chainer,rezoo/chainer,ronekko/chainer,hvy/chainer,okuta/chainer,ktnyt/chainer,jnishi/chainer,niboshi/chainer,pfnet/chainer,cupy/cupy,kashif/chainer,cupy/cupy,chainer/chainer,okuta/chainer,jnishi/chainer,cupy/cupy,ktnyt/chainer,anaruse/chainer,okuta/chainer,tkerola/chainer,keisuke-umezawa/chainer,keisuke-umezawa/chainer,wkentaro/chainer,jnishi/chainer,ktnyt/chainer,aonotas/chainer,keisuke-umezawa/chainer,chainer/chainer,jnishi/chainer,niboshi/chainer,ktnyt/chainer,delta2323/chainer,hvy/chainer,niboshi/chainer,niboshi/chainer,hvy/chainer
--- +++ @@ -6,7 +6,6 @@ from chainer import testing -# # sqrt def make_data(shape, dtype): @@ -20,7 +19,6 @@ pass -# # rsqrt def rsqrt(x):
3e6700e4bd7107c37cb706086ae93adec7164083
RealtimeInterval.py
RealtimeInterval.py
import time class RealtimeInterval: startTime = 0 interval = 0 def __init__(self, intervalInSeconds): self.startTime = time.time() self.interval = intervalInSeconds def start(self): self.startTime = time.time() def hasElapsed(self): timeNow = time.time() if self.startTime == 0: self.startTime = timeNow return False elapsed = timeNow - self.startTime if (elapsed >= self.interval): self.startTime = timeNow; return True
import time class RealtimeInterval: def __init__(self, intervalInSeconds, allowImmediate = True): self.interval = intervalInSeconds self.allowImmediate = allowImmediate self.reset() def reset(self): if self.allowImmediate: self.startTime = 0 else: self.startTime = time.time() def hasElapsed(self): timeNow = time.time() elapsed = timeNow - self.startTime if (elapsed >= self.interval): self.startTime = timeNow; return True
Improve real time throttle so that it can start immediate the first time.
Improve real time throttle so that it can start immediate the first time.
Python
mit
AluminatiFRC/Vision2016,AluminatiFRC/Vision2016
--- +++ @@ -1,22 +1,19 @@ import time class RealtimeInterval: - startTime = 0 - interval = 0 + def __init__(self, intervalInSeconds, allowImmediate = True): + self.interval = intervalInSeconds + self.allowImmediate = allowImmediate + self.reset() - def __init__(self, intervalInSeconds): - self.startTime = time.time() - self.interval = intervalInSeconds - - def start(self): - self.startTime = time.time() + def reset(self): + if self.allowImmediate: + self.startTime = 0 + else: + self.startTime = time.time() def hasElapsed(self): timeNow = time.time() - if self.startTime == 0: - self.startTime = timeNow - return False - elapsed = timeNow - self.startTime if (elapsed >= self.interval): self.startTime = timeNow;
4940a996a967608bb3c69659d1cc9f97fd2686c7
telepathy/server/properties.py
telepathy/server/properties.py
# telepathy-spec - Base classes defining the interfaces of the Telepathy framework # # Copyright (C) 2005,2006 Collabora Limited # Copyright (C) 2005,2006 Nokia Corporation # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Library General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA import dbus.service from telepathy import * from telepathy._generated.Properties import PropertiesInterface
# telepathy-spec - Base classes defining the interfaces of the Telepathy framework # # Copyright (C) 2005,2006 Collabora Limited # Copyright (C) 2005,2006 Nokia Corporation # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Library General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA import dbus.service from telepathy import * from telepathy._generated.Properties_Interface import PropertiesInterface
Fix import for renaming of Properties to Properties_INterface
Fix import for renaming of Properties to Properties_INterface 20070206124719-53eee-3edd233f30e8a6c5ae1cbaaa1a39a7bbdfb8373c.gz
Python
lgpl-2.1
freedesktop-unofficial-mirror/telepathy__telepathy-spec,TelepathyIM/telepathy-spec
--- +++ @@ -21,4 +21,4 @@ from telepathy import * -from telepathy._generated.Properties import PropertiesInterface +from telepathy._generated.Properties_Interface import PropertiesInterface
377a0d4acd9a578146c0f02f518dbea502c8461f
arividam/siteconfig/apps.py
arividam/siteconfig/apps.py
from __future__ import unicode_literals from django.apps import AppConfig class SiteconfigConfig(AppConfig): name = 'siteconfig'
from __future__ import unicode_literals from django.apps import AppConfig from cms.cms_plugins import AliasPlugin from cms.plugin_pool import plugin_pool class SiteconfigConfig(AppConfig): name = 'siteconfig' verbose_name = "Site Configuration" def ready(self): def return_pass(self, r, p): pass AliasPlugin.get_extra_global_plugin_menu_items = return_pass AliasPlugin.get_extra_placeholder_menu_items = return_pass plugin_pool.unregister_plugin(AliasPlugin)
Disable AliasPlugin since it can accidentally
Disable AliasPlugin since it can accidentally cause problems if an alias is placed within itself
Python
mit
c4sc/arividam,c4sc/arividam,c4sc/arividam,c4sc/arividam
--- +++ @@ -1,7 +1,18 @@ from __future__ import unicode_literals from django.apps import AppConfig +from cms.cms_plugins import AliasPlugin +from cms.plugin_pool import plugin_pool class SiteconfigConfig(AppConfig): name = 'siteconfig' + verbose_name = "Site Configuration" + + def ready(self): + def return_pass(self, r, p): + pass + AliasPlugin.get_extra_global_plugin_menu_items = return_pass + AliasPlugin.get_extra_placeholder_menu_items = return_pass + plugin_pool.unregister_plugin(AliasPlugin) +
f291bb4b5bbf711fa12980fa3a9c8ceb831c6104
frigg/authentication/models.py
frigg/authentication/models.py
# -*- coding: utf8 -*- from django.contrib.auth.models import AbstractUser from django.utils.functional import cached_property from social.apps.django_app.default.models import UserSocialAuth from frigg.helpers import github class User(AbstractUser): @cached_property def github_token(self): try: return self.social_auth.get(provider='github').extra_data['access_token'] except UserSocialAuth.DoesNotExist: return def save(self, *args, **kwargs): create = not hasattr(self, 'id') super(User, self).save(*args, **kwargs) if create: self.update_repo_permissions() def update_repo_permissions(self): if self.github_token: github.update_repo_permissions(self)
# -*- coding: utf8 -*- from django.contrib.auth.models import AbstractUser from django.utils.functional import cached_property from social.apps.django_app.default.models import UserSocialAuth from frigg.helpers import github class User(AbstractUser): @cached_property def github_token(self): try: return self.social_auth.get(provider='github').extra_data['access_token'] except UserSocialAuth.DoesNotExist: return def save(self, *args, **kwargs): create = self.pk is None super(User, self).save(*args, **kwargs) if create: self.update_repo_permissions() def update_repo_permissions(self): if self.github_token: github.update_repo_permissions(self)
Fix is new check in User.save()
Fix is new check in User.save()
Python
mit
frigg/frigg-hq,frigg/frigg-hq,frigg/frigg-hq
--- +++ @@ -16,7 +16,7 @@ return def save(self, *args, **kwargs): - create = not hasattr(self, 'id') + create = self.pk is None super(User, self).save(*args, **kwargs) if create: self.update_repo_permissions()
08de7924f56606225e1772320831a02f2ae4aabd
core/AppResources.py
core/AppResources.py
""" AppResources :Authors: Berend Klein Haneveld """ import os from AppVars import AppVars class AppResources(object): """ AppResources is a static class that can be used to find common resources easily. Just provide a name to the imageNamed() method and it will return the correct path. """ @staticmethod def imageNamed(imageName): """ Returns the full path to the given imageName. Note: Future versions might be more intelligent and can handle searching through the resource folder. For now it just combines the AppVars imagePath with the imageName. :type imageName: basestring :rtype: basestring """ return os.path.join(AppVars.imagePath(), imageName)
""" AppResources :Authors: Berend Klein Haneveld """ import os from AppVars import AppVars from core.elastix.Transformation import Transformation class AppResources(object): """ AppResources is a static class that can be used to find common resources easily. Just provide a name to the imageNamed() method and it will return the correct path. """ @staticmethod def imageNamed(imageName): """ Returns the full path to the given imageName. Note: Future versions might be more intelligent and can handle searching through the resource folder. For now it just combines the AppVars imagePath with the imageName. :type imageName: basestring :rtype: basestring """ return os.path.join(AppVars.imagePath(), imageName) @staticmethod def elastixTemplates(): """ Returns a list of all the available elastix templates in the resource folder. """ transformations = [] fileNames = os.listdir(AppVars.transformationsPath()) for fileName in fileNames: fullFileName = os.path.join(AppVars.transformationsPath(), fileName) transformation = Transformation() if transformation.loadFromFile(fullFileName): transformations.append(transformation) return transformations
Add method for getting the default transformations.
Add method for getting the default transformations.
Python
mit
berendkleinhaneveld/Registrationshop,berendkleinhaneveld/Registrationshop
--- +++ @@ -7,6 +7,7 @@ import os from AppVars import AppVars +from core.elastix.Transformation import Transformation class AppResources(object): @@ -30,3 +31,18 @@ :rtype: basestring """ return os.path.join(AppVars.imagePath(), imageName) + + @staticmethod + def elastixTemplates(): + """ + Returns a list of all the available elastix templates in the + resource folder. + """ + transformations = [] + fileNames = os.listdir(AppVars.transformationsPath()) + for fileName in fileNames: + fullFileName = os.path.join(AppVars.transformationsPath(), fileName) + transformation = Transformation() + if transformation.loadFromFile(fullFileName): + transformations.append(transformation) + return transformations
9f39c7740d23b115680c36968407cf110029dbee
Python/item14.py
Python/item14.py
#!/usr/local/bin/python def divide1(x,y): try: return True,x/y except Exception , e: print e return False,None x1=5 y1=0 x2=2 y2=1 success1,result1= divide1(x1,y1) if not success1: print "Error" else: print result1 success2,result2= divide1(x2,y2) if not success2: print "Error" else: print result2
#!/usr/local/bin/python #def divide1(x,y): # try: # return True,x/y # except Exception , e: # print e # return False,None # #x1=5 #y1=0 #x2=2 #y2=1 #success1,result1= divide1(x1,y1) #if not success1: # print "Error" #else: # print result1 # #success2,result2= divide1(x2,y2) #if not success2: # print "Error" #else: # print result2 def divide(x,y): try: return x/y except ValueError , e: raise ValueError('Input value error') x,y=0,2 try: result=divide(x,y) except ValueError: print 'Value error.' else: print result
Add another way to solve the problem.
Add another way to solve the problem.
Python
mit
Vayne-Lover/Effective
--- +++ @@ -1,23 +1,39 @@ #!/usr/local/bin/python -def divide1(x,y): +#def divide1(x,y): +# try: +# return True,x/y +# except Exception , e: +# print e +# return False,None +# +#x1=5 +#y1=0 +#x2=2 +#y2=1 +#success1,result1= divide1(x1,y1) +#if not success1: +# print "Error" +#else: +# print result1 +# +#success2,result2= divide1(x2,y2) +#if not success2: +# print "Error" +#else: +# print result2 + +def divide(x,y): try: - return True,x/y - except Exception , e: - print e - return False,None + return x/y + except ValueError , e: + raise ValueError('Input value error') -x1=5 -y1=0 -x2=2 -y2=1 -success1,result1= divide1(x1,y1) -if not success1: - print "Error" +x,y=0,2 +try: + result=divide(x,y) +except ValueError: + print 'Value error.' else: - print result1 + print result -success2,result2= divide1(x2,y2) -if not success2: - print "Error" -else: - print result2 +
cf25aeb751fc681907b1684c2675fc6d38b537ed
tests/test_webdriver_chrome.py
tests/test_webdriver_chrome.py
# -*- coding: utf-8 -*- try: import unittest2 as unittest except ImportError: import unittest from splinter import Browser from fake_webapp import EXAMPLE_APP from base import WebDriverTests class ChromeBrowserTest(WebDriverTests, unittest.TestCase): @classmethod def setUpClass(cls): cls.browser = Browser("chrome") @classmethod def tearDownClass(cls): cls.browser.quit() def setUp(self): self.browser.visit(EXAMPLE_APP) def test_attach_file_is_not_implemented(self): "attach file is not implemented for chrome driver" with self.assertRaises(NotImplementedError): self.browser.attach_file('file', 'file_path')
# -*- coding: utf-8 -*- try: import unittest2 as unittest except ImportError: import unittest from splinter import Browser from fake_webapp import EXAMPLE_APP from base import WebDriverTests class ChromeBrowserTest(WebDriverTests, unittest.TestCase): @classmethod def setUpClass(cls): cls.browser = Browser("chrome") @classmethod def tearDownClass(cls): cls.browser.quit() def setUp(self): self.browser.visit(EXAMPLE_APP)
Test for the chrome attach_file disallowance removed
Test for the chrome attach_file disallowance removed
Python
bsd-3-clause
objarni/splinter,underdogio/splinter,bubenkoff/splinter,underdogio/splinter,bmcculley/splinter,lrowe/splinter,bubenkoff/splinter,objarni/splinter,lrowe/splinter,drptbl/splinter,nikolas/splinter,cobrateam/splinter,underdogio/splinter,objarni/splinter,myself659/splinter,bmcculley/splinter,gjvis/splinter,drptbl/splinter,myself659/splinter,myself659/splinter,gjvis/splinter,drptbl/splinter,gjvis/splinter,nikolas/splinter,cobrateam/splinter,nikolas/splinter,lrowe/splinter,cobrateam/splinter,bmcculley/splinter
--- +++ @@ -22,8 +22,3 @@ def setUp(self): self.browser.visit(EXAMPLE_APP) - - def test_attach_file_is_not_implemented(self): - "attach file is not implemented for chrome driver" - with self.assertRaises(NotImplementedError): - self.browser.attach_file('file', 'file_path')
ea40d0c1c51fbf0964cd5642b061bf0e3f3dbe71
classifier/utils/misc_utils.py
classifier/utils/misc_utils.py
#!/usr/bin/python3 from tensorflow.examples.tutorials.mnist import input_data import tensorflow as tf import numpy as np DATASET_PATH = 'data/fashion' def load_dataset(): """Loads fashion dataset Returns: Datasets object """ data = input_data.read_data_sets(DATASET_PATH, one_hot=True) return data def get_hparams(hparams_str): """Parses hparams_str to HParams object. Arguments: hparams_str: String of comma separated param=value pairs. Returns: hparams: tf.contrib.training.HParams object from hparams_str. If hparams_str is None, then a default HParams object is returned. """ hparams = tf.contrib.training.HParams(learning_rate=0.001, conv1_depth=32, conv2_depth=128, dense_layer_units=1024, batch_size=128, keep_prob=0.5, lambd=0.01, num_epochs=1, augment_percent=0.0) if hparams_str: hparams.parse(hparams_str) return hparams def shuffle_dataset(images, labels): num_examples = images.shape[0] permutation = list(np.random.permutation(num_examples)) return (images[permutation, :], labels[permutation, :])
#!/usr/bin/python3 from tensorflow.examples.tutorials.mnist import input_data import tensorflow as tf import numpy as np DATASET_PATH = 'data/fashion' def load_dataset(): """Loads fashion dataset Returns: Datasets object """ data = input_data.read_data_sets(DATASET_PATH, one_hot=True) return data def get_hparams(hparams_str): """Parses hparams_str to HParams object. Arguments: hparams_str: String of comma separated param=value pairs. Returns: hparams: tf.contrib.training.HParams object from hparams_str. If hparams_str is None, then a default HParams object is returned. """ hparams = tf.contrib.training.HParams(learning_rate=0.001, conv1_depth=32, conv2_depth=128, dense_layer_units=1024, batch_size=128, keep_prob=0.5, lambd=0.0, num_epochs=1, augment_percent=0.0) if hparams_str: hparams.parse(hparams_str) return hparams def shuffle_dataset(images, labels): num_examples = images.shape[0] permutation = list(np.random.permutation(num_examples)) return (images[permutation, :], labels[permutation, :])
Set default lambda value to 0
Set default lambda value to 0
Python
mit
vianasw/fashion-classifier
--- +++ @@ -28,7 +28,7 @@ """ hparams = tf.contrib.training.HParams(learning_rate=0.001, conv1_depth=32, conv2_depth=128, dense_layer_units=1024, batch_size=128, - keep_prob=0.5, lambd=0.01, num_epochs=1, augment_percent=0.0) + keep_prob=0.5, lambd=0.0, num_epochs=1, augment_percent=0.0) if hparams_str: hparams.parse(hparams_str) return hparams
3c0d465dde4a93fe60b8b2ce897cb4c5745450ad
pysarus.py
pysarus.py
#!/usr/bin/python3 #Pysarus #A python wrapper for Big Huge Thesarus #Jacob Adams import urllib.request import json #where to save reteived defintions #if None than no files are saved savepath = "." #Your API key for Big Huge Thesarus APIkey = "" def thesarus(word): if(savepath): try: return json.load(savepath+word) except: print("No file found in "+savepath+" for "+word) web = urllib.request.urlopen("http://words.bighugelabs.com/api/2/"+word+"/json") jsonobj = json.loads(web.read()) if(savepath): json.dump(jsonobj,savepath+word) return jsonobj
#!/usr/bin/python3 #Pysarus #A python wrapper for Big Huge Thesarus #Jacob Adams import urllib.request import json #where to save reteived defintions #if None than no files are saved savepath = "." #Your API key for Big Huge Thesarus APIkey = "" def thesarus(word): if(savepath): try: return json.load(savepath+word) except: print("No file found in "+savepath+" for "+word) web = urllib.request.urlopen("http://words.bighugelabs.com/api/2/"+APIkey+"/"+word+"/json") jsonobj = json.loads(web.read()) if(savepath): json.dump(jsonobj,savepath+word) return jsonobj
Use API key in URL
Use API key in URL
Python
mit
Tookmund/Pysarus
--- +++ @@ -19,7 +19,7 @@ return json.load(savepath+word) except: print("No file found in "+savepath+" for "+word) - web = urllib.request.urlopen("http://words.bighugelabs.com/api/2/"+word+"/json") + web = urllib.request.urlopen("http://words.bighugelabs.com/api/2/"+APIkey+"/"+word+"/json") jsonobj = json.loads(web.read()) if(savepath): json.dump(jsonobj,savepath+word)
663f986ff516a401d1ae2c0136a6f6ab4253e9c5
importlib_metadata/__init__.py
importlib_metadata/__init__.py
import os import sys import glob class Distribution: def __init__(self, path): """ Construct a distribution from a path to the metadata dir """ self.path = path @classmethod def for_name(cls, name, path=sys.path): for path_item in path: glob_spec = os.path.join(path_item, f'{name}-*.dist-info') match = next(glob.iglob(glob_spec)) return cls(os.path.join(path_item, match)) @classmethod def for_module(cls, mod): return cls.for_name(cls.dist_name_for_module(mod)) @staticmethod def name_for_module(mod): return getattr(mod, '__dist_name__', mod.__name__)
Add initial implementation of a Distribution class
Add initial implementation of a Distribution class
Python
apache-2.0
python/importlib_metadata
--- +++ @@ -0,0 +1,26 @@ +import os +import sys +import glob + + +class Distribution: + def __init__(self, path): + """ + Construct a distribution from a path to the metadata dir + """ + self.path = path + + @classmethod + def for_name(cls, name, path=sys.path): + for path_item in path: + glob_spec = os.path.join(path_item, f'{name}-*.dist-info') + match = next(glob.iglob(glob_spec)) + return cls(os.path.join(path_item, match)) + + @classmethod + def for_module(cls, mod): + return cls.for_name(cls.dist_name_for_module(mod)) + + @staticmethod + def name_for_module(mod): + return getattr(mod, '__dist_name__', mod.__name__)
9ad660586832ea780b75e8b3f783fb6fd5cf40c4
csunplugged/utils/errors/Error.py
csunplugged/utils/errors/Error.py
"""Base error used to create custom errors for loaders.""" ERROR_TITLE_TEMPLATE = "****************************ERROR****************************\n" ERROR_FILENAME_TEMPLATE = "File: {filename}\n" ERROR_REFERENCE_TEMPLATE = "Referenced in: {reference}\n" ERROR_SUGGESTIONS_TEMPLATE = """ - Did you spell the name of the file correctly? - Does the file exist? - Is the file saved in the correct directory? """ class Error(Exception): """Base class for Errors. (Exceptions from external sources such as inputs). """ def __init__(self): """Create the base class for errors.""" self.base_message = ERROR_TITLE_TEMPLATE + ERROR_FILENAME_TEMPLATE self.reference_message = ERROR_REFERENCE_TEMPLATE self.missing_file_suggestions = ERROR_SUGGESTIONS_TEMPLATE
"""Base error used to create custom errors for loaders.""" ERROR_TITLE_TEMPLATE = "\n****************************ERROR****************************\n" ERROR_FILENAME_TEMPLATE = "File: {filename}\n" ERROR_REFERENCE_TEMPLATE = "Referenced in: {reference}\n" ERROR_SUGGESTIONS_TEMPLATE = """ - Did you spell the name of the file correctly? - Does the file exist? - Is the file saved in the correct directory? """ class Error(Exception): """Base class for Errors. (Exceptions from external sources such as inputs). """ def __init__(self): """Create the base class for errors.""" self.base_message = ERROR_TITLE_TEMPLATE + ERROR_FILENAME_TEMPLATE self.reference_message = ERROR_REFERENCE_TEMPLATE self.missing_file_suggestions = ERROR_SUGGESTIONS_TEMPLATE
Add newline before custom error header
Add newline before custom error header
Python
mit
uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged
--- +++ @@ -1,6 +1,6 @@ """Base error used to create custom errors for loaders.""" -ERROR_TITLE_TEMPLATE = "****************************ERROR****************************\n" +ERROR_TITLE_TEMPLATE = "\n****************************ERROR****************************\n" ERROR_FILENAME_TEMPLATE = "File: {filename}\n" ERROR_REFERENCE_TEMPLATE = "Referenced in: {reference}\n" ERROR_SUGGESTIONS_TEMPLATE = """
7e0024878352ba544a8b40d2c8b5741aedf05a70
Code/login_proxy.py
Code/login_proxy.py
# Sarah M. - 2017 import sys import datetime from colors import farben def request(flow): now = datetime.datetime.now() content = flow.request.get_text() host = flow.request.pretty_host method = flow.request.method if method == "POST" and ("pass" in content) or ("password" in content) : with open ("/home/pi/SpyPi/Code/proxy.txt", "a") as myfile: myfile.write(farben.AUF + str(now) +" // " + farben.END) myfile.write(farben.LD + host + farben.END) myfile.write("\n") myfile.write(farben.IN + content + farben.END) myfile.write("\n") myfile.write("\n")
# Sarah M. - 2017 import re import sys import datetime from colors import farben def request(flow): now = datetime.datetime.now() content = flow.request.get_text() host = flow.request.pretty_host method = flow.request.method if method == "POST" and ("pass" in content) or ("password" in content): with open("/home/pi/SpyPi/Code/proxy.txt", "a") as myfile: myfile.write(farben.AUF + str(now) + " // " + farben.END) myfile.write(farben.LD + host + farben.END) myfile.write("\n") passwords = re.findall(r"(?:pass|password)=([^&]*)", content) myfile.write(farben.IN + passwords[0] + farben.END) myfile.write("\n") myfile.write("\n")
Add regex for parsing password url parameter
Add regex for parsing password url parameter
Python
apache-2.0
sarah314/SpyPi
--- +++ @@ -1,19 +1,22 @@ # Sarah M. - 2017 +import re import sys import datetime from colors import farben + def request(flow): now = datetime.datetime.now() content = flow.request.get_text() host = flow.request.pretty_host method = flow.request.method - if method == "POST" and ("pass" in content) or ("password" in content) : - with open ("/home/pi/SpyPi/Code/proxy.txt", "a") as myfile: - myfile.write(farben.AUF + str(now) +" // " + farben.END) + if method == "POST" and ("pass" in content) or ("password" in content): + with open("/home/pi/SpyPi/Code/proxy.txt", "a") as myfile: + myfile.write(farben.AUF + str(now) + " // " + farben.END) myfile.write(farben.LD + host + farben.END) myfile.write("\n") - myfile.write(farben.IN + content + farben.END) + passwords = re.findall(r"(?:pass|password)=([^&]*)", content) + myfile.write(farben.IN + passwords[0] + farben.END) myfile.write("\n") myfile.write("\n")
d566444d584f644afc580ff9d3cf8e1adc7ccb30
examples/device/audio_test/src/plot_audio_samples.py
examples/device/audio_test/src/plot_audio_samples.py
import sounddevice as sd import matplotlib.pyplot as plt import numpy as np if __name__ == '__main__': # devList = sd.query_devices() # print(devList) fs = 48000 # Sample rate duration = 100e-3 # Duration of recording device = 'Microphone (MicNode) MME' # MME is needed since there are more than one MicNode device APIs (at least in Windows) myrecording = sd.rec(int(duration * fs), samplerate=fs, channels=1, dtype='int16', device=device) print('Waiting...') sd.wait() # Wait until recording is finished print('Done!') time = np.arange(0, duration, 1 / fs) # time vector plt.plot(time, myrecording) plt.xlabel('Time [s]') plt.ylabel('Amplitude') plt.title('MicNode') plt.show()
import sounddevice as sd import matplotlib.pyplot as plt import numpy as np if __name__ == '__main__': # devList = sd.query_devices() # print(devList) fs = 48000 # Sample rate duration = 100e-3 # Duration of recording device = 'Microphone (MicNode) MME' # MME is needed since there are more than one MicNode device APIs (at least in Windows) myrecording = sd.rec(int(duration * fs), samplerate=fs, channels=1, dtype='int16', device=device) print('Waiting...') sd.wait() # Wait until recording is finished print('Done!') time = np.arange(0, duration, 1 / fs) # time vector plt.plot(time, myrecording) plt.xlabel('Time [s]') plt.ylabel('Amplitude') plt.title('MicNode') plt.show()
Add new line at end of python script
Add new line at end of python script
Python
mit
hathach/tinyusb,hathach/tinyusb,hathach/tinyusb
--- +++ @@ -22,3 +22,4 @@ plt.ylabel('Amplitude') plt.title('MicNode') plt.show() +
3c4eb325424fad2f68cfb9360d417bd531106711
exercises/palindrome-products/palindrome_products.py
exercises/palindrome-products/palindrome_products.py
def largest_palindrome(): pass def smallest_palindrome(): pass
def largest_palindrome(max_factor, min_factor): pass def smallest_palindrome(max_factor, min_factor): pass
Add parameter to exercise placeholder
palindrome-product: Add parameter to exercise placeholder
Python
mit
mweb/python,smalley/python,jmluy/xpython,behrtam/xpython,jmluy/xpython,smalley/python,pheanex/xpython,exercism/xpython,N-Parsons/exercism-python,mweb/python,N-Parsons/exercism-python,behrtam/xpython,exercism/python,exercism/python,pheanex/xpython,exercism/xpython
--- +++ @@ -1,6 +1,6 @@ -def largest_palindrome(): +def largest_palindrome(max_factor, min_factor): pass -def smallest_palindrome(): +def smallest_palindrome(max_factor, min_factor): pass
f15c623374f6ca955a37a90d3c90bd19fb781f00
dallinger/experiments/__init__.py
dallinger/experiments/__init__.py
"""A home for all Dallinger Experiments. Experiments should be registered with a ``setuptools`` ``entry_point`` for the ``dallinger.experiments`` group. """ import logging from pkg_resources import iter_entry_points from ..experiment import Experiment logger = logging.getLogger(__name__) logger.addHandler(logging.NullHandler()) # Avoid PEP-8 warning, we want this to be importable from this location Experiment = Experiment for entry_point in iter_entry_points(group='dallinger.experiments'): try: globals()[entry_point.name] = entry_point.load() except ImportError: logger.exception('Could not import registered entry point {}'.format( entry_point.name ))
"""A home for all Dallinger Experiments. Experiments should be registered with a ``setuptools`` ``entry_point`` for the ``dallinger.experiments`` group. """ import logging from pkg_resources import iter_entry_points from ..config import get_config from ..experiment import Experiment config = get_config() config.load() logger = logging.getLogger(__name__) logger.addHandler(logging.NullHandler()) # Avoid PEP-8 warning, we want this to be importable from this location Experiment = Experiment for entry_point in iter_entry_points(group='dallinger.experiments'): try: globals()[entry_point.name] = entry_point.load() except ImportError: logger.exception('Could not import registered entry point {}'.format( entry_point.name ))
Load config when loading dallinger.experiments
Load config when loading dallinger.experiments
Python
mit
Dallinger/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,jcpeterson/Dallinger,Dallinger/Dallinger,jcpeterson/Dallinger,Dallinger/Dallinger,jcpeterson/Dallinger,jcpeterson/Dallinger,jcpeterson/Dallinger
--- +++ @@ -3,7 +3,12 @@ """ import logging from pkg_resources import iter_entry_points + +from ..config import get_config from ..experiment import Experiment + +config = get_config() +config.load() logger = logging.getLogger(__name__) logger.addHandler(logging.NullHandler())
424aa401806ddf536b9bc75efb1493561a5c2a5b
product/views.py
product/views.py
from django.views.generic import DetailView, ListView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.urls import reverse_lazy from django.shortcuts import render from django.contrib.messages.views import SuccessMessageMixin from product.models import ProductCategory # Create your views here. class ProductCategoryList(ListView): model = ProductCategory context_object_name = 'product_categories' class ProductCategoryDetail(DetailView): model = ProductCategory context_object_name = 'product_category' class ProductCategoryCreate(CreateView, SuccessMessageMixin): model = ProductCategory fields = ['name'] success_message = "Category %(name)s created" class ProductCategoryUpdate(UpdateView, SuccessMessageMixin): model = ProductCategory fields = ['name'] success_message = "Category %(name)s updated" class ProductCategoryDelete(DeleteView, SuccessMessageMixin): model = ProductCategory context_object_name = 'product_category' success_url = reverse_lazy('product-category-list') success_message = "Category %(name)s removed"
from django.http import HttpResponseRedirect from django.views.generic import DetailView, ListView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.urls import reverse_lazy from django.shortcuts import render from django.contrib import messages from django.contrib.messages.views import SuccessMessageMixin from product.models import ProductCategory # Create your views here. class ProductCategoryList(ListView): model = ProductCategory context_object_name = 'product_categories' class ProductCategoryDetail(DetailView): model = ProductCategory context_object_name = 'product_category' class ProductCategoryCreate(SuccessMessageMixin, CreateView): model = ProductCategory fields = ['name'] success_message = "Category %(name)s created" class ProductCategoryUpdate(SuccessMessageMixin, UpdateView): model = ProductCategory fields = ['name'] success_message = "Category %(name)s updated" class ProductCategoryDelete(DeleteView): model = ProductCategory context_object_name = 'product_category' success_url = reverse_lazy('product-category-list') success_message = "Category removed" cancel_message = "Removal cancelled" def post(self, request, *args, **kwargs): if "cancel" in request.POST: url = self.success_url messages.warning(self.request, self.cancel_message) return HttpResponseRedirect(url) else: messages.success(self.request, self.success_message) return super(ProductCategoryDelete, self).delete(request, *args, **kwargs)
Make messages show in delete view.
Make messages show in delete view.
Python
mit
borderitsolutions/amadaa,borderitsolutions/amadaa,borderitsolutions/amadaa
--- +++ @@ -1,7 +1,9 @@ +from django.http import HttpResponseRedirect from django.views.generic import DetailView, ListView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.urls import reverse_lazy from django.shortcuts import render +from django.contrib import messages from django.contrib.messages.views import SuccessMessageMixin from product.models import ProductCategory @@ -15,18 +17,30 @@ model = ProductCategory context_object_name = 'product_category' -class ProductCategoryCreate(CreateView, SuccessMessageMixin): +class ProductCategoryCreate(SuccessMessageMixin, CreateView): model = ProductCategory fields = ['name'] success_message = "Category %(name)s created" -class ProductCategoryUpdate(UpdateView, SuccessMessageMixin): +class ProductCategoryUpdate(SuccessMessageMixin, UpdateView): model = ProductCategory fields = ['name'] success_message = "Category %(name)s updated" -class ProductCategoryDelete(DeleteView, SuccessMessageMixin): +class ProductCategoryDelete(DeleteView): model = ProductCategory context_object_name = 'product_category' success_url = reverse_lazy('product-category-list') - success_message = "Category %(name)s removed" + success_message = "Category removed" + cancel_message = "Removal cancelled" + + def post(self, request, *args, **kwargs): + if "cancel" in request.POST: + url = self.success_url + messages.warning(self.request, self.cancel_message) + return HttpResponseRedirect(url) + else: + messages.success(self.request, self.success_message) + return super(ProductCategoryDelete, self).delete(request, + *args, **kwargs) +
a5926a3ef469c4b323f994dd026b55cac7fa1b2f
turbustat/tests/test_dendro.py
turbustat/tests/test_dendro.py
# Licensed under an MIT open source license - see LICENSE ''' Tests for Dendrogram statistics ''' from unittest import TestCase import numpy as np import numpy.testing as npt from ..statistics import Dendrogram_Stats, DendroDistance from ._testing_data import \ dataset1, dataset2, computed_data, computed_distances class testDendrograms(TestCase): def setUp(self): self.min_deltas = np.logspace(-1.5, 0.5, 40) def test_DendroStat(self): self.tester = Dendrogram_Stats(dataset1["cube"], min_deltas=self.min_deltas) self.tester.run() npt.assert_allclose(self.tester.numfeatures, computed_data["dendrogram_val"]) def test_DendroDistance(self): self.tester_dist = \ DendroDistance(dataset1["cube"], dataset2["cube"], min_deltas=self.min_deltas).distance_metric() npt.assert_almost_equal(self.tester_dist.histogram_distance, computed_distances["dendrohist_distance"]) npt.assert_almost_equal(self.tester_dist.num_distance, computed_distances["dendronum_distance"])
# Licensed under an MIT open source license - see LICENSE ''' Tests for Dendrogram statistics ''' import numpy as np import numpy.testing as npt from ..statistics import Dendrogram_Stats, DendroDistance from ._testing_data import \ dataset1, dataset2, computed_data, computed_distances min_deltas = np.logspace(-1.5, 0.5, 40) def test_DendroStat(): tester = Dendrogram_Stats(dataset1["cube"], min_deltas=min_deltas) tester.run(periodic_bounds=False) npt.assert_allclose(tester.numfeatures, computed_data["dendrogram_val"]) def test_DendroDistance(): tester_dist = \ DendroDistance(dataset1["cube"], dataset2["cube"], min_deltas=min_deltas, periodic_bounds=False).distance_metric() npt.assert_almost_equal(tester_dist.histogram_distance, computed_distances["dendrohist_distance"]) npt.assert_almost_equal(tester_dist.num_distance, computed_distances["dendronum_distance"])
Update dendro tests and specify no periodic boundaries to be consistent w/ previous unit testing
Update dendro tests and specify no periodic boundaries to be consistent w/ previous unit testing
Python
mit
Astroua/TurbuStat,e-koch/TurbuStat
--- +++ @@ -4,8 +4,6 @@ ''' Tests for Dendrogram statistics ''' - -from unittest import TestCase import numpy as np import numpy.testing as npt @@ -15,28 +13,28 @@ dataset1, dataset2, computed_data, computed_distances -class testDendrograms(TestCase): +min_deltas = np.logspace(-1.5, 0.5, 40) - def setUp(self): - self.min_deltas = np.logspace(-1.5, 0.5, 40) - def test_DendroStat(self): +def test_DendroStat(): - self.tester = Dendrogram_Stats(dataset1["cube"], - min_deltas=self.min_deltas) - self.tester.run() + tester = Dendrogram_Stats(dataset1["cube"], + min_deltas=min_deltas) + tester.run(periodic_bounds=False) - npt.assert_allclose(self.tester.numfeatures, - computed_data["dendrogram_val"]) + npt.assert_allclose(tester.numfeatures, + computed_data["dendrogram_val"]) - def test_DendroDistance(self): - self.tester_dist = \ - DendroDistance(dataset1["cube"], - dataset2["cube"], - min_deltas=self.min_deltas).distance_metric() +def test_DendroDistance(): - npt.assert_almost_equal(self.tester_dist.histogram_distance, - computed_distances["dendrohist_distance"]) - npt.assert_almost_equal(self.tester_dist.num_distance, - computed_distances["dendronum_distance"]) + tester_dist = \ + DendroDistance(dataset1["cube"], + dataset2["cube"], + min_deltas=min_deltas, + periodic_bounds=False).distance_metric() + + npt.assert_almost_equal(tester_dist.histogram_distance, + computed_distances["dendrohist_distance"]) + npt.assert_almost_equal(tester_dist.num_distance, + computed_distances["dendronum_distance"])
04069a5d5d6f5647394aba987ae5798629bf4a73
Ghidra/Features/Python/ghidra_scripts/ImportSymbolsScript.py
Ghidra/Features/Python/ghidra_scripts/ImportSymbolsScript.py
#Imports a file with lines in the form "symbolName 0xADDRESS" #@category Data #@author f = askFile("Give me a file to open", "Go baby go!") for line in file(f.absolutePath): # note, cannot use open(), since that is in GhidraScript pieces = line.split() address = toAddr(long(pieces[1], 16)) print "creating symbol", pieces[0], "at address", address createLabel(address, pieces[0], False)
# Imports a file with lines in the form "symbolName 0xADDRESS function_or_label" where "f" indicates a function and "l" a label # @author unkown; edited by matedealer <git@matedealer.de> # @category Data # from ghidra.program.model.symbol.SourceType import * import string functionManager = currentProgram.getFunctionManager() f = askFile("Give me a file to open", "Go baby go!") for line in file(f.absolutePath): # note, cannot use open(), since that is in GhidraScript pieces = line.split() name = pieces[0] address = toAddr(long(pieces[1], 16)) try: function_or_label = pieces[2] except IndexError: function_or_label = "l" if function_or_label == "f": func = functionManager.getFunctionAt(address) if func is not None: old_name = func.getName() func.setName(name, USER_DEFINED) print("Renamed function {} to {} at address {}".format(old_name, name, address)) else: func = createFunction(address, name) print("Created function {} at address {}".format(name, address)) else: print("Created label {} at address {}".format(name, address)) createLabel(address, name, False)
Add optional 3 option to ImportSymbolScript.py to allow importing function names.
Add optional 3 option to ImportSymbolScript.py to allow importing function names. Add python script to import functions and labels Use print() instead of print Merge ImportSymbolsScript.py and ImportFunctionAndLabels.py Made third token optional
Python
apache-2.0
NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra
--- +++ @@ -1,11 +1,38 @@ -#Imports a file with lines in the form "symbolName 0xADDRESS" -#@category Data -#@author - +# Imports a file with lines in the form "symbolName 0xADDRESS function_or_label" where "f" indicates a function and "l" a label +# @author unkown; edited by matedealer <git@matedealer.de> +# @category Data +# + +from ghidra.program.model.symbol.SourceType import * +import string + +functionManager = currentProgram.getFunctionManager() + f = askFile("Give me a file to open", "Go baby go!") for line in file(f.absolutePath): # note, cannot use open(), since that is in GhidraScript pieces = line.split() + + name = pieces[0] address = toAddr(long(pieces[1], 16)) - print "creating symbol", pieces[0], "at address", address - createLabel(address, pieces[0], False) + + try: + function_or_label = pieces[2] + except IndexError: + function_or_label = "l" + + + if function_or_label == "f": + func = functionManager.getFunctionAt(address) + + if func is not None: + old_name = func.getName() + func.setName(name, USER_DEFINED) + print("Renamed function {} to {} at address {}".format(old_name, name, address)) + else: + func = createFunction(address, name) + print("Created function {} at address {}".format(name, address)) + + else: + print("Created label {} at address {}".format(name, address)) + createLabel(address, name, False)
f844f9e153406577b844a864110bcc54fd6b01f3
nose2/tests/functional/support/scenario/expected_failures/expected_failures.py
nose2/tests/functional/support/scenario/expected_failures/expected_failures.py
import unittest class TestWithExpectedFailures(unittest.TestCase): @unittest.expectedFailure def test_should_fail(self): assert False @unittest.expectedFailure def test_should_pass(self): assert True def test_whatever(self): assert True def test_fails(self): assert False
from nose2.compat import unittest class TestWithExpectedFailures(unittest.TestCase): @unittest.expectedFailure def test_should_fail(self): assert False @unittest.expectedFailure def test_should_pass(self): assert True def test_whatever(self): assert True def test_fails(self): assert False
Fix for py26 and expectedFailure
Fix for py26 and expectedFailure
Python
bsd-2-clause
ojengwa/nose2,little-dude/nose2,ptthiem/nose2,ezigman/nose2,ptthiem/nose2,ezigman/nose2,little-dude/nose2,ojengwa/nose2
--- +++ @@ -1,4 +1,4 @@ -import unittest +from nose2.compat import unittest class TestWithExpectedFailures(unittest.TestCase):
d57a974acfd9054dafca692404f217788da22f01
allauth/socialaccount/providers/gitlab/provider.py
allauth/socialaccount/providers/gitlab/provider.py
# -*- coding: utf-8 -*- from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class GitLabAccount(ProviderAccount): def get_profile_url(self): return self.account.extra_data.get('html_url') def get_avatar_url(self): return self.account.extra_data.get('avatar_url') def to_str(self): dflt = super(GitLabAccount, self).to_str() return self.account.extra_data.get('name', dflt) class GitLabProvider(OAuth2Provider): id = 'gitlab' name = 'GitLab' account_class = GitLabAccount def extract_uid(self, data): return str(data['id']) def extract_common_fields(self, data): return dict( email=data.get('email'), username=data.get('username'), name=data.get('name'), ) provider_classes = [GitLabProvider]
# -*- coding: utf-8 -*- from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class GitLabAccount(ProviderAccount): def get_profile_url(self): return self.account.extra_data.get('web_url') def get_avatar_url(self): return self.account.extra_data.get('avatar_url') def to_str(self): dflt = super(GitLabAccount, self).to_str() return self.account.extra_data.get('name', dflt) class GitLabProvider(OAuth2Provider): id = 'gitlab' name = 'GitLab' account_class = GitLabAccount def extract_uid(self, data): return str(data['id']) def extract_common_fields(self, data): return dict( email=data.get('email'), username=data.get('username'), name=data.get('name'), ) provider_classes = [GitLabProvider]
Fix GitLab profile_url (html_url -> web_url)
Fix GitLab profile_url (html_url -> web_url)
Python
mit
spool/django-allauth,pztrick/django-allauth,bittner/django-allauth,pztrick/django-allauth,joshowen/django-allauth,pztrick/django-allauth,rsalmaso/django-allauth,bittner/django-allauth,rsalmaso/django-allauth,pennersr/django-allauth,bittner/django-allauth,AltSchool/django-allauth,lukeburden/django-allauth,lukeburden/django-allauth,joshowen/django-allauth,pennersr/django-allauth,pennersr/django-allauth,spool/django-allauth,rsalmaso/django-allauth,spool/django-allauth,joshowen/django-allauth,AltSchool/django-allauth,AltSchool/django-allauth,lukeburden/django-allauth
--- +++ @@ -6,7 +6,7 @@ class GitLabAccount(ProviderAccount): def get_profile_url(self): - return self.account.extra_data.get('html_url') + return self.account.extra_data.get('web_url') def get_avatar_url(self): return self.account.extra_data.get('avatar_url')
8fd968028492f113a91358b87ee045f3f2b5d38b
core/templatetags/bootstrap.py
core/templatetags/bootstrap.py
# -*- coding: utf-8 -*- from django import template from django.utils.safestring import mark_safe register = template.Library() @register.filter() def bool_icon(value): """ Create a safe HTML version of True/False using Bootstrap styles. :param value: a boolean. :returns: a string of html for an icon representing the boolean. """ if value: classes = 'icon-true text-success' else: classes = 'icon-false text-danger' icon_html = '<i class="icon {}" aria-hidden="true"></i>'.format(classes) return mark_safe(icon_html)
# -*- coding: utf-8 -*- from django import template from django.utils.safestring import mark_safe register = template.Library() @register.filter() def bool_icon(value): """ Create a safe HTML version of True/False using Bootstrap styles. :param value: a boolean. :returns: a string of html for an icon representing the boolean. """ if value: classes = 'icon-true text-success' else: classes = 'icon-false text-danger' icon_html = '<i class="{}" aria-hidden="true"></i>'.format(classes) return mark_safe(icon_html)
Update existing test for icon class changes
Update existing test for icon class changes
Python
bsd-2-clause
cdubz/babybuddy,cdubz/babybuddy,cdubz/babybuddy
--- +++ @@ -16,5 +16,5 @@ classes = 'icon-true text-success' else: classes = 'icon-false text-danger' - icon_html = '<i class="icon {}" aria-hidden="true"></i>'.format(classes) + icon_html = '<i class="{}" aria-hidden="true"></i>'.format(classes) return mark_safe(icon_html)
69f1f5f78477e6c89338661e71ecd9732a287673
datafilters/views.py
datafilters/views.py
from django.views.generic.list import MultipleObjectMixin __all__ = ('FilterFormMixin',) class FilterFormMixin(MultipleObjectMixin): """ Mixin that adds filtering behaviour for Class Based Views. Changed in a way that can play nicely with other CBV simply by overriding the get_queryset(self) and get_context_data(self, **kwargs) method. """ filter_form_cls = None use_filter_chaining = False def get_filter(self): return self.filter_form_cls(self.request.GET, runtime_context=self.get_runtime_context(), use_filter_chaining=self.use_filter_chaining) def get_queryset(self): qs = super(FilterFormMixin, self).get_queryset() qs = self.get_filter().filter(qs).distinct() return qs def get_context_data(self, **kwargs): context = super(FilterFormMixin, self).get_context_data(**kwargs) context['filterform'] = self.get_filter() return context def get_runtime_context(self): return {'user': self.request.user}
from django.views.generic.list import MultipleObjectMixin __all__ = ('FilterFormMixin',) class FilterFormMixin(MultipleObjectMixin): """ Mixin that adds filtering behaviour for Class Based Views. Changed in a way that can play nicely with other CBV simply by overriding the get_queryset(self) and get_context_data(self, **kwargs) method. """ filter_form_cls = None use_filter_chaining = False context_filterform_name = 'filterform' def get_filter(self): return self.filter_form_cls(self.request.GET, runtime_context=self.get_runtime_context(), use_filter_chaining=self.use_filter_chaining) def get_queryset(self): qs = super(FilterFormMixin, self).get_queryset() qs = self.get_filter().filter(qs).distinct() return qs def get_context_data(self, **kwargs): context = super(FilterFormMixin, self).get_context_data(**kwargs) context[self.context_filterform_name] = self.get_filter() return context def get_runtime_context(self): return {'user': self.request.user}
Make context name for a filter form configurable
Make context name for a filter form configurable
Python
mit
zorainc/django-datafilters,freevoid/django-datafilters,zorainc/django-datafilters
--- +++ @@ -11,6 +11,7 @@ """ filter_form_cls = None use_filter_chaining = False + context_filterform_name = 'filterform' def get_filter(self): return self.filter_form_cls(self.request.GET, @@ -24,7 +25,7 @@ def get_context_data(self, **kwargs): context = super(FilterFormMixin, self).get_context_data(**kwargs) - context['filterform'] = self.get_filter() + context[self.context_filterform_name] = self.get_filter() return context def get_runtime_context(self):
c95d6e0f215cb81a00a0af869595bb6e89e887e7
test/lib/01-con-discon-success.py
test/lib/01-con-discon-success.py
#!/usr/bin/python # Test whether a client produces a correct connect and subsequent disconnect. import os import subprocess import socket import sys import time from struct import * rc = 1 keepalive = 60 connect_packet = pack('!BBH6sBBHH21s', 16, 12+2+21,6,"MQIsdp",3,2,keepalive,21,"01-con-discon-success") connack_packet = pack('!BBBB', 32, 2, 0, 0); sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(('', 1888)) sock.listen(5) client_args = sys.argv[1:] env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' client = subprocess.Popen(client_args, env=env) try: (conn, address) = sock.accept() connect_recvd = conn.recv(256) if connect_recvd != connect_packet: print("FAIL: Received incorrect connect.") print("Received: "+connect_recvd+" length="+str(len(connect_recvd))) print("Expected: "+connect_packet+" length="+str(len(connect_packet))) else: rc = 0 finally: client.terminate() client.wait() exit(rc)
#!/usr/bin/python # Test whether a client produces a correct connect and subsequent disconnect. import os import subprocess import socket import sys import time from struct import * rc = 1 keepalive = 60 connect_packet = pack('!BBH6sBBHH21s', 16, 12+2+21,6,"MQIsdp",3,2,keepalive,21,"01-con-discon-success") connack_packet = pack('!BBBB', 32, 2, 0, 0); sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(('', 1888)) sock.listen(5) client_args = sys.argv[1:] env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' client = subprocess.Popen(client_args, env=env) try: (conn, address) = sock.accept() connect_recvd = conn.recv(256) if connect_recvd != connect_packet: print("FAIL: Received incorrect connect.") print("Received: "+connect_recvd+" length="+str(len(connect_recvd))) print("Expected: "+connect_packet+" length="+str(len(connect_packet))) else: rc = 0 conn.close() finally: client.terminate() client.wait() sock.close() exit(rc)
Set SO_REUSEADDR in client test.
Set SO_REUSEADDR in client test.
Python
bsd-3-clause
zlargon/mosquitto,zlargon/mosquitto,zlargon/mosquitto,zlargon/mosquitto,zlargon/mosquitto
--- +++ @@ -16,6 +16,7 @@ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) +sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(('', 1888)) sock.listen(5) @@ -34,9 +35,12 @@ print("Expected: "+connect_packet+" length="+str(len(connect_packet))) else: rc = 0 + + conn.close() finally: client.terminate() client.wait() + sock.close() exit(rc)
313a81093527c88631713f6b4ad8c652554edb50
l10n_br_base/migrations/12.0.1.0.0/post-migration.py
l10n_br_base/migrations/12.0.1.0.0/post-migration.py
# -*- coding: utf-8 -*- # Copyright 2018 KMEE INFORMATICA LTDA - Gabriel Cardoso de Faria # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from openupgradelib import openupgrade @openupgrade.migrate() def migrate(env, version): cr = env.cr cr.execute( '''INSERT INTO res_city(id, name, country_id, state_id, ibge_code) SELECT nextval('res_city_id_seq'), name, (SELECT id FROM res_country WHERE code='BR'), state_id, ibge_code FROM l10n_br_base_city WHERE ibge_code NOT IN (SELECT ibge_code FROM res_city); ''') cr.execute( '''INSERT INTO state_tax_numbers(id, inscr_est, partner_id, state_id) SELECT nextval('state_tax_numbers_id_seq'), inscr_est, partner_id, state_id FROM other_inscricoes_estaduais; ''') cr.execute( '''UPDATE res_partner rp SET city_id=( SELECT id FROM res_city WHERE ibge_code=( SELECT ibge_code FROM l10n_br_base_city WHERE id=rp.l10n_br_city_id)) ''')
# -*- coding: utf-8 -*- # Copyright 2018 KMEE INFORMATICA LTDA - Gabriel Cardoso de Faria # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from openupgradelib import openupgrade _model_renames = [ ('l10n_br_base.city', 'res.city'), ] _table_renames = [ ('l10n_br_base_city', 'res_city'), ] @openupgrade.migrate() def migrate(env, version): cr = env.cr openupgrade.rename_models(cr, _model_renames) openupgrade.rename_tables(cr, _table_renames) cr.execute( '''INSERT INTO state_tax_numbers(id, inscr_est, partner_id, state_id) SELECT nextval('state_tax_numbers_id_seq'), inscr_est, partner_id, state_id FROM other_inscricoes_estaduais; ''') cr.execute( '''UPDATE res_partner rp SET city_id=( SELECT id FROM res_city WHERE ibge_code=( SELECT ibge_code FROM l10n_br_base_city WHERE id=rp.l10n_br_city_id)) ''')
Rename table _model_renames and _table_renames
[ADD] Rename table _model_renames and _table_renames Signed-off-by: Luis Felipe Mileo <c9a5b4d335634d99740001a1172b3e56e4fc5aa8@kmee.com.br>
Python
agpl-3.0
akretion/l10n-brazil,OCA/l10n-brazil,OCA/l10n-brazil,OCA/l10n-brazil,akretion/l10n-brazil,akretion/l10n-brazil
--- +++ @@ -4,18 +4,23 @@ from openupgradelib import openupgrade +_model_renames = [ + ('l10n_br_base.city', 'res.city'), +] + +_table_renames = [ + ('l10n_br_base_city', 'res_city'), +] + + @openupgrade.migrate() def migrate(env, version): cr = env.cr - cr.execute( - '''INSERT INTO res_city(id, name, country_id, state_id, ibge_code) - SELECT nextval('res_city_id_seq'), name, (SELECT id FROM res_country - WHERE code='BR'), state_id, ibge_code FROM l10n_br_base_city - WHERE ibge_code NOT IN (SELECT ibge_code FROM res_city); - ''') + openupgrade.rename_models(cr, _model_renames) + openupgrade.rename_tables(cr, _table_renames) cr.execute( '''INSERT INTO state_tax_numbers(id, inscr_est, partner_id, state_id) - SELECT nextval('state_tax_numbers_id_seq'), inscr_est, partner_id, + SELECT nextval('state_tax_numbers_id_seq'), inscr_est, partner_id, state_id FROM other_inscricoes_estaduais; ''') cr.execute(
c38e9c886bf10f18db7ab182b231ef7a6fe53b8e
binder/jupyter_notebook_config.py
binder/jupyter_notebook_config.py
c.ServerProxy.servers = { 'lab-dev': { 'command': [ 'jupyter', 'lab', '--debug', '--no-browser', '--port={port}', '--NotebookApp.token=""', '--NotebookApp.base_url={base_url}lab-dev', ], 'absolute_url': True } } c.NotebookApp.default_url = '/lab-dev' import logging c.NotebookApp.log_level = logging.DEBUG
c.ServerProxy.servers = { 'lab-dev': { 'command': [ 'jupyter', 'lab', '--debug', '--no-browser', '--port={port}', '--NotebookApp.token=""', '--NotebookApp.base_url={base_url}lab-dev', # Disable dns rebinding protection here, since our 'Host' header # is not going to be localhost when coming from hub.mybinder.org '--NotebookApp.allow_remote_access=True' ], 'absolute_url': True } } c.NotebookApp.default_url = '/lab-dev' import logging c.NotebookApp.log_level = logging.DEBUG
Disable dns rebinding protection for dev mode notebook
Disable dns rebinding protection for dev mode notebook
Python
bsd-3-clause
jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab
--- +++ @@ -8,6 +8,9 @@ '--port={port}', '--NotebookApp.token=""', '--NotebookApp.base_url={base_url}lab-dev', + # Disable dns rebinding protection here, since our 'Host' header + # is not going to be localhost when coming from hub.mybinder.org + '--NotebookApp.allow_remote_access=True' ], 'absolute_url': True }
be3ee0a06ec350431e66efbcbcead28075056f55
django_extensions/tests/models.py
django_extensions/tests/models.py
from django.db import models try: from django_extensions.db.fields.encrypted import EncryptedTextField, EncryptedCharField except ImportError: class EncryptedCharField(): def __init__(self, **kwargs): pass; class EncryptedTextField(): def __init__(self, **kwargs): pass; class Secret(models.Model): name = EncryptedCharField(blank=True, max_length=255) text = EncryptedTextField(blank=True)
from django.db import models try: from django_extensions.db.fields.encrypted import EncryptedTextField, EncryptedCharField except ImportError: class EncryptedCharField(): def __init__(self, **kwargs): pass class EncryptedTextField(): def __init__(self, **kwargs): pass class Secret(models.Model): name = EncryptedCharField(blank=True, max_length=255) text = EncryptedTextField(blank=True)
Remove bogus semicolons, thanks justinlilly
Remove bogus semicolons, thanks justinlilly
Python
mit
django-extensions/django-extensions,levic/django-extensions,linuxmaniac/django-extensions,kevgathuku/django-extensions,ewjoachim/django-extensions,joeyespo/django-extensions,Christophe31/django-extensions,Moulde/django-extensions,nikolas/django-extensions,barseghyanartur/django-extensions,atchariya/django-extensions,frewsxcv/django-extensions,mandx/django-extensions,marctc/django-extensions,ewjoachim/django-extensions,frewsxcv/django-extensions,gdoermann/django-extensions,artscoop/django-extensions,marctc/django-extensions,zefciu/django-extensions,levic/django-extensions,django-extensions/django-extensions,helenst/django-extensions,t1m0thy/django-extensions,atchariya/django-extensions,Moulde/django-extensions,JoseTomasTocino/django-extensions,barseghyanartur/django-extensions,jpadilla/django-extensions,helenst/django-extensions,rodo/django-extensions,haakenlid/django-extensions,Christophe31/django-extensions,mandx/django-extensions,github-account-because-they-want-it/django-extensions,fusionbox/django-extensions,django-extensions/django-extensions,maroux/django-extensions,ewjoachim/django-extensions,zefciu/django-extensions,t1m0thy/django-extensions,haakenlid/django-extensions,bionikspoon/django-extensions,gvangool/django-extensions,JoseTomasTocino/django-extensions,atchariya/django-extensions,dpetzold/django-extensions,zefciu/django-extensions,artscoop/django-extensions,github-account-because-they-want-it/django-extensions,lamby/django-extensions,linuxmaniac/django-extensions,haakenlid/django-extensions,barseghyanartur/django-extensions,nikolas/django-extensions,lamby/django-extensions,Moulde/django-extensions,mandx/django-extensions,helenst/django-extensions,dpetzold/django-extensions,jpadilla/django-extensions,VishvajitP/django-extensions,ctrl-alt-d/django-extensions,t1m0thy/django-extensions,bionikspoon/django-extensions,linuxmaniac/django-extensions,JoseTomasTocino/django-extensions,dpetzold/django-extensions,levic/django-extensions,kevgathuku/django-extensions,gdoermann/django-extensions,artscoop/django-extensions,gvangool/django-extensions,nikolas/django-extensions,ctrl-alt-d/django-extensions,fusionbox/django-extensions,joeyespo/django-extensions,maroux/django-extensions,ctrl-alt-d/django-extensions,VishvajitP/django-extensions,marctc/django-extensions,lamby/django-extensions,bionikspoon/django-extensions,joeyespo/django-extensions,github-account-because-they-want-it/django-extensions,kevgathuku/django-extensions,VishvajitP/django-extensions,maroux/django-extensions,gvangool/django-extensions,rodo/django-extensions,rodo/django-extensions,jpadilla/django-extensions,frewsxcv/django-extensions
--- +++ @@ -6,11 +6,11 @@ class EncryptedCharField(): def __init__(self, **kwargs): - pass; + pass class EncryptedTextField(): def __init__(self, **kwargs): - pass; + pass class Secret(models.Model):
fb99c40fa0dcf59aaaf45a14b238a240a453bcaa
climlab/__init__.py
climlab/__init__.py
__version__ = '0.2.4' # This list defines all the modules that will be loaded if a user invokes # from climLab import * # totally out of date! #__all__ = ["constants", "thermo", "orbital_table", # "long_orbital_table", "insolation", "ebm", # "column", "convadj"] #from climlab import radiation # this should ensure that we can still import constants.py as climlab.constants from climlab.utils import constants from climlab.utils import thermo, legendre # some more useful shorcuts #from climlab.model import ebm, column from climlab.model.column import GreyRadiationModel, RadiativeConvectiveModel, BandRCModel from climlab.model.ebm import EBM, EBM_annual, EBM_seasonal from climlab.domain import domain from climlab.domain.field import Field, global_mean from climlab.domain.axis import Axis from climlab.process.process import Process, process_like, get_axes from climlab.process.time_dependent_process import TimeDependentProcess from climlab.process.implicit import ImplicitProcess from climlab.process.diagnostic import DiagnosticProcess from climlab.process.energy_budget import EnergyBudget
__version__ = '0.2.5' # This list defines all the modules that will be loaded if a user invokes # from climLab import * # totally out of date! #__all__ = ["constants", "thermo", "orbital_table", # "long_orbital_table", "insolation", "ebm", # "column", "convadj"] #from climlab import radiation # this should ensure that we can still import constants.py as climlab.constants from climlab.utils import constants from climlab.utils import thermo, legendre # some more useful shorcuts #from climlab.model import ebm, column from climlab.model.column import GreyRadiationModel, RadiativeConvectiveModel, BandRCModel from climlab.model.ebm import EBM, EBM_annual, EBM_seasonal from climlab.domain import domain from climlab.domain.field import Field, global_mean from climlab.domain.axis import Axis from climlab.process.process import Process, process_like, get_axes from climlab.process.time_dependent_process import TimeDependentProcess from climlab.process.implicit import ImplicitProcess from climlab.process.diagnostic import DiagnosticProcess from climlab.process.energy_budget import EnergyBudget
Increment version number to 0.2.5
Increment version number to 0.2.5
Python
mit
brian-rose/climlab,cjcardinale/climlab,cjcardinale/climlab,brian-rose/climlab,cjcardinale/climlab
--- +++ @@ -1,4 +1,4 @@ -__version__ = '0.2.4' +__version__ = '0.2.5' # This list defines all the modules that will be loaded if a user invokes # from climLab import *
ec33927709b1d9ce484e6f243068a334de389aa1
example/app/models.py
example/app/models.py
# Define a custom User class to work with django-social-auth from django.db import models class CustomUserManager(models.Manager): def create_user(self, username, email): return self.model._default_manager.create(username=username) class CustomUser(models.Model): username = models.CharField(max_length=128) last_login = models.DateTimeField(blank=True, null=True) objects = CustomUserManager() def is_authenticated(self): return True from social_auth.signals import pre_update from social_auth.backends.facebook import FacebookBackend def facebook_extra_values(sender, user, response, details, **kwargs): return False pre_update.connect(facebook_extra_values, sender=FacebookBackend)
# Define a custom User class to work with django-social-auth from django.db import models class CustomUserManager(models.Manager): def create_user(self, username, email): return self.model._default_manager.create(username=username) class CustomUser(models.Model): username = models.CharField(max_length=128) last_login = models.DateTimeField(blank=True, null=True) objects = CustomUserManager() def is_authenticated(self): return True
Clean signal handler from example app
Clean signal handler from example app
Python
bsd-3-clause
beswarm/django-social-auth,omab/django-social-auth,adw0rd/django-social-auth,gustavoam/django-social-auth,limdauto/django-social-auth,michael-borisov/django-social-auth,vuchau/django-social-auth,limdauto/django-social-auth,sk7/django-social-auth,caktus/django-social-auth,vxvinh1511/django-social-auth,duoduo369/django-social-auth,michael-borisov/django-social-auth,beswarm/django-social-auth,vxvinh1511/django-social-auth,dongguangming/django-social-auth,qas612820704/django-social-auth,gustavoam/django-social-auth,krvss/django-social-auth,MjAbuz/django-social-auth,mayankcu/Django-social,lovehhf/django-social-auth,VishvajitP/django-social-auth,MjAbuz/django-social-auth,qas612820704/django-social-auth,getsentry/django-social-auth,antoviaque/django-social-auth-norel,omab/django-social-auth,dongguangming/django-social-auth,lovehhf/django-social-auth,caktus/django-social-auth,WW-Digital/django-social-auth,1st/django-social-auth,VishvajitP/django-social-auth,vuchau/django-social-auth
--- +++ @@ -15,13 +15,3 @@ def is_authenticated(self): return True - - -from social_auth.signals import pre_update -from social_auth.backends.facebook import FacebookBackend - - -def facebook_extra_values(sender, user, response, details, **kwargs): - return False - -pre_update.connect(facebook_extra_values, sender=FacebookBackend)
1eab43e1b1402a53c2dec53abe61bcae5f4b3026
robots/admin.py
robots/admin.py
from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from robots.models import Url, Rule from robots.forms import RuleAdminForm class RuleAdmin(admin.ModelAdmin): form = RuleAdminForm fieldsets = ( (None, {'fields': ('robot', 'sites')}), (_('URL patterns'), { 'fields': ('allowed', 'disallowed'), }), (_('Advanced options'), { 'classes': ('collapse',), 'fields': ('crawl_delay',), }), ) list_filter = ('sites',) list_display = ('robot', 'allowed_urls', 'disallowed_urls') search_fields = ('robot', 'allowed__pattern', 'disallowed__pattern') admin.site.register(Url) admin.site.register(Rule, RuleAdmin)
from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from robots.models import Url, Rule from robots.forms import RuleAdminForm class RuleAdmin(admin.ModelAdmin): form = RuleAdminForm fieldsets = ( (None, {'fields': ('robot', 'sites')}), (_('URL patterns'), { 'fields': ('allowed', 'disallowed'), }), (_('Advanced options'), { 'classes': ('collapse',), 'fields': ('crawl_delay',), }), ) list_filter = ('sites',) list_display = ('robot', 'allowed_urls', 'disallowed_urls') search_fields = ('robot', 'allowed__pattern', 'disallowed__pattern') filter_horizontal = ('allowed', 'disallowed') admin.site.register(Url) admin.site.register(Rule, RuleAdmin)
Add filter_horizontal for for allowed and disallowed
Add filter_horizontal for for allowed and disallowed
Python
bsd-3-clause
jazzband/django-robots,jezdez/django-robots,jezdez/django-robots,jscott1971/django-robots,jscott1971/django-robots,jazzband/django-robots
--- +++ @@ -20,6 +20,7 @@ list_filter = ('sites',) list_display = ('robot', 'allowed_urls', 'disallowed_urls') search_fields = ('robot', 'allowed__pattern', 'disallowed__pattern') + filter_horizontal = ('allowed', 'disallowed') admin.site.register(Url) admin.site.register(Rule, RuleAdmin)
4dc2bb7e2973f39dabb267fb8d6782fe61fe36a9
sample/utils.py
sample/utils.py
import os def open_lastrun_file(mode='r'): '''Open and return lastrun file.''' # path to data directory data_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'data') os.makedirs(data_dir, exist_ok=True) # path to lastrun file lastrun_path = os.path.join(data_dir, 'lastrun.txt') return open(lastrun_path, mode)
import os def open_lastrun_file(mode='r'): '''Open and return lastrun file.''' # path to data directory data_dir = os.path.expanduser('~/.local/share/classer/') os.makedirs(data_dir, exist_ok=True) # path to lastrun file lastrun_path = os.path.join(data_dir, 'lastrun.txt') return open(lastrun_path, mode)
Change data dir to ~/.local/share/classer
Change data dir to ~/.local/share/classer
Python
mit
lqmanh/classer
--- +++ @@ -5,7 +5,7 @@ '''Open and return lastrun file.''' # path to data directory - data_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'data') + data_dir = os.path.expanduser('~/.local/share/classer/') os.makedirs(data_dir, exist_ok=True) # path to lastrun file
b95e6069a1faa849b1c5b31daf0dfd4dd4b5be23
electionleaflets/boundaries/models.py
electionleaflets/boundaries/models.py
from django.db import models from legacy.models import Constituency class Boundary(models.Model): id = models.IntegerField(primary_key=True) constituency_id = models.IntegerField() boundary = models.TextField() zoom = models.IntegerField() north = models.FloatField() south = models.FloatField() east = models.FloatField() west = models.FloatField() class Meta: db_table = u'boundaries_boundary'
from django.db import models from legacy.models import Constituency class Boundary(models.Model): constituency = models.ForeignKey( Constituency ) boundary = models.TextField() zoom = models.IntegerField() north = models.FloatField() south = models.FloatField() east = models.FloatField() west = models.FloatField() class Meta: db_table = u'boundaries_boundary'
Put the model back the way it was
Put the model back the way it was
Python
mit
JustinWingChungHui/electionleaflets,electionleaflets/electionleaflets,electionleaflets/electionleaflets,JustinWingChungHui/electionleaflets,DemocracyClub/electionleaflets,JustinWingChungHui/electionleaflets,DemocracyClub/electionleaflets,DemocracyClub/electionleaflets,JustinWingChungHui/electionleaflets
--- +++ @@ -2,8 +2,7 @@ from legacy.models import Constituency class Boundary(models.Model): - id = models.IntegerField(primary_key=True) - constituency_id = models.IntegerField() + constituency = models.ForeignKey( Constituency ) boundary = models.TextField() zoom = models.IntegerField() north = models.FloatField()
969ea8afcb111c68a145cc69791e531303807608
insight_reloaded/tests/test_api.py
insight_reloaded/tests/test_api.py
# -*- coding: utf-8 -*- import json from mock import MagicMock from tornado.testing import AsyncHTTPTestCase from insight_reloaded.api import application from insight_reloaded import __version__ as VERSION class InsightApiHTTPTest(AsyncHTTPTestCase): def get_app(self): return application def test_api_version(self): self.http_client.fetch(self.get_url('/'), self.stop) response = self.wait() body_json = json.loads(response.body) self.assertIn('version', body_json) self.assertIn('insight_reloaded', body_json) self.assertEqual('insight-reloaded', body_json['name']) self.assertEqual(VERSION, body_json['version']) def test_api_request(self): self.http_client.fetch(self.get_url('/') + u'?url=http://my_file_url.com/file.pdf', self.stop) response = self.wait() json_body = json.loads(response.body) self.assertIn('insight_reloaded', json_body) self.assertEqual(json_body['number_in_queue'], 1) def test_api_url_missing(self): self.http_client.fetch(self.get_url('/') + '?arg=foobar', self.stop) response = self.wait() self.assertEqual(response.code, 404)
# -*- coding: utf-8 -*- import json from mock import MagicMock from tornado.testing import AsyncHTTPTestCase from insight_reloaded.api import application from insight_reloaded import __version__ as VERSION from tornado import ioloop class InsightApiHTTPTest(AsyncHTTPTestCase): def get_new_ioloop(self): return ioloop.IOLoop.instance() def get_app(self): return application def test_api_version(self): self.http_client.fetch(self.get_url('/'), self.stop) response = self.wait() body_json = json.loads(response.body) self.assertIn('version', body_json) self.assertIn('insight_reloaded', body_json) self.assertEqual('insight-reloaded', body_json['name']) self.assertEqual(VERSION, body_json['version']) def test_api_request(self): self.http_client.fetch(self.get_url('/') + u'?url=http://my_file_url.com/file.pdf', self.stop) response = self.wait() json_body = json.loads(response.body) self.assertIn('insight_reloaded', json_body) self.assertEqual(json_body['number_in_queue'], 1) def test_api_url_missing(self): self.http_client.fetch(self.get_url('/') + '?arg=foobar', self.stop) response = self.wait() self.assertEqual(response.code, 404)
Use global ioloop as we don't pass test ioloop to tornado redis
Use global ioloop as we don't pass test ioloop to tornado redis
Python
bsd-3-clause
novapost/insight-reloaded
--- +++ @@ -5,8 +5,14 @@ from insight_reloaded.api import application from insight_reloaded import __version__ as VERSION +from tornado import ioloop + class InsightApiHTTPTest(AsyncHTTPTestCase): + + def get_new_ioloop(self): + return ioloop.IOLoop.instance() + def get_app(self): return application
a3a1ead4954500b29a1474b333336f90a95718db
thecodingloverss.py
thecodingloverss.py
import feedparser, sys, urllib2 from bs4 import BeautifulSoup as BS from feedgen.feed import FeedGenerator from flask import Flask app = Flask(__name__) @app.route('/') def index(): d = feedparser.parse('http://thecodinglove.com/rss') fg = FeedGenerator() fg.title('The coding love with images.') fg.link(href='http://thecodinglove.com') fg.description('The coding love with images.') for entry in d.entries: contributor = entry.summary_detail.value href = entry.links[0].href published = entry.published title = entry.title bs = BS(urllib2.urlopen(href), "lxml") image = bs.p.img.get('src') imgsrc='<img src="%s">' % image description = "%s <br/> %s" % (imgsrc, contributor) fe = fg.add_entry() fe.id(href) fe.link(href=href) fe.pubdate(published) fe.title(title) fe.description(description) rssfeed = fg.rss_str(pretty=True) return rssfeed
import feedparser, sys, urllib2 from bs4 import BeautifulSoup as BS from feedgen.feed import FeedGenerator from flask import Flask app = Flask(__name__) @app.route('/') def index(): d = feedparser.parse('http://thecodinglove.com/rss') fg = FeedGenerator() fg.title('The coding love with images.') fg.link(href='http://thecodinglove.com') fg.description('The coding love with images.') for entry in d.entries: try: contributor = entry.summary_detail.value except: contributor = "n/a" href = entry.links[0].href published = entry.published title = entry.title bs = BS(urllib2.urlopen(href), "lxml") image = bs.p.img.get('src') imgsrc='<img src="%s">' % image description = "%s <br/> %s" % (imgsrc, contributor) fe = fg.add_entry() fe.id(href) fe.link(href=href) fe.pubdate(published) fe.title(title) fe.description(description) rssfeed = fg.rss_str(pretty=True) return rssfeed
Check that contributor exist in the source feed.
Check that contributor exist in the source feed. Otherwise things will break sooner or later.
Python
mit
chrillux/thecodingloverss
--- +++ @@ -18,7 +18,11 @@ for entry in d.entries: - contributor = entry.summary_detail.value + try: + contributor = entry.summary_detail.value + except: + contributor = "n/a" + href = entry.links[0].href published = entry.published title = entry.title
95234ec552c7157ed9020e90f19b2abd1f813735
backend/uclapi/gunicorn_config.py
backend/uclapi/gunicorn_config.py
import multiprocessing bind = "127.0.0.1:9000" # Run cores * 4 + 1 workers in gunicorn # This is set deliberately high in case of long Oracle transactions locking Django up workers = multiprocessing.cpu_count() * 4 + 1 threads = multiprocessing.cpu_count() * 4 # Using gaiohttp because of the long blocking calls to the Oracle database worker_class = "gaiohttp" daemon = True proc_name = "uclapi_gunicorn"
import multiprocessing bind = "127.0.0.1:9000" # Run cores * 4 + 1 workers in gunicorn # This is set deliberately high in case of long Oracle transactions locking Django up workers = multiprocessing.cpu_count() * 4 + 1 threads = multiprocessing.cpu_count() * 4 # Using gaiohttp because of the long blocking calls to the Oracle database worker_class = "gaiohttp" daemon = False proc_name = "uclapi_gunicorn"
Disable daemonised mode so that Supervisor can properly control gunicorn
Disable daemonised mode so that Supervisor can properly control gunicorn
Python
mit
uclapi/uclapi,uclapi/uclapi,uclapi/uclapi,uclapi/uclapi
--- +++ @@ -10,6 +10,6 @@ # Using gaiohttp because of the long blocking calls to the Oracle database worker_class = "gaiohttp" -daemon = True +daemon = False proc_name = "uclapi_gunicorn"
d137f2cf16b088e2d9722568fce6dad89d950016
Cauldron/ext/expose/keywords.py
Cauldron/ext/expose/keywords.py
# -*- coding: utf-8 -*- """ An extension for keywords which expose pieces of native python objects. """ from __future__ import absolute_import from Cauldron.types import Integer, DispatcherKeywordType from Cauldron.exc import NoWriteNecessary __all__ = ['ExposeAttribute'] class ExposeAttribute(DispatcherKeywordType): """This keyword exposes a specific attribute from an object. """ KTL_REGISTERED = False def __init__(self, name, service, obj, attribute, *args, **kwargs): self._object = obj self._attribute = attribute super(HeartbeatKeyword, self).__init__(name, service, *args, **kwargs) def read(self): """Read this keyword from the target object.""" return getattr(self._object, self._attribute) def write(self, value): """Write this keyword to the target object.""" setattr(self._object, self._attribute, value)
# -*- coding: utf-8 -*- """ An extension for keywords which expose pieces of native python objects. """ from __future__ import absolute_import from Cauldron.types import Integer, DispatcherKeywordType from Cauldron.exc import NoWriteNecessary __all__ = ['ExposeAttribute'] class ExposeAttribute(DispatcherKeywordType): """This keyword exposes a specific attribute from an object. """ KTL_REGISTERED = False def __init__(self, name, service, obj, attribute, *args, **kwargs): self._object = obj self._attribute = attribute super(ExposeAttribute, self).__init__(name, service, *args, **kwargs) def read(self): """Read this keyword from the target object.""" return getattr(self._object, self._attribute) def write(self, value): """Write this keyword to the target object.""" setattr(self._object, self._attribute, value)
FIx a bug in exposed attribute keyword
FIx a bug in exposed attribute keyword
Python
bsd-3-clause
alexrudy/Cauldron
--- +++ @@ -18,7 +18,7 @@ def __init__(self, name, service, obj, attribute, *args, **kwargs): self._object = obj self._attribute = attribute - super(HeartbeatKeyword, self).__init__(name, service, *args, **kwargs) + super(ExposeAttribute, self).__init__(name, service, *args, **kwargs) def read(self): """Read this keyword from the target object."""
2a3ffa2e8bde58d4e3dec053ad437842eac80106
thing/middleware.py
thing/middleware.py
import datetime class LastSeenMiddleware(object): def process_request(self, request): if not request.user.is_authenticated(): return None profile = request.user.get_profile() profile.last_seen = datetime.datetime.now() profile.save() return None
import datetime class LastSeenMiddleware(object): def process_request(self, request): if not request.user.is_authenticated(): return None profile = request.user.get_profile() profile.last_seen = datetime.datetime.utcnow() profile.save() return None
Change LastSeenMiddleware to store last_seen as utcnow() instead of now()
Change LastSeenMiddleware to store last_seen as utcnow() instead of now()
Python
bsd-2-clause
cmptrgeekken/evething,Gillingham/evething,Gillingham/evething,madcowfred/evething,Gillingham/evething,madcowfred/evething,cmptrgeekken/evething,cmptrgeekken/evething,madcowfred/evething,Gillingham/evething,madcowfred/evething,cmptrgeekken/evething,cmptrgeekken/evething
--- +++ @@ -5,6 +5,6 @@ if not request.user.is_authenticated(): return None profile = request.user.get_profile() - profile.last_seen = datetime.datetime.now() + profile.last_seen = datetime.datetime.utcnow() profile.save() return None
75615b2328e521b6bb37321d1cd7dc75c4d3bfef
hecate/core/topology/border.py
hecate/core/topology/border.py
from hecate.core.topology.mixins import DimensionsMixin class Border(DimensionsMixin): """ Base class for all types of borders. """ def __init__(self): self.topology = None class TorusBorder(Border): supported_dimensions = list(range(1, 100)) def wrap_coords(self, coord_prefix): code = "" for i in range(self.dimensions): code += "{x}{i} %= {w}{i};\n".format( x=coord_prefix, i=i, w=self.topology.lattice.width_prefix ) return code
from hecate.core.topology.mixins import DimensionsMixin class Border(DimensionsMixin): """ Base class for all types of borders. """ def __init__(self): self.topology = None class TorusBorder(Border): supported_dimensions = list(range(1, 100)) def wrap_coords(self, coord_prefix): code = "" for i in range(self.dimensions): code += "{x}{i} = ({x}{i} + {w}{i}) % {w}{i};\n".format( x=coord_prefix, i=i, w=self.topology.lattice.width_prefix ) return code
Fix incorrect TorusBorder wrapping in negative direction
Fix incorrect TorusBorder wrapping in negative direction
Python
mit
a5kin/hecate,a5kin/hecate
--- +++ @@ -16,7 +16,7 @@ def wrap_coords(self, coord_prefix): code = "" for i in range(self.dimensions): - code += "{x}{i} %= {w}{i};\n".format( + code += "{x}{i} = ({x}{i} + {w}{i}) % {w}{i};\n".format( x=coord_prefix, i=i, w=self.topology.lattice.width_prefix )
6189ded93330e9483e6d677e26b49319c649c9f0
test/handler_fixture.py
test/handler_fixture.py
import unittest import tempfile import shutil import groundstation.node import groundstation.transfer.response import groundstation.transfer.request from groundstation.station import Station class MockStream(list): def enqueue(self, *args, **kwargs): self.append(*args, **kwargs) def MockTERMINATE(): pass class MockStation(object): def __init__(self): self.tmpdir = tempfile.mkdtemp() self.node = groundstation.node.Node() self.station = Station(self.tmpdir, self.node) self.stream = MockStream() self.TERMINATE = MockTERMINATE def _Response(self, *args, **kwargs): kwargs['station'] = self.station return groundstation.transfer.response.Response(*args, **kwargs) def _Request(self, *args, **kwargs): kwargs['station'] = self.station return groundstation.transfer.request.Request(*args, **kwargs) def __del__(self): shutil.rmtree(self.tmpdir) @property def id(self): return "test_station" class StationHandlerTestCase(unittest.TestCase): def setUp(self): self.station = MockStation()
import unittest import tempfile import shutil import uuid import groundstation.node import groundstation.transfer.response import groundstation.transfer.request from groundstation.station import Station class MockStream(list): def enqueue(self, *args, **kwargs): self.append(*args, **kwargs) def MockTERMINATE(): pass class MockStation(object): def __init__(self, **kwargs): self.tmpdir = tempfile.mkdtemp() self.node = groundstation.node.Node() self.station = Station(self.tmpdir, self.node) self.stream = MockStream() self.TERMINATE = MockTERMINATE if 'origin' in kwargs: self.origin = kwargs['origin'] else: self.origin = uuid.uuid1() def _Response(self, *args, **kwargs): kwargs['station'] = self.station return groundstation.transfer.response.Response(*args, **kwargs) def _Request(self, *args, **kwargs): kwargs['station'] = self.station return groundstation.transfer.request.Request(*args, **kwargs) def __del__(self): shutil.rmtree(self.tmpdir) @property def id(self): return "test_station" class StationHandlerTestCase(unittest.TestCase): def setUp(self): self.station = MockStation()
Implement an origin on MockStation
Implement an origin on MockStation
Python
mit
richo/groundstation,richo/groundstation,richo/groundstation,richo/groundstation,richo/groundstation
--- +++ @@ -1,6 +1,7 @@ import unittest import tempfile import shutil +import uuid import groundstation.node import groundstation.transfer.response @@ -18,12 +19,16 @@ class MockStation(object): - def __init__(self): + def __init__(self, **kwargs): self.tmpdir = tempfile.mkdtemp() self.node = groundstation.node.Node() self.station = Station(self.tmpdir, self.node) self.stream = MockStream() self.TERMINATE = MockTERMINATE + if 'origin' in kwargs: + self.origin = kwargs['origin'] + else: + self.origin = uuid.uuid1() def _Response(self, *args, **kwargs): kwargs['station'] = self.station
39b6868042e95a5a412d3d3b9fa5f735e35ddb2c
umodbus/__init__.py
umodbus/__init__.py
from logging import getLogger try: from logging import NullHandler # For Python 2.7 compatibility. except ImportError: from logging import Handler class NullHandler(Handler): def emit(self, record): pass log = getLogger('uModbus') log.addHandler(NullHandler()) from .server import get_server # NOQA
from logging import getLogger, NullHandler log = getLogger('uModbus') log.addHandler(NullHandler()) from .server import get_server # NOQA
Remove another piece of unreachable code.
Remove another piece of unreachable code.
Python
mpl-2.0
AdvancedClimateSystems/python-modbus,AdvancedClimateSystems/uModbus
--- +++ @@ -1,14 +1,4 @@ -from logging import getLogger - -try: - from logging import NullHandler -# For Python 2.7 compatibility. -except ImportError: - from logging import Handler - - class NullHandler(Handler): - def emit(self, record): - pass +from logging import getLogger, NullHandler log = getLogger('uModbus') log.addHandler(NullHandler())
bc8675b170748b51403fb31d03ed06399268cb7b
examples/test_deferred_asserts.py
examples/test_deferred_asserts.py
""" This test demonstrates the use of deferred asserts. Deferred asserts won't raise exceptions from failures until either process_deferred_asserts() is called, or the test reaches the tearDown() step. """ import pytest from seleniumbase import BaseCase class DeferredAssertTests(BaseCase): @pytest.mark.expected_failure def test_deferred_asserts(self): self.open("https://xkcd.com/993/") self.wait_for_element("#comic") print("\n(This test should fail)") self.deferred_assert_element('img[alt="Brand Identity"]') self.deferred_assert_element('img[alt="Rocket Ship"]') # Will Fail self.deferred_assert_element("#comicmap") self.deferred_assert_text("Fake Item", "#middleContainer") # Will Fail self.deferred_assert_text("Random", "#middleContainer") self.deferred_assert_element('a[name="Super Fake !!!"]') # Will Fail self.process_deferred_asserts()
""" This test demonstrates the use of deferred asserts. Deferred asserts won't raise exceptions from failures until either process_deferred_asserts() is called, or the test reaches the tearDown() step. Requires version 2.1.6 or newer for the deferred_assert_exact_text() method. """ import pytest from seleniumbase import BaseCase class DeferredAssertTests(BaseCase): @pytest.mark.expected_failure def test_deferred_asserts(self): self.open("https://xkcd.com/993/") self.wait_for_element("#comic") print("\n(This test should fail)") self.deferred_assert_element('img[alt="Brand Identity"]') self.deferred_assert_element('img[alt="Rocket Ship"]') # Will Fail self.deferred_assert_element("#comicmap") self.deferred_assert_text("Fake Item", "#middleContainer") # Will Fail self.deferred_assert_text("Random", "#middleContainer") self.deferred_assert_element('a[name="Super Fake !!!"]') # Will Fail self.deferred_assert_exact_text("Brand Identity", "#ctitle") self.deferred_assert_exact_text("Fake Food", "#comic") # Will Fail self.process_deferred_asserts()
Update an example test that uses deferred asserts
Update an example test that uses deferred asserts
Python
mit
mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase
--- +++ @@ -2,6 +2,7 @@ This test demonstrates the use of deferred asserts. Deferred asserts won't raise exceptions from failures until either process_deferred_asserts() is called, or the test reaches the tearDown() step. +Requires version 2.1.6 or newer for the deferred_assert_exact_text() method. """ import pytest from seleniumbase import BaseCase @@ -19,4 +20,6 @@ self.deferred_assert_text("Fake Item", "#middleContainer") # Will Fail self.deferred_assert_text("Random", "#middleContainer") self.deferred_assert_element('a[name="Super Fake !!!"]') # Will Fail + self.deferred_assert_exact_text("Brand Identity", "#ctitle") + self.deferred_assert_exact_text("Fake Food", "#comic") # Will Fail self.process_deferred_asserts()
f89d59d89af12473c609948bae518151a9adc64a
accelerator/migrations/0074_update_url_to_community.py
accelerator/migrations/0074_update_url_to_community.py
# Generated by Django 2.2.10 on 2021-11-05 12:29 from django.db import migrations from django.db.models.query_utils import Q def update_url_to_community(apps, schema_editor): people_url = "/people" mentor_url = "/directory" community_url = "/community" SiteRedirectPage = apps.get_model('accelerator', 'SiteRedirectPage') for siteredirectpage in SiteRedirectPage.objects.all(): has_old_url = siteredirectpage.objects.filter(Q(new_url=people_url)| Q(new_url=mentor_url)) if has_old_url.exists(): has_old_url.update(new_url=community_url) class Migration(migrations.Migration): dependencies = [ ('accelerator', '0073_auto_20210909_1706'), ] operations = [ migrations.RunPython(update_url_to_community, migrations.RunPython.noop) ]
# Generated by Django 2.2.10 on 2021-11-05 12:29 from django.db import migrations from django.db.models.query_utils import Q def update_url_to_community(apps, schema_editor): people_url = "/people" mentor_url = "/directory" community_url = "/community" SiteRedirectPage = apps.get_model('accelerator', 'SiteRedirectPage') SiteRedirectPage.objects.filter(Q(new_url=people_url)| Q(new_url=mentor_url)).update(new_url=community_url) class Migration(migrations.Migration): dependencies = [ ('accelerator', '0073_auto_20210909_1706'), ] operations = [ migrations.RunPython(update_url_to_community, migrations.RunPython.noop) ]
Fix the query for updating the people and mentor urls to community url
[AC-9046] Fix the query for updating the people and mentor urls to community url
Python
mit
masschallenge/django-accelerator,masschallenge/django-accelerator
--- +++ @@ -9,10 +9,7 @@ mentor_url = "/directory" community_url = "/community" SiteRedirectPage = apps.get_model('accelerator', 'SiteRedirectPage') - for siteredirectpage in SiteRedirectPage.objects.all(): - has_old_url = siteredirectpage.objects.filter(Q(new_url=people_url)| Q(new_url=mentor_url)) - if has_old_url.exists(): - has_old_url.update(new_url=community_url) + SiteRedirectPage.objects.filter(Q(new_url=people_url)| Q(new_url=mentor_url)).update(new_url=community_url) class Migration(migrations.Migration):
672d491fc88683531e12e5576e10bc5e7d9a71bd
bindings/python/testsuite/test_timeline_file_source.py
bindings/python/testsuite/test_timeline_file_source.py
import gst from common import TestCase import ges class TimelineFileSource(TestCase): def testTimelineFileSource(self): src = ges.TimelineFileSource("blahblahblah") src.set_mute(True) src.set_max_duration(long(100)) src.set_supported_formats("video") assert (src.get_supported_formats().value_nicks[0] == "video") src.set_is_image(True) assert (src.get_max_duration() == 100) assert (src.is_image() == True) assert (src.get_uri() == "blahblahblah")
import gst from common import TestCase import ges class TimelineFileSource(TestCase): def testTimelineFileSource(self): src = ges.TimelineFileSource("file://blahblahblah") src.set_mute(True) src.set_max_duration(long(100)) src.set_supported_formats("video") assert (src.get_supported_formats().value_nicks[0] == "video") src.set_is_image(True) assert (src.get_max_duration() == 100) assert (src.is_image() == True) assert (src.get_uri() == "file://blahblahblah")
Fix the timeline_file_source test suite
pyges: Fix the timeline_file_source test suite Can't create a GESTimelineFileSource if you don't have the protocol in the uri
Python
lgpl-2.1
cfoch/gst-editing-services,MathieuDuponchelle/PitiviGes,volodymyrrudyi/gst-editing-services,cfoch/ges,freesteph/gst-editing-services,cfoch/gst-editing-services,cfoch/ges,freesteph/gst-editing-services,cfoch/ges,pitivi/gst-editing-services,MathieuDuponchelle/PitiviGes,volodymyrrudyi/gst-editing-services,cfoch/ges,pitivi/gst-editing-services,pitivi/gst-editing-services,cfoch/gst-editing-services,pitivi/gst-editing-services,MathieuDuponchelle/PitiviGes,freesteph/gst-editing-services,MathieuDuponchelle/PitiviGes,volodymyrrudyi/gst-editing-services,cfoch/gst-editing-services
--- +++ @@ -6,7 +6,7 @@ class TimelineFileSource(TestCase): def testTimelineFileSource(self): - src = ges.TimelineFileSource("blahblahblah") + src = ges.TimelineFileSource("file://blahblahblah") src.set_mute(True) src.set_max_duration(long(100)) @@ -15,4 +15,4 @@ src.set_is_image(True) assert (src.get_max_duration() == 100) assert (src.is_image() == True) - assert (src.get_uri() == "blahblahblah") + assert (src.get_uri() == "file://blahblahblah")
1456ebbf7621d257b7f67117a34bcf4c35de41d3
K2fov/tests/test_k2onsilicon.py
K2fov/tests/test_k2onsilicon.py
"""Test whether the K2onSilicon command-line tool works.""" import tempfile from ..K2onSilicon import K2onSilicon_main def test_K2onSilicon(): """Test the basics: does K2onSilicon run without error on a dummy file?""" csv = '0, 0, 0\n' with tempfile.NamedTemporaryFile() as temp: try: # Python 3 temp.write(bytes(csv, 'utf-8')) except TypeError: # Legacy Python temp.write(csv) temp.flush() K2onSilicon_main(args=[temp.name, "1"])
"""Test whether the `K2onSilicon` command-line tool works.""" import tempfile import numpy as np from ..K2onSilicon import K2onSilicon_main def test_K2onSilicon(): """Test the basics: does K2onSilicon run without error on a dummy file?""" csv = '269.5, -28.5, 12\n0, 0, 20\n' with tempfile.NamedTemporaryFile() as temp: try: # Python 3 temp.write(bytes(csv, 'utf-8')) except TypeError: # Legacy Python temp.write(csv) temp.flush() K2onSilicon_main(args=[temp.name, "9"]) # Verify the output output_fn = "targets_siliconFlag.csv" ra, dec, mag, status = np.atleast_2d( np.genfromtxt( output_fn, usecols=[0, 1, 2, 3], delimiter=',' ) ).T # The first target is one silicon in C9, the second is not assert(int(status[0]) == 2) assert(int(status[1]) == 0) # Sanity check of the other columns assert(ra[0] == 269.5) assert(dec[0] == -28.5) assert(mag[0] == 12) assert(ra[1] == 0) assert(dec[1] == 0) assert(mag[1] == 20)
Make the K2onSilicon unit test more comprehensive
Make the K2onSilicon unit test more comprehensive
Python
mit
KeplerGO/K2fov,mrtommyb/K2fov
--- +++ @@ -1,12 +1,13 @@ -"""Test whether the K2onSilicon command-line tool works.""" +"""Test whether the `K2onSilicon` command-line tool works.""" import tempfile +import numpy as np from ..K2onSilicon import K2onSilicon_main def test_K2onSilicon(): """Test the basics: does K2onSilicon run without error on a dummy file?""" - csv = '0, 0, 0\n' + csv = '269.5, -28.5, 12\n0, 0, 20\n' with tempfile.NamedTemporaryFile() as temp: try: # Python 3 @@ -15,4 +16,24 @@ # Legacy Python temp.write(csv) temp.flush() - K2onSilicon_main(args=[temp.name, "1"]) + K2onSilicon_main(args=[temp.name, "9"]) + + # Verify the output + output_fn = "targets_siliconFlag.csv" + ra, dec, mag, status = np.atleast_2d( + np.genfromtxt( + output_fn, + usecols=[0, 1, 2, 3], + delimiter=',' + ) + ).T + # The first target is one silicon in C9, the second is not + assert(int(status[0]) == 2) + assert(int(status[1]) == 0) + # Sanity check of the other columns + assert(ra[0] == 269.5) + assert(dec[0] == -28.5) + assert(mag[0] == 12) + assert(ra[1] == 0) + assert(dec[1] == 0) + assert(mag[1] == 20)
98f6a07188cc9a9aa9373c3795db49b1e576c2a8
iatidq/dqimportpublisherconditions.py
iatidq/dqimportpublisherconditions.py
# IATI Data Quality, tools for Data QA on IATI-formatted publications # by Mark Brough, Martin Keegan, Ben Webb and Jennifer Smith # # Copyright (C) 2013 Publish What You Fund # # This programme is free software; you may redistribute and/or modify # it under the terms of the GNU Affero General Public License v3.0 from iatidq import db import models import csv import util import urllib2 def _importPCs(fh, local=True): results = {} for n, line in enumerate(fh): text = line.strip('\n') results[n]=text import dqparseconditions test_functions = dqparseconditions.parsePC(results) tested_results = [] for n, line in results.items(): data = test_functions[n](line) data["description"] = line tested_results.append(data) return tested_results def importPCsFromFile(filename='tests/organisation_structures.txt', local=True): with file(filename) as fh: return _importPCs(fh, local=True) def importPCsFromUrl(url): fh = urllib2.urlopen(url) return _importPCs(fh, local=False) if __name__ == "__main__": importPCs('../tests/organisation_structures.txt')
# IATI Data Quality, tools for Data QA on IATI-formatted publications # by Mark Brough, Martin Keegan, Ben Webb and Jennifer Smith # # Copyright (C) 2013 Publish What You Fund # # This programme is free software; you may redistribute and/or modify # it under the terms of the GNU Affero General Public License v3.0 from iatidq import db import models import csv import util import urllib2 def _parsePCresults(results): import dqparseconditions test_functions = dqparseconditions.parsePC(results) tested_results = [] for n, line in results.items(): data = test_functions[n](line) data["description"] = line tested_results.append(data) return tested_results def importPCsFromText(text): results = {} for n, line in enumerate(text.split("\n")): results[n]=line return _parsePCresults(results) def _importPCs(fh, local=True): results = {} for n, line in enumerate(fh): text = line.strip('\n') results[n]=text return _parsePCresults(results) def importPCsFromFile(filename='tests/organisation_structures.txt', local=True): with file(filename) as fh: return _importPCs(fh, local=True) def importPCsFromUrl(url): fh = urllib2.urlopen(url) return _importPCs(fh, local=False) if __name__ == "__main__": importPCs('../tests/organisation_structures.txt')
Allow publisher conditions to be imported from text
Allow publisher conditions to be imported from text
Python
agpl-3.0
pwyf/IATI-Data-Quality,pwyf/IATI-Data-Quality,pwyf/IATI-Data-Quality,pwyf/IATI-Data-Quality
--- +++ @@ -14,13 +14,7 @@ import util import urllib2 -def _importPCs(fh, local=True): - - results = {} - for n, line in enumerate(fh): - text = line.strip('\n') - results[n]=text - +def _parsePCresults(results): import dqparseconditions test_functions = dqparseconditions.parsePC(results) tested_results = [] @@ -30,6 +24,19 @@ tested_results.append(data) return tested_results + +def importPCsFromText(text): + results = {} + for n, line in enumerate(text.split("\n")): + results[n]=line + return _parsePCresults(results) + +def _importPCs(fh, local=True): + results = {} + for n, line in enumerate(fh): + text = line.strip('\n') + results[n]=text + return _parsePCresults(results) def importPCsFromFile(filename='tests/organisation_structures.txt', local=True): with file(filename) as fh:
82c57b4fad49b171cd0833b38867474d6578220c
client/examples/followbot.py
client/examples/followbot.py
from botchallenge import * USERNAME = "" # Put your minecraft username here SERVER = "" # Put the address of the minecraft server here robot = Robot(USERNAME, SERVER) while True: me = robot.get_location() owner = robot.get_owner_location() print(me.distance(owner)) if me.distance(owner) > 4: d = robot.find_path(owner) robot.turn(d) robot.move(d)
from botchallenge import * import time USERNAME = "" # Put your minecraft username here SERVER = "" # Put the address of the minecraft server here robot = Robot(USERNAME, SERVER) while True: me = robot.get_location() owner = robot.get_owner_location() print(me.distance(owner)) if me.distance(owner) > 4: d = robot.find_path(owner) robot.turn(d) robot.move(d) else: time.sleep(2)
Add timer to follow bot
Add timer to follow bot
Python
mit
Rafiot/botchallenge,Rafiot/botchallenge,Rafiot/botchallenge,Rafiot/botchallenge
--- +++ @@ -1,5 +1,6 @@ from botchallenge import * +import time USERNAME = "" # Put your minecraft username here SERVER = "" # Put the address of the minecraft server here @@ -15,4 +16,6 @@ d = robot.find_path(owner) robot.turn(d) robot.move(d) + else: + time.sleep(2)
dda641ad312fea5c0274618bea8025625083ea6c
utils/celery_worker.py
utils/celery_worker.py
import os import sys # Append .. to sys path sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import multiscanner from celery import Celery from celery.contrib.batches import Batches app = Celery('celery_worker', broker='pyamqp://guest@localhost//') @app.task(base=Batches, flush_every=100, flush_interval=10) def multiscanner_celery(filelist, config=multiscanner.CONFIG): ''' TODO: Add other ars + config options... This function essentially takes in a file list and runs multiscanner on them. Results are stored in the storage configured in storage.ini. Usage: from celery_worker import multiscanner_celery multiscanner_celery.delay([list, of, files, to, scan]) ''' storage_conf = multiscanner.common.get_storage_config_path(config) storage_handler = multiscanner.storage.StorageHandler(configfile=storage_conf) resultlist = multiscanner.multiscan(filelist, configfile=config) results = multiscanner.parse_reports(resultlist, python=True) storage_handler.store(results, wait=False) storage_handler.close() return results
import os import sys # Append .. to sys path sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import multiscanner from celery import Celery app = Celery('celery_worker', broker='pyamqp://guest@localhost//') @app.task def multiscanner_celery(filelist, config=multiscanner.CONFIG): ''' TODO: Add other ars + config options... This function essentially takes in a file list and runs multiscanner on them. Results are stored in the storage configured in storage.ini. Usage: from celery_worker import multiscanner_celery multiscanner_celery.delay([list, of, files, to, scan]) ''' storage_conf = multiscanner.common.get_storage_config_path(config) storage_handler = multiscanner.storage.StorageHandler(configfile=storage_conf) resultlist = multiscanner.multiscan(filelist, configfile=config) results = multiscanner.parse_reports(resultlist, python=True) storage_handler.store(results, wait=False) storage_handler.close() return results
Remove batching code. (not in celery contrib)
Remove batching code. (not in celery contrib)
Python
mpl-2.0
MITRECND/multiscanner,MITRECND/multiscanner,awest1339/multiscanner,jmlong1027/multiscanner,jmlong1027/multiscanner,mitre/multiscanner,awest1339/multiscanner,mitre/multiscanner,mitre/multiscanner,jmlong1027/multiscanner,jmlong1027/multiscanner,awest1339/multiscanner,awest1339/multiscanner
--- +++ @@ -5,11 +5,10 @@ import multiscanner from celery import Celery -from celery.contrib.batches import Batches app = Celery('celery_worker', broker='pyamqp://guest@localhost//') -@app.task(base=Batches, flush_every=100, flush_interval=10) +@app.task def multiscanner_celery(filelist, config=multiscanner.CONFIG): ''' TODO: Add other ars + config options...
2cadf977592bd1082f5914cf365849d3f9897b9c
admin/common_auth/models.py
admin/common_auth/models.py
from django.contrib.auth.models import ( AbstractBaseUser, PermissionsMixin, BaseUserManager, ) from django.db import models class MyUserManager(BaseUserManager): def create_user(self, email, password=None): if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): user = self.create_user(email, password=password, ) user.is_superuser = True user.is_admin = True user.is_staff = True user.is_active = True user.save(using=self._db) return user def prereg_users(self): return self.filter(groups__name='prereg_group') class MyUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) first_name = models.CharField(max_length=30, blank=False) last_name = models.CharField(max_length=30, blank=False) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) confirmed = models.BooleanField(default=False) osf_id = models.CharField(max_length=5, blank=True) desk_token = models.CharField(max_length=45, blank=True) desk_token_secret = models.CharField(max_length=45, blank=True) objects = MyUserManager() USERNAME_FIELD = 'email' def get_full_name(self): return ('{0} {1}'.format(self.first_name, self.last_name)).strip() or self.email def get_short_name(self): # The user is identified by their email address return self.email def __unicode__(self): return self.email class Meta: ordering = ['email'] @property def osf_user(self): # import on call to avoid interference w/ django's manage.py commands like collectstatic from website.models import User as OsfUserModel if not self.osf_id: raise RuntimeError('This user does not have an associated Osf User') return OsfUserModel.load(self.osf_id) def is_in_group(self, group): return self.groups.filter(name=group).exists() def group_names(self): return self.groups.all().values_list('name', flat=True)
from django.db import models class AdminProfile(models.Model): user = models.OneToOneField('osf.OSFUser', related_name='admin_profile') desk_token = models.CharField(max_length=45, blank=True) desk_token_secret = models.CharField(max_length=45, blank=True)
Remove MyUser in favor of AdminProfile and OSFUser
Remove MyUser in favor of AdminProfile and OSFUser Admin users are now the same as the OSFUser - AdminProfile gives access to a few extra fields related to desk keys. AdminProfile has a one to one relationship with a OSFUser.
Python
apache-2.0
mfraezz/osf.io,mattclark/osf.io,HalcyonChimera/osf.io,caneruguz/osf.io,Johnetordoff/osf.io,Nesiehr/osf.io,acshi/osf.io,chrisseto/osf.io,mattclark/osf.io,pattisdr/osf.io,CenterForOpenScience/osf.io,brianjgeiger/osf.io,Nesiehr/osf.io,crcresearch/osf.io,Nesiehr/osf.io,hmoco/osf.io,aaxelb/osf.io,brianjgeiger/osf.io,TomBaxter/osf.io,hmoco/osf.io,monikagrabowska/osf.io,cslzchen/osf.io,hmoco/osf.io,Johnetordoff/osf.io,HalcyonChimera/osf.io,mluo613/osf.io,alexschiller/osf.io,TomBaxter/osf.io,brianjgeiger/osf.io,mfraezz/osf.io,cslzchen/osf.io,chrisseto/osf.io,crcresearch/osf.io,aaxelb/osf.io,alexschiller/osf.io,acshi/osf.io,mluo613/osf.io,binoculars/osf.io,icereval/osf.io,cwisecarver/osf.io,cwisecarver/osf.io,monikagrabowska/osf.io,monikagrabowska/osf.io,monikagrabowska/osf.io,binoculars/osf.io,mluo613/osf.io,cslzchen/osf.io,HalcyonChimera/osf.io,caneruguz/osf.io,TomBaxter/osf.io,Nesiehr/osf.io,adlius/osf.io,baylee-d/osf.io,adlius/osf.io,icereval/osf.io,chennan47/osf.io,mfraezz/osf.io,hmoco/osf.io,felliott/osf.io,baylee-d/osf.io,Johnetordoff/osf.io,felliott/osf.io,cwisecarver/osf.io,acshi/osf.io,caseyrollins/osf.io,CenterForOpenScience/osf.io,erinspace/osf.io,acshi/osf.io,laurenrevere/osf.io,CenterForOpenScience/osf.io,binoculars/osf.io,adlius/osf.io,saradbowman/osf.io,CenterForOpenScience/osf.io,alexschiller/osf.io,mluo613/osf.io,sloria/osf.io,caneruguz/osf.io,mattclark/osf.io,sloria/osf.io,acshi/osf.io,mluo613/osf.io,pattisdr/osf.io,leb2dg/osf.io,icereval/osf.io,erinspace/osf.io,saradbowman/osf.io,aaxelb/osf.io,erinspace/osf.io,felliott/osf.io,monikagrabowska/osf.io,baylee-d/osf.io,leb2dg/osf.io,chrisseto/osf.io,laurenrevere/osf.io,brianjgeiger/osf.io,cwisecarver/osf.io,sloria/osf.io,cslzchen/osf.io,chennan47/osf.io,chennan47/osf.io,mfraezz/osf.io,pattisdr/osf.io,caseyrollins/osf.io,chrisseto/osf.io,aaxelb/osf.io,caseyrollins/osf.io,laurenrevere/osf.io,alexschiller/osf.io,leb2dg/osf.io,alexschiller/osf.io,adlius/osf.io,Johnetordoff/osf.io,felliott/osf.io,HalcyonChimera/osf.io,leb2dg/osf.io,caneruguz/osf.io,crcresearch/osf.io
--- +++ @@ -1,83 +1,9 @@ -from django.contrib.auth.models import ( - AbstractBaseUser, - PermissionsMixin, - BaseUserManager, -) from django.db import models -class MyUserManager(BaseUserManager): - def create_user(self, email, password=None): - if not email: - raise ValueError('Users must have an email address') +class AdminProfile(models.Model): - user = self.model( - email=self.normalize_email(email), - ) + user = models.OneToOneField('osf.OSFUser', related_name='admin_profile') - user.set_password(password) - user.save(using=self._db) - return user - - def create_superuser(self, email, password): - user = self.create_user(email, password=password, ) - user.is_superuser = True - user.is_admin = True - user.is_staff = True - user.is_active = True - user.save(using=self._db) - return user - - def prereg_users(self): - return self.filter(groups__name='prereg_group') - - -class MyUser(AbstractBaseUser, PermissionsMixin): - email = models.EmailField( - verbose_name='email address', - max_length=255, - unique=True, - ) - - first_name = models.CharField(max_length=30, blank=False) - last_name = models.CharField(max_length=30, blank=False) - is_active = models.BooleanField(default=True) - is_admin = models.BooleanField(default=False) - is_staff = models.BooleanField(default=False) - date_joined = models.DateTimeField(auto_now_add=True) - confirmed = models.BooleanField(default=False) - osf_id = models.CharField(max_length=5, blank=True) desk_token = models.CharField(max_length=45, blank=True) desk_token_secret = models.CharField(max_length=45, blank=True) - - objects = MyUserManager() - - USERNAME_FIELD = 'email' - - def get_full_name(self): - return ('{0} {1}'.format(self.first_name, self.last_name)).strip() or self.email - - def get_short_name(self): - # The user is identified by their email address - return self.email - - def __unicode__(self): - return self.email - - class Meta: - ordering = ['email'] - - @property - def osf_user(self): - # import on call to avoid interference w/ django's manage.py commands like collectstatic - from website.models import User as OsfUserModel - - if not self.osf_id: - raise RuntimeError('This user does not have an associated Osf User') - return OsfUserModel.load(self.osf_id) - - def is_in_group(self, group): - return self.groups.filter(name=group).exists() - - def group_names(self): - return self.groups.all().values_list('name', flat=True)
3072b6dd724255c3fba3bc6f837ec823d507e321
grammpy_transforms/contextfree.py
grammpy_transforms/contextfree.py
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 10.08.2017 20:33 :Licence GNUv3 Part of grammpy-transforms """ from grammpy import Grammar from .NongeneratingSymbolsRemove import remove_nongenerating_symbols from .UnreachableSymbolsRemove import remove_unreachable_symbols class ContextFree: @staticmethod def remove_nongenerating_symbols(grammar: Grammar, transform_grammar=False): return remove_nongenerating_symbols(grammar, transform_grammar) @staticmethod def is_grammar_generating(grammar: Grammar, tranform_gramar=False, perform_remove=True): g = grammar if perform_remove: g = ContextFree.remove_nongenerating_symbols(grammar, transform_grammar=tranform_gramar) return g.start_get() in g.nonterms() @staticmethod def remove_unreachable_symbols(grammar: Grammar, transform_grammar=False): return remove_unreachable_symbols(grammar, transform_grammar)
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 10.08.2017 20:33 :Licence GNUv3 Part of grammpy-transforms """ from grammpy import Grammar from .NongeneratingSymbolsRemove import remove_nongenerating_symbols from .UnreachableSymbolsRemove import remove_unreachable_symbols class ContextFree: @staticmethod def remove_nongenerating_symbols(grammar: Grammar, transform_grammar=False): return remove_nongenerating_symbols(grammar, transform_grammar) @staticmethod def is_grammar_generating(grammar: Grammar, transform_grammar=False, perform_remove=True): g = grammar if perform_remove: g = ContextFree.remove_nongenerating_symbols(grammar, transform_grammar=transform_grammar) return g.start_get() in g.nonterms() @staticmethod def remove_unreachable_symbols(grammar: Grammar, transform_grammar=False): return remove_unreachable_symbols(grammar, transform_grammar) @staticmethod def remove_useless_symbols(grammar: Grammar, transform_grammar=False, *, perform_unreachable_alg = True, perform_nongenerating_alg = True) -> Grammar: if perform_nongenerating_alg: grammar = ContextFree.remove_nongenerating_symbols(grammar, transform_grammar=transform_grammar) transform_grammar = False if perform_unreachable_alg: grammar = ContextFree.remove_unreachable_symbols(grammar, transform_grammar=transform_grammar) return grammar
Implement alg to remove useless symbols
Implement alg to remove useless symbols
Python
mit
PatrikValkovic/grammpy
--- +++ @@ -18,12 +18,23 @@ return remove_nongenerating_symbols(grammar, transform_grammar) @staticmethod - def is_grammar_generating(grammar: Grammar, tranform_gramar=False, perform_remove=True): + def is_grammar_generating(grammar: Grammar, transform_grammar=False, perform_remove=True): g = grammar if perform_remove: - g = ContextFree.remove_nongenerating_symbols(grammar, transform_grammar=tranform_gramar) + g = ContextFree.remove_nongenerating_symbols(grammar, transform_grammar=transform_grammar) return g.start_get() in g.nonterms() @staticmethod def remove_unreachable_symbols(grammar: Grammar, transform_grammar=False): return remove_unreachable_symbols(grammar, transform_grammar) + + @staticmethod + def remove_useless_symbols(grammar: Grammar, transform_grammar=False, *, + perform_unreachable_alg = True, + perform_nongenerating_alg = True) -> Grammar: + if perform_nongenerating_alg: + grammar = ContextFree.remove_nongenerating_symbols(grammar, transform_grammar=transform_grammar) + transform_grammar = False + if perform_unreachable_alg: + grammar = ContextFree.remove_unreachable_symbols(grammar, transform_grammar=transform_grammar) + return grammar
092bd3d506ec281a24adcecef6ca498443df5f59
kboard/board/urls.py
kboard/board/urls.py
# Created by JHJ on 2016. 10. 5. from django.conf.urls import url from . import views app_name = 'board' urlpatterns = [ url(r'^$', views.board_list, name='board_list'), url(r'^(?P<board_slug>[-a-z]+)/$', views.post_list, name='post_list'), url(r'^(?P<board_slug>[-a-z]+)/new/$', views.new_post, name='new_post'), url(r'^(?P<post_id>\d+)/delete/$', views.delete_post, name='delete_post'), url(r'^(?P<post_id>\d+)/$', views.view_post, name='view_post'), url(r'^(?P<post_id>\d+)/comment/new/$', views.new_comment, name='new_comment'), url(r'^(?P<post_id>\d+)/comment/delete/$', views.delete_comment, name='delete_comment'), ]
# Created by JHJ on 2016. 10. 5. from django.conf.urls import url from . import views app_name = 'board' urlpatterns = [ url(r'^$', views.board_list, name='board_list'), url(r'^(?P<board_slug>[-a-z]+)/$', views.post_list, name='post_list'), url(r'^(?P<board_slug>[-a-z]+)/new/$', views.new_post, name='new_post'), url(r'^(?P<post_id>\d+)/delete/$', views.delete_post, name='delete_post'), url(r'^(?P<post_id>\d+)/$', views.view_post, name='view_post'), url(r'^(?P<post_id>\d+)/comment/new/$', views.new_comment, name='new_comment'), url(r'^(?P<post_id>\d+)/comment/(?P<comment_id>\d+)/delete/$', views.delete_comment, name='delete_comment'), ]
Add 'comment_id' parameter in 'delete_comment' url
Add 'comment_id' parameter in 'delete_comment' url
Python
mit
hyesun03/k-board,guswnsxodlf/k-board,hyesun03/k-board,kboard/kboard,guswnsxodlf/k-board,kboard/kboard,guswnsxodlf/k-board,cjh5414/kboard,darjeeling/k-board,hyesun03/k-board,kboard/kboard,cjh5414/kboard,cjh5414/kboard
--- +++ @@ -12,5 +12,5 @@ url(r'^(?P<post_id>\d+)/delete/$', views.delete_post, name='delete_post'), url(r'^(?P<post_id>\d+)/$', views.view_post, name='view_post'), url(r'^(?P<post_id>\d+)/comment/new/$', views.new_comment, name='new_comment'), - url(r'^(?P<post_id>\d+)/comment/delete/$', views.delete_comment, name='delete_comment'), + url(r'^(?P<post_id>\d+)/comment/(?P<comment_id>\d+)/delete/$', views.delete_comment, name='delete_comment'), ]
a2627a5e0fc68be04af50259e1fd504be389aeb1
kino/utils/config.py
kino/utils/config.py
from utils.data_handler import DataHandler class Config(object): class __Config: def __init__(self): self.data_handler = DataHandler() self.fname = "config.json" config = self.__read_config() self.kino = config["kino"] self.github = config["github"] def __read_config(self): return self.data_handler.read_file(self.fname) instance = None def __init__(self): if not Config.instance: Config.instance = Config.__Config() def __getattr__(self, name): return getattr(self.instance, name)
# -*- coding: utf-8 -*- from utils.data_handler import DataHandler class Config(object): class __Config: def __init__(self): self.data_handler = DataHandler() self.fname = "config.json" config = self.__read_config() self.kino = config["kino"] self.github = config["github"] self.weather = config["weather"] def __read_config(self): return self.data_handler.read_file(self.fname) instance = None def __init__(self): if not Config.instance: Config.instance = Config.__Config() def __getattr__(self, name): return getattr(self.instance, name)
Add Config weather - (DARKSKY API KEY, HOME, WORK_PLACE
Add Config weather - (DARKSKY API KEY, HOME, WORK_PLACE
Python
mit
DongjunLee/kino-bot
--- +++ @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- from utils.data_handler import DataHandler @@ -10,6 +11,7 @@ config = self.__read_config() self.kino = config["kino"] self.github = config["github"] + self.weather = config["weather"] def __read_config(self): return self.data_handler.read_file(self.fname)
57f2a438845cd0d7263da6ac66142d5403e41d98
examples/markdown/build.py
examples/markdown/build.py
#!/usr/bin/env python3 # build.py import os # Markdown to HTML library # https://pypi.org/project/Markdown/ import markdown from staticjinja import Site markdowner = markdown.Markdown(output_format="html5") def md_context(template): with open(template.filename) as f: markdown_content = f.read() return {"post_content_html": markdowner.convert(markdown_content)} def render_md(site, template, **kwargs): # Given a template such as posts/post1.md # Determine the post's title (post1) and it's directory (posts/) directory, fname = os.path.split(template.name) post_title, _ = fname.split(".") # Determine where the result will be streamed (build/posts/post1.html) out_dir = os.path.join(site.outpath, directory) post_fname = "{}.html".format(post_title) out = os.path.join(out_dir, post_fname) # Render and stream the result if not os.path.exists(out_dir): os.makedirs(out_dir) post_template = site.get_template("_post.html") post_template.stream(**kwargs).dump(out, encoding="utf-8") site = Site.make_site( searchpath="src", outpath="build", contexts=[(r".*\.md", md_context)], rules=[(r".*\.md", render_md)], ) site.render()
#!/usr/bin/env python3 # build.py import os from pathlib import Path import markdown from staticjinja import Site markdowner = markdown.Markdown(output_format="html5") def md_context(template): markdown_content = Path(template.filename).read_text() return {"post_content_html": markdowner.convert(markdown_content)} def render_md(site, template, **kwargs): # i.e. posts/post1.md -> build/posts/post1.html out = site.outpath / Path(template.name).with_suffix(".html") # Compile and stream the result os.makedirs(out.parent, exist_ok=True) site.get_template("_post.html").stream(**kwargs).dump(str(out), encoding="utf-8") site = Site.make_site( searchpath="src", outpath="build", contexts=[(r".*\.md", md_context)], rules=[(r".*\.md", render_md)], ) site.render()
Simplify markdown example using pathlib
example: Simplify markdown example using pathlib
Python
mit
Ceasar/staticjinja,Ceasar/staticjinja
--- +++ @@ -1,9 +1,8 @@ #!/usr/bin/env python3 # build.py import os +from pathlib import Path -# Markdown to HTML library -# https://pypi.org/project/Markdown/ import markdown from staticjinja import Site @@ -12,27 +11,17 @@ def md_context(template): - with open(template.filename) as f: - markdown_content = f.read() - return {"post_content_html": markdowner.convert(markdown_content)} + markdown_content = Path(template.filename).read_text() + return {"post_content_html": markdowner.convert(markdown_content)} def render_md(site, template, **kwargs): - # Given a template such as posts/post1.md - # Determine the post's title (post1) and it's directory (posts/) - directory, fname = os.path.split(template.name) - post_title, _ = fname.split(".") + # i.e. posts/post1.md -> build/posts/post1.html + out = site.outpath / Path(template.name).with_suffix(".html") - # Determine where the result will be streamed (build/posts/post1.html) - out_dir = os.path.join(site.outpath, directory) - post_fname = "{}.html".format(post_title) - out = os.path.join(out_dir, post_fname) - - # Render and stream the result - if not os.path.exists(out_dir): - os.makedirs(out_dir) - post_template = site.get_template("_post.html") - post_template.stream(**kwargs).dump(out, encoding="utf-8") + # Compile and stream the result + os.makedirs(out.parent, exist_ok=True) + site.get_template("_post.html").stream(**kwargs).dump(str(out), encoding="utf-8") site = Site.make_site(
986dc7064f1dfb651d6185c38a2b5070bf8926f8
examples/restore_alerts.py
examples/restore_alerts.py
#!/usr/bin/env python # # Restore Alerts of the format in a JSON dumpfile from the list_alerts.py example. # import os import sys import json sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..')) from sdcclient import SdcClient # # Parse arguments # if len(sys.argv) != 3: print 'usage: %s <sysdig-token> <file-name>' % sys.argv[0] print 'You can find your token at https://app.sysdigcloud.com/#/settings/user' sys.exit(1) sdc_token = sys.argv[1] alerts_dump_file = sys.argv[2] # # Instantiate the SDC client # sdclient = SdcClient(sdc_token) with open(alerts_dump_file, 'r') as f: j = json.load(f) for a in j['alerts']: res = sdclient.create_alert(alert_obj=a) if not res[0]: print res[1] sys.exit(1) print 'All Alerts in ' + alerts_dump_file + ' created successfully.'
#!/usr/bin/env python # # Restore Alerts of the format in a JSON dumpfile from the list_alerts.py example. # import os import sys import json sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..')) from sdcclient import SdcClient # # Parse arguments # if len(sys.argv) != 3: print 'usage: %s <sysdig-token> <file-name>' % sys.argv[0] print 'You can find your token at https://app.sysdigcloud.com/#/settings/user' sys.exit(1) sdc_token = sys.argv[1] alerts_dump_file = sys.argv[2] # # Instantiate the SDC client # sdclient = SdcClient(sdc_token) with open(alerts_dump_file, 'r') as f: j = json.load(f) for a in j['alerts']: a['description'] += ' (created via restore_alerts.py)' res = sdclient.create_alert(alert_obj=a) if not res[0]: print res[1] sys.exit(1) print 'All Alerts in ' + alerts_dump_file + ' created successfully.'
Append note to Description indicating the Alert was created programmatically
Append note to Description indicating the Alert was created programmatically
Python
mit
draios/python-sdc-client,draios/python-sdc-client
--- +++ @@ -28,6 +28,7 @@ with open(alerts_dump_file, 'r') as f: j = json.load(f) for a in j['alerts']: + a['description'] += ' (created via restore_alerts.py)' res = sdclient.create_alert(alert_obj=a) if not res[0]: print res[1]
eecde2e8fdd3b105e68a5bd4bab16bdfb9767546
eximhandler/eximhandler.py
eximhandler/eximhandler.py
import logging from subprocess import Popen, PIPE class EximHandler(logging.Handler): """ A handler class which sends an email using exim for each logging event. """ def __init__(self, toaddr, subject, exim_path="/usr/sbin/exim"): """ Initialize the handler. """ logging.Handler.__init__(self) self.toaddr = toaddr self.subject = subject self.exim_path = exim_path def getSubject(self, record): """ Determine the subject for the email. If you want to specify a subject line which is record-dependent, override this method. """ return self.subject def emit(self, record): """ Emit a record. Format the record and send it to the specified address. """ body = self.format(record) try: proc1 = Popen( ['echo', '-e', 'Subject: %s\n\n%s' % (self.subject, body)], stdout=PIPE ) proc2 = Popen( [self.exim_path, '-odf', '-i', self.toaddr], stdin=proc1.stdout, stdout=PIPE ) # Allow proc1 to receive a SIGPIPE if proc2 exits. proc1.stdout.close() # Wait for proc2 to exit proc2.communicate() except (KeyboardInterrupt, SystemExit): raise except Exception: self.handleError(record)
import logging from subprocess import Popen, PIPE class EximHandler(logging.Handler): """ A handler class which sends an email using exim for each logging event. """ def __init__(self, toaddr, subject, exim_path="/usr/sbin/exim"): """ Initialize the handler. """ logging.Handler.__init__(self) self.toaddr = toaddr self.subject = subject self.exim_path = exim_path def get_subject(self, record): """ Determine the subject for the email. If you want to specify a subject line which is record-dependent, override this method. """ return self.subject def emit(self, record): """ Emit a record. Format the record and send it to the specified address. """ subject = self.get_subject(record) body = self.format(record) try: proc1 = Popen( ['echo', '-e', 'Subject: %s\n\n%s' % (subject, body)], stdout=PIPE ) proc2 = Popen( [self.exim_path, '-odf', '-i', self.toaddr], stdin=proc1.stdout, stdout=PIPE ) # Allow proc1 to receive a SIGPIPE if proc2 exits. proc1.stdout.close() # Wait for proc2 to exit proc2.communicate() except (KeyboardInterrupt, SystemExit): raise except Exception: self.handleError(record)
Fix to allow overriding subject formatting
Fix to allow overriding subject formatting
Python
unlicense
danmichaelo/eximhandler
--- +++ @@ -15,7 +15,7 @@ self.subject = subject self.exim_path = exim_path - def getSubject(self, record): + def get_subject(self, record): """ Determine the subject for the email. @@ -30,10 +30,11 @@ Format the record and send it to the specified address. """ + subject = self.get_subject(record) body = self.format(record) try: proc1 = Popen( - ['echo', '-e', 'Subject: %s\n\n%s' % (self.subject, body)], + ['echo', '-e', 'Subject: %s\n\n%s' % (subject, body)], stdout=PIPE )
22b8e32cc350228b328f026ccf9e3e90ef9f2aed
manoseimas/settings/vagrant.py
manoseimas/settings/vagrant.py
from manoseimas.settings.base import * # noqa from manoseimas.settings.development import * # noqa INTERNAL_IPS = ( '127.0.0.1', '10.0.2.2', # Vagrant host IP in default config ) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'OPTIONS': { 'init_command': 'SET storage_engine=INNODB', 'read_default_file': os.path.expanduser('~/.my.cnf'), }, } }
from manoseimas.settings.base import * # noqa from manoseimas.settings.development import * # noqa INTERNAL_IPS = ( '127.0.0.1', '10.0.2.2', # Vagrant host IP in default config ) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'OPTIONS': { 'init_command': ('SET storage_engine=INNODB; ' 'SET GLOBAL sql_mode=STRICT_ALL_TABLES;'), 'read_default_file': os.path.expanduser('~/.my.cnf'), }, } }
Set STRICT_ALL_TABLES on connection to prevent MySQL from silently truncating data.
Set STRICT_ALL_TABLES on connection to prevent MySQL from silently truncating data.
Python
agpl-3.0
ManoSeimas/manoseimas.lt,ManoSeimas/manoseimas.lt,ManoSeimas/manoseimas.lt,ManoSeimas/manoseimas.lt
--- +++ @@ -10,7 +10,8 @@ 'default': { 'ENGINE': 'django.db.backends.mysql', 'OPTIONS': { - 'init_command': 'SET storage_engine=INNODB', + 'init_command': ('SET storage_engine=INNODB; ' + 'SET GLOBAL sql_mode=STRICT_ALL_TABLES;'), 'read_default_file': os.path.expanduser('~/.my.cnf'), }, }
7a94ef4efddc639a13c00669c4cf10f07e8aa290
mezzanine/pages/context_processors.py
mezzanine/pages/context_processors.py
from mezzanine.pages.models import Page def page(request): """ Adds the current page to the template context and runs its ``set_helper`` method. This was previously part of ``PageMiddleware``, but moved to a context processor so that we could assign these template context variables without the middleware depending on Django's ``TemplateResponse``. """ context = {} page = getattr(request, "page", None) if page and isinstance(page, Page): # set_helpers has always expected the current template context, # but here we're just passing in our context dict with enough # variables to satisfy it. context = {"request": request, "page": page, "_current_page": page} page.set_helpers(context) return context
from mezzanine.pages.models import Page def page(request): """ Adds the current page to the template context and runs its ``set_helper`` method. This was previously part of ``PageMiddleware``, but moved to a context processor so that we could assign these template context variables without the middleware depending on Django's ``TemplateResponse``. """ context = {} page = getattr(request, "page", None) if isinstance(page, Page): # set_helpers has always expected the current template context, # but here we're just passing in our context dict with enough # variables to satisfy it. context = {"request": request, "page": page, "_current_page": page} page.set_helpers(context) return context
Clean up page context processor check.
Clean up page context processor check.
Python
bsd-2-clause
wbtuomela/mezzanine,dsanders11/mezzanine,christianwgd/mezzanine,Cicero-Zhao/mezzanine,geodesign/mezzanine,promil23/mezzanine,sjdines/mezzanine,industrydive/mezzanine,sjuxax/mezzanine,dsanders11/mezzanine,christianwgd/mezzanine,ryneeverett/mezzanine,viaregio/mezzanine,geodesign/mezzanine,ryneeverett/mezzanine,vladir/mezzanine,viaregio/mezzanine,wbtuomela/mezzanine,promil23/mezzanine,douglaskastle/mezzanine,readevalprint/mezzanine,dovydas/mezzanine,dovydas/mezzanine,spookylukey/mezzanine,eino-makitalo/mezzanine,jerivas/mezzanine,readevalprint/mezzanine,eino-makitalo/mezzanine,sjuxax/mezzanine,geodesign/mezzanine,spookylukey/mezzanine,vladir/mezzanine,stephenmcd/mezzanine,viaregio/mezzanine,molokov/mezzanine,Cicero-Zhao/mezzanine,sjuxax/mezzanine,sjdines/mezzanine,promil23/mezzanine,frankier/mezzanine,jerivas/mezzanine,readevalprint/mezzanine,nikolas/mezzanine,industrydive/mezzanine,spookylukey/mezzanine,christianwgd/mezzanine,douglaskastle/mezzanine,stephenmcd/mezzanine,vladir/mezzanine,dsanders11/mezzanine,molokov/mezzanine,frankier/mezzanine,gradel/mezzanine,ryneeverett/mezzanine,stephenmcd/mezzanine,dovydas/mezzanine,gradel/mezzanine,sjdines/mezzanine,wbtuomela/mezzanine,eino-makitalo/mezzanine,jerivas/mezzanine,industrydive/mezzanine,molokov/mezzanine,frankier/mezzanine,gradel/mezzanine,douglaskastle/mezzanine,nikolas/mezzanine,nikolas/mezzanine
--- +++ @@ -1,3 +1,4 @@ + from mezzanine.pages.models import Page @@ -11,7 +12,7 @@ """ context = {} page = getattr(request, "page", None) - if page and isinstance(page, Page): + if isinstance(page, Page): # set_helpers has always expected the current template context, # but here we're just passing in our context dict with enough # variables to satisfy it.
61d455cbc2b4177fbb4640211679f5c1948042ff
configurator/__init__.py
configurator/__init__.py
# # Copyright 2015 Yasser Gonzalez Fernandez # # 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 # """Calculation of optimal configuration processes. Attributes: __version__: The current version string. """ import os import subprocess def _get_version(version="0.5.1"): try: # Get version from the git repo, if installed in editable mode. pkg_dir = os.path.dirname(__file__) src_dir = os.path.abspath(os.path.join(pkg_dir, os.pardir)) git_dir = os.path.join(src_dir, ".git") git_args = ("git", "--work-tree", src_dir, "--git-dir", git_dir, "describe", "--tags", "--always") output = subprocess.check_output(git_args) version = output.decode("utf-8").strip() if version.rfind("-") >= 0: version = version[:version.rfind("-")] # strip SHA1 hash version = version.replace("-", ".post") # PEP 440 compatible except Exception: pass # fallback to the hardcoded version return version __version__ = _get_version()
# # Copyright 2015 Yasser Gonzalez Fernandez # # 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 # """Calculation of optimal configuration processes. Attributes: __version__: The current version string. """ import os import subprocess def _get_version(version="0.5.1"): try: # Get version from the git repo, if installed in editable mode. pkg_dir = os.path.dirname(__file__) src_dir = os.path.abspath(os.path.join(pkg_dir, os.pardir)) git_dir = os.path.join(src_dir, ".git") git_args = ("git", "--work-tree", src_dir, "--git-dir", git_dir, "describe", "--tags", "--always") output = subprocess.check_output(git_args, stderr=subprocess.DEVNULL) version = output.decode("utf-8").strip() if version.rfind("-") >= 0: version = version[:version.rfind("-")] # strip SHA1 hash version = version.replace("-", ".post") # PEP 440 compatible except Exception: pass # fallback to the hardcoded version return version __version__ = _get_version()
Hide stderr output when calling get to get version
Hide stderr output when calling get to get version
Python
apache-2.0
yasserglez/configurator,yasserglez/configurator
--- +++ @@ -26,7 +26,7 @@ git_dir = os.path.join(src_dir, ".git") git_args = ("git", "--work-tree", src_dir, "--git-dir", git_dir, "describe", "--tags", "--always") - output = subprocess.check_output(git_args) + output = subprocess.check_output(git_args, stderr=subprocess.DEVNULL) version = output.decode("utf-8").strip() if version.rfind("-") >= 0: version = version[:version.rfind("-")] # strip SHA1 hash