commit
stringlengths 40
40
| old_file
stringlengths 4
118
| new_file
stringlengths 4
118
| old_contents
stringlengths 10
2.94k
| new_contents
stringlengths 21
3.18k
| subject
stringlengths 16
444
| message
stringlengths 17
2.63k
| lang
stringclasses 1
value | license
stringclasses 13
values | repos
stringlengths 5
43k
| ndiff
stringlengths 51
3.32k
| instruction
stringlengths 16
444
| content
stringlengths 133
4.32k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
268976034ad508c2ef48dec60da40dec57af824f | setup.py | setup.py | from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
setup(
name = "DragonCreole",
packages = ["dragoncreole"],
version = "0.1.0",
description = "Optimized parser for creole-like markup language",
author = "Zauber Paracelsus",
author_email = "admin@zauberparacelsus.xyz",
url = "http://github.com/zauberparacelsus/dragoncreole",
download_url = "https://github.com/zauberparacelsus/dragoncreole/tarball/0.1",
keywords = ["parser", "markup", "html"],
install_requires= [
'html2text'
],
classifiers = [
"Programming Language :: Python",
"Development Status :: 4 - Beta",
"Environment :: Other Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)",
"Operating System :: OS Independent",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Text Processing :: Markup :: HTML"
],
long_description = "",
cmdclass = {"build_ext": build_ext},
ext_modules = [Extension("DragonCreoleC", ["dragoncreole/dragoncreole.py"])]
)
| from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
setup(
name = "DragonCreole",
packages = ["dragoncreole"],
version = "0.1.0",
description = "Optimized parser for creole-like markup language",
author = "Zauber Paracelsus",
author_email = "admin@zauberparacelsus.xyz",
url = "http://github.com/zauberparacelsus/dragoncreole",
download_url = "https://github.com/zauberparacelsus/dragoncreole/tarball/0.1",
keywords = ["parser", "markup", "html"],
install_requires= [
'html2text',
'cython'
],
classifiers = [
"Programming Language :: Python",
"Development Status :: 4 - Beta",
"Environment :: Other Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)",
"Operating System :: OS Independent",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Text Processing :: Markup :: HTML"
],
long_description = "",
cmdclass = {"build_ext": build_ext},
ext_modules = [Extension("dragoncreole.DragonCreoleC", ["dragoncreole/dragoncreole.py"])]
)
| Tweak for building with cython | Tweak for building with cython
| Python | mpl-2.0 | zauberparacelsus/dragoncreole,zauberparacelsus/dragoncreole | from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
setup(
name = "DragonCreole",
packages = ["dragoncreole"],
version = "0.1.0",
description = "Optimized parser for creole-like markup language",
author = "Zauber Paracelsus",
author_email = "admin@zauberparacelsus.xyz",
url = "http://github.com/zauberparacelsus/dragoncreole",
download_url = "https://github.com/zauberparacelsus/dragoncreole/tarball/0.1",
keywords = ["parser", "markup", "html"],
install_requires= [
- 'html2text'
+ 'html2text',
+ 'cython'
],
classifiers = [
"Programming Language :: Python",
"Development Status :: 4 - Beta",
"Environment :: Other Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)",
"Operating System :: OS Independent",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Text Processing :: Markup :: HTML"
],
long_description = "",
cmdclass = {"build_ext": build_ext},
- ext_modules = [Extension("DragonCreoleC", ["dragoncreole/dragoncreole.py"])]
+ ext_modules = [Extension("dragoncreole.DragonCreoleC", ["dragoncreole/dragoncreole.py"])]
)
| Tweak for building with cython | ## Code Before:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
setup(
name = "DragonCreole",
packages = ["dragoncreole"],
version = "0.1.0",
description = "Optimized parser for creole-like markup language",
author = "Zauber Paracelsus",
author_email = "admin@zauberparacelsus.xyz",
url = "http://github.com/zauberparacelsus/dragoncreole",
download_url = "https://github.com/zauberparacelsus/dragoncreole/tarball/0.1",
keywords = ["parser", "markup", "html"],
install_requires= [
'html2text'
],
classifiers = [
"Programming Language :: Python",
"Development Status :: 4 - Beta",
"Environment :: Other Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)",
"Operating System :: OS Independent",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Text Processing :: Markup :: HTML"
],
long_description = "",
cmdclass = {"build_ext": build_ext},
ext_modules = [Extension("DragonCreoleC", ["dragoncreole/dragoncreole.py"])]
)
## Instruction:
Tweak for building with cython
## Code After:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
setup(
name = "DragonCreole",
packages = ["dragoncreole"],
version = "0.1.0",
description = "Optimized parser for creole-like markup language",
author = "Zauber Paracelsus",
author_email = "admin@zauberparacelsus.xyz",
url = "http://github.com/zauberparacelsus/dragoncreole",
download_url = "https://github.com/zauberparacelsus/dragoncreole/tarball/0.1",
keywords = ["parser", "markup", "html"],
install_requires= [
'html2text',
'cython'
],
classifiers = [
"Programming Language :: Python",
"Development Status :: 4 - Beta",
"Environment :: Other Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)",
"Operating System :: OS Independent",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Text Processing :: Markup :: HTML"
],
long_description = "",
cmdclass = {"build_ext": build_ext},
ext_modules = [Extension("dragoncreole.DragonCreoleC", ["dragoncreole/dragoncreole.py"])]
)
|
1f03b2945b4e52ce22a3b9e6143d02d3bd9aef99 | overtime_calculator/tests/auth_test.py | overtime_calculator/tests/auth_test.py | import shutil
import pytest
import hug
from overtime_calculator.src import api
from overtime_calculator.src.auth import get_user_folder
def test_register():
user_name = 'test1'
response = hug.test.post(
api,
'/register',
{'username': user_name, 'password': user_name},
)
assert response.data == {'status': 'ok'}
def test_signin():
response = hug.test.post(api, '/signin', {'username': 'test_1', 'password': 'test_1'})
print(response.data)
assert response.data['token'] is not None
def teardown_module():
user_folder = get_user_folder('test1')
shutil.rmtree(str(user_folder), ignore_errors=False)
| import shutil
import pytest
import hug
from overtime_calculator.src import api
from overtime_calculator.src.auth import get_user_folder
EXISTING_USER = 'test1'
UNREGISTERED_USER = 'test2'
def test_registration_of_new_user():
response = hug.test.post(
api,
'/register',
{'username': EXISTING_USER, 'password': EXISTING_USER},
)
print(response.data) # Will only show if test fails and is run with --verbose (-v)
assert response.data == {'status': 'ok'}
def test_second_registration_of_registered_user():
response = hug.test.post(
api,
'/register',
{'username': EXISTING_USER, 'password': EXISTING_USER},
)
print(response.data) # Will only show if test fails and is run with --verbose (-v)
assert response.data == dict(error='username already in use')
def test_sign_in_of_existing_user():
response = hug.test.post(
api,
'/signin',
{'username': EXISTING_USER, 'password': EXISTING_USER}
)
print(response.data) # Will only show if test fails and is run with --verbose (-v)
assert 'token' in response.data and response.data['token']
def teardown_module():
user_folder = get_user_folder(EXISTING_USER)
shutil.rmtree(str(user_folder), ignore_errors=False)
| Add test for already registered user | Feature: Add test for already registered user
| Python | mit | x10an14/overtime-calculator | import shutil
import pytest
import hug
from overtime_calculator.src import api
from overtime_calculator.src.auth import get_user_folder
+ EXISTING_USER = 'test1'
+ UNREGISTERED_USER = 'test2'
- def test_register():
- user_name = 'test1'
+
+ def test_registration_of_new_user():
response = hug.test.post(
api,
'/register',
- {'username': user_name, 'password': user_name},
+ {'username': EXISTING_USER, 'password': EXISTING_USER},
)
+ print(response.data) # Will only show if test fails and is run with --verbose (-v)
assert response.data == {'status': 'ok'}
- def test_signin():
- response = hug.test.post(api, '/signin', {'username': 'test_1', 'password': 'test_1'})
- print(response.data)
- assert response.data['token'] is not None
+
+ def test_second_registration_of_registered_user():
+ response = hug.test.post(
+ api,
+ '/register',
+ {'username': EXISTING_USER, 'password': EXISTING_USER},
+ )
+ print(response.data) # Will only show if test fails and is run with --verbose (-v)
+ assert response.data == dict(error='username already in use')
+
+
+ def test_sign_in_of_existing_user():
+ response = hug.test.post(
+ api,
+ '/signin',
+ {'username': EXISTING_USER, 'password': EXISTING_USER}
+ )
+ print(response.data) # Will only show if test fails and is run with --verbose (-v)
+ assert 'token' in response.data and response.data['token']
+
def teardown_module():
- user_folder = get_user_folder('test1')
+ user_folder = get_user_folder(EXISTING_USER)
shutil.rmtree(str(user_folder), ignore_errors=False)
| Add test for already registered user | ## Code Before:
import shutil
import pytest
import hug
from overtime_calculator.src import api
from overtime_calculator.src.auth import get_user_folder
def test_register():
user_name = 'test1'
response = hug.test.post(
api,
'/register',
{'username': user_name, 'password': user_name},
)
assert response.data == {'status': 'ok'}
def test_signin():
response = hug.test.post(api, '/signin', {'username': 'test_1', 'password': 'test_1'})
print(response.data)
assert response.data['token'] is not None
def teardown_module():
user_folder = get_user_folder('test1')
shutil.rmtree(str(user_folder), ignore_errors=False)
## Instruction:
Add test for already registered user
## Code After:
import shutil
import pytest
import hug
from overtime_calculator.src import api
from overtime_calculator.src.auth import get_user_folder
EXISTING_USER = 'test1'
UNREGISTERED_USER = 'test2'
def test_registration_of_new_user():
response = hug.test.post(
api,
'/register',
{'username': EXISTING_USER, 'password': EXISTING_USER},
)
print(response.data) # Will only show if test fails and is run with --verbose (-v)
assert response.data == {'status': 'ok'}
def test_second_registration_of_registered_user():
response = hug.test.post(
api,
'/register',
{'username': EXISTING_USER, 'password': EXISTING_USER},
)
print(response.data) # Will only show if test fails and is run with --verbose (-v)
assert response.data == dict(error='username already in use')
def test_sign_in_of_existing_user():
response = hug.test.post(
api,
'/signin',
{'username': EXISTING_USER, 'password': EXISTING_USER}
)
print(response.data) # Will only show if test fails and is run with --verbose (-v)
assert 'token' in response.data and response.data['token']
def teardown_module():
user_folder = get_user_folder(EXISTING_USER)
shutil.rmtree(str(user_folder), ignore_errors=False)
|
77ee44b0af8a80babf0a88ddd4f53f2f4ad10d2d | tests/test_event.py | tests/test_event.py | import unittest
from evesp.event import Event
class TestEvent(unittest.TestCase):
def setUp(self):
self.evt = Event(foo='bar')
def test_event_creation(self):
self.assertEqual(self.evt.foo, 'bar')
self.assertRaises(AttributeError, getattr, self.evt, 'non_existing')
def test_event_pickle_serialization(self):
ser_evt = self.evt.serialize()
deser_evt = Event.deserialize(ser_evt)
self.assertEqual(deser_evt.foo, 'bar')
self.assertRaises(AttributeError, getattr, deser_evt, 'non_existing')
def test_event_json_serialization(self):
ser_evt = self.evt.to_json()
deser_evt = Event.from_json(ser_evt)
self.assertEqual(deser_evt.foo, 'bar')
self.assertRaises(AttributeError, getattr, deser_evt, 'non_existing')
if __name__ == "__main__":
unittest.main()
# vim:sw=4:ts=4:et:
| import unittest
from evesp.event import Event
class TestEvent(unittest.TestCase):
def setUp(self):
self.evt = Event(foo='bar')
def test_event_creation(self):
self.assertEqual(self.evt.foo, 'bar')
def test_non_existing_event(self):
self.assertRaises(AttributeError, getattr, self.evt, 'non_existing')
def test_event_pickle_serialization(self):
ser_evt = self.evt.serialize()
deser_evt = Event.deserialize(ser_evt)
self.assertEqual(deser_evt.foo, 'bar')
self.assertRaises(AttributeError, getattr, deser_evt, 'non_existing')
def test_event_json_serialization(self):
ser_evt = self.evt.to_json()
deser_evt = Event.from_json(ser_evt)
self.assertEqual(deser_evt.foo, 'bar')
self.assertRaises(AttributeError, getattr, deser_evt, 'non_existing')
if __name__ == "__main__":
unittest.main()
# vim:sw=4:ts=4:et:
| Split one test into two tests | Split one test into two tests
| Python | apache-2.0 | BlackLight/evesp | import unittest
from evesp.event import Event
class TestEvent(unittest.TestCase):
def setUp(self):
self.evt = Event(foo='bar')
def test_event_creation(self):
self.assertEqual(self.evt.foo, 'bar')
+
+ def test_non_existing_event(self):
self.assertRaises(AttributeError, getattr, self.evt, 'non_existing')
def test_event_pickle_serialization(self):
ser_evt = self.evt.serialize()
deser_evt = Event.deserialize(ser_evt)
self.assertEqual(deser_evt.foo, 'bar')
self.assertRaises(AttributeError, getattr, deser_evt, 'non_existing')
def test_event_json_serialization(self):
ser_evt = self.evt.to_json()
deser_evt = Event.from_json(ser_evt)
self.assertEqual(deser_evt.foo, 'bar')
self.assertRaises(AttributeError, getattr, deser_evt, 'non_existing')
if __name__ == "__main__":
unittest.main()
# vim:sw=4:ts=4:et:
| Split one test into two tests | ## Code Before:
import unittest
from evesp.event import Event
class TestEvent(unittest.TestCase):
def setUp(self):
self.evt = Event(foo='bar')
def test_event_creation(self):
self.assertEqual(self.evt.foo, 'bar')
self.assertRaises(AttributeError, getattr, self.evt, 'non_existing')
def test_event_pickle_serialization(self):
ser_evt = self.evt.serialize()
deser_evt = Event.deserialize(ser_evt)
self.assertEqual(deser_evt.foo, 'bar')
self.assertRaises(AttributeError, getattr, deser_evt, 'non_existing')
def test_event_json_serialization(self):
ser_evt = self.evt.to_json()
deser_evt = Event.from_json(ser_evt)
self.assertEqual(deser_evt.foo, 'bar')
self.assertRaises(AttributeError, getattr, deser_evt, 'non_existing')
if __name__ == "__main__":
unittest.main()
# vim:sw=4:ts=4:et:
## Instruction:
Split one test into two tests
## Code After:
import unittest
from evesp.event import Event
class TestEvent(unittest.TestCase):
def setUp(self):
self.evt = Event(foo='bar')
def test_event_creation(self):
self.assertEqual(self.evt.foo, 'bar')
def test_non_existing_event(self):
self.assertRaises(AttributeError, getattr, self.evt, 'non_existing')
def test_event_pickle_serialization(self):
ser_evt = self.evt.serialize()
deser_evt = Event.deserialize(ser_evt)
self.assertEqual(deser_evt.foo, 'bar')
self.assertRaises(AttributeError, getattr, deser_evt, 'non_existing')
def test_event_json_serialization(self):
ser_evt = self.evt.to_json()
deser_evt = Event.from_json(ser_evt)
self.assertEqual(deser_evt.foo, 'bar')
self.assertRaises(AttributeError, getattr, deser_evt, 'non_existing')
if __name__ == "__main__":
unittest.main()
# vim:sw=4:ts=4:et:
|
a27b03a89af6442dc8e1be3d310a8fc046a98ed4 | foampy/tests.py | foampy/tests.py |
from .core import *
from .dictionaries import *
from .types import *
from .foil import *
| """Tests for foamPy."""
from .core import *
from .dictionaries import *
from .types import *
from .foil import *
def test_load_all_torque_drag():
"""Test the `load_all_torque_drag` function."""
t, torque, drag = load_all_torque_drag(casedir="test")
assert t.max() == 4.0
| Add test for loading all torque and drag data | Add test for loading all torque and drag data
| Python | mit | petebachant/foamPy,petebachant/foamPy,petebachant/foamPy | + """Tests for foamPy."""
from .core import *
from .dictionaries import *
from .types import *
from .foil import *
+
+ def test_load_all_torque_drag():
+ """Test the `load_all_torque_drag` function."""
+ t, torque, drag = load_all_torque_drag(casedir="test")
+ assert t.max() == 4.0
+ | Add test for loading all torque and drag data | ## Code Before:
from .core import *
from .dictionaries import *
from .types import *
from .foil import *
## Instruction:
Add test for loading all torque and drag data
## Code After:
"""Tests for foamPy."""
from .core import *
from .dictionaries import *
from .types import *
from .foil import *
def test_load_all_torque_drag():
"""Test the `load_all_torque_drag` function."""
t, torque, drag = load_all_torque_drag(casedir="test")
assert t.max() == 4.0
|
f2d91d2c296e3662a1b656f0fdf5191665ff363b | skimage/transform/__init__.py | skimage/transform/__init__.py | from .hough_transform import *
from .radon_transform import *
from .finite_radon_transform import *
from .integral import *
from ._geometric import (warp, warp_coords, estimate_transform,
SimilarityTransform, AffineTransform,
ProjectiveTransform, PolynomialTransform,
PiecewiseAffineTransform)
from ._warps import swirl, homography, resize, rotate, rescale
from .pyramids import (pyramid_reduce, pyramid_expand,
pyramid_gaussian, pyramid_laplacian)
| from .hough_transform import *
from .radon_transform import *
from .finite_radon_transform import *
from .integral import *
from ._geometric import (warp, warp_coords, estimate_transform,
SimilarityTransform, AffineTransform,
ProjectiveTransform, PolynomialTransform,
PiecewiseAffineTransform)
from ._warps import swirl, resize, rotate, rescale
from .pyramids import (pyramid_reduce, pyramid_expand,
pyramid_gaussian, pyramid_laplacian)
| Remove deprecated import of hompgraphy | Remove deprecated import of hompgraphy
| Python | bsd-3-clause | youprofit/scikit-image,almarklein/scikit-image,keflavich/scikit-image,pratapvardhan/scikit-image,vighneshbirodkar/scikit-image,almarklein/scikit-image,almarklein/scikit-image,chriscrosscutler/scikit-image,ajaybhat/scikit-image,SamHames/scikit-image,oew1v07/scikit-image,vighneshbirodkar/scikit-image,youprofit/scikit-image,SamHames/scikit-image,robintw/scikit-image,emon10005/scikit-image,emon10005/scikit-image,ClinicalGraphics/scikit-image,Midafi/scikit-image,warmspringwinds/scikit-image,vighneshbirodkar/scikit-image,ofgulban/scikit-image,michaelaye/scikit-image,ofgulban/scikit-image,Britefury/scikit-image,michaelaye/scikit-image,blink1073/scikit-image,paalge/scikit-image,Britefury/scikit-image,keflavich/scikit-image,rjeli/scikit-image,newville/scikit-image,bennlich/scikit-image,SamHames/scikit-image,ajaybhat/scikit-image,michaelpacer/scikit-image,chintak/scikit-image,jwiggins/scikit-image,warmspringwinds/scikit-image,chintak/scikit-image,oew1v07/scikit-image,ClinicalGraphics/scikit-image,dpshelio/scikit-image,SamHames/scikit-image,juliusbierk/scikit-image,Midafi/scikit-image,GaZ3ll3/scikit-image,ofgulban/scikit-image,paalge/scikit-image,chintak/scikit-image,robintw/scikit-image,bsipocz/scikit-image,bsipocz/scikit-image,rjeli/scikit-image,bennlich/scikit-image,juliusbierk/scikit-image,chriscrosscutler/scikit-image,jwiggins/scikit-image,michaelpacer/scikit-image,WarrenWeckesser/scikits-image,Hiyorimi/scikit-image,almarklein/scikit-image,pratapvardhan/scikit-image,Hiyorimi/scikit-image,WarrenWeckesser/scikits-image,chintak/scikit-image,dpshelio/scikit-image,rjeli/scikit-image,newville/scikit-image,GaZ3ll3/scikit-image,paalge/scikit-image,blink1073/scikit-image | from .hough_transform import *
from .radon_transform import *
from .finite_radon_transform import *
from .integral import *
from ._geometric import (warp, warp_coords, estimate_transform,
SimilarityTransform, AffineTransform,
ProjectiveTransform, PolynomialTransform,
PiecewiseAffineTransform)
- from ._warps import swirl, homography, resize, rotate, rescale
+ from ._warps import swirl, resize, rotate, rescale
from .pyramids import (pyramid_reduce, pyramid_expand,
pyramid_gaussian, pyramid_laplacian)
| Remove deprecated import of hompgraphy | ## Code Before:
from .hough_transform import *
from .radon_transform import *
from .finite_radon_transform import *
from .integral import *
from ._geometric import (warp, warp_coords, estimate_transform,
SimilarityTransform, AffineTransform,
ProjectiveTransform, PolynomialTransform,
PiecewiseAffineTransform)
from ._warps import swirl, homography, resize, rotate, rescale
from .pyramids import (pyramid_reduce, pyramid_expand,
pyramid_gaussian, pyramid_laplacian)
## Instruction:
Remove deprecated import of hompgraphy
## Code After:
from .hough_transform import *
from .radon_transform import *
from .finite_radon_transform import *
from .integral import *
from ._geometric import (warp, warp_coords, estimate_transform,
SimilarityTransform, AffineTransform,
ProjectiveTransform, PolynomialTransform,
PiecewiseAffineTransform)
from ._warps import swirl, resize, rotate, rescale
from .pyramids import (pyramid_reduce, pyramid_expand,
pyramid_gaussian, pyramid_laplacian)
|
589534c52ceff1d4aabb8d72b779359ce2032827 | tests/integration/integration/runner.py | tests/integration/integration/runner.py | import os
import subprocess
def load_variables_from_env(prefix="XII_INTEGRATION_"):
length = len(prefix)
vars = {}
for var in filter(lambda x: x.startswith(prefix), os.environ):
vars[var[length:]] = os.environ[var]
return vars
def run_xii(deffile, cmd, variables={}, gargs=None, cargs=None):
xii_env = os.environ.copy()
for key, value in variables.items():
print("=> XII_" + key + " defined")
xii_env["XII_" + key] = value
call = ["xii", "--no-parallel", "--deffile", deffile, gargs, cmd, cargs]
print("calling `{}`".format(" ".join(filter(None, call))))
process = subprocess.Popen(call, stdout=subprocess.PIPE, env=xii_env)
for line in process.stdout:
print("> " + line.rstrip(os.linesep))
if process.returncode != 0:
raise RuntimeError("running xii failed")
| import os
import subprocess
def load_variables_from_env(prefix="XII_INTEGRATION_"):
length = len(prefix)
vars = {}
for var in filter(lambda x: x.startswith(prefix), os.environ):
vars[var[length:]] = os.environ[var]
return vars
def run_xii(deffile, cmd, variables={}, gargs=None, cargs=None):
xii_env = os.environ.copy()
for key, value in variables.items():
print("=> XII_" + key + " defined")
xii_env["XII_" + key] = value
call = ["xii", "--no-parallel", "--deffile", deffile, cmd]
print("calling `{}`".format(" ".join(call)))
process = subprocess.Popen(call, stdout=subprocess.PIPE, env=xii_env)
for line in process.stdout:
print("> " + line.rstrip(os.linesep))
if process.returncode != 0:
raise RuntimeError("running xii failed")
| Make cargs and gargs truly optional | Make cargs and gargs truly optional
| Python | apache-2.0 | xii/xii,xii/xii | import os
import subprocess
def load_variables_from_env(prefix="XII_INTEGRATION_"):
length = len(prefix)
vars = {}
for var in filter(lambda x: x.startswith(prefix), os.environ):
vars[var[length:]] = os.environ[var]
return vars
def run_xii(deffile, cmd, variables={}, gargs=None, cargs=None):
xii_env = os.environ.copy()
for key, value in variables.items():
print("=> XII_" + key + " defined")
xii_env["XII_" + key] = value
- call = ["xii", "--no-parallel", "--deffile", deffile, gargs, cmd, cargs]
+ call = ["xii", "--no-parallel", "--deffile", deffile, cmd]
- print("calling `{}`".format(" ".join(filter(None, call))))
+ print("calling `{}`".format(" ".join(call)))
process = subprocess.Popen(call, stdout=subprocess.PIPE, env=xii_env)
for line in process.stdout:
print("> " + line.rstrip(os.linesep))
if process.returncode != 0:
raise RuntimeError("running xii failed")
| Make cargs and gargs truly optional | ## Code Before:
import os
import subprocess
def load_variables_from_env(prefix="XII_INTEGRATION_"):
length = len(prefix)
vars = {}
for var in filter(lambda x: x.startswith(prefix), os.environ):
vars[var[length:]] = os.environ[var]
return vars
def run_xii(deffile, cmd, variables={}, gargs=None, cargs=None):
xii_env = os.environ.copy()
for key, value in variables.items():
print("=> XII_" + key + " defined")
xii_env["XII_" + key] = value
call = ["xii", "--no-parallel", "--deffile", deffile, gargs, cmd, cargs]
print("calling `{}`".format(" ".join(filter(None, call))))
process = subprocess.Popen(call, stdout=subprocess.PIPE, env=xii_env)
for line in process.stdout:
print("> " + line.rstrip(os.linesep))
if process.returncode != 0:
raise RuntimeError("running xii failed")
## Instruction:
Make cargs and gargs truly optional
## Code After:
import os
import subprocess
def load_variables_from_env(prefix="XII_INTEGRATION_"):
length = len(prefix)
vars = {}
for var in filter(lambda x: x.startswith(prefix), os.environ):
vars[var[length:]] = os.environ[var]
return vars
def run_xii(deffile, cmd, variables={}, gargs=None, cargs=None):
xii_env = os.environ.copy()
for key, value in variables.items():
print("=> XII_" + key + " defined")
xii_env["XII_" + key] = value
call = ["xii", "--no-parallel", "--deffile", deffile, cmd]
print("calling `{}`".format(" ".join(call)))
process = subprocess.Popen(call, stdout=subprocess.PIPE, env=xii_env)
for line in process.stdout:
print("> " + line.rstrip(os.linesep))
if process.returncode != 0:
raise RuntimeError("running xii failed")
|
b36f89088ab1270054140a3d3020960f23c9790b | aldryn_blog/cms_toolbar.py | aldryn_blog/cms_toolbar.py | from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from cms.toolbar_pool import toolbar_pool
from cms.toolbar_base import CMSToolbar
from aldryn_blog import request_post_identifier
@toolbar_pool.register
class BlogToolbar(CMSToolbar):
def populate(self):
if not (self.is_current_app and self.request.user.has_perm('aldryn_blog.add_post')):
return
menu = self.toolbar.get_or_create_menu('blog-app', _('Blog'))
menu.add_modal_item(_('Add Blog Post'), reverse('admin:aldryn_blog_post_add') + '?_popup',
close_on_url=reverse('admin:aldryn_blog_post_changelist'))
blog_entry = getattr(self.request, request_post_identifier, None)
if blog_entry and self.request.user.has_perm('aldryn_blog.change_post'):
menu.add_modal_item(_('Edit Blog Post'), reverse('admin:aldryn_blog_post_change', args=(
blog_entry.pk,)) + '?_popup',
close_on_url=reverse('admin:aldryn_blog_post_changelist'), active=True)
| from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from cms.toolbar_pool import toolbar_pool
from cms.toolbar_base import CMSToolbar
from aldryn_blog import request_post_identifier
@toolbar_pool.register
class BlogToolbar(CMSToolbar):
def populate(self):
if not (self.is_current_app and self.request.user.has_perm('aldryn_blog.add_post')):
return
menu = self.toolbar.get_or_create_menu('blog-app', _('Blog'))
menu.add_modal_item(_('Add Blog Post'), reverse('admin:aldryn_blog_post_add'),
close_on_url=reverse('admin:aldryn_blog_post_changelist'))
blog_entry = getattr(self.request, request_post_identifier, None)
if blog_entry and self.request.user.has_perm('aldryn_blog.change_post'):
menu.add_modal_item(_('Edit Blog Post'), reverse('admin:aldryn_blog_post_change', args=(
blog_entry.pk,)),
close_on_url=reverse('admin:aldryn_blog_post_changelist'), active=True)
| Remove '?_popup' from toolbar urls | Remove '?_popup' from toolbar urls
| Python | bsd-3-clause | aldryn/aldryn-blog,aldryn/aldryn-blog | from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from cms.toolbar_pool import toolbar_pool
from cms.toolbar_base import CMSToolbar
from aldryn_blog import request_post_identifier
@toolbar_pool.register
class BlogToolbar(CMSToolbar):
def populate(self):
if not (self.is_current_app and self.request.user.has_perm('aldryn_blog.add_post')):
return
menu = self.toolbar.get_or_create_menu('blog-app', _('Blog'))
- menu.add_modal_item(_('Add Blog Post'), reverse('admin:aldryn_blog_post_add') + '?_popup',
+ menu.add_modal_item(_('Add Blog Post'), reverse('admin:aldryn_blog_post_add'),
close_on_url=reverse('admin:aldryn_blog_post_changelist'))
blog_entry = getattr(self.request, request_post_identifier, None)
if blog_entry and self.request.user.has_perm('aldryn_blog.change_post'):
menu.add_modal_item(_('Edit Blog Post'), reverse('admin:aldryn_blog_post_change', args=(
- blog_entry.pk,)) + '?_popup',
+ blog_entry.pk,)),
close_on_url=reverse('admin:aldryn_blog_post_changelist'), active=True)
| Remove '?_popup' from toolbar urls | ## Code Before:
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from cms.toolbar_pool import toolbar_pool
from cms.toolbar_base import CMSToolbar
from aldryn_blog import request_post_identifier
@toolbar_pool.register
class BlogToolbar(CMSToolbar):
def populate(self):
if not (self.is_current_app and self.request.user.has_perm('aldryn_blog.add_post')):
return
menu = self.toolbar.get_or_create_menu('blog-app', _('Blog'))
menu.add_modal_item(_('Add Blog Post'), reverse('admin:aldryn_blog_post_add') + '?_popup',
close_on_url=reverse('admin:aldryn_blog_post_changelist'))
blog_entry = getattr(self.request, request_post_identifier, None)
if blog_entry and self.request.user.has_perm('aldryn_blog.change_post'):
menu.add_modal_item(_('Edit Blog Post'), reverse('admin:aldryn_blog_post_change', args=(
blog_entry.pk,)) + '?_popup',
close_on_url=reverse('admin:aldryn_blog_post_changelist'), active=True)
## Instruction:
Remove '?_popup' from toolbar urls
## Code After:
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from cms.toolbar_pool import toolbar_pool
from cms.toolbar_base import CMSToolbar
from aldryn_blog import request_post_identifier
@toolbar_pool.register
class BlogToolbar(CMSToolbar):
def populate(self):
if not (self.is_current_app and self.request.user.has_perm('aldryn_blog.add_post')):
return
menu = self.toolbar.get_or_create_menu('blog-app', _('Blog'))
menu.add_modal_item(_('Add Blog Post'), reverse('admin:aldryn_blog_post_add'),
close_on_url=reverse('admin:aldryn_blog_post_changelist'))
blog_entry = getattr(self.request, request_post_identifier, None)
if blog_entry and self.request.user.has_perm('aldryn_blog.change_post'):
menu.add_modal_item(_('Edit Blog Post'), reverse('admin:aldryn_blog_post_change', args=(
blog_entry.pk,)),
close_on_url=reverse('admin:aldryn_blog_post_changelist'), active=True)
|
33dd6ab01cea7a2a83d3d9d0c7682f716cbcb8b2 | molecule/default/tests/test_default.py | molecule/default/tests/test_default.py | import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_hosts_file(host):
f = host.file('/etc/hosts')
assert f.exists
assert f.user == 'root'
assert f.group == 'root'
def test_cvmfs_client(host):
"""Test that the CVMFS client is properly installed"""
pkg = host.package('cvmfs')
client = host.file('/usr/bin/cvmfs2')
version = '2.4.3'
assert pkg.is_installed
assert pkg.version.startswith(version)
def test_CODE_RADE_mounted(host):
"""Check that the CODE-RADE repo is mounted"""
assert host.mount_point("/cvmfs/code-rade.africa-grid.org").exists
def test_CODE_RADE_version(host):
"""Check CODE-RADE version"""
cvmfs_version = host.file('/cvmfs/code-rade.africa-grid.org/version')
assert cvmfs_version.exists
assert cvmfs_version.contains('FR3') | import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_hosts_file(host):
"""Basic checks on the host."""
f = host.file('/etc/hosts')
assert f.exists
assert f.user == 'root'
assert f.group == 'root'
def test_cvmfs_client(host):
"""Test that the CVMFS client is properly installed."""
pkg = host.package('cvmfs')
client = host.file('/usr/bin/cvmfs2')
version = '2.4.3'
assert pkg.is_installed
assert pkg.version.startswith(version)
assert client.exists
def test_CODE_RADE_mounted(host):
"""Check that the CODE-RADE repo is mounted"""
assert host.mount_point("/cvmfs/code-rade.africa-grid.org").exists
def test_CODE_RADE_version(host):
"""Check CODE-RADE version."""
cvmfs_version = host.file('/cvmfs/code-rade.africa-grid.org/version')
assert cvmfs_version.exists
assert cvmfs_version.contains('FR3') | Fix lint errors in tests | Fix lint errors in tests
| Python | apache-2.0 | brucellino/cvmfs-client-2.2,brucellino/cvmfs-client-2.2,AAROC/cvmfs-client-2.2,AAROC/cvmfs-client-2.2 | import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_hosts_file(host):
+ """Basic checks on the host."""
f = host.file('/etc/hosts')
assert f.exists
assert f.user == 'root'
assert f.group == 'root'
+
def test_cvmfs_client(host):
- """Test that the CVMFS client is properly installed"""
+ """Test that the CVMFS client is properly installed."""
pkg = host.package('cvmfs')
client = host.file('/usr/bin/cvmfs2')
version = '2.4.3'
assert pkg.is_installed
assert pkg.version.startswith(version)
+ assert client.exists
def test_CODE_RADE_mounted(host):
"""Check that the CODE-RADE repo is mounted"""
assert host.mount_point("/cvmfs/code-rade.africa-grid.org").exists
+
def test_CODE_RADE_version(host):
- """Check CODE-RADE version"""
+ """Check CODE-RADE version."""
cvmfs_version = host.file('/cvmfs/code-rade.africa-grid.org/version')
assert cvmfs_version.exists
assert cvmfs_version.contains('FR3') | Fix lint errors in tests | ## Code Before:
import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_hosts_file(host):
f = host.file('/etc/hosts')
assert f.exists
assert f.user == 'root'
assert f.group == 'root'
def test_cvmfs_client(host):
"""Test that the CVMFS client is properly installed"""
pkg = host.package('cvmfs')
client = host.file('/usr/bin/cvmfs2')
version = '2.4.3'
assert pkg.is_installed
assert pkg.version.startswith(version)
def test_CODE_RADE_mounted(host):
"""Check that the CODE-RADE repo is mounted"""
assert host.mount_point("/cvmfs/code-rade.africa-grid.org").exists
def test_CODE_RADE_version(host):
"""Check CODE-RADE version"""
cvmfs_version = host.file('/cvmfs/code-rade.africa-grid.org/version')
assert cvmfs_version.exists
assert cvmfs_version.contains('FR3')
## Instruction:
Fix lint errors in tests
## Code After:
import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_hosts_file(host):
"""Basic checks on the host."""
f = host.file('/etc/hosts')
assert f.exists
assert f.user == 'root'
assert f.group == 'root'
def test_cvmfs_client(host):
"""Test that the CVMFS client is properly installed."""
pkg = host.package('cvmfs')
client = host.file('/usr/bin/cvmfs2')
version = '2.4.3'
assert pkg.is_installed
assert pkg.version.startswith(version)
assert client.exists
def test_CODE_RADE_mounted(host):
"""Check that the CODE-RADE repo is mounted"""
assert host.mount_point("/cvmfs/code-rade.africa-grid.org").exists
def test_CODE_RADE_version(host):
"""Check CODE-RADE version."""
cvmfs_version = host.file('/cvmfs/code-rade.africa-grid.org/version')
assert cvmfs_version.exists
assert cvmfs_version.contains('FR3') |
7930f968830efd40e1fb200ef331f0c4d955db65 | api/base.py | api/base.py | from django.contrib.auth.models import User
from tastypie.resources import ModelResource
from tastypie import fields
from tastypie.authentication import BasicAuthentication
from tastypie.authorization import DjangoAuthorization, Authorization
from tastypie.constants import ALL, ALL_WITH_RELATIONS
from builds.models import Build
from projects.models import Project
class UserResource(ModelResource):
class Meta:
authentication = BasicAuthentication()
authorization = DjangoAuthorization()
allowed_methods = ['get', 'post', 'put']
queryset = User.objects.all()
fields = ['username', 'first_name',
'last_name', 'last_login',
'id']
filtering = {
"username": ('exact', 'startswith'),
}
class ProjectResource(ModelResource):
user = fields.ForeignKey(UserResource, 'user')
class Meta:
authentication = BasicAuthentication()
authorization = DjangoAuthorization()
allowed_methods = ['get', 'post', 'put']
queryset = Project.objects.all()
filtering = {
"slug": ('exact', 'startswith'),
}
excludes = ['build_pdf', 'path', 'skip', 'featured']
class BuildResource(ModelResource):
project = fields.ForeignKey(ProjectResource, 'project')
class Meta:
allowed_methods = ['get']
queryset = Build.objects.all()
filtering = {
"project": ALL,
}
| from django.contrib.auth.models import User
from tastypie.resources import ModelResource
from tastypie import fields
from tastypie.authentication import BasicAuthentication
from tastypie.authorization import DjangoAuthorization, Authorization
from tastypie.constants import ALL, ALL_WITH_RELATIONS
from builds.models import Build
from projects.models import Project
class UserResource(ModelResource):
class Meta:
#authentication = BasicAuthentication()
#authorization = DjangoAuthorization()
#allowed_methods = ['get', 'post', 'put']
allowed_methods = ['get']
queryset = User.objects.all()
fields = ['username', 'first_name',
'last_name', 'last_login',
'id']
filtering = {
"username": ('exact', 'startswith'),
}
class ProjectResource(ModelResource):
user = fields.ForeignKey(UserResource, 'user')
class Meta:
#authentication = BasicAuthentication()
#authorization = DjangoAuthorization()
allowed_methods = ['get']
queryset = Project.objects.all()
filtering = {
"slug": ('exact', 'startswith'),
}
excludes = ['build_pdf', 'path', 'skip', 'featured']
class BuildResource(ModelResource):
project = fields.ForeignKey(ProjectResource, 'project')
class Meta:
allowed_methods = ['get']
queryset = Build.objects.all()
filtering = {
"project": ALL,
}
| Make API read-only and publically available. | Make API read-only and publically available.
| Python | mit | d0ugal/readthedocs.org,atsuyim/readthedocs.org,clarkperkins/readthedocs.org,soulshake/readthedocs.org,agjohnson/readthedocs.org,SteveViss/readthedocs.org,jerel/readthedocs.org,raven47git/readthedocs.org,rtfd/readthedocs.org,johncosta/private-readthedocs.org,ojii/readthedocs.org,Carreau/readthedocs.org,sid-kap/readthedocs.org,espdev/readthedocs.org,wanghaven/readthedocs.org,d0ugal/readthedocs.org,sils1297/readthedocs.org,nikolas/readthedocs.org,alex/readthedocs.org,jerel/readthedocs.org,clarkperkins/readthedocs.org,stevepiercy/readthedocs.org,GovReady/readthedocs.org,LukasBoersma/readthedocs.org,kenwang76/readthedocs.org,tddv/readthedocs.org,mrshoki/readthedocs.org,wanghaven/readthedocs.org,alex/readthedocs.org,wanghaven/readthedocs.org,stevepiercy/readthedocs.org,CedarLogic/readthedocs.org,wijerasa/readthedocs.org,pombredanne/readthedocs.org,techtonik/readthedocs.org,safwanrahman/readthedocs.org,dirn/readthedocs.org,espdev/readthedocs.org,sunnyzwh/readthedocs.org,raven47git/readthedocs.org,royalwang/readthedocs.org,VishvajitP/readthedocs.org,singingwolfboy/readthedocs.org,davidfischer/readthedocs.org,atsuyim/readthedocs.org,safwanrahman/readthedocs.org,techtonik/readthedocs.org,soulshake/readthedocs.org,gjtorikian/readthedocs.org,takluyver/readthedocs.org,dirn/readthedocs.org,singingwolfboy/readthedocs.org,pombredanne/readthedocs.org,asampat3090/readthedocs.org,fujita-shintaro/readthedocs.org,soulshake/readthedocs.org,asampat3090/readthedocs.org,emawind84/readthedocs.org,asampat3090/readthedocs.org,Tazer/readthedocs.org,sils1297/readthedocs.org,laplaceliu/readthedocs.org,espdev/readthedocs.org,VishvajitP/readthedocs.org,laplaceliu/readthedocs.org,raven47git/readthedocs.org,michaelmcandrew/readthedocs.org,hach-que/readthedocs.org,tddv/readthedocs.org,kenshinthebattosai/readthedocs.org,gjtorikian/readthedocs.org,VishvajitP/readthedocs.org,SteveViss/readthedocs.org,jerel/readthedocs.org,mhils/readthedocs.org,hach-que/readthedocs.org,stevepiercy/readthedocs.org,emawind84/readthedocs.org,mrshoki/readthedocs.org,nyergler/pythonslides,hach-que/readthedocs.org,emawind84/readthedocs.org,jerel/readthedocs.org,sid-kap/readthedocs.org,kenwang76/readthedocs.org,rtfd/readthedocs.org,singingwolfboy/readthedocs.org,titiushko/readthedocs.org,Tazer/readthedocs.org,SteveViss/readthedocs.org,kdkeyser/readthedocs.org,Carreau/readthedocs.org,hach-que/readthedocs.org,Tazer/readthedocs.org,dirn/readthedocs.org,davidfischer/readthedocs.org,kdkeyser/readthedocs.org,emawind84/readthedocs.org,Tazer/readthedocs.org,attakei/readthedocs-oauth,istresearch/readthedocs.org,istresearch/readthedocs.org,VishvajitP/readthedocs.org,LukasBoersma/readthedocs.org,michaelmcandrew/readthedocs.org,titiushko/readthedocs.org,ojii/readthedocs.org,attakei/readthedocs-oauth,istresearch/readthedocs.org,michaelmcandrew/readthedocs.org,kenshinthebattosai/readthedocs.org,fujita-shintaro/readthedocs.org,nikolas/readthedocs.org,mhils/readthedocs.org,kdkeyser/readthedocs.org,davidfischer/readthedocs.org,clarkperkins/readthedocs.org,mrshoki/readthedocs.org,safwanrahman/readthedocs.org,laplaceliu/readthedocs.org,cgourlay/readthedocs.org,nikolas/readthedocs.org,nyergler/pythonslides,sils1297/readthedocs.org,safwanrahman/readthedocs.org,soulshake/readthedocs.org,LukasBoersma/readthedocs.org,attakei/readthedocs-oauth,laplaceliu/readthedocs.org,CedarLogic/readthedocs.org,wanghaven/readthedocs.org,michaelmcandrew/readthedocs.org,raven47git/readthedocs.org,atsuyim/readthedocs.org,KamranMackey/readthedocs.org,techtonik/readthedocs.org,davidfischer/readthedocs.org,KamranMackey/readthedocs.org,asampat3090/readthedocs.org,tddv/readthedocs.org,takluyver/readthedocs.org,d0ugal/readthedocs.org,dirn/readthedocs.org,ojii/readthedocs.org,johncosta/private-readthedocs.org,wijerasa/readthedocs.org,johncosta/private-readthedocs.org,fujita-shintaro/readthedocs.org,Carreau/readthedocs.org,agjohnson/readthedocs.org,rtfd/readthedocs.org,gjtorikian/readthedocs.org,KamranMackey/readthedocs.org,titiushko/readthedocs.org,clarkperkins/readthedocs.org,cgourlay/readthedocs.org,GovReady/readthedocs.org,cgourlay/readthedocs.org,royalwang/readthedocs.org,techtonik/readthedocs.org,attakei/readthedocs-oauth,alex/readthedocs.org,kenwang76/readthedocs.org,LukasBoersma/readthedocs.org,kenshinthebattosai/readthedocs.org,royalwang/readthedocs.org,ojii/readthedocs.org,cgourlay/readthedocs.org,KamranMackey/readthedocs.org,nyergler/pythonslides,espdev/readthedocs.org,atsuyim/readthedocs.org,SteveViss/readthedocs.org,sunnyzwh/readthedocs.org,agjohnson/readthedocs.org,titiushko/readthedocs.org,fujita-shintaro/readthedocs.org,mhils/readthedocs.org,Carreau/readthedocs.org,agjohnson/readthedocs.org,gjtorikian/readthedocs.org,kenwang76/readthedocs.org,mhils/readthedocs.org,wijerasa/readthedocs.org,sunnyzwh/readthedocs.org,kenshinthebattosai/readthedocs.org,alex/readthedocs.org,sid-kap/readthedocs.org,singingwolfboy/readthedocs.org,royalwang/readthedocs.org,mrshoki/readthedocs.org,stevepiercy/readthedocs.org,takluyver/readthedocs.org,nikolas/readthedocs.org,GovReady/readthedocs.org,sils1297/readthedocs.org,takluyver/readthedocs.org,istresearch/readthedocs.org,wijerasa/readthedocs.org,pombredanne/readthedocs.org,rtfd/readthedocs.org,d0ugal/readthedocs.org,GovReady/readthedocs.org,espdev/readthedocs.org,nyergler/pythonslides,sunnyzwh/readthedocs.org,CedarLogic/readthedocs.org,kdkeyser/readthedocs.org,CedarLogic/readthedocs.org,sid-kap/readthedocs.org | from django.contrib.auth.models import User
from tastypie.resources import ModelResource
from tastypie import fields
from tastypie.authentication import BasicAuthentication
from tastypie.authorization import DjangoAuthorization, Authorization
from tastypie.constants import ALL, ALL_WITH_RELATIONS
from builds.models import Build
from projects.models import Project
class UserResource(ModelResource):
class Meta:
- authentication = BasicAuthentication()
+ #authentication = BasicAuthentication()
- authorization = DjangoAuthorization()
+ #authorization = DjangoAuthorization()
- allowed_methods = ['get', 'post', 'put']
+ #allowed_methods = ['get', 'post', 'put']
+ allowed_methods = ['get']
queryset = User.objects.all()
fields = ['username', 'first_name',
'last_name', 'last_login',
'id']
filtering = {
"username": ('exact', 'startswith'),
}
class ProjectResource(ModelResource):
user = fields.ForeignKey(UserResource, 'user')
class Meta:
- authentication = BasicAuthentication()
+ #authentication = BasicAuthentication()
- authorization = DjangoAuthorization()
+ #authorization = DjangoAuthorization()
- allowed_methods = ['get', 'post', 'put']
+ allowed_methods = ['get']
queryset = Project.objects.all()
filtering = {
"slug": ('exact', 'startswith'),
}
excludes = ['build_pdf', 'path', 'skip', 'featured']
class BuildResource(ModelResource):
project = fields.ForeignKey(ProjectResource, 'project')
class Meta:
allowed_methods = ['get']
queryset = Build.objects.all()
filtering = {
"project": ALL,
}
| Make API read-only and publically available. | ## Code Before:
from django.contrib.auth.models import User
from tastypie.resources import ModelResource
from tastypie import fields
from tastypie.authentication import BasicAuthentication
from tastypie.authorization import DjangoAuthorization, Authorization
from tastypie.constants import ALL, ALL_WITH_RELATIONS
from builds.models import Build
from projects.models import Project
class UserResource(ModelResource):
class Meta:
authentication = BasicAuthentication()
authorization = DjangoAuthorization()
allowed_methods = ['get', 'post', 'put']
queryset = User.objects.all()
fields = ['username', 'first_name',
'last_name', 'last_login',
'id']
filtering = {
"username": ('exact', 'startswith'),
}
class ProjectResource(ModelResource):
user = fields.ForeignKey(UserResource, 'user')
class Meta:
authentication = BasicAuthentication()
authorization = DjangoAuthorization()
allowed_methods = ['get', 'post', 'put']
queryset = Project.objects.all()
filtering = {
"slug": ('exact', 'startswith'),
}
excludes = ['build_pdf', 'path', 'skip', 'featured']
class BuildResource(ModelResource):
project = fields.ForeignKey(ProjectResource, 'project')
class Meta:
allowed_methods = ['get']
queryset = Build.objects.all()
filtering = {
"project": ALL,
}
## Instruction:
Make API read-only and publically available.
## Code After:
from django.contrib.auth.models import User
from tastypie.resources import ModelResource
from tastypie import fields
from tastypie.authentication import BasicAuthentication
from tastypie.authorization import DjangoAuthorization, Authorization
from tastypie.constants import ALL, ALL_WITH_RELATIONS
from builds.models import Build
from projects.models import Project
class UserResource(ModelResource):
class Meta:
#authentication = BasicAuthentication()
#authorization = DjangoAuthorization()
#allowed_methods = ['get', 'post', 'put']
allowed_methods = ['get']
queryset = User.objects.all()
fields = ['username', 'first_name',
'last_name', 'last_login',
'id']
filtering = {
"username": ('exact', 'startswith'),
}
class ProjectResource(ModelResource):
user = fields.ForeignKey(UserResource, 'user')
class Meta:
#authentication = BasicAuthentication()
#authorization = DjangoAuthorization()
allowed_methods = ['get']
queryset = Project.objects.all()
filtering = {
"slug": ('exact', 'startswith'),
}
excludes = ['build_pdf', 'path', 'skip', 'featured']
class BuildResource(ModelResource):
project = fields.ForeignKey(ProjectResource, 'project')
class Meta:
allowed_methods = ['get']
queryset = Build.objects.all()
filtering = {
"project": ALL,
}
|
bd193b0fdb7fec412aed24ad8f4c6353372d634f | polling_stations/apps/data_collection/management/commands/import_westberks.py | polling_stations/apps/data_collection/management/commands/import_westberks.py |
from data_collection.management.commands import BaseShpImporter, import_polling_station_shapefiles
class Command(BaseShpImporter):
"""
Imports the Polling Station data from Wokingham Council
"""
council_id = 'E06000037'
districts_name = 'polling_districts'
stations_name = 'polling_places.shp'
def district_record_to_dict(self, record):
return {
'internal_council_id': record[0],
'name': record[2],
}
def station_record_to_dict(self, record):
return {
'internal_council_id': record[4],
'postcode' : record[5].split(',')[-1],
'address' : "\n".join(record[5].split(',')[:-1]),
}
def import_polling_stations(self):
import_polling_station_shapefiles(self)
|
from data_collection.management.commands import BaseShpShpImporter
class Command(BaseShpShpImporter):
"""
Imports the Polling Station data from Wokingham Council
"""
council_id = 'E06000037'
districts_name = 'polling_districts'
stations_name = 'polling_places.shp'
def district_record_to_dict(self, record):
return {
'internal_council_id': record[0],
'name': record[2],
}
def station_record_to_dict(self, record):
return {
'internal_council_id': record[4],
'postcode' : record[5].split(',')[-1],
'address' : "\n".join(record[5].split(',')[:-1]),
}
| Refactor West Berks to use new BaseShpShpImporter | Refactor West Berks to use new BaseShpShpImporter
| Python | bsd-3-clause | chris48s/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,andylolz/UK-Polling-Stations,andylolz/UK-Polling-Stations,chris48s/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,chris48s/UK-Polling-Stations,andylolz/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations |
- from data_collection.management.commands import BaseShpImporter, import_polling_station_shapefiles
+ from data_collection.management.commands import BaseShpShpImporter
- class Command(BaseShpImporter):
+ class Command(BaseShpShpImporter):
"""
Imports the Polling Station data from Wokingham Council
"""
council_id = 'E06000037'
districts_name = 'polling_districts'
stations_name = 'polling_places.shp'
-
+
- def district_record_to_dict(self, record):
+ def district_record_to_dict(self, record):
return {
'internal_council_id': record[0],
'name': record[2],
}
-
def station_record_to_dict(self, record):
return {
'internal_council_id': record[4],
'postcode' : record[5].split(',')[-1],
'address' : "\n".join(record[5].split(',')[:-1]),
}
-
- def import_polling_stations(self):
- import_polling_station_shapefiles(self)
| Refactor West Berks to use new BaseShpShpImporter | ## Code Before:
from data_collection.management.commands import BaseShpImporter, import_polling_station_shapefiles
class Command(BaseShpImporter):
"""
Imports the Polling Station data from Wokingham Council
"""
council_id = 'E06000037'
districts_name = 'polling_districts'
stations_name = 'polling_places.shp'
def district_record_to_dict(self, record):
return {
'internal_council_id': record[0],
'name': record[2],
}
def station_record_to_dict(self, record):
return {
'internal_council_id': record[4],
'postcode' : record[5].split(',')[-1],
'address' : "\n".join(record[5].split(',')[:-1]),
}
def import_polling_stations(self):
import_polling_station_shapefiles(self)
## Instruction:
Refactor West Berks to use new BaseShpShpImporter
## Code After:
from data_collection.management.commands import BaseShpShpImporter
class Command(BaseShpShpImporter):
"""
Imports the Polling Station data from Wokingham Council
"""
council_id = 'E06000037'
districts_name = 'polling_districts'
stations_name = 'polling_places.shp'
def district_record_to_dict(self, record):
return {
'internal_council_id': record[0],
'name': record[2],
}
def station_record_to_dict(self, record):
return {
'internal_council_id': record[4],
'postcode' : record[5].split(',')[-1],
'address' : "\n".join(record[5].split(',')[:-1]),
}
|
a08483b5fc55556b46c08e988ac297b1dffaed48 | app/utils/utilities.py | app/utils/utilities.py | from re import search
from flask import g
from flask_restplus import abort
from flask_httpauth import HTTPBasicAuth
from app.models.user import User
from instance.config import Config
auth = HTTPBasicAuth()
def validate_email(email):
''' Method to check that a valid email is provided '''
email_re = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"
return True if search(email_re, email) else False
@auth.verify_token
def verify_token(token=None):
''' Method to verify token '''
token = request.headers.get('x-access-token')
user_id = User.verify_authentication_token(token)
if user_id:
g.current_user = User.query.filter_by(id=user.id).first()
return True
return False
| from re import search
from flask import g, request
from flask_httpauth import HTTPTokenAuth
from app.models.user import User
auth = HTTPTokenAuth(scheme='Token')
def validate_email(email):
''' Method to check that a valid email is provided '''
email_re = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"
return True if search(email_re, email) else False
@auth.verify_token
def verify_token(token=None):
''' Method to verify token '''
token = request.headers.get('x-access-token')
user_id = User.verify_authentication_token(token)
if user_id:
g.current_user = User.query.filter_by(id=user_id).first()
return True
return False
| Implement HTTPTokenAuth Store user data in global | Implement HTTPTokenAuth
Store user data in global
| Python | mit | Elbertbiggs360/buckelist-api | from re import search
- from flask import g
+ from flask import g, request
- from flask_restplus import abort
- from flask_httpauth import HTTPBasicAuth
+ from flask_httpauth import HTTPTokenAuth
from app.models.user import User
- from instance.config import Config
- auth = HTTPBasicAuth()
+ auth = HTTPTokenAuth(scheme='Token')
def validate_email(email):
- ''' Method to check that a valid email is provided '''
+ ''' Method to check that a valid email is provided '''
email_re = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"
return True if search(email_re, email) else False
@auth.verify_token
def verify_token(token=None):
''' Method to verify token '''
token = request.headers.get('x-access-token')
user_id = User.verify_authentication_token(token)
if user_id:
- g.current_user = User.query.filter_by(id=user.id).first()
+ g.current_user = User.query.filter_by(id=user_id).first()
return True
return False
| Implement HTTPTokenAuth Store user data in global | ## Code Before:
from re import search
from flask import g
from flask_restplus import abort
from flask_httpauth import HTTPBasicAuth
from app.models.user import User
from instance.config import Config
auth = HTTPBasicAuth()
def validate_email(email):
''' Method to check that a valid email is provided '''
email_re = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"
return True if search(email_re, email) else False
@auth.verify_token
def verify_token(token=None):
''' Method to verify token '''
token = request.headers.get('x-access-token')
user_id = User.verify_authentication_token(token)
if user_id:
g.current_user = User.query.filter_by(id=user.id).first()
return True
return False
## Instruction:
Implement HTTPTokenAuth Store user data in global
## Code After:
from re import search
from flask import g, request
from flask_httpauth import HTTPTokenAuth
from app.models.user import User
auth = HTTPTokenAuth(scheme='Token')
def validate_email(email):
''' Method to check that a valid email is provided '''
email_re = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"
return True if search(email_re, email) else False
@auth.verify_token
def verify_token(token=None):
''' Method to verify token '''
token = request.headers.get('x-access-token')
user_id = User.verify_authentication_token(token)
if user_id:
g.current_user = User.query.filter_by(id=user_id).first()
return True
return False
|
0a336447546442ab5d48716223713135a4812adf | get_problem.py | get_problem.py | import sys
from bs4 import BeautifulSoup
from requests import get, codes
def match_soup_class(target, mode='class'):
def do_match(tag):
classes = tag.get(mode, [])
return all(c in classes for c in target)
return do_match
def main():
if len(sys.argv) == 1:
p = 1
else:
p = int(sys.argv[1])
url = 'https://projecteuler.net/problem=%d' % p
r = get(url)
if r.status_code != codes.ok:
print('[url request failed] ', url)
return
soup = BeautifulSoup(r.text, 'html.parser')
for content in soup.find_all(match_soup_class(['problem_content'])):
print(content.text)
if __name__ == '__main__':
main()
| import sys
from bs4 import BeautifulSoup
from requests import get, codes
def match_soup_class(target, mode='class'):
def do_match(tag):
classes = tag.get(mode, [])
return all(c in classes for c in target)
return do_match
def main():
if len(sys.argv) == 1:
p = 1
else:
p = int(sys.argv[1])
url = 'https://projecteuler.net/problem=%d' % p
r = get(url)
if r.status_code != codes.ok:
print('[url request failed] ', url)
return
soup = BeautifulSoup(r.text, 'html.parser')
print("'''")
print('Problem %d' % p)
for content in soup.find_all(match_soup_class(['problem_content'])):
print(content.text)
print("'''")
if __name__ == '__main__':
main()
| ADD comment for python file | ADD comment for python file
| Python | mit | byung-u/ProjectEuler | import sys
from bs4 import BeautifulSoup
from requests import get, codes
def match_soup_class(target, mode='class'):
def do_match(tag):
classes = tag.get(mode, [])
return all(c in classes for c in target)
return do_match
def main():
if len(sys.argv) == 1:
p = 1
else:
p = int(sys.argv[1])
url = 'https://projecteuler.net/problem=%d' % p
r = get(url)
if r.status_code != codes.ok:
print('[url request failed] ', url)
return
soup = BeautifulSoup(r.text, 'html.parser')
+ print("'''")
+ print('Problem %d' % p)
for content in soup.find_all(match_soup_class(['problem_content'])):
print(content.text)
-
+ print("'''")
if __name__ == '__main__':
main()
| ADD comment for python file | ## Code Before:
import sys
from bs4 import BeautifulSoup
from requests import get, codes
def match_soup_class(target, mode='class'):
def do_match(tag):
classes = tag.get(mode, [])
return all(c in classes for c in target)
return do_match
def main():
if len(sys.argv) == 1:
p = 1
else:
p = int(sys.argv[1])
url = 'https://projecteuler.net/problem=%d' % p
r = get(url)
if r.status_code != codes.ok:
print('[url request failed] ', url)
return
soup = BeautifulSoup(r.text, 'html.parser')
for content in soup.find_all(match_soup_class(['problem_content'])):
print(content.text)
if __name__ == '__main__':
main()
## Instruction:
ADD comment for python file
## Code After:
import sys
from bs4 import BeautifulSoup
from requests import get, codes
def match_soup_class(target, mode='class'):
def do_match(tag):
classes = tag.get(mode, [])
return all(c in classes for c in target)
return do_match
def main():
if len(sys.argv) == 1:
p = 1
else:
p = int(sys.argv[1])
url = 'https://projecteuler.net/problem=%d' % p
r = get(url)
if r.status_code != codes.ok:
print('[url request failed] ', url)
return
soup = BeautifulSoup(r.text, 'html.parser')
print("'''")
print('Problem %d' % p)
for content in soup.find_all(match_soup_class(['problem_content'])):
print(content.text)
print("'''")
if __name__ == '__main__':
main()
|
42b4837570fd936c5a7593026fc4868c38d4b09d | base/management/commands/revision_count.py | base/management/commands/revision_count.py |
from django.core.management.base import BaseCommand
from django.apps import apps
# from reversion import revisions as reversion
from reversion.models import Version
from reversion.errors import RegistrationError
class Command(BaseCommand):
help = "Count reversion records for each model"
def handle(self, *args, **options):
total_count = 0
print_pattern = "{:<15} {:<30s} {:>10d}"
prev_app = None
for model in sorted(
apps.get_models(),
key=lambda mod: mod.__module__ + '.' + mod.__name__):
app_name = model._meta.app_label
model_name = model.__name__
try:
qs = Version.objects.get_for_model(model)
count = qs.count()
total_count += count
if prev_app and prev_app != app_name:
print()
print (print_pattern.format(
app_name if prev_app != app_name else "",
model_name, count
))
prev_app = app_name
except RegistrationError:
# model is not registered with reversion ignore
pass
print ()
print (print_pattern.format("Total Records", "", total_count))
|
from django.core.management.base import BaseCommand
from django.apps import apps
# from reversion import revisions as reversion
from reversion.models import Version
from reversion.errors import RegistrationError
class Command(BaseCommand):
help = "Count reversion records for each model"
def handle(self, *args, **options):
total_count = 0
print_pattern = "{:<15} {:<30s} {:>10d}"
title_pattern = "{:<15} {:<30s} {:>10s}"
self.stdout.write(title_pattern.format("App", "Model", "Revisions"))
self.stdout.write(title_pattern.format("===", "=====", "========="))
prev_app = None
for model in sorted(
apps.get_models(),
key=lambda mod: mod.__module__ + '.' + mod.__name__):
app_name = model._meta.app_label
model_name = model.__name__
try:
qs = Version.objects.get_for_model(model)
count = qs.count()
total_count += count
if prev_app and prev_app != app_name:
self.stdout.write("")
self.stdout.write(print_pattern.format(
app_name if prev_app != app_name else "",
model_name, count
))
prev_app = app_name
except RegistrationError:
# model is not registered with reversion ignore
pass
self.stdout.write("")
self.stdout.write(print_pattern.format("Total Records", "", total_count))
| Add titles to columns and use write instead of print | Add titles to columns and use write instead of print
| Python | apache-2.0 | pkimber/base,pkimber/base,pkimber/base,pkimber/base |
from django.core.management.base import BaseCommand
from django.apps import apps
# from reversion import revisions as reversion
from reversion.models import Version
from reversion.errors import RegistrationError
class Command(BaseCommand):
help = "Count reversion records for each model"
def handle(self, *args, **options):
total_count = 0
print_pattern = "{:<15} {:<30s} {:>10d}"
+ title_pattern = "{:<15} {:<30s} {:>10s}"
+ self.stdout.write(title_pattern.format("App", "Model", "Revisions"))
+ self.stdout.write(title_pattern.format("===", "=====", "========="))
prev_app = None
for model in sorted(
apps.get_models(),
key=lambda mod: mod.__module__ + '.' + mod.__name__):
app_name = model._meta.app_label
model_name = model.__name__
try:
qs = Version.objects.get_for_model(model)
count = qs.count()
total_count += count
if prev_app and prev_app != app_name:
- print()
+ self.stdout.write("")
- print (print_pattern.format(
+ self.stdout.write(print_pattern.format(
app_name if prev_app != app_name else "",
model_name, count
))
prev_app = app_name
except RegistrationError:
# model is not registered with reversion ignore
pass
- print ()
+ self.stdout.write("")
- print (print_pattern.format("Total Records", "", total_count))
+ self.stdout.write(print_pattern.format("Total Records", "", total_count))
| Add titles to columns and use write instead of print | ## Code Before:
from django.core.management.base import BaseCommand
from django.apps import apps
# from reversion import revisions as reversion
from reversion.models import Version
from reversion.errors import RegistrationError
class Command(BaseCommand):
help = "Count reversion records for each model"
def handle(self, *args, **options):
total_count = 0
print_pattern = "{:<15} {:<30s} {:>10d}"
prev_app = None
for model in sorted(
apps.get_models(),
key=lambda mod: mod.__module__ + '.' + mod.__name__):
app_name = model._meta.app_label
model_name = model.__name__
try:
qs = Version.objects.get_for_model(model)
count = qs.count()
total_count += count
if prev_app and prev_app != app_name:
print()
print (print_pattern.format(
app_name if prev_app != app_name else "",
model_name, count
))
prev_app = app_name
except RegistrationError:
# model is not registered with reversion ignore
pass
print ()
print (print_pattern.format("Total Records", "", total_count))
## Instruction:
Add titles to columns and use write instead of print
## Code After:
from django.core.management.base import BaseCommand
from django.apps import apps
# from reversion import revisions as reversion
from reversion.models import Version
from reversion.errors import RegistrationError
class Command(BaseCommand):
help = "Count reversion records for each model"
def handle(self, *args, **options):
total_count = 0
print_pattern = "{:<15} {:<30s} {:>10d}"
title_pattern = "{:<15} {:<30s} {:>10s}"
self.stdout.write(title_pattern.format("App", "Model", "Revisions"))
self.stdout.write(title_pattern.format("===", "=====", "========="))
prev_app = None
for model in sorted(
apps.get_models(),
key=lambda mod: mod.__module__ + '.' + mod.__name__):
app_name = model._meta.app_label
model_name = model.__name__
try:
qs = Version.objects.get_for_model(model)
count = qs.count()
total_count += count
if prev_app and prev_app != app_name:
self.stdout.write("")
self.stdout.write(print_pattern.format(
app_name if prev_app != app_name else "",
model_name, count
))
prev_app = app_name
except RegistrationError:
# model is not registered with reversion ignore
pass
self.stdout.write("")
self.stdout.write(print_pattern.format("Total Records", "", total_count))
|
8b7aa0a540c7927b53adf6368e9cb8476816d941 | asciibooth/statuses.py | asciibooth/statuses.py | import random
from . import config
def sampler(source):
def reshuffle():
copy = list(source)
random.shuffle(copy)
return copy
stack = reshuffle()
lastitem = ''
while True:
try:
item = stack.pop()
if item == lastitem:
item = stack.pop()
yield item
lastitem = item
except IndexError:
stack = reshuffle()
continue
def incremental_chance(increment=0.01, start=0.5):
current_chance = start
while True:
r = random.random()
success = (r < current_chance)
if success:
current_chance = start
else:
current_chance += increment
yield success
def status_generator():
random_status = sampler(config.TWEET_MESSAGES)
show_status = incremental_chance(start=0, increment=0.25)
fixed = config.TWEET_FIXED
while True:
status = ''
if next(show_status):
status = next(random_status) + " "
yield "{status}{fixed}".format(status=status, fixed=fixed)
if __name__ == '__main__':
gen = status_generator()
for i in range(0, 20):
print(next(gen))
| import random
from . import config
def sampler(source):
def reshuffle():
copy = list(source)
random.shuffle(copy)
return copy
stack = reshuffle()
lastitem = ''
while True:
try:
item = stack.pop()
if item == lastitem:
item = stack.pop()
yield item
lastitem = item
except IndexError:
stack = reshuffle()
continue
def incremental_chance(start=0.5, increment=0.01):
current_chance = start
while True:
r = random.random()
success = (r < current_chance)
if success:
current_chance = start
else:
current_chance += increment
yield success
def status_generator():
random_status = sampler(config.TWEET_MESSAGES)
show_status = incremental_chance(start=config.TWEET_CHANCE_INITIAL, increment=config.TWEET_CHANCE_INCREMENT)
fixed = config.TWEET_FIXED
while True:
status = ''
if next(show_status):
status = next(random_status) + " "
yield "{status}{fixed}".format(status=status, fixed=fixed)
if __name__ == '__main__':
gen = status_generator()
for i in range(0, 20):
print(next(gen))
| Add configuration options for randomness | Add configuration options for randomness
| Python | cc0-1.0 | jnv/asciibooth,jnv/asciibooth | import random
from . import config
def sampler(source):
def reshuffle():
copy = list(source)
random.shuffle(copy)
return copy
stack = reshuffle()
lastitem = ''
while True:
try:
item = stack.pop()
if item == lastitem:
item = stack.pop()
yield item
lastitem = item
except IndexError:
stack = reshuffle()
continue
- def incremental_chance(increment=0.01, start=0.5):
+ def incremental_chance(start=0.5, increment=0.01):
current_chance = start
while True:
r = random.random()
success = (r < current_chance)
if success:
current_chance = start
else:
current_chance += increment
yield success
def status_generator():
random_status = sampler(config.TWEET_MESSAGES)
- show_status = incremental_chance(start=0, increment=0.25)
+ show_status = incremental_chance(start=config.TWEET_CHANCE_INITIAL, increment=config.TWEET_CHANCE_INCREMENT)
fixed = config.TWEET_FIXED
while True:
status = ''
if next(show_status):
status = next(random_status) + " "
yield "{status}{fixed}".format(status=status, fixed=fixed)
if __name__ == '__main__':
gen = status_generator()
for i in range(0, 20):
print(next(gen))
| Add configuration options for randomness | ## Code Before:
import random
from . import config
def sampler(source):
def reshuffle():
copy = list(source)
random.shuffle(copy)
return copy
stack = reshuffle()
lastitem = ''
while True:
try:
item = stack.pop()
if item == lastitem:
item = stack.pop()
yield item
lastitem = item
except IndexError:
stack = reshuffle()
continue
def incremental_chance(increment=0.01, start=0.5):
current_chance = start
while True:
r = random.random()
success = (r < current_chance)
if success:
current_chance = start
else:
current_chance += increment
yield success
def status_generator():
random_status = sampler(config.TWEET_MESSAGES)
show_status = incremental_chance(start=0, increment=0.25)
fixed = config.TWEET_FIXED
while True:
status = ''
if next(show_status):
status = next(random_status) + " "
yield "{status}{fixed}".format(status=status, fixed=fixed)
if __name__ == '__main__':
gen = status_generator()
for i in range(0, 20):
print(next(gen))
## Instruction:
Add configuration options for randomness
## Code After:
import random
from . import config
def sampler(source):
def reshuffle():
copy = list(source)
random.shuffle(copy)
return copy
stack = reshuffle()
lastitem = ''
while True:
try:
item = stack.pop()
if item == lastitem:
item = stack.pop()
yield item
lastitem = item
except IndexError:
stack = reshuffle()
continue
def incremental_chance(start=0.5, increment=0.01):
current_chance = start
while True:
r = random.random()
success = (r < current_chance)
if success:
current_chance = start
else:
current_chance += increment
yield success
def status_generator():
random_status = sampler(config.TWEET_MESSAGES)
show_status = incremental_chance(start=config.TWEET_CHANCE_INITIAL, increment=config.TWEET_CHANCE_INCREMENT)
fixed = config.TWEET_FIXED
while True:
status = ''
if next(show_status):
status = next(random_status) + " "
yield "{status}{fixed}".format(status=status, fixed=fixed)
if __name__ == '__main__':
gen = status_generator()
for i in range(0, 20):
print(next(gen))
|
0d023a51283d477e4b3d02059361b003a91134e0 | jaspyx/scope.py | jaspyx/scope.py | class Scope(object):
tmp_index = 0
def __init__(self, parent=None):
self.parent = parent
self.prefix = []
self.declarations = {}
self.globals = set()
self.inherited = True
def prefixed(self, name):
return '.'.join(self.prefix + [name])
def declare(self, name, var=True):
self.declarations[name] = var
def get_scope(self, name, inherit=False):
if name in self.declarations and (not inherit or self.inherited):
return self
elif self.parent is not None:
return self.parent.get_scope(name, True)
else:
return None
def declare_global(self, name):
self.globals.add(name)
def is_global(self, name):
return name in self.globals
def get_global_scope(self):
if self.parent:
return self.parent.get_global_scope()
else:
return self
@classmethod
def alloc_temp(cls):
cls.tmp_index += 1
return '__jpx_tmp_%i' % cls.tmp_index
| class Scope(object):
def __init__(self, parent=None):
self.parent = parent
self.prefix = []
self.declarations = {}
self.globals = set()
self.inherited = True
def prefixed(self, name):
return '.'.join(self.prefix + [name])
def declare(self, name, var=True):
self.declarations[name] = var
def get_scope(self, name, inherit=False):
if name in self.declarations and (not inherit or self.inherited):
return self
elif self.parent is not None:
return self.parent.get_scope(name, True)
else:
return None
def declare_global(self, name):
self.globals.add(name)
def is_global(self, name):
return name in self.globals
def get_global_scope(self):
if self.parent:
return self.parent.get_global_scope()
else:
return self
| Remove temp var allocation code. | Remove temp var allocation code.
| Python | mit | ztane/jaspyx,iksteen/jaspyx | class Scope(object):
- tmp_index = 0
-
def __init__(self, parent=None):
self.parent = parent
self.prefix = []
self.declarations = {}
self.globals = set()
self.inherited = True
def prefixed(self, name):
return '.'.join(self.prefix + [name])
def declare(self, name, var=True):
self.declarations[name] = var
def get_scope(self, name, inherit=False):
if name in self.declarations and (not inherit or self.inherited):
return self
elif self.parent is not None:
return self.parent.get_scope(name, True)
else:
return None
def declare_global(self, name):
self.globals.add(name)
def is_global(self, name):
return name in self.globals
def get_global_scope(self):
if self.parent:
return self.parent.get_global_scope()
else:
return self
- @classmethod
- def alloc_temp(cls):
- cls.tmp_index += 1
- return '__jpx_tmp_%i' % cls.tmp_index
- | Remove temp var allocation code. | ## Code Before:
class Scope(object):
tmp_index = 0
def __init__(self, parent=None):
self.parent = parent
self.prefix = []
self.declarations = {}
self.globals = set()
self.inherited = True
def prefixed(self, name):
return '.'.join(self.prefix + [name])
def declare(self, name, var=True):
self.declarations[name] = var
def get_scope(self, name, inherit=False):
if name in self.declarations and (not inherit or self.inherited):
return self
elif self.parent is not None:
return self.parent.get_scope(name, True)
else:
return None
def declare_global(self, name):
self.globals.add(name)
def is_global(self, name):
return name in self.globals
def get_global_scope(self):
if self.parent:
return self.parent.get_global_scope()
else:
return self
@classmethod
def alloc_temp(cls):
cls.tmp_index += 1
return '__jpx_tmp_%i' % cls.tmp_index
## Instruction:
Remove temp var allocation code.
## Code After:
class Scope(object):
def __init__(self, parent=None):
self.parent = parent
self.prefix = []
self.declarations = {}
self.globals = set()
self.inherited = True
def prefixed(self, name):
return '.'.join(self.prefix + [name])
def declare(self, name, var=True):
self.declarations[name] = var
def get_scope(self, name, inherit=False):
if name in self.declarations and (not inherit or self.inherited):
return self
elif self.parent is not None:
return self.parent.get_scope(name, True)
else:
return None
def declare_global(self, name):
self.globals.add(name)
def is_global(self, name):
return name in self.globals
def get_global_scope(self):
if self.parent:
return self.parent.get_global_scope()
else:
return self
|
4524b88eef8a46d40c4d353c3561401ac3689878 | bookmarks/urls.py | bookmarks/urls.py | from django.conf.urls import patterns, url
# for voting
from voting.views import vote_on_object
from bookmarks.models import Bookmark
urlpatterns = patterns('',
url(r'^$', 'bookmarks.views.bookmarks', name="all_bookmarks"),
url(r'^your_bookmarks/$', 'bookmarks.views.your_bookmarks', name="your_bookmarks"),
url(r'^add/$', 'bookmarks.views.add', name="add_bookmark"),
url(r'^(\d+)/delete/$', 'bookmarks.views.delete', name="delete_bookmark_instance"),
# for voting
(r'^(?P<object_id>\d+)/(?P<direction>up|down|clear)vote/?$',
vote_on_object, dict(
model=Bookmark,
template_object_name='bookmark',
template_name='kb/link_confirm_vote.html',
allow_xmlhttprequest=True)),
)
| from django.conf.urls import patterns, url
from django.views.decorators.csrf import csrf_exempt
# for voting
from voting.views import vote_on_object
from bookmarks.models import Bookmark
urlpatterns = patterns('',
url(r'^$', 'bookmarks.views.bookmarks', name="all_bookmarks"),
url(r'^your_bookmarks/$', 'bookmarks.views.your_bookmarks', name="your_bookmarks"),
url(r'^add/$', 'bookmarks.views.add', name="add_bookmark"),
url(r'^(\d+)/delete/$', 'bookmarks.views.delete', name="delete_bookmark_instance"),
# for voting
(r'^(?P<object_id>\d+)/(?P<direction>up|down|clear)vote/?$',
csrf_exempt(vote_on_object), dict(
model=Bookmark,
template_object_name='bookmark',
template_name='kb/link_confirm_vote.html',
allow_xmlhttprequest=True)),
)
| Disable csrf checks for voting | Disable csrf checks for voting
| Python | mit | incuna/incuna-bookmarks,incuna/incuna-bookmarks | from django.conf.urls import patterns, url
+ from django.views.decorators.csrf import csrf_exempt
# for voting
from voting.views import vote_on_object
from bookmarks.models import Bookmark
urlpatterns = patterns('',
url(r'^$', 'bookmarks.views.bookmarks', name="all_bookmarks"),
url(r'^your_bookmarks/$', 'bookmarks.views.your_bookmarks', name="your_bookmarks"),
url(r'^add/$', 'bookmarks.views.add', name="add_bookmark"),
url(r'^(\d+)/delete/$', 'bookmarks.views.delete', name="delete_bookmark_instance"),
# for voting
(r'^(?P<object_id>\d+)/(?P<direction>up|down|clear)vote/?$',
- vote_on_object, dict(
+ csrf_exempt(vote_on_object), dict(
model=Bookmark,
template_object_name='bookmark',
template_name='kb/link_confirm_vote.html',
allow_xmlhttprequest=True)),
)
| Disable csrf checks for voting | ## Code Before:
from django.conf.urls import patterns, url
# for voting
from voting.views import vote_on_object
from bookmarks.models import Bookmark
urlpatterns = patterns('',
url(r'^$', 'bookmarks.views.bookmarks', name="all_bookmarks"),
url(r'^your_bookmarks/$', 'bookmarks.views.your_bookmarks', name="your_bookmarks"),
url(r'^add/$', 'bookmarks.views.add', name="add_bookmark"),
url(r'^(\d+)/delete/$', 'bookmarks.views.delete', name="delete_bookmark_instance"),
# for voting
(r'^(?P<object_id>\d+)/(?P<direction>up|down|clear)vote/?$',
vote_on_object, dict(
model=Bookmark,
template_object_name='bookmark',
template_name='kb/link_confirm_vote.html',
allow_xmlhttprequest=True)),
)
## Instruction:
Disable csrf checks for voting
## Code After:
from django.conf.urls import patterns, url
from django.views.decorators.csrf import csrf_exempt
# for voting
from voting.views import vote_on_object
from bookmarks.models import Bookmark
urlpatterns = patterns('',
url(r'^$', 'bookmarks.views.bookmarks', name="all_bookmarks"),
url(r'^your_bookmarks/$', 'bookmarks.views.your_bookmarks', name="your_bookmarks"),
url(r'^add/$', 'bookmarks.views.add', name="add_bookmark"),
url(r'^(\d+)/delete/$', 'bookmarks.views.delete', name="delete_bookmark_instance"),
# for voting
(r'^(?P<object_id>\d+)/(?P<direction>up|down|clear)vote/?$',
csrf_exempt(vote_on_object), dict(
model=Bookmark,
template_object_name='bookmark',
template_name='kb/link_confirm_vote.html',
allow_xmlhttprequest=True)),
)
|
c2b0f66d5760d61444b4909e40c45993780cd473 | examples/champion.py | examples/champion.py | import cassiopeia as cass
from cassiopeia.core import Champion
def test_cass():
#annie = Champion(name="Annie", region="NA")
annie = Champion(name="Annie")
print(annie.name)
print(annie.title)
print(annie.title)
for spell in annie.spells:
print(spell.name, spell.keywords)
print(annie.info.difficulty)
print(annie.passive.name)
#print(annie.recommended_itemsets[0].item_sets[0].items)
print(annie.free_to_play)
print(annie._Ghost__all_loaded)
print(annie)
return
print()
#ziggs = cass.get_champion(region="NA", "Ziggs")
ziggs = cass.get_champion("Renekton")
print(ziggs.name)
print(ziggs.region)
#print(ziggs.recommended_itemset[0].item_sets[0].items)
print(ziggs.free_to_play)
for spell in ziggs.spells:
for var in spell.variables:
print(spell.name, var)
print(ziggs._Ghost__all_loaded)
if __name__ == "__main__":
test_cass()
| import cassiopeia as cass
from cassiopeia.core import Champion
def test_cass():
#annie = Champion(name="Annie", region="NA")
annie = Champion(name="Annie")
print(annie.name)
print(annie.title)
print(annie.title)
for spell in annie.spells:
print(spell.name, spell.keywords)
print(annie.info.difficulty)
print(annie.passive.name)
#print(annie.recommended_itemsets[0].item_sets[0].items)
print(annie.free_to_play)
print(annie._Ghost__all_loaded)
print(annie)
print()
#ziggs = cass.get_champion(region="NA", "Ziggs")
ziggs = cass.get_champion("Ziggs")
print(ziggs.name)
print(ziggs.region)
#print(ziggs.recommended_itemset[0].item_sets[0].items)
print(ziggs.free_to_play)
for spell in ziggs.spells:
for var in spell.variables:
print(spell.name, var)
print(ziggs._Ghost__all_loaded)
if __name__ == "__main__":
test_cass()
| Remove `return`, get Ziggs instead of Renekton, since we're saving as Ziggs | Remove `return`, get Ziggs instead of Renekton, since we're saving as Ziggs
| Python | mit | robrua/cassiopeia,meraki-analytics/cassiopeia,10se1ucgo/cassiopeia | import cassiopeia as cass
from cassiopeia.core import Champion
def test_cass():
#annie = Champion(name="Annie", region="NA")
annie = Champion(name="Annie")
print(annie.name)
print(annie.title)
print(annie.title)
for spell in annie.spells:
print(spell.name, spell.keywords)
print(annie.info.difficulty)
print(annie.passive.name)
#print(annie.recommended_itemsets[0].item_sets[0].items)
print(annie.free_to_play)
print(annie._Ghost__all_loaded)
print(annie)
- return
print()
#ziggs = cass.get_champion(region="NA", "Ziggs")
- ziggs = cass.get_champion("Renekton")
+ ziggs = cass.get_champion("Ziggs")
print(ziggs.name)
print(ziggs.region)
#print(ziggs.recommended_itemset[0].item_sets[0].items)
print(ziggs.free_to_play)
for spell in ziggs.spells:
for var in spell.variables:
print(spell.name, var)
print(ziggs._Ghost__all_loaded)
if __name__ == "__main__":
test_cass()
| Remove `return`, get Ziggs instead of Renekton, since we're saving as Ziggs | ## Code Before:
import cassiopeia as cass
from cassiopeia.core import Champion
def test_cass():
#annie = Champion(name="Annie", region="NA")
annie = Champion(name="Annie")
print(annie.name)
print(annie.title)
print(annie.title)
for spell in annie.spells:
print(spell.name, spell.keywords)
print(annie.info.difficulty)
print(annie.passive.name)
#print(annie.recommended_itemsets[0].item_sets[0].items)
print(annie.free_to_play)
print(annie._Ghost__all_loaded)
print(annie)
return
print()
#ziggs = cass.get_champion(region="NA", "Ziggs")
ziggs = cass.get_champion("Renekton")
print(ziggs.name)
print(ziggs.region)
#print(ziggs.recommended_itemset[0].item_sets[0].items)
print(ziggs.free_to_play)
for spell in ziggs.spells:
for var in spell.variables:
print(spell.name, var)
print(ziggs._Ghost__all_loaded)
if __name__ == "__main__":
test_cass()
## Instruction:
Remove `return`, get Ziggs instead of Renekton, since we're saving as Ziggs
## Code After:
import cassiopeia as cass
from cassiopeia.core import Champion
def test_cass():
#annie = Champion(name="Annie", region="NA")
annie = Champion(name="Annie")
print(annie.name)
print(annie.title)
print(annie.title)
for spell in annie.spells:
print(spell.name, spell.keywords)
print(annie.info.difficulty)
print(annie.passive.name)
#print(annie.recommended_itemsets[0].item_sets[0].items)
print(annie.free_to_play)
print(annie._Ghost__all_loaded)
print(annie)
print()
#ziggs = cass.get_champion(region="NA", "Ziggs")
ziggs = cass.get_champion("Ziggs")
print(ziggs.name)
print(ziggs.region)
#print(ziggs.recommended_itemset[0].item_sets[0].items)
print(ziggs.free_to_play)
for spell in ziggs.spells:
for var in spell.variables:
print(spell.name, var)
print(ziggs._Ghost__all_loaded)
if __name__ == "__main__":
test_cass()
|
f22eff612427dc5f530858bb47326d69b48aa68a | darchan/urls.py | darchan/urls.py | from __future__ import unicode_literals
from django.conf.urls import patterns, url
urlpatterns = patterns(
'darchan.views',
url(r'^view_matrix/$', 'v_view_last_matrix', name='view_last_matrix'),
url(r'^view_matrix/(?P<builder_id>\d+)/(?P<depth>\d+)/$', 'v_view_matrix',
name='view_matrix'),
url(r'^generate_matrix/$', 'v_generate_matrix', name='generate_matrix'),
url(r'^download_csv/(?P<builder_id>\d+)/(?P<depth>\d+)/$',
'v_download_csv', name='download_csv'),
)
| from django.conf.urls import url
from darchan import views
urlpatterns = [
url(r'^view_matrix/$',
views.v_view_last_matrix, name='view_last_matrix'),
url(r'^view_matrix/(?P<builder_id>\d+)/(?P<depth>\d+)/$',
views.v_view_matrix, name='view_matrix'),
url(r'^generate_matrix/$',
views.v_generate_matrix, name='generate_matrix'),
url(r'^download_csv/(?P<builder_id>\d+)/(?P<depth>\d+)/$',
views.v_download_csv, name='download_csv'),
]
| Update support to Django 1.9 | Update support to Django 1.9
| Python | mpl-2.0 | Pawamoy/django-archan,Pawamoy/django-archan,Pawamoy/django-archan | - from __future__ import unicode_literals
- from django.conf.urls import patterns, url
+ from django.conf.urls import url
+ from darchan import views
- urlpatterns = patterns(
- 'darchan.views',
+ urlpatterns = [
+ url(r'^view_matrix/$',
- url(r'^view_matrix/$', 'v_view_last_matrix', name='view_last_matrix'),
+ views.v_view_last_matrix, name='view_last_matrix'),
- url(r'^view_matrix/(?P<builder_id>\d+)/(?P<depth>\d+)/$', 'v_view_matrix',
+ url(r'^view_matrix/(?P<builder_id>\d+)/(?P<depth>\d+)/$',
- name='view_matrix'),
- url(r'^generate_matrix/$', 'v_generate_matrix', name='generate_matrix'),
+ views.v_view_matrix, name='view_matrix'),
+ url(r'^generate_matrix/$',
+ views.v_generate_matrix, name='generate_matrix'),
url(r'^download_csv/(?P<builder_id>\d+)/(?P<depth>\d+)/$',
- 'v_download_csv', name='download_csv'),
+ views.v_download_csv, name='download_csv'),
- )
+ ]
| Update support to Django 1.9 | ## Code Before:
from __future__ import unicode_literals
from django.conf.urls import patterns, url
urlpatterns = patterns(
'darchan.views',
url(r'^view_matrix/$', 'v_view_last_matrix', name='view_last_matrix'),
url(r'^view_matrix/(?P<builder_id>\d+)/(?P<depth>\d+)/$', 'v_view_matrix',
name='view_matrix'),
url(r'^generate_matrix/$', 'v_generate_matrix', name='generate_matrix'),
url(r'^download_csv/(?P<builder_id>\d+)/(?P<depth>\d+)/$',
'v_download_csv', name='download_csv'),
)
## Instruction:
Update support to Django 1.9
## Code After:
from django.conf.urls import url
from darchan import views
urlpatterns = [
url(r'^view_matrix/$',
views.v_view_last_matrix, name='view_last_matrix'),
url(r'^view_matrix/(?P<builder_id>\d+)/(?P<depth>\d+)/$',
views.v_view_matrix, name='view_matrix'),
url(r'^generate_matrix/$',
views.v_generate_matrix, name='generate_matrix'),
url(r'^download_csv/(?P<builder_id>\d+)/(?P<depth>\d+)/$',
views.v_download_csv, name='download_csv'),
]
|
7e2d6cfa6b6a536d1df6e2d2d523a4bb4094f5eb | src/poliastro/plotting/misc.py | src/poliastro/plotting/misc.py | from poliastro.bodies import (
Earth,
Jupiter,
Mars,
Mercury,
Neptune,
Saturn,
Uranus,
Venus,
)
from poliastro.plotting.core import OrbitPlotter2D, OrbitPlotter3D
from poliastro.twobody import Orbit
def plot_solar_system(outer=True, epoch=None, use_3d=False):
"""
Plots the whole solar system in one single call.
.. versionadded:: 0.9.0
Parameters
------------
outer : bool, optional
Whether to print the outer Solar System, default to True.
epoch: ~astropy.time.Time, optional
Epoch value of the plot, default to J2000.
"""
bodies = [Mercury, Venus, Earth, Mars]
if outer:
bodies.extend([Jupiter, Saturn, Uranus, Neptune])
if use_3d:
op = OrbitPlotter3D()
else:
op = OrbitPlotter2D()
for body in bodies:
orb = Orbit.from_body_ephem(body, epoch)
op.plot(orb, label=str(body))
# Sets frame to the orbit of the Earth by default
# TODO: Wait until https://github.com/poliastro/poliastro/issues/316
# op.set_frame(*Orbit.from_body_ephem(Earth, epoch).pqw())
return op
| from typing import Union
from poliastro.bodies import (
Earth,
Jupiter,
Mars,
Mercury,
Neptune,
Saturn,
Uranus,
Venus,
)
from poliastro.plotting.core import OrbitPlotter2D, OrbitPlotter3D
from poliastro.twobody import Orbit
def plot_solar_system(outer=True, epoch=None, use_3d=False):
"""
Plots the whole solar system in one single call.
.. versionadded:: 0.9.0
Parameters
------------
outer : bool, optional
Whether to print the outer Solar System, default to True.
epoch : ~astropy.time.Time, optional
Epoch value of the plot, default to J2000.
use_3d : bool, optional
Produce 3D plot, default to False.
"""
bodies = [Mercury, Venus, Earth, Mars]
if outer:
bodies.extend([Jupiter, Saturn, Uranus, Neptune])
if use_3d:
op = OrbitPlotter3D() # type: Union[OrbitPlotter3D, OrbitPlotter2D]
else:
op = OrbitPlotter2D()
op.set_frame(*Orbit.from_body_ephem(Earth, epoch).pqw()) # type: ignore
for body in bodies:
orb = Orbit.from_body_ephem(body, epoch)
op.plot(orb, label=str(body))
return op
| Set frame only when using 2D | Set frame only when using 2D
| Python | mit | Juanlu001/poliastro,Juanlu001/poliastro,Juanlu001/poliastro,poliastro/poliastro | + from typing import Union
+
from poliastro.bodies import (
Earth,
Jupiter,
Mars,
Mercury,
Neptune,
Saturn,
Uranus,
Venus,
)
from poliastro.plotting.core import OrbitPlotter2D, OrbitPlotter3D
from poliastro.twobody import Orbit
def plot_solar_system(outer=True, epoch=None, use_3d=False):
"""
Plots the whole solar system in one single call.
.. versionadded:: 0.9.0
Parameters
------------
outer : bool, optional
Whether to print the outer Solar System, default to True.
- epoch: ~astropy.time.Time, optional
+ epoch : ~astropy.time.Time, optional
Epoch value of the plot, default to J2000.
+ use_3d : bool, optional
+ Produce 3D plot, default to False.
+
"""
bodies = [Mercury, Venus, Earth, Mars]
if outer:
bodies.extend([Jupiter, Saturn, Uranus, Neptune])
if use_3d:
- op = OrbitPlotter3D()
+ op = OrbitPlotter3D() # type: Union[OrbitPlotter3D, OrbitPlotter2D]
else:
op = OrbitPlotter2D()
+ op.set_frame(*Orbit.from_body_ephem(Earth, epoch).pqw()) # type: ignore
for body in bodies:
orb = Orbit.from_body_ephem(body, epoch)
op.plot(orb, label=str(body))
- # Sets frame to the orbit of the Earth by default
- # TODO: Wait until https://github.com/poliastro/poliastro/issues/316
- # op.set_frame(*Orbit.from_body_ephem(Earth, epoch).pqw())
-
return op
| Set frame only when using 2D | ## Code Before:
from poliastro.bodies import (
Earth,
Jupiter,
Mars,
Mercury,
Neptune,
Saturn,
Uranus,
Venus,
)
from poliastro.plotting.core import OrbitPlotter2D, OrbitPlotter3D
from poliastro.twobody import Orbit
def plot_solar_system(outer=True, epoch=None, use_3d=False):
"""
Plots the whole solar system in one single call.
.. versionadded:: 0.9.0
Parameters
------------
outer : bool, optional
Whether to print the outer Solar System, default to True.
epoch: ~astropy.time.Time, optional
Epoch value of the plot, default to J2000.
"""
bodies = [Mercury, Venus, Earth, Mars]
if outer:
bodies.extend([Jupiter, Saturn, Uranus, Neptune])
if use_3d:
op = OrbitPlotter3D()
else:
op = OrbitPlotter2D()
for body in bodies:
orb = Orbit.from_body_ephem(body, epoch)
op.plot(orb, label=str(body))
# Sets frame to the orbit of the Earth by default
# TODO: Wait until https://github.com/poliastro/poliastro/issues/316
# op.set_frame(*Orbit.from_body_ephem(Earth, epoch).pqw())
return op
## Instruction:
Set frame only when using 2D
## Code After:
from typing import Union
from poliastro.bodies import (
Earth,
Jupiter,
Mars,
Mercury,
Neptune,
Saturn,
Uranus,
Venus,
)
from poliastro.plotting.core import OrbitPlotter2D, OrbitPlotter3D
from poliastro.twobody import Orbit
def plot_solar_system(outer=True, epoch=None, use_3d=False):
"""
Plots the whole solar system in one single call.
.. versionadded:: 0.9.0
Parameters
------------
outer : bool, optional
Whether to print the outer Solar System, default to True.
epoch : ~astropy.time.Time, optional
Epoch value of the plot, default to J2000.
use_3d : bool, optional
Produce 3D plot, default to False.
"""
bodies = [Mercury, Venus, Earth, Mars]
if outer:
bodies.extend([Jupiter, Saturn, Uranus, Neptune])
if use_3d:
op = OrbitPlotter3D() # type: Union[OrbitPlotter3D, OrbitPlotter2D]
else:
op = OrbitPlotter2D()
op.set_frame(*Orbit.from_body_ephem(Earth, epoch).pqw()) # type: ignore
for body in bodies:
orb = Orbit.from_body_ephem(body, epoch)
op.plot(orb, label=str(body))
return op
|
40347e45646aa57c9181cb289dfa88a3b3eb3396 | experiment/models.py | experiment/models.py | from django.db import models
from experiment_session.models import ExperimentSession
from django.core.validators import MinValueValidator
class Experiment(models.Model):
LIGHTOFF_FIXED = 'fixed'
LIGHTOFF_WAITING = 'waiting'
_LIGHTOFF_CHOICES = (
(LIGHTOFF_FIXED, 'Fixed'),
(LIGHTOFF_WAITING, 'Waiting')
)
AUDIO_NONE = 'none'
AUDIO_BEEP = 'beep'
_AUDIO_CHOICES = (
(AUDIO_NONE, 'None'),
(AUDIO_BEEP, 'Audible beep on error')
)
name = models.CharField(unique=True, max_length=255)
lightoffmode = models.CharField(
choices=_LIGHTOFF_CHOICES,
max_length=30
)
lightofftimeout = models.IntegerField(validators=(MinValueValidator(0),))
audiomode = models.CharField(
choices=_AUDIO_CHOICES,
max_length=30
)
repeatscount = models.IntegerField(
validators=(
MinValueValidator(1),
)
)
createdon = models.DateTimeField(auto_now_add=True, editable=False)
traininglength = models.IntegerField(validators=(MinValueValidator(0),))
instructions = models.CharField(max_length=10000, default='')
def __str__(self):
return self.name
| from django.db import models
from experiment_session.models import ExperimentSession
from django.core.validators import MinValueValidator
class Experiment(models.Model):
LIGHTOFF_FIXED = 'fixed'
LIGHTOFF_WAITING = 'waiting'
_LIGHTOFF_CHOICES = (
(LIGHTOFF_FIXED, 'Fixed'),
(LIGHTOFF_WAITING, 'Waiting')
)
AUDIO_NONE = 'none'
AUDIO_BEEP = 'beep'
_AUDIO_CHOICES = (
(AUDIO_NONE, 'None'),
(AUDIO_BEEP, 'Audible beep on error')
)
name = models.CharField(unique=True, max_length=255)
lightoffmode = models.CharField(
choices=_LIGHTOFF_CHOICES,
max_length=30
)
lightofftimeout = models.IntegerField(validators=(MinValueValidator(0),))
audiomode = models.CharField(
choices=_AUDIO_CHOICES,
max_length=30
)
repeatscount = models.IntegerField(
validators=(
MinValueValidator(1),
)
)
createdon = models.DateTimeField(auto_now_add=True, editable=False)
traininglength = models.IntegerField(validators=(MinValueValidator(0),))
instructions = models.CharField(max_length=10000, blank=True)
def __str__(self):
return self.name
| Allow empty strings as instructions | Allow empty strings as instructions
| Python | mit | piotrb5e3/1023alternative-backend | from django.db import models
from experiment_session.models import ExperimentSession
from django.core.validators import MinValueValidator
class Experiment(models.Model):
LIGHTOFF_FIXED = 'fixed'
LIGHTOFF_WAITING = 'waiting'
_LIGHTOFF_CHOICES = (
(LIGHTOFF_FIXED, 'Fixed'),
(LIGHTOFF_WAITING, 'Waiting')
)
AUDIO_NONE = 'none'
AUDIO_BEEP = 'beep'
_AUDIO_CHOICES = (
(AUDIO_NONE, 'None'),
(AUDIO_BEEP, 'Audible beep on error')
)
name = models.CharField(unique=True, max_length=255)
lightoffmode = models.CharField(
choices=_LIGHTOFF_CHOICES,
max_length=30
)
lightofftimeout = models.IntegerField(validators=(MinValueValidator(0),))
audiomode = models.CharField(
choices=_AUDIO_CHOICES,
max_length=30
)
repeatscount = models.IntegerField(
validators=(
MinValueValidator(1),
)
)
createdon = models.DateTimeField(auto_now_add=True, editable=False)
traininglength = models.IntegerField(validators=(MinValueValidator(0),))
- instructions = models.CharField(max_length=10000, default='')
+ instructions = models.CharField(max_length=10000, blank=True)
def __str__(self):
return self.name
| Allow empty strings as instructions | ## Code Before:
from django.db import models
from experiment_session.models import ExperimentSession
from django.core.validators import MinValueValidator
class Experiment(models.Model):
LIGHTOFF_FIXED = 'fixed'
LIGHTOFF_WAITING = 'waiting'
_LIGHTOFF_CHOICES = (
(LIGHTOFF_FIXED, 'Fixed'),
(LIGHTOFF_WAITING, 'Waiting')
)
AUDIO_NONE = 'none'
AUDIO_BEEP = 'beep'
_AUDIO_CHOICES = (
(AUDIO_NONE, 'None'),
(AUDIO_BEEP, 'Audible beep on error')
)
name = models.CharField(unique=True, max_length=255)
lightoffmode = models.CharField(
choices=_LIGHTOFF_CHOICES,
max_length=30
)
lightofftimeout = models.IntegerField(validators=(MinValueValidator(0),))
audiomode = models.CharField(
choices=_AUDIO_CHOICES,
max_length=30
)
repeatscount = models.IntegerField(
validators=(
MinValueValidator(1),
)
)
createdon = models.DateTimeField(auto_now_add=True, editable=False)
traininglength = models.IntegerField(validators=(MinValueValidator(0),))
instructions = models.CharField(max_length=10000, default='')
def __str__(self):
return self.name
## Instruction:
Allow empty strings as instructions
## Code After:
from django.db import models
from experiment_session.models import ExperimentSession
from django.core.validators import MinValueValidator
class Experiment(models.Model):
LIGHTOFF_FIXED = 'fixed'
LIGHTOFF_WAITING = 'waiting'
_LIGHTOFF_CHOICES = (
(LIGHTOFF_FIXED, 'Fixed'),
(LIGHTOFF_WAITING, 'Waiting')
)
AUDIO_NONE = 'none'
AUDIO_BEEP = 'beep'
_AUDIO_CHOICES = (
(AUDIO_NONE, 'None'),
(AUDIO_BEEP, 'Audible beep on error')
)
name = models.CharField(unique=True, max_length=255)
lightoffmode = models.CharField(
choices=_LIGHTOFF_CHOICES,
max_length=30
)
lightofftimeout = models.IntegerField(validators=(MinValueValidator(0),))
audiomode = models.CharField(
choices=_AUDIO_CHOICES,
max_length=30
)
repeatscount = models.IntegerField(
validators=(
MinValueValidator(1),
)
)
createdon = models.DateTimeField(auto_now_add=True, editable=False)
traininglength = models.IntegerField(validators=(MinValueValidator(0),))
instructions = models.CharField(max_length=10000, blank=True)
def __str__(self):
return self.name
|
04944ccd83e924fed6b351a6073d837a5ce639e9 | sevenbridges/models/compound/price_breakdown.py | sevenbridges/models/compound/price_breakdown.py | import six
from sevenbridges.meta.resource import Resource
from sevenbridges.meta.fields import StringField
class Breakdown(Resource):
"""
Breakdown resource contains price breakdown by storage and computation.
"""
storage = StringField(read_only=True)
computation = StringField(read_only=True)
def __str__(self):
return six.text_type(
'<Breakdown: storage={storage}, computation={computation}>'.format(
storage=self.storage, computation=self.computation
)
)
| import six
from sevenbridges.meta.resource import Resource
from sevenbridges.meta.fields import StringField
class Breakdown(Resource):
"""
Breakdown resource contains price breakdown by storage and computation.
"""
storage = StringField(read_only=True)
computation = StringField(read_only=True)
data_transfer = StringField(read_only=True)
def __str__(self):
if self.data_transfer:
return six.text_type(
'<Breakdown: storage={storage}, computation={computation}, '
'data_transfer={data_transfer}>'.format(
storage=self.storage, computation=self.computation,
data_transfer=self.data_transfer
)
)
return six.text_type(
'<Breakdown: storage={storage}, computation={computation}>'.format(
storage=self.storage, computation=self.computation
)
)
| Add data_transfer to price breakdown | Add data_transfer to price breakdown
| Python | apache-2.0 | sbg/sevenbridges-python | import six
from sevenbridges.meta.resource import Resource
from sevenbridges.meta.fields import StringField
class Breakdown(Resource):
"""
Breakdown resource contains price breakdown by storage and computation.
"""
storage = StringField(read_only=True)
computation = StringField(read_only=True)
+ data_transfer = StringField(read_only=True)
def __str__(self):
+ if self.data_transfer:
+ return six.text_type(
+ '<Breakdown: storage={storage}, computation={computation}, '
+ 'data_transfer={data_transfer}>'.format(
+ storage=self.storage, computation=self.computation,
+ data_transfer=self.data_transfer
+ )
+ )
return six.text_type(
'<Breakdown: storage={storage}, computation={computation}>'.format(
storage=self.storage, computation=self.computation
)
)
| Add data_transfer to price breakdown | ## Code Before:
import six
from sevenbridges.meta.resource import Resource
from sevenbridges.meta.fields import StringField
class Breakdown(Resource):
"""
Breakdown resource contains price breakdown by storage and computation.
"""
storage = StringField(read_only=True)
computation = StringField(read_only=True)
def __str__(self):
return six.text_type(
'<Breakdown: storage={storage}, computation={computation}>'.format(
storage=self.storage, computation=self.computation
)
)
## Instruction:
Add data_transfer to price breakdown
## Code After:
import six
from sevenbridges.meta.resource import Resource
from sevenbridges.meta.fields import StringField
class Breakdown(Resource):
"""
Breakdown resource contains price breakdown by storage and computation.
"""
storage = StringField(read_only=True)
computation = StringField(read_only=True)
data_transfer = StringField(read_only=True)
def __str__(self):
if self.data_transfer:
return six.text_type(
'<Breakdown: storage={storage}, computation={computation}, '
'data_transfer={data_transfer}>'.format(
storage=self.storage, computation=self.computation,
data_transfer=self.data_transfer
)
)
return six.text_type(
'<Breakdown: storage={storage}, computation={computation}>'.format(
storage=self.storage, computation=self.computation
)
)
|
9b0d5796c1e48a3bf294971dc129499876936a36 | send2trash/plat_osx.py | send2trash/plat_osx.py |
from platform import mac_ver
from sys import version_info
# If macOS is 11.0 or newer try to use the pyobjc version to get around #51
# NOTE: pyobjc only supports python >= 3.6
if version_info >= (3, 6) and int(mac_ver()[0].split(".", 1)[0]) >= 11:
try:
from .plat_osx_pyobjc import send2trash
except ImportError:
# Try to fall back to ctypes version, although likely problematic still
from .plat_osx_ctypes import send2trash
else:
# Just use the old version otherwise
from .plat_osx_ctypes import send2trash # noqa: F401
|
from platform import mac_ver
from sys import version_info
# NOTE: version of pyobjc only supports python >= 3.6 and 10.9+
macos_ver = tuple(int(part) for part in mac_ver()[0].split("."))
if version_info >= (3, 6) and macos_ver >= (10, 9):
try:
from .plat_osx_pyobjc import send2trash
except ImportError:
# Try to fall back to ctypes version, although likely problematic still
from .plat_osx_ctypes import send2trash
else:
# Just use the old version otherwise
from .plat_osx_ctypes import send2trash # noqa: F401
| Change conditional for macos pyobjc usage | Change conditional for macos pyobjc usage
macOS 11.x will occasionally identify as 10.16, since there was no real
reason to prevent on all supported platforms allow.
| Python | bsd-3-clause | hsoft/send2trash |
from platform import mac_ver
from sys import version_info
- # If macOS is 11.0 or newer try to use the pyobjc version to get around #51
- # NOTE: pyobjc only supports python >= 3.6
+ # NOTE: version of pyobjc only supports python >= 3.6 and 10.9+
- if version_info >= (3, 6) and int(mac_ver()[0].split(".", 1)[0]) >= 11:
+ macos_ver = tuple(int(part) for part in mac_ver()[0].split("."))
+ if version_info >= (3, 6) and macos_ver >= (10, 9):
try:
from .plat_osx_pyobjc import send2trash
except ImportError:
# Try to fall back to ctypes version, although likely problematic still
from .plat_osx_ctypes import send2trash
else:
# Just use the old version otherwise
from .plat_osx_ctypes import send2trash # noqa: F401
| Change conditional for macos pyobjc usage | ## Code Before:
from platform import mac_ver
from sys import version_info
# If macOS is 11.0 or newer try to use the pyobjc version to get around #51
# NOTE: pyobjc only supports python >= 3.6
if version_info >= (3, 6) and int(mac_ver()[0].split(".", 1)[0]) >= 11:
try:
from .plat_osx_pyobjc import send2trash
except ImportError:
# Try to fall back to ctypes version, although likely problematic still
from .plat_osx_ctypes import send2trash
else:
# Just use the old version otherwise
from .plat_osx_ctypes import send2trash # noqa: F401
## Instruction:
Change conditional for macos pyobjc usage
## Code After:
from platform import mac_ver
from sys import version_info
# NOTE: version of pyobjc only supports python >= 3.6 and 10.9+
macos_ver = tuple(int(part) for part in mac_ver()[0].split("."))
if version_info >= (3, 6) and macos_ver >= (10, 9):
try:
from .plat_osx_pyobjc import send2trash
except ImportError:
# Try to fall back to ctypes version, although likely problematic still
from .plat_osx_ctypes import send2trash
else:
# Just use the old version otherwise
from .plat_osx_ctypes import send2trash # noqa: F401
|
6dbd72af13f017d9b1681da49f60aaf69f0a9e41 | tests/transformer_test_case.py | tests/transformer_test_case.py | class TransformerTestCase(object):
def get_pattern_for_spec(self, patterns, spec):
for pattern in patterns:
if pattern.search(spec):
return pattern
| from spec2scl import settings
from spec2scl import specfile
class TransformerTestCase(object):
def make_prep(self, spec):
# just create one of settings.RUNTIME_SECTIONS, so that we can test all the matching
return '%prep\n' + spec
def get_pattern_for_spec(self, handler, spec_text):
spec = specfile.Specfile(spec_text)
for s_name, s_text in spec.sections:
for i, pattern in enumerate(handler.matches):
if pattern.search(s_text) and s_name in handler.sections[i]:
return pattern
| Improve our custom test case | Improve our custom test case
- create a make_prep method that allows quick creation of prep section from anything for good testing of custom transformers (that usually don't transform header section)
- improve get_pattern_for_spec with section checking
| Python | mit | mbooth101/spec2scl,sclorg/spec2scl | + from spec2scl import settings
+ from spec2scl import specfile
+
class TransformerTestCase(object):
+ def make_prep(self, spec):
+ # just create one of settings.RUNTIME_SECTIONS, so that we can test all the matching
+ return '%prep\n' + spec
+
- def get_pattern_for_spec(self, patterns, spec):
+ def get_pattern_for_spec(self, handler, spec_text):
- for pattern in patterns:
- if pattern.search(spec):
+ spec = specfile.Specfile(spec_text)
+ for s_name, s_text in spec.sections:
+ for i, pattern in enumerate(handler.matches):
+ if pattern.search(s_text) and s_name in handler.sections[i]:
- return pattern
+ return pattern
| Improve our custom test case | ## Code Before:
class TransformerTestCase(object):
def get_pattern_for_spec(self, patterns, spec):
for pattern in patterns:
if pattern.search(spec):
return pattern
## Instruction:
Improve our custom test case
## Code After:
from spec2scl import settings
from spec2scl import specfile
class TransformerTestCase(object):
def make_prep(self, spec):
# just create one of settings.RUNTIME_SECTIONS, so that we can test all the matching
return '%prep\n' + spec
def get_pattern_for_spec(self, handler, spec_text):
spec = specfile.Specfile(spec_text)
for s_name, s_text in spec.sections:
for i, pattern in enumerate(handler.matches):
if pattern.search(s_text) and s_name in handler.sections[i]:
return pattern
|
4de9bee656041c9cfcd91ec61d294460f6427d77 | lib/database.py | lib/database.py |
class Database:
def __init__(self, db):
self.db = db
self.cursor = db.cursor()
def disconnect(self):
self.cursor.close()
self.db.close()
def query(self, sql):
self.cursor.execute(sql)
return self.cursor.fetchall()
def insert(self, sql):
self.cursor.execute(sql)
self.db.commit()
| import pymysql
class Database:
def __init__(self, db):
self.db = db
self.cursor = db.cursor()
def disconnect(self):
self.cursor.close()
self.db.close()
def query(self, sql):
try:
self.cursor.execute(sql)
return self.cursor.fetchall()
except pymysql.OperationalError:
self.db.ping()
self.cursor.execute(sql)
return self.cursor.fetchall()
def insert(self, sql):
try:
self.cursor.execute(sql)
self.db.commit()
except pymysql.OperationalError:
self.db.ping()
self.cursor.execute(sql)
self.db.commit()
| Reconnect if the connection times out. | Reconnect if the connection times out.
| Python | mit | aquaticpond/pyqodbc | + import pymysql
class Database:
def __init__(self, db):
self.db = db
self.cursor = db.cursor()
def disconnect(self):
self.cursor.close()
self.db.close()
def query(self, sql):
+ try:
- self.cursor.execute(sql)
+ self.cursor.execute(sql)
- return self.cursor.fetchall()
+ return self.cursor.fetchall()
+ except pymysql.OperationalError:
+ self.db.ping()
+ self.cursor.execute(sql)
+ return self.cursor.fetchall()
def insert(self, sql):
+ try:
- self.cursor.execute(sql)
+ self.cursor.execute(sql)
- self.db.commit()
+ self.db.commit()
+ except pymysql.OperationalError:
+ self.db.ping()
+ self.cursor.execute(sql)
+ self.db.commit()
-
- | Reconnect if the connection times out. | ## Code Before:
class Database:
def __init__(self, db):
self.db = db
self.cursor = db.cursor()
def disconnect(self):
self.cursor.close()
self.db.close()
def query(self, sql):
self.cursor.execute(sql)
return self.cursor.fetchall()
def insert(self, sql):
self.cursor.execute(sql)
self.db.commit()
## Instruction:
Reconnect if the connection times out.
## Code After:
import pymysql
class Database:
def __init__(self, db):
self.db = db
self.cursor = db.cursor()
def disconnect(self):
self.cursor.close()
self.db.close()
def query(self, sql):
try:
self.cursor.execute(sql)
return self.cursor.fetchall()
except pymysql.OperationalError:
self.db.ping()
self.cursor.execute(sql)
return self.cursor.fetchall()
def insert(self, sql):
try:
self.cursor.execute(sql)
self.db.commit()
except pymysql.OperationalError:
self.db.ping()
self.cursor.execute(sql)
self.db.commit()
|
8657f7aef8944eae718cabaaa7dfd25d2ec95960 | conditions/__init__.py | conditions/__init__.py | from .conditions import *
from .exceptions import *
from .fields import *
from .lists import *
from .types import *
| from .conditions import Condition, CompareCondition
from .exceptions import UndefinedConditionError, InvalidConditionError
from .fields import ConditionsWidget, ConditionsFormField, ConditionsField
from .lists import CondList, CondAllList, CondAnyList, eval_conditions
from .types import conditions_from_module
__all__ = [
'Condition', 'CompareCondition', 'UndefinedConditionError', 'InvalidConditionError', 'ConditionsWidget',
'ConditionsFormField', 'ConditionsField', 'CondList', 'CondAllList', 'CondAnyList', 'eval_conditions',
'conditions_from_module',
]
| Replace star imports with explicit imports | PEP8: Replace star imports with explicit imports
| Python | isc | RevolutionTech/django-conditions,RevolutionTech/django-conditions,RevolutionTech/django-conditions | - from .conditions import *
- from .exceptions import *
- from .fields import *
- from .lists import *
- from .types import *
+ from .conditions import Condition, CompareCondition
+ from .exceptions import UndefinedConditionError, InvalidConditionError
+ from .fields import ConditionsWidget, ConditionsFormField, ConditionsField
+ from .lists import CondList, CondAllList, CondAnyList, eval_conditions
+ from .types import conditions_from_module
+
+ __all__ = [
+ 'Condition', 'CompareCondition', 'UndefinedConditionError', 'InvalidConditionError', 'ConditionsWidget',
+ 'ConditionsFormField', 'ConditionsField', 'CondList', 'CondAllList', 'CondAnyList', 'eval_conditions',
+ 'conditions_from_module',
+ ]
+ | Replace star imports with explicit imports | ## Code Before:
from .conditions import *
from .exceptions import *
from .fields import *
from .lists import *
from .types import *
## Instruction:
Replace star imports with explicit imports
## Code After:
from .conditions import Condition, CompareCondition
from .exceptions import UndefinedConditionError, InvalidConditionError
from .fields import ConditionsWidget, ConditionsFormField, ConditionsField
from .lists import CondList, CondAllList, CondAnyList, eval_conditions
from .types import conditions_from_module
__all__ = [
'Condition', 'CompareCondition', 'UndefinedConditionError', 'InvalidConditionError', 'ConditionsWidget',
'ConditionsFormField', 'ConditionsField', 'CondList', 'CondAllList', 'CondAnyList', 'eval_conditions',
'conditions_from_module',
]
|
7d79e6f0404b04ababaca3d8c50b1e682fd64222 | chainer/initializer.py | chainer/initializer.py | import typing as tp # NOQA
from chainer import types # NOQA
from chainer import utils
class Initializer(object):
"""Initializes array.
It initializes the given array.
Attributes:
dtype: Data type specifier. It is for type check in ``__call__``
function.
"""
def __init__(self, dtype=None):
# type: (tp.Optional[types.DTypeSpec]) -> None
self.dtype = dtype # type: types.DTypeSpec
def __call__(self, array):
# type: (types.NdArray) -> None
"""Initializes given array.
This method destructively changes the value of array.
The derived class is required to implement this method.
The algorithms used to make the new values depend on the
concrete derived classes.
Args:
array (:ref:`ndarray`):
An array to be initialized by this initializer.
"""
raise NotImplementedError()
# Original code forked from MIT licensed keras project
# https://github.com/fchollet/keras/blob/master/keras/initializations.py
def get_fans(shape):
if not isinstance(shape, tuple):
raise ValueError('shape must be tuple')
if len(shape) < 2:
raise ValueError('shape must be of length >= 2: shape={}', shape)
receptive_field_size = utils.size_of_shape(shape[2:])
fan_in = shape[1] * receptive_field_size
fan_out = shape[0] * receptive_field_size
return fan_in, fan_out
| import typing as tp # NOQA
from chainer import types # NOQA
from chainer import utils
class Initializer(object):
"""Initializes array.
It initializes the given array.
Attributes:
dtype: Data type specifier. It is for type check in ``__call__``
function.
"""
def __init__(self, dtype=None):
# type: (tp.Optional[types.DTypeSpec]) -> None
self.dtype = dtype # type: types.DTypeSpec
def __call__(self, array):
# type: (types.NdArray) -> None
"""Initializes given array.
This method destructively changes the value of array.
The derived class is required to implement this method.
The algorithms used to make the new values depend on the
concrete derived classes.
Args:
array (:ref:`ndarray`):
An array to be initialized by this initializer.
"""
raise NotImplementedError()
# Original code forked from MIT licensed keras project
# https://github.com/fchollet/keras/blob/master/keras/initializations.py
def get_fans(shape):
if not isinstance(shape, tuple):
raise ValueError(
'shape must be tuple. Actual type: {}'.format(type(shape)))
if len(shape) < 2:
raise ValueError(
'shape must be of length >= 2. Actual shape: {}'.format(shape))
receptive_field_size = utils.size_of_shape(shape[2:])
fan_in = shape[1] * receptive_field_size
fan_out = shape[0] * receptive_field_size
return fan_in, fan_out
| Fix error messages in get_fans | Fix error messages in get_fans
| Python | mit | niboshi/chainer,tkerola/chainer,niboshi/chainer,keisuke-umezawa/chainer,okuta/chainer,chainer/chainer,wkentaro/chainer,niboshi/chainer,okuta/chainer,okuta/chainer,wkentaro/chainer,pfnet/chainer,okuta/chainer,hvy/chainer,wkentaro/chainer,keisuke-umezawa/chainer,keisuke-umezawa/chainer,keisuke-umezawa/chainer,chainer/chainer,chainer/chainer,hvy/chainer,wkentaro/chainer,chainer/chainer,niboshi/chainer,hvy/chainer,hvy/chainer | import typing as tp # NOQA
from chainer import types # NOQA
from chainer import utils
class Initializer(object):
"""Initializes array.
It initializes the given array.
Attributes:
dtype: Data type specifier. It is for type check in ``__call__``
function.
"""
def __init__(self, dtype=None):
# type: (tp.Optional[types.DTypeSpec]) -> None
self.dtype = dtype # type: types.DTypeSpec
def __call__(self, array):
# type: (types.NdArray) -> None
"""Initializes given array.
This method destructively changes the value of array.
The derived class is required to implement this method.
The algorithms used to make the new values depend on the
concrete derived classes.
Args:
array (:ref:`ndarray`):
An array to be initialized by this initializer.
"""
raise NotImplementedError()
# Original code forked from MIT licensed keras project
# https://github.com/fchollet/keras/blob/master/keras/initializations.py
def get_fans(shape):
if not isinstance(shape, tuple):
- raise ValueError('shape must be tuple')
+ raise ValueError(
+ 'shape must be tuple. Actual type: {}'.format(type(shape)))
if len(shape) < 2:
- raise ValueError('shape must be of length >= 2: shape={}', shape)
+ raise ValueError(
+ 'shape must be of length >= 2. Actual shape: {}'.format(shape))
receptive_field_size = utils.size_of_shape(shape[2:])
fan_in = shape[1] * receptive_field_size
fan_out = shape[0] * receptive_field_size
return fan_in, fan_out
| Fix error messages in get_fans | ## Code Before:
import typing as tp # NOQA
from chainer import types # NOQA
from chainer import utils
class Initializer(object):
"""Initializes array.
It initializes the given array.
Attributes:
dtype: Data type specifier. It is for type check in ``__call__``
function.
"""
def __init__(self, dtype=None):
# type: (tp.Optional[types.DTypeSpec]) -> None
self.dtype = dtype # type: types.DTypeSpec
def __call__(self, array):
# type: (types.NdArray) -> None
"""Initializes given array.
This method destructively changes the value of array.
The derived class is required to implement this method.
The algorithms used to make the new values depend on the
concrete derived classes.
Args:
array (:ref:`ndarray`):
An array to be initialized by this initializer.
"""
raise NotImplementedError()
# Original code forked from MIT licensed keras project
# https://github.com/fchollet/keras/blob/master/keras/initializations.py
def get_fans(shape):
if not isinstance(shape, tuple):
raise ValueError('shape must be tuple')
if len(shape) < 2:
raise ValueError('shape must be of length >= 2: shape={}', shape)
receptive_field_size = utils.size_of_shape(shape[2:])
fan_in = shape[1] * receptive_field_size
fan_out = shape[0] * receptive_field_size
return fan_in, fan_out
## Instruction:
Fix error messages in get_fans
## Code After:
import typing as tp # NOQA
from chainer import types # NOQA
from chainer import utils
class Initializer(object):
"""Initializes array.
It initializes the given array.
Attributes:
dtype: Data type specifier. It is for type check in ``__call__``
function.
"""
def __init__(self, dtype=None):
# type: (tp.Optional[types.DTypeSpec]) -> None
self.dtype = dtype # type: types.DTypeSpec
def __call__(self, array):
# type: (types.NdArray) -> None
"""Initializes given array.
This method destructively changes the value of array.
The derived class is required to implement this method.
The algorithms used to make the new values depend on the
concrete derived classes.
Args:
array (:ref:`ndarray`):
An array to be initialized by this initializer.
"""
raise NotImplementedError()
# Original code forked from MIT licensed keras project
# https://github.com/fchollet/keras/blob/master/keras/initializations.py
def get_fans(shape):
if not isinstance(shape, tuple):
raise ValueError(
'shape must be tuple. Actual type: {}'.format(type(shape)))
if len(shape) < 2:
raise ValueError(
'shape must be of length >= 2. Actual shape: {}'.format(shape))
receptive_field_size = utils.size_of_shape(shape[2:])
fan_in = shape[1] * receptive_field_size
fan_out = shape[0] * receptive_field_size
return fan_in, fan_out
|
3786d778f583f96cb4dce37a175d2c460a020724 | cnxauthoring/events.py | cnxauthoring/events.py |
from pyramid.events import NewRequest
def add_cors_headers(request, response):
settings = request.registry.settings
acac = settings['cors.access_control_allow_credentials']
acao = settings['cors.access_control_allow_origin'].split()
acah = settings['cors.access_control_allow_headers']
acam = settings['cors.access_control_allow_methods']
if acac:
response.headerlist.append(
('Access-Control-Allow-Credentials', acac))
if acao:
if request.host in acao:
response.headerlist.append(
('Access-Control-Allow-Origin', request.host))
else:
response.headerlist.append(
('Access-Control-Allow-Origin', acao[0]))
if acah:
response.headerlist.append(
('Access-Control-Allow-Headers', acah))
if acam:
response.headerlist.append(
('Access-Control-Allow-Methods', acam))
def new_request_subscriber(event):
request = event.request
request.add_response_callback(add_cors_headers)
def main(config):
config.add_subscriber(new_request_subscriber, NewRequest)
|
from pyramid.events import NewRequest
def add_cors_headers(request, response):
settings = request.registry.settings
acac = settings['cors.access_control_allow_credentials']
acao = settings['cors.access_control_allow_origin'].split()
acah = settings['cors.access_control_allow_headers']
acam = settings['cors.access_control_allow_methods']
if acac:
response.headerlist.append(
('Access-Control-Allow-Credentials', acac))
if acao:
if request.headers.get('Origin') in acao:
response.headerlist.append(
('Access-Control-Allow-Origin', request.headers.get('Origin')))
else:
response.headerlist.append(
('Access-Control-Allow-Origin', acao[0]))
if acah:
response.headerlist.append(
('Access-Control-Allow-Headers', acah))
if acam:
response.headerlist.append(
('Access-Control-Allow-Methods', acam))
def new_request_subscriber(event):
request = event.request
request.add_response_callback(add_cors_headers)
def main(config):
config.add_subscriber(new_request_subscriber, NewRequest)
| Fix Access-Control-Allow-Origin to return the request origin | Fix Access-Control-Allow-Origin to return the request origin
request.host is the host part of the request url. For example, if
webview is trying to access http://localhost:8080/users/profile,
request. It's the Origin field in the headers that we should be
matching.
| Python | agpl-3.0 | Connexions/cnx-authoring |
from pyramid.events import NewRequest
def add_cors_headers(request, response):
settings = request.registry.settings
acac = settings['cors.access_control_allow_credentials']
acao = settings['cors.access_control_allow_origin'].split()
acah = settings['cors.access_control_allow_headers']
acam = settings['cors.access_control_allow_methods']
if acac:
response.headerlist.append(
('Access-Control-Allow-Credentials', acac))
if acao:
- if request.host in acao:
+ if request.headers.get('Origin') in acao:
response.headerlist.append(
- ('Access-Control-Allow-Origin', request.host))
+ ('Access-Control-Allow-Origin', request.headers.get('Origin')))
else:
response.headerlist.append(
('Access-Control-Allow-Origin', acao[0]))
if acah:
response.headerlist.append(
('Access-Control-Allow-Headers', acah))
if acam:
response.headerlist.append(
('Access-Control-Allow-Methods', acam))
def new_request_subscriber(event):
request = event.request
request.add_response_callback(add_cors_headers)
def main(config):
config.add_subscriber(new_request_subscriber, NewRequest)
| Fix Access-Control-Allow-Origin to return the request origin | ## Code Before:
from pyramid.events import NewRequest
def add_cors_headers(request, response):
settings = request.registry.settings
acac = settings['cors.access_control_allow_credentials']
acao = settings['cors.access_control_allow_origin'].split()
acah = settings['cors.access_control_allow_headers']
acam = settings['cors.access_control_allow_methods']
if acac:
response.headerlist.append(
('Access-Control-Allow-Credentials', acac))
if acao:
if request.host in acao:
response.headerlist.append(
('Access-Control-Allow-Origin', request.host))
else:
response.headerlist.append(
('Access-Control-Allow-Origin', acao[0]))
if acah:
response.headerlist.append(
('Access-Control-Allow-Headers', acah))
if acam:
response.headerlist.append(
('Access-Control-Allow-Methods', acam))
def new_request_subscriber(event):
request = event.request
request.add_response_callback(add_cors_headers)
def main(config):
config.add_subscriber(new_request_subscriber, NewRequest)
## Instruction:
Fix Access-Control-Allow-Origin to return the request origin
## Code After:
from pyramid.events import NewRequest
def add_cors_headers(request, response):
settings = request.registry.settings
acac = settings['cors.access_control_allow_credentials']
acao = settings['cors.access_control_allow_origin'].split()
acah = settings['cors.access_control_allow_headers']
acam = settings['cors.access_control_allow_methods']
if acac:
response.headerlist.append(
('Access-Control-Allow-Credentials', acac))
if acao:
if request.headers.get('Origin') in acao:
response.headerlist.append(
('Access-Control-Allow-Origin', request.headers.get('Origin')))
else:
response.headerlist.append(
('Access-Control-Allow-Origin', acao[0]))
if acah:
response.headerlist.append(
('Access-Control-Allow-Headers', acah))
if acam:
response.headerlist.append(
('Access-Control-Allow-Methods', acam))
def new_request_subscriber(event):
request = event.request
request.add_response_callback(add_cors_headers)
def main(config):
config.add_subscriber(new_request_subscriber, NewRequest)
|
46741fdbda00a8b1574dfdf0689c8a26454d28f6 | actions/cloudbolt_plugins/aws/poll_for_init_complete.py | actions/cloudbolt_plugins/aws/poll_for_init_complete.py | import sys
import time
from infrastructure.models import Server
from jobs.models import Job
TIMEOUT = 600
def is_reachable(server):
"""
:type server: Server
"""
instance_id = server.ec2serverinfo.instance_id
ec2_region = server.ec2serverinfo.ec2_region
rh = server.resource_handler.cast()
rh.connect_ec2(ec2_region)
wc = rh.resource_technology.work_class
instance = wc.get_instance(instance_id)
conn = instance.connection
status = conn.get_all_instance_status(instance_id)
return True if status[0].instance_status.details[u'reachability'] == u'passed' else False
def run(job, logger=None):
assert isinstance(job, Job)
assert job.type == u'provision'
server = job.server_set.first()
timeout = time.time() + TIMEOUT
while True:
if is_reachable(server):
job.set_progress("EC2 instance is reachable.")
break
elif time.time() > timeout:
job.set_progress("Waited {} seconds. Continuing...".format(TIMEOUT))
break
else:
time.sleep(2)
return "", "", ""
if __name__ == '__main__':
if len(sys.argv) != 2:
print ' Usage: {} <job_id>'.format(sys.argv[0])
sys.exit(1)
print run(Job.objects.get(id=sys.argv[1]))
| import time
from jobs.models import Job
TIMEOUT = 600
def is_reachable(server):
instance_id = server.ec2serverinfo.instance_id
ec2_region = server.ec2serverinfo.ec2_region
rh = server.resource_handler.cast()
rh.connect_ec2(ec2_region)
wc = rh.resource_technology.work_class
instance = wc.get_instance(instance_id)
status = instance.connection.get_all_instance_status(instance_id)
return True if status[0].instance_status.details[u'reachability'] == u'passed' else False
def run(job, logger=None, **kwargs):
assert isinstance(job, Job) and job.type == u'provision'
server = job.server_set.first()
timeout = time.time() + TIMEOUT
while True:
if is_reachable(server):
job.set_progress("EC2 instance is reachable.")
break
elif time.time() > timeout:
job.set_progress("Waited {} seconds. Continuing...".format(TIMEOUT))
break
else:
time.sleep(2)
return "", "", ""
| Clean up poll for init complete script | Clean up poll for init complete script
| Python | apache-2.0 | CloudBoltSoftware/cloudbolt-forge,CloudBoltSoftware/cloudbolt-forge,CloudBoltSoftware/cloudbolt-forge,CloudBoltSoftware/cloudbolt-forge | - import sys
import time
- from infrastructure.models import Server
from jobs.models import Job
TIMEOUT = 600
def is_reachable(server):
- """
- :type server: Server
- """
instance_id = server.ec2serverinfo.instance_id
ec2_region = server.ec2serverinfo.ec2_region
rh = server.resource_handler.cast()
rh.connect_ec2(ec2_region)
wc = rh.resource_technology.work_class
instance = wc.get_instance(instance_id)
- conn = instance.connection
- status = conn.get_all_instance_status(instance_id)
+ status = instance.connection.get_all_instance_status(instance_id)
return True if status[0].instance_status.details[u'reachability'] == u'passed' else False
- def run(job, logger=None):
+ def run(job, logger=None, **kwargs):
+ assert isinstance(job, Job) and job.type == u'provision'
- assert isinstance(job, Job)
- assert job.type == u'provision'
server = job.server_set.first()
timeout = time.time() + TIMEOUT
while True:
if is_reachable(server):
job.set_progress("EC2 instance is reachable.")
break
elif time.time() > timeout:
job.set_progress("Waited {} seconds. Continuing...".format(TIMEOUT))
break
else:
time.sleep(2)
return "", "", ""
-
- if __name__ == '__main__':
- if len(sys.argv) != 2:
- print ' Usage: {} <job_id>'.format(sys.argv[0])
- sys.exit(1)
-
- print run(Job.objects.get(id=sys.argv[1]))
- | Clean up poll for init complete script | ## Code Before:
import sys
import time
from infrastructure.models import Server
from jobs.models import Job
TIMEOUT = 600
def is_reachable(server):
"""
:type server: Server
"""
instance_id = server.ec2serverinfo.instance_id
ec2_region = server.ec2serverinfo.ec2_region
rh = server.resource_handler.cast()
rh.connect_ec2(ec2_region)
wc = rh.resource_technology.work_class
instance = wc.get_instance(instance_id)
conn = instance.connection
status = conn.get_all_instance_status(instance_id)
return True if status[0].instance_status.details[u'reachability'] == u'passed' else False
def run(job, logger=None):
assert isinstance(job, Job)
assert job.type == u'provision'
server = job.server_set.first()
timeout = time.time() + TIMEOUT
while True:
if is_reachable(server):
job.set_progress("EC2 instance is reachable.")
break
elif time.time() > timeout:
job.set_progress("Waited {} seconds. Continuing...".format(TIMEOUT))
break
else:
time.sleep(2)
return "", "", ""
if __name__ == '__main__':
if len(sys.argv) != 2:
print ' Usage: {} <job_id>'.format(sys.argv[0])
sys.exit(1)
print run(Job.objects.get(id=sys.argv[1]))
## Instruction:
Clean up poll for init complete script
## Code After:
import time
from jobs.models import Job
TIMEOUT = 600
def is_reachable(server):
instance_id = server.ec2serverinfo.instance_id
ec2_region = server.ec2serverinfo.ec2_region
rh = server.resource_handler.cast()
rh.connect_ec2(ec2_region)
wc = rh.resource_technology.work_class
instance = wc.get_instance(instance_id)
status = instance.connection.get_all_instance_status(instance_id)
return True if status[0].instance_status.details[u'reachability'] == u'passed' else False
def run(job, logger=None, **kwargs):
assert isinstance(job, Job) and job.type == u'provision'
server = job.server_set.first()
timeout = time.time() + TIMEOUT
while True:
if is_reachable(server):
job.set_progress("EC2 instance is reachable.")
break
elif time.time() > timeout:
job.set_progress("Waited {} seconds. Continuing...".format(TIMEOUT))
break
else:
time.sleep(2)
return "", "", ""
|
fd77039104175a4b5702b46b21a2fa223676ddf4 | bowser/Database.py | bowser/Database.py | import json
import redis
class Database(object):
def __init__(self):
self.redis = redis.StrictRedis(host='redis', port=6379, db=0)
def set_data_of_server_channel(self, server, channel, data):
self.redis.hmset(server, {channel: json.dumps(data)})
def fetch_data_of_server_channel(self, server, channel):
data = self.redis.hget(server, channel)
json_data = json.loads(data.decode('utf-8'))
return json_data
| import json
import redis
class Database(object):
def __init__(self):
self.redis = redis.StrictRedis(host='redis', port=6379, db=0)
def set_data_of_server_channel(self, server, channel, data):
self.redis.hmset(server, {channel: json.dumps(data)})
def fetch_data_of_server_channel(self, server, channel):
data = self.redis.hget(server, channel)
if data is None:
raise KeyError
json_data = json.loads(data.decode('utf-8'))
return json_data
| Raise KeyErrors for missing data in redis | fix: Raise KeyErrors for missing data in redis
| Python | mit | kevinkjt2000/discord-minecraft-server-status | import json
import redis
class Database(object):
def __init__(self):
self.redis = redis.StrictRedis(host='redis', port=6379, db=0)
def set_data_of_server_channel(self, server, channel, data):
self.redis.hmset(server, {channel: json.dumps(data)})
def fetch_data_of_server_channel(self, server, channel):
data = self.redis.hget(server, channel)
+ if data is None:
+ raise KeyError
json_data = json.loads(data.decode('utf-8'))
return json_data
| Raise KeyErrors for missing data in redis | ## Code Before:
import json
import redis
class Database(object):
def __init__(self):
self.redis = redis.StrictRedis(host='redis', port=6379, db=0)
def set_data_of_server_channel(self, server, channel, data):
self.redis.hmset(server, {channel: json.dumps(data)})
def fetch_data_of_server_channel(self, server, channel):
data = self.redis.hget(server, channel)
json_data = json.loads(data.decode('utf-8'))
return json_data
## Instruction:
Raise KeyErrors for missing data in redis
## Code After:
import json
import redis
class Database(object):
def __init__(self):
self.redis = redis.StrictRedis(host='redis', port=6379, db=0)
def set_data_of_server_channel(self, server, channel, data):
self.redis.hmset(server, {channel: json.dumps(data)})
def fetch_data_of_server_channel(self, server, channel):
data = self.redis.hget(server, channel)
if data is None:
raise KeyError
json_data = json.loads(data.decode('utf-8'))
return json_data
|
3f166b110d4e8623966ca29c71445973da4876f9 | armstrong/hatband/forms.py | armstrong/hatband/forms.py | from django import forms
from django.db import models
from . import widgets
RICH_TEXT_DBFIELD_OVERRIDES = {
models.TextField: {'widget': widgets.RichTextWidget},
}
class BackboneFormMixin(object):
class Media:
js = (
'hatband/js/jquery-1.6.2.min.js',
'hatband/js/underscore.js',
'hatband/js/backbone.js',
'hatband/js/backbone-inline-base.js')
class OrderableGenericKeyLookupForm(BackboneFormMixin, forms.ModelForm):
class Meta:
widgets = {
"content_type": forms.HiddenInput(),
"object_id": widgets.GenericKeyWidget(),
"order": forms.HiddenInput(),
}
| from django import forms
from django.conf import settings
from django.db import models
from . import widgets
RICH_TEXT_DBFIELD_OVERRIDES = {
models.TextField: {'widget': widgets.RichTextWidget},
}
class BackboneFormMixin(object):
if getattr(settings, "ARMSTRONG_ADMIN_PROVIDE_STATIC", True):
class Media:
js = (
'hatband/js/jquery-1.6.2.min.js',
'hatband/js/underscore.js',
'hatband/js/backbone.js',
'hatband/js/backbone-inline-base.js')
class OrderableGenericKeyLookupForm(BackboneFormMixin, forms.ModelForm):
class Meta:
widgets = {
"content_type": forms.HiddenInput(),
"object_id": widgets.GenericKeyWidget(),
"order": forms.HiddenInput(),
}
| Make it possible to turn off admin JS | Make it possible to turn off admin JS
| Python | apache-2.0 | armstrong/armstrong.hatband,armstrong/armstrong.hatband,texastribune/armstrong.hatband,armstrong/armstrong.hatband,texastribune/armstrong.hatband,texastribune/armstrong.hatband | from django import forms
+ from django.conf import settings
from django.db import models
from . import widgets
RICH_TEXT_DBFIELD_OVERRIDES = {
models.TextField: {'widget': widgets.RichTextWidget},
}
class BackboneFormMixin(object):
+ if getattr(settings, "ARMSTRONG_ADMIN_PROVIDE_STATIC", True):
- class Media:
+ class Media:
- js = (
+ js = (
- 'hatband/js/jquery-1.6.2.min.js',
+ 'hatband/js/jquery-1.6.2.min.js',
- 'hatband/js/underscore.js',
+ 'hatband/js/underscore.js',
- 'hatband/js/backbone.js',
+ 'hatband/js/backbone.js',
- 'hatband/js/backbone-inline-base.js')
+ 'hatband/js/backbone-inline-base.js')
class OrderableGenericKeyLookupForm(BackboneFormMixin, forms.ModelForm):
class Meta:
widgets = {
"content_type": forms.HiddenInput(),
"object_id": widgets.GenericKeyWidget(),
"order": forms.HiddenInput(),
}
| Make it possible to turn off admin JS | ## Code Before:
from django import forms
from django.db import models
from . import widgets
RICH_TEXT_DBFIELD_OVERRIDES = {
models.TextField: {'widget': widgets.RichTextWidget},
}
class BackboneFormMixin(object):
class Media:
js = (
'hatband/js/jquery-1.6.2.min.js',
'hatband/js/underscore.js',
'hatband/js/backbone.js',
'hatband/js/backbone-inline-base.js')
class OrderableGenericKeyLookupForm(BackboneFormMixin, forms.ModelForm):
class Meta:
widgets = {
"content_type": forms.HiddenInput(),
"object_id": widgets.GenericKeyWidget(),
"order": forms.HiddenInput(),
}
## Instruction:
Make it possible to turn off admin JS
## Code After:
from django import forms
from django.conf import settings
from django.db import models
from . import widgets
RICH_TEXT_DBFIELD_OVERRIDES = {
models.TextField: {'widget': widgets.RichTextWidget},
}
class BackboneFormMixin(object):
if getattr(settings, "ARMSTRONG_ADMIN_PROVIDE_STATIC", True):
class Media:
js = (
'hatband/js/jquery-1.6.2.min.js',
'hatband/js/underscore.js',
'hatband/js/backbone.js',
'hatband/js/backbone-inline-base.js')
class OrderableGenericKeyLookupForm(BackboneFormMixin, forms.ModelForm):
class Meta:
widgets = {
"content_type": forms.HiddenInput(),
"object_id": widgets.GenericKeyWidget(),
"order": forms.HiddenInput(),
}
|
46db910f9b9a150b785ea3b36a9e4f73db326d78 | loader.py | loader.py | from etl import get_local_handles, ingest_feeds, CSV_ETL_CLASSES
from local import LocalConfig
from interface import Marcotti
if __name__ == "__main__":
settings = LocalConfig()
marcotti = Marcotti(settings)
with marcotti.create_session() as sess:
for entity, etl_class in CSV_ETL_CLASSES:
data_file = settings.CSV_DATA[entity]
if data_file is None:
continue
if entity in ['Salaries', 'Partials', 'FieldStats', 'GkStats', 'LeaguePoints']:
params = (sess, settings.COMPETITION_NAME, settings.SEASON_NAME)
else:
params = (sess,)
ingest_feeds(get_local_handles, settings.CSV_DATA_DIR, data_file, etl_class(*params))
| import os
import logging
from etl import get_local_handles, ingest_feeds, CSV_ETL_CLASSES
from local import LocalConfig
from interface import Marcotti
LOG_FORMAT = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s: %(message)s')
ch = logging.FileHandler(os.path.join(LocalConfig().LOG_DIR, 'marcotti.log'))
ch.setLevel(logging.INFO)
ch.setFormatter(LOG_FORMAT)
logger = logging.getLogger('loader')
logger.setLevel(logging.INFO)
logger.addHandler(ch)
if __name__ == "__main__":
settings = LocalConfig()
marcotti = Marcotti(settings)
logger.info("Data ingestion start")
with marcotti.create_session() as sess:
for entity, etl_class in CSV_ETL_CLASSES:
data_file = settings.CSV_DATA[entity]
if data_file is None:
logger.info("Skipping ingestion into %s data model", entity)
else:
if type(data_file) is list:
data_file = os.path.join(*data_file)
logger.info("Ingesting %s into %s data model",
os.path.join(settings.CSV_DATA_DIR, data_file), entity)
if entity in ['Salaries', 'Partials', 'FieldStats', 'GkStats', 'LeaguePoints']:
params = (sess, settings.COMPETITION_NAME, settings.SEASON_NAME)
else:
params = (sess,)
ingest_feeds(get_local_handles, settings.CSV_DATA_DIR, data_file, etl_class(*params))
logger.info("Data ingestion complete")
| Add logging messages to data ingestion tool | Add logging messages to data ingestion tool
| Python | mit | soccermetrics/marcotti-mls | + import os
+ import logging
+
from etl import get_local_handles, ingest_feeds, CSV_ETL_CLASSES
from local import LocalConfig
from interface import Marcotti
+ LOG_FORMAT = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s: %(message)s')
+ ch = logging.FileHandler(os.path.join(LocalConfig().LOG_DIR, 'marcotti.log'))
+ ch.setLevel(logging.INFO)
+ ch.setFormatter(LOG_FORMAT)
+
+ logger = logging.getLogger('loader')
+ logger.setLevel(logging.INFO)
+ logger.addHandler(ch)
+
+
if __name__ == "__main__":
settings = LocalConfig()
marcotti = Marcotti(settings)
+ logger.info("Data ingestion start")
with marcotti.create_session() as sess:
for entity, etl_class in CSV_ETL_CLASSES:
data_file = settings.CSV_DATA[entity]
if data_file is None:
+ logger.info("Skipping ingestion into %s data model", entity)
- continue
- if entity in ['Salaries', 'Partials', 'FieldStats', 'GkStats', 'LeaguePoints']:
- params = (sess, settings.COMPETITION_NAME, settings.SEASON_NAME)
else:
+ if type(data_file) is list:
+ data_file = os.path.join(*data_file)
+ logger.info("Ingesting %s into %s data model",
+ os.path.join(settings.CSV_DATA_DIR, data_file), entity)
+ if entity in ['Salaries', 'Partials', 'FieldStats', 'GkStats', 'LeaguePoints']:
+ params = (sess, settings.COMPETITION_NAME, settings.SEASON_NAME)
+ else:
- params = (sess,)
+ params = (sess,)
- ingest_feeds(get_local_handles, settings.CSV_DATA_DIR, data_file, etl_class(*params))
+ ingest_feeds(get_local_handles, settings.CSV_DATA_DIR, data_file, etl_class(*params))
+ logger.info("Data ingestion complete")
| Add logging messages to data ingestion tool | ## Code Before:
from etl import get_local_handles, ingest_feeds, CSV_ETL_CLASSES
from local import LocalConfig
from interface import Marcotti
if __name__ == "__main__":
settings = LocalConfig()
marcotti = Marcotti(settings)
with marcotti.create_session() as sess:
for entity, etl_class in CSV_ETL_CLASSES:
data_file = settings.CSV_DATA[entity]
if data_file is None:
continue
if entity in ['Salaries', 'Partials', 'FieldStats', 'GkStats', 'LeaguePoints']:
params = (sess, settings.COMPETITION_NAME, settings.SEASON_NAME)
else:
params = (sess,)
ingest_feeds(get_local_handles, settings.CSV_DATA_DIR, data_file, etl_class(*params))
## Instruction:
Add logging messages to data ingestion tool
## Code After:
import os
import logging
from etl import get_local_handles, ingest_feeds, CSV_ETL_CLASSES
from local import LocalConfig
from interface import Marcotti
LOG_FORMAT = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s: %(message)s')
ch = logging.FileHandler(os.path.join(LocalConfig().LOG_DIR, 'marcotti.log'))
ch.setLevel(logging.INFO)
ch.setFormatter(LOG_FORMAT)
logger = logging.getLogger('loader')
logger.setLevel(logging.INFO)
logger.addHandler(ch)
if __name__ == "__main__":
settings = LocalConfig()
marcotti = Marcotti(settings)
logger.info("Data ingestion start")
with marcotti.create_session() as sess:
for entity, etl_class in CSV_ETL_CLASSES:
data_file = settings.CSV_DATA[entity]
if data_file is None:
logger.info("Skipping ingestion into %s data model", entity)
else:
if type(data_file) is list:
data_file = os.path.join(*data_file)
logger.info("Ingesting %s into %s data model",
os.path.join(settings.CSV_DATA_DIR, data_file), entity)
if entity in ['Salaries', 'Partials', 'FieldStats', 'GkStats', 'LeaguePoints']:
params = (sess, settings.COMPETITION_NAME, settings.SEASON_NAME)
else:
params = (sess,)
ingest_feeds(get_local_handles, settings.CSV_DATA_DIR, data_file, etl_class(*params))
logger.info("Data ingestion complete")
|
dfc6b2d2d8cda75349dfab33d9639b5ea24cc520 | contentcuration/contentcuration/ricecooker_versions.py | contentcuration/contentcuration/ricecooker_versions.py | import xmlrpclib
from socket import gaierror
VERSION_OK = "0.5.13"
try:
pypi = xmlrpclib.ServerProxy('https://pypi.python.org/pypi')
VERSION_OK = pypi.package_releases('ricecooker')[0]
except gaierror:
pass
VERSION_OK_MESSAGE = "Ricecooker v{} is up-to-date."
VERSION_SOFT_WARNING = "0.5.6"
VERSION_SOFT_WARNING_MESSAGE = "You are using Ricecooker v{}, however v{} is available. You should consider upgrading your Ricecooker."
VERSION_HARD_WARNING = "0.3.13"
VERSION_HARD_WARNING_MESSAGE = "Ricecooker v{} is deprecated. Any channels created with this version will be unlinked with any future upgrades. You are strongly recommended to upgrade to v{}."
VERSION_ERROR = None
VERSION_ERROR_MESSAGE = "Ricecooker v{} is no longer compatible. You must upgrade to v{} to continue."
| import xmlrpclib
from socket import gaierror, error
VERSION_OK = "0.6.0"
try:
pypi = xmlrpclib.ServerProxy('https://pypi.python.org/pypi')
VERSION_OK = pypi.package_releases('ricecooker')[0]
except (gaierror, error):
pass
VERSION_OK_MESSAGE = "Ricecooker v{} is up-to-date."
VERSION_SOFT_WARNING = "0.5.6"
VERSION_SOFT_WARNING_MESSAGE = "You are using Ricecooker v{}, however v{} is available. You should consider upgrading your Ricecooker."
VERSION_HARD_WARNING = "0.3.13"
VERSION_HARD_WARNING_MESSAGE = "Ricecooker v{} is deprecated. Any channels created with this version will be unlinked with any future upgrades. You are strongly recommended to upgrade to v{}."
VERSION_ERROR = None
VERSION_ERROR_MESSAGE = "Ricecooker v{} is no longer compatible. You must upgrade to v{} to continue."
| Add error handling to reduce dependency on pypi | Add error handling to reduce dependency on pypi
| Python | mit | DXCanas/content-curation,DXCanas/content-curation,jayoshih/content-curation,jayoshih/content-curation,jayoshih/content-curation,jayoshih/content-curation,fle-internal/content-curation,fle-internal/content-curation,fle-internal/content-curation,fle-internal/content-curation,DXCanas/content-curation,DXCanas/content-curation | import xmlrpclib
- from socket import gaierror
+ from socket import gaierror, error
- VERSION_OK = "0.5.13"
+ VERSION_OK = "0.6.0"
try:
pypi = xmlrpclib.ServerProxy('https://pypi.python.org/pypi')
VERSION_OK = pypi.package_releases('ricecooker')[0]
- except gaierror:
+ except (gaierror, error):
pass
VERSION_OK_MESSAGE = "Ricecooker v{} is up-to-date."
VERSION_SOFT_WARNING = "0.5.6"
VERSION_SOFT_WARNING_MESSAGE = "You are using Ricecooker v{}, however v{} is available. You should consider upgrading your Ricecooker."
VERSION_HARD_WARNING = "0.3.13"
VERSION_HARD_WARNING_MESSAGE = "Ricecooker v{} is deprecated. Any channels created with this version will be unlinked with any future upgrades. You are strongly recommended to upgrade to v{}."
VERSION_ERROR = None
VERSION_ERROR_MESSAGE = "Ricecooker v{} is no longer compatible. You must upgrade to v{} to continue."
| Add error handling to reduce dependency on pypi | ## Code Before:
import xmlrpclib
from socket import gaierror
VERSION_OK = "0.5.13"
try:
pypi = xmlrpclib.ServerProxy('https://pypi.python.org/pypi')
VERSION_OK = pypi.package_releases('ricecooker')[0]
except gaierror:
pass
VERSION_OK_MESSAGE = "Ricecooker v{} is up-to-date."
VERSION_SOFT_WARNING = "0.5.6"
VERSION_SOFT_WARNING_MESSAGE = "You are using Ricecooker v{}, however v{} is available. You should consider upgrading your Ricecooker."
VERSION_HARD_WARNING = "0.3.13"
VERSION_HARD_WARNING_MESSAGE = "Ricecooker v{} is deprecated. Any channels created with this version will be unlinked with any future upgrades. You are strongly recommended to upgrade to v{}."
VERSION_ERROR = None
VERSION_ERROR_MESSAGE = "Ricecooker v{} is no longer compatible. You must upgrade to v{} to continue."
## Instruction:
Add error handling to reduce dependency on pypi
## Code After:
import xmlrpclib
from socket import gaierror, error
VERSION_OK = "0.6.0"
try:
pypi = xmlrpclib.ServerProxy('https://pypi.python.org/pypi')
VERSION_OK = pypi.package_releases('ricecooker')[0]
except (gaierror, error):
pass
VERSION_OK_MESSAGE = "Ricecooker v{} is up-to-date."
VERSION_SOFT_WARNING = "0.5.6"
VERSION_SOFT_WARNING_MESSAGE = "You are using Ricecooker v{}, however v{} is available. You should consider upgrading your Ricecooker."
VERSION_HARD_WARNING = "0.3.13"
VERSION_HARD_WARNING_MESSAGE = "Ricecooker v{} is deprecated. Any channels created with this version will be unlinked with any future upgrades. You are strongly recommended to upgrade to v{}."
VERSION_ERROR = None
VERSION_ERROR_MESSAGE = "Ricecooker v{} is no longer compatible. You must upgrade to v{} to continue."
|
6cfc9de7fe8fd048a75845a69bdeefc7c742bae4 | oneall/django_oneall/management/commands/emaillogin.py | oneall/django_oneall/management/commands/emaillogin.py | from django.core.management.base import BaseCommand
from django.core.urlresolvers import reverse
from ...auth import EmailTokenAuthBackend
class Command(BaseCommand):
help = "E-mail login without sending the actual e-mail."
def add_arguments(self, parser):
parser.add_argument('email', type=str)
def handle(self, email, **options):
if '@' not in email:
self.stderr.write("Failed. E-mail is mandatory.")
return 1
query_string = EmailTokenAuthBackend().issue(email)
self.stdout.write("Complete login with: %s?%s" % (reverse('oneall-login'), query_string))
| from django.core.mail import EmailMessage
from django.core.management.base import BaseCommand
from django.core.urlresolvers import reverse
from ...auth import EmailTokenAuthBackend
class Command(BaseCommand):
help = "Issues an e-mail login token."
def add_arguments(self, parser):
parser.add_argument('-s', '--send', dest='send', action='store_true',
help="Actually e-mail the token instead of only displaying it.")
parser.add_argument('email', type=str)
def handle(self, email, send, **options):
if '@' not in email:
self.stderr.write("Failed. E-mail is mandatory.")
return
query_string = EmailTokenAuthBackend().issue(email)
msg = "Complete login with: %s?%s" % (reverse('oneall-login'), query_string)
self.stdout.write(msg)
if send:
mail = EmailMessage()
mail.to = [email]
mail.subject = 'Login Test'
mail.body = msg
try:
sent = mail.send()
self.stdout.write("Sent %d message." % sent)
except ConnectionError as e:
self.stderr.write(str(e))
| Add the possibility of testing SMTP from the command-line. | Add the possibility of testing SMTP from the command-line.
| Python | mit | leandigo/django-oneall,ckot/django-oneall,leandigo/django-oneall,ckot/django-oneall | + from django.core.mail import EmailMessage
from django.core.management.base import BaseCommand
from django.core.urlresolvers import reverse
from ...auth import EmailTokenAuthBackend
class Command(BaseCommand):
- help = "E-mail login without sending the actual e-mail."
+ help = "Issues an e-mail login token."
def add_arguments(self, parser):
+ parser.add_argument('-s', '--send', dest='send', action='store_true',
+ help="Actually e-mail the token instead of only displaying it.")
parser.add_argument('email', type=str)
- def handle(self, email, **options):
+ def handle(self, email, send, **options):
if '@' not in email:
self.stderr.write("Failed. E-mail is mandatory.")
- return 1
+ return
query_string = EmailTokenAuthBackend().issue(email)
- self.stdout.write("Complete login with: %s?%s" % (reverse('oneall-login'), query_string))
+ msg = "Complete login with: %s?%s" % (reverse('oneall-login'), query_string)
+ self.stdout.write(msg)
+ if send:
+ mail = EmailMessage()
+ mail.to = [email]
+ mail.subject = 'Login Test'
+ mail.body = msg
+ try:
+ sent = mail.send()
+ self.stdout.write("Sent %d message." % sent)
+ except ConnectionError as e:
+ self.stderr.write(str(e))
| Add the possibility of testing SMTP from the command-line. | ## Code Before:
from django.core.management.base import BaseCommand
from django.core.urlresolvers import reverse
from ...auth import EmailTokenAuthBackend
class Command(BaseCommand):
help = "E-mail login without sending the actual e-mail."
def add_arguments(self, parser):
parser.add_argument('email', type=str)
def handle(self, email, **options):
if '@' not in email:
self.stderr.write("Failed. E-mail is mandatory.")
return 1
query_string = EmailTokenAuthBackend().issue(email)
self.stdout.write("Complete login with: %s?%s" % (reverse('oneall-login'), query_string))
## Instruction:
Add the possibility of testing SMTP from the command-line.
## Code After:
from django.core.mail import EmailMessage
from django.core.management.base import BaseCommand
from django.core.urlresolvers import reverse
from ...auth import EmailTokenAuthBackend
class Command(BaseCommand):
help = "Issues an e-mail login token."
def add_arguments(self, parser):
parser.add_argument('-s', '--send', dest='send', action='store_true',
help="Actually e-mail the token instead of only displaying it.")
parser.add_argument('email', type=str)
def handle(self, email, send, **options):
if '@' not in email:
self.stderr.write("Failed. E-mail is mandatory.")
return
query_string = EmailTokenAuthBackend().issue(email)
msg = "Complete login with: %s?%s" % (reverse('oneall-login'), query_string)
self.stdout.write(msg)
if send:
mail = EmailMessage()
mail.to = [email]
mail.subject = 'Login Test'
mail.body = msg
try:
sent = mail.send()
self.stdout.write("Sent %d message." % sent)
except ConnectionError as e:
self.stderr.write(str(e))
|
7a936665eff8a6a8f6889334ad2238cbfcded18b | member.py | member.py | import requests
from credentials import label_id
from gmailauth import refresh
access_token = refresh()
headers = {'Authorization': ('Bearer ' + access_token)}
def list_messages(headers):
params = {'labelIds': label_id, 'q': 'newer_than:3d'}
r = requests.get('https://www.googleapis.com/gmail/v1/users/me/messages',
headers=headers, params=params)
j = r.json()
messages = []
if 'messages' in j:
messages.extend(j['messages'])
# return messages
message_ids = []
for item in messages:
message_ids.append(item['id'])
return message_ids
print(list_messages(headers))
def get_message(headers, identity):
params = {'id': identity, format: 'metadata'}
r = requests.get('https://www.googleapis.com/gmail/v1/users/me/messages/id',
headers=headers, params=params)
j = r.json()
print(r.status_code, r.reason)
h = j['payload']
subject = ''
for header in h['headers']:
if header['name'] == 'Subject':
subject = header['value']
break
print(subject)
for item in list_messages(headers):
get_message(headers, item)
# get_message(headers, list_messages(headers))
| import requests
from base64 import urlsafe_b64decode
from credentials import label_id, url1, url2
from gmailauth import refresh
# access_token = refresh()
headers = {'Authorization': ('Bearer ' + access_token)}
def list_messages(headers):
params = {'labelIds': label_id, 'q': 'newer_than:2d'}
r = requests.get('https://www.googleapis.com/gmail/v1/users/me/messages',
headers=headers, params=params)
j = r.json()
messages = []
if 'messages' in j:
messages.extend(j['messages'])
# return messages
message_ids = []
for item in messages:
message_ids.append(item['id'])
return message_ids
def get_message(headers, identity):
params = {'id': identity, 'format': 'raw'}
r = requests.get('https://www.googleapis.com/gmail/v1/users/me/messages/id',
headers=headers, params=params)
j = r.json()
raw = j['raw']
d = urlsafe_b64decode(raw)
p = d.decode()
s = p.find('https')
l = len(p)
print(p[s:l])
print('----------')
return(p[s:l])
# for item in list_messages(headers):
# get_message(headers, item)
| Return the order details URL from email body. | Return the order details URL from email body.
There is currently no Agile API method that will return the order
details for an activity so the URL from the email must be used in
conjunction with a web scraper to get the relevant details.
| Python | mit | deadlyraptor/reels | import requests
+ from base64 import urlsafe_b64decode
- from credentials import label_id
+ from credentials import label_id, url1, url2
from gmailauth import refresh
- access_token = refresh()
+ # access_token = refresh()
headers = {'Authorization': ('Bearer ' + access_token)}
def list_messages(headers):
- params = {'labelIds': label_id, 'q': 'newer_than:3d'}
+ params = {'labelIds': label_id, 'q': 'newer_than:2d'}
r = requests.get('https://www.googleapis.com/gmail/v1/users/me/messages',
headers=headers, params=params)
j = r.json()
messages = []
if 'messages' in j:
messages.extend(j['messages'])
# return messages
message_ids = []
for item in messages:
message_ids.append(item['id'])
return message_ids
- print(list_messages(headers))
-
def get_message(headers, identity):
- params = {'id': identity, format: 'metadata'}
+ params = {'id': identity, 'format': 'raw'}
r = requests.get('https://www.googleapis.com/gmail/v1/users/me/messages/id',
headers=headers, params=params)
j = r.json()
- print(r.status_code, r.reason)
- h = j['payload']
- subject = ''
- for header in h['headers']:
- if header['name'] == 'Subject':
- subject = header['value']
- break
- print(subject)
+ raw = j['raw']
+ d = urlsafe_b64decode(raw)
+ p = d.decode()
+ s = p.find('https')
+ l = len(p)
+ print(p[s:l])
+ print('----------')
+ return(p[s:l])
- for item in list_messages(headers):
+ # for item in list_messages(headers):
- get_message(headers, item)
+ # get_message(headers, item)
- # get_message(headers, list_messages(headers))
- | Return the order details URL from email body. | ## Code Before:
import requests
from credentials import label_id
from gmailauth import refresh
access_token = refresh()
headers = {'Authorization': ('Bearer ' + access_token)}
def list_messages(headers):
params = {'labelIds': label_id, 'q': 'newer_than:3d'}
r = requests.get('https://www.googleapis.com/gmail/v1/users/me/messages',
headers=headers, params=params)
j = r.json()
messages = []
if 'messages' in j:
messages.extend(j['messages'])
# return messages
message_ids = []
for item in messages:
message_ids.append(item['id'])
return message_ids
print(list_messages(headers))
def get_message(headers, identity):
params = {'id': identity, format: 'metadata'}
r = requests.get('https://www.googleapis.com/gmail/v1/users/me/messages/id',
headers=headers, params=params)
j = r.json()
print(r.status_code, r.reason)
h = j['payload']
subject = ''
for header in h['headers']:
if header['name'] == 'Subject':
subject = header['value']
break
print(subject)
for item in list_messages(headers):
get_message(headers, item)
# get_message(headers, list_messages(headers))
## Instruction:
Return the order details URL from email body.
## Code After:
import requests
from base64 import urlsafe_b64decode
from credentials import label_id, url1, url2
from gmailauth import refresh
# access_token = refresh()
headers = {'Authorization': ('Bearer ' + access_token)}
def list_messages(headers):
params = {'labelIds': label_id, 'q': 'newer_than:2d'}
r = requests.get('https://www.googleapis.com/gmail/v1/users/me/messages',
headers=headers, params=params)
j = r.json()
messages = []
if 'messages' in j:
messages.extend(j['messages'])
# return messages
message_ids = []
for item in messages:
message_ids.append(item['id'])
return message_ids
def get_message(headers, identity):
params = {'id': identity, 'format': 'raw'}
r = requests.get('https://www.googleapis.com/gmail/v1/users/me/messages/id',
headers=headers, params=params)
j = r.json()
raw = j['raw']
d = urlsafe_b64decode(raw)
p = d.decode()
s = p.find('https')
l = len(p)
print(p[s:l])
print('----------')
return(p[s:l])
# for item in list_messages(headers):
# get_message(headers, item)
|
ed11fa0ebc365b8a7b0f31c8b09bf23b891e44b6 | discover_tests.py | discover_tests.py | import os
import sys
import unittest
def additional_tests():
setup_file = sys.modules['__main__'].__file__
setup_dir = os.path.abspath(os.path.dirname(setup_file))
return unittest.defaultTestLoader.discover(setup_dir)
| import os
import sys
import unittest
if not hasattr(unittest.defaultTestLoader, 'discover'):
import unittest2 as unittest
def additional_tests():
setup_file = sys.modules['__main__'].__file__
setup_dir = os.path.abspath(os.path.dirname(setup_file))
return unittest.defaultTestLoader.discover(setup_dir)
| Allow test discovery on Py26 with unittest2 | Allow test discovery on Py26 with unittest2
| Python | mit | QuLogic/python-future,michaelpacer/python-future,PythonCharmers/python-future,QuLogic/python-future,krischer/python-future,PythonCharmers/python-future,krischer/python-future,michaelpacer/python-future | import os
import sys
import unittest
+
+ if not hasattr(unittest.defaultTestLoader, 'discover'):
+ import unittest2 as unittest
def additional_tests():
setup_file = sys.modules['__main__'].__file__
setup_dir = os.path.abspath(os.path.dirname(setup_file))
return unittest.defaultTestLoader.discover(setup_dir)
| Allow test discovery on Py26 with unittest2 | ## Code Before:
import os
import sys
import unittest
def additional_tests():
setup_file = sys.modules['__main__'].__file__
setup_dir = os.path.abspath(os.path.dirname(setup_file))
return unittest.defaultTestLoader.discover(setup_dir)
## Instruction:
Allow test discovery on Py26 with unittest2
## Code After:
import os
import sys
import unittest
if not hasattr(unittest.defaultTestLoader, 'discover'):
import unittest2 as unittest
def additional_tests():
setup_file = sys.modules['__main__'].__file__
setup_dir = os.path.abspath(os.path.dirname(setup_file))
return unittest.defaultTestLoader.discover(setup_dir)
|
63f04662f5ca22443ab6080f559ac898302cf103 | tests/integration/conftest.py | tests/integration/conftest.py | def pytest_collection_modifyitems(session, config, items):
# Ensure that all tests with require a redeploy are run after
# tests that don't need a redeploy.
final_list = []
on_redeploy_tests = []
for item in items:
if item.get_marker('on_redeploy') is not None:
on_redeploy_tests.append(item)
else:
final_list.append(item)
final_list.extend(on_redeploy_tests)
items[:] = final_list
| DEPLOY_TEST_BASENAME = 'test_features.py'
def pytest_collection_modifyitems(session, config, items):
# Ensure that all tests with require a redeploy are run after
# tests that don't need a redeploy.
start, end = _get_start_end_index(DEPLOY_TEST_BASENAME, items)
marked = []
unmarked = []
for item in items[start:end]:
if item.get_marker('on_redeploy') is not None:
marked.append(item)
else:
unmarked.append(item)
items[start:end] = unmarked + marked
def _get_start_end_index(basename, items):
# precondition: all the tests for test_features.py are
# in a contiguous range. This is the case because pytest
# will group all tests in a module together.
matched = [item.fspath.basename == basename for item in items]
return (
matched.index(True),
len(matched) - list(reversed(matched)).index(True)
)
| Reorder redeploy tests within a single module | Reorder redeploy tests within a single module
The original code for on_redeploy was making the
assumption that there was only one integration test file.
When test_package.py was added, the tests always failed
because the redeploy tests were run *after* the package tests
which messed with the module scope fixtures.
Now we ensure we only reorder tests within test_features.py.
| Python | apache-2.0 | awslabs/chalice | + DEPLOY_TEST_BASENAME = 'test_features.py'
+
+
def pytest_collection_modifyitems(session, config, items):
# Ensure that all tests with require a redeploy are run after
# tests that don't need a redeploy.
- final_list = []
- on_redeploy_tests = []
+ start, end = _get_start_end_index(DEPLOY_TEST_BASENAME, items)
+ marked = []
+ unmarked = []
- for item in items:
+ for item in items[start:end]:
if item.get_marker('on_redeploy') is not None:
- on_redeploy_tests.append(item)
+ marked.append(item)
else:
- final_list.append(item)
+ unmarked.append(item)
+ items[start:end] = unmarked + marked
- final_list.extend(on_redeploy_tests)
- items[:] = final_list
+
+ def _get_start_end_index(basename, items):
+ # precondition: all the tests for test_features.py are
+ # in a contiguous range. This is the case because pytest
+ # will group all tests in a module together.
+ matched = [item.fspath.basename == basename for item in items]
+ return (
+ matched.index(True),
+ len(matched) - list(reversed(matched)).index(True)
+ )
+ | Reorder redeploy tests within a single module | ## Code Before:
def pytest_collection_modifyitems(session, config, items):
# Ensure that all tests with require a redeploy are run after
# tests that don't need a redeploy.
final_list = []
on_redeploy_tests = []
for item in items:
if item.get_marker('on_redeploy') is not None:
on_redeploy_tests.append(item)
else:
final_list.append(item)
final_list.extend(on_redeploy_tests)
items[:] = final_list
## Instruction:
Reorder redeploy tests within a single module
## Code After:
DEPLOY_TEST_BASENAME = 'test_features.py'
def pytest_collection_modifyitems(session, config, items):
# Ensure that all tests with require a redeploy are run after
# tests that don't need a redeploy.
start, end = _get_start_end_index(DEPLOY_TEST_BASENAME, items)
marked = []
unmarked = []
for item in items[start:end]:
if item.get_marker('on_redeploy') is not None:
marked.append(item)
else:
unmarked.append(item)
items[start:end] = unmarked + marked
def _get_start_end_index(basename, items):
# precondition: all the tests for test_features.py are
# in a contiguous range. This is the case because pytest
# will group all tests in a module together.
matched = [item.fspath.basename == basename for item in items]
return (
matched.index(True),
len(matched) - list(reversed(matched)).index(True)
)
|
d42314b323aa0f8c764d72a5ebebc0e7d5ac88f3 | nova/api/openstack/compute/schemas/v3/create_backup.py | nova/api/openstack/compute/schemas/v3/create_backup.py |
from nova.api.validation import parameter_types
create_backup = {
'type': 'object',
'properties': {
'create_backup': {
'type': 'object',
'properties': {
'name': parameter_types.name,
'backup_type': {
'type': 'string',
'enum': ['daily', 'weekly'],
},
'rotation': {
'type': ['integer', 'string'],
'pattern': '^[0-9]+$',
'minimum': 0,
},
'metadata': {
'type': 'object',
}
},
'required': ['name', 'backup_type', 'rotation'],
'additionalProperties': False,
},
},
'required': ['create_backup'],
'additionalProperties': False,
}
|
from nova.api.validation import parameter_types
create_backup = {
'type': 'object',
'properties': {
'create_backup': {
'type': 'object',
'properties': {
'name': parameter_types.name,
'backup_type': {
'type': 'string',
},
'rotation': {
'type': ['integer', 'string'],
'pattern': '^[0-9]+$',
'minimum': 0,
},
'metadata': {
'type': 'object',
}
},
'required': ['name', 'backup_type', 'rotation'],
'additionalProperties': False,
},
},
'required': ['create_backup'],
'additionalProperties': False,
}
| Remove param check for backup type on v2.1 API | Remove param check for backup type on v2.1 API
The backup type is only used by glance, so nova check it make
no sense; currently we have daily and weekly as only valid param
but someone may add 'monthly' as param. nova should allow it
and delegate the error. This patch removes check on v2.1 API.
Change-Id: I59bbc0f589c8c280eb8cd87aa279898fffaeab7a
Closes-Bug: #1361490
| Python | apache-2.0 | devendermishrajio/nova,affo/nova,projectcalico/calico-nova,whitepages/nova,klmitch/nova,jianghuaw/nova,cernops/nova,Stavitsky/nova,fnordahl/nova,blueboxgroup/nova,CEG-FYP-OpenStack/scheduler,Francis-Liu/animated-broccoli,j-carpentier/nova,joker946/nova,hanlind/nova,rajalokan/nova,zhimin711/nova,silenceli/nova,ruslanloman/nova,isyippee/nova,akash1808/nova_test_latest,BeyondTheClouds/nova,belmiromoreira/nova,yatinkumbhare/openstack-nova,mmnelemane/nova,BeyondTheClouds/nova,JioCloud/nova_test_latest,mmnelemane/nova,mikalstill/nova,double12gzh/nova,sebrandon1/nova,cloudbase/nova-virtualbox,phenoxim/nova,devendermishrajio/nova_test_latest,NeCTAR-RC/nova,JioCloud/nova,apporc/nova,ruslanloman/nova,jianghuaw/nova,rahulunair/nova,whitepages/nova,adelina-t/nova,blueboxgroup/nova,noironetworks/nova,alaski/nova,adelina-t/nova,rahulunair/nova,felixma/nova,Juniper/nova,iuliat/nova,alexandrucoman/vbox-nova-driver,Tehsmash/nova,dims/nova,orbitfp7/nova,tealover/nova,yosshy/nova,mahak/nova,CEG-FYP-OpenStack/scheduler,JianyuWang/nova,cernops/nova,sebrandon1/nova,akash1808/nova_test_latest,Juniper/nova,varunarya10/nova_test_latest,Juniper/nova,double12gzh/nova,devendermishrajio/nova_test_latest,tudorvio/nova,BeyondTheClouds/nova,felixma/nova,alexandrucoman/vbox-nova-driver,cyx1231st/nova,CloudServer/nova,projectcalico/calico-nova,iuliat/nova,openstack/nova,mahak/nova,vmturbo/nova,eonpatapon/nova,jeffrey4l/nova,cloudbase/nova,rajalokan/nova,yosshy/nova,vmturbo/nova,nikesh-mahalka/nova,mandeepdhami/nova,mgagne/nova,mahak/nova,TwinkleChawla/nova,CloudServer/nova,belmiromoreira/nova,thomasem/nova,shail2810/nova,devendermishrajio/nova,JioCloud/nova_test_latest,NeCTAR-RC/nova,jeffrey4l/nova,cloudbase/nova-virtualbox,openstack/nova,zhimin711/nova,gooddata/openstack-nova,zzicewind/nova,Metaswitch/calico-nova,joker946/nova,LoHChina/nova,cyx1231st/nova,jianghuaw/nova,ted-gould/nova,raildo/nova,zaina/nova,ted-gould/nova,zaina/nova,petrutlucian94/nova,jianghuaw/nova,phenoxim/nova,mandeepdhami/nova,Yusuke1987/openstack_template,rajalokan/nova,cloudbase/nova,vmturbo/nova,affo/nova,akash1808/nova,gooddata/openstack-nova,bgxavier/nova,Stavitsky/nova,rajalokan/nova,MountainWei/nova,bgxavier/nova,fnordahl/nova,scripnichenko/nova,hanlind/nova,yatinkumbhare/openstack-nova,sebrandon1/nova,Francis-Liu/animated-broccoli,watonyweng/nova,barnsnake351/nova,JioCloud/nova,TwinkleChawla/nova,raildo/nova,bigswitch/nova,Tehsmash/nova,varunarya10/nova_test_latest,CCI-MOC/nova,shail2810/nova,gooddata/openstack-nova,dims/nova,zzicewind/nova,vmturbo/nova,tealover/nova,mgagne/nova,alvarolopez/nova,eonpatapon/nova,barnsnake351/nova,klmitch/nova,mikalstill/nova,rahulunair/nova,apporc/nova,edulramirez/nova,openstack/nova,isyippee/nova,tudorvio/nova,Metaswitch/calico-nova,JianyuWang/nova,kimjaejoong/nova,hanlind/nova,kimjaejoong/nova,bigswitch/nova,tangfeixiong/nova,petrutlucian94/nova,klmitch/nova,gooddata/openstack-nova,scripnichenko/nova,MountainWei/nova,cernops/nova,orbitfp7/nova,takeshineshiro/nova,klmitch/nova,edulramirez/nova,akash1808/nova,j-carpentier/nova,tangfeixiong/nova,silenceli/nova,nikesh-mahalka/nova,dawnpower/nova,CCI-MOC/nova,takeshineshiro/nova,LoHChina/nova,Juniper/nova,alaski/nova,noironetworks/nova,alvarolopez/nova,Yusuke1987/openstack_template,watonyweng/nova,thomasem/nova,cloudbase/nova,mikalstill/nova,dawnpower/nova |
from nova.api.validation import parameter_types
create_backup = {
'type': 'object',
'properties': {
'create_backup': {
'type': 'object',
'properties': {
'name': parameter_types.name,
'backup_type': {
'type': 'string',
- 'enum': ['daily', 'weekly'],
},
'rotation': {
'type': ['integer', 'string'],
'pattern': '^[0-9]+$',
'minimum': 0,
},
'metadata': {
'type': 'object',
}
},
'required': ['name', 'backup_type', 'rotation'],
'additionalProperties': False,
},
},
'required': ['create_backup'],
'additionalProperties': False,
}
| Remove param check for backup type on v2.1 API | ## Code Before:
from nova.api.validation import parameter_types
create_backup = {
'type': 'object',
'properties': {
'create_backup': {
'type': 'object',
'properties': {
'name': parameter_types.name,
'backup_type': {
'type': 'string',
'enum': ['daily', 'weekly'],
},
'rotation': {
'type': ['integer', 'string'],
'pattern': '^[0-9]+$',
'minimum': 0,
},
'metadata': {
'type': 'object',
}
},
'required': ['name', 'backup_type', 'rotation'],
'additionalProperties': False,
},
},
'required': ['create_backup'],
'additionalProperties': False,
}
## Instruction:
Remove param check for backup type on v2.1 API
## Code After:
from nova.api.validation import parameter_types
create_backup = {
'type': 'object',
'properties': {
'create_backup': {
'type': 'object',
'properties': {
'name': parameter_types.name,
'backup_type': {
'type': 'string',
},
'rotation': {
'type': ['integer', 'string'],
'pattern': '^[0-9]+$',
'minimum': 0,
},
'metadata': {
'type': 'object',
}
},
'required': ['name', 'backup_type', 'rotation'],
'additionalProperties': False,
},
},
'required': ['create_backup'],
'additionalProperties': False,
}
|
54c4e434276b242de56529e63bb6c5c61d891412 | indico/modules/events/surveys/tasks.py | indico/modules/events/surveys/tasks.py |
from __future__ import unicode_literals
from celery.schedules import crontab
from indico.core.celery import celery
from indico.core.db import db
from indico.modules.events.surveys.models.surveys import Survey
@celery.periodic_task(name='survey_start_notifications', run_every=crontab(minute='*/30'))
def send_start_notifications():
opened_surveys = Survey.find_all(~Survey.is_deleted, ~Survey.start_notification_sent, Survey.has_started,
Survey.notifications_enabled)
try:
for survey in opened_surveys:
survey.send_start_notification()
finally:
db.session.commit()
|
from __future__ import unicode_literals
from celery.schedules import crontab
from indico.core.celery import celery
from indico.core.db import db
from indico.modules.events.surveys.models.surveys import Survey
@celery.periodic_task(name='survey_start_notifications', run_every=crontab(minute='*/30'))
def send_start_notifications():
active_surveys = Survey.find_all(Survey.is_active, ~Survey.start_notification_sent, Survey.notifications_enabled)
try:
for survey in active_surveys:
survey.send_start_notification()
finally:
db.session.commit()
| Use safer condition for survey start notification | Use safer condition for survey start notification
| Python | mit | mvidalgarcia/indico,ThiefMaster/indico,pferreir/indico,indico/indico,mic4ael/indico,DirkHoffmann/indico,ThiefMaster/indico,indico/indico,ThiefMaster/indico,indico/indico,mic4ael/indico,indico/indico,OmeGak/indico,OmeGak/indico,pferreir/indico,DirkHoffmann/indico,mic4ael/indico,DirkHoffmann/indico,OmeGak/indico,DirkHoffmann/indico,mic4ael/indico,mvidalgarcia/indico,pferreir/indico,ThiefMaster/indico,mvidalgarcia/indico,mvidalgarcia/indico,pferreir/indico,OmeGak/indico |
from __future__ import unicode_literals
from celery.schedules import crontab
from indico.core.celery import celery
from indico.core.db import db
from indico.modules.events.surveys.models.surveys import Survey
@celery.periodic_task(name='survey_start_notifications', run_every=crontab(minute='*/30'))
def send_start_notifications():
- opened_surveys = Survey.find_all(~Survey.is_deleted, ~Survey.start_notification_sent, Survey.has_started,
+ active_surveys = Survey.find_all(Survey.is_active, ~Survey.start_notification_sent, Survey.notifications_enabled)
- Survey.notifications_enabled)
try:
- for survey in opened_surveys:
+ for survey in active_surveys:
survey.send_start_notification()
finally:
db.session.commit()
| Use safer condition for survey start notification | ## Code Before:
from __future__ import unicode_literals
from celery.schedules import crontab
from indico.core.celery import celery
from indico.core.db import db
from indico.modules.events.surveys.models.surveys import Survey
@celery.periodic_task(name='survey_start_notifications', run_every=crontab(minute='*/30'))
def send_start_notifications():
opened_surveys = Survey.find_all(~Survey.is_deleted, ~Survey.start_notification_sent, Survey.has_started,
Survey.notifications_enabled)
try:
for survey in opened_surveys:
survey.send_start_notification()
finally:
db.session.commit()
## Instruction:
Use safer condition for survey start notification
## Code After:
from __future__ import unicode_literals
from celery.schedules import crontab
from indico.core.celery import celery
from indico.core.db import db
from indico.modules.events.surveys.models.surveys import Survey
@celery.periodic_task(name='survey_start_notifications', run_every=crontab(minute='*/30'))
def send_start_notifications():
active_surveys = Survey.find_all(Survey.is_active, ~Survey.start_notification_sent, Survey.notifications_enabled)
try:
for survey in active_surveys:
survey.send_start_notification()
finally:
db.session.commit()
|
d0461fa033bdca4fffeff718219f8b71123449d7 | pskb_website/models/__init__.py | pskb_website/models/__init__.py |
from .article import search_for_article
from .article import get_available_articles
from .article import read_article
from .article import save_article
from .article import delete_article
from .article import branch_article
from .article import branch_or_save_article
from .article import get_articles_for_author
from .article import get_public_articles_for_author
from .article import save_article_meta_data
from .article import find_article_by_title
from .article import change_article_stack
from .file import read_file
from .file import read_redirects
from .file import update_article_listing
from .file import published_articles
from .file import in_review_articles
from .file import draft_articles
from .user import find_user
from .email_list import add_subscriber
from .image import save_image
from .lib import to_json
|
from .article import search_for_article
from .article import get_available_articles
from .article import read_article
from .article import save_article
from .article import delete_article
from .article import branch_article
from .article import branch_or_save_article
from .article import get_articles_for_author
from .article import get_public_articles_for_author
from .article import find_article_by_title
from .article import change_article_stack
from .file import read_file
from .file import read_redirects
from .file import update_article_listing
from .user import find_user
from .email_list import add_subscriber
from .image import save_image
from .lib import to_json
| Remove some functions from exported model API that are not used outside model layer | Remove some functions from exported model API that are not used outside model layer
- Just some refactoring to trim down the number of things exported that aren't
necessary at this time.
| Python | agpl-3.0 | paulocheque/guides-cms,pluralsight/guides-cms,pluralsight/guides-cms,paulocheque/guides-cms,paulocheque/guides-cms,pluralsight/guides-cms |
from .article import search_for_article
from .article import get_available_articles
from .article import read_article
from .article import save_article
from .article import delete_article
from .article import branch_article
from .article import branch_or_save_article
from .article import get_articles_for_author
from .article import get_public_articles_for_author
- from .article import save_article_meta_data
from .article import find_article_by_title
from .article import change_article_stack
from .file import read_file
from .file import read_redirects
from .file import update_article_listing
- from .file import published_articles
- from .file import in_review_articles
- from .file import draft_articles
from .user import find_user
from .email_list import add_subscriber
from .image import save_image
from .lib import to_json
| Remove some functions from exported model API that are not used outside model layer | ## Code Before:
from .article import search_for_article
from .article import get_available_articles
from .article import read_article
from .article import save_article
from .article import delete_article
from .article import branch_article
from .article import branch_or_save_article
from .article import get_articles_for_author
from .article import get_public_articles_for_author
from .article import save_article_meta_data
from .article import find_article_by_title
from .article import change_article_stack
from .file import read_file
from .file import read_redirects
from .file import update_article_listing
from .file import published_articles
from .file import in_review_articles
from .file import draft_articles
from .user import find_user
from .email_list import add_subscriber
from .image import save_image
from .lib import to_json
## Instruction:
Remove some functions from exported model API that are not used outside model layer
## Code After:
from .article import search_for_article
from .article import get_available_articles
from .article import read_article
from .article import save_article
from .article import delete_article
from .article import branch_article
from .article import branch_or_save_article
from .article import get_articles_for_author
from .article import get_public_articles_for_author
from .article import find_article_by_title
from .article import change_article_stack
from .file import read_file
from .file import read_redirects
from .file import update_article_listing
from .user import find_user
from .email_list import add_subscriber
from .image import save_image
from .lib import to_json
|
ab035185e2c2023280c29aa5239deac820ec873d | openprescribing/openprescribing/settings/e2etest.py | openprescribing/openprescribing/settings/e2etest.py | from __future__ import absolute_import
from .test import *
DATABASES = {
"default": {
"ENGINE": "django.contrib.gis.db.backends.postgis",
"NAME": utils.get_env_setting("E2E_DB_NAME"),
"USER": utils.get_env_setting("DB_USER"),
"PASSWORD": utils.get_env_setting("DB_PASS"),
"HOST": utils.get_env_setting("DB_HOST", "127.0.0.1"),
}
}
PIPELINE_METADATA_DIR = os.path.join(APPS_ROOT, "pipeline", "metadata")
PIPELINE_DATA_BASEDIR = os.path.join(APPS_ROOT, "pipeline", "e2e-test-data", "data", "")
PIPELINE_IMPORT_LOG_PATH = os.path.join(
APPS_ROOT, "pipeline", "e2e-test-data", "log.json"
)
SLACK_SENDING_ACTIVE = True
BQ_DEFAULT_TABLE_EXPIRATION_MS = 24 * 60 * 60 * 1000 # 24 hours
| from __future__ import absolute_import
from .test import *
DATABASES = {
"default": {
"ENGINE": "django.contrib.gis.db.backends.postgis",
"NAME": utils.get_env_setting("E2E_DB_NAME"),
"USER": utils.get_env_setting("DB_USER"),
"PASSWORD": utils.get_env_setting("DB_PASS"),
"HOST": utils.get_env_setting("DB_HOST", "127.0.0.1"),
}
}
PIPELINE_METADATA_DIR = os.path.join(APPS_ROOT, "pipeline", "metadata")
PIPELINE_DATA_BASEDIR = os.path.join(APPS_ROOT, "pipeline", "e2e-test-data", "data", "")
PIPELINE_IMPORT_LOG_PATH = os.path.join(
APPS_ROOT, "pipeline", "e2e-test-data", "log.json"
)
SLACK_SENDING_ACTIVE = True
BQ_DEFAULT_TABLE_EXPIRATION_MS = 24 * 60 * 60 * 1000 # 24 hours
# We want to use the real measure definitions, not the test ones!
MEASURE_DEFINITIONS_PATH = os.path.join(APPS_ROOT, "measure_definitions")
| Use real measure definitions in e2e tests | Use real measure definitions in e2e tests | Python | mit | ebmdatalab/openprescribing,annapowellsmith/openpresc,ebmdatalab/openprescribing,annapowellsmith/openpresc,ebmdatalab/openprescribing,ebmdatalab/openprescribing,annapowellsmith/openpresc,annapowellsmith/openpresc | from __future__ import absolute_import
from .test import *
DATABASES = {
"default": {
"ENGINE": "django.contrib.gis.db.backends.postgis",
"NAME": utils.get_env_setting("E2E_DB_NAME"),
"USER": utils.get_env_setting("DB_USER"),
"PASSWORD": utils.get_env_setting("DB_PASS"),
"HOST": utils.get_env_setting("DB_HOST", "127.0.0.1"),
}
}
PIPELINE_METADATA_DIR = os.path.join(APPS_ROOT, "pipeline", "metadata")
PIPELINE_DATA_BASEDIR = os.path.join(APPS_ROOT, "pipeline", "e2e-test-data", "data", "")
PIPELINE_IMPORT_LOG_PATH = os.path.join(
APPS_ROOT, "pipeline", "e2e-test-data", "log.json"
)
SLACK_SENDING_ACTIVE = True
BQ_DEFAULT_TABLE_EXPIRATION_MS = 24 * 60 * 60 * 1000 # 24 hours
+ # We want to use the real measure definitions, not the test ones!
+ MEASURE_DEFINITIONS_PATH = os.path.join(APPS_ROOT, "measure_definitions")
+ | Use real measure definitions in e2e tests | ## Code Before:
from __future__ import absolute_import
from .test import *
DATABASES = {
"default": {
"ENGINE": "django.contrib.gis.db.backends.postgis",
"NAME": utils.get_env_setting("E2E_DB_NAME"),
"USER": utils.get_env_setting("DB_USER"),
"PASSWORD": utils.get_env_setting("DB_PASS"),
"HOST": utils.get_env_setting("DB_HOST", "127.0.0.1"),
}
}
PIPELINE_METADATA_DIR = os.path.join(APPS_ROOT, "pipeline", "metadata")
PIPELINE_DATA_BASEDIR = os.path.join(APPS_ROOT, "pipeline", "e2e-test-data", "data", "")
PIPELINE_IMPORT_LOG_PATH = os.path.join(
APPS_ROOT, "pipeline", "e2e-test-data", "log.json"
)
SLACK_SENDING_ACTIVE = True
BQ_DEFAULT_TABLE_EXPIRATION_MS = 24 * 60 * 60 * 1000 # 24 hours
## Instruction:
Use real measure definitions in e2e tests
## Code After:
from __future__ import absolute_import
from .test import *
DATABASES = {
"default": {
"ENGINE": "django.contrib.gis.db.backends.postgis",
"NAME": utils.get_env_setting("E2E_DB_NAME"),
"USER": utils.get_env_setting("DB_USER"),
"PASSWORD": utils.get_env_setting("DB_PASS"),
"HOST": utils.get_env_setting("DB_HOST", "127.0.0.1"),
}
}
PIPELINE_METADATA_DIR = os.path.join(APPS_ROOT, "pipeline", "metadata")
PIPELINE_DATA_BASEDIR = os.path.join(APPS_ROOT, "pipeline", "e2e-test-data", "data", "")
PIPELINE_IMPORT_LOG_PATH = os.path.join(
APPS_ROOT, "pipeline", "e2e-test-data", "log.json"
)
SLACK_SENDING_ACTIVE = True
BQ_DEFAULT_TABLE_EXPIRATION_MS = 24 * 60 * 60 * 1000 # 24 hours
# We want to use the real measure definitions, not the test ones!
MEASURE_DEFINITIONS_PATH = os.path.join(APPS_ROOT, "measure_definitions")
|
0bb36aebdf0766c9244c6e317df89ddda86361b0 | polls/admin.py | polls/admin.py | from __future__ import unicode_literals
from django.contrib import admin
from .models import Question, Choice, Answer
class ChoiceInline(admin.TabularInline):
model = Choice
class QuestionAdmin(admin.ModelAdmin):
inlines = [
ChoiceInline,
]
admin.site.register(Question, QuestionAdmin)
admin.site.register(Answer)
| from __future__ import unicode_literals
from django.contrib import admin
from .models import Question, Choice, Answer
class ChoiceInline(admin.TabularInline):
model = Choice
def copy_question(modeladmin, request, queryset):
for orig in queryset:
q = Question(question_text="Kopie van "+orig.question_text)
q.save()
for orig_choice in orig.choice_set.all():
c = Choice(question=q, choice_text=orig_choice.choice_text)
c.save()
copy_question.short_description = "Kopieer stemmingen"
class QuestionAdmin(admin.ModelAdmin):
inlines = [
ChoiceInline,
]
actions = [copy_question]
admin.site.register(Question, QuestionAdmin)
admin.site.register(Answer)
| Allow Questions to be copied | Allow Questions to be copied
| Python | apache-2.0 | gerard-/votingapp,gerard-/votingapp | from __future__ import unicode_literals
from django.contrib import admin
from .models import Question, Choice, Answer
class ChoiceInline(admin.TabularInline):
model = Choice
+ def copy_question(modeladmin, request, queryset):
+ for orig in queryset:
+ q = Question(question_text="Kopie van "+orig.question_text)
+ q.save()
+ for orig_choice in orig.choice_set.all():
+ c = Choice(question=q, choice_text=orig_choice.choice_text)
+ c.save()
+
+ copy_question.short_description = "Kopieer stemmingen"
+
class QuestionAdmin(admin.ModelAdmin):
inlines = [
ChoiceInline,
]
+ actions = [copy_question]
admin.site.register(Question, QuestionAdmin)
admin.site.register(Answer)
| Allow Questions to be copied | ## Code Before:
from __future__ import unicode_literals
from django.contrib import admin
from .models import Question, Choice, Answer
class ChoiceInline(admin.TabularInline):
model = Choice
class QuestionAdmin(admin.ModelAdmin):
inlines = [
ChoiceInline,
]
admin.site.register(Question, QuestionAdmin)
admin.site.register(Answer)
## Instruction:
Allow Questions to be copied
## Code After:
from __future__ import unicode_literals
from django.contrib import admin
from .models import Question, Choice, Answer
class ChoiceInline(admin.TabularInline):
model = Choice
def copy_question(modeladmin, request, queryset):
for orig in queryset:
q = Question(question_text="Kopie van "+orig.question_text)
q.save()
for orig_choice in orig.choice_set.all():
c = Choice(question=q, choice_text=orig_choice.choice_text)
c.save()
copy_question.short_description = "Kopieer stemmingen"
class QuestionAdmin(admin.ModelAdmin):
inlines = [
ChoiceInline,
]
actions = [copy_question]
admin.site.register(Question, QuestionAdmin)
admin.site.register(Answer)
|
6ca27fba516ddc63ad6bae98b20e5f9a42b37451 | examples/plotting/file/image.py | examples/plotting/file/image.py |
import numpy as np
from bokeh.plotting import *
from bokeh.objects import Range1d
N = 1000
x = np.linspace(0, 10, N)
y = np.linspace(0, 10, N)
xx, yy = np.meshgrid(x, y)
d = np.sin(xx)*np.cos(yy)
output_file("image.html", title="image.py example")
image(
image=[d], x=[0], y=[0], dw=[10], dh=[10], palette=["Spectral-11"],
x_range=[0, 10], y_range=[0, 10],
tools="pan,wheel_zoom,box_zoom,reset,previewsave", name="image_example"
)
curplot().x_range = [5, 10]
show() # open a browser
|
import numpy as np
from bokeh.plotting import *
N = 1000
x = np.linspace(0, 10, N)
y = np.linspace(0, 10, N)
xx, yy = np.meshgrid(x, y)
d = np.sin(xx)*np.cos(yy)
output_file("image.html", title="image.py example")
image(
image=[d], x=[0], y=[0], dw=[10], dh=[10], palette=["Spectral-11"],
x_range=[0, 10], y_range=[0, 10],
tools="pan,wheel_zoom,box_zoom,reset,previewsave", name="image_example"
)
show() # open a browser
| Fix example and remove extraneous import. | Fix example and remove extraneous import.
| Python | bsd-3-clause | birdsarah/bokeh,srinathv/bokeh,justacec/bokeh,eteq/bokeh,saifrahmed/bokeh,eteq/bokeh,rothnic/bokeh,dennisobrien/bokeh,deeplook/bokeh,draperjames/bokeh,tacaswell/bokeh,daodaoliang/bokeh,abele/bokeh,abele/bokeh,phobson/bokeh,Karel-van-de-Plassche/bokeh,percyfal/bokeh,ericdill/bokeh,timsnyder/bokeh,CrazyGuo/bokeh,ptitjano/bokeh,quasiben/bokeh,rothnic/bokeh,ericmjl/bokeh,rs2/bokeh,philippjfr/bokeh,ericmjl/bokeh,rhiever/bokeh,stonebig/bokeh,timothydmorton/bokeh,rs2/bokeh,azjps/bokeh,roxyboy/bokeh,aiguofer/bokeh,justacec/bokeh,draperjames/bokeh,stuart-knock/bokeh,paultcochrane/bokeh,aiguofer/bokeh,birdsarah/bokeh,awanke/bokeh,ChristosChristofidis/bokeh,roxyboy/bokeh,laurent-george/bokeh,ahmadia/bokeh,saifrahmed/bokeh,birdsarah/bokeh,mutirri/bokeh,jplourenco/bokeh,htygithub/bokeh,laurent-george/bokeh,canavandl/bokeh,daodaoliang/bokeh,bokeh/bokeh,ahmadia/bokeh,schoolie/bokeh,schoolie/bokeh,evidation-health/bokeh,maxalbert/bokeh,dennisobrien/bokeh,ChristosChristofidis/bokeh,saifrahmed/bokeh,roxyboy/bokeh,muku42/bokeh,phobson/bokeh,jakirkham/bokeh,josherick/bokeh,ericmjl/bokeh,eteq/bokeh,ptitjano/bokeh,mutirri/bokeh,muku42/bokeh,timsnyder/bokeh,lukebarnard1/bokeh,DuCorey/bokeh,percyfal/bokeh,phobson/bokeh,laurent-george/bokeh,bokeh/bokeh,draperjames/bokeh,canavandl/bokeh,carlvlewis/bokeh,xguse/bokeh,carlvlewis/bokeh,mutirri/bokeh,DuCorey/bokeh,lukebarnard1/bokeh,muku42/bokeh,Karel-van-de-Plassche/bokeh,ptitjano/bokeh,tacaswell/bokeh,xguse/bokeh,akloster/bokeh,PythonCharmers/bokeh,aavanian/bokeh,roxyboy/bokeh,evidation-health/bokeh,alan-unravel/bokeh,mindriot101/bokeh,aavanian/bokeh,msarahan/bokeh,aiguofer/bokeh,bsipocz/bokeh,caseyclements/bokeh,percyfal/bokeh,tacaswell/bokeh,PythonCharmers/bokeh,ChristosChristofidis/bokeh,ChinaQuants/bokeh,timothydmorton/bokeh,mutirri/bokeh,ericdill/bokeh,timsnyder/bokeh,KasperPRasmussen/bokeh,matbra/bokeh,aavanian/bokeh,KasperPRasmussen/bokeh,satishgoda/bokeh,josherick/bokeh,srinathv/bokeh,ahmadia/bokeh,caseyclements/bokeh,draperjames/bokeh,stonebig/bokeh,clairetang6/bokeh,almarklein/bokeh,carlvlewis/bokeh,almarklein/bokeh,laurent-george/bokeh,satishgoda/bokeh,ericdill/bokeh,srinathv/bokeh,philippjfr/bokeh,deeplook/bokeh,msarahan/bokeh,timsnyder/bokeh,justacec/bokeh,rothnic/bokeh,aiguofer/bokeh,azjps/bokeh,DuCorey/bokeh,azjps/bokeh,PythonCharmers/bokeh,percyfal/bokeh,awanke/bokeh,bsipocz/bokeh,maxalbert/bokeh,almarklein/bokeh,dennisobrien/bokeh,bokeh/bokeh,DuCorey/bokeh,CrazyGuo/bokeh,matbra/bokeh,rs2/bokeh,josherick/bokeh,ericdill/bokeh,dennisobrien/bokeh,ChinaQuants/bokeh,clairetang6/bokeh,muku42/bokeh,stuart-knock/bokeh,Karel-van-de-Plassche/bokeh,bokeh/bokeh,khkaminska/bokeh,paultcochrane/bokeh,khkaminska/bokeh,xguse/bokeh,ChristosChristofidis/bokeh,jplourenco/bokeh,KasperPRasmussen/bokeh,ChinaQuants/bokeh,azjps/bokeh,abele/bokeh,msarahan/bokeh,maxalbert/bokeh,rs2/bokeh,alan-unravel/bokeh,awanke/bokeh,paultcochrane/bokeh,philippjfr/bokeh,timothydmorton/bokeh,htygithub/bokeh,quasiben/bokeh,rhiever/bokeh,evidation-health/bokeh,rhiever/bokeh,ericmjl/bokeh,msarahan/bokeh,timsnyder/bokeh,deeplook/bokeh,saifrahmed/bokeh,philippjfr/bokeh,xguse/bokeh,rhiever/bokeh,KasperPRasmussen/bokeh,tacaswell/bokeh,jplourenco/bokeh,phobson/bokeh,clairetang6/bokeh,ptitjano/bokeh,aavanian/bokeh,matbra/bokeh,Karel-van-de-Plassche/bokeh,bsipocz/bokeh,KasperPRasmussen/bokeh,Karel-van-de-Plassche/bokeh,ericmjl/bokeh,draperjames/bokeh,DuCorey/bokeh,justacec/bokeh,ChinaQuants/bokeh,eteq/bokeh,jakirkham/bokeh,PythonCharmers/bokeh,schoolie/bokeh,akloster/bokeh,htygithub/bokeh,lukebarnard1/bokeh,bsipocz/bokeh,schoolie/bokeh,azjps/bokeh,caseyclements/bokeh,akloster/bokeh,stuart-knock/bokeh,stuart-knock/bokeh,mindriot101/bokeh,CrazyGuo/bokeh,abele/bokeh,khkaminska/bokeh,maxalbert/bokeh,rs2/bokeh,CrazyGuo/bokeh,jakirkham/bokeh,bokeh/bokeh,khkaminska/bokeh,quasiben/bokeh,satishgoda/bokeh,clairetang6/bokeh,canavandl/bokeh,daodaoliang/bokeh,ahmadia/bokeh,gpfreitas/bokeh,josherick/bokeh,philippjfr/bokeh,phobson/bokeh,dennisobrien/bokeh,matbra/bokeh,satishgoda/bokeh,ptitjano/bokeh,akloster/bokeh,percyfal/bokeh,caseyclements/bokeh,htygithub/bokeh,canavandl/bokeh,carlvlewis/bokeh,paultcochrane/bokeh,mindriot101/bokeh,schoolie/bokeh,lukebarnard1/bokeh,gpfreitas/bokeh,gpfreitas/bokeh,alan-unravel/bokeh,evidation-health/bokeh,timothydmorton/bokeh,aavanian/bokeh,gpfreitas/bokeh,jakirkham/bokeh,awanke/bokeh,rothnic/bokeh,aiguofer/bokeh,stonebig/bokeh,jplourenco/bokeh,stonebig/bokeh,deeplook/bokeh,jakirkham/bokeh,alan-unravel/bokeh,mindriot101/bokeh,birdsarah/bokeh,srinathv/bokeh,daodaoliang/bokeh |
import numpy as np
from bokeh.plotting import *
- from bokeh.objects import Range1d
N = 1000
x = np.linspace(0, 10, N)
y = np.linspace(0, 10, N)
xx, yy = np.meshgrid(x, y)
d = np.sin(xx)*np.cos(yy)
output_file("image.html", title="image.py example")
image(
image=[d], x=[0], y=[0], dw=[10], dh=[10], palette=["Spectral-11"],
x_range=[0, 10], y_range=[0, 10],
tools="pan,wheel_zoom,box_zoom,reset,previewsave", name="image_example"
)
- curplot().x_range = [5, 10]
-
show() # open a browser
| Fix example and remove extraneous import. | ## Code Before:
import numpy as np
from bokeh.plotting import *
from bokeh.objects import Range1d
N = 1000
x = np.linspace(0, 10, N)
y = np.linspace(0, 10, N)
xx, yy = np.meshgrid(x, y)
d = np.sin(xx)*np.cos(yy)
output_file("image.html", title="image.py example")
image(
image=[d], x=[0], y=[0], dw=[10], dh=[10], palette=["Spectral-11"],
x_range=[0, 10], y_range=[0, 10],
tools="pan,wheel_zoom,box_zoom,reset,previewsave", name="image_example"
)
curplot().x_range = [5, 10]
show() # open a browser
## Instruction:
Fix example and remove extraneous import.
## Code After:
import numpy as np
from bokeh.plotting import *
N = 1000
x = np.linspace(0, 10, N)
y = np.linspace(0, 10, N)
xx, yy = np.meshgrid(x, y)
d = np.sin(xx)*np.cos(yy)
output_file("image.html", title="image.py example")
image(
image=[d], x=[0], y=[0], dw=[10], dh=[10], palette=["Spectral-11"],
x_range=[0, 10], y_range=[0, 10],
tools="pan,wheel_zoom,box_zoom,reset,previewsave", name="image_example"
)
show() # open a browser
|
5d8b217659fdd4a7248a60b430a24fe909bca805 | test/test_acoustics.py | test/test_acoustics.py | import numpy as np
import pyfds as fds
def test_acoustic_material():
water = fds.AcousticMaterial(1500, 1000)
water.bulk_viscosity = 1e-3
water.shear_viscosity = 1e-3
assert np.isclose(water.absorption_coef, 7e-3 / 3)
| import numpy as np
import pyfds as fds
def test_acoustic_material():
water = fds.AcousticMaterial(1500, 1000)
water.bulk_viscosity = 1e-3
water.shear_viscosity = 1e-3
assert np.isclose(water.absorption_coef, 7e-3 / 3)
def test_acoustic1d_create_matrices():
fld = fds.Acoustic1D(t_delta=1, t_samples=1,
x_delta=1, x_samples=3,
material=fds.AcousticMaterial(700, 0.01, bulk_viscosity=1))
fld.create_matrices()
assert np.allclose(fld.a_p_v.toarray(), [[-4900, 4900, 0], [0, -4900, 4900], [0, 0, -4900]])
assert np.allclose(fld.a_v_p.toarray(), [[100, 0, 0], [-100, 100, 0], [0, -100, 100]])
assert np.allclose(fld.a_v_v.toarray(), [[-200, 100, 0], [100, -200, 100], [0, 100, -200]])
| Add test case for Acoustic1D.create_matrices(). | Add test case for Acoustic1D.create_matrices().
| Python | bsd-3-clause | emtpb/pyfds | import numpy as np
import pyfds as fds
def test_acoustic_material():
water = fds.AcousticMaterial(1500, 1000)
water.bulk_viscosity = 1e-3
water.shear_viscosity = 1e-3
assert np.isclose(water.absorption_coef, 7e-3 / 3)
+
+ def test_acoustic1d_create_matrices():
+ fld = fds.Acoustic1D(t_delta=1, t_samples=1,
+ x_delta=1, x_samples=3,
+ material=fds.AcousticMaterial(700, 0.01, bulk_viscosity=1))
+ fld.create_matrices()
+ assert np.allclose(fld.a_p_v.toarray(), [[-4900, 4900, 0], [0, -4900, 4900], [0, 0, -4900]])
+ assert np.allclose(fld.a_v_p.toarray(), [[100, 0, 0], [-100, 100, 0], [0, -100, 100]])
+ assert np.allclose(fld.a_v_v.toarray(), [[-200, 100, 0], [100, -200, 100], [0, 100, -200]])
+ | Add test case for Acoustic1D.create_matrices(). | ## Code Before:
import numpy as np
import pyfds as fds
def test_acoustic_material():
water = fds.AcousticMaterial(1500, 1000)
water.bulk_viscosity = 1e-3
water.shear_viscosity = 1e-3
assert np.isclose(water.absorption_coef, 7e-3 / 3)
## Instruction:
Add test case for Acoustic1D.create_matrices().
## Code After:
import numpy as np
import pyfds as fds
def test_acoustic_material():
water = fds.AcousticMaterial(1500, 1000)
water.bulk_viscosity = 1e-3
water.shear_viscosity = 1e-3
assert np.isclose(water.absorption_coef, 7e-3 / 3)
def test_acoustic1d_create_matrices():
fld = fds.Acoustic1D(t_delta=1, t_samples=1,
x_delta=1, x_samples=3,
material=fds.AcousticMaterial(700, 0.01, bulk_viscosity=1))
fld.create_matrices()
assert np.allclose(fld.a_p_v.toarray(), [[-4900, 4900, 0], [0, -4900, 4900], [0, 0, -4900]])
assert np.allclose(fld.a_v_p.toarray(), [[100, 0, 0], [-100, 100, 0], [0, -100, 100]])
assert np.allclose(fld.a_v_v.toarray(), [[-200, 100, 0], [100, -200, 100], [0, 100, -200]])
|
8d55ea0cfbafc9f6dc1044ba27c3313c36ea73c6 | pombola/south_africa/templatetags/za_people_display.py | pombola/south_africa/templatetags/za_people_display.py | from django import template
register = template.Library()
NO_PLACE_ORGS = ('parliament', 'national-assembly', )
MEMBER_ORGS = ('parliament', 'national-assembly', )
@register.assignment_tag()
def should_display_place(organisation):
return organisation.slug not in NO_PLACE_ORGS
@register.assignment_tag()
def should_display_position(organisation, position_title):
should_display = True
if organisation.slug in MEMBER_ORGS and unicode(position_title) in (u'Member',):
should_display = False
if 'ncop' == organisation.slug and unicode(position_title) in (u'Delegate',):
should_display = False
return should_display
| from django import template
register = template.Library()
NO_PLACE_ORGS = ('parliament', 'national-assembly', )
MEMBER_ORGS = ('parliament', 'national-assembly', )
@register.assignment_tag()
def should_display_place(organisation):
if not organisation:
return True
return organisation.slug not in NO_PLACE_ORGS
@register.assignment_tag()
def should_display_position(organisation, position_title):
should_display = True
if organisation.slug in MEMBER_ORGS and unicode(position_title) in (u'Member',):
should_display = False
if 'ncop' == organisation.slug and unicode(position_title) in (u'Delegate',):
should_display = False
return should_display
| Fix display of people on constituency office page | [ZA] Fix display of people on constituency office page
This template tag was being called without an organisation, so in
production it was just silently failing, but in development it was
raising an exception.
This adds an extra check so that if there is no organisation then we
just short circuit and return `True`.
| Python | agpl-3.0 | mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola | from django import template
register = template.Library()
NO_PLACE_ORGS = ('parliament', 'national-assembly', )
MEMBER_ORGS = ('parliament', 'national-assembly', )
@register.assignment_tag()
def should_display_place(organisation):
+ if not organisation:
+ return True
return organisation.slug not in NO_PLACE_ORGS
@register.assignment_tag()
def should_display_position(organisation, position_title):
should_display = True
if organisation.slug in MEMBER_ORGS and unicode(position_title) in (u'Member',):
should_display = False
if 'ncop' == organisation.slug and unicode(position_title) in (u'Delegate',):
should_display = False
return should_display
| Fix display of people on constituency office page | ## Code Before:
from django import template
register = template.Library()
NO_PLACE_ORGS = ('parliament', 'national-assembly', )
MEMBER_ORGS = ('parliament', 'national-assembly', )
@register.assignment_tag()
def should_display_place(organisation):
return organisation.slug not in NO_PLACE_ORGS
@register.assignment_tag()
def should_display_position(organisation, position_title):
should_display = True
if organisation.slug in MEMBER_ORGS and unicode(position_title) in (u'Member',):
should_display = False
if 'ncop' == organisation.slug and unicode(position_title) in (u'Delegate',):
should_display = False
return should_display
## Instruction:
Fix display of people on constituency office page
## Code After:
from django import template
register = template.Library()
NO_PLACE_ORGS = ('parliament', 'national-assembly', )
MEMBER_ORGS = ('parliament', 'national-assembly', )
@register.assignment_tag()
def should_display_place(organisation):
if not organisation:
return True
return organisation.slug not in NO_PLACE_ORGS
@register.assignment_tag()
def should_display_position(organisation, position_title):
should_display = True
if organisation.slug in MEMBER_ORGS and unicode(position_title) in (u'Member',):
should_display = False
if 'ncop' == organisation.slug and unicode(position_title) in (u'Delegate',):
should_display = False
return should_display
|
e44dc4d68845845f601803f31e10833a24cdb27c | prosite_app.py | prosite_app.py |
import prosite_matcher
if __name__ == '__main__':
print("\n Hi, this is Prosite Matcher! \n")
sequence = input("Sequence: ")
regex = input("Regular expression: ")
prositeMatcher = prosite_matcher.PrositeMatcher()
prositeMatcher.compile(regex)
matches, ranges = prositeMatcher.get_matches(sequence)
print("Found patterns: ", end="")
if (len(matches) > 0):
print(sequence[ 0 : ranges[0][0] ], end="")
for i in range(0, len(matches)):
print("\033[91m", end="")
print(sequence[ ranges[i][0] : ranges[i][1] ], end="")
print("\033[0m", end="")
if (i < len(matches) - 1):
print(sequence[ ranges[i][1] : ranges[i + 1][0] ], end="")
print(sequence[ ranges[len(ranges) - 1][1] : len(sequence)])
else:
print(sequence)
print("")
for elem in list(zip(matches, ranges)):
print(elem[0], end=" ")
print(elem[1])
print("")
|
import prosite_matcher
if __name__ == '__main__':
print("\n Hi, this is Prosite Matcher! \n")
sequence = input("Sequence: ")
regex = input("Regular expression: ")
if sequence != None and sequence != "" and regex != None and regex != "":
prositeMatcher = prosite_matcher.PrositeMatcher()
prositeMatcher.compile(regex)
matches, ranges = prositeMatcher.get_matches(sequence)
print("Found patterns: ", end="")
if (len(matches) > 0):
print(sequence[ 0 : ranges[0][0] ], end="")
for i in range(0, len(matches)):
print("\033[91m", end="")
print(sequence[ ranges[i][0] : ranges[i][1] ], end="")
print("\033[0m", end="")
if (i < len(matches) - 1):
print(sequence[ ranges[i][1] : ranges[i + 1][0] ], end="")
print(sequence[ ranges[len(ranges) - 1][1] : len(sequence)])
else:
print(sequence)
print("")
for elem in list(zip(matches, ranges)):
print(elem[0], end=" ")
print(elem[1])
print("")
else:
print("Sequence and regular expression can't be empty.") | Add check for empty sequence or regex. | Add check for empty sequence or regex.
| Python | mit | stack-overflow/py_finite_state |
import prosite_matcher
if __name__ == '__main__':
print("\n Hi, this is Prosite Matcher! \n")
sequence = input("Sequence: ")
regex = input("Regular expression: ")
+ if sequence != None and sequence != "" and regex != None and regex != "":
- prositeMatcher = prosite_matcher.PrositeMatcher()
- prositeMatcher.compile(regex)
- matches, ranges = prositeMatcher.get_matches(sequence)
- print("Found patterns: ", end="")
+ prositeMatcher = prosite_matcher.PrositeMatcher()
+ prositeMatcher.compile(regex)
+ matches, ranges = prositeMatcher.get_matches(sequence)
- if (len(matches) > 0):
+ print("Found patterns: ", end="")
- print(sequence[ 0 : ranges[0][0] ], end="")
+ if (len(matches) > 0):
- for i in range(0, len(matches)):
+ print(sequence[ 0 : ranges[0][0] ], end="")
+ for i in range(0, len(matches)):
- print("\033[91m", end="")
- print(sequence[ ranges[i][0] : ranges[i][1] ], end="")
- print("\033[0m", end="")
- if (i < len(matches) - 1):
- print(sequence[ ranges[i][1] : ranges[i + 1][0] ], end="")
+ print("\033[91m", end="")
+ print(sequence[ ranges[i][0] : ranges[i][1] ], end="")
+ print("\033[0m", end="")
+ if (i < len(matches) - 1):
+ print(sequence[ ranges[i][1] : ranges[i + 1][0] ], end="")
+
- print(sequence[ ranges[len(ranges) - 1][1] : len(sequence)])
+ print(sequence[ ranges[len(ranges) - 1][1] : len(sequence)])
+
+ else:
+
+ print(sequence)
+
+ print("")
+
+ for elem in list(zip(matches, ranges)):
+ print(elem[0], end=" ")
+ print(elem[1])
+
+ print("")
else:
+ print("Sequence and regular expression can't be empty.")
- print(sequence)
-
- print("")
-
- for elem in list(zip(matches, ranges)):
- print(elem[0], end=" ")
- print(elem[1])
-
- print("")
- | Add check for empty sequence or regex. | ## Code Before:
import prosite_matcher
if __name__ == '__main__':
print("\n Hi, this is Prosite Matcher! \n")
sequence = input("Sequence: ")
regex = input("Regular expression: ")
prositeMatcher = prosite_matcher.PrositeMatcher()
prositeMatcher.compile(regex)
matches, ranges = prositeMatcher.get_matches(sequence)
print("Found patterns: ", end="")
if (len(matches) > 0):
print(sequence[ 0 : ranges[0][0] ], end="")
for i in range(0, len(matches)):
print("\033[91m", end="")
print(sequence[ ranges[i][0] : ranges[i][1] ], end="")
print("\033[0m", end="")
if (i < len(matches) - 1):
print(sequence[ ranges[i][1] : ranges[i + 1][0] ], end="")
print(sequence[ ranges[len(ranges) - 1][1] : len(sequence)])
else:
print(sequence)
print("")
for elem in list(zip(matches, ranges)):
print(elem[0], end=" ")
print(elem[1])
print("")
## Instruction:
Add check for empty sequence or regex.
## Code After:
import prosite_matcher
if __name__ == '__main__':
print("\n Hi, this is Prosite Matcher! \n")
sequence = input("Sequence: ")
regex = input("Regular expression: ")
if sequence != None and sequence != "" and regex != None and regex != "":
prositeMatcher = prosite_matcher.PrositeMatcher()
prositeMatcher.compile(regex)
matches, ranges = prositeMatcher.get_matches(sequence)
print("Found patterns: ", end="")
if (len(matches) > 0):
print(sequence[ 0 : ranges[0][0] ], end="")
for i in range(0, len(matches)):
print("\033[91m", end="")
print(sequence[ ranges[i][0] : ranges[i][1] ], end="")
print("\033[0m", end="")
if (i < len(matches) - 1):
print(sequence[ ranges[i][1] : ranges[i + 1][0] ], end="")
print(sequence[ ranges[len(ranges) - 1][1] : len(sequence)])
else:
print(sequence)
print("")
for elem in list(zip(matches, ranges)):
print(elem[0], end=" ")
print(elem[1])
print("")
else:
print("Sequence and regular expression can't be empty.") |
4b172a9b2b9a9a70843bd41ad858d6f3120769b0 | tests/test_funcargs.py | tests/test_funcargs.py | from django.test.client import Client
from pytest_django.client import RequestFactory
pytest_plugins = ['pytester']
def test_params(testdir):
testdir.makeconftest("""
import os, sys
import pytest_django as plugin
sys.path.insert(0, os.path.realpath(os.path.join(os.path.dirname(plugin.__file__), '../')))
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
pytest_plugins = ['django']
""")
p = testdir.makepyfile("""
import py
@py.test.params([dict(arg1=1, arg2=1), dict(arg1=1, arg2=2)])
def test_myfunc(arg1, arg2):
assert arg1 == arg2
""")
result = testdir.runpytest("-v", p)
assert result.stdout.fnmatch_lines([
"*test_myfunc*0*PASS*",
"*test_myfunc*1*FAIL*",
"*1 failed, 1 passed*"
])
def test_client(client):
assert isinstance(client, Client)
def test_rf(rf):
assert isinstance(rf, RequestFactory)
| from django.test.client import Client
from pytest_django.client import RequestFactory
import py
pytest_plugins = ['pytester']
def test_params(testdir):
# Setting up the path isn't working - plugin.__file__ points to the wrong place
return
testdir.makeconftest("""
import os, sys
import pytest_django as plugin
sys.path.insert(0, os.path.realpath(os.path.join(os.path.dirname(plugin.__file__), '../')))
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
pytest_plugins = ['django']
""")
p = testdir.makepyfile("""
import py
@py.test.params([dict(arg1=1, arg2=1), dict(arg1=1, arg2=2)])
def test_myfunc(arg1, arg2):
assert arg1 == arg2
""")
result = testdir.runpytest("-v", p)
assert result.stdout.fnmatch_lines([
"*test_myfunc*0*PASS*",
"*test_myfunc*1*FAIL*",
"*1 failed, 1 passed*"
])
def test_client(client):
assert isinstance(client, Client)
def test_rf(rf):
assert isinstance(rf, RequestFactory)
| Disable params test for now | Disable params test for now
| Python | bsd-3-clause | ojake/pytest-django,pelme/pytest-django,hoh/pytest-django,thedrow/pytest-django,pombredanne/pytest_django,felixonmars/pytest-django,ktosiek/pytest-django,RonnyPfannschmidt/pytest_django,aptivate/pytest-django,davidszotten/pytest-django,reincubate/pytest-django,bforchhammer/pytest-django,tomviner/pytest-django,bfirsh/pytest_django | from django.test.client import Client
from pytest_django.client import RequestFactory
+ import py
pytest_plugins = ['pytester']
def test_params(testdir):
+ # Setting up the path isn't working - plugin.__file__ points to the wrong place
+ return
+
testdir.makeconftest("""
import os, sys
import pytest_django as plugin
sys.path.insert(0, os.path.realpath(os.path.join(os.path.dirname(plugin.__file__), '../')))
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
pytest_plugins = ['django']
""")
p = testdir.makepyfile("""
import py
@py.test.params([dict(arg1=1, arg2=1), dict(arg1=1, arg2=2)])
def test_myfunc(arg1, arg2):
assert arg1 == arg2
""")
result = testdir.runpytest("-v", p)
assert result.stdout.fnmatch_lines([
"*test_myfunc*0*PASS*",
"*test_myfunc*1*FAIL*",
"*1 failed, 1 passed*"
])
def test_client(client):
assert isinstance(client, Client)
def test_rf(rf):
assert isinstance(rf, RequestFactory)
| Disable params test for now | ## Code Before:
from django.test.client import Client
from pytest_django.client import RequestFactory
pytest_plugins = ['pytester']
def test_params(testdir):
testdir.makeconftest("""
import os, sys
import pytest_django as plugin
sys.path.insert(0, os.path.realpath(os.path.join(os.path.dirname(plugin.__file__), '../')))
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
pytest_plugins = ['django']
""")
p = testdir.makepyfile("""
import py
@py.test.params([dict(arg1=1, arg2=1), dict(arg1=1, arg2=2)])
def test_myfunc(arg1, arg2):
assert arg1 == arg2
""")
result = testdir.runpytest("-v", p)
assert result.stdout.fnmatch_lines([
"*test_myfunc*0*PASS*",
"*test_myfunc*1*FAIL*",
"*1 failed, 1 passed*"
])
def test_client(client):
assert isinstance(client, Client)
def test_rf(rf):
assert isinstance(rf, RequestFactory)
## Instruction:
Disable params test for now
## Code After:
from django.test.client import Client
from pytest_django.client import RequestFactory
import py
pytest_plugins = ['pytester']
def test_params(testdir):
# Setting up the path isn't working - plugin.__file__ points to the wrong place
return
testdir.makeconftest("""
import os, sys
import pytest_django as plugin
sys.path.insert(0, os.path.realpath(os.path.join(os.path.dirname(plugin.__file__), '../')))
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
pytest_plugins = ['django']
""")
p = testdir.makepyfile("""
import py
@py.test.params([dict(arg1=1, arg2=1), dict(arg1=1, arg2=2)])
def test_myfunc(arg1, arg2):
assert arg1 == arg2
""")
result = testdir.runpytest("-v", p)
assert result.stdout.fnmatch_lines([
"*test_myfunc*0*PASS*",
"*test_myfunc*1*FAIL*",
"*1 failed, 1 passed*"
])
def test_client(client):
assert isinstance(client, Client)
def test_rf(rf):
assert isinstance(rf, RequestFactory)
|
849552b1a2afdd89552e7c0395fc7be1786d5cbc | pybossa/auth/user.py | pybossa/auth/user.py |
from flask.ext.login import current_user
def create(user=None):
if current_user.is_authenticated():
if current_user.admin:
return True
else:
return False
else:
return False
def read(user=None):
return True
def update(user):
return create(user)
def delete(user):
return update(user)
|
from flask.ext.login import current_user
def create(user=None): # pragma: no cover
if current_user.is_authenticated():
if current_user.admin:
return True
else:
return False
else:
return False
def read(user=None): # pragma: no cover
return True
def update(user): # pragma: no cover
return create(user)
def delete(user): # pragma: no cover
return update(user)
| Exclude it from coverage as these permissions are not used yet. | Exclude it from coverage as these permissions are not used yet.
| Python | agpl-3.0 | PyBossa/pybossa,PyBossa/pybossa,CulturePlex/pybossa,jean/pybossa,inteligencia-coletiva-lsd/pybossa,harihpr/tweetclickers,stefanhahmann/pybossa,stefanhahmann/pybossa,geotagx/pybossa,geotagx/pybossa,CulturePlex/pybossa,OpenNewsLabs/pybossa,proyectos-analizo-info/pybossa-analizo-info,proyectos-analizo-info/pybossa-analizo-info,Scifabric/pybossa,proyectos-analizo-info/pybossa-analizo-info,jean/pybossa,CulturePlex/pybossa,inteligencia-coletiva-lsd/pybossa,harihpr/tweetclickers,Scifabric/pybossa,OpenNewsLabs/pybossa |
from flask.ext.login import current_user
- def create(user=None):
+ def create(user=None): # pragma: no cover
if current_user.is_authenticated():
if current_user.admin:
return True
else:
return False
else:
return False
- def read(user=None):
+ def read(user=None): # pragma: no cover
return True
- def update(user):
+ def update(user): # pragma: no cover
return create(user)
- def delete(user):
+ def delete(user): # pragma: no cover
return update(user)
| Exclude it from coverage as these permissions are not used yet. | ## Code Before:
from flask.ext.login import current_user
def create(user=None):
if current_user.is_authenticated():
if current_user.admin:
return True
else:
return False
else:
return False
def read(user=None):
return True
def update(user):
return create(user)
def delete(user):
return update(user)
## Instruction:
Exclude it from coverage as these permissions are not used yet.
## Code After:
from flask.ext.login import current_user
def create(user=None): # pragma: no cover
if current_user.is_authenticated():
if current_user.admin:
return True
else:
return False
else:
return False
def read(user=None): # pragma: no cover
return True
def update(user): # pragma: no cover
return create(user)
def delete(user): # pragma: no cover
return update(user)
|
5c9bdb1260562f0623807ce9a5751d33c806374a | pyfr/nputil.py | pyfr/nputil.py |
import numpy as np
_npeval_syms = {'__builtins__': None,
'exp': np.exp, 'log': np.log,
'sin': np.sin, 'asin': np.arcsin,
'cos': np.cos, 'acos': np.arccos,
'tan': np.tan, 'atan': np.arctan, 'atan2': np.arctan2,
'abs': np.abs, 'pow': np.power, 'sqrt': np.sqrt,
'pi': np.pi}
def npeval(expr, locals):
# Allow '^' to be used for exponentiation
expr = expr.replace('^', '**')
return eval(expr, _npeval_syms, locals)
_range_eval_syms = {'__builtins__': None,
'range': lambda s,e,n: list(np.linspace(s, e, n))}
def range_eval(expr):
return [float(t) for t in eval(expr, _range_eval_syms, None)]
_ctype_map = {np.float32: 'float', np.float64: 'double'}
def npdtype_to_ctype(dtype):
return _ctype_map[np.dtype(dtype).type]
|
import numpy as np
def npaligned(shape, dtype, alignb=32):
nbytes = np.prod(shape)*np.dtype(dtype).itemsize
buf = np.zeros(nbytes + alignb, dtype=np.uint8)
off = -buf.ctypes.data % alignb
return buf[off:nbytes + off].view(dtype).reshape(shape)
_npeval_syms = {'__builtins__': None,
'exp': np.exp, 'log': np.log,
'sin': np.sin, 'asin': np.arcsin,
'cos': np.cos, 'acos': np.arccos,
'tan': np.tan, 'atan': np.arctan, 'atan2': np.arctan2,
'abs': np.abs, 'pow': np.power, 'sqrt': np.sqrt,
'pi': np.pi}
def npeval(expr, locals):
# Allow '^' to be used for exponentiation
expr = expr.replace('^', '**')
return eval(expr, _npeval_syms, locals)
_range_eval_syms = {'__builtins__': None,
'range': lambda s,e,n: list(np.linspace(s, e, n))}
def range_eval(expr):
return [float(t) for t in eval(expr, _range_eval_syms, None)]
_ctype_map = {np.float32: 'float', np.float64: 'double'}
def npdtype_to_ctype(dtype):
return _ctype_map[np.dtype(dtype).type]
| Add support for allocating aligned NumPy arrays. | Add support for allocating aligned NumPy arrays.
| Python | bsd-3-clause | tjcorona/PyFR,tjcorona/PyFR,BrianVermeire/PyFR,Aerojspark/PyFR,iyer-arvind/PyFR,tjcorona/PyFR |
import numpy as np
+
+
+ def npaligned(shape, dtype, alignb=32):
+ nbytes = np.prod(shape)*np.dtype(dtype).itemsize
+ buf = np.zeros(nbytes + alignb, dtype=np.uint8)
+ off = -buf.ctypes.data % alignb
+
+ return buf[off:nbytes + off].view(dtype).reshape(shape)
_npeval_syms = {'__builtins__': None,
'exp': np.exp, 'log': np.log,
'sin': np.sin, 'asin': np.arcsin,
'cos': np.cos, 'acos': np.arccos,
'tan': np.tan, 'atan': np.arctan, 'atan2': np.arctan2,
'abs': np.abs, 'pow': np.power, 'sqrt': np.sqrt,
'pi': np.pi}
def npeval(expr, locals):
# Allow '^' to be used for exponentiation
expr = expr.replace('^', '**')
return eval(expr, _npeval_syms, locals)
_range_eval_syms = {'__builtins__': None,
'range': lambda s,e,n: list(np.linspace(s, e, n))}
def range_eval(expr):
return [float(t) for t in eval(expr, _range_eval_syms, None)]
_ctype_map = {np.float32: 'float', np.float64: 'double'}
def npdtype_to_ctype(dtype):
return _ctype_map[np.dtype(dtype).type]
| Add support for allocating aligned NumPy arrays. | ## Code Before:
import numpy as np
_npeval_syms = {'__builtins__': None,
'exp': np.exp, 'log': np.log,
'sin': np.sin, 'asin': np.arcsin,
'cos': np.cos, 'acos': np.arccos,
'tan': np.tan, 'atan': np.arctan, 'atan2': np.arctan2,
'abs': np.abs, 'pow': np.power, 'sqrt': np.sqrt,
'pi': np.pi}
def npeval(expr, locals):
# Allow '^' to be used for exponentiation
expr = expr.replace('^', '**')
return eval(expr, _npeval_syms, locals)
_range_eval_syms = {'__builtins__': None,
'range': lambda s,e,n: list(np.linspace(s, e, n))}
def range_eval(expr):
return [float(t) for t in eval(expr, _range_eval_syms, None)]
_ctype_map = {np.float32: 'float', np.float64: 'double'}
def npdtype_to_ctype(dtype):
return _ctype_map[np.dtype(dtype).type]
## Instruction:
Add support for allocating aligned NumPy arrays.
## Code After:
import numpy as np
def npaligned(shape, dtype, alignb=32):
nbytes = np.prod(shape)*np.dtype(dtype).itemsize
buf = np.zeros(nbytes + alignb, dtype=np.uint8)
off = -buf.ctypes.data % alignb
return buf[off:nbytes + off].view(dtype).reshape(shape)
_npeval_syms = {'__builtins__': None,
'exp': np.exp, 'log': np.log,
'sin': np.sin, 'asin': np.arcsin,
'cos': np.cos, 'acos': np.arccos,
'tan': np.tan, 'atan': np.arctan, 'atan2': np.arctan2,
'abs': np.abs, 'pow': np.power, 'sqrt': np.sqrt,
'pi': np.pi}
def npeval(expr, locals):
# Allow '^' to be used for exponentiation
expr = expr.replace('^', '**')
return eval(expr, _npeval_syms, locals)
_range_eval_syms = {'__builtins__': None,
'range': lambda s,e,n: list(np.linspace(s, e, n))}
def range_eval(expr):
return [float(t) for t in eval(expr, _range_eval_syms, None)]
_ctype_map = {np.float32: 'float', np.float64: 'double'}
def npdtype_to_ctype(dtype):
return _ctype_map[np.dtype(dtype).type]
|
126c58d78360e69c2d16a40f9396a8158844e2b1 | tests/test_creators.py | tests/test_creators.py |
def test_matrix_creation_endpoint(client):
response = client.post('/matrix', {
'bibliography': '12312312',
'fields': 'title,description',
})
print(response.json())
assert response.status_code == 200
| from condor.models import Bibliography
def test_matrix_creation_endpoint(client, session):
bib = Bibliography(eid='123', description='lorem')
session.add(bib)
session.flush()
response = client.post('/matrix', {
'bibliography': '123',
'fields': 'title,description',
})
response = client.get(f"/matrix/{response.json().get('eid')}")
assert response.status_code == 200
assert response.json().get('bibliography_eid') == '123'
| Create test for matrix post endpoint | Create test for matrix post endpoint
| Python | mit | odarbelaeze/condor-api | + from condor.models import Bibliography
- def test_matrix_creation_endpoint(client):
+ def test_matrix_creation_endpoint(client, session):
+ bib = Bibliography(eid='123', description='lorem')
+ session.add(bib)
+ session.flush()
+
response = client.post('/matrix', {
- 'bibliography': '12312312',
+ 'bibliography': '123',
'fields': 'title,description',
})
- print(response.json())
+
+ response = client.get(f"/matrix/{response.json().get('eid')}")
+
assert response.status_code == 200
+ assert response.json().get('bibliography_eid') == '123'
| Create test for matrix post endpoint | ## Code Before:
def test_matrix_creation_endpoint(client):
response = client.post('/matrix', {
'bibliography': '12312312',
'fields': 'title,description',
})
print(response.json())
assert response.status_code == 200
## Instruction:
Create test for matrix post endpoint
## Code After:
from condor.models import Bibliography
def test_matrix_creation_endpoint(client, session):
bib = Bibliography(eid='123', description='lorem')
session.add(bib)
session.flush()
response = client.post('/matrix', {
'bibliography': '123',
'fields': 'title,description',
})
response = client.get(f"/matrix/{response.json().get('eid')}")
assert response.status_code == 200
assert response.json().get('bibliography_eid') == '123'
|
e94d39bf330312dc46697a689b56f7518ebd501c | footer/magic/images.py | footer/magic/images.py | import cairosvg
from django.template import Template, Context
def make_svg(context):
svg_tmpl = Template("""
<svg xmlns="http://www.w3.org/2000/svg"
width="500" height="600" viewBox="0 0 500 400">
<text x="0" y="0" font-family="Verdana" font-size="10" fill="blue" dy="0">
{{ name }} {{ text }}
{% for k,v in data.items %}
{% if v.items %}
<tspan x="0" dy="1.0em">
{{ k }}:
</tspan>
{% for kk, vv in v.items %}
<tspan x="0" dy="1.0em">
{{ kk }}: {{ vv }}
</tspan>
{% endfor %}
{% else %}
<tspan x="0" dy="1.0em">
{{ k }}: {{ v }}
</tspan>
{% endif %}
{% endfor %}
</text>
</svg>
""".strip())
svg = svg_tmpl.render(Context({'data': context}))
return svg
def write_svg_to_png(svg_raw, outfile):
cairosvg.svg2png(bytestring=svg_raw, write_to=outfile)
return outfile
| import cairosvg
from django.template import Template, Context
def make_svg(context):
svg_tmpl = Template("""
<svg xmlns="http://www.w3.org/2000/svg"
width="500" height="600" viewBox="0 0 500 400">
<text x="0" y="0" font-family="Verdana" font-size="10" fill="blue" dy="0">
{{ name }} {{ text }}
{% for k,v in data.items %}
{% if v.items %}
<tspan x="0" dy="1.0em">
{{ k }}:
</tspan>
{% for kk, vv in v.items %}
<tspan x="0" dy="1.0em">
{{ kk }}: <tspan fill="red" dy="0.0em">{{ vv }}</tspan>
</tspan>
{% endfor %}
{% else %}
<tspan x="0" dy="1.0em">
{{ k }}: <tspan fill="red" dy="0.0em">{{ v }}</tspan>
</tspan>
{% endif %}
{% endfor %}
</text>
</svg>
""".strip())
svg = svg_tmpl.render(Context({'data': context}))
return svg
def write_svg_to_png(svg_raw, outfile):
cairosvg.svg2png(bytestring=svg_raw, write_to=outfile)
return outfile
| Add some color to SVG key/values | Add some color to SVG key/values
| Python | mit | mihow/footer,mihow/footer,mihow/footer,mihow/footer | import cairosvg
from django.template import Template, Context
def make_svg(context):
svg_tmpl = Template("""
<svg xmlns="http://www.w3.org/2000/svg"
width="500" height="600" viewBox="0 0 500 400">
<text x="0" y="0" font-family="Verdana" font-size="10" fill="blue" dy="0">
{{ name }} {{ text }}
{% for k,v in data.items %}
{% if v.items %}
<tspan x="0" dy="1.0em">
{{ k }}:
</tspan>
{% for kk, vv in v.items %}
<tspan x="0" dy="1.0em">
- {{ kk }}: {{ vv }}
+ {{ kk }}: <tspan fill="red" dy="0.0em">{{ vv }}</tspan>
</tspan>
{% endfor %}
{% else %}
<tspan x="0" dy="1.0em">
- {{ k }}: {{ v }}
+ {{ k }}: <tspan fill="red" dy="0.0em">{{ v }}</tspan>
</tspan>
{% endif %}
{% endfor %}
</text>
</svg>
""".strip())
svg = svg_tmpl.render(Context({'data': context}))
return svg
def write_svg_to_png(svg_raw, outfile):
cairosvg.svg2png(bytestring=svg_raw, write_to=outfile)
return outfile
| Add some color to SVG key/values | ## Code Before:
import cairosvg
from django.template import Template, Context
def make_svg(context):
svg_tmpl = Template("""
<svg xmlns="http://www.w3.org/2000/svg"
width="500" height="600" viewBox="0 0 500 400">
<text x="0" y="0" font-family="Verdana" font-size="10" fill="blue" dy="0">
{{ name }} {{ text }}
{% for k,v in data.items %}
{% if v.items %}
<tspan x="0" dy="1.0em">
{{ k }}:
</tspan>
{% for kk, vv in v.items %}
<tspan x="0" dy="1.0em">
{{ kk }}: {{ vv }}
</tspan>
{% endfor %}
{% else %}
<tspan x="0" dy="1.0em">
{{ k }}: {{ v }}
</tspan>
{% endif %}
{% endfor %}
</text>
</svg>
""".strip())
svg = svg_tmpl.render(Context({'data': context}))
return svg
def write_svg_to_png(svg_raw, outfile):
cairosvg.svg2png(bytestring=svg_raw, write_to=outfile)
return outfile
## Instruction:
Add some color to SVG key/values
## Code After:
import cairosvg
from django.template import Template, Context
def make_svg(context):
svg_tmpl = Template("""
<svg xmlns="http://www.w3.org/2000/svg"
width="500" height="600" viewBox="0 0 500 400">
<text x="0" y="0" font-family="Verdana" font-size="10" fill="blue" dy="0">
{{ name }} {{ text }}
{% for k,v in data.items %}
{% if v.items %}
<tspan x="0" dy="1.0em">
{{ k }}:
</tspan>
{% for kk, vv in v.items %}
<tspan x="0" dy="1.0em">
{{ kk }}: <tspan fill="red" dy="0.0em">{{ vv }}</tspan>
</tspan>
{% endfor %}
{% else %}
<tspan x="0" dy="1.0em">
{{ k }}: <tspan fill="red" dy="0.0em">{{ v }}</tspan>
</tspan>
{% endif %}
{% endfor %}
</text>
</svg>
""".strip())
svg = svg_tmpl.render(Context({'data': context}))
return svg
def write_svg_to_png(svg_raw, outfile):
cairosvg.svg2png(bytestring=svg_raw, write_to=outfile)
return outfile
|
ebdafecea8c5b6597a7b2e2822afc98b9c47bb05 | toast/math/__init__.py | toast/math/__init__.py | def lerp(fromValue, toValue, step):
return fromValue + (toValue - fromValue) * step | def lerp(fromValue, toValue, percent):
return fromValue + (toValue - fromValue) * percent | Refactor to lerp param names. | Refactor to lerp param names.
| Python | mit | JoshuaSkelly/Toast,JSkelly/Toast | - def lerp(fromValue, toValue, step):
+ def lerp(fromValue, toValue, percent):
- return fromValue + (toValue - fromValue) * step
+ return fromValue + (toValue - fromValue) * percent | Refactor to lerp param names. | ## Code Before:
def lerp(fromValue, toValue, step):
return fromValue + (toValue - fromValue) * step
## Instruction:
Refactor to lerp param names.
## Code After:
def lerp(fromValue, toValue, percent):
return fromValue + (toValue - fromValue) * percent |
b2e743a19f13c898b2d95595a7a7175eca4bdb2c | results/urls.py | results/urls.py | __author__ = 'ankesh'
from django.conf.urls import patterns, url
import views
urlpatterns = patterns('',
url(r'^(?P<filename>[a-zA-Z0-9]+)/$', views.show_result, name='showResult'),
url(r'^compare/(?P<filename>[a-zA-Z0-9]+)/$', views.compare_result, name='compareResult'),
)
| __author__ = 'ankesh'
from django.conf.urls import patterns, url
import views
urlpatterns = patterns('',
url(r'^(?P<filename>[a-zA-Z0-9]+)/$', views.show_result, name='showResult'),
url(r'^compare/(?P<filename>[a-zA-Z0-9]+)/$', views.compare_result, name='compareResult'),
url(r'^recent/$', views.recent_results, name='recentResults'),
)
| Update URLs to include recent results | Update URLs to include recent results
| Python | bsd-2-clause | ankeshanand/benchmark,ankeshanand/benchmark,ankeshanand/benchmark,ankeshanand/benchmark | __author__ = 'ankesh'
from django.conf.urls import patterns, url
import views
urlpatterns = patterns('',
url(r'^(?P<filename>[a-zA-Z0-9]+)/$', views.show_result, name='showResult'),
url(r'^compare/(?P<filename>[a-zA-Z0-9]+)/$', views.compare_result, name='compareResult'),
+ url(r'^recent/$', views.recent_results, name='recentResults'),
)
| Update URLs to include recent results | ## Code Before:
__author__ = 'ankesh'
from django.conf.urls import patterns, url
import views
urlpatterns = patterns('',
url(r'^(?P<filename>[a-zA-Z0-9]+)/$', views.show_result, name='showResult'),
url(r'^compare/(?P<filename>[a-zA-Z0-9]+)/$', views.compare_result, name='compareResult'),
)
## Instruction:
Update URLs to include recent results
## Code After:
__author__ = 'ankesh'
from django.conf.urls import patterns, url
import views
urlpatterns = patterns('',
url(r'^(?P<filename>[a-zA-Z0-9]+)/$', views.show_result, name='showResult'),
url(r'^compare/(?P<filename>[a-zA-Z0-9]+)/$', views.compare_result, name='compareResult'),
url(r'^recent/$', views.recent_results, name='recentResults'),
)
|
7e3dfe47598401f4d5b96a377927473bb8adc244 | bush/aws/base.py | bush/aws/base.py | from bush.aws.session import create_session
class AWSBase:
# USAGE = ""
# SUB_COMMANDS = []
def __init__(self, options, resource_name):
self.name = resource_name
self.options = options
self.session = create_session(options)
self.resource = self.session.resource(resource_name)
self.client = self.session.client(resource_name)
| from bush.aws.session import create_session
class AWSBase:
# USAGE = ""
# SUB_COMMANDS = []
def __init__(self, options, resource_name):
self.name = resource_name
self.options = options
self.session = create_session(options)
@property
def resource(self):
if not hasattr(self, '__resource'):
self.__set_resource()
return self.__resource
@property
def client(self):
if not hasattr(self, '__client'):
self.__set_client()
return self.__client
def __set_resource(self):
self.__resource = self.session.resource(self.name)
def __set_client(self):
self.__client = self.session.client(self.name)
| Set resource and client when it is needed | Set resource and client when it is needed
| Python | mit | okamos/bush | from bush.aws.session import create_session
class AWSBase:
# USAGE = ""
# SUB_COMMANDS = []
def __init__(self, options, resource_name):
self.name = resource_name
self.options = options
self.session = create_session(options)
- self.resource = self.session.resource(resource_name)
- self.client = self.session.client(resource_name)
+ @property
+ def resource(self):
+ if not hasattr(self, '__resource'):
+ self.__set_resource()
+ return self.__resource
+
+ @property
+ def client(self):
+ if not hasattr(self, '__client'):
+ self.__set_client()
+ return self.__client
+
+ def __set_resource(self):
+ self.__resource = self.session.resource(self.name)
+
+ def __set_client(self):
+ self.__client = self.session.client(self.name)
+ | Set resource and client when it is needed | ## Code Before:
from bush.aws.session import create_session
class AWSBase:
# USAGE = ""
# SUB_COMMANDS = []
def __init__(self, options, resource_name):
self.name = resource_name
self.options = options
self.session = create_session(options)
self.resource = self.session.resource(resource_name)
self.client = self.session.client(resource_name)
## Instruction:
Set resource and client when it is needed
## Code After:
from bush.aws.session import create_session
class AWSBase:
# USAGE = ""
# SUB_COMMANDS = []
def __init__(self, options, resource_name):
self.name = resource_name
self.options = options
self.session = create_session(options)
@property
def resource(self):
if not hasattr(self, '__resource'):
self.__set_resource()
return self.__resource
@property
def client(self):
if not hasattr(self, '__client'):
self.__set_client()
return self.__client
def __set_resource(self):
self.__resource = self.session.resource(self.name)
def __set_client(self):
self.__client = self.session.client(self.name)
|
2425f5a3b0b3f465eec86de9873696611dfda04a | example_project/users/social_pipeline.py | example_project/users/social_pipeline.py | import hashlib
from rest_framework.response import Response
def auto_logout(*args, **kwargs):
"""Do not compare current user with new one"""
return {'user': None}
def save_avatar(strategy, details, user=None, *args, **kwargs):
"""Get user avatar from social provider."""
if user:
backend_name = kwargs['backend'].__class__.__name__.lower()
response = kwargs.get('response', {})
social_thumb = None
if 'facebook' in backend_name:
if 'id' in response:
social_thumb = (
'http://graph.facebook.com/{0}/picture?type=normal'
).format(response['id'])
elif 'twitter' in backend_name and response.get('profile_image_url'):
social_thumb = response['profile_image_url']
elif 'googleoauth2' in backend_name and response.get('image', {}).get('url'):
social_thumb = response['image']['url'].split('?')[0]
else:
social_thumb = 'http://www.gravatar.com/avatar/'
social_thumb += hashlib.md5(user.email.lower().encode('utf8')).hexdigest()
social_thumb += '?size=100'
if social_thumb and user.social_thumb != social_thumb:
user.social_thumb = social_thumb
strategy.storage.user.changed(user)
def check_for_email(backend, uid, user=None, *args, **kwargs):
if not kwargs['details'].get('email'):
return Response({'error': "Email wasn't provided by facebook"}, status=400)
| import hashlib
from rest_framework.response import Response
def auto_logout(*args, **kwargs):
"""Do not compare current user with new one"""
return {'user': None}
def save_avatar(strategy, details, user=None, *args, **kwargs):
"""Get user avatar from social provider."""
if user:
backend_name = kwargs['backend'].__class__.__name__.lower()
response = kwargs.get('response', {})
social_thumb = None
if 'facebook' in backend_name:
if 'id' in response:
social_thumb = (
'http://graph.facebook.com/{0}/picture?type=normal'
).format(response['id'])
elif 'twitter' in backend_name and response.get('profile_image_url'):
social_thumb = response['profile_image_url']
elif 'googleoauth2' in backend_name and response.get('image', {}).get('url'):
social_thumb = response['image']['url'].split('?')[0]
else:
social_thumb = 'http://www.gravatar.com/avatar/'
social_thumb += hashlib.md5(user.email.lower().encode('utf8')).hexdigest()
social_thumb += '?size=100'
if social_thumb and user.social_thumb != social_thumb:
user.social_thumb = social_thumb
strategy.storage.user.changed(user)
def check_for_email(backend, uid, user=None, *args, **kwargs):
if not kwargs['details'].get('email'):
return Response({'error': "Email wasn't provided by oauth provider"}, status=400)
| Fix error message in example project | Fix error message in example project
| Python | mit | st4lk/django-rest-social-auth,st4lk/django-rest-social-auth,st4lk/django-rest-social-auth | import hashlib
from rest_framework.response import Response
def auto_logout(*args, **kwargs):
"""Do not compare current user with new one"""
return {'user': None}
def save_avatar(strategy, details, user=None, *args, **kwargs):
"""Get user avatar from social provider."""
if user:
backend_name = kwargs['backend'].__class__.__name__.lower()
response = kwargs.get('response', {})
social_thumb = None
if 'facebook' in backend_name:
if 'id' in response:
social_thumb = (
'http://graph.facebook.com/{0}/picture?type=normal'
).format(response['id'])
elif 'twitter' in backend_name and response.get('profile_image_url'):
social_thumb = response['profile_image_url']
elif 'googleoauth2' in backend_name and response.get('image', {}).get('url'):
social_thumb = response['image']['url'].split('?')[0]
else:
social_thumb = 'http://www.gravatar.com/avatar/'
social_thumb += hashlib.md5(user.email.lower().encode('utf8')).hexdigest()
social_thumb += '?size=100'
if social_thumb and user.social_thumb != social_thumb:
user.social_thumb = social_thumb
strategy.storage.user.changed(user)
def check_for_email(backend, uid, user=None, *args, **kwargs):
if not kwargs['details'].get('email'):
- return Response({'error': "Email wasn't provided by facebook"}, status=400)
+ return Response({'error': "Email wasn't provided by oauth provider"}, status=400)
| Fix error message in example project | ## Code Before:
import hashlib
from rest_framework.response import Response
def auto_logout(*args, **kwargs):
"""Do not compare current user with new one"""
return {'user': None}
def save_avatar(strategy, details, user=None, *args, **kwargs):
"""Get user avatar from social provider."""
if user:
backend_name = kwargs['backend'].__class__.__name__.lower()
response = kwargs.get('response', {})
social_thumb = None
if 'facebook' in backend_name:
if 'id' in response:
social_thumb = (
'http://graph.facebook.com/{0}/picture?type=normal'
).format(response['id'])
elif 'twitter' in backend_name and response.get('profile_image_url'):
social_thumb = response['profile_image_url']
elif 'googleoauth2' in backend_name and response.get('image', {}).get('url'):
social_thumb = response['image']['url'].split('?')[0]
else:
social_thumb = 'http://www.gravatar.com/avatar/'
social_thumb += hashlib.md5(user.email.lower().encode('utf8')).hexdigest()
social_thumb += '?size=100'
if social_thumb and user.social_thumb != social_thumb:
user.social_thumb = social_thumb
strategy.storage.user.changed(user)
def check_for_email(backend, uid, user=None, *args, **kwargs):
if not kwargs['details'].get('email'):
return Response({'error': "Email wasn't provided by facebook"}, status=400)
## Instruction:
Fix error message in example project
## Code After:
import hashlib
from rest_framework.response import Response
def auto_logout(*args, **kwargs):
"""Do not compare current user with new one"""
return {'user': None}
def save_avatar(strategy, details, user=None, *args, **kwargs):
"""Get user avatar from social provider."""
if user:
backend_name = kwargs['backend'].__class__.__name__.lower()
response = kwargs.get('response', {})
social_thumb = None
if 'facebook' in backend_name:
if 'id' in response:
social_thumb = (
'http://graph.facebook.com/{0}/picture?type=normal'
).format(response['id'])
elif 'twitter' in backend_name and response.get('profile_image_url'):
social_thumb = response['profile_image_url']
elif 'googleoauth2' in backend_name and response.get('image', {}).get('url'):
social_thumb = response['image']['url'].split('?')[0]
else:
social_thumb = 'http://www.gravatar.com/avatar/'
social_thumb += hashlib.md5(user.email.lower().encode('utf8')).hexdigest()
social_thumb += '?size=100'
if social_thumb and user.social_thumb != social_thumb:
user.social_thumb = social_thumb
strategy.storage.user.changed(user)
def check_for_email(backend, uid, user=None, *args, **kwargs):
if not kwargs['details'].get('email'):
return Response({'error': "Email wasn't provided by oauth provider"}, status=400)
|
20f6df95d302ea79d11208ada6218a2c99d397e3 | common.py | common.py | import json
from base64 import b64encode
# http://stackoverflow.com/a/4256027/212555
def del_none(o):
"""
Delete keys with the value ``None`` in a dictionary, recursively.
This alters the input so you may wish to ``copy`` the dict first.
"""
if isinstance(o, dict):
d = o
else:
d = o.__dict__
for key, value in list(d.items()):
if value is None:
del d[key]
elif isinstance(value, dict):
del_none(value)
return d
def _to_json_dict(o):
if isinstance(o, bytes):
try:
return o.decode("ASCII")
except UnicodeError:
return b64encode(o)
if isinstance(o, set):
return list(o)
return o.__dict__
def to_json(o):
return json.dumps(del_none(o), default=_to_json_dict, indent=4)
| import json
from base64 import b64encode
# http://stackoverflow.com/a/4256027/212555
def del_none(o):
"""
Delete keys with the value ``None`` in a dictionary, recursively.
This alters the input so you may wish to ``copy`` the dict first.
"""
if isinstance(o, dict):
d = o.copy()
else:
d = o.__dict__.copy()
for key, value in list(d.items()):
if value is None:
del d[key]
elif isinstance(value, dict):
del_none(value)
return d
def _to_json_dict(o):
if isinstance(o, bytes):
try:
return o.decode("ASCII")
except UnicodeError:
return b64encode(o)
if isinstance(o, set):
return list(o)
return o.__dict__
def to_json(o):
return json.dumps(del_none(o), default=_to_json_dict, indent=4)
| Make a copy of dicts before deleting things from them when printing. | Make a copy of dicts before deleting things from them when printing.
| Python | bsd-2-clause | brendanlong/mpeg-ts-inspector,brendanlong/mpeg-ts-inspector | import json
from base64 import b64encode
# http://stackoverflow.com/a/4256027/212555
def del_none(o):
"""
Delete keys with the value ``None`` in a dictionary, recursively.
This alters the input so you may wish to ``copy`` the dict first.
"""
if isinstance(o, dict):
- d = o
+ d = o.copy()
else:
- d = o.__dict__
+ d = o.__dict__.copy()
for key, value in list(d.items()):
if value is None:
del d[key]
elif isinstance(value, dict):
del_none(value)
return d
def _to_json_dict(o):
if isinstance(o, bytes):
try:
return o.decode("ASCII")
except UnicodeError:
return b64encode(o)
if isinstance(o, set):
return list(o)
return o.__dict__
def to_json(o):
return json.dumps(del_none(o), default=_to_json_dict, indent=4)
| Make a copy of dicts before deleting things from them when printing. | ## Code Before:
import json
from base64 import b64encode
# http://stackoverflow.com/a/4256027/212555
def del_none(o):
"""
Delete keys with the value ``None`` in a dictionary, recursively.
This alters the input so you may wish to ``copy`` the dict first.
"""
if isinstance(o, dict):
d = o
else:
d = o.__dict__
for key, value in list(d.items()):
if value is None:
del d[key]
elif isinstance(value, dict):
del_none(value)
return d
def _to_json_dict(o):
if isinstance(o, bytes):
try:
return o.decode("ASCII")
except UnicodeError:
return b64encode(o)
if isinstance(o, set):
return list(o)
return o.__dict__
def to_json(o):
return json.dumps(del_none(o), default=_to_json_dict, indent=4)
## Instruction:
Make a copy of dicts before deleting things from them when printing.
## Code After:
import json
from base64 import b64encode
# http://stackoverflow.com/a/4256027/212555
def del_none(o):
"""
Delete keys with the value ``None`` in a dictionary, recursively.
This alters the input so you may wish to ``copy`` the dict first.
"""
if isinstance(o, dict):
d = o.copy()
else:
d = o.__dict__.copy()
for key, value in list(d.items()):
if value is None:
del d[key]
elif isinstance(value, dict):
del_none(value)
return d
def _to_json_dict(o):
if isinstance(o, bytes):
try:
return o.decode("ASCII")
except UnicodeError:
return b64encode(o)
if isinstance(o, set):
return list(o)
return o.__dict__
def to_json(o):
return json.dumps(del_none(o), default=_to_json_dict, indent=4)
|
fd7027ae889d61949998ea02fbb56dbc8e6005a4 | polling_stations/apps/data_importers/management/commands/import_cheltenham.py | polling_stations/apps/data_importers/management/commands/import_cheltenham.py | from data_importers.management.commands import BaseHalaroseCsvImporter
class Command(BaseHalaroseCsvImporter):
council_id = "CHT"
addresses_name = (
"2022-05-05/2022-02-25T12:48:35.558843/polling_station_export-2022-02-25.csv"
)
stations_name = (
"2022-05-05/2022-02-25T12:48:35.558843/polling_station_export-2022-02-25.csv"
)
elections = ["2022-05-05"]
def address_record_to_dict(self, record):
if record.housepostcode in [
"GL50 2RF",
"GL52 6RN",
"GL52 2ES",
"GL53 7AJ",
"GL50 3RB",
"GL53 0HL",
"GL50 2DZ",
]:
return None
return super().address_record_to_dict(record)
| from data_importers.management.commands import BaseHalaroseCsvImporter
class Command(BaseHalaroseCsvImporter):
council_id = "CHT"
addresses_name = (
"2022-05-05/2022-02-25T12:48:35.558843/polling_station_export-2022-02-25.csv"
)
stations_name = (
"2022-05-05/2022-02-25T12:48:35.558843/polling_station_export-2022-02-25.csv"
)
elections = ["2022-05-05"]
def address_record_to_dict(self, record):
if record.housepostcode in [
"GL50 2RF",
"GL52 6RN",
"GL52 2ES",
"GL53 7AJ",
"GL50 3RB",
"GL53 0HL",
"GL50 2DZ",
]:
return None
return super().address_record_to_dict(record)
def station_record_to_dict(self, record):
if record.pollingstationnumber == "191":
record = record._replace(pollingstationaddress_1="")
return super().station_record_to_dict(record)
| Fix to CHT station name | Fix to CHT station name
| Python | bsd-3-clause | DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations | from data_importers.management.commands import BaseHalaroseCsvImporter
class Command(BaseHalaroseCsvImporter):
council_id = "CHT"
addresses_name = (
"2022-05-05/2022-02-25T12:48:35.558843/polling_station_export-2022-02-25.csv"
)
stations_name = (
"2022-05-05/2022-02-25T12:48:35.558843/polling_station_export-2022-02-25.csv"
)
elections = ["2022-05-05"]
def address_record_to_dict(self, record):
if record.housepostcode in [
"GL50 2RF",
"GL52 6RN",
"GL52 2ES",
"GL53 7AJ",
"GL50 3RB",
"GL53 0HL",
"GL50 2DZ",
]:
return None
return super().address_record_to_dict(record)
+ def station_record_to_dict(self, record):
+ if record.pollingstationnumber == "191":
+ record = record._replace(pollingstationaddress_1="")
+ return super().station_record_to_dict(record)
+ | Fix to CHT station name | ## Code Before:
from data_importers.management.commands import BaseHalaroseCsvImporter
class Command(BaseHalaroseCsvImporter):
council_id = "CHT"
addresses_name = (
"2022-05-05/2022-02-25T12:48:35.558843/polling_station_export-2022-02-25.csv"
)
stations_name = (
"2022-05-05/2022-02-25T12:48:35.558843/polling_station_export-2022-02-25.csv"
)
elections = ["2022-05-05"]
def address_record_to_dict(self, record):
if record.housepostcode in [
"GL50 2RF",
"GL52 6RN",
"GL52 2ES",
"GL53 7AJ",
"GL50 3RB",
"GL53 0HL",
"GL50 2DZ",
]:
return None
return super().address_record_to_dict(record)
## Instruction:
Fix to CHT station name
## Code After:
from data_importers.management.commands import BaseHalaroseCsvImporter
class Command(BaseHalaroseCsvImporter):
council_id = "CHT"
addresses_name = (
"2022-05-05/2022-02-25T12:48:35.558843/polling_station_export-2022-02-25.csv"
)
stations_name = (
"2022-05-05/2022-02-25T12:48:35.558843/polling_station_export-2022-02-25.csv"
)
elections = ["2022-05-05"]
def address_record_to_dict(self, record):
if record.housepostcode in [
"GL50 2RF",
"GL52 6RN",
"GL52 2ES",
"GL53 7AJ",
"GL50 3RB",
"GL53 0HL",
"GL50 2DZ",
]:
return None
return super().address_record_to_dict(record)
def station_record_to_dict(self, record):
if record.pollingstationnumber == "191":
record = record._replace(pollingstationaddress_1="")
return super().station_record_to_dict(record)
|
add50f0356756469c1ee1e52f13faee7df85f280 | tests/rest/rest_test_suite.py | tests/rest/rest_test_suite.py | import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), "../"))
from http_test_suite import HTTPTestSuite
from mozdef_util.utilities.dot_dict import DotDict
import mock
from configlib import OptionParser
class RestTestDict(DotDict):
@property
def __dict__(self):
return self
class RestTestSuite(HTTPTestSuite):
def setup(self):
sample_config = RestTestDict()
sample_config.configfile = os.path.join(os.path.dirname(__file__), 'index.conf')
OptionParser.parse_args = mock.Mock(return_value=(sample_config, {}))
from rest import index
self.application = index.application
super(RestTestSuite, self).setup()
| import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), "../"))
from http_test_suite import HTTPTestSuite
from mozdef_util.utilities.dot_dict import DotDict
import mock
from configlib import OptionParser
import importlib
class RestTestDict(DotDict):
@property
def __dict__(self):
return self
class RestTestSuite(HTTPTestSuite):
def setup(self):
sample_config = RestTestDict()
sample_config.configfile = os.path.join(os.path.dirname(__file__), 'index.conf')
OptionParser.parse_args = mock.Mock(return_value=(sample_config, {}))
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../../rest"))
import plugins
importlib.reload(plugins)
from rest import index
self.application = index.application
super(RestTestSuite, self).setup()
| Fix import path for rest plugins | Fix import path for rest plugins
| Python | mpl-2.0 | mozilla/MozDef,mozilla/MozDef,mpurzynski/MozDef,mpurzynski/MozDef,mozilla/MozDef,mpurzynski/MozDef,jeffbryner/MozDef,jeffbryner/MozDef,mozilla/MozDef,mpurzynski/MozDef,jeffbryner/MozDef,jeffbryner/MozDef | import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), "../"))
from http_test_suite import HTTPTestSuite
from mozdef_util.utilities.dot_dict import DotDict
import mock
from configlib import OptionParser
+ import importlib
class RestTestDict(DotDict):
@property
def __dict__(self):
return self
class RestTestSuite(HTTPTestSuite):
def setup(self):
sample_config = RestTestDict()
sample_config.configfile = os.path.join(os.path.dirname(__file__), 'index.conf')
OptionParser.parse_args = mock.Mock(return_value=(sample_config, {}))
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../../rest"))
+ import plugins
+ importlib.reload(plugins)
from rest import index
+
self.application = index.application
super(RestTestSuite, self).setup()
| Fix import path for rest plugins | ## Code Before:
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), "../"))
from http_test_suite import HTTPTestSuite
from mozdef_util.utilities.dot_dict import DotDict
import mock
from configlib import OptionParser
class RestTestDict(DotDict):
@property
def __dict__(self):
return self
class RestTestSuite(HTTPTestSuite):
def setup(self):
sample_config = RestTestDict()
sample_config.configfile = os.path.join(os.path.dirname(__file__), 'index.conf')
OptionParser.parse_args = mock.Mock(return_value=(sample_config, {}))
from rest import index
self.application = index.application
super(RestTestSuite, self).setup()
## Instruction:
Fix import path for rest plugins
## Code After:
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), "../"))
from http_test_suite import HTTPTestSuite
from mozdef_util.utilities.dot_dict import DotDict
import mock
from configlib import OptionParser
import importlib
class RestTestDict(DotDict):
@property
def __dict__(self):
return self
class RestTestSuite(HTTPTestSuite):
def setup(self):
sample_config = RestTestDict()
sample_config.configfile = os.path.join(os.path.dirname(__file__), 'index.conf')
OptionParser.parse_args = mock.Mock(return_value=(sample_config, {}))
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../../rest"))
import plugins
importlib.reload(plugins)
from rest import index
self.application = index.application
super(RestTestSuite, self).setup()
|
64cd71fd171cd1b76b111aedc94423006176f811 | src/tldt/cli.py | src/tldt/cli.py | import argparse
import tldt
def main():
parser = argparse.ArgumentParser(description="cacat")
parser.add_argument("head_repo")
parser.add_argument("head_sha")
parser.add_argument("base_repo")
parser.add_argument("base_sha")
args = parser.parse_args()
tldt.main(head_repo=args.head_repo,
head_sha=args.head_sha,
base_repo=args.base_repo,
base_sha=args.base_sha)
if __name__ == '__main__':
main()
| import argparse
import os.path
import tldt
def main():
user_home = os.path.expanduser("~")
parser = argparse.ArgumentParser(description="cacat")
parser.add_argument("head_repo")
parser.add_argument("head_sha")
parser.add_argument("base_repo")
parser.add_argument("base_sha")
parser.add_argument("--configuration", default=os.path.join(user_home, "tldt.ini"))
args = parser.parse_args()
tldt.main(head_repo=args.head_repo,
head_sha=args.head_sha,
base_repo=args.base_repo,
base_sha=args.base_sha,
configuration_path=args.configuration)
if __name__ == '__main__':
main()
| Add configuration file option with default to ~/tldt.ini | Add configuration file option with default to ~/tldt.ini
| Python | unlicense | rciorba/tldt,rciorba/tldt | import argparse
+ import os.path
import tldt
def main():
+ user_home = os.path.expanduser("~")
parser = argparse.ArgumentParser(description="cacat")
parser.add_argument("head_repo")
parser.add_argument("head_sha")
parser.add_argument("base_repo")
parser.add_argument("base_sha")
+ parser.add_argument("--configuration", default=os.path.join(user_home, "tldt.ini"))
args = parser.parse_args()
tldt.main(head_repo=args.head_repo,
- head_sha=args.head_sha,
+ head_sha=args.head_sha,
- base_repo=args.base_repo,
+ base_repo=args.base_repo,
- base_sha=args.base_sha)
+ base_sha=args.base_sha,
-
+ configuration_path=args.configuration)
if __name__ == '__main__':
main()
| Add configuration file option with default to ~/tldt.ini | ## Code Before:
import argparse
import tldt
def main():
parser = argparse.ArgumentParser(description="cacat")
parser.add_argument("head_repo")
parser.add_argument("head_sha")
parser.add_argument("base_repo")
parser.add_argument("base_sha")
args = parser.parse_args()
tldt.main(head_repo=args.head_repo,
head_sha=args.head_sha,
base_repo=args.base_repo,
base_sha=args.base_sha)
if __name__ == '__main__':
main()
## Instruction:
Add configuration file option with default to ~/tldt.ini
## Code After:
import argparse
import os.path
import tldt
def main():
user_home = os.path.expanduser("~")
parser = argparse.ArgumentParser(description="cacat")
parser.add_argument("head_repo")
parser.add_argument("head_sha")
parser.add_argument("base_repo")
parser.add_argument("base_sha")
parser.add_argument("--configuration", default=os.path.join(user_home, "tldt.ini"))
args = parser.parse_args()
tldt.main(head_repo=args.head_repo,
head_sha=args.head_sha,
base_repo=args.base_repo,
base_sha=args.base_sha,
configuration_path=args.configuration)
if __name__ == '__main__':
main()
|
6cf42d661facf1c11de545959b91c073709eac8e | webapp_tests.py | webapp_tests.py | import os
import webapp
import unittest
class WebappTestExtractingServiceDomainsFromLinks(unittest.TestCase):
#def setUp(self):
# self.app = webapp.app.test_client()
def test_extract_service_domain_from_link(self):
status, domain = webapp.extract_service_domain_from_link('https://foo.service.gov.uk/blah')
assert True == status
assert "foo.service.gov.uk" == domain
def test_extract_nonservice_domain_from_link(self):
status, domain = webapp.extract_service_domain_from_link('https://foo.foo.gov.uk/blah')
assert False == status
if __name__ == '__main__':
unittest.main()
| import os
import webapp
import unittest
class WebappTestExtractingServiceDomainsFromLinks(unittest.TestCase):
#def setUp(self):
# self.app = webapp.app.test_client()
def test_extract_service_domain_from_link(self):
status, domain = webapp.extract_service_domain_from_link('https://foo.service.gov.uk/blah')
assert True == status
assert "foo.service.gov.uk" == domain
def test_extract_nonservice_domain_from_link(self):
status, domain = webapp.extract_service_domain_from_link('https://foo.foo.gov.uk/blah')
assert False == status
class WebappTestExtractingServiceLinkFromSlug(unittest.TestCase):
def test_find_link_from_slug(self):
status, link = webapp.find_link_from_slug('/lasting-power-of-attorney')
assert True == status
assert "https://lastingpowerofattorney.service.gov.uk/" == link
def test_fail_to_find_link_from_slug(self):
status, link = webapp.find_link_from_slug('/bank-holidays')
assert False == status
if __name__ == '__main__':
unittest.main()
| Add a test for extracting service domain from a link | Add a test for extracting service domain from a link
| Python | mit | alphagov/service-domain-checker | import os
import webapp
import unittest
class WebappTestExtractingServiceDomainsFromLinks(unittest.TestCase):
#def setUp(self):
# self.app = webapp.app.test_client()
def test_extract_service_domain_from_link(self):
status, domain = webapp.extract_service_domain_from_link('https://foo.service.gov.uk/blah')
assert True == status
assert "foo.service.gov.uk" == domain
+
def test_extract_nonservice_domain_from_link(self):
status, domain = webapp.extract_service_domain_from_link('https://foo.foo.gov.uk/blah')
assert False == status
+
+ class WebappTestExtractingServiceLinkFromSlug(unittest.TestCase):
+
+ def test_find_link_from_slug(self):
+ status, link = webapp.find_link_from_slug('/lasting-power-of-attorney')
+ assert True == status
+ assert "https://lastingpowerofattorney.service.gov.uk/" == link
+
+ def test_fail_to_find_link_from_slug(self):
+ status, link = webapp.find_link_from_slug('/bank-holidays')
+ assert False == status
+
+
if __name__ == '__main__':
unittest.main()
| Add a test for extracting service domain from a link | ## Code Before:
import os
import webapp
import unittest
class WebappTestExtractingServiceDomainsFromLinks(unittest.TestCase):
#def setUp(self):
# self.app = webapp.app.test_client()
def test_extract_service_domain_from_link(self):
status, domain = webapp.extract_service_domain_from_link('https://foo.service.gov.uk/blah')
assert True == status
assert "foo.service.gov.uk" == domain
def test_extract_nonservice_domain_from_link(self):
status, domain = webapp.extract_service_domain_from_link('https://foo.foo.gov.uk/blah')
assert False == status
if __name__ == '__main__':
unittest.main()
## Instruction:
Add a test for extracting service domain from a link
## Code After:
import os
import webapp
import unittest
class WebappTestExtractingServiceDomainsFromLinks(unittest.TestCase):
#def setUp(self):
# self.app = webapp.app.test_client()
def test_extract_service_domain_from_link(self):
status, domain = webapp.extract_service_domain_from_link('https://foo.service.gov.uk/blah')
assert True == status
assert "foo.service.gov.uk" == domain
def test_extract_nonservice_domain_from_link(self):
status, domain = webapp.extract_service_domain_from_link('https://foo.foo.gov.uk/blah')
assert False == status
class WebappTestExtractingServiceLinkFromSlug(unittest.TestCase):
def test_find_link_from_slug(self):
status, link = webapp.find_link_from_slug('/lasting-power-of-attorney')
assert True == status
assert "https://lastingpowerofattorney.service.gov.uk/" == link
def test_fail_to_find_link_from_slug(self):
status, link = webapp.find_link_from_slug('/bank-holidays')
assert False == status
if __name__ == '__main__':
unittest.main()
|
c12a1b53166c34c074e018fcc149a0aa2db56b43 | helpscout/models/folder.py | helpscout/models/folder.py |
import properties
from .. import BaseModel
class Folder(BaseModel):
name = properties.String(
'Folder name',
required=True,
)
type = properties.StringChoice(
'The type of folder.',
choices=['needsattention',
'drafts',
'assigned',
'open',
'closed',
'spam',
'mine',
],
default='drafts',
required=True,
)
user_id = properties.Integer(
'If the folder type is ``MyTickets``, this represents the Help Scout '
'user to which this folder belongs. Otherwise it is empty.',
)
total_count = properties.Integer(
'Total number of conversations in this folder.',
)
active_count = properties.Integer(
'Total number of conversations in this folder that are in an active '
'state (vs pending).',
)
modified_at = properties.DateTime(
'UTC time when this folder was modified.',
)
|
import properties
from .. import BaseModel
class Folder(BaseModel):
name = properties.String(
'Folder name',
required=True,
)
type = properties.StringChoice(
'The type of folder.',
choices=['needsattention',
'drafts',
'assigned',
'open',
'closed',
'spam',
'mine',
'team',
],
default='drafts',
required=True,
)
user_id = properties.Integer(
'If the folder type is ``MyTickets``, this represents the Help Scout '
'user to which this folder belongs. Otherwise it is empty.',
)
total_count = properties.Integer(
'Total number of conversations in this folder.',
)
active_count = properties.Integer(
'Total number of conversations in this folder that are in an active '
'state (vs pending).',
)
modified_at = properties.DateTime(
'UTC time when this folder was modified.',
)
| Add 'team' to Folder type options | [ADD] Add 'team' to Folder type options
| Python | mit | LasLabs/python-helpscout |
import properties
from .. import BaseModel
class Folder(BaseModel):
name = properties.String(
'Folder name',
required=True,
)
type = properties.StringChoice(
'The type of folder.',
choices=['needsattention',
'drafts',
'assigned',
'open',
'closed',
'spam',
'mine',
+ 'team',
],
default='drafts',
required=True,
)
user_id = properties.Integer(
'If the folder type is ``MyTickets``, this represents the Help Scout '
'user to which this folder belongs. Otherwise it is empty.',
)
total_count = properties.Integer(
'Total number of conversations in this folder.',
)
active_count = properties.Integer(
'Total number of conversations in this folder that are in an active '
'state (vs pending).',
)
modified_at = properties.DateTime(
'UTC time when this folder was modified.',
)
| Add 'team' to Folder type options | ## Code Before:
import properties
from .. import BaseModel
class Folder(BaseModel):
name = properties.String(
'Folder name',
required=True,
)
type = properties.StringChoice(
'The type of folder.',
choices=['needsattention',
'drafts',
'assigned',
'open',
'closed',
'spam',
'mine',
],
default='drafts',
required=True,
)
user_id = properties.Integer(
'If the folder type is ``MyTickets``, this represents the Help Scout '
'user to which this folder belongs. Otherwise it is empty.',
)
total_count = properties.Integer(
'Total number of conversations in this folder.',
)
active_count = properties.Integer(
'Total number of conversations in this folder that are in an active '
'state (vs pending).',
)
modified_at = properties.DateTime(
'UTC time when this folder was modified.',
)
## Instruction:
Add 'team' to Folder type options
## Code After:
import properties
from .. import BaseModel
class Folder(BaseModel):
name = properties.String(
'Folder name',
required=True,
)
type = properties.StringChoice(
'The type of folder.',
choices=['needsattention',
'drafts',
'assigned',
'open',
'closed',
'spam',
'mine',
'team',
],
default='drafts',
required=True,
)
user_id = properties.Integer(
'If the folder type is ``MyTickets``, this represents the Help Scout '
'user to which this folder belongs. Otherwise it is empty.',
)
total_count = properties.Integer(
'Total number of conversations in this folder.',
)
active_count = properties.Integer(
'Total number of conversations in this folder that are in an active '
'state (vs pending).',
)
modified_at = properties.DateTime(
'UTC time when this folder was modified.',
)
|
bccfc6d3c0035e2a5668607ebb7dd6047ee1942f | kokki/cookbooks/mdadm/recipes/default.py | kokki/cookbooks/mdadm/recipes/default.py |
from kokki import *
if env.config.mdadm.arrays:
Package("mdadm")
Execute("mdadm-update-conf",
action = "nothing",
command = ("("
"echo DEVICE partitions > /etc/mdadm/mdadm.conf"
"; mdadm --detail --scan >> /etc/mdadm/mdadm.conf"
")"
))
for array in env.config.mdadm.arrays:
env.cookbooks.mdadm.Array(**array)
if array.get('fstype'):
if array['fstype'] == "xfs":
Package("xfsprogs")
Execute("mkfs.%(fstype)s -f %(device)s" % dict(fstype=array['fstype'], device=array['name']),
not_if = """if [ "`file -s %(device)s`" = "%(device)s: data" ]; then exit 1; fi""" % dict(device=array['name']))
if array.get('mount_point'):
Mount(array['mount_point'],
device = array['name'],
fstype = array['fstype'],
options = array['fsoptions'] if array.get('fsoptions') is not None else ["noatime"],
action = ["mount", "enable"])
|
from kokki import *
if env.config.mdadm.arrays:
Package("mdadm")
Execute("mdadm-update-conf",
action = "nothing",
command = ("("
"echo DEVICE partitions > /etc/mdadm/mdadm.conf"
"; mdadm --detail --scan >> /etc/mdadm/mdadm.conf"
")"
))
for array in env.config.mdadm.arrays:
fstype = array.pop('fstype', None)
fsoptions = array.pop('fsoptions', None)
mount_point = array.pop('mount_point', None)
env.cookbooks.mdadm.Array(**array)
if fstype:
if fstype == "xfs":
Package("xfsprogs")
Execute("mkfs.%(fstype)s -f %(device)s" % dict(fstype=fstype, device=array['name']),
not_if = """if [ "`file -s %(device)s`" = "%(device)s: data" ]; then exit 1; fi""" % dict(device=array['name']))
if mount_point:
Mount(mount_point,
device = array['name'],
fstype = fstype,
options = fsoptions if fsoptions is not None else ["noatime"],
action = ["mount", "enable"])
| Fix to mounting mdadm raid arrays | Fix to mounting mdadm raid arrays
| Python | bsd-3-clause | samuel/kokki |
from kokki import *
if env.config.mdadm.arrays:
Package("mdadm")
Execute("mdadm-update-conf",
action = "nothing",
command = ("("
"echo DEVICE partitions > /etc/mdadm/mdadm.conf"
"; mdadm --detail --scan >> /etc/mdadm/mdadm.conf"
")"
))
for array in env.config.mdadm.arrays:
+ fstype = array.pop('fstype', None)
+ fsoptions = array.pop('fsoptions', None)
+ mount_point = array.pop('mount_point', None)
+
env.cookbooks.mdadm.Array(**array)
- if array.get('fstype'):
+ if fstype:
- if array['fstype'] == "xfs":
+ if fstype == "xfs":
Package("xfsprogs")
- Execute("mkfs.%(fstype)s -f %(device)s" % dict(fstype=array['fstype'], device=array['name']),
+ Execute("mkfs.%(fstype)s -f %(device)s" % dict(fstype=fstype, device=array['name']),
not_if = """if [ "`file -s %(device)s`" = "%(device)s: data" ]; then exit 1; fi""" % dict(device=array['name']))
- if array.get('mount_point'):
+ if mount_point:
- Mount(array['mount_point'],
+ Mount(mount_point,
device = array['name'],
- fstype = array['fstype'],
+ fstype = fstype,
- options = array['fsoptions'] if array.get('fsoptions') is not None else ["noatime"],
+ options = fsoptions if fsoptions is not None else ["noatime"],
action = ["mount", "enable"])
| Fix to mounting mdadm raid arrays | ## Code Before:
from kokki import *
if env.config.mdadm.arrays:
Package("mdadm")
Execute("mdadm-update-conf",
action = "nothing",
command = ("("
"echo DEVICE partitions > /etc/mdadm/mdadm.conf"
"; mdadm --detail --scan >> /etc/mdadm/mdadm.conf"
")"
))
for array in env.config.mdadm.arrays:
env.cookbooks.mdadm.Array(**array)
if array.get('fstype'):
if array['fstype'] == "xfs":
Package("xfsprogs")
Execute("mkfs.%(fstype)s -f %(device)s" % dict(fstype=array['fstype'], device=array['name']),
not_if = """if [ "`file -s %(device)s`" = "%(device)s: data" ]; then exit 1; fi""" % dict(device=array['name']))
if array.get('mount_point'):
Mount(array['mount_point'],
device = array['name'],
fstype = array['fstype'],
options = array['fsoptions'] if array.get('fsoptions') is not None else ["noatime"],
action = ["mount", "enable"])
## Instruction:
Fix to mounting mdadm raid arrays
## Code After:
from kokki import *
if env.config.mdadm.arrays:
Package("mdadm")
Execute("mdadm-update-conf",
action = "nothing",
command = ("("
"echo DEVICE partitions > /etc/mdadm/mdadm.conf"
"; mdadm --detail --scan >> /etc/mdadm/mdadm.conf"
")"
))
for array in env.config.mdadm.arrays:
fstype = array.pop('fstype', None)
fsoptions = array.pop('fsoptions', None)
mount_point = array.pop('mount_point', None)
env.cookbooks.mdadm.Array(**array)
if fstype:
if fstype == "xfs":
Package("xfsprogs")
Execute("mkfs.%(fstype)s -f %(device)s" % dict(fstype=fstype, device=array['name']),
not_if = """if [ "`file -s %(device)s`" = "%(device)s: data" ]; then exit 1; fi""" % dict(device=array['name']))
if mount_point:
Mount(mount_point,
device = array['name'],
fstype = fstype,
options = fsoptions if fsoptions is not None else ["noatime"],
action = ["mount", "enable"])
|
4f2e23fe260e5f061d7d57821908492f14a2c56a | withtool/subprocess.py | withtool/subprocess.py | import subprocess
def run(command):
try:
subprocess.check_call(command, shell=True)
except:
pass
| import subprocess
def run(command):
try:
subprocess.check_call(command, shell=True)
except Exception:
pass
| Set expected exception class in "except" block | Set expected exception class in "except" block
Fix issue E722 of flake8
| Python | mit | renanivo/with | import subprocess
def run(command):
try:
subprocess.check_call(command, shell=True)
- except:
+ except Exception:
pass
| Set expected exception class in "except" block | ## Code Before:
import subprocess
def run(command):
try:
subprocess.check_call(command, shell=True)
except:
pass
## Instruction:
Set expected exception class in "except" block
## Code After:
import subprocess
def run(command):
try:
subprocess.check_call(command, shell=True)
except Exception:
pass
|
ff308a17c79fe2c27dcb2a1f888ee1332f6fdc11 | events.py | events.py |
import Natural.util as util
import sublime, sublime_plugin
class PerformEventListener(sublime_plugin.EventListener):
"""Suggest subroutine completions for the perform statement."""
def on_query_completions(self, view, prefix, points):
if not util.is_natural_file(view):
return None
texts = util.text_preceding_points(view, points)
if all([text.strip().endswith('perform') for text in texts]):
subroutines = util.find_text_by_selector(view,
'entity.name.function.natural')
if not subroutines:
return None
subroutines.sort()
completions = [[sub, sub] for sub in subroutines]
return (completions, sublime.INHIBIT_WORD_COMPLETIONS)
|
import Natural.util as util
import sublime, sublime_plugin
class PerformEventListener(sublime_plugin.EventListener):
"""Suggest subroutine completions for the perform statement."""
def on_query_completions(self, view, prefix, points):
if not util.is_natural_file(view):
return None
texts = util.text_preceding_points(view, points)
if all([text.strip().endswith('perform') for text in texts]):
subroutines = util.find_text_by_selector(view,
'entity.name.function.natural')
if not subroutines:
return None
subroutines.sort()
completions = [[sub, sub] for sub in subroutines]
return (completions, sublime.INHIBIT_WORD_COMPLETIONS)
class AddRulerToColumn72Listener(sublime_plugin.EventListener):
"""Add a ruler to column 72 when a Natural file is opened. If the user has
other rulers, they're not messed with."""
def on_load(self, view):
if not util.is_natural_file(view):
return
rulers = view.settings().get('rulers')
if 72 not in rulers:
rulers.append(72)
rulers.sort()
view.settings().set('rulers', rulers)
| Add a ruler to column 72 | Add a ruler to column 72
| Python | mit | andref/Unnatural-Sublime-Package |
import Natural.util as util
import sublime, sublime_plugin
class PerformEventListener(sublime_plugin.EventListener):
"""Suggest subroutine completions for the perform statement."""
def on_query_completions(self, view, prefix, points):
if not util.is_natural_file(view):
return None
texts = util.text_preceding_points(view, points)
if all([text.strip().endswith('perform') for text in texts]):
subroutines = util.find_text_by_selector(view,
'entity.name.function.natural')
if not subroutines:
return None
subroutines.sort()
completions = [[sub, sub] for sub in subroutines]
return (completions, sublime.INHIBIT_WORD_COMPLETIONS)
+
+ class AddRulerToColumn72Listener(sublime_plugin.EventListener):
+ """Add a ruler to column 72 when a Natural file is opened. If the user has
+ other rulers, they're not messed with."""
+
+ def on_load(self, view):
+ if not util.is_natural_file(view):
+ return
+ rulers = view.settings().get('rulers')
+ if 72 not in rulers:
+ rulers.append(72)
+ rulers.sort()
+ view.settings().set('rulers', rulers)
+ | Add a ruler to column 72 | ## Code Before:
import Natural.util as util
import sublime, sublime_plugin
class PerformEventListener(sublime_plugin.EventListener):
"""Suggest subroutine completions for the perform statement."""
def on_query_completions(self, view, prefix, points):
if not util.is_natural_file(view):
return None
texts = util.text_preceding_points(view, points)
if all([text.strip().endswith('perform') for text in texts]):
subroutines = util.find_text_by_selector(view,
'entity.name.function.natural')
if not subroutines:
return None
subroutines.sort()
completions = [[sub, sub] for sub in subroutines]
return (completions, sublime.INHIBIT_WORD_COMPLETIONS)
## Instruction:
Add a ruler to column 72
## Code After:
import Natural.util as util
import sublime, sublime_plugin
class PerformEventListener(sublime_plugin.EventListener):
"""Suggest subroutine completions for the perform statement."""
def on_query_completions(self, view, prefix, points):
if not util.is_natural_file(view):
return None
texts = util.text_preceding_points(view, points)
if all([text.strip().endswith('perform') for text in texts]):
subroutines = util.find_text_by_selector(view,
'entity.name.function.natural')
if not subroutines:
return None
subroutines.sort()
completions = [[sub, sub] for sub in subroutines]
return (completions, sublime.INHIBIT_WORD_COMPLETIONS)
class AddRulerToColumn72Listener(sublime_plugin.EventListener):
"""Add a ruler to column 72 when a Natural file is opened. If the user has
other rulers, they're not messed with."""
def on_load(self, view):
if not util.is_natural_file(view):
return
rulers = view.settings().get('rulers')
if 72 not in rulers:
rulers.append(72)
rulers.sort()
view.settings().set('rulers', rulers)
|
5a2f848badcdf9bf968e23cfb55f53eb023d18a4 | tests/helper.py | tests/helper.py | import unittest
import os
import yaml
from functools import wraps
from cmd import init_db, seed_db
from models import db
from scuevals_api import create_app
class TestCase(unittest.TestCase):
def setUp(self):
app = create_app()
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['TEST_DATABASE_URL']
app.testing = True
self.appx = app
self.app = app.test_client()
with app.app_context():
init_db(app, db)
seed_db(db)
def tearDown(self):
with self.appx.app_context():
db.session.remove()
db.drop_all()
def use_data(file):
def use_data_decorator(f):
@wraps(f)
def wrapper(*args):
with open(os.path.join('fixtures/data', file), 'r') as stream:
data = yaml.load(stream)
args = args + (data, )
return f(*args)
return wrapper
return use_data_decorator
| import unittest
import os
import yaml
from functools import wraps
from flask_jwt_simple import create_jwt
from cmd import init_db, seed_db
from models import db, Student
from scuevals_api import create_app
class TestCase(unittest.TestCase):
def setUp(self):
app = create_app()
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['TEST_DATABASE_URL']
app.testing = True
self.appx = app
self.app = app.test_client()
student = Student(
id=0,
email='jdoe@scu.edu',
first_name='John',
last_name='Doe',
university_id=1
)
ident = {
'id': student.id,
'email': student.email,
'first_name': student.first_name,
'last_name': student.last_name
}
with app.app_context():
db.drop_all()
init_db(app, db)
seed_db(db)
db.session.add(student)
db.session.commit()
self.jwt = create_jwt(identity=ident)
def tearDown(self):
with self.appx.app_context():
db.session.remove()
db.drop_all()
def use_data(file):
def use_data_decorator(f):
@wraps(f)
def wrapper(*args):
with open(os.path.join('fixtures/data', file), 'r') as stream:
data = yaml.load(stream)
args = args + (data, )
return f(*args)
return wrapper
return use_data_decorator
| Add authentication to base TestCase | Add authentication to base TestCase
| Python | agpl-3.0 | SCUEvals/scuevals-api,SCUEvals/scuevals-api | import unittest
import os
import yaml
from functools import wraps
+ from flask_jwt_simple import create_jwt
from cmd import init_db, seed_db
- from models import db
+ from models import db, Student
from scuevals_api import create_app
class TestCase(unittest.TestCase):
def setUp(self):
app = create_app()
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['TEST_DATABASE_URL']
app.testing = True
self.appx = app
self.app = app.test_client()
+ student = Student(
+ id=0,
+ email='jdoe@scu.edu',
+ first_name='John',
+ last_name='Doe',
+ university_id=1
+ )
+
+ ident = {
+ 'id': student.id,
+ 'email': student.email,
+ 'first_name': student.first_name,
+ 'last_name': student.last_name
+ }
+
with app.app_context():
+ db.drop_all()
init_db(app, db)
seed_db(db)
+
+ db.session.add(student)
+ db.session.commit()
+
+ self.jwt = create_jwt(identity=ident)
def tearDown(self):
with self.appx.app_context():
db.session.remove()
db.drop_all()
def use_data(file):
def use_data_decorator(f):
@wraps(f)
def wrapper(*args):
with open(os.path.join('fixtures/data', file), 'r') as stream:
data = yaml.load(stream)
args = args + (data, )
return f(*args)
return wrapper
return use_data_decorator
| Add authentication to base TestCase | ## Code Before:
import unittest
import os
import yaml
from functools import wraps
from cmd import init_db, seed_db
from models import db
from scuevals_api import create_app
class TestCase(unittest.TestCase):
def setUp(self):
app = create_app()
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['TEST_DATABASE_URL']
app.testing = True
self.appx = app
self.app = app.test_client()
with app.app_context():
init_db(app, db)
seed_db(db)
def tearDown(self):
with self.appx.app_context():
db.session.remove()
db.drop_all()
def use_data(file):
def use_data_decorator(f):
@wraps(f)
def wrapper(*args):
with open(os.path.join('fixtures/data', file), 'r') as stream:
data = yaml.load(stream)
args = args + (data, )
return f(*args)
return wrapper
return use_data_decorator
## Instruction:
Add authentication to base TestCase
## Code After:
import unittest
import os
import yaml
from functools import wraps
from flask_jwt_simple import create_jwt
from cmd import init_db, seed_db
from models import db, Student
from scuevals_api import create_app
class TestCase(unittest.TestCase):
def setUp(self):
app = create_app()
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['TEST_DATABASE_URL']
app.testing = True
self.appx = app
self.app = app.test_client()
student = Student(
id=0,
email='jdoe@scu.edu',
first_name='John',
last_name='Doe',
university_id=1
)
ident = {
'id': student.id,
'email': student.email,
'first_name': student.first_name,
'last_name': student.last_name
}
with app.app_context():
db.drop_all()
init_db(app, db)
seed_db(db)
db.session.add(student)
db.session.commit()
self.jwt = create_jwt(identity=ident)
def tearDown(self):
with self.appx.app_context():
db.session.remove()
db.drop_all()
def use_data(file):
def use_data_decorator(f):
@wraps(f)
def wrapper(*args):
with open(os.path.join('fixtures/data', file), 'r') as stream:
data = yaml.load(stream)
args = args + (data, )
return f(*args)
return wrapper
return use_data_decorator
|
811421407379dedc217795000f6f2cbe54510f96 | kolibri/core/utils/urls.py | kolibri/core/utils/urls.py | from django.urls import reverse
from six.moves.urllib.parse import urljoin
from kolibri.utils.conf import OPTIONS
def reverse_remote(
baseurl, viewname, urlconf=None, args=None, kwargs=None, current_app=None
):
# Get the reversed URL
reversed_url = reverse(
viewname, urlconf=urlconf, args=args, kwargs=kwargs, current_app=current_app
)
# Remove any configured URL prefix from the URL that is specific to this deployment
reversed_url = reversed_url.replace(OPTIONS["Deployment"]["URL_PATH_PREFIX"], "")
# Join the URL to baseurl, but remove any leading "/" to ensure that if there is a path prefix on baseurl
# it doesn't get ignored by the urljoin (which it would if the reversed_url had a leading '/',
# as it would be read as an absolute path)
return urljoin(baseurl, reversed_url.lstrip("/"))
| from django.urls import reverse
from six.moves.urllib.parse import urljoin
from kolibri.utils.conf import OPTIONS
def reverse_remote(
baseurl, viewname, urlconf=None, args=None, kwargs=None, current_app=None
):
# Get the reversed URL
reversed_url = reverse(
viewname, urlconf=urlconf, args=args, kwargs=kwargs, current_app=current_app
)
# Remove any configured URL prefix from the URL that is specific to this deployment
prefix_length = len(OPTIONS["Deployment"]["URL_PATH_PREFIX"])
reversed_url = reversed_url[prefix_length:]
# Join the URL to baseurl, but remove any leading "/" to ensure that if there is a path prefix on baseurl
# it doesn't get ignored by the urljoin (which it would if the reversed_url had a leading '/',
# as it would be read as an absolute path)
return urljoin(baseurl, reversed_url.lstrip("/"))
| Truncate rather than replace to prevent erroneous substitutions. | Truncate rather than replace to prevent erroneous substitutions.
| Python | mit | learningequality/kolibri,learningequality/kolibri,learningequality/kolibri,learningequality/kolibri | from django.urls import reverse
from six.moves.urllib.parse import urljoin
from kolibri.utils.conf import OPTIONS
def reverse_remote(
baseurl, viewname, urlconf=None, args=None, kwargs=None, current_app=None
):
# Get the reversed URL
reversed_url = reverse(
viewname, urlconf=urlconf, args=args, kwargs=kwargs, current_app=current_app
)
# Remove any configured URL prefix from the URL that is specific to this deployment
- reversed_url = reversed_url.replace(OPTIONS["Deployment"]["URL_PATH_PREFIX"], "")
+ prefix_length = len(OPTIONS["Deployment"]["URL_PATH_PREFIX"])
+ reversed_url = reversed_url[prefix_length:]
# Join the URL to baseurl, but remove any leading "/" to ensure that if there is a path prefix on baseurl
# it doesn't get ignored by the urljoin (which it would if the reversed_url had a leading '/',
# as it would be read as an absolute path)
return urljoin(baseurl, reversed_url.lstrip("/"))
| Truncate rather than replace to prevent erroneous substitutions. | ## Code Before:
from django.urls import reverse
from six.moves.urllib.parse import urljoin
from kolibri.utils.conf import OPTIONS
def reverse_remote(
baseurl, viewname, urlconf=None, args=None, kwargs=None, current_app=None
):
# Get the reversed URL
reversed_url = reverse(
viewname, urlconf=urlconf, args=args, kwargs=kwargs, current_app=current_app
)
# Remove any configured URL prefix from the URL that is specific to this deployment
reversed_url = reversed_url.replace(OPTIONS["Deployment"]["URL_PATH_PREFIX"], "")
# Join the URL to baseurl, but remove any leading "/" to ensure that if there is a path prefix on baseurl
# it doesn't get ignored by the urljoin (which it would if the reversed_url had a leading '/',
# as it would be read as an absolute path)
return urljoin(baseurl, reversed_url.lstrip("/"))
## Instruction:
Truncate rather than replace to prevent erroneous substitutions.
## Code After:
from django.urls import reverse
from six.moves.urllib.parse import urljoin
from kolibri.utils.conf import OPTIONS
def reverse_remote(
baseurl, viewname, urlconf=None, args=None, kwargs=None, current_app=None
):
# Get the reversed URL
reversed_url = reverse(
viewname, urlconf=urlconf, args=args, kwargs=kwargs, current_app=current_app
)
# Remove any configured URL prefix from the URL that is specific to this deployment
prefix_length = len(OPTIONS["Deployment"]["URL_PATH_PREFIX"])
reversed_url = reversed_url[prefix_length:]
# Join the URL to baseurl, but remove any leading "/" to ensure that if there is a path prefix on baseurl
# it doesn't get ignored by the urljoin (which it would if the reversed_url had a leading '/',
# as it would be read as an absolute path)
return urljoin(baseurl, reversed_url.lstrip("/"))
|
741133b4fa502fc585c771abef96b6213d3f5214 | pyheufybot/modules/nickservidentify.py | pyheufybot/modules/nickservidentify.py | from module_interface import Module, ModuleType
from message import IRCResponse, ResponseType
from pyheufybot import globalvars
class NickServIdentify(Module):
def __init__(self):
self.moduleType = ModuleType.PASSIVE
self.messageTypes = ["USER"]
self.helpText = "Attempts to log into NickServ with the password in the config"
def execute(self, message, serverInfo):
config = globalvars.botHandler.factories[serverInfo.name].config
passwordType = config.getSettingWithDefault("passwordType", None)
password = config.getSettingWithDefault("password", "")
if passwordType == "NickServ":
return [ IRCResponse("NickServ", password, responseType.MESSAGE) ]
else:
return []
| from pyheufybot.module_interface import Module, ModuleType
from pyheufybot.message import IRCResponse, ResponseType
from pyheufybot import globalvars
class NickServIdentify(Module):
def __init__(self):
self.moduleType = ModuleType.PASSIVE
self.messageTypes = ["USER"]
self.helpText = "Attempts to log into NickServ with the password in the config"
def execute(self, message, serverInfo):
config = globalvars.botHandler.factories[serverInfo.name].config
passwordType = config.getSettingWithDefault("passwordType", None)
password = config.getSettingWithDefault("password", "")
if passwordType == "NickServ":
return [ IRCResponse("NickServ", "IDENTIFY " + password, responseType.MESSAGE) ]
else:
return []
| Fix the syntax for NickServ logins | Fix the syntax for NickServ logins
| Python | mit | Heufneutje/PyHeufyBot,Heufneutje/PyHeufyBot | - from module_interface import Module, ModuleType
+ from pyheufybot.module_interface import Module, ModuleType
- from message import IRCResponse, ResponseType
+ from pyheufybot.message import IRCResponse, ResponseType
from pyheufybot import globalvars
class NickServIdentify(Module):
def __init__(self):
self.moduleType = ModuleType.PASSIVE
self.messageTypes = ["USER"]
self.helpText = "Attempts to log into NickServ with the password in the config"
def execute(self, message, serverInfo):
config = globalvars.botHandler.factories[serverInfo.name].config
passwordType = config.getSettingWithDefault("passwordType", None)
password = config.getSettingWithDefault("password", "")
if passwordType == "NickServ":
- return [ IRCResponse("NickServ", password, responseType.MESSAGE) ]
+ return [ IRCResponse("NickServ", "IDENTIFY " + password, responseType.MESSAGE) ]
else:
return []
| Fix the syntax for NickServ logins | ## Code Before:
from module_interface import Module, ModuleType
from message import IRCResponse, ResponseType
from pyheufybot import globalvars
class NickServIdentify(Module):
def __init__(self):
self.moduleType = ModuleType.PASSIVE
self.messageTypes = ["USER"]
self.helpText = "Attempts to log into NickServ with the password in the config"
def execute(self, message, serverInfo):
config = globalvars.botHandler.factories[serverInfo.name].config
passwordType = config.getSettingWithDefault("passwordType", None)
password = config.getSettingWithDefault("password", "")
if passwordType == "NickServ":
return [ IRCResponse("NickServ", password, responseType.MESSAGE) ]
else:
return []
## Instruction:
Fix the syntax for NickServ logins
## Code After:
from pyheufybot.module_interface import Module, ModuleType
from pyheufybot.message import IRCResponse, ResponseType
from pyheufybot import globalvars
class NickServIdentify(Module):
def __init__(self):
self.moduleType = ModuleType.PASSIVE
self.messageTypes = ["USER"]
self.helpText = "Attempts to log into NickServ with the password in the config"
def execute(self, message, serverInfo):
config = globalvars.botHandler.factories[serverInfo.name].config
passwordType = config.getSettingWithDefault("passwordType", None)
password = config.getSettingWithDefault("password", "")
if passwordType == "NickServ":
return [ IRCResponse("NickServ", "IDENTIFY " + password, responseType.MESSAGE) ]
else:
return []
|
34bd55b33e865c65386f934c7ac0b89f3cc76485 | edgedb/lang/common/shell/reqs.py | edgedb/lang/common/shell/reqs.py |
from metamagic import app
from metamagic.exceptions import MetamagicError
class UnsatisfiedRequirementError(MetamagicError):
pass
class CommandRequirement:
pass
class ValidApplication(CommandRequirement):
def __init__(self, args):
if not app.Application.active:
raise UnsatisfiedRequirementError('need active Application')
|
from metamagic.exceptions import MetamagicError
class UnsatisfiedRequirementError(MetamagicError):
pass
class CommandRequirement:
pass
| Drop 'metamagic.app' package. Long live Node. | app: Drop 'metamagic.app' package. Long live Node.
| Python | apache-2.0 | edgedb/edgedb,edgedb/edgedb,edgedb/edgedb |
- from metamagic import app
from metamagic.exceptions import MetamagicError
class UnsatisfiedRequirementError(MetamagicError):
pass
class CommandRequirement:
pass
-
- class ValidApplication(CommandRequirement):
- def __init__(self, args):
- if not app.Application.active:
- raise UnsatisfiedRequirementError('need active Application')
- | Drop 'metamagic.app' package. Long live Node. | ## Code Before:
from metamagic import app
from metamagic.exceptions import MetamagicError
class UnsatisfiedRequirementError(MetamagicError):
pass
class CommandRequirement:
pass
class ValidApplication(CommandRequirement):
def __init__(self, args):
if not app.Application.active:
raise UnsatisfiedRequirementError('need active Application')
## Instruction:
Drop 'metamagic.app' package. Long live Node.
## Code After:
from metamagic.exceptions import MetamagicError
class UnsatisfiedRequirementError(MetamagicError):
pass
class CommandRequirement:
pass
|
63a7b11d3ae51a944bf2e70637dea503e455c2f5 | fontdump/cli.py | fontdump/cli.py | from collections import OrderedDict
import requests
import cssutils
USER_AGENTS = OrderedDict()
USER_AGENTS['woff'] = 'Mozilla/5.0 AppleWebKit/537.36 Chrome/30', # Chrome
USER_AGENTS['ttf'] = 'Mozilla/5.0 (Linux; U; Android 2.1-update1;)', #Andord 2
USER_AGENTS['eot'] = 'Mozilla/4.0 (compatible; MSIE 6.0;)', # IE6
USER_AGENTS['woff'] = 'Mozilla/4.0 (iPad; CPU OS 4_0_1 ) AppleWebKit', #iOS<4.2
def main():
font_url = 'http://fonts.googleapis.com/css?family=Open+Sans:300,400,700,800|Dosis:300,400'
sheets={}
for (format, ua) in USER_AGENTS.items():
headers = {
'User-Agent': ua,
}
r =requests.get(font_url, headers=headers)
sheets[format] = cssutils.parseString(r.content)
if __name__ == '__main__':
main() | import requests
import cssutils
USER_AGENTS = {
'woff': 'Mozilla/5.0 AppleWebKit/537.36 Chrome/30', # Chrome
'eot': 'Mozilla/4.0 (compatible; MSIE 6.0;)', # IE6
'ttf': 'Mozilla/5.0 (Linux; U; Android 2.1-update1;)', #Andord 2
'svg': 'Mozilla/4.0 (iPad; CPU OS 4_0_1 ) AppleWebKit', #iOS<4.2
}
def main():
font_url = 'http://fonts.googleapis.com/css?family=Open+Sans:300,400,700,800|Dosis:300,400'
sheets={}
for (format, ua) in USER_AGENTS.items():
headers = {
'User-Agent': ua,
}
r =requests.get(font_url, headers=headers)
sheets[format] = cssutils.parseString(r.content)
if __name__ == '__main__':
main() | Revert "The order of the formats matters. Use OrderedDict instead of dict" | Revert "The order of the formats matters. Use OrderedDict instead of dict"
I can't rely on the order of dict. The control flow is more complex.
This reverts commit 3389ed71971ddacd185bbbf8fe667a8651108c70.
| Python | mit | glasslion/fontdump | - from collections import OrderedDict
-
import requests
import cssutils
- USER_AGENTS = OrderedDict()
+ USER_AGENTS = {
- USER_AGENTS['woff'] = 'Mozilla/5.0 AppleWebKit/537.36 Chrome/30', # Chrome
+ 'woff': 'Mozilla/5.0 AppleWebKit/537.36 Chrome/30', # Chrome
+ 'eot': 'Mozilla/4.0 (compatible; MSIE 6.0;)', # IE6
- USER_AGENTS['ttf'] = 'Mozilla/5.0 (Linux; U; Android 2.1-update1;)', #Andord 2
+ 'ttf': 'Mozilla/5.0 (Linux; U; Android 2.1-update1;)', #Andord 2
- USER_AGENTS['eot'] = 'Mozilla/4.0 (compatible; MSIE 6.0;)', # IE6
- USER_AGENTS['woff'] = 'Mozilla/4.0 (iPad; CPU OS 4_0_1 ) AppleWebKit', #iOS<4.2
+ 'svg': 'Mozilla/4.0 (iPad; CPU OS 4_0_1 ) AppleWebKit', #iOS<4.2
-
+ }
def main():
font_url = 'http://fonts.googleapis.com/css?family=Open+Sans:300,400,700,800|Dosis:300,400'
sheets={}
for (format, ua) in USER_AGENTS.items():
headers = {
'User-Agent': ua,
}
r =requests.get(font_url, headers=headers)
sheets[format] = cssutils.parseString(r.content)
if __name__ == '__main__':
main() | Revert "The order of the formats matters. Use OrderedDict instead of dict" | ## Code Before:
from collections import OrderedDict
import requests
import cssutils
USER_AGENTS = OrderedDict()
USER_AGENTS['woff'] = 'Mozilla/5.0 AppleWebKit/537.36 Chrome/30', # Chrome
USER_AGENTS['ttf'] = 'Mozilla/5.0 (Linux; U; Android 2.1-update1;)', #Andord 2
USER_AGENTS['eot'] = 'Mozilla/4.0 (compatible; MSIE 6.0;)', # IE6
USER_AGENTS['woff'] = 'Mozilla/4.0 (iPad; CPU OS 4_0_1 ) AppleWebKit', #iOS<4.2
def main():
font_url = 'http://fonts.googleapis.com/css?family=Open+Sans:300,400,700,800|Dosis:300,400'
sheets={}
for (format, ua) in USER_AGENTS.items():
headers = {
'User-Agent': ua,
}
r =requests.get(font_url, headers=headers)
sheets[format] = cssutils.parseString(r.content)
if __name__ == '__main__':
main()
## Instruction:
Revert "The order of the formats matters. Use OrderedDict instead of dict"
## Code After:
import requests
import cssutils
USER_AGENTS = {
'woff': 'Mozilla/5.0 AppleWebKit/537.36 Chrome/30', # Chrome
'eot': 'Mozilla/4.0 (compatible; MSIE 6.0;)', # IE6
'ttf': 'Mozilla/5.0 (Linux; U; Android 2.1-update1;)', #Andord 2
'svg': 'Mozilla/4.0 (iPad; CPU OS 4_0_1 ) AppleWebKit', #iOS<4.2
}
def main():
font_url = 'http://fonts.googleapis.com/css?family=Open+Sans:300,400,700,800|Dosis:300,400'
sheets={}
for (format, ua) in USER_AGENTS.items():
headers = {
'User-Agent': ua,
}
r =requests.get(font_url, headers=headers)
sheets[format] = cssutils.parseString(r.content)
if __name__ == '__main__':
main() |
62f9608d50898d0a82e013d54454ed1edb004cff | fab_deploy/joyent/setup.py | fab_deploy/joyent/setup.py | from fabric.api import run, sudo
from fabric.contrib.files import append
from fab_deploy.base import setup as base_setup
class JoyentMixin(object):
def _set_profile(self):
append('/etc/profile', 'CC="gcc -m64"; export CC', use_sudo=True)
append('/etc/profile', 'LDSHARED="gcc -m64 -G"; export LDSHARED', use_sudo=True)
def _ssh_restart(self):
run('svcadm restart ssh')
class AppMixin(JoyentMixin):
packages = ['python27', 'py27-psycopg2', 'py27-setuptools',
'py27-imaging', 'py27-expat']
def _install_packages(self):
for package in self.packages:
sudo('pkg_add %s' % package)
sudo('easy_install-2.7 pip')
self._install_venv()
class LBSetup(JoyentMixin, base_setup.LBSetup):
pass
class AppSetup(AppMixin, base_setup.AppSetup):
pass
class DBSetup(JoyentMixin, base_setup.DBSetup):
pass
class SlaveSetup(JoyentMixin, base_setup.SlaveSetup):
pass
class DevSetup(AppMixin, base_setup.DevSetup):
pass
app_server = AppSetup()
lb_server = LBSetup()
dev_server = DevSetup()
db_server = DBSetup()
slave_db = SlaveSetup()
| from fabric.api import run, sudo
from fabric.contrib.files import append
from fab_deploy.base import setup as base_setup
class JoyentMixin(object):
def _set_profile(self):
append('/etc/profile', 'CC="gcc -m64"; export CC', use_sudo=True)
append('/etc/profile', 'LDSHARED="gcc -m64 -G"; export LDSHARED', use_sudo=True)
def _ssh_restart(self):
run('svcadm restart ssh')
class AppMixin(JoyentMixin):
packages = ['python27', 'py27-psycopg2', 'py27-setuptools',
'py27-imaging', 'py27-expat']
def _set_profile(self):
JoyentMixin._set_profile(self)
base_setup.AppSetup._set_profile(self)
def _install_packages(self):
for package in self.packages:
sudo('pkg_add %s' % package)
sudo('easy_install-2.7 pip')
self._install_venv()
class LBSetup(JoyentMixin, base_setup.LBSetup):
pass
class AppSetup(AppMixin, base_setup.AppSetup):
pass
class DBSetup(JoyentMixin, base_setup.DBSetup):
pass
class SlaveSetup(JoyentMixin, base_setup.SlaveSetup):
pass
class DevSetup(AppMixin, base_setup.DevSetup):
pass
app_server = AppSetup()
lb_server = LBSetup()
dev_server = DevSetup()
db_server = DBSetup()
slave_db = SlaveSetup()
| Add environ vars for joyent | Add environ vars for joyent | Python | mit | ff0000/red-fab-deploy2,ff0000/red-fab-deploy2,ff0000/red-fab-deploy2 | from fabric.api import run, sudo
from fabric.contrib.files import append
from fab_deploy.base import setup as base_setup
class JoyentMixin(object):
def _set_profile(self):
append('/etc/profile', 'CC="gcc -m64"; export CC', use_sudo=True)
append('/etc/profile', 'LDSHARED="gcc -m64 -G"; export LDSHARED', use_sudo=True)
def _ssh_restart(self):
run('svcadm restart ssh')
class AppMixin(JoyentMixin):
packages = ['python27', 'py27-psycopg2', 'py27-setuptools',
'py27-imaging', 'py27-expat']
+
+ def _set_profile(self):
+ JoyentMixin._set_profile(self)
+ base_setup.AppSetup._set_profile(self)
def _install_packages(self):
for package in self.packages:
sudo('pkg_add %s' % package)
sudo('easy_install-2.7 pip')
self._install_venv()
class LBSetup(JoyentMixin, base_setup.LBSetup):
pass
class AppSetup(AppMixin, base_setup.AppSetup):
pass
class DBSetup(JoyentMixin, base_setup.DBSetup):
pass
class SlaveSetup(JoyentMixin, base_setup.SlaveSetup):
pass
class DevSetup(AppMixin, base_setup.DevSetup):
pass
app_server = AppSetup()
lb_server = LBSetup()
dev_server = DevSetup()
db_server = DBSetup()
slave_db = SlaveSetup()
| Add environ vars for joyent | ## Code Before:
from fabric.api import run, sudo
from fabric.contrib.files import append
from fab_deploy.base import setup as base_setup
class JoyentMixin(object):
def _set_profile(self):
append('/etc/profile', 'CC="gcc -m64"; export CC', use_sudo=True)
append('/etc/profile', 'LDSHARED="gcc -m64 -G"; export LDSHARED', use_sudo=True)
def _ssh_restart(self):
run('svcadm restart ssh')
class AppMixin(JoyentMixin):
packages = ['python27', 'py27-psycopg2', 'py27-setuptools',
'py27-imaging', 'py27-expat']
def _install_packages(self):
for package in self.packages:
sudo('pkg_add %s' % package)
sudo('easy_install-2.7 pip')
self._install_venv()
class LBSetup(JoyentMixin, base_setup.LBSetup):
pass
class AppSetup(AppMixin, base_setup.AppSetup):
pass
class DBSetup(JoyentMixin, base_setup.DBSetup):
pass
class SlaveSetup(JoyentMixin, base_setup.SlaveSetup):
pass
class DevSetup(AppMixin, base_setup.DevSetup):
pass
app_server = AppSetup()
lb_server = LBSetup()
dev_server = DevSetup()
db_server = DBSetup()
slave_db = SlaveSetup()
## Instruction:
Add environ vars for joyent
## Code After:
from fabric.api import run, sudo
from fabric.contrib.files import append
from fab_deploy.base import setup as base_setup
class JoyentMixin(object):
def _set_profile(self):
append('/etc/profile', 'CC="gcc -m64"; export CC', use_sudo=True)
append('/etc/profile', 'LDSHARED="gcc -m64 -G"; export LDSHARED', use_sudo=True)
def _ssh_restart(self):
run('svcadm restart ssh')
class AppMixin(JoyentMixin):
packages = ['python27', 'py27-psycopg2', 'py27-setuptools',
'py27-imaging', 'py27-expat']
def _set_profile(self):
JoyentMixin._set_profile(self)
base_setup.AppSetup._set_profile(self)
def _install_packages(self):
for package in self.packages:
sudo('pkg_add %s' % package)
sudo('easy_install-2.7 pip')
self._install_venv()
class LBSetup(JoyentMixin, base_setup.LBSetup):
pass
class AppSetup(AppMixin, base_setup.AppSetup):
pass
class DBSetup(JoyentMixin, base_setup.DBSetup):
pass
class SlaveSetup(JoyentMixin, base_setup.SlaveSetup):
pass
class DevSetup(AppMixin, base_setup.DevSetup):
pass
app_server = AppSetup()
lb_server = LBSetup()
dev_server = DevSetup()
db_server = DBSetup()
slave_db = SlaveSetup()
|
91d104a25db499ccef54878dcbfce42dbb4aa932 | taskin/task.py | taskin/task.py | import abc
def do_flow(flow, result=None):
for item in flow:
print(item, result)
result = item(result)
return result
class MapTask(object):
def __init__(self, args, task):
self.args = args
self.task = task
self.pool = Pool(cpu_count())
def iter_input(self, input):
for args in self.args:
if not isinstance(args, (tuple, list)):
args = [args]
yield tuple([input] + args)
def __call__(self, input):
return self.pool.map(self.task, self.iter_input(input))
class IfTask(object):
def __init__(self, check, a, b):
self.check = check
self.a = a
self.b = b
def __call__(self, input):
if check(input):
return do_flow(self.a, input)
return do_flow(self.b, input)
| from multiprocessing import Pool as ProcessPool
from multiprocessing.dummy import Pool as ThreadPool
from multiprocessing import cpu_count
def do_flow(flow, result=None):
for item in flow:
print(item, result)
result = item(result)
return result
class PoolAPI(object):
def map(self, *args, **kw):
return self.pool.map(*args, **kw)
class ThreadPool(PoolAPI):
def __init__(self, size=20):
self.size = size
self.pool = ThreadPool(self.size)
class ProcessPool(PoolAPI):
def __init__(self, size=None):
self.size = size or cpu_count()
self.pool = ProcessPool(self.size)
class MapTask(object):
pool_types = [
'thread', 'process'
]
def __init__(self, args, task, pool):
self.args = args
self.task = task
self.pool = pool
def iter_input(self, input):
for args in self.args:
if not isinstance(args, (tuple, list)):
args = [args]
yield tuple([input] + args)
def __call__(self, input):
return self.pool.map(self.task, self.iter_input(input))
class IfTask(object):
def __init__(self, check, a, b):
self.check = check
self.a = a
self.b = b
def __call__(self, input):
if check(input):
return do_flow(self.a, input)
return do_flow(self.b, input)
| Add totally untested pools ;) | Add totally untested pools ;)
| Python | bsd-3-clause | ionrock/taskin | - import abc
+ from multiprocessing import Pool as ProcessPool
+ from multiprocessing.dummy import Pool as ThreadPool
+ from multiprocessing import cpu_count
def do_flow(flow, result=None):
for item in flow:
print(item, result)
result = item(result)
return result
+ class PoolAPI(object):
+ def map(self, *args, **kw):
+ return self.pool.map(*args, **kw)
+
+
+ class ThreadPool(PoolAPI):
+
+ def __init__(self, size=20):
+ self.size = size
+ self.pool = ThreadPool(self.size)
+
+
+ class ProcessPool(PoolAPI):
+
+ def __init__(self, size=None):
+ self.size = size or cpu_count()
+ self.pool = ProcessPool(self.size)
+
+
class MapTask(object):
+ pool_types = [
+ 'thread', 'process'
+ ]
+
- def __init__(self, args, task):
+ def __init__(self, args, task, pool):
self.args = args
self.task = task
- self.pool = Pool(cpu_count())
+ self.pool = pool
def iter_input(self, input):
for args in self.args:
if not isinstance(args, (tuple, list)):
args = [args]
yield tuple([input] + args)
-
def __call__(self, input):
return self.pool.map(self.task, self.iter_input(input))
class IfTask(object):
def __init__(self, check, a, b):
self.check = check
self.a = a
self.b = b
def __call__(self, input):
if check(input):
return do_flow(self.a, input)
return do_flow(self.b, input)
| Add totally untested pools ;) | ## Code Before:
import abc
def do_flow(flow, result=None):
for item in flow:
print(item, result)
result = item(result)
return result
class MapTask(object):
def __init__(self, args, task):
self.args = args
self.task = task
self.pool = Pool(cpu_count())
def iter_input(self, input):
for args in self.args:
if not isinstance(args, (tuple, list)):
args = [args]
yield tuple([input] + args)
def __call__(self, input):
return self.pool.map(self.task, self.iter_input(input))
class IfTask(object):
def __init__(self, check, a, b):
self.check = check
self.a = a
self.b = b
def __call__(self, input):
if check(input):
return do_flow(self.a, input)
return do_flow(self.b, input)
## Instruction:
Add totally untested pools ;)
## Code After:
from multiprocessing import Pool as ProcessPool
from multiprocessing.dummy import Pool as ThreadPool
from multiprocessing import cpu_count
def do_flow(flow, result=None):
for item in flow:
print(item, result)
result = item(result)
return result
class PoolAPI(object):
def map(self, *args, **kw):
return self.pool.map(*args, **kw)
class ThreadPool(PoolAPI):
def __init__(self, size=20):
self.size = size
self.pool = ThreadPool(self.size)
class ProcessPool(PoolAPI):
def __init__(self, size=None):
self.size = size or cpu_count()
self.pool = ProcessPool(self.size)
class MapTask(object):
pool_types = [
'thread', 'process'
]
def __init__(self, args, task, pool):
self.args = args
self.task = task
self.pool = pool
def iter_input(self, input):
for args in self.args:
if not isinstance(args, (tuple, list)):
args = [args]
yield tuple([input] + args)
def __call__(self, input):
return self.pool.map(self.task, self.iter_input(input))
class IfTask(object):
def __init__(self, check, a, b):
self.check = check
self.a = a
self.b = b
def __call__(self, input):
if check(input):
return do_flow(self.a, input)
return do_flow(self.b, input)
|
247c4dcaf3e1c1f9c069ab8a2fc06cfcd75f8ea9 | UM/Util.py | UM/Util.py | def parseBool(value):
return value in [True, "True", "true", 1]
| def parseBool(value):
return value in [True, "True", "true", "Yes", "yes", 1]
| Add "Yes" as an option for parsing bools | Add "Yes" as an option for parsing bools
CURA-2204
| Python | agpl-3.0 | onitake/Uranium,onitake/Uranium | def parseBool(value):
- return value in [True, "True", "true", 1]
+ return value in [True, "True", "true", "Yes", "yes", 1]
| Add "Yes" as an option for parsing bools | ## Code Before:
def parseBool(value):
return value in [True, "True", "true", 1]
## Instruction:
Add "Yes" as an option for parsing bools
## Code After:
def parseBool(value):
return value in [True, "True", "true", "Yes", "yes", 1]
|
6e3ddfc47487a8841a79d6265c96ba63005fccec | bnw_handlers/command_onoff.py | bnw_handlers/command_onoff.py |
from base import *
import random
import bnw_core.bnw_objects as objs
@require_auth
@defer.inlineCallbacks
def cmd_on(request):
""" Включение доставки сообщений """
_ = yield objs.User.mupdate({'name':request.user['name']},{'$set':{'off':False}},safe=True)
if request.user['off']:
defer.returnValue(
dict(ok=True,desc='Welcome back!')
)
else:
defer.returnValue(
dict(ok=True,desc='Welcoooome baaaack, I said.')
)
@require_auth
@defer.inlineCallbacks
def cmd_off(request):
""" Выключение доставки сообщений """
_ = yield objs.User.mupdate({'name':request.user['name']},{'$set':{'off':True}},safe=True)
if request.user['off']:
defer.returnValue(
dict(ok=True,desc='See you later.')
)
else:
defer.returnValue(
dict(ok=True,desc='C u l8r!')
)
|
from base import *
import random
import bnw_core.bnw_objects as objs
@require_auth
@defer.inlineCallbacks
def cmd_on(request):
""" Включение доставки сообщений """
_ = yield objs.User.mupdate({'name':request.user['name']},{'$set':{'off':False}},safe=True)
if request.user.get('off',False):
defer.returnValue(
dict(ok=True,desc='Welcome back!')
)
else:
defer.returnValue(
dict(ok=True,desc='Welcoooome baaaack, I said.')
)
@require_auth
@defer.inlineCallbacks
def cmd_off(request):
""" Выключение доставки сообщений """
_ = yield objs.User.mupdate({'name':request.user['name']},{'$set':{'off':True}},safe=True)
if request.user.get('off',False):
defer.returnValue(
dict(ok=True,desc='See you later.')
)
else:
defer.returnValue(
dict(ok=True,desc='C u l8r!')
)
| Fix on/off if there is no 'off' field. | Fix on/off if there is no 'off' field.
| Python | bsd-2-clause | un-def/bnw,stiletto/bnw,un-def/bnw,stiletto/bnw,ojab/bnw,ojab/bnw,stiletto/bnw,un-def/bnw,ojab/bnw,stiletto/bnw,un-def/bnw,ojab/bnw |
from base import *
import random
import bnw_core.bnw_objects as objs
@require_auth
@defer.inlineCallbacks
def cmd_on(request):
""" Включение доставки сообщений """
_ = yield objs.User.mupdate({'name':request.user['name']},{'$set':{'off':False}},safe=True)
- if request.user['off']:
+ if request.user.get('off',False):
defer.returnValue(
dict(ok=True,desc='Welcome back!')
)
else:
defer.returnValue(
dict(ok=True,desc='Welcoooome baaaack, I said.')
)
@require_auth
@defer.inlineCallbacks
def cmd_off(request):
""" Выключение доставки сообщений """
_ = yield objs.User.mupdate({'name':request.user['name']},{'$set':{'off':True}},safe=True)
- if request.user['off']:
+ if request.user.get('off',False):
defer.returnValue(
dict(ok=True,desc='See you later.')
)
else:
defer.returnValue(
dict(ok=True,desc='C u l8r!')
)
| Fix on/off if there is no 'off' field. | ## Code Before:
from base import *
import random
import bnw_core.bnw_objects as objs
@require_auth
@defer.inlineCallbacks
def cmd_on(request):
""" Включение доставки сообщений """
_ = yield objs.User.mupdate({'name':request.user['name']},{'$set':{'off':False}},safe=True)
if request.user['off']:
defer.returnValue(
dict(ok=True,desc='Welcome back!')
)
else:
defer.returnValue(
dict(ok=True,desc='Welcoooome baaaack, I said.')
)
@require_auth
@defer.inlineCallbacks
def cmd_off(request):
""" Выключение доставки сообщений """
_ = yield objs.User.mupdate({'name':request.user['name']},{'$set':{'off':True}},safe=True)
if request.user['off']:
defer.returnValue(
dict(ok=True,desc='See you later.')
)
else:
defer.returnValue(
dict(ok=True,desc='C u l8r!')
)
## Instruction:
Fix on/off if there is no 'off' field.
## Code After:
from base import *
import random
import bnw_core.bnw_objects as objs
@require_auth
@defer.inlineCallbacks
def cmd_on(request):
""" Включение доставки сообщений """
_ = yield objs.User.mupdate({'name':request.user['name']},{'$set':{'off':False}},safe=True)
if request.user.get('off',False):
defer.returnValue(
dict(ok=True,desc='Welcome back!')
)
else:
defer.returnValue(
dict(ok=True,desc='Welcoooome baaaack, I said.')
)
@require_auth
@defer.inlineCallbacks
def cmd_off(request):
""" Выключение доставки сообщений """
_ = yield objs.User.mupdate({'name':request.user['name']},{'$set':{'off':True}},safe=True)
if request.user.get('off',False):
defer.returnValue(
dict(ok=True,desc='See you later.')
)
else:
defer.returnValue(
dict(ok=True,desc='C u l8r!')
)
|
82e82805eae5b070aec49816977d2f50ff274d30 | controllers/api/api_match_controller.py | controllers/api/api_match_controller.py | import json
import webapp2
from controllers.api.api_base_controller import ApiBaseController
from helpers.model_to_dict import ModelToDict
from models.match import Match
class ApiMatchControllerBase(ApiBaseController):
CACHE_KEY_FORMAT = "apiv2_match_controller_{}" # (match_key)
CACHE_VERSION = 2
CACHE_HEADER_LENGTH = 60 * 60
def __init__(self, *args, **kw):
super(ApiMatchControllerBase, self).__init__(*args, **kw)
self.match_key = self.request.route_kwargs["match_key"]
self._partial_cache_key = self.CACHE_KEY_FORMAT.format(self.match_key)
@property
def _validators(self):
return [("match_id_validator", self.match_key)]
def _set_match(self, match_key):
self.match = Match.get_by_id(match_key)
if self.match is None:
self._errors = json.dumps({"404": "%s match not found" % self.match_key})
self.abort(404)
class ApiMatchController(ApiMatchControllerBase):
def _track_call(self, match_key):
self._track_call_defer('match', match_key)
def _render(self, match_key):
self._set_match(match_key)
match_dict = ModelToDict.matchConverter(self.match)
return json.dumps(match_dict, ensure_ascii=True)
| import json
import webapp2
from controllers.api.api_base_controller import ApiBaseController
from helpers.model_to_dict import ModelToDict
from models.match import Match
class ApiMatchControllerBase(ApiBaseController):
def __init__(self, *args, **kw):
super(ApiMatchControllerBase, self).__init__(*args, **kw)
self.match_key = self.request.route_kwargs["match_key"]
@property
def _validators(self):
return [("match_id_validator", self.match_key)]
def _set_match(self, match_key):
self.match = Match.get_by_id(match_key)
if self.match is None:
self._errors = json.dumps({"404": "%s match not found" % self.match_key})
self.abort(404)
class ApiMatchController(ApiMatchControllerBase):
CACHE_KEY_FORMAT = "apiv2_match_controller_{}" # (match_key)
CACHE_VERSION = 2
CACHE_HEADER_LENGTH = 60 * 60
def __init__(self, *args, **kw):
super(ApiMatchController, self).__init__(*args, **kw)
self._partial_cache_key = self.CACHE_KEY_FORMAT.format(self.match_key)
def _track_call(self, match_key):
self._track_call_defer('match', match_key)
def _render(self, match_key):
self._set_match(match_key)
match_dict = ModelToDict.matchConverter(self.match)
return json.dumps(match_dict, ensure_ascii=True)
| Move cache key out of base class | Move cache key out of base class
| Python | mit | josephbisch/the-blue-alliance,bvisness/the-blue-alliance,bdaroz/the-blue-alliance,bvisness/the-blue-alliance,fangeugene/the-blue-alliance,1fish2/the-blue-alliance,phil-lopreiato/the-blue-alliance,synth3tk/the-blue-alliance,jaredhasenklein/the-blue-alliance,tsteward/the-blue-alliance,nwalters512/the-blue-alliance,phil-lopreiato/the-blue-alliance,the-blue-alliance/the-blue-alliance,1fish2/the-blue-alliance,jaredhasenklein/the-blue-alliance,tsteward/the-blue-alliance,verycumbersome/the-blue-alliance,tsteward/the-blue-alliance,jaredhasenklein/the-blue-alliance,jaredhasenklein/the-blue-alliance,the-blue-alliance/the-blue-alliance,phil-lopreiato/the-blue-alliance,bdaroz/the-blue-alliance,bvisness/the-blue-alliance,the-blue-alliance/the-blue-alliance,phil-lopreiato/the-blue-alliance,tsteward/the-blue-alliance,verycumbersome/the-blue-alliance,fangeugene/the-blue-alliance,bdaroz/the-blue-alliance,josephbisch/the-blue-alliance,fangeugene/the-blue-alliance,bdaroz/the-blue-alliance,synth3tk/the-blue-alliance,fangeugene/the-blue-alliance,nwalters512/the-blue-alliance,bvisness/the-blue-alliance,jaredhasenklein/the-blue-alliance,verycumbersome/the-blue-alliance,josephbisch/the-blue-alliance,nwalters512/the-blue-alliance,bvisness/the-blue-alliance,synth3tk/the-blue-alliance,the-blue-alliance/the-blue-alliance,bdaroz/the-blue-alliance,nwalters512/the-blue-alliance,the-blue-alliance/the-blue-alliance,the-blue-alliance/the-blue-alliance,bvisness/the-blue-alliance,tsteward/the-blue-alliance,tsteward/the-blue-alliance,josephbisch/the-blue-alliance,jaredhasenklein/the-blue-alliance,1fish2/the-blue-alliance,1fish2/the-blue-alliance,1fish2/the-blue-alliance,josephbisch/the-blue-alliance,synth3tk/the-blue-alliance,nwalters512/the-blue-alliance,synth3tk/the-blue-alliance,josephbisch/the-blue-alliance,fangeugene/the-blue-alliance,phil-lopreiato/the-blue-alliance,1fish2/the-blue-alliance,verycumbersome/the-blue-alliance,verycumbersome/the-blue-alliance,fangeugene/the-blue-alliance,synth3tk/the-blue-alliance,verycumbersome/the-blue-alliance,nwalters512/the-blue-alliance,phil-lopreiato/the-blue-alliance,bdaroz/the-blue-alliance | import json
import webapp2
from controllers.api.api_base_controller import ApiBaseController
from helpers.model_to_dict import ModelToDict
from models.match import Match
class ApiMatchControllerBase(ApiBaseController):
- CACHE_KEY_FORMAT = "apiv2_match_controller_{}" # (match_key)
- CACHE_VERSION = 2
- CACHE_HEADER_LENGTH = 60 * 60
-
def __init__(self, *args, **kw):
super(ApiMatchControllerBase, self).__init__(*args, **kw)
self.match_key = self.request.route_kwargs["match_key"]
- self._partial_cache_key = self.CACHE_KEY_FORMAT.format(self.match_key)
@property
def _validators(self):
return [("match_id_validator", self.match_key)]
def _set_match(self, match_key):
self.match = Match.get_by_id(match_key)
if self.match is None:
self._errors = json.dumps({"404": "%s match not found" % self.match_key})
self.abort(404)
class ApiMatchController(ApiMatchControllerBase):
+ CACHE_KEY_FORMAT = "apiv2_match_controller_{}" # (match_key)
+ CACHE_VERSION = 2
+ CACHE_HEADER_LENGTH = 60 * 60
+
+ def __init__(self, *args, **kw):
+ super(ApiMatchController, self).__init__(*args, **kw)
+ self._partial_cache_key = self.CACHE_KEY_FORMAT.format(self.match_key)
+
def _track_call(self, match_key):
self._track_call_defer('match', match_key)
def _render(self, match_key):
self._set_match(match_key)
match_dict = ModelToDict.matchConverter(self.match)
return json.dumps(match_dict, ensure_ascii=True)
| Move cache key out of base class | ## Code Before:
import json
import webapp2
from controllers.api.api_base_controller import ApiBaseController
from helpers.model_to_dict import ModelToDict
from models.match import Match
class ApiMatchControllerBase(ApiBaseController):
CACHE_KEY_FORMAT = "apiv2_match_controller_{}" # (match_key)
CACHE_VERSION = 2
CACHE_HEADER_LENGTH = 60 * 60
def __init__(self, *args, **kw):
super(ApiMatchControllerBase, self).__init__(*args, **kw)
self.match_key = self.request.route_kwargs["match_key"]
self._partial_cache_key = self.CACHE_KEY_FORMAT.format(self.match_key)
@property
def _validators(self):
return [("match_id_validator", self.match_key)]
def _set_match(self, match_key):
self.match = Match.get_by_id(match_key)
if self.match is None:
self._errors = json.dumps({"404": "%s match not found" % self.match_key})
self.abort(404)
class ApiMatchController(ApiMatchControllerBase):
def _track_call(self, match_key):
self._track_call_defer('match', match_key)
def _render(self, match_key):
self._set_match(match_key)
match_dict = ModelToDict.matchConverter(self.match)
return json.dumps(match_dict, ensure_ascii=True)
## Instruction:
Move cache key out of base class
## Code After:
import json
import webapp2
from controllers.api.api_base_controller import ApiBaseController
from helpers.model_to_dict import ModelToDict
from models.match import Match
class ApiMatchControllerBase(ApiBaseController):
def __init__(self, *args, **kw):
super(ApiMatchControllerBase, self).__init__(*args, **kw)
self.match_key = self.request.route_kwargs["match_key"]
@property
def _validators(self):
return [("match_id_validator", self.match_key)]
def _set_match(self, match_key):
self.match = Match.get_by_id(match_key)
if self.match is None:
self._errors = json.dumps({"404": "%s match not found" % self.match_key})
self.abort(404)
class ApiMatchController(ApiMatchControllerBase):
CACHE_KEY_FORMAT = "apiv2_match_controller_{}" # (match_key)
CACHE_VERSION = 2
CACHE_HEADER_LENGTH = 60 * 60
def __init__(self, *args, **kw):
super(ApiMatchController, self).__init__(*args, **kw)
self._partial_cache_key = self.CACHE_KEY_FORMAT.format(self.match_key)
def _track_call(self, match_key):
self._track_call_defer('match', match_key)
def _render(self, match_key):
self._set_match(match_key)
match_dict = ModelToDict.matchConverter(self.match)
return json.dumps(match_dict, ensure_ascii=True)
|
b2771e6b33bd889c971b77e1b30c1cc5a0b9eb24 | platform.py | platform.py |
from platformio.managers.platform import PlatformBase
class Ststm32Platform(PlatformBase):
def configure_default_packages(self, variables, targets):
board = variables.get("board")
if "mbed" in variables.get("pioframework",
[]) or board == "mxchip_az3166":
self.packages['toolchain-gccarmnoneeabi'][
'version'] = ">=1.60301.0"
if board == "mxchip_az3166":
self.frameworks['arduino'][
'script'] = "builder/frameworks/arduino/mxchip.py"
self.packages['tool-openocd']['type'] = "uploader"
return PlatformBase.configure_default_packages(self, variables,
targets)
|
from platformio.managers.platform import PlatformBase
class Ststm32Platform(PlatformBase):
def configure_default_packages(self, variables, targets):
board = variables.get("board")
if "mbed" in variables.get("pioframework",
[]) or board == "mxchip_az3166":
self.packages['toolchain-gccarmnoneeabi'][
'version'] = ">=1.60301.0"
if board == "mxchip_az3166":
self.frameworks['arduino'][
'package'] = "framework-arduinostm32mxchip"
self.frameworks['arduino'][
'script'] = "builder/frameworks/arduino/mxchip.py"
self.packages['tool-openocd']['type'] = "uploader"
return PlatformBase.configure_default_packages(self, variables,
targets)
| Use appropriate package for mxchip_az3166 | Use appropriate package for mxchip_az3166
| Python | apache-2.0 | platformio/platform-ststm32,platformio/platform-ststm32 |
from platformio.managers.platform import PlatformBase
class Ststm32Platform(PlatformBase):
def configure_default_packages(self, variables, targets):
board = variables.get("board")
if "mbed" in variables.get("pioframework",
[]) or board == "mxchip_az3166":
self.packages['toolchain-gccarmnoneeabi'][
'version'] = ">=1.60301.0"
if board == "mxchip_az3166":
self.frameworks['arduino'][
+ 'package'] = "framework-arduinostm32mxchip"
+ self.frameworks['arduino'][
'script'] = "builder/frameworks/arduino/mxchip.py"
self.packages['tool-openocd']['type'] = "uploader"
return PlatformBase.configure_default_packages(self, variables,
targets)
| Use appropriate package for mxchip_az3166 | ## Code Before:
from platformio.managers.platform import PlatformBase
class Ststm32Platform(PlatformBase):
def configure_default_packages(self, variables, targets):
board = variables.get("board")
if "mbed" in variables.get("pioframework",
[]) or board == "mxchip_az3166":
self.packages['toolchain-gccarmnoneeabi'][
'version'] = ">=1.60301.0"
if board == "mxchip_az3166":
self.frameworks['arduino'][
'script'] = "builder/frameworks/arduino/mxchip.py"
self.packages['tool-openocd']['type'] = "uploader"
return PlatformBase.configure_default_packages(self, variables,
targets)
## Instruction:
Use appropriate package for mxchip_az3166
## Code After:
from platformio.managers.platform import PlatformBase
class Ststm32Platform(PlatformBase):
def configure_default_packages(self, variables, targets):
board = variables.get("board")
if "mbed" in variables.get("pioframework",
[]) or board == "mxchip_az3166":
self.packages['toolchain-gccarmnoneeabi'][
'version'] = ">=1.60301.0"
if board == "mxchip_az3166":
self.frameworks['arduino'][
'package'] = "framework-arduinostm32mxchip"
self.frameworks['arduino'][
'script'] = "builder/frameworks/arduino/mxchip.py"
self.packages['tool-openocd']['type'] = "uploader"
return PlatformBase.configure_default_packages(self, variables,
targets)
|
1096d0f13ebbc5900c21626a5caf6276b36229d8 | Lib/test/test_coding.py | Lib/test/test_coding.py |
import test.test_support, unittest
import os
class CodingTest(unittest.TestCase):
def test_bad_coding(self):
module_name = 'bad_coding'
self.verify_bad_module(module_name)
def test_bad_coding2(self):
module_name = 'bad_coding2'
self.verify_bad_module(module_name)
def verify_bad_module(self, module_name):
self.assertRaises(SyntaxError, __import__, 'test.' + module_name)
path = os.path.dirname(__file__)
filename = os.path.join(path, module_name + '.py')
fp = open(filename)
text = fp.read()
fp.close()
self.assertRaises(SyntaxError, compile, text, filename, 'exec')
def test_exec_valid_coding(self):
d = {}
exec('# coding: cp949\na = 5\n', d)
self.assertEqual(d['a'], 5)
def test_main():
test.test_support.run_unittest(CodingTest)
if __name__ == "__main__":
test_main()
|
import test.test_support, unittest
import os
class CodingTest(unittest.TestCase):
def test_bad_coding(self):
module_name = 'bad_coding'
self.verify_bad_module(module_name)
def test_bad_coding2(self):
module_name = 'bad_coding2'
self.verify_bad_module(module_name)
def verify_bad_module(self, module_name):
self.assertRaises(SyntaxError, __import__, 'test.' + module_name)
path = os.path.dirname(__file__)
filename = os.path.join(path, module_name + '.py')
fp = open(filename, encoding='utf-8')
text = fp.read()
fp.close()
self.assertRaises(SyntaxError, compile, text, filename, 'exec')
def test_exec_valid_coding(self):
d = {}
exec('# coding: cp949\na = 5\n', d)
self.assertEqual(d['a'], 5)
def test_main():
test.test_support.run_unittest(CodingTest)
if __name__ == "__main__":
test_main()
| Fix a test failure on non-UTF-8 locales: bad_coding2.py is encoded in utf-8. | Fix a test failure on non-UTF-8 locales: bad_coding2.py is encoded
in utf-8.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator |
import test.test_support, unittest
import os
class CodingTest(unittest.TestCase):
def test_bad_coding(self):
module_name = 'bad_coding'
self.verify_bad_module(module_name)
def test_bad_coding2(self):
module_name = 'bad_coding2'
self.verify_bad_module(module_name)
def verify_bad_module(self, module_name):
self.assertRaises(SyntaxError, __import__, 'test.' + module_name)
path = os.path.dirname(__file__)
filename = os.path.join(path, module_name + '.py')
- fp = open(filename)
+ fp = open(filename, encoding='utf-8')
text = fp.read()
fp.close()
self.assertRaises(SyntaxError, compile, text, filename, 'exec')
def test_exec_valid_coding(self):
d = {}
exec('# coding: cp949\na = 5\n', d)
self.assertEqual(d['a'], 5)
def test_main():
test.test_support.run_unittest(CodingTest)
if __name__ == "__main__":
test_main()
| Fix a test failure on non-UTF-8 locales: bad_coding2.py is encoded in utf-8. | ## Code Before:
import test.test_support, unittest
import os
class CodingTest(unittest.TestCase):
def test_bad_coding(self):
module_name = 'bad_coding'
self.verify_bad_module(module_name)
def test_bad_coding2(self):
module_name = 'bad_coding2'
self.verify_bad_module(module_name)
def verify_bad_module(self, module_name):
self.assertRaises(SyntaxError, __import__, 'test.' + module_name)
path = os.path.dirname(__file__)
filename = os.path.join(path, module_name + '.py')
fp = open(filename)
text = fp.read()
fp.close()
self.assertRaises(SyntaxError, compile, text, filename, 'exec')
def test_exec_valid_coding(self):
d = {}
exec('# coding: cp949\na = 5\n', d)
self.assertEqual(d['a'], 5)
def test_main():
test.test_support.run_unittest(CodingTest)
if __name__ == "__main__":
test_main()
## Instruction:
Fix a test failure on non-UTF-8 locales: bad_coding2.py is encoded in utf-8.
## Code After:
import test.test_support, unittest
import os
class CodingTest(unittest.TestCase):
def test_bad_coding(self):
module_name = 'bad_coding'
self.verify_bad_module(module_name)
def test_bad_coding2(self):
module_name = 'bad_coding2'
self.verify_bad_module(module_name)
def verify_bad_module(self, module_name):
self.assertRaises(SyntaxError, __import__, 'test.' + module_name)
path = os.path.dirname(__file__)
filename = os.path.join(path, module_name + '.py')
fp = open(filename, encoding='utf-8')
text = fp.read()
fp.close()
self.assertRaises(SyntaxError, compile, text, filename, 'exec')
def test_exec_valid_coding(self):
d = {}
exec('# coding: cp949\na = 5\n', d)
self.assertEqual(d['a'], 5)
def test_main():
test.test_support.run_unittest(CodingTest)
if __name__ == "__main__":
test_main()
|
9901044b2b3218714a3c807e982db518aa97a446 | djangoautoconf/features/bae_settings.py | djangoautoconf/features/bae_settings.py |
try:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': const.CACHE_ADDR,
'TIMEOUT': 60,
}
}
except:
pass
try:
from bae.core import const
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': bae_secrets.database_name,
'USER': const.MYSQL_USER,
'PASSWORD': const.MYSQL_PASS,
'HOST': const.MYSQL_HOST,
'PORT': const.MYSQL_PORT,
}
}
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
###Or
#SESSION_ENGINE = 'django.contrib.sessions.backends.db'
##################################
except:
pass
EMAIL_BACKEND = 'django.core.mail.backends.bcms.EmailBackend'
try:
from objsys.baidu_mail import EmailBackend
EMAIL_BACKEND = 'objsys.baidu_mail.EmailBackend'
except:
EMAIL_BACKEND = 'django.core.mail.backends.dummy.EmailBackend'
|
try:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': const.CACHE_ADDR,
'TIMEOUT': 60,
}
}
except:
pass
try:
from bae.core import const
import bae_secrets
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': bae_secrets.database_name,
'USER': const.MYSQL_USER,
'PASSWORD': const.MYSQL_PASS,
'HOST': const.MYSQL_HOST,
'PORT': const.MYSQL_PORT,
}
}
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
###Or
#SESSION_ENGINE = 'django.contrib.sessions.backends.db'
##################################
except:
pass
EMAIL_BACKEND = 'django.core.mail.backends.bcms.EmailBackend'
try:
from objsys.baidu_mail import EmailBackend
EMAIL_BACKEND = 'objsys.baidu_mail.EmailBackend'
except:
EMAIL_BACKEND = 'django.core.mail.backends.dummy.EmailBackend'
| Move BAE secret into try catch block | Move BAE secret into try catch block
| Python | bsd-3-clause | weijia/djangoautoconf,weijia/djangoautoconf | +
try:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': const.CACHE_ADDR,
'TIMEOUT': 60,
}
}
except:
pass
try:
from bae.core import const
+ import bae_secrets
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': bae_secrets.database_name,
'USER': const.MYSQL_USER,
'PASSWORD': const.MYSQL_PASS,
'HOST': const.MYSQL_HOST,
'PORT': const.MYSQL_PORT,
}
}
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
###Or
#SESSION_ENGINE = 'django.contrib.sessions.backends.db'
##################################
except:
pass
EMAIL_BACKEND = 'django.core.mail.backends.bcms.EmailBackend'
try:
from objsys.baidu_mail import EmailBackend
EMAIL_BACKEND = 'objsys.baidu_mail.EmailBackend'
except:
EMAIL_BACKEND = 'django.core.mail.backends.dummy.EmailBackend'
| Move BAE secret into try catch block | ## Code Before:
try:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': const.CACHE_ADDR,
'TIMEOUT': 60,
}
}
except:
pass
try:
from bae.core import const
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': bae_secrets.database_name,
'USER': const.MYSQL_USER,
'PASSWORD': const.MYSQL_PASS,
'HOST': const.MYSQL_HOST,
'PORT': const.MYSQL_PORT,
}
}
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
###Or
#SESSION_ENGINE = 'django.contrib.sessions.backends.db'
##################################
except:
pass
EMAIL_BACKEND = 'django.core.mail.backends.bcms.EmailBackend'
try:
from objsys.baidu_mail import EmailBackend
EMAIL_BACKEND = 'objsys.baidu_mail.EmailBackend'
except:
EMAIL_BACKEND = 'django.core.mail.backends.dummy.EmailBackend'
## Instruction:
Move BAE secret into try catch block
## Code After:
try:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': const.CACHE_ADDR,
'TIMEOUT': 60,
}
}
except:
pass
try:
from bae.core import const
import bae_secrets
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': bae_secrets.database_name,
'USER': const.MYSQL_USER,
'PASSWORD': const.MYSQL_PASS,
'HOST': const.MYSQL_HOST,
'PORT': const.MYSQL_PORT,
}
}
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
###Or
#SESSION_ENGINE = 'django.contrib.sessions.backends.db'
##################################
except:
pass
EMAIL_BACKEND = 'django.core.mail.backends.bcms.EmailBackend'
try:
from objsys.baidu_mail import EmailBackend
EMAIL_BACKEND = 'objsys.baidu_mail.EmailBackend'
except:
EMAIL_BACKEND = 'django.core.mail.backends.dummy.EmailBackend'
|
3ed807b44289c00d6a82b0c253f7ff8072336fdd | changes/jobs/cleanup_tasks.py | changes/jobs/cleanup_tasks.py | from __future__ import absolute_import
from datetime import datetime, timedelta
from changes.config import queue
from changes.constants import Status
from changes.models.task import Task
from changes.queue.task import TrackedTask
CHECK_TIME = timedelta(minutes=60)
EXPIRE_TIME = timedelta(days=7)
# NOTE: This isn't itself a TrackedTask, but probably should be.
def cleanup_tasks():
"""
Find any tasks which haven't checked in within a reasonable time period and
requeue them if necessary.
Additionally remove any old Task entries which are completed.
"""
now = datetime.utcnow()
pending_tasks = Task.query.filter(
Task.status != Status.finished,
Task.date_modified < now - CHECK_TIME,
)
for task in pending_tasks:
task_func = TrackedTask(queue.get_task(task.task_name))
task_func.delay(
task_id=task.task_id.hex,
parent_task_id=task.parent_id.hex if task.parent_id else None,
**task.data['kwargs']
)
Task.query.filter(
Task.status == Status.finished,
Task.date_modified < now - EXPIRE_TIME,
).delete()
| from __future__ import absolute_import
from datetime import datetime, timedelta
from changes.config import queue, statsreporter
from changes.constants import Status
from changes.models.task import Task
from changes.queue.task import TrackedTask
CHECK_TIME = timedelta(minutes=60)
EXPIRE_TIME = timedelta(days=7)
# NOTE: This isn't itself a TrackedTask, but probably should be.
@statsreporter.timer('task_duration_cleanup_task')
def cleanup_tasks():
"""
Find any tasks which haven't checked in within a reasonable time period and
requeue them if necessary.
Additionally remove any old Task entries which are completed.
"""
now = datetime.utcnow()
pending_tasks = Task.query.filter(
Task.status != Status.finished,
Task.date_modified < now - CHECK_TIME,
)
for task in pending_tasks:
task_func = TrackedTask(queue.get_task(task.task_name))
task_func.delay(
task_id=task.task_id.hex,
parent_task_id=task.parent_id.hex if task.parent_id else None,
**task.data['kwargs']
)
deleted = Task.query.filter(
Task.status == Status.finished,
Task.date_modified < now - EXPIRE_TIME,
# Filtering by date_created isn't necessary, but it allows us to filter using an index on
# a value that doesn't update, which makes our deletion more efficient.
Task.date_created < now - EXPIRE_TIME,
).delete(synchronize_session=False)
statsreporter.stats().incr('tasks_deleted', deleted)
| Make periodic expired task deletion more efficient | Make periodic expired task deletion more efficient
Summary: Also adds tracking for the number of tasks deleted at each run.
Test Plan: None
Reviewers: paulruan
Reviewed By: paulruan
Subscribers: changesbot, anupc
Differential Revision: https://tails.corp.dropbox.com/D232735
| Python | apache-2.0 | dropbox/changes,dropbox/changes,dropbox/changes,dropbox/changes | from __future__ import absolute_import
from datetime import datetime, timedelta
- from changes.config import queue
+ from changes.config import queue, statsreporter
from changes.constants import Status
from changes.models.task import Task
from changes.queue.task import TrackedTask
CHECK_TIME = timedelta(minutes=60)
EXPIRE_TIME = timedelta(days=7)
# NOTE: This isn't itself a TrackedTask, but probably should be.
+ @statsreporter.timer('task_duration_cleanup_task')
def cleanup_tasks():
"""
Find any tasks which haven't checked in within a reasonable time period and
requeue them if necessary.
Additionally remove any old Task entries which are completed.
"""
now = datetime.utcnow()
pending_tasks = Task.query.filter(
Task.status != Status.finished,
Task.date_modified < now - CHECK_TIME,
)
for task in pending_tasks:
task_func = TrackedTask(queue.get_task(task.task_name))
task_func.delay(
task_id=task.task_id.hex,
parent_task_id=task.parent_id.hex if task.parent_id else None,
**task.data['kwargs']
)
- Task.query.filter(
+ deleted = Task.query.filter(
Task.status == Status.finished,
Task.date_modified < now - EXPIRE_TIME,
- ).delete()
+ # Filtering by date_created isn't necessary, but it allows us to filter using an index on
+ # a value that doesn't update, which makes our deletion more efficient.
+ Task.date_created < now - EXPIRE_TIME,
+ ).delete(synchronize_session=False)
+ statsreporter.stats().incr('tasks_deleted', deleted)
| Make periodic expired task deletion more efficient | ## Code Before:
from __future__ import absolute_import
from datetime import datetime, timedelta
from changes.config import queue
from changes.constants import Status
from changes.models.task import Task
from changes.queue.task import TrackedTask
CHECK_TIME = timedelta(minutes=60)
EXPIRE_TIME = timedelta(days=7)
# NOTE: This isn't itself a TrackedTask, but probably should be.
def cleanup_tasks():
"""
Find any tasks which haven't checked in within a reasonable time period and
requeue them if necessary.
Additionally remove any old Task entries which are completed.
"""
now = datetime.utcnow()
pending_tasks = Task.query.filter(
Task.status != Status.finished,
Task.date_modified < now - CHECK_TIME,
)
for task in pending_tasks:
task_func = TrackedTask(queue.get_task(task.task_name))
task_func.delay(
task_id=task.task_id.hex,
parent_task_id=task.parent_id.hex if task.parent_id else None,
**task.data['kwargs']
)
Task.query.filter(
Task.status == Status.finished,
Task.date_modified < now - EXPIRE_TIME,
).delete()
## Instruction:
Make periodic expired task deletion more efficient
## Code After:
from __future__ import absolute_import
from datetime import datetime, timedelta
from changes.config import queue, statsreporter
from changes.constants import Status
from changes.models.task import Task
from changes.queue.task import TrackedTask
CHECK_TIME = timedelta(minutes=60)
EXPIRE_TIME = timedelta(days=7)
# NOTE: This isn't itself a TrackedTask, but probably should be.
@statsreporter.timer('task_duration_cleanup_task')
def cleanup_tasks():
"""
Find any tasks which haven't checked in within a reasonable time period and
requeue them if necessary.
Additionally remove any old Task entries which are completed.
"""
now = datetime.utcnow()
pending_tasks = Task.query.filter(
Task.status != Status.finished,
Task.date_modified < now - CHECK_TIME,
)
for task in pending_tasks:
task_func = TrackedTask(queue.get_task(task.task_name))
task_func.delay(
task_id=task.task_id.hex,
parent_task_id=task.parent_id.hex if task.parent_id else None,
**task.data['kwargs']
)
deleted = Task.query.filter(
Task.status == Status.finished,
Task.date_modified < now - EXPIRE_TIME,
# Filtering by date_created isn't necessary, but it allows us to filter using an index on
# a value that doesn't update, which makes our deletion more efficient.
Task.date_created < now - EXPIRE_TIME,
).delete(synchronize_session=False)
statsreporter.stats().incr('tasks_deleted', deleted)
|
dd8c85a49a31693f43e6f6877a0657d63cbc1b01 | auth0/v2/device_credentials.py | auth0/v2/device_credentials.py | from .rest import RestClient
class DeviceCredentials(object):
"""Auth0 connection endpoints
Args:
domain (str): Your Auth0 domain, e.g: 'username.auth0.com'
jwt_token (str): An API token created with your account's global
keys. You can create one by using the token generator in the
API Explorer: https://auth0.com/docs/api/v2
"""
def __init__(self, domain, jwt_token):
self.domain = domain
self.client = RestClient(jwt=jwt_token)
def _url(self, id=None):
url = 'https://%s/api/v2/device-credentials' % self.domain
if id is not None:
return url + '/' + id
return url
def get(self, user_id=None, client_id=None, type=None,
fields=[], include_fields=True):
params = {
'fields': ','.join(fields) or None,
'include_fields': str(include_fields).lower(),
'user_id': user_id,
'client_id': client_id,
'type': type,
}
return self.client.get(self._url(), params=params)
def create(self, body):
return self.client.post(self._url(), data=body)
def delete(self, id):
return self.client.delete(self._url(id))
| from .rest import RestClient
class DeviceCredentials(object):
"""Auth0 connection endpoints
Args:
domain (str): Your Auth0 domain, e.g: 'username.auth0.com'
jwt_token (str): An API token created with your account's global
keys. You can create one by using the token generator in the
API Explorer: https://auth0.com/docs/api/v2
"""
def __init__(self, domain, jwt_token):
self.domain = domain
self.client = RestClient(jwt=jwt_token)
def _url(self, id=None):
url = 'https://%s/api/v2/device-credentials' % self.domain
if id is not None:
return url + '/' + id
return url
def get(self, user_id, client_id, type, fields=[], include_fields=True):
params = {
'fields': ','.join(fields) or None,
'include_fields': str(include_fields).lower(),
'user_id': user_id,
'client_id': client_id,
'type': type,
}
return self.client.get(self._url(), params=params)
def create(self, body):
return self.client.post(self._url(), data=body)
def delete(self, id):
return self.client.delete(self._url(id))
| Remove default arguments for user_id, client_id and type | Remove default arguments for user_id, client_id and type
| Python | mit | auth0/auth0-python,auth0/auth0-python | from .rest import RestClient
class DeviceCredentials(object):
"""Auth0 connection endpoints
Args:
domain (str): Your Auth0 domain, e.g: 'username.auth0.com'
jwt_token (str): An API token created with your account's global
keys. You can create one by using the token generator in the
API Explorer: https://auth0.com/docs/api/v2
"""
def __init__(self, domain, jwt_token):
self.domain = domain
self.client = RestClient(jwt=jwt_token)
def _url(self, id=None):
url = 'https://%s/api/v2/device-credentials' % self.domain
if id is not None:
return url + '/' + id
return url
+ def get(self, user_id, client_id, type, fields=[], include_fields=True):
- def get(self, user_id=None, client_id=None, type=None,
- fields=[], include_fields=True):
params = {
'fields': ','.join(fields) or None,
'include_fields': str(include_fields).lower(),
'user_id': user_id,
'client_id': client_id,
'type': type,
}
return self.client.get(self._url(), params=params)
def create(self, body):
return self.client.post(self._url(), data=body)
def delete(self, id):
return self.client.delete(self._url(id))
| Remove default arguments for user_id, client_id and type | ## Code Before:
from .rest import RestClient
class DeviceCredentials(object):
"""Auth0 connection endpoints
Args:
domain (str): Your Auth0 domain, e.g: 'username.auth0.com'
jwt_token (str): An API token created with your account's global
keys. You can create one by using the token generator in the
API Explorer: https://auth0.com/docs/api/v2
"""
def __init__(self, domain, jwt_token):
self.domain = domain
self.client = RestClient(jwt=jwt_token)
def _url(self, id=None):
url = 'https://%s/api/v2/device-credentials' % self.domain
if id is not None:
return url + '/' + id
return url
def get(self, user_id=None, client_id=None, type=None,
fields=[], include_fields=True):
params = {
'fields': ','.join(fields) or None,
'include_fields': str(include_fields).lower(),
'user_id': user_id,
'client_id': client_id,
'type': type,
}
return self.client.get(self._url(), params=params)
def create(self, body):
return self.client.post(self._url(), data=body)
def delete(self, id):
return self.client.delete(self._url(id))
## Instruction:
Remove default arguments for user_id, client_id and type
## Code After:
from .rest import RestClient
class DeviceCredentials(object):
"""Auth0 connection endpoints
Args:
domain (str): Your Auth0 domain, e.g: 'username.auth0.com'
jwt_token (str): An API token created with your account's global
keys. You can create one by using the token generator in the
API Explorer: https://auth0.com/docs/api/v2
"""
def __init__(self, domain, jwt_token):
self.domain = domain
self.client = RestClient(jwt=jwt_token)
def _url(self, id=None):
url = 'https://%s/api/v2/device-credentials' % self.domain
if id is not None:
return url + '/' + id
return url
def get(self, user_id, client_id, type, fields=[], include_fields=True):
params = {
'fields': ','.join(fields) or None,
'include_fields': str(include_fields).lower(),
'user_id': user_id,
'client_id': client_id,
'type': type,
}
return self.client.get(self._url(), params=params)
def create(self, body):
return self.client.post(self._url(), data=body)
def delete(self, id):
return self.client.delete(self._url(id))
|
24ea32f71faab214a6f350d2d48b2f5715d8262d | manage.py | manage.py | from flask_restful import Api
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager
from app import app
from app import db
from app.auth import Register, Login
from app.bucketlist_api import BucketList, BucketListEntry
from app.bucketlist_items import BucketListItems, BucketListItemSingle
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
api = Api(app)
api.add_resource(Register, '/auth/register')
api.add_resource(Login, '/auth/login')
api.add_resource(BucketList, '/bucketlists')
api.add_resource(BucketListEntry, '/bucketlists/<int:bucketlist_id>')
api.add_resource(BucketListItems, '/bucketlists/<int:bucketlist_id>/items')
api.add_resource(BucketListItemSingle,
'/bucketlists/<int:bucketlist_id>/items/<int:item_id>')
if __name__ == '__main__':
manager.run()
| from flask_restful import Api
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager
from app import app, db
from app.auth import Register, Login
from app.bucketlist_api import BucketLists, BucketListSingle
from app.bucketlist_items import BucketListItems, BucketListItemSingle
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
api = Api(app)
api.add_resource(Register, '/auth/register')
api.add_resource(Login, '/auth/login')
api.add_resource(BucketLists, '/bucketlists')
api.add_resource(BucketListSingle, '/bucketlists/<int:bucketlist_id>')
api.add_resource(BucketListItems, '/bucketlists/<int:bucketlist_id>/items')
api.add_resource(BucketListItemSingle,
'/bucketlists/<int:bucketlist_id>/items/<int:item_id>')
if __name__ == '__main__':
manager.run()
| Set urls for bucketlist items endpoints | Set urls for bucketlist items endpoints
| Python | mit | andela-bmwenda/cp2-bucketlist-api | from flask_restful import Api
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager
- from app import app
+ from app import app, db
- from app import db
from app.auth import Register, Login
- from app.bucketlist_api import BucketList, BucketListEntry
+ from app.bucketlist_api import BucketLists, BucketListSingle
from app.bucketlist_items import BucketListItems, BucketListItemSingle
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
api = Api(app)
api.add_resource(Register, '/auth/register')
api.add_resource(Login, '/auth/login')
- api.add_resource(BucketList, '/bucketlists')
+ api.add_resource(BucketLists, '/bucketlists')
- api.add_resource(BucketListEntry, '/bucketlists/<int:bucketlist_id>')
+ api.add_resource(BucketListSingle, '/bucketlists/<int:bucketlist_id>')
api.add_resource(BucketListItems, '/bucketlists/<int:bucketlist_id>/items')
api.add_resource(BucketListItemSingle,
'/bucketlists/<int:bucketlist_id>/items/<int:item_id>')
if __name__ == '__main__':
manager.run()
| Set urls for bucketlist items endpoints | ## Code Before:
from flask_restful import Api
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager
from app import app
from app import db
from app.auth import Register, Login
from app.bucketlist_api import BucketList, BucketListEntry
from app.bucketlist_items import BucketListItems, BucketListItemSingle
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
api = Api(app)
api.add_resource(Register, '/auth/register')
api.add_resource(Login, '/auth/login')
api.add_resource(BucketList, '/bucketlists')
api.add_resource(BucketListEntry, '/bucketlists/<int:bucketlist_id>')
api.add_resource(BucketListItems, '/bucketlists/<int:bucketlist_id>/items')
api.add_resource(BucketListItemSingle,
'/bucketlists/<int:bucketlist_id>/items/<int:item_id>')
if __name__ == '__main__':
manager.run()
## Instruction:
Set urls for bucketlist items endpoints
## Code After:
from flask_restful import Api
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager
from app import app, db
from app.auth import Register, Login
from app.bucketlist_api import BucketLists, BucketListSingle
from app.bucketlist_items import BucketListItems, BucketListItemSingle
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
api = Api(app)
api.add_resource(Register, '/auth/register')
api.add_resource(Login, '/auth/login')
api.add_resource(BucketLists, '/bucketlists')
api.add_resource(BucketListSingle, '/bucketlists/<int:bucketlist_id>')
api.add_resource(BucketListItems, '/bucketlists/<int:bucketlist_id>/items')
api.add_resource(BucketListItemSingle,
'/bucketlists/<int:bucketlist_id>/items/<int:item_id>')
if __name__ == '__main__':
manager.run()
|
638a1c434ef8202774675581c3659511fa9d1cd3 | vehicles/management/commands/import_edinburgh.py | vehicles/management/commands/import_edinburgh.py | from django.contrib.gis.geos import Point
from busstops.models import Service
from ...models import Vehicle, VehicleLocation, VehicleJourney
from ..import_live_vehicles import ImportLiveVehiclesCommand
class Command(ImportLiveVehiclesCommand):
url = 'http://tfeapp.com/live/vehicles.php'
source_name = 'TfE'
services = Service.objects.filter(operator__in=('LOTH', 'EDTR', 'ECBU', 'NELB'), current=True)
def get_journey(self, item):
journey = VehicleJourney(
code=item['journey_id'],
destination=item['destination']
)
vehicle_defaults = {}
try:
journey.service = self.services.get(line_name=item['service_name'])
vehicle_defaults['operator'] = journey.service.operator.first()
except (Service.DoesNotExist, Service.MultipleObjectsReturned) as e:
if item['service_name'] not in {'ET1', 'MA1', '3BBT'}:
print(e, item['service_name'])
vehicle_code = item['vehicle_id']
if vehicle_code.isdigit():
vehicle_defaults['fleet_number'] = vehicle_code
journey.vehicle, vehicle_created = Vehicle.objects.update_or_create(
vehicle_defaults,
source=self.source,
code=vehicle_code
)
return journey, vehicle_created
def create_vehicle_location(self, item):
return VehicleLocation(
latlong=Point(item['longitude'], item['latitude']),
heading=item['heading']
)
| from django.contrib.gis.geos import Point
from busstops.models import Service
from ...models import Vehicle, VehicleLocation, VehicleJourney
from ..import_live_vehicles import ImportLiveVehiclesCommand
class Command(ImportLiveVehiclesCommand):
url = 'http://tfeapp.com/live/vehicles.php'
source_name = 'TfE'
services = Service.objects.filter(operator__in=('LOTH', 'EDTR', 'ECBU', 'NELB'), current=True)
def get_journey(self, item):
journey = VehicleJourney(
code=item['journey_id'] or '',
destination=item['destination'] or ''
)
vehicle_defaults = {}
try:
journey.service = self.services.get(line_name=item['service_name'])
vehicle_defaults['operator'] = journey.service.operator.first()
except (Service.DoesNotExist, Service.MultipleObjectsReturned) as e:
if item['service_name'] not in {'ET1', 'MA1', '3BBT'}:
print(e, item['service_name'])
vehicle_code = item['vehicle_id']
if vehicle_code.isdigit():
vehicle_defaults['fleet_number'] = vehicle_code
journey.vehicle, vehicle_created = Vehicle.objects.update_or_create(
vehicle_defaults,
source=self.source,
code=vehicle_code
)
return journey, vehicle_created
def create_vehicle_location(self, item):
return VehicleLocation(
latlong=Point(item['longitude'], item['latitude']),
heading=item['heading']
)
| Fix null Edinburgh journey code or destination | Fix null Edinburgh journey code or destination
| Python | mpl-2.0 | jclgoodwin/bustimes.org.uk,jclgoodwin/bustimes.org.uk,jclgoodwin/bustimes.org.uk,jclgoodwin/bustimes.org.uk | from django.contrib.gis.geos import Point
from busstops.models import Service
from ...models import Vehicle, VehicleLocation, VehicleJourney
from ..import_live_vehicles import ImportLiveVehiclesCommand
class Command(ImportLiveVehiclesCommand):
url = 'http://tfeapp.com/live/vehicles.php'
source_name = 'TfE'
services = Service.objects.filter(operator__in=('LOTH', 'EDTR', 'ECBU', 'NELB'), current=True)
def get_journey(self, item):
journey = VehicleJourney(
- code=item['journey_id'],
+ code=item['journey_id'] or '',
- destination=item['destination']
+ destination=item['destination'] or ''
)
vehicle_defaults = {}
try:
journey.service = self.services.get(line_name=item['service_name'])
vehicle_defaults['operator'] = journey.service.operator.first()
except (Service.DoesNotExist, Service.MultipleObjectsReturned) as e:
if item['service_name'] not in {'ET1', 'MA1', '3BBT'}:
print(e, item['service_name'])
vehicle_code = item['vehicle_id']
if vehicle_code.isdigit():
vehicle_defaults['fleet_number'] = vehicle_code
journey.vehicle, vehicle_created = Vehicle.objects.update_or_create(
vehicle_defaults,
source=self.source,
code=vehicle_code
)
return journey, vehicle_created
def create_vehicle_location(self, item):
return VehicleLocation(
latlong=Point(item['longitude'], item['latitude']),
heading=item['heading']
)
| Fix null Edinburgh journey code or destination | ## Code Before:
from django.contrib.gis.geos import Point
from busstops.models import Service
from ...models import Vehicle, VehicleLocation, VehicleJourney
from ..import_live_vehicles import ImportLiveVehiclesCommand
class Command(ImportLiveVehiclesCommand):
url = 'http://tfeapp.com/live/vehicles.php'
source_name = 'TfE'
services = Service.objects.filter(operator__in=('LOTH', 'EDTR', 'ECBU', 'NELB'), current=True)
def get_journey(self, item):
journey = VehicleJourney(
code=item['journey_id'],
destination=item['destination']
)
vehicle_defaults = {}
try:
journey.service = self.services.get(line_name=item['service_name'])
vehicle_defaults['operator'] = journey.service.operator.first()
except (Service.DoesNotExist, Service.MultipleObjectsReturned) as e:
if item['service_name'] not in {'ET1', 'MA1', '3BBT'}:
print(e, item['service_name'])
vehicle_code = item['vehicle_id']
if vehicle_code.isdigit():
vehicle_defaults['fleet_number'] = vehicle_code
journey.vehicle, vehicle_created = Vehicle.objects.update_or_create(
vehicle_defaults,
source=self.source,
code=vehicle_code
)
return journey, vehicle_created
def create_vehicle_location(self, item):
return VehicleLocation(
latlong=Point(item['longitude'], item['latitude']),
heading=item['heading']
)
## Instruction:
Fix null Edinburgh journey code or destination
## Code After:
from django.contrib.gis.geos import Point
from busstops.models import Service
from ...models import Vehicle, VehicleLocation, VehicleJourney
from ..import_live_vehicles import ImportLiveVehiclesCommand
class Command(ImportLiveVehiclesCommand):
url = 'http://tfeapp.com/live/vehicles.php'
source_name = 'TfE'
services = Service.objects.filter(operator__in=('LOTH', 'EDTR', 'ECBU', 'NELB'), current=True)
def get_journey(self, item):
journey = VehicleJourney(
code=item['journey_id'] or '',
destination=item['destination'] or ''
)
vehicle_defaults = {}
try:
journey.service = self.services.get(line_name=item['service_name'])
vehicle_defaults['operator'] = journey.service.operator.first()
except (Service.DoesNotExist, Service.MultipleObjectsReturned) as e:
if item['service_name'] not in {'ET1', 'MA1', '3BBT'}:
print(e, item['service_name'])
vehicle_code = item['vehicle_id']
if vehicle_code.isdigit():
vehicle_defaults['fleet_number'] = vehicle_code
journey.vehicle, vehicle_created = Vehicle.objects.update_or_create(
vehicle_defaults,
source=self.source,
code=vehicle_code
)
return journey, vehicle_created
def create_vehicle_location(self, item):
return VehicleLocation(
latlong=Point(item['longitude'], item['latitude']),
heading=item['heading']
)
|
c9da64ac1c90abdee8fc72488a4bef58a95aa7c6 | biwako/bin/fields/compounds.py | biwako/bin/fields/compounds.py | import io
from .base import Field, DynamicValue, FullyDecoded
class SubStructure(Field):
def __init__(self, structure, *args, **kwargs):
self.structure = structure
super(SubStructure, self).__init__(*args, **kwargs)
def read(self, file):
value = self.structure(file)
value_bytes = b''
# Force the evaluation of the entire structure in
# order to make sure other fields work properly
for field in self.structure._fields:
getattr(value, field.name)
value_bytes += value._raw_values[field.name]
raise FullyDecoded(value_bytes, value)
def encode(self, obj, value):
output = io.BytesIO()
value.save(output)
return output.getvalue()
class List(Field):
def __init__(self, field, *args, **kwargs):
super(List, self).__init__(*args, **kwargs)
self.field = field
def read(self, file):
value_bytes = b''
values = []
if self.instance:
instance_field = field.for_instance(self.instance)
for i in range(self.size):
bytes, value = instance_field.read_value(file)
value_bytes += bytes
values.append(value)
return values
def encode(self, obj, values):
encoded_values = []
for value in values:
encoded_values.append(self.field.encode(obj, value))
return b''.join(encoded_values)
| import io
from .base import Field, DynamicValue, FullyDecoded
class SubStructure(Field):
def __init__(self, structure, *args, **kwargs):
self.structure = structure
super(SubStructure, self).__init__(*args, **kwargs)
def read(self, file):
value = self.structure(file)
value_bytes = b''
# Force the evaluation of the entire structure in
# order to make sure other fields work properly
for field in self.structure._fields:
getattr(value, field.name)
value_bytes += value._raw_values[field.name]
raise FullyDecoded(value_bytes, value)
def encode(self, obj, value):
output = io.BytesIO()
value.save(output)
return output.getvalue()
class List(Field):
def __init__(self, field, *args, **kwargs):
super(List, self).__init__(*args, **kwargs)
self.field = field
def read(self, file):
value_bytes = b''
values = []
if self.instance:
instance_field = self.field.for_instance(self.instance)
for i in range(self.size):
bytes, value = instance_field.read_value(file)
value_bytes += bytes
values.append(value)
raise FullyDecoded(value_bytes, values)
def encode(self, obj, values):
encoded_values = []
for value in values:
encoded_values.append(self.field.encode(obj, value))
return b''.join(encoded_values)
| Fix List to use the new decoding system | Fix List to use the new decoding system
| Python | bsd-3-clause | gulopine/steel | import io
from .base import Field, DynamicValue, FullyDecoded
class SubStructure(Field):
def __init__(self, structure, *args, **kwargs):
self.structure = structure
super(SubStructure, self).__init__(*args, **kwargs)
def read(self, file):
value = self.structure(file)
value_bytes = b''
# Force the evaluation of the entire structure in
# order to make sure other fields work properly
for field in self.structure._fields:
getattr(value, field.name)
value_bytes += value._raw_values[field.name]
raise FullyDecoded(value_bytes, value)
def encode(self, obj, value):
output = io.BytesIO()
value.save(output)
return output.getvalue()
class List(Field):
def __init__(self, field, *args, **kwargs):
super(List, self).__init__(*args, **kwargs)
self.field = field
def read(self, file):
value_bytes = b''
values = []
if self.instance:
- instance_field = field.for_instance(self.instance)
+ instance_field = self.field.for_instance(self.instance)
for i in range(self.size):
bytes, value = instance_field.read_value(file)
value_bytes += bytes
values.append(value)
- return values
+ raise FullyDecoded(value_bytes, values)
def encode(self, obj, values):
encoded_values = []
for value in values:
encoded_values.append(self.field.encode(obj, value))
return b''.join(encoded_values)
| Fix List to use the new decoding system | ## Code Before:
import io
from .base import Field, DynamicValue, FullyDecoded
class SubStructure(Field):
def __init__(self, structure, *args, **kwargs):
self.structure = structure
super(SubStructure, self).__init__(*args, **kwargs)
def read(self, file):
value = self.structure(file)
value_bytes = b''
# Force the evaluation of the entire structure in
# order to make sure other fields work properly
for field in self.structure._fields:
getattr(value, field.name)
value_bytes += value._raw_values[field.name]
raise FullyDecoded(value_bytes, value)
def encode(self, obj, value):
output = io.BytesIO()
value.save(output)
return output.getvalue()
class List(Field):
def __init__(self, field, *args, **kwargs):
super(List, self).__init__(*args, **kwargs)
self.field = field
def read(self, file):
value_bytes = b''
values = []
if self.instance:
instance_field = field.for_instance(self.instance)
for i in range(self.size):
bytes, value = instance_field.read_value(file)
value_bytes += bytes
values.append(value)
return values
def encode(self, obj, values):
encoded_values = []
for value in values:
encoded_values.append(self.field.encode(obj, value))
return b''.join(encoded_values)
## Instruction:
Fix List to use the new decoding system
## Code After:
import io
from .base import Field, DynamicValue, FullyDecoded
class SubStructure(Field):
def __init__(self, structure, *args, **kwargs):
self.structure = structure
super(SubStructure, self).__init__(*args, **kwargs)
def read(self, file):
value = self.structure(file)
value_bytes = b''
# Force the evaluation of the entire structure in
# order to make sure other fields work properly
for field in self.structure._fields:
getattr(value, field.name)
value_bytes += value._raw_values[field.name]
raise FullyDecoded(value_bytes, value)
def encode(self, obj, value):
output = io.BytesIO()
value.save(output)
return output.getvalue()
class List(Field):
def __init__(self, field, *args, **kwargs):
super(List, self).__init__(*args, **kwargs)
self.field = field
def read(self, file):
value_bytes = b''
values = []
if self.instance:
instance_field = self.field.for_instance(self.instance)
for i in range(self.size):
bytes, value = instance_field.read_value(file)
value_bytes += bytes
values.append(value)
raise FullyDecoded(value_bytes, values)
def encode(self, obj, values):
encoded_values = []
for value in values:
encoded_values.append(self.field.encode(obj, value))
return b''.join(encoded_values)
|
1e5e2a236277dc9ba11f9fe4aff3279f692da3f7 | ploy/tests/conftest.py | ploy/tests/conftest.py | from mock import patch
import pytest
import os
import shutil
import tempfile
class Directory:
def __init__(self, directory):
self.directory = directory
def __getitem__(self, name):
path = os.path.join(self.directory, name)
assert not os.path.relpath(path, self.directory).startswith('..')
return File(path)
class File:
def __init__(self, path):
self.directory = os.path.dirname(path)
self.path = path
def fill(self, content):
if not os.path.exists(self.directory):
os.makedirs(self.directory)
with open(self.path, 'w') as f:
if isinstance(content, (list, tuple)):
content = '\n'.join(content)
f.write(content)
@pytest.yield_fixture
def tempdir():
""" Returns an object for easy use of a temporary directory which is
cleaned up afterwards.
Use tempdir[filepath] to access files.
Use .fill(lines) on the returned object to write content to the file.
"""
directory = tempfile.mkdtemp()
yield Directory(directory)
shutil.rmtree(directory)
@pytest.yield_fixture
def ployconf(tempdir):
""" Returns a Configfile object which manages ploy.conf.
"""
yield tempdir['etc/ploy.conf']
@pytest.yield_fixture
def os_execvp_mock():
with patch("os.execvp") as os_execvp_mock:
yield os_execvp_mock
| from mock import patch
import pytest
import os
import shutil
import tempfile
class Directory:
def __init__(self, directory):
self.directory = directory
def __getitem__(self, name):
path = os.path.join(self.directory, name)
assert not os.path.relpath(path, self.directory).startswith('..')
return File(path)
class File:
def __init__(self, path):
self.directory = os.path.dirname(path)
self.path = path
def fill(self, content):
if not os.path.exists(self.directory):
os.makedirs(self.directory)
with open(self.path, 'w') as f:
if isinstance(content, (list, tuple)):
content = '\n'.join(content)
f.write(content)
def content(self):
with open(self.path) as f:
return f.read()
@pytest.yield_fixture
def tempdir():
""" Returns an object for easy use of a temporary directory which is
cleaned up afterwards.
Use tempdir[filepath] to access files.
Use .fill(lines) on the returned object to write content to the file.
"""
directory = tempfile.mkdtemp()
yield Directory(directory)
shutil.rmtree(directory)
@pytest.yield_fixture
def ployconf(tempdir):
""" Returns a Configfile object which manages ploy.conf.
"""
yield tempdir['etc/ploy.conf']
@pytest.yield_fixture
def os_execvp_mock():
with patch("os.execvp") as os_execvp_mock:
yield os_execvp_mock
| Add convenience function to read tempdir files. | Add convenience function to read tempdir files.
| Python | bsd-3-clause | fschulze/ploy,ployground/ploy | from mock import patch
import pytest
import os
import shutil
import tempfile
class Directory:
def __init__(self, directory):
self.directory = directory
def __getitem__(self, name):
path = os.path.join(self.directory, name)
assert not os.path.relpath(path, self.directory).startswith('..')
return File(path)
class File:
def __init__(self, path):
self.directory = os.path.dirname(path)
self.path = path
def fill(self, content):
if not os.path.exists(self.directory):
os.makedirs(self.directory)
with open(self.path, 'w') as f:
if isinstance(content, (list, tuple)):
content = '\n'.join(content)
f.write(content)
+ def content(self):
+ with open(self.path) as f:
+ return f.read()
+
@pytest.yield_fixture
def tempdir():
""" Returns an object for easy use of a temporary directory which is
cleaned up afterwards.
Use tempdir[filepath] to access files.
Use .fill(lines) on the returned object to write content to the file.
"""
directory = tempfile.mkdtemp()
yield Directory(directory)
shutil.rmtree(directory)
@pytest.yield_fixture
def ployconf(tempdir):
""" Returns a Configfile object which manages ploy.conf.
"""
yield tempdir['etc/ploy.conf']
@pytest.yield_fixture
def os_execvp_mock():
with patch("os.execvp") as os_execvp_mock:
yield os_execvp_mock
| Add convenience function to read tempdir files. | ## Code Before:
from mock import patch
import pytest
import os
import shutil
import tempfile
class Directory:
def __init__(self, directory):
self.directory = directory
def __getitem__(self, name):
path = os.path.join(self.directory, name)
assert not os.path.relpath(path, self.directory).startswith('..')
return File(path)
class File:
def __init__(self, path):
self.directory = os.path.dirname(path)
self.path = path
def fill(self, content):
if not os.path.exists(self.directory):
os.makedirs(self.directory)
with open(self.path, 'w') as f:
if isinstance(content, (list, tuple)):
content = '\n'.join(content)
f.write(content)
@pytest.yield_fixture
def tempdir():
""" Returns an object for easy use of a temporary directory which is
cleaned up afterwards.
Use tempdir[filepath] to access files.
Use .fill(lines) on the returned object to write content to the file.
"""
directory = tempfile.mkdtemp()
yield Directory(directory)
shutil.rmtree(directory)
@pytest.yield_fixture
def ployconf(tempdir):
""" Returns a Configfile object which manages ploy.conf.
"""
yield tempdir['etc/ploy.conf']
@pytest.yield_fixture
def os_execvp_mock():
with patch("os.execvp") as os_execvp_mock:
yield os_execvp_mock
## Instruction:
Add convenience function to read tempdir files.
## Code After:
from mock import patch
import pytest
import os
import shutil
import tempfile
class Directory:
def __init__(self, directory):
self.directory = directory
def __getitem__(self, name):
path = os.path.join(self.directory, name)
assert not os.path.relpath(path, self.directory).startswith('..')
return File(path)
class File:
def __init__(self, path):
self.directory = os.path.dirname(path)
self.path = path
def fill(self, content):
if not os.path.exists(self.directory):
os.makedirs(self.directory)
with open(self.path, 'w') as f:
if isinstance(content, (list, tuple)):
content = '\n'.join(content)
f.write(content)
def content(self):
with open(self.path) as f:
return f.read()
@pytest.yield_fixture
def tempdir():
""" Returns an object for easy use of a temporary directory which is
cleaned up afterwards.
Use tempdir[filepath] to access files.
Use .fill(lines) on the returned object to write content to the file.
"""
directory = tempfile.mkdtemp()
yield Directory(directory)
shutil.rmtree(directory)
@pytest.yield_fixture
def ployconf(tempdir):
""" Returns a Configfile object which manages ploy.conf.
"""
yield tempdir['etc/ploy.conf']
@pytest.yield_fixture
def os_execvp_mock():
with patch("os.execvp") as os_execvp_mock:
yield os_execvp_mock
|
854709e1c2f5351c8e7af49e238fe54632f23ff5 | takeyourmeds/settings/defaults/apps.py | takeyourmeds/settings/defaults/apps.py | INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'allauth',
'allauth.account',
'djcelery',
'rest_framework',
'takeyourmeds.api',
'takeyourmeds.reminder',
'takeyourmeds.static',
'takeyourmeds.telephony',
'takeyourmeds.utils',
)
| INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.sites',
'django.contrib.staticfiles',
'allauth',
'allauth.account',
'djcelery',
'rest_framework',
'takeyourmeds.api',
'takeyourmeds.reminder',
'takeyourmeds.static',
'takeyourmeds.telephony',
'takeyourmeds.utils',
)
| Return .sites to INSTALLED_APPS until we drop allauth | Return .sites to INSTALLED_APPS until we drop allauth
| Python | mit | takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web | INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
+ 'django.contrib.sites',
'django.contrib.staticfiles',
'allauth',
'allauth.account',
'djcelery',
'rest_framework',
'takeyourmeds.api',
'takeyourmeds.reminder',
'takeyourmeds.static',
'takeyourmeds.telephony',
'takeyourmeds.utils',
)
| Return .sites to INSTALLED_APPS until we drop allauth | ## Code Before:
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'allauth',
'allauth.account',
'djcelery',
'rest_framework',
'takeyourmeds.api',
'takeyourmeds.reminder',
'takeyourmeds.static',
'takeyourmeds.telephony',
'takeyourmeds.utils',
)
## Instruction:
Return .sites to INSTALLED_APPS until we drop allauth
## Code After:
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.sites',
'django.contrib.staticfiles',
'allauth',
'allauth.account',
'djcelery',
'rest_framework',
'takeyourmeds.api',
'takeyourmeds.reminder',
'takeyourmeds.static',
'takeyourmeds.telephony',
'takeyourmeds.utils',
)
|
37f08dab37601b7621743467d6b78fb0306b5054 | lcapy/config.py | lcapy/config.py | exclude = ('C', 'O', 'S', 'N', 'E', 'E1', 'Q')
# Aliases for SymPy symbols
aliases = {'delta': 'DiracDelta', 'step': 'Heaviside', 'u': 'Heaviside',
'j': 'I'}
# String replacements when printing as LaTeX. For example, SymPy uses
# theta for Heaviside's step.
latex_string_map = {r'\theta\left': r'u\left'}
import sympy as sym
print_expr_map = {sym.I: 'j'}
# Hack to print i as j
from sympy.printing.pretty.pretty_symbology import atoms_table
atoms_table['ImaginaryUnit'] = '\u2149'
| exclude = ('C', 'O', 'S', 'N', 'E', 'E1', 'Q', 'beta', 'gamma', 'zeta')
# Aliases for SymPy symbols
aliases = {'delta': 'DiracDelta', 'step': 'Heaviside', 'u': 'Heaviside',
'j': 'I'}
# String replacements when printing as LaTeX. For example, SymPy uses
# theta for Heaviside's step.
latex_string_map = {r'\theta\left': r'u\left'}
import sympy as sym
print_expr_map = {sym.I: 'j'}
# Hack to pretty print i as j
from sympy.printing.pretty.pretty_symbology import atoms_table
atoms_table['ImaginaryUnit'] = '\u2149'
| Exclude beta, gamma, zeta functions | Exclude beta, gamma, zeta functions
| Python | lgpl-2.1 | mph-/lcapy | - exclude = ('C', 'O', 'S', 'N', 'E', 'E1', 'Q')
+ exclude = ('C', 'O', 'S', 'N', 'E', 'E1', 'Q', 'beta', 'gamma', 'zeta')
# Aliases for SymPy symbols
aliases = {'delta': 'DiracDelta', 'step': 'Heaviside', 'u': 'Heaviside',
'j': 'I'}
# String replacements when printing as LaTeX. For example, SymPy uses
# theta for Heaviside's step.
latex_string_map = {r'\theta\left': r'u\left'}
import sympy as sym
print_expr_map = {sym.I: 'j'}
- # Hack to print i as j
+ # Hack to pretty print i as j
from sympy.printing.pretty.pretty_symbology import atoms_table
atoms_table['ImaginaryUnit'] = '\u2149'
| Exclude beta, gamma, zeta functions | ## Code Before:
exclude = ('C', 'O', 'S', 'N', 'E', 'E1', 'Q')
# Aliases for SymPy symbols
aliases = {'delta': 'DiracDelta', 'step': 'Heaviside', 'u': 'Heaviside',
'j': 'I'}
# String replacements when printing as LaTeX. For example, SymPy uses
# theta for Heaviside's step.
latex_string_map = {r'\theta\left': r'u\left'}
import sympy as sym
print_expr_map = {sym.I: 'j'}
# Hack to print i as j
from sympy.printing.pretty.pretty_symbology import atoms_table
atoms_table['ImaginaryUnit'] = '\u2149'
## Instruction:
Exclude beta, gamma, zeta functions
## Code After:
exclude = ('C', 'O', 'S', 'N', 'E', 'E1', 'Q', 'beta', 'gamma', 'zeta')
# Aliases for SymPy symbols
aliases = {'delta': 'DiracDelta', 'step': 'Heaviside', 'u': 'Heaviside',
'j': 'I'}
# String replacements when printing as LaTeX. For example, SymPy uses
# theta for Heaviside's step.
latex_string_map = {r'\theta\left': r'u\left'}
import sympy as sym
print_expr_map = {sym.I: 'j'}
# Hack to pretty print i as j
from sympy.printing.pretty.pretty_symbology import atoms_table
atoms_table['ImaginaryUnit'] = '\u2149'
|
b278cf74b6ac57daee8e4ead6044f43ffd89a1f1 | importer/importer/__init__.py | importer/importer/__init__.py | import aiohttp
import os.path
from datetime import datetime
from aioes import Elasticsearch
from .importer import import_data
from .kudago import KudaGo
from .utils import read_json_file
ELASTIC_ENDPOINTS = ['localhost:9200']
ELASTIC_ALIAS = 'theatrics'
async def initialize():
elastic = Elasticsearch(ELASTIC_ENDPOINTS)
module_path = os.path.dirname(__file__)
config_filename = os.path.join(module_path, 'configuration', 'index.json')
index_configuration = read_json_file(config_filename)
alias_name = ELASTIC_ALIAS
index_name = generate_index_name()
await elastic.indices.create(index_name, index_configuration)
await elastic.indices.put_alias(alias_name, index_name)
async def update(since):
async with aiohttp.ClientSession() as http_client:
elastic = Elasticsearch(ELASTIC_ENDPOINTS)
kudago = KudaGo(http_client)
await import_data(kudago, elastic, ELASTIC_ALIAS, since=since)
def generate_index_name():
return '{}-{}'.format(ELASTIC_ALIAS, int(datetime.now().timestamp()))
| import aiohttp
import os.path
from datetime import datetime
from aioes import Elasticsearch
from .importer import import_data
from .kudago import KudaGo
from .utils import read_json_file
ELASTIC_ENDPOINTS = ['localhost:9200']
ELASTIC_ALIAS = 'theatrics'
# commands
async def initialize():
elastic = Elasticsearch(ELASTIC_ENDPOINTS)
index_name = await create_new_index(elastic)
await switch_alias_to_index(elastic, ELASTIC_ALIAS, index_name)
async def update(since):
async with aiohttp.ClientSession() as http_client:
elastic = Elasticsearch(ELASTIC_ENDPOINTS)
kudago = KudaGo(http_client)
await import_data(kudago, elastic, ELASTIC_ALIAS, since=since)
# index management
async def create_new_index(elastic):
module_path = os.path.dirname(__file__)
config_filename = os.path.join(module_path, 'configuration', 'index.json')
index_configuration = read_json_file(config_filename)
index_name = generate_index_name()
await elastic.indices.create(index_name, index_configuration)
return index_name
async def switch_alias_to_index(elastic, alias_name, index_name):
existing_aliases = await elastic.indices.get_aliases(name=alias_name)
actions = [{
'add': {
'index': index_name,
'alias': alias_name
}
}]
for existing_index_name in existing_aliases:
actions.append({
'remove': {
'index': existing_index_name,
'alias': alias_name,
}
})
await elastic.indices.update_aliases(actions)
def generate_index_name():
return '{}-{}'.format(ELASTIC_ALIAS, int(datetime.now().timestamp()))
| Remove all previous aliases when initializing | Remove all previous aliases when initializing
| Python | mit | despawnerer/theatrics,despawnerer/theatrics,despawnerer/theatrics | import aiohttp
import os.path
from datetime import datetime
from aioes import Elasticsearch
from .importer import import_data
from .kudago import KudaGo
from .utils import read_json_file
ELASTIC_ENDPOINTS = ['localhost:9200']
ELASTIC_ALIAS = 'theatrics'
+ # commands
+
async def initialize():
elastic = Elasticsearch(ELASTIC_ENDPOINTS)
+ index_name = await create_new_index(elastic)
+ await switch_alias_to_index(elastic, ELASTIC_ALIAS, index_name)
- module_path = os.path.dirname(__file__)
- config_filename = os.path.join(module_path, 'configuration', 'index.json')
- index_configuration = read_json_file(config_filename)
-
- alias_name = ELASTIC_ALIAS
- index_name = generate_index_name()
-
- await elastic.indices.create(index_name, index_configuration)
- await elastic.indices.put_alias(alias_name, index_name)
async def update(since):
async with aiohttp.ClientSession() as http_client:
elastic = Elasticsearch(ELASTIC_ENDPOINTS)
kudago = KudaGo(http_client)
await import_data(kudago, elastic, ELASTIC_ALIAS, since=since)
+ # index management
+
+ async def create_new_index(elastic):
+ module_path = os.path.dirname(__file__)
+ config_filename = os.path.join(module_path, 'configuration', 'index.json')
+ index_configuration = read_json_file(config_filename)
+ index_name = generate_index_name()
+ await elastic.indices.create(index_name, index_configuration)
+ return index_name
+
+
+ async def switch_alias_to_index(elastic, alias_name, index_name):
+ existing_aliases = await elastic.indices.get_aliases(name=alias_name)
+ actions = [{
+ 'add': {
+ 'index': index_name,
+ 'alias': alias_name
+ }
+ }]
+ for existing_index_name in existing_aliases:
+ actions.append({
+ 'remove': {
+ 'index': existing_index_name,
+ 'alias': alias_name,
+ }
+ })
+
+ await elastic.indices.update_aliases(actions)
+
+
def generate_index_name():
return '{}-{}'.format(ELASTIC_ALIAS, int(datetime.now().timestamp()))
| Remove all previous aliases when initializing | ## Code Before:
import aiohttp
import os.path
from datetime import datetime
from aioes import Elasticsearch
from .importer import import_data
from .kudago import KudaGo
from .utils import read_json_file
ELASTIC_ENDPOINTS = ['localhost:9200']
ELASTIC_ALIAS = 'theatrics'
async def initialize():
elastic = Elasticsearch(ELASTIC_ENDPOINTS)
module_path = os.path.dirname(__file__)
config_filename = os.path.join(module_path, 'configuration', 'index.json')
index_configuration = read_json_file(config_filename)
alias_name = ELASTIC_ALIAS
index_name = generate_index_name()
await elastic.indices.create(index_name, index_configuration)
await elastic.indices.put_alias(alias_name, index_name)
async def update(since):
async with aiohttp.ClientSession() as http_client:
elastic = Elasticsearch(ELASTIC_ENDPOINTS)
kudago = KudaGo(http_client)
await import_data(kudago, elastic, ELASTIC_ALIAS, since=since)
def generate_index_name():
return '{}-{}'.format(ELASTIC_ALIAS, int(datetime.now().timestamp()))
## Instruction:
Remove all previous aliases when initializing
## Code After:
import aiohttp
import os.path
from datetime import datetime
from aioes import Elasticsearch
from .importer import import_data
from .kudago import KudaGo
from .utils import read_json_file
ELASTIC_ENDPOINTS = ['localhost:9200']
ELASTIC_ALIAS = 'theatrics'
# commands
async def initialize():
elastic = Elasticsearch(ELASTIC_ENDPOINTS)
index_name = await create_new_index(elastic)
await switch_alias_to_index(elastic, ELASTIC_ALIAS, index_name)
async def update(since):
async with aiohttp.ClientSession() as http_client:
elastic = Elasticsearch(ELASTIC_ENDPOINTS)
kudago = KudaGo(http_client)
await import_data(kudago, elastic, ELASTIC_ALIAS, since=since)
# index management
async def create_new_index(elastic):
module_path = os.path.dirname(__file__)
config_filename = os.path.join(module_path, 'configuration', 'index.json')
index_configuration = read_json_file(config_filename)
index_name = generate_index_name()
await elastic.indices.create(index_name, index_configuration)
return index_name
async def switch_alias_to_index(elastic, alias_name, index_name):
existing_aliases = await elastic.indices.get_aliases(name=alias_name)
actions = [{
'add': {
'index': index_name,
'alias': alias_name
}
}]
for existing_index_name in existing_aliases:
actions.append({
'remove': {
'index': existing_index_name,
'alias': alias_name,
}
})
await elastic.indices.update_aliases(actions)
def generate_index_name():
return '{}-{}'.format(ELASTIC_ALIAS, int(datetime.now().timestamp()))
|
3dd205a9dad39abb12e7a05c178117545402c2e1 | reinforcement-learning/train.py | reinforcement-learning/train.py | """This is the agent which currently takes the action with proper q learning."""
import time
start = time.time()
from tqdm import tqdm
import env
import os
import rl
env.make("text")
episodes = 10000
import argparse
parser = argparse.ArgumentParser(description="Train agent on the falling game.")
parser.add_argument("--remove-file", help="Remove existing q table.", default=True)
parser.add_argument("--episodes", type=str, help="Number of episodes to train for.", default=10000)
args = parser.parse_args()
if args.remove_file == True:
os.remove("q-table.npy")
rl.load_q()
elif args.remove_file == "False":
rl.load_q()
else:
print("Invalid argument.")
quit()
episodes = int(args.episodes)
with tqdm(total=episodes) as pbar:
for episode in range(episodes):
env.reset()
episode_reward = 0
for t in range(100):
episode_reward += env.actual_reward
if env.done:
pbar.update(1)
break
action = rl.choose_action(rl.table[env.object[0]])
rl.q(env.player, action)
episode_reward += env.reward(action)
env.action(action)
env.update()
rl.save_q()
print("Q table:")
print(rl.table[env.object[0]])
| """This is the agent which currently takes the action with proper q learning."""
import time
start = time.time()
from tqdm import tqdm
import env
import os
import rl
env.make("text")
episodes = 10000
import argparse
parser = argparse.ArgumentParser(description="Train agent on the falling game.")
parser.add_argument("--remove-file", help="Remove existing q table.", default=True)
parser.add_argument("--episodes", type=str, help="Number of episodes to train for.", default=10000)
args = parser.parse_args()
if args.remove_file == True:
os.remove("q-table.npy")
rl.load_q()
elif args.remove_file == "False":
rl.load_q()
else:
print("Invalid argument.")
quit()
episodes = int(args.episodes)
with tqdm(total=episodes) as pbar:
for episode in range(episodes):
env.reset()
episode_reward = 0
for t in range(100):
episode_reward += env.actual_reward
if env.done:
pbar.update(1)
break
action = rl.choose_action(env.player, "train")
rl.q(env.player, action)
episode_reward += env.reward(action)
env.action(action)
env.update()
rl.save_q()
print("Q table:")
print(rl.table[env.object[0]])
| Update to newest version of rl.py. | Update to newest version of rl.py.
| Python | mit | danieloconell/Louis | """This is the agent which currently takes the action with proper q learning."""
import time
start = time.time()
from tqdm import tqdm
import env
import os
import rl
env.make("text")
episodes = 10000
import argparse
parser = argparse.ArgumentParser(description="Train agent on the falling game.")
parser.add_argument("--remove-file", help="Remove existing q table.", default=True)
parser.add_argument("--episodes", type=str, help="Number of episodes to train for.", default=10000)
args = parser.parse_args()
if args.remove_file == True:
os.remove("q-table.npy")
rl.load_q()
elif args.remove_file == "False":
rl.load_q()
else:
print("Invalid argument.")
quit()
episodes = int(args.episodes)
with tqdm(total=episodes) as pbar:
for episode in range(episodes):
env.reset()
episode_reward = 0
for t in range(100):
episode_reward += env.actual_reward
if env.done:
pbar.update(1)
break
- action = rl.choose_action(rl.table[env.object[0]])
+ action = rl.choose_action(env.player, "train")
rl.q(env.player, action)
episode_reward += env.reward(action)
env.action(action)
env.update()
rl.save_q()
print("Q table:")
print(rl.table[env.object[0]])
| Update to newest version of rl.py. | ## Code Before:
"""This is the agent which currently takes the action with proper q learning."""
import time
start = time.time()
from tqdm import tqdm
import env
import os
import rl
env.make("text")
episodes = 10000
import argparse
parser = argparse.ArgumentParser(description="Train agent on the falling game.")
parser.add_argument("--remove-file", help="Remove existing q table.", default=True)
parser.add_argument("--episodes", type=str, help="Number of episodes to train for.", default=10000)
args = parser.parse_args()
if args.remove_file == True:
os.remove("q-table.npy")
rl.load_q()
elif args.remove_file == "False":
rl.load_q()
else:
print("Invalid argument.")
quit()
episodes = int(args.episodes)
with tqdm(total=episodes) as pbar:
for episode in range(episodes):
env.reset()
episode_reward = 0
for t in range(100):
episode_reward += env.actual_reward
if env.done:
pbar.update(1)
break
action = rl.choose_action(rl.table[env.object[0]])
rl.q(env.player, action)
episode_reward += env.reward(action)
env.action(action)
env.update()
rl.save_q()
print("Q table:")
print(rl.table[env.object[0]])
## Instruction:
Update to newest version of rl.py.
## Code After:
"""This is the agent which currently takes the action with proper q learning."""
import time
start = time.time()
from tqdm import tqdm
import env
import os
import rl
env.make("text")
episodes = 10000
import argparse
parser = argparse.ArgumentParser(description="Train agent on the falling game.")
parser.add_argument("--remove-file", help="Remove existing q table.", default=True)
parser.add_argument("--episodes", type=str, help="Number of episodes to train for.", default=10000)
args = parser.parse_args()
if args.remove_file == True:
os.remove("q-table.npy")
rl.load_q()
elif args.remove_file == "False":
rl.load_q()
else:
print("Invalid argument.")
quit()
episodes = int(args.episodes)
with tqdm(total=episodes) as pbar:
for episode in range(episodes):
env.reset()
episode_reward = 0
for t in range(100):
episode_reward += env.actual_reward
if env.done:
pbar.update(1)
break
action = rl.choose_action(env.player, "train")
rl.q(env.player, action)
episode_reward += env.reward(action)
env.action(action)
env.update()
rl.save_q()
print("Q table:")
print(rl.table[env.object[0]])
|
f88c2135ddc197283bbfb8b481774deb613571cf | python/raindrops/raindrops.py | python/raindrops/raindrops.py | def raindrops(number):
if is_three_a_factor(number):
return "Pling"
return "{}".format(number)
def is_three_a_factor(number):
return number % 3 == 0
| def raindrops(number):
if is_three_a_factor(number):
return "Pling"
if is_five_a_factor(number):
return "Plang"
return "{}".format(number)
def is_three_a_factor(number):
return number % 3 == 0
def is_five_a_factor(number):
return number % 5 == 0
| Handle 5 as a factor | Handle 5 as a factor
| Python | mit | rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism | def raindrops(number):
if is_three_a_factor(number):
return "Pling"
+ if is_five_a_factor(number):
+ return "Plang"
return "{}".format(number)
def is_three_a_factor(number):
return number % 3 == 0
+ def is_five_a_factor(number):
+ return number % 5 == 0
+ | Handle 5 as a factor | ## Code Before:
def raindrops(number):
if is_three_a_factor(number):
return "Pling"
return "{}".format(number)
def is_three_a_factor(number):
return number % 3 == 0
## Instruction:
Handle 5 as a factor
## Code After:
def raindrops(number):
if is_three_a_factor(number):
return "Pling"
if is_five_a_factor(number):
return "Plang"
return "{}".format(number)
def is_three_a_factor(number):
return number % 3 == 0
def is_five_a_factor(number):
return number % 5 == 0
|
5e5a6a55d43bf66c7f71d054b92a66528bf2a571 | driver/driver.py | driver/driver.py | from abc import ABCMeta, abstractmethod
class Driver(metaclass=ABCMeta):
@abstractmethod
def create(self):
pass
@abstractmethod
def resize(self, id, quota):
pass
@abstractmethod
def clone(self, id):
pass
@abstractmethod
def remove(self, id):
pass
@abstractmethod
def expose(self, id):
pass | from abc import ABCMeta, abstractmethod
class Driver(metaclass=ABCMeta):
@abstractmethod
def create(self, requirements):
pass
@abstractmethod
def _set_quota(self, id, quota):
pass
@abstractmethod
def resize(self, id, quota):
pass
@abstractmethod
def clone(self, id):
pass
@abstractmethod
def remove(self, id):
pass
@abstractmethod
def expose(self, id, host, permissions):
pass
| Fix inconsistency in parameters with base class | Fix inconsistency in parameters with base class
| Python | apache-2.0 | PressLabs/cobalt,PressLabs/cobalt | from abc import ABCMeta, abstractmethod
class Driver(metaclass=ABCMeta):
@abstractmethod
- def create(self):
+ def create(self, requirements):
+ pass
+
+ @abstractmethod
+ def _set_quota(self, id, quota):
pass
@abstractmethod
def resize(self, id, quota):
pass
@abstractmethod
def clone(self, id):
pass
@abstractmethod
def remove(self, id):
pass
@abstractmethod
- def expose(self, id):
+ def expose(self, id, host, permissions):
pass
+ | Fix inconsistency in parameters with base class | ## Code Before:
from abc import ABCMeta, abstractmethod
class Driver(metaclass=ABCMeta):
@abstractmethod
def create(self):
pass
@abstractmethod
def resize(self, id, quota):
pass
@abstractmethod
def clone(self, id):
pass
@abstractmethod
def remove(self, id):
pass
@abstractmethod
def expose(self, id):
pass
## Instruction:
Fix inconsistency in parameters with base class
## Code After:
from abc import ABCMeta, abstractmethod
class Driver(metaclass=ABCMeta):
@abstractmethod
def create(self, requirements):
pass
@abstractmethod
def _set_quota(self, id, quota):
pass
@abstractmethod
def resize(self, id, quota):
pass
@abstractmethod
def clone(self, id):
pass
@abstractmethod
def remove(self, id):
pass
@abstractmethod
def expose(self, id, host, permissions):
pass
|
1fe377ec1957d570a1dcc860c2bda415088bf6be | dwight_chroot/platform_utils.py | dwight_chroot/platform_utils.py | import os
import pwd
import subprocess
from .exceptions import CommandFailed
def get_user_shell():
return pwd.getpwuid(os.getuid()).pw_shell
def execute_command_assert_success(cmd, **kw):
returned = execute_command(cmd, **kw)
if returned.returncode != 0:
raise CommandFailed("Command {0!r} failed with exit code {1}".format(cmd, returned))
return returned
def execute_command(cmd, **kw):
returned = subprocess.Popen(cmd, shell=True, **kw)
returned.wait()
return returned
| import os
import pwd
import subprocess
from .exceptions import CommandFailed
def get_user_shell():
return pwd.getpwuid(os.getuid()).pw_shell
def execute_command_assert_success(cmd, **kw):
returned = execute_command(cmd, **kw)
if returned.returncode != 0:
raise CommandFailed("Command {0!r} failed with exit code {1}".format(cmd, returned.returncode))
return returned
def execute_command(cmd, **kw):
returned = subprocess.Popen(cmd, shell=True, **kw)
returned.wait()
return returned
| Fix execute_command_assert_success return code logging | Fix execute_command_assert_success return code logging
| Python | bsd-3-clause | vmalloc/dwight,vmalloc/dwight,vmalloc/dwight | import os
import pwd
import subprocess
from .exceptions import CommandFailed
def get_user_shell():
return pwd.getpwuid(os.getuid()).pw_shell
def execute_command_assert_success(cmd, **kw):
returned = execute_command(cmd, **kw)
if returned.returncode != 0:
- raise CommandFailed("Command {0!r} failed with exit code {1}".format(cmd, returned))
+ raise CommandFailed("Command {0!r} failed with exit code {1}".format(cmd, returned.returncode))
return returned
def execute_command(cmd, **kw):
returned = subprocess.Popen(cmd, shell=True, **kw)
returned.wait()
return returned
| Fix execute_command_assert_success return code logging | ## Code Before:
import os
import pwd
import subprocess
from .exceptions import CommandFailed
def get_user_shell():
return pwd.getpwuid(os.getuid()).pw_shell
def execute_command_assert_success(cmd, **kw):
returned = execute_command(cmd, **kw)
if returned.returncode != 0:
raise CommandFailed("Command {0!r} failed with exit code {1}".format(cmd, returned))
return returned
def execute_command(cmd, **kw):
returned = subprocess.Popen(cmd, shell=True, **kw)
returned.wait()
return returned
## Instruction:
Fix execute_command_assert_success return code logging
## Code After:
import os
import pwd
import subprocess
from .exceptions import CommandFailed
def get_user_shell():
return pwd.getpwuid(os.getuid()).pw_shell
def execute_command_assert_success(cmd, **kw):
returned = execute_command(cmd, **kw)
if returned.returncode != 0:
raise CommandFailed("Command {0!r} failed with exit code {1}".format(cmd, returned.returncode))
return returned
def execute_command(cmd, **kw):
returned = subprocess.Popen(cmd, shell=True, **kw)
returned.wait()
return returned
|
b1c5f75c266f5f5b9976ce2ca7c2b9065ef41bb1 | groupmestats/generatestats.py | groupmestats/generatestats.py | import argparse
import webbrowser
from .groupserializer import GroupSerializer
from .statistic import all_statistics
from .statistics import *
def gstat_stats():
parser = argparse.ArgumentParser(description="Generates stats for a group")
parser.add_argument("-g", "--group", dest="group_name", required=True,
help="Group to generate stats for.")
parser.add_argument("-s", "--stat", dest="stats", default=[],
action="append",
help=("Name of stat to generate. This may be specified"
" more than once. Choices: %s "
% ", ".join(all_statistics.keys())))
parser.add_argument("--all-stats", action="store_true", default=False,
help="Generate all possible stats.")
parser.add_argument("--ignore-user", dest="ignore_users", default=[],
action="append",
help="User to ignore. May be specified more than once.")
args = parser.parse_args()
stats = [stat_class() for name, stat_class in all_statistics.items()
if args.all_stats or name in args.stats]
if not stats:
parser.print_help()
raise RuntimeError("Must specify a valid --stat or use --all-stats")
(group, messages) = GroupSerializer.load(args.group_name)
for stat in stats:
stat.calculate(group, messages, ignore_users=args.ignore_users)
for stat in stats:
output_html_filename = stat.show()
try:
# webbrowser.open_new_tab(output_html_filename)
pass
except:
pass
| import argparse
import webbrowser
from .groupserializer import GroupSerializer
from .statistic import all_statistics
from .statistics import *
def gstat_stats():
parser = argparse.ArgumentParser(description="Generates stats for a group")
parser.add_argument("-g", "--group", dest="group_name", required=True,
help="Group to generate stats for.")
parser.add_argument("-s", "--stat", dest="stats", default=[],
action="append",
help=("Name of stat to generate. This may be specified"
" more than once. Choices: %s "
% ", ".join(all_statistics.keys())))
parser.add_argument("--all-stats", action="store_true", default=False,
help="Generate all possible stats.")
parser.add_argument("--ignore-user", dest="ignore_users", default=[],
action="append",
help="User to ignore. May be specified more than once.")
args = parser.parse_args()
stats = [stat_class() for name, stat_class in all_statistics.items()
if args.all_stats or name in args.stats]
print("args: %s" % str(args))
if not stats:
parser.print_help()
raise RuntimeError("Must specify a valid --stat or use --all-stats")
(group, messages) = GroupSerializer.load(args.group_name)
for stat in stats:
stat.calculate(group, messages, ignore_users=args.ignore_users)
for stat in stats:
output_html_filename = stat.show()
try:
# webbrowser.open_new_tab(output_html_filename)
pass
except:
pass
| Print args when generating stats | Print args when generating stats
| Python | mit | kjteske/groupmestats,kjteske/groupmestats | import argparse
import webbrowser
from .groupserializer import GroupSerializer
from .statistic import all_statistics
from .statistics import *
def gstat_stats():
parser = argparse.ArgumentParser(description="Generates stats for a group")
parser.add_argument("-g", "--group", dest="group_name", required=True,
help="Group to generate stats for.")
parser.add_argument("-s", "--stat", dest="stats", default=[],
action="append",
help=("Name of stat to generate. This may be specified"
" more than once. Choices: %s "
% ", ".join(all_statistics.keys())))
parser.add_argument("--all-stats", action="store_true", default=False,
help="Generate all possible stats.")
parser.add_argument("--ignore-user", dest="ignore_users", default=[],
action="append",
help="User to ignore. May be specified more than once.")
args = parser.parse_args()
stats = [stat_class() for name, stat_class in all_statistics.items()
if args.all_stats or name in args.stats]
+
+ print("args: %s" % str(args))
if not stats:
parser.print_help()
raise RuntimeError("Must specify a valid --stat or use --all-stats")
(group, messages) = GroupSerializer.load(args.group_name)
for stat in stats:
stat.calculate(group, messages, ignore_users=args.ignore_users)
for stat in stats:
output_html_filename = stat.show()
try:
# webbrowser.open_new_tab(output_html_filename)
pass
except:
pass
| Print args when generating stats | ## Code Before:
import argparse
import webbrowser
from .groupserializer import GroupSerializer
from .statistic import all_statistics
from .statistics import *
def gstat_stats():
parser = argparse.ArgumentParser(description="Generates stats for a group")
parser.add_argument("-g", "--group", dest="group_name", required=True,
help="Group to generate stats for.")
parser.add_argument("-s", "--stat", dest="stats", default=[],
action="append",
help=("Name of stat to generate. This may be specified"
" more than once. Choices: %s "
% ", ".join(all_statistics.keys())))
parser.add_argument("--all-stats", action="store_true", default=False,
help="Generate all possible stats.")
parser.add_argument("--ignore-user", dest="ignore_users", default=[],
action="append",
help="User to ignore. May be specified more than once.")
args = parser.parse_args()
stats = [stat_class() for name, stat_class in all_statistics.items()
if args.all_stats or name in args.stats]
if not stats:
parser.print_help()
raise RuntimeError("Must specify a valid --stat or use --all-stats")
(group, messages) = GroupSerializer.load(args.group_name)
for stat in stats:
stat.calculate(group, messages, ignore_users=args.ignore_users)
for stat in stats:
output_html_filename = stat.show()
try:
# webbrowser.open_new_tab(output_html_filename)
pass
except:
pass
## Instruction:
Print args when generating stats
## Code After:
import argparse
import webbrowser
from .groupserializer import GroupSerializer
from .statistic import all_statistics
from .statistics import *
def gstat_stats():
parser = argparse.ArgumentParser(description="Generates stats for a group")
parser.add_argument("-g", "--group", dest="group_name", required=True,
help="Group to generate stats for.")
parser.add_argument("-s", "--stat", dest="stats", default=[],
action="append",
help=("Name of stat to generate. This may be specified"
" more than once. Choices: %s "
% ", ".join(all_statistics.keys())))
parser.add_argument("--all-stats", action="store_true", default=False,
help="Generate all possible stats.")
parser.add_argument("--ignore-user", dest="ignore_users", default=[],
action="append",
help="User to ignore. May be specified more than once.")
args = parser.parse_args()
stats = [stat_class() for name, stat_class in all_statistics.items()
if args.all_stats or name in args.stats]
print("args: %s" % str(args))
if not stats:
parser.print_help()
raise RuntimeError("Must specify a valid --stat or use --all-stats")
(group, messages) = GroupSerializer.load(args.group_name)
for stat in stats:
stat.calculate(group, messages, ignore_users=args.ignore_users)
for stat in stats:
output_html_filename = stat.show()
try:
# webbrowser.open_new_tab(output_html_filename)
pass
except:
pass
|
7b7f33439b16faeef67022374cf88ba9a275ce8a | flocker/filesystems/interfaces.py | flocker/filesystems/interfaces.py |
from __future__ import absolute_import
from zope.interface import Interface
class IFilesystemSnapshots(Interface):
"""
Support creating and listing snapshots of a specific filesystem.
"""
def create(name):
"""
Create a snapshot of the filesystem.
:param name: The name of the snapshot.
:type name: :py:class:`flocker.snapshots.SnapshotName`
:return: Deferred that fires on snapshot creation, or errbacks if
snapshotting failed. The Deferred should support cancellation
if at all possible.
"""
def list():
"""
Return all the filesystem's snapshots.
:return: Deferred that fires with a ``list`` of
:py:class:`flocker.snapshots.SnapshotName`. This will likely be
improved in later iterations.
"""
|
from __future__ import absolute_import
from zope.interface import Interface
class IFilesystemSnapshots(Interface):
"""
Support creating and listing snapshots of a specific filesystem.
"""
def create(name):
"""
Create a snapshot of the filesystem.
:param name: The name of the snapshot.
:type name: :py:class:`flocker.snapshots.SnapshotName`
:return: Deferred that fires on snapshot creation, or errbacks if
snapshotting failed. The Deferred should support cancellation
if at all possible.
"""
def list():
"""
Return all the filesystem's snapshots.
:return: Deferred that fires with a ``list`` of
:py:class:`flocker.snapshots.SnapshotName`.
"""
| Address review comment: Don't state the obvious. | Address review comment: Don't state the obvious.
| Python | apache-2.0 | LaynePeng/flocker,agonzalezro/flocker,AndyHuu/flocker,achanda/flocker,jml/flocker,AndyHuu/flocker,lukemarsden/flocker,mbrukman/flocker,runcom/flocker,Azulinho/flocker,jml/flocker,mbrukman/flocker,w4ngyi/flocker,hackday-profilers/flocker,achanda/flocker,lukemarsden/flocker,achanda/flocker,beni55/flocker,lukemarsden/flocker,beni55/flocker,Azulinho/flocker,mbrukman/flocker,hackday-profilers/flocker,moypray/flocker,AndyHuu/flocker,LaynePeng/flocker,moypray/flocker,adamtheturtle/flocker,w4ngyi/flocker,1d4Nf6/flocker,agonzalezro/flocker,Azulinho/flocker,wallnerryan/flocker-profiles,adamtheturtle/flocker,adamtheturtle/flocker,LaynePeng/flocker,beni55/flocker,moypray/flocker,runcom/flocker,jml/flocker,hackday-profilers/flocker,agonzalezro/flocker,runcom/flocker,wallnerryan/flocker-profiles,1d4Nf6/flocker,1d4Nf6/flocker,wallnerryan/flocker-profiles,w4ngyi/flocker |
from __future__ import absolute_import
from zope.interface import Interface
class IFilesystemSnapshots(Interface):
"""
Support creating and listing snapshots of a specific filesystem.
"""
def create(name):
"""
Create a snapshot of the filesystem.
:param name: The name of the snapshot.
:type name: :py:class:`flocker.snapshots.SnapshotName`
:return: Deferred that fires on snapshot creation, or errbacks if
snapshotting failed. The Deferred should support cancellation
if at all possible.
"""
def list():
"""
Return all the filesystem's snapshots.
:return: Deferred that fires with a ``list`` of
- :py:class:`flocker.snapshots.SnapshotName`. This will likely be
+ :py:class:`flocker.snapshots.SnapshotName`.
- improved in later iterations.
"""
| Address review comment: Don't state the obvious. | ## Code Before:
from __future__ import absolute_import
from zope.interface import Interface
class IFilesystemSnapshots(Interface):
"""
Support creating and listing snapshots of a specific filesystem.
"""
def create(name):
"""
Create a snapshot of the filesystem.
:param name: The name of the snapshot.
:type name: :py:class:`flocker.snapshots.SnapshotName`
:return: Deferred that fires on snapshot creation, or errbacks if
snapshotting failed. The Deferred should support cancellation
if at all possible.
"""
def list():
"""
Return all the filesystem's snapshots.
:return: Deferred that fires with a ``list`` of
:py:class:`flocker.snapshots.SnapshotName`. This will likely be
improved in later iterations.
"""
## Instruction:
Address review comment: Don't state the obvious.
## Code After:
from __future__ import absolute_import
from zope.interface import Interface
class IFilesystemSnapshots(Interface):
"""
Support creating and listing snapshots of a specific filesystem.
"""
def create(name):
"""
Create a snapshot of the filesystem.
:param name: The name of the snapshot.
:type name: :py:class:`flocker.snapshots.SnapshotName`
:return: Deferred that fires on snapshot creation, or errbacks if
snapshotting failed. The Deferred should support cancellation
if at all possible.
"""
def list():
"""
Return all the filesystem's snapshots.
:return: Deferred that fires with a ``list`` of
:py:class:`flocker.snapshots.SnapshotName`.
"""
|
df51d042bf1958f48fc39f1f3870285c87491243 | lemon/templatetags/main_menu.py | lemon/templatetags/main_menu.py | from django.template import Library, Variable
from django.template import TemplateSyntaxError, VariableDoesNotExist
from django.template.defaulttags import URLNode
from ..models import MenuItem
from ..settings import CONFIG
register = Library()
class MainMenuItemURLNode(URLNode):
def __init__(self, content_type):
self.content_type = Variable(content_type)
self.args = ()
self.kwargs = {}
self.asvar = False
self.legacy_view_name = True
def render(self, context):
try:
content_type = self.content_type.resolve(context)
opts = content_type.model_class()._meta
app_label = opts.app_label
module_name = opts.module_name
self.view_name = 'admin:%s_%s_changelist' % \
(app_label, module_name)
except VariableDoesNotExist:
return ''
return super(MainMenuItemURLNode, self).render(context)
@register.inclusion_tag('lemon/main_menu.html')
def main_menu():
queryset = MenuItem.objects.select_related('section', 'content_type')
queryset = queryset.order_by('section__position', 'position')
return {'menu_items': queryset, 'menu_links': CONFIG['MENU_LINKS']}
@register.tag
def main_menu_item_url(parser, token):
try:
tag_name, content_type = token.split_contents()
except ValueError:
raise TemplateSyntaxError(
'%r tag requiresa single argument' % token.contents.split()[0]
)
return MainMenuItemURLNode(content_type)
| from django.core.urlresolvers import reverse, NoReverseMatch
from django.template import Library, Variable, Node
from django.template import TemplateSyntaxError, VariableDoesNotExist
from django.template.defaulttags import URLNode
from ..models import MenuItem
from ..settings import CONFIG
register = Library()
class MainMenuItemURLNode(Node):
def __init__(self, content_type):
self.content_type = Variable(content_type)
def render(self, context):
try:
content_type = self.content_type.resolve(context)
except VariableDoesNotExist:
return ''
opts = content_type.model_class()._meta
app_label = opts.app_label
module_name = opts.module_name
view_name = 'admin:%s_%s_changelist' % \
(app_label, module_name)
try:
return reverse(view_name)
except NoReverseMatch:
return ''
@register.inclusion_tag('lemon/main_menu.html')
def main_menu():
queryset = MenuItem.objects.select_related('section', 'content_type')
queryset = queryset.order_by('section__position', 'position')
return {'menu_items': queryset, 'menu_links': CONFIG['MENU_LINKS']}
@register.tag
def main_menu_item_url(parser, token):
try:
tag_name, content_type = token.split_contents()
except ValueError:
raise TemplateSyntaxError(
'%r tag requires a single argument' % token.contents.split()[0]
)
return MainMenuItemURLNode(content_type)
| Fix main menu url reversing in admin | Fix main menu url reversing in admin
| Python | bsd-3-clause | trilan/lemon,trilan/lemon,trilan/lemon | + from django.core.urlresolvers import reverse, NoReverseMatch
- from django.template import Library, Variable
+ from django.template import Library, Variable, Node
from django.template import TemplateSyntaxError, VariableDoesNotExist
from django.template.defaulttags import URLNode
from ..models import MenuItem
from ..settings import CONFIG
register = Library()
- class MainMenuItemURLNode(URLNode):
+ class MainMenuItemURLNode(Node):
def __init__(self, content_type):
self.content_type = Variable(content_type)
- self.args = ()
- self.kwargs = {}
- self.asvar = False
- self.legacy_view_name = True
def render(self, context):
try:
content_type = self.content_type.resolve(context)
- opts = content_type.model_class()._meta
- app_label = opts.app_label
- module_name = opts.module_name
- self.view_name = 'admin:%s_%s_changelist' % \
- (app_label, module_name)
except VariableDoesNotExist:
return ''
- return super(MainMenuItemURLNode, self).render(context)
+ opts = content_type.model_class()._meta
+ app_label = opts.app_label
+ module_name = opts.module_name
+ view_name = 'admin:%s_%s_changelist' % \
+ (app_label, module_name)
+ try:
+ return reverse(view_name)
+ except NoReverseMatch:
+ return ''
@register.inclusion_tag('lemon/main_menu.html')
def main_menu():
queryset = MenuItem.objects.select_related('section', 'content_type')
queryset = queryset.order_by('section__position', 'position')
return {'menu_items': queryset, 'menu_links': CONFIG['MENU_LINKS']}
@register.tag
def main_menu_item_url(parser, token):
try:
tag_name, content_type = token.split_contents()
except ValueError:
raise TemplateSyntaxError(
- '%r tag requiresa single argument' % token.contents.split()[0]
+ '%r tag requires a single argument' % token.contents.split()[0]
)
return MainMenuItemURLNode(content_type)
| Fix main menu url reversing in admin | ## Code Before:
from django.template import Library, Variable
from django.template import TemplateSyntaxError, VariableDoesNotExist
from django.template.defaulttags import URLNode
from ..models import MenuItem
from ..settings import CONFIG
register = Library()
class MainMenuItemURLNode(URLNode):
def __init__(self, content_type):
self.content_type = Variable(content_type)
self.args = ()
self.kwargs = {}
self.asvar = False
self.legacy_view_name = True
def render(self, context):
try:
content_type = self.content_type.resolve(context)
opts = content_type.model_class()._meta
app_label = opts.app_label
module_name = opts.module_name
self.view_name = 'admin:%s_%s_changelist' % \
(app_label, module_name)
except VariableDoesNotExist:
return ''
return super(MainMenuItemURLNode, self).render(context)
@register.inclusion_tag('lemon/main_menu.html')
def main_menu():
queryset = MenuItem.objects.select_related('section', 'content_type')
queryset = queryset.order_by('section__position', 'position')
return {'menu_items': queryset, 'menu_links': CONFIG['MENU_LINKS']}
@register.tag
def main_menu_item_url(parser, token):
try:
tag_name, content_type = token.split_contents()
except ValueError:
raise TemplateSyntaxError(
'%r tag requiresa single argument' % token.contents.split()[0]
)
return MainMenuItemURLNode(content_type)
## Instruction:
Fix main menu url reversing in admin
## Code After:
from django.core.urlresolvers import reverse, NoReverseMatch
from django.template import Library, Variable, Node
from django.template import TemplateSyntaxError, VariableDoesNotExist
from django.template.defaulttags import URLNode
from ..models import MenuItem
from ..settings import CONFIG
register = Library()
class MainMenuItemURLNode(Node):
def __init__(self, content_type):
self.content_type = Variable(content_type)
def render(self, context):
try:
content_type = self.content_type.resolve(context)
except VariableDoesNotExist:
return ''
opts = content_type.model_class()._meta
app_label = opts.app_label
module_name = opts.module_name
view_name = 'admin:%s_%s_changelist' % \
(app_label, module_name)
try:
return reverse(view_name)
except NoReverseMatch:
return ''
@register.inclusion_tag('lemon/main_menu.html')
def main_menu():
queryset = MenuItem.objects.select_related('section', 'content_type')
queryset = queryset.order_by('section__position', 'position')
return {'menu_items': queryset, 'menu_links': CONFIG['MENU_LINKS']}
@register.tag
def main_menu_item_url(parser, token):
try:
tag_name, content_type = token.split_contents()
except ValueError:
raise TemplateSyntaxError(
'%r tag requires a single argument' % token.contents.split()[0]
)
return MainMenuItemURLNode(content_type)
|
28786f30be37bb43a175262f96b618fc440d5ace | send-email.py | send-email.py |
import datetime
import os
import sys
import smtplib
from email.mime.text import MIMEText
def timeString():
return str(datetime.datetime.now())
if not os.path.exists('email-list'):
print(timeString(), ':\tERROR: email-list not found.', sep='')
quit(1)
if not os.path.exists('credentials'):
print(timeString(), ':\tERROR: credentials not found.', sep='')
quit(1)
with open('credentials', 'r') as _file:
_lines = [str(e).strip('\n') for e in _file]
server = _lines[0]
port = _lines[1]
username = _lines[2]
password = _lines[3]
with open('new-products.html', 'r') as _file:
_message = _file.read()
with open('email-list', 'r') as _file:
recipients = [e.strip('\n') for e in _file]
session=smtplib.SMTP(server, port)
session.ehlo()
session.starttls()
session.login(username, password)
for message_to in recipients:
msg = MIMEText(_message, 'html')
msg['To'] = message_to
msg['From'] = username
msg['Subject'] = 'ALERT: New Cymbals detected on mycymbal.com'
msg = msg.as_string()
session.sendmail(username, message_to, msg)
print(timeString(), ':\tEmailed ', message_to, sep='')
session.quit()
|
import datetime
import os
import sys
import smtplib
from email.mime.text import MIMEText
def timeString():
return str(datetime.datetime.now())
if not os.path.exists('email-list'):
print(timeString(), ':\tERROR: email-list not found.', sep='')
quit(1)
if not os.path.exists('credentials'):
print(timeString(), ':\tERROR: credentials not found.', sep='')
quit(1)
with open('credentials', 'r') as _file:
_lines = [str(e).strip('\n') for e in _file]
server = _lines[0]
port = _lines[1]
username = _lines[2]
password = _lines[3]
with open('new-products.html', 'r') as _file:
_message = _file.read()
with open('email-list', 'r') as _file:
recipients = [e.strip('\n') for e in _file]
session=smtplib.SMTP(server, port)
session.ehlo()
session.starttls()
session.login(username, password)
for message_to in recipients:
msg = MIMEText(_message, 'html')
msg['To'] = message_to
msg['From'] = username
msg['Subject'] = 'MyCymbal Digest'
msg = msg.as_string()
session.sendmail(username, message_to, msg)
print(timeString(), ':\tEmailed ', message_to, sep='')
session.quit()
| Change email subject. Not much of an ALERT if it happens every day. | Change email subject. Not much of an ALERT if it happens every day.
| Python | unlicense | nerflad/mds-new-products,nerflad/mds-new-products,nerflad/mds-new-products |
import datetime
import os
import sys
import smtplib
from email.mime.text import MIMEText
def timeString():
return str(datetime.datetime.now())
if not os.path.exists('email-list'):
print(timeString(), ':\tERROR: email-list not found.', sep='')
quit(1)
if not os.path.exists('credentials'):
print(timeString(), ':\tERROR: credentials not found.', sep='')
quit(1)
with open('credentials', 'r') as _file:
_lines = [str(e).strip('\n') for e in _file]
server = _lines[0]
port = _lines[1]
username = _lines[2]
password = _lines[3]
with open('new-products.html', 'r') as _file:
_message = _file.read()
with open('email-list', 'r') as _file:
recipients = [e.strip('\n') for e in _file]
session=smtplib.SMTP(server, port)
session.ehlo()
session.starttls()
session.login(username, password)
for message_to in recipients:
msg = MIMEText(_message, 'html')
msg['To'] = message_to
msg['From'] = username
- msg['Subject'] = 'ALERT: New Cymbals detected on mycymbal.com'
+ msg['Subject'] = 'MyCymbal Digest'
msg = msg.as_string()
session.sendmail(username, message_to, msg)
print(timeString(), ':\tEmailed ', message_to, sep='')
session.quit()
| Change email subject. Not much of an ALERT if it happens every day. | ## Code Before:
import datetime
import os
import sys
import smtplib
from email.mime.text import MIMEText
def timeString():
return str(datetime.datetime.now())
if not os.path.exists('email-list'):
print(timeString(), ':\tERROR: email-list not found.', sep='')
quit(1)
if not os.path.exists('credentials'):
print(timeString(), ':\tERROR: credentials not found.', sep='')
quit(1)
with open('credentials', 'r') as _file:
_lines = [str(e).strip('\n') for e in _file]
server = _lines[0]
port = _lines[1]
username = _lines[2]
password = _lines[3]
with open('new-products.html', 'r') as _file:
_message = _file.read()
with open('email-list', 'r') as _file:
recipients = [e.strip('\n') for e in _file]
session=smtplib.SMTP(server, port)
session.ehlo()
session.starttls()
session.login(username, password)
for message_to in recipients:
msg = MIMEText(_message, 'html')
msg['To'] = message_to
msg['From'] = username
msg['Subject'] = 'ALERT: New Cymbals detected on mycymbal.com'
msg = msg.as_string()
session.sendmail(username, message_to, msg)
print(timeString(), ':\tEmailed ', message_to, sep='')
session.quit()
## Instruction:
Change email subject. Not much of an ALERT if it happens every day.
## Code After:
import datetime
import os
import sys
import smtplib
from email.mime.text import MIMEText
def timeString():
return str(datetime.datetime.now())
if not os.path.exists('email-list'):
print(timeString(), ':\tERROR: email-list not found.', sep='')
quit(1)
if not os.path.exists('credentials'):
print(timeString(), ':\tERROR: credentials not found.', sep='')
quit(1)
with open('credentials', 'r') as _file:
_lines = [str(e).strip('\n') for e in _file]
server = _lines[0]
port = _lines[1]
username = _lines[2]
password = _lines[3]
with open('new-products.html', 'r') as _file:
_message = _file.read()
with open('email-list', 'r') as _file:
recipients = [e.strip('\n') for e in _file]
session=smtplib.SMTP(server, port)
session.ehlo()
session.starttls()
session.login(username, password)
for message_to in recipients:
msg = MIMEText(_message, 'html')
msg['To'] = message_to
msg['From'] = username
msg['Subject'] = 'MyCymbal Digest'
msg = msg.as_string()
session.sendmail(username, message_to, msg)
print(timeString(), ':\tEmailed ', message_to, sep='')
session.quit()
|
400c506627deca5d85454928254b1968e09dc33e | scrape.py | scrape.py | import scholarly
import requests
_EXACT_SEARCH = '/scholar?q="{}"'
_START_YEAR = '&as_ylo={}'
_END_YEAR = '&as_yhi={}'
def search(query, exact=True, start_year=None, end_year=None):
"""Search by scholar query and return a generator of Publication objects"""
url = _EXACT_SEARCH.format(requests.utils.quote(query))
if start_year:
url += _START_YEAR.format(start_year)
if end_year:
url += _END_YEAR.format(end_year)
soup = scholarly._get_soup(url)
return scholarly._search_scholar_soup(soup)
if __name__ == '__main__':
s = search("Cure Alzheimer's Fund", start_year=2015, end_year=2015)
num = 0
for x in s:
x.fill()
stuff = ['title', 'author', 'journal', 'volume', 'issue']
for thing in stuff:
if thing in x.bib:
print("{}: {}".format(thing, x.bib[thing]))
num += 1
print("Number of results:", num)
| import re
import requests
import scholarly
_EXACT_SEARCH = '/scholar?q="{}"'
_START_YEAR = '&as_ylo={}'
_END_YEAR = '&as_yhi={}'
class Papers(object):
"""Wrapper around scholarly._search_scholar_soup that allows one to get the
number of papers found in the search with len()"""
def __init__(self, query, start_year=None, end_year=None):
url = _EXACT_SEARCH.format(requests.utils.quote(query))
if start_year:
url += _START_YEAR.format(start_year)
if end_year:
url += _END_YEAR.format(end_year)
soup = scholarly._get_soup(url)
results = soup.find('div', id='gs_ab_md').text
self.num = int(re.search(r'\d+ results', results).group(0).split()[0])
self.papers = scholarly._search_scholar_soup(soup)
def __len__(self):
return self.num
def __iter__(self):
return (paper.fill().bib for paper in self.papers)
def get_published_papers():
""" Returns a generator that returns dicts with paper metadata."""
return Papers("Cure Alzheimer's Fund", start_year=2015, end_year=2015)
def main():
papers = get_published_papers()
print("Number of results:", len(papers))
for paper in papers:
stuff = ['title', 'author', 'journal', 'volume', 'issue']
for thing in stuff:
if thing in paper:
print("{}: {}".format(thing, paper[thing]))
if __name__ == '__main__':
main()
| Allow getting number of results found with len() | Allow getting number of results found with len()
| Python | mit | Spferical/cure-alzheimers-fund-tracker,Spferical/cure-alzheimers-fund-tracker,Spferical/cure-alzheimers-fund-tracker | + import re
+ import requests
import scholarly
- import requests
_EXACT_SEARCH = '/scholar?q="{}"'
_START_YEAR = '&as_ylo={}'
_END_YEAR = '&as_yhi={}'
- def search(query, exact=True, start_year=None, end_year=None):
- """Search by scholar query and return a generator of Publication objects"""
+
+
+ class Papers(object):
+ """Wrapper around scholarly._search_scholar_soup that allows one to get the
+ number of papers found in the search with len()"""
+ def __init__(self, query, start_year=None, end_year=None):
- url = _EXACT_SEARCH.format(requests.utils.quote(query))
+ url = _EXACT_SEARCH.format(requests.utils.quote(query))
- if start_year:
+ if start_year:
- url += _START_YEAR.format(start_year)
+ url += _START_YEAR.format(start_year)
- if end_year:
+ if end_year:
- url += _END_YEAR.format(end_year)
+ url += _END_YEAR.format(end_year)
- soup = scholarly._get_soup(url)
+ soup = scholarly._get_soup(url)
+ results = soup.find('div', id='gs_ab_md').text
+ self.num = int(re.search(r'\d+ results', results).group(0).split()[0])
+
- return scholarly._search_scholar_soup(soup)
+ self.papers = scholarly._search_scholar_soup(soup)
+
+ def __len__(self):
+ return self.num
+
+ def __iter__(self):
+ return (paper.fill().bib for paper in self.papers)
+
+
+ def get_published_papers():
+ """ Returns a generator that returns dicts with paper metadata."""
+ return Papers("Cure Alzheimer's Fund", start_year=2015, end_year=2015)
+
+
+ def main():
+ papers = get_published_papers()
+ print("Number of results:", len(papers))
+ for paper in papers:
+ stuff = ['title', 'author', 'journal', 'volume', 'issue']
+ for thing in stuff:
+ if thing in paper:
+ print("{}: {}".format(thing, paper[thing]))
if __name__ == '__main__':
+ main()
- s = search("Cure Alzheimer's Fund", start_year=2015, end_year=2015)
- num = 0
- for x in s:
- x.fill()
- stuff = ['title', 'author', 'journal', 'volume', 'issue']
- for thing in stuff:
- if thing in x.bib:
- print("{}: {}".format(thing, x.bib[thing]))
- num += 1
- print("Number of results:", num)
| Allow getting number of results found with len() | ## Code Before:
import scholarly
import requests
_EXACT_SEARCH = '/scholar?q="{}"'
_START_YEAR = '&as_ylo={}'
_END_YEAR = '&as_yhi={}'
def search(query, exact=True, start_year=None, end_year=None):
"""Search by scholar query and return a generator of Publication objects"""
url = _EXACT_SEARCH.format(requests.utils.quote(query))
if start_year:
url += _START_YEAR.format(start_year)
if end_year:
url += _END_YEAR.format(end_year)
soup = scholarly._get_soup(url)
return scholarly._search_scholar_soup(soup)
if __name__ == '__main__':
s = search("Cure Alzheimer's Fund", start_year=2015, end_year=2015)
num = 0
for x in s:
x.fill()
stuff = ['title', 'author', 'journal', 'volume', 'issue']
for thing in stuff:
if thing in x.bib:
print("{}: {}".format(thing, x.bib[thing]))
num += 1
print("Number of results:", num)
## Instruction:
Allow getting number of results found with len()
## Code After:
import re
import requests
import scholarly
_EXACT_SEARCH = '/scholar?q="{}"'
_START_YEAR = '&as_ylo={}'
_END_YEAR = '&as_yhi={}'
class Papers(object):
"""Wrapper around scholarly._search_scholar_soup that allows one to get the
number of papers found in the search with len()"""
def __init__(self, query, start_year=None, end_year=None):
url = _EXACT_SEARCH.format(requests.utils.quote(query))
if start_year:
url += _START_YEAR.format(start_year)
if end_year:
url += _END_YEAR.format(end_year)
soup = scholarly._get_soup(url)
results = soup.find('div', id='gs_ab_md').text
self.num = int(re.search(r'\d+ results', results).group(0).split()[0])
self.papers = scholarly._search_scholar_soup(soup)
def __len__(self):
return self.num
def __iter__(self):
return (paper.fill().bib for paper in self.papers)
def get_published_papers():
""" Returns a generator that returns dicts with paper metadata."""
return Papers("Cure Alzheimer's Fund", start_year=2015, end_year=2015)
def main():
papers = get_published_papers()
print("Number of results:", len(papers))
for paper in papers:
stuff = ['title', 'author', 'journal', 'volume', 'issue']
for thing in stuff:
if thing in paper:
print("{}: {}".format(thing, paper[thing]))
if __name__ == '__main__':
main()
|
2e9cb250d58474354bdfff1edb4fc9e71ee95d60 | lightbus/utilities/importing.py | lightbus/utilities/importing.py | import importlib
import logging
from typing import Sequence, Tuple, Callable
import pkg_resources
logger = logging.getLogger(__name__)
def import_module_from_string(name):
return importlib.import_module(name)
def import_from_string(name):
components = name.split(".")
mod = __import__(components[0])
for comp in components[1:]:
mod = getattr(mod, comp)
return mod
def load_entrypoint_classes(entrypoint_name) -> Sequence[Tuple[str, str, Callable]]:
"""Load classes specified in an entrypoint
Entrypoints are specified in setup.py, and Lightbus uses them to
discover plugins & transports.
"""
found_classes = []
for entrypoint in pkg_resources.iter_entry_points(entrypoint_name):
class_ = entrypoint.load()
found_classes.append((entrypoint.module_name, entrypoint.name, class_))
return found_classes
| import importlib
import logging
import sys
from typing import Sequence, Tuple, Callable
import pkg_resources
logger = logging.getLogger(__name__)
def import_module_from_string(name):
if name in sys.modules:
return sys.modules[name]
else:
return importlib.import_module(name)
def import_from_string(name):
components = name.split(".")
mod = __import__(components[0])
for comp in components[1:]:
mod = getattr(mod, comp)
return mod
def load_entrypoint_classes(entrypoint_name) -> Sequence[Tuple[str, str, Callable]]:
"""Load classes specified in an entrypoint
Entrypoints are specified in setup.py, and Lightbus uses them to
discover plugins & transports.
"""
found_classes = []
for entrypoint in pkg_resources.iter_entry_points(entrypoint_name):
class_ = entrypoint.load()
found_classes.append((entrypoint.module_name, entrypoint.name, class_))
return found_classes
| Fix to import_module_from_string() to prevent multiple imports | Fix to import_module_from_string() to prevent multiple imports
| Python | apache-2.0 | adamcharnock/lightbus | import importlib
import logging
+ import sys
from typing import Sequence, Tuple, Callable
import pkg_resources
logger = logging.getLogger(__name__)
def import_module_from_string(name):
+ if name in sys.modules:
+ return sys.modules[name]
+ else:
- return importlib.import_module(name)
+ return importlib.import_module(name)
def import_from_string(name):
components = name.split(".")
mod = __import__(components[0])
for comp in components[1:]:
mod = getattr(mod, comp)
return mod
def load_entrypoint_classes(entrypoint_name) -> Sequence[Tuple[str, str, Callable]]:
"""Load classes specified in an entrypoint
Entrypoints are specified in setup.py, and Lightbus uses them to
discover plugins & transports.
"""
found_classes = []
for entrypoint in pkg_resources.iter_entry_points(entrypoint_name):
class_ = entrypoint.load()
found_classes.append((entrypoint.module_name, entrypoint.name, class_))
return found_classes
| Fix to import_module_from_string() to prevent multiple imports | ## Code Before:
import importlib
import logging
from typing import Sequence, Tuple, Callable
import pkg_resources
logger = logging.getLogger(__name__)
def import_module_from_string(name):
return importlib.import_module(name)
def import_from_string(name):
components = name.split(".")
mod = __import__(components[0])
for comp in components[1:]:
mod = getattr(mod, comp)
return mod
def load_entrypoint_classes(entrypoint_name) -> Sequence[Tuple[str, str, Callable]]:
"""Load classes specified in an entrypoint
Entrypoints are specified in setup.py, and Lightbus uses them to
discover plugins & transports.
"""
found_classes = []
for entrypoint in pkg_resources.iter_entry_points(entrypoint_name):
class_ = entrypoint.load()
found_classes.append((entrypoint.module_name, entrypoint.name, class_))
return found_classes
## Instruction:
Fix to import_module_from_string() to prevent multiple imports
## Code After:
import importlib
import logging
import sys
from typing import Sequence, Tuple, Callable
import pkg_resources
logger = logging.getLogger(__name__)
def import_module_from_string(name):
if name in sys.modules:
return sys.modules[name]
else:
return importlib.import_module(name)
def import_from_string(name):
components = name.split(".")
mod = __import__(components[0])
for comp in components[1:]:
mod = getattr(mod, comp)
return mod
def load_entrypoint_classes(entrypoint_name) -> Sequence[Tuple[str, str, Callable]]:
"""Load classes specified in an entrypoint
Entrypoints are specified in setup.py, and Lightbus uses them to
discover plugins & transports.
"""
found_classes = []
for entrypoint in pkg_resources.iter_entry_points(entrypoint_name):
class_ = entrypoint.load()
found_classes.append((entrypoint.module_name, entrypoint.name, class_))
return found_classes
|
b74c56b3999800917946378f20288407347710e6 | social/backends/gae.py | social/backends/gae.py | from __future__ import absolute_import
from google.appengine.api import users
from social.backends.base import BaseAuth
from social.exceptions import AuthException
class GoogleAppEngineAuth(BaseAuth):
"""GoogleAppengine authentication backend"""
name = 'google-appengine'
def get_user_id(self, details, response):
"""Return current user id."""
user = users.get_current_user()
if user:
return user.user_id()
def get_user_details(self, response):
"""Return user basic information (id and email only)."""
user = users.get_current_user()
return {'username': user.user_id(),
'email': user.email(),
'fullname': '',
'first_name': '',
'last_name': ''}
def auth_url(self):
"""Build and return complete URL."""
return users.create_login_url(self.redirect_uri)
def auth_complete(self, *args, **kwargs):
"""Completes login process, must return user instance."""
if not users.get_current_user():
raise AuthException('Authentication error')
kwargs.update({'response': '', 'backend': self})
return self.strategy.authenticate(*args, **kwargs)
BACKENDS = {
'gae': GoogleAppEngineAuth
}
| from __future__ import absolute_import
from google.appengine.api import users
from social.backends.base import BaseAuth
from social.exceptions import AuthException
class GoogleAppEngineAuth(BaseAuth):
"""GoogleAppengine authentication backend"""
name = 'google-appengine'
def get_user_id(self, details, response):
"""Return current user id."""
user = users.get_current_user()
if user:
return user.user_id()
def get_user_details(self, response):
"""Return user basic information (id and email only)."""
user = users.get_current_user()
return {'username': user.user_id(),
'email': user.email(),
'fullname': '',
'first_name': '',
'last_name': ''}
def auth_url(self):
"""Build and return complete URL."""
return users.create_login_url(self.redirect_uri)
def auth_complete(self, *args, **kwargs):
"""Completes login process, must return user instance."""
if not users.get_current_user():
raise AuthException('Authentication error')
kwargs.update({'response': '', 'backend': self})
return self.strategy.authenticate(*args, **kwargs)
BACKENDS = {
'google-appengine': GoogleAppEngineAuth
}
| Rename to be consistent with backend name | Rename to be consistent with backend name
| Python | bsd-3-clause | ononeor12/python-social-auth,barseghyanartur/python-social-auth,tutumcloud/python-social-auth,webjunkie/python-social-auth,cmichal/python-social-auth,henocdz/python-social-auth,mchdks/python-social-auth,falcon1kr/python-social-auth,cmichal/python-social-auth,contracode/python-social-auth,SeanHayes/python-social-auth,VishvajitP/python-social-auth,robbiet480/python-social-auth,duoduo369/python-social-auth,lamby/python-social-auth,mrwags/python-social-auth,tkajtoch/python-social-auth,nirmalvp/python-social-auth,mchdks/python-social-auth,JerzySpendel/python-social-auth,henocdz/python-social-auth,rsteca/python-social-auth,joelstanner/python-social-auth,mark-adams/python-social-auth,frankier/python-social-auth,mathspace/python-social-auth,ByteInternet/python-social-auth,drxos/python-social-auth,mathspace/python-social-auth,msampathkumar/python-social-auth,yprez/python-social-auth,frankier/python-social-auth,yprez/python-social-auth,VishvajitP/python-social-auth,SeanHayes/python-social-auth,python-social-auth/social-app-django,firstjob/python-social-auth,ononeor12/python-social-auth,falcon1kr/python-social-auth,michael-borisov/python-social-auth,tkajtoch/python-social-auth,JJediny/python-social-auth,ariestiyansyah/python-social-auth,jameslittle/python-social-auth,clef/python-social-auth,chandolia/python-social-auth,bjorand/python-social-auth,S01780/python-social-auth,mrwags/python-social-auth,muhammad-ammar/python-social-auth,jneves/python-social-auth,daniula/python-social-auth,cmichal/python-social-auth,wildtetris/python-social-auth,jneves/python-social-auth,bjorand/python-social-auth,contracode/python-social-auth,ByteInternet/python-social-auth,cjltsod/python-social-auth,S01780/python-social-auth,barseghyanartur/python-social-auth,daniula/python-social-auth,lneoe/python-social-auth,muhammad-ammar/python-social-auth,Andygmb/python-social-auth,webjunkie/python-social-auth,muhammad-ammar/python-social-auth,DhiaEddineSaidi/python-social-auth,garrett-schlesinger/python-social-auth,python-social-auth/social-storage-sqlalchemy,JJediny/python-social-auth,jameslittle/python-social-auth,JerzySpendel/python-social-auth,fearlessspider/python-social-auth,tobias47n9e/social-core,ononeor12/python-social-auth,msampathkumar/python-social-auth,henocdz/python-social-auth,san-mate/python-social-auth,jneves/python-social-auth,daniula/python-social-auth,mark-adams/python-social-auth,garrett-schlesinger/python-social-auth,iruga090/python-social-auth,wildtetris/python-social-auth,MSOpenTech/python-social-auth,alrusdi/python-social-auth,merutak/python-social-auth,lamby/python-social-auth,ariestiyansyah/python-social-auth,lneoe/python-social-auth,VishvajitP/python-social-auth,degs098/python-social-auth,imsparsh/python-social-auth,nvbn/python-social-auth,rsteca/python-social-auth,degs098/python-social-auth,JJediny/python-social-auth,cjltsod/python-social-auth,rsalmaso/python-social-auth,michael-borisov/python-social-auth,tkajtoch/python-social-auth,barseghyanartur/python-social-auth,tutumcloud/python-social-auth,robbiet480/python-social-auth,noodle-learns-programming/python-social-auth,falcon1kr/python-social-auth,jameslittle/python-social-auth,jeyraof/python-social-auth,san-mate/python-social-auth,python-social-auth/social-app-django,rsteca/python-social-auth,lamby/python-social-auth,chandolia/python-social-auth,imsparsh/python-social-auth,jeyraof/python-social-auth,Andygmb/python-social-auth,iruga090/python-social-auth,iruga090/python-social-auth,noodle-learns-programming/python-social-auth,msampathkumar/python-social-auth,clef/python-social-auth,fearlessspider/python-social-auth,JerzySpendel/python-social-auth,hsr-ba-fs15-dat/python-social-auth,chandolia/python-social-auth,hsr-ba-fs15-dat/python-social-auth,DhiaEddineSaidi/python-social-auth,python-social-auth/social-core,rsalmaso/python-social-auth,robbiet480/python-social-auth,python-social-auth/social-docs,python-social-auth/social-app-cherrypy,drxos/python-social-auth,MSOpenTech/python-social-auth,firstjob/python-social-auth,contracode/python-social-auth,fearlessspider/python-social-auth,duoduo369/python-social-auth,alrusdi/python-social-auth,alrusdi/python-social-auth,mrwags/python-social-auth,mathspace/python-social-auth,hsr-ba-fs15-dat/python-social-auth,degs098/python-social-auth,python-social-auth/social-core,joelstanner/python-social-auth,webjunkie/python-social-auth,jeyraof/python-social-auth,san-mate/python-social-auth,clef/python-social-auth,Andygmb/python-social-auth,lawrence34/python-social-auth,drxos/python-social-auth,imsparsh/python-social-auth,michael-borisov/python-social-auth,noodle-learns-programming/python-social-auth,python-social-auth/social-app-django,lawrence34/python-social-auth,merutak/python-social-auth,DhiaEddineSaidi/python-social-auth,nirmalvp/python-social-auth,ariestiyansyah/python-social-auth,bjorand/python-social-auth,MSOpenTech/python-social-auth,yprez/python-social-auth,lawrence34/python-social-auth,ByteInternet/python-social-auth,nirmalvp/python-social-auth,nvbn/python-social-auth,lneoe/python-social-auth,S01780/python-social-auth,mark-adams/python-social-auth,firstjob/python-social-auth,joelstanner/python-social-auth,merutak/python-social-auth,mchdks/python-social-auth,wildtetris/python-social-auth | from __future__ import absolute_import
from google.appengine.api import users
from social.backends.base import BaseAuth
from social.exceptions import AuthException
class GoogleAppEngineAuth(BaseAuth):
"""GoogleAppengine authentication backend"""
name = 'google-appengine'
def get_user_id(self, details, response):
"""Return current user id."""
user = users.get_current_user()
if user:
return user.user_id()
def get_user_details(self, response):
"""Return user basic information (id and email only)."""
user = users.get_current_user()
return {'username': user.user_id(),
'email': user.email(),
'fullname': '',
'first_name': '',
'last_name': ''}
def auth_url(self):
"""Build and return complete URL."""
return users.create_login_url(self.redirect_uri)
def auth_complete(self, *args, **kwargs):
"""Completes login process, must return user instance."""
if not users.get_current_user():
raise AuthException('Authentication error')
kwargs.update({'response': '', 'backend': self})
return self.strategy.authenticate(*args, **kwargs)
BACKENDS = {
- 'gae': GoogleAppEngineAuth
+ 'google-appengine': GoogleAppEngineAuth
}
| Rename to be consistent with backend name | ## Code Before:
from __future__ import absolute_import
from google.appengine.api import users
from social.backends.base import BaseAuth
from social.exceptions import AuthException
class GoogleAppEngineAuth(BaseAuth):
"""GoogleAppengine authentication backend"""
name = 'google-appengine'
def get_user_id(self, details, response):
"""Return current user id."""
user = users.get_current_user()
if user:
return user.user_id()
def get_user_details(self, response):
"""Return user basic information (id and email only)."""
user = users.get_current_user()
return {'username': user.user_id(),
'email': user.email(),
'fullname': '',
'first_name': '',
'last_name': ''}
def auth_url(self):
"""Build and return complete URL."""
return users.create_login_url(self.redirect_uri)
def auth_complete(self, *args, **kwargs):
"""Completes login process, must return user instance."""
if not users.get_current_user():
raise AuthException('Authentication error')
kwargs.update({'response': '', 'backend': self})
return self.strategy.authenticate(*args, **kwargs)
BACKENDS = {
'gae': GoogleAppEngineAuth
}
## Instruction:
Rename to be consistent with backend name
## Code After:
from __future__ import absolute_import
from google.appengine.api import users
from social.backends.base import BaseAuth
from social.exceptions import AuthException
class GoogleAppEngineAuth(BaseAuth):
"""GoogleAppengine authentication backend"""
name = 'google-appengine'
def get_user_id(self, details, response):
"""Return current user id."""
user = users.get_current_user()
if user:
return user.user_id()
def get_user_details(self, response):
"""Return user basic information (id and email only)."""
user = users.get_current_user()
return {'username': user.user_id(),
'email': user.email(),
'fullname': '',
'first_name': '',
'last_name': ''}
def auth_url(self):
"""Build and return complete URL."""
return users.create_login_url(self.redirect_uri)
def auth_complete(self, *args, **kwargs):
"""Completes login process, must return user instance."""
if not users.get_current_user():
raise AuthException('Authentication error')
kwargs.update({'response': '', 'backend': self})
return self.strategy.authenticate(*args, **kwargs)
BACKENDS = {
'google-appengine': GoogleAppEngineAuth
}
|
b78c457d52702beb5067eb7c3067cb69af5e935d | itunes/exceptions.py | itunes/exceptions.py |
class ITunesError(Exception):
"""
Base exception class for iTunes interface.
"""
pass
class AppleScriptError(ITunesError):
"""
Represents an error received from AppleScript while running a script.
Parameters
----------
message : str
The message that the exception will hold.
script : str
The AppleScript that was running when this exception was raised (default
"").
Attributes
----------
script : str
The AppleScript that was running when this exception was raised, if one
was provided.
"""
def __init__(self, message, script=""):
super(AppleScriptError, self).__init__(message)
self.script = script
|
class ITunesError(Exception):
"""
Base exception class for iTunes interface.
"""
pass
class AppleScriptError(ITunesError):
"""
Represents an error received from AppleScript while running a script.
Parameters
----------
message : str
The message that the exception will hold.
script : str
The AppleScript that was running when this exception was raised (default
"").
Attributes
----------
script : str
The AppleScript that was running when this exception was raised, if one
was provided.
"""
def __init__(self, message, script=""):
super(AppleScriptError, self).__init__(message)
self.script = script
class TrackError(ITunesError):
"""
Represents an error in finding or playing a track.
Parameters
----------
message : str
The message that the exception will hold.
title : str
The title of the track that caused the error (default "").
Attributes
----------
title : str
The title of the track that caused the error.
"""
def __init__(self, message, title=""):
super(TrackError, self).__init__(message)
self.title = title
| Add custom exception for track-related errors | Add custom exception for track-related errors
The new exception type (`TrackError`) will be used when a track cannot
be played or found.
| Python | mit | adanoff/iTunesTUI |
class ITunesError(Exception):
"""
Base exception class for iTunes interface.
"""
pass
class AppleScriptError(ITunesError):
"""
Represents an error received from AppleScript while running a script.
Parameters
----------
message : str
The message that the exception will hold.
script : str
The AppleScript that was running when this exception was raised (default
"").
Attributes
----------
script : str
The AppleScript that was running when this exception was raised, if one
was provided.
"""
def __init__(self, message, script=""):
super(AppleScriptError, self).__init__(message)
self.script = script
+ class TrackError(ITunesError):
+ """
+ Represents an error in finding or playing a track.
+
+ Parameters
+ ----------
+ message : str
+ The message that the exception will hold.
+ title : str
+ The title of the track that caused the error (default "").
+
+ Attributes
+ ----------
+ title : str
+ The title of the track that caused the error.
+ """
+
+ def __init__(self, message, title=""):
+
+ super(TrackError, self).__init__(message)
+ self.title = title
+ | Add custom exception for track-related errors | ## Code Before:
class ITunesError(Exception):
"""
Base exception class for iTunes interface.
"""
pass
class AppleScriptError(ITunesError):
"""
Represents an error received from AppleScript while running a script.
Parameters
----------
message : str
The message that the exception will hold.
script : str
The AppleScript that was running when this exception was raised (default
"").
Attributes
----------
script : str
The AppleScript that was running when this exception was raised, if one
was provided.
"""
def __init__(self, message, script=""):
super(AppleScriptError, self).__init__(message)
self.script = script
## Instruction:
Add custom exception for track-related errors
## Code After:
class ITunesError(Exception):
"""
Base exception class for iTunes interface.
"""
pass
class AppleScriptError(ITunesError):
"""
Represents an error received from AppleScript while running a script.
Parameters
----------
message : str
The message that the exception will hold.
script : str
The AppleScript that was running when this exception was raised (default
"").
Attributes
----------
script : str
The AppleScript that was running when this exception was raised, if one
was provided.
"""
def __init__(self, message, script=""):
super(AppleScriptError, self).__init__(message)
self.script = script
class TrackError(ITunesError):
"""
Represents an error in finding or playing a track.
Parameters
----------
message : str
The message that the exception will hold.
title : str
The title of the track that caused the error (default "").
Attributes
----------
title : str
The title of the track that caused the error.
"""
def __init__(self, message, title=""):
super(TrackError, self).__init__(message)
self.title = title
|
b339c25068e849dbbf769f22893125b15325eb66 | figgypy/utils.py | figgypy/utils.py | import os
def env_or_default(var, default=None):
"""Get environment variable or provide default.
Args:
var (str): environment variable to search for
default (optional(str)): default to return
"""
if var in os.environ:
return os.environ[var]
return default
| from __future__ import unicode_literals
from future.utils import bytes_to_native_str as n
from base64 import b64encode
import os
import boto3
def env_or_default(var, default=None):
"""Get environment variable or provide default.
Args:
var (str): environment variable to search for
default (optional(str)): default to return
"""
if var in os.environ:
return os.environ[var]
return default
def kms_encrypt(value, key, aws_config=None):
"""Encrypt and value with KMS key.
Args:
value (str): value to encrypt
key (str): key id or alias
aws_config (optional[dict]): aws credentials
dict of arguments passed into boto3 session
example:
aws_creds = {'aws_access_key_id': aws_access_key_id,
'aws_secret_access_key': aws_secret_access_key,
'region_name': 'us-east-1'}
Returns:
str: encrypted cipher text
"""
aws_config = aws_config or {}
aws = boto3.session.Session(**aws_config)
client = aws.client('kms')
enc_res = client.encrypt(KeyId=key,
Plaintext=value)
return n(b64encode(enc_res['CiphertextBlob']))
| Add new helper function to encrypt for KMS | Add new helper function to encrypt for KMS
| Python | mit | theherk/figgypy | + from __future__ import unicode_literals
+ from future.utils import bytes_to_native_str as n
+
+ from base64 import b64encode
import os
+
+ import boto3
def env_or_default(var, default=None):
"""Get environment variable or provide default.
Args:
var (str): environment variable to search for
default (optional(str)): default to return
"""
if var in os.environ:
return os.environ[var]
return default
+
+ def kms_encrypt(value, key, aws_config=None):
+ """Encrypt and value with KMS key.
+
+ Args:
+ value (str): value to encrypt
+ key (str): key id or alias
+ aws_config (optional[dict]): aws credentials
+ dict of arguments passed into boto3 session
+ example:
+ aws_creds = {'aws_access_key_id': aws_access_key_id,
+ 'aws_secret_access_key': aws_secret_access_key,
+ 'region_name': 'us-east-1'}
+
+ Returns:
+ str: encrypted cipher text
+ """
+ aws_config = aws_config or {}
+ aws = boto3.session.Session(**aws_config)
+ client = aws.client('kms')
+ enc_res = client.encrypt(KeyId=key,
+ Plaintext=value)
+ return n(b64encode(enc_res['CiphertextBlob']))
+ | Add new helper function to encrypt for KMS | ## Code Before:
import os
def env_or_default(var, default=None):
"""Get environment variable or provide default.
Args:
var (str): environment variable to search for
default (optional(str)): default to return
"""
if var in os.environ:
return os.environ[var]
return default
## Instruction:
Add new helper function to encrypt for KMS
## Code After:
from __future__ import unicode_literals
from future.utils import bytes_to_native_str as n
from base64 import b64encode
import os
import boto3
def env_or_default(var, default=None):
"""Get environment variable or provide default.
Args:
var (str): environment variable to search for
default (optional(str)): default to return
"""
if var in os.environ:
return os.environ[var]
return default
def kms_encrypt(value, key, aws_config=None):
"""Encrypt and value with KMS key.
Args:
value (str): value to encrypt
key (str): key id or alias
aws_config (optional[dict]): aws credentials
dict of arguments passed into boto3 session
example:
aws_creds = {'aws_access_key_id': aws_access_key_id,
'aws_secret_access_key': aws_secret_access_key,
'region_name': 'us-east-1'}
Returns:
str: encrypted cipher text
"""
aws_config = aws_config or {}
aws = boto3.session.Session(**aws_config)
client = aws.client('kms')
enc_res = client.encrypt(KeyId=key,
Plaintext=value)
return n(b64encode(enc_res['CiphertextBlob']))
|
0f4ca12e524be7cbd82ac79e81a62015b47ca6ef | openfisca_core/tests/formula_helpers.py | openfisca_core/tests/formula_helpers.py |
import numpy
from nose.tools import raises
from openfisca_core.formula_helpers import apply_threshold as apply_threshold
from openfisca_core.tools import assert_near
@raises(AssertionError)
def test_apply_threshold_with_too_many_thresholds():
input = numpy.array([10])
thresholds = [5]
outputs = [10]
return apply_threshold(input, thresholds, outputs)
@raises(AssertionError)
def test_apply_threshold_with_too_few_thresholds():
input = numpy.array([10])
thresholds = [5]
outputs = [10, 15, 20]
return apply_threshold(input, thresholds, outputs)
def test_apply_threshold():
input = numpy.array([4, 5, 6, 7, 8])
thresholds = [5, 7]
outputs = [10, 15, 20]
result = apply_threshold(input, thresholds, outputs)
assert_near(result, [10, 10, 15, 15, 20])
|
import numpy
from nose.tools import raises
from openfisca_core.formula_helpers import apply_threshold as apply_threshold
from openfisca_core.tools import assert_near
@raises(AssertionError)
def test_apply_threshold_with_too_many_thresholds():
input = numpy.array([10])
thresholds = [5]
outputs = [10]
return apply_threshold(input, thresholds, outputs)
@raises(AssertionError)
def test_apply_threshold_with_too_few_thresholds():
input = numpy.array([10])
thresholds = [5]
outputs = [10, 15, 20]
return apply_threshold(input, thresholds, outputs)
def test_apply_threshold():
input = numpy.array([4, 5, 6, 7, 8])
thresholds = [5, 7]
outputs = [10, 15, 20]
result = apply_threshold(input, thresholds, outputs)
assert_near(result, [10, 10, 15, 15, 20])
def test_apply_threshold_with_variable_threshold():
input = numpy.array([1000, 1000, 1000])
thresholds = [numpy.array([500, 1500, 1000])] # Only one thresold, but varies with the person
outputs = [True, False] # True if input <= threshold, false otherwise
result = apply_threshold(input, thresholds, outputs)
assert_near(result, [False, True, True])
| Add more tricky case test for apply_threshold | Add more tricky case test for apply_threshold
| Python | agpl-3.0 | benjello/openfisca-core,openfisca/openfisca-core,benjello/openfisca-core,sgmap/openfisca-core,openfisca/openfisca-core |
import numpy
from nose.tools import raises
from openfisca_core.formula_helpers import apply_threshold as apply_threshold
from openfisca_core.tools import assert_near
@raises(AssertionError)
def test_apply_threshold_with_too_many_thresholds():
input = numpy.array([10])
thresholds = [5]
outputs = [10]
return apply_threshold(input, thresholds, outputs)
@raises(AssertionError)
def test_apply_threshold_with_too_few_thresholds():
input = numpy.array([10])
thresholds = [5]
outputs = [10, 15, 20]
return apply_threshold(input, thresholds, outputs)
def test_apply_threshold():
input = numpy.array([4, 5, 6, 7, 8])
thresholds = [5, 7]
outputs = [10, 15, 20]
result = apply_threshold(input, thresholds, outputs)
assert_near(result, [10, 10, 15, 15, 20])
+ def test_apply_threshold_with_variable_threshold():
+ input = numpy.array([1000, 1000, 1000])
+ thresholds = [numpy.array([500, 1500, 1000])] # Only one thresold, but varies with the person
+ outputs = [True, False] # True if input <= threshold, false otherwise
+ result = apply_threshold(input, thresholds, outputs)
+ assert_near(result, [False, True, True])
+ | Add more tricky case test for apply_threshold | ## Code Before:
import numpy
from nose.tools import raises
from openfisca_core.formula_helpers import apply_threshold as apply_threshold
from openfisca_core.tools import assert_near
@raises(AssertionError)
def test_apply_threshold_with_too_many_thresholds():
input = numpy.array([10])
thresholds = [5]
outputs = [10]
return apply_threshold(input, thresholds, outputs)
@raises(AssertionError)
def test_apply_threshold_with_too_few_thresholds():
input = numpy.array([10])
thresholds = [5]
outputs = [10, 15, 20]
return apply_threshold(input, thresholds, outputs)
def test_apply_threshold():
input = numpy.array([4, 5, 6, 7, 8])
thresholds = [5, 7]
outputs = [10, 15, 20]
result = apply_threshold(input, thresholds, outputs)
assert_near(result, [10, 10, 15, 15, 20])
## Instruction:
Add more tricky case test for apply_threshold
## Code After:
import numpy
from nose.tools import raises
from openfisca_core.formula_helpers import apply_threshold as apply_threshold
from openfisca_core.tools import assert_near
@raises(AssertionError)
def test_apply_threshold_with_too_many_thresholds():
input = numpy.array([10])
thresholds = [5]
outputs = [10]
return apply_threshold(input, thresholds, outputs)
@raises(AssertionError)
def test_apply_threshold_with_too_few_thresholds():
input = numpy.array([10])
thresholds = [5]
outputs = [10, 15, 20]
return apply_threshold(input, thresholds, outputs)
def test_apply_threshold():
input = numpy.array([4, 5, 6, 7, 8])
thresholds = [5, 7]
outputs = [10, 15, 20]
result = apply_threshold(input, thresholds, outputs)
assert_near(result, [10, 10, 15, 15, 20])
def test_apply_threshold_with_variable_threshold():
input = numpy.array([1000, 1000, 1000])
thresholds = [numpy.array([500, 1500, 1000])] # Only one thresold, but varies with the person
outputs = [True, False] # True if input <= threshold, false otherwise
result = apply_threshold(input, thresholds, outputs)
assert_near(result, [False, True, True])
|
342e6134a63c5b575ae8e4348a54f61350bca2da | parser/crimeparser/pipelinesEnricher.py | parser/crimeparser/pipelinesEnricher.py | from geopy import Nominatim
from geopy.extra.rate_limiter import RateLimiter
class GeoCodePipeline(object):
def open_spider(self, spider):
geolocator = Nominatim(timeout=5)
self.__geocodeFunc = RateLimiter(geolocator.geocode, min_delay_seconds=2)
def process_item(self, item, spider):
for crime in item["crimes"]:
place = crime["place"]
latitude, longitude = self.__geocode_address(place)
crime["latitude"] = latitude
crime["longitude"] = longitude
return item
def __geocode_address(self, place):
if place is None:
return None, None
location = self.__geocodeFunc(place)
if location is not None:
return location.latitude, location.longitude
else:
return None, None
| from geopy import Nominatim, Photon
from geopy.extra.rate_limiter import RateLimiter
class GeoCodePipeline(object):
def open_spider(self, spider):
geolocator = Photon(timeout=5)
self.__geocodeFunc = RateLimiter(geolocator.geocode, min_delay_seconds=2)
def process_item(self, item, spider):
for crime in item["crimes"]:
place = crime["place"]
latitude, longitude = self.__geocode_address(place)
crime["latitude"] = latitude
crime["longitude"] = longitude
return item
def __geocode_address(self, place):
if place is None:
return None, None
location = self.__geocodeFunc(place)
if location is not None:
return location.latitude, location.longitude
else:
return None, None
| Use Phonon instead of Nominatim for geo coding | Use Phonon instead of Nominatim for geo coding
Phonon is more fault tolerant to spelling mistakes.
| Python | mit | aberklotz/crimereport,aberklotz/crimereport,aberklotz/crimereport | - from geopy import Nominatim
+ from geopy import Nominatim, Photon
from geopy.extra.rate_limiter import RateLimiter
class GeoCodePipeline(object):
def open_spider(self, spider):
- geolocator = Nominatim(timeout=5)
+ geolocator = Photon(timeout=5)
self.__geocodeFunc = RateLimiter(geolocator.geocode, min_delay_seconds=2)
def process_item(self, item, spider):
for crime in item["crimes"]:
place = crime["place"]
latitude, longitude = self.__geocode_address(place)
crime["latitude"] = latitude
crime["longitude"] = longitude
return item
def __geocode_address(self, place):
if place is None:
return None, None
location = self.__geocodeFunc(place)
if location is not None:
return location.latitude, location.longitude
else:
return None, None
| Use Phonon instead of Nominatim for geo coding | ## Code Before:
from geopy import Nominatim
from geopy.extra.rate_limiter import RateLimiter
class GeoCodePipeline(object):
def open_spider(self, spider):
geolocator = Nominatim(timeout=5)
self.__geocodeFunc = RateLimiter(geolocator.geocode, min_delay_seconds=2)
def process_item(self, item, spider):
for crime in item["crimes"]:
place = crime["place"]
latitude, longitude = self.__geocode_address(place)
crime["latitude"] = latitude
crime["longitude"] = longitude
return item
def __geocode_address(self, place):
if place is None:
return None, None
location = self.__geocodeFunc(place)
if location is not None:
return location.latitude, location.longitude
else:
return None, None
## Instruction:
Use Phonon instead of Nominatim for geo coding
## Code After:
from geopy import Nominatim, Photon
from geopy.extra.rate_limiter import RateLimiter
class GeoCodePipeline(object):
def open_spider(self, spider):
geolocator = Photon(timeout=5)
self.__geocodeFunc = RateLimiter(geolocator.geocode, min_delay_seconds=2)
def process_item(self, item, spider):
for crime in item["crimes"]:
place = crime["place"]
latitude, longitude = self.__geocode_address(place)
crime["latitude"] = latitude
crime["longitude"] = longitude
return item
def __geocode_address(self, place):
if place is None:
return None, None
location = self.__geocodeFunc(place)
if location is not None:
return location.latitude, location.longitude
else:
return None, None
|