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 |
|---|---|---|---|---|---|---|---|---|---|---|
c0549776224eaceda575c4eea37defa2acc0557b | setup.py | setup.py | import os
try:
from setuptools import setup
except:
from distutils.core import setup
setup(name = "clrsvsim",
version = "0.0.2",
description = "Color Genomics Structural Variant Simulator",
author = "Color Genomics",
author_email = "dev@color.com",
url = "https://github.com/ColorGenomics/clrsvsim",
packages = ["clrsvsim"],
install_requires=[
'cigar==0.1.3',
'mock==2.0.0',
'nose==1.3.7',
'numpy==1.10.1',
'preconditions==0.1',
'pyfasta==0.5.2',
'pysam==0.10.0',
],
license = "Apache-2.0",
)
| try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(name = "clrsvsim",
version = "0.0.2",
description = "Color Genomics Structural Variant Simulator",
author = "Color Genomics",
author_email = "dev@color.com",
url = "https://github.com/ColorGenomics/clrsvsim",
packages = ["clrsvsim"],
install_requires=[
'cigar==0.1.3',
'mock==2.0.0',
'nose==1.3.7',
'numpy==1.10.1',
'preconditions==0.1',
'pyfasta==0.5.2',
'pysam==0.10.0',
],
license = "Apache-2.0",
)
| Remove unneeded import, fix bare except | Remove unneeded import, fix bare except
The `os` module isn't needed, so we need not import it.
Additionally, a bare `except` clause is pretty much never desired, since
it includes all exceptions, including sigkills.
Instead, just check for an `ImportError`, since that's what we're really
trying to do: fall back on `distutils` if `setuptools` is not present.
| Python | apache-2.0 | color/clrsvsim | ---
+++
@@ -1,9 +1,7 @@
-import os
-
try:
- from setuptools import setup
-except:
- from distutils.core import setup
+ from setuptools import setup
+except ImportError:
+ from distutils.core import setup
setup(name = "clrsvsim", |
2d7be7f8344a928aecdb2bbfeb7531bb0c35aeee | setup.py | setup.py | from setuptools import setup
from mdtoc import __version__
long_description = "Adds table of contents to Markdown files"
setup(
name="mdtoc",
version=__version__,
description=long_description,
author="Scott Frazer",
author_email="scott.d.frazer@gmail.com",
packages=["mdtoc"],
install_requires=["xtermcolor", "requests<3.0.0"],
scripts={"scripts/mdtoc"},
license="MIT",
keywords="Markdown, table of contents, toc",
url="http://github.com/scottfrazer/mdtoc",
classifiers=[
"License :: OSI Approved :: MIT License",
"Environment :: Console",
"Topic :: Utilities",
"Topic :: Text Processing",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"Natural Language :: English",
],
)
| import os
from setuptools import setup
from mdtoc import __version__
setup(
name="mdtoc",
version=__version__,
description="Adds table of contents to Markdown files",
long_description=open(
os.path.join(os.path.abspath(os.path.dirname(__file__)), "README.md")
).read(),
author="Scott Frazer",
author_email="scott.d.frazer@gmail.com",
packages=["mdtoc"],
install_requires=["xtermcolor", "requests<3.0.0"],
scripts={"scripts/mdtoc"},
license="MIT",
keywords="Markdown, table of contents, toc",
url="http://github.com/scottfrazer/mdtoc",
classifiers=[
"License :: OSI Approved :: MIT License",
"Environment :: Console",
"Topic :: Utilities",
"Topic :: Text Processing",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"Natural Language :: English",
],
)
| Use a .md long_description for PyPI | Use a .md long_description for PyPI
| Python | mit | scottfrazer/mdtoc | ---
+++
@@ -1,13 +1,15 @@
+import os
from setuptools import setup
from mdtoc import __version__
-long_description = "Adds table of contents to Markdown files"
-
setup(
name="mdtoc",
version=__version__,
- description=long_description,
+ description="Adds table of contents to Markdown files",
+ long_description=open(
+ os.path.join(os.path.abspath(os.path.dirname(__file__)), "README.md")
+ ).read(),
author="Scott Frazer",
author_email="scott.d.frazer@gmail.com",
packages=["mdtoc"], |
9a0de77615c943de4344b4c74d5d5114b8baf0ab | eggsclaim.py | eggsclaim.py | import signal
import sys
import serial
import sms
from xbee import XBee
egg_was_present = False
def signal_handler(signal, frame):
xbee.halt()
serial_port.close()
sys.exit(0)
def packet_received(packet):
samples = packet['samples'][0]
egg_is_present = True if 'dio-4' in samples else False
if egg_was_present != egg_is_present and egg_is_present:
sms.send_sms("", "Cock-a-doodle-doo! An egg is waiting for you!")
egg_was_present = egg_is_present
signal.signal(signal.SIGINT, signal_handler)
serial_port = serial.Serial('/dev/ttyp0', 9600)
xbee = XBee(serial_port, callback=packet_received) | import signal
import sys
import serial
import sms
from xbee import XBee
egg_was_present = False
def signal_handler(signal, frame):
xbee.halt()
serial_port.close()
sys.exit(0)
def packet_received(packet):
samples = packet['samples'][0]
egg_is_present = True if 'dio-4' in samples else False
if egg_is_present and egg_is_present != egg_was_present:
sms.send_sms("", "Cock-a-doodle-doo! An egg is waiting for you!")
egg_was_present = egg_is_present
signal.signal(signal.SIGINT, signal_handler)
serial_port = serial.Serial('/dev/ttyp0', 9600)
xbee = XBee(serial_port, callback=packet_received) | Rearrange conditions to make logic clearer | Rearrange conditions to make logic clearer
| Python | mit | jamespettigrew/eggsclaim | ---
+++
@@ -15,7 +15,7 @@
samples = packet['samples'][0]
egg_is_present = True if 'dio-4' in samples else False
- if egg_was_present != egg_is_present and egg_is_present:
+ if egg_is_present and egg_is_present != egg_was_present:
sms.send_sms("", "Cock-a-doodle-doo! An egg is waiting for you!")
egg_was_present = egg_is_present
|
e8c9c22c7c57ff2de8b9ef9e73ec8f339aa73fd7 | setup.py | setup.py | #!/usr/bin/env python
import os
import sys
if sys.version < '2.7':
print 'Python >= 2.7 required'
sys.exit(1)
from setuptools import setup
long_description = '''
A simple Python package for using Twitter search functionality
that is only available through the Twitter web interface
(such as searching for tweets older than a few weeks).'''.strip()
setup(
name = 'twitterwebsearch',
version='0.0.5',
author = 'Raynor Vliegendhart',
author_email = 'ShinNoNoir@gmail.com',
url = 'https://github.com/ShinNoNoir/twitterwebsearch',
packages=['twitterwebsearch'],
description = "Package for Twitter's web search",
long_description = long_description,
platforms = 'Any',
license = 'MIT (see: LICENSE.txt)',
keywords = 'Twitter, search',
install_requires = open('requirements.txt').readlines(),
)
| #!/usr/bin/env python
import os
import sys
if sys.version < '2.7':
print 'Python >= 2.7 required'
sys.exit(1)
from setuptools import setup
long_description = '''
A simple Python package for using Twitter search functionality
that is only available through the Twitter web interface
(such as searching for tweets older than a few weeks).'''.strip()
setup(
name = 'twitterwebsearch',
version='0.1.1',
author = 'Raynor Vliegendhart',
author_email = 'ShinNoNoir@gmail.com',
url = 'https://github.com/ShinNoNoir/twitterwebsearch',
packages=['twitterwebsearch'],
description = "Package for Twitter's web search",
long_description = long_description,
platforms = 'Any',
license = 'MIT (see: LICENSE.txt)',
keywords = 'Twitter, search',
install_requires = open('requirements.txt').readlines(),
)
| Increase version number to 0.1.1 (breaking API change) | Increase version number to 0.1.1 (breaking API change)
| Python | mit | ShinNoNoir/twitterwebsearch | ---
+++
@@ -15,7 +15,7 @@
setup(
name = 'twitterwebsearch',
- version='0.0.5',
+ version='0.1.1',
author = 'Raynor Vliegendhart',
author_email = 'ShinNoNoir@gmail.com',
url = 'https://github.com/ShinNoNoir/twitterwebsearch', |
48418ac0fe75bbb331878b80d9d0903dde445838 | setup.py | setup.py | from distutils.core import setup
setup(
name='pyticketswitch',
version='1.6.1',
author='Matt Jared',
author_email='mattjared@ingresso.co.uk',
packages=[
'pyticketswitch',
'pyticketswitch.test',
'pyticketswitch.interface_objects'
],
license='LICENSE.txt',
description='A Python interface for the Ingresso XML Core API',
long_description=open('README.rst').read(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Programming Language :: Python :: 2.7',
],
)
| from distutils.core import setup
setup(
name='pyticketswitch',
version='1.6.1',
author='Ingresso',
author_email='systems@ingresso.co.uk',
packages=[
'pyticketswitch',
'pyticketswitch.test',
'pyticketswitch.interface_objects'
],
license='LICENSE.txt',
description='A Python interface for the Ingresso XML Core API',
long_description=open('README.rst').read(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Programming Language :: Python :: 2.7',
],
)
| Update author and email address | Update author and email address
| Python | mit | ingresso-group/pyticketswitch,ingtechteam/pyticketswitch,graingert/pyticketswitch | ---
+++
@@ -3,8 +3,8 @@
setup(
name='pyticketswitch',
version='1.6.1',
- author='Matt Jared',
- author_email='mattjared@ingresso.co.uk',
+ author='Ingresso',
+ author_email='systems@ingresso.co.uk',
packages=[
'pyticketswitch',
'pyticketswitch.test', |
5782d01fa95624c784c6298486caefbe527fb76f | setup.py | setup.py | from distutils.core import setup
from hal.version import __version__ as version
setup(
name='hal',
packages=['hal'],
version=version,
description='Command Line Assistant',
author='Anup Pokhrel',
author_email='virtualanup@gmail.com',
url='https://github.com/virtualanup/hal',
download_url='https://github.com/virtualanup/hal/archive/{}.tar.gz'.format(version),
keywords=['assistant', 'hal'],
classifiers=[],
install_requires=[
'six==1.10.0',
'simpleeval==0.9.1',
'pytz==2016.10'
],
)
| from distutils.core import setup
from hal.version import __version__ as version
setup(
name='hal-assistant',
packages=['hal'],
version=version,
description='Command Line Assistant',
author='Anup Pokhrel',
author_email='virtualanup@gmail.com',
url='https://github.com/virtualanup/hal',
download_url='https://github.com/virtualanup/hal/archive/{}.tar.gz'.format(version),
keywords=['assistant', 'hal'],
classifiers=[],
install_requires=[
'six==1.10.0',
'simpleeval==0.9.1',
'pytz==2016.10'
],
)
| Change package name to hal-assistant | Change package name to hal-assistant
| Python | mit | virtualanup/hal | ---
+++
@@ -3,7 +3,7 @@
from hal.version import __version__ as version
setup(
- name='hal',
+ name='hal-assistant',
packages=['hal'],
version=version,
description='Command Line Assistant', |
caafe83bd35b0b82135be593b88ec9ed64bfb508 | setup.py | setup.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name='OpenFisca-Senegal',
version='0.0.0',
author='OpenFisca Team',
author_email='contact@openfisca.fr',
classifiers=[
"Development Status :: 2 - Pre-Alpha",
"License :: OSI Approved :: GNU Affero General Public License v3",
"Operating System :: POSIX",
"Programming Language :: Python",
"Topic :: Scientific/Engineering :: Information Analysis",
],
description=u'Senegalese tax and benefit system for OpenFisca',
keywords='benefit microsimulation senegal social tax',
license='http://www.fsf.org/licensing/licenses/agpl-3.0.html',
url='https://github.com/openfisca/openfisca-senegal',
data_files=[
('share/openfisca/openfisca-senegal',
['CHANGELOG.md', 'LICENSE', 'README.md']),
],
extras_require={
'test': ['nose'],
},
install_requires=[
'OpenFisca-Core >= 3.0.0, < 4.0',
'notebook',
],
packages=find_packages(exclude=['openfisca_senegal.tests*']),
test_suite='nose.collector',
)
| #! /usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name='OpenFisca-Senegal',
version='0.0.0',
author='OpenFisca Team',
author_email='contact@openfisca.fr',
classifiers=[
"Development Status :: 2 - Pre-Alpha",
"License :: OSI Approved :: GNU Affero General Public License v3",
"Operating System :: POSIX",
"Programming Language :: Python",
"Topic :: Scientific/Engineering :: Information Analysis",
],
description=u'Senegalese tax and benefit system for OpenFisca',
keywords='benefit microsimulation senegal social tax',
license='http://www.fsf.org/licensing/licenses/agpl-3.0.html',
url='https://github.com/openfisca/openfisca-senegal',
data_files=[
('share/openfisca/openfisca-senegal',
['CHANGELOG.md', 'LICENSE', 'README.md']),
],
extras_require={
'test': ['nose'],
},
install_requires=[
'OpenFisca-Core >= 4.1.4b1, < 5.0',
'notebook',
],
packages=find_packages(exclude=['openfisca_senegal.tests*']),
test_suite='nose.collector',
)
| Upgrade openfisca core to v4 | Upgrade openfisca core to v4
| Python | agpl-3.0 | openfisca/senegal | ---
+++
@@ -30,7 +30,7 @@
'test': ['nose'],
},
install_requires=[
- 'OpenFisca-Core >= 3.0.0, < 4.0',
+ 'OpenFisca-Core >= 4.1.4b1, < 5.0',
'notebook',
],
packages=find_packages(exclude=['openfisca_senegal.tests*']), |
5d5f5b2924a238452a19c1035a4d2eee9c857ceb | setup.py | setup.py | #!/usr/bin/env python
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(
name='django-bleach',
version="0.1.0",
description='Easily use bleach with Django models and templates',
author='Tim Heap',
author_email='heap.tim@gmail.com',
url='https://bitbucket.org/ionata/django-bleach',
packages=['django_bleach',],
package_data={},
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
],
)
| #!/usr/bin/env python
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(
name='django-bleach',
version="0.1.0",
description='Easily use bleach with Django models and templates',
author='Tim Heap',
author_email='heap.tim@gmail.com',
url='https://bitbucket.org/ionata/django-bleach',
packages=['django_bleach',],
install_requires = ['bleach'],
package_data={},
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
],
)
| Add bleach as a requirement | Add bleach as a requirement
| Python | bsd-2-clause | python-force/django-bleach | ---
+++
@@ -15,6 +15,7 @@
author_email='heap.tim@gmail.com',
url='https://bitbucket.org/ionata/django-bleach',
packages=['django_bleach',],
+ install_requires = ['bleach'],
package_data={},
classifiers=[
'Environment :: Web Environment', |
fa6880c9a1da67097fb495339d1b62b3bcda854d | setup.py | setup.py | from setuptools import setup, find_packages
setup(
name='exchangerates',
version='0.1.01',
description="A module to make it easier to handle historical exchange rates",
long_description="",
classifiers=[
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
'Programming Language :: Python :: 2.7'
],
author='Mark Brough',
author_email='mark@brough.io',
url='http://github.com/markbrough/exchangerates',
license='MIT',
packages=find_packages(exclude=['ez_setup', 'examples']),
namespace_packages=[],
include_package_data=True,
zip_safe=True,
install_requires=[
'lxml == 3.7.3',
'requests == 2.13.0'
],
entry_points={
}
)
| from setuptools import setup, find_packages
setup(
name='exchangerates',
version='0.1.2',
description="A module to make it easier to handle historical exchange rates",
long_description="",
classifiers=[
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
'Programming Language :: Python :: 2.7'
],
author='Mark Brough',
author_email='mark@brough.io',
url='http://github.com/markbrough/exchangerates',
license='MIT',
packages=find_packages(exclude=['ez_setup', 'examples']),
namespace_packages=[],
include_package_data=True,
zip_safe=True,
install_requires=[
'lxml == 3.7.3',
'requests == 2.13.0'
],
entry_points={
}
)
| Use a different version number | Use a different version number
| Python | mit | markbrough/exchangerates | ---
+++
@@ -3,7 +3,7 @@
setup(
name='exchangerates',
- version='0.1.01',
+ version='0.1.2',
description="A module to make it easier to handle historical exchange rates",
long_description="",
classifiers=[ |
a22bdc548940218c408069218c4351941c68d296 | setup.py | setup.py | """
Flask-InfluxDB
"""
from setuptools import setup
setup(
name="Flask-InfluxDB",
version="0.3",
url="http://github.com/btashton/flask-influxdb",
license="BSD",
author="Brennan Ashton",
author_email="brennan@ombitron.com",
description="Flask bindings for the InfluxDB time series database",
long_description=__doc__,
py_modules=["flask_influxdb"],
zip_safe=False,
include_package_data=True,
platforms="any",
install_requires=["Flask", "influxdb==5.2.2",],
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",
],
)
| """
Flask-InfluxDB
"""
from setuptools import setup
setup(
name="Flask-InfluxDB",
version="0.3.1",
url="http://github.com/btashton/flask-influxdb",
license="BSD",
author="Brennan Ashton",
author_email="brennan@ombitron.com",
description="Flask bindings for the InfluxDB time series database",
long_description=__doc__,
packages=["flask_influxdb"],
zip_safe=False,
include_package_data=True,
platforms="any",
install_requires=["Flask", "influxdb==5.2.2",],
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",
],
)
| Fix packaging issue in 0.3 release | Fix packaging issue in 0.3 release
Signed-off-by: Brennan Ashton <3c2365aa085787349a5327558db844b55eabde30@brennanashton.com>
| Python | bsd-3-clause | Ombitron/flask-influxdb,Ombitron/flask-influxdb | ---
+++
@@ -5,14 +5,14 @@
setup(
name="Flask-InfluxDB",
- version="0.3",
+ version="0.3.1",
url="http://github.com/btashton/flask-influxdb",
license="BSD",
author="Brennan Ashton",
author_email="brennan@ombitron.com",
description="Flask bindings for the InfluxDB time series database",
long_description=__doc__,
- py_modules=["flask_influxdb"],
+ packages=["flask_influxdb"],
zip_safe=False,
include_package_data=True,
platforms="any", |
56a7f8aac203d2d0d685c0472d74090dc2e4da0c | setup.py | setup.py | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import sys, os
version = '0.1.9.dev'
setup(name='testdroid',
version=version,
description="Testdroid API client for Python",
long_description="""\
Testdroid API client for Python""",
classifiers=['Operating System :: OS Independent',
'Topic :: Software Development',
'Intended Audience :: Developers'], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
keywords='testdroid rest api client',
author='Henri Kivelä <henri.kivela@bitbar.com>, Sakari Rautiainen <sakari.rautiainen@bitbar.com>, Teppo Malinen <teppo.malinen@bitbar.com, Jarno Tuovinen <jarno.tuovinen@bitbar.com>',
author_email='info@bitbar.com',
url='http://www.testdroid.com',
license='Apache License v2.0',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
zip_safe=True,
install_requires=[
'requests', 'pillow',
],
entry_points = {
'console_scripts': [
'testdroid = testdroid:main',
],
},
)
| # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import sys, os
version = '0.1.9.dev'
setup(name='testdroid',
version=version,
description="Testdroid API client for Python",
long_description="""\
Testdroid API client for Python""",
classifiers=['Operating System :: OS Independent',
'Topic :: Software Development',
'Intended Audience :: Developers'], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
keywords='testdroid rest api client',
author='Henri Kivelä <henri.kivela@bitbar.com>, Sakari Rautiainen <sakari.rautiainen@bitbar.com>, Teppo Malinen <teppo.malinen@bitbar.com>, Jarno Tuovinen <jarno.tuovinen@bitbar.com>',
author_email='info@bitbar.com',
url='http://www.testdroid.com',
license='Apache License v2.0',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
zip_safe=True,
install_requires=[
'requests', 'pillow',
],
entry_points = {
'console_scripts': [
'testdroid = testdroid:main',
],
},
)
| Fix typo from authors field | Fix typo from authors field
| Python | apache-2.0 | aknackiron/testdroid-api-client-python,bitbar/testdroid-api-client-python,teppomalinen/testdroid-api-client-python | ---
+++
@@ -13,7 +13,7 @@
'Topic :: Software Development',
'Intended Audience :: Developers'], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
keywords='testdroid rest api client',
- author='Henri Kivelä <henri.kivela@bitbar.com>, Sakari Rautiainen <sakari.rautiainen@bitbar.com>, Teppo Malinen <teppo.malinen@bitbar.com, Jarno Tuovinen <jarno.tuovinen@bitbar.com>',
+ author='Henri Kivelä <henri.kivela@bitbar.com>, Sakari Rautiainen <sakari.rautiainen@bitbar.com>, Teppo Malinen <teppo.malinen@bitbar.com>, Jarno Tuovinen <jarno.tuovinen@bitbar.com>',
author_email='info@bitbar.com',
url='http://www.testdroid.com',
license='Apache License v2.0', |
cccca9c2feba5cbcb439f6d829e1e930819cb9c1 | setup.py | setup.py | #!/usr/bin/env python
from setuptools import setup, find_packages
tests_require = []
setup(
name='ashlar',
version='0.0.2',
description='Define and validate schemas for metadata for geotemporal event records',
author='Azavea, Inc.',
author_email='info@azavea.com',
keywords='gis jsonschema',
packages=find_packages(exclude=['tests']),
dependency_links=[
'https://github.com/azavea/djsonb/tarball/develop#egg=djsonb-0.1.4'
],
install_requires=[
'Django ==1.8.6',
'djangorestframework >=3.1.1',
'djangorestframework-gis >=0.8.1',
'django-filter >=0.9.2',
'djsonb >=0.1.4',
'jsonschema >=2.4.0',
'psycopg2 >=2.6',
'django-extensions >=1.5.2',
'python-dateutil >=2.4.2',
'PyYAML >=3.11'
],
extras_require={
'dev': [],
'test': tests_require
},
test_suite='tests',
tests_require=tests_require,
)
| #!/usr/bin/env python
from setuptools import setup, find_packages
tests_require = []
setup(
name='ashlar',
version='0.0.2',
description='Define and validate schemas for metadata for geotemporal event records',
author='Azavea, Inc.',
author_email='info@azavea.com',
keywords='gis jsonschema',
packages=find_packages(exclude=['tests']),
dependency_links=[
'https://github.com/azavea/djsonb/tarball/develop#egg=djsonb-0.1.5'
],
install_requires=[
'Django ==1.8.6',
'djangorestframework >=3.1.1',
'djangorestframework-gis >=0.8.1',
'django-filter >=0.9.2',
'djsonb >=0.1.5',
'jsonschema >=2.4.0',
'psycopg2 >=2.6',
'django-extensions >=1.5.2',
'python-dateutil >=2.4.2',
'PyYAML >=3.11',
'pytz >= 2015.7'
],
extras_require={
'dev': [],
'test': tests_require
},
test_suite='tests',
tests_require=tests_require,
)
| Update djsonb, and add pytz | Update djsonb, and add pytz
| Python | mit | azavea/ashlar,flibbertigibbet/ashlar,azavea/ashlar,flibbertigibbet/ashlar | ---
+++
@@ -13,19 +13,20 @@
keywords='gis jsonschema',
packages=find_packages(exclude=['tests']),
dependency_links=[
- 'https://github.com/azavea/djsonb/tarball/develop#egg=djsonb-0.1.4'
+ 'https://github.com/azavea/djsonb/tarball/develop#egg=djsonb-0.1.5'
],
install_requires=[
'Django ==1.8.6',
'djangorestframework >=3.1.1',
'djangorestframework-gis >=0.8.1',
'django-filter >=0.9.2',
- 'djsonb >=0.1.4',
+ 'djsonb >=0.1.5',
'jsonschema >=2.4.0',
'psycopg2 >=2.6',
'django-extensions >=1.5.2',
'python-dateutil >=2.4.2',
- 'PyYAML >=3.11'
+ 'PyYAML >=3.11',
+ 'pytz >= 2015.7'
],
extras_require={
'dev': [], |
3c8cea52ba0b4d6aadf34f1323cb54bf0238f394 | setup.py | setup.py | #!/usr/bin/env python
from setuptools import setup, find_packages
import re
# get version from __init__.py
INITFILE = "toytree/__init__.py"
CUR_VERSION = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
open(INITFILE, "r").read(),
re.M).group(1)
# run setup
setup(
name="toytree",
version=CUR_VERSION,
url="https://github.com/eaton-lab/toytree",
author="Deren Eaton",
author_email="de2356@columbia.edu",
description="minimalist tree plotting using toyplot",
long_description=open('README.rst').read(),
long_description_content_type='text/x-rst',
packages=find_packages(),
install_requires=[
"toyplot",
"numpy",
"requests",
"future",
],
entry_points={},
license='GPL',
classifiers=[
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
],
)
| #!/usr/bin/env python
from setuptools import setup, find_packages
import re
# get version from __init__.py
INITFILE = "toytree/__init__.py"
CUR_VERSION = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
open(INITFILE, "r").read(),
re.M).group(1)
# run setup
setup(
name="toytree",
version=CUR_VERSION,
url="https://github.com/eaton-lab/toytree",
author="Deren Eaton",
author_email="de2356@columbia.edu",
description="minimalist tree plotting using toyplot",
long_description=open('README.md').read(),
long_description_content_type='text/x-rst',
packages=find_packages(),
install_requires=[
"toyplot",
"numpy",
"requests",
"future",
],
entry_points={},
license='GPL',
classifiers=[
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
],
)
| Change readme to md to match. | Change readme to md to match. | Python | bsd-3-clause | eaton-lab/toytree | ---
+++
@@ -17,7 +17,7 @@
author="Deren Eaton",
author_email="de2356@columbia.edu",
description="minimalist tree plotting using toyplot",
- long_description=open('README.rst').read(),
+ long_description=open('README.md').read(),
long_description_content_type='text/x-rst',
packages=find_packages(),
install_requires=[ |
9cfa095f5f2aa0a62afc0572eb3605e81d607e10 | setup.py | setup.py | from setuptools import setup
from kafka_info import __version__
setup(
name="kafka_info",
version=__version__,
author="Federico Giraud",
author_email="fgiraud@yelp.com",
description="Shows kafka cluster information and metrics",
packages=["kafka_info", "kafka_info.utils"],
data_files=[("bash_completion.d", ["bash_completion.d/kafka-info"])],
scripts=["kafka-info"],
install_requires=[
"argparse",
"argcomplete",
"kazoo",
"PyYAML",
],
)
| from setuptools import setup
from kafka_info import __version__
setup(
name="kafka_info",
version=__version__,
author="Federico Giraud",
author_email="fgiraud@yelp.com",
description="Shows kafka cluster information and metrics",
packages=["kafka_info", "kafka_info.utils", "kafka_info.commands"],
data_files=[("bash_completion.d", ["bash_completion.d/kafka-info"])],
scripts=["kafka-info"],
install_requires=[
"argparse",
"argcomplete",
"kazoo",
"PyYAML",
],
)
| Fix package, bump to 0.1.3 | Fix package, bump to 0.1.3
| Python | apache-2.0 | anthonysandrin/kafka-utils,Yelp/kafka-utils,anthonysandrin/kafka-utils,Yelp/kafka-utils | ---
+++
@@ -9,7 +9,7 @@
author="Federico Giraud",
author_email="fgiraud@yelp.com",
description="Shows kafka cluster information and metrics",
- packages=["kafka_info", "kafka_info.utils"],
+ packages=["kafka_info", "kafka_info.utils", "kafka_info.commands"],
data_files=[("bash_completion.d", ["bash_completion.d/kafka-info"])],
scripts=["kafka-info"],
install_requires=[ |
5a7bf12879c637f72c78d5f0a3e45915dd08711a | setup.py | setup.py | #!/usr/bin/env python
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist bdist_wininst upload -r pypi')
sys.exit()
with open('README.rst') as f:
readme = f.read()
with open('LICENSE') as f:
license = f.read()
setup(
name='django-rest-surveys',
version='0.1.0',
description='A RESTful backend for giving surveys.',
long_description=readme,
author='Designlab',
author_email='hello@trydesignlab.com',
url='https://github.com/danxshap/django-rest-surveys',
packages=['rest_surveys'],
package_data={'': ['LICENSE']},
package_dir={'rest_surveys': 'rest_surveys'},
install_requires=[
'Django>=1.7',
'djangorestframework>=3.0',
'django-inline-ordering',
'djangorestframework-bulk',
],
license=license,
)
| #!/usr/bin/env python
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist bdist_wininst upload -r pypi')
sys.exit()
with open('README.rst') as f:
readme = f.read()
with open('LICENSE') as f:
license = f.read()
setup(
name='django-rest-surveys',
version='0.1.0',
description='A RESTful backend for giving surveys.',
long_description=readme,
author='Designlab',
author_email='hello@trydesignlab.com',
url='https://github.com/danxshap/django-rest-surveys',
packages=['rest_surveys'],
package_data={'': ['LICENSE']},
package_dir={'rest_surveys': 'rest_surveys'},
install_requires=[
'Django>=1.7',
'django-inline-ordering',
'django-filter<=0.11.0',
'djangorestframework>=3.0',
'djangorestframework-bulk',
],
license=license,
)
| Add django-filter to the required packages | Add django-filter to the required packages
| Python | mit | danxshap/django-rest-surveys | ---
+++
@@ -30,8 +30,9 @@
package_dir={'rest_surveys': 'rest_surveys'},
install_requires=[
'Django>=1.7',
+ 'django-inline-ordering',
+ 'django-filter<=0.11.0',
'djangorestframework>=3.0',
- 'django-inline-ordering',
'djangorestframework-bulk',
],
license=license, |
c36d6b17be66c0dfd0a540205b24b22b97739fb9 | setup.py | setup.py | from setuptools import setup
setup(
name='PyFVCOM',
packages=['PyFVCOM'],
version='2.1.0',
description=("PyFVCOM is a collection of various tools and utilities which can be used to extract, analyse and plot input and output files from FVCOM."),
author='Pierre Cazenave',
author_email='pica@pml.ac.uk',
url='https://gitlab.ecosystem-modelling.pml.ac.uk/fvcom/PyFVCOM',
download_url='http://gitlab.em.pml.ac.uk/fvcom/PyFVCOM/repository/archive.tar.gz?ref=2.1.0',
keywords=['fvcom', 'unstructured grid', 'mesh'],
license='MIT',
platforms='any',
install_requires=['jdcal', 'lxml', 'matplotlib', 'netCDF4', 'networkx', 'numpy>=1.13.0', 'pandas', 'pyproj', 'pytz', 'scipy', 'pyshp', 'UTide', 'shapely'],
classifiers=[]
)
| from setuptools import setup
version = '2.1.0'
setup(name='PyFVCOM',
packages=['PyFVCOM'],
version=version,
description=("PyFVCOM is a collection of various tools and utilities which can be used to extract, analyse and plot input and output files from FVCOM."),
author='Pierre Cazenave',
author_email='pica@pml.ac.uk',
url='https://gitlab.ecosystem-modelling.pml.ac.uk/fvcom/PyFVCOM',
download_url='http://gitlab.em.pml.ac.uk/fvcom/PyFVCOM/repository/archive.tar.gz?ref={}'.format(version),
keywords=['fvcom', 'unstructured grid', 'mesh'],
license='MIT',
platforms='any',
install_requires=['jdcal', 'lxml', 'matplotlib', 'netCDF4', 'networkx', 'numpy>=1.13.0', 'pandas', 'pyproj', 'pytz', 'scipy', 'pyshp', 'UTide', 'shapely'],
classifiers=[])
| Fix formatting and define the version up front. | Fix formatting and define the version up front.
| Python | mit | pwcazenave/PyFVCOM | ---
+++
@@ -1,18 +1,18 @@
from setuptools import setup
-setup(
- name='PyFVCOM',
- packages=['PyFVCOM'],
- version='2.1.0',
- description=("PyFVCOM is a collection of various tools and utilities which can be used to extract, analyse and plot input and output files from FVCOM."),
- author='Pierre Cazenave',
- author_email='pica@pml.ac.uk',
- url='https://gitlab.ecosystem-modelling.pml.ac.uk/fvcom/PyFVCOM',
- download_url='http://gitlab.em.pml.ac.uk/fvcom/PyFVCOM/repository/archive.tar.gz?ref=2.1.0',
- keywords=['fvcom', 'unstructured grid', 'mesh'],
- license='MIT',
- platforms='any',
- install_requires=['jdcal', 'lxml', 'matplotlib', 'netCDF4', 'networkx', 'numpy>=1.13.0', 'pandas', 'pyproj', 'pytz', 'scipy', 'pyshp', 'UTide', 'shapely'],
- classifiers=[]
-)
+version = '2.1.0'
+setup(name='PyFVCOM',
+ packages=['PyFVCOM'],
+ version=version,
+ description=("PyFVCOM is a collection of various tools and utilities which can be used to extract, analyse and plot input and output files from FVCOM."),
+ author='Pierre Cazenave',
+ author_email='pica@pml.ac.uk',
+ url='https://gitlab.ecosystem-modelling.pml.ac.uk/fvcom/PyFVCOM',
+ download_url='http://gitlab.em.pml.ac.uk/fvcom/PyFVCOM/repository/archive.tar.gz?ref={}'.format(version),
+ keywords=['fvcom', 'unstructured grid', 'mesh'],
+ license='MIT',
+ platforms='any',
+ install_requires=['jdcal', 'lxml', 'matplotlib', 'netCDF4', 'networkx', 'numpy>=1.13.0', 'pandas', 'pyproj', 'pytz', 'scipy', 'pyshp', 'UTide', 'shapely'],
+ classifiers=[])
+ |
c1218917e6169c9eaaf821f96610c1e9e6d81862 | setup.py | setup.py | from setuptools import setup
setup(
name = 'tomso',
packages = ['tomso'],
version = '0.0.7',
description = 'Tools for Modelling Stars and their Oscillations',
author = 'Warrick Ball',
author_email = 'W.H.Ball@bham.ac.uk',
url = 'https://github.com/warrickball/tomso',
download_url = 'https://github.com/warrickball/tomso/archive/v0.0.7.tar.gz',
install_requires=['numpy'],
keywords = [],
classifiers = [],
license = 'MIT'
)
| from setuptools import setup
setup(
name = 'tomso',
packages = ['tomso'],
version = '0.0.7',
description = 'Tools for Modelling Stars and their Oscillations',
long_description=open('README.md').read(),
long_description_content_type='text/markdown',
author = 'Warrick Ball',
author_email = 'W.H.Ball@bham.ac.uk',
url = 'https://github.com/warrickball/tomso',
download_url = 'https://github.com/warrickball/tomso/archive/v0.0.7.tar.gz',
install_requires=['numpy'],
keywords = [],
classifiers = [],
license = 'MIT'
)
| Use README.md for PyPI description | Use README.md for PyPI description
| Python | mit | warrickball/tomso | ---
+++
@@ -5,6 +5,8 @@
packages = ['tomso'],
version = '0.0.7',
description = 'Tools for Modelling Stars and their Oscillations',
+ long_description=open('README.md').read(),
+ long_description_content_type='text/markdown',
author = 'Warrick Ball',
author_email = 'W.H.Ball@bham.ac.uk',
url = 'https://github.com/warrickball/tomso', |
80d4cd9008d70664e7981a5e6018565d6b63d07a | setup.py | setup.py | from distutils.core import setup
setup(
name='udiskie',
version='0.3.9',
description='Removable disk automounter for udisks',
author='Byron Clark',
author_email='byron@theclarkfamily.name',
url='http://bitbucket.org/byronclark/udiskie',
license='MIT',
packages=[
'udiskie',
],
scripts=[
'bin/udiskie',
'bin/udiskie-umount',
],
)
| from distutils.core import setup
setup(
name='udiskie',
version='0.3.10',
description='Removable disk automounter for udisks',
author='Byron Clark',
author_email='byron@theclarkfamily.name',
url='http://bitbucket.org/byronclark/udiskie',
license='MIT',
packages=[
'udiskie',
],
scripts=[
'bin/udiskie',
'bin/udiskie-umount',
],
)
| Prepare for next development cycle. | Prepare for next development cycle.
| Python | mit | coldfix/udiskie,pstray/udiskie,pstray/udiskie,khardix/udiskie,coldfix/udiskie,mathstuf/udiskie | ---
+++
@@ -2,7 +2,7 @@
setup(
name='udiskie',
- version='0.3.9',
+ version='0.3.10',
description='Removable disk automounter for udisks',
author='Byron Clark',
author_email='byron@theclarkfamily.name', |
3e04c7e86d92785ba07f30ed2c0ec4eb575d6218 | setup.py | setup.py | from setuptools import setup, find_packages
import sys, os
setup(name='cc.license',
version='0.01',
description="License selection based on ccREL-based metadata.",
classifiers=[],
keywords='',
author='Creative Commons',
author_email='software@creativecommons.org',
url='http://wiki.creativecommons.org/CcLicense',
license='MIT',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
#package_data={'cc.license': ['*.xml', '*.txt']}, # doesn't work
data_files=[('cc/license/rdf', ['license.rdf/rdf/index.rdf',
'license.rdf/rdf/selectors.rdf',
'license.rdf/rdf/jurisdictions.rdf']),
('cc/license/xml', ['license.rdf/xml/questions.xml'])],
zip_safe=False,
test_suite='nose.collector',
install_requires=[
'setuptools',
'zope.interface',
'nose',
'Genshi',
'pylons', # XXX why does nose throw a RuntimeWarning without this?
],
setup_requires=['setuptools-git',],
entry_points="""
# -*- Entry points: -*-
[nose.plugins]
pylons = pylons.test:PylonsPlugin
""",
)
| from setuptools import setup, find_packages
import sys, os
setup(name='cc.license',
version='0.02',
description="License selection based on ccREL-based metadata.",
classifiers=[],
keywords='',
author='Creative Commons',
author_email='software@creativecommons.org',
url='http://wiki.creativecommons.org/CcLicense',
license='MIT',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
#package_data={'cc.license': ['*.xml', '*.txt']}, # doesn't work
data_files=[('cc/license/rdf', ['license.rdf/rdf/index.rdf',
'license.rdf/rdf/selectors.rdf',
'license.rdf/rdf/jurisdictions.rdf']),
('cc/license/xml', ['license.rdf/xml/questions.xml'])],
zip_safe=False,
test_suite='nose.collector',
install_requires=[
'setuptools',
'zope.interface',
'nose',
'Genshi',
'pylons', # XXX why does nose throw a RuntimeWarning without this?
],
setup_requires=['setuptools-git',],
entry_points="""
# -*- Entry points: -*-
[nose.plugins]
pylons = pylons.test:PylonsPlugin
""",
)
| Increment minor version number for new release (v0.02). | Increment minor version number for new release (v0.02).
| Python | mit | creativecommons/cc.license,creativecommons/cc.license | ---
+++
@@ -2,7 +2,7 @@
import sys, os
setup(name='cc.license',
- version='0.01',
+ version='0.02',
description="License selection based on ccREL-based metadata.",
classifiers=[],
keywords='', |
a1208aeffb57e16f49007f86b144ab6d576cbd0d | setup.py | setup.py | #! /usr/bin/env python
# coding: utf-8
from setuptools import find_packages, setup
setup(name='egoio',
author='NEXT ENERGY, Reiner Lemoine Institut gGmbH, ZNES',
author_email='ulf.p.mueller@hs-flensburg.de',
description='ego input/output repository',
version='0.3.0',
url='https://github.com/openego/ego.io',
packages=find_packages(),
license='GNU Affero General Public License v3.0',
install_requires=[
'geoalchemy2 >= 0.3.0, <= 0.4.0',
'sqlalchemy >= 1.0.11, <= 1.1.15',
'keyring >= 4.0',
'psycopg2'],
extras_require={
"sqlalchemy": 'postgresql'},
package_data={'tools': 'sqlacodegen_oedb.sh'}
)
| #! /usr/bin/env python
# coding: utf-8
from setuptools import find_packages, setup
setup(name='egoio',
author='NEXT ENERGY, Reiner Lemoine Institut gGmbH, ZNES',
author_email='ulf.p.mueller@hs-flensburg.de',
description='ego input/output repository',
version='0.3.0',
url='https://github.com/openego/ego.io',
packages=find_packages(),
license='GNU Affero General Public License v3.0',
install_requires=[
'geoalchemy2 >= 0.3.0, <= 0.4.1',
'sqlalchemy >= 1.0.11, <= 1.2.0',
'keyring >= 4.0',
'psycopg2'],
extras_require={
"sqlalchemy": 'postgresql'},
package_data={'tools': 'sqlacodegen_oedb.sh'}
)
| Update SQLAlchemy and Geoalchemy2 version range | Update SQLAlchemy and Geoalchemy2 version range
| Python | agpl-3.0 | openego/ego.io,openego/ego.io | ---
+++
@@ -12,8 +12,8 @@
packages=find_packages(),
license='GNU Affero General Public License v3.0',
install_requires=[
- 'geoalchemy2 >= 0.3.0, <= 0.4.0',
- 'sqlalchemy >= 1.0.11, <= 1.1.15',
+ 'geoalchemy2 >= 0.3.0, <= 0.4.1',
+ 'sqlalchemy >= 1.0.11, <= 1.2.0',
'keyring >= 4.0',
'psycopg2'],
extras_require={ |
33f87d824118d07cf8a7379bc46f624da5e3b433 | setup.py | setup.py | import sys
IS_PYTHON3 = sys.version_info[0] == 3
if not IS_PYTHON3:
print("Error: signac requires python version >= 3.x.")
sys.exit(1)
from setuptools import setup, find_packages
setup(
name='signac',
version='0.1.7dev1',
packages=find_packages(),
author='Carl Simon Adorf',
author_email='csadorf@umich.edu',
description="Computational Database.",
keywords='simulation tools mc md monte-carlo mongodb '
'jobmanagement materials database',
classifiers=[
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Topic :: Scientific/Engineering :: Physics",
],
extras_require={
'db': ['pymongo>=3.0'],
'mpi': ['mpi4py'],
'conversion': ['networkx>=1.1.0'],
},
entry_points={
'console_scripts': [
'signac = signac.contrib.script:main',
'signac_init = signac.contrib.init_project:main',
'signac_configure = signac.contrib.configure:main',
'signac_admin = signac.admin.manage:main',
'signac_server = signac.contrib.server:main',
'signac_user = signac.contrib.admin:main',
'signac_admin_project = signac.admin.manage_project:main',
],
},
)
| import sys
IS_PYTHON3 = sys.version_info[0] == 3
if not IS_PYTHON3:
print("Error: signac requires python version >= 3.x.")
sys.exit(1)
from setuptools import setup, find_packages
setup(
name='signac',
version='0.1.7dev5',
packages=find_packages(),
author='Carl Simon Adorf',
author_email='csadorf@umich.edu',
description="Computational Database.",
keywords='simulation tools mc md monte-carlo mongodb '
'jobmanagement materials database',
classifiers=[
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Topic :: Scientific/Engineering :: Physics",
],
extras_require={
'db': ['pymongo>=3.0'],
'mpi': ['mpi4py'],
'conversion': ['networkx>=1.1.0'],
},
)
| Remove entry points and bump dev version. | Remove entry points and bump dev version.
| Python | bsd-3-clause | csadorf/signac,csadorf/signac | ---
+++
@@ -8,7 +8,7 @@
setup(
name='signac',
- version='0.1.7dev1',
+ version='0.1.7dev5',
packages=find_packages(),
author='Carl Simon Adorf',
@@ -29,16 +29,4 @@
'mpi': ['mpi4py'],
'conversion': ['networkx>=1.1.0'],
},
-
- entry_points={
- 'console_scripts': [
- 'signac = signac.contrib.script:main',
- 'signac_init = signac.contrib.init_project:main',
- 'signac_configure = signac.contrib.configure:main',
- 'signac_admin = signac.admin.manage:main',
- 'signac_server = signac.contrib.server:main',
- 'signac_user = signac.contrib.admin:main',
- 'signac_admin_project = signac.admin.manage_project:main',
- ],
- },
) |
dd062287f182c1a4d7d32c3db365c0ee92eb4120 | setup.py | setup.py | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
classifiers = [
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.3",
"Topic :: Database",
"Topic :: Software Development",
"Topic :: Software Development :: Testing",
]
setup(
name='test.mysql',
version='0.1.0',
description='automatically setups a mysqld instance in a temporary directory, and destroys it after testing',
long_description='',
classifiers=classifiers,
keywords=[],
author='Takeshi Komiya',
author_email='i.tkomiya at gmail.com',
url='http://bitbucket.org/tk0miya/test.mysql',
license='Apache License 2.0',
packages=find_packages('src'),
package_dir={'': 'src'},
package_data = {'': ['buildout.cfg']},
include_package_data=True,
install_requires=[
'pymysql',
],
extras_require=dict(
test=[
'Nose',
'pep8',
],
),
test_suite='nose.collector',
)
| # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
classifiers = [
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.3",
"Topic :: Database",
"Topic :: Software Development",
"Topic :: Software Development :: Testing",
]
setup(
name='test.mysqld',
version='0.1.0',
description='automatically setups a mysqld instance in a temporary directory, and destroys it after testing',
long_description='',
classifiers=classifiers,
keywords=[],
author='Takeshi Komiya',
author_email='i.tkomiya at gmail.com',
url='http://bitbucket.org/tk0miya/test.mysql',
license='Apache License 2.0',
packages=find_packages('src'),
package_dir={'': 'src'},
package_data = {'': ['buildout.cfg']},
include_package_data=True,
install_requires=[
'pymysql',
],
extras_require=dict(
test=[
'Nose',
'pep8',
],
),
test_suite='nose.collector',
)
| Fix module name: test.mysql -> test.mysqld | Fix module name: test.mysql -> test.mysqld
| Python | apache-2.0 | tk0miya/testing.mysqld | ---
+++
@@ -15,7 +15,7 @@
setup(
- name='test.mysql',
+ name='test.mysqld',
version='0.1.0',
description='automatically setups a mysqld instance in a temporary directory, and destroys it after testing',
long_description='', |
04fb3d2a7d9416fe91b069b92d8fa157ea3d657b | setup.py | setup.py | from __future__ import absolute_import
from setuptools import setup, find_packages
setup(
name='flyingcloud',
version='0.1.9',
description='Build Docker images using SaltStack',
author='CookBrite, Inc.',
author_email='flyingcloud-admin@cookbrite.com',
license='Apache Software License 2.0',
url='https://github.com/cookbrite/flyingcloud',
packages=find_packages(exclude='tests'),
install_requires=['docker-py', 'sh', 'six'],
classifiers=['Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Development Status :: 3 - Alpha',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: Information Technology',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: Apache Software License',
'Operating System :: POSIX :: Linux',
'Topic :: Utilities',
'Topic :: System :: Clustering',
'Topic :: System :: Distributed Computing'],
long_description=open('README.rst').read(),
keywords="docker saltstack devops automation",
)
| from __future__ import absolute_import
from setuptools import setup, find_packages
setup(
name='flyingcloud',
version='0.1.9',
description='Build Docker images using SaltStack',
author='CookBrite, Inc.',
author_email='flyingcloud-admin@cookbrite.com',
license='Apache Software License 2.0',
url='https://github.com/cookbrite/flyingcloud',
packages=find_packages(exclude='tests'),
install_requires=['docker-py', 'requests', 'sh', 'six'],
classifiers=['Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Development Status :: 3 - Alpha',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: Information Technology',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: Apache Software License',
'Operating System :: POSIX :: Linux',
'Topic :: Utilities',
'Topic :: System :: Clustering',
'Topic :: System :: Distributed Computing'],
long_description=open('README.rst').read(),
keywords="docker saltstack devops automation",
)
| Add requests as a dependency | Add requests as a dependency
| Python | apache-2.0 | cookbrite/flyingcloud,cookbrite/flyingcloud | ---
+++
@@ -11,7 +11,7 @@
license='Apache Software License 2.0',
url='https://github.com/cookbrite/flyingcloud',
packages=find_packages(exclude='tests'),
- install_requires=['docker-py', 'sh', 'six'],
+ install_requires=['docker-py', 'requests', 'sh', 'six'],
classifiers=['Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Development Status :: 3 - Alpha', |
065cc9310a93af251db7a8464f6562ef62e3961c | setup.py | setup.py | #! /usr/bin/env python
# encoding: utf-8
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
REQUIREMENTS = [i.strip() for i in open("requirements.txt").readlines()]
setup(
name='pagseguro-sdk',
version="0.1.0",
description='SDK para utilização do PagSeguro em Python',
url='https://pagseguro-sdk.readthedocs.com/',
author='Jean O. Rodrigues',
author_email='github@jean.bz',
download_url='https://github.com/jeanmask/pagseguro-sdk/archive/v0.1.0.tar.gz',
license='MIT',
packages=['pagseguro'],
install_requires=REQUIREMENTS,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Environment :: Web Environment',
'Intended Audience :: End Users/Desktop',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
| #! /usr/bin/env python
# encoding: utf-8
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
REQUIREMENTS = [i.strip() for i in open("requirements.txt").readlines()]
setup(
name='pagseguro-sdk',
version="0.1.0",
description='SDK para utilização do PagSeguro em Python',
url='http://pagseguro-sdk.readthedocs.org/',
author='Jean O. Rodrigues',
author_email='github@jean.bz',
download_url='https://github.com/jeanmask/pagseguro-sdk/archive/v0.1.0.tar.gz',
license='MIT',
packages=['pagseguro'],
install_requires=REQUIREMENTS,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Environment :: Web Environment',
'Intended Audience :: End Users/Desktop',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
| Fix read the docs url. | Fix read the docs url.
| Python | mit | jeanmask/pagseguro-sdk | ---
+++
@@ -13,7 +13,7 @@
name='pagseguro-sdk',
version="0.1.0",
description='SDK para utilização do PagSeguro em Python',
- url='https://pagseguro-sdk.readthedocs.com/',
+ url='http://pagseguro-sdk.readthedocs.org/',
author='Jean O. Rodrigues',
author_email='github@jean.bz',
download_url='https://github.com/jeanmask/pagseguro-sdk/archive/v0.1.0.tar.gz', |
abb49ae96786018c7a8a8cd3c8b30d612f710ed2 | setup.py | setup.py | """Rachiopy setup script."""
from setuptools import find_packages, setup
VERSION = "1.0.3"
GITHUB_USERNAME = "rfverbruggen"
GITHUB_REPOSITORY = "rachiopy"
GITHUB_PATH = f"{GITHUB_USERNAME}/{GITHUB_REPOSITORY}"
GITHUB_URL = f"https://github.com/{GITHUB_PATH}"
DOWNLOAD_URL = f"{GITHUB_URL}/archive/{VERSION}.tar.gz"
PROJECT_URLS = {"Bug Reports": f"{GITHUB_URL}/issues"}
PACKAGES = find_packages(exclude=["tests", "tests.*"])
setup(
name="RachioPy",
version=VERSION,
author="Robbert Verbruggen",
author_email="rfverbruggen@icloud.com",
packages=PACKAGES,
install_requires=["requests"],
url=GITHUB_URL,
download_url=DOWNLOAD_URL,
project_urls=PROJECT_URLS,
license="MIT",
description="A Python module for the Rachio API.",
platforms="Cross Platform",
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3",
"Topic :: Software Development",
],
)
| """Rachiopy setup script."""
from setuptools import find_packages, setup
from datetime import datetime
NOW = datetime.now().strftime("%m%d%Y%H%M%S")
VERSION = f"1.0.4-dev{NOW}"
GITHUB_USERNAME = "rfverbruggen"
GITHUB_REPOSITORY = "rachiopy"
GITHUB_PATH = f"{GITHUB_USERNAME}/{GITHUB_REPOSITORY}"
GITHUB_URL = f"https://github.com/{GITHUB_PATH}"
DOWNLOAD_URL = f"{GITHUB_URL}/archive/{VERSION}.tar.gz"
PROJECT_URLS = {"Bug Reports": f"{GITHUB_URL}/issues"}
PACKAGES = find_packages(exclude=["tests", "tests.*"])
setup(
name="RachioPy",
version=VERSION,
author="Robbert Verbruggen",
author_email="rfverbruggen@icloud.com",
packages=PACKAGES,
install_requires=["requests"],
url=GITHUB_URL,
download_url=DOWNLOAD_URL,
project_urls=PROJECT_URLS,
license="MIT",
description="A Python module for the Rachio API.",
platforms="Cross Platform",
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3",
"Topic :: Software Development",
],
)
| Set the next dev version number: 1.0.4-dev | Set the next dev version number: 1.0.4-dev | Python | mit | rfverbruggen/rachiopy | ---
+++
@@ -1,7 +1,10 @@
"""Rachiopy setup script."""
from setuptools import find_packages, setup
+from datetime import datetime
-VERSION = "1.0.3"
+NOW = datetime.now().strftime("%m%d%Y%H%M%S")
+
+VERSION = f"1.0.4-dev{NOW}"
GITHUB_USERNAME = "rfverbruggen"
GITHUB_REPOSITORY = "rachiopy" |
de5fbf7d63245e9d14844e66fdf16f88dbfae2e5 | rest_framework/authtoken/migrations/0001_initial.py | rest_framework/authtoken/migrations/0001_initial.py |
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Token',
fields=[
('key', models.CharField(max_length=40, serialize=False, primary_key=True)),
('created', models.DateTimeField(auto_now_add=True)),
('user', models.OneToOneField(related_name=b'auth_token', to=settings.AUTH_USER_MODEL)),
],
options={
},
bases=(models.Model,),
),
]
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Token',
fields=[
('key', models.CharField(primary_key=True, serialize=False, max_length=40)),
('created', models.DateTimeField(auto_now_add=True)),
('user', models.OneToOneField(to=settings.AUTH_USER_MODEL, related_name='auth_token')),
],
options={
},
bases=(models.Model,),
),
]
| Update initial migration to work on Python 3 | Update initial migration to work on Python 3 | Python | bsd-2-clause | ajaali/django-rest-framework,mgaitan/django-rest-framework,xiaotangyuan/django-rest-framework,wedaly/django-rest-framework,edx/django-rest-framework,uploadcare/django-rest-framework,brandoncazander/django-rest-framework,mgaitan/django-rest-framework,werthen/django-rest-framework,akalipetis/django-rest-framework,YBJAY00000/django-rest-framework,douwevandermeij/django-rest-framework,elim/django-rest-framework,jpulec/django-rest-framework,abdulhaq-e/django-rest-framework,waytai/django-rest-framework,sbellem/django-rest-framework,justanr/django-rest-framework,akalipetis/django-rest-framework,antonyc/django-rest-framework,simudream/django-rest-framework,gregmuellegger/django-rest-framework,AlexandreProenca/django-rest-framework,aericson/django-rest-framework,jpadilla/django-rest-framework,johnraz/django-rest-framework,fishky/django-rest-framework,jerryhebert/django-rest-framework,sheppard/django-rest-framework,wwj718/django-rest-framework,raphaelmerx/django-rest-framework,cyberj/django-rest-framework,kgeorgy/django-rest-framework,justanr/django-rest-framework,cheif/django-rest-framework,leeahoward/django-rest-framework,alacritythief/django-rest-framework,cyberj/django-rest-framework,ebsaral/django-rest-framework,MJafarMashhadi/django-rest-framework,nryoung/django-rest-framework,rubendura/django-rest-framework,jness/django-rest-framework,James1345/django-rest-framework,jtiai/django-rest-framework,qsorix/django-rest-framework,raphaelmerx/django-rest-framework,kgeorgy/django-rest-framework,rhblind/django-rest-framework,hunter007/django-rest-framework,davesque/django-rest-framework,jtiai/django-rest-framework,bluedazzle/django-rest-framework,gregmuellegger/django-rest-framework,hnakamur/django-rest-framework,adambain-vokal/django-rest-framework,zeldalink0515/django-rest-framework,tomchristie/django-rest-framework,tigeraniya/django-rest-framework,cheif/django-rest-framework,lubomir/django-rest-framework,iheitlager/django-rest-framework,AlexandreProenca/django-rest-framework,andriy-s/django-rest-framework,VishvajitP/django-rest-framework,krinart/django-rest-framework,abdulhaq-e/django-rest-framework,zeldalink0515/django-rest-framework,ambivalentno/django-rest-framework,ashishfinoit/django-rest-framework,gregmuellegger/django-rest-framework,canassa/django-rest-framework,YBJAY00000/django-rest-framework,vstoykov/django-rest-framework,alacritythief/django-rest-framework,ajaali/django-rest-framework,hunter007/django-rest-framework,uruz/django-rest-framework,delinhabit/django-rest-framework,lubomir/django-rest-framework,pombredanne/django-rest-framework,leeahoward/django-rest-framework,mgaitan/django-rest-framework,tcroiset/django-rest-framework,adambain-vokal/django-rest-framework,d0ugal/django-rest-framework,nryoung/django-rest-framework,ossanna16/django-rest-framework,potpath/django-rest-framework,nryoung/django-rest-framework,nhorelik/django-rest-framework,jpadilla/django-rest-framework,ashishfinoit/django-rest-framework,qsorix/django-rest-framework,rafaelcaricio/django-rest-framework,uruz/django-rest-framework,arpheno/django-rest-framework,cheif/django-rest-framework,kylefox/django-rest-framework,brandoncazander/django-rest-framework,linovia/django-rest-framework,linovia/django-rest-framework,yiyocx/django-rest-framework,jpulec/django-rest-framework,ambivalentno/django-rest-framework,jerryhebert/django-rest-framework,damycra/django-rest-framework,pombredanne/django-rest-framework,andriy-s/django-rest-framework,abdulhaq-e/django-rest-framework,buptlsl/django-rest-framework,leeahoward/django-rest-framework,kylefox/django-rest-framework,delinhabit/django-rest-framework,tcroiset/django-rest-framework,MJafarMashhadi/django-rest-framework,ajaali/django-rest-framework,rhblind/django-rest-framework,agconti/django-rest-framework,ticosax/django-rest-framework,bluedazzle/django-rest-framework,wwj718/django-rest-framework,davesque/django-rest-framework,alacritythief/django-rest-framework,jpulec/django-rest-framework,ashishfinoit/django-rest-framework,tomchristie/django-rest-framework,potpath/django-rest-framework,ossanna16/django-rest-framework,aericson/django-rest-framework,ticosax/django-rest-framework,antonyc/django-rest-framework,iheitlager/django-rest-framework,ticosax/django-rest-framework,rubendura/django-rest-framework,HireAnEsquire/django-rest-framework,paolopaolopaolo/django-rest-framework,ezheidtmann/django-rest-framework,delinhabit/django-rest-framework,aericson/django-rest-framework,d0ugal/django-rest-framework,canassa/django-rest-framework,wangpanjun/django-rest-framework,rafaelang/django-rest-framework,kezabelle/django-rest-framework,paolopaolopaolo/django-rest-framework,wzbozon/django-rest-framework,wangpanjun/django-rest-framework,callorico/django-rest-framework,krinart/django-rest-framework,thedrow/django-rest-framework-1,linovia/django-rest-framework,jpadilla/django-rest-framework,bluedazzle/django-rest-framework,wangpanjun/django-rest-framework,thedrow/django-rest-framework-1,yiyocx/django-rest-framework,brandoncazander/django-rest-framework,potpath/django-rest-framework,canassa/django-rest-framework,dmwyatt/django-rest-framework,pombredanne/django-rest-framework,maryokhin/django-rest-framework,MJafarMashhadi/django-rest-framework,ambivalentno/django-rest-framework,qsorix/django-rest-framework,sheppard/django-rest-framework,hnarayanan/django-rest-framework,arpheno/django-rest-framework,wzbozon/django-rest-framework,lubomir/django-rest-framework,johnraz/django-rest-framework,damycra/django-rest-framework,werthen/django-rest-framework,atombrella/django-rest-framework,uruz/django-rest-framework,James1345/django-rest-framework,tigeraniya/django-rest-framework,waytai/django-rest-framework,sehmaschine/django-rest-framework,fishky/django-rest-framework,yiyocx/django-rest-framework,nhorelik/django-rest-framework,YBJAY00000/django-rest-framework,johnraz/django-rest-framework,kylefox/django-rest-framework,werthen/django-rest-framework,wwj718/django-rest-framework,dmwyatt/django-rest-framework,xiaotangyuan/django-rest-framework,atombrella/django-rest-framework,hnarayanan/django-rest-framework,James1345/django-rest-framework,tigeraniya/django-rest-framework,kgeorgy/django-rest-framework,maryokhin/django-rest-framework,sbellem/django-rest-framework,xiaotangyuan/django-rest-framework,AlexandreProenca/django-rest-framework,douwevandermeij/django-rest-framework,sehmaschine/django-rest-framework,hnakamur/django-rest-framework,edx/django-rest-framework,HireAnEsquire/django-rest-framework,vstoykov/django-rest-framework,rafaelcaricio/django-rest-framework,sbellem/django-rest-framework,vstoykov/django-rest-framework,kezabelle/django-rest-framework,HireAnEsquire/django-rest-framework,kezabelle/django-rest-framework,jness/django-rest-framework,elim/django-rest-framework,raphaelmerx/django-rest-framework,davesque/django-rest-framework,rubendura/django-rest-framework,simudream/django-rest-framework,kennydude/django-rest-framework,ossanna16/django-rest-framework,waytai/django-rest-framework,justanr/django-rest-framework,maryokhin/django-rest-framework,thedrow/django-rest-framework-1,cyberj/django-rest-framework,wedaly/django-rest-framework,rafaelang/django-rest-framework,rafaelcaricio/django-rest-framework,rafaelang/django-rest-framework,tcroiset/django-rest-framework,rhblind/django-rest-framework,jness/django-rest-framework,ebsaral/django-rest-framework,sehmaschine/django-rest-framework,kennydude/django-rest-framework,kennydude/django-rest-framework,ezheidtmann/django-rest-framework,sheppard/django-rest-framework,akalipetis/django-rest-framework,tomchristie/django-rest-framework,adambain-vokal/django-rest-framework,hunter007/django-rest-framework,damycra/django-rest-framework,edx/django-rest-framework,nhorelik/django-rest-framework,dmwyatt/django-rest-framework,jerryhebert/django-rest-framework,d0ugal/django-rest-framework,jtiai/django-rest-framework,callorico/django-rest-framework,callorico/django-rest-framework,agconti/django-rest-framework,uploadcare/django-rest-framework,andriy-s/django-rest-framework,iheitlager/django-rest-framework,krinart/django-rest-framework,agconti/django-rest-framework,zeldalink0515/django-rest-framework,wzbozon/django-rest-framework,fishky/django-rest-framework,arpheno/django-rest-framework,wedaly/django-rest-framework,paolopaolopaolo/django-rest-framework,VishvajitP/django-rest-framework,VishvajitP/django-rest-framework,simudream/django-rest-framework,ezheidtmann/django-rest-framework,ebsaral/django-rest-framework,antonyc/django-rest-framework,elim/django-rest-framework,atombrella/django-rest-framework,hnarayanan/django-rest-framework,buptlsl/django-rest-framework,buptlsl/django-rest-framework,hnakamur/django-rest-framework,douwevandermeij/django-rest-framework,uploadcare/django-rest-framework | ---
+++
@@ -1,4 +1,4 @@
-
+# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
@@ -15,9 +15,9 @@
migrations.CreateModel(
name='Token',
fields=[
- ('key', models.CharField(max_length=40, serialize=False, primary_key=True)),
+ ('key', models.CharField(primary_key=True, serialize=False, max_length=40)),
('created', models.DateTimeField(auto_now_add=True)),
- ('user', models.OneToOneField(related_name=b'auth_token', to=settings.AUTH_USER_MODEL)),
+ ('user', models.OneToOneField(to=settings.AUTH_USER_MODEL, related_name='auth_token')),
],
options={
}, |
8e9fd28004c1f8daadc5ce7f51b40543c28720c0 | djangoautoconf/settings_templates/smtp_account_template.py | djangoautoconf/settings_templates/smtp_account_template.py | __author__ = 'q19420'
smtp_username = "test"
smtp_password = "testpass" | __author__ = 'weijia'
smtp_username = None
smtp_password = None | Use None as username and password for SMTP. | Use None as username and password for SMTP.
| Python | bsd-3-clause | weijia/djangoautoconf,weijia/djangoautoconf | ---
+++
@@ -1,5 +1,5 @@
-__author__ = 'q19420'
+__author__ = 'weijia'
-smtp_username = "test"
-smtp_password = "testpass"
+smtp_username = None
+smtp_password = None |
60f87cb4c3523faf5c5cdbc5f16453cae755988b | angr/procedures/java_jni/GetArrayElements.py | angr/procedures/java_jni/GetArrayElements.py | from . import JNISimProcedure
from ...engines.soot.values.arrayref import SimSootValue_ArrayRef
class GetArrayElements(JNISimProcedure):
return_ty = 'reference'
def run(self, ptr_env, array, ptr_isCopy):
array_ref = self.state.jni_references.lookup(array)
values = self.load_java_array(self.state, array_ref)
memory_addr = self.store_in_native_memory(values, array_ref.type)
return memory_addr
def load_java_array(self, array_ref, start_idx=None, end_idx=None):
if start_idx is None:
start_idx = 0
if end_idx is None:
end_idx = self.state.solver.max(array_ref.size)
javavm_memory = self.state.get_javavm_view_of_plugin("memory")
values = []
for idx in range(start_idx, end_idx):
idx_array_ref = SimSootValue_ArrayRef.get_arrayref_for_idx(base=array_ref, idx=idx)
value = javavm_memory.load(idx_array_ref)
values.append(value)
return values | from . import JNISimProcedure
from ...engines.soot.values.arrayref import SimSootValue_ArrayRef
class GetArrayElements(JNISimProcedure):
return_ty = 'reference'
def run(self, ptr_env, array, ptr_isCopy):
array_ref = self.state.jni_references.lookup(array)
values = self.load_java_array(self.state, array_ref)
memory_addr = self.store_in_native_memory(values, array_ref.type)
if self.state.solver.eval(ptr_isCopy != 0):
self.store_in_native_memory(data=self.JNI_TRUE, data_type='boolean', addr=ptr_isCopy)
return memory_addr
def load_java_array(self, array_ref, start_idx=None, end_idx=None):
if start_idx is None:
start_idx = 0
if end_idx is None:
end_idx = self.state.solver.max(array_ref.size)
javavm_memory = self.state.get_javavm_view_of_plugin("memory")
values = []
for idx in range(start_idx, end_idx):
idx_array_ref = SimSootValue_ArrayRef.get_arrayref_for_idx(base=array_ref, idx=idx)
value = javavm_memory.load(idx_array_ref)
values.append(value)
return values | Fix case if isCopy is null | Fix case if isCopy is null
| Python | bsd-2-clause | schieb/angr,schieb/angr,angr/angr,angr/angr,iamahuman/angr,angr/angr,iamahuman/angr,schieb/angr,iamahuman/angr | ---
+++
@@ -9,6 +9,8 @@
array_ref = self.state.jni_references.lookup(array)
values = self.load_java_array(self.state, array_ref)
memory_addr = self.store_in_native_memory(values, array_ref.type)
+ if self.state.solver.eval(ptr_isCopy != 0):
+ self.store_in_native_memory(data=self.JNI_TRUE, data_type='boolean', addr=ptr_isCopy)
return memory_addr
def load_java_array(self, array_ref, start_idx=None, end_idx=None): |
36d7a5f754fef3bdab0103229fe8b5ee267f9376 | scripts/urls-starting-with.py | scripts/urls-starting-with.py | import re
import sys
from xml.sax import make_parser, handler
if len(sys.argv) < 3:
print "This script expects two arguments: \n1. The path to a posts.xml file from a Stack Overflow data dump.\n2. A URL prefix to search for."
else:
start_with = sys.argv[2]
class SOProcessor(handler.ContentHandler):
def startElement(self, name, attrs):
if name == "row":
if attrs["PostTypeId"] == "1":
body = attrs["Body"]
if start_with in body:
matches = re.findall(r'<a href="([^"]+)"', body)
for url in filter(lambda x: x.startswith(start_with), matches):
print url
parser = make_parser()
parser.setContentHandler(SOProcessor())
parser.parse(open(sys.argv[1]))
| import re
import sys
from xml.sax import make_parser, handler
if len(sys.argv) < 3:
print "This script expects two arguments: \n1. The path to a posts.xml file from a Stack Overflow data dump.\n2. A URL prefix to search for."
else:
start_with = sys.argv[2]
class SOProcessor(handler.ContentHandler):
def startElement(self, name, attrs):
if name == "row":
if attrs["PostTypeId"] == "1":
body = attrs["Body"]
if start_with in body:
matches = re.findall(r'<a href="([^"]+)"', body)
for url in filter(lambda x: x.startswith(start_with), matches):
print url, attrs["Tags"]
parser = make_parser()
parser.setContentHandler(SOProcessor())
parser.parse(open(sys.argv[1]))
| Print tags out when scanning for URLs. | Print tags out when scanning for URLs.
| Python | bsd-3-clause | alnorth/stackdoc,alnorth/stackdoc,alnorth/stackdoc | ---
+++
@@ -16,7 +16,7 @@
if start_with in body:
matches = re.findall(r'<a href="([^"]+)"', body)
for url in filter(lambda x: x.startswith(start_with), matches):
- print url
+ print url, attrs["Tags"]
parser = make_parser()
parser.setContentHandler(SOProcessor()) |
fe4f2fa1c64d40a15c49cc4183a59c912574fdff | ibmcnx/doc/DataSources.py | ibmcnx/doc/DataSources.py | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
cell = "'/Cell:" + AdminControl.getCell() + "/'"
cellid = AdminConfig.getid( cell )
dbs = AdminConfig.list( 'DataSource', str(cellid) )
for db in dbs:
t1 = ibmcnx.functions.getDSId( db )
AdminConfig.list( t1 ) | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
print AdminControl.getCell()
cell = "'/Cell:" + AdminControl.getCell() + "/'"
cellid = AdminConfig.getid( cell )
dbs = AdminConfig.list( 'DataSource', str(cellid) )
for db in dbs:
t1 = ibmcnx.functions.getDSId( db )
AdminConfig.list( t1 ) | Create script to save documentation to a file | 4: Create script to save documentation to a file
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/4 | Python | apache-2.0 | stoeps13/ibmcnx2,stoeps13/ibmcnx2 | ---
+++
@@ -14,6 +14,7 @@
import ibmcnx.functions
+print AdminControl.getCell()
cell = "'/Cell:" + AdminControl.getCell() + "/'"
cellid = AdminConfig.getid( cell )
dbs = AdminConfig.list( 'DataSource', str(cellid) ) |
ed59db63ab5832468b1348f6cd9bf00880fbbdbc | busstops/management/commands/import_areas.py | busstops/management/commands/import_areas.py | """
Import administrative areas from the NPTG.
Usage:
import_areas < AdminAreas.csv
"""
from ..import_from_csv import ImportFromCSVCommand
from ...models import AdminArea
class Command(ImportFromCSVCommand):
def handle_row(self, row):
AdminArea.objects.update_or_create(
id=row['AdministrativeAreaCode'],
defaults={
'atco_code': row['AtcoAreaCode'],
'name': row['AreaName'],
'short_name': row['ShortName'],
'country': row['Country'],
'region_id': row['RegionCode'],
}
)
| """
Import administrative areas from the NPTG.
Usage:
import_areas < AdminAreas.csv
"""
from ..import_from_csv import ImportFromCSVCommand
from ...models import AdminArea
class Command(ImportFromCSVCommand):
def handle_row(self, row):
AdminArea.objects.update_or_create(
id=row['AdministrativeAreaCode'],
defaults={
'atco_code': row['AtcoAreaCode'],
'name': row['AreaName'],
'short_name': row['ShortName'],
'country': row['Country'],
'region_id': row['RegionCode'],
}
)
def handle(self, *args, **options):
super(Command, self).handle(*args, **options)
# Move Cumbria to the North West.
# There is the legacy of the confusing 'North East and Cumbria' Traveline region,
# but actually Cumbrian bus services are in the North West now
AdminArea.objects.filter(name='Cumbria').update(region_id='NW')
| Move Cumbria to the North West | Move Cumbria to the North West
| Python | mpl-2.0 | jclgoodwin/bustimes.org.uk,jclgoodwin/bustimes.org.uk,stev-0/bustimes.org.uk,jclgoodwin/bustimes.org.uk,stev-0/bustimes.org.uk,jclgoodwin/bustimes.org.uk,stev-0/bustimes.org.uk,stev-0/bustimes.org.uk,stev-0/bustimes.org.uk | ---
+++
@@ -23,3 +23,11 @@
'region_id': row['RegionCode'],
}
)
+
+ def handle(self, *args, **options):
+ super(Command, self).handle(*args, **options)
+
+ # Move Cumbria to the North West.
+ # There is the legacy of the confusing 'North East and Cumbria' Traveline region,
+ # but actually Cumbrian bus services are in the North West now
+ AdminArea.objects.filter(name='Cumbria').update(region_id='NW') |
8974832551f48ef3fbd3023cc2c26836aa01de1c | derrida/__init__.py | derrida/__init__.py | __version_info__ = (1, 1, 0, None)
# Dot-connect all but the last. Last is dash-connected if not None.
__version__ = '.'.join([str(i) for i in __version_info__[:-1]])
if __version_info__[-1] is not None:
__version__ += ('-%s' % (__version_info__[-1],))
# context processor to add version to the template environment
def context_extras(request):
return {
# software version
'SW_VERSION': __version__
}
| __version_info__ = (1, 2, 0, 'dev')
# Dot-connect all but the last. Last is dash-connected if not None.
__version__ = '.'.join([str(i) for i in __version_info__[:-1]])
if __version_info__[-1] is not None:
__version__ += ('-%s' % (__version_info__[-1],))
# context processor to add version to the template environment
def context_extras(request):
return {
# software version
'SW_VERSION': __version__
}
| Set develop version to 1.2-dev | Set develop version to 1.2-dev
| Python | apache-2.0 | Princeton-CDH/derrida-django,Princeton-CDH/derrida-django,Princeton-CDH/derrida-django,Princeton-CDH/derrida-django | ---
+++
@@ -1,4 +1,4 @@
-__version_info__ = (1, 1, 0, None)
+__version_info__ = (1, 2, 0, 'dev')
# Dot-connect all but the last. Last is dash-connected if not None. |
c98ac4ca313606c966dc45dbe7861898177f2f04 | api/tests/test_delete_bucket_list.py | api/tests/test_delete_bucket_list.py | import json
from api.test import BaseTestCase
from api.models import BucketList
class TestDeleteBucketList(BaseTestCase):
def test_delete_bucket_list(self):
bucket_list_one = {
"description": "Movies i have to watch by the end of the week",
"status": "Pending",
"title": "Entertainment",
"user_id": 1
}
self.client.post('/api/v1/bucketlists',
headers={
'Authorization': 'JWT ' + self.token
},
data=json.dumps(bucket_list_one),
content_type='application/json')
count = len(BucketList.query.all())
self.client.delete('/api/v1/bucketlists/1',
headers={
'Authorization': 'JWT ' + self.token
},)
new_count = len(BucketList.query.all())
self.assertEqual(new_count - count, -1)
| import json
from api.test import BaseTestCase
from api.models import BucketList
class TestDeleteBucketList(BaseTestCase):
def test_delete_bucket_list(self):
bucket_list_one = {
"description": "Movies i have to watch by the end of the week",
"status": "Pending",
"title": "Entertainment",
"user_id": 1
}
self.client.post('/api/v1/bucketlists',
headers={
'Authorization': 'JWT ' + self.token
},
data=json.dumps(bucket_list_one),
content_type='application/json')
count = len(BucketList.query.all())
self.client.delete('/api/v1/bucketlists/1',
headers={
'Authorization': 'JWT ' + self.token
},)
new_count = len(BucketList.query.all())
self.assertEqual(new_count - count, -1)
response = self.client.get(
'/api/v1/bucketlists/1',
headers=dict(
Authorization='Bearer ' + self.token
)
)
self.assertIn("Bucket list not found", str(response.data))
self.assertEqual(response.status_code, 404)
| Modify test to test that bucketlist nolonger exists in system | Modify test to test that bucketlist nolonger exists in system
| Python | mit | EdwinKato/bucket-list,EdwinKato/bucket-list,EdwinKato/bucket-list,EdwinKato/bucket-list,EdwinKato/bucket-list | ---
+++
@@ -27,3 +27,13 @@
},)
new_count = len(BucketList.query.all())
self.assertEqual(new_count - count, -1)
+
+ response = self.client.get(
+ '/api/v1/bucketlists/1',
+ headers=dict(
+ Authorization='Bearer ' + self.token
+ )
+ )
+
+ self.assertIn("Bucket list not found", str(response.data))
+ self.assertEqual(response.status_code, 404) |
a2aceffa0133756d833ba0057b3d22e7f4d95406 | utils.py | utils.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
def is_image_file(f):
known_extensions = ('.jpg', '.jpeg', '.png')
return os.path.isfile(f) and f.lower().endswith(known_extensions)
def get_files_list(paths, recursive):
result = []
for path in paths:
if os.path.isdir(path):
if recursive:
for root, dir_names, file_names in os.walk(path):
for filename in file_names:
f = os.path.join(root, filename)
if is_image_file(f):
result.append(f)
else:
for filename in os.listdir(path):
f = os.path.join(path, filename)
if is_image_file(f):
result.append(f)
elif is_image_file(path):
result.append(path)
else:
raise RuntimeError('unknown image format ', path)
return result
def get_file_list(path):
return get_files_list((path,), True)
def make_dir_by_file_name(file_name):
dir_name, file_name = os.path.split(file_name)
file_name_wo_ext = os.path.splitext(file_name)[0]
out_dir = os.path.join(dir_name, file_name_wo_ext)
if not os.path.exists(out_dir):
os.makedirs(out_dir)
return out_dir
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
def is_image_file(f):
known_extensions = ('.bmp', '.jpg', '.jpeg', '.png')
return os.path.isfile(f) and f.lower().endswith(known_extensions)
def get_files_list(paths, recursive):
result = []
for path in paths:
if os.path.isdir(path):
if recursive:
for root, dir_names, file_names in os.walk(path):
for filename in file_names:
f = os.path.join(root, filename)
if is_image_file(f):
result.append(f)
else:
for filename in os.listdir(path):
f = os.path.join(path, filename)
if is_image_file(f):
result.append(f)
elif is_image_file(path):
result.append(path)
else:
raise RuntimeError('unknown image format ', path)
return result
def get_file_list(path):
return get_files_list((path,), True)
def make_dir_by_file_name(file_name):
dir_name, file_name = os.path.split(file_name)
file_name_wo_ext = os.path.splitext(file_name)[0]
out_dir = os.path.join(dir_name, file_name_wo_ext)
if not os.path.exists(out_dir):
os.makedirs(out_dir)
return out_dir
| Add BMP files to supported list | Add BMP files to supported list
| Python | mit | vladimirgamalian/pictools | ---
+++
@@ -5,7 +5,7 @@
def is_image_file(f):
- known_extensions = ('.jpg', '.jpeg', '.png')
+ known_extensions = ('.bmp', '.jpg', '.jpeg', '.png')
return os.path.isfile(f) and f.lower().endswith(known_extensions)
|
ae2be1dc39baa8f8cd73e574d384619290b0c707 | tests/api/views/users/read_test.py | tests/api/views/users/read_test.py | from tests.data import add_fixtures, users
def test_read_user(db_session, client):
john = users.john()
add_fixtures(db_session, john)
res = client.get('/users/{id}'.format(id=john.id))
assert res.status_code == 200
assert res.json == {
u'id': john.id,
u'firstName': u'John',
u'lastName': u'Doe',
u'name': u'John Doe',
u'club': None,
u'trackingCallsign': None,
u'trackingDelay': 0,
u'followers': 0,
u'following': 0,
}
def test_read_missing_user(client):
res = client.get('/users/1000000000000')
assert res.status_code == 404
def test_read_user_with_invalid_id(client):
res = client.get('/users/abc')
assert res.status_code == 404
| from skylines.model import Follower
from tests.api import auth_for
from tests.data import add_fixtures, users
def test_read_user(db_session, client):
john = users.john()
add_fixtures(db_session, john)
res = client.get('/users/{id}'.format(id=john.id))
assert res.status_code == 200
assert res.json == {
u'id': john.id,
u'firstName': u'John',
u'lastName': u'Doe',
u'name': u'John Doe',
u'club': None,
u'trackingCallsign': None,
u'trackingDelay': 0,
u'followers': 0,
u'following': 0,
}
def test_following(db_session, client):
john = users.john()
jane = users.jane()
Follower.follow(john, jane)
add_fixtures(db_session, john, jane)
res = client.get('/users/{id}'.format(id=john.id))
assert res.status_code == 200
assert res.json['following'] == 1
res = client.get('/users/{id}'.format(id=jane.id))
assert res.status_code == 200
assert res.json['followers'] == 1
assert 'followed' not in res.json
res = client.get('/users/{id}'.format(id=jane.id), headers=auth_for(john))
assert res.status_code == 200
assert res.json['followers'] == 1
assert res.json['followed'] == True
def test_read_missing_user(client):
res = client.get('/users/1000000000000')
assert res.status_code == 404
def test_read_user_with_invalid_id(client):
res = client.get('/users/abc')
assert res.status_code == 404
| Add more "GET /users/:id" tests | tests/api: Add more "GET /users/:id" tests
| Python | agpl-3.0 | Turbo87/skylines,skylines-project/skylines,shadowoneau/skylines,Harry-R/skylines,shadowoneau/skylines,RBE-Avionik/skylines,skylines-project/skylines,RBE-Avionik/skylines,Turbo87/skylines,RBE-Avionik/skylines,shadowoneau/skylines,Harry-R/skylines,Turbo87/skylines,skylines-project/skylines,Harry-R/skylines,Harry-R/skylines,shadowoneau/skylines,skylines-project/skylines,RBE-Avionik/skylines,Turbo87/skylines | ---
+++
@@ -1,3 +1,5 @@
+from skylines.model import Follower
+from tests.api import auth_for
from tests.data import add_fixtures, users
@@ -20,6 +22,27 @@
}
+def test_following(db_session, client):
+ john = users.john()
+ jane = users.jane()
+ Follower.follow(john, jane)
+ add_fixtures(db_session, john, jane)
+
+ res = client.get('/users/{id}'.format(id=john.id))
+ assert res.status_code == 200
+ assert res.json['following'] == 1
+
+ res = client.get('/users/{id}'.format(id=jane.id))
+ assert res.status_code == 200
+ assert res.json['followers'] == 1
+ assert 'followed' not in res.json
+
+ res = client.get('/users/{id}'.format(id=jane.id), headers=auth_for(john))
+ assert res.status_code == 200
+ assert res.json['followers'] == 1
+ assert res.json['followed'] == True
+
+
def test_read_missing_user(client):
res = client.get('/users/1000000000000')
assert res.status_code == 404 |
788284da7d586b538fefb3beb751938fc555d923 | ovp_users/models/profile.py | ovp_users/models/profile.py | from django.db import models
from django.utils.translation import ugettext_lazy as _
from ovp_users.helpers import get_settings, import_from_string
gender_choices = (
("male", "Male"),
("female", "Female"),
("unspecified", "Unspecified"),
)
class UserProfile(models.Model):
user = models.OneToOneField("User", blank=True, null=True, related_name="%(app_label)s_%(class)s_profile")
full_name = models.CharField(_("Full name"), max_length=300, null=True, blank=True)
skills = models.ManyToManyField("ovp_core.Skill")
causes = models.ManyToManyField("ovp_core.Cause")
about = models.TextField(_("About me"), null=True, blank=True)
gender = models.CharField(_("Gender"), max_length=10, choices=gender_choices, default='unspecified')
def get_profile_model():
s = get_settings()
class_path = s.get("PROFILE_MODEL", None)
if class_path:
return import_from_string(class_path)
return UserProfile
| from django.db import models
from django.utils.translation import ugettext_lazy as _
from ovp_users.helpers import get_settings, import_from_string
gender_choices = (
("male", "Male"),
("female", "Female"),
("unspecified", "Unspecified"),
)
class UserProfile(models.Model):
user = models.OneToOneField("User", blank=True, null=True, related_name="%(app_label)s_%(class)s_profile")
full_name = models.CharField(_("Full name"), max_length=300, null=True, blank=True)
skills = models.ManyToManyField("ovp_core.Skill")
causes = models.ManyToManyField("ovp_core.Cause")
about = models.TextField(_("About me"), null=True, blank=True)
gender = models.CharField(_("Gender"), max_length=20, choices=gender_choices, default='unspecified')
def get_profile_model():
s = get_settings()
class_path = s.get("PROFILE_MODEL", None)
if class_path:
return import_from_string(class_path)
return UserProfile
| Set Profile.gender maxlength to 20 | Set Profile.gender maxlength to 20
| Python | agpl-3.0 | OpenVolunteeringPlatform/django-ovp-users,OpenVolunteeringPlatform/django-ovp-users | ---
+++
@@ -15,7 +15,7 @@
skills = models.ManyToManyField("ovp_core.Skill")
causes = models.ManyToManyField("ovp_core.Cause")
about = models.TextField(_("About me"), null=True, blank=True)
- gender = models.CharField(_("Gender"), max_length=10, choices=gender_choices, default='unspecified')
+ gender = models.CharField(_("Gender"), max_length=20, choices=gender_choices, default='unspecified')
def get_profile_model():
s = get_settings() |
da3c17d9142161c9dd9136e604fb9d0f82355044 | tests/tools_tests.py | tests/tools_tests.py | """Tests for ifcfg.tools."""
import logging
import os
import unittest
import ifcfg
from ifcfg.tools import exec_cmd
from nose.tools import eq_
class IfcfgToolsTestCase(unittest.TestCase):
def test_minimal_logger(self):
os.environ['IFCFG_DEBUG'] = '1'
log = ifcfg.tools.minimal_logger(__name__)
eq_(log.level, logging.DEBUG)
os.environ['IFCFG_DEBUG'] = '0'
def test_command(self):
output, __, __ = exec_cmd("echo -n 'this is a test'")
self.assertEqual(output, "this is a test")
| """Tests for ifcfg.tools."""
import locale
import logging
import os
import sys
import unittest
import ifcfg
from ifcfg.tools import exec_cmd
from nose.tools import eq_
class IfcfgToolsTestCase(unittest.TestCase):
def test_minimal_logger(self):
os.environ['IFCFG_DEBUG'] = '1'
log = ifcfg.tools.minimal_logger(__name__)
eq_(log.level, logging.DEBUG)
os.environ['IFCFG_DEBUG'] = '0'
def test_command(self):
output, __, __ = exec_cmd("echo -n 'this is a test'")
self.assertEqual(output, "this is a test")
@unittest.skipIf(sys.version[0] != '2',
"Python 2 only supports non-unicode stuff")
def test_command_non_unicode(self):
getpreferredencoding_orig = locale.getpreferredencoding
locale.getpreferredencoding = lambda: "ISO-8859-1"
output, __, __ = exec_cmd("echo -n 'this is a test'")
self.assertEqual(output, "this is a test")
locale.getpreferredencoding = getpreferredencoding_orig
| Add a Python2 test for non-unicode commands | Add a Python2 test for non-unicode commands
| Python | bsd-3-clause | ftao/python-ifcfg | ---
+++
@@ -1,7 +1,9 @@
"""Tests for ifcfg.tools."""
+import locale
import logging
import os
+import sys
import unittest
import ifcfg
@@ -20,3 +22,13 @@
def test_command(self):
output, __, __ = exec_cmd("echo -n 'this is a test'")
self.assertEqual(output, "this is a test")
+
+
+ @unittest.skipIf(sys.version[0] != '2',
+ "Python 2 only supports non-unicode stuff")
+ def test_command_non_unicode(self):
+ getpreferredencoding_orig = locale.getpreferredencoding
+ locale.getpreferredencoding = lambda: "ISO-8859-1"
+ output, __, __ = exec_cmd("echo -n 'this is a test'")
+ self.assertEqual(output, "this is a test")
+ locale.getpreferredencoding = getpreferredencoding_orig |
dfa94ee2f7712ed66157ff0024989025831bf6ac | calaccess_website/urls.py | calaccess_website/urls.py | from django.conf.urls import url
from calaccess_website import views
urlpatterns = [
# The homepage
url(
r'^$',
views.VersionArchiveIndex.as_view(),
name="version_index",
),
# Version archive views
url(
r'^versions/archive/(?P<year>[0-9]{4})/$',
views.VersionYearArchiveList.as_view(),
name="version_year_archive"
),
url(
r'^versions/(?P<pk>[0-9]{1,})/$',
views.VersionDetail.as_view(),
name="version_detail"
),
url(
r'^versions/latest/$',
views.LatestVersion.as_view(),
name='version_latest_redirect'
),
# Raw data file archive views
url(
r'^raw-data-files/$',
views.RawDataFileList.as_view(),
name='rawdatafiles_list'
),
url(
r'^raw-data-files/(?P<file_name>\w+)/$',
views.RawDataFileDetail.as_view(),
name='rawdatafile_detail',
),
]
| from django.conf.urls import url
from calaccess_website import views
urlpatterns = [
# The homepage
url(
r'^$',
views.VersionArchiveIndex.as_view(),
name="version_index",
),
# Version archive views
url(
r'^archive/(?P<year>[0-9]{4})/$',
views.VersionYearArchiveList.as_view(),
name="version_year_archive"
),
url(
r'^versions/(?P<pk>[0-9]{1,})/$',
views.VersionDetail.as_view(),
name="version_detail"
),
url(
r'^versions/latest/$',
views.LatestVersion.as_view(),
name='version_latest_redirect'
),
# Raw data file archive views
url(
r'^raw-data-files/$',
views.RawDataFileList.as_view(),
name='rawdatafiles_list'
),
url(
r'^raw-data-files/(?P<file_name>\w+)/$',
views.RawDataFileDetail.as_view(),
name='rawdatafile_detail',
),
]
| Remove 'versions/' from archive url path | Remove 'versions/' from archive url path
| Python | mit | california-civic-data-coalition/django-calaccess-downloads-website,california-civic-data-coalition/django-calaccess-downloads-website,california-civic-data-coalition/django-calaccess-downloads-website | ---
+++
@@ -12,7 +12,7 @@
# Version archive views
url(
- r'^versions/archive/(?P<year>[0-9]{4})/$',
+ r'^archive/(?P<year>[0-9]{4})/$',
views.VersionYearArchiveList.as_view(),
name="version_year_archive"
), |
4b488c8d0842bb25c719fcd93ee0ae46978b5680 | meta/util.py | meta/util.py | import os
import sys
import time
import math
from contextlib import contextmanager
@contextmanager
def timeit_msg(msg):
print '{}...'.format(msg),
sys.stdout.flush()
start = time.time()
yield
stop = time.time()
print ' ({:1.3f} s)'.format((stop-start))
def get_file_size(fname):
fstats = os.stat(fname)
size = fstats.st_size
exponent = int(math.log(size, 10))
divisor = {'B': 0, 'kB': 3, 'MB': 6, 'GB': 9}
if exponent < 3:
res = 'B'
if exponent >= 3 and exponent < 6:
res = 'kB'
elif exponent >= 6 and exponent < 9:
res = 'MB'
else:
res = 'GB'
return '{:1.2f} {}'.format(float(size) / 10**divisor[res], res)
| import os
import sys
import time
import math
import sqlite3
from contextlib import contextmanager
import meta
@contextmanager
def timeit_msg(msg):
print '{}...'.format(msg),
sys.stdout.flush()
start = time.time()
yield
stop = time.time()
print ' ({:1.3f} s)'.format((stop-start))
def get_file_size(fname):
fstats = os.stat(fname)
size = fstats.st_size
exponent = int(math.log(size, 10))
divisor = {'B': 0, 'kB': 3, 'MB': 6, 'GB': 9}
if exponent < 3:
res = 'B'
if exponent >= 3 and exponent < 6:
res = 'kB'
elif exponent >= 6 and exponent < 9:
res = 'MB'
else:
res = 'GB'
return '{:1.2f} {}'.format(float(size) / 10**divisor[res], res)
def get_ncbi_db_conn():
dbfile = os.path.join(meta.__path__[0], 'data', 'NCBI.db')
conn = sqlite3.connect(dbfile)
conn.text_factory = str
return conn
| Add support for connecting to NCBI database | Add support for connecting to NCBI database
| Python | mit | abulovic/pgnd-meta | ---
+++
@@ -2,7 +2,10 @@
import sys
import time
import math
+import sqlite3
from contextlib import contextmanager
+
+import meta
@contextmanager
def timeit_msg(msg):
@@ -30,4 +33,10 @@
res = 'GB'
return '{:1.2f} {}'.format(float(size) / 10**divisor[res], res)
+def get_ncbi_db_conn():
+ dbfile = os.path.join(meta.__path__[0], 'data', 'NCBI.db')
+ conn = sqlite3.connect(dbfile)
+ conn.text_factory = str
+ return conn
+ |
dac3cedaee583db4cc3c05a9cb2c4f15a707123e | pylib/mapit/middleware.py | pylib/mapit/middleware.py | import re
class JSONPMiddleware(object):
def process_response(self, request, response):
if request.GET.get('callback') and re.match('[a-zA-Z0-9_]+$', request.GET.get('callback')):
response.content = request.GET.get('callback') + '(' + response.content + ')'
return response
| import re
class JSONPMiddleware(object):
def process_response(self, request, response):
if request.GET.get('callback') and re.match('[a-zA-Z0-9_]+$', request.GET.get('callback')):
response.content = request.GET.get('callback') + '(' + response.content + ')'
response.status_code = 200 # Must return OK for JSONP to be processed
return response
| Set up JSONP requests to always return 200. | Set up JSONP requests to always return 200.
| Python | agpl-3.0 | Sinar/mapit,Code4SA/mapit,New-Bamboo/mapit,opencorato/mapit,Sinar/mapit,opencorato/mapit,opencorato/mapit,chris48s/mapit,chris48s/mapit,Code4SA/mapit,chris48s/mapit,New-Bamboo/mapit,Code4SA/mapit | ---
+++
@@ -4,5 +4,6 @@
def process_response(self, request, response):
if request.GET.get('callback') and re.match('[a-zA-Z0-9_]+$', request.GET.get('callback')):
response.content = request.GET.get('callback') + '(' + response.content + ')'
+ response.status_code = 200 # Must return OK for JSONP to be processed
return response
|
c80893c5789998b6d6068703bb2434919abc65a3 | sqjobs/tests/django_test.py | sqjobs/tests/django_test.py | #!/usr/bin/env python
import os
import sys
from django.conf import settings
import django
DEFAULT_SETTINGS = {
'INSTALLED_APPS': (
'sqjobs',
'sqjobs.tests',
'sqjobs.contrib.django.djsqjobs'
),
'DATABASES': {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
},
'USE_TZ': 'true',
'SILENCED_SYSTEM_CHECKS': ["1_7.W001"],
}
if not settings.configured:
settings.configure(**DEFAULT_SETTINGS)
if hasattr(django, 'setup'):
django.setup()
parent = os.path.dirname(os.path.dirname(os.path.dirname(
os.path.abspath(__file__)
)))
sys.path.insert(0, parent)
from django.test.runner import DiscoverRunner
DiscoverRunner(failfast=False).run_tests([
'sqjobs.tests'
], verbosity=1)
| #!/usr/bin/env python
import os
import sys
from django.conf import settings
import django
DEFAULT_SETTINGS = {
'INSTALLED_APPS': (
'sqjobs',
'sqjobs.tests',
'sqjobs.contrib.django.djsqjobs'
),
'DATABASES': {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
},
'USE_TZ': 'true',
'SILENCED_SYSTEM_CHECKS': ["1_7.W001"],
}
if not settings.configured:
settings.configure(**DEFAULT_SETTINGS)
if hasattr(django, 'setup'):
django.setup()
parent = os.path.dirname(os.path.dirname(os.path.dirname(
os.path.abspath(__file__)
)))
sys.path.insert(0, parent)
from django.test.runner import DiscoverRunner
res = DiscoverRunner(failfast=False).run_tests([
'sqjobs.tests'
], verbosity=1)
os._exit(res)
| Return status when executing tests with DiscoverRunner | Return status when executing tests with DiscoverRunner
| Python | bsd-3-clause | gnufede/sqjobs,gnufede/sqjobs | ---
+++
@@ -36,6 +36,8 @@
from django.test.runner import DiscoverRunner
-DiscoverRunner(failfast=False).run_tests([
+res = DiscoverRunner(failfast=False).run_tests([
'sqjobs.tests'
], verbosity=1)
+
+os._exit(res) |
2548a0c5e108fa22867c6a0e4f5b06ceba52dac0 | bottery/message.py | bottery/message.py | import os
from datetime import datetime
import attr
from jinja2 import Environment, FileSystemLoader, select_autoescape
@attr.s
class Message:
id = attr.ib()
platform = attr.ib()
user = attr.ib()
chat = attr.ib()
text = attr.ib()
timestamp = attr.ib()
raw = attr.ib()
@property
def datetime(self):
return datetime.utcfromtimestamp(self.timestamp)
def render(message, template_name, context={}):
base_dir = os.path.join(os.getcwd(), 'templates')
paths = [base_dir]
# Include paths on settings
# paths.extend(settings.TEMPLATES)
env = Environment(
loader=FileSystemLoader(paths),
autoescape=select_autoescape(['html']))
template = env.get_template(template_name)
default_context = {
'user': message.user,
'platform': message.platform,
}
default_context.update(context)
return template.render(**default_context)
| import os
from datetime import datetime
import attr
from jinja2 import Environment, FileSystemLoader, select_autoescape
from bottery.conf import settings
@attr.s
class Message:
id = attr.ib()
platform = attr.ib()
user = attr.ib()
chat = attr.ib()
text = attr.ib()
timestamp = attr.ib()
raw = attr.ib()
@property
def datetime(self):
return datetime.utcfromtimestamp(self.timestamp)
def render(message, template_name, context=None):
context = context or {}
base_dir = os.path.join(os.getcwd(), 'templates')
paths = [base_dir]
paths.extend(settings.TEMPLATES)
env = Environment(
loader=FileSystemLoader(paths),
autoescape=select_autoescape(['html']))
template = env.get_template(template_name)
default_context = {
'user': message.user,
'platform': message.platform,
}
default_context.update(context)
return template.render(**default_context)
| Extend templates dirs on settings.py | Extend templates dirs on settings.py
| Python | mit | rougeth/bottery | ---
+++
@@ -3,6 +3,8 @@
import attr
from jinja2 import Environment, FileSystemLoader, select_autoescape
+
+from bottery.conf import settings
@attr.s
@@ -20,11 +22,11 @@
return datetime.utcfromtimestamp(self.timestamp)
-def render(message, template_name, context={}):
+def render(message, template_name, context=None):
+ context = context or {}
base_dir = os.path.join(os.getcwd(), 'templates')
paths = [base_dir]
- # Include paths on settings
- # paths.extend(settings.TEMPLATES)
+ paths.extend(settings.TEMPLATES)
env = Environment(
loader=FileSystemLoader(paths), |
0d73f5d18a927ffebc3fa32180b608f0c96dcdf1 | Exe_04.py | Exe_04.py | cars = 100
space_in_a_car = 4.0
drivers = 30
passengers = 90
cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
average_passengers_per_car = passengers / cars_driven
print("There are", cars, "cars available.")
print("There are only", drivers, "drivers available.")
print("There will be", cars_not_driven, "empty cars today.")
print("We can transport", carpool_capacity, "people today.")
print("We have", passengers, "to carpool today.")
print("We need to put about", average_passengers_per_car, "in each car.") | cars = 100
space_in_a_car = 4.0
drivers = 30
passengers = 90
cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
average_passengers_per_car = passengers / cars_driven
print("There are", cars, "cars available.")
print("There are only", drivers, "drivers available.")
print("There will be", cars_not_driven, "empty cars today.")
print("We can transport", carpool_capacity, "people today.")
print("We have", passengers, "to carpool today.")
print("We need to put about", average_passengers_per_car, "in each car.")
# Upgrade part
my_name = 'Binh D. Nguyen'
my_age = 22
my_height = 74 # inches
my_weight = 180 # lbs
my_eyes = 'Black'
my_teeth = 'White'
my_hair = 'Black'
#print "Let's talk about %s." % my_name
print(f"Let's talk about {my_name:}.")
#print "He's %d inches tall." % my_height
print("He's {:d} inches tall.".format(my_height))
#print "He's %d pounds heavy." % my_weight
#print "Actually that's not too heavy."
#print "He's got %s eyes and %s hair." % (my_eyes, my_hair)
print(f"He's got { my_eyes:} eyes and {my_hair:} hair.")
#print "His teeth are usually %s depending on the coffee." % my_teeth
# this line is tricky, try to get it exactly right
#print "If I add %d, %d, and %d I get %d." % (
# my_age, my_height, my_weight, my_age + my_height + my_weight)
print(f"If I add {my_age}, {my_height}, and {my_weight} I get {my_age + my_height + my_weight}.")
| Update exercise of variables and names | Update exercise of variables and names
| Python | mit | Oreder/PythonSelfStudy | ---
+++
@@ -14,3 +14,27 @@
print("We can transport", carpool_capacity, "people today.")
print("We have", passengers, "to carpool today.")
print("We need to put about", average_passengers_per_car, "in each car.")
+
+# Upgrade part
+my_name = 'Binh D. Nguyen'
+my_age = 22
+my_height = 74 # inches
+my_weight = 180 # lbs
+my_eyes = 'Black'
+my_teeth = 'White'
+my_hair = 'Black'
+
+#print "Let's talk about %s." % my_name
+print(f"Let's talk about {my_name:}.")
+#print "He's %d inches tall." % my_height
+print("He's {:d} inches tall.".format(my_height))
+#print "He's %d pounds heavy." % my_weight
+#print "Actually that's not too heavy."
+#print "He's got %s eyes and %s hair." % (my_eyes, my_hair)
+print(f"He's got { my_eyes:} eyes and {my_hair:} hair.")
+#print "His teeth are usually %s depending on the coffee." % my_teeth
+
+# this line is tricky, try to get it exactly right
+#print "If I add %d, %d, and %d I get %d." % (
+# my_age, my_height, my_weight, my_age + my_height + my_weight)
+print(f"If I add {my_age}, {my_height}, and {my_weight} I get {my_age + my_height + my_weight}.") |
cc51207881be9c76690bcbc1ce14d048ecc71d76 | commweb/cartridge_hook.py | commweb/cartridge_hook.py | from cartridge.shop.checkout import CheckoutError
from cartridge.shop.models import Cart
from commweb.exc import PaymentDeclinedError
from commweb.purchase import Purchase
def cartridge_payment_handler(request, order_form, order):
cart = Cart.objects.from_request(request)
trans_id = 'WFS_%d' % order.id
p = Purchase(cart.total_price(), trans_id,
order_form.cleaned_data['card_number'],
order_form.cleaned_data['card_expiry_year'][2:4],
order_form.cleaned_data['card_expiry_month'],
order_form.cleaned_data['card_ccv'])
try:
p.process()
return trans_id
except PaymentDeclinedError, e:
raise CheckoutError('Payment declined: %s' % str(e))
| from cartridge.shop.checkout import CheckoutError
from commweb.exc import PaymentDeclinedError
from commweb.purchase import Purchase
def cartridge_payment_handler(request, order_form, order):
trans_id = 'WFS_%d' % order.id
p = Purchase(order.total, trans_id,
order_form.cleaned_data['card_number'],
order_form.cleaned_data['card_expiry_year'][2:4],
order_form.cleaned_data['card_expiry_month'],
order_form.cleaned_data['card_ccv'])
try:
p.process()
return trans_id
except PaymentDeclinedError, e:
raise CheckoutError('Payment declined: %s' % str(e))
| Fix bug where shipping wasn't included in payment amount with cartridge handler | Fix bug where shipping wasn't included in payment amount with cartridge handler
| Python | bsd-2-clause | sjkingo/django-commweb | ---
+++
@@ -1,14 +1,12 @@
from cartridge.shop.checkout import CheckoutError
-from cartridge.shop.models import Cart
from commweb.exc import PaymentDeclinedError
from commweb.purchase import Purchase
def cartridge_payment_handler(request, order_form, order):
- cart = Cart.objects.from_request(request)
trans_id = 'WFS_%d' % order.id
- p = Purchase(cart.total_price(), trans_id,
+ p = Purchase(order.total, trans_id,
order_form.cleaned_data['card_number'],
order_form.cleaned_data['card_expiry_year'][2:4],
order_form.cleaned_data['card_expiry_month'], |
09371cf8f27c49dec97b05e26ede4709fb01aa81 | examples/filter/simple_example.py | examples/filter/simple_example.py | import pyrox.filtering as filtering
class SimpleFilter(filtering.HttpFilter):
"""
This is an example of a simple filter that simply prints out the
user-agent value from the header
"""
@filtering.handles_request_head
def on_request_head(self, request_message):
user_agent_header = request_message.get_header('user-agent')
if user_agent_header and len(user_agent_header.values) > 0:
# If there is a user-agent value then print it out and pass
# the request upstream
print(user_agent_header.values[0])
return filtering.pass_event()
else:
# If there is no user-agent, then reject the request
return filtering.reject()
| import pyrox.filtering as filtering
class SimpleFilter(filtering.HttpFilter):
"""
This is an example of a simple filter that simply prints out the
user-agent value from the header
"""
@filtering.handles_request_head
def on_request_head(self, request_message):
user_agent_header = request_message.get_header('user-agent')
if user_agent_header and len(user_agent_header.values) > 0:
# If there is a user-agent value then print it out and pass
# the request upstream
print(user_agent_header.values[0])
return filtering.next()
else:
# If there is no user-agent, then reject the request
return filtering.reject()
| Remove pass_event (deprecated) and replace with next | Remove pass_event (deprecated) and replace with next | Python | mit | zinic/pyrox,jon-armstrong/pyrox,jon-armstrong/pyrox,akatrevorjay/pyrox,zinic/pyrox,jon-armstrong/pyrox,zinic/pyrox,akatrevorjay/pyrox,akatrevorjay/pyrox | ---
+++
@@ -14,7 +14,7 @@
# If there is a user-agent value then print it out and pass
# the request upstream
print(user_agent_header.values[0])
- return filtering.pass_event()
+ return filtering.next()
else:
# If there is no user-agent, then reject the request
return filtering.reject() |
83cbec4ccf669c997bbe6c7131f63ad08a482c39 | examples/mnist-deepautoencoder.py | examples/mnist-deepautoencoder.py | #!/usr/bin/env python
import matplotlib.pyplot as plt
import theanets
from utils import load_mnist, plot_layers, plot_images
train, valid, _ = load_mnist()
e = theanets.Experiment(
theanets.Autoencoder,
layers=(784, 256, 64, 36, 64, 256, 784),
train_batches=100,
tied_weights=True,
)
e.train(train, valid, optimize='layerwise', patience=1, min_improvement=0.1)
e.train(train, valid)
plot_layers([e.network.find(i, 0) for i in (1, 2, 3)], tied_weights=True)
plt.tight_layout()
plt.show()
valid = valid[:16*16]
plot_images(valid, 121, 'Sample data')
plot_images(e.network.predict(valid), 122, 'Reconstructed data')
plt.tight_layout()
plt.show()
| #!/usr/bin/env python
import matplotlib.pyplot as plt
import theanets
from utils import load_mnist, plot_layers, plot_images
train, valid, _ = load_mnist()
e = theanets.Experiment(
theanets.Autoencoder,
layers=(784, 256, 64, 36, ('tied', 64), ('tied', 256), ('tied', 784)),
train_batches=100,
)
e.train(train, valid, optimize='layerwise', patience=1, min_improvement=0.1)
e.train(train, valid)
plot_layers([e.network.find(i, 'w') for i in (1, 2, 3)], tied_weights=True)
plt.tight_layout()
plt.show()
valid = valid[:16*16]
plot_images(valid, 121, 'Sample data')
plot_images(e.network.predict(valid), 122, 'Reconstructed data')
plt.tight_layout()
plt.show()
| Update example with newer tied layer specification. | Update example with newer tied layer specification.
| Python | mit | lmjohns3/theanets,chrinide/theanets,devdoer/theanets | ---
+++
@@ -10,14 +10,13 @@
e = theanets.Experiment(
theanets.Autoencoder,
- layers=(784, 256, 64, 36, 64, 256, 784),
+ layers=(784, 256, 64, 36, ('tied', 64), ('tied', 256), ('tied', 784)),
train_batches=100,
- tied_weights=True,
)
e.train(train, valid, optimize='layerwise', patience=1, min_improvement=0.1)
e.train(train, valid)
-plot_layers([e.network.find(i, 0) for i in (1, 2, 3)], tied_weights=True)
+plot_layers([e.network.find(i, 'w') for i in (1, 2, 3)], tied_weights=True)
plt.tight_layout()
plt.show()
|
f10ac5cb7e01feeaaab5b8d308cb0640afaa895c | tests/test_encoding.py | tests/test_encoding.py | # -*- encoding: utf-8 -*-
import pytest
from owslib.fes import PropertyIsEqualTo
from pydov.search.boring import BoringSearch
from tests.abstract import (
AbstractTestSearch,
service_ok,
)
class TestEncoding(AbstractTestSearch):
"""Class grouping tests related to encoding issues."""
@pytest.mark.online
@pytest.mark.skipif(not service_ok(), reason="DOV service is unreachable")
def test_search(self):
"""Test the search method with strange character in the output.
Test whether the output has the correct encoding.
"""
boringsearch = BoringSearch()
query = PropertyIsEqualTo(
propertyname='pkey_boring',
literal='https://www.dov.vlaanderen.be/data/boring/1928-031159')
df = boringsearch.search(query=query,
return_fields=('pkey_boring', 'uitvoerder'))
assert df.uitvoerder[0] == 'Societé Belge des Bétons'
| # -*- encoding: utf-8 -*-
import pytest
from owslib.fes import PropertyIsEqualTo
from pydov.search.boring import BoringSearch
from tests.abstract import (
AbstractTestSearch,
service_ok,
)
class TestEncoding(AbstractTestSearch):
"""Class grouping tests related to encoding issues."""
@pytest.mark.online
@pytest.mark.skipif(not service_ok(), reason="DOV service is unreachable")
def test_search(self):
"""Test the search method with strange character in the output.
Test whether the output has the correct encoding.
"""
boringsearch = BoringSearch()
query = PropertyIsEqualTo(
propertyname='pkey_boring',
literal='https://www.dov.vlaanderen.be/data/boring/1928-031159')
df = boringsearch.search(query=query,
return_fields=('pkey_boring', 'uitvoerder'))
assert df.uitvoerder[0] == u'Societé Belge des Bétons'
| Fix encoding test: compare with unicode string. | Fix encoding test: compare with unicode string.
| Python | mit | DOV-Vlaanderen/pydov | ---
+++
@@ -29,4 +29,4 @@
df = boringsearch.search(query=query,
return_fields=('pkey_boring', 'uitvoerder'))
- assert df.uitvoerder[0] == 'Societé Belge des Bétons'
+ assert df.uitvoerder[0] == u'Societé Belge des Bétons' |
5c2b5b4ad973717ab35c75ff8d5d63d87c15cf79 | twphotos/settings.py | twphotos/settings.py | import ConfigParser
import os
import sys
USER_DIR = os.path.join(os.path.expanduser('~'))
USER_CONFIG = os.path.join(USER_DIR, '.twphotos')
d = os.path.dirname(__file__)
PROJECT_PATH = os.path.abspath(os.path.join(d, os.pardir))
TEST_CONFIG = os.path.join(PROJECT_PATH, '.twphotos')
sys.path.append(os.path.join(PROJECT_PATH, 'python-twitter'))
config = ConfigParser.ConfigParser()
if os.environ.get('TWPHOTOS_TEST_CONFIG'):
config.read(TEST_CONFIG)
else:
config.read(USER_CONFIG)
items = {}
item_names = [
'consumer_key',
'consumer_secret',
'access_token_key',
'access_token_secret',
]
if config.has_section('twphotos'):
items = dict(config.items('twphotos'))
for name in items:
if name not in item_names:
raise Exception('Unknown name "%s" in credential file.' % name)
if len(items) < 4:
raise Exception('No credentials found.')
CONSUMER_KEY = items.get('consumer_key')
CONSUMER_SECRET = items.get('consumer_secret')
ACCESS_TOKEN = items.get('access_token_key')
ACCESS_TOKEN_SECRET = items.get('access_token_secret')
COUNT_PER_GET = 200
MEDIA_SIZES = ['large', 'medium', 'small', 'thumb']
| import ConfigParser
import os
import sys
USER_DIR = os.path.join(os.path.expanduser('~'))
USER_CONFIG = os.path.join(USER_DIR, '.twphotos')
d = os.path.dirname(__file__)
PROJECT_PATH = os.path.abspath(os.path.join(d, os.pardir))
TEST_CONFIG = os.path.join(PROJECT_PATH, '.twphotos')
sys.path.insert(1, os.path.join(PROJECT_PATH, 'python-twitter'))
config = ConfigParser.ConfigParser()
if os.environ.get('TWPHOTOS_TEST_CONFIG'):
config.read(TEST_CONFIG)
else:
config.read(USER_CONFIG)
items = {}
item_names = [
'consumer_key',
'consumer_secret',
'access_token_key',
'access_token_secret',
]
if config.has_section('twphotos'):
items = dict(config.items('twphotos'))
for name in items:
if name not in item_names:
raise Exception('Unknown name "%s" in credential file.' % name)
if len(items) < 4:
raise Exception('No credentials found.')
CONSUMER_KEY = items.get('consumer_key')
CONSUMER_SECRET = items.get('consumer_secret')
ACCESS_TOKEN = items.get('access_token_key')
ACCESS_TOKEN_SECRET = items.get('access_token_secret')
COUNT_PER_GET = 200
MEDIA_SIZES = ['large', 'medium', 'small', 'thumb']
| Add sys.path for python-twitter for local development | Add sys.path for python-twitter for local development
| Python | bsd-2-clause | shichao-an/twitter-photos | ---
+++
@@ -7,7 +7,7 @@
d = os.path.dirname(__file__)
PROJECT_PATH = os.path.abspath(os.path.join(d, os.pardir))
TEST_CONFIG = os.path.join(PROJECT_PATH, '.twphotos')
-sys.path.append(os.path.join(PROJECT_PATH, 'python-twitter'))
+sys.path.insert(1, os.path.join(PROJECT_PATH, 'python-twitter'))
config = ConfigParser.ConfigParser()
if os.environ.get('TWPHOTOS_TEST_CONFIG'):
config.read(TEST_CONFIG) |
79fd5586625d2d7873bc71514eda121325a9646a | linkedin_scraper/commands/people_search.py | linkedin_scraper/commands/people_search.py | from getpass import getpass
from scrapy.commands.crawl import Command as BaseCommand
def sanitize_query(query):
return query.replace(' ', '+')
class Command(BaseCommand):
def short_desc(self):
return "Scrap people from LinkedIn"
def syntax(self):
return "[options] <query>"
def add_options(self, parser):
super().add_options(parser)
parser.add_option('-u', '--username', help='Name of LinkedIn account')
parser.add_option('-p', '--password',
help='Password for LinkedIn account')
def process_options(self, args, opts):
opts.output = opts.output or 'results.csv'
opts.loglevel = opts.loglevel or 'INFO'
super().process_options(args, opts)
people_search_options = {
'query': sanitize_query(args[0]),
'username': opts.username or input(
'Please provide your LinkedIn username: '),
'password': opts.password or getpass(
'Please provide password for your LinkedIn account: ')
}
opts.spargs.update(people_search_options)
def run(self, args, opts):
# Run people_search spider
args = ['people_search']
super().run(args, opts)
| from getpass import getpass
from scrapy.commands.crawl import Command as BaseCommand
from scrapy.exceptions import UsageError
def sanitize_query(query):
return query.replace(' ', '+')
class Command(BaseCommand):
def short_desc(self):
return "Scrap people from LinkedIn"
def syntax(self):
return "[options] <query>"
def add_options(self, parser):
super().add_options(parser)
parser.add_option('-u', '--username', help='Name of LinkedIn account')
parser.add_option('-p', '--password',
help='Password for LinkedIn account')
def process_options(self, args, opts):
opts.output = opts.output or 'results.csv'
opts.loglevel = opts.loglevel or 'INFO'
super().process_options(args, opts)
try:
query = sanitize_query(args[0])
except IndexError:
raise UsageError()
people_search_options = {
'query': query,
'username': opts.username or input(
'Please provide your LinkedIn username: '),
'password': opts.password or getpass(
'Please provide password for your LinkedIn account: ')
}
opts.spargs.update(people_search_options)
def run(self, args, opts):
# Run people_search spider
args = ['people_search']
super().run(args, opts)
| Fix IndexError when running command without arguments. | Fix IndexError when running command without arguments.
| Python | mit | nihn/linkedin-scraper,nihn/linkedin-scraper | ---
+++
@@ -1,6 +1,7 @@
from getpass import getpass
from scrapy.commands.crawl import Command as BaseCommand
+from scrapy.exceptions import UsageError
def sanitize_query(query):
@@ -27,8 +28,13 @@
super().process_options(args, opts)
+ try:
+ query = sanitize_query(args[0])
+ except IndexError:
+ raise UsageError()
+
people_search_options = {
- 'query': sanitize_query(args[0]),
+ 'query': query,
'username': opts.username or input(
'Please provide your LinkedIn username: '),
'password': opts.password or getpass( |
f9abd5434dded655591029ae45859e8608b4e5d6 | django_facebook/decorators.py | django_facebook/decorators.py | from functools import update_wrapper, wraps
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.http import HttpResponse, HttpResponseRedirect
from django.utils.decorators import available_attrs
from django.utils.http import urlquote
def facebook_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME):
"""
Decorator for views that checks that the user is logged in, redirecting
to the log-in page if necessary.
"""
def _passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
if not login_url:
from django.conf import settings
login_url = settings.LOGIN_URL
def decorator(view_func):
def _wrapped_view(request, *args, **kwargs):
if test_func(request):
return view_func(request, *args, **kwargs)
path = urlquote(request.get_full_path())
tup = login_url, redirect_field_name, path
return HttpResponseRedirect('%s?%s=%s' % tup)
return wraps(view_func, assigned=available_attrs(view_func))(_wrapped_view)
return decorator
actual_decorator = _passes_test(
lambda r: r.facebook.uid,
redirect_field_name=redirect_field_name
)
if function:
return actual_decorator(function)
return actual_decorator
| from functools import update_wrapper, wraps
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.http import HttpResponse, HttpResponseRedirect
from django.utils.decorators import available_attrs
from django.utils.http import urlquote
def facebook_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME):
"""
Decorator for views that checks that the user is logged in, redirecting
to the log-in page if necessary.
"""
def _passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
if not login_url:
from django.conf import settings
login_url = settings.LOGIN_URL
def decorator(view_func):
def _wrapped_view(request, *args, **kwargs):
if test_func(request):
return view_func(request, *args, **kwargs)
path = urlquote(request.get_full_path())
tup = login_url, redirect_field_name, path
return HttpResponseRedirect('%s?%s=%s' % tup)
return wraps(view_func, assigned=available_attrs(view_func))(_wrapped_view)
return decorator
actual_decorator = _passes_test(
lambda r: r.facebook,
redirect_field_name=redirect_field_name
)
if function:
return actual_decorator(function)
return actual_decorator
| Fix possible problem with middleware | Fix possible problem with middleware
| Python | mit | tino/django-facebook2,srijanmishra/django-facebook,aidanlister/django-facebook,tino/django-facebook2,vstoykov/django4facebook | ---
+++
@@ -25,7 +25,7 @@
return decorator
actual_decorator = _passes_test(
- lambda r: r.facebook.uid,
+ lambda r: r.facebook,
redirect_field_name=redirect_field_name
)
|
5dc4a262771e616458feeaa9bf4ca8568736761a | docs/contributors/generate.py | docs/contributors/generate.py | """
Generate snippets to copy-paste.
"""
import sys
from jinja2 import Template
from fetch import HERE, load_awesome_people
TPL_FILE = HERE / 'snippet.jinja2'
HTTPIE_TEAM = {
'BoboTiG',
'claudiatd',
'jakubroztocil',
'jkbr',
}
def generate_snippets(release: str) -> str:
people = load_awesome_people()
contributors = {
name: details
for name, details in people.items()
if details['github'] not in HTTPIE_TEAM
and (release in details['committed'] or release in details['reported'])
}
template = Template(source=TPL_FILE.read_text(encoding='utf-8'))
output = template.render(contributors=contributors, release=release)
print(output)
return 0
if __name__ == '__main__':
ret = 1
try:
ret = generate_snippets(sys.argv[1])
except (IndexError, TypeError):
ret = 2
print(f'''
Generate snippets for contributors to a release.
Usage:
python {sys.argv[0]} {sys.argv[0]} <RELEASE>
''')
sys.exit(ret)
| """
Generate snippets to copy-paste.
"""
import sys
from jinja2 import Template
from fetch import HERE, load_awesome_people
TPL_FILE = HERE / 'snippet.jinja2'
HTTPIE_TEAM = {
'claudiatd',
'jakubroztocil',
'jkbr',
}
def generate_snippets(release: str) -> str:
people = load_awesome_people()
contributors = {
name: details
for name, details in people.items()
if details['github'] not in HTTPIE_TEAM
and (release in details['committed'] or release in details['reported'])
}
template = Template(source=TPL_FILE.read_text(encoding='utf-8'))
output = template.render(contributors=contributors, release=release)
print(output)
return 0
if __name__ == '__main__':
ret = 1
try:
ret = generate_snippets(sys.argv[1])
except (IndexError, TypeError):
ret = 2
print(f'''
Generate snippets for contributors to a release.
Usage:
python {sys.argv[0]} {sys.argv[0]} <RELEASE>
''')
sys.exit(ret)
| Remove myself from the HTTPie team | Remove myself from the HTTPie team | Python | bsd-3-clause | jakubroztocil/httpie,PKRoma/httpie,jakubroztocil/httpie,jakubroztocil/httpie,PKRoma/httpie | ---
+++
@@ -9,7 +9,6 @@
TPL_FILE = HERE / 'snippet.jinja2'
HTTPIE_TEAM = {
- 'BoboTiG',
'claudiatd',
'jakubroztocil',
'jkbr', |
f16d93216e1f0890b0551ca3b741130bb12781ef | gold_digger/settings/__init__.py | gold_digger/settings/__init__.py | # -*- coding: utf-8 -*-
from os import environ, path
from ._settings_default import *
from ..exceptions import ImproperlyConfigured
profile = environ.get("GOLD_DIGGER_PROFILE", "local")
if profile == "master":
from ._settings_master import *
elif profile == "local":
try:
from ._settings_local import *
except ImportError:
raise ImproperlyConfigured(
"Local configuration not found. Create file _settings_local.py in {} directory according to README.".format(
path.abspath(path.join(__file__, path.pardir))
)
)
else:
raise ValueError("Unsupported settings profile. Got: {}. Use one of: master, staging, local.".format(profile))
| # -*- coding: utf-8 -*-
from os import environ, path
from ._settings_default import *
from ..exceptions import ImproperlyConfigured
PROFILE = environ.get("GOLD_DIGGER_PROFILE", "local")
if PROFILE == "master":
from ._settings_master import *
elif PROFILE == "local":
try:
from ._settings_local import *
except ImportError:
raise ImproperlyConfigured(
f"Local configuration not found. Create file _settings_local.py in {path.abspath(path.join(__file__, path.pardir))} directory according to README."
)
else:
raise ValueError(f"Unsupported settings profile. Got: {PROFILE}. Use one of: master, staging, local.")
| Make global variable upper-case and use f-strings | Make global variable upper-case and use f-strings
| Python | apache-2.0 | business-factory/gold-digger | ---
+++
@@ -5,18 +5,16 @@
from ._settings_default import *
from ..exceptions import ImproperlyConfigured
-profile = environ.get("GOLD_DIGGER_PROFILE", "local")
+PROFILE = environ.get("GOLD_DIGGER_PROFILE", "local")
-if profile == "master":
+if PROFILE == "master":
from ._settings_master import *
-elif profile == "local":
+elif PROFILE == "local":
try:
from ._settings_local import *
except ImportError:
raise ImproperlyConfigured(
- "Local configuration not found. Create file _settings_local.py in {} directory according to README.".format(
- path.abspath(path.join(__file__, path.pardir))
- )
+ f"Local configuration not found. Create file _settings_local.py in {path.abspath(path.join(__file__, path.pardir))} directory according to README."
)
else:
- raise ValueError("Unsupported settings profile. Got: {}. Use one of: master, staging, local.".format(profile))
+ raise ValueError(f"Unsupported settings profile. Got: {PROFILE}. Use one of: master, staging, local.") |
763051db8cb4efe9b3e85fdb3d974674cf435607 | us_ignite/snippets/management/commands/snippets_load_fixtures.py | us_ignite/snippets/management/commands/snippets_load_fixtures.py | from django.core.management.base import BaseCommand
from us_ignite.snippets.models import Snippet
FIXTURES = [
{
'slug': 'home-box',
'name': 'UP NEXT: LOREM IPSUM',
'body': '',
'url_text': 'GET INVOLVED',
'url': '',
},
{
'slug': 'featured',
'name': 'FEATURED CONTENT',
'body': '',
'url_text': 'FEATURED',
'url': '',
},
{
'slug': 'welcome-email',
'name': 'Welcome to US Ignite',
'body': '',
'url_text': '',
'url': '',
},
]
class Command(BaseCommand):
def handle(self, *args, **options):
for data in FIXTURES:
try:
# Ignore existing snippets:
Snippet.objects.get(slug=data['slug'])
continue
except Snippet.DoesNotExist:
pass
data.update({
'status': Snippet.PUBLISHED,
})
Snippet.objects.create(**data)
print u'Importing %s' % data['slug']
print "Done!"
| from django.core.management.base import BaseCommand
from us_ignite.snippets.models import Snippet
FIXTURES = [
{
'slug': 'home-box',
'name': 'UP NEXT: LOREM IPSUM',
'body': '',
'url_text': 'GET INVOLVED',
'url': '',
},
{
'slug': 'featured',
'name': 'FEATURED CONTENT',
'body': '',
'url_text': 'FEATURED',
'url': '',
},
{
'slug': 'welcome-email',
'name': 'Welcome to US Ignite',
'body': '',
'url_text': '',
'url': '',
},
{
'slug': 'blog-sidebar',
'name': 'Dynamic content',
'body': '',
'url_text': '',
'url': '',
},
]
class Command(BaseCommand):
def handle(self, *args, **options):
for data in FIXTURES:
try:
# Ignore existing snippets:
Snippet.objects.get(slug=data['slug'])
continue
except Snippet.DoesNotExist:
pass
data.update({
'status': Snippet.PUBLISHED,
})
Snippet.objects.create(**data)
print u'Importing %s' % data['slug']
print "Done!"
| Add fixture for the advert in the blog sidebar advert. | Add fixture for the advert in the blog sidebar advert.
| Python | bsd-3-clause | us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite | ---
+++
@@ -25,6 +25,13 @@
'url_text': '',
'url': '',
},
+ {
+ 'slug': 'blog-sidebar',
+ 'name': 'Dynamic content',
+ 'body': '',
+ 'url_text': '',
+ 'url': '',
+ },
]
|
49a371728a2e9167494264e0c07c6dd90abec0ff | saleor/core/views.py | saleor/core/views.py | from django.template.response import TemplateResponse
from ..product.utils import products_with_availability, products_with_details
def home(request):
products = Product.objects.get_available_products()[:6]
products = products.prefetch_related('categories', 'images',
'variants__stock')
return TemplateResponse(
request, 'home.html',
{'products': products, 'parent': None})
| from django.template.response import TemplateResponse
from ..product.utils import products_with_availability, products_with_details
def home(request):
products = products_with_details(request.user)[:6]
products = products_with_availability(
products, discounts=request.discounts, local_currency=request.currency)
return TemplateResponse(
request, 'home.html',
{'products': products, 'parent': None})
| Fix homepage after wrong rebase | Fix homepage after wrong rebase
| Python | bsd-3-clause | jreigel/saleor,car3oon/saleor,HyperManTT/ECommerceSaleor,tfroehlich82/saleor,HyperManTT/ECommerceSaleor,UITools/saleor,mociepka/saleor,car3oon/saleor,KenMutemi/saleor,jreigel/saleor,UITools/saleor,UITools/saleor,mociepka/saleor,maferelo/saleor,itbabu/saleor,UITools/saleor,KenMutemi/saleor,mociepka/saleor,itbabu/saleor,maferelo/saleor,tfroehlich82/saleor,HyperManTT/ECommerceSaleor,jreigel/saleor,itbabu/saleor,tfroehlich82/saleor,UITools/saleor,KenMutemi/saleor,car3oon/saleor,maferelo/saleor | ---
+++
@@ -4,9 +4,9 @@
def home(request):
- products = Product.objects.get_available_products()[:6]
- products = products.prefetch_related('categories', 'images',
- 'variants__stock')
+ products = products_with_details(request.user)[:6]
+ products = products_with_availability(
+ products, discounts=request.discounts, local_currency=request.currency)
return TemplateResponse(
request, 'home.html',
{'products': products, 'parent': None}) |
ef7163a18ee1cf11c1290f2a8832d8cf39fb552c | fjord/base/tests/test_commands.py | fjord/base/tests/test_commands.py | from django.core.management import call_command
from fjord.base.tests import TestCase
class TestGenerateData(TestCase):
def test_generate_data(self):
"""Make sure ./manage.py generatedata runs."""
call_command('generatedata')
call_command('generatedata', bigsample=True)
class TestPOLint(TestCase):
def test_polint(self):
"""Make sure ./manage.py polint runs."""
# Note: This doesn't make sure it works--just that it doesn't kick
# up obvious errors when it runs like if Dennis has changed in
# some way that prevents it from working correctly.
try:
call_command('polint')
except SystemExit:
# WOAH! WTF ARE YOU DOING? The lint command calls
# sys.exit() because it needs to return correct exit codes
# so we catch that here and ignore it. Otherwise testing
# it will kill the test suite.
pass
| from django.core.management import call_command
from fjord.base.tests import TestCase
class TestGenerateData(TestCase):
def test_generate_data(self):
"""Make sure ./manage.py generatedata runs."""
call_command('generatedata')
call_command('generatedata', bigsample=True)
class TestPOLint(TestCase):
def test_polint(self):
"""Make sure ./manage.py polint runs."""
# Note: This doesn't make sure it works--just that it doesn't kick
# up obvious errors when it runs like if Dennis has changed in
# some way that prevents it from working correctly.
try:
call_command('polint', '--version')
except SystemExit:
# WOAH! WTF ARE YOU DOING? The lint command calls
# sys.exit() because it needs to return correct exit codes
# so we catch that here and ignore it. Otherwise testing
# it will kill the test suite.
pass
| Adjust test_polint to be less stdout-spammy | Adjust test_polint to be less stdout-spammy
| Python | bsd-3-clause | hoosteeno/fjord,lgp171188/fjord,mozilla/fjord,Ritsyy/fjord,lgp171188/fjord,rlr/fjord,staranjeet/fjord,DESHRAJ/fjord,hoosteeno/fjord,Ritsyy/fjord,rlr/fjord,lgp171188/fjord,DESHRAJ/fjord,mozilla/fjord,hoosteeno/fjord,hoosteeno/fjord,rlr/fjord,Ritsyy/fjord,staranjeet/fjord,lgp171188/fjord,mozilla/fjord,Ritsyy/fjord,DESHRAJ/fjord,rlr/fjord,staranjeet/fjord,mozilla/fjord,staranjeet/fjord | ---
+++
@@ -18,7 +18,7 @@
# some way that prevents it from working correctly.
try:
- call_command('polint')
+ call_command('polint', '--version')
except SystemExit:
# WOAH! WTF ARE YOU DOING? The lint command calls
# sys.exit() because it needs to return correct exit codes |
c0c822df243894106a7fd376582598e4aebb4c24 | kobo/hub/decorators.py | kobo/hub/decorators.py | # -*- coding: utf-8 -*-
from django.core.exceptions import PermissionDenied, SuspiciousOperation
from kobo.decorators import decorator_with_args
from kobo.django.xmlrpc.decorators import *
def validate_worker(func):
def _new_func(request, *args, **kwargs):
if not request.user.is_authenticated():
raise PermissionDenied("Login required.")
if getattr(request, 'worker', None) is None:
raise SuspiciousOperation("User doesn't match any worker: %s" % request.user.username)
return func(request, *args, **kwargs)
_new_func.__name__ = func.__name__
_new_func.__doc__ = func.__doc__
_new_func.__dict__.update(func.__dict__)
return _new_func
| # -*- coding: utf-8 -*-
import socket
from django.core.exceptions import PermissionDenied, SuspiciousOperation
from kobo.decorators import decorator_with_args
from kobo.django.xmlrpc.decorators import *
def validate_worker(func):
def _new_func(request, *args, **kwargs):
if not request.user.is_authenticated():
raise PermissionDenied("Login required.")
if getattr(request, 'worker', None) is None:
raise SuspiciousOperation("User doesn't match any worker: %s" % request.user.username)
fqdn = socket.getfqdn(request.META["REMOTE_ADDR"])
prefix, hostname = request.user.username.split("/", 1)
if hostname != fqdn:
raise SuspiciousOperation("Worker's FQDN (%s) doesn't match username (%s)" % (fqdn, hostname))
return func(request, *args, **kwargs)
_new_func.__name__ = func.__name__
_new_func.__doc__ = func.__doc__
_new_func.__dict__.update(func.__dict__)
return _new_func
| Check worker's FQDN against username. | Check worker's FQDN against username.
| Python | lgpl-2.1 | pombredanne/https-git.fedorahosted.org-git-kobo,pombredanne/https-git.fedorahosted.org-git-kobo,pombredanne/https-git.fedorahosted.org-git-kobo,release-engineering/kobo,release-engineering/kobo,release-engineering/kobo,release-engineering/kobo,pombredanne/https-git.fedorahosted.org-git-kobo | ---
+++
@@ -1,5 +1,7 @@
# -*- coding: utf-8 -*-
+
+import socket
from django.core.exceptions import PermissionDenied, SuspiciousOperation
from kobo.decorators import decorator_with_args
@@ -14,6 +16,11 @@
if getattr(request, 'worker', None) is None:
raise SuspiciousOperation("User doesn't match any worker: %s" % request.user.username)
+ fqdn = socket.getfqdn(request.META["REMOTE_ADDR"])
+ prefix, hostname = request.user.username.split("/", 1)
+ if hostname != fqdn:
+ raise SuspiciousOperation("Worker's FQDN (%s) doesn't match username (%s)" % (fqdn, hostname))
+
return func(request, *args, **kwargs)
_new_func.__name__ = func.__name__ |
337e7ae58abc7c192633144cc3913078ae3d38bf | hc2002/plugin/symbolic_values.py | hc2002/plugin/symbolic_values.py | import hc2002.plugin as plugin
import hc2002.config as config
plugin.register_for_resource(__name__, 'hc2002.resource.instance')
_prefixes = ('availability-zone:', 'image:', 'kernel:', 'key:',
'load-balancers:', 'ramdisk:', 'security-groups:', 'spot-price:',
'subnet:')
def apply(instance):
def _resolve_symbol(value):
visited = set()
while isinstance(value, basestring) \
and value.startswith(prefix):
value = value.format(region=config.region, **instance)
if value in instance \
and value not in visited:
visited.add(value)
value = instance[value]
return value
# Resolve symbols
for prefix in _prefixes:
key = prefix[:-1]
if key not in instance:
continue
if isinstance(instance[key], basestring):
instance[key] = _resolve_symbol(instance[key])
elif isinstance(instance[key], list):
instance[key] = map(_resolve_symbol, instance[key])
# Drop resolvable symbols
for key in instance.keys():
if key.startswith(_prefixes):
del instance[key]
| import hc2002.plugin as plugin
import hc2002.config as config
plugin.register_for_resource(__name__, 'hc2002.resource.instance')
_prefixes = ('availability-zone:', 'image:', 'kernel:', 'key:',
'load-balancers:', 'ramdisk:', 'security-groups:', 'spot-price:',
'subnet:')
def apply(instance):
def resolve_symbol(original_value):
value = original_value
visited = set()
while isinstance(value, basestring) \
and value.startswith(prefix):
value = value.format(region=config.region, **instance)
if value in instance \
and value not in visited:
visited.add(value)
value = instance[value]
else:
if original_value == value:
raise Exception("Unable to resolve '%s'" % value)
else:
raise Exception(
"While resolving '%s': unable to resolve '%s'"
% (original_value, value))
return value
# Resolve symbols
for prefix in _prefixes:
key = prefix[:-1]
if key not in instance:
continue
if isinstance(instance[key], basestring):
instance[key] = resolve_symbol(instance[key])
elif isinstance(instance[key], list):
instance[key] = map(resolve_symbol, instance[key])
# Drop resolvable symbols
for key in instance.keys():
if key.startswith(_prefixes):
del instance[key]
| Fix infinite loop with missing symbol definition | Fix infinite loop with missing symbol definition
The local function _resolve_symbol is renamed for improved tracebacks.
| Python | apache-2.0 | biochimia/hc2000 | ---
+++
@@ -8,7 +8,8 @@
'subnet:')
def apply(instance):
- def _resolve_symbol(value):
+ def resolve_symbol(original_value):
+ value = original_value
visited = set()
while isinstance(value, basestring) \
and value.startswith(prefix):
@@ -17,6 +18,13 @@
and value not in visited:
visited.add(value)
value = instance[value]
+ else:
+ if original_value == value:
+ raise Exception("Unable to resolve '%s'" % value)
+ else:
+ raise Exception(
+ "While resolving '%s': unable to resolve '%s'"
+ % (original_value, value))
return value
# Resolve symbols
@@ -26,9 +34,9 @@
continue
if isinstance(instance[key], basestring):
- instance[key] = _resolve_symbol(instance[key])
+ instance[key] = resolve_symbol(instance[key])
elif isinstance(instance[key], list):
- instance[key] = map(_resolve_symbol, instance[key])
+ instance[key] = map(resolve_symbol, instance[key])
# Drop resolvable symbols
for key in instance.keys(): |
470f089a764185350b698725c6720e602c1eb804 | neutron/plugins/ml2/drivers/mlnx/config.py | neutron/plugins/ml2/drivers/mlnx/config.py | # Copyright (c) 2014 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from oslo.config import cfg
from neutron.extensions import portbindings
eswitch_opts = [
cfg.StrOpt('vnic_type',
default=portbindings.VIF_TYPE_MLNX_DIRECT,
help=_("Type of VM network interface: mlnx_direct or "
"hostdev")),
cfg.BoolOpt('apply_profile_patch',
default=False,
help=_("Enable server compatibility with old nova ")),
]
cfg.CONF.register_opts(eswitch_opts, "ESWITCH")
| # Copyright (c) 2014 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from oslo.config import cfg
from neutron.extensions import portbindings
eswitch_opts = [
cfg.StrOpt('vnic_type',
default=portbindings.VIF_TYPE_MLNX_DIRECT,
help=_("Type of VM network interface: mlnx_direct or "
"hostdev")),
cfg.BoolOpt('apply_profile_patch',
default=False,
help=_("Enable server compatibility with old nova")),
]
cfg.CONF.register_opts(eswitch_opts, "ESWITCH")
| Remove extra space in help string | Remove extra space in help string
Extra spaces make the openstack-manuals tests fail with a niceness
error. This patch removes an extra space at the end of a help string.
Change-Id: I29bab90ea5a6f648c4539c7cd20cd9b2b63055c2
| Python | apache-2.0 | apporc/neutron,magic0704/neutron,wenhuizhang/neutron,glove747/liberty-neutron,asgard-lab/neutron,neoareslinux/neutron,adelina-t/neutron,silenci/neutron,chitr/neutron,CiscoSystems/neutron,waltBB/neutron_read,paninetworks/neutron,openstack/neutron,sasukeh/neutron,yamahata/neutron,eayunstack/neutron,aristanetworks/neutron,eonpatapon/neutron,swdream/neutron,yamahata/neutron,barnsnake351/neutron,swdream/neutron,miyakz1192/neutron,gkotton/neutron,cisco-openstack/neutron,sasukeh/neutron,alexandrucoman/vbox-neutron-agent,leeseuljeong/leeseulstack_neutron,paninetworks/neutron,noironetworks/neutron,sebrandon1/neutron,vijayendrabvs/hap,cisco-openstack/neutron,leeseulstack/openstack,vijayendrabvs/hap,vveerava/Openstack,gkotton/neutron,projectcalico/calico-neutron,gopal1cloud/neutron,antonioUnina/neutron,leeseulstack/openstack,mahak/neutron,watonyweng/neutron,wolverineav/neutron,redhat-openstack/neutron,projectcalico/calico-neutron,wolverineav/neutron,takeshineshiro/neutron,mattt416/neutron,javaos74/neutron,Stavitsky/neutron,blueboxgroup/neutron,SmartInfrastructures/neutron,vivekanand1101/neutron,vveerava/Openstack,rdo-management/neutron,infobloxopen/neutron,klmitch/neutron,vivekanand1101/neutron,gopal1cloud/neutron,adelina-t/neutron,cloudbase/neutron-virtualbox,eayunstack/neutron,leeseulstack/openstack,chitr/neutron,yamahata/tacker,wenhuizhang/neutron,mmnelemane/neutron,jumpojoy/neutron,eonpatapon/neutron,SmartInfrastructures/neutron,takeshineshiro/neutron,Stavitsky/neutron,CiscoSystems/neutron,suneeth51/neutron,bgxavier/neutron,mattt416/neutron,miyakz1192/neutron,Metaswitch/calico-neutron,skyddv/neutron,jerryz1982/neutron,huntxu/neutron,cloudbase/neutron,watonyweng/neutron,shahbazn/neutron,igor-toga/local-snat,JianyuWang/neutron,antonioUnina/neutron,mandeepdhami/neutron,sajuptpm/neutron-ipam,barnsnake351/neutron,cernops/neutron,huntxu/neutron,JioCloud/neutron,vijayendrabvs/hap,silenci/neutron,blueboxgroup/neutron,bgxavier/neutron,yuewko/neutron,dhanunjaya/neutron,cernops/neutron,SamYaple/neutron,asgard-lab/neutron,neoareslinux/neutron,sajuptpm/neutron-ipam,virtualopensystems/neutron,redhat-openstack/neutron,shahbazn/neutron,mahak/neutron,mahak/neutron,pnavarro/neutron,cloudbase/neutron,CiscoSystems/neutron,vveerava/Openstack,leeseuljeong/leeseulstack_neutron,yamahata/tacker,suneeth51/neutron,dims/neutron,magic0704/neutron,MaximNevrov/neutron,leeseuljeong/leeseulstack_neutron,MaximNevrov/neutron,skyddv/neutron,waltBB/neutron_read,blueboxgroup/neutron,pnavarro/neutron,bigswitch/neutron,virtualopensystems/neutron,cloudbase/neutron-virtualbox,sajuptpm/neutron-ipam,vbannai/neutron,klmitch/neutron,mandeepdhami/neutron,aristanetworks/neutron,virtualopensystems/neutron,openstack/neutron,igor-toga/local-snat,mmnelemane/neutron,yamahata/tacker,Metaswitch/calico-neutron,apporc/neutron,sebrandon1/neutron,alexandrucoman/vbox-neutron-agent,NeCTAR-RC/neutron,yamahata/neutron,infobloxopen/neutron,noironetworks/neutron,jumpojoy/neutron,vbannai/neutron,yanheven/neutron,SamYaple/neutron,JioCloud/neutron,JianyuWang/neutron,yuewko/neutron,jacknjzhou/neutron,NeCTAR-RC/neutron,dhanunjaya/neutron,javaos74/neutron,glove747/liberty-neutron,jerryz1982/neutron,vbannai/neutron,yanheven/neutron,dims/neutron,bigswitch/neutron,gkotton/neutron,rdo-management/neutron,jacknjzhou/neutron,openstack/neutron | ---
+++
@@ -25,7 +25,7 @@
"hostdev")),
cfg.BoolOpt('apply_profile_patch',
default=False,
- help=_("Enable server compatibility with old nova ")),
+ help=_("Enable server compatibility with old nova")),
]
|
ad766ba20db73ceb433b9afe3b5db3e52cf1494a | addons/sale_stock/models/stock_config_settings.py | addons/sale_stock/models/stock_config_settings.py | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class StockConfigSettings(models.TransientModel):
_inherit = 'stock.config.settings'
security_lead = fields.Float(related='company_id.security_lead')
default_new_security_lead = fields.Boolean(string="Security Lead Time for Sales", default_model="stock.config.settings", help="Margin of error for dates promised to customers. Products will be scheduled for procurement and delivery that many days earlier than the actual promised date, to cope with unexpected delays in the supply chain.")
default_picking_policy = fields.Selection([
('direct', 'Ship products as soon as available, with back orders'),
('one', 'Ship all products at once')
], "Shipping Management", default='direct', default_model="sale.order")
| # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class StockConfigSettings(models.TransientModel):
_inherit = 'stock.config.settings'
security_lead = fields.Float(related='company_id.security_lead')
default_new_security_lead = fields.Boolean(string="Security Lead Time for Sales", default_model="stock.config.settings", help="Margin of error for dates promised to customers. Products will be scheduled for procurement and delivery that many days earlier than the actual promised date, to cope with unexpected delays in the supply chain.")
default_picking_policy = fields.Selection([
('direct', 'Ship products as soon as available, with back orders'),
('one', 'Ship all products at once')
], "Shipping Management", default='direct', default_model="sale.order", required=True)
| Make default_picking_policy a required field in settings | [IMP] stock: Make default_picking_policy a required field in settings
| Python | agpl-3.0 | ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo | ---
+++
@@ -12,4 +12,4 @@
default_picking_policy = fields.Selection([
('direct', 'Ship products as soon as available, with back orders'),
('one', 'Ship all products at once')
- ], "Shipping Management", default='direct', default_model="sale.order")
+ ], "Shipping Management", default='direct', default_model="sale.order", required=True) |
96dd8312cded04e5f5758495e72238d58905be7b | count.py | count.py | import json
from collections import Counter
from Bio import SeqIO
from Bio.SeqUtils import GC
for seq_record in SeqIO.parse("samples/test.fasta", "fasta"):
cnt = Counter()
line = str(seq_record.seq)
i = 0
for j in range(((len(line))/ 3)):
cnt[line[i:i+3]] += 1
i += 3
print json.dumps(
[{
"id" : seq_record.id,
"ratios" : cnt
}], sort_keys=True, indent=4, separators=(',', ': '))
| #!/usr/bin/python
import getopt
import json
import sys
from collections import Counter
from Bio import SeqIO
from Bio.SeqUtils import GC
def compute(inputfile):
for seq_record in SeqIO.parse(inputfile, "fasta"):
cnt = Counter()
line = str(seq_record.seq)
i = 0
for j in range(((len(line))/ 3)):
cnt[line[i:i+3]] += 1
i += 3
print json.dumps(
[{
"id" : seq_record.id,
"ratios" : cnt
}], sort_keys=True, indent=4, separators=(',', ': '))
def main(argv):
inputfile = 'samples/test.fasta'
try:
opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
except getopt.GetoptError:
print 'count.py -i <inputfile> -o <outputfile>'
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print 'count.py -i <inputfile>'
sys.exit()
elif opt in ("-i", "--ifile"):
inputfile = arg
print 'Input file is', inputfile
compute(inputfile)
if __name__ == "__main__":
main(sys.argv[1:])
| Add -i flag for input | Add -i flag for input
| Python | apache-2.0 | PDX-Flamingo/codonpdx-python,PDX-Flamingo/codonpdx-python | ---
+++
@@ -1,18 +1,43 @@
+#!/usr/bin/python
+
+import getopt
import json
-
+import sys
from collections import Counter
from Bio import SeqIO
from Bio.SeqUtils import GC
-for seq_record in SeqIO.parse("samples/test.fasta", "fasta"):
- cnt = Counter()
- line = str(seq_record.seq)
- i = 0
- for j in range(((len(line))/ 3)):
- cnt[line[i:i+3]] += 1
- i += 3
- print json.dumps(
- [{
- "id" : seq_record.id,
- "ratios" : cnt
- }], sort_keys=True, indent=4, separators=(',', ': '))
+
+def compute(inputfile):
+ for seq_record in SeqIO.parse(inputfile, "fasta"):
+ cnt = Counter()
+ line = str(seq_record.seq)
+ i = 0
+ for j in range(((len(line))/ 3)):
+ cnt[line[i:i+3]] += 1
+ i += 3
+ print json.dumps(
+ [{
+ "id" : seq_record.id,
+ "ratios" : cnt
+ }], sort_keys=True, indent=4, separators=(',', ': '))
+
+def main(argv):
+ inputfile = 'samples/test.fasta'
+ try:
+ opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
+ except getopt.GetoptError:
+ print 'count.py -i <inputfile> -o <outputfile>'
+ sys.exit(2)
+ for opt, arg in opts:
+ if opt == '-h':
+ print 'count.py -i <inputfile>'
+ sys.exit()
+ elif opt in ("-i", "--ifile"):
+ inputfile = arg
+ print 'Input file is', inputfile
+
+ compute(inputfile)
+
+if __name__ == "__main__":
+ main(sys.argv[1:]) |
29562b08e436abc8465404e49d9193537721b717 | src/odin/contrib/money/fields.py | src/odin/contrib/money/fields.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function
from odin import exceptions
from odin.fields import ScalarField
from odin.validators import EMPTY_VALUES
from .datatypes import Amount
__all__ = ('AmountField', )
class AmountField(ScalarField):
"""
Field that contains a monetary amount (with an optional currency).
"""
default_error_messages = {
'invalid': "'%s' value must be a (amount, currency).",
'invalid_currency': "'%s' currency is not supported.",
}
data_type_name = "Amount"
def __init__(self, allowed_currencies=None, **kwargs):
super(AmountField, self).__init__(**kwargs)
self.allowed_currencies = allowed_currencies
def to_python(self, value):
if value in EMPTY_VALUES:
return
if isinstance(value, Amount):
return value
try:
return Amount(value)
except (ValueError, TypeError):
msg = self.error_messages['invalid'] % value
raise exceptions.ValidationError(msg)
def validate(self, value):
super(AmountField, self).validate(value)
if self.allowed_currencies and value not in EMPTY_VALUES:
if value.currency not in self.allowed_currencies:
msg = self.error_messages['invalid_currency'] % str(value.currency)
raise exceptions.ValidationError(msg)
def prepare(self, value):
if value in EMPTY_VALUES:
return
return float(value), value.currency.code
| # -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function
from odin import exceptions
from odin.fields import ScalarField
from odin.validators import EMPTY_VALUES
from .datatypes import Amount
__all__ = ("AmountField",)
class AmountField(ScalarField):
"""
Field that contains a monetary amount (with an optional currency).
"""
default_error_messages = {
"invalid": "'%s' value must be a (amount, currency).",
"invalid_currency": "'%s' currency is not supported.",
}
data_type_name = "Amount"
def __init__(self, allowed_currencies=None, **kwargs):
super(AmountField, self).__init__(**kwargs)
self.allowed_currencies = allowed_currencies
def to_python(self, value):
if value in EMPTY_VALUES:
return
if isinstance(value, Amount):
return value
try:
return Amount(value)
except (ValueError, TypeError):
msg = self.error_messages["invalid"] % value
raise exceptions.ValidationError(msg)
def validate(self, value):
super(AmountField, self).validate(value)
if (
self.allowed_currencies
and (value not in EMPTY_VALUES)
and (value.currency not in self.allowed_currencies)
):
msg = self.error_messages["invalid_currency"] % str(value.currency)
raise exceptions.ValidationError(msg)
def prepare(self, value):
if value in EMPTY_VALUES:
return
return float(value), value.currency.code
| Correct issue from Sonar (and black file) | Correct issue from Sonar (and black file)
| Python | bsd-3-clause | python-odin/odin | ---
+++
@@ -5,16 +5,17 @@
from odin.validators import EMPTY_VALUES
from .datatypes import Amount
-__all__ = ('AmountField', )
+__all__ = ("AmountField",)
class AmountField(ScalarField):
"""
Field that contains a monetary amount (with an optional currency).
"""
+
default_error_messages = {
- 'invalid': "'%s' value must be a (amount, currency).",
- 'invalid_currency': "'%s' currency is not supported.",
+ "invalid": "'%s' value must be a (amount, currency).",
+ "invalid_currency": "'%s' currency is not supported.",
}
data_type_name = "Amount"
@@ -31,15 +32,18 @@
try:
return Amount(value)
except (ValueError, TypeError):
- msg = self.error_messages['invalid'] % value
+ msg = self.error_messages["invalid"] % value
raise exceptions.ValidationError(msg)
def validate(self, value):
super(AmountField, self).validate(value)
- if self.allowed_currencies and value not in EMPTY_VALUES:
- if value.currency not in self.allowed_currencies:
- msg = self.error_messages['invalid_currency'] % str(value.currency)
- raise exceptions.ValidationError(msg)
+ if (
+ self.allowed_currencies
+ and (value not in EMPTY_VALUES)
+ and (value.currency not in self.allowed_currencies)
+ ):
+ msg = self.error_messages["invalid_currency"] % str(value.currency)
+ raise exceptions.ValidationError(msg)
def prepare(self, value):
if value in EMPTY_VALUES: |
6b93f6a6bedf875d4bad1af2493c91b28a625ea9 | chempy/electrochemistry/tests/test_nernst.py | chempy/electrochemistry/tests/test_nernst.py | # -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function)
from ..nernst import nernst_potential
def test_nernst_potential():
# Sodium in cells
assert abs(1000 * nernst_potential(145, 15, 1, 310) - 60.605) < 1e-4
# Potassium in cells
assert abs(1000 * nernst_potential(4, 150, 1, 310) - (-96.8196)) < 1e-4
| # -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function)
from ..nernst import nernst_potential
from chempy.util.testing import requires
from chempy.units import default_units, default_constants, units_library
def test_nernst_potential():
"""
Test cases obtained from textbook examples of Nernst potential in cellular
membranes. 310K = 37C, typical mammalian cell environment temperature.
"""
# Sodium in cells
assert abs(1000 * nernst_potential(145, 15, 1, 310) - 60.605) < 1e-4
# Potassium in cells
assert abs(1000 * nernst_potential(4, 150, 1, 310) - (-96.8196)) < 1e-4
# Calcium in cells
assert abs(1000 * nernst_potential(2, 7e-5, 2, 310) - 137.0436) < 1e-4
# Chloride in cells
assert abs(1000 * nernst_potential(110, 10, -1, 310) - (-64.0567)) < 1e-4
@requires(units_library)
def test_nernst_potential_units():
v = nernst_potential(145, 15, 1, 310, default_constants, default_units)
assert (1000 * v - 60.605) < 1e-4
| Add additional testing to electrochemistry/Nernst | Add additional testing to electrochemistry/Nernst
| Python | bsd-2-clause | bjodah/aqchem,bjodah/aqchem,bjodah/chempy,bjodah/chempy,bjodah/aqchem | ---
+++
@@ -2,10 +2,26 @@
from __future__ import (absolute_import, division, print_function)
from ..nernst import nernst_potential
+from chempy.util.testing import requires
+from chempy.units import default_units, default_constants, units_library
def test_nernst_potential():
+ """
+ Test cases obtained from textbook examples of Nernst potential in cellular
+ membranes. 310K = 37C, typical mammalian cell environment temperature.
+ """
# Sodium in cells
assert abs(1000 * nernst_potential(145, 15, 1, 310) - 60.605) < 1e-4
# Potassium in cells
assert abs(1000 * nernst_potential(4, 150, 1, 310) - (-96.8196)) < 1e-4
+ # Calcium in cells
+ assert abs(1000 * nernst_potential(2, 7e-5, 2, 310) - 137.0436) < 1e-4
+ # Chloride in cells
+ assert abs(1000 * nernst_potential(110, 10, -1, 310) - (-64.0567)) < 1e-4
+
+
+@requires(units_library)
+def test_nernst_potential_units():
+ v = nernst_potential(145, 15, 1, 310, default_constants, default_units)
+ assert (1000 * v - 60.605) < 1e-4 |
2735d4a7b1ae0af0d58ea0accb973ab11477783e | django_hosts/tests/urls/simple.py | django_hosts/tests/urls/simple.py | from django.conf.urls.defaults import patterns, url
from django.views.generic import TemplateView
urlpatterns = patterns('django.views.generic.simple',
url(r'^simple/$', TemplateView.as_view(), name='simple-direct'),
)
| from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('django.views.generic.simple',
url(r'^simple/$', 'django.shortcuts.render', name='simple-direct'),
)
| Use django.shortcuts.render instead of TemplateView | Use django.shortcuts.render instead of TemplateView | Python | bsd-3-clause | jezdez/django-hosts | ---
+++
@@ -1,6 +1,5 @@
from django.conf.urls.defaults import patterns, url
-from django.views.generic import TemplateView
urlpatterns = patterns('django.views.generic.simple',
- url(r'^simple/$', TemplateView.as_view(), name='simple-direct'),
+ url(r'^simple/$', 'django.shortcuts.render', name='simple-direct'),
) |
cb533d74f2e634d9e8c7d0515307fad107da36ef | {{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/apps/site/urls.py | {{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/apps/site/urls.py | from django.conf import settings
from django.conf.urls import url
from django.http import HttpResponse
from django.views import generic
from . import views
urlpatterns = (
url(r'^robots\.txt$', views.RobotsView.as_view(), name="robots"),
)
if getattr(settings, 'LOADERIO_TOKEN', None):
loaderio_token = settings.LOADERIO_TOKEN
class LoaderioTokenView(generic.View):
def get(self, request, *args, **kwargs):
return HttpResponse('{}'.format(loaderio_token))
urlpatterns += (
url(r'^{}/$'.format(loaderio_token), LoaderioTokenView.as_view()),
)
| from django.conf import settings
from django.conf.urls import url
from django.http import HttpResponse
from django.views import generic
from . import views
urlpatterns = (
url(r'^robots\.txt$', views.RobotsView.as_view(), name="robots"),
)
if getattr(settings, 'LOADERIO_TOKEN', None):
loaderio_token = settings.LOADERIO_TOKEN
class LoaderioTokenView(generic.View):
def get(self, request, *args, **kwargs):
return HttpResponse('{}'.format(loaderio_token))
urlpatterns += (
url(r'^{}/$'.format(loaderio_token), LoaderioTokenView.as_view()),
)
| Add a missing line between imports | Add a missing line between imports
| Python | mit | dulaccc/cookiecutter-django-herokuapp,dulaccc/cookiecutter-django-herokuapp,dulaccc/cookiecutter-django-herokuapp,dulaccc/cookiecutter-django-herokuapp | ---
+++
@@ -4,6 +4,7 @@
from django.views import generic
from . import views
+
urlpatterns = (
url(r'^robots\.txt$', views.RobotsView.as_view(), name="robots"), |
f0cf4b51987befb25f605ee421554da7615c9472 | readthedocs/builds/admin.py | readthedocs/builds/admin.py | """Django admin interface for `~builds.models.Build` and related models.
"""
from django.contrib import admin
from readthedocs.builds.models import Build, VersionAlias, Version, BuildCommandResult
from guardian.admin import GuardedModelAdmin
class BuildCommandResultInline(admin.TabularInline):
model = BuildCommandResult
fields = ('command', 'exit_code')
class BuildAdmin(admin.ModelAdmin):
fields = ('project', 'version', 'type', 'state', 'success', 'length')
list_display = ('project', 'success', 'type', 'state')
raw_id_fields = ('project', 'version')
inlines = (BuildCommandResultInline,)
class VersionAdmin(GuardedModelAdmin):
search_fields = ('slug', 'project__name')
list_filter = ('project', 'privacy_level')
admin.site.register(Build, BuildAdmin)
admin.site.register(VersionAlias)
admin.site.register(Version, VersionAdmin)
| """Django admin interface for `~builds.models.Build` and related models.
"""
from django.contrib import admin
from readthedocs.builds.models import Build, VersionAlias, Version, BuildCommandResult
from guardian.admin import GuardedModelAdmin
class BuildCommandResultInline(admin.TabularInline):
model = BuildCommandResult
fields = ('command', 'exit_code')
class BuildAdmin(admin.ModelAdmin):
fields = ('project', 'version', 'type', 'state', 'success', 'length')
list_display = ('project', 'success', 'type', 'state', 'date')
raw_id_fields = ('project', 'version')
inlines = (BuildCommandResultInline,)
class VersionAdmin(GuardedModelAdmin):
search_fields = ('slug', 'project__name')
list_filter = ('project', 'privacy_level')
admin.site.register(Build, BuildAdmin)
admin.site.register(VersionAlias)
admin.site.register(Version, VersionAdmin)
| Add date back to build display | Add date back to build display
| Python | mit | davidfischer/readthedocs.org,safwanrahman/readthedocs.org,espdev/readthedocs.org,safwanrahman/readthedocs.org,rtfd/readthedocs.org,tddv/readthedocs.org,davidfischer/readthedocs.org,espdev/readthedocs.org,rtfd/readthedocs.org,pombredanne/readthedocs.org,espdev/readthedocs.org,espdev/readthedocs.org,davidfischer/readthedocs.org,espdev/readthedocs.org,pombredanne/readthedocs.org,davidfischer/readthedocs.org,tddv/readthedocs.org,safwanrahman/readthedocs.org,safwanrahman/readthedocs.org,rtfd/readthedocs.org,tddv/readthedocs.org,pombredanne/readthedocs.org,rtfd/readthedocs.org | ---
+++
@@ -14,7 +14,7 @@
class BuildAdmin(admin.ModelAdmin):
fields = ('project', 'version', 'type', 'state', 'success', 'length')
- list_display = ('project', 'success', 'type', 'state')
+ list_display = ('project', 'success', 'type', 'state', 'date')
raw_id_fields = ('project', 'version')
inlines = (BuildCommandResultInline,)
|
0ca07405b864f761ae1d7ed659cac67c799bf39a | src/core/queue.py | src/core/queue.py | # -*- coding: utf-8 -*-
"""ICU (LEGO Island Configuration Utility).
Created 2015 Triangle717
<http://le717.github.io/>
Licensed under The MIT License
<http://opensource.org/licenses/MIT/>
"""
class ActionsQueue:
def __init__(self):
self.queue = []
# Normal buttons
def btnBrowse(self, val):
print(val)
def actionReset(self, val):
print(val)
def btnRedirect(self, val):
print(val)
# Radio buttons
def radioColor256(self, val):
print(val)
def radioColor16b(self, val):
print(val)
def radioModelLow(self, val):
print(val)
def radioModelFast(self, val):
print(val)
def radioModelHigh(self, val):
print(val)
def radioTexFast(self, val):
print(val)
def radioTexHigh(self, val):
print(val)
# Check boxes
def chkCursor(self, val):
print(val)
def chkDraw3D(self, val):
print(val)
def chkFlipVideo(self, val):
print(val)
def chkFullscreen(self, val):
print(val)
def chkJoystick(self, val):
print(val)
def chkMusic(self, val):
print(val)
def chkSound(self, val):
print(val)
# Direct3D dropdown selection
def comboD3D(self, val):
print(val)
| # -*- coding: utf-8 -*-
"""ICU (LEGO Island Configuration Utility).
Created 2015 Triangle717
<http://le717.github.io/>
Licensed under The MIT License
<http://opensource.org/licenses/MIT/>
"""
class ActionsQueue:
def __init__(self):
self.queue = []
class Responses:
def __init__(self):
pass
# Normal buttons
def btnBrowse(self, val):
print(val)
def actionReset(self, val):
print(val)
def btnRedirect(self, val):
print(val)
# Radio buttons
def radioColor256(self, val):
print(val)
def radioColor16b(self, val):
print(val)
def radioModelLow(self, val):
print(val)
def radioModelFast(self, val):
print(val)
def radioModelHigh(self, val):
print(val)
def radioTexFast(self, val):
print(val)
def radioTexHigh(self, val):
print(val)
# Check boxes
def chkCursor(self, val):
print(val)
def chkDraw3D(self, val):
print(val)
def chkFlipVideo(self, val):
print(val)
def chkFullscreen(self, val):
print(val)
def chkJoystick(self, val):
print(val)
def chkMusic(self, val):
print(val)
def chkSound(self, val):
print(val)
# Direct3D dropdown selection
def comboD3D(self, val):
print(val)
| Move those methods to own class | Move those methods to own class [ci skip]
| Python | mit | le717/ICU | ---
+++
@@ -14,6 +14,12 @@
def __init__(self):
self.queue = []
+
+
+class Responses:
+
+ def __init__(self):
+ pass
# Normal buttons
def btnBrowse(self, val): |
facfa3bcd7d35163e0504ef4b6f9b3b15e778993 | modeltranslation/management/commands/update_translation_fields.py | modeltranslation/management/commands/update_translation_fields.py | # -*- coding: utf-8 -*-
from django.db.models import F, Q
from django.core.management.base import NoArgsCommand
from modeltranslation.settings import DEFAULT_LANGUAGE
from modeltranslation.translator import translator
from modeltranslation.utils import build_localized_fieldname
class Command(NoArgsCommand):
help = ('Updates the default translation fields of all or the specified'
'translated application using the value of the original field.')
def handle(self, **options):
verbosity = int(options['verbosity'])
if verbosity > 0:
self.stdout.write("Using default language: %s\n" % DEFAULT_LANGUAGE)
for model, trans_opts in translator._registry.items():
if model._meta.abstract:
continue
if verbosity > 0:
self.stdout.write("Updating data of model '%s'\n" % model)
for fieldname in trans_opts.fields:
def_lang_fieldname = build_localized_fieldname(
fieldname, DEFAULT_LANGUAGE)
# We'll only update fields which do not have an existing value
q = Q(**{def_lang_fieldname: None})
field = model._meta.get_field(fieldname)
if field.empty_strings_allowed:
q |= Q(**{def_lang_fieldname: ""})
try:
model.objects.filter(q).rewrite(False).update(
**{def_lang_fieldname: F(fieldname)})
except AttributeError:
# FIXME: Workaround for abstract models. See issue #123 for details.
model.objects.filter(q).update(**{def_lang_fieldname: F(fieldname)})
| # -*- coding: utf-8 -*-
from django.db.models import F, Q
from django.core.management.base import NoArgsCommand
from modeltranslation.settings import DEFAULT_LANGUAGE
from modeltranslation.translator import translator
from modeltranslation.utils import build_localized_fieldname
class Command(NoArgsCommand):
help = ('Updates the default translation fields of all or the specified'
'translated application using the value of the original field.')
def handle(self, **options):
verbosity = int(options['verbosity'])
if verbosity > 0:
self.stdout.write("Using default language: %s\n" % DEFAULT_LANGUAGE)
for model, trans_opts in translator._registry.items():
if model._meta.abstract:
continue
if verbosity > 0:
self.stdout.write("Updating data of model '%s'\n" % model)
for fieldname in trans_opts.fields:
def_lang_fieldname = build_localized_fieldname(
fieldname, DEFAULT_LANGUAGE)
# We'll only update fields which do not have an existing value
q = Q(**{def_lang_fieldname: None})
field = model._meta.get_field(fieldname)
if field.empty_strings_allowed:
q |= Q(**{def_lang_fieldname: ""})
model.objects.filter(q).rewrite(False).update(**{def_lang_fieldname: F(fieldname)})
| Revert "Added a workaround for abstract models not being handled correctly." | Revert "Added a workaround for abstract models not being handled correctly."
This reverts commit a3e44c187b5abfa6d9b360cecc5c1daa746134f5.
| Python | bsd-3-clause | marctc/django-modeltranslation,akheron/django-modeltranslation,nanuxbe/django-modeltranslation,marctc/django-modeltranslation,nanuxbe/django-modeltranslation,SideStudios/django-modeltranslation,akheron/django-modeltranslation,yoza/django-modeltranslation,extertioner/django-modeltranslation,extertioner/django-modeltranslation,deschler/django-modeltranslation,acdha/django-modeltranslation,acdha/django-modeltranslation,vstoykov/django-modeltranslation,deschler/django-modeltranslation,yoza/django-modeltranslation,SideStudios/django-modeltranslation,vstoykov/django-modeltranslation | ---
+++
@@ -30,9 +30,4 @@
if field.empty_strings_allowed:
q |= Q(**{def_lang_fieldname: ""})
- try:
- model.objects.filter(q).rewrite(False).update(
- **{def_lang_fieldname: F(fieldname)})
- except AttributeError:
- # FIXME: Workaround for abstract models. See issue #123 for details.
- model.objects.filter(q).update(**{def_lang_fieldname: F(fieldname)})
+ model.objects.filter(q).rewrite(False).update(**{def_lang_fieldname: F(fieldname)}) |
ae6ed4e7dc6510637d322eb6403f43b9d4aa5d25 | karteikarten/helpers/exporters.py | karteikarten/helpers/exporters.py | # Copyright (C) 2013 Braden Walters
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from karteikarten.models import Card
class AnkiExporter(object):
'''
Exports cards to ANKI Text File.
'''
@staticmethod
def export(cardset):
result = u'front\tback\n'
for card in Card.objects.filter(parent_card_set = cardset):
result += card.front.replace('\n', '<br />') + '\t' + \
card.back.replace('\n', '<br />') + '\n'
return result
@staticmethod
def getExtension():
return '.txt'
| # Copyright (C) 2013 Braden Walters
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from karteikarten.models import Card
class AnkiExporter(object):
'''
Exports cards to ANKI Text File.
'''
@staticmethod
def export(cardset):
result = u'front\tback\n'
for card in Card.objects.filter(parent_card_set = cardset):
result += card.front.replace('\n', '<br />').replace('\r', '') + '\t' + \
card.back.replace('\n', '<br />').replace('\r', '') + '\n'
return result
@staticmethod
def getExtension():
return '.txt'
| Remove carriage returns in Anki exporter | Remove carriage returns in Anki exporter
| Python | agpl-3.0 | meoblast001/kksystem,meoblast001/kksystem,meoblast001/kksystem | ---
+++
@@ -23,8 +23,8 @@
def export(cardset):
result = u'front\tback\n'
for card in Card.objects.filter(parent_card_set = cardset):
- result += card.front.replace('\n', '<br />') + '\t' + \
- card.back.replace('\n', '<br />') + '\n'
+ result += card.front.replace('\n', '<br />').replace('\r', '') + '\t' + \
+ card.back.replace('\n', '<br />').replace('\r', '') + '\n'
return result
@staticmethod |
24d3af9288102e5061c3a1f9e6fe2d7d578f6cc5 | astro.py | astro.py | import ephem
m = getattr(ephem, (raw_input('Planet: ')))
print ephem.constellation(m(raw_input('yyyy/mm/dd: '))) | import ephem
def const(planet_name, date_string): # function name and parameters
planet_class = getattr(ephem, planet_name) # sets ephem object class
planet = planet_class() # sets planet variable
south_bend = ephem.Observer() # Creates the Observer object
south_bend.lat = '41.67' # latitude
south_bend.lon = '-86.26' # west is negative
south_bend.date = date_string # sets date parameter
planet.compute(south_bend) # calculates the location data
print ephem.constellation((planet.ra, planet.dec))
return planet.alt, planet.az
print const(raw_input('Planet: '), getattr(ephem, now()))
| Select planet and display alt/az data | Select planet and display alt/az data
Created a function localized to South Bend, IN, to display altitude and
azimuth data for a planet selected.
| Python | mit | bennettscience/PySky | ---
+++
@@ -1,5 +1,14 @@
import ephem
-m = getattr(ephem, (raw_input('Planet: ')))
+def const(planet_name, date_string): # function name and parameters
+ planet_class = getattr(ephem, planet_name) # sets ephem object class
+ planet = planet_class() # sets planet variable
+ south_bend = ephem.Observer() # Creates the Observer object
+ south_bend.lat = '41.67' # latitude
+ south_bend.lon = '-86.26' # west is negative
+ south_bend.date = date_string # sets date parameter
+ planet.compute(south_bend) # calculates the location data
+ print ephem.constellation((planet.ra, planet.dec))
+ return planet.alt, planet.az
-print ephem.constellation(m(raw_input('yyyy/mm/dd: ')))
+print const(raw_input('Planet: '), getattr(ephem, now())) |
071926edc64241b0359c9a0148fc0825a09cb6ba | marionette/__init__.py | marionette/__init__.py |
from cgi import parse_header
import json
from django.http import HttpResponse, Http404
RPC_MARKER = '_rpc'
class Resource(object):
def __init__(self, request, *args, **kwargs):
self.request = request
self.args = args
self.kwargs = kwargs
@classmethod
def as_view(cls):
def view(request, *args, **kwargs):
self = cls(request, *args, **kwargs)
return self.dispatch(request)
return view
def dispatch(self, request):
method = request.META['HTTP_X_RPC_ACTION']
func = getattr(self, method, None)
if not getattr(func, RPC_MARKER, True):
raise Http404
data = self.get_request_data(request)
resp = func(data)
return HttpResponse(json.dumps(resp), content_type='application/json')
def get_request_data(self, default=None):
'''Retrieve data from request'''
c_type, _ = parse_header(self.request.META.get('CONTENT_TYPE', ''))
if c_type in ['application/json', 'text/json']:
if not self.request.body:
return default
return self.loads(self.request.body)
if self.request.method == 'GET':
return self.request.GET
return self.request.POST
def rpc(view):
'''Mark a view as accessible via RPC'''
setattr(view, '_rpc', True)
return view
|
from cgi import parse_header
import json
from django.http import HttpResponse, Http404
RPC_MARKER = '_rpc'
class Resource(object):
def __init__(self, request, *args, **kwargs):
self.request = request
self.args = args
self.kwargs = kwargs
@classmethod
def as_view(cls):
def view(request, *args, **kwargs):
self = cls(request, *args, **kwargs)
return self.dispatch(request)
return view
def dispatch(self, request):
method = request.META['HTTP_X_RPC_ACTION']
func = getattr(self, method, None)
if not getattr(func, RPC_MARKER, True):
raise Http404
data = self.get_request_data(request)
resp = self.execute(func, data)
return HttpResponse(json.dumps(resp), content_type='application/json')
def execute(self, handler, data):
'''Helpful hook to ease wrapping the handler'''
return handler(**data)
def get_request_data(self, default=None):
'''Retrieve data from request'''
c_type, _ = parse_header(self.request.META.get('CONTENT_TYPE', ''))
if c_type in ['application/json', 'text/json']:
if not self.request.body:
return default
return self.loads(self.request.body)
if self.request.method == 'GET':
return self.request.GET
return self.request.POST
def rpc(view):
'''Mark a view as accessible via RPC'''
setattr(view, '_rpc', True)
return view
| Add execute hook to allow wrapping handler calls | Add execute hook to allow wrapping handler calls
| Python | mit | funkybob/django-marionette | ---
+++
@@ -29,9 +29,13 @@
data = self.get_request_data(request)
- resp = func(data)
+ resp = self.execute(func, data)
return HttpResponse(json.dumps(resp), content_type='application/json')
+
+ def execute(self, handler, data):
+ '''Helpful hook to ease wrapping the handler'''
+ return handler(**data)
def get_request_data(self, default=None):
'''Retrieve data from request''' |
6f947c99411692f8fe4899203ed9bf202b0412a3 | cihai/__about__.py | cihai/__about__.py | __title__ = 'cihai'
__package_name__ = 'cihai'
__version__ = '0.9.0a3'
__description__ = 'Library for CJK (chinese, japanese, korean) language data.'
__author__ = 'Tony Narlock'
__email__ = 'tony@git-pull.com'
__github__ = 'https://github.com/cihai/cihai'
__pypi__ = 'https://pypi.org/project/cihai/'
__license__ = 'MIT'
__copyright__ = 'Copyright 2013- cihai software foundation'
| __title__ = 'cihai'
__package_name__ = 'cihai'
__version__ = '0.9.0a3'
__description__ = 'Library for CJK (chinese, japanese, korean) language data.'
__author__ = 'Tony Narlock'
__email__ = 'tony@git-pull.com'
__github__ = 'https://github.com/cihai/cihai'
__docs__ = 'https://cihai.git-pull.com'
__tracker__ = 'https://github.com/cihai/cihai/issues'
__pypi__ = 'https://pypi.org/project/cihai/'
__license__ = 'MIT'
__copyright__ = 'Copyright 2013- cihai software foundation'
| Add tracker and doc URL to metadata | Add tracker and doc URL to metadata
| Python | mit | cihai/cihai,cihai/cihai | ---
+++
@@ -5,6 +5,8 @@
__author__ = 'Tony Narlock'
__email__ = 'tony@git-pull.com'
__github__ = 'https://github.com/cihai/cihai'
+__docs__ = 'https://cihai.git-pull.com'
+__tracker__ = 'https://github.com/cihai/cihai/issues'
__pypi__ = 'https://pypi.org/project/cihai/'
__license__ = 'MIT'
__copyright__ = 'Copyright 2013- cihai software foundation' |
d6ddc3b41040a374c61d4624e052fa8f1e58ee37 | metakernel/__init__.py | metakernel/__init__.py | from .metakernel import MetaKernel
from .process_metakernel import ProcessMetaKernel
from .magic import Magic, option
from .parser import Parser
__all__ = ['Magic', 'MetaKernel', 'option']
__version__ = '0.3'
del magic, metakernel, parser, process_metakernel
| from .metakernel import MetaKernel
import .pyexpect
from .process_metakernel import ProcessMetaKernel
from .magic import Magic, option
from .parser import Parser
__all__ = ['Magic', 'MetaKernel', 'option']
__version__ = '0.3'
del magic, metakernel, parser, process_metakernel, pyexpect
| Fix import error in Python 2 | Fix import error in Python 2
| Python | bsd-3-clause | Calysto/metakernel | ---
+++
@@ -1,4 +1,5 @@
from .metakernel import MetaKernel
+import .pyexpect
from .process_metakernel import ProcessMetaKernel
from .magic import Magic, option
from .parser import Parser
@@ -7,4 +8,4 @@
__version__ = '0.3'
-del magic, metakernel, parser, process_metakernel
+del magic, metakernel, parser, process_metakernel, pyexpect |
ec9239fda210f3d71a81045fdba9d72bab04a05b | indra/sources/drugbank/__init__.py | indra/sources/drugbank/__init__.py | """This module provides an API and processor for DrugBank content.
It builds on the XML-formatted data schema of DrugBank and expects
the XML file to be available locally. The full DrugBank download
can be obtained at: https://www.drugbank.ca/releases/latest. Once the
XML file is decompressed, it can be processed using the process_xml
function."""
from .api import get_drugbank_processor, process_xml
| """This module provides an API and processor for DrugBank content.
It builds on the XML-formatted data schema of DrugBank and expects
the XML file to be available locally. The full DrugBank download
can be obtained at: https://www.drugbank.ca/releases/latest. Once the
XML file is decompressed, it can be processed using the process_xml
function.
Alternatively, the latest DrugBank data can be automatically loaded via
:mod:`drugbank_downloader` with the following code after doing
``pip install drugbank_downloader bioversions``:
.. code-block:: python
import pickle
import indra.sources.drugbank
processor = indra.sources.drugbank.get_drugbank_processor()
with open('drugbank_indra_statements.pkl', 'wb') as file:
pickle.dump(processor.statements, file, protocol=pickle.HIGHEST_PROTOCOL)
"""
from .api import get_drugbank_processor, process_xml
| Add more docs on how to get drugbank quickly | Add more docs on how to get drugbank quickly
| Python | bsd-2-clause | sorgerlab/belpy,sorgerlab/indra,bgyori/indra,sorgerlab/indra,johnbachman/indra,bgyori/indra,sorgerlab/belpy,sorgerlab/indra,johnbachman/indra,johnbachman/indra,sorgerlab/belpy,bgyori/indra | ---
+++
@@ -3,5 +3,18 @@
the XML file to be available locally. The full DrugBank download
can be obtained at: https://www.drugbank.ca/releases/latest. Once the
XML file is decompressed, it can be processed using the process_xml
-function."""
+function.
+
+Alternatively, the latest DrugBank data can be automatically loaded via
+:mod:`drugbank_downloader` with the following code after doing
+``pip install drugbank_downloader bioversions``:
+
+.. code-block:: python
+
+ import pickle
+ import indra.sources.drugbank
+ processor = indra.sources.drugbank.get_drugbank_processor()
+ with open('drugbank_indra_statements.pkl', 'wb') as file:
+ pickle.dump(processor.statements, file, protocol=pickle.HIGHEST_PROTOCOL)
+"""
from .api import get_drugbank_processor, process_xml |
922db591ca726acae07e2628119b95aa705f414c | leetcode/ds_string_word_pattern.py | leetcode/ds_string_word_pattern.py |
# @file Word Pattern
# @brief Given 2 sets check if it is a bijection
# https://leetcode.com/problems/word-pattern/
'''
Given a pattern and a string str, find if str follows the same pattern.
Here follow means a full match, such that there is a bijection between
a letter in pattern and a non-empty word in str.
Examples:
pattern = "abba", str = "dog cat cat dog" should return true.
pattern = "abba", str = "dog cat cat fish" should return false.
pattern = "aaaa", str = "dog cat cat dog" should return false.
pattern = "abba", str = "dog dog dog dog" should return false.
Notes:
You may assume pattern contains only lowercase letters, and str contains
lowercase letters separated by a single space.
'''
|
# @file Word Pattern
# @brief Given 2 sets check if it is a bijection
# https://leetcode.com/problems/word-pattern/
'''
Given a pattern and a string str, find if str follows the same pattern.
Here follow means a full match, such that there is a bijection between
a letter in pattern and a non-empty word in str.
Examples:
pattern = "abba", str = "dog cat cat dog" should return true.
pattern = "abba", str = "dog cat cat fish" should return false.
pattern = "aaaa", str = "dog cat cat dog" should return false.
pattern = "abba", str = "dog dog dog dog" should return false.
Notes:
You may assume pattern contains only lowercase letters, and str contains
lowercase letters separated by a single space.
'''
# Approach 1:
def wordPattern(self, pattern, str):
clist = pattern #treat string as a list of chars
wlist = str.split() #split string into a list of words
# map(function, sequence): map applies the given function to every element in the sequence and returns a list
# index - finds the index of the first occurence of every element in both list and string
return map(clist.index, clist) == map(wlist.index, wlist)
# Approach 2:
def wordPattern(self, pattern, str):
clist = pattern
wlist = str.split()
# zip returns a tuple, cpupling the ith elements from both lists
return len(clist) == len(wlist) and len(set(clist)) == len(set(wlist)) == len(set(zip(clist, wlist)))
# "abba", "dog cat cat dog", True.
# "abba", "dog cat cat fish" False.
# "aaaa", "dog cat cat dog" False.
# "abba", "dog dog dog dog" False.
| Add two approaches for string word pattern | Add two approaches for string word pattern | Python | mit | ngovindaraj/Python | ---
+++
@@ -18,3 +18,22 @@
lowercase letters separated by a single space.
'''
+# Approach 1:
+def wordPattern(self, pattern, str):
+ clist = pattern #treat string as a list of chars
+ wlist = str.split() #split string into a list of words
+ # map(function, sequence): map applies the given function to every element in the sequence and returns a list
+ # index - finds the index of the first occurence of every element in both list and string
+ return map(clist.index, clist) == map(wlist.index, wlist)
+
+# Approach 2:
+def wordPattern(self, pattern, str):
+ clist = pattern
+ wlist = str.split()
+ # zip returns a tuple, cpupling the ith elements from both lists
+ return len(clist) == len(wlist) and len(set(clist)) == len(set(wlist)) == len(set(zip(clist, wlist)))
+
+# "abba", "dog cat cat dog", True.
+# "abba", "dog cat cat fish" False.
+# "aaaa", "dog cat cat dog" False.
+# "abba", "dog dog dog dog" False. |
c1f270700d9de209577b64c40b71b5f5b69c5aae | cards.py | cards.py | from pymongo import MongoClient
class Cards:
def __init__(self, dbname='cards'):
"""Instantiate this class.
Set up a connection to the given Mongo database.
Get to the collection we'll store cards in.
Args:
dbname (str): Database name.
"""
self.client = MongoClient()
self.db = self.client[dbname]
self.cards_coll = self.db['cards']
@property
def sets(self):
"""Return a list of all the card sets in the database.
Args:
None
Returns:
list: List of all card sets in the database.
"""
return self.cards_coll.distinct('set')
def retrieve_set(self, setname):
"""Return a list of all the cards in the given set.
Args:
setname (str): Name of set.
Returns:
list: List of all cards in the the given set.
"""
return list(self.cards_coll.find({'set': setname}))
def create_card(self, setname, color, text, creator):
"""Insert a new card with the given properties into the database.
Args:
setname (str): Name of set the card will belong to.
color (str): Color the card will have.
text (str): Text that will appear on the card.
creator (str): Creator to attribute the card to.
Returns:
None
"""
card = {
'set': setname,
'color': color,
'text': text,
'creator': creator,
}
self.cards_coll.insert_one(card)
| from pymongo import MongoClient
class Cards:
def __init__(self, dbname='cards'):
"""Instantiate this class.
Set up a connection to the given Mongo database.
Get to the collection we'll store cards in.
Args:
dbname (str): Database name.
"""
self.client = MongoClient()
self.db = self.client[dbname]
self.cards_coll = self.db['cards']
@property
def sets(self):
"""Return a list of all the card sets in the database.
Args:
None
Returns:
list: List of all card sets in the database.
"""
return self.cards_coll.distinct('set')
def retrieve_set(self, setname):
"""Return a list of all the cards in the given set.
Args:
setname (str): Name of set.
Returns:
list: List of all cards in the the given set.
"""
return list(self.cards_coll.find({'set': setname}))
def create_cards(self, cards):
"""Insert a new card with the given properties into the database.
Args:
cards: List of dictionaries with set, color, text, and creator keys.
Returns:
None
"""
keys = ['set', 'color', 'text', 'creator']
filtered = [ { k: card[k] for k in keys if k in card} for card in cards]
self.cards_coll.insert_many(filtered)
| Refactor create_card method to take a list of card dictionaries. Rename method accordingly. | Refactor create_card method to take a list of card dictionaries. Rename method accordingly.
| Python | isc | wwu-nosql/cards | ---
+++
@@ -37,22 +37,16 @@
"""
return list(self.cards_coll.find({'set': setname}))
- def create_card(self, setname, color, text, creator):
+ def create_cards(self, cards):
"""Insert a new card with the given properties into the database.
Args:
- setname (str): Name of set the card will belong to.
- color (str): Color the card will have.
- text (str): Text that will appear on the card.
- creator (str): Creator to attribute the card to.
+ cards: List of dictionaries with set, color, text, and creator keys.
Returns:
None
"""
- card = {
- 'set': setname,
- 'color': color,
- 'text': text,
- 'creator': creator,
- }
- self.cards_coll.insert_one(card)
+
+ keys = ['set', 'color', 'text', 'creator']
+ filtered = [ { k: card[k] for k in keys if k in card} for card in cards]
+ self.cards_coll.insert_many(filtered) |
f70b2a187c274685cb19def1b48256822b0e3f9f | tests/conftest.py | tests/conftest.py | import py
import pytest
from tests.lib.path import Path
@pytest.fixture
def tmpdir(request):
"""
Return a temporary directory path object which is unique to each test
function invocation, created as a sub directory of the base temporary
directory. The returned object is a ``tests.lib.path.Path`` object.
This is taken from pytest itself but modified to return our typical
path object instead of py.path.local.
"""
name = request.node.name
name = py.std.re.sub("[\W]", "_", name)
tmp = request.config._tmpdirhandler.mktemp(name, numbered=True)
return Path(tmp)
| import py
import pytest
from tests.lib.path import Path
from tests.lib.scripttest import PipTestEnvironment
from tests.lib.venv import VirtualEnvironment
@pytest.fixture
def tmpdir(request):
"""
Return a temporary directory path object which is unique to each test
function invocation, created as a sub directory of the base temporary
directory. The returned object is a ``tests.lib.path.Path`` object.
This is taken from pytest itself but modified to return our typical
path object instead of py.path.local.
"""
name = request.node.name
name = py.std.re.sub("[\W]", "_", name)
tmp = request.config._tmpdirhandler.mktemp(name, numbered=True)
return Path(tmp)
@pytest.fixture
def virtualenv(tmpdir):
"""
Return a virtual environment which is unique to each test function
invocation created inside of a sub directory of the test function's
temporary directory. The returned object is a
``tests.lib.venv.VirtualEnvironment`` object.
"""
return VirtualEnvironment.create(tmpdir.join(".venv"))
@pytest.fixture
def script(tmpdir, virtualenv):
"""
Return a PipTestEnvironment which is unique to each test function and
will execute all commands inside of the unique virtual environment for this
test function. The returned object is a
``tests.lib.scripttest.PipTestEnvironment``.
"""
return PipTestEnvironment(
# The base location for our test environment
tmpdir,
# Tell the Test Environment where our virtualenv is located
virtualenv=virtualenv.location,
# Do not ignore hidden files, they need to be checked as well
ignore_hidden=False,
# We are starting with an already empty directory
start_clear=False,
# We want to ensure no temporary files are left behind, so the
# PipTestEnvironment needs to capture and assert against temp
capture_temp=True,
assert_no_temp=True,
)
| Use our classes from tests.lib.* in pytest fixtures | Use our classes from tests.lib.* in pytest fixtures
| Python | mit | KarelJakubec/pip,qbdsoft/pip,alquerci/pip,nthall/pip,dstufft/pip,nthall/pip,esc/pip,blarghmatey/pip,chaoallsome/pip,wkeyword/pip,alex/pip,jmagnusson/pip,James-Firth/pip,msabramo/pip,atdaemon/pip,natefoo/pip,rouge8/pip,h4ck3rm1k3/pip,zvezdan/pip,haridsv/pip,rbtcollins/pip,Ivoz/pip,luzfcb/pip,harrisonfeng/pip,willingc/pip,qbdsoft/pip,natefoo/pip,harrisonfeng/pip,Gabriel439/pip,Gabriel439/pip,caosmo/pip,wkeyword/pip,RonnyPfannschmidt/pip,habnabit/pip,yati-sagade/pip,squidsoup/pip,squidsoup/pip,fiber-space/pip,pjdelport/pip,haridsv/pip,h4ck3rm1k3/pip,erikrose/pip,ianw/pip,techtonik/pip,benesch/pip,supriyantomaftuh/pip,atdaemon/pip,mindw/pip,nthall/pip,zorosteven/pip,rbtcollins/pip,habnabit/pip,alquerci/pip,cjerdonek/pip,tdsmith/pip,graingert/pip,squidsoup/pip,supriyantomaftuh/pip,harrisonfeng/pip,qwcode/pip,jamezpolley/pip,qwcode/pip,pradyunsg/pip,dstufft/pip,fiber-space/pip,alex/pip,rouge8/pip,pypa/pip,ncoghlan/pip,graingert/pip,Gabriel439/pip,rbtcollins/pip,fiber-space/pip,ChristopherHogan/pip,prasaianooz/pip,mattrobenolt/pip,jmagnusson/pip,RonnyPfannschmidt/pip,esc/pip,yati-sagade/pip,prasaianooz/pip,jythontools/pip,sigmavirus24/pip,chaoallsome/pip,qbdsoft/pip,minrk/pip,haridsv/pip,dstufft/pip,alex/pip,willingc/pip,ncoghlan/pip,RonnyPfannschmidt/pip,h4ck3rm1k3/pip,zvezdan/pip,patricklaw/pip,mindw/pip,jasonkying/pip,sigmavirus24/pip,mattrobenolt/pip,jythontools/pip,benesch/pip,xavfernandez/pip,supriyantomaftuh/pip,atdaemon/pip,sbidoul/pip,rouge8/pip,mujiansu/pip,mujiansu/pip,jythontools/pip,pjdelport/pip,ncoghlan/pip,blarghmatey/pip,jamezpolley/pip,patricklaw/pip,mindw/pip,sbidoul/pip,jasonkying/pip,zenlambda/pip,prasaianooz/pip,chaoallsome/pip,sigmavirus24/pip,tdsmith/pip,pjdelport/pip,Carreau/pip,graingert/pip,ChristopherHogan/pip,erikrose/pip,tdsmith/pip,zenlambda/pip,ianw/pip,pradyunsg/pip,mujiansu/pip,zorosteven/pip,davidovich/pip,techtonik/pip,benesch/pip,habnabit/pip,zvezdan/pip,pypa/pip,zorosteven/pip,yati-sagade/pip,luzfcb/pip,davidovich/pip,jmagnusson/pip,techtonik/pip,xavfernandez/pip,erikrose/pip,cjerdonek/pip,esc/pip,caosmo/pip,jamezpolley/pip,Carreau/pip,James-Firth/pip,caosmo/pip,wkeyword/pip,KarelJakubec/pip,jasonkying/pip,minrk/pip,luzfcb/pip,KarelJakubec/pip,xavfernandez/pip,Ivoz/pip,ChristopherHogan/pip,pfmoore/pip,blarghmatey/pip,pfmoore/pip,natefoo/pip,davidovich/pip,James-Firth/pip,willingc/pip,msabramo/pip,zenlambda/pip | ---
+++
@@ -2,6 +2,8 @@
import pytest
from tests.lib.path import Path
+from tests.lib.scripttest import PipTestEnvironment
+from tests.lib.venv import VirtualEnvironment
@pytest.fixture
@@ -18,3 +20,42 @@
name = py.std.re.sub("[\W]", "_", name)
tmp = request.config._tmpdirhandler.mktemp(name, numbered=True)
return Path(tmp)
+
+
+@pytest.fixture
+def virtualenv(tmpdir):
+ """
+ Return a virtual environment which is unique to each test function
+ invocation created inside of a sub directory of the test function's
+ temporary directory. The returned object is a
+ ``tests.lib.venv.VirtualEnvironment`` object.
+ """
+ return VirtualEnvironment.create(tmpdir.join(".venv"))
+
+
+@pytest.fixture
+def script(tmpdir, virtualenv):
+ """
+ Return a PipTestEnvironment which is unique to each test function and
+ will execute all commands inside of the unique virtual environment for this
+ test function. The returned object is a
+ ``tests.lib.scripttest.PipTestEnvironment``.
+ """
+ return PipTestEnvironment(
+ # The base location for our test environment
+ tmpdir,
+
+ # Tell the Test Environment where our virtualenv is located
+ virtualenv=virtualenv.location,
+
+ # Do not ignore hidden files, they need to be checked as well
+ ignore_hidden=False,
+
+ # We are starting with an already empty directory
+ start_clear=False,
+
+ # We want to ensure no temporary files are left behind, so the
+ # PipTestEnvironment needs to capture and assert against temp
+ capture_temp=True,
+ assert_no_temp=True,
+ ) |
ff3123e21e366a5908655dbd8130ac60ec5eee10 | uvt_user/utils.py | uvt_user/utils.py | from __future__ import unicode_literals
import re
from ldap3 import Server, Connection
class LDAPError(Exception):
pass
def search_ldap(username):
'''Searches the Tilburg University LDAP server for the given username and returns a tuple of first name, last name, full name, ANR, emplId and email address. Permission has been granted by TiU's legal department for retrieving this data. Raises LDAPError on any kind of error.'''
result = ()
baseDN = "o=Universiteit van Tilburg,c=NL"
searchFilter = '(uid={})'.format(username)
attributes = ['givenName', 'sortableSurname', 'cn', 'employeeNumber', 'emplId', 'mail']
try:
server = Server('ldaps.uvt.nl', use_ssl=True)
conn = Connection(server, auto_bind=True)
conn.search(baseDN, searchFilter, attributes=attributes)
response = conn.response[0]['attributes']
for a in attributes:
if a in response:
result += (response[a][0],)
else:
result += ('',)
except IndexError:
raise LDAPError('Username not found')
except Exception:
raise LDAPError('Unknown error in LDAP query')
return result
| from __future__ import unicode_literals
import re
from ldap3 import Server, Connection
class LDAPError(Exception):
pass
def search_ldap(username):
'''Searches the Tilburg University LDAP server for the given username and returns a tuple of first name, last name, full name, ANR, emplId and email address. Permission has been granted by TiU's legal department for retrieving this data. Raises LDAPError on any kind of error.'''
result = ()
baseDN = "o=Universiteit van Tilburg,c=NL"
searchFilter = '(uid={})'.format(username)
attributes = ['givenName', 'sortableSurname', 'cn', 'employeeNumber', 'emplId', 'mail']
try:
server = Server('ldaps.uvt.nl', use_ssl=True)
conn = Connection(server, auto_bind=True)
conn.search(baseDN, searchFilter, attributes=attributes)
response = conn.response[0]['attributes']
for a in attributes:
if a in response and response[a]:
if type(response[a]) is list:
result += (response[a][0],)
else:
result += (response[a],)
else:
result += ('',)
except IndexError:
raise LDAPError('Username not found')
except Exception:
raise LDAPError('Unknown error in LDAP query')
return result
| Fix potential bug in case LDAP does not return lists | Fix potential bug in case LDAP does not return lists
| Python | agpl-3.0 | JaapJoris/bps,JaapJoris/bps | ---
+++
@@ -20,8 +20,11 @@
conn.search(baseDN, searchFilter, attributes=attributes)
response = conn.response[0]['attributes']
for a in attributes:
- if a in response:
- result += (response[a][0],)
+ if a in response and response[a]:
+ if type(response[a]) is list:
+ result += (response[a][0],)
+ else:
+ result += (response[a],)
else:
result += ('',)
except IndexError: |
32dae9d8af362c5ec00af069d70272a125aa02c5 | firmata/__init__.py | firmata/__init__.py | """Provides an API wrapper around the Firmata wire protocol.
There are two major pieces to the firmata module. When FirmataInit() is called, a thread is spun up to handle serial
port IO. Its sole function is to read bytes into the read queue and write bytes from the write queue. These queues are
then used by the main body of code to respond to API calls made by the host application.
The API presented to the host program is encapsulated in the `Board` class, instances of which are obtained by calling
the previously mentioned `FirmataInit()` function. You can create as many Board classes as you wish, but you will not
go to space today if you create more than on on the same serial port.
"""
from Queue import Queue, Empty
import serial
import threading
from firmata.constants import *
IO_TIMEOUT = 0.2 # Number of seconds to block on IO. Set to None for infinite timeout.
BYTES_IN_CHUNK = 100
class _IOThread(threading.Thread):
def __init__(self, port, baud):
self._port = port
self._baud = baud
self.shutdown = False
self.from_board = Queue()
self.to_board = Queue()
super(_IOThread, self).__init__()
def run(self):
serial_port = serial.Serial(port=self._port, baudrate=self._baud, timeout=0.2)
while not self.shutdown:
r = serial_port.read(BYTES_IN_CHUNK)
[self.from_board.put(i) for i in r]
bytes_written = 0
while not self.to_board.empty() and bytes_written < BYTES_IN_CHUNK:
try:
w = self.to_board.get(block=False)
serial_port.write(w)
self.to_board.task_done()
bytes_written += 1
except Empty:
break
class Board(object):
def __init__(self, port, baud, start_serial=False):
"""Board object constructor. Should not be called directly.
Args:
port: The serial port to use. Expressed as either a string or an integer (see pyserial docs for more info.)
baud: A number representing the baud rate to use for serial communication.
start_serial: If True, starts the serial IO thread right away. Default: False.
"""
self._io_thread = _IOThread(port, baud)
if start_serial:
self._io_thread.start()
self._out = self._io_thread.to_board
self._in = self._io_thread.from_board
def FirmataInit(port, baud=57600):
"""Instantiate a `Board` object for a given serial port.
Args:
port: The serial port to use. Expressed as either a string or an integer (see pyserial docs for more info.)
baud: A number representing the baud rate to use for serial communication.
Returns:
A Board object which implements the firmata protocol over the specified serial port.
"""
return Board(port, baud, start_serial=True)
| Add basic skeleton of the library, including the implementation of the IO thread system. | Add basic skeleton of the library, including the implementation of the IO thread system.
| Python | apache-2.0 | google/firmata.py | ---
+++
@@ -0,0 +1,70 @@
+"""Provides an API wrapper around the Firmata wire protocol.
+
+There are two major pieces to the firmata module. When FirmataInit() is called, a thread is spun up to handle serial
+port IO. Its sole function is to read bytes into the read queue and write bytes from the write queue. These queues are
+then used by the main body of code to respond to API calls made by the host application.
+
+The API presented to the host program is encapsulated in the `Board` class, instances of which are obtained by calling
+the previously mentioned `FirmataInit()` function. You can create as many Board classes as you wish, but you will not
+go to space today if you create more than on on the same serial port.
+"""
+
+from Queue import Queue, Empty
+import serial
+import threading
+
+from firmata.constants import *
+
+IO_TIMEOUT = 0.2 # Number of seconds to block on IO. Set to None for infinite timeout.
+BYTES_IN_CHUNK = 100
+
+class _IOThread(threading.Thread):
+ def __init__(self, port, baud):
+ self._port = port
+ self._baud = baud
+ self.shutdown = False
+ self.from_board = Queue()
+ self.to_board = Queue()
+ super(_IOThread, self).__init__()
+
+ def run(self):
+ serial_port = serial.Serial(port=self._port, baudrate=self._baud, timeout=0.2)
+ while not self.shutdown:
+ r = serial_port.read(BYTES_IN_CHUNK)
+ [self.from_board.put(i) for i in r]
+ bytes_written = 0
+ while not self.to_board.empty() and bytes_written < BYTES_IN_CHUNK:
+ try:
+ w = self.to_board.get(block=False)
+ serial_port.write(w)
+ self.to_board.task_done()
+ bytes_written += 1
+ except Empty:
+ break
+
+class Board(object):
+ def __init__(self, port, baud, start_serial=False):
+ """Board object constructor. Should not be called directly.
+
+ Args:
+ port: The serial port to use. Expressed as either a string or an integer (see pyserial docs for more info.)
+ baud: A number representing the baud rate to use for serial communication.
+ start_serial: If True, starts the serial IO thread right away. Default: False.
+ """
+ self._io_thread = _IOThread(port, baud)
+ if start_serial:
+ self._io_thread.start()
+ self._out = self._io_thread.to_board
+ self._in = self._io_thread.from_board
+
+def FirmataInit(port, baud=57600):
+ """Instantiate a `Board` object for a given serial port.
+
+ Args:
+ port: The serial port to use. Expressed as either a string or an integer (see pyserial docs for more info.)
+ baud: A number representing the baud rate to use for serial communication.
+
+ Returns:
+ A Board object which implements the firmata protocol over the specified serial port.
+ """
+ return Board(port, baud, start_serial=True) | |
a7622fc3d996407799cec166968c1e56baf07ea9 | wqflask/wqflask/markdown_routes.py | wqflask/wqflask/markdown_routes.py | """Markdown routes
Render pages from github, or if they are unavailable, look for it else where
"""
import requests
import mistune
from flask import Blueprint
from flask import render_template
glossary_blueprint = Blueprint('glossary_blueprint', __name__)
@glossary_blueprint.route('/')
def glossary():
markdown_url = ("https://raw.githubusercontent.com"
"/genenetwork/genenetwork2/"
"wqflask/wqflask/static"
"/glossary.md")
md_content = requests.get(markdown_url)
if md_content.status_code == 200:
return render_template(
"glossary_html",
rendered_markdown=mistune.html(
md_content.content.decode("utf-8"))), 200
return render_template(
"glossary.html",
rendered_markdown=mistune.html("# Github Down!")), 200
| """Markdown routes
Render pages from github, or if they are unavailable, look for it else where
"""
import os
import requests
import mistune
from flask import Blueprint
from flask import render_template
glossary_blueprint = Blueprint('glossary_blueprint', __name__)
def render_markdown(file_name):
"""Try to fetch the file name from Github and if that fails, try to
look for it inside the file system
"""
markdown_url = (f"https://raw.githubusercontent.com"
f"/genenetwork/genenetwork2/"
f"wqflask/wqflask/static/"
f"{file_name}")
md_content = requests.get(markdown_url)
if md_content.status_code == 200:
return mistune.html(md_content.content.decode("utf-8"))
with open(os.path.join(os.path.abspath(os.path.dirname(__file__)),
f"static/markdown/{file_name}")) as md_file:
markdown = md_file.read()
return mistune.html(markdown)
@glossary_blueprint.route('/')
def glossary():
return render_template(
"glossary.html",
rendered_markdown=render_markdown("glossary.md")), 200
| Move logic for fetching md files to it's own function | Move logic for fetching md files to it's own function
* wqflask/wqflask/markdown_routes.py
(render_markdown): New function.
(glossary): use render_markdown function.
| Python | agpl-3.0 | genenetwork/genenetwork2,zsloan/genenetwork2,zsloan/genenetwork2,genenetwork/genenetwork2,genenetwork/genenetwork2,genenetwork/genenetwork2,pjotrp/genenetwork2,pjotrp/genenetwork2,zsloan/genenetwork2,pjotrp/genenetwork2,pjotrp/genenetwork2,pjotrp/genenetwork2,zsloan/genenetwork2 | ---
+++
@@ -2,6 +2,7 @@
Render pages from github, or if they are unavailable, look for it else where
"""
+import os
import requests
import mistune
@@ -11,19 +12,27 @@
glossary_blueprint = Blueprint('glossary_blueprint', __name__)
+def render_markdown(file_name):
+ """Try to fetch the file name from Github and if that fails, try to
+look for it inside the file system
+
+ """
+ markdown_url = (f"https://raw.githubusercontent.com"
+ f"/genenetwork/genenetwork2/"
+ f"wqflask/wqflask/static/"
+ f"{file_name}")
+ md_content = requests.get(markdown_url)
+ if md_content.status_code == 200:
+ return mistune.html(md_content.content.decode("utf-8"))
+
+ with open(os.path.join(os.path.abspath(os.path.dirname(__file__)),
+ f"static/markdown/{file_name}")) as md_file:
+ markdown = md_file.read()
+ return mistune.html(markdown)
+
+
@glossary_blueprint.route('/')
def glossary():
- markdown_url = ("https://raw.githubusercontent.com"
- "/genenetwork/genenetwork2/"
- "wqflask/wqflask/static"
- "/glossary.md")
- md_content = requests.get(markdown_url)
- if md_content.status_code == 200:
- return render_template(
- "glossary_html",
- rendered_markdown=mistune.html(
- md_content.content.decode("utf-8"))), 200
-
return render_template(
"glossary.html",
- rendered_markdown=mistune.html("# Github Down!")), 200
+ rendered_markdown=render_markdown("glossary.md")), 200 |
1abfdea38e868d68c532961459d2b4cbef5a9b71 | src/zeit/website/section.py | src/zeit/website/section.py | import zeit.website.interfaces
from zeit.cms.section.interfaces import ISectionMarker
import grokcore.component as grok
import zeit.cms.checkout.interfaces
import zeit.cms.content.interfaces
import zope.interface
@grok.subscribe(
zeit.cms.content.interfaces.ICommonMetadata,
zeit.cms.checkout.interfaces.IBeforeCheckinEvent)
def provide_website_content(content, event):
content = zope.security.proxy.getObject(content)
if not content.rebrush_website_content:
return
for iface in zope.interface.providedBy(content):
if issubclass(iface, ISectionMarker):
zope.interface.noLongerProvides(content, iface)
zope.interface.alsoProvides(content, zeit.website.interfaces.IWebsiteSection)
| import zeit.website.interfaces
from zeit.cms.section.interfaces import ISectionMarker
import grokcore.component as grok
import zeit.cms.checkout.interfaces
import zeit.cms.content.interfaces
import zope.interface
@grok.subscribe(
zeit.cms.content.interfaces.ICommonMetadata,
zeit.cms.checkout.interfaces.IBeforeCheckinEvent)
def provide_website_content(content, event):
content = zope.security.proxy.getObject(content)
if not content.rebrush_website_content:
zope.interface.noLongerProvides(content,
zeit.website.interfaces.IWebsiteSection)
return
for iface in zope.interface.providedBy(content):
if issubclass(iface, ISectionMarker):
zope.interface.noLongerProvides(content, iface)
zope.interface.alsoProvides(content, zeit.website.interfaces.IWebsiteSection)
| Remove iface, if rebrush_contetn ist not set | Remove iface, if rebrush_contetn ist not set
| Python | bsd-3-clause | ZeitOnline/zeit.website | ---
+++
@@ -12,6 +12,8 @@
def provide_website_content(content, event):
content = zope.security.proxy.getObject(content)
if not content.rebrush_website_content:
+ zope.interface.noLongerProvides(content,
+ zeit.website.interfaces.IWebsiteSection)
return
for iface in zope.interface.providedBy(content):
if issubclass(iface, ISectionMarker): |
358f31fcc8155e15f28f77aee6b434fad2a54935 | iris_sdk/models/import_tn_checker.py | iris_sdk/models/import_tn_checker.py | #!/usr/bin/env python
from __future__ import division, absolute_import, print_function
from future.builtins import super
from iris_sdk.models.base_resource import BaseResource
from iris_sdk.models.data.import_tn_checker import ImportTnCheckerData
from iris_sdk.models.import_tn_checker_response import ImportTnCheckerResponse
XML_NAME_IMPORTTN_CHECKER = "ImportTnCheckerPayload"
XPATH_IMPORTTN_CHECKER = "/importTnChecker"
class ImportTnChecker(BaseResource, ImportTnCheckerData):
"""Request portability information for hosted messaging on a set of TNs"""
_save_post = True
_node_name = XML_NAME_IMPORTTN_CHECKER
_xpath = XPATH_IMPORTTN_CHECKER
def __call__(self, numbers):
# self.clear()
self.telephone_numbers.items.extend(numbers)
return self._post_data(ImportTnCheckerResponse())
def __init__(self, parent=None, client=None):
super().__init__(parent, client)
ImportTnCheckerData.__init__(self)
| #!/usr/bin/env python
from __future__ import division, absolute_import, print_function
from future.builtins import super
from iris_sdk.models.base_resource import BaseResource
from iris_sdk.models.data.import_tn_checker import ImportTnCheckerData
from iris_sdk.models.import_tn_checker_response import ImportTnCheckerResponse
XML_NAME_IMPORTTN_CHECKER = "ImportTnCheckerPayload"
XPATH_IMPORTTN_CHECKER = "/importTnChecker"
class ImportTnChecker(BaseResource, ImportTnCheckerData):
"""Request portability information for hosted messaging on a set of TNs"""
_save_post = True
_node_name = XML_NAME_IMPORTTN_CHECKER
_xpath = XPATH_IMPORTTN_CHECKER
def __call__(self, numbers):
self.clear()
self.telephone_numbers.items.extend(numbers)
return self._post_data(ImportTnCheckerResponse())
def __init__(self, parent=None, client=None):
super().__init__(parent, client)
ImportTnCheckerData.__init__(self)
| Reset the ImportTnChecker on every call | Reset the ImportTnChecker on every call
The list of phone numbers was being retained, potentially resulting in
duplicates with every call.
| Python | mit | bandwidthcom/python-bandwidth-iris | ---
+++
@@ -18,7 +18,7 @@
_xpath = XPATH_IMPORTTN_CHECKER
def __call__(self, numbers):
- # self.clear()
+ self.clear()
self.telephone_numbers.items.extend(numbers)
return self._post_data(ImportTnCheckerResponse())
|
533d6294a47a4a974dfda1743e9fcd6146ede27f | codonpdx/insert.py | codonpdx/insert.py | #!/usr/bin/env python
import json
import sys
from db import dbManager
# insert an organism into a database table
def insert(args):
if args.json:
data = json.loads(args.json)
else:
data = json.load(args.infile)
with dbManager('config/db.cfg') as db:
for org in data:
db.insertOrganism(org, args.dbname, args.job)
return data
| #!/usr/bin/env python
import json
import sys
from db import dbManager
# insert an organism into a database table
def insert(args):
if hasattr(args, 'json'):
data = json.loads(args.json)
else:
data = json.load(args.infile)
with dbManager('config/db.cfg') as db:
for org in data:
db.insertOrganism(org, args.dbname, args.job)
return data
| Fix testing for JSON parameter existence. | Fix testing for JSON parameter existence.
| Python | apache-2.0 | PDX-Flamingo/codonpdx-python,PDX-Flamingo/codonpdx-python | ---
+++
@@ -7,7 +7,7 @@
# insert an organism into a database table
def insert(args):
- if args.json:
+ if hasattr(args, 'json'):
data = json.loads(args.json)
else:
data = json.load(args.infile) |
215c6d714df53f6f52f2bf819f2a01f1c1eab294 | learntris.py | learntris.py | #!/usr/bin/env python
import sys
class Grid(object):
def __init__(self):
self.board = ['. '*10 for row in range(0,22)]
self.score = 0
self.lines_clear = 0
def draw_board(self):
for cell in self.board:
print cell
def given(self):
self.board = []
for row in range(0,22):
self.board.append(raw_input())
def clear(self):
self.board = ['. '*10 for row in range(0,22)]
def show_score(self):
print self.score
def show_clear_lines(self):
print self.lines_clear
def main():
grid = Grid()
commands = {'p': grid.draw_board,
'g': grid.given,
'c': grid.clear,
'?s': grid.show_score,
'?n': grid.show_clear_lines}
while True:
command = raw_input()
if command == 'q':
break
commands[command]()
if __name__ == '__main__':
main() | #!/usr/bin/env python
import sys
class Grid(object):
def __init__(self):
self.board = [[None] * 10 for i in range(22)]
self.score = 0
self.lines_clear = 0
def draw_board(self):
current_board = self.board
for row in current_board:
row = map(lambda cell: '.' if cell == None else y, row)
print ' '.join(row)
def given(self):
self.board = []
for row in range(0,22):
self.board.append(raw_input())
def clear(self):
self.board = ['. '*10 for row in range(0,22)]
def show_score(self):
print self.score
def show_clear_lines(self):
print self.lines_clear
def main():
grid = Grid()
commands = {'p': grid.draw_board,
'g': grid.given,
'c': grid.clear,
'?s': grid.show_score,
'?n': grid.show_clear_lines}
while True:
command = raw_input()
if command == 'q':
break
commands[command]()
if __name__ == '__main__':
main() | Change data structure to multidimensional array Now passing Test 2 | Change data structure to multidimensional array
Now passing Test 2
| Python | mit | mosegontar/learntris | ---
+++
@@ -5,14 +5,17 @@
class Grid(object):
def __init__(self):
- self.board = ['. '*10 for row in range(0,22)]
+ self.board = [[None] * 10 for i in range(22)]
self.score = 0
self.lines_clear = 0
def draw_board(self):
- for cell in self.board:
- print cell
+ current_board = self.board
+
+ for row in current_board:
+ row = map(lambda cell: '.' if cell == None else y, row)
+ print ' '.join(row)
def given(self):
self.board = []
@@ -39,10 +42,11 @@
'?n': grid.show_clear_lines}
while True:
- command = raw_input()
+ command = raw_input()
if command == 'q':
break
commands[command]()
+
if __name__ == '__main__': |
73e28db67c8e2ea897790844dd3eb65e6c4c5c98 | extensions/rules/coord_two_dim.py | extensions/rules/coord_two_dim.py | # coding: utf-8
#
# Copyright 2014 The Oppia Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softwar
# 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.
"""Rules for CoordTwoDim objects."""
__author__ = 'Sean Lip'
from extensions.rules import base
class Within(base.CoordTwoDimRule):
description = 'is within {{d|Real}} km of {{p|CoordTwoDim}}'
class NotWithin(base.CoordTwoDimRule):
description = 'is not within {{d|Real}} km of {{p|CoordTwoDim}}'
class FuzzyMatches(base.CoordTwoDimRule):
description = 'is similar to {{training_data|ListOfCoordTwoDim}}'
| # coding: utf-8
#
# Copyright 2014 The Oppia Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softwar
# 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.
"""Rules for CoordTwoDim objects."""
__author__ = 'Sean Lip'
from extensions.rules import base
class Within(base.CoordTwoDimRule):
description = 'is within {{d|Real}} km of {{p|CoordTwoDim}}'
class NotWithin(base.CoordTwoDimRule):
description = 'is not within {{d|Real}} km of {{p|CoordTwoDim}}'
class FuzzyMatches(base.CoordTwoDimRule):
description = 'is similar to {{training_data|ListOfCoordTwoDim}}'
# TODO(wxy): Create a better classifier for this interaction. Currently,
# the frontend implementation of this rule returns a booleen value,
# checking if the answer is close to any point in the training data.
# If this fails, the answer should then go to a backend classifier that
# picks the answer group with the best matching answer group.
| Add TODO for interactive map classifier | Add TODO for interactive map classifier
| Python | apache-2.0 | zgchizi/oppia-uc,kevinlee12/oppia,michaelWagner/oppia,oppia/oppia,kennho/oppia,jestapinski/oppia,prasanna08/oppia,prasanna08/oppia,amitdeutsch/oppia,DewarM/oppia,kingctan/oppia,rackstar17/oppia,sdulal/oppia,zgchizi/oppia-uc,prasanna08/oppia,kennho/oppia,prasanna08/oppia,AllanYangZhou/oppia,souravbadami/oppia,AllanYangZhou/oppia,sbhowmik89/oppia,oppia/oppia,jestapinski/oppia,terrameijar/oppia,sbhowmik89/oppia,himanshu-dixit/oppia,MAKOSCAFEE/oppia,kennho/oppia,sdulal/oppia,DewarM/oppia,brianrodri/oppia,raju249/oppia,MAKOSCAFEE/oppia,amitdeutsch/oppia,AllanYangZhou/oppia,himanshu-dixit/oppia,bjvoth/oppia,michaelWagner/oppia,amitdeutsch/oppia,mit0110/oppia,mit0110/oppia,zgchizi/oppia-uc,anthkris/oppia,sdulal/oppia,michaelWagner/oppia,sbhowmik89/oppia,kingctan/oppia,edallison/oppia,amgowano/oppia,bjvoth/oppia,kevinlee12/oppia,anggorodewanto/oppia,jestapinski/oppia,brianrodri/oppia,souravbadami/oppia,sbhowmik89/oppia,oppia/oppia,MaximLich/oppia,DewarM/oppia,raju249/oppia,shaz13/oppia,bjvoth/oppia,oppia/oppia,rackstar17/oppia,rackstar17/oppia,kingctan/oppia,kevinlee12/oppia,anggorodewanto/oppia,MaximLich/oppia,DewarM/oppia,mit0110/oppia,MaximLich/oppia,zgchizi/oppia-uc,souravbadami/oppia,rackstar17/oppia,prasanna08/oppia,kennho/oppia,amgowano/oppia,kevinlee12/oppia,sbhowmik89/oppia,amgowano/oppia,souravbadami/oppia,sdulal/oppia,amitdeutsch/oppia,bjvoth/oppia,edallison/oppia,anggorodewanto/oppia,edallison/oppia,anthkris/oppia,MAKOSCAFEE/oppia,bjvoth/oppia,brianrodri/oppia,terrameijar/oppia,souravbadami/oppia,anggorodewanto/oppia,kennho/oppia,anthkris/oppia,brianrodri/oppia,MaximLich/oppia,terrameijar/oppia,oppia/oppia,himanshu-dixit/oppia,raju249/oppia,jestapinski/oppia,mit0110/oppia,AllanYangZhou/oppia,terrameijar/oppia,anthkris/oppia,amgowano/oppia,michaelWagner/oppia,brianrodri/oppia,edallison/oppia,michaelWagner/oppia,amitdeutsch/oppia,kevinlee12/oppia,sdulal/oppia,kingctan/oppia,mit0110/oppia,shaz13/oppia,himanshu-dixit/oppia,shaz13/oppia,raju249/oppia,kingctan/oppia,shaz13/oppia,DewarM/oppia,MAKOSCAFEE/oppia | ---
+++
@@ -31,3 +31,8 @@
class FuzzyMatches(base.CoordTwoDimRule):
description = 'is similar to {{training_data|ListOfCoordTwoDim}}'
+ # TODO(wxy): Create a better classifier for this interaction. Currently,
+ # the frontend implementation of this rule returns a booleen value,
+ # checking if the answer is close to any point in the training data.
+ # If this fails, the answer should then go to a backend classifier that
+ # picks the answer group with the best matching answer group. |
ba745d03c11d7478c4da5a68246ec9d461077365 | experiments/rnnencdec/__init__.py | experiments/rnnencdec/__init__.py | from encdec import RNNEncoderDecoder
from encdec import get_batch_iterator
from encdec import parse_input
from encdec import create_padded_batch
from state import prototype_state
from state import prototype_search_state
from state import prototype_sentence_state
from state import prototype_autoenc_state
from state import prototype_phrase_en_zn_state
from state import prototype_de2en_state
| from encdec import RNNEncoderDecoder
from encdec import get_batch_iterator
from encdec import parse_input
from encdec import create_padded_batch
from state import prototype_state
from state import prototype_search_state
from state import prototype_sentence_state
| Remove states that do not exist anymore | Remove states that do not exist anymore
| Python | bsd-3-clause | sebastien-j/LV_groundhog,ZenDevelopmentSystems/GroundHog,kyunghyuncho/GroundHog,dmitriy-serdyuk/EncDecASR,OlafLee/LV_groundhog,ZenDevelopmentSystems/GroundHog,sebastien-j/LV_groundhog,lisa-groundhog/GroundHog,vseledkin/LV_groundhog,vseledkin/LV_groundhog,zerkh/GroundHog,hezhenghao/GroundHog,zerkh/GroundHog,OlafLee/LV_groundhog,kyunghyuncho/GroundHog,ZhangAustin/GroundHog,vseledkin/LV_groundhog,ZhangAustin/GroundHog,zerkh/GroundHog,lisa-groundhog/GroundHog,hezhenghao/GroundHog,dmitriy-serdyuk/EncDecASR,OlafLee/LV_groundhog,kyunghyuncho/GroundHog,lisa-groundhog/GroundHog,ronuchit/GroundHog,ZhangAustin/GroundHog,ZenDevelopmentSystems/GroundHog,sebastien-j/LV_groundhog,kyunghyuncho/GroundHog,sebastien-j/LV_groundhog,OlafLee/LV_groundhog,zerkh/GroundHog,vseledkin/LV_groundhog,vseledkin/LV_groundhog,OlafLee/LV_groundhog,ronuchit/GroundHog,hezhenghao/GroundHog,vseledkin/LV_groundhog,dmitriy-serdyuk/EncDecASR,ronuchit/GroundHog,sebastien-j/LV_groundhog,ronuchit/GroundHog,ronuchit/GroundHog,dmitriy-serdyuk/EncDecASR,kyunghyuncho/GroundHog,hezhenghao/GroundHog,lisa-groundhog/GroundHog,OlafLee/LV_groundhog,zerkh/GroundHog,ZhangAustin/GroundHog,sebastien-j/LV_groundhog,hezhenghao/GroundHog,ZenDevelopmentSystems/GroundHog,lisa-groundhog/GroundHog,ZenDevelopmentSystems/GroundHog | ---
+++
@@ -6,6 +6,3 @@
from state import prototype_state
from state import prototype_search_state
from state import prototype_sentence_state
-from state import prototype_autoenc_state
-from state import prototype_phrase_en_zn_state
-from state import prototype_de2en_state |
befe47c35c68e17231e21febbf52041f245b8985 | django_mailer/managers.py | django_mailer/managers.py | from django.db import models
from django_mailer import constants
class QueueManager(models.Manager):
use_for_related_fields = True
def high_priority(self):
"""
Return a QuerySet of high priority queued messages.
"""
return self.filter(priority=constants.PRIORITY_HIGH)
def normal_priority(self):
"""
Return a QuerySet of normal priority queued messages.
"""
return self.filter(priority=constants.PRIORITY_NORMAL)
def low_priority(self):
"""
Return a QuerySet of low priority queued messages.
"""
return self.filter(priority=constants.PRIORITY_LOW)
def non_deferred(self):
"""
Return a QuerySet containing all non-deferred queued messages.
"""
return self.filter(deferred=False)
def deferred(self):
"""
Return a QuerySet of all deferred messages in the queue.
"""
return self.filter(deferred=True)
def retry_deferred(self, new_priority=None):
"""
Reset the deferred flag for all deferred messages so they will be
retried.
"""
count = self.deferred().count()
update_kwargs = dict(deferred=False)
if new_priority is not None:
update_kwargs['priority'] = new_priority
self.deferred().update(**update_kwargs)
return count
| from django.db import models
from django_mailer import constants
class QueueManager(models.Manager):
use_for_related_fields = True
def high_priority(self):
"""
Return a QuerySet of high priority queued messages.
"""
return self.filter(priority=constants.PRIORITY_HIGH)
def normal_priority(self):
"""
Return a QuerySet of normal priority queued messages.
"""
return self.filter(priority=constants.PRIORITY_NORMAL)
def low_priority(self):
"""
Return a QuerySet of low priority queued messages.
"""
return self.filter(priority=constants.PRIORITY_LOW)
def non_deferred(self):
"""
Return a QuerySet containing all non-deferred queued messages.
"""
return self.filter(deferred=False)
def deferred(self):
"""
Return a QuerySet of all deferred messages in the queue.
"""
return self.filter(deferred=True)
def retry_deferred(self, new_priority=None):
"""
Reset the deferred flag for all deferred messages so they will be
retried.
"""
count = self.deferred().count()
update_kwargs = dict(deferred=False, retries=models.F('retries')+1)
if new_priority is not None:
update_kwargs['priority'] = new_priority
self.deferred().update(**update_kwargs)
return count
| Update the retries count of a queued message when it is changed back from deferred | Update the retries count of a queued message when it is changed back from deferred
| Python | mit | APSL/django-mailer-2,Giftovus/django-mailer-2,davidmarble/django-mailer-2,SmileyChris/django-mailer-2,kvh/django-mailer-2,maykinmedia/django-mailer-2,PSyton/django-mailer-2,APSL/django-mailer-2,colinhowe/django-mailer-2,rofrankel/django-mailer-2,maykinmedia/django-mailer-2,APSL/django-mailer-2,GreenLightGo/django-mailer-2,morenopc/django-mailer-2,shn/django-mailer-2,maykinmedia/django-mailer-2,mfwarren/django-mailer-2,mrbox/django-mailer-2,tachang/django-mailer-2,damkop/django-mailer-2,danfairs/django-mailer-2,tclancy/django-mailer-2,tsanders-kalloop/django-mailer-2,fenginx/django-mailer-2,victorfontes/django-mailer-2,k1000/django-mailer-2,pegler/django-mailer-2,torchbox/django-mailer-2 | ---
+++
@@ -47,7 +47,7 @@
"""
count = self.deferred().count()
- update_kwargs = dict(deferred=False)
+ update_kwargs = dict(deferred=False, retries=models.F('retries')+1)
if new_priority is not None:
update_kwargs['priority'] = new_priority
self.deferred().update(**update_kwargs) |
53a38a716c01cfd15bc1aff89c6c7908a5218bfb | integration_tests/experiment_type.py | integration_tests/experiment_type.py | from enum import unique, IntEnum
@unique
class ExperimentType(IntEnum):
Detumbling = 1
EraseFlash = 2
SunS = 3
LEOP = 4
RadFET = 5
SADS = 6
Sail = 7
Fibo = 8
Payload = 9
Camera = 10
@unique
class StartResult(IntEnum):
Success = 0
Failure = 1
@unique
class IterationResult(IntEnum):
Finished = 0
LoopImmediately = 1
WaitForNextCycle = 2,
Failure = 3
| from enum import unique, IntEnum
@unique
class ExperimentType(IntEnum):
Detumbling = 1
EraseFlash = 2
SunS = 3
LEOP = 4
RadFET = 5
SADS = 6
Sail = 7
Fibo = 8
Payload = 9
Camera = 10
@unique
class StartResult(IntEnum):
Success = 0
Failure = 1
@unique
class IterationResult(IntEnum):
NoResult = 0
Finished = 1
LoopImmediately = 2
WaitForNextCycle = 3
Failure = 4
| Fix python projection of experiment iteration result enumeration. | Fix python projection of experiment iteration result enumeration.
| Python | agpl-3.0 | PW-Sat2/PWSat2OBC,PW-Sat2/PWSat2OBC,PW-Sat2/PWSat2OBC,PW-Sat2/PWSat2OBC | ---
+++
@@ -23,7 +23,8 @@
@unique
class IterationResult(IntEnum):
- Finished = 0
- LoopImmediately = 1
- WaitForNextCycle = 2,
- Failure = 3
+ NoResult = 0
+ Finished = 1
+ LoopImmediately = 2
+ WaitForNextCycle = 3
+ Failure = 4 |
31212104810f6c700ccc9561ac3d355b1894ef47 | glimpse/__init__.py | glimpse/__init__.py | """
Hierarchical visual models in C++ and Python
============================================
The Glimpse project is a library for implementing hierarchical visual models
in C++ and Python. The goal of this project is to allow a broad range of
feed-forward, hierarchical models to be encoded in a high-level declarative
manner, with low-level details of the implementation hidden from view. This
project combines an efficient implementation with the ability to leverage
parallel processing facilities and is designed to run on multiple operating
systems using only common, freely-available components.
See http://pythonhosted.org/glimpse/ for complete documentation.
"""
import sys
__version__ = '0.2.1'
| """
Hierarchical visual models in C++ and Python
============================================
The Glimpse project is a library for implementing hierarchical visual models
in C++ and Python. The goal of this project is to allow a broad range of
feed-forward, hierarchical models to be encoded in a high-level declarative
manner, with low-level details of the implementation hidden from view. This
project combines an efficient implementation with the ability to leverage
parallel processing facilities and is designed to run on multiple operating
systems using only common, freely-available components.
See http://pythonhosted.org/glimpse/ for complete documentation.
"""
import sys
__version__ = '0.2.1'
import glimpse.util.pil_fix # workaround PIL error on OS X
| Fix PIL bug on OS X. | Fix PIL bug on OS X.
| Python | mit | mthomure/glimpse-project,mthomure/glimpse-project,mthomure/glimpse-project | ---
+++
@@ -15,3 +15,5 @@
"""
import sys
__version__ = '0.2.1'
+
+import glimpse.util.pil_fix # workaround PIL error on OS X |
ce85550a4bf080e629fbf1443d31a5305c0e0ac3 | IPython/utils/tests/test_tempdir.py | IPython/utils/tests/test_tempdir.py | #-----------------------------------------------------------------------------
# Copyright (C) 2012- The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------
import os
from IPython.utils.tempdir import NamedFileInTemporaryDirectory
def test_named_file_in_temporary_directory():
with NamedFileInTemporaryDirectory('filename') as file:
name = file.name
assert not file.closed
assert os.path.exists(name)
file.write('test')
assert file.closed
assert not os.path.exists(name)
| #-----------------------------------------------------------------------------
# Copyright (C) 2012- The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------
import os
from IPython.utils.tempdir import NamedFileInTemporaryDirectory
def test_named_file_in_temporary_directory():
with NamedFileInTemporaryDirectory('filename') as file:
name = file.name
assert not file.closed
assert os.path.exists(name)
file.write(b'test')
assert file.closed
assert not os.path.exists(name)
| Fix failing test in Python 3 | Fix failing test in Python 3
| Python | bsd-3-clause | ipython/ipython,ipython/ipython | ---
+++
@@ -15,6 +15,6 @@
name = file.name
assert not file.closed
assert os.path.exists(name)
- file.write('test')
+ file.write(b'test')
assert file.closed
assert not os.path.exists(name) |
bf7f726821f2ac74e99fd5fd06729ea2becab0c9 | ModuleInterface.py | ModuleInterface.py | import GlobalVars
class ModuleInterface(object):
triggers = []
acceptedTypes = ['PRIVMSG']
help = '<no help defined (yet)>'
def __init__(self):
self.onStart()
def onStart(self):
pass
def hasAlias(self, message):
if message.Type in self.acceptedTypes and message.Command in GlobalVars.commandAliases.keys():
return True
def shouldTrigger(self, message):
if message.Type not in self.acceptedTypes:
return False
if message.Command not in self.triggers:
return False
return True
def onTrigger(self, Hubbot, message):
pass | import GlobalVars
class ModuleInterface(object):
triggers = []
acceptedTypes = ['PRIVMSG']
help = '<no help defined (yet)>'
def __init__(self):
self.onStart()
def onStart(self):
pass
def hasAlias(self, message):
if message.Type in self.acceptedTypes and message.Command in GlobalVars.commandAliases.keys():
return True
else:
return False
def shouldTrigger(self, message):
if message.Type not in self.acceptedTypes:
return False
if message.Command not in self.triggers:
return False
return True
def onTrigger(self, Hubbot, message):
pass | Return false if no alias. | [ModuleInteface] Return false if no alias.
| Python | mit | HubbeKing/Hubbot_Twisted | ---
+++
@@ -15,6 +15,8 @@
def hasAlias(self, message):
if message.Type in self.acceptedTypes and message.Command in GlobalVars.commandAliases.keys():
return True
+ else:
+ return False
def shouldTrigger(self, message):
if message.Type not in self.acceptedTypes: |
2c4f32fbc407acb0b65ddc6fb71d192af74e740e | tcconfig/parser/_interface.py | tcconfig/parser/_interface.py | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, unicode_literals
import abc
import six
@six.add_metaclass(abc.ABCMeta)
class ParserInterface(object):
@abc.abstractmethod
def parse(self, text): # pragma: no cover
pass
@six.add_metaclass(abc.ABCMeta)
class AbstractParser(ParserInterface):
def __init__(self):
self._clear()
@abc.abstractproperty
def _tc_subcommand(self): # pragma: no cover
pass
@abc.abstractmethod
def _clear(self): # pragma: no cover
pass
@staticmethod
def _to_unicode(text):
try:
return text.decode("ascii")
except AttributeError:
return text
| # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, unicode_literals
import abc
import six
@six.add_metaclass(abc.ABCMeta)
class ParserInterface(object):
@abc.abstractmethod
def parse(self, device, text): # pragma: no cover
pass
@six.add_metaclass(abc.ABCMeta)
class AbstractParser(ParserInterface):
def __init__(self):
self._clear()
@abc.abstractproperty
def _tc_subcommand(self): # pragma: no cover
pass
@abc.abstractmethod
def _clear(self): # pragma: no cover
pass
@staticmethod
def _to_unicode(text):
try:
return text.decode("ascii")
except AttributeError:
return text
| Align the method signature with subclasses | Align the method signature with subclasses
| Python | mit | thombashi/tcconfig,thombashi/tcconfig | ---
+++
@@ -14,7 +14,7 @@
@six.add_metaclass(abc.ABCMeta)
class ParserInterface(object):
@abc.abstractmethod
- def parse(self, text): # pragma: no cover
+ def parse(self, device, text): # pragma: no cover
pass
|
bdc51bb7a71dba4a25fcded0d2758a9af5e15679 | pythran/tests/test_doc.py | pythran/tests/test_doc.py | import unittest
import doctest
class TestDoctest(unittest.TestCase):
modules = ('passes',)
def test_package(self):
import pythran
failed, _ = doctest.testmod(pythran)
self.assertEqual(failed, 0)
def test_passes(self):
from pythran import passes
failed, _ = doctest.testmod(passes)
self.assertEqual(failed, 0)
def test_optimizations(self):
from pythran import optimizations
failed, _ = doctest.testmod(optimizations)
self.assertEqual(failed, 0)
def test_backend(self):
from pythran import backend
failed, _ = doctest.testmod(backend)
self.assertEqual(failed, 0)
def test_cxxtypes(self):
from pythran import cxxtypes
failed, _ = doctest.testmod(cxxtypes)
self.assertEqual(failed, 0)
def test_openmp(self):
from pythran import openmp
failed, _ = doctest.testmod(openmp)
self.assertEqual(failed, 0)
#def test_typing(self):
# from pythran import typing
# failed, _ = doctest.testmod(typing)
# self.assertEqual(failed, 0)
if __name__ == '__main__':
unittest.main()
| import unittest
import doctest
import pythran
import inspect
class TestDoctest(unittest.TestCase):
'''
Enable automatic doctest integration to unittest
Every module in the pythran package is scanned for doctests
and one test per module is created
'''
pass
def generic_test_package(self, mod):
failed, _ = doctest.testmod(mod)
self.assertEqual(failed, 0)
def add_module_doctest(module_name):
module = getattr(pythran, module_name)
if inspect.ismodule(module):
setattr(TestDoctest, 'test_' + module_name,
lambda self: generic_test_package(self, module))
map(add_module_doctest, dir(pythran))
if __name__ == '__main__':
unittest.main()
| Make doctest integration in unittest generic. | Make doctest integration in unittest generic.
Rely on introspection rather than redundant typing.
| Python | bsd-3-clause | pbrunet/pythran,artas360/pythran,pbrunet/pythran,pbrunet/pythran,serge-sans-paille/pythran,artas360/pythran,hainm/pythran,serge-sans-paille/pythran,hainm/pythran,pombredanne/pythran,pombredanne/pythran,pombredanne/pythran,hainm/pythran,artas360/pythran | ---
+++
@@ -1,45 +1,28 @@
import unittest
import doctest
+import pythran
+import inspect
class TestDoctest(unittest.TestCase):
+ '''
+ Enable automatic doctest integration to unittest
- modules = ('passes',)
+ Every module in the pythran package is scanned for doctests
+ and one test per module is created
+ '''
+ pass
- def test_package(self):
- import pythran
- failed, _ = doctest.testmod(pythran)
- self.assertEqual(failed, 0)
+def generic_test_package(self, mod):
+ failed, _ = doctest.testmod(mod)
+ self.assertEqual(failed, 0)
- def test_passes(self):
- from pythran import passes
- failed, _ = doctest.testmod(passes)
- self.assertEqual(failed, 0)
+def add_module_doctest(module_name):
+ module = getattr(pythran, module_name)
+ if inspect.ismodule(module):
+ setattr(TestDoctest, 'test_' + module_name,
+ lambda self: generic_test_package(self, module))
- def test_optimizations(self):
- from pythran import optimizations
- failed, _ = doctest.testmod(optimizations)
- self.assertEqual(failed, 0)
-
- def test_backend(self):
- from pythran import backend
- failed, _ = doctest.testmod(backend)
- self.assertEqual(failed, 0)
-
- def test_cxxtypes(self):
- from pythran import cxxtypes
- failed, _ = doctest.testmod(cxxtypes)
- self.assertEqual(failed, 0)
-
- def test_openmp(self):
- from pythran import openmp
- failed, _ = doctest.testmod(openmp)
- self.assertEqual(failed, 0)
-
- #def test_typing(self):
- # from pythran import typing
- # failed, _ = doctest.testmod(typing)
- # self.assertEqual(failed, 0)
-
+map(add_module_doctest, dir(pythran))
if __name__ == '__main__':
unittest.main() |
9c7808b1f6571daaaf19dc1bfc57bf83cfb37bad | hybra/wordclouds.py | hybra/wordclouds.py | from __future__ import absolute_import, division, print_function, unicode_literals
from collections import Counter
import re
def create_wordcloud( data, stopwords = ["the", "a", "or", "tai", "and", "ja", "to", "on", "in", "of", "for", "is", "i", "this", "http", "www", "fi", "com"] ):
import types
if isinstance( data, types.GeneratorType ):
data = list( data )
if len(data) == 0:
print( "Dataset empty." )
return
from wordcloud import WordCloud
text = ''
for d in data:
text += d['text_content'].lower() + ' '
text = text.strip()
stopwords = map( lambda w: str(w), stopwords )
wc = WordCloud( background_color="white", width=800, height=400, stopwords = stopwords )
wc.generate( text )
plt.figure(figsize=(15,10))
plt.imshow(wc, interpolation="bilinear")
plt.axis("off")
plt.show()
| from __future__ import absolute_import, division, print_function, unicode_literals
from collections import Counter
import re
def create_wordcloud( data, plt, stopwords = ["the", "a", "or", "tai", "and", "ja", "to", "on", "in", "of", "for", "is", "i", "this", "http", "www", "fi", "com"] ):
import types
if isinstance( data, types.GeneratorType ):
data = list( data )
if len(data) == 0:
print( "Dataset empty." )
return
from wordcloud import WordCloud
text = ''
for d in data:
text += d['text_content'].lower() + ' '
text = text.strip()
stopwords = map( lambda w: str(w), stopwords )
wc = WordCloud( background_color="white", width=800, height=400, stopwords = stopwords )
wc.generate( text )
plt.figure(figsize=(15,10))
plt.imshow(wc, interpolation="bilinear")
plt.axis("off")
plt.show()
| Fix bug in wordcloud method | Fix bug in wordcloud method
| Python | mit | HIIT/hybra-core,HIIT/hybra-core,HIIT/hybra-core,HIIT/hybra-core,HIIT/hybra-core | ---
+++
@@ -3,7 +3,7 @@
from collections import Counter
import re
-def create_wordcloud( data, stopwords = ["the", "a", "or", "tai", "and", "ja", "to", "on", "in", "of", "for", "is", "i", "this", "http", "www", "fi", "com"] ):
+def create_wordcloud( data, plt, stopwords = ["the", "a", "or", "tai", "and", "ja", "to", "on", "in", "of", "for", "is", "i", "this", "http", "www", "fi", "com"] ):
import types
|
0e2275c0d2623a7ec62e7109d3ffdd859118ed9d | external_tools/src/main/python/images/move_corrupt_images.py | external_tools/src/main/python/images/move_corrupt_images.py | """
Script to move corrupt images to 'dirty' directory
Reads list of images to move. Does not verify that images are corrupt -
Simply moves to 'dirty' directory of appropriate data-release creating
the required directory structure
"""
import os
import argparse
parser = argparse.ArgumentParser(
description="Move corrupt images to 'dirty' dir")
parser.add_argument('-i', dest='inputFiles', required=True,
help='File containing list of images to move'
)
parser.add_argument('-s', dest='splitString',
help='token to separate the basedir from input files'
)
parser.add_argument('-r', dest='replacementString',
help='String to replace the split string with'
)
parser.add_argument('-d', dest='destDirBase', required=True,
help='Path to the base of the destination dir'
)
args = parser.parse_args()
input_files = args.inputFiles
split_string = "" if args.splitString is None else args.splitString
replacement_string = "" if args.replacementString is None else args.replacementString
with open(input_files,'rt') as f:
fnames = [fname.strip('\n') for fname in f.readlines()]
for fname in fnames:
fname = fname.replace(' ','\ ')
fname2 = fname.replace(split_string, replacement_string)
if os.path.exists(fname2):
continue
out_dir = os.path.dirname(fname2)
if not os.path.isdir(out_dir):
os.makedirs(out_dir)
command = "mv " + fname + " " + fname2
print(command)
os.system(command)
| """
Script to move corrupt images to 'dirty' directory
Reads list of images to move. Does not verify that images are corrupt -
Simply moves to 'dirty' directory of appropriate data-release creating
the required directory structure
"""
import os
import argparse
parser = argparse.ArgumentParser(
description="Move corrupt images to 'dirty' dir")
parser.add_argument('-i', dest='inputFiles', required=True,
help='File containing list of images to move'
)
parser.add_argument('-s', dest='splitString',
help='token to separate the basedir from input files'
)
parser.add_argument('-r', dest='replacementString',
help='String to replace the split string with'
)
parser.add_argument('-d', dest='destDirBase', required=True,
help='Path to the base of the destination dir'
)
args = parser.parse_args()
input_files = args.inputFiles
split_string = "" if args.splitString is None else args.splitString
replacement_string = "" if args.replacementString is None else args.replacementString
with open(input_files,'rt') as f:
fnames = [fname.strip('\n') for fname in f.readlines()]
for fname in fnames:
fname2 = fname.replace(split_string, replacement_string)
os.rename(fname, fname2)
| Use os.rename instead of os.path in moving dirs | Use os.rename instead of os.path in moving dirs
| Python | apache-2.0 | mpi2/PhenotypeData,mpi2/PhenotypeData,mpi2/PhenotypeData,mpi2/PhenotypeData,mpi2/PhenotypeData,mpi2/PhenotypeData | ---
+++
@@ -31,18 +31,8 @@
split_string = "" if args.splitString is None else args.splitString
replacement_string = "" if args.replacementString is None else args.replacementString
-
-
with open(input_files,'rt') as f:
fnames = [fname.strip('\n') for fname in f.readlines()]
for fname in fnames:
- fname = fname.replace(' ','\ ')
fname2 = fname.replace(split_string, replacement_string)
- if os.path.exists(fname2):
- continue
- out_dir = os.path.dirname(fname2)
- if not os.path.isdir(out_dir):
- os.makedirs(out_dir)
- command = "mv " + fname + " " + fname2
- print(command)
- os.system(command)
+ os.rename(fname, fname2) |
4b193d9f0c46f91c5a58446e6443d8779e7ca5ce | server/plugins/ardinfo/scripts/ard_info.py | server/plugins/ardinfo/scripts/ard_info.py | #!/usr/bin/python
import os
import sys
sys.path.append("/usr/local/munki/munkilib")
import FoundationPlist
sys.path.append("/usr/local/sal")
import utils
def main():
ard_path = "/Library/Preferences/com.apple.RemoteDesktop.plist"
if os.path.exists(ard_path):
ard_prefs = FoundationPlist.readPlist(ard_path)
else:
ard_prefs = {}
sal_result_key = "ARD_Info_{}"
prefs_key_prefix = "Text{}"
data = {
sal_result_key.format(i): ard_prefs.get(prefs_key_prefix.format(i), "")
for i in range(1, 5)}
utils.add_plugin_results('ARD_Info', data)
if __name__ == "__main__":
main()
| #!/usr/bin/python
import os
import sys
sys.path.append("/usr/local/munki")
from munkilib import FoundationPlist
sys.path.append("/usr/local/sal")
import utils
def main():
ard_path = "/Library/Preferences/com.apple.RemoteDesktop.plist"
if os.path.exists(ard_path):
ard_prefs = FoundationPlist.readPlist(ard_path)
else:
ard_prefs = {}
sal_result_key = "ARD_Info_{}"
prefs_key_prefix = "Text{}"
data = {
sal_result_key.format(i): ard_prefs.get(prefs_key_prefix.format(i), "")
for i in range(1, 5)}
utils.add_plugin_results('ARD_Info', data)
if __name__ == "__main__":
main()
| Fix name clash over "utils" in ardinfo plugin script. | Fix name clash over "utils" in ardinfo plugin script.
| Python | apache-2.0 | sheagcraig/sal,sheagcraig/sal,salopensource/sal,sheagcraig/sal,salopensource/sal,salopensource/sal,sheagcraig/sal,salopensource/sal | ---
+++
@@ -4,8 +4,8 @@
import os
import sys
-sys.path.append("/usr/local/munki/munkilib")
-import FoundationPlist
+sys.path.append("/usr/local/munki")
+from munkilib import FoundationPlist
sys.path.append("/usr/local/sal")
import utils
|
b920b818f6b4a83ce39a34f4f1b3afe6f8002906 | integration-test/400-bay-water.py | integration-test/400-bay-water.py | # San Pablo Bay
# https://www.openstreetmap.org/way/43950409
assert_has_feature(
14, 2623, 6318, 'water',
{ 'kind': 'bay', 'label_placement': True })
# Sansum Narrows
# https://www.openstreetmap.org/relation/1019862
assert_has_feature(
11, 321, 705, 'water',
{ 'kind': 'strait', 'label_placement': True })
# Horsens Fjord
# https://www.openstreetmap.org/relation/1451065
assert_has_feature(
14, 8645, 5114, 'water',
{ 'kind': 'fjord', 'label_placement': True })
| # San Pablo Bay
# https://www.openstreetmap.org/way/43950409
assert_has_feature(
14, 2623, 6318, 'water',
{ 'kind': 'bay', 'label_placement': True })
# Sansum Narrows
# https://www.openstreetmap.org/relation/1019862
assert_has_feature(
11, 321, 705, 'water',
{ 'kind': 'strait', 'label_placement': True })
# Horsens Fjord
# https://www.openstreetmap.org/relation/1451065
assert_has_feature(
14, 8646, 5112, 'water',
{ 'kind': 'fjord', 'label_placement': True })
| Update tile coordinate for fjord label placement | Update tile coordinate for fjord label placement
| Python | mit | mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource | ---
+++
@@ -13,5 +13,5 @@
# Horsens Fjord
# https://www.openstreetmap.org/relation/1451065
assert_has_feature(
- 14, 8645, 5114, 'water',
+ 14, 8646, 5112, 'water',
{ 'kind': 'fjord', 'label_placement': True }) |
5bbd288c40e3a2bc1ee791545d704452699334f3 | cr8/aio.py | cr8/aio.py |
from tqdm import tqdm
import asyncio
try:
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
except ImportError:
pass
async def map_async(q, corof, iterable):
for i in iterable:
task = asyncio.ensure_future(corof(*i))
await q.put(task)
await q.join()
await q.put(None)
async def consume(q):
with tqdm(unit=' requests') as t:
while True:
task = await q.get()
if task is None:
break
await task
t.update(1)
q.task_done()
def run(coro, iterable, concurrency, loop=None):
loop = loop or asyncio.get_event_loop()
q = asyncio.Queue(maxsize=concurrency)
loop.run_until_complete(asyncio.gather(
map_async(q, coro, iterable),
consume(q)))
|
from tqdm import tqdm
import asyncio
try:
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
except ImportError:
pass
async def map_async(q, corof, iterable):
for i in iterable:
task = asyncio.ensure_future(corof(*i))
await q.put(task)
await q.put(None)
async def consume(q):
with tqdm(unit=' requests') as t:
while True:
task = await q.get()
if task is None:
break
await task
t.update(1)
def run(coro, iterable, concurrency, loop=None):
loop = loop or asyncio.get_event_loop()
q = asyncio.Queue(maxsize=concurrency)
loop.run_until_complete(asyncio.gather(
map_async(q, coro, iterable),
consume(q)))
| Remove q.join() / task_done() usage | Remove q.join() / task_done() usage
Don't have to block producer anymore - it will wait for the consumer to
finish anyway
| Python | mit | mikethebeer/cr8,mfussenegger/cr8 | ---
+++
@@ -12,7 +12,6 @@
for i in iterable:
task = asyncio.ensure_future(corof(*i))
await q.put(task)
- await q.join()
await q.put(None)
@@ -24,7 +23,6 @@
break
await task
t.update(1)
- q.task_done()
def run(coro, iterable, concurrency, loop=None): |
7698ec18abd25ed41b3104a382e7d8ca38d755ca | tests/unit/test_describe.py | tests/unit/test_describe.py | import pytest
from mock import Mock
from formica import cli
from tests.unit.constants import STACK
def test_describes_change_set(boto_client, change_set):
cli.main(['describe', '--stack', STACK])
boto_client.assert_called_with('cloudformation')
change_set.assert_called_with(stack=STACK)
change_set.return_value.describe.assert_called_once()
| import pytest
from mock import Mock
from formica import cli
from tests.unit.constants import STACK
def test_describes_change_set(boto_client, change_set):
cli.main(['describe', '--stack', STACK])
change_set.assert_called_with(stack=STACK)
change_set.return_value.describe.assert_called_once()
| Remove Assert Call not necessary anymore | Remove Assert Call not necessary anymore
| Python | mit | flomotlik/formica | ---
+++
@@ -7,6 +7,5 @@
def test_describes_change_set(boto_client, change_set):
cli.main(['describe', '--stack', STACK])
- boto_client.assert_called_with('cloudformation')
change_set.assert_called_with(stack=STACK)
change_set.return_value.describe.assert_called_once() |
41b45872fae69e6c791aa79332981f12e33f7075 | numpy/distutils/fcompiler/nag.py | numpy/distutils/fcompiler/nag.py | import os
import sys
from numpy.distutils.cpuinfo import cpu
from numpy.distutils.fcompiler import FCompiler
class NAGFCompiler(FCompiler):
compiler_type = 'nag'
version_pattern = r'NAGWare Fortran 95 compiler Release (?P<version>[^\s]*)'
executables = {
'version_cmd' : ["f95", "-V"],
'compiler_f77' : ["f95", "-fixed"],
'compiler_fix' : ["f95", "-fixed"],
'compiler_f90' : ["f95"],
'linker_so' : ["f95"],
'archiver' : ["ar", "-cr"],
'ranlib' : ["ranlib"]
}
def get_flags_linker_so(self):
if sys.platform=='darwin':
return ['-unsharedf95','-Wl,-bundle,-flat_namespace,-undefined,suppress']
return ["-Wl,shared"]
def get_flags_opt(self):
return ['-O4']
def get_flags_arch(self):
return ['-target=native']
def get_flags_debug(self):
return ['-g','-gline','-g90','-nan','-C']
if __name__ == '__main__':
from distutils import log
log.set_verbosity(2)
from numpy.distutils.fcompiler import new_fcompiler
compiler = new_fcompiler(compiler='nag')
compiler.customize()
print compiler.get_version()
| import os
import sys
from numpy.distutils.cpuinfo import cpu
from numpy.distutils.fcompiler import FCompiler
class NAGFCompiler(FCompiler):
compiler_type = 'nag'
version_pattern = r'NAGWare Fortran 95 compiler Release (?P<version>[^\s]*)'
executables = {
'version_cmd' : ["f95", "-V"],
'compiler_f77' : ["f95", "-fixed"],
'compiler_fix' : ["f95", "-fixed"],
'compiler_f90' : ["f95"],
'linker_so' : ["f95"],
'archiver' : ["ar", "-cr"],
'ranlib' : ["ranlib"]
}
def get_flags_linker_so(self):
if sys.platform=='darwin':
return ['-unsharedf95','-Wl,-bundle,-flat_namespace,-undefined,suppress']
return ["-Wl,-shared"]
def get_flags_opt(self):
return ['-O4']
def get_flags_arch(self):
return ['-target=native']
def get_flags_debug(self):
return ['-g','-gline','-g90','-nan','-C']
if __name__ == '__main__':
from distutils import log
log.set_verbosity(2)
from numpy.distutils.fcompiler import new_fcompiler
compiler = new_fcompiler(compiler='nag')
compiler.customize()
print compiler.get_version()
| Fix for using NAG Fortran 95, due to James Graham <jg307@cam.ac.uk> | Fix for using NAG Fortran 95, due to James Graham <jg307@cam.ac.uk>
git-svn-id: 77a43f9646713b91fea7788fad5dfbf67e151ece@2515 94b884b6-d6fd-0310-90d3-974f1d3f35e1
| Python | bsd-3-clause | jasonmccampbell/numpy-refactor-sprint,teoliphant/numpy-refactor,teoliphant/numpy-refactor,efiring/numpy-work,Ademan/NumPy-GSoC,illume/numpy3k,illume/numpy3k,chadnetzer/numpy-gaurdro,illume/numpy3k,chadnetzer/numpy-gaurdro,teoliphant/numpy-refactor,jasonmccampbell/numpy-refactor-sprint,efiring/numpy-work,chadnetzer/numpy-gaurdro,teoliphant/numpy-refactor,Ademan/NumPy-GSoC,jasonmccampbell/numpy-refactor-sprint,efiring/numpy-work,teoliphant/numpy-refactor,Ademan/NumPy-GSoC,chadnetzer/numpy-gaurdro,efiring/numpy-work,illume/numpy3k,Ademan/NumPy-GSoC,jasonmccampbell/numpy-refactor-sprint | ---
+++
@@ -22,7 +22,7 @@
def get_flags_linker_so(self):
if sys.platform=='darwin':
return ['-unsharedf95','-Wl,-bundle,-flat_namespace,-undefined,suppress']
- return ["-Wl,shared"]
+ return ["-Wl,-shared"]
def get_flags_opt(self):
return ['-O4']
def get_flags_arch(self): |
d6b3f4e0798f430761f51529ea61c368e1ce610a | utest/contrib/testrunner/test_pybot_arguments_validation.py | utest/contrib/testrunner/test_pybot_arguments_validation.py | import unittest
import robot.errors
from robotide.contrib.testrunner.runprofiles import PybotProfile
class TestPybotArgumentsValidation(unittest.TestCase):
def setUp(self):
self._profile = PybotProfile(lambda:0)
@unittest.expectedFailure # No more DataError, better argument detection
def test_invalid_argument(self):
try:
self.assertRaisesRegex(robot.errors.DataError,
'option --invalidargument not recognized',
self._profile._get_invalid_message,
'--invalidargument')
except AttributeError: # Python2
self.assertRaisesRegexp(robot.errors.DataError,
'option --invalidargument not recognized',
self._profile._get_invalid_message,
'--invalidargument')
def test_valid_argument_short(self):
self._working_arguments('-T')
def _working_arguments(self, args):
self.assertEqual(None, self._profile._get_invalid_message(args))
def test_valid_argument_long(self):
self._working_arguments('--timestampoutputs')
def test_valid_argument_with_value(self):
self._working_arguments('--log somelog.html')
def test_runfailed_argument_works(self):
self._working_arguments('--runfailed output.xml')
if __name__ == '__main__':
unittest.main()
| import unittest
import robotide.lib.robot.errors
from robotide.contrib.testrunner.runprofiles import PybotProfile
class TestPybotArgumentsValidation(unittest.TestCase):
def setUp(self):
self._profile = PybotProfile(lambda:0)
@unittest.expectedFailure # No more DataError, better argument detection
def test_invalid_argument(self):
try:
self.assertRaisesRegex(robotide.lib.robot.errors.DataError,
'option --invalidargument not recognized',
self._profile._get_invalid_message,
'--invalidargument')
except AttributeError: # Python2
self.assertRaisesRegexp(robotide.lib.robot.errors.DataError,
'option --invalidargument not recognized',
self._profile._get_invalid_message,
'--invalidargument')
def test_valid_argument_short(self):
self._working_arguments('-T')
def _working_arguments(self, args):
self.assertEqual(None, self._profile._get_invalid_message(args))
def test_valid_argument_long(self):
self._working_arguments('--timestampoutputs')
def test_valid_argument_with_value(self):
self._working_arguments('--log somelog.html')
def test_runfailed_argument_works(self):
self._working_arguments('--runfailed output.xml')
if __name__ == '__main__':
unittest.main()
| Fix unit test for when robotframework is not installed. | Fix unit test for when robotframework is not installed.
| Python | apache-2.0 | HelioGuilherme66/RIDE,robotframework/RIDE,robotframework/RIDE,HelioGuilherme66/RIDE,HelioGuilherme66/RIDE,robotframework/RIDE,HelioGuilherme66/RIDE,robotframework/RIDE | ---
+++
@@ -1,5 +1,5 @@
import unittest
-import robot.errors
+import robotide.lib.robot.errors
from robotide.contrib.testrunner.runprofiles import PybotProfile
@@ -11,12 +11,12 @@
@unittest.expectedFailure # No more DataError, better argument detection
def test_invalid_argument(self):
try:
- self.assertRaisesRegex(robot.errors.DataError,
+ self.assertRaisesRegex(robotide.lib.robot.errors.DataError,
'option --invalidargument not recognized',
self._profile._get_invalid_message,
'--invalidargument')
except AttributeError: # Python2
- self.assertRaisesRegexp(robot.errors.DataError,
+ self.assertRaisesRegexp(robotide.lib.robot.errors.DataError,
'option --invalidargument not recognized',
self._profile._get_invalid_message,
'--invalidargument') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.