commit
stringlengths
40
40
old_file
stringlengths
4
118
new_file
stringlengths
4
118
old_contents
stringlengths
10
3.52k
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
7
43k
ndiff
stringlengths
52
3.32k
instruction
stringlengths
16
444
content
stringlengths
133
4.32k
fuzzy_diff
stringlengths
17
3.24k
1cc892fd521ae33b1d492004411db3f1392295c4
enhydris/telemetry/tasks.py
enhydris/telemetry/tasks.py
from django.core.cache import cache from celery.utils.log import get_task_logger from enhydris.celery import app from enhydris.telemetry.models import Telemetry FETCH_TIMEOUT = 300 LOCK_TIMEOUT = FETCH_TIMEOUT + 60 logger = get_task_logger(__name__) @app.task def fetch_all_telemetry_data(): for telemetry in Telemetry.objects.all(): if True: fetch_telemetry_data.delay(telemetry.id) @app.task(bind=True, soft_time_limit=FETCH_TIMEOUT, time_limit=FETCH_TIMEOUT + 10) def fetch_telemetry_data(self, telemetry_id): telemetry = Telemetry.objects.get(id=telemetry_id) lock_id = f"telemetry-{telemetry_id}" acquired_lock = cache.add(lock_id, self.app.oid, LOCK_TIMEOUT) if acquired_lock: telemetry.fetch() cache.delete(lock_id) else: lock_owner = cache.get(lock_id) logger.error( f"Cannot acquire lock for fetching telemetry with id={telemetry.id}; " f"apparently the lock is owned by {lock_owner}." )
from django.core.cache import cache from celery.utils.log import get_task_logger from enhydris.celery import app from enhydris.telemetry.models import Telemetry FETCH_TIMEOUT = 300 LOCK_TIMEOUT = FETCH_TIMEOUT + 60 logger = get_task_logger(__name__) @app.task def fetch_all_telemetry_data(): for telemetry in Telemetry.objects.all(): if telemetry.is_due: fetch_telemetry_data.delay(telemetry.id) @app.task(bind=True, soft_time_limit=FETCH_TIMEOUT, time_limit=FETCH_TIMEOUT + 10) def fetch_telemetry_data(self, telemetry_id): telemetry = Telemetry.objects.get(id=telemetry_id) lock_id = f"telemetry-{telemetry_id}" acquired_lock = cache.add(lock_id, self.app.oid, LOCK_TIMEOUT) if acquired_lock: telemetry.fetch() cache.delete(lock_id) else: lock_owner = cache.get(lock_id) logger.error( f"Cannot acquire lock for fetching telemetry with id={telemetry.id}; " f"apparently the lock is owned by {lock_owner}." )
Fix error in telemetry task
Fix error in telemetry task A condition had been changed to always match for debugging purposes, and was accidentally committed that way.
Python
agpl-3.0
openmeteo/enhydris,openmeteo/enhydris,openmeteo/enhydris,aptiko/enhydris,aptiko/enhydris,aptiko/enhydris
from django.core.cache import cache from celery.utils.log import get_task_logger from enhydris.celery import app from enhydris.telemetry.models import Telemetry FETCH_TIMEOUT = 300 LOCK_TIMEOUT = FETCH_TIMEOUT + 60 logger = get_task_logger(__name__) @app.task def fetch_all_telemetry_data(): for telemetry in Telemetry.objects.all(): - if True: + if telemetry.is_due: fetch_telemetry_data.delay(telemetry.id) @app.task(bind=True, soft_time_limit=FETCH_TIMEOUT, time_limit=FETCH_TIMEOUT + 10) def fetch_telemetry_data(self, telemetry_id): telemetry = Telemetry.objects.get(id=telemetry_id) lock_id = f"telemetry-{telemetry_id}" acquired_lock = cache.add(lock_id, self.app.oid, LOCK_TIMEOUT) if acquired_lock: telemetry.fetch() cache.delete(lock_id) else: lock_owner = cache.get(lock_id) logger.error( f"Cannot acquire lock for fetching telemetry with id={telemetry.id}; " f"apparently the lock is owned by {lock_owner}." )
Fix error in telemetry task
## Code Before: from django.core.cache import cache from celery.utils.log import get_task_logger from enhydris.celery import app from enhydris.telemetry.models import Telemetry FETCH_TIMEOUT = 300 LOCK_TIMEOUT = FETCH_TIMEOUT + 60 logger = get_task_logger(__name__) @app.task def fetch_all_telemetry_data(): for telemetry in Telemetry.objects.all(): if True: fetch_telemetry_data.delay(telemetry.id) @app.task(bind=True, soft_time_limit=FETCH_TIMEOUT, time_limit=FETCH_TIMEOUT + 10) def fetch_telemetry_data(self, telemetry_id): telemetry = Telemetry.objects.get(id=telemetry_id) lock_id = f"telemetry-{telemetry_id}" acquired_lock = cache.add(lock_id, self.app.oid, LOCK_TIMEOUT) if acquired_lock: telemetry.fetch() cache.delete(lock_id) else: lock_owner = cache.get(lock_id) logger.error( f"Cannot acquire lock for fetching telemetry with id={telemetry.id}; " f"apparently the lock is owned by {lock_owner}." ) ## Instruction: Fix error in telemetry task ## Code After: from django.core.cache import cache from celery.utils.log import get_task_logger from enhydris.celery import app from enhydris.telemetry.models import Telemetry FETCH_TIMEOUT = 300 LOCK_TIMEOUT = FETCH_TIMEOUT + 60 logger = get_task_logger(__name__) @app.task def fetch_all_telemetry_data(): for telemetry in Telemetry.objects.all(): if telemetry.is_due: fetch_telemetry_data.delay(telemetry.id) @app.task(bind=True, soft_time_limit=FETCH_TIMEOUT, time_limit=FETCH_TIMEOUT + 10) def fetch_telemetry_data(self, telemetry_id): telemetry = Telemetry.objects.get(id=telemetry_id) lock_id = f"telemetry-{telemetry_id}" acquired_lock = cache.add(lock_id, self.app.oid, LOCK_TIMEOUT) if acquired_lock: telemetry.fetch() cache.delete(lock_id) else: lock_owner = cache.get(lock_id) logger.error( f"Cannot acquire lock for fetching telemetry with id={telemetry.id}; " f"apparently the lock is owned by {lock_owner}." )
... def fetch_all_telemetry_data(): for telemetry in Telemetry.objects.all(): if telemetry.is_due: fetch_telemetry_data.delay(telemetry.id) ...
c32bdff4b0ee570ed58cd869830d89e3251cf82a
pytils/test/__init__.py
pytils/test/__init__.py
__all__ = ["test_numeral", "test_dt", "test_translit", "test_utils", "test_typo"] import unittest def get_django_suite(): try: import django except ImportError: return unittest.TestSuite() import pytils.test.templatetags return pytils.test.templatetags.get_suite() def get_suite(): """Return TestSuite for all unit-test of pytils""" suite = unittest.TestSuite() for module_name in __all__: imported_module = __import__("pytils.test."+module_name, globals(), locals(), ["pytils.test"]) loader = unittest.defaultTestLoader suite.addTest(loader.loadTestsFromModule(imported_module)) suite.addTest(get_django_suite()) return suite def run_tests_from_module(module, verbosity=1): """Run unit-tests for single module""" suite = unittest.TestSuite() loader = unittest.defaultTestLoader suite.addTest(loader.loadTestsFromModule(module)) unittest.TextTestRunner(verbosity=verbosity).run(suite) def run(verbosity=1): """Run all unit-test of pytils""" suite = get_suite() unittest.TextTestRunner(verbosity=verbosity).run(suite) if __name__ == '__main__': run(2)
__all__ = ["test_numeral", "test_dt", "test_translit", "test_utils", "test_typo"] import unittest import sys def get_django_suite(): try: import django except ImportError: return unittest.TestSuite() import pytils.test.templatetags return pytils.test.templatetags.get_suite() def get_suite(): """Return TestSuite for all unit-test of pytils""" suite = unittest.TestSuite() for module_name in __all__: imported_module = __import__("pytils.test."+module_name, globals(), locals(), ["pytils.test"]) loader = unittest.defaultTestLoader suite.addTest(loader.loadTestsFromModule(imported_module)) suite.addTest(get_django_suite()) return suite def run_tests_from_module(module, verbosity=1): """Run unit-tests for single module""" suite = unittest.TestSuite() loader = unittest.defaultTestLoader suite.addTest(loader.loadTestsFromModule(module)) unittest.TextTestRunner(verbosity=verbosity).run(suite) def run(verbosity=1): """Run all unit-test of pytils""" suite = get_suite() res = unittest.TextTestRunner(verbosity=verbosity).run(suite) if res.errors or res.failures: sys.exit(1) if __name__ == '__main__': run(2)
Exit with non-0 status if there are failed tests or errors.
Py3: Exit with non-0 status if there are failed tests or errors.
Python
mit
Forever-Young/pytils,j2a/pytils
__all__ = ["test_numeral", "test_dt", "test_translit", "test_utils", "test_typo"] import unittest + import sys def get_django_suite(): try: import django except ImportError: return unittest.TestSuite() import pytils.test.templatetags return pytils.test.templatetags.get_suite() def get_suite(): """Return TestSuite for all unit-test of pytils""" suite = unittest.TestSuite() for module_name in __all__: imported_module = __import__("pytils.test."+module_name, globals(), locals(), ["pytils.test"]) loader = unittest.defaultTestLoader suite.addTest(loader.loadTestsFromModule(imported_module)) suite.addTest(get_django_suite()) return suite def run_tests_from_module(module, verbosity=1): """Run unit-tests for single module""" suite = unittest.TestSuite() loader = unittest.defaultTestLoader suite.addTest(loader.loadTestsFromModule(module)) unittest.TextTestRunner(verbosity=verbosity).run(suite) def run(verbosity=1): """Run all unit-test of pytils""" suite = get_suite() - unittest.TextTestRunner(verbosity=verbosity).run(suite) + res = unittest.TextTestRunner(verbosity=verbosity).run(suite) + if res.errors or res.failures: + sys.exit(1) if __name__ == '__main__': run(2)
Exit with non-0 status if there are failed tests or errors.
## Code Before: __all__ = ["test_numeral", "test_dt", "test_translit", "test_utils", "test_typo"] import unittest def get_django_suite(): try: import django except ImportError: return unittest.TestSuite() import pytils.test.templatetags return pytils.test.templatetags.get_suite() def get_suite(): """Return TestSuite for all unit-test of pytils""" suite = unittest.TestSuite() for module_name in __all__: imported_module = __import__("pytils.test."+module_name, globals(), locals(), ["pytils.test"]) loader = unittest.defaultTestLoader suite.addTest(loader.loadTestsFromModule(imported_module)) suite.addTest(get_django_suite()) return suite def run_tests_from_module(module, verbosity=1): """Run unit-tests for single module""" suite = unittest.TestSuite() loader = unittest.defaultTestLoader suite.addTest(loader.loadTestsFromModule(module)) unittest.TextTestRunner(verbosity=verbosity).run(suite) def run(verbosity=1): """Run all unit-test of pytils""" suite = get_suite() unittest.TextTestRunner(verbosity=verbosity).run(suite) if __name__ == '__main__': run(2) ## Instruction: Exit with non-0 status if there are failed tests or errors. ## Code After: __all__ = ["test_numeral", "test_dt", "test_translit", "test_utils", "test_typo"] import unittest import sys def get_django_suite(): try: import django except ImportError: return unittest.TestSuite() import pytils.test.templatetags return pytils.test.templatetags.get_suite() def get_suite(): """Return TestSuite for all unit-test of pytils""" suite = unittest.TestSuite() for module_name in __all__: imported_module = __import__("pytils.test."+module_name, globals(), locals(), ["pytils.test"]) loader = unittest.defaultTestLoader suite.addTest(loader.loadTestsFromModule(imported_module)) suite.addTest(get_django_suite()) return suite def run_tests_from_module(module, verbosity=1): """Run unit-tests for single module""" suite = unittest.TestSuite() loader = unittest.defaultTestLoader suite.addTest(loader.loadTestsFromModule(module)) unittest.TextTestRunner(verbosity=verbosity).run(suite) def run(verbosity=1): """Run all unit-test of pytils""" suite = get_suite() res = unittest.TextTestRunner(verbosity=verbosity).run(suite) if res.errors or res.failures: sys.exit(1) if __name__ == '__main__': run(2)
// ... existing code ... import unittest import sys def get_django_suite(): // ... modified code ... """Run all unit-test of pytils""" suite = get_suite() res = unittest.TextTestRunner(verbosity=verbosity).run(suite) if res.errors or res.failures: sys.exit(1) if __name__ == '__main__': // ... rest of the code ...
e54b28430f7b301e04eb5b02ce667019df4434bf
chrome/test/chromeos/autotest/files/client/site_tests/desktopui_SyncIntegrationTests/desktopui_SyncIntegrationTests.py
chrome/test/chromeos/autotest/files/client/site_tests/desktopui_SyncIntegrationTests/desktopui_SyncIntegrationTests.py
from autotest_lib.client.cros import chrome_test class desktopui_SyncIntegrationTests(chrome_test.ChromeTestBase): version = 1 def run_once(self): password_file = '%s/sync_password.txt' % self.bindir self.run_chrome_test('sync_integration_tests', ('--password-file-for-test=%s ' + '--test-terminate-timeout=300000') % password_file)
from autotest_lib.client.cros import chrome_test class desktopui_SyncIntegrationTests(chrome_test.ChromeTestBase): version = 1 binary_to_run = 'sync_integration_tests' cmd_line_params = '--test-terminate-timeout=120000' def run_once(self): self.run_chrome_test(self.binary_to_run, self.cmd_line_params)
Make the sync integration tests self-contained on autotest
Make the sync integration tests self-contained on autotest In the past, the sync integration tests used to require a password file stored on every test device in order to do a gaia sign in using production gaia servers. This caused the tests to be brittle. As of today, the sync integration tests no longer rely on a password file, with gaia sign in being stubbed out locally. This patch reconfigures the tests on autotest, so that it no longer looks for a local password file. In addition, the tests run much faster now, and therefore, we reduce the max timeout to a more reasonable 2 minutes (in the extreme case). BUG=chromium-os:11294, chromium-os:9262 TEST=sync_integration_tests Review URL: http://codereview.chromium.org/6387004 git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@72561 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
Python
bsd-3-clause
wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser
from autotest_lib.client.cros import chrome_test class desktopui_SyncIntegrationTests(chrome_test.ChromeTestBase): version = 1 + binary_to_run = 'sync_integration_tests' + cmd_line_params = '--test-terminate-timeout=120000' + def run_once(self): - password_file = '%s/sync_password.txt' % self.bindir + self.run_chrome_test(self.binary_to_run, self.cmd_line_params) - self.run_chrome_test('sync_integration_tests', - ('--password-file-for-test=%s ' + - '--test-terminate-timeout=300000') % password_file) -
Make the sync integration tests self-contained on autotest
## Code Before: from autotest_lib.client.cros import chrome_test class desktopui_SyncIntegrationTests(chrome_test.ChromeTestBase): version = 1 def run_once(self): password_file = '%s/sync_password.txt' % self.bindir self.run_chrome_test('sync_integration_tests', ('--password-file-for-test=%s ' + '--test-terminate-timeout=300000') % password_file) ## Instruction: Make the sync integration tests self-contained on autotest ## Code After: from autotest_lib.client.cros import chrome_test class desktopui_SyncIntegrationTests(chrome_test.ChromeTestBase): version = 1 binary_to_run = 'sync_integration_tests' cmd_line_params = '--test-terminate-timeout=120000' def run_once(self): self.run_chrome_test(self.binary_to_run, self.cmd_line_params)
# ... existing code ... version = 1 binary_to_run = 'sync_integration_tests' cmd_line_params = '--test-terminate-timeout=120000' def run_once(self): self.run_chrome_test(self.binary_to_run, self.cmd_line_params) # ... rest of the code ...
99aac92ca2a4958b7daff7b64d52c0e58db3554c
opal/tests/test_core_views.py
opal/tests/test_core_views.py
from opal.core import test from opal.core import views class SerializerTestCase(test.OpalTestCase): def test_serializer_default_will_super(self): s = views.OpalSerializer() with self.assertRaises(TypeError): s.default(None)
import warnings from opal.core import test from opal.core import views class SerializerTestCase(test.OpalTestCase): def test_serializer_default_will_super(self): s = views.OpalSerializer() with self.assertRaises(TypeError): s.default(None) class BuildJSONResponseTestCase(test.OpalTestCase): def test_underscore_spelling_warns(self): with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') r = views._build_json_response({}) self.assertEqual(200, r.status_code) assert len(w) == 1 assert issubclass(w[-1].category, DeprecationWarning) assert "will be removed" in str(w[-1].message)
Add test for warn spelling of build_json_response
Add test for warn spelling of build_json_response
Python
agpl-3.0
khchine5/opal,khchine5/opal,khchine5/opal
+ import warnings + from opal.core import test from opal.core import views class SerializerTestCase(test.OpalTestCase): def test_serializer_default_will_super(self): s = views.OpalSerializer() with self.assertRaises(TypeError): s.default(None) + + class BuildJSONResponseTestCase(test.OpalTestCase): + + def test_underscore_spelling_warns(self): + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter('always') + r = views._build_json_response({}) + self.assertEqual(200, r.status_code) + assert len(w) == 1 + assert issubclass(w[-1].category, DeprecationWarning) + assert "will be removed" in str(w[-1].message) +
Add test for warn spelling of build_json_response
## Code Before: from opal.core import test from opal.core import views class SerializerTestCase(test.OpalTestCase): def test_serializer_default_will_super(self): s = views.OpalSerializer() with self.assertRaises(TypeError): s.default(None) ## Instruction: Add test for warn spelling of build_json_response ## Code After: import warnings from opal.core import test from opal.core import views class SerializerTestCase(test.OpalTestCase): def test_serializer_default_will_super(self): s = views.OpalSerializer() with self.assertRaises(TypeError): s.default(None) class BuildJSONResponseTestCase(test.OpalTestCase): def test_underscore_spelling_warns(self): with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') r = views._build_json_response({}) self.assertEqual(200, r.status_code) assert len(w) == 1 assert issubclass(w[-1].category, DeprecationWarning) assert "will be removed" in str(w[-1].message)
// ... existing code ... import warnings from opal.core import test // ... modified code ... with self.assertRaises(TypeError): s.default(None) class BuildJSONResponseTestCase(test.OpalTestCase): def test_underscore_spelling_warns(self): with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') r = views._build_json_response({}) self.assertEqual(200, r.status_code) assert len(w) == 1 assert issubclass(w[-1].category, DeprecationWarning) assert "will be removed" in str(w[-1].message) // ... rest of the code ...
e22aee1c56289a81ca3d4b5fdf0f97cc8235d870
twitter_feed/templatetags/twitter_tags.py
twitter_feed/templatetags/twitter_tags.py
from django import template from twitter.models import Tweet register = template.Library() @register.assignment_tag def latest_tweets(number_of_tweets=2): try: tweets = Tweet.objects.filter( user__active=True).order_by('-time')[:number_of_tweets] except (ValueError, AssertionError): raise template.TemplateSyntaxError( "Tag latest_tweets requires a single positive integer argument, given %r." % number_of_tweets) return tweets
from django import template from twitter.models import Tweet register = template.Library() @register.assignment_tag def latest_tweets(number_of_tweets=2): try: tweets = Tweet.objects.filter( user__active=True).order_by('-time')[:number_of_tweets] except (ValueError, AssertionError, TypeError): raise template.TemplateSyntaxError( "Tag latest_tweets requires a single positive integer argument, given %r." % number_of_tweets) return tweets
Handle TypeError for python 3.4.
Handle TypeError for python 3.4.
Python
mit
CIGIHub/wagtail-twitter-feed
from django import template from twitter.models import Tweet register = template.Library() @register.assignment_tag def latest_tweets(number_of_tweets=2): try: tweets = Tweet.objects.filter( user__active=True).order_by('-time')[:number_of_tweets] - except (ValueError, AssertionError): + except (ValueError, AssertionError, TypeError): raise template.TemplateSyntaxError( "Tag latest_tweets requires a single positive integer argument, given %r." % number_of_tweets) return tweets
Handle TypeError for python 3.4.
## Code Before: from django import template from twitter.models import Tweet register = template.Library() @register.assignment_tag def latest_tweets(number_of_tweets=2): try: tweets = Tweet.objects.filter( user__active=True).order_by('-time')[:number_of_tweets] except (ValueError, AssertionError): raise template.TemplateSyntaxError( "Tag latest_tweets requires a single positive integer argument, given %r." % number_of_tweets) return tweets ## Instruction: Handle TypeError for python 3.4. ## Code After: from django import template from twitter.models import Tweet register = template.Library() @register.assignment_tag def latest_tweets(number_of_tweets=2): try: tweets = Tweet.objects.filter( user__active=True).order_by('-time')[:number_of_tweets] except (ValueError, AssertionError, TypeError): raise template.TemplateSyntaxError( "Tag latest_tweets requires a single positive integer argument, given %r." % number_of_tweets) return tweets
// ... existing code ... tweets = Tweet.objects.filter( user__active=True).order_by('-time')[:number_of_tweets] except (ValueError, AssertionError, TypeError): raise template.TemplateSyntaxError( "Tag latest_tweets requires a single positive integer argument, given %r." // ... rest of the code ...
bd5844aa6c59c8d34df12e358e5e06eefcb55f9d
qiita_pet/handlers/download.py
qiita_pet/handlers/download.py
from tornado.web import authenticated from os.path import split from .base_handlers import BaseHandler from qiita_pet.exceptions import QiitaPetAuthorizationError from qiita_db.util import filepath_id_to_rel_path from qiita_db.meta_util import get_accessible_filepath_ids class DownloadHandler(BaseHandler): @authenticated def get(self, filepath_id): filepath_id = int(filepath_id) # Check access to file accessible_filepaths = get_accessible_filepath_ids(self.current_user) if filepath_id not in accessible_filepaths: raise QiitaPetAuthorizationError( self.current_user, 'filepath id %d' % filepath_id) relpath = filepath_id_to_rel_path(filepath_id) fname = split(relpath)[-1] self.set_header('Content-Description', 'File Transfer') self.set_header('Content-Type', 'application/octet-stream') self.set_header('Content-Transfer-Encoding', 'binary') self.set_header('Expires', '0') self.set_header('X-Accel-Redirect', '/protected/' + relpath) self.set_header('Content-Disposition', 'attachment; filename=%s' % fname) self.finish()
from tornado.web import authenticated from os.path import basename from .base_handlers import BaseHandler from qiita_pet.exceptions import QiitaPetAuthorizationError from qiita_db.util import filepath_id_to_rel_path from qiita_db.meta_util import get_accessible_filepath_ids class DownloadHandler(BaseHandler): @authenticated def get(self, filepath_id): filepath_id = int(filepath_id) # Check access to file accessible_filepaths = get_accessible_filepath_ids(self.current_user) if filepath_id not in accessible_filepaths: raise QiitaPetAuthorizationError( self.current_user, 'filepath id %d' % filepath_id) relpath = filepath_id_to_rel_path(filepath_id) fname = basename(relpath) self.set_header('Content-Description', 'File Transfer') self.set_header('Content-Type', 'application/octet-stream') self.set_header('Content-Transfer-Encoding', 'binary') self.set_header('Expires', '0') self.set_header('X-Accel-Redirect', '/protected/' + relpath) self.set_header('Content-Disposition', 'attachment; filename=%s' % fname) self.finish()
Use basename instead of os.path.split(...)[-1]
Use basename instead of os.path.split(...)[-1]
Python
bsd-3-clause
ElDeveloper/qiita,josenavas/QiiTa,RNAer/qiita,squirrelo/qiita,RNAer/qiita,ElDeveloper/qiita,antgonza/qiita,adamrp/qiita,wasade/qiita,antgonza/qiita,squirrelo/qiita,biocore/qiita,adamrp/qiita,josenavas/QiiTa,biocore/qiita,ElDeveloper/qiita,adamrp/qiita,antgonza/qiita,RNAer/qiita,squirrelo/qiita,ElDeveloper/qiita,wasade/qiita,josenavas/QiiTa,wasade/qiita,antgonza/qiita,biocore/qiita,josenavas/QiiTa,biocore/qiita,squirrelo/qiita,RNAer/qiita,adamrp/qiita
from tornado.web import authenticated - from os.path import split + from os.path import basename from .base_handlers import BaseHandler from qiita_pet.exceptions import QiitaPetAuthorizationError from qiita_db.util import filepath_id_to_rel_path from qiita_db.meta_util import get_accessible_filepath_ids class DownloadHandler(BaseHandler): @authenticated def get(self, filepath_id): filepath_id = int(filepath_id) # Check access to file accessible_filepaths = get_accessible_filepath_ids(self.current_user) if filepath_id not in accessible_filepaths: raise QiitaPetAuthorizationError( self.current_user, 'filepath id %d' % filepath_id) relpath = filepath_id_to_rel_path(filepath_id) - fname = split(relpath)[-1] + fname = basename(relpath) self.set_header('Content-Description', 'File Transfer') self.set_header('Content-Type', 'application/octet-stream') self.set_header('Content-Transfer-Encoding', 'binary') self.set_header('Expires', '0') self.set_header('X-Accel-Redirect', '/protected/' + relpath) self.set_header('Content-Disposition', 'attachment; filename=%s' % fname) self.finish()
Use basename instead of os.path.split(...)[-1]
## Code Before: from tornado.web import authenticated from os.path import split from .base_handlers import BaseHandler from qiita_pet.exceptions import QiitaPetAuthorizationError from qiita_db.util import filepath_id_to_rel_path from qiita_db.meta_util import get_accessible_filepath_ids class DownloadHandler(BaseHandler): @authenticated def get(self, filepath_id): filepath_id = int(filepath_id) # Check access to file accessible_filepaths = get_accessible_filepath_ids(self.current_user) if filepath_id not in accessible_filepaths: raise QiitaPetAuthorizationError( self.current_user, 'filepath id %d' % filepath_id) relpath = filepath_id_to_rel_path(filepath_id) fname = split(relpath)[-1] self.set_header('Content-Description', 'File Transfer') self.set_header('Content-Type', 'application/octet-stream') self.set_header('Content-Transfer-Encoding', 'binary') self.set_header('Expires', '0') self.set_header('X-Accel-Redirect', '/protected/' + relpath) self.set_header('Content-Disposition', 'attachment; filename=%s' % fname) self.finish() ## Instruction: Use basename instead of os.path.split(...)[-1] ## Code After: from tornado.web import authenticated from os.path import basename from .base_handlers import BaseHandler from qiita_pet.exceptions import QiitaPetAuthorizationError from qiita_db.util import filepath_id_to_rel_path from qiita_db.meta_util import get_accessible_filepath_ids class DownloadHandler(BaseHandler): @authenticated def get(self, filepath_id): filepath_id = int(filepath_id) # Check access to file accessible_filepaths = get_accessible_filepath_ids(self.current_user) if filepath_id not in accessible_filepaths: raise QiitaPetAuthorizationError( self.current_user, 'filepath id %d' % filepath_id) relpath = filepath_id_to_rel_path(filepath_id) fname = basename(relpath) self.set_header('Content-Description', 'File Transfer') self.set_header('Content-Type', 'application/octet-stream') self.set_header('Content-Transfer-Encoding', 'binary') self.set_header('Expires', '0') self.set_header('X-Accel-Redirect', '/protected/' + relpath) self.set_header('Content-Disposition', 'attachment; filename=%s' % fname) self.finish()
// ... existing code ... from tornado.web import authenticated from os.path import basename from .base_handlers import BaseHandler // ... modified code ... relpath = filepath_id_to_rel_path(filepath_id) fname = basename(relpath) self.set_header('Content-Description', 'File Transfer') // ... rest of the code ...
14d51aa701dcc8d1d3f026af947c935abb0eabe3
examples/rune.py
examples/rune.py
import cassiopeia as cass from cassiopeia.core import Summoner def test_cass(): name = "Kalturi" runes = cass.get_runes() for rune in runes: if rune.tier == 3: print(rune.name) if __name__ == "__main__": test_cass()
import cassiopeia as cass def print_t3_runes(): for rune in cass.get_runes(): if rune.tier == 3: print(rune.name) if __name__ == "__main__": print_t3_runes()
Change function name, remove unneeded summoner name
Change function name, remove unneeded summoner name
Python
mit
robrua/cassiopeia,10se1ucgo/cassiopeia,meraki-analytics/cassiopeia
import cassiopeia as cass - from cassiopeia.core import Summoner - def test_cass(): - name = "Kalturi" + def print_t3_runes(): - runes = cass.get_runes() + for rune in cass.get_runes(): - for rune in runes: if rune.tier == 3: print(rune.name) if __name__ == "__main__": - test_cass() + print_t3_runes()
Change function name, remove unneeded summoner name
## Code Before: import cassiopeia as cass from cassiopeia.core import Summoner def test_cass(): name = "Kalturi" runes = cass.get_runes() for rune in runes: if rune.tier == 3: print(rune.name) if __name__ == "__main__": test_cass() ## Instruction: Change function name, remove unneeded summoner name ## Code After: import cassiopeia as cass def print_t3_runes(): for rune in cass.get_runes(): if rune.tier == 3: print(rune.name) if __name__ == "__main__": print_t3_runes()
... import cassiopeia as cass def print_t3_runes(): for rune in cass.get_runes(): if rune.tier == 3: print(rune.name) ... if __name__ == "__main__": print_t3_runes() ...
7ad47fad53be18a07aede85c02e41176a96c5de2
learnwithpeople/__init__.py
learnwithpeople/__init__.py
from .celery import app as celery_app __version__ = "dev" GIT_REVISION = "dev"
from .celery import app as celery_app __all__ = ('celery_app',) __version__ = "dev" GIT_REVISION = "dev"
Update celery setup according to docs
Update celery setup according to docs
Python
mit
p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles
from .celery import app as celery_app + + __all__ = ('celery_app',) __version__ = "dev" GIT_REVISION = "dev"
Update celery setup according to docs
## Code Before: from .celery import app as celery_app __version__ = "dev" GIT_REVISION = "dev" ## Instruction: Update celery setup according to docs ## Code After: from .celery import app as celery_app __all__ = ('celery_app',) __version__ = "dev" GIT_REVISION = "dev"
# ... existing code ... from .celery import app as celery_app __all__ = ('celery_app',) __version__ = "dev" # ... rest of the code ...
d51fcb604f9e4a0f9b7d4178d4c85209594afbde
dataset/types.py
dataset/types.py
from datetime import datetime, date from sqlalchemy import Integer, UnicodeText, Float, BigInteger from sqlalchemy import Boolean, Date, DateTime, Unicode from sqlalchemy.types import TypeEngine class Types(object): """A holder class for easy access to SQLAlchemy type names.""" integer = Integer string = Unicode text = UnicodeText float = Float bigint = BigInteger boolean = Boolean date = Date datetime = DateTime def guess(cls, sample): """Given a single sample, guess the column type for the field. If the sample is an instance of an SQLAlchemy type, the type will be used instead. """ if isinstance(sample, TypeEngine): return sample if isinstance(sample, bool): return cls.boolean elif isinstance(sample, int): return cls.bigint elif isinstance(sample, float): return cls.float elif isinstance(sample, datetime): return cls.datetime elif isinstance(sample, date): return cls.date return cls.text
from datetime import datetime, date from sqlalchemy import Integer, UnicodeText, Float, BigInteger from sqlalchemy import Boolean, Date, DateTime, Unicode from sqlalchemy.types import TypeEngine class Types(object): """A holder class for easy access to SQLAlchemy type names.""" integer = Integer string = Unicode text = UnicodeText float = Float bigint = BigInteger boolean = Boolean date = Date datetime = DateTime def guess(self, sample): """Given a single sample, guess the column type for the field. If the sample is an instance of an SQLAlchemy type, the type will be used instead. """ if isinstance(sample, TypeEngine): return sample if isinstance(sample, bool): return self.boolean elif isinstance(sample, int): return self.bigint elif isinstance(sample, float): return self.float elif isinstance(sample, datetime): return self.datetime elif isinstance(sample, date): return self.date return self.text
Replace `cls` argument with `self` Not sure if this was originally intended to be a `@classmethod` but it's now written and called as a method bound to an instance of the class.
Replace `cls` argument with `self` Not sure if this was originally intended to be a `@classmethod` but it's now written and called as a method bound to an instance of the class.
Python
mit
pudo/dataset
from datetime import datetime, date from sqlalchemy import Integer, UnicodeText, Float, BigInteger from sqlalchemy import Boolean, Date, DateTime, Unicode from sqlalchemy.types import TypeEngine class Types(object): """A holder class for easy access to SQLAlchemy type names.""" integer = Integer string = Unicode text = UnicodeText float = Float bigint = BigInteger boolean = Boolean date = Date datetime = DateTime - def guess(cls, sample): + def guess(self, sample): """Given a single sample, guess the column type for the field. If the sample is an instance of an SQLAlchemy type, the type will be used instead. """ if isinstance(sample, TypeEngine): return sample if isinstance(sample, bool): - return cls.boolean + return self.boolean elif isinstance(sample, int): - return cls.bigint + return self.bigint elif isinstance(sample, float): - return cls.float + return self.float elif isinstance(sample, datetime): - return cls.datetime + return self.datetime elif isinstance(sample, date): - return cls.date + return self.date - return cls.text + return self.text
Replace `cls` argument with `self` Not sure if this was originally intended to be a `@classmethod` but it's now written and called as a method bound to an instance of the class.
## Code Before: from datetime import datetime, date from sqlalchemy import Integer, UnicodeText, Float, BigInteger from sqlalchemy import Boolean, Date, DateTime, Unicode from sqlalchemy.types import TypeEngine class Types(object): """A holder class for easy access to SQLAlchemy type names.""" integer = Integer string = Unicode text = UnicodeText float = Float bigint = BigInteger boolean = Boolean date = Date datetime = DateTime def guess(cls, sample): """Given a single sample, guess the column type for the field. If the sample is an instance of an SQLAlchemy type, the type will be used instead. """ if isinstance(sample, TypeEngine): return sample if isinstance(sample, bool): return cls.boolean elif isinstance(sample, int): return cls.bigint elif isinstance(sample, float): return cls.float elif isinstance(sample, datetime): return cls.datetime elif isinstance(sample, date): return cls.date return cls.text ## Instruction: Replace `cls` argument with `self` Not sure if this was originally intended to be a `@classmethod` but it's now written and called as a method bound to an instance of the class. ## Code After: from datetime import datetime, date from sqlalchemy import Integer, UnicodeText, Float, BigInteger from sqlalchemy import Boolean, Date, DateTime, Unicode from sqlalchemy.types import TypeEngine class Types(object): """A holder class for easy access to SQLAlchemy type names.""" integer = Integer string = Unicode text = UnicodeText float = Float bigint = BigInteger boolean = Boolean date = Date datetime = DateTime def guess(self, sample): """Given a single sample, guess the column type for the field. If the sample is an instance of an SQLAlchemy type, the type will be used instead. """ if isinstance(sample, TypeEngine): return sample if isinstance(sample, bool): return self.boolean elif isinstance(sample, int): return self.bigint elif isinstance(sample, float): return self.float elif isinstance(sample, datetime): return self.datetime elif isinstance(sample, date): return self.date return self.text
... datetime = DateTime def guess(self, sample): """Given a single sample, guess the column type for the field. ... return sample if isinstance(sample, bool): return self.boolean elif isinstance(sample, int): return self.bigint elif isinstance(sample, float): return self.float elif isinstance(sample, datetime): return self.datetime elif isinstance(sample, date): return self.date return self.text ...
3f64d95cae68548cbb0d5a200247b3f7d6c3ccf4
mongorm/__init__.py
mongorm/__init__.py
from mongorm.database import Database from mongorm.document import Field, Index from mongorm.utils import DotDict, JSONEncoder class ValidationError(Exception): pass __all__ = [ 'VERSION', 'ValidationError', 'Database', 'Field', 'Index', 'DotDict', 'JSONEncoder' ]
from mongorm.database import Database from mongorm.document import Field, Index from mongorm.utils import DotDict, JSONEncoder class ValidationError(Exception): pass __all__ = [ 'ValidationError', 'Database', 'Field', 'Index', 'DotDict', 'JSONEncoder' ]
Remove VERSION that prevented import *.
Remove VERSION that prevented import *.
Python
bsd-2-clause
rahulg/mongorm
from mongorm.database import Database from mongorm.document import Field, Index from mongorm.utils import DotDict, JSONEncoder class ValidationError(Exception): pass __all__ = [ - 'VERSION', 'ValidationError', 'Database', 'Field', 'Index', 'DotDict', 'JSONEncoder' ]
Remove VERSION that prevented import *.
## Code Before: from mongorm.database import Database from mongorm.document import Field, Index from mongorm.utils import DotDict, JSONEncoder class ValidationError(Exception): pass __all__ = [ 'VERSION', 'ValidationError', 'Database', 'Field', 'Index', 'DotDict', 'JSONEncoder' ] ## Instruction: Remove VERSION that prevented import *. ## Code After: from mongorm.database import Database from mongorm.document import Field, Index from mongorm.utils import DotDict, JSONEncoder class ValidationError(Exception): pass __all__ = [ 'ValidationError', 'Database', 'Field', 'Index', 'DotDict', 'JSONEncoder' ]
... __all__ = [ 'ValidationError', 'Database', ...
6bbafa2e9102840768ee875407be1878f2aa05ca
tests/pytests/unit/engines/test_script.py
tests/pytests/unit/engines/test_script.py
import pytest import salt.config import salt.engines.script as script from salt.exceptions import CommandExecutionError from tests.support.mock import patch @pytest.fixture def configure_loader_modules(): opts = salt.config.DEFAULT_MASTER_OPTS return {script: {"__opts__": opts}} def test__get_serializer(): """ Test known serializer is returned or exception is raised if unknown serializer """ for serializers in ("json", "yaml", "msgpack"): assert script._get_serializer(serializers) with pytest.raises(CommandExecutionError): script._get_serializer("bad") def test__read_stdout(): """ Test we can yield stdout """ with patch("subprocess.Popen") as popen_mock: popen_mock.stdout.readline.return_value = "test" assert next(script._read_stdout(popen_mock)) == "test"
import pytest import salt.config import salt.engines.script as script from salt.exceptions import CommandExecutionError from tests.support.mock import patch @pytest.fixture def configure_loader_modules(): opts = salt.config.DEFAULT_MASTER_OPTS return {script: {"__opts__": opts}} def test__get_serializer(): """ Test known serializer is returned or exception is raised if unknown serializer """ for serializers in ("json", "yaml", "msgpack"): assert script._get_serializer(serializers) with pytest.raises(CommandExecutionError): script._get_serializer("bad") def test__read_stdout(): """ Test we can yield stdout """ with patch("subprocess.Popen") as popen_mock: popen_mock.stdout.readline.return_value = "test" assert next(script._read_stdout(popen_mock)) == "test" def test__read_stdout_terminates_properly(): """ Test that _read_stdout terminates with the sentinel """ with patch("subprocess.Popen", autospec=True) as popen_mock: popen_mock.stdout.readline.return_value = b"" with pytest.raises(StopIteration): next(script._read_stdout(popen_mock))
Test iteration stops at empty bytes
Test iteration stops at empty bytes
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
import pytest import salt.config import salt.engines.script as script from salt.exceptions import CommandExecutionError from tests.support.mock import patch @pytest.fixture def configure_loader_modules(): opts = salt.config.DEFAULT_MASTER_OPTS return {script: {"__opts__": opts}} def test__get_serializer(): """ Test known serializer is returned or exception is raised if unknown serializer """ for serializers in ("json", "yaml", "msgpack"): assert script._get_serializer(serializers) with pytest.raises(CommandExecutionError): script._get_serializer("bad") def test__read_stdout(): """ Test we can yield stdout """ with patch("subprocess.Popen") as popen_mock: popen_mock.stdout.readline.return_value = "test" assert next(script._read_stdout(popen_mock)) == "test" + def test__read_stdout_terminates_properly(): + """ + Test that _read_stdout terminates with the sentinel + """ + with patch("subprocess.Popen", autospec=True) as popen_mock: + popen_mock.stdout.readline.return_value = b"" + with pytest.raises(StopIteration): + next(script._read_stdout(popen_mock)) +
Test iteration stops at empty bytes
## Code Before: import pytest import salt.config import salt.engines.script as script from salt.exceptions import CommandExecutionError from tests.support.mock import patch @pytest.fixture def configure_loader_modules(): opts = salt.config.DEFAULT_MASTER_OPTS return {script: {"__opts__": opts}} def test__get_serializer(): """ Test known serializer is returned or exception is raised if unknown serializer """ for serializers in ("json", "yaml", "msgpack"): assert script._get_serializer(serializers) with pytest.raises(CommandExecutionError): script._get_serializer("bad") def test__read_stdout(): """ Test we can yield stdout """ with patch("subprocess.Popen") as popen_mock: popen_mock.stdout.readline.return_value = "test" assert next(script._read_stdout(popen_mock)) == "test" ## Instruction: Test iteration stops at empty bytes ## Code After: import pytest import salt.config import salt.engines.script as script from salt.exceptions import CommandExecutionError from tests.support.mock import patch @pytest.fixture def configure_loader_modules(): opts = salt.config.DEFAULT_MASTER_OPTS return {script: {"__opts__": opts}} def test__get_serializer(): """ Test known serializer is returned or exception is raised if unknown serializer """ for serializers in ("json", "yaml", "msgpack"): assert script._get_serializer(serializers) with pytest.raises(CommandExecutionError): script._get_serializer("bad") def test__read_stdout(): """ Test we can yield stdout """ with patch("subprocess.Popen") as popen_mock: popen_mock.stdout.readline.return_value = "test" assert next(script._read_stdout(popen_mock)) == "test" def test__read_stdout_terminates_properly(): """ Test that _read_stdout terminates with the sentinel """ with patch("subprocess.Popen", autospec=True) as popen_mock: popen_mock.stdout.readline.return_value = b"" with pytest.raises(StopIteration): next(script._read_stdout(popen_mock))
// ... existing code ... popen_mock.stdout.readline.return_value = "test" assert next(script._read_stdout(popen_mock)) == "test" def test__read_stdout_terminates_properly(): """ Test that _read_stdout terminates with the sentinel """ with patch("subprocess.Popen", autospec=True) as popen_mock: popen_mock.stdout.readline.return_value = b"" with pytest.raises(StopIteration): next(script._read_stdout(popen_mock)) // ... rest of the code ...
a38ee91cbb45cba35c930aae780a469c0cbc762c
mrbelvedereci/build/tasks.py
mrbelvedereci/build/tasks.py
from celery import shared_task from mrbelvedereci.build.models import Build from mrbelvedereci.salesforce.models import Org @shared_task def run_build(build_id): build = Build.objects.get(id=build_id) build.run() return build.status @shared_task def check_queued_build(build_id): build = Build.objects.get(id = build_id) # Check for concurrency blocking try: org = Org.objects.get(name = build.trigger.org, repo = build.repo) except Org.DoesNotExist: return # If this is not a scratch org, ensure no builds are currently running against the org if not org.scratch: running_builds = Build.objects.filter(status='running', repo=build.repo, org = build.org).count() if running_builds: # Requeue this job to check again in 5 seconds check_queued_build.apply_async((build.id,), countdown=5) return 'Queued: checking again in 5 seconds' # Queue the background job with a 1 second delay to allow the transaction to commit run_build.apply_async((build.id,), countdown=1)
from celery import shared_task from mrbelvedereci.build.models import Build from mrbelvedereci.salesforce.models import Org @shared_task def run_build(build_id): build = Build.objects.get(id=build_id) build.run() return build.status @shared_task def check_queued_build(build_id): build = Build.objects.get(id = build_id) # Check for concurrency blocking try: org = Org.objects.get(name = build.trigger.org, repo = build.repo) except Org.DoesNotExist: return # If this is not a scratch org, ensure no builds are currently running against the org if not org.scratch: running_builds = Build.objects.filter(status='running', repo=build.repo, trigger__org = build.trigger.org).count() if running_builds: # Requeue this job to check again in 5 seconds check_queued_build.apply_async((build.id,), countdown=5) return 'Queued: checking again in 5 seconds' # Queue the background job with a 1 second delay to allow the transaction to commit run_build.apply_async((build.id,), countdown=1)
Fix path to org field
Fix path to org field
Python
bsd-3-clause
SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci
from celery import shared_task from mrbelvedereci.build.models import Build from mrbelvedereci.salesforce.models import Org @shared_task def run_build(build_id): build = Build.objects.get(id=build_id) build.run() return build.status @shared_task def check_queued_build(build_id): build = Build.objects.get(id = build_id) # Check for concurrency blocking try: org = Org.objects.get(name = build.trigger.org, repo = build.repo) except Org.DoesNotExist: return # If this is not a scratch org, ensure no builds are currently running against the org if not org.scratch: - running_builds = Build.objects.filter(status='running', repo=build.repo, org = build.org).count() + running_builds = Build.objects.filter(status='running', repo=build.repo, trigger__org = build.trigger.org).count() if running_builds: # Requeue this job to check again in 5 seconds check_queued_build.apply_async((build.id,), countdown=5) return 'Queued: checking again in 5 seconds' # Queue the background job with a 1 second delay to allow the transaction to commit run_build.apply_async((build.id,), countdown=1)
Fix path to org field
## Code Before: from celery import shared_task from mrbelvedereci.build.models import Build from mrbelvedereci.salesforce.models import Org @shared_task def run_build(build_id): build = Build.objects.get(id=build_id) build.run() return build.status @shared_task def check_queued_build(build_id): build = Build.objects.get(id = build_id) # Check for concurrency blocking try: org = Org.objects.get(name = build.trigger.org, repo = build.repo) except Org.DoesNotExist: return # If this is not a scratch org, ensure no builds are currently running against the org if not org.scratch: running_builds = Build.objects.filter(status='running', repo=build.repo, org = build.org).count() if running_builds: # Requeue this job to check again in 5 seconds check_queued_build.apply_async((build.id,), countdown=5) return 'Queued: checking again in 5 seconds' # Queue the background job with a 1 second delay to allow the transaction to commit run_build.apply_async((build.id,), countdown=1) ## Instruction: Fix path to org field ## Code After: from celery import shared_task from mrbelvedereci.build.models import Build from mrbelvedereci.salesforce.models import Org @shared_task def run_build(build_id): build = Build.objects.get(id=build_id) build.run() return build.status @shared_task def check_queued_build(build_id): build = Build.objects.get(id = build_id) # Check for concurrency blocking try: org = Org.objects.get(name = build.trigger.org, repo = build.repo) except Org.DoesNotExist: return # If this is not a scratch org, ensure no builds are currently running against the org if not org.scratch: running_builds = Build.objects.filter(status='running', repo=build.repo, trigger__org = build.trigger.org).count() if running_builds: # Requeue this job to check again in 5 seconds check_queued_build.apply_async((build.id,), countdown=5) return 'Queued: checking again in 5 seconds' # Queue the background job with a 1 second delay to allow the transaction to commit run_build.apply_async((build.id,), countdown=1)
// ... existing code ... # If this is not a scratch org, ensure no builds are currently running against the org if not org.scratch: running_builds = Build.objects.filter(status='running', repo=build.repo, trigger__org = build.trigger.org).count() if running_builds: # Requeue this job to check again in 5 seconds // ... rest of the code ...
e8bb81a8be7c76c2e1839d8315bd29f381fea4ae
enable/__init__.py
enable/__init__.py
__version__ = '4.3.0' __requires__ = [ 'traitsui', 'PIL', ]
__version__ = '4.3.0' __requires__ = [ 'traitsui', 'PIL', 'casuarius', ]
Add casuarius to the list of required packages.
Add casuarius to the list of required packages.
Python
bsd-3-clause
tommy-u/enable,tommy-u/enable,tommy-u/enable,tommy-u/enable
__version__ = '4.3.0' __requires__ = [ 'traitsui', 'PIL', + 'casuarius', ]
Add casuarius to the list of required packages.
## Code Before: __version__ = '4.3.0' __requires__ = [ 'traitsui', 'PIL', ] ## Instruction: Add casuarius to the list of required packages. ## Code After: __version__ = '4.3.0' __requires__ = [ 'traitsui', 'PIL', 'casuarius', ]
// ... existing code ... 'traitsui', 'PIL', 'casuarius', ] // ... rest of the code ...
2d74b55a0c110a836190af819b55673bce2300a0
gaphor/ui/macosshim.py
gaphor/ui/macosshim.py
try: import gi gi.require_version("GtkosxApplication", "1.0") except ValueError: macos_init = None else: from gi.repository import GtkosxApplication macos_app = GtkosxApplication.Application.get() def open_file(macos_app, path, application): if path == __file__: return False app_file_manager = application.get_service("app_file_manager") app_file_manager.load(path) return True def block_termination(macos_app, application): quit = application.quit() return not quit def macos_init(application): macos_app.connect("NSApplicationOpenFile", open_file, application) macos_app.connect( "NSApplicationBlockTermination", block_termination, application )
try: import gi from gi.repository import Gtk if Gtk.get_major_version() == 3: gi.require_version("GtkosxApplication", "1.0") else: raise ValueError() except ValueError: macos_init = None else: from gi.repository import GtkosxApplication macos_app = GtkosxApplication.Application.get() def open_file(macos_app, path, application): if path == __file__: return False app_file_manager = application.get_service("app_file_manager") app_file_manager.load(path) return True def block_termination(macos_app, application): quit = application.quit() return not quit def macos_init(application): macos_app.connect("NSApplicationOpenFile", open_file, application) macos_app.connect( "NSApplicationBlockTermination", block_termination, application )
Fix macos shim for gtk 4
Fix macos shim for gtk 4
Python
lgpl-2.1
amolenaar/gaphor,amolenaar/gaphor
try: import gi + from gi.repository import Gtk + if Gtk.get_major_version() == 3: - gi.require_version("GtkosxApplication", "1.0") + gi.require_version("GtkosxApplication", "1.0") + else: + raise ValueError() except ValueError: macos_init = None else: from gi.repository import GtkosxApplication macos_app = GtkosxApplication.Application.get() def open_file(macos_app, path, application): if path == __file__: return False app_file_manager = application.get_service("app_file_manager") app_file_manager.load(path) return True def block_termination(macos_app, application): quit = application.quit() return not quit def macos_init(application): macos_app.connect("NSApplicationOpenFile", open_file, application) macos_app.connect( "NSApplicationBlockTermination", block_termination, application )
Fix macos shim for gtk 4
## Code Before: try: import gi gi.require_version("GtkosxApplication", "1.0") except ValueError: macos_init = None else: from gi.repository import GtkosxApplication macos_app = GtkosxApplication.Application.get() def open_file(macos_app, path, application): if path == __file__: return False app_file_manager = application.get_service("app_file_manager") app_file_manager.load(path) return True def block_termination(macos_app, application): quit = application.quit() return not quit def macos_init(application): macos_app.connect("NSApplicationOpenFile", open_file, application) macos_app.connect( "NSApplicationBlockTermination", block_termination, application ) ## Instruction: Fix macos shim for gtk 4 ## Code After: try: import gi from gi.repository import Gtk if Gtk.get_major_version() == 3: gi.require_version("GtkosxApplication", "1.0") else: raise ValueError() except ValueError: macos_init = None else: from gi.repository import GtkosxApplication macos_app = GtkosxApplication.Application.get() def open_file(macos_app, path, application): if path == __file__: return False app_file_manager = application.get_service("app_file_manager") app_file_manager.load(path) return True def block_termination(macos_app, application): quit = application.quit() return not quit def macos_init(application): macos_app.connect("NSApplicationOpenFile", open_file, application) macos_app.connect( "NSApplicationBlockTermination", block_termination, application )
... try: import gi from gi.repository import Gtk if Gtk.get_major_version() == 3: gi.require_version("GtkosxApplication", "1.0") else: raise ValueError() except ValueError: macos_init = None ...
54fdf3922615d5907a2e5344bf027df389572feb
byceps/services/user/transfer/models.py
byceps/services/user/transfer/models.py
from __future__ import annotations from dataclasses import dataclass from datetime import date from typing import Any, Optional from ....typing import UserID @dataclass(frozen=True) class User: id: UserID screen_name: Optional[str] suspended: bool deleted: bool locale: Optional[str] avatar_url: Optional[str] is_orga: bool @dataclass(frozen=True) class UserDetail: first_names: Optional[str] last_name: Optional[str] date_of_birth: Optional[date] country: Optional[str] zip_code: Optional[str] city: Optional[str] street: Optional[str] phone_number: Optional[str] internal_comment: Optional[str] extras: dict[str, Any] @dataclass(frozen=True) class UserWithDetail(User): detail: UserDetail
from __future__ import annotations from dataclasses import dataclass from datetime import date from typing import Any, Optional from ....typing import UserID @dataclass(frozen=True) class User: id: UserID screen_name: Optional[str] suspended: bool deleted: bool locale: Optional[str] avatar_url: Optional[str] is_orga: bool @dataclass(frozen=True) class UserDetail: first_names: Optional[str] last_name: Optional[str] date_of_birth: Optional[date] country: Optional[str] zip_code: Optional[str] city: Optional[str] street: Optional[str] phone_number: Optional[str] internal_comment: Optional[str] extras: dict[str, Any] @property def full_name(self) -> Optional[str]: names = [self.first_names, self.last_name] return ' '.join(filter(None, names)) or None @dataclass(frozen=True) class UserWithDetail(User): detail: UserDetail
Fix display of full user name at least on current user's settings page
Fix display of full user name at least on current user's settings page
Python
bsd-3-clause
homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps
from __future__ import annotations from dataclasses import dataclass from datetime import date from typing import Any, Optional from ....typing import UserID @dataclass(frozen=True) class User: id: UserID screen_name: Optional[str] suspended: bool deleted: bool locale: Optional[str] avatar_url: Optional[str] is_orga: bool @dataclass(frozen=True) class UserDetail: first_names: Optional[str] last_name: Optional[str] date_of_birth: Optional[date] country: Optional[str] zip_code: Optional[str] city: Optional[str] street: Optional[str] phone_number: Optional[str] internal_comment: Optional[str] extras: dict[str, Any] + @property + def full_name(self) -> Optional[str]: + names = [self.first_names, self.last_name] + return ' '.join(filter(None, names)) or None + @dataclass(frozen=True) class UserWithDetail(User): detail: UserDetail
Fix display of full user name at least on current user's settings page
## Code Before: from __future__ import annotations from dataclasses import dataclass from datetime import date from typing import Any, Optional from ....typing import UserID @dataclass(frozen=True) class User: id: UserID screen_name: Optional[str] suspended: bool deleted: bool locale: Optional[str] avatar_url: Optional[str] is_orga: bool @dataclass(frozen=True) class UserDetail: first_names: Optional[str] last_name: Optional[str] date_of_birth: Optional[date] country: Optional[str] zip_code: Optional[str] city: Optional[str] street: Optional[str] phone_number: Optional[str] internal_comment: Optional[str] extras: dict[str, Any] @dataclass(frozen=True) class UserWithDetail(User): detail: UserDetail ## Instruction: Fix display of full user name at least on current user's settings page ## Code After: from __future__ import annotations from dataclasses import dataclass from datetime import date from typing import Any, Optional from ....typing import UserID @dataclass(frozen=True) class User: id: UserID screen_name: Optional[str] suspended: bool deleted: bool locale: Optional[str] avatar_url: Optional[str] is_orga: bool @dataclass(frozen=True) class UserDetail: first_names: Optional[str] last_name: Optional[str] date_of_birth: Optional[date] country: Optional[str] zip_code: Optional[str] city: Optional[str] street: Optional[str] phone_number: Optional[str] internal_comment: Optional[str] extras: dict[str, Any] @property def full_name(self) -> Optional[str]: names = [self.first_names, self.last_name] return ' '.join(filter(None, names)) or None @dataclass(frozen=True) class UserWithDetail(User): detail: UserDetail
// ... existing code ... extras: dict[str, Any] @property def full_name(self) -> Optional[str]: names = [self.first_names, self.last_name] return ' '.join(filter(None, names)) or None @dataclass(frozen=True) // ... rest of the code ...
0483563fd08063e856915099075b203379e61e7c
bejmy/categories/admin.py
bejmy/categories/admin.py
from django.contrib import admin from bejmy.categories.models import Category @admin.register(Category) class CategoryAdmin(admin.ModelAdmin): list_display = ( 'name', 'user', 'transaction_type', ) list_filter = ( 'user', 'transaction_type', ) search_fields = ( 'name', ) raw_id_fields = ('parent',) def get_queryset(self, request, *args, **kwargs): queryset = super().get_queryset(request, *args, **kwargs) if not self.request.user.is_superuser(): queryset = queryset.filter(user=request.user) return queryset
from django.contrib import admin from bejmy.categories.models import Category from mptt.admin import MPTTModelAdmin @admin.register(Category) class CategoryAdmin(MPTTModelAdmin): list_display = ( 'name', 'user', 'transaction_type', ) list_filter = ( 'user', 'transaction_type', ) search_fields = ( 'name', ) raw_id_fields = ('parent',) def get_queryset(self, request, *args, **kwargs): queryset = super().get_queryset(request, *args, **kwargs) if not self.request.user.is_superuser(): queryset = queryset.filter(user=request.user) return queryset
Access to all accounts only for superusers
Access to all accounts only for superusers
Python
mit
bejmy/backend,bejmy/backend
from django.contrib import admin from bejmy.categories.models import Category + from mptt.admin import MPTTModelAdmin + @admin.register(Category) - class CategoryAdmin(admin.ModelAdmin): + class CategoryAdmin(MPTTModelAdmin): list_display = ( 'name', 'user', 'transaction_type', ) list_filter = ( 'user', 'transaction_type', ) search_fields = ( 'name', ) raw_id_fields = ('parent',) def get_queryset(self, request, *args, **kwargs): queryset = super().get_queryset(request, *args, **kwargs) if not self.request.user.is_superuser(): queryset = queryset.filter(user=request.user) return queryset
Access to all accounts only for superusers
## Code Before: from django.contrib import admin from bejmy.categories.models import Category @admin.register(Category) class CategoryAdmin(admin.ModelAdmin): list_display = ( 'name', 'user', 'transaction_type', ) list_filter = ( 'user', 'transaction_type', ) search_fields = ( 'name', ) raw_id_fields = ('parent',) def get_queryset(self, request, *args, **kwargs): queryset = super().get_queryset(request, *args, **kwargs) if not self.request.user.is_superuser(): queryset = queryset.filter(user=request.user) return queryset ## Instruction: Access to all accounts only for superusers ## Code After: from django.contrib import admin from bejmy.categories.models import Category from mptt.admin import MPTTModelAdmin @admin.register(Category) class CategoryAdmin(MPTTModelAdmin): list_display = ( 'name', 'user', 'transaction_type', ) list_filter = ( 'user', 'transaction_type', ) search_fields = ( 'name', ) raw_id_fields = ('parent',) def get_queryset(self, request, *args, **kwargs): queryset = super().get_queryset(request, *args, **kwargs) if not self.request.user.is_superuser(): queryset = queryset.filter(user=request.user) return queryset
... from bejmy.categories.models import Category from mptt.admin import MPTTModelAdmin @admin.register(Category) class CategoryAdmin(MPTTModelAdmin): list_display = ( 'name', ...
1ea27e8989657bb35dd37b6ee2e038e1358fbc96
social_core/backends/globus.py
social_core/backends/globus.py
from social_core.backends.open_id_connect import OpenIdConnectAuth class GlobusOpenIdConnect(OpenIdConnectAuth): name = 'globus' OIDC_ENDPOINT = 'https://auth.globus.org' EXTRA_DATA = [ ('expires_in', 'expires_in', True), ('refresh_token', 'refresh_token', True), ('id_token', 'id_token', True), ('other_tokens', 'other_tokens', True), ] def get_user_details(self, response): username_key = self.setting('USERNAME_KEY', default=self.USERNAME_KEY) name = response.get('name') or '' fullname, first_name, last_name = self.get_user_names(name) return {'username': response.get(username_key), 'email': response.get('email'), 'fullname': fullname, 'first_name': first_name, 'last_name': last_name}
from social_core.backends.open_id_connect import OpenIdConnectAuth class GlobusOpenIdConnect(OpenIdConnectAuth): name = 'globus' OIDC_ENDPOINT = 'https://auth.globus.org' JWT_ALGORITHMS = ['RS256', 'RS512'] EXTRA_DATA = [ ('expires_in', 'expires_in', True), ('refresh_token', 'refresh_token', True), ('id_token', 'id_token', True), ('other_tokens', 'other_tokens', True), ] def get_user_details(self, response): username_key = self.setting('USERNAME_KEY', default=self.USERNAME_KEY) name = response.get('name') or '' fullname, first_name, last_name = self.get_user_names(name) return {'username': response.get(username_key), 'email': response.get('email'), 'fullname': fullname, 'first_name': first_name, 'last_name': last_name}
Set a JWT signature algorithm for the Globus backend to RS512
Set a JWT signature algorithm for the Globus backend to RS512
Python
bsd-3-clause
python-social-auth/social-core,python-social-auth/social-core
from social_core.backends.open_id_connect import OpenIdConnectAuth class GlobusOpenIdConnect(OpenIdConnectAuth): name = 'globus' OIDC_ENDPOINT = 'https://auth.globus.org' + JWT_ALGORITHMS = ['RS256', 'RS512'] EXTRA_DATA = [ ('expires_in', 'expires_in', True), ('refresh_token', 'refresh_token', True), ('id_token', 'id_token', True), ('other_tokens', 'other_tokens', True), ] def get_user_details(self, response): username_key = self.setting('USERNAME_KEY', default=self.USERNAME_KEY) name = response.get('name') or '' fullname, first_name, last_name = self.get_user_names(name) return {'username': response.get(username_key), 'email': response.get('email'), 'fullname': fullname, 'first_name': first_name, 'last_name': last_name}
Set a JWT signature algorithm for the Globus backend to RS512
## Code Before: from social_core.backends.open_id_connect import OpenIdConnectAuth class GlobusOpenIdConnect(OpenIdConnectAuth): name = 'globus' OIDC_ENDPOINT = 'https://auth.globus.org' EXTRA_DATA = [ ('expires_in', 'expires_in', True), ('refresh_token', 'refresh_token', True), ('id_token', 'id_token', True), ('other_tokens', 'other_tokens', True), ] def get_user_details(self, response): username_key = self.setting('USERNAME_KEY', default=self.USERNAME_KEY) name = response.get('name') or '' fullname, first_name, last_name = self.get_user_names(name) return {'username': response.get(username_key), 'email': response.get('email'), 'fullname': fullname, 'first_name': first_name, 'last_name': last_name} ## Instruction: Set a JWT signature algorithm for the Globus backend to RS512 ## Code After: from social_core.backends.open_id_connect import OpenIdConnectAuth class GlobusOpenIdConnect(OpenIdConnectAuth): name = 'globus' OIDC_ENDPOINT = 'https://auth.globus.org' JWT_ALGORITHMS = ['RS256', 'RS512'] EXTRA_DATA = [ ('expires_in', 'expires_in', True), ('refresh_token', 'refresh_token', True), ('id_token', 'id_token', True), ('other_tokens', 'other_tokens', True), ] def get_user_details(self, response): username_key = self.setting('USERNAME_KEY', default=self.USERNAME_KEY) name = response.get('name') or '' fullname, first_name, last_name = self.get_user_names(name) return {'username': response.get(username_key), 'email': response.get('email'), 'fullname': fullname, 'first_name': first_name, 'last_name': last_name}
// ... existing code ... name = 'globus' OIDC_ENDPOINT = 'https://auth.globus.org' JWT_ALGORITHMS = ['RS256', 'RS512'] EXTRA_DATA = [ ('expires_in', 'expires_in', True), // ... rest of the code ...
a04a5a80057e86af2c5df0e87a7d2c3c221123ae
rpc_server/CouchDBViewDefinitions.py
rpc_server/CouchDBViewDefinitions.py
definitions = ( { "doc": "basicStats", "view": "addCar", "map": """ function(doc) { // car creations for (var id in doc.cars){ if (doc.cars[id].state && doc.cars[id].state === 'add') { emit(id, {'time': doc.time}); } } }""" }, { "doc": "basicStats", "view": "deleteCar", "map": """ function(doc) { for (var id in doc.cars){ if (doc.cars[id].state && doc.cars[id].state === 'del') { emit(id, {'time': doc.time}); } } } """ } ,)
definitions = ( { "doc": "basicStats", "view": "addCar", "map": """ function(doc) { // car creations for (var id in doc.cars){ if (doc.cars[id].state && doc.cars[id].state === 'add') { emit(id, {'time': doc.time}); } } }""" }, { "doc": "basicStats", "view": "deleteCar", "map": """ function(doc) { for (var id in doc.cars){ if (doc.cars[id].state && doc.cars[id].state === 'del') { emit(id, {'time': doc.time}); } } } """ }, { "doc": "manage", "view": "jobs", "map": """ function(doc) { if (doc.type === 'job'){ emit(doc.name, doc._id); } } """ } ,)
Add view to get project jobs.
Add view to get project jobs.
Python
apache-2.0
anthony-kolesov/kts46,anthony-kolesov/kts46,anthony-kolesov/kts46,anthony-kolesov/kts46
definitions = ( { "doc": "basicStats", "view": "addCar", "map": """ function(doc) { // car creations for (var id in doc.cars){ if (doc.cars[id].state && doc.cars[id].state === 'add') { emit(id, {'time': doc.time}); } } }""" }, { "doc": "basicStats", "view": "deleteCar", "map": """ function(doc) { for (var id in doc.cars){ if (doc.cars[id].state && doc.cars[id].state === 'del') { emit(id, {'time': doc.time}); } } } """ + }, + { + "doc": "manage", "view": "jobs", + "map": """ + function(doc) { + if (doc.type === 'job'){ + emit(doc.name, doc._id); + } + } + """ } ,)
Add view to get project jobs.
## Code Before: definitions = ( { "doc": "basicStats", "view": "addCar", "map": """ function(doc) { // car creations for (var id in doc.cars){ if (doc.cars[id].state && doc.cars[id].state === 'add') { emit(id, {'time': doc.time}); } } }""" }, { "doc": "basicStats", "view": "deleteCar", "map": """ function(doc) { for (var id in doc.cars){ if (doc.cars[id].state && doc.cars[id].state === 'del') { emit(id, {'time': doc.time}); } } } """ } ,) ## Instruction: Add view to get project jobs. ## Code After: definitions = ( { "doc": "basicStats", "view": "addCar", "map": """ function(doc) { // car creations for (var id in doc.cars){ if (doc.cars[id].state && doc.cars[id].state === 'add') { emit(id, {'time': doc.time}); } } }""" }, { "doc": "basicStats", "view": "deleteCar", "map": """ function(doc) { for (var id in doc.cars){ if (doc.cars[id].state && doc.cars[id].state === 'del') { emit(id, {'time': doc.time}); } } } """ }, { "doc": "manage", "view": "jobs", "map": """ function(doc) { if (doc.type === 'job'){ emit(doc.name, doc._id); } } """ } ,)
# ... existing code ... } """ }, { "doc": "manage", "view": "jobs", "map": """ function(doc) { if (doc.type === 'job'){ emit(doc.name, doc._id); } } """ } ,) # ... rest of the code ...
763077f355386b8a5fdb4bda44f5d2856563f674
sklearn_porter/estimator/EstimatorApiABC.py
sklearn_porter/estimator/EstimatorApiABC.py
from typing import Union, Optional, Tuple from pathlib import Path from abc import ABC, abstractmethod from sklearn_porter.enums import Method, Language, Template class EstimatorApiABC(ABC): """ An abstract interface to ensure equal methods between the main class `sklearn_porter.Estimator` and all subclasses in `sklearn-porter.estimator.*`. """ @abstractmethod def port( self, language: Optional[Language] = None, template: Optional[Template] = None, to_json: bool = False, **kwargs ) -> Union[str, Tuple[str, str]]: """ Port an estimator. Parameters ---------- method : Method The required method. language : Language The required language. template : Template The required template. kwargs Returns ------- The ported estimator. """ pass @abstractmethod def dump( self, language: Optional[Language] = None, template: Optional[Template] = None, directory: Optional[Union[str, Path]] = None, to_json: bool = False, **kwargs ) -> Union[str, Tuple[str, str]]: """ Dump an estimator to the filesystem. Parameters ---------- method : Method The required method. language : Language The required language. template : Template The required template directory : str or Path The destination directory. kwargs Returns ------- The paths to the dumped files. """ pass
from typing import Union, Optional, Tuple from pathlib import Path from abc import ABC, abstractmethod from sklearn_porter.enums import Language, Template class EstimatorApiABC(ABC): """ An abstract interface to ensure equal methods between the main class `sklearn_porter.Estimator` and all subclasses in `sklearn-porter.estimator.*`. """ @abstractmethod def port( self, language: Optional[Language] = None, template: Optional[Template] = None, to_json: bool = False, **kwargs ) -> Union[str, Tuple[str, str]]: """ Port an estimator. Parameters ---------- language : Language The required language. template : Template The required template. to_json : bool (default: False) Return the result as JSON string. kwargs Returns ------- The ported estimator. """ @abstractmethod def dump( self, language: Optional[Language] = None, template: Optional[Template] = None, directory: Optional[Union[str, Path]] = None, to_json: bool = False, **kwargs ) -> Union[str, Tuple[str, str]]: """ Dump an estimator to the filesystem. Parameters ---------- language : Language The required language. template : Template The required template directory : str or Path The destination directory. to_json : bool (default: False) Return the result as JSON string. kwargs Returns ------- The paths to the dumped files. """
Remove unused imports and `pass` keywords
feature/oop-api-refactoring: Remove unused imports and `pass` keywords
Python
bsd-3-clause
nok/sklearn-porter
from typing import Union, Optional, Tuple from pathlib import Path from abc import ABC, abstractmethod - from sklearn_porter.enums import Method, Language, Template + from sklearn_porter.enums import Language, Template class EstimatorApiABC(ABC): """ An abstract interface to ensure equal methods between the main class `sklearn_porter.Estimator` and all subclasses in `sklearn-porter.estimator.*`. """ @abstractmethod def port( self, language: Optional[Language] = None, template: Optional[Template] = None, to_json: bool = False, **kwargs ) -> Union[str, Tuple[str, str]]: """ Port an estimator. Parameters ---------- - method : Method - The required method. language : Language The required language. template : Template The required template. + to_json : bool (default: False) + Return the result as JSON string. kwargs Returns ------- The ported estimator. """ - pass @abstractmethod def dump( self, language: Optional[Language] = None, template: Optional[Template] = None, directory: Optional[Union[str, Path]] = None, to_json: bool = False, **kwargs ) -> Union[str, Tuple[str, str]]: """ Dump an estimator to the filesystem. Parameters ---------- - method : Method - The required method. language : Language The required language. template : Template The required template directory : str or Path The destination directory. + to_json : bool (default: False) + Return the result as JSON string. kwargs Returns ------- The paths to the dumped files. """ - pass
Remove unused imports and `pass` keywords
## Code Before: from typing import Union, Optional, Tuple from pathlib import Path from abc import ABC, abstractmethod from sklearn_porter.enums import Method, Language, Template class EstimatorApiABC(ABC): """ An abstract interface to ensure equal methods between the main class `sklearn_porter.Estimator` and all subclasses in `sklearn-porter.estimator.*`. """ @abstractmethod def port( self, language: Optional[Language] = None, template: Optional[Template] = None, to_json: bool = False, **kwargs ) -> Union[str, Tuple[str, str]]: """ Port an estimator. Parameters ---------- method : Method The required method. language : Language The required language. template : Template The required template. kwargs Returns ------- The ported estimator. """ pass @abstractmethod def dump( self, language: Optional[Language] = None, template: Optional[Template] = None, directory: Optional[Union[str, Path]] = None, to_json: bool = False, **kwargs ) -> Union[str, Tuple[str, str]]: """ Dump an estimator to the filesystem. Parameters ---------- method : Method The required method. language : Language The required language. template : Template The required template directory : str or Path The destination directory. kwargs Returns ------- The paths to the dumped files. """ pass ## Instruction: Remove unused imports and `pass` keywords ## Code After: from typing import Union, Optional, Tuple from pathlib import Path from abc import ABC, abstractmethod from sklearn_porter.enums import Language, Template class EstimatorApiABC(ABC): """ An abstract interface to ensure equal methods between the main class `sklearn_porter.Estimator` and all subclasses in `sklearn-porter.estimator.*`. """ @abstractmethod def port( self, language: Optional[Language] = None, template: Optional[Template] = None, to_json: bool = False, **kwargs ) -> Union[str, Tuple[str, str]]: """ Port an estimator. Parameters ---------- language : Language The required language. template : Template The required template. to_json : bool (default: False) Return the result as JSON string. kwargs Returns ------- The ported estimator. """ @abstractmethod def dump( self, language: Optional[Language] = None, template: Optional[Template] = None, directory: Optional[Union[str, Path]] = None, to_json: bool = False, **kwargs ) -> Union[str, Tuple[str, str]]: """ Dump an estimator to the filesystem. Parameters ---------- language : Language The required language. template : Template The required template directory : str or Path The destination directory. to_json : bool (default: False) Return the result as JSON string. kwargs Returns ------- The paths to the dumped files. """
... from abc import ABC, abstractmethod from sklearn_porter.enums import Language, Template ... Parameters ---------- language : Language The required language. ... template : Template The required template. to_json : bool (default: False) Return the result as JSON string. kwargs ... The ported estimator. """ @abstractmethod ... Parameters ---------- language : Language The required language. ... directory : str or Path The destination directory. to_json : bool (default: False) Return the result as JSON string. kwargs ... The paths to the dumped files. """ ...
a0863e53ccc8f548486eaa5f3e1f79774dea4b75
tests/api/views/clubs/list_test.py
tests/api/views/clubs/list_test.py
from tests.data import add_fixtures, clubs def test_list_all(db_session, client): sfn = clubs.sfn() lva = clubs.lva() add_fixtures(db_session, sfn, lva) res = client.get("/clubs") assert res.status_code == 200 assert res.json == { "clubs": [ {"id": lva.id, "name": "LV Aachen"}, {"id": sfn.id, "name": "Sportflug Niederberg"}, ] } def test_name_filter(db_session, client): sfn = clubs.sfn() lva = clubs.lva() add_fixtures(db_session, sfn, lva) res = client.get("/clubs?name=LV%20Aachen") assert res.status_code == 200 assert res.json == {"clubs": [{"id": lva.id, "name": "LV Aachen"}]} def test_name_filter_with_unknown_club(db_session, client): res = client.get("/clubs?name=Unknown") assert res.status_code == 200 assert res.json == {"clubs": []}
from pytest_voluptuous import S from voluptuous.validators import ExactSequence from tests.data import add_fixtures, clubs def test_list_all(db_session, client): add_fixtures(db_session, clubs.sfn(), clubs.lva()) res = client.get("/clubs") assert res.status_code == 200 assert res.json == S( { "clubs": ExactSequence( [ {"id": int, "name": "LV Aachen"}, {"id": int, "name": "Sportflug Niederberg"}, ] ) } ) def test_name_filter(db_session, client): add_fixtures(db_session, clubs.sfn(), clubs.lva()) res = client.get("/clubs?name=LV%20Aachen") assert res.status_code == 200 assert res.json == S({"clubs": ExactSequence([{"id": int, "name": "LV Aachen"}])}) def test_name_filter_with_unknown_club(db_session, client): res = client.get("/clubs?name=Unknown") assert res.status_code == 200 assert res.json == S({"clubs": ExactSequence([])})
Use `pytest-voluptuous` to simplify JSON compare code
api/clubs/list/test: Use `pytest-voluptuous` to simplify JSON compare code
Python
agpl-3.0
skylines-project/skylines,skylines-project/skylines,skylines-project/skylines,skylines-project/skylines
+ from pytest_voluptuous import S + from voluptuous.validators import ExactSequence + from tests.data import add_fixtures, clubs def test_list_all(db_session, client): - sfn = clubs.sfn() - lva = clubs.lva() - add_fixtures(db_session, sfn, lva) + add_fixtures(db_session, clubs.sfn(), clubs.lva()) res = client.get("/clubs") assert res.status_code == 200 - assert res.json == { + assert res.json == S( - "clubs": [ - {"id": lva.id, "name": "LV Aachen"}, - {"id": sfn.id, "name": "Sportflug Niederberg"}, - ] + { + "clubs": ExactSequence( + [ + {"id": int, "name": "LV Aachen"}, + {"id": int, "name": "Sportflug Niederberg"}, + ] + ) + } - } + ) def test_name_filter(db_session, client): - sfn = clubs.sfn() - lva = clubs.lva() - add_fixtures(db_session, sfn, lva) + add_fixtures(db_session, clubs.sfn(), clubs.lva()) res = client.get("/clubs?name=LV%20Aachen") assert res.status_code == 200 - assert res.json == {"clubs": [{"id": lva.id, "name": "LV Aachen"}]} + assert res.json == S({"clubs": ExactSequence([{"id": int, "name": "LV Aachen"}])}) def test_name_filter_with_unknown_club(db_session, client): res = client.get("/clubs?name=Unknown") assert res.status_code == 200 - assert res.json == {"clubs": []} + assert res.json == S({"clubs": ExactSequence([])})
Use `pytest-voluptuous` to simplify JSON compare code
## Code Before: from tests.data import add_fixtures, clubs def test_list_all(db_session, client): sfn = clubs.sfn() lva = clubs.lva() add_fixtures(db_session, sfn, lva) res = client.get("/clubs") assert res.status_code == 200 assert res.json == { "clubs": [ {"id": lva.id, "name": "LV Aachen"}, {"id": sfn.id, "name": "Sportflug Niederberg"}, ] } def test_name_filter(db_session, client): sfn = clubs.sfn() lva = clubs.lva() add_fixtures(db_session, sfn, lva) res = client.get("/clubs?name=LV%20Aachen") assert res.status_code == 200 assert res.json == {"clubs": [{"id": lva.id, "name": "LV Aachen"}]} def test_name_filter_with_unknown_club(db_session, client): res = client.get("/clubs?name=Unknown") assert res.status_code == 200 assert res.json == {"clubs": []} ## Instruction: Use `pytest-voluptuous` to simplify JSON compare code ## Code After: from pytest_voluptuous import S from voluptuous.validators import ExactSequence from tests.data import add_fixtures, clubs def test_list_all(db_session, client): add_fixtures(db_session, clubs.sfn(), clubs.lva()) res = client.get("/clubs") assert res.status_code == 200 assert res.json == S( { "clubs": ExactSequence( [ {"id": int, "name": "LV Aachen"}, {"id": int, "name": "Sportflug Niederberg"}, ] ) } ) def test_name_filter(db_session, client): add_fixtures(db_session, clubs.sfn(), clubs.lva()) res = client.get("/clubs?name=LV%20Aachen") assert res.status_code == 200 assert res.json == S({"clubs": ExactSequence([{"id": int, "name": "LV Aachen"}])}) def test_name_filter_with_unknown_club(db_session, client): res = client.get("/clubs?name=Unknown") assert res.status_code == 200 assert res.json == S({"clubs": ExactSequence([])})
// ... existing code ... from pytest_voluptuous import S from voluptuous.validators import ExactSequence from tests.data import add_fixtures, clubs // ... modified code ... def test_list_all(db_session, client): add_fixtures(db_session, clubs.sfn(), clubs.lva()) res = client.get("/clubs") assert res.status_code == 200 assert res.json == S( { "clubs": ExactSequence( [ {"id": int, "name": "LV Aachen"}, {"id": int, "name": "Sportflug Niederberg"}, ] ) } ) def test_name_filter(db_session, client): add_fixtures(db_session, clubs.sfn(), clubs.lva()) res = client.get("/clubs?name=LV%20Aachen") assert res.status_code == 200 assert res.json == S({"clubs": ExactSequence([{"id": int, "name": "LV Aachen"}])}) ... res = client.get("/clubs?name=Unknown") assert res.status_code == 200 assert res.json == S({"clubs": ExactSequence([])}) // ... rest of the code ...
ed05dbf4dc231ea659b19310e6065d4781bd18bc
code/tests/test_smoothing.py
code/tests/test_smoothing.py
# Test method .smooth() smooth1, smooth2 = subtest_runtest1.smooth(0), subtest_runtest1.smooth(1, 5) smooth3 = subtest_runtest1.smooth(2, 0.25) assert [smooth1.max(), smooth1.shape, smooth1.sum()] == [0, (3, 3, 3), 0] assert [smooth2.max(), smooth2.shape, smooth2.sum()] == [1, (3, 3, 3), 27] assert [smooth3.max(), smooth3.shape, smooth3.sum()] == [8, (3, 3, 3), 108] assert [smooth1.std(), smooth2.std()] == [0, 0] assert_almost_equal(smooth3.std(), 1.6329931618554521)
from __future__ import absolute_import, division, print_function from nose.tools import assert_equal from numpy.testing import assert_almost_equal, assert_array_equal import numpy as np import sys sys.path.append("code/utils") from smoothing import * import make_class subtest_runtest1 = make_class.run("test", "001", filtered_data=True) # Test method .smooth() smooth1, smooth2 = subtest_runtest1.smooth(0), subtest_runtest1.smooth(1, 5) smooth3 = subtest_runtest1.smooth(2, 0.25) assert [smooth1.max(), smooth1.shape, smooth1.sum()] == [0, (3, 3, 3), 0] assert [smooth2.max(), smooth2.shape, smooth2.sum()] == [1, (3, 3, 3), 27] assert [smooth3.max(), smooth3.shape, smooth3.sum()] == [8, (3, 3, 3), 108] assert [smooth1.std(), smooth2.std()] == [0, 0] assert_almost_equal(smooth3.std(), 1.6329931618554521)
Add seperate test function for smoothing.py
Add seperate test function for smoothing.py
Python
bsd-3-clause
berkeley-stat159/project-delta
+ + from __future__ import absolute_import, division, print_function + from nose.tools import assert_equal + from numpy.testing import assert_almost_equal, assert_array_equal + import numpy as np + import sys + + sys.path.append("code/utils") + from smoothing import * + import make_class + + subtest_runtest1 = make_class.run("test", "001", filtered_data=True) # Test method .smooth() smooth1, smooth2 = subtest_runtest1.smooth(0), subtest_runtest1.smooth(1, 5) smooth3 = subtest_runtest1.smooth(2, 0.25) assert [smooth1.max(), smooth1.shape, smooth1.sum()] == [0, (3, 3, 3), 0] assert [smooth2.max(), smooth2.shape, smooth2.sum()] == [1, (3, 3, 3), 27] assert [smooth3.max(), smooth3.shape, smooth3.sum()] == [8, (3, 3, 3), 108] assert [smooth1.std(), smooth2.std()] == [0, 0] assert_almost_equal(smooth3.std(), 1.6329931618554521)
Add seperate test function for smoothing.py
## Code Before: # Test method .smooth() smooth1, smooth2 = subtest_runtest1.smooth(0), subtest_runtest1.smooth(1, 5) smooth3 = subtest_runtest1.smooth(2, 0.25) assert [smooth1.max(), smooth1.shape, smooth1.sum()] == [0, (3, 3, 3), 0] assert [smooth2.max(), smooth2.shape, smooth2.sum()] == [1, (3, 3, 3), 27] assert [smooth3.max(), smooth3.shape, smooth3.sum()] == [8, (3, 3, 3), 108] assert [smooth1.std(), smooth2.std()] == [0, 0] assert_almost_equal(smooth3.std(), 1.6329931618554521) ## Instruction: Add seperate test function for smoothing.py ## Code After: from __future__ import absolute_import, division, print_function from nose.tools import assert_equal from numpy.testing import assert_almost_equal, assert_array_equal import numpy as np import sys sys.path.append("code/utils") from smoothing import * import make_class subtest_runtest1 = make_class.run("test", "001", filtered_data=True) # Test method .smooth() smooth1, smooth2 = subtest_runtest1.smooth(0), subtest_runtest1.smooth(1, 5) smooth3 = subtest_runtest1.smooth(2, 0.25) assert [smooth1.max(), smooth1.shape, smooth1.sum()] == [0, (3, 3, 3), 0] assert [smooth2.max(), smooth2.shape, smooth2.sum()] == [1, (3, 3, 3), 27] assert [smooth3.max(), smooth3.shape, smooth3.sum()] == [8, (3, 3, 3), 108] assert [smooth1.std(), smooth2.std()] == [0, 0] assert_almost_equal(smooth3.std(), 1.6329931618554521)
# ... existing code ... from __future__ import absolute_import, division, print_function from nose.tools import assert_equal from numpy.testing import assert_almost_equal, assert_array_equal import numpy as np import sys sys.path.append("code/utils") from smoothing import * import make_class subtest_runtest1 = make_class.run("test", "001", filtered_data=True) # Test method .smooth() # ... rest of the code ...
6c8dd596a0f5f84acee54938d2f948f25445327d
src/Scripts/correlation-histogram.py
src/Scripts/correlation-histogram.py
from collections import defaultdict import csv term_term_correlation = defaultdict(int) term_all_correlation = defaultdict(int) # TODO: don't hardcode name. with open("/tmp/Correlate-0.csv") as f: reader = csv.reader(f) for row in reader: term_all = 0 pos = 0 for item in row: if pos > 0 and pos % 2 == 0: correlation = int(item) term_all += correlation term_term_correlation[correlation] += 1 pos += 1 term_all_correlation[term_all] += 1 def dict_to_csv(dd, filename): with open(filename, 'w') as f: writer = csv.writer(f) for k,v in dd.items(): writer.writerow([k,v]) dict_to_csv(term_term_correlation, "/tmp/term-term.csv") dict_to_csv(term_all_correlation, "/tmp/term-all.csv")
from collections import defaultdict import csv term_term_correlation = defaultdict(lambda:defaultdict(int)) term_all_correlation = defaultdict(lambda:defaultdict(int)) def bf_correlate_to_dicts(term_term_correlation, term_all_correlation, basepath, treatment): filename = basepath + "-" + treatment + ".csv" with open(filename) as f: reader = csv.reader(f) for row in reader: term_all = 0 pos = 0 for item in row: if pos > 0 and pos % 2 == 0: correlation = int(item) term_all += correlation term_term_correlation[treatment][correlation] += 1 pos += 1 term_all_correlation[treatment][term_all] += 1 def dict_to_csv(dd, filename): with open(filename, 'w') as f: writer = csv.writer(f) writer.writerow(["bucket","y","treatment"]) for treatment,subdict in dd.items(): for k, v in subdict.items(): writer.writerow([k,v,treatment]) bf_correlate_to_dicts(term_term_correlation, term_all_correlation, "/tmp/correlate-150k", "rank3-rank0") bf_correlate_to_dicts(term_term_correlation, term_all_correlation, "/tmp/correlate-150k", "rank0") dict_to_csv(term_term_correlation, "/tmp/term-term.csv") dict_to_csv(term_all_correlation, "/tmp/term-all.csv")
Put multple treatments into the same histogram.
Put multple treatments into the same histogram.
Python
mit
danluu/BitFunnel,BitFunnel/BitFunnel,BitFunnel/BitFunnel,danluu/BitFunnel,danluu/BitFunnel,danluu/BitFunnel,BitFunnel/BitFunnel,BitFunnel/BitFunnel,BitFunnel/BitFunnel,danluu/BitFunnel,BitFunnel/BitFunnel,danluu/BitFunnel
from collections import defaultdict import csv - term_term_correlation = defaultdict(int) + term_term_correlation = defaultdict(lambda:defaultdict(int)) - term_all_correlation = defaultdict(int) + term_all_correlation = defaultdict(lambda:defaultdict(int)) - # TODO: don't hardcode name. - with open("/tmp/Correlate-0.csv") as f: + def bf_correlate_to_dicts(term_term_correlation, + term_all_correlation, + basepath, + treatment): + filename = basepath + "-" + treatment + ".csv" + with open(filename) as f: - reader = csv.reader(f) + reader = csv.reader(f) - for row in reader: + for row in reader: - term_all = 0 + term_all = 0 - pos = 0 + pos = 0 - for item in row: + for item in row: - if pos > 0 and pos % 2 == 0: + if pos > 0 and pos % 2 == 0: - correlation = int(item) + correlation = int(item) - term_all += correlation + term_all += correlation - term_term_correlation[correlation] += 1 + term_term_correlation[treatment][correlation] += 1 - pos += 1 + pos += 1 - term_all_correlation[term_all] += 1 + term_all_correlation[treatment][term_all] += 1 def dict_to_csv(dd, filename): with open(filename, 'w') as f: writer = csv.writer(f) + writer.writerow(["bucket","y","treatment"]) + for treatment,subdict in dd.items(): - for k,v in dd.items(): + for k, v in subdict.items(): - writer.writerow([k,v]) + writer.writerow([k,v,treatment]) + bf_correlate_to_dicts(term_term_correlation, + term_all_correlation, + "/tmp/correlate-150k", + "rank3-rank0") + bf_correlate_to_dicts(term_term_correlation, + term_all_correlation, + "/tmp/correlate-150k", + "rank0") dict_to_csv(term_term_correlation, "/tmp/term-term.csv") dict_to_csv(term_all_correlation, "/tmp/term-all.csv")
Put multple treatments into the same histogram.
## Code Before: from collections import defaultdict import csv term_term_correlation = defaultdict(int) term_all_correlation = defaultdict(int) # TODO: don't hardcode name. with open("/tmp/Correlate-0.csv") as f: reader = csv.reader(f) for row in reader: term_all = 0 pos = 0 for item in row: if pos > 0 and pos % 2 == 0: correlation = int(item) term_all += correlation term_term_correlation[correlation] += 1 pos += 1 term_all_correlation[term_all] += 1 def dict_to_csv(dd, filename): with open(filename, 'w') as f: writer = csv.writer(f) for k,v in dd.items(): writer.writerow([k,v]) dict_to_csv(term_term_correlation, "/tmp/term-term.csv") dict_to_csv(term_all_correlation, "/tmp/term-all.csv") ## Instruction: Put multple treatments into the same histogram. ## Code After: from collections import defaultdict import csv term_term_correlation = defaultdict(lambda:defaultdict(int)) term_all_correlation = defaultdict(lambda:defaultdict(int)) def bf_correlate_to_dicts(term_term_correlation, term_all_correlation, basepath, treatment): filename = basepath + "-" + treatment + ".csv" with open(filename) as f: reader = csv.reader(f) for row in reader: term_all = 0 pos = 0 for item in row: if pos > 0 and pos % 2 == 0: correlation = int(item) term_all += correlation term_term_correlation[treatment][correlation] += 1 pos += 1 term_all_correlation[treatment][term_all] += 1 def dict_to_csv(dd, filename): with open(filename, 'w') as f: writer = csv.writer(f) writer.writerow(["bucket","y","treatment"]) for treatment,subdict in dd.items(): for k, v in subdict.items(): writer.writerow([k,v,treatment]) bf_correlate_to_dicts(term_term_correlation, term_all_correlation, "/tmp/correlate-150k", "rank3-rank0") bf_correlate_to_dicts(term_term_correlation, term_all_correlation, "/tmp/correlate-150k", "rank0") dict_to_csv(term_term_correlation, "/tmp/term-term.csv") dict_to_csv(term_all_correlation, "/tmp/term-all.csv")
# ... existing code ... import csv term_term_correlation = defaultdict(lambda:defaultdict(int)) term_all_correlation = defaultdict(lambda:defaultdict(int)) def bf_correlate_to_dicts(term_term_correlation, term_all_correlation, basepath, treatment): filename = basepath + "-" + treatment + ".csv" with open(filename) as f: reader = csv.reader(f) for row in reader: term_all = 0 pos = 0 for item in row: if pos > 0 and pos % 2 == 0: correlation = int(item) term_all += correlation term_term_correlation[treatment][correlation] += 1 pos += 1 term_all_correlation[treatment][term_all] += 1 def dict_to_csv(dd, filename): # ... modified code ... with open(filename, 'w') as f: writer = csv.writer(f) writer.writerow(["bucket","y","treatment"]) for treatment,subdict in dd.items(): for k, v in subdict.items(): writer.writerow([k,v,treatment]) bf_correlate_to_dicts(term_term_correlation, term_all_correlation, "/tmp/correlate-150k", "rank3-rank0") bf_correlate_to_dicts(term_term_correlation, term_all_correlation, "/tmp/correlate-150k", "rank0") dict_to_csv(term_term_correlation, "/tmp/term-term.csv") dict_to_csv(term_all_correlation, "/tmp/term-all.csv") # ... rest of the code ...
73b7da1a0360f50e660e1983ec02dd5225bde3a3
mitmproxy/platform/__init__.py
mitmproxy/platform/__init__.py
import sys resolver = None if sys.platform == "linux2": from . import linux resolver = linux.Resolver elif sys.platform == "darwin": from . import osx resolver = osx.Resolver elif sys.platform.startswith("freebsd"): from . import osx resolver = osx.Resolver elif sys.platform == "win32": from . import windows resolver = windows.Resolver
import sys import re resolver = None if re.match(r"linux(?:2)?", sys.platform): from . import linux resolver = linux.Resolver elif sys.platform == "darwin": from . import osx resolver = osx.Resolver elif sys.platform.startswith("freebsd"): from . import osx resolver = osx.Resolver elif sys.platform == "win32": from . import windows resolver = windows.Resolver
Fix platform import on Linux using python3
Fix platform import on Linux using python3 Using python3, sys.platform returns "linux" instead of "linux2" using python2. This patch accepts "linux" as well as "linux2".
Python
mit
mosajjal/mitmproxy,vhaupert/mitmproxy,laurmurclar/mitmproxy,Kriechi/mitmproxy,dwfreed/mitmproxy,xaxa89/mitmproxy,ujjwal96/mitmproxy,mosajjal/mitmproxy,Kriechi/mitmproxy,mitmproxy/mitmproxy,mitmproxy/mitmproxy,laurmurclar/mitmproxy,ujjwal96/mitmproxy,vhaupert/mitmproxy,zlorb/mitmproxy,StevenVanAcker/mitmproxy,Kriechi/mitmproxy,ddworken/mitmproxy,mitmproxy/mitmproxy,mosajjal/mitmproxy,ujjwal96/mitmproxy,mhils/mitmproxy,mosajjal/mitmproxy,StevenVanAcker/mitmproxy,xaxa89/mitmproxy,cortesi/mitmproxy,StevenVanAcker/mitmproxy,zlorb/mitmproxy,MatthewShao/mitmproxy,StevenVanAcker/mitmproxy,mhils/mitmproxy,zlorb/mitmproxy,mitmproxy/mitmproxy,dwfreed/mitmproxy,MatthewShao/mitmproxy,jvillacorta/mitmproxy,mhils/mitmproxy,MatthewShao/mitmproxy,Kriechi/mitmproxy,xaxa89/mitmproxy,ddworken/mitmproxy,mitmproxy/mitmproxy,dwfreed/mitmproxy,ddworken/mitmproxy,cortesi/mitmproxy,laurmurclar/mitmproxy,cortesi/mitmproxy,jvillacorta/mitmproxy,dwfreed/mitmproxy,MatthewShao/mitmproxy,mhils/mitmproxy,ujjwal96/mitmproxy,mhils/mitmproxy,vhaupert/mitmproxy,ddworken/mitmproxy,xaxa89/mitmproxy,vhaupert/mitmproxy,cortesi/mitmproxy,jvillacorta/mitmproxy,jvillacorta/mitmproxy,zlorb/mitmproxy,laurmurclar/mitmproxy
import sys + import re resolver = None - if sys.platform == "linux2": + if re.match(r"linux(?:2)?", sys.platform): from . import linux resolver = linux.Resolver elif sys.platform == "darwin": from . import osx resolver = osx.Resolver elif sys.platform.startswith("freebsd"): from . import osx resolver = osx.Resolver elif sys.platform == "win32": from . import windows resolver = windows.Resolver
Fix platform import on Linux using python3
## Code Before: import sys resolver = None if sys.platform == "linux2": from . import linux resolver = linux.Resolver elif sys.platform == "darwin": from . import osx resolver = osx.Resolver elif sys.platform.startswith("freebsd"): from . import osx resolver = osx.Resolver elif sys.platform == "win32": from . import windows resolver = windows.Resolver ## Instruction: Fix platform import on Linux using python3 ## Code After: import sys import re resolver = None if re.match(r"linux(?:2)?", sys.platform): from . import linux resolver = linux.Resolver elif sys.platform == "darwin": from . import osx resolver = osx.Resolver elif sys.platform.startswith("freebsd"): from . import osx resolver = osx.Resolver elif sys.platform == "win32": from . import windows resolver = windows.Resolver
... import sys import re resolver = None if re.match(r"linux(?:2)?", sys.platform): from . import linux resolver = linux.Resolver ...
78ec1cffde6443016bae2c8aefdb67ab26bfab10
__init__.py
__init__.py
from . import OctoPrintOutputDevicePlugin from . import DiscoverOctoPrintAction from UM.i18n import i18nCatalog catalog = i18nCatalog("cura") def getMetaData(): return { "type": "extension", "plugin": { "name": "Wifi connection", "author": "Ultimaker", "description": catalog.i18nc("Wifi connection", "Wifi connection"), "api": 3 } } def register(app): return { "output_device": OctoPrintOutputDevicePlugin.OctoPrintOutputDevicePlugin(), "machine_action": DiscoverOctoPrintAction.DiscoverOctoPrintAction() }
from . import OctoPrintOutputDevicePlugin from . import DiscoverOctoPrintAction from UM.i18n import i18nCatalog catalog = i18nCatalog("cura") def getMetaData(): return { "type": "extension", "plugin": { "name": "OctoPrint connection", "author": "fieldOfView", "version": "1.0", "description": catalog.i18nc("@info:whatsthis", "Allows sending prints to OctoPrint and monitoring the progress"), "api": 3 } } def register(app): return { "output_device": OctoPrintOutputDevicePlugin.OctoPrintOutputDevicePlugin(), "machine_action": DiscoverOctoPrintAction.DiscoverOctoPrintAction() }
Update plugin information (name, description, version, author)
Update plugin information (name, description, version, author)
Python
agpl-3.0
fieldOfView/OctoPrintPlugin
from . import OctoPrintOutputDevicePlugin from . import DiscoverOctoPrintAction from UM.i18n import i18nCatalog catalog = i18nCatalog("cura") def getMetaData(): return { "type": "extension", "plugin": { - "name": "Wifi connection", + "name": "OctoPrint connection", - "author": "Ultimaker", + "author": "fieldOfView", - "description": catalog.i18nc("Wifi connection", "Wifi connection"), + "version": "1.0", + "description": catalog.i18nc("@info:whatsthis", "Allows sending prints to OctoPrint and monitoring the progress"), "api": 3 } } def register(app): return { "output_device": OctoPrintOutputDevicePlugin.OctoPrintOutputDevicePlugin(), "machine_action": DiscoverOctoPrintAction.DiscoverOctoPrintAction() }
Update plugin information (name, description, version, author)
## Code Before: from . import OctoPrintOutputDevicePlugin from . import DiscoverOctoPrintAction from UM.i18n import i18nCatalog catalog = i18nCatalog("cura") def getMetaData(): return { "type": "extension", "plugin": { "name": "Wifi connection", "author": "Ultimaker", "description": catalog.i18nc("Wifi connection", "Wifi connection"), "api": 3 } } def register(app): return { "output_device": OctoPrintOutputDevicePlugin.OctoPrintOutputDevicePlugin(), "machine_action": DiscoverOctoPrintAction.DiscoverOctoPrintAction() } ## Instruction: Update plugin information (name, description, version, author) ## Code After: from . import OctoPrintOutputDevicePlugin from . import DiscoverOctoPrintAction from UM.i18n import i18nCatalog catalog = i18nCatalog("cura") def getMetaData(): return { "type": "extension", "plugin": { "name": "OctoPrint connection", "author": "fieldOfView", "version": "1.0", "description": catalog.i18nc("@info:whatsthis", "Allows sending prints to OctoPrint and monitoring the progress"), "api": 3 } } def register(app): return { "output_device": OctoPrintOutputDevicePlugin.OctoPrintOutputDevicePlugin(), "machine_action": DiscoverOctoPrintAction.DiscoverOctoPrintAction() }
... "type": "extension", "plugin": { "name": "OctoPrint connection", "author": "fieldOfView", "version": "1.0", "description": catalog.i18nc("@info:whatsthis", "Allows sending prints to OctoPrint and monitoring the progress"), "api": 3 } ...
fb21faaec025a0a6ca2d98c8b2381902f3b1444a
pybug/align/lucaskanade/__init__.py
pybug/align/lucaskanade/__init__.py
import appearance import image from residual import (LSIntensity, ECC, GradientImages, GradientCorrelation)
import appearance import image from residual import (LSIntensity, ECC, GaborFourier, GradientImages, GradientCorrelation)
Add GaborFourier to default import
Add GaborFourier to default import
Python
bsd-3-clause
menpo/menpo,yuxiang-zhou/menpo,grigorisg9gr/menpo,mozata/menpo,mozata/menpo,mozata/menpo,mozata/menpo,grigorisg9gr/menpo,menpo/menpo,menpo/menpo,jabooth/menpo-archive,jabooth/menpo-archive,jabooth/menpo-archive,yuxiang-zhou/menpo,grigorisg9gr/menpo,patricksnape/menpo,yuxiang-zhou/menpo,jabooth/menpo-archive,patricksnape/menpo,patricksnape/menpo
import appearance import image from residual import (LSIntensity, ECC, + GaborFourier, GradientImages, GradientCorrelation)
Add GaborFourier to default import
## Code Before: import appearance import image from residual import (LSIntensity, ECC, GradientImages, GradientCorrelation) ## Instruction: Add GaborFourier to default import ## Code After: import appearance import image from residual import (LSIntensity, ECC, GaborFourier, GradientImages, GradientCorrelation)
# ... existing code ... from residual import (LSIntensity, ECC, GaborFourier, GradientImages, GradientCorrelation) # ... rest of the code ...
b06f0e17541f7d424e73fd200ae10db0722b1a5a
organizer/views.py
organizer/views.py
from django.shortcuts import ( get_object_or_404, render) from .forms import TagForm from .models import Startup, Tag def startup_detail(request, slug): startup = get_object_or_404( Startup, slug__iexact=slug) return render( request, 'organizer/startup_detail.html', {'startup': startup}) def startup_list(request): return render( request, 'organizer/startup_list.html', {'startup_list': Startup.objects.all()}) def tag_create(request): if request.method == 'POST': form = TagForm(request.POST) if form.is_valid(): # create new object from data # show webpage for new object pass else: # empty data or invalid data # show bound HTML form (with errors) pass else: # request.method != 'POST' # show unbound HTML form pass def tag_detail(request, slug): tag = get_object_or_404( Tag, slug__iexact=slug) return render( request, 'organizer/tag_detail.html', {'tag': tag}) def tag_list(request): return render( request, 'organizer/tag_list.html', {'tag_list': Tag.objects.all()})
from django.shortcuts import ( get_object_or_404, redirect, render) from .forms import TagForm from .models import Startup, Tag def startup_detail(request, slug): startup = get_object_or_404( Startup, slug__iexact=slug) return render( request, 'organizer/startup_detail.html', {'startup': startup}) def startup_list(request): return render( request, 'organizer/startup_list.html', {'startup_list': Startup.objects.all()}) def tag_create(request): if request.method == 'POST': form = TagForm(request.POST) if form.is_valid(): new_tag = form.save() return redirect(new_tag) else: # empty data or invalid data # show bound HTML form (with errors) pass else: # request.method != 'POST' # show unbound HTML form pass def tag_detail(request, slug): tag = get_object_or_404( Tag, slug__iexact=slug) return render( request, 'organizer/tag_detail.html', {'tag': tag}) def tag_list(request): return render( request, 'organizer/tag_list.html', {'tag_list': Tag.objects.all()})
Create and redirect to Tag in tag_create().
Ch09: Create and redirect to Tag in tag_create().
Python
bsd-2-clause
jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8
from django.shortcuts import ( - get_object_or_404, render) + get_object_or_404, redirect, render) from .forms import TagForm from .models import Startup, Tag def startup_detail(request, slug): startup = get_object_or_404( Startup, slug__iexact=slug) return render( request, 'organizer/startup_detail.html', {'startup': startup}) def startup_list(request): return render( request, 'organizer/startup_list.html', {'startup_list': Startup.objects.all()}) def tag_create(request): if request.method == 'POST': form = TagForm(request.POST) if form.is_valid(): + new_tag = form.save() + return redirect(new_tag) - # create new object from data - # show webpage for new object - pass else: # empty data or invalid data # show bound HTML form (with errors) pass else: # request.method != 'POST' # show unbound HTML form pass def tag_detail(request, slug): tag = get_object_or_404( Tag, slug__iexact=slug) return render( request, 'organizer/tag_detail.html', {'tag': tag}) def tag_list(request): return render( request, 'organizer/tag_list.html', {'tag_list': Tag.objects.all()})
Create and redirect to Tag in tag_create().
## Code Before: from django.shortcuts import ( get_object_or_404, render) from .forms import TagForm from .models import Startup, Tag def startup_detail(request, slug): startup = get_object_or_404( Startup, slug__iexact=slug) return render( request, 'organizer/startup_detail.html', {'startup': startup}) def startup_list(request): return render( request, 'organizer/startup_list.html', {'startup_list': Startup.objects.all()}) def tag_create(request): if request.method == 'POST': form = TagForm(request.POST) if form.is_valid(): # create new object from data # show webpage for new object pass else: # empty data or invalid data # show bound HTML form (with errors) pass else: # request.method != 'POST' # show unbound HTML form pass def tag_detail(request, slug): tag = get_object_or_404( Tag, slug__iexact=slug) return render( request, 'organizer/tag_detail.html', {'tag': tag}) def tag_list(request): return render( request, 'organizer/tag_list.html', {'tag_list': Tag.objects.all()}) ## Instruction: Create and redirect to Tag in tag_create(). ## Code After: from django.shortcuts import ( get_object_or_404, redirect, render) from .forms import TagForm from .models import Startup, Tag def startup_detail(request, slug): startup = get_object_or_404( Startup, slug__iexact=slug) return render( request, 'organizer/startup_detail.html', {'startup': startup}) def startup_list(request): return render( request, 'organizer/startup_list.html', {'startup_list': Startup.objects.all()}) def tag_create(request): if request.method == 'POST': form = TagForm(request.POST) if form.is_valid(): new_tag = form.save() return redirect(new_tag) else: # empty data or invalid data # show bound HTML form (with errors) pass else: # request.method != 'POST' # show unbound HTML form pass def tag_detail(request, slug): tag = get_object_or_404( Tag, slug__iexact=slug) return render( request, 'organizer/tag_detail.html', {'tag': tag}) def tag_list(request): return render( request, 'organizer/tag_list.html', {'tag_list': Tag.objects.all()})
... from django.shortcuts import ( get_object_or_404, redirect, render) from .forms import TagForm ... form = TagForm(request.POST) if form.is_valid(): new_tag = form.save() return redirect(new_tag) else: # empty data or invalid data # show bound HTML form (with errors) ...
9b8d18d52ef6ddd5009a448bcaf003435b387e72
wake/views.py
wake/views.py
from been.couch import CouchStore from flask import render_template from wake import app store = CouchStore().load() @app.route('/') def wake(): return render_template('stream.html', events=store.collapsed_events())
from been.couch import CouchStore from flask import render_template, abort from wake import app store = CouchStore().load() @app.route('/') def wake(): return render_template('stream.html', events=store.collapsed_events()) @app.route('/<slug>') def by_slug(slug): events = list(store.events_by_slug(slug)) if not events: abort(404) return render_template('stream.html', events=events)
Add by_slug view for single events.
Add by_slug view for single events.
Python
bsd-3-clause
chromakode/wake
from been.couch import CouchStore - from flask import render_template + from flask import render_template, abort from wake import app store = CouchStore().load() @app.route('/') def wake(): return render_template('stream.html', events=store.collapsed_events()) + @app.route('/<slug>') + def by_slug(slug): + events = list(store.events_by_slug(slug)) + if not events: + abort(404) + return render_template('stream.html', events=events) + +
Add by_slug view for single events.
## Code Before: from been.couch import CouchStore from flask import render_template from wake import app store = CouchStore().load() @app.route('/') def wake(): return render_template('stream.html', events=store.collapsed_events()) ## Instruction: Add by_slug view for single events. ## Code After: from been.couch import CouchStore from flask import render_template, abort from wake import app store = CouchStore().load() @app.route('/') def wake(): return render_template('stream.html', events=store.collapsed_events()) @app.route('/<slug>') def by_slug(slug): events = list(store.events_by_slug(slug)) if not events: abort(404) return render_template('stream.html', events=events)
// ... existing code ... from been.couch import CouchStore from flask import render_template, abort from wake import app // ... modified code ... def wake(): return render_template('stream.html', events=store.collapsed_events()) @app.route('/<slug>') def by_slug(slug): events = list(store.events_by_slug(slug)) if not events: abort(404) return render_template('stream.html', events=events) // ... rest of the code ...
d90d91906981a4393810069b494d68230f17439e
frameworks/Scala/spray/setup.py
frameworks/Scala/spray/setup.py
import subprocess import sys import time import os def start(args, logfile, errfile): if os.name == 'nt': subprocess.check_call('"..\\sbt\\sbt.bat" assembly', shell=True, cwd="spray", stderr=errfile, stdout=logfile) else: subprocess.check_call("../sbt/sbt assembly", shell=True, cwd="spray", stderr=errfile, stdout=logfile) subprocess.Popen("java -jar target/scala-2.10/spray-benchmark-assembly-1.0.jar", cwd="spray", shell=True, stderr=errfile, stdout=logfile) time.sleep(5) return 0 def stop(logfile, errfile): if os.name == 'nt': subprocess.check_call("wmic process where \"CommandLine LIKE '%spray-benchmark%'\" call terminate", stderr=errfile, stdout=logfile) else: p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE) out, err = p.communicate() for line in out.splitlines(): if 'spray-benchmark' in line: try: pid = int(line.split(None, 2)[1]) os.kill(pid, 15) except OSError: pass return 0
import subprocess import sys import time import os def start(args, logfile, errfile): if os.name == 'nt': subprocess.check_call('"..\\sbt\\sbt.bat" assembly', shell=True, cwd="spray", stderr=errfile, stdout=logfile) else: subprocess.check_call("$FWROOT/sbt/sbt assembly", shell=True, cwd="spray", stderr=errfile, stdout=logfile) subprocess.Popen("java -jar target/scala-2.10/spray-benchmark-assembly-1.0.jar", cwd="spray", shell=True, stderr=errfile, stdout=logfile) return 0 def stop(logfile, errfile): if os.name == 'nt': subprocess.check_call("wmic process where \"CommandLine LIKE '%spray-benchmark%'\" call terminate", stderr=errfile, stdout=logfile) else: p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE) out, err = p.communicate() for line in out.splitlines(): if 'spray-benchmark' in line: try: pid = int(line.split(None, 2)[1]) os.kill(pid, 15) except OSError: pass return 0
Enable spray to find sbt
Enable spray to find sbt
Python
bsd-3-clause
zane-techempower/FrameworkBenchmarks,denkab/FrameworkBenchmarks,Verber/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,zapov/FrameworkBenchmarks,herloct/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,sgml/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,joshk/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,valyala/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,sgml/FrameworkBenchmarks,sgml/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,zapov/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,joshk/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,denkab/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,testn/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,zapov/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,khellang/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,valyala/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,herloct/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,Verber/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,doom369/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,zloster/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,jamming/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,testn/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,khellang/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,testn/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,grob/FrameworkBenchmarks,torhve/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,testn/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,methane/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,denkab/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,doom369/FrameworkBenchmarks,sgml/FrameworkBenchmarks,testn/FrameworkBenchmarks,actframework/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,doom369/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,sgml/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,grob/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,zloster/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,Verber/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,sgml/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,valyala/FrameworkBenchmarks,testn/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,torhve/FrameworkBenchmarks,actframework/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,valyala/FrameworkBenchmarks,valyala/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,actframework/FrameworkBenchmarks,sxend/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,Verber/FrameworkBenchmarks,zapov/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,zloster/FrameworkBenchmarks,jamming/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,joshk/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,herloct/FrameworkBenchmarks,sxend/FrameworkBenchmarks,doom369/FrameworkBenchmarks,actframework/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,denkab/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,valyala/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,sxend/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,sgml/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,torhve/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,zloster/FrameworkBenchmarks,zapov/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,actframework/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,zloster/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,grob/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,valyala/FrameworkBenchmarks,zloster/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,zapov/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,denkab/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,Verber/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,joshk/FrameworkBenchmarks,jamming/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,actframework/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,valyala/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,methane/FrameworkBenchmarks,sxend/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,actframework/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,valyala/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,grob/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,sxend/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,doom369/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,testn/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,doom369/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,denkab/FrameworkBenchmarks,zapov/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,methane/FrameworkBenchmarks,jamming/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,doom369/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,sxend/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,actframework/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,khellang/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,grob/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,denkab/FrameworkBenchmarks,doom369/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,denkab/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,zloster/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,doom369/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,actframework/FrameworkBenchmarks,zloster/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,denkab/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,doom369/FrameworkBenchmarks,jamming/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,valyala/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,grob/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,zapov/FrameworkBenchmarks,actframework/FrameworkBenchmarks,zapov/FrameworkBenchmarks,doom369/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,sxend/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,joshk/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,Verber/FrameworkBenchmarks,doom369/FrameworkBenchmarks,zapov/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,jamming/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,herloct/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,zapov/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,zapov/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,Verber/FrameworkBenchmarks,valyala/FrameworkBenchmarks,zloster/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,denkab/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,torhve/FrameworkBenchmarks,khellang/FrameworkBenchmarks,methane/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,herloct/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,testn/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,sxend/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,torhve/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,doom369/FrameworkBenchmarks,khellang/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,Verber/FrameworkBenchmarks,khellang/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,Verber/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,valyala/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,herloct/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,sgml/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,joshk/FrameworkBenchmarks,denkab/FrameworkBenchmarks,khellang/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,torhve/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,zloster/FrameworkBenchmarks,methane/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,sxend/FrameworkBenchmarks,Verber/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,testn/FrameworkBenchmarks,testn/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,testn/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,methane/FrameworkBenchmarks,Verber/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,khellang/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,sxend/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,denkab/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,joshk/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,doom369/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,actframework/FrameworkBenchmarks,torhve/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,actframework/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,khellang/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,valyala/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,grob/FrameworkBenchmarks,herloct/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,testn/FrameworkBenchmarks,torhve/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,khellang/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,methane/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,zloster/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,jamming/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,zapov/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,grob/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,methane/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,Verber/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,herloct/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,khellang/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,methane/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,zapov/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,zloster/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,herloct/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,khellang/FrameworkBenchmarks,sgml/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,zloster/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,sxend/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,actframework/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,herloct/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,jamming/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,Verber/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,jamming/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,grob/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,torhve/FrameworkBenchmarks,sxend/FrameworkBenchmarks,Verber/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,sxend/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,joshk/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,torhve/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,joshk/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,actframework/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,grob/FrameworkBenchmarks,methane/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,methane/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,zapov/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,sxend/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,doom369/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,testn/FrameworkBenchmarks,sgml/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,khellang/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,grob/FrameworkBenchmarks,methane/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,herloct/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,zloster/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,herloct/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,doom369/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,joshk/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,sgml/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,valyala/FrameworkBenchmarks,grob/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,methane/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,zloster/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,khellang/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,jamming/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,zloster/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,actframework/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,grob/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,doom369/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,herloct/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,sxend/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,sgml/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,denkab/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,denkab/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,jamming/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,sgml/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,joshk/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,zloster/FrameworkBenchmarks,torhve/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,jamming/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,zloster/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,methane/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,torhve/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,actframework/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,sxend/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,testn/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,sxend/FrameworkBenchmarks,joshk/FrameworkBenchmarks,grob/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,joshk/FrameworkBenchmarks,jamming/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,sgml/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,herloct/FrameworkBenchmarks,sxend/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,jamming/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,zapov/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,herloct/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,joshk/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks
import subprocess import sys import time import os def start(args, logfile, errfile): if os.name == 'nt': subprocess.check_call('"..\\sbt\\sbt.bat" assembly', shell=True, cwd="spray", stderr=errfile, stdout=logfile) else: - subprocess.check_call("../sbt/sbt assembly", shell=True, cwd="spray", stderr=errfile, stdout=logfile) + subprocess.check_call("$FWROOT/sbt/sbt assembly", shell=True, cwd="spray", stderr=errfile, stdout=logfile) subprocess.Popen("java -jar target/scala-2.10/spray-benchmark-assembly-1.0.jar", cwd="spray", shell=True, stderr=errfile, stdout=logfile) - time.sleep(5) return 0 def stop(logfile, errfile): if os.name == 'nt': subprocess.check_call("wmic process where \"CommandLine LIKE '%spray-benchmark%'\" call terminate", stderr=errfile, stdout=logfile) else: p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE) out, err = p.communicate() for line in out.splitlines(): if 'spray-benchmark' in line: try: pid = int(line.split(None, 2)[1]) os.kill(pid, 15) except OSError: pass return 0
Enable spray to find sbt
## Code Before: import subprocess import sys import time import os def start(args, logfile, errfile): if os.name == 'nt': subprocess.check_call('"..\\sbt\\sbt.bat" assembly', shell=True, cwd="spray", stderr=errfile, stdout=logfile) else: subprocess.check_call("../sbt/sbt assembly", shell=True, cwd="spray", stderr=errfile, stdout=logfile) subprocess.Popen("java -jar target/scala-2.10/spray-benchmark-assembly-1.0.jar", cwd="spray", shell=True, stderr=errfile, stdout=logfile) time.sleep(5) return 0 def stop(logfile, errfile): if os.name == 'nt': subprocess.check_call("wmic process where \"CommandLine LIKE '%spray-benchmark%'\" call terminate", stderr=errfile, stdout=logfile) else: p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE) out, err = p.communicate() for line in out.splitlines(): if 'spray-benchmark' in line: try: pid = int(line.split(None, 2)[1]) os.kill(pid, 15) except OSError: pass return 0 ## Instruction: Enable spray to find sbt ## Code After: import subprocess import sys import time import os def start(args, logfile, errfile): if os.name == 'nt': subprocess.check_call('"..\\sbt\\sbt.bat" assembly', shell=True, cwd="spray", stderr=errfile, stdout=logfile) else: subprocess.check_call("$FWROOT/sbt/sbt assembly", shell=True, cwd="spray", stderr=errfile, stdout=logfile) subprocess.Popen("java -jar target/scala-2.10/spray-benchmark-assembly-1.0.jar", cwd="spray", shell=True, stderr=errfile, stdout=logfile) return 0 def stop(logfile, errfile): if os.name == 'nt': subprocess.check_call("wmic process where \"CommandLine LIKE '%spray-benchmark%'\" call terminate", stderr=errfile, stdout=logfile) else: p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE) out, err = p.communicate() for line in out.splitlines(): if 'spray-benchmark' in line: try: pid = int(line.split(None, 2)[1]) os.kill(pid, 15) except OSError: pass return 0
# ... existing code ... subprocess.check_call('"..\\sbt\\sbt.bat" assembly', shell=True, cwd="spray", stderr=errfile, stdout=logfile) else: subprocess.check_call("$FWROOT/sbt/sbt assembly", shell=True, cwd="spray", stderr=errfile, stdout=logfile) subprocess.Popen("java -jar target/scala-2.10/spray-benchmark-assembly-1.0.jar", cwd="spray", shell=True, stderr=errfile, stdout=logfile) return 0 # ... rest of the code ...
fda08d81e3b6a4aae5610973053890bf8b283bf0
buffer/tests/test_profile.py
buffer/tests/test_profile.py
import json from nose.tools import eq_, raises from mock import MagicMock, patch from buffer.models.profile import Profile, PATHS mocked_response = { 'name': 'me', 'service': 'twiter', 'id': 1 } def test_profile_schedules_getter(): ''' Test schedules gettering from buffer api ''' mocked_api = MagicMock() mocked_api.get.return_value = '123' profile = Profile(mocked_api, mocked_response) eq_(profile.schedules, '123') mocked_api.get.assert_called_once_with(url = PATHS['GET_SCHEDULES'] % 1) def test_profile_schedules_setter(): ''' Test schedules setter from buffer api ''' mocked_api = MagicMock() mocked_api.get.return_value = '123' profile = Profile(mocked_api, mocked_response) profile.schedules = { 'times': ['mo'] } mocked_api.post.assert_called_once_with(url=PATHS['UPDATE_SCHEDULES'] % 1, data='schedules[0][times][]=mo&')
import json from nose.tools import eq_, raises from mock import MagicMock, patch from buffer.models.profile import Profile, PATHS mocked_response = { 'name': 'me', 'service': 'twiter', 'id': 1 } def test_profile_schedules_getter(): ''' Test schedules gettering from buffer api ''' mocked_api = MagicMock() mocked_api.get.return_value = '123' profile = Profile(mocked_api, mocked_response) eq_(profile.schedules, '123') mocked_api.get.assert_called_once_with(url = PATHS['GET_SCHEDULES'] % 1) def test_profile_schedules_setter(): ''' Test schedules setter from buffer api ''' mocked_api = MagicMock() mocked_api.get.return_value = '123' profile = Profile(mocked_api, mocked_response) profile.schedules = { 'times': ['mo'] } mocked_api.post.assert_called_once_with(url=PATHS['UPDATE_SCHEDULES'] % 1, data='schedules[0][times][]=mo&') def test_profile_updates(): ''' Test updates relationship with a profile ''' mocked_api = MagicMock() with patch('buffer.models.profile.Updates') as mocked_updates: profile = Profile(api=mocked_api, raw_response={'id': 1}) updates = profile.updates mocked_updates.assert_called_once_with(api=mocked_api, profile_id=1)
Test profile's relationship with updates
Test profile's relationship with updates
Python
mit
vtemian/buffpy,bufferapp/buffer-python
import json from nose.tools import eq_, raises from mock import MagicMock, patch from buffer.models.profile import Profile, PATHS mocked_response = { 'name': 'me', 'service': 'twiter', 'id': 1 } def test_profile_schedules_getter(): ''' Test schedules gettering from buffer api ''' mocked_api = MagicMock() mocked_api.get.return_value = '123' profile = Profile(mocked_api, mocked_response) eq_(profile.schedules, '123') mocked_api.get.assert_called_once_with(url = PATHS['GET_SCHEDULES'] % 1) def test_profile_schedules_setter(): ''' Test schedules setter from buffer api ''' mocked_api = MagicMock() mocked_api.get.return_value = '123' profile = Profile(mocked_api, mocked_response) profile.schedules = { 'times': ['mo'] } mocked_api.post.assert_called_once_with(url=PATHS['UPDATE_SCHEDULES'] % 1, data='schedules[0][times][]=mo&') + def test_profile_updates(): + ''' + Test updates relationship with a profile + ''' + + mocked_api = MagicMock() + + with patch('buffer.models.profile.Updates') as mocked_updates: + profile = Profile(api=mocked_api, raw_response={'id': 1}) + updates = profile.updates + + mocked_updates.assert_called_once_with(api=mocked_api, profile_id=1) +
Test profile's relationship with updates
## Code Before: import json from nose.tools import eq_, raises from mock import MagicMock, patch from buffer.models.profile import Profile, PATHS mocked_response = { 'name': 'me', 'service': 'twiter', 'id': 1 } def test_profile_schedules_getter(): ''' Test schedules gettering from buffer api ''' mocked_api = MagicMock() mocked_api.get.return_value = '123' profile = Profile(mocked_api, mocked_response) eq_(profile.schedules, '123') mocked_api.get.assert_called_once_with(url = PATHS['GET_SCHEDULES'] % 1) def test_profile_schedules_setter(): ''' Test schedules setter from buffer api ''' mocked_api = MagicMock() mocked_api.get.return_value = '123' profile = Profile(mocked_api, mocked_response) profile.schedules = { 'times': ['mo'] } mocked_api.post.assert_called_once_with(url=PATHS['UPDATE_SCHEDULES'] % 1, data='schedules[0][times][]=mo&') ## Instruction: Test profile's relationship with updates ## Code After: import json from nose.tools import eq_, raises from mock import MagicMock, patch from buffer.models.profile import Profile, PATHS mocked_response = { 'name': 'me', 'service': 'twiter', 'id': 1 } def test_profile_schedules_getter(): ''' Test schedules gettering from buffer api ''' mocked_api = MagicMock() mocked_api.get.return_value = '123' profile = Profile(mocked_api, mocked_response) eq_(profile.schedules, '123') mocked_api.get.assert_called_once_with(url = PATHS['GET_SCHEDULES'] % 1) def test_profile_schedules_setter(): ''' Test schedules setter from buffer api ''' mocked_api = MagicMock() mocked_api.get.return_value = '123' profile = Profile(mocked_api, mocked_response) profile.schedules = { 'times': ['mo'] } mocked_api.post.assert_called_once_with(url=PATHS['UPDATE_SCHEDULES'] % 1, data='schedules[0][times][]=mo&') def test_profile_updates(): ''' Test updates relationship with a profile ''' mocked_api = MagicMock() with patch('buffer.models.profile.Updates') as mocked_updates: profile = Profile(api=mocked_api, raw_response={'id': 1}) updates = profile.updates mocked_updates.assert_called_once_with(api=mocked_api, profile_id=1)
# ... existing code ... mocked_api.post.assert_called_once_with(url=PATHS['UPDATE_SCHEDULES'] % 1, data='schedules[0][times][]=mo&') def test_profile_updates(): ''' Test updates relationship with a profile ''' mocked_api = MagicMock() with patch('buffer.models.profile.Updates') as mocked_updates: profile = Profile(api=mocked_api, raw_response={'id': 1}) updates = profile.updates mocked_updates.assert_called_once_with(api=mocked_api, profile_id=1) # ... rest of the code ...
599f093ba30afbf169f21559ca247eaba99dcebf
samples/custom/forms.py
samples/custom/forms.py
from django import forms class YesNoIgnoredField(forms.NullBooleanField): widget = forms.widgets.RadioSelect( choices=( (True, "Sim"), (False, "Não"), (None, "Ignorado"), ), )
from django import forms class YesNoIgnoredField(forms.NullBooleanField): widget = forms.widgets.RadioSelect( attrs={'class': 'inline'}, choices=( (True, "Sim"), (False, "Não"), (None, "Ignorado"), ), )
Add inline class to YesNoIgnored field
:memo: Add inline class to YesNoIgnored field
Python
mit
gcrsaldanha/fiocruz,gems-uff/labsys,gcrsaldanha/fiocruz,gems-uff/labsys,gems-uff/labsys
from django import forms class YesNoIgnoredField(forms.NullBooleanField): widget = forms.widgets.RadioSelect( + attrs={'class': 'inline'}, choices=( (True, "Sim"), (False, "Não"), (None, "Ignorado"), ), )
Add inline class to YesNoIgnored field
## Code Before: from django import forms class YesNoIgnoredField(forms.NullBooleanField): widget = forms.widgets.RadioSelect( choices=( (True, "Sim"), (False, "Não"), (None, "Ignorado"), ), ) ## Instruction: Add inline class to YesNoIgnored field ## Code After: from django import forms class YesNoIgnoredField(forms.NullBooleanField): widget = forms.widgets.RadioSelect( attrs={'class': 'inline'}, choices=( (True, "Sim"), (False, "Não"), (None, "Ignorado"), ), )
... class YesNoIgnoredField(forms.NullBooleanField): widget = forms.widgets.RadioSelect( attrs={'class': 'inline'}, choices=( (True, "Sim"), (False, "Não"), (None, "Ignorado"), ...
c86b6390e46bac17c64e19010912c4cb165fa9dd
satnogsclient/settings.py
satnogsclient/settings.py
from os import environ DEMODULATION_COMMAND = environ.get('DEMODULATION_COMMAND', None) ENCODING_COMMAND = environ.get('ENCODING_COMMAND', None) DECODING_COMMAND = environ.get('DECODING_COMMAND', None) OUTPUT_PATH = environ.get('OUTPUT_PATH', None)
from os import environ DEMODULATION_COMMAND = environ.get('SATNOGS_DEMODULATION_COMMAND', None) ENCODING_COMMAND = environ.get('SATNOGS_ENCODING_COMMAND', None) DECODING_COMMAND = environ.get('SATNOGS_DECODING_COMMAND', None) OUTPUT_PATH = environ.get('SATNOGS_OUTPUT_PATH', None)
Add prefix to required environment variables.
Add prefix to required environment variables.
Python
agpl-3.0
cshields/satnogs-client,adamkalis/satnogs-client,adamkalis/satnogs-client,cshields/satnogs-client
from os import environ - DEMODULATION_COMMAND = environ.get('DEMODULATION_COMMAND', None) + DEMODULATION_COMMAND = environ.get('SATNOGS_DEMODULATION_COMMAND', None) - ENCODING_COMMAND = environ.get('ENCODING_COMMAND', None) + ENCODING_COMMAND = environ.get('SATNOGS_ENCODING_COMMAND', None) - DECODING_COMMAND = environ.get('DECODING_COMMAND', None) + DECODING_COMMAND = environ.get('SATNOGS_DECODING_COMMAND', None) - OUTPUT_PATH = environ.get('OUTPUT_PATH', None) + OUTPUT_PATH = environ.get('SATNOGS_OUTPUT_PATH', None)
Add prefix to required environment variables.
## Code Before: from os import environ DEMODULATION_COMMAND = environ.get('DEMODULATION_COMMAND', None) ENCODING_COMMAND = environ.get('ENCODING_COMMAND', None) DECODING_COMMAND = environ.get('DECODING_COMMAND', None) OUTPUT_PATH = environ.get('OUTPUT_PATH', None) ## Instruction: Add prefix to required environment variables. ## Code After: from os import environ DEMODULATION_COMMAND = environ.get('SATNOGS_DEMODULATION_COMMAND', None) ENCODING_COMMAND = environ.get('SATNOGS_ENCODING_COMMAND', None) DECODING_COMMAND = environ.get('SATNOGS_DECODING_COMMAND', None) OUTPUT_PATH = environ.get('SATNOGS_OUTPUT_PATH', None)
# ... existing code ... from os import environ DEMODULATION_COMMAND = environ.get('SATNOGS_DEMODULATION_COMMAND', None) ENCODING_COMMAND = environ.get('SATNOGS_ENCODING_COMMAND', None) DECODING_COMMAND = environ.get('SATNOGS_DECODING_COMMAND', None) OUTPUT_PATH = environ.get('SATNOGS_OUTPUT_PATH', None) # ... rest of the code ...
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 "", "", ""
... import time from jobs.models import Job ... def is_reachable(server): instance_id = server.ec2serverinfo.instance_id ec2_region = server.ec2serverinfo.ec2_region ... 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() ... return "", "", "" ...
6c351939243f758119ed91de299d6d37dc305359
application/main/routes/__init__.py
application/main/routes/__init__.py
from .all_changes import AllChanges from .show_change import ShowChange from .changes_for_date import ChangesForDate from .changes_for_class import ChangesForClass all_routes = [ (r'/', AllChanges), (r'/changes/show/([0-9A-Za-z\-_]+)', ShowChange), (r'/changes/by_date/([0-9]{4}-[0-9]{2}-[0-9]{2})', ChangesForDate), (r'/changes/for_class/([0-9A-Za-z\.]+)', ChangesForClass), ]
from .all_changes import AllChanges from .show_change import ShowChange from .changes_for_date import ChangesForDate from .changes_for_class import ChangesForClass all_routes = [ (r'/', AllChanges), (r'/changes/show/([0-9A-Za-z\-_]+)', ShowChange), (r'/changes/by_date/([0-9]{4}-[0-9]{2}-[0-9]{2})', ChangesForDate), (r'/changes/for_class/(.+)', ChangesForClass), ]
Expand class name routing target
Expand class name routing target
Python
bsd-3-clause
p22co/edaemon,paulsnar/edaemon,p22co/edaemon,p22co/edaemon,paulsnar/edaemon,paulsnar/edaemon
from .all_changes import AllChanges from .show_change import ShowChange from .changes_for_date import ChangesForDate from .changes_for_class import ChangesForClass all_routes = [ (r'/', AllChanges), (r'/changes/show/([0-9A-Za-z\-_]+)', ShowChange), (r'/changes/by_date/([0-9]{4}-[0-9]{2}-[0-9]{2})', ChangesForDate), - (r'/changes/for_class/([0-9A-Za-z\.]+)', ChangesForClass), + (r'/changes/for_class/(.+)', ChangesForClass), ]
Expand class name routing target
## Code Before: from .all_changes import AllChanges from .show_change import ShowChange from .changes_for_date import ChangesForDate from .changes_for_class import ChangesForClass all_routes = [ (r'/', AllChanges), (r'/changes/show/([0-9A-Za-z\-_]+)', ShowChange), (r'/changes/by_date/([0-9]{4}-[0-9]{2}-[0-9]{2})', ChangesForDate), (r'/changes/for_class/([0-9A-Za-z\.]+)', ChangesForClass), ] ## Instruction: Expand class name routing target ## Code After: from .all_changes import AllChanges from .show_change import ShowChange from .changes_for_date import ChangesForDate from .changes_for_class import ChangesForClass all_routes = [ (r'/', AllChanges), (r'/changes/show/([0-9A-Za-z\-_]+)', ShowChange), (r'/changes/by_date/([0-9]{4}-[0-9]{2}-[0-9]{2})', ChangesForDate), (r'/changes/for_class/(.+)', ChangesForClass), ]
// ... existing code ... (r'/changes/show/([0-9A-Za-z\-_]+)', ShowChange), (r'/changes/by_date/([0-9]{4}-[0-9]{2}-[0-9]{2})', ChangesForDate), (r'/changes/for_class/(.+)', ChangesForClass), ] // ... rest of the code ...
018eab65881a2279efca88e1448dba0708a4dfe1
django_excel_to_model/management/commands/model_create_utils/django_tables2_utils.py
django_excel_to_model/management/commands/model_create_utils/django_tables2_utils.py
from django_excel_to_model.management.commands.model_create_utils.attribute_generator import ClassAttributeCreator import django_tables2 as tables def get_django_tables2_from_dict(data_dict): c = ClassAttributeCreator() table_meta_class = type("Meta", (), { "attrs": {'class': 'table table-striped table-bordered table-advance table-hover'}} ) table_attributes = {"Meta": table_meta_class} table_data = {} for data_key in data_dict.keys(): attr_name = c.refine_attr_name(data_key) table_attributes[attr_name] = tables.Column(verbose_name=data_key) table_data[attr_name] = data_dict[data_key] item_table_class = type("Item" + "DictTableClass", (tables.Table,), table_attributes) return item_table_class([table_data])
from django_excel_to_model.management.commands.model_create_utils.attribute_generator import ClassAttributeCreator import django_tables2 as tables def get_django_tables2_from_dict(data_dict): c = ClassAttributeCreator() table_meta_class = type("Meta", (), { "attrs": {'class': 'table table-striped table-bordered table-advance table-hover'}, "orderable": False, }) table_attributes = {"Meta": table_meta_class} table_data = {} for data_key in data_dict.keys(): attr_name = c.refine_attr_name(data_key) table_attributes[attr_name] = tables.Column(verbose_name=data_key) table_data[attr_name] = data_dict[data_key] item_table_class = type("Item" + "DictTableClass", (tables.Table,), table_attributes) return item_table_class([table_data])
Remove sort function by default for table generated from dict.
Remove sort function by default for table generated from dict.
Python
bsd-3-clause
weijia/django-excel-to-model,weijia/django-excel-to-model
from django_excel_to_model.management.commands.model_create_utils.attribute_generator import ClassAttributeCreator import django_tables2 as tables def get_django_tables2_from_dict(data_dict): c = ClassAttributeCreator() table_meta_class = type("Meta", (), { - "attrs": {'class': 'table table-striped table-bordered table-advance table-hover'}} + "attrs": {'class': 'table table-striped table-bordered table-advance table-hover'}, - ) + "orderable": False, + }) table_attributes = {"Meta": table_meta_class} table_data = {} for data_key in data_dict.keys(): attr_name = c.refine_attr_name(data_key) table_attributes[attr_name] = tables.Column(verbose_name=data_key) table_data[attr_name] = data_dict[data_key] item_table_class = type("Item" + "DictTableClass", (tables.Table,), table_attributes) return item_table_class([table_data])
Remove sort function by default for table generated from dict.
## Code Before: from django_excel_to_model.management.commands.model_create_utils.attribute_generator import ClassAttributeCreator import django_tables2 as tables def get_django_tables2_from_dict(data_dict): c = ClassAttributeCreator() table_meta_class = type("Meta", (), { "attrs": {'class': 'table table-striped table-bordered table-advance table-hover'}} ) table_attributes = {"Meta": table_meta_class} table_data = {} for data_key in data_dict.keys(): attr_name = c.refine_attr_name(data_key) table_attributes[attr_name] = tables.Column(verbose_name=data_key) table_data[attr_name] = data_dict[data_key] item_table_class = type("Item" + "DictTableClass", (tables.Table,), table_attributes) return item_table_class([table_data]) ## Instruction: Remove sort function by default for table generated from dict. ## Code After: from django_excel_to_model.management.commands.model_create_utils.attribute_generator import ClassAttributeCreator import django_tables2 as tables def get_django_tables2_from_dict(data_dict): c = ClassAttributeCreator() table_meta_class = type("Meta", (), { "attrs": {'class': 'table table-striped table-bordered table-advance table-hover'}, "orderable": False, }) table_attributes = {"Meta": table_meta_class} table_data = {} for data_key in data_dict.keys(): attr_name = c.refine_attr_name(data_key) table_attributes[attr_name] = tables.Column(verbose_name=data_key) table_data[attr_name] = data_dict[data_key] item_table_class = type("Item" + "DictTableClass", (tables.Table,), table_attributes) return item_table_class([table_data])
# ... existing code ... c = ClassAttributeCreator() table_meta_class = type("Meta", (), { "attrs": {'class': 'table table-striped table-bordered table-advance table-hover'}, "orderable": False, }) table_attributes = {"Meta": table_meta_class} table_data = {} # ... rest of the code ...
4212b35221a69468b62f933e3dbe5ffeaa9d53dc
tests/test_domain_parser.py
tests/test_domain_parser.py
import unittest from domain_parser import domain_parser class DomainParserTestCase(unittest.TestCase): def test_google(self): """Is google.com properly parsed?""" assert domain_parser.parse_domain( 'http://www.google.com') == ('com', 'google', 'www') def test_guardian(self): """Is 'co.uk', which is wildcarded in the TLD list, parsed properly?""" assert domain_parser.parse_domain( 'http://www.guardian.co.uk') == ('co.uk', 'guardian', 'www') def test_no_scheme(self): """Is 'www.google.com', which doesn't include the scheme ('http'), parsed properly?""" assert domain_parser.parse_domain( 'www.google.com') == ('com', 'google', 'www') def test_secure_scheme(self): """Is 'https://www.google.com', which include 'https' instead of 'http', parsed properly?""" assert domain_parser.parse_domain( 'https://www.google.com') == ('com', 'google', 'www')
import unittest from domain_parser import domain_parser class DomainParserTestCase(unittest.TestCase): def test_google(self): """Is google.com properly parsed?""" assert domain_parser.parse_domain( 'http://www.google.com') == ('com', 'google', 'www') def test_guardian(self): """Is 'co.uk', which is wildcarded in the TLD list, parsed properly?""" assert domain_parser.parse_domain( 'http://www.guardian.co.uk') == ('co.uk', 'guardian', 'www') def test_no_scheme(self): """Is 'www.google.com', which doesn't include the scheme ('http'), parsed properly?""" assert domain_parser.parse_domain( 'www.google.com') == ('com', 'google', 'www') def test_secure_scheme(self): """Is 'https://www.google.com', which include 'https' instead of 'http', parsed properly?""" assert domain_parser.parse_domain( 'https://www.google.com') == ('com', 'google', 'www') def test_internationalized_domain_name(self): """Is 'маил.гоогле.рф', which is entirely composed of non-latin characters, parsed properly?""" # Should always pass when run with Python 3. assert domain_parser.parse_domain( 'http://маил.гоогле.рф') == ('рф', 'гоогле', 'маил')
Add test for internationalized domain names
Add test for internationalized domain names Test that a domain name composed entirely of non-latin characters is parsed properly. This should always pass with Python 3 but it will fail with Python 2 because 'parse_domain' returns 'str(second_level_domain)', which tries to encode second_level_domain in ASCII.
Python
apache-2.0
jeffknupp/domain-parser,jeffknupp/domain-parser
import unittest from domain_parser import domain_parser class DomainParserTestCase(unittest.TestCase): def test_google(self): """Is google.com properly parsed?""" assert domain_parser.parse_domain( 'http://www.google.com') == ('com', 'google', 'www') def test_guardian(self): """Is 'co.uk', which is wildcarded in the TLD list, parsed properly?""" assert domain_parser.parse_domain( 'http://www.guardian.co.uk') == ('co.uk', 'guardian', 'www') def test_no_scheme(self): """Is 'www.google.com', which doesn't include the scheme ('http'), parsed properly?""" assert domain_parser.parse_domain( 'www.google.com') == ('com', 'google', 'www') def test_secure_scheme(self): """Is 'https://www.google.com', which include 'https' instead of 'http', parsed properly?""" assert domain_parser.parse_domain( 'https://www.google.com') == ('com', 'google', 'www') + def test_internationalized_domain_name(self): + """Is 'маил.гоогле.рф', which is entirely composed of non-latin characters, parsed properly?""" + # Should always pass when run with Python 3. + assert domain_parser.parse_domain( + 'http://маил.гоогле.рф') == ('рф', 'гоогле', 'маил') +
Add test for internationalized domain names
## Code Before: import unittest from domain_parser import domain_parser class DomainParserTestCase(unittest.TestCase): def test_google(self): """Is google.com properly parsed?""" assert domain_parser.parse_domain( 'http://www.google.com') == ('com', 'google', 'www') def test_guardian(self): """Is 'co.uk', which is wildcarded in the TLD list, parsed properly?""" assert domain_parser.parse_domain( 'http://www.guardian.co.uk') == ('co.uk', 'guardian', 'www') def test_no_scheme(self): """Is 'www.google.com', which doesn't include the scheme ('http'), parsed properly?""" assert domain_parser.parse_domain( 'www.google.com') == ('com', 'google', 'www') def test_secure_scheme(self): """Is 'https://www.google.com', which include 'https' instead of 'http', parsed properly?""" assert domain_parser.parse_domain( 'https://www.google.com') == ('com', 'google', 'www') ## Instruction: Add test for internationalized domain names ## Code After: import unittest from domain_parser import domain_parser class DomainParserTestCase(unittest.TestCase): def test_google(self): """Is google.com properly parsed?""" assert domain_parser.parse_domain( 'http://www.google.com') == ('com', 'google', 'www') def test_guardian(self): """Is 'co.uk', which is wildcarded in the TLD list, parsed properly?""" assert domain_parser.parse_domain( 'http://www.guardian.co.uk') == ('co.uk', 'guardian', 'www') def test_no_scheme(self): """Is 'www.google.com', which doesn't include the scheme ('http'), parsed properly?""" assert domain_parser.parse_domain( 'www.google.com') == ('com', 'google', 'www') def test_secure_scheme(self): """Is 'https://www.google.com', which include 'https' instead of 'http', parsed properly?""" assert domain_parser.parse_domain( 'https://www.google.com') == ('com', 'google', 'www') def test_internationalized_domain_name(self): """Is 'маил.гоогле.рф', which is entirely composed of non-latin characters, parsed properly?""" # Should always pass when run with Python 3. assert domain_parser.parse_domain( 'http://маил.гоогле.рф') == ('рф', 'гоогле', 'маил')
... assert domain_parser.parse_domain( 'https://www.google.com') == ('com', 'google', 'www') def test_internationalized_domain_name(self): """Is 'маил.гоогле.рф', which is entirely composed of non-latin characters, parsed properly?""" # Should always pass when run with Python 3. assert domain_parser.parse_domain( 'http://маил.гоогле.рф') == ('рф', 'гоогле', 'маил') ...
012ab9bf79ae2f70079534ce6ab527f8e08a50f3
doc/tutorials/python/secure-msg-template.py
doc/tutorials/python/secure-msg-template.py
async def init(): me = input('Who are you? ').strip() wallet_name = '%s-wallet' % me # 1. Create Wallet and Get Wallet Handle try: await wallet.create_wallet(pool_name, wallet_name, None, None, None) except: pass wallet_handle = await wallet.open_wallet(wallet_name, None, None) print('wallet = %s' % wallet_handle) (my_did, my_vk) = await did.create_and_store_my_did(wallet_handle, "{}") print('my_did and verkey = %s %s' % (my_did, my_vk)) their = input("Other party's DID and verkey? ").strip().split(' ') return wallet_handle, my_did, my_vk, their[0], their[1]
import asyncio import time import re async def prep(wallet_handle, my_vk, their_vk, msg): print('prepping %s' % msg) async def init(): return None, None, None, None, None async def read(wallet_handle, my_vk): print('reading') async def demo(): wallet_handle, my_did, my_vk, their_did, their_vk = await init() while True: argv = input('> ').strip().split(' ') cmd = argv[0].lower() rest = ' '.join(argv[1:]) if re.match(cmd, 'prep'): await prep(wallet_handle, my_vk, their_vk, rest) elif re.match(cmd, 'read'): await read(wallet_handle, my_vk) elif re.match(cmd, 'quit'): break else: print('Huh?') if __name__ == '__main__': try: loop = asyncio.get_event_loop() loop.run_until_complete(demo()) time.sleep(1) # waiting for libindy thread complete except KeyboardInterrupt: print('')
Fix template that was accidentally overwritten
Fix template that was accidentally overwritten
Python
apache-2.0
anastasia-tarasova/indy-sdk,anastasia-tarasova/indy-sdk,Artemkaaas/indy-sdk,anastasia-tarasova/indy-sdk,srottem/indy-sdk,peacekeeper/indy-sdk,peacekeeper/indy-sdk,srottem/indy-sdk,srottem/indy-sdk,peacekeeper/indy-sdk,Artemkaaas/indy-sdk,srottem/indy-sdk,srottem/indy-sdk,srottem/indy-sdk,anastasia-tarasova/indy-sdk,Artemkaaas/indy-sdk,peacekeeper/indy-sdk,peacekeeper/indy-sdk,peacekeeper/indy-sdk,Artemkaaas/indy-sdk,Artemkaaas/indy-sdk,Artemkaaas/indy-sdk,peacekeeper/indy-sdk,srottem/indy-sdk,anastasia-tarasova/indy-sdk,anastasia-tarasova/indy-sdk,Artemkaaas/indy-sdk,anastasia-tarasova/indy-sdk,peacekeeper/indy-sdk,anastasia-tarasova/indy-sdk,Artemkaaas/indy-sdk,srottem/indy-sdk,anastasia-tarasova/indy-sdk,anastasia-tarasova/indy-sdk,Artemkaaas/indy-sdk,Artemkaaas/indy-sdk,peacekeeper/indy-sdk,srottem/indy-sdk,peacekeeper/indy-sdk,anastasia-tarasova/indy-sdk,srottem/indy-sdk,peacekeeper/indy-sdk,srottem/indy-sdk,Artemkaaas/indy-sdk,anastasia-tarasova/indy-sdk,anastasia-tarasova/indy-sdk,peacekeeper/indy-sdk,Artemkaaas/indy-sdk,srottem/indy-sdk,peacekeeper/indy-sdk,Artemkaaas/indy-sdk,srottem/indy-sdk
+ import asyncio + import time + import re + + async def prep(wallet_handle, my_vk, their_vk, msg): + print('prepping %s' % msg) + async def init(): + return None, None, None, None, None - me = input('Who are you? ').strip() - wallet_name = '%s-wallet' % me - # 1. Create Wallet and Get Wallet Handle + async def read(wallet_handle, my_vk): + print('reading') + + async def demo(): + wallet_handle, my_did, my_vk, their_did, their_vk = await init() + + while True: + argv = input('> ').strip().split(' ') + cmd = argv[0].lower() + rest = ' '.join(argv[1:]) + if re.match(cmd, 'prep'): + await prep(wallet_handle, my_vk, their_vk, rest) + elif re.match(cmd, 'read'): + await read(wallet_handle, my_vk) + elif re.match(cmd, 'quit'): + break + else: + print('Huh?') + + if __name__ == '__main__': try: - await wallet.create_wallet(pool_name, wallet_name, None, None, None) - except: - pass - wallet_handle = await wallet.open_wallet(wallet_name, None, None) - print('wallet = %s' % wallet_handle) + loop = asyncio.get_event_loop() + loop.run_until_complete(demo()) + time.sleep(1) # waiting for libindy thread complete + except KeyboardInterrupt: + print('') - (my_did, my_vk) = await did.create_and_store_my_did(wallet_handle, "{}") - print('my_did and verkey = %s %s' % (my_did, my_vk)) - - their = input("Other party's DID and verkey? ").strip().split(' ') - return wallet_handle, my_did, my_vk, their[0], their[1] -
Fix template that was accidentally overwritten
## Code Before: async def init(): me = input('Who are you? ').strip() wallet_name = '%s-wallet' % me # 1. Create Wallet and Get Wallet Handle try: await wallet.create_wallet(pool_name, wallet_name, None, None, None) except: pass wallet_handle = await wallet.open_wallet(wallet_name, None, None) print('wallet = %s' % wallet_handle) (my_did, my_vk) = await did.create_and_store_my_did(wallet_handle, "{}") print('my_did and verkey = %s %s' % (my_did, my_vk)) their = input("Other party's DID and verkey? ").strip().split(' ') return wallet_handle, my_did, my_vk, their[0], their[1] ## Instruction: Fix template that was accidentally overwritten ## Code After: import asyncio import time import re async def prep(wallet_handle, my_vk, their_vk, msg): print('prepping %s' % msg) async def init(): return None, None, None, None, None async def read(wallet_handle, my_vk): print('reading') async def demo(): wallet_handle, my_did, my_vk, their_did, their_vk = await init() while True: argv = input('> ').strip().split(' ') cmd = argv[0].lower() rest = ' '.join(argv[1:]) if re.match(cmd, 'prep'): await prep(wallet_handle, my_vk, their_vk, rest) elif re.match(cmd, 'read'): await read(wallet_handle, my_vk) elif re.match(cmd, 'quit'): break else: print('Huh?') if __name__ == '__main__': try: loop = asyncio.get_event_loop() loop.run_until_complete(demo()) time.sleep(1) # waiting for libindy thread complete except KeyboardInterrupt: print('')
// ... existing code ... import asyncio import time import re async def prep(wallet_handle, my_vk, their_vk, msg): print('prepping %s' % msg) async def init(): return None, None, None, None, None async def read(wallet_handle, my_vk): print('reading') async def demo(): wallet_handle, my_did, my_vk, their_did, their_vk = await init() while True: argv = input('> ').strip().split(' ') cmd = argv[0].lower() rest = ' '.join(argv[1:]) if re.match(cmd, 'prep'): await prep(wallet_handle, my_vk, their_vk, rest) elif re.match(cmd, 'read'): await read(wallet_handle, my_vk) elif re.match(cmd, 'quit'): break else: print('Huh?') if __name__ == '__main__': try: loop = asyncio.get_event_loop() loop.run_until_complete(demo()) time.sleep(1) # waiting for libindy thread complete except KeyboardInterrupt: print('') // ... rest of the code ...
2d8b7253445193131d027bd12d3389bbc03858e5
massa/__init__.py
massa/__init__.py
from flask import Flask, render_template, g from .container import build from .web import bp as web from .api import bp as api from .middleware import HTTPMethodOverrideMiddleware def create_app(config=None): app = Flask('massa') app.config.from_object(config or 'massa.config.Production') app.config.from_envvar('MASSA_CONFIG', silent=True) sl = build(app) app.register_blueprint(web) app.register_blueprint(api, url_prefix='/api') @app.before_request def globals(): g.sl = sl app.wsgi_app = HTTPMethodOverrideMiddleware(app.wsgi_app) return app
from flask import Flask, g from .container import build from .web import bp as web from .api import bp as api from .middleware import HTTPMethodOverrideMiddleware def create_app(config=None): app = Flask('massa') app.config.from_object(config or 'massa.config.Production') app.config.from_envvar('MASSA_CONFIG', silent=True) sl = build(app) app.register_blueprint(web) app.register_blueprint(api, url_prefix='/api') @app.before_request def globals(): g.sl = sl app.wsgi_app = HTTPMethodOverrideMiddleware(app.wsgi_app) return app
Remove unused render_template from import statement.
Remove unused render_template from import statement.
Python
mit
jaapverloop/massa
- from flask import Flask, render_template, g + from flask import Flask, g from .container import build from .web import bp as web from .api import bp as api from .middleware import HTTPMethodOverrideMiddleware def create_app(config=None): app = Flask('massa') app.config.from_object(config or 'massa.config.Production') app.config.from_envvar('MASSA_CONFIG', silent=True) sl = build(app) app.register_blueprint(web) app.register_blueprint(api, url_prefix='/api') @app.before_request def globals(): g.sl = sl app.wsgi_app = HTTPMethodOverrideMiddleware(app.wsgi_app) return app
Remove unused render_template from import statement.
## Code Before: from flask import Flask, render_template, g from .container import build from .web import bp as web from .api import bp as api from .middleware import HTTPMethodOverrideMiddleware def create_app(config=None): app = Flask('massa') app.config.from_object(config or 'massa.config.Production') app.config.from_envvar('MASSA_CONFIG', silent=True) sl = build(app) app.register_blueprint(web) app.register_blueprint(api, url_prefix='/api') @app.before_request def globals(): g.sl = sl app.wsgi_app = HTTPMethodOverrideMiddleware(app.wsgi_app) return app ## Instruction: Remove unused render_template from import statement. ## Code After: from flask import Flask, g from .container import build from .web import bp as web from .api import bp as api from .middleware import HTTPMethodOverrideMiddleware def create_app(config=None): app = Flask('massa') app.config.from_object(config or 'massa.config.Production') app.config.from_envvar('MASSA_CONFIG', silent=True) sl = build(app) app.register_blueprint(web) app.register_blueprint(api, url_prefix='/api') @app.before_request def globals(): g.sl = sl app.wsgi_app = HTTPMethodOverrideMiddleware(app.wsgi_app) return app
// ... existing code ... from flask import Flask, g from .container import build from .web import bp as web // ... rest of the code ...
72a9dd0f0cff3fc6dcc97a4068b82e4b13bbc127
accounts/management/__init__.py
accounts/management/__init__.py
from django.db.models.signals import post_syncdb from django.conf import settings from accounts import models def ensure_core_accounts_exists(sender, **kwargs): create_source_account() create_sales_account() create_expired_account() def create_sales_account(): name = getattr(settings, 'ACCOUNTS_SALES_NAME') __, created = models.Account.objects.get_or_create(name=name) if created: print "Created sales account '%s'" % name def create_expired_account(): name = getattr(settings, 'ACCOUNTS_EXPIRED_NAME') __, created = models.Account.objects.get_or_create(name=name) if created: print "Created expired account '%s'" % name def create_source_account(): # Create a source account if one does not exist if not hasattr(settings, 'ACCOUNTS_SOURCE_NAME'): return # We only create the source account if there are no accounts already # created. if models.Account.objects.all().count() > 0: return name = getattr(settings, 'ACCOUNTS_SOURCE_NAME') __, created = models.Account.objects.get_or_create(name=name, credit_limit=None) if created: print "Created source account '%s'" % name post_syncdb.connect(ensure_core_accounts_exists, sender=models)
from django.db.models.signals import post_syncdb from django.conf import settings from accounts import models def ensure_core_accounts_exists(sender, **kwargs): create_source_account() create_sales_account() create_expired_account() def create_sales_account(): name = getattr(settings, 'ACCOUNTS_SALES_NAME') models.Account.objects.get_or_create(name=name) def create_expired_account(): name = getattr(settings, 'ACCOUNTS_EXPIRED_NAME') models.Account.objects.get_or_create(name=name) def create_source_account(): # Create a source account if one does not exist if not hasattr(settings, 'ACCOUNTS_SOURCE_NAME'): return # We only create the source account if there are no accounts already # created. if models.Account.objects.all().count() > 0: return name = getattr(settings, 'ACCOUNTS_SOURCE_NAME') models.Account.objects.get_or_create(name=name, credit_limit=None) post_syncdb.connect(ensure_core_accounts_exists, sender=models)
Remove print statements for syncdb receivers
Remove print statements for syncdb receivers
Python
bsd-3-clause
django-oscar/django-oscar-accounts,michaelkuty/django-oscar-accounts,Mariana-Tek/django-oscar-accounts,amsys/django-account-balances,carver/django-account-balances,Jannes123/django-oscar-accounts,machtfit/django-oscar-accounts,michaelkuty/django-oscar-accounts,amsys/django-account-balances,django-oscar/django-oscar-accounts,Mariana-Tek/django-oscar-accounts,machtfit/django-oscar-accounts,Jannes123/django-oscar-accounts
from django.db.models.signals import post_syncdb from django.conf import settings from accounts import models def ensure_core_accounts_exists(sender, **kwargs): create_source_account() create_sales_account() create_expired_account() def create_sales_account(): name = getattr(settings, 'ACCOUNTS_SALES_NAME') - __, created = models.Account.objects.get_or_create(name=name) + models.Account.objects.get_or_create(name=name) - if created: - print "Created sales account '%s'" % name def create_expired_account(): name = getattr(settings, 'ACCOUNTS_EXPIRED_NAME') - __, created = models.Account.objects.get_or_create(name=name) + models.Account.objects.get_or_create(name=name) - if created: - print "Created expired account '%s'" % name def create_source_account(): # Create a source account if one does not exist if not hasattr(settings, 'ACCOUNTS_SOURCE_NAME'): return # We only create the source account if there are no accounts already # created. if models.Account.objects.all().count() > 0: return name = getattr(settings, 'ACCOUNTS_SOURCE_NAME') - __, created = models.Account.objects.get_or_create(name=name, + models.Account.objects.get_or_create(name=name, credit_limit=None) - credit_limit=None) - if created: - print "Created source account '%s'" % name post_syncdb.connect(ensure_core_accounts_exists, sender=models)
Remove print statements for syncdb receivers
## Code Before: from django.db.models.signals import post_syncdb from django.conf import settings from accounts import models def ensure_core_accounts_exists(sender, **kwargs): create_source_account() create_sales_account() create_expired_account() def create_sales_account(): name = getattr(settings, 'ACCOUNTS_SALES_NAME') __, created = models.Account.objects.get_or_create(name=name) if created: print "Created sales account '%s'" % name def create_expired_account(): name = getattr(settings, 'ACCOUNTS_EXPIRED_NAME') __, created = models.Account.objects.get_or_create(name=name) if created: print "Created expired account '%s'" % name def create_source_account(): # Create a source account if one does not exist if not hasattr(settings, 'ACCOUNTS_SOURCE_NAME'): return # We only create the source account if there are no accounts already # created. if models.Account.objects.all().count() > 0: return name = getattr(settings, 'ACCOUNTS_SOURCE_NAME') __, created = models.Account.objects.get_or_create(name=name, credit_limit=None) if created: print "Created source account '%s'" % name post_syncdb.connect(ensure_core_accounts_exists, sender=models) ## Instruction: Remove print statements for syncdb receivers ## Code After: from django.db.models.signals import post_syncdb from django.conf import settings from accounts import models def ensure_core_accounts_exists(sender, **kwargs): create_source_account() create_sales_account() create_expired_account() def create_sales_account(): name = getattr(settings, 'ACCOUNTS_SALES_NAME') models.Account.objects.get_or_create(name=name) def create_expired_account(): name = getattr(settings, 'ACCOUNTS_EXPIRED_NAME') models.Account.objects.get_or_create(name=name) def create_source_account(): # Create a source account if one does not exist if not hasattr(settings, 'ACCOUNTS_SOURCE_NAME'): return # We only create the source account if there are no accounts already # created. if models.Account.objects.all().count() > 0: return name = getattr(settings, 'ACCOUNTS_SOURCE_NAME') models.Account.objects.get_or_create(name=name, credit_limit=None) post_syncdb.connect(ensure_core_accounts_exists, sender=models)
# ... existing code ... def create_sales_account(): name = getattr(settings, 'ACCOUNTS_SALES_NAME') models.Account.objects.get_or_create(name=name) # ... modified code ... def create_expired_account(): name = getattr(settings, 'ACCOUNTS_EXPIRED_NAME') models.Account.objects.get_or_create(name=name) ... return name = getattr(settings, 'ACCOUNTS_SOURCE_NAME') models.Account.objects.get_or_create(name=name, credit_limit=None) # ... rest of the code ...
73ff56f4b8859e82b0d69a6505c982e26de27859
util.py
util.py
def product(nums): r = 1 for n in nums: r *= n return r def choose(n, k): if 0 <= k <= n: ntok = 1 ktok = 1 for t in range(1, min(k, n - k) + 1): ntok *= n ktok *= t n -= 1 return ntok // ktok else: return 0 def format_floats(floats): fstr = ' '.join('{:10.08f}' for _ in floats) return fstr.format(*floats)
import colorsys import random def randcolor(): hue = random.random() sat = random.randint(700, 1000) / 1000 val = random.randint(700, 1000) / 1000 return tuple(int(f*255) for f in colorsys.hsv_to_rgb(hue, sat, val)) def product(nums): r = 1 for n in nums: r *= n return r def choose(n, k): if 0 <= k <= n: ntok = 1 ktok = 1 for t in range(1, min(k, n - k) + 1): ntok *= n ktok *= t n -= 1 return ntok // ktok else: return 0 def format_floats(floats): fstr = ' '.join('{:10.08f}' for _ in floats) return fstr.format(*floats)
Add randcolor function to uitl
Add randcolor function to uitl
Python
unlicense
joseph346/cellular
+ import colorsys + import random + + def randcolor(): + hue = random.random() + sat = random.randint(700, 1000) / 1000 + val = random.randint(700, 1000) / 1000 + return tuple(int(f*255) for f in colorsys.hsv_to_rgb(hue, sat, val)) def product(nums): r = 1 for n in nums: r *= n return r def choose(n, k): if 0 <= k <= n: ntok = 1 ktok = 1 for t in range(1, min(k, n - k) + 1): ntok *= n ktok *= t n -= 1 return ntok // ktok else: return 0 def format_floats(floats): fstr = ' '.join('{:10.08f}' for _ in floats) return fstr.format(*floats)
Add randcolor function to uitl
## Code Before: def product(nums): r = 1 for n in nums: r *= n return r def choose(n, k): if 0 <= k <= n: ntok = 1 ktok = 1 for t in range(1, min(k, n - k) + 1): ntok *= n ktok *= t n -= 1 return ntok // ktok else: return 0 def format_floats(floats): fstr = ' '.join('{:10.08f}' for _ in floats) return fstr.format(*floats) ## Instruction: Add randcolor function to uitl ## Code After: import colorsys import random def randcolor(): hue = random.random() sat = random.randint(700, 1000) / 1000 val = random.randint(700, 1000) / 1000 return tuple(int(f*255) for f in colorsys.hsv_to_rgb(hue, sat, val)) def product(nums): r = 1 for n in nums: r *= n return r def choose(n, k): if 0 <= k <= n: ntok = 1 ktok = 1 for t in range(1, min(k, n - k) + 1): ntok *= n ktok *= t n -= 1 return ntok // ktok else: return 0 def format_floats(floats): fstr = ' '.join('{:10.08f}' for _ in floats) return fstr.format(*floats)
... import colorsys import random def randcolor(): hue = random.random() sat = random.randint(700, 1000) / 1000 val = random.randint(700, 1000) / 1000 return tuple(int(f*255) for f in colorsys.hsv_to_rgb(hue, sat, val)) def product(nums): ...
74b31ba7fec330ec167c2e001f60695272da71b8
pages/views.py
pages/views.py
from django.views import generic from django.contrib.auth.models import Group from django_countries.fields import Country from hosting.models import Profile, Place from hosting.utils import sort_by_name class AboutView(generic.TemplateView): template_name = 'pages/about.html' about = AboutView.as_view() class TermsAndConditionsView(generic.TemplateView): template_name = 'pages/terms_conditions.html' terms_conditions = TermsAndConditionsView.as_view() class SupervisorsView(generic.TemplateView): template_name = 'pages/supervisors.html' def countries(self): places = Place.objects.filter(in_book=True) groups = Group.objects.exclude(user=None) countries = sort_by_name({p.country for p in places}) for country in countries: try: group = groups.get(name=str(country)) country.supervisors = sorted(user.profile for user in group.user_set.all()) except Group.DoesNotExist: pass country.place_count = places.filter(country=country).count() return countries supervisors = SupervisorsView.as_view() class FaqView(generic.TemplateView): template_name = 'pages/faq.html' faq = FaqView.as_view()
from django.views import generic from django.contrib.auth.models import Group from hosting.models import Place from hosting.utils import sort_by_name class AboutView(generic.TemplateView): template_name = 'pages/about.html' about = AboutView.as_view() class TermsAndConditionsView(generic.TemplateView): template_name = 'pages/terms_conditions.html' terms_conditions = TermsAndConditionsView.as_view() class SupervisorsView(generic.TemplateView): template_name = 'pages/supervisors.html' def countries(self): places = Place.available_objects.filter(in_book=True) groups = Group.objects.exclude(user=None) countries = sort_by_name({p.country for p in places}) for country in countries: try: group = groups.get(name=str(country)) country.supervisors = sorted(user.profile for user in group.user_set.all()) except Group.DoesNotExist: pass country.place_count = places.filter(country=country).count() return countries supervisors = SupervisorsView.as_view() class FaqView(generic.TemplateView): template_name = 'pages/faq.html' faq = FaqView.as_view()
Fix numbers in LO list.
Fix numbers in LO list.
Python
agpl-3.0
batisteo/pasportaservo,tejo-esperanto/pasportaservo,tejo-esperanto/pasportaservo,tejo-esperanto/pasportaservo,tejo-esperanto/pasportaservo,batisteo/pasportaservo,batisteo/pasportaservo,batisteo/pasportaservo
from django.views import generic from django.contrib.auth.models import Group - from django_countries.fields import Country - from hosting.models import Profile, Place + from hosting.models import Place from hosting.utils import sort_by_name class AboutView(generic.TemplateView): template_name = 'pages/about.html' about = AboutView.as_view() class TermsAndConditionsView(generic.TemplateView): template_name = 'pages/terms_conditions.html' terms_conditions = TermsAndConditionsView.as_view() class SupervisorsView(generic.TemplateView): template_name = 'pages/supervisors.html' def countries(self): - places = Place.objects.filter(in_book=True) + places = Place.available_objects.filter(in_book=True) groups = Group.objects.exclude(user=None) countries = sort_by_name({p.country for p in places}) for country in countries: try: group = groups.get(name=str(country)) country.supervisors = sorted(user.profile for user in group.user_set.all()) except Group.DoesNotExist: pass country.place_count = places.filter(country=country).count() return countries supervisors = SupervisorsView.as_view() class FaqView(generic.TemplateView): template_name = 'pages/faq.html' faq = FaqView.as_view()
Fix numbers in LO list.
## Code Before: from django.views import generic from django.contrib.auth.models import Group from django_countries.fields import Country from hosting.models import Profile, Place from hosting.utils import sort_by_name class AboutView(generic.TemplateView): template_name = 'pages/about.html' about = AboutView.as_view() class TermsAndConditionsView(generic.TemplateView): template_name = 'pages/terms_conditions.html' terms_conditions = TermsAndConditionsView.as_view() class SupervisorsView(generic.TemplateView): template_name = 'pages/supervisors.html' def countries(self): places = Place.objects.filter(in_book=True) groups = Group.objects.exclude(user=None) countries = sort_by_name({p.country for p in places}) for country in countries: try: group = groups.get(name=str(country)) country.supervisors = sorted(user.profile for user in group.user_set.all()) except Group.DoesNotExist: pass country.place_count = places.filter(country=country).count() return countries supervisors = SupervisorsView.as_view() class FaqView(generic.TemplateView): template_name = 'pages/faq.html' faq = FaqView.as_view() ## Instruction: Fix numbers in LO list. ## Code After: from django.views import generic from django.contrib.auth.models import Group from hosting.models import Place from hosting.utils import sort_by_name class AboutView(generic.TemplateView): template_name = 'pages/about.html' about = AboutView.as_view() class TermsAndConditionsView(generic.TemplateView): template_name = 'pages/terms_conditions.html' terms_conditions = TermsAndConditionsView.as_view() class SupervisorsView(generic.TemplateView): template_name = 'pages/supervisors.html' def countries(self): places = Place.available_objects.filter(in_book=True) groups = Group.objects.exclude(user=None) countries = sort_by_name({p.country for p in places}) for country in countries: try: group = groups.get(name=str(country)) country.supervisors = sorted(user.profile for user in group.user_set.all()) except Group.DoesNotExist: pass country.place_count = places.filter(country=country).count() return countries supervisors = SupervisorsView.as_view() class FaqView(generic.TemplateView): template_name = 'pages/faq.html' faq = FaqView.as_view()
... from django.contrib.auth.models import Group from hosting.models import Place from hosting.utils import sort_by_name ... def countries(self): places = Place.available_objects.filter(in_book=True) groups = Group.objects.exclude(user=None) countries = sort_by_name({p.country for p in places}) ...
319d6cb62c55d4eec124d9872d491aebaaad468a
froide/publicbody/search_indexes.py
froide/publicbody/search_indexes.py
from haystack import indexes from haystack import site from publicbody.models import PublicBody class PublicBodyIndex(indexes.SearchIndex): text = indexes.CharField(document=True, use_template=True) name = indexes.CharField(model_attr='name') geography = indexes.CharField(model_attr='geography') topic_auto = indexes.EdgeNgramField(model_attr='topic') name_auto = indexes.EdgeNgramField(model_attr='name') url = indexes.CharField(model_attr='get_absolute_url') def get_queryset(self): """Used when the entire index for model is updated.""" return PublicBody.objects.get_for_search_index() site.register(PublicBody, PublicBodyIndex)
from haystack import indexes from haystack import site from publicbody.models import PublicBody class PublicBodyIndex(indexes.SearchIndex): text = indexes.EdgeNgramField(document=True, use_template=True) name = indexes.CharField(model_attr='name') geography = indexes.CharField(model_attr='geography') topic_auto = indexes.EdgeNgramField(model_attr='topic') name_auto = indexes.EdgeNgramField(model_attr='name') url = indexes.CharField(model_attr='get_absolute_url') def get_queryset(self): """Used when the entire index for model is updated.""" return PublicBody.objects.get_for_search_index() site.register(PublicBody, PublicBodyIndex)
Make Public Body document search an EdgeNgram Field to improve search
Make Public Body document search an EdgeNgram Field to improve search
Python
mit
ryankanno/froide,stefanw/froide,fin/froide,okfse/froide,LilithWittmann/froide,CodeforHawaii/froide,catcosmo/froide,catcosmo/froide,CodeforHawaii/froide,LilithWittmann/froide,ryankanno/froide,okfse/froide,LilithWittmann/froide,catcosmo/froide,CodeforHawaii/froide,ryankanno/froide,catcosmo/froide,okfse/froide,LilithWittmann/froide,stefanw/froide,catcosmo/froide,CodeforHawaii/froide,LilithWittmann/froide,ryankanno/froide,fin/froide,stefanw/froide,ryankanno/froide,stefanw/froide,fin/froide,stefanw/froide,fin/froide,okfse/froide,okfse/froide,CodeforHawaii/froide
from haystack import indexes from haystack import site from publicbody.models import PublicBody class PublicBodyIndex(indexes.SearchIndex): - text = indexes.CharField(document=True, use_template=True) + text = indexes.EdgeNgramField(document=True, use_template=True) name = indexes.CharField(model_attr='name') geography = indexes.CharField(model_attr='geography') topic_auto = indexes.EdgeNgramField(model_attr='topic') name_auto = indexes.EdgeNgramField(model_attr='name') url = indexes.CharField(model_attr='get_absolute_url') def get_queryset(self): """Used when the entire index for model is updated.""" return PublicBody.objects.get_for_search_index() - site.register(PublicBody, PublicBodyIndex)
Make Public Body document search an EdgeNgram Field to improve search
## Code Before: from haystack import indexes from haystack import site from publicbody.models import PublicBody class PublicBodyIndex(indexes.SearchIndex): text = indexes.CharField(document=True, use_template=True) name = indexes.CharField(model_attr='name') geography = indexes.CharField(model_attr='geography') topic_auto = indexes.EdgeNgramField(model_attr='topic') name_auto = indexes.EdgeNgramField(model_attr='name') url = indexes.CharField(model_attr='get_absolute_url') def get_queryset(self): """Used when the entire index for model is updated.""" return PublicBody.objects.get_for_search_index() site.register(PublicBody, PublicBodyIndex) ## Instruction: Make Public Body document search an EdgeNgram Field to improve search ## Code After: from haystack import indexes from haystack import site from publicbody.models import PublicBody class PublicBodyIndex(indexes.SearchIndex): text = indexes.EdgeNgramField(document=True, use_template=True) name = indexes.CharField(model_attr='name') geography = indexes.CharField(model_attr='geography') topic_auto = indexes.EdgeNgramField(model_attr='topic') name_auto = indexes.EdgeNgramField(model_attr='name') url = indexes.CharField(model_attr='get_absolute_url') def get_queryset(self): """Used when the entire index for model is updated.""" return PublicBody.objects.get_for_search_index() site.register(PublicBody, PublicBodyIndex)
... class PublicBodyIndex(indexes.SearchIndex): text = indexes.EdgeNgramField(document=True, use_template=True) name = indexes.CharField(model_attr='name') geography = indexes.CharField(model_attr='geography') ... return PublicBody.objects.get_for_search_index() site.register(PublicBody, PublicBodyIndex) ...
194557f236016ec0978e5cc465ba40e7b8dff714
s3backup/main.py
s3backup/main.py
from s3backup.clients import compare, LocalSyncClient def sync(): local_client = LocalSyncClient('/home/michael/Notebooks') current = local_client.get_current_state() index = local_client.get_index_state() print(list(compare(current, index))) local_client.update_index()
import os from s3backup.clients import compare, LocalSyncClient def sync(): target_folder = os.path.expanduser('~/Notebooks') local_client = LocalSyncClient(target_folder) current = local_client.get_current_state() index = local_client.get_index_state() print(list(compare(current, index))) local_client.update_index()
Use expanduser to prevent hardcoding username
Use expanduser to prevent hardcoding username
Python
mit
MichaelAquilina/s3backup,MichaelAquilina/s3backup
+ + import os from s3backup.clients import compare, LocalSyncClient def sync(): - local_client = LocalSyncClient('/home/michael/Notebooks') + target_folder = os.path.expanduser('~/Notebooks') + + local_client = LocalSyncClient(target_folder) current = local_client.get_current_state() index = local_client.get_index_state() print(list(compare(current, index))) local_client.update_index()
Use expanduser to prevent hardcoding username
## Code Before: from s3backup.clients import compare, LocalSyncClient def sync(): local_client = LocalSyncClient('/home/michael/Notebooks') current = local_client.get_current_state() index = local_client.get_index_state() print(list(compare(current, index))) local_client.update_index() ## Instruction: Use expanduser to prevent hardcoding username ## Code After: import os from s3backup.clients import compare, LocalSyncClient def sync(): target_folder = os.path.expanduser('~/Notebooks') local_client = LocalSyncClient(target_folder) current = local_client.get_current_state() index = local_client.get_index_state() print(list(compare(current, index))) local_client.update_index()
// ... existing code ... import os from s3backup.clients import compare, LocalSyncClient // ... modified code ... def sync(): target_folder = os.path.expanduser('~/Notebooks') local_client = LocalSyncClient(target_folder) current = local_client.get_current_state() index = local_client.get_index_state() // ... rest of the code ...
9c9a33869747223952b4a999a5a14354ffb3e540
contrib/examples/actions/pythonactions/forloop_parse_github_repos.py
contrib/examples/actions/pythonactions/forloop_parse_github_repos.py
from st2actions.runners.pythonrunner import Action from bs4 import BeautifulSoup class ParseGithubRepos(Action): def run(self, content): try: soup = BeautifulSoup(content, 'html.parser') repo_list = soup.find_all("h3") output = {} for each_item in repo_list: repo_half_url = each_item.find("a")['href'] repo_name = repo_half_url.split("/")[-1] repo_url = "https://github.com" + repo_half_url output[repo_name] = repo_url except Exception as e: return (False, "Could not parse data: {}".format(e.message)) return (True, output)
from st2actions.runners.pythonrunner import Action from bs4 import BeautifulSoup class ParseGithubRepos(Action): def run(self, content): try: soup = BeautifulSoup(content, 'html.parser') repo_list = soup.find_all("h3") output = {} for each_item in repo_list: repo_half_url = each_item.find("a")['href'] repo_name = repo_half_url.split("/")[-1] repo_url = "https://github.com" + repo_half_url output[repo_name] = repo_url except Exception as e: raise Exception("Could not parse data: {}".format(e.message)) return (True, output)
Throw exception instead of returning false.
Throw exception instead of returning false.
Python
apache-2.0
StackStorm/st2,Plexxi/st2,Plexxi/st2,nzlosh/st2,Plexxi/st2,StackStorm/st2,Plexxi/st2,StackStorm/st2,nzlosh/st2,nzlosh/st2,nzlosh/st2,StackStorm/st2
from st2actions.runners.pythonrunner import Action from bs4 import BeautifulSoup class ParseGithubRepos(Action): def run(self, content): try: soup = BeautifulSoup(content, 'html.parser') repo_list = soup.find_all("h3") output = {} for each_item in repo_list: repo_half_url = each_item.find("a")['href'] repo_name = repo_half_url.split("/")[-1] repo_url = "https://github.com" + repo_half_url output[repo_name] = repo_url except Exception as e: - return (False, "Could not parse data: {}".format(e.message)) + raise Exception("Could not parse data: {}".format(e.message)) return (True, output)
Throw exception instead of returning false.
## Code Before: from st2actions.runners.pythonrunner import Action from bs4 import BeautifulSoup class ParseGithubRepos(Action): def run(self, content): try: soup = BeautifulSoup(content, 'html.parser') repo_list = soup.find_all("h3") output = {} for each_item in repo_list: repo_half_url = each_item.find("a")['href'] repo_name = repo_half_url.split("/")[-1] repo_url = "https://github.com" + repo_half_url output[repo_name] = repo_url except Exception as e: return (False, "Could not parse data: {}".format(e.message)) return (True, output) ## Instruction: Throw exception instead of returning false. ## Code After: from st2actions.runners.pythonrunner import Action from bs4 import BeautifulSoup class ParseGithubRepos(Action): def run(self, content): try: soup = BeautifulSoup(content, 'html.parser') repo_list = soup.find_all("h3") output = {} for each_item in repo_list: repo_half_url = each_item.find("a")['href'] repo_name = repo_half_url.split("/")[-1] repo_url = "https://github.com" + repo_half_url output[repo_name] = repo_url except Exception as e: raise Exception("Could not parse data: {}".format(e.message)) return (True, output)
... output[repo_name] = repo_url except Exception as e: raise Exception("Could not parse data: {}".format(e.message)) return (True, output) ...
a5dd30e38e58c08d67a2f831e2ae3cbc4a288337
diary/admin.py
diary/admin.py
from django.contrib import admin from diary.models import DiaryItem, EventLocation, ImageItem class DiaryAdmin(admin.ModelAdmin): list_display = ('title', 'start_date', 'start_time', 'author', 'location') # Register your models here. admin.site.register(DiaryItem, DiaryAdmin) admin.site.register(EventLocation) admin.site.register(ImageItem)
from django.contrib import admin from diary.models import DiaryItem, EventLocation, ImageItem class DiaryAdmin(admin.ModelAdmin): list_display = ('title', 'start_date', 'start_time', 'author', 'location') exclude = ('author',) def save_model(self, request, obj, form, change): if obj.pk is None: obj.author = request.user obj.save() # Register your models here. admin.site.register(DiaryItem, DiaryAdmin) admin.site.register(EventLocation) admin.site.register(ImageItem)
Set author automatically for diary items
Set author automatically for diary items
Python
mit
DevLoL/devlol.at,DevLoL/devlol.at,DevLoL/devlol.at,DevLoL/devlol.at
from django.contrib import admin from diary.models import DiaryItem, EventLocation, ImageItem class DiaryAdmin(admin.ModelAdmin): - list_display = ('title', 'start_date', 'start_time', 'author', 'location') + list_display = ('title', 'start_date', 'start_time', 'author', 'location') + exclude = ('author',) + def save_model(self, request, obj, form, change): + if obj.pk is None: + obj.author = request.user + obj.save() # Register your models here. admin.site.register(DiaryItem, DiaryAdmin) admin.site.register(EventLocation) admin.site.register(ImageItem)
Set author automatically for diary items
## Code Before: from django.contrib import admin from diary.models import DiaryItem, EventLocation, ImageItem class DiaryAdmin(admin.ModelAdmin): list_display = ('title', 'start_date', 'start_time', 'author', 'location') # Register your models here. admin.site.register(DiaryItem, DiaryAdmin) admin.site.register(EventLocation) admin.site.register(ImageItem) ## Instruction: Set author automatically for diary items ## Code After: from django.contrib import admin from diary.models import DiaryItem, EventLocation, ImageItem class DiaryAdmin(admin.ModelAdmin): list_display = ('title', 'start_date', 'start_time', 'author', 'location') exclude = ('author',) def save_model(self, request, obj, form, change): if obj.pk is None: obj.author = request.user obj.save() # Register your models here. admin.site.register(DiaryItem, DiaryAdmin) admin.site.register(EventLocation) admin.site.register(ImageItem)
# ... existing code ... class DiaryAdmin(admin.ModelAdmin): list_display = ('title', 'start_date', 'start_time', 'author', 'location') exclude = ('author',) def save_model(self, request, obj, form, change): if obj.pk is None: obj.author = request.user obj.save() # Register your models here. # ... rest of the code ...
3e3f7b827e226146ec7d3efe523f1f900ac4e99a
sjconfparts/type.py
sjconfparts/type.py
class Type: @classmethod def str_to_list(xcls, str_object): list = map(str.strip, str_object.split(',')) try: list.remove('') except ValueError: pass return list @classmethod def list_to_str(xcls, list_object): return ', '.join(list_object) @classmethod def str_to_bool(xcls, str_object): if str_object == "yes" or str_object == "on" or str_object == "true": return True elif str_object == "no" or str_object == "off" or str_object == "false": return False else: raise TypeError @classmethod def bool_to_str(xcls, bool_object): if bool_object: return "yes" else: return "no"
class Type: @classmethod def str_to_list(xcls, str_object): list = map(str.strip, str_object.split(',')) try: list.remove('') except ValueError: pass return list @classmethod def list_to_str(xcls, list_object): return ', '.join(list_object) @classmethod def str_to_bool(xcls, str_object): if str_object == "yes" or str_object == "on" or str_object == "true" or str_object == "enabled" or str_object == "enable": return True elif str_object == "no" or str_object == "off" or str_object == "false" or str_object == "disabled" or str_object == "disable": return False else: raise TypeError @classmethod def bool_to_str(xcls, bool_object): if bool_object: return "yes" else: return "no"
Allow “enabled“, “enable”, “disabled“, “disable” as boolean values
Allow “enabled“, “enable”, “disabled“, “disable” as boolean values
Python
lgpl-2.1
SmartJog/sjconf,SmartJog/sjconf
class Type: @classmethod def str_to_list(xcls, str_object): list = map(str.strip, str_object.split(',')) try: list.remove('') except ValueError: pass return list @classmethod def list_to_str(xcls, list_object): return ', '.join(list_object) @classmethod def str_to_bool(xcls, str_object): - if str_object == "yes" or str_object == "on" or str_object == "true": + if str_object == "yes" or str_object == "on" or str_object == "true" or str_object == "enabled" or str_object == "enable": return True - elif str_object == "no" or str_object == "off" or str_object == "false": + elif str_object == "no" or str_object == "off" or str_object == "false" or str_object == "disabled" or str_object == "disable": return False else: raise TypeError @classmethod def bool_to_str(xcls, bool_object): if bool_object: return "yes" else: return "no"
Allow “enabled“, “enable”, “disabled“, “disable” as boolean values
## Code Before: class Type: @classmethod def str_to_list(xcls, str_object): list = map(str.strip, str_object.split(',')) try: list.remove('') except ValueError: pass return list @classmethod def list_to_str(xcls, list_object): return ', '.join(list_object) @classmethod def str_to_bool(xcls, str_object): if str_object == "yes" or str_object == "on" or str_object == "true": return True elif str_object == "no" or str_object == "off" or str_object == "false": return False else: raise TypeError @classmethod def bool_to_str(xcls, bool_object): if bool_object: return "yes" else: return "no" ## Instruction: Allow “enabled“, “enable”, “disabled“, “disable” as boolean values ## Code After: class Type: @classmethod def str_to_list(xcls, str_object): list = map(str.strip, str_object.split(',')) try: list.remove('') except ValueError: pass return list @classmethod def list_to_str(xcls, list_object): return ', '.join(list_object) @classmethod def str_to_bool(xcls, str_object): if str_object == "yes" or str_object == "on" or str_object == "true" or str_object == "enabled" or str_object == "enable": return True elif str_object == "no" or str_object == "off" or str_object == "false" or str_object == "disabled" or str_object == "disable": return False else: raise TypeError @classmethod def bool_to_str(xcls, bool_object): if bool_object: return "yes" else: return "no"
# ... existing code ... @classmethod def str_to_bool(xcls, str_object): if str_object == "yes" or str_object == "on" or str_object == "true" or str_object == "enabled" or str_object == "enable": return True elif str_object == "no" or str_object == "off" or str_object == "false" or str_object == "disabled" or str_object == "disable": return False else: # ... rest of the code ...
b875f457d7a4926f5028428ead4cecc75af90c2e
examples/launch_cloud_harness.py
examples/launch_cloud_harness.py
import json import os from osgeo import gdal from gbdxtools import Interface from gbdx_task_template import TaskTemplate, Task, InputPort, OutputPort gbdx = Interface() # data = "s3://receiving-dgcs-tdgplatform-com/054813633050_01_003" # WV02 Image over San Francisco # aoptask = gbdx.Task("AOP_Strip_Processor", data=data, enable_acomp=True, enable_pansharpen=True) class RasterMetaApp(TaskTemplate): task = Task("RasterMetaTask") task.input_raster = InputPort(value="/Users/michaelconnor/demo_image") task.output_meta = OutputPort(value="/Users/michaelconnor") def invoke(self): images = self.task.input_raster.list_files(extensions=[".tiff", ".tif"]) # Magic Starts here for img in images: header = "META FOR %s\n\n" % os.path.basename(img) gtif = gdal.Open(img) self.task.output_meta.write('metadata.txt', header) self.task.output_meta.write('metadata.txt', json.dumps(gtif.GetMetadata(), indent=2)) # Create a cloud-harness ch_task = gbdx.Task(RasterMetaApp) # NOTE: This will override the value in the class definition above. ch_task.inputs.input_raster = 's3://test-tdgplatform-com/data/envi_src/sm_tiff' # Overwrite the value from workflow = gbdx.Workflow([ch_task]) # workflow = gbdx.Workflow([aoptask, ch_task]) workflow.savedata(ch_task.outputs.output_meta, location='CH_OUT') # workflow.savedata(aoptask.outputs.data, location='AOP_OUT') # NOTE: Always required because the source bundle must be uploaded. ch_task.upload_input_ports() print(workflow.generate_workflow_description()) print(workflow.execute())
from gbdxtools import Interface gbdx = Interface() # Create a cloud-harness gbdxtools Task from ch_tasks.cp_task import CopyTask cp_task = gbdx.Task(CopyTask) from ch_tasks.raster_meta import RasterMetaTask ch_task = gbdx.Task(RasterMetaTask) # NOTE: This will override the value in the class definition. ch_task.inputs.input_raster = cp_task.outputs.output_data.value # Overwrite the value from workflow = gbdx.Workflow([cp_task, ch_task]) workflow.savedata(cp_task.outputs.output_data, location='CH_Demo/output_data') workflow.savedata(ch_task.outputs.output_meta, location='CH_Demo/output_meta') print(workflow.execute()) # Will upload cloud-harness ports before executing # print(workflow.generate_workflow_description())
Remove the cloud-harness task and add second cloud-harness task for chaining.
Remove the cloud-harness task and add second cloud-harness task for chaining.
Python
mit
michaelconnor00/gbdxtools,michaelconnor00/gbdxtools
+ from gbdxtools import Interface + gbdx = Interface() - import json - import os - from osgeo import gdal - from gbdxtools import Interface - from gbdx_task_template import TaskTemplate, Task, InputPort, OutputPort + # Create a cloud-harness gbdxtools Task + + from ch_tasks.cp_task import CopyTask + cp_task = gbdx.Task(CopyTask) + + from ch_tasks.raster_meta import RasterMetaTask + ch_task = gbdx.Task(RasterMetaTask) + + # NOTE: This will override the value in the class definition. + ch_task.inputs.input_raster = cp_task.outputs.output_data.value # Overwrite the value from + + workflow = gbdx.Workflow([cp_task, ch_task]) + + workflow.savedata(cp_task.outputs.output_data, location='CH_Demo/output_data') + workflow.savedata(ch_task.outputs.output_meta, location='CH_Demo/output_meta') - gbdx = Interface() + print(workflow.execute()) # Will upload cloud-harness ports before executing + # print(workflow.generate_workflow_description()) - # data = "s3://receiving-dgcs-tdgplatform-com/054813633050_01_003" # WV02 Image over San Francisco - # aoptask = gbdx.Task("AOP_Strip_Processor", data=data, enable_acomp=True, enable_pansharpen=True) - - - class RasterMetaApp(TaskTemplate): - - task = Task("RasterMetaTask") - - task.input_raster = InputPort(value="/Users/michaelconnor/demo_image") - - task.output_meta = OutputPort(value="/Users/michaelconnor") - - def invoke(self): - - images = self.task.input_raster.list_files(extensions=[".tiff", ".tif"]) - - # Magic Starts here - for img in images: - header = "META FOR %s\n\n" % os.path.basename(img) - gtif = gdal.Open(img) - - self.task.output_meta.write('metadata.txt', header) - self.task.output_meta.write('metadata.txt', json.dumps(gtif.GetMetadata(), indent=2)) - - # Create a cloud-harness - ch_task = gbdx.Task(RasterMetaApp) - - - # NOTE: This will override the value in the class definition above. - ch_task.inputs.input_raster = 's3://test-tdgplatform-com/data/envi_src/sm_tiff' # Overwrite the value from - - - workflow = gbdx.Workflow([ch_task]) - # workflow = gbdx.Workflow([aoptask, ch_task]) - - workflow.savedata(ch_task.outputs.output_meta, location='CH_OUT') - # workflow.savedata(aoptask.outputs.data, location='AOP_OUT') - - # NOTE: Always required because the source bundle must be uploaded. - ch_task.upload_input_ports() - - - print(workflow.generate_workflow_description()) - print(workflow.execute()) -
Remove the cloud-harness task and add second cloud-harness task for chaining.
## Code Before: import json import os from osgeo import gdal from gbdxtools import Interface from gbdx_task_template import TaskTemplate, Task, InputPort, OutputPort gbdx = Interface() # data = "s3://receiving-dgcs-tdgplatform-com/054813633050_01_003" # WV02 Image over San Francisco # aoptask = gbdx.Task("AOP_Strip_Processor", data=data, enable_acomp=True, enable_pansharpen=True) class RasterMetaApp(TaskTemplate): task = Task("RasterMetaTask") task.input_raster = InputPort(value="/Users/michaelconnor/demo_image") task.output_meta = OutputPort(value="/Users/michaelconnor") def invoke(self): images = self.task.input_raster.list_files(extensions=[".tiff", ".tif"]) # Magic Starts here for img in images: header = "META FOR %s\n\n" % os.path.basename(img) gtif = gdal.Open(img) self.task.output_meta.write('metadata.txt', header) self.task.output_meta.write('metadata.txt', json.dumps(gtif.GetMetadata(), indent=2)) # Create a cloud-harness ch_task = gbdx.Task(RasterMetaApp) # NOTE: This will override the value in the class definition above. ch_task.inputs.input_raster = 's3://test-tdgplatform-com/data/envi_src/sm_tiff' # Overwrite the value from workflow = gbdx.Workflow([ch_task]) # workflow = gbdx.Workflow([aoptask, ch_task]) workflow.savedata(ch_task.outputs.output_meta, location='CH_OUT') # workflow.savedata(aoptask.outputs.data, location='AOP_OUT') # NOTE: Always required because the source bundle must be uploaded. ch_task.upload_input_ports() print(workflow.generate_workflow_description()) print(workflow.execute()) ## Instruction: Remove the cloud-harness task and add second cloud-harness task for chaining. ## Code After: from gbdxtools import Interface gbdx = Interface() # Create a cloud-harness gbdxtools Task from ch_tasks.cp_task import CopyTask cp_task = gbdx.Task(CopyTask) from ch_tasks.raster_meta import RasterMetaTask ch_task = gbdx.Task(RasterMetaTask) # NOTE: This will override the value in the class definition. ch_task.inputs.input_raster = cp_task.outputs.output_data.value # Overwrite the value from workflow = gbdx.Workflow([cp_task, ch_task]) workflow.savedata(cp_task.outputs.output_data, location='CH_Demo/output_data') workflow.savedata(ch_task.outputs.output_meta, location='CH_Demo/output_meta') print(workflow.execute()) # Will upload cloud-harness ports before executing # print(workflow.generate_workflow_description())
# ... existing code ... from gbdxtools import Interface gbdx = Interface() # Create a cloud-harness gbdxtools Task from ch_tasks.cp_task import CopyTask cp_task = gbdx.Task(CopyTask) from ch_tasks.raster_meta import RasterMetaTask ch_task = gbdx.Task(RasterMetaTask) # NOTE: This will override the value in the class definition. ch_task.inputs.input_raster = cp_task.outputs.output_data.value # Overwrite the value from workflow = gbdx.Workflow([cp_task, ch_task]) workflow.savedata(cp_task.outputs.output_data, location='CH_Demo/output_data') workflow.savedata(ch_task.outputs.output_meta, location='CH_Demo/output_meta') print(workflow.execute()) # Will upload cloud-harness ports before executing # print(workflow.generate_workflow_description()) # ... rest of the code ...
1e2086b868861034d89138349c4da909f380f19e
feedback/views.py
feedback/views.py
from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt from rest_framework import serializers, status from rest_framework.response import Response from rest_framework.views import APIView from .models import Feedback class FeedbackSerializer(serializers.ModelSerializer): class Meta: model = Feedback @method_decorator(csrf_exempt, name='dispatch') class FeedbackView(APIView): @csrf_exempt def post(self, request, format=None): if self.request.user.is_authenticated(): user = self.request.user else: user = None if 'user' in request.data: del request.data['user'] user_agent = request.data.get('user_agent') if not user_agent: user_agent = request.META.get('HTTP_USER_AGENT', None) serializer = FeedbackSerializer(data=request.data) if serializer.is_valid(): serializer.save(user=user, user_agent=user_agent) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt from rest_framework import serializers, status from rest_framework.response import Response from rest_framework.views import APIView from .models import Feedback class FeedbackSerializer(serializers.ModelSerializer): class Meta: model = Feedback fields = '__all__' @method_decorator(csrf_exempt, name='dispatch') class FeedbackView(APIView): @csrf_exempt def post(self, request, format=None): if self.request.user.is_authenticated(): user = self.request.user else: user = None if 'user' in request.data: del request.data['user'] user_agent = request.data.get('user_agent') if not user_agent: user_agent = request.META.get('HTTP_USER_AGENT', None) serializer = FeedbackSerializer(data=request.data) if serializer.is_valid(): serializer.save(user=user, user_agent=user_agent) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Make feedback compatible with DRF >3.3.0
Make feedback compatible with DRF >3.3.0
Python
mit
City-of-Helsinki/digihel,City-of-Helsinki/digihel,City-of-Helsinki/digihel,City-of-Helsinki/digihel
from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt from rest_framework import serializers, status from rest_framework.response import Response from rest_framework.views import APIView from .models import Feedback class FeedbackSerializer(serializers.ModelSerializer): class Meta: model = Feedback + fields = '__all__' @method_decorator(csrf_exempt, name='dispatch') class FeedbackView(APIView): @csrf_exempt def post(self, request, format=None): if self.request.user.is_authenticated(): user = self.request.user else: user = None if 'user' in request.data: del request.data['user'] user_agent = request.data.get('user_agent') if not user_agent: user_agent = request.META.get('HTTP_USER_AGENT', None) serializer = FeedbackSerializer(data=request.data) if serializer.is_valid(): serializer.save(user=user, user_agent=user_agent) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Make feedback compatible with DRF >3.3.0
## Code Before: from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt from rest_framework import serializers, status from rest_framework.response import Response from rest_framework.views import APIView from .models import Feedback class FeedbackSerializer(serializers.ModelSerializer): class Meta: model = Feedback @method_decorator(csrf_exempt, name='dispatch') class FeedbackView(APIView): @csrf_exempt def post(self, request, format=None): if self.request.user.is_authenticated(): user = self.request.user else: user = None if 'user' in request.data: del request.data['user'] user_agent = request.data.get('user_agent') if not user_agent: user_agent = request.META.get('HTTP_USER_AGENT', None) serializer = FeedbackSerializer(data=request.data) if serializer.is_valid(): serializer.save(user=user, user_agent=user_agent) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) ## Instruction: Make feedback compatible with DRF >3.3.0 ## Code After: from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt from rest_framework import serializers, status from rest_framework.response import Response from rest_framework.views import APIView from .models import Feedback class FeedbackSerializer(serializers.ModelSerializer): class Meta: model = Feedback fields = '__all__' @method_decorator(csrf_exempt, name='dispatch') class FeedbackView(APIView): @csrf_exempt def post(self, request, format=None): if self.request.user.is_authenticated(): user = self.request.user else: user = None if 'user' in request.data: del request.data['user'] user_agent = request.data.get('user_agent') if not user_agent: user_agent = request.META.get('HTTP_USER_AGENT', None) serializer = FeedbackSerializer(data=request.data) if serializer.is_valid(): serializer.save(user=user, user_agent=user_agent) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
... class Meta: model = Feedback fields = '__all__' ...
ba3544fc18d5c5e827b1c1777b7811201545a8c5
boto/pyami/scriptbase.py
boto/pyami/scriptbase.py
import os, sys, time, traceback import smtplib from boto.utils import ShellCommand, get_ts import boto import boto.utils class ScriptBase: def __init__(self, config_file=None): self.instance_id = boto.config.get('Instance', 'instance-id', 'default') self.name = self.__class__.__name__ self.ts = get_ts() if config_file: boto.config.read(config_file) def notify(self, subject, body=''): boto.utils.notify(subject, body) def mkdir(self, path): if not os.path.isdir(path): try: os.mkdir(path) except: boto.log.error('Error creating directory: %s' % path) def umount(self, path): if os.path.ismount(path): self.run('umount %s' % path) def run(self, command, notify=True, exit_on_error=False): self.last_command = ShellCommand(command) if self.last_command.status != 0: boto.log.error(self.last_command.output) if notify: self.notify('Error encountered', self.last_command.output) if exit_on_error: sys.exit(-1) return self.last_command.status def main(self): pass
import os, sys, time, traceback import smtplib from boto.utils import ShellCommand, get_ts import boto import boto.utils class ScriptBase: def __init__(self, config_file=None): self.instance_id = boto.config.get('Instance', 'instance-id', 'default') self.name = self.__class__.__name__ self.ts = get_ts() if config_file: boto.config.read(config_file) def notify(self, subject, body=''): boto.utils.notify(subject, body) def mkdir(self, path): if not os.path.isdir(path): try: os.mkdir(path) except: boto.log.error('Error creating directory: %s' % path) def umount(self, path): if os.path.ismount(path): self.run('umount %s' % path) def run(self, command, notify=True, exit_on_error=False): self.last_command = ShellCommand(command) if self.last_command.status != 0: boto.log.error('Error running command: "%s". Output: "%s"' % (command, self.last_command.output)) if notify: self.notify('Error encountered', \ 'Error running the following command:\n\t%s\n\nCommand output:\n\t%s' % \ (command, self.last_command.output)) if exit_on_error: sys.exit(-1) return self.last_command.status def main(self): pass
Add the command that failed to the error log and the error email to help debug problems where the error produces no output.
Add the command that failed to the error log and the error email to help debug problems where the error produces no output.
Python
mit
appneta/boto,dimdung/boto,j-carl/boto,ekalosak/boto,drbild/boto,acourtney2015/boto,bryx-inc/boto,darjus-amzn/boto,ddzialak/boto,alfredodeza/boto,vijaylbais/boto,clouddocx/boto,israelbenatar/boto,alex/boto,podhmo/boto,cyclecomputing/boto,shipci/boto,kouk/boto,jindongh/boto,felix-d/boto,Timus1712/boto,alex/boto,lochiiconnectivity/boto,Pretio/boto,dablak/boto,weebygames/boto,tpodowd/boto,jamesls/boto,disruptek/boto,dablak/boto,elainexmas/boto,jameslegg/boto,lochiiconnectivity/boto,varunarya10/boto,jamesls/boto,jameslegg/boto,bleib1dj/boto,nikhilraog/boto,pfhayes/boto,yangchaogit/boto,abridgett/boto,serviceagility/boto,tpodowd/boto,campenberger/boto,ryansb/boto,kouk/boto,ocadotechnology/boto,zzzirk/boto,FATruden/boto,revmischa/boto,weka-io/boto,rayluo/boto,shaunbrady/boto,TiVoMaker/boto,rosmo/boto,ric03uec/boto,vishnugonela/boto,lra/boto,drbild/boto,andresriancho/boto,garnaat/boto,awatts/boto,trademob/boto,andresriancho/boto,khagler/boto,nishigori/boto,ramitsurana/boto,SaranyaKarthikeyan/boto,nexusz99/boto,appneta/boto,zachmullen/boto,Asana/boto,rjschwei/boto,s0enke/boto,rjschwei/boto,stevenbrichards/boto,disruptek/boto,jotes/boto,janslow/boto
import os, sys, time, traceback import smtplib from boto.utils import ShellCommand, get_ts import boto import boto.utils class ScriptBase: def __init__(self, config_file=None): self.instance_id = boto.config.get('Instance', 'instance-id', 'default') self.name = self.__class__.__name__ self.ts = get_ts() if config_file: boto.config.read(config_file) def notify(self, subject, body=''): boto.utils.notify(subject, body) def mkdir(self, path): if not os.path.isdir(path): try: os.mkdir(path) except: boto.log.error('Error creating directory: %s' % path) def umount(self, path): if os.path.ismount(path): self.run('umount %s' % path) def run(self, command, notify=True, exit_on_error=False): self.last_command = ShellCommand(command) if self.last_command.status != 0: - boto.log.error(self.last_command.output) + boto.log.error('Error running command: "%s". Output: "%s"' % (command, self.last_command.output)) if notify: - self.notify('Error encountered', self.last_command.output) + self.notify('Error encountered', \ + 'Error running the following command:\n\t%s\n\nCommand output:\n\t%s' % \ + (command, self.last_command.output)) if exit_on_error: sys.exit(-1) return self.last_command.status def main(self): pass
Add the command that failed to the error log and the error email to help debug problems where the error produces no output.
## Code Before: import os, sys, time, traceback import smtplib from boto.utils import ShellCommand, get_ts import boto import boto.utils class ScriptBase: def __init__(self, config_file=None): self.instance_id = boto.config.get('Instance', 'instance-id', 'default') self.name = self.__class__.__name__ self.ts = get_ts() if config_file: boto.config.read(config_file) def notify(self, subject, body=''): boto.utils.notify(subject, body) def mkdir(self, path): if not os.path.isdir(path): try: os.mkdir(path) except: boto.log.error('Error creating directory: %s' % path) def umount(self, path): if os.path.ismount(path): self.run('umount %s' % path) def run(self, command, notify=True, exit_on_error=False): self.last_command = ShellCommand(command) if self.last_command.status != 0: boto.log.error(self.last_command.output) if notify: self.notify('Error encountered', self.last_command.output) if exit_on_error: sys.exit(-1) return self.last_command.status def main(self): pass ## Instruction: Add the command that failed to the error log and the error email to help debug problems where the error produces no output. ## Code After: import os, sys, time, traceback import smtplib from boto.utils import ShellCommand, get_ts import boto import boto.utils class ScriptBase: def __init__(self, config_file=None): self.instance_id = boto.config.get('Instance', 'instance-id', 'default') self.name = self.__class__.__name__ self.ts = get_ts() if config_file: boto.config.read(config_file) def notify(self, subject, body=''): boto.utils.notify(subject, body) def mkdir(self, path): if not os.path.isdir(path): try: os.mkdir(path) except: boto.log.error('Error creating directory: %s' % path) def umount(self, path): if os.path.ismount(path): self.run('umount %s' % path) def run(self, command, notify=True, exit_on_error=False): self.last_command = ShellCommand(command) if self.last_command.status != 0: boto.log.error('Error running command: "%s". Output: "%s"' % (command, self.last_command.output)) if notify: self.notify('Error encountered', \ 'Error running the following command:\n\t%s\n\nCommand output:\n\t%s' % \ (command, self.last_command.output)) if exit_on_error: sys.exit(-1) return self.last_command.status def main(self): pass
# ... existing code ... self.last_command = ShellCommand(command) if self.last_command.status != 0: boto.log.error('Error running command: "%s". Output: "%s"' % (command, self.last_command.output)) if notify: self.notify('Error encountered', \ 'Error running the following command:\n\t%s\n\nCommand output:\n\t%s' % \ (command, self.last_command.output)) if exit_on_error: sys.exit(-1) # ... rest of the code ...
3b105973a6aad7885fd56182ad32e2731de9a432
django_evolution/compat/patches/sqlite_legacy_alter_table.py
django_evolution/compat/patches/sqlite_legacy_alter_table.py
"""Patch to enable SQLite Legacy Alter Table support.""" from __future__ import unicode_literals import sqlite3 import django from django.db.backends.sqlite3.base import DatabaseWrapper def needs_patch(): """Return whether the SQLite backend needs patching. It will need patching if using Django 1.11 through 2.1.4 while using SQLite3 v2.26. Returns: bool: ``True`` if the backend needs to be patched. ``False`` if it does not. """ return (sqlite3.sqlite_version_info > (2, 26, 0) and (1, 11) <= django.VERSION < (2, 1, 5)) def apply_patch(): """Apply a patch to the SQLite database backend. This will turn on SQLite's ``legacy_alter_table`` mode on when modifying the schema, which is needed in order to successfully allow Django to make table modifications. """ class DatabaseSchemaEditor(DatabaseWrapper.SchemaEditorClass): def __enter__(self): with self.connection.cursor() as c: c.execute('PRAGMA legacy_alter_table = ON') return super(DatabaseSchemaEditor, self).__enter__() def __exit__(self, *args, **kwargs): super(DatabaseSchemaEditor, self).__exit__(*args, **kwargs) with self.connection.cursor() as c: c.execute('PRAGMA legacy_alter_table = OFF') DatabaseWrapper.SchemaEditorClass = DatabaseSchemaEditor
"""Patch to enable SQLite Legacy Alter Table support.""" from __future__ import unicode_literals import sqlite3 import django def needs_patch(): """Return whether the SQLite backend needs patching. It will need patching if using Django 1.11 through 2.1.4 while using SQLite3 v2.26. Returns: bool: ``True`` if the backend needs to be patched. ``False`` if it does not. """ return (sqlite3.sqlite_version_info > (2, 26, 0) and (1, 11) <= django.VERSION < (2, 1, 5)) def apply_patch(): """Apply a patch to the SQLite database backend. This will turn on SQLite's ``legacy_alter_table`` mode on when modifying the schema, which is needed in order to successfully allow Django to make table modifications. """ from django.db.backends.sqlite3.base import DatabaseWrapper class DatabaseSchemaEditor(DatabaseWrapper.SchemaEditorClass): def __enter__(self): with self.connection.cursor() as c: c.execute('PRAGMA legacy_alter_table = ON') return super(DatabaseSchemaEditor, self).__enter__() def __exit__(self, *args, **kwargs): super(DatabaseSchemaEditor, self).__exit__(*args, **kwargs) with self.connection.cursor() as c: c.execute('PRAGMA legacy_alter_table = OFF') DatabaseWrapper.SchemaEditorClass = DatabaseSchemaEditor
Fix a premature import when patching SQLite compatibility.
Fix a premature import when patching SQLite compatibility. We provide a compatibility patch that fixes certain versions of SQLite with Django prior to 2.1.5. This patch made the assumption that it could import the Django SQLite backend at the module level, since SQLite is built into Python. However, on modern versions of Django, this will fail to import if the version of SQLite is too old. We now import this only if we're about to apply the patch, in which case we've already confirmed the compatible version range. Testing Done: Tested on reviews.reviewboard.org, where this problem was first encountered due to an older SQLite. We no longer hit a premature import. Reviewed at https://reviews.reviewboard.org/r/12414/
Python
bsd-3-clause
beanbaginc/django-evolution
"""Patch to enable SQLite Legacy Alter Table support.""" from __future__ import unicode_literals import sqlite3 import django - from django.db.backends.sqlite3.base import DatabaseWrapper def needs_patch(): """Return whether the SQLite backend needs patching. It will need patching if using Django 1.11 through 2.1.4 while using SQLite3 v2.26. Returns: bool: ``True`` if the backend needs to be patched. ``False`` if it does not. """ return (sqlite3.sqlite_version_info > (2, 26, 0) and (1, 11) <= django.VERSION < (2, 1, 5)) def apply_patch(): """Apply a patch to the SQLite database backend. This will turn on SQLite's ``legacy_alter_table`` mode on when modifying the schema, which is needed in order to successfully allow Django to make table modifications. """ + from django.db.backends.sqlite3.base import DatabaseWrapper + class DatabaseSchemaEditor(DatabaseWrapper.SchemaEditorClass): def __enter__(self): with self.connection.cursor() as c: c.execute('PRAGMA legacy_alter_table = ON') return super(DatabaseSchemaEditor, self).__enter__() def __exit__(self, *args, **kwargs): super(DatabaseSchemaEditor, self).__exit__(*args, **kwargs) with self.connection.cursor() as c: c.execute('PRAGMA legacy_alter_table = OFF') DatabaseWrapper.SchemaEditorClass = DatabaseSchemaEditor
Fix a premature import when patching SQLite compatibility.
## Code Before: """Patch to enable SQLite Legacy Alter Table support.""" from __future__ import unicode_literals import sqlite3 import django from django.db.backends.sqlite3.base import DatabaseWrapper def needs_patch(): """Return whether the SQLite backend needs patching. It will need patching if using Django 1.11 through 2.1.4 while using SQLite3 v2.26. Returns: bool: ``True`` if the backend needs to be patched. ``False`` if it does not. """ return (sqlite3.sqlite_version_info > (2, 26, 0) and (1, 11) <= django.VERSION < (2, 1, 5)) def apply_patch(): """Apply a patch to the SQLite database backend. This will turn on SQLite's ``legacy_alter_table`` mode on when modifying the schema, which is needed in order to successfully allow Django to make table modifications. """ class DatabaseSchemaEditor(DatabaseWrapper.SchemaEditorClass): def __enter__(self): with self.connection.cursor() as c: c.execute('PRAGMA legacy_alter_table = ON') return super(DatabaseSchemaEditor, self).__enter__() def __exit__(self, *args, **kwargs): super(DatabaseSchemaEditor, self).__exit__(*args, **kwargs) with self.connection.cursor() as c: c.execute('PRAGMA legacy_alter_table = OFF') DatabaseWrapper.SchemaEditorClass = DatabaseSchemaEditor ## Instruction: Fix a premature import when patching SQLite compatibility. ## Code After: """Patch to enable SQLite Legacy Alter Table support.""" from __future__ import unicode_literals import sqlite3 import django def needs_patch(): """Return whether the SQLite backend needs patching. It will need patching if using Django 1.11 through 2.1.4 while using SQLite3 v2.26. Returns: bool: ``True`` if the backend needs to be patched. ``False`` if it does not. """ return (sqlite3.sqlite_version_info > (2, 26, 0) and (1, 11) <= django.VERSION < (2, 1, 5)) def apply_patch(): """Apply a patch to the SQLite database backend. This will turn on SQLite's ``legacy_alter_table`` mode on when modifying the schema, which is needed in order to successfully allow Django to make table modifications. """ from django.db.backends.sqlite3.base import DatabaseWrapper class DatabaseSchemaEditor(DatabaseWrapper.SchemaEditorClass): def __enter__(self): with self.connection.cursor() as c: c.execute('PRAGMA legacy_alter_table = ON') return super(DatabaseSchemaEditor, self).__enter__() def __exit__(self, *args, **kwargs): super(DatabaseSchemaEditor, self).__exit__(*args, **kwargs) with self.connection.cursor() as c: c.execute('PRAGMA legacy_alter_table = OFF') DatabaseWrapper.SchemaEditorClass = DatabaseSchemaEditor
... import django ... table modifications. """ from django.db.backends.sqlite3.base import DatabaseWrapper class DatabaseSchemaEditor(DatabaseWrapper.SchemaEditorClass): def __enter__(self): ...
12fc9a49a0dd55836165d89df6bb59ffecdd03eb
bayespy/inference/vmp/nodes/__init__.py
bayespy/inference/vmp/nodes/__init__.py
from . import * from .bernoulli import Bernoulli from .binomial import Binomial from .categorical import Categorical from .multinomial import Multinomial from .poisson import Poisson from .beta import Beta from .beta import Complement from .dirichlet import Dirichlet, DirichletConcentration from .exponential import Exponential from .gaussian import Gaussian, GaussianARD from .wishart import Wishart from .gamma import Gamma, GammaShape from .gaussian import (GaussianGamma, GaussianWishart) from .gaussian_markov_chain import GaussianMarkovChain from .gaussian_markov_chain import VaryingGaussianMarkovChain from .gaussian_markov_chain import SwitchingGaussianMarkovChain from .categorical_markov_chain import CategoricalMarkovChain from .mixture import Mixture, MultiMixture from .gate import Gate from .concatenate import Concatenate from .dot import Dot from .dot import SumMultiply from .add import Add from .take import Take from .gaussian import ConcatGaussian from .logpdf import LogPDF from .constant import Constant
from . import * from .bernoulli import Bernoulli from .binomial import Binomial from .categorical import Categorical from .multinomial import Multinomial from .poisson import Poisson from .beta import Beta from .beta import Complement from .dirichlet import Dirichlet, DirichletConcentration from .exponential import Exponential from .gaussian import Gaussian, GaussianARD from .wishart import Wishart from .gamma import Gamma, GammaShape from .gaussian import (GaussianGamma, GaussianWishart) from .gaussian_markov_chain import GaussianMarkovChain from .gaussian_markov_chain import VaryingGaussianMarkovChain from .gaussian_markov_chain import SwitchingGaussianMarkovChain from .categorical_markov_chain import CategoricalMarkovChain from .mixture import Mixture, MultiMixture from .gate import Gate from .gate import Choose from .concatenate import Concatenate from .dot import Dot from .dot import SumMultiply from .add import Add from .take import Take from .gaussian import ConcatGaussian from .logpdf import LogPDF from .constant import Constant
Add Choose node to imported nodes
ENH: Add Choose node to imported nodes
Python
mit
bayespy/bayespy,jluttine/bayespy
from . import * from .bernoulli import Bernoulli from .binomial import Binomial from .categorical import Categorical from .multinomial import Multinomial from .poisson import Poisson from .beta import Beta from .beta import Complement from .dirichlet import Dirichlet, DirichletConcentration from .exponential import Exponential from .gaussian import Gaussian, GaussianARD from .wishart import Wishart from .gamma import Gamma, GammaShape from .gaussian import (GaussianGamma, GaussianWishart) from .gaussian_markov_chain import GaussianMarkovChain from .gaussian_markov_chain import VaryingGaussianMarkovChain from .gaussian_markov_chain import SwitchingGaussianMarkovChain from .categorical_markov_chain import CategoricalMarkovChain from .mixture import Mixture, MultiMixture from .gate import Gate + from .gate import Choose from .concatenate import Concatenate from .dot import Dot from .dot import SumMultiply from .add import Add from .take import Take from .gaussian import ConcatGaussian from .logpdf import LogPDF from .constant import Constant
Add Choose node to imported nodes
## Code Before: from . import * from .bernoulli import Bernoulli from .binomial import Binomial from .categorical import Categorical from .multinomial import Multinomial from .poisson import Poisson from .beta import Beta from .beta import Complement from .dirichlet import Dirichlet, DirichletConcentration from .exponential import Exponential from .gaussian import Gaussian, GaussianARD from .wishart import Wishart from .gamma import Gamma, GammaShape from .gaussian import (GaussianGamma, GaussianWishart) from .gaussian_markov_chain import GaussianMarkovChain from .gaussian_markov_chain import VaryingGaussianMarkovChain from .gaussian_markov_chain import SwitchingGaussianMarkovChain from .categorical_markov_chain import CategoricalMarkovChain from .mixture import Mixture, MultiMixture from .gate import Gate from .concatenate import Concatenate from .dot import Dot from .dot import SumMultiply from .add import Add from .take import Take from .gaussian import ConcatGaussian from .logpdf import LogPDF from .constant import Constant ## Instruction: Add Choose node to imported nodes ## Code After: from . import * from .bernoulli import Bernoulli from .binomial import Binomial from .categorical import Categorical from .multinomial import Multinomial from .poisson import Poisson from .beta import Beta from .beta import Complement from .dirichlet import Dirichlet, DirichletConcentration from .exponential import Exponential from .gaussian import Gaussian, GaussianARD from .wishart import Wishart from .gamma import Gamma, GammaShape from .gaussian import (GaussianGamma, GaussianWishart) from .gaussian_markov_chain import GaussianMarkovChain from .gaussian_markov_chain import VaryingGaussianMarkovChain from .gaussian_markov_chain import SwitchingGaussianMarkovChain from .categorical_markov_chain import CategoricalMarkovChain from .mixture import Mixture, MultiMixture from .gate import Gate from .gate import Choose from .concatenate import Concatenate from .dot import Dot from .dot import SumMultiply from .add import Add from .take import Take from .gaussian import ConcatGaussian from .logpdf import LogPDF from .constant import Constant
# ... existing code ... from .mixture import Mixture, MultiMixture from .gate import Gate from .gate import Choose from .concatenate import Concatenate # ... rest of the code ...
bdeb28f2f7840c04dbf65b6c0771c121f229e59a
tests.py
tests.py
import sys import os import unittest from straight.plugin.loader import StraightPluginLoader class PluginTestCase(unittest.TestCase): def setUp(self): self.loader = StraightPluginLoader() self.added_path = os.path.join(os.path.dirname(__file__), 'more-test-plugins') self.added_path = os.path.join(os.path.dirname(__file__), 'some-test-plugins') sys.path.append(self.added_path) def tearDown(self): del sys.path[-1] del sys.path[-1] def test_load(self): modules = list(self.loader.load('testplugin')) assert len(modules) == 2, modules def test_plugin(self): assert self.loader.load('testplugin')[0].do(1) == 2 if __name__ == '__main__': unittest.main()
import sys import os import unittest from straight.plugin.loader import StraightPluginLoader class PluginTestCase(unittest.TestCase): def setUp(self): self.loader = StraightPluginLoader() sys.path.append(os.path.join(os.path.dirname(__file__), 'more-test-plugins')) sys.path.append(os.path.join(os.path.dirname(__file__), 'some-test-plugins')) def tearDown(self): del sys.path[-1] del sys.path[-1] def test_load(self): modules = list(self.loader.load('testplugin')) assert len(modules) == 2, modules def test_plugin(self): assert self.loader.load('testplugin')[0].do(1) == 2 if __name__ == '__main__': unittest.main()
Fix test case for multiple locations of a namespace
Fix test case for multiple locations of a namespace
Python
mit
ironfroggy/straight.plugin,pombredanne/straight.plugin
import sys import os import unittest from straight.plugin.loader import StraightPluginLoader class PluginTestCase(unittest.TestCase): def setUp(self): self.loader = StraightPluginLoader() - self.added_path = os.path.join(os.path.dirname(__file__), 'more-test-plugins') + sys.path.append(os.path.join(os.path.dirname(__file__), 'more-test-plugins')) - self.added_path = os.path.join(os.path.dirname(__file__), 'some-test-plugins') + sys.path.append(os.path.join(os.path.dirname(__file__), 'some-test-plugins')) - sys.path.append(self.added_path) def tearDown(self): del sys.path[-1] del sys.path[-1] def test_load(self): modules = list(self.loader.load('testplugin')) assert len(modules) == 2, modules def test_plugin(self): assert self.loader.load('testplugin')[0].do(1) == 2 if __name__ == '__main__': unittest.main()
Fix test case for multiple locations of a namespace
## Code Before: import sys import os import unittest from straight.plugin.loader import StraightPluginLoader class PluginTestCase(unittest.TestCase): def setUp(self): self.loader = StraightPluginLoader() self.added_path = os.path.join(os.path.dirname(__file__), 'more-test-plugins') self.added_path = os.path.join(os.path.dirname(__file__), 'some-test-plugins') sys.path.append(self.added_path) def tearDown(self): del sys.path[-1] del sys.path[-1] def test_load(self): modules = list(self.loader.load('testplugin')) assert len(modules) == 2, modules def test_plugin(self): assert self.loader.load('testplugin')[0].do(1) == 2 if __name__ == '__main__': unittest.main() ## Instruction: Fix test case for multiple locations of a namespace ## Code After: import sys import os import unittest from straight.plugin.loader import StraightPluginLoader class PluginTestCase(unittest.TestCase): def setUp(self): self.loader = StraightPluginLoader() sys.path.append(os.path.join(os.path.dirname(__file__), 'more-test-plugins')) sys.path.append(os.path.join(os.path.dirname(__file__), 'some-test-plugins')) def tearDown(self): del sys.path[-1] del sys.path[-1] def test_load(self): modules = list(self.loader.load('testplugin')) assert len(modules) == 2, modules def test_plugin(self): assert self.loader.load('testplugin')[0].do(1) == 2 if __name__ == '__main__': unittest.main()
... def setUp(self): self.loader = StraightPluginLoader() sys.path.append(os.path.join(os.path.dirname(__file__), 'more-test-plugins')) sys.path.append(os.path.join(os.path.dirname(__file__), 'some-test-plugins')) def tearDown(self): ...
8442e89d005af039252b0f8ab757bb54fa4ed71c
tests.py
tests.py
import unittest from pollster.pollster import Pollster, Chart class TestBasic(unittest.TestCase): def test_basic_setup(self): p = Pollster() self.assertIsNotNone(p) def test_charts(self): c = Pollster().charts() self.assertIsNotNone(c) self.assertIsInstance(c, list) self.assertGreater(len(c), 0) def test_chart(self): c = Pollster().charts()[0] self.assertIsInstance(c, Chart) cc = Pollster().chart(c.slug) self.assertEqual(c.slug, cc.slug) for attr in ['last_updated', 'title', 'url', 'estimates', 'poll_count', 'topic', 'state', 'slug', ]: self.assertIsNotNone(getattr(c, attr)) self.assertIsNotNone(getattr(cc, attr)) self.assertEqual(getattr(c, attr), getattr(cc, attr)) self.assertIsInstance(c.estimates_by_date(), list) def test_polls(self): polls = Pollster().polls(topic='2016-president') self.assertGreater(len(polls), 0)
import unittest from pollster.pollster import Pollster, Chart class TestBasic(unittest.TestCase): def test_basic_setup(self): p = Pollster() self.assertIsNotNone(p) def test_charts(self): c = Pollster().charts() self.assertIsNotNone(c) self.assertIsInstance(c, list) self.assertGreater(len(c), 0) def test_chart(self): c = Pollster().charts()[0] self.assertIsInstance(c, Chart) cc = Pollster().chart(c.slug) self.assertEqual(c.slug, cc.slug) for attr in ['last_updated', 'title', 'url', 'estimates', 'poll_count', 'topic', 'state', 'slug', ]: self.assertIsNotNone(getattr(c, attr)) self.assertIsNotNone(getattr(cc, attr)) self.assertEqual(getattr(c, attr), getattr(cc, attr)) self.assertIsInstance(c.estimates_by_date(), list) def test_polls(self): polls = Pollster().polls(topic='2016-president') self.assertGreater(len(polls), 0) poll = polls[0] for attr in ['id', 'pollster', 'start_date', 'end_date', 'method', 'source', 'questions', 'survey_houses', 'sponsors', 'partisan', 'affiliation']: self.assertIsNotNone(getattr(poll, attr))
Update Poll test to check members.
Update Poll test to check members.
Python
bsd-2-clause
huffpostdata/python-pollster,ternus/python-pollster
import unittest from pollster.pollster import Pollster, Chart class TestBasic(unittest.TestCase): def test_basic_setup(self): p = Pollster() self.assertIsNotNone(p) def test_charts(self): c = Pollster().charts() self.assertIsNotNone(c) self.assertIsInstance(c, list) self.assertGreater(len(c), 0) def test_chart(self): c = Pollster().charts()[0] self.assertIsInstance(c, Chart) cc = Pollster().chart(c.slug) self.assertEqual(c.slug, cc.slug) for attr in ['last_updated', 'title', 'url', 'estimates', 'poll_count', 'topic', 'state', 'slug', ]: self.assertIsNotNone(getattr(c, attr)) self.assertIsNotNone(getattr(cc, attr)) self.assertEqual(getattr(c, attr), getattr(cc, attr)) self.assertIsInstance(c.estimates_by_date(), list) def test_polls(self): polls = Pollster().polls(topic='2016-president') self.assertGreater(len(polls), 0) + poll = polls[0] + for attr in ['id', + 'pollster', + 'start_date', + 'end_date', + 'method', + 'source', + 'questions', + 'survey_houses', + 'sponsors', + 'partisan', + 'affiliation']: + self.assertIsNotNone(getattr(poll, attr))
Update Poll test to check members.
## Code Before: import unittest from pollster.pollster import Pollster, Chart class TestBasic(unittest.TestCase): def test_basic_setup(self): p = Pollster() self.assertIsNotNone(p) def test_charts(self): c = Pollster().charts() self.assertIsNotNone(c) self.assertIsInstance(c, list) self.assertGreater(len(c), 0) def test_chart(self): c = Pollster().charts()[0] self.assertIsInstance(c, Chart) cc = Pollster().chart(c.slug) self.assertEqual(c.slug, cc.slug) for attr in ['last_updated', 'title', 'url', 'estimates', 'poll_count', 'topic', 'state', 'slug', ]: self.assertIsNotNone(getattr(c, attr)) self.assertIsNotNone(getattr(cc, attr)) self.assertEqual(getattr(c, attr), getattr(cc, attr)) self.assertIsInstance(c.estimates_by_date(), list) def test_polls(self): polls = Pollster().polls(topic='2016-president') self.assertGreater(len(polls), 0) ## Instruction: Update Poll test to check members. ## Code After: import unittest from pollster.pollster import Pollster, Chart class TestBasic(unittest.TestCase): def test_basic_setup(self): p = Pollster() self.assertIsNotNone(p) def test_charts(self): c = Pollster().charts() self.assertIsNotNone(c) self.assertIsInstance(c, list) self.assertGreater(len(c), 0) def test_chart(self): c = Pollster().charts()[0] self.assertIsInstance(c, Chart) cc = Pollster().chart(c.slug) self.assertEqual(c.slug, cc.slug) for attr in ['last_updated', 'title', 'url', 'estimates', 'poll_count', 'topic', 'state', 'slug', ]: self.assertIsNotNone(getattr(c, attr)) self.assertIsNotNone(getattr(cc, attr)) self.assertEqual(getattr(c, attr), getattr(cc, attr)) self.assertIsInstance(c.estimates_by_date(), list) def test_polls(self): polls = Pollster().polls(topic='2016-president') self.assertGreater(len(polls), 0) poll = polls[0] for attr in ['id', 'pollster', 'start_date', 'end_date', 'method', 'source', 'questions', 'survey_houses', 'sponsors', 'partisan', 'affiliation']: self.assertIsNotNone(getattr(poll, attr))
... polls = Pollster().polls(topic='2016-president') self.assertGreater(len(polls), 0) poll = polls[0] for attr in ['id', 'pollster', 'start_date', 'end_date', 'method', 'source', 'questions', 'survey_houses', 'sponsors', 'partisan', 'affiliation']: self.assertIsNotNone(getattr(poll, attr)) ...
f7341acf0717d238073a688c6047e18b524efab1
qmpy/configuration/resources/__init__.py
qmpy/configuration/resources/__init__.py
import yaml import os, os.path loc = os.path.dirname(os.path.abspath(__file__)) hosts = yaml.load(open(loc+'/hosts.yml')) projects = yaml.load(open(loc+'/projects.yml')) allocations = yaml.load(open(loc+'/allocations.yml')) users = yaml.load(open(loc+'/users.yml'))
import yaml import os loc = os.path.dirname(os.path.abspath(__file__)) with open(os.path.join(loc, 'hosts.yml'), 'r') as fr: hosts = yaml.load(fr) with open(os.path.join(loc, 'projects.yml'), 'r') as fr: projects = yaml.load(fr) with open(os.path.join(loc, 'allocations.yml'), 'r') as fr: allocations = yaml.load(fr) with open(os.path.join(loc, 'users.yml'), 'r') as fr: users = yaml.load(fr)
Use OS-agnostic path joining operations
Use OS-agnostic path joining operations
Python
mit
wolverton-research-group/qmpy,wolverton-research-group/qmpy,wolverton-research-group/qmpy,wolverton-research-group/qmpy,wolverton-research-group/qmpy
import yaml - import os, os.path + import os loc = os.path.dirname(os.path.abspath(__file__)) + with open(os.path.join(loc, 'hosts.yml'), 'r') as fr: + hosts = yaml.load(fr) - hosts = yaml.load(open(loc+'/hosts.yml')) - projects = yaml.load(open(loc+'/projects.yml')) - allocations = yaml.load(open(loc+'/allocations.yml')) - users = yaml.load(open(loc+'/users.yml')) + with open(os.path.join(loc, 'projects.yml'), 'r') as fr: + projects = yaml.load(fr) + + with open(os.path.join(loc, 'allocations.yml'), 'r') as fr: + allocations = yaml.load(fr) + + with open(os.path.join(loc, 'users.yml'), 'r') as fr: + users = yaml.load(fr) +
Use OS-agnostic path joining operations
## Code Before: import yaml import os, os.path loc = os.path.dirname(os.path.abspath(__file__)) hosts = yaml.load(open(loc+'/hosts.yml')) projects = yaml.load(open(loc+'/projects.yml')) allocations = yaml.load(open(loc+'/allocations.yml')) users = yaml.load(open(loc+'/users.yml')) ## Instruction: Use OS-agnostic path joining operations ## Code After: import yaml import os loc = os.path.dirname(os.path.abspath(__file__)) with open(os.path.join(loc, 'hosts.yml'), 'r') as fr: hosts = yaml.load(fr) with open(os.path.join(loc, 'projects.yml'), 'r') as fr: projects = yaml.load(fr) with open(os.path.join(loc, 'allocations.yml'), 'r') as fr: allocations = yaml.load(fr) with open(os.path.join(loc, 'users.yml'), 'r') as fr: users = yaml.load(fr)
# ... existing code ... import yaml import os loc = os.path.dirname(os.path.abspath(__file__)) with open(os.path.join(loc, 'hosts.yml'), 'r') as fr: hosts = yaml.load(fr) with open(os.path.join(loc, 'projects.yml'), 'r') as fr: projects = yaml.load(fr) with open(os.path.join(loc, 'allocations.yml'), 'r') as fr: allocations = yaml.load(fr) with open(os.path.join(loc, 'users.yml'), 'r') as fr: users = yaml.load(fr) # ... rest of the code ...
09eb16e94052cbf45708b20e783a602342a2b85b
photutils/__init__.py
photutils/__init__.py
import os # Affiliated packages may add whatever they like to this file, but # should keep this content at the top. # ---------------------------------------------------------------------------- from ._astropy_init import * # noqa # ---------------------------------------------------------------------------- if not _ASTROPY_SETUP_: # noqa from .aperture import * # noqa from .background import * # noqa from .centroids import * # noqa from .detection import * # noqa from .morphology import * # noqa from .psf import * # noqa from .segmentation import * # noqa # Set the bibtex entry to the article referenced in CITATION. def _get_bibtex(): citation_file = os.path.join(os.path.dirname(__file__), 'CITATION') with open(citation_file, 'r') as citation: refs = citation.read().split('@misc')[1:] if len(refs) == 0: return '' bibtexreference = "@misc{0}".format(refs[0]) return bibtexreference __citation__ = __bibtex__ = _get_bibtex()
import os # Affiliated packages may add whatever they like to this file, but # should keep this content at the top. # ---------------------------------------------------------------------------- from ._astropy_init import * # noqa # ---------------------------------------------------------------------------- if not _ASTROPY_SETUP_: # noqa from .aperture import * # noqa from .background import * # noqa from .centroids import * # noqa from .detection import * # noqa from .morphology import * # noqa from .psf import * # noqa from .segmentation import * # noqa __all__ = ['test'] # the test runner is defined in _astropy_init # Set the bibtex entry to the article referenced in CITATION. def _get_bibtex(): citation_file = os.path.join(os.path.dirname(__file__), 'CITATION') with open(citation_file, 'r') as citation: refs = citation.read().split('@misc')[1:] if len(refs) == 0: return '' bibtexreference = "@misc{0}".format(refs[0]) return bibtexreference __citation__ = __bibtex__ = _get_bibtex()
Add __all__ in package init for the test runner
Add __all__ in package init for the test runner
Python
bsd-3-clause
larrybradley/photutils,astropy/photutils
import os # Affiliated packages may add whatever they like to this file, but # should keep this content at the top. # ---------------------------------------------------------------------------- from ._astropy_init import * # noqa # ---------------------------------------------------------------------------- if not _ASTROPY_SETUP_: # noqa from .aperture import * # noqa from .background import * # noqa from .centroids import * # noqa from .detection import * # noqa from .morphology import * # noqa from .psf import * # noqa from .segmentation import * # noqa + __all__ = ['test'] # the test runner is defined in _astropy_init + # Set the bibtex entry to the article referenced in CITATION. def _get_bibtex(): citation_file = os.path.join(os.path.dirname(__file__), 'CITATION') with open(citation_file, 'r') as citation: refs = citation.read().split('@misc')[1:] if len(refs) == 0: return '' bibtexreference = "@misc{0}".format(refs[0]) return bibtexreference __citation__ = __bibtex__ = _get_bibtex()
Add __all__ in package init for the test runner
## Code Before: import os # Affiliated packages may add whatever they like to this file, but # should keep this content at the top. # ---------------------------------------------------------------------------- from ._astropy_init import * # noqa # ---------------------------------------------------------------------------- if not _ASTROPY_SETUP_: # noqa from .aperture import * # noqa from .background import * # noqa from .centroids import * # noqa from .detection import * # noqa from .morphology import * # noqa from .psf import * # noqa from .segmentation import * # noqa # Set the bibtex entry to the article referenced in CITATION. def _get_bibtex(): citation_file = os.path.join(os.path.dirname(__file__), 'CITATION') with open(citation_file, 'r') as citation: refs = citation.read().split('@misc')[1:] if len(refs) == 0: return '' bibtexreference = "@misc{0}".format(refs[0]) return bibtexreference __citation__ = __bibtex__ = _get_bibtex() ## Instruction: Add __all__ in package init for the test runner ## Code After: import os # Affiliated packages may add whatever they like to this file, but # should keep this content at the top. # ---------------------------------------------------------------------------- from ._astropy_init import * # noqa # ---------------------------------------------------------------------------- if not _ASTROPY_SETUP_: # noqa from .aperture import * # noqa from .background import * # noqa from .centroids import * # noqa from .detection import * # noqa from .morphology import * # noqa from .psf import * # noqa from .segmentation import * # noqa __all__ = ['test'] # the test runner is defined in _astropy_init # Set the bibtex entry to the article referenced in CITATION. def _get_bibtex(): citation_file = os.path.join(os.path.dirname(__file__), 'CITATION') with open(citation_file, 'r') as citation: refs = citation.read().split('@misc')[1:] if len(refs) == 0: return '' bibtexreference = "@misc{0}".format(refs[0]) return bibtexreference __citation__ = __bibtex__ = _get_bibtex()
... from .segmentation import * # noqa __all__ = ['test'] # the test runner is defined in _astropy_init # Set the bibtex entry to the article referenced in CITATION. ...
4a37433c43ffda2443f80cc93c99f9cd76aa6475
examples/miniapps/movie_lister/movies/__init__.py
examples/miniapps/movie_lister/movies/__init__.py
import movies.finders import movies.listers import movies.models import dependency_injector.containers as containers import dependency_injector.providers as providers class MoviesModule(containers.DeclarativeContainer): """IoC container of movies module component providers.""" models_factory = providers.Factory(movies.models.Movie) finder = providers.AbstractFactory(movies.finders.MovieFinder, movie_model=models_factory.delegate()) lister = providers.Factory(movies.listers.MovieLister, movie_finder=finder)
import movies.finders import movies.listers import movies.models import dependency_injector.containers as containers import dependency_injector.providers as providers class MoviesModule(containers.DeclarativeContainer): """IoC container of movies module component providers.""" movie = providers.Factory(movies.models.Movie) finder = providers.AbstractFactory(movies.finders.MovieFinder, movie_model=movie.provider) lister = providers.Factory(movies.listers.MovieLister, movie_finder=finder)
Add minor fixes to movie lister miniapp
Add minor fixes to movie lister miniapp
Python
bsd-3-clause
rmk135/objects,ets-labs/python-dependency-injector,ets-labs/dependency_injector,rmk135/dependency_injector
import movies.finders import movies.listers import movies.models import dependency_injector.containers as containers import dependency_injector.providers as providers class MoviesModule(containers.DeclarativeContainer): """IoC container of movies module component providers.""" - models_factory = providers.Factory(movies.models.Movie) + movie = providers.Factory(movies.models.Movie) finder = providers.AbstractFactory(movies.finders.MovieFinder, - movie_model=models_factory.delegate()) + movie_model=movie.provider) lister = providers.Factory(movies.listers.MovieLister, movie_finder=finder)
Add minor fixes to movie lister miniapp
## Code Before: import movies.finders import movies.listers import movies.models import dependency_injector.containers as containers import dependency_injector.providers as providers class MoviesModule(containers.DeclarativeContainer): """IoC container of movies module component providers.""" models_factory = providers.Factory(movies.models.Movie) finder = providers.AbstractFactory(movies.finders.MovieFinder, movie_model=models_factory.delegate()) lister = providers.Factory(movies.listers.MovieLister, movie_finder=finder) ## Instruction: Add minor fixes to movie lister miniapp ## Code After: import movies.finders import movies.listers import movies.models import dependency_injector.containers as containers import dependency_injector.providers as providers class MoviesModule(containers.DeclarativeContainer): """IoC container of movies module component providers.""" movie = providers.Factory(movies.models.Movie) finder = providers.AbstractFactory(movies.finders.MovieFinder, movie_model=movie.provider) lister = providers.Factory(movies.listers.MovieLister, movie_finder=finder)
// ... existing code ... """IoC container of movies module component providers.""" movie = providers.Factory(movies.models.Movie) finder = providers.AbstractFactory(movies.finders.MovieFinder, movie_model=movie.provider) lister = providers.Factory(movies.listers.MovieLister, // ... rest of the code ...
a76c7ddc80c3896dd4397b4713de267001706722
thefederation/migrations/0020_remove_port_from_node_hostnames.py
thefederation/migrations/0020_remove_port_from_node_hostnames.py
from django.db import migrations from django.db.migrations import RunPython def forward(apps, schema): Node = apps.get_model("thefederation", "Node") for node in Node.objects.filter(host__contains=":"): node.host = node.host.split(":")[0] if node.name.split(':')[0] == node.host: node.name = node.host Node.objects.filter(id=node.id).update(host=node.host, name=node.name) class Migration(migrations.Migration): dependencies = [ ('thefederation', '0019_add_some_defaults_for_node_organization_fields'), ] operations = [ RunPython(forward, RunPython.noop) ]
from django.db import migrations, IntegrityError from django.db.migrations import RunPython def forward(apps, schema): Node = apps.get_model("thefederation", "Node") for node in Node.objects.filter(host__contains=":"): node.host = node.host.split(":")[0] if node.name.split(':')[0] == node.host: node.name = node.host try: Node.objects.filter(id=node.id).update(host=node.host, name=node.name) except IntegrityError: pass class Migration(migrations.Migration): dependencies = [ ('thefederation', '0019_add_some_defaults_for_node_organization_fields'), ] operations = [ RunPython(forward, RunPython.noop) ]
Make port removing migrating a bit less flaky
Make port removing migrating a bit less flaky
Python
agpl-3.0
jaywink/the-federation.info,jaywink/the-federation.info,jaywink/the-federation.info
- from django.db import migrations + from django.db import migrations, IntegrityError from django.db.migrations import RunPython def forward(apps, schema): Node = apps.get_model("thefederation", "Node") for node in Node.objects.filter(host__contains=":"): node.host = node.host.split(":")[0] if node.name.split(':')[0] == node.host: node.name = node.host + try: - Node.objects.filter(id=node.id).update(host=node.host, name=node.name) + Node.objects.filter(id=node.id).update(host=node.host, name=node.name) + except IntegrityError: + pass class Migration(migrations.Migration): dependencies = [ ('thefederation', '0019_add_some_defaults_for_node_organization_fields'), ] operations = [ RunPython(forward, RunPython.noop) ]
Make port removing migrating a bit less flaky
## Code Before: from django.db import migrations from django.db.migrations import RunPython def forward(apps, schema): Node = apps.get_model("thefederation", "Node") for node in Node.objects.filter(host__contains=":"): node.host = node.host.split(":")[0] if node.name.split(':')[0] == node.host: node.name = node.host Node.objects.filter(id=node.id).update(host=node.host, name=node.name) class Migration(migrations.Migration): dependencies = [ ('thefederation', '0019_add_some_defaults_for_node_organization_fields'), ] operations = [ RunPython(forward, RunPython.noop) ] ## Instruction: Make port removing migrating a bit less flaky ## Code After: from django.db import migrations, IntegrityError from django.db.migrations import RunPython def forward(apps, schema): Node = apps.get_model("thefederation", "Node") for node in Node.objects.filter(host__contains=":"): node.host = node.host.split(":")[0] if node.name.split(':')[0] == node.host: node.name = node.host try: Node.objects.filter(id=node.id).update(host=node.host, name=node.name) except IntegrityError: pass class Migration(migrations.Migration): dependencies = [ ('thefederation', '0019_add_some_defaults_for_node_organization_fields'), ] operations = [ RunPython(forward, RunPython.noop) ]
... from django.db import migrations, IntegrityError from django.db.migrations import RunPython ... if node.name.split(':')[0] == node.host: node.name = node.host try: Node.objects.filter(id=node.id).update(host=node.host, name=node.name) except IntegrityError: pass ...
a8112a8ee3723d5ae097998efc7c43bd27cbee95
engineer/processors.py
engineer/processors.py
import logging import subprocess from path import path from engineer.conf import settings __author__ = '[email protected]' logger = logging.getLogger(__name__) # Helper function to preprocess LESS files on demand def preprocess_less(file): input_file = path(settings.OUTPUT_CACHE_DIR / settings.ENGINEER.STATIC_DIR.basename() / file) css_file = path("%s.css" % str(input_file)[:-5]) if not css_file.exists(): cmd = str.format(str(settings.LESS_PREPROCESSOR), infile=input_file, outfile=css_file).split() try: result = subprocess.check_output(cmd) except subprocess.CalledProcessError as e: logger.critical(e.cmd) logger.critical(e.output) raise logger.info("Preprocessed LESS file %s." % file) return ""
import logging import platform import subprocess from path import path from engineer.conf import settings __author__ = '[email protected]' logger = logging.getLogger(__name__) # Helper function to preprocess LESS files on demand def preprocess_less(file): input_file = path(settings.OUTPUT_CACHE_DIR / settings.ENGINEER.STATIC_DIR.basename() / file) css_file = path("%s.css" % str(input_file)[:-5]) if not css_file.exists(): cmd = str.format(str(settings.LESS_PREPROCESSOR), infile=input_file, outfile=css_file).split() try: result = subprocess.check_output(cmd) except subprocess.CalledProcessError as e: logger.critical("Error pre-processing LESS file %s." % file) logger.critical(e.output) exit(1355) except WindowsError as e: logger.critical("Unexpected error pre-processing LESS file %s." % file) logger.critical(e.strerror) exit(1355) except Exception as e: logger.critical("Unexpected error pre-processing LESS file %s." % file) logger.critical(e.message) if platform.system() != 'Windows': logger.critical("Are you sure lessc is on your path?") exit(1355) logger.info("Preprocessed LESS file %s." % file) return ""
Handle LESS preprocessor errors more gracefully.
Handle LESS preprocessor errors more gracefully.
Python
mit
tylerbutler/engineer,tylerbutler/engineer,tylerbutler/engineer
import logging + import platform import subprocess from path import path from engineer.conf import settings __author__ = '[email protected]' logger = logging.getLogger(__name__) # Helper function to preprocess LESS files on demand def preprocess_less(file): input_file = path(settings.OUTPUT_CACHE_DIR / settings.ENGINEER.STATIC_DIR.basename() / file) css_file = path("%s.css" % str(input_file)[:-5]) if not css_file.exists(): cmd = str.format(str(settings.LESS_PREPROCESSOR), infile=input_file, outfile=css_file).split() try: result = subprocess.check_output(cmd) except subprocess.CalledProcessError as e: - logger.critical(e.cmd) + logger.critical("Error pre-processing LESS file %s." % file) logger.critical(e.output) - raise + exit(1355) + except WindowsError as e: + logger.critical("Unexpected error pre-processing LESS file %s." % file) + logger.critical(e.strerror) + exit(1355) + except Exception as e: + logger.critical("Unexpected error pre-processing LESS file %s." % file) + logger.critical(e.message) + if platform.system() != 'Windows': + logger.critical("Are you sure lessc is on your path?") + exit(1355) logger.info("Preprocessed LESS file %s." % file) return ""
Handle LESS preprocessor errors more gracefully.
## Code Before: import logging import subprocess from path import path from engineer.conf import settings __author__ = '[email protected]' logger = logging.getLogger(__name__) # Helper function to preprocess LESS files on demand def preprocess_less(file): input_file = path(settings.OUTPUT_CACHE_DIR / settings.ENGINEER.STATIC_DIR.basename() / file) css_file = path("%s.css" % str(input_file)[:-5]) if not css_file.exists(): cmd = str.format(str(settings.LESS_PREPROCESSOR), infile=input_file, outfile=css_file).split() try: result = subprocess.check_output(cmd) except subprocess.CalledProcessError as e: logger.critical(e.cmd) logger.critical(e.output) raise logger.info("Preprocessed LESS file %s." % file) return "" ## Instruction: Handle LESS preprocessor errors more gracefully. ## Code After: import logging import platform import subprocess from path import path from engineer.conf import settings __author__ = '[email protected]' logger = logging.getLogger(__name__) # Helper function to preprocess LESS files on demand def preprocess_less(file): input_file = path(settings.OUTPUT_CACHE_DIR / settings.ENGINEER.STATIC_DIR.basename() / file) css_file = path("%s.css" % str(input_file)[:-5]) if not css_file.exists(): cmd = str.format(str(settings.LESS_PREPROCESSOR), infile=input_file, outfile=css_file).split() try: result = subprocess.check_output(cmd) except subprocess.CalledProcessError as e: logger.critical("Error pre-processing LESS file %s." % file) logger.critical(e.output) exit(1355) except WindowsError as e: logger.critical("Unexpected error pre-processing LESS file %s." % file) logger.critical(e.strerror) exit(1355) except Exception as e: logger.critical("Unexpected error pre-processing LESS file %s." % file) logger.critical(e.message) if platform.system() != 'Windows': logger.critical("Are you sure lessc is on your path?") exit(1355) logger.info("Preprocessed LESS file %s." % file) return ""
... import logging import platform import subprocess from path import path ... result = subprocess.check_output(cmd) except subprocess.CalledProcessError as e: logger.critical("Error pre-processing LESS file %s." % file) logger.critical(e.output) exit(1355) except WindowsError as e: logger.critical("Unexpected error pre-processing LESS file %s." % file) logger.critical(e.strerror) exit(1355) except Exception as e: logger.critical("Unexpected error pre-processing LESS file %s." % file) logger.critical(e.message) if platform.system() != 'Windows': logger.critical("Are you sure lessc is on your path?") exit(1355) logger.info("Preprocessed LESS file %s." % file) return "" ...
0b15611eb0020bc2cdb4a4435756315b0bd97a21
seria/cli.py
seria/cli.py
import click from .compat import StringIO import seria CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help']) @click.command(context_settings=CONTEXT_SETTINGS) @click.option('--xml', 'out_fmt', flag_value='xml') @click.option('--yaml', 'out_fmt', flag_value='yaml') @click.option('--json', 'out_fmt', flag_value='json') @click.argument('input', type=click.File('rb'), default='-') @click.argument('output', type=click.File('wb'), default='-') def cli(out_fmt, input, output): """Converts text.""" _input = StringIO() for l in input: try: _input.write(str(l)) except TypeError: _input.write(bytes(l, 'utf-8')) _serialized_obj = seria.load(_input) output.write(_serialized_obj.dump(out_fmt)) if __name__ == '__main__': cli(out_fmt, input, output)
import click from .compat import StringIO, str, builtin_str import seria CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help']) @click.command(context_settings=CONTEXT_SETTINGS) @click.option('--xml', 'out_fmt', flag_value='xml') @click.option('--yaml', 'out_fmt', flag_value='yaml') @click.option('--json', 'out_fmt', flag_value='json') @click.argument('input', type=click.File('r'), default='-') @click.argument('output', type=click.File('w'), default='-') def cli(out_fmt, input, output): """Converts text.""" _input = StringIO() for l in input: try: _input.write(str(l)) except TypeError: _input.write(bytes(l, 'utf-8')) _input = seria.load(_input) _out = (_input.dump(out_fmt)) output.write(_out) if __name__ == '__main__': cli(out_fmt, input, output)
Fix errors with 2/3 FLO support
Fix errors with 2/3 FLO support
Python
mit
rtluckie/seria
import click - from .compat import StringIO + from .compat import StringIO, str, builtin_str import seria CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help']) @click.command(context_settings=CONTEXT_SETTINGS) @click.option('--xml', 'out_fmt', flag_value='xml') @click.option('--yaml', 'out_fmt', flag_value='yaml') @click.option('--json', 'out_fmt', flag_value='json') - @click.argument('input', type=click.File('rb'), default='-') + @click.argument('input', type=click.File('r'), default='-') - @click.argument('output', type=click.File('wb'), default='-') + @click.argument('output', type=click.File('w'), default='-') def cli(out_fmt, input, output): """Converts text.""" _input = StringIO() for l in input: try: _input.write(str(l)) except TypeError: _input.write(bytes(l, 'utf-8')) - _serialized_obj = seria.load(_input) + _input = seria.load(_input) - output.write(_serialized_obj.dump(out_fmt)) + _out = (_input.dump(out_fmt)) + output.write(_out) if __name__ == '__main__': cli(out_fmt, input, output) - -
Fix errors with 2/3 FLO support
## Code Before: import click from .compat import StringIO import seria CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help']) @click.command(context_settings=CONTEXT_SETTINGS) @click.option('--xml', 'out_fmt', flag_value='xml') @click.option('--yaml', 'out_fmt', flag_value='yaml') @click.option('--json', 'out_fmt', flag_value='json') @click.argument('input', type=click.File('rb'), default='-') @click.argument('output', type=click.File('wb'), default='-') def cli(out_fmt, input, output): """Converts text.""" _input = StringIO() for l in input: try: _input.write(str(l)) except TypeError: _input.write(bytes(l, 'utf-8')) _serialized_obj = seria.load(_input) output.write(_serialized_obj.dump(out_fmt)) if __name__ == '__main__': cli(out_fmt, input, output) ## Instruction: Fix errors with 2/3 FLO support ## Code After: import click from .compat import StringIO, str, builtin_str import seria CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help']) @click.command(context_settings=CONTEXT_SETTINGS) @click.option('--xml', 'out_fmt', flag_value='xml') @click.option('--yaml', 'out_fmt', flag_value='yaml') @click.option('--json', 'out_fmt', flag_value='json') @click.argument('input', type=click.File('r'), default='-') @click.argument('output', type=click.File('w'), default='-') def cli(out_fmt, input, output): """Converts text.""" _input = StringIO() for l in input: try: _input.write(str(l)) except TypeError: _input.write(bytes(l, 'utf-8')) _input = seria.load(_input) _out = (_input.dump(out_fmt)) output.write(_out) if __name__ == '__main__': cli(out_fmt, input, output)
// ... existing code ... import click from .compat import StringIO, str, builtin_str import seria // ... modified code ... @click.option('--yaml', 'out_fmt', flag_value='yaml') @click.option('--json', 'out_fmt', flag_value='json') @click.argument('input', type=click.File('r'), default='-') @click.argument('output', type=click.File('w'), default='-') def cli(out_fmt, input, output): """Converts text.""" ... except TypeError: _input.write(bytes(l, 'utf-8')) _input = seria.load(_input) _out = (_input.dump(out_fmt)) output.write(_out) ... if __name__ == '__main__': cli(out_fmt, input, output) // ... rest of the code ...
ba8509a34104ff6aab5e97a6bed842b245ec4b64
examples/pi-montecarlo/pi_distarray.py
examples/pi-montecarlo/pi_distarray.py
from __future__ import division import sys from util import timer from distarray.dist import Context, Distribution, hypot from distarray.dist.random import Random context = Context() random = Random(context) def local_sum(mask): return mask.ndarray.sum() @timer def calc_pi(n): """Estimate pi using distributed NumPy arrays.""" distribution = Distribution.from_shape(context=context, shape=(n,)) x = random.rand(distribution) y = random.rand(distribution) r = hypot(x, y) mask = (r < 1) lsum = context.apply(local_sum, (mask.key,)) return 4 * sum(lsum) / n if __name__ == '__main__': N = int(sys.argv[1]) result, time = calc_pi(N) print('time : %3.4g\nresult: %.7f' % (time, result))
from __future__ import division, print_function import sys from util import timer from distarray.dist import Context, Distribution, hypot from distarray.dist.random import Random context = Context() random = Random(context) @timer def calc_pi(n): """Estimate pi using distributed NumPy arrays.""" distribution = Distribution.from_shape(context=context, shape=(n,)) x = random.rand(distribution) y = random.rand(distribution) r = hypot(x, y) mask = (r < 1) return 4 * mask.sum().toarray() / n if __name__ == '__main__': N = int(sys.argv[1]) result, time = calc_pi(N) print('time : %3.4g\nresult: %.7f' % (time, result))
Update pi-montecarlo example to use `sum` again.
Update pi-montecarlo example to use `sum` again.
Python
bsd-3-clause
RaoUmer/distarray,enthought/distarray,enthought/distarray,RaoUmer/distarray
- from __future__ import division + from __future__ import division, print_function import sys from util import timer from distarray.dist import Context, Distribution, hypot from distarray.dist.random import Random context = Context() random = Random(context) - def local_sum(mask): - return mask.ndarray.sum() - - @timer def calc_pi(n): """Estimate pi using distributed NumPy arrays.""" distribution = Distribution.from_shape(context=context, shape=(n,)) x = random.rand(distribution) y = random.rand(distribution) r = hypot(x, y) mask = (r < 1) + return 4 * mask.sum().toarray() / n - lsum = context.apply(local_sum, (mask.key,)) - return 4 * sum(lsum) / n if __name__ == '__main__': N = int(sys.argv[1]) result, time = calc_pi(N) print('time : %3.4g\nresult: %.7f' % (time, result))
Update pi-montecarlo example to use `sum` again.
## Code Before: from __future__ import division import sys from util import timer from distarray.dist import Context, Distribution, hypot from distarray.dist.random import Random context = Context() random = Random(context) def local_sum(mask): return mask.ndarray.sum() @timer def calc_pi(n): """Estimate pi using distributed NumPy arrays.""" distribution = Distribution.from_shape(context=context, shape=(n,)) x = random.rand(distribution) y = random.rand(distribution) r = hypot(x, y) mask = (r < 1) lsum = context.apply(local_sum, (mask.key,)) return 4 * sum(lsum) / n if __name__ == '__main__': N = int(sys.argv[1]) result, time = calc_pi(N) print('time : %3.4g\nresult: %.7f' % (time, result)) ## Instruction: Update pi-montecarlo example to use `sum` again. ## Code After: from __future__ import division, print_function import sys from util import timer from distarray.dist import Context, Distribution, hypot from distarray.dist.random import Random context = Context() random = Random(context) @timer def calc_pi(n): """Estimate pi using distributed NumPy arrays.""" distribution = Distribution.from_shape(context=context, shape=(n,)) x = random.rand(distribution) y = random.rand(distribution) r = hypot(x, y) mask = (r < 1) return 4 * mask.sum().toarray() / n if __name__ == '__main__': N = int(sys.argv[1]) result, time = calc_pi(N) print('time : %3.4g\nresult: %.7f' % (time, result))
// ... existing code ... from __future__ import division, print_function import sys // ... modified code ... @timer def calc_pi(n): ... r = hypot(x, y) mask = (r < 1) return 4 * mask.sum().toarray() / n // ... rest of the code ...
62d9fdfe0ad3fc37286aa19a87e2890aaf90f639
tasks/check_rd2_enablement.py
tasks/check_rd2_enablement.py
import simple_salesforce from cumulusci.tasks.salesforce import BaseSalesforceApiTask class is_rd2_enabled(BaseSalesforceApiTask): def _run_task(self): try: settings = self.sf.query( "SELECT IsRecurringDonations2Enabled__c " "FROM npe03__Recurring_Donations_Settings__c " "WHERE SetupOwnerId IN (SELECT Id FROM Organization)" ) except simple_salesforce.exceptions.SalesforceMalformedRequest: # The field does not exist in the target org, meaning it's # pre-RD2 self.return_values = False return if settings.get("records"): if settings["records"][0]["IsRecurringDonations2Enabled__c"]: self.return_values = True self.return_values = False
import simple_salesforce from cumulusci.tasks.salesforce import BaseSalesforceApiTask class is_rd2_enabled(BaseSalesforceApiTask): def _run_task(self): try: settings = self.sf.query( "SELECT IsRecurringDonations2Enabled__c " "FROM npe03__Recurring_Donations_Settings__c " "WHERE SetupOwnerId IN (SELECT Id FROM Organization)" ) except simple_salesforce.exceptions.SalesforceMalformedRequest: # The field does not exist in the target org, meaning it's # pre-RD2 self.return_values = False return if settings.get("records"): if settings["records"][0]["IsRecurringDonations2Enabled__c"]: self.return_values = True return self.return_values = False
Correct bug in preflight check
Correct bug in preflight check
Python
bsd-3-clause
SalesforceFoundation/Cumulus,SalesforceFoundation/Cumulus,SalesforceFoundation/Cumulus,SalesforceFoundation/Cumulus
import simple_salesforce from cumulusci.tasks.salesforce import BaseSalesforceApiTask class is_rd2_enabled(BaseSalesforceApiTask): def _run_task(self): try: settings = self.sf.query( "SELECT IsRecurringDonations2Enabled__c " "FROM npe03__Recurring_Donations_Settings__c " "WHERE SetupOwnerId IN (SELECT Id FROM Organization)" ) except simple_salesforce.exceptions.SalesforceMalformedRequest: # The field does not exist in the target org, meaning it's # pre-RD2 self.return_values = False return if settings.get("records"): if settings["records"][0]["IsRecurringDonations2Enabled__c"]: self.return_values = True + return self.return_values = False
Correct bug in preflight check
## Code Before: import simple_salesforce from cumulusci.tasks.salesforce import BaseSalesforceApiTask class is_rd2_enabled(BaseSalesforceApiTask): def _run_task(self): try: settings = self.sf.query( "SELECT IsRecurringDonations2Enabled__c " "FROM npe03__Recurring_Donations_Settings__c " "WHERE SetupOwnerId IN (SELECT Id FROM Organization)" ) except simple_salesforce.exceptions.SalesforceMalformedRequest: # The field does not exist in the target org, meaning it's # pre-RD2 self.return_values = False return if settings.get("records"): if settings["records"][0]["IsRecurringDonations2Enabled__c"]: self.return_values = True self.return_values = False ## Instruction: Correct bug in preflight check ## Code After: import simple_salesforce from cumulusci.tasks.salesforce import BaseSalesforceApiTask class is_rd2_enabled(BaseSalesforceApiTask): def _run_task(self): try: settings = self.sf.query( "SELECT IsRecurringDonations2Enabled__c " "FROM npe03__Recurring_Donations_Settings__c " "WHERE SetupOwnerId IN (SELECT Id FROM Organization)" ) except simple_salesforce.exceptions.SalesforceMalformedRequest: # The field does not exist in the target org, meaning it's # pre-RD2 self.return_values = False return if settings.get("records"): if settings["records"][0]["IsRecurringDonations2Enabled__c"]: self.return_values = True return self.return_values = False
// ... existing code ... if settings["records"][0]["IsRecurringDonations2Enabled__c"]: self.return_values = True return self.return_values = False // ... rest of the code ...
69d856b5b6ec9f87b55174ebbd414d9960bb626d
tests/offline/test_pricing.py
tests/offline/test_pricing.py
from __future__ import unicode_literals # Third-party modules import pytest # Project modules from fnapy.exceptions import FnapyPricingError from tests import make_requests_get_mock, fake_manager from tests.offline import create_context_for_requests def test_query_pricing(monkeypatch, fake_manager): context = create_context_for_requests(monkeypatch, fake_manager, 'query_pricing', 'pricing_query') with context: fake_manager.query_pricing(ean='0886971942323') # This time, we must also test the response because it may contain an error we # want to catch and raise a FnapyPricingError def test_query_pricing_with_invalid_ean(monkeypatch, fake_manager): context = create_context_for_requests(monkeypatch, fake_manager, 'query_pricing_with_invalid_ean', 'pricing_query') with context: with pytest.raises(FnapyPricingError): fake_manager.query_pricing(ean='007')
from __future__ import unicode_literals # Third-party modules import pytest # Project modules from fnapy.exceptions import FnapyPricingError from tests import make_requests_get_mock, fake_manager from tests.offline import create_context_for_requests def test_query_pricing(monkeypatch, fake_manager): context = create_context_for_requests(monkeypatch, fake_manager, 'query_pricing', 'pricing_query') with context: eans = [7321900286480, 9780262510875, 5060314991222] fake_manager.query_pricing(eans=eans) # This time, we must also test the response because it may contain an error we # want to catch and raise a FnapyPricingError def test_query_pricing_with_invalid_ean(monkeypatch, fake_manager): context = create_context_for_requests(monkeypatch, fake_manager, 'query_pricing_with_invalid_ean', 'pricing_query') with context: with pytest.raises(FnapyPricingError): fake_manager.query_pricing(eans=['007'])
Update the tests for query_pricing
Update the tests for query_pricing
Python
mit
alexandriagroup/fnapy,alexandriagroup/fnapy
from __future__ import unicode_literals # Third-party modules import pytest # Project modules from fnapy.exceptions import FnapyPricingError from tests import make_requests_get_mock, fake_manager from tests.offline import create_context_for_requests def test_query_pricing(monkeypatch, fake_manager): context = create_context_for_requests(monkeypatch, fake_manager, 'query_pricing', 'pricing_query') with context: + eans = [7321900286480, 9780262510875, 5060314991222] - fake_manager.query_pricing(ean='0886971942323') + fake_manager.query_pricing(eans=eans) # This time, we must also test the response because it may contain an error we # want to catch and raise a FnapyPricingError def test_query_pricing_with_invalid_ean(monkeypatch, fake_manager): context = create_context_for_requests(monkeypatch, fake_manager, 'query_pricing_with_invalid_ean', 'pricing_query') with context: with pytest.raises(FnapyPricingError): - fake_manager.query_pricing(ean='007') + fake_manager.query_pricing(eans=['007'])
Update the tests for query_pricing
## Code Before: from __future__ import unicode_literals # Third-party modules import pytest # Project modules from fnapy.exceptions import FnapyPricingError from tests import make_requests_get_mock, fake_manager from tests.offline import create_context_for_requests def test_query_pricing(monkeypatch, fake_manager): context = create_context_for_requests(monkeypatch, fake_manager, 'query_pricing', 'pricing_query') with context: fake_manager.query_pricing(ean='0886971942323') # This time, we must also test the response because it may contain an error we # want to catch and raise a FnapyPricingError def test_query_pricing_with_invalid_ean(monkeypatch, fake_manager): context = create_context_for_requests(monkeypatch, fake_manager, 'query_pricing_with_invalid_ean', 'pricing_query') with context: with pytest.raises(FnapyPricingError): fake_manager.query_pricing(ean='007') ## Instruction: Update the tests for query_pricing ## Code After: from __future__ import unicode_literals # Third-party modules import pytest # Project modules from fnapy.exceptions import FnapyPricingError from tests import make_requests_get_mock, fake_manager from tests.offline import create_context_for_requests def test_query_pricing(monkeypatch, fake_manager): context = create_context_for_requests(monkeypatch, fake_manager, 'query_pricing', 'pricing_query') with context: eans = [7321900286480, 9780262510875, 5060314991222] fake_manager.query_pricing(eans=eans) # This time, we must also test the response because it may contain an error we # want to catch and raise a FnapyPricingError def test_query_pricing_with_invalid_ean(monkeypatch, fake_manager): context = create_context_for_requests(monkeypatch, fake_manager, 'query_pricing_with_invalid_ean', 'pricing_query') with context: with pytest.raises(FnapyPricingError): fake_manager.query_pricing(eans=['007'])
# ... existing code ... 'query_pricing', 'pricing_query') with context: eans = [7321900286480, 9780262510875, 5060314991222] fake_manager.query_pricing(eans=eans) # ... modified code ... with context: with pytest.raises(FnapyPricingError): fake_manager.query_pricing(eans=['007']) # ... rest of the code ...
6fa6ef07dd18794b75d63ffa2a5be83e2ec9b674
bit/count_ones.py
bit/count_ones.py
def count_ones(n): """ :type n: int :rtype: int """ counter = 0 while n: counter += n & 1 n >>= 1 return counter
def count_ones(n): """ :type n: int :rtype: int """ if n < 0: return counter = 0 while n: counter += n & 1 n >>= 1 return counter
Check if the input is negative
Check if the input is negative As the comments mention, the code would work only for unsigned integers. If a negative integer is provided as input, then the code runs into an infinite loop. To avoid this, we are checking if the input is negative. If yes, then return control before loop is entered.
Python
mit
amaozhao/algorithms,keon/algorithms
def count_ones(n): """ :type n: int :rtype: int """ + if n < 0: + return counter = 0 while n: counter += n & 1 n >>= 1 return counter
Check if the input is negative
## Code Before: def count_ones(n): """ :type n: int :rtype: int """ counter = 0 while n: counter += n & 1 n >>= 1 return counter ## Instruction: Check if the input is negative ## Code After: def count_ones(n): """ :type n: int :rtype: int """ if n < 0: return counter = 0 while n: counter += n & 1 n >>= 1 return counter
... :rtype: int """ if n < 0: return counter = 0 while n: ...
01fa3a2ce4181629db2027fd9797e5592bdadada
python/balcaza/t2wrapper.py
python/balcaza/t2wrapper.py
from t2activity import NestedWorkflow from t2types import ListType, String from t2flow import Workflow class WrapperWorkflow(Workflow): def __init__(self, flow): self.flow = flow Workflow.__init__(self, flow.title, flow.author, flow.description) setattr(self.task, flow.name, NestedWorkflow(flow)) nested = getattr(self.task, flow.name) for port in flow.input: # Set type to same depth, but basetype of String depth = port.type.getDepth() if depth == 0: type = String else: type = ListType(String, depth) # Copy any annotations type.dict = port.type.dict setattr(self.input, port.name, type) getattr(self.input, port.name) >> getattr(nested.input, port.name) for port in flow.output: # Set type to same depth, but basetype of String depth = port.type.getDepth() if depth == 0: type = String else: type = ListType(String, depth) # Copy any annotations type.dict = port.type.dict setattr(self.output, port.name, type) getattr(nested.output, port.name) >> getattr(self.output, port.name)
from t2activity import NestedWorkflow from t2types import ListType, String from t2flow import Workflow class WrapperWorkflow(Workflow): def __init__(self, flow): self.flow = flow Workflow.__init__(self, flow.title, flow.author, flow.description) setattr(self.task, flow.name, NestedWorkflow(flow)) nested = getattr(self.task, flow.name) for port in flow.input: # Set type to same depth, but basetype of String depth = port.type.getDepth() if depth == 0: type = String else: type = ListType(String, depth) # Copy any annotations type.dict = port.type.dict self.input[port.name] = type self.input[port.name] >> nested.input[port.name] for port in flow.output: # Set type to same depth, but basetype of String depth = port.type.getDepth() if depth == 0: type = String else: type = ListType(String, depth) # Copy any annotations type.dict = port.type.dict self.output[port.name] = type nested.output[port.name] >> self.output[port.name]
Change wrapper code to use [] notation for attribute access
Change wrapper code to use [] notation for attribute access
Python
lgpl-2.1
jongiddy/balcazapy,jongiddy/balcazapy,jongiddy/balcazapy
from t2activity import NestedWorkflow from t2types import ListType, String from t2flow import Workflow class WrapperWorkflow(Workflow): def __init__(self, flow): self.flow = flow Workflow.__init__(self, flow.title, flow.author, flow.description) setattr(self.task, flow.name, NestedWorkflow(flow)) nested = getattr(self.task, flow.name) for port in flow.input: # Set type to same depth, but basetype of String depth = port.type.getDepth() if depth == 0: type = String else: type = ListType(String, depth) # Copy any annotations type.dict = port.type.dict - setattr(self.input, port.name, type) + self.input[port.name] = type - getattr(self.input, port.name) >> getattr(nested.input, port.name) + self.input[port.name] >> nested.input[port.name] for port in flow.output: # Set type to same depth, but basetype of String depth = port.type.getDepth() if depth == 0: type = String else: type = ListType(String, depth) # Copy any annotations type.dict = port.type.dict - setattr(self.output, port.name, type) + self.output[port.name] = type - getattr(nested.output, port.name) >> getattr(self.output, port.name) + nested.output[port.name] >> self.output[port.name]
Change wrapper code to use [] notation for attribute access
## Code Before: from t2activity import NestedWorkflow from t2types import ListType, String from t2flow import Workflow class WrapperWorkflow(Workflow): def __init__(self, flow): self.flow = flow Workflow.__init__(self, flow.title, flow.author, flow.description) setattr(self.task, flow.name, NestedWorkflow(flow)) nested = getattr(self.task, flow.name) for port in flow.input: # Set type to same depth, but basetype of String depth = port.type.getDepth() if depth == 0: type = String else: type = ListType(String, depth) # Copy any annotations type.dict = port.type.dict setattr(self.input, port.name, type) getattr(self.input, port.name) >> getattr(nested.input, port.name) for port in flow.output: # Set type to same depth, but basetype of String depth = port.type.getDepth() if depth == 0: type = String else: type = ListType(String, depth) # Copy any annotations type.dict = port.type.dict setattr(self.output, port.name, type) getattr(nested.output, port.name) >> getattr(self.output, port.name) ## Instruction: Change wrapper code to use [] notation for attribute access ## Code After: from t2activity import NestedWorkflow from t2types import ListType, String from t2flow import Workflow class WrapperWorkflow(Workflow): def __init__(self, flow): self.flow = flow Workflow.__init__(self, flow.title, flow.author, flow.description) setattr(self.task, flow.name, NestedWorkflow(flow)) nested = getattr(self.task, flow.name) for port in flow.input: # Set type to same depth, but basetype of String depth = port.type.getDepth() if depth == 0: type = String else: type = ListType(String, depth) # Copy any annotations type.dict = port.type.dict self.input[port.name] = type self.input[port.name] >> nested.input[port.name] for port in flow.output: # Set type to same depth, but basetype of String depth = port.type.getDepth() if depth == 0: type = String else: type = ListType(String, depth) # Copy any annotations type.dict = port.type.dict self.output[port.name] = type nested.output[port.name] >> self.output[port.name]
... # Copy any annotations type.dict = port.type.dict self.input[port.name] = type self.input[port.name] >> nested.input[port.name] for port in flow.output: # Set type to same depth, but basetype of String ... # Copy any annotations type.dict = port.type.dict self.output[port.name] = type nested.output[port.name] >> self.output[port.name] ...
f4c8f003a4ffdd8e64468d261aa2cd34d58f1b9d
src/compdb/__init__.py
src/compdb/__init__.py
import warnings from signac import * msg = "compdb was renamed to signac. Please import signac in the future." warnings.warn(DeprecationWarning, msg)
import warnings from signac import * __all__ = ['core', 'contrib', 'db'] msg = "compdb was renamed to signac. Please import signac in the future." print('Warning!',msg) warnings.warn(msg, DeprecationWarning)
Add surrogate compdb package, linking to signac.
Add surrogate compdb package, linking to signac. Provided to guarantee compatibility. Prints warning on import.
Python
bsd-3-clause
csadorf/signac,csadorf/signac
import warnings from signac import * + __all__ = ['core', 'contrib', 'db'] msg = "compdb was renamed to signac. Please import signac in the future." + print('Warning!',msg) - warnings.warn(DeprecationWarning, msg) + warnings.warn(msg, DeprecationWarning)
Add surrogate compdb package, linking to signac.
## Code Before: import warnings from signac import * msg = "compdb was renamed to signac. Please import signac in the future." warnings.warn(DeprecationWarning, msg) ## Instruction: Add surrogate compdb package, linking to signac. ## Code After: import warnings from signac import * __all__ = ['core', 'contrib', 'db'] msg = "compdb was renamed to signac. Please import signac in the future." print('Warning!',msg) warnings.warn(msg, DeprecationWarning)
... from signac import * __all__ = ['core', 'contrib', 'db'] msg = "compdb was renamed to signac. Please import signac in the future." print('Warning!',msg) warnings.warn(msg, DeprecationWarning) ...
dc2c960bb937cc287dedf95d407ed2e95f3f6724
sigma_files/serializers.py
sigma_files/serializers.py
from rest_framework import serializers from sigma.utils import CurrentUserCreateOnlyDefault from sigma_files.models import Image class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image file = serializers.ImageField(max_length=255) height = serializers.IntegerField(source='file.height', read_only=True) width = serializers.IntegerField(source='file.width', read_only=True) owner = serializers.PrimaryKeyRelatedField(read_only=True, default=CurrentUserCreateOnlyDefault())
from rest_framework import serializers from dry_rest_permissions.generics import DRYPermissionsField from sigma.utils import CurrentUserCreateOnlyDefault from sigma_files.models import Image class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image file = serializers.ImageField(max_length=255) height = serializers.IntegerField(source='file.height', read_only=True) width = serializers.IntegerField(source='file.width', read_only=True) owner = serializers.PrimaryKeyRelatedField(read_only=True, default=CurrentUserCreateOnlyDefault()) permissions = DRYPermissionsField(actions=['read', 'write'])
Add permissions field on ImageSerializer
Add permissions field on ImageSerializer
Python
agpl-3.0
ProjetSigma/backend,ProjetSigma/backend
from rest_framework import serializers + from dry_rest_permissions.generics import DRYPermissionsField from sigma.utils import CurrentUserCreateOnlyDefault from sigma_files.models import Image class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image file = serializers.ImageField(max_length=255) height = serializers.IntegerField(source='file.height', read_only=True) width = serializers.IntegerField(source='file.width', read_only=True) owner = serializers.PrimaryKeyRelatedField(read_only=True, default=CurrentUserCreateOnlyDefault()) + permissions = DRYPermissionsField(actions=['read', 'write'])
Add permissions field on ImageSerializer
## Code Before: from rest_framework import serializers from sigma.utils import CurrentUserCreateOnlyDefault from sigma_files.models import Image class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image file = serializers.ImageField(max_length=255) height = serializers.IntegerField(source='file.height', read_only=True) width = serializers.IntegerField(source='file.width', read_only=True) owner = serializers.PrimaryKeyRelatedField(read_only=True, default=CurrentUserCreateOnlyDefault()) ## Instruction: Add permissions field on ImageSerializer ## Code After: from rest_framework import serializers from dry_rest_permissions.generics import DRYPermissionsField from sigma.utils import CurrentUserCreateOnlyDefault from sigma_files.models import Image class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image file = serializers.ImageField(max_length=255) height = serializers.IntegerField(source='file.height', read_only=True) width = serializers.IntegerField(source='file.width', read_only=True) owner = serializers.PrimaryKeyRelatedField(read_only=True, default=CurrentUserCreateOnlyDefault()) permissions = DRYPermissionsField(actions=['read', 'write'])
# ... existing code ... from rest_framework import serializers from dry_rest_permissions.generics import DRYPermissionsField from sigma.utils import CurrentUserCreateOnlyDefault # ... modified code ... width = serializers.IntegerField(source='file.width', read_only=True) owner = serializers.PrimaryKeyRelatedField(read_only=True, default=CurrentUserCreateOnlyDefault()) permissions = DRYPermissionsField(actions=['read', 'write']) # ... rest of the code ...
760a663ab1c079ea03f022c169f7d2d05346dc02
scipy/ndimage/io.py
scipy/ndimage/io.py
from __future__ import division, print_function, absolute_import _have_pil = True try: from scipy.misc.pilutil import imread as _imread except ImportError: _have_pil = False __all__ = ['imread'] # Use the implementation of `imread` in `scipy.misc.pilutil.imread`. # If it weren't for the different names of the first arguments of # ndimage.io.imread and misc.pilutil.imread, we could simplify this file # by writing # from scipy.misc.pilutil import imread # Unfortunately, because the argument names are different, that # introduces a backwards incompatibility. def imread(fname, flatten=False, mode=None): if _have_pil: return _imread(fname, flatten, mode) raise ImportError("Could not import the Python Imaging Library (PIL)" " required to load image files. Please refer to" " http://pypi.python.org/pypi/PIL/ for installation" " instructions.") if _have_pil and _imread.__doc__ is not None: imread.__doc__ = _imread.__doc__.replace('name : str', 'fname : str')
from __future__ import division, print_function, absolute_import _have_pil = True try: from scipy.misc.pilutil import imread as _imread except ImportError: _have_pil = False __all__ = ['imread'] # Use the implementation of `imread` in `scipy.misc.pilutil.imread`. # If it weren't for the different names of the first arguments of # ndimage.io.imread and misc.pilutil.imread, we could simplify this file # by writing # from scipy.misc.pilutil import imread # Unfortunately, because the argument names are different, that # introduces a backwards incompatibility. def imread(fname, flatten=False, mode=None): if _have_pil: return _imread(fname, flatten, mode) raise ImportError("Could not import the Python Imaging Library (PIL)" " required to load image files. Please refer to" " http://pillow.readthedocs.org/en/latest/installation.html" " for installation instructions.") if _have_pil and _imread.__doc__ is not None: imread.__doc__ = _imread.__doc__.replace('name : str', 'fname : str')
Update PIL error install URL
DOC: Update PIL error install URL Update URL for PIL import error to point to Pillow installation instead of PIL, for the latter is somewhat out of date and does not even Python 3 at the moment unlike Pillow. Closes gh-5779.
Python
bsd-3-clause
anielsen001/scipy,dominicelse/scipy,aarchiba/scipy,gdooper/scipy,gfyoung/scipy,gertingold/scipy,woodscn/scipy,aeklant/scipy,Gillu13/scipy,rgommers/scipy,pyramania/scipy,scipy/scipy,mikebenfield/scipy,jakevdp/scipy,perimosocordiae/scipy,sriki18/scipy,anielsen001/scipy,person142/scipy,lhilt/scipy,aeklant/scipy,behzadnouri/scipy,sriki18/scipy,gfyoung/scipy,jamestwebber/scipy,kleskjr/scipy,lhilt/scipy,argriffing/scipy,jakevdp/scipy,Newman101/scipy,WarrenWeckesser/scipy,ilayn/scipy,jor-/scipy,jamestwebber/scipy,kleskjr/scipy,ilayn/scipy,anntzer/scipy,lhilt/scipy,grlee77/scipy,mdhaber/scipy,jakevdp/scipy,andyfaff/scipy,gdooper/scipy,kleskjr/scipy,pyramania/scipy,kalvdans/scipy,vigna/scipy,e-q/scipy,mdhaber/scipy,andyfaff/scipy,befelix/scipy,surhudm/scipy,niknow/scipy,larsmans/scipy,haudren/scipy,Newman101/scipy,ilayn/scipy,larsmans/scipy,anielsen001/scipy,gdooper/scipy,Stefan-Endres/scipy,woodscn/scipy,woodscn/scipy,tylerjereddy/scipy,nonhermitian/scipy,andyfaff/scipy,WarrenWeckesser/scipy,pbrod/scipy,zerothi/scipy,person142/scipy,surhudm/scipy,matthewalbani/scipy,anntzer/scipy,endolith/scipy,sriki18/scipy,apbard/scipy,pschella/scipy,behzadnouri/scipy,pschella/scipy,pbrod/scipy,befelix/scipy,gertingold/scipy,pyramania/scipy,nmayorov/scipy,chatcannon/scipy,mdhaber/scipy,andyfaff/scipy,bkendzior/scipy,apbard/scipy,jor-/scipy,arokem/scipy,maniteja123/scipy,maniteja123/scipy,chatcannon/scipy,larsmans/scipy,Eric89GXL/scipy,kalvdans/scipy,josephcslater/scipy,nonhermitian/scipy,aarchiba/scipy,Stefan-Endres/scipy,haudren/scipy,haudren/scipy,anielsen001/scipy,endolith/scipy,perimosocordiae/scipy,zerothi/scipy,person142/scipy,anntzer/scipy,surhudm/scipy,woodscn/scipy,befelix/scipy,jjhelmus/scipy,dominicelse/scipy,aarchiba/scipy,maniteja123/scipy,WarrenWeckesser/scipy,matthew-brett/scipy,Stefan-Endres/scipy,niknow/scipy,dominicelse/scipy,Stefan-Endres/scipy,argriffing/scipy,mikebenfield/scipy,person142/scipy,anntzer/scipy,chatcannon/scipy,maniteja123/scipy,scipy/scipy,Gillu13/scipy,jor-/scipy,chatcannon/scipy,andyfaff/scipy,arokem/scipy,pizzathief/scipy,arokem/scipy,nmayorov/scipy,Stefan-Endres/scipy,larsmans/scipy,larsmans/scipy,jor-/scipy,vigna/scipy,kleskjr/scipy,jor-/scipy,matthewalbani/scipy,zerothi/scipy,scipy/scipy,aeklant/scipy,tylerjereddy/scipy,Stefan-Endres/scipy,grlee77/scipy,befelix/scipy,aarchiba/scipy,bkendzior/scipy,rgommers/scipy,larsmans/scipy,matthew-brett/scipy,WarrenWeckesser/scipy,Newman101/scipy,gfyoung/scipy,argriffing/scipy,grlee77/scipy,ilayn/scipy,anntzer/scipy,vigna/scipy,woodscn/scipy,pschella/scipy,Eric89GXL/scipy,endolith/scipy,Gillu13/scipy,mikebenfield/scipy,perimosocordiae/scipy,mikebenfield/scipy,behzadnouri/scipy,anntzer/scipy,pschella/scipy,matthew-brett/scipy,jjhelmus/scipy,nonhermitian/scipy,matthew-brett/scipy,zerothi/scipy,matthewalbani/scipy,woodscn/scipy,kalvdans/scipy,ilayn/scipy,gertingold/scipy,haudren/scipy,surhudm/scipy,perimosocordiae/scipy,Newman101/scipy,andyfaff/scipy,aeklant/scipy,gdooper/scipy,scipy/scipy,matthewalbani/scipy,dominicelse/scipy,sriki18/scipy,jamestwebber/scipy,Newman101/scipy,anielsen001/scipy,nmayorov/scipy,person142/scipy,argriffing/scipy,haudren/scipy,josephcslater/scipy,scipy/scipy,behzadnouri/scipy,jakevdp/scipy,rgommers/scipy,gdooper/scipy,grlee77/scipy,befelix/scipy,matthew-brett/scipy,pizzathief/scipy,pyramania/scipy,pizzathief/scipy,perimosocordiae/scipy,chatcannon/scipy,sriki18/scipy,niknow/scipy,argriffing/scipy,gertingold/scipy,kleskjr/scipy,jjhelmus/scipy,vigna/scipy,zerothi/scipy,Gillu13/scipy,pyramania/scipy,maniteja123/scipy,rgommers/scipy,nonhermitian/scipy,surhudm/scipy,josephcslater/scipy,mdhaber/scipy,tylerjereddy/scipy,e-q/scipy,arokem/scipy,mikebenfield/scipy,jjhelmus/scipy,niknow/scipy,ilayn/scipy,Gillu13/scipy,WarrenWeckesser/scipy,sriki18/scipy,arokem/scipy,perimosocordiae/scipy,pschella/scipy,kalvdans/scipy,endolith/scipy,haudren/scipy,niknow/scipy,Newman101/scipy,zerothi/scipy,pbrod/scipy,kleskjr/scipy,pbrod/scipy,aarchiba/scipy,josephcslater/scipy,behzadnouri/scipy,chatcannon/scipy,WarrenWeckesser/scipy,gfyoung/scipy,rgommers/scipy,jamestwebber/scipy,anielsen001/scipy,Eric89GXL/scipy,Eric89GXL/scipy,pbrod/scipy,nmayorov/scipy,Eric89GXL/scipy,Eric89GXL/scipy,e-q/scipy,apbard/scipy,dominicelse/scipy,e-q/scipy,tylerjereddy/scipy,pizzathief/scipy,endolith/scipy,jakevdp/scipy,lhilt/scipy,kalvdans/scipy,aeklant/scipy,nmayorov/scipy,josephcslater/scipy,argriffing/scipy,matthewalbani/scipy,Gillu13/scipy,lhilt/scipy,apbard/scipy,bkendzior/scipy,niknow/scipy,apbard/scipy,mdhaber/scipy,jamestwebber/scipy,jjhelmus/scipy,tylerjereddy/scipy,gfyoung/scipy,e-q/scipy,nonhermitian/scipy,behzadnouri/scipy,gertingold/scipy,endolith/scipy,pizzathief/scipy,surhudm/scipy,bkendzior/scipy,maniteja123/scipy,grlee77/scipy,pbrod/scipy,vigna/scipy,bkendzior/scipy,scipy/scipy,mdhaber/scipy
from __future__ import division, print_function, absolute_import _have_pil = True try: from scipy.misc.pilutil import imread as _imread except ImportError: _have_pil = False __all__ = ['imread'] # Use the implementation of `imread` in `scipy.misc.pilutil.imread`. # If it weren't for the different names of the first arguments of # ndimage.io.imread and misc.pilutil.imread, we could simplify this file # by writing # from scipy.misc.pilutil import imread # Unfortunately, because the argument names are different, that # introduces a backwards incompatibility. def imread(fname, flatten=False, mode=None): if _have_pil: return _imread(fname, flatten, mode) raise ImportError("Could not import the Python Imaging Library (PIL)" " required to load image files. Please refer to" - " http://pypi.python.org/pypi/PIL/ for installation" + " http://pillow.readthedocs.org/en/latest/installation.html" - " instructions.") + " for installation instructions.") if _have_pil and _imread.__doc__ is not None: imread.__doc__ = _imread.__doc__.replace('name : str', 'fname : str')
Update PIL error install URL
## Code Before: from __future__ import division, print_function, absolute_import _have_pil = True try: from scipy.misc.pilutil import imread as _imread except ImportError: _have_pil = False __all__ = ['imread'] # Use the implementation of `imread` in `scipy.misc.pilutil.imread`. # If it weren't for the different names of the first arguments of # ndimage.io.imread and misc.pilutil.imread, we could simplify this file # by writing # from scipy.misc.pilutil import imread # Unfortunately, because the argument names are different, that # introduces a backwards incompatibility. def imread(fname, flatten=False, mode=None): if _have_pil: return _imread(fname, flatten, mode) raise ImportError("Could not import the Python Imaging Library (PIL)" " required to load image files. Please refer to" " http://pypi.python.org/pypi/PIL/ for installation" " instructions.") if _have_pil and _imread.__doc__ is not None: imread.__doc__ = _imread.__doc__.replace('name : str', 'fname : str') ## Instruction: Update PIL error install URL ## Code After: from __future__ import division, print_function, absolute_import _have_pil = True try: from scipy.misc.pilutil import imread as _imread except ImportError: _have_pil = False __all__ = ['imread'] # Use the implementation of `imread` in `scipy.misc.pilutil.imread`. # If it weren't for the different names of the first arguments of # ndimage.io.imread and misc.pilutil.imread, we could simplify this file # by writing # from scipy.misc.pilutil import imread # Unfortunately, because the argument names are different, that # introduces a backwards incompatibility. def imread(fname, flatten=False, mode=None): if _have_pil: return _imread(fname, flatten, mode) raise ImportError("Could not import the Python Imaging Library (PIL)" " required to load image files. Please refer to" " http://pillow.readthedocs.org/en/latest/installation.html" " for installation instructions.") if _have_pil and _imread.__doc__ is not None: imread.__doc__ = _imread.__doc__.replace('name : str', 'fname : str')
# ... existing code ... raise ImportError("Could not import the Python Imaging Library (PIL)" " required to load image files. Please refer to" " http://pillow.readthedocs.org/en/latest/installation.html" " for installation instructions.") if _have_pil and _imread.__doc__ is not None: # ... rest of the code ...
b3f91806b525ddef50d541f937bed539f9bae20a
mezzanine/project_template/deploy/live_settings.py
mezzanine/project_template/deploy/live_settings.py
DATABASES = { "default": { # Ends with "postgresql_psycopg2", "mysql", "sqlite3" or "oracle". "ENGINE": "django.db.backends.postgresql_psycopg2", # DB name or path to database file if using sqlite3. "NAME": "%(proj_name)s", # Not used with sqlite3. "USER": "%(proj_name)s", # Not used with sqlite3. "PASSWORD": "%(db_pass)s", # Set to empty string for localhost. Not used with sqlite3. "HOST": "127.0.0.1", # Set to empty string for default. Not used with sqlite3. "PORT": "", } } SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTOCOL", "https") CACHE_MIDDLEWARE_SECONDS = 60 CACHES = { "default": { "BACKEND": "django.core.cache.backends.memcached.MemcachedCache", "LOCATION": "127.0.0.1:11211", } }
DATABASES = { "default": { # Ends with "postgresql_psycopg2", "mysql", "sqlite3" or "oracle". "ENGINE": "django.db.backends.postgresql_psycopg2", # DB name or path to database file if using sqlite3. "NAME": "%(proj_name)s", # Not used with sqlite3. "USER": "%(proj_name)s", # Not used with sqlite3. "PASSWORD": "%(db_pass)s", # Set to empty string for localhost. Not used with sqlite3. "HOST": "127.0.0.1", # Set to empty string for default. Not used with sqlite3. "PORT": "", } } SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTOCOL", "https") CACHE_MIDDLEWARE_SECONDS = 60 CACHES = { "default": { "BACKEND": "django.core.cache.backends.memcached.MemcachedCache", "LOCATION": "127.0.0.1:11211", } } SESSION_ENGINE = "django.contrib.sessions.backends.cache"
Use cache backend for sessions in deployed settings.
Use cache backend for sessions in deployed settings.
Python
bsd-2-clause
Kniyl/mezzanine,webounty/mezzanine,spookylukey/mezzanine,theclanks/mezzanine,batpad/mezzanine,sjdines/mezzanine,dovydas/mezzanine,readevalprint/mezzanine,eino-makitalo/mezzanine,industrydive/mezzanine,joshcartme/mezzanine,Cajoline/mezzanine,frankier/mezzanine,PegasusWang/mezzanine,biomassives/mezzanine,Skytorn86/mezzanine,adrian-the-git/mezzanine,agepoly/mezzanine,saintbird/mezzanine,damnfine/mezzanine,stbarnabas/mezzanine,dsanders11/mezzanine,biomassives/mezzanine,gradel/mezzanine,joshcartme/mezzanine,vladir/mezzanine,geodesign/mezzanine,molokov/mezzanine,geodesign/mezzanine,geodesign/mezzanine,sjuxax/mezzanine,orlenko/sfpirg,SoLoHiC/mezzanine,orlenko/sfpirg,wyzex/mezzanine,vladir/mezzanine,wyzex/mezzanine,douglaskastle/mezzanine,Cicero-Zhao/mezzanine,nikolas/mezzanine,theclanks/mezzanine,scarcry/snm-mezzanine,wyzex/mezzanine,frankchin/mezzanine,dekomote/mezzanine-modeltranslation-backport,dekomote/mezzanine-modeltranslation-backport,readevalprint/mezzanine,dsanders11/mezzanine,gbosh/mezzanine,saintbird/mezzanine,damnfine/mezzanine,molokov/mezzanine,scarcry/snm-mezzanine,SoLoHiC/mezzanine,christianwgd/mezzanine,sjuxax/mezzanine,stephenmcd/mezzanine,ZeroXn/mezzanine,vladir/mezzanine,batpad/mezzanine,nikolas/mezzanine,Kniyl/mezzanine,wrwrwr/mezzanine,biomassives/mezzanine,promil23/mezzanine,dekomote/mezzanine-modeltranslation-backport,Skytorn86/mezzanine,jerivas/mezzanine,cccs-web/mezzanine,AlexHill/mezzanine,Cajoline/mezzanine,mush42/mezzanine,fusionbox/mezzanine,agepoly/mezzanine,orlenko/sfpirg,dsanders11/mezzanine,wbtuomela/mezzanine,guibernardino/mezzanine,wbtuomela/mezzanine,viaregio/mezzanine,orlenko/plei,emile2016/mezzanine,dustinrb/mezzanine,webounty/mezzanine,douglaskastle/mezzanine,orlenko/plei,promil23/mezzanine,gradel/mezzanine,frankier/mezzanine,emile2016/mezzanine,Skytorn86/mezzanine,mush42/mezzanine,cccs-web/mezzanine,SoLoHiC/mezzanine,damnfine/mezzanine,douglaskastle/mezzanine,nikolas/mezzanine,PegasusWang/mezzanine,industrydive/mezzanine,spookylukey/mezzanine,Cicero-Zhao/mezzanine,PegasusWang/mezzanine,adrian-the-git/mezzanine,viaregio/mezzanine,fusionbox/mezzanine,eino-makitalo/mezzanine,jerivas/mezzanine,ryneeverett/mezzanine,dovydas/mezzanine,gbosh/mezzanine,emile2016/mezzanine,frankchin/mezzanine,dovydas/mezzanine,saintbird/mezzanine,ZeroXn/mezzanine,webounty/mezzanine,ryneeverett/mezzanine,jerivas/mezzanine,agepoly/mezzanine,stephenmcd/mezzanine,readevalprint/mezzanine,wrwrwr/mezzanine,gradel/mezzanine,theclanks/mezzanine,joshcartme/mezzanine,dustinrb/mezzanine,frankchin/mezzanine,Kniyl/mezzanine,tuxinhang1989/mezzanine,christianwgd/mezzanine,molokov/mezzanine,ryneeverett/mezzanine,stbarnabas/mezzanine,tuxinhang1989/mezzanine,sjdines/mezzanine,ZeroXn/mezzanine,viaregio/mezzanine,jjz/mezzanine,jjz/mezzanine,guibernardino/mezzanine,Cajoline/mezzanine,industrydive/mezzanine,sjuxax/mezzanine,tuxinhang1989/mezzanine,eino-makitalo/mezzanine,orlenko/plei,jjz/mezzanine,sjdines/mezzanine,gbosh/mezzanine,mush42/mezzanine,dustinrb/mezzanine,scarcry/snm-mezzanine,christianwgd/mezzanine,adrian-the-git/mezzanine,stephenmcd/mezzanine,promil23/mezzanine,spookylukey/mezzanine,wbtuomela/mezzanine,frankier/mezzanine,AlexHill/mezzanine
DATABASES = { "default": { # Ends with "postgresql_psycopg2", "mysql", "sqlite3" or "oracle". "ENGINE": "django.db.backends.postgresql_psycopg2", # DB name or path to database file if using sqlite3. "NAME": "%(proj_name)s", # Not used with sqlite3. "USER": "%(proj_name)s", # Not used with sqlite3. "PASSWORD": "%(db_pass)s", # Set to empty string for localhost. Not used with sqlite3. "HOST": "127.0.0.1", # Set to empty string for default. Not used with sqlite3. "PORT": "", } } SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTOCOL", "https") CACHE_MIDDLEWARE_SECONDS = 60 CACHES = { "default": { "BACKEND": "django.core.cache.backends.memcached.MemcachedCache", "LOCATION": "127.0.0.1:11211", } } + SESSION_ENGINE = "django.contrib.sessions.backends.cache" +
Use cache backend for sessions in deployed settings.
## Code Before: DATABASES = { "default": { # Ends with "postgresql_psycopg2", "mysql", "sqlite3" or "oracle". "ENGINE": "django.db.backends.postgresql_psycopg2", # DB name or path to database file if using sqlite3. "NAME": "%(proj_name)s", # Not used with sqlite3. "USER": "%(proj_name)s", # Not used with sqlite3. "PASSWORD": "%(db_pass)s", # Set to empty string for localhost. Not used with sqlite3. "HOST": "127.0.0.1", # Set to empty string for default. Not used with sqlite3. "PORT": "", } } SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTOCOL", "https") CACHE_MIDDLEWARE_SECONDS = 60 CACHES = { "default": { "BACKEND": "django.core.cache.backends.memcached.MemcachedCache", "LOCATION": "127.0.0.1:11211", } } ## Instruction: Use cache backend for sessions in deployed settings. ## Code After: DATABASES = { "default": { # Ends with "postgresql_psycopg2", "mysql", "sqlite3" or "oracle". "ENGINE": "django.db.backends.postgresql_psycopg2", # DB name or path to database file if using sqlite3. "NAME": "%(proj_name)s", # Not used with sqlite3. "USER": "%(proj_name)s", # Not used with sqlite3. "PASSWORD": "%(db_pass)s", # Set to empty string for localhost. Not used with sqlite3. "HOST": "127.0.0.1", # Set to empty string for default. Not used with sqlite3. "PORT": "", } } SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTOCOL", "https") CACHE_MIDDLEWARE_SECONDS = 60 CACHES = { "default": { "BACKEND": "django.core.cache.backends.memcached.MemcachedCache", "LOCATION": "127.0.0.1:11211", } } SESSION_ENGINE = "django.contrib.sessions.backends.cache"
# ... existing code ... } } SESSION_ENGINE = "django.contrib.sessions.backends.cache" # ... rest of the code ...
2768f7ac50a7b91d984f0f872b647e647d768e93
IPython/lib/tests/test_security.py
IPython/lib/tests/test_security.py
from IPython.lib import passwd from IPython.lib.security import passwd_check, salt_len import nose.tools as nt def test_passwd_structure(): p = passwd('passphrase') algorithm, salt, hashed = p.split(':') nt.assert_equal(algorithm, 'sha1') nt.assert_equal(len(salt), salt_len) nt.assert_equal(len(hashed), 40) def test_roundtrip(): p = passwd('passphrase') nt.assert_equal(passwd_check(p, 'passphrase'), True) def test_bad(): p = passwd('passphrase') nt.assert_equal(passwd_check(p, p), False) nt.assert_equal(passwd_check(p, 'a:b:c:d'), False) nt.assert_equal(passwd_check(p, 'a:b'), False)
from IPython.lib import passwd from IPython.lib.security import passwd_check, salt_len import nose.tools as nt def test_passwd_structure(): p = passwd('passphrase') algorithm, salt, hashed = p.split(':') nt.assert_equal(algorithm, 'sha1') nt.assert_equal(len(salt), salt_len) nt.assert_equal(len(hashed), 40) def test_roundtrip(): p = passwd('passphrase') nt.assert_equal(passwd_check(p, 'passphrase'), True) def test_bad(): p = passwd('passphrase') nt.assert_equal(passwd_check(p, p), False) nt.assert_equal(passwd_check(p, 'a:b:c:d'), False) nt.assert_equal(passwd_check(p, 'a:b'), False) def test_passwd_check_unicode(): # GH issue #4524 phash = u'sha1:9dc18846ca26:6bb62badc41fde529c258a8a7fbe259a91313df8' assert passwd_check(phash, u'mypassword³')
Add failing (on Py 2) test for passwd_check with unicode arguments
Add failing (on Py 2) test for passwd_check with unicode arguments
Python
bsd-3-clause
ipython/ipython,ipython/ipython
from IPython.lib import passwd from IPython.lib.security import passwd_check, salt_len import nose.tools as nt def test_passwd_structure(): p = passwd('passphrase') algorithm, salt, hashed = p.split(':') nt.assert_equal(algorithm, 'sha1') nt.assert_equal(len(salt), salt_len) nt.assert_equal(len(hashed), 40) def test_roundtrip(): p = passwd('passphrase') nt.assert_equal(passwd_check(p, 'passphrase'), True) def test_bad(): p = passwd('passphrase') nt.assert_equal(passwd_check(p, p), False) nt.assert_equal(passwd_check(p, 'a:b:c:d'), False) nt.assert_equal(passwd_check(p, 'a:b'), False) - + def test_passwd_check_unicode(): + # GH issue #4524 + phash = u'sha1:9dc18846ca26:6bb62badc41fde529c258a8a7fbe259a91313df8' + assert passwd_check(phash, u'mypassword³')
Add failing (on Py 2) test for passwd_check with unicode arguments
## Code Before: from IPython.lib import passwd from IPython.lib.security import passwd_check, salt_len import nose.tools as nt def test_passwd_structure(): p = passwd('passphrase') algorithm, salt, hashed = p.split(':') nt.assert_equal(algorithm, 'sha1') nt.assert_equal(len(salt), salt_len) nt.assert_equal(len(hashed), 40) def test_roundtrip(): p = passwd('passphrase') nt.assert_equal(passwd_check(p, 'passphrase'), True) def test_bad(): p = passwd('passphrase') nt.assert_equal(passwd_check(p, p), False) nt.assert_equal(passwd_check(p, 'a:b:c:d'), False) nt.assert_equal(passwd_check(p, 'a:b'), False) ## Instruction: Add failing (on Py 2) test for passwd_check with unicode arguments ## Code After: from IPython.lib import passwd from IPython.lib.security import passwd_check, salt_len import nose.tools as nt def test_passwd_structure(): p = passwd('passphrase') algorithm, salt, hashed = p.split(':') nt.assert_equal(algorithm, 'sha1') nt.assert_equal(len(salt), salt_len) nt.assert_equal(len(hashed), 40) def test_roundtrip(): p = passwd('passphrase') nt.assert_equal(passwd_check(p, 'passphrase'), True) def test_bad(): p = passwd('passphrase') nt.assert_equal(passwd_check(p, p), False) nt.assert_equal(passwd_check(p, 'a:b:c:d'), False) nt.assert_equal(passwd_check(p, 'a:b'), False) def test_passwd_check_unicode(): # GH issue #4524 phash = u'sha1:9dc18846ca26:6bb62badc41fde529c258a8a7fbe259a91313df8' assert passwd_check(phash, u'mypassword³')
... nt.assert_equal(passwd_check(p, 'a:b'), False) def test_passwd_check_unicode(): # GH issue #4524 phash = u'sha1:9dc18846ca26:6bb62badc41fde529c258a8a7fbe259a91313df8' assert passwd_check(phash, u'mypassword³') ...
a72cf5997439533d7ce74d6c4fc50d1189466c1b
peloid/app/shell/service.py
peloid/app/shell/service.py
from twisted.cred import portal from twisted.conch.checkers import SSHPublicKeyDatabase from carapace.util import ssh as util from peloid.app import mud from peloid.app.shell import gameshell, setupshell def getGameShellFactory(**namespace): """ The "namespace" kwargs here contains the passed objects that will be accessible via the shell, namely: * "app" * "services" These two are passed in the call to peloid.app.service.makeService. """ game = mud.Game() sshRealm = gameshell.TerminalRealm(namespace, game) sshPortal = portal.Portal(sshRealm) factory = gameshell.GameShellFactory(sshPortal) factory.privateKeys = {'ssh-rsa': util.getPrivKey()} factory.publicKeys = {'ssh-rsa': util.getPubKey()} factory.portal.registerChecker(SSHPublicKeyDatabase()) return factory def getSetupShellFactory(**namespace): return setupshell.SetupShellServerFactory(namespace)
from twisted.cred import portal from twisted.conch.checkers import SSHPublicKeyDatabase from carapace.util import ssh as util from peloid import const from peloid.app import mud from peloid.app.shell import gameshell, setupshell def getGameShellFactory(**namespace): """ The "namespace" kwargs here contains the passed objects that will be accessible via the shell, namely: * "app" * "services" These two are passed in the call to peloid.app.service.makeService. """ game = mud.Game() game.setMode(const.modes.lobby) sshRealm = gameshell.TerminalRealm(namespace, game) sshPortal = portal.Portal(sshRealm) factory = gameshell.GameShellFactory(sshPortal) factory.privateKeys = {'ssh-rsa': util.getPrivKey()} factory.publicKeys = {'ssh-rsa': util.getPubKey()} factory.portal.registerChecker(SSHPublicKeyDatabase()) return factory def getSetupShellFactory(**namespace): return setupshell.SetupShellServerFactory(namespace)
Set initial mode to lobby.
Set initial mode to lobby.
Python
mit
oubiwann/peloid
from twisted.cred import portal from twisted.conch.checkers import SSHPublicKeyDatabase from carapace.util import ssh as util + from peloid import const from peloid.app import mud from peloid.app.shell import gameshell, setupshell def getGameShellFactory(**namespace): """ The "namespace" kwargs here contains the passed objects that will be accessible via the shell, namely: * "app" * "services" These two are passed in the call to peloid.app.service.makeService. """ game = mud.Game() + game.setMode(const.modes.lobby) sshRealm = gameshell.TerminalRealm(namespace, game) sshPortal = portal.Portal(sshRealm) factory = gameshell.GameShellFactory(sshPortal) factory.privateKeys = {'ssh-rsa': util.getPrivKey()} factory.publicKeys = {'ssh-rsa': util.getPubKey()} factory.portal.registerChecker(SSHPublicKeyDatabase()) return factory def getSetupShellFactory(**namespace): return setupshell.SetupShellServerFactory(namespace) -
Set initial mode to lobby.
## Code Before: from twisted.cred import portal from twisted.conch.checkers import SSHPublicKeyDatabase from carapace.util import ssh as util from peloid.app import mud from peloid.app.shell import gameshell, setupshell def getGameShellFactory(**namespace): """ The "namespace" kwargs here contains the passed objects that will be accessible via the shell, namely: * "app" * "services" These two are passed in the call to peloid.app.service.makeService. """ game = mud.Game() sshRealm = gameshell.TerminalRealm(namespace, game) sshPortal = portal.Portal(sshRealm) factory = gameshell.GameShellFactory(sshPortal) factory.privateKeys = {'ssh-rsa': util.getPrivKey()} factory.publicKeys = {'ssh-rsa': util.getPubKey()} factory.portal.registerChecker(SSHPublicKeyDatabase()) return factory def getSetupShellFactory(**namespace): return setupshell.SetupShellServerFactory(namespace) ## Instruction: Set initial mode to lobby. ## Code After: from twisted.cred import portal from twisted.conch.checkers import SSHPublicKeyDatabase from carapace.util import ssh as util from peloid import const from peloid.app import mud from peloid.app.shell import gameshell, setupshell def getGameShellFactory(**namespace): """ The "namespace" kwargs here contains the passed objects that will be accessible via the shell, namely: * "app" * "services" These two are passed in the call to peloid.app.service.makeService. """ game = mud.Game() game.setMode(const.modes.lobby) sshRealm = gameshell.TerminalRealm(namespace, game) sshPortal = portal.Portal(sshRealm) factory = gameshell.GameShellFactory(sshPortal) factory.privateKeys = {'ssh-rsa': util.getPrivKey()} factory.publicKeys = {'ssh-rsa': util.getPubKey()} factory.portal.registerChecker(SSHPublicKeyDatabase()) return factory def getSetupShellFactory(**namespace): return setupshell.SetupShellServerFactory(namespace)
# ... existing code ... from carapace.util import ssh as util from peloid import const from peloid.app import mud from peloid.app.shell import gameshell, setupshell # ... modified code ... """ game = mud.Game() game.setMode(const.modes.lobby) sshRealm = gameshell.TerminalRealm(namespace, game) sshPortal = portal.Portal(sshRealm) # ... rest of the code ...
aae36c00e6dbea1ed68d2a921021d586d5ff723e
openquake/baselib/safeprint.py
openquake/baselib/safeprint.py
from __future__ import print_function import sys try: import __builtin__ except ImportError: # Python 3 import builtins as __builtin__ def print(*args, **kwargs): conv_str = () for s in args: conv_str = s.encode('utf-8').decode(sys.stdout.encoding, 'ignore') return __builtin__.print(conv_str, **kwargs)
from __future__ import print_function from sys import stdout try: import __builtin__ except ImportError: # Python 3 import builtins as __builtin__ def print(*args, **kwargs): ret_str = () # when stdout is redirected to a file, python 2 uses ascii for the writer; # python 3 uses what is configured in the system (i.e. 'utf-8') str_encoding = stdout.encoding if stdout.encoding is not None else 'ascii' for s in args: ret_str = s.encode('utf-8').decode(str_encoding, 'ignore') return __builtin__.print(ret_str, **kwargs)
Fix out redirection in python2
Fix out redirection in python2
Python
agpl-3.0
gem/oq-engine,gem/oq-engine,gem/oq-hazardlib,gem/oq-hazardlib,gem/oq-hazardlib,gem/oq-engine,gem/oq-engine,gem/oq-engine
from __future__ import print_function - import sys + from sys import stdout try: import __builtin__ except ImportError: # Python 3 import builtins as __builtin__ def print(*args, **kwargs): - conv_str = () + ret_str = () + # when stdout is redirected to a file, python 2 uses ascii for the writer; + # python 3 uses what is configured in the system (i.e. 'utf-8') + str_encoding = stdout.encoding if stdout.encoding is not None else 'ascii' for s in args: - conv_str = s.encode('utf-8').decode(sys.stdout.encoding, 'ignore') + ret_str = s.encode('utf-8').decode(str_encoding, 'ignore') - return __builtin__.print(conv_str, **kwargs) + return __builtin__.print(ret_str, **kwargs) +
Fix out redirection in python2
## Code Before: from __future__ import print_function import sys try: import __builtin__ except ImportError: # Python 3 import builtins as __builtin__ def print(*args, **kwargs): conv_str = () for s in args: conv_str = s.encode('utf-8').decode(sys.stdout.encoding, 'ignore') return __builtin__.print(conv_str, **kwargs) ## Instruction: Fix out redirection in python2 ## Code After: from __future__ import print_function from sys import stdout try: import __builtin__ except ImportError: # Python 3 import builtins as __builtin__ def print(*args, **kwargs): ret_str = () # when stdout is redirected to a file, python 2 uses ascii for the writer; # python 3 uses what is configured in the system (i.e. 'utf-8') str_encoding = stdout.encoding if stdout.encoding is not None else 'ascii' for s in args: ret_str = s.encode('utf-8').decode(str_encoding, 'ignore') return __builtin__.print(ret_str, **kwargs)
// ... existing code ... from __future__ import print_function from sys import stdout try: // ... modified code ... def print(*args, **kwargs): ret_str = () # when stdout is redirected to a file, python 2 uses ascii for the writer; # python 3 uses what is configured in the system (i.e. 'utf-8') str_encoding = stdout.encoding if stdout.encoding is not None else 'ascii' for s in args: ret_str = s.encode('utf-8').decode(str_encoding, 'ignore') return __builtin__.print(ret_str, **kwargs) // ... rest of the code ...
f35c6f989129d6298eb2f419ccb6fe8d4c734fd6
taskq/run.py
taskq/run.py
import time import transaction from taskq import models from daemon import runner class TaskRunner(): def __init__(self): self.stdin_path = '/dev/null' self.stdout_path = '/dev/tty' self.stderr_path = '/dev/tty' self.pidfile_path = '/tmp/task-runner.pid' self.pidfile_timeout = 5 def run(self): while True: task = models.Task.query.filter_by( status=models.TASK_STATUS_WAITING).first() if not task: time.sleep(2) continue with transaction.manager: task.status = models.TASK_STATUS_IN_PROGRESS task.perform() task.status = models.TASK_STATUS_FINISHED models.DBSession.add(task) time.sleep(2) def main(): app = TaskRunner() daemon_runner = runner.DaemonRunner(app) daemon_runner.do_action() if __name__ == '__main__': main()
import time import transaction from daemon import runner from taskq import models class TaskDaemonRunner(runner.DaemonRunner): def _status(self): pid = self.pidfile.read_pid() message = [] if pid: message += ['Daemon started with pid %s' % pid] else: message += ['Daemon not running'] tasks = models.Task.query.filter_by( status=models.TASK_STATUS_WAITING).all() message += ['Number of waiting tasks: %s' % len(tasks)] runner.emit_message('\n'.join(message)) action_funcs = { u'start': runner.DaemonRunner._start, u'stop': runner.DaemonRunner._stop, u'restart': runner.DaemonRunner._restart, u'status': _status, } class TaskRunner(): def __init__(self): self.stdin_path = '/dev/null' self.stdout_path = '/dev/tty' self.stderr_path = '/dev/tty' self.pidfile_path = '/tmp/task-runner.pid' self.pidfile_timeout = 5 def run(self): while True: task = models.Task.query.filter_by( status=models.TASK_STATUS_WAITING).first() if not task: time.sleep(2) continue with transaction.manager: task.status = models.TASK_STATUS_IN_PROGRESS task.perform() task.status = models.TASK_STATUS_FINISHED models.DBSession.add(task) time.sleep(2) def main(): app = TaskRunner() daemon_runner = TaskDaemonRunner(app) daemon_runner.do_action() if __name__ == '__main__': main()
Add status to the daemon
Add status to the daemon
Python
mit
LeResKP/sqla-taskq
import time import transaction + from daemon import runner from taskq import models - from daemon import runner + + + class TaskDaemonRunner(runner.DaemonRunner): + + def _status(self): + pid = self.pidfile.read_pid() + message = [] + if pid: + message += ['Daemon started with pid %s' % pid] + else: + message += ['Daemon not running'] + + tasks = models.Task.query.filter_by( + status=models.TASK_STATUS_WAITING).all() + message += ['Number of waiting tasks: %s' % len(tasks)] + runner.emit_message('\n'.join(message)) + + action_funcs = { + u'start': runner.DaemonRunner._start, + u'stop': runner.DaemonRunner._stop, + u'restart': runner.DaemonRunner._restart, + u'status': _status, + } class TaskRunner(): def __init__(self): self.stdin_path = '/dev/null' self.stdout_path = '/dev/tty' self.stderr_path = '/dev/tty' self.pidfile_path = '/tmp/task-runner.pid' self.pidfile_timeout = 5 def run(self): while True: task = models.Task.query.filter_by( status=models.TASK_STATUS_WAITING).first() if not task: time.sleep(2) continue with transaction.manager: task.status = models.TASK_STATUS_IN_PROGRESS task.perform() task.status = models.TASK_STATUS_FINISHED models.DBSession.add(task) time.sleep(2) def main(): app = TaskRunner() - daemon_runner = runner.DaemonRunner(app) + daemon_runner = TaskDaemonRunner(app) daemon_runner.do_action() if __name__ == '__main__': main()
Add status to the daemon
## Code Before: import time import transaction from taskq import models from daemon import runner class TaskRunner(): def __init__(self): self.stdin_path = '/dev/null' self.stdout_path = '/dev/tty' self.stderr_path = '/dev/tty' self.pidfile_path = '/tmp/task-runner.pid' self.pidfile_timeout = 5 def run(self): while True: task = models.Task.query.filter_by( status=models.TASK_STATUS_WAITING).first() if not task: time.sleep(2) continue with transaction.manager: task.status = models.TASK_STATUS_IN_PROGRESS task.perform() task.status = models.TASK_STATUS_FINISHED models.DBSession.add(task) time.sleep(2) def main(): app = TaskRunner() daemon_runner = runner.DaemonRunner(app) daemon_runner.do_action() if __name__ == '__main__': main() ## Instruction: Add status to the daemon ## Code After: import time import transaction from daemon import runner from taskq import models class TaskDaemonRunner(runner.DaemonRunner): def _status(self): pid = self.pidfile.read_pid() message = [] if pid: message += ['Daemon started with pid %s' % pid] else: message += ['Daemon not running'] tasks = models.Task.query.filter_by( status=models.TASK_STATUS_WAITING).all() message += ['Number of waiting tasks: %s' % len(tasks)] runner.emit_message('\n'.join(message)) action_funcs = { u'start': runner.DaemonRunner._start, u'stop': runner.DaemonRunner._stop, u'restart': runner.DaemonRunner._restart, u'status': _status, } class TaskRunner(): def __init__(self): self.stdin_path = '/dev/null' self.stdout_path = '/dev/tty' self.stderr_path = '/dev/tty' self.pidfile_path = '/tmp/task-runner.pid' self.pidfile_timeout = 5 def run(self): while True: task = models.Task.query.filter_by( status=models.TASK_STATUS_WAITING).first() if not task: time.sleep(2) continue with transaction.manager: task.status = models.TASK_STATUS_IN_PROGRESS task.perform() task.status = models.TASK_STATUS_FINISHED models.DBSession.add(task) time.sleep(2) def main(): app = TaskRunner() daemon_runner = TaskDaemonRunner(app) daemon_runner.do_action() if __name__ == '__main__': main()
// ... existing code ... import time import transaction from daemon import runner from taskq import models class TaskDaemonRunner(runner.DaemonRunner): def _status(self): pid = self.pidfile.read_pid() message = [] if pid: message += ['Daemon started with pid %s' % pid] else: message += ['Daemon not running'] tasks = models.Task.query.filter_by( status=models.TASK_STATUS_WAITING).all() message += ['Number of waiting tasks: %s' % len(tasks)] runner.emit_message('\n'.join(message)) action_funcs = { u'start': runner.DaemonRunner._start, u'stop': runner.DaemonRunner._stop, u'restart': runner.DaemonRunner._restart, u'status': _status, } // ... modified code ... def main(): app = TaskRunner() daemon_runner = TaskDaemonRunner(app) daemon_runner.do_action() // ... rest of the code ...
90405c60b5d2ce583597382bc72e116cb9a450bd
project/library/models.py
project/library/models.py
from django.db import models class Author(models.Model): '''Object for book author''' first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) def __unicode__(self): return self.last_name + ", " + self.first_name class Book(models.Model): '''Object for library books''' title = models.CharField(max_length=128) isbn = models.CharField(max_length=13) isbn13 = models.CharField(max_length=13) description = models.TextField() authors = models.ManyToManyField(Author) year_published = models.SmallIntegerField(null=True) status = models.TextField(default="In") def __unicode__(self): return self.title class Reservation(models.Model): '''Object for book reservations''' book_id = models.ForeignKey('Book') member_name = models.CharField(max_length=128) email = models.EmailField() date_created = models.DateTimeField() def __unicode__(self): return self.member_name + ":" + self.book_id
from datetime import datetime from django.db import models class Author(models.Model): '''Object for book author''' first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) def __unicode__(self): return self.last_name + ", " + self.first_name class Book(models.Model): '''Object for library books''' title = models.CharField(max_length=128) isbn = models.CharField(max_length=13) isbn13 = models.CharField(max_length=13) description = models.TextField() authors = models.ManyToManyField(Author) year_published = models.SmallIntegerField(null=True) status = models.TextField(default="In") def __unicode__(self): return self.title class Reservation(models.Model): '''Object for book reservations''' book_id = models.ForeignKey('Book') member_name = models.CharField(max_length=128) email = models.EmailField() date_created = models.DateTimeField(default=datetime.now()) def __unicode__(self): return self.member_name + ":" + self.book_id
Update reservation object to use current time
Update reservation object to use current time
Python
mit
DUCSS/ducss-site-old,DUCSS/ducss-site-old,DUCSS/ducss-site-old
+ from datetime import datetime from django.db import models class Author(models.Model): '''Object for book author''' first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) def __unicode__(self): return self.last_name + ", " + self.first_name class Book(models.Model): '''Object for library books''' title = models.CharField(max_length=128) isbn = models.CharField(max_length=13) isbn13 = models.CharField(max_length=13) description = models.TextField() authors = models.ManyToManyField(Author) year_published = models.SmallIntegerField(null=True) status = models.TextField(default="In") def __unicode__(self): return self.title class Reservation(models.Model): '''Object for book reservations''' book_id = models.ForeignKey('Book') member_name = models.CharField(max_length=128) email = models.EmailField() - date_created = models.DateTimeField() + date_created = models.DateTimeField(default=datetime.now()) def __unicode__(self): return self.member_name + ":" + self.book_id
Update reservation object to use current time
## Code Before: from django.db import models class Author(models.Model): '''Object for book author''' first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) def __unicode__(self): return self.last_name + ", " + self.first_name class Book(models.Model): '''Object for library books''' title = models.CharField(max_length=128) isbn = models.CharField(max_length=13) isbn13 = models.CharField(max_length=13) description = models.TextField() authors = models.ManyToManyField(Author) year_published = models.SmallIntegerField(null=True) status = models.TextField(default="In") def __unicode__(self): return self.title class Reservation(models.Model): '''Object for book reservations''' book_id = models.ForeignKey('Book') member_name = models.CharField(max_length=128) email = models.EmailField() date_created = models.DateTimeField() def __unicode__(self): return self.member_name + ":" + self.book_id ## Instruction: Update reservation object to use current time ## Code After: from datetime import datetime from django.db import models class Author(models.Model): '''Object for book author''' first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) def __unicode__(self): return self.last_name + ", " + self.first_name class Book(models.Model): '''Object for library books''' title = models.CharField(max_length=128) isbn = models.CharField(max_length=13) isbn13 = models.CharField(max_length=13) description = models.TextField() authors = models.ManyToManyField(Author) year_published = models.SmallIntegerField(null=True) status = models.TextField(default="In") def __unicode__(self): return self.title class Reservation(models.Model): '''Object for book reservations''' book_id = models.ForeignKey('Book') member_name = models.CharField(max_length=128) email = models.EmailField() date_created = models.DateTimeField(default=datetime.now()) def __unicode__(self): return self.member_name + ":" + self.book_id
... from datetime import datetime from django.db import models ... member_name = models.CharField(max_length=128) email = models.EmailField() date_created = models.DateTimeField(default=datetime.now()) def __unicode__(self): ...
06ec5baaa799836c656f67b083b77197943d97f2
drogher/__init__.py
drogher/__init__.py
from . import shippers def barcode(b): for klass in ['DHL', 'FedExExpress', 'FedExGround96', 'UPS', 'USPSIMpb', 'USPS13']: shipper = getattr(shippers, klass)(b) if shipper.is_valid: return shipper return shippers.Unknown(b)
from . import shippers def barcode(b, barcode_classes=None): if barcode_classes is None: barcode_classes = ['DHL', 'FedExExpress', 'FedExGround96', 'UPS', 'USPSIMpb', 'USPS13'] for klass in barcode_classes: shipper = getattr(shippers, klass)(b) if shipper.is_valid: return shipper return shippers.Unknown(b)
Allow barcode classes to be optionally specified
Allow barcode classes to be optionally specified
Python
bsd-3-clause
jbittel/drogher
from . import shippers - def barcode(b): + def barcode(b, barcode_classes=None): + if barcode_classes is None: - for klass in ['DHL', 'FedExExpress', 'FedExGround96', 'UPS', 'USPSIMpb', 'USPS13']: + barcode_classes = ['DHL', 'FedExExpress', 'FedExGround96', 'UPS', 'USPSIMpb', 'USPS13'] + for klass in barcode_classes: shipper = getattr(shippers, klass)(b) if shipper.is_valid: return shipper return shippers.Unknown(b)
Allow barcode classes to be optionally specified
## Code Before: from . import shippers def barcode(b): for klass in ['DHL', 'FedExExpress', 'FedExGround96', 'UPS', 'USPSIMpb', 'USPS13']: shipper = getattr(shippers, klass)(b) if shipper.is_valid: return shipper return shippers.Unknown(b) ## Instruction: Allow barcode classes to be optionally specified ## Code After: from . import shippers def barcode(b, barcode_classes=None): if barcode_classes is None: barcode_classes = ['DHL', 'FedExExpress', 'FedExGround96', 'UPS', 'USPSIMpb', 'USPS13'] for klass in barcode_classes: shipper = getattr(shippers, klass)(b) if shipper.is_valid: return shipper return shippers.Unknown(b)
... def barcode(b, barcode_classes=None): if barcode_classes is None: barcode_classes = ['DHL', 'FedExExpress', 'FedExGround96', 'UPS', 'USPSIMpb', 'USPS13'] for klass in barcode_classes: shipper = getattr(shippers, klass)(b) if shipper.is_valid: ...
dc934f178c5101e0aad592b55101c36608a2eab9
girder/molecules/molecules/utilities/pagination.py
girder/molecules/molecules/utilities/pagination.py
def default_pagination_params(limit=None, offset=None, sort=None): """Returns default params unless they are set""" if limit is None: limit = 25 if offset is None: offset = 0 if sort is None: sort = [('_id', -1)] return limit, offset, sort def parse_pagination_params(params): """Parse params and get (limit, offset, sort) The defaults will be returned if not found in params. """ # Defaults limit, offset, sort = default_pagination_params() if params: if 'limit' in params: limit = int(params['limit']) if 'offset' in params: offset = int(params['offset']) if 'sort' in params and 'sortdir' in params: sort = [(params['sort'], int(params['sortdir']))] return limit, offset, sort def search_results_dict(results, limit, offset, sort): """This is for consistent search results""" ret = { 'matches': len(results), 'limit': limit, 'offset': offset, 'results': results } return ret
from girder.constants import SortDir def default_pagination_params(limit=None, offset=None, sort=None): """Returns default params unless they are set""" if limit is None: limit = 25 if offset is None: offset = 0 if sort is None: sort = [('_id', SortDir.DESCENDING)] return limit, offset, sort def parse_pagination_params(params): """Parse params and get (limit, offset, sort) The defaults will be returned if not found in params. """ # Defaults limit, offset, sort = default_pagination_params() if params: if 'limit' in params: limit = int(params['limit']) if 'offset' in params: offset = int(params['offset']) if 'sort' in params and 'sortdir' in params: sort = [(params['sort'], int(params['sortdir']))] return limit, offset, sort def search_results_dict(results, limit, offset, sort): """This is for consistent search results""" ret = { 'matches': len(results), 'limit': limit, 'offset': offset, 'results': results } return ret
Use SortDir.DESCENDING for default sort direction
Use SortDir.DESCENDING for default sort direction Signed-off-by: Patrick Avery <[email protected]>
Python
bsd-3-clause
OpenChemistry/mongochemserver
+ from girder.constants import SortDir def default_pagination_params(limit=None, offset=None, sort=None): """Returns default params unless they are set""" if limit is None: limit = 25 if offset is None: offset = 0 if sort is None: - sort = [('_id', -1)] + sort = [('_id', SortDir.DESCENDING)] return limit, offset, sort def parse_pagination_params(params): """Parse params and get (limit, offset, sort) The defaults will be returned if not found in params. """ # Defaults limit, offset, sort = default_pagination_params() if params: if 'limit' in params: limit = int(params['limit']) if 'offset' in params: offset = int(params['offset']) if 'sort' in params and 'sortdir' in params: sort = [(params['sort'], int(params['sortdir']))] return limit, offset, sort def search_results_dict(results, limit, offset, sort): """This is for consistent search results""" ret = { 'matches': len(results), 'limit': limit, 'offset': offset, 'results': results } return ret
Use SortDir.DESCENDING for default sort direction
## Code Before: def default_pagination_params(limit=None, offset=None, sort=None): """Returns default params unless they are set""" if limit is None: limit = 25 if offset is None: offset = 0 if sort is None: sort = [('_id', -1)] return limit, offset, sort def parse_pagination_params(params): """Parse params and get (limit, offset, sort) The defaults will be returned if not found in params. """ # Defaults limit, offset, sort = default_pagination_params() if params: if 'limit' in params: limit = int(params['limit']) if 'offset' in params: offset = int(params['offset']) if 'sort' in params and 'sortdir' in params: sort = [(params['sort'], int(params['sortdir']))] return limit, offset, sort def search_results_dict(results, limit, offset, sort): """This is for consistent search results""" ret = { 'matches': len(results), 'limit': limit, 'offset': offset, 'results': results } return ret ## Instruction: Use SortDir.DESCENDING for default sort direction ## Code After: from girder.constants import SortDir def default_pagination_params(limit=None, offset=None, sort=None): """Returns default params unless they are set""" if limit is None: limit = 25 if offset is None: offset = 0 if sort is None: sort = [('_id', SortDir.DESCENDING)] return limit, offset, sort def parse_pagination_params(params): """Parse params and get (limit, offset, sort) The defaults will be returned if not found in params. """ # Defaults limit, offset, sort = default_pagination_params() if params: if 'limit' in params: limit = int(params['limit']) if 'offset' in params: offset = int(params['offset']) if 'sort' in params and 'sortdir' in params: sort = [(params['sort'], int(params['sortdir']))] return limit, offset, sort def search_results_dict(results, limit, offset, sort): """This is for consistent search results""" ret = { 'matches': len(results), 'limit': limit, 'offset': offset, 'results': results } return ret
// ... existing code ... from girder.constants import SortDir def default_pagination_params(limit=None, offset=None, sort=None): // ... modified code ... offset = 0 if sort is None: sort = [('_id', SortDir.DESCENDING)] return limit, offset, sort // ... rest of the code ...
ddbf22b6e4d19c2b0c47543d6f4d7fe8fc704483
errors.py
errors.py
"""Errors specific to TwistedSNMP""" noError = 0 tooBig = 1 # Response message would have been too large noSuchName = 2 #There is no such variable name in this MIB badValue = 3 # The value given has the wrong type or length class OIDNameError( NameError ): """An OID was specified which is not defined in namespace""" def __init__( self, oid, errorIndex=-1 , errorCode=noSuchName, message=""): """Initialise the OIDNameError""" self.oid, self.errorIndex, self.errorCode, self.message = oid, errorIndex, errorCode, message def __repr__( self ): """Represent the OIDNameError as a string""" return """%s( %r, %s, %s, %r )"""%( self.__class__.__name__, self.oid, self.errorIndex, self.errorCode, self.message, )
"""Errors specific to TwistedSNMP""" noError = 0 tooBig = 1 # Response message would have been too large noSuchName = 2 #There is no such variable name in this MIB badValue = 3 # The value given has the wrong type or length class OIDNameError( NameError ): """An OID was specified which is not defined in namespace""" def __init__( self, oid, errorIndex=-1 , errorCode=noSuchName, message=""): """Initialise the OIDNameError""" self.oid, self.errorIndex, self.errorCode, self.message = oid, errorIndex, errorCode, message def __repr__( self ): """Represent the OIDNameError as a string""" return """%s( %r, %s, %s, %r )"""%( self.__class__.__name__, self.oid, self.errorIndex, self.errorCode, self.message, ) __str__ = __repr__
Make __str__ = to repr
Make __str__ = to repr
Python
bsd-3-clause
mmattice/TwistedSNMP
"""Errors specific to TwistedSNMP""" noError = 0 tooBig = 1 # Response message would have been too large noSuchName = 2 #There is no such variable name in this MIB badValue = 3 # The value given has the wrong type or length class OIDNameError( NameError ): """An OID was specified which is not defined in namespace""" def __init__( self, oid, errorIndex=-1 , errorCode=noSuchName, message=""): """Initialise the OIDNameError""" self.oid, self.errorIndex, self.errorCode, self.message = oid, errorIndex, errorCode, message def __repr__( self ): """Represent the OIDNameError as a string""" return """%s( %r, %s, %s, %r )"""%( self.__class__.__name__, self.oid, self.errorIndex, self.errorCode, self.message, ) + __str__ = __repr__
Make __str__ = to repr
## Code Before: """Errors specific to TwistedSNMP""" noError = 0 tooBig = 1 # Response message would have been too large noSuchName = 2 #There is no such variable name in this MIB badValue = 3 # The value given has the wrong type or length class OIDNameError( NameError ): """An OID was specified which is not defined in namespace""" def __init__( self, oid, errorIndex=-1 , errorCode=noSuchName, message=""): """Initialise the OIDNameError""" self.oid, self.errorIndex, self.errorCode, self.message = oid, errorIndex, errorCode, message def __repr__( self ): """Represent the OIDNameError as a string""" return """%s( %r, %s, %s, %r )"""%( self.__class__.__name__, self.oid, self.errorIndex, self.errorCode, self.message, ) ## Instruction: Make __str__ = to repr ## Code After: """Errors specific to TwistedSNMP""" noError = 0 tooBig = 1 # Response message would have been too large noSuchName = 2 #There is no such variable name in this MIB badValue = 3 # The value given has the wrong type or length class OIDNameError( NameError ): """An OID was specified which is not defined in namespace""" def __init__( self, oid, errorIndex=-1 , errorCode=noSuchName, message=""): """Initialise the OIDNameError""" self.oid, self.errorIndex, self.errorCode, self.message = oid, errorIndex, errorCode, message def __repr__( self ): """Represent the OIDNameError as a string""" return """%s( %r, %s, %s, %r )"""%( self.__class__.__name__, self.oid, self.errorIndex, self.errorCode, self.message, ) __str__ = __repr__
# ... existing code ... self.message, ) __str__ = __repr__ # ... rest of the code ...
3f51ab2ada60e78c9821cef557cb06194a24226a
tests/optvis/test_integration.py
tests/optvis/test_integration.py
from __future__ import absolute_import, division, print_function import pytest import tensorflow as tf from lucid.modelzoo.vision_models import InceptionV1 from lucid.optvis import objectives, param, render, transform model = InceptionV1() model.load_graphdef() @pytest.mark.parametrize("decorrelate", [True, False]) @pytest.mark.parametrize("fft", [True, False]) def test_integration(decorrelate, fft): obj = objectives.neuron("mixed3a_pre_relu", 0) param_f = lambda: param.image(16, decorrelate=decorrelate, fft=fft) rendering = render.render_vis(model, obj, param_f=param_f, thresholds=(1,2), verbose=False, transforms=[]) start_image = rendering[0] end_image = rendering[-1] objective_f = objectives.neuron("mixed3a", 177) param_f = lambda: param.image(64, decorrelate=decorrelate, fft=fft) rendering = render.render_vis(model, objective_f, param_f, verbose=False, thresholds=(0,64), use_fixed_seed=True) start_image, end_image = rendering assert (start_image != end_image).any()
from __future__ import absolute_import, division, print_function import pytest import tensorflow as tf from lucid.modelzoo.vision_models import InceptionV1 from lucid.optvis import objectives, param, render, transform @pytest.fixture def inceptionv1(): model = InceptionV1() model.load_graphdef() return model @pytest.mark.parametrize("decorrelate", [True, False]) @pytest.mark.parametrize("fft", [True, False]) def test_integration(decorrelate, fft, inceptionv1): obj = objectives.neuron("mixed3a_pre_relu", 0) param_f = lambda: param.image(16, decorrelate=decorrelate, fft=fft) rendering = render.render_vis(inceptionv1, obj, param_f=param_f, thresholds=(1,2), verbose=False, transforms=[]) start_image = rendering[0] end_image = rendering[-1] objective_f = objectives.neuron("mixed3a", 177) param_f = lambda: param.image(64, decorrelate=decorrelate, fft=fft) rendering = render.render_vis(inceptionv1, objective_f, param_f, verbose=False, thresholds=(0,64), use_fixed_seed=True) start_image, end_image = rendering assert (start_image != end_image).any()
Move model init into pytest fixture to avoid loading model and downloading graph just by importing the test module
Move model init into pytest fixture to avoid loading model and downloading graph just by importing the test module
Python
apache-2.0
tensorflow/lucid,tensorflow/lucid,tensorflow/lucid,tensorflow/lucid
from __future__ import absolute_import, division, print_function import pytest import tensorflow as tf from lucid.modelzoo.vision_models import InceptionV1 from lucid.optvis import objectives, param, render, transform + @pytest.fixture + def inceptionv1(): - model = InceptionV1() + model = InceptionV1() - model.load_graphdef() + model.load_graphdef() - + return model @pytest.mark.parametrize("decorrelate", [True, False]) @pytest.mark.parametrize("fft", [True, False]) - def test_integration(decorrelate, fft): + def test_integration(decorrelate, fft, inceptionv1): obj = objectives.neuron("mixed3a_pre_relu", 0) param_f = lambda: param.image(16, decorrelate=decorrelate, fft=fft) - rendering = render.render_vis(model, obj, param_f=param_f, thresholds=(1,2), + rendering = render.render_vis(inceptionv1, obj, param_f=param_f, thresholds=(1,2), verbose=False, transforms=[]) start_image = rendering[0] end_image = rendering[-1] objective_f = objectives.neuron("mixed3a", 177) param_f = lambda: param.image(64, decorrelate=decorrelate, fft=fft) - rendering = render.render_vis(model, objective_f, param_f, verbose=False, thresholds=(0,64), use_fixed_seed=True) + rendering = render.render_vis(inceptionv1, objective_f, param_f, verbose=False, thresholds=(0,64), use_fixed_seed=True) start_image, end_image = rendering assert (start_image != end_image).any()
Move model init into pytest fixture to avoid loading model and downloading graph just by importing the test module
## Code Before: from __future__ import absolute_import, division, print_function import pytest import tensorflow as tf from lucid.modelzoo.vision_models import InceptionV1 from lucid.optvis import objectives, param, render, transform model = InceptionV1() model.load_graphdef() @pytest.mark.parametrize("decorrelate", [True, False]) @pytest.mark.parametrize("fft", [True, False]) def test_integration(decorrelate, fft): obj = objectives.neuron("mixed3a_pre_relu", 0) param_f = lambda: param.image(16, decorrelate=decorrelate, fft=fft) rendering = render.render_vis(model, obj, param_f=param_f, thresholds=(1,2), verbose=False, transforms=[]) start_image = rendering[0] end_image = rendering[-1] objective_f = objectives.neuron("mixed3a", 177) param_f = lambda: param.image(64, decorrelate=decorrelate, fft=fft) rendering = render.render_vis(model, objective_f, param_f, verbose=False, thresholds=(0,64), use_fixed_seed=True) start_image, end_image = rendering assert (start_image != end_image).any() ## Instruction: Move model init into pytest fixture to avoid loading model and downloading graph just by importing the test module ## Code After: from __future__ import absolute_import, division, print_function import pytest import tensorflow as tf from lucid.modelzoo.vision_models import InceptionV1 from lucid.optvis import objectives, param, render, transform @pytest.fixture def inceptionv1(): model = InceptionV1() model.load_graphdef() return model @pytest.mark.parametrize("decorrelate", [True, False]) @pytest.mark.parametrize("fft", [True, False]) def test_integration(decorrelate, fft, inceptionv1): obj = objectives.neuron("mixed3a_pre_relu", 0) param_f = lambda: param.image(16, decorrelate=decorrelate, fft=fft) rendering = render.render_vis(inceptionv1, obj, param_f=param_f, thresholds=(1,2), verbose=False, transforms=[]) start_image = rendering[0] end_image = rendering[-1] objective_f = objectives.neuron("mixed3a", 177) param_f = lambda: param.image(64, decorrelate=decorrelate, fft=fft) rendering = render.render_vis(inceptionv1, objective_f, param_f, verbose=False, thresholds=(0,64), use_fixed_seed=True) start_image, end_image = rendering assert (start_image != end_image).any()
// ... existing code ... @pytest.fixture def inceptionv1(): model = InceptionV1() model.load_graphdef() return model @pytest.mark.parametrize("decorrelate", [True, False]) @pytest.mark.parametrize("fft", [True, False]) def test_integration(decorrelate, fft, inceptionv1): obj = objectives.neuron("mixed3a_pre_relu", 0) param_f = lambda: param.image(16, decorrelate=decorrelate, fft=fft) rendering = render.render_vis(inceptionv1, obj, param_f=param_f, thresholds=(1,2), verbose=False, transforms=[]) start_image = rendering[0] // ... modified code ... objective_f = objectives.neuron("mixed3a", 177) param_f = lambda: param.image(64, decorrelate=decorrelate, fft=fft) rendering = render.render_vis(inceptionv1, objective_f, param_f, verbose=False, thresholds=(0,64), use_fixed_seed=True) start_image, end_image = rendering // ... rest of the code ...
a1a426a49511a52f5a40ab07310c1af4197feca2
includes/helpers.py
includes/helpers.py
def time_string(tdel): if tdel.days > 14: return "{}w ago".format(tdel.days//7) elif tdel.days > 1: return "{}d ago".format(tdel.days) elif tdel.seconds > 7200: return "{}h ago".format((tdel.days*24)+(tdel.seconds//3600)) elif tdel.seconds > 120: return "{}m ago".format(tdel.seconds//60) else: return "{}s ago".format(tdel.seconds)
def time_string(tdel): if tdel.days > 14: return "{}w ago".format(tdel.days//7) elif tdel.days > 1: return "{}d ago".format(tdel.days) elif tdel.days == 1 or tdel.seconds > 7200: return "{}h ago".format((tdel.days*24)+(tdel.seconds//3600)) elif tdel.seconds > 120: return "{}m ago".format(tdel.seconds//60) else: return "{}s ago".format(tdel.seconds)
Fix for 24-48 hours being incorrectly shown as 0-24 hours.
Fix for 24-48 hours being incorrectly shown as 0-24 hours.
Python
mit
Sulter/MASTERlinker
def time_string(tdel): if tdel.days > 14: return "{}w ago".format(tdel.days//7) elif tdel.days > 1: return "{}d ago".format(tdel.days) - elif tdel.seconds > 7200: + elif tdel.days == 1 or tdel.seconds > 7200: return "{}h ago".format((tdel.days*24)+(tdel.seconds//3600)) elif tdel.seconds > 120: return "{}m ago".format(tdel.seconds//60) else: return "{}s ago".format(tdel.seconds)
Fix for 24-48 hours being incorrectly shown as 0-24 hours.
## Code Before: def time_string(tdel): if tdel.days > 14: return "{}w ago".format(tdel.days//7) elif tdel.days > 1: return "{}d ago".format(tdel.days) elif tdel.seconds > 7200: return "{}h ago".format((tdel.days*24)+(tdel.seconds//3600)) elif tdel.seconds > 120: return "{}m ago".format(tdel.seconds//60) else: return "{}s ago".format(tdel.seconds) ## Instruction: Fix for 24-48 hours being incorrectly shown as 0-24 hours. ## Code After: def time_string(tdel): if tdel.days > 14: return "{}w ago".format(tdel.days//7) elif tdel.days > 1: return "{}d ago".format(tdel.days) elif tdel.days == 1 or tdel.seconds > 7200: return "{}h ago".format((tdel.days*24)+(tdel.seconds//3600)) elif tdel.seconds > 120: return "{}m ago".format(tdel.seconds//60) else: return "{}s ago".format(tdel.seconds)
# ... existing code ... elif tdel.days > 1: return "{}d ago".format(tdel.days) elif tdel.days == 1 or tdel.seconds > 7200: return "{}h ago".format((tdel.days*24)+(tdel.seconds//3600)) elif tdel.seconds > 120: # ... rest of the code ...
5779380fd4ec28367c1f232710291b3f81e1791f
nested_comments/views.py
nested_comments/views.py
from django.shortcuts import get_object_or_404 from django.views.generic import * # Third party apps from django_filters.rest_framework import DjangoFilterBackend from rest_framework import generics from rest_framework.decorators import api_view from rest_framework import permissions from rest_framework.reverse import reverse from rest_framework.response import Response # Other AstroBin apps from common.mixins import AjaxableResponseMixin # This app from .forms import NestedCommentForm from .models import NestedComment from .permissions import IsOwnerOrReadOnly from .serializers import * class NestedCommentList(generics.ListCreateAPIView): """ API endpoint that represents a list of nested comment.s """ model = NestedComment queryset = NestedComment.objects.order_by('pk') serializer_class = NestedCommentSerializer filter_backends = (DjangoFilterBackend,) filter_fields = ('content_type', 'object_id',) permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,) def pre_save(self, obj): obj.author = self.request.user class NestedCommentDetail(generics.RetrieveUpdateDestroyAPIView): """ API endpoint that represents a single nested comment. """ model = NestedComment serializer_class = NestedCommentSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,) def pre_save(self, obj): obj.author = self.request.user
from django.shortcuts import get_object_or_404 from django.views.generic import * # Third party apps from django_filters.rest_framework import DjangoFilterBackend from rest_framework import generics from rest_framework.decorators import api_view from rest_framework import permissions from rest_framework.reverse import reverse from rest_framework.response import Response # Other AstroBin apps from common.mixins import AjaxableResponseMixin # This app from .forms import NestedCommentForm from .models import NestedComment from .permissions import IsOwnerOrReadOnly from .serializers import * class NestedCommentList(generics.ListCreateAPIView): """ API endpoint that represents a list of nested comment.s """ model = NestedComment queryset = NestedComment.objects.order_by('pk') serializer_class = NestedCommentSerializer filter_backends = (DjangoFilterBackend,) filter_fields = ('content_type', 'object_id',) permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,) def pre_save(self, obj): obj.author = self.request.user class NestedCommentDetail(generics.RetrieveUpdateDestroyAPIView): """ API endpoint that represents a single nested comment. """ model = NestedComment queryset = NestedComment.objects.all() serializer_class = NestedCommentSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,) def pre_save(self, obj): obj.author = self.request.user
Add queryset attribute to NestedCommentDetail view
Add queryset attribute to NestedCommentDetail view
Python
agpl-3.0
astrobin/astrobin,astrobin/astrobin,astrobin/astrobin,astrobin/astrobin
from django.shortcuts import get_object_or_404 from django.views.generic import * # Third party apps from django_filters.rest_framework import DjangoFilterBackend from rest_framework import generics from rest_framework.decorators import api_view from rest_framework import permissions from rest_framework.reverse import reverse from rest_framework.response import Response # Other AstroBin apps from common.mixins import AjaxableResponseMixin # This app from .forms import NestedCommentForm from .models import NestedComment from .permissions import IsOwnerOrReadOnly from .serializers import * class NestedCommentList(generics.ListCreateAPIView): """ API endpoint that represents a list of nested comment.s """ model = NestedComment queryset = NestedComment.objects.order_by('pk') serializer_class = NestedCommentSerializer filter_backends = (DjangoFilterBackend,) filter_fields = ('content_type', 'object_id',) permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,) def pre_save(self, obj): obj.author = self.request.user class NestedCommentDetail(generics.RetrieveUpdateDestroyAPIView): """ API endpoint that represents a single nested comment. """ model = NestedComment + queryset = NestedComment.objects.all() serializer_class = NestedCommentSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,) def pre_save(self, obj): obj.author = self.request.user
Add queryset attribute to NestedCommentDetail view
## Code Before: from django.shortcuts import get_object_or_404 from django.views.generic import * # Third party apps from django_filters.rest_framework import DjangoFilterBackend from rest_framework import generics from rest_framework.decorators import api_view from rest_framework import permissions from rest_framework.reverse import reverse from rest_framework.response import Response # Other AstroBin apps from common.mixins import AjaxableResponseMixin # This app from .forms import NestedCommentForm from .models import NestedComment from .permissions import IsOwnerOrReadOnly from .serializers import * class NestedCommentList(generics.ListCreateAPIView): """ API endpoint that represents a list of nested comment.s """ model = NestedComment queryset = NestedComment.objects.order_by('pk') serializer_class = NestedCommentSerializer filter_backends = (DjangoFilterBackend,) filter_fields = ('content_type', 'object_id',) permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,) def pre_save(self, obj): obj.author = self.request.user class NestedCommentDetail(generics.RetrieveUpdateDestroyAPIView): """ API endpoint that represents a single nested comment. """ model = NestedComment serializer_class = NestedCommentSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,) def pre_save(self, obj): obj.author = self.request.user ## Instruction: Add queryset attribute to NestedCommentDetail view ## Code After: from django.shortcuts import get_object_or_404 from django.views.generic import * # Third party apps from django_filters.rest_framework import DjangoFilterBackend from rest_framework import generics from rest_framework.decorators import api_view from rest_framework import permissions from rest_framework.reverse import reverse from rest_framework.response import Response # Other AstroBin apps from common.mixins import AjaxableResponseMixin # This app from .forms import NestedCommentForm from .models import NestedComment from .permissions import IsOwnerOrReadOnly from .serializers import * class NestedCommentList(generics.ListCreateAPIView): """ API endpoint that represents a list of nested comment.s """ model = NestedComment queryset = NestedComment.objects.order_by('pk') serializer_class = NestedCommentSerializer filter_backends = (DjangoFilterBackend,) filter_fields = ('content_type', 'object_id',) permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,) def pre_save(self, obj): obj.author = self.request.user class NestedCommentDetail(generics.RetrieveUpdateDestroyAPIView): """ API endpoint that represents a single nested comment. """ model = NestedComment queryset = NestedComment.objects.all() serializer_class = NestedCommentSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,) def pre_save(self, obj): obj.author = self.request.user
// ... existing code ... """ model = NestedComment queryset = NestedComment.objects.all() serializer_class = NestedCommentSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, // ... rest of the code ...
74ededafa70c7ec5548d86289c6dbfc5e4cff6f2
tests/integration/ssh/test_deploy.py
tests/integration/ssh/test_deploy.py
''' salt-ssh testing ''' # Import Python libs from __future__ import absolute_import # Import salt testing libs from tests.support.case import SSHCase class SSHTest(SSHCase): ''' Test general salt-ssh functionality ''' def test_ping(self): ''' Test a simple ping ''' ret = self.run_function('test.ping') self.assertTrue(ret, 'Ping did not return true')
''' salt-ssh testing ''' # Import Python libs from __future__ import absolute_import import os import shutil # Import salt testing libs from tests.support.case import SSHCase class SSHTest(SSHCase): ''' Test general salt-ssh functionality ''' def test_ping(self): ''' Test a simple ping ''' ret = self.run_function('test.ping') self.assertTrue(ret, 'Ping did not return true') def test_thin_dir(self): ''' test to make sure thin_dir is created and salt-call file is included ''' thin_dir = self.run_function('config.get', ['thin_dir'], wipe=False) os.path.isdir(thin_dir) os.path.exists(os.path.join(thin_dir, 'salt-call')) os.path.exists(os.path.join(thin_dir, 'running_data')) def tearDown(self): ''' make sure to clean up any old ssh directories ''' salt_dir = self.run_function('config.get', ['thin_dir'], wipe=False) if os.path.exists(salt_dir): shutil.rmtree(salt_dir)
Add ssh thin_dir integration test
Add ssh thin_dir integration test
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
''' salt-ssh testing ''' # Import Python libs from __future__ import absolute_import + import os + import shutil # Import salt testing libs from tests.support.case import SSHCase class SSHTest(SSHCase): ''' Test general salt-ssh functionality ''' def test_ping(self): ''' Test a simple ping ''' ret = self.run_function('test.ping') self.assertTrue(ret, 'Ping did not return true') + def test_thin_dir(self): + ''' + test to make sure thin_dir is created + and salt-call file is included + ''' + thin_dir = self.run_function('config.get', ['thin_dir'], wipe=False) + os.path.isdir(thin_dir) + os.path.exists(os.path.join(thin_dir, 'salt-call')) + os.path.exists(os.path.join(thin_dir, 'running_data')) + + def tearDown(self): + ''' + make sure to clean up any old ssh directories + ''' + salt_dir = self.run_function('config.get', ['thin_dir'], wipe=False) + if os.path.exists(salt_dir): + shutil.rmtree(salt_dir) +
Add ssh thin_dir integration test
## Code Before: ''' salt-ssh testing ''' # Import Python libs from __future__ import absolute_import # Import salt testing libs from tests.support.case import SSHCase class SSHTest(SSHCase): ''' Test general salt-ssh functionality ''' def test_ping(self): ''' Test a simple ping ''' ret = self.run_function('test.ping') self.assertTrue(ret, 'Ping did not return true') ## Instruction: Add ssh thin_dir integration test ## Code After: ''' salt-ssh testing ''' # Import Python libs from __future__ import absolute_import import os import shutil # Import salt testing libs from tests.support.case import SSHCase class SSHTest(SSHCase): ''' Test general salt-ssh functionality ''' def test_ping(self): ''' Test a simple ping ''' ret = self.run_function('test.ping') self.assertTrue(ret, 'Ping did not return true') def test_thin_dir(self): ''' test to make sure thin_dir is created and salt-call file is included ''' thin_dir = self.run_function('config.get', ['thin_dir'], wipe=False) os.path.isdir(thin_dir) os.path.exists(os.path.join(thin_dir, 'salt-call')) os.path.exists(os.path.join(thin_dir, 'running_data')) def tearDown(self): ''' make sure to clean up any old ssh directories ''' salt_dir = self.run_function('config.get', ['thin_dir'], wipe=False) if os.path.exists(salt_dir): shutil.rmtree(salt_dir)
# ... existing code ... # Import Python libs from __future__ import absolute_import import os import shutil # Import salt testing libs # ... modified code ... ret = self.run_function('test.ping') self.assertTrue(ret, 'Ping did not return true') def test_thin_dir(self): ''' test to make sure thin_dir is created and salt-call file is included ''' thin_dir = self.run_function('config.get', ['thin_dir'], wipe=False) os.path.isdir(thin_dir) os.path.exists(os.path.join(thin_dir, 'salt-call')) os.path.exists(os.path.join(thin_dir, 'running_data')) def tearDown(self): ''' make sure to clean up any old ssh directories ''' salt_dir = self.run_function('config.get', ['thin_dir'], wipe=False) if os.path.exists(salt_dir): shutil.rmtree(salt_dir) # ... rest of the code ...
84fbe1eebc2c19b72ab4bba8017e1cb37818afc1
scripts/reactions.py
scripts/reactions.py
import argparse from lenrmc.nubase import System from lenrmc.terminal import TerminalView, StudiesTerminalView class App(object): def __init__(self, **kwargs): self.kwargs = kwargs if 'studies' == self.kwargs.get('view'): self.view_cls = StudiesTerminalView else: self.view_cls = TerminalView def run(self): s = System.parse(self.kwargs['system'], **self.kwargs) for line in self.view_cls(s).lines(**self.kwargs): print(line) def parse_arguments(): parser = argparse.ArgumentParser() parser.add_argument('system', type=str) parser.add_argument('--lb', dest='lower_bound') parser.add_argument('--spins', dest='spins', action='store_true') parser.add_argument('--references', dest='references', action='store_true') parser.add_argument('--view', type=str, dest='view') parser.set_defaults( lower_bound = 0, spins = False, references = True, view = 'default', ) return parser.parse_args() if '__main__' == __name__: opts = parse_arguments() App(**vars(opts)).run()
import argparse from lenrmc.nubase import System from lenrmc.terminal import TerminalView, StudiesTerminalView class App(object): def __init__(self, **kwargs): self.kwargs = kwargs if 'studies' == self.kwargs.get('view') or kwargs.get('studies'): self.view_cls = StudiesTerminalView else: self.view_cls = TerminalView def run(self): s = System.parse(self.kwargs['system'], **self.kwargs) for line in self.view_cls(s).lines(**self.kwargs): print(line) def parse_arguments(): parser = argparse.ArgumentParser() parser.add_argument('system', type=str) parser.add_argument('--lb', dest='lower_bound') parser.add_argument('--spins', dest='spins', action='store_true') parser.add_argument('--references', dest='references', action='store_true') parser.add_argument('--view', type=str, dest='view') parser.add_argument('--studies', dest='studies', action='store_true') parser.set_defaults( lower_bound = 0, spins = False, references = True, view = 'default', ) return parser.parse_args() if '__main__' == __name__: opts = parse_arguments() App(**vars(opts)).run()
Add --studies as an alias for --view studies.
Add --studies as an alias for --view studies.
Python
mit
emwalker/lenrmc
import argparse from lenrmc.nubase import System from lenrmc.terminal import TerminalView, StudiesTerminalView class App(object): def __init__(self, **kwargs): self.kwargs = kwargs - if 'studies' == self.kwargs.get('view'): + if 'studies' == self.kwargs.get('view') or kwargs.get('studies'): self.view_cls = StudiesTerminalView else: self.view_cls = TerminalView def run(self): s = System.parse(self.kwargs['system'], **self.kwargs) for line in self.view_cls(s).lines(**self.kwargs): print(line) def parse_arguments(): parser = argparse.ArgumentParser() parser.add_argument('system', type=str) parser.add_argument('--lb', dest='lower_bound') parser.add_argument('--spins', dest='spins', action='store_true') parser.add_argument('--references', dest='references', action='store_true') parser.add_argument('--view', type=str, dest='view') + parser.add_argument('--studies', dest='studies', action='store_true') parser.set_defaults( lower_bound = 0, spins = False, references = True, view = 'default', ) return parser.parse_args() if '__main__' == __name__: opts = parse_arguments() App(**vars(opts)).run()
Add --studies as an alias for --view studies.
## Code Before: import argparse from lenrmc.nubase import System from lenrmc.terminal import TerminalView, StudiesTerminalView class App(object): def __init__(self, **kwargs): self.kwargs = kwargs if 'studies' == self.kwargs.get('view'): self.view_cls = StudiesTerminalView else: self.view_cls = TerminalView def run(self): s = System.parse(self.kwargs['system'], **self.kwargs) for line in self.view_cls(s).lines(**self.kwargs): print(line) def parse_arguments(): parser = argparse.ArgumentParser() parser.add_argument('system', type=str) parser.add_argument('--lb', dest='lower_bound') parser.add_argument('--spins', dest='spins', action='store_true') parser.add_argument('--references', dest='references', action='store_true') parser.add_argument('--view', type=str, dest='view') parser.set_defaults( lower_bound = 0, spins = False, references = True, view = 'default', ) return parser.parse_args() if '__main__' == __name__: opts = parse_arguments() App(**vars(opts)).run() ## Instruction: Add --studies as an alias for --view studies. ## Code After: import argparse from lenrmc.nubase import System from lenrmc.terminal import TerminalView, StudiesTerminalView class App(object): def __init__(self, **kwargs): self.kwargs = kwargs if 'studies' == self.kwargs.get('view') or kwargs.get('studies'): self.view_cls = StudiesTerminalView else: self.view_cls = TerminalView def run(self): s = System.parse(self.kwargs['system'], **self.kwargs) for line in self.view_cls(s).lines(**self.kwargs): print(line) def parse_arguments(): parser = argparse.ArgumentParser() parser.add_argument('system', type=str) parser.add_argument('--lb', dest='lower_bound') parser.add_argument('--spins', dest='spins', action='store_true') parser.add_argument('--references', dest='references', action='store_true') parser.add_argument('--view', type=str, dest='view') parser.add_argument('--studies', dest='studies', action='store_true') parser.set_defaults( lower_bound = 0, spins = False, references = True, view = 'default', ) return parser.parse_args() if '__main__' == __name__: opts = parse_arguments() App(**vars(opts)).run()
... def __init__(self, **kwargs): self.kwargs = kwargs if 'studies' == self.kwargs.get('view') or kwargs.get('studies'): self.view_cls = StudiesTerminalView else: ... parser.add_argument('--references', dest='references', action='store_true') parser.add_argument('--view', type=str, dest='view') parser.add_argument('--studies', dest='studies', action='store_true') parser.set_defaults( lower_bound = 0, ...
07ee6957d20a1c02b22ed5d91d20211506e7ca54
partner_feeds/templatetags/partner_feed_tags.py
partner_feeds/templatetags/partner_feed_tags.py
from django import template from partner_feeds.models import Partner register = template.Library() @register.assignment_tag def get_partners(*args): partners = [] for name in args: try: partner = Partner.objects.get(name=name) except Partner.DoesNotExist: continue partner.posts = partner.post_set.all().order_by('-date') partners.append(partner) return partners
from django import template from partner_feeds.models import Partner, Post register = template.Library() @register.assignment_tag def get_partners(*partner_names): """ Given a list of partner names, return those partners with posts attached to them in the order that they were passed to this function """ partners = list(Partner.objects.filter(name__in=partner_names)) for partner in partners: partner.posts = Post.objects.filter(partner=partner) partners.sort(key=lambda p: partner_names.index(p.name)) return partners
Update `get_partners` assignment tag to reduce the number of queries
Update `get_partners` assignment tag to reduce the number of queries Maintains the same interface so no other changes should be required
Python
bsd-2-clause
theatlantic/django-partner-feeds
from django import template - from partner_feeds.models import Partner + from partner_feeds.models import Partner, Post register = template.Library() + @register.assignment_tag - def get_partners(*args): + def get_partners(*partner_names): - partners = [] - for name in args: - try: - partner = Partner.objects.get(name=name) - except Partner.DoesNotExist: - continue - partner.posts = partner.post_set.all().order_by('-date') - partners.append(partner) + """ + Given a list of partner names, return those partners with posts attached to + them in the order that they were passed to this function + + """ + partners = list(Partner.objects.filter(name__in=partner_names)) + for partner in partners: + partner.posts = Post.objects.filter(partner=partner) + partners.sort(key=lambda p: partner_names.index(p.name)) return partners +
Update `get_partners` assignment tag to reduce the number of queries
## Code Before: from django import template from partner_feeds.models import Partner register = template.Library() @register.assignment_tag def get_partners(*args): partners = [] for name in args: try: partner = Partner.objects.get(name=name) except Partner.DoesNotExist: continue partner.posts = partner.post_set.all().order_by('-date') partners.append(partner) return partners ## Instruction: Update `get_partners` assignment tag to reduce the number of queries ## Code After: from django import template from partner_feeds.models import Partner, Post register = template.Library() @register.assignment_tag def get_partners(*partner_names): """ Given a list of partner names, return those partners with posts attached to them in the order that they were passed to this function """ partners = list(Partner.objects.filter(name__in=partner_names)) for partner in partners: partner.posts = Post.objects.filter(partner=partner) partners.sort(key=lambda p: partner_names.index(p.name)) return partners
// ... existing code ... from django import template from partner_feeds.models import Partner, Post register = template.Library() @register.assignment_tag def get_partners(*partner_names): """ Given a list of partner names, return those partners with posts attached to them in the order that they were passed to this function """ partners = list(Partner.objects.filter(name__in=partner_names)) for partner in partners: partner.posts = Post.objects.filter(partner=partner) partners.sort(key=lambda p: partner_names.index(p.name)) return partners // ... rest of the code ...
e493d5403de51d8ee448e532d60204041aa88c19
jedihttp/handlers.py
jedihttp/handlers.py
import bottle from bottle import response, request import json import jedi import logging app = bottle.Bottle( __name__ ) logger = logging.getLogger( __name__ ) @app.post( '/healthy' ) def healthy(): return _Json({}) @app.post( '/ready' ) def ready(): return _Json({}) @app.post( '/completions' ) def completion(): logger.info( 'received /completions request' ) script = _GetJediScript( request.json ) return _Json( { 'completions': [ { 'name': completion.name, 'description': completion.description, 'docstring': completion.docstring(), 'module_path': completion.module_path, 'line': completion.line, 'column': completion.column } for completion in script.completions() ] } ) def _GetJediScript( request_data ): source = request_data[ 'source' ] line = request_data[ 'line' ] col = request_data[ 'col' ] path = request_data[ 'path' ] return jedi.Script( source, line, col, path ) def _Json( data ): response.content_type = 'application/json' return json.dumps( data )
import bottle from bottle import response, request import json import jedi import logging app = bottle.Bottle( __name__ ) logger = logging.getLogger( __name__ ) @app.post( '/healthy' ) def healthy(): return _Json({'healthy': True}) @app.post( '/ready' ) def ready(): return _Json({'ready': True}) @app.post( '/completions' ) def completion(): logger.info( 'received /completions request' ) script = _GetJediScript( request.json ) return _Json( { 'completions': [ { 'name': completion.name, 'description': completion.description, 'docstring': completion.docstring(), 'module_path': completion.module_path, 'line': completion.line, 'column': completion.column } for completion in script.completions() ] } ) def _GetJediScript( request_data ): source = request_data[ 'source' ] line = request_data[ 'line' ] col = request_data[ 'col' ] path = request_data[ 'path' ] return jedi.Script( source, line, col, path ) def _Json( data ): response.content_type = 'application/json' return json.dumps( data )
Send descriptive responses for /ready and /healthy
Send descriptive responses for /ready and /healthy
Python
apache-2.0
vheon/JediHTTP,micbou/JediHTTP,micbou/JediHTTP,vheon/JediHTTP
import bottle from bottle import response, request import json import jedi import logging app = bottle.Bottle( __name__ ) logger = logging.getLogger( __name__ ) @app.post( '/healthy' ) def healthy(): - return _Json({}) + return _Json({'healthy': True}) @app.post( '/ready' ) def ready(): - return _Json({}) + return _Json({'ready': True}) @app.post( '/completions' ) def completion(): logger.info( 'received /completions request' ) script = _GetJediScript( request.json ) return _Json( { 'completions': [ { 'name': completion.name, 'description': completion.description, 'docstring': completion.docstring(), 'module_path': completion.module_path, 'line': completion.line, 'column': completion.column } for completion in script.completions() ] } ) def _GetJediScript( request_data ): source = request_data[ 'source' ] line = request_data[ 'line' ] col = request_data[ 'col' ] path = request_data[ 'path' ] return jedi.Script( source, line, col, path ) def _Json( data ): response.content_type = 'application/json' return json.dumps( data )
Send descriptive responses for /ready and /healthy
## Code Before: import bottle from bottle import response, request import json import jedi import logging app = bottle.Bottle( __name__ ) logger = logging.getLogger( __name__ ) @app.post( '/healthy' ) def healthy(): return _Json({}) @app.post( '/ready' ) def ready(): return _Json({}) @app.post( '/completions' ) def completion(): logger.info( 'received /completions request' ) script = _GetJediScript( request.json ) return _Json( { 'completions': [ { 'name': completion.name, 'description': completion.description, 'docstring': completion.docstring(), 'module_path': completion.module_path, 'line': completion.line, 'column': completion.column } for completion in script.completions() ] } ) def _GetJediScript( request_data ): source = request_data[ 'source' ] line = request_data[ 'line' ] col = request_data[ 'col' ] path = request_data[ 'path' ] return jedi.Script( source, line, col, path ) def _Json( data ): response.content_type = 'application/json' return json.dumps( data ) ## Instruction: Send descriptive responses for /ready and /healthy ## Code After: import bottle from bottle import response, request import json import jedi import logging app = bottle.Bottle( __name__ ) logger = logging.getLogger( __name__ ) @app.post( '/healthy' ) def healthy(): return _Json({'healthy': True}) @app.post( '/ready' ) def ready(): return _Json({'ready': True}) @app.post( '/completions' ) def completion(): logger.info( 'received /completions request' ) script = _GetJediScript( request.json ) return _Json( { 'completions': [ { 'name': completion.name, 'description': completion.description, 'docstring': completion.docstring(), 'module_path': completion.module_path, 'line': completion.line, 'column': completion.column } for completion in script.completions() ] } ) def _GetJediScript( request_data ): source = request_data[ 'source' ] line = request_data[ 'line' ] col = request_data[ 'col' ] path = request_data[ 'path' ] return jedi.Script( source, line, col, path ) def _Json( data ): response.content_type = 'application/json' return json.dumps( data )
// ... existing code ... @app.post( '/healthy' ) def healthy(): return _Json({'healthy': True}) // ... modified code ... @app.post( '/ready' ) def ready(): return _Json({'ready': True}) // ... rest of the code ...
0e779581be648ca80eea6b97f9963606d85659b9
opensfm/commands/__init__.py
opensfm/commands/__init__.py
import extract_metadata import detect_features import match_features import create_tracks import reconstruct import mesh import undistort import compute_depthmaps import export_ply import export_openmvs opensfm_commands = [ extract_metadata, detect_features, match_features, create_tracks, reconstruct, mesh, undistort, compute_depthmaps, export_ply, export_openmvs, ]
import extract_metadata import detect_features import match_features import create_tracks import reconstruct import mesh import undistort import compute_depthmaps import export_ply import export_openmvs import export_visualsfm opensfm_commands = [ extract_metadata, detect_features, match_features, create_tracks, reconstruct, mesh, undistort, compute_depthmaps, export_ply, export_openmvs, export_visualsfm, ]
Add exporter to VisualSfM format
Add exporter to VisualSfM format
Python
bsd-2-clause
BrookRoberts/OpenSfM,mapillary/OpenSfM,sunbingfengPI/OpenSFM_Test,BrookRoberts/OpenSfM,sunbingfengPI/OpenSFM_Test,sunbingfengPI/OpenSFM_Test,sunbingfengPI/OpenSFM_Test,oscarlorentzon/OpenSfM,BrookRoberts/OpenSfM,oscarlorentzon/OpenSfM,oscarlorentzon/OpenSfM,oscarlorentzon/OpenSfM,mapillary/OpenSfM,mapillary/OpenSfM,BrookRoberts/OpenSfM,BrookRoberts/OpenSfM,mapillary/OpenSfM,mapillary/OpenSfM,sunbingfengPI/OpenSFM_Test,oscarlorentzon/OpenSfM
import extract_metadata import detect_features import match_features import create_tracks import reconstruct import mesh import undistort import compute_depthmaps import export_ply import export_openmvs + import export_visualsfm opensfm_commands = [ extract_metadata, detect_features, match_features, create_tracks, reconstruct, mesh, undistort, compute_depthmaps, export_ply, export_openmvs, + export_visualsfm, ]
Add exporter to VisualSfM format
## Code Before: import extract_metadata import detect_features import match_features import create_tracks import reconstruct import mesh import undistort import compute_depthmaps import export_ply import export_openmvs opensfm_commands = [ extract_metadata, detect_features, match_features, create_tracks, reconstruct, mesh, undistort, compute_depthmaps, export_ply, export_openmvs, ] ## Instruction: Add exporter to VisualSfM format ## Code After: import extract_metadata import detect_features import match_features import create_tracks import reconstruct import mesh import undistort import compute_depthmaps import export_ply import export_openmvs import export_visualsfm opensfm_commands = [ extract_metadata, detect_features, match_features, create_tracks, reconstruct, mesh, undistort, compute_depthmaps, export_ply, export_openmvs, export_visualsfm, ]
// ... existing code ... import export_ply import export_openmvs import export_visualsfm opensfm_commands = [ // ... modified code ... export_ply, export_openmvs, export_visualsfm, ] // ... rest of the code ...
5d463f5823baad3ea485a54719a5799d14f10a27
lda/__init__.py
lda/__init__.py
from __future__ import absolute_import, unicode_literals # noqa import logging import pbr.version from lda.lda import LDA # noqa __version__ = pbr.version.VersionInfo('lda').version_string() logging.getLogger('lda').addHandler(logging.NullHandler())
from __future__ import absolute_import, unicode_literals # noqa import logging import pbr.version from lda.lda import LDA # noqa import lda.datasets # noqa __version__ = pbr.version.VersionInfo('lda').version_string() logging.getLogger('lda').addHandler(logging.NullHandler())
Make lda.datasets available after import lda
Make lda.datasets available after import lda
Python
mpl-2.0
hothHowler/lda,ww880412/lda,ww880412/lda,ariddell/lda,tdhopper/lda-1,tdhopper/lda-1,ariddell/lda-debian,ww880412/lda,tdhopper/lda-1,ariddell/lda,hothHowler/lda,ariddell/lda-debian,ariddell/lda,hothHowler/lda,ariddell/lda-debian
from __future__ import absolute_import, unicode_literals # noqa import logging import pbr.version from lda.lda import LDA # noqa + import lda.datasets # noqa __version__ = pbr.version.VersionInfo('lda').version_string() logging.getLogger('lda').addHandler(logging.NullHandler())
Make lda.datasets available after import lda
## Code Before: from __future__ import absolute_import, unicode_literals # noqa import logging import pbr.version from lda.lda import LDA # noqa __version__ = pbr.version.VersionInfo('lda').version_string() logging.getLogger('lda').addHandler(logging.NullHandler()) ## Instruction: Make lda.datasets available after import lda ## Code After: from __future__ import absolute_import, unicode_literals # noqa import logging import pbr.version from lda.lda import LDA # noqa import lda.datasets # noqa __version__ = pbr.version.VersionInfo('lda').version_string() logging.getLogger('lda').addHandler(logging.NullHandler())
... from lda.lda import LDA # noqa import lda.datasets # noqa __version__ = pbr.version.VersionInfo('lda').version_string() ...
8a544ac2db71d4041c77fdb0ddfe27b84b565bb5
salt/utils/saltminionservice.py
salt/utils/saltminionservice.py
from salt.utils.winservice import Service, instart import salt # Import third party libs import win32serviceutil import win32service import winerror import win32api # Import python libs import sys class MinionService(Service): def start(self): self.runflag = True self.log("Starting the Salt Minion") minion = salt.Minion() minion.start() while self.runflag: pass #self.sleep(10) #self.log("I'm alive ...") def stop(self): self.runflag = False self.log("Shutting down the Salt Minion") def console_event_handler(event): if event == 5: # Do nothing on CTRL_LOGOFF_EVENT return True return False def _main(): win32api.SetConsoleCtrlHandler(console_event_handler, 1) servicename = 'salt-minion' try: status = win32serviceutil.QueryServiceStatus(servicename) except win32service.error as details: if details[0] == winerror.ERROR_SERVICE_DOES_NOT_EXIST: instart(MinionService, servicename, 'Salt Minion') sys.exit(0) if status[1] == win32service.SERVICE_RUNNING: win32serviceutil.StopServiceWithDeps(servicename) win32serviceutil.StartService(servicename) else: win32serviceutil.StartService(servicename) if __name__ == '__main__': _main()
from salt.utils.winservice import Service, instart import salt # Import third party libs import win32serviceutil import win32service import winerror # Import python libs import sys class MinionService(Service): def start(self): self.runflag = True self.log("Starting the Salt Minion") minion = salt.Minion() minion.start() while self.runflag: pass #self.sleep(10) #self.log("I'm alive ...") def stop(self): self.runflag = False self.log("Shutting down the Salt Minion") def _main(): servicename = 'salt-minion' try: status = win32serviceutil.QueryServiceStatus(servicename) except win32service.error as details: if details[0] == winerror.ERROR_SERVICE_DOES_NOT_EXIST: instart(MinionService, servicename, 'Salt Minion') sys.exit(0) if status[1] == win32service.SERVICE_RUNNING: win32serviceutil.StopServiceWithDeps(servicename) win32serviceutil.StartService(servicename) else: win32serviceutil.StartService(servicename) if __name__ == '__main__': _main()
Revert "Catch and ignore CTRL_LOGOFF_EVENT when run as a windows service"
Revert "Catch and ignore CTRL_LOGOFF_EVENT when run as a windows service" This reverts commit a7ddf81b37b578b1448f83b0efb4f7116de0c3fb.
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
from salt.utils.winservice import Service, instart import salt # Import third party libs import win32serviceutil import win32service import winerror - import win32api # Import python libs import sys class MinionService(Service): def start(self): self.runflag = True self.log("Starting the Salt Minion") minion = salt.Minion() minion.start() while self.runflag: pass #self.sleep(10) #self.log("I'm alive ...") def stop(self): self.runflag = False self.log("Shutting down the Salt Minion") - def console_event_handler(event): - if event == 5: - # Do nothing on CTRL_LOGOFF_EVENT - return True - return False def _main(): - win32api.SetConsoleCtrlHandler(console_event_handler, 1) servicename = 'salt-minion' try: status = win32serviceutil.QueryServiceStatus(servicename) except win32service.error as details: if details[0] == winerror.ERROR_SERVICE_DOES_NOT_EXIST: instart(MinionService, servicename, 'Salt Minion') sys.exit(0) if status[1] == win32service.SERVICE_RUNNING: win32serviceutil.StopServiceWithDeps(servicename) win32serviceutil.StartService(servicename) else: win32serviceutil.StartService(servicename) if __name__ == '__main__': _main()
Revert "Catch and ignore CTRL_LOGOFF_EVENT when run as a windows service"
## Code Before: from salt.utils.winservice import Service, instart import salt # Import third party libs import win32serviceutil import win32service import winerror import win32api # Import python libs import sys class MinionService(Service): def start(self): self.runflag = True self.log("Starting the Salt Minion") minion = salt.Minion() minion.start() while self.runflag: pass #self.sleep(10) #self.log("I'm alive ...") def stop(self): self.runflag = False self.log("Shutting down the Salt Minion") def console_event_handler(event): if event == 5: # Do nothing on CTRL_LOGOFF_EVENT return True return False def _main(): win32api.SetConsoleCtrlHandler(console_event_handler, 1) servicename = 'salt-minion' try: status = win32serviceutil.QueryServiceStatus(servicename) except win32service.error as details: if details[0] == winerror.ERROR_SERVICE_DOES_NOT_EXIST: instart(MinionService, servicename, 'Salt Minion') sys.exit(0) if status[1] == win32service.SERVICE_RUNNING: win32serviceutil.StopServiceWithDeps(servicename) win32serviceutil.StartService(servicename) else: win32serviceutil.StartService(servicename) if __name__ == '__main__': _main() ## Instruction: Revert "Catch and ignore CTRL_LOGOFF_EVENT when run as a windows service" ## Code After: from salt.utils.winservice import Service, instart import salt # Import third party libs import win32serviceutil import win32service import winerror # Import python libs import sys class MinionService(Service): def start(self): self.runflag = True self.log("Starting the Salt Minion") minion = salt.Minion() minion.start() while self.runflag: pass #self.sleep(10) #self.log("I'm alive ...") def stop(self): self.runflag = False self.log("Shutting down the Salt Minion") def _main(): servicename = 'salt-minion' try: status = win32serviceutil.QueryServiceStatus(servicename) except win32service.error as details: if details[0] == winerror.ERROR_SERVICE_DOES_NOT_EXIST: instart(MinionService, servicename, 'Salt Minion') sys.exit(0) if status[1] == win32service.SERVICE_RUNNING: win32serviceutil.StopServiceWithDeps(servicename) win32serviceutil.StartService(servicename) else: win32serviceutil.StartService(servicename) if __name__ == '__main__': _main()
# ... existing code ... import win32service import winerror # Import python libs # ... modified code ... self.log("Shutting down the Salt Minion") def _main(): servicename = 'salt-minion' try: # ... rest of the code ...
0b56e5d8b1da9c5b76a39cead7f4642384750c0a
utils/http.py
utils/http.py
import requests from django.conf import settings AUTH = getattr(settings, 'BASIC_AUTH_DOMAINS', None) def url_exists(url): """Check that a url (when following redirection) exists. This is needed because Django's validators rely on Python's urllib2 which in verions < 2.6 won't follow redirects. """ try: # This AUTH stuff is a hack to get around the HTTP Basic Auth on dev # and staging to prevent partner stuff from going public. if AUTH: for domain, auth in AUTH.items(): if domain in url: return 200 <= requests.head(url, auth=auth).status_code < 400 return 200 <= requests.head(url).status_code < 400 except requests.ConnectionError: return False
import requests def url_exists(url): """Check that a url (when following redirection) exists. This is needed because Django's validators rely on Python's urllib2 which in verions < 2.6 won't follow redirects. """ try: return 200 <= requests.head(url).status_code < 400 except requests.ConnectionError: return False
Remove the unnecessary and never-used basic auth hack.
Remove the unnecessary and never-used basic auth hack.
Python
agpl-3.0
ReachingOut/unisubs,ofer43211/unisubs,ReachingOut/unisubs,ujdhesa/unisubs,eloquence/unisubs,pculture/unisubs,ujdhesa/unisubs,wevoice/wesub,ReachingOut/unisubs,wevoice/wesub,pculture/unisubs,eloquence/unisubs,norayr/unisubs,norayr/unisubs,eloquence/unisubs,pculture/unisubs,wevoice/wesub,ReachingOut/unisubs,pculture/unisubs,norayr/unisubs,ujdhesa/unisubs,ofer43211/unisubs,ofer43211/unisubs,wevoice/wesub,ofer43211/unisubs,ujdhesa/unisubs,eloquence/unisubs,norayr/unisubs
import requests - from django.conf import settings - - - AUTH = getattr(settings, 'BASIC_AUTH_DOMAINS', None) def url_exists(url): """Check that a url (when following redirection) exists. - This is needed because Django's validators rely on Python's urllib2 + This is needed because Django's validators rely on Python's urllib2 which in - which in verions < 2.6 won't follow redirects. + verions < 2.6 won't follow redirects. """ try: - # This AUTH stuff is a hack to get around the HTTP Basic Auth on dev - # and staging to prevent partner stuff from going public. - if AUTH: - for domain, auth in AUTH.items(): - if domain in url: - return 200 <= requests.head(url, auth=auth).status_code < 400 - return 200 <= requests.head(url).status_code < 400 except requests.ConnectionError: return False
Remove the unnecessary and never-used basic auth hack.
## Code Before: import requests from django.conf import settings AUTH = getattr(settings, 'BASIC_AUTH_DOMAINS', None) def url_exists(url): """Check that a url (when following redirection) exists. This is needed because Django's validators rely on Python's urllib2 which in verions < 2.6 won't follow redirects. """ try: # This AUTH stuff is a hack to get around the HTTP Basic Auth on dev # and staging to prevent partner stuff from going public. if AUTH: for domain, auth in AUTH.items(): if domain in url: return 200 <= requests.head(url, auth=auth).status_code < 400 return 200 <= requests.head(url).status_code < 400 except requests.ConnectionError: return False ## Instruction: Remove the unnecessary and never-used basic auth hack. ## Code After: import requests def url_exists(url): """Check that a url (when following redirection) exists. This is needed because Django's validators rely on Python's urllib2 which in verions < 2.6 won't follow redirects. """ try: return 200 <= requests.head(url).status_code < 400 except requests.ConnectionError: return False
// ... existing code ... import requests def url_exists(url): // ... modified code ... """Check that a url (when following redirection) exists. This is needed because Django's validators rely on Python's urllib2 which in verions < 2.6 won't follow redirects. """ try: return 200 <= requests.head(url).status_code < 400 except requests.ConnectionError: // ... rest of the code ...
f2a7fe543aa338e81bea692b8267154e64e7478d
polling_stations/apps/file_uploads/utils.py
polling_stations/apps/file_uploads/utils.py
import os from django.db.models import Q from councils.models import Council, UserCouncils def get_domain(request): return os.environ.get("APP_DOMAIN", request.META.get("HTTP_HOST")) def assign_councils_to_user(user): """ Adds rows to the join table between User and Council """ email_domain = user.email.rsplit("@", 1)[1] councils = Council.objects.filter( Q(electoral_services_email__contains=email_domain) | Q(registration_email__contains=email_domain) ) for council in councils: UserCouncils.objects.update_or_create(user=user, council=council)
import os from django.db.models import Q from councils.models import Council, UserCouncils def get_domain(request): return os.environ.get("APP_DOMAIN", request.META.get("HTTP_HOST")) def assign_councils_to_user(user): """ Adds rows to the join table between User and Council """ email_domain = user.email.rsplit("@", 1)[1] councils = Council.objects.using("logger").filter( Q(electoral_services_email__contains=email_domain) | Q(registration_email__contains=email_domain) ) for council in councils: UserCouncils.objects.using("logger").update_or_create( user=user, council=council )
Make sure UserCouncil is created in logger db
Make sure UserCouncil is created in logger db
Python
bsd-3-clause
DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations
import os from django.db.models import Q from councils.models import Council, UserCouncils def get_domain(request): return os.environ.get("APP_DOMAIN", request.META.get("HTTP_HOST")) def assign_councils_to_user(user): """ Adds rows to the join table between User and Council """ email_domain = user.email.rsplit("@", 1)[1] - councils = Council.objects.filter( + councils = Council.objects.using("logger").filter( Q(electoral_services_email__contains=email_domain) | Q(registration_email__contains=email_domain) ) for council in councils: - UserCouncils.objects.update_or_create(user=user, council=council) + UserCouncils.objects.using("logger").update_or_create( + user=user, council=council + )
Make sure UserCouncil is created in logger db
## Code Before: import os from django.db.models import Q from councils.models import Council, UserCouncils def get_domain(request): return os.environ.get("APP_DOMAIN", request.META.get("HTTP_HOST")) def assign_councils_to_user(user): """ Adds rows to the join table between User and Council """ email_domain = user.email.rsplit("@", 1)[1] councils = Council.objects.filter( Q(electoral_services_email__contains=email_domain) | Q(registration_email__contains=email_domain) ) for council in councils: UserCouncils.objects.update_or_create(user=user, council=council) ## Instruction: Make sure UserCouncil is created in logger db ## Code After: import os from django.db.models import Q from councils.models import Council, UserCouncils def get_domain(request): return os.environ.get("APP_DOMAIN", request.META.get("HTTP_HOST")) def assign_councils_to_user(user): """ Adds rows to the join table between User and Council """ email_domain = user.email.rsplit("@", 1)[1] councils = Council.objects.using("logger").filter( Q(electoral_services_email__contains=email_domain) | Q(registration_email__contains=email_domain) ) for council in councils: UserCouncils.objects.using("logger").update_or_create( user=user, council=council )
... """ email_domain = user.email.rsplit("@", 1)[1] councils = Council.objects.using("logger").filter( Q(electoral_services_email__contains=email_domain) | Q(registration_email__contains=email_domain) ... for council in councils: UserCouncils.objects.using("logger").update_or_create( user=user, council=council ) ...
eb368c344075ce78606d4656ebfb19c7e7ccdf50
src/054.py
src/054.py
from path import dirpath def ans(): lines = open(dirpath() + '054.txt').readlines() cards = [line.strip().split() for line in lines] return None if __name__ == '__main__': print(ans())
from collections import ( defaultdict, namedtuple, ) from path import dirpath def _value(rank): try: return int(rank) except ValueError: return 10 + 'TJQKA'.index(rank) def _sort_by_rank(hand): return list(reversed(sorted( hand, key=lambda card: _value(card[0]), ))) def _of_a_kind(hand, count): counts = defaultdict(list) for card in hand: counts[card[0]].append(card) filtered = { rank: cards for rank, cards in counts.items() if count <= len(cards) } if len(filtered) < 1: return None return max( filtered.values(), key=lambda cards: _value(cards[0][0]) ) def high_card(hand): return _of_a_kind(hand, 1) def two_of_a_kind(hand): return _of_a_kind(hand, 2) def three_of_a_kind(hand): return _of_a_kind(hand, 3) def four_of_a_kind(hand): return _of_a_kind(hand, 4) def full_house(hand): three = three_of_a_kind(hand) if not three: return None pair = two_of_a_kind([card for card in hand if card not in three]) if not pair: return None return three + pair def straight(hand): sorted_ = sorted([_value(card[0]) for card in hand]) if sorted_ == list(range(sorted_[0], sorted_[-1] + 1)): return _sort_by_rank(hand) return None def flush(hand): counts = defaultdict(list) for card in hand: counts[card[1]].append(card) for cards in counts.values(): if len(cards) == 5: return _sort_by_rank(cards) return None def straight_flush(hand): return flush(hand) if straight(hand) else None def ans(): lines = open(dirpath() + '054.txt').readlines() turns = [line.strip().split() for line in lines] num_wins = 0 for cards in turns: one = cards[:5] two = cards[5:] return None if __name__ == '__main__': print(ans())
Write some logic for 54
Write some logic for 54
Python
mit
mackorone/euler
+ from collections import ( + defaultdict, + namedtuple, + ) from path import dirpath + + + def _value(rank): + try: + return int(rank) + except ValueError: + return 10 + 'TJQKA'.index(rank) + + + def _sort_by_rank(hand): + return list(reversed(sorted( + hand, + key=lambda card: _value(card[0]), + ))) + + + def _of_a_kind(hand, count): + counts = defaultdict(list) + for card in hand: + counts[card[0]].append(card) + filtered = { + rank: cards for + rank, cards in counts.items() if + count <= len(cards) + } + if len(filtered) < 1: + return None + return max( + filtered.values(), + key=lambda cards: _value(cards[0][0]) + ) + + + def high_card(hand): + return _of_a_kind(hand, 1) + + + def two_of_a_kind(hand): + return _of_a_kind(hand, 2) + + + def three_of_a_kind(hand): + return _of_a_kind(hand, 3) + + + def four_of_a_kind(hand): + return _of_a_kind(hand, 4) + + + def full_house(hand): + three = three_of_a_kind(hand) + if not three: + return None + pair = two_of_a_kind([card for card in hand if card not in three]) + if not pair: + return None + return three + pair + + + def straight(hand): + sorted_ = sorted([_value(card[0]) for card in hand]) + if sorted_ == list(range(sorted_[0], sorted_[-1] + 1)): + return _sort_by_rank(hand) + return None + + + def flush(hand): + counts = defaultdict(list) + for card in hand: + counts[card[1]].append(card) + for cards in counts.values(): + if len(cards) == 5: + return _sort_by_rank(cards) + return None + + + def straight_flush(hand): + return flush(hand) if straight(hand) else None def ans(): lines = open(dirpath() + '054.txt').readlines() - cards = [line.strip().split() for line in lines] + turns = [line.strip().split() for line in lines] + num_wins = 0 + for cards in turns: + one = cards[:5] + two = cards[5:] return None if __name__ == '__main__': print(ans())
Write some logic for 54
## Code Before: from path import dirpath def ans(): lines = open(dirpath() + '054.txt').readlines() cards = [line.strip().split() for line in lines] return None if __name__ == '__main__': print(ans()) ## Instruction: Write some logic for 54 ## Code After: from collections import ( defaultdict, namedtuple, ) from path import dirpath def _value(rank): try: return int(rank) except ValueError: return 10 + 'TJQKA'.index(rank) def _sort_by_rank(hand): return list(reversed(sorted( hand, key=lambda card: _value(card[0]), ))) def _of_a_kind(hand, count): counts = defaultdict(list) for card in hand: counts[card[0]].append(card) filtered = { rank: cards for rank, cards in counts.items() if count <= len(cards) } if len(filtered) < 1: return None return max( filtered.values(), key=lambda cards: _value(cards[0][0]) ) def high_card(hand): return _of_a_kind(hand, 1) def two_of_a_kind(hand): return _of_a_kind(hand, 2) def three_of_a_kind(hand): return _of_a_kind(hand, 3) def four_of_a_kind(hand): return _of_a_kind(hand, 4) def full_house(hand): three = three_of_a_kind(hand) if not three: return None pair = two_of_a_kind([card for card in hand if card not in three]) if not pair: return None return three + pair def straight(hand): sorted_ = sorted([_value(card[0]) for card in hand]) if sorted_ == list(range(sorted_[0], sorted_[-1] + 1)): return _sort_by_rank(hand) return None def flush(hand): counts = defaultdict(list) for card in hand: counts[card[1]].append(card) for cards in counts.values(): if len(cards) == 5: return _sort_by_rank(cards) return None def straight_flush(hand): return flush(hand) if straight(hand) else None def ans(): lines = open(dirpath() + '054.txt').readlines() turns = [line.strip().split() for line in lines] num_wins = 0 for cards in turns: one = cards[:5] two = cards[5:] return None if __name__ == '__main__': print(ans())
# ... existing code ... from collections import ( defaultdict, namedtuple, ) from path import dirpath def _value(rank): try: return int(rank) except ValueError: return 10 + 'TJQKA'.index(rank) def _sort_by_rank(hand): return list(reversed(sorted( hand, key=lambda card: _value(card[0]), ))) def _of_a_kind(hand, count): counts = defaultdict(list) for card in hand: counts[card[0]].append(card) filtered = { rank: cards for rank, cards in counts.items() if count <= len(cards) } if len(filtered) < 1: return None return max( filtered.values(), key=lambda cards: _value(cards[0][0]) ) def high_card(hand): return _of_a_kind(hand, 1) def two_of_a_kind(hand): return _of_a_kind(hand, 2) def three_of_a_kind(hand): return _of_a_kind(hand, 3) def four_of_a_kind(hand): return _of_a_kind(hand, 4) def full_house(hand): three = three_of_a_kind(hand) if not three: return None pair = two_of_a_kind([card for card in hand if card not in three]) if not pair: return None return three + pair def straight(hand): sorted_ = sorted([_value(card[0]) for card in hand]) if sorted_ == list(range(sorted_[0], sorted_[-1] + 1)): return _sort_by_rank(hand) return None def flush(hand): counts = defaultdict(list) for card in hand: counts[card[1]].append(card) for cards in counts.values(): if len(cards) == 5: return _sort_by_rank(cards) return None def straight_flush(hand): return flush(hand) if straight(hand) else None # ... modified code ... def ans(): lines = open(dirpath() + '054.txt').readlines() turns = [line.strip().split() for line in lines] num_wins = 0 for cards in turns: one = cards[:5] two = cards[5:] return None # ... rest of the code ...
aceeac7e9dd2735add937bc7141cfdb29b6201c7
pywatson/watson.py
pywatson/watson.py
from pywatson.answer.answer import Answer from pywatson.question.question import Question import requests class Watson: """The Watson API adapter class""" def __init__(self, url, username, password): self.url = url self.username = username self.password = password def ask_question(self, question_text, question=None): """Ask Watson a question via the Question and Answer API :param question_text: question to ask Watson :type question_text: str :param question: if question_text is not provided, a Question object representing the question to ask Watson :type question: Question :return: Answer """ if question is not None: q = question.to_dict() else: q = Question(question_text).to_dict() r = requests.post(self.url + '/question', json=q) return Answer(r.json())
from pywatson.answer.answer import Answer from pywatson.question.question import Question import requests class Watson(object): """The Watson API adapter class""" def __init__(self, url, username, password): self.url = url self.username = username self.password = password def ask_question(self, question_text, question=None): """Ask Watson a question via the Question and Answer API :param question_text: question to ask Watson :type question_text: str :param question: if question_text is not provided, a Question object representing the question to ask Watson :type question: Question :return: Answer """ if question is not None: q = question.__dict__ else: q = Question(question_text).__dict__ r = requests.post(self.url + '/question', json=q) return Answer(r.json())
Use __dict__ instead of to_dict()
Use __dict__ instead of to_dict()
Python
mit
sherlocke/pywatson
from pywatson.answer.answer import Answer from pywatson.question.question import Question import requests - class Watson: + class Watson(object): """The Watson API adapter class""" def __init__(self, url, username, password): self.url = url self.username = username self.password = password def ask_question(self, question_text, question=None): """Ask Watson a question via the Question and Answer API :param question_text: question to ask Watson :type question_text: str :param question: if question_text is not provided, a Question object representing the question to ask Watson :type question: Question :return: Answer """ if question is not None: - q = question.to_dict() + q = question.__dict__ else: - q = Question(question_text).to_dict() + q = Question(question_text).__dict__ r = requests.post(self.url + '/question', json=q) return Answer(r.json())
Use __dict__ instead of to_dict()
## Code Before: from pywatson.answer.answer import Answer from pywatson.question.question import Question import requests class Watson: """The Watson API adapter class""" def __init__(self, url, username, password): self.url = url self.username = username self.password = password def ask_question(self, question_text, question=None): """Ask Watson a question via the Question and Answer API :param question_text: question to ask Watson :type question_text: str :param question: if question_text is not provided, a Question object representing the question to ask Watson :type question: Question :return: Answer """ if question is not None: q = question.to_dict() else: q = Question(question_text).to_dict() r = requests.post(self.url + '/question', json=q) return Answer(r.json()) ## Instruction: Use __dict__ instead of to_dict() ## Code After: from pywatson.answer.answer import Answer from pywatson.question.question import Question import requests class Watson(object): """The Watson API adapter class""" def __init__(self, url, username, password): self.url = url self.username = username self.password = password def ask_question(self, question_text, question=None): """Ask Watson a question via the Question and Answer API :param question_text: question to ask Watson :type question_text: str :param question: if question_text is not provided, a Question object representing the question to ask Watson :type question: Question :return: Answer """ if question is not None: q = question.__dict__ else: q = Question(question_text).__dict__ r = requests.post(self.url + '/question', json=q) return Answer(r.json())
... class Watson(object): """The Watson API adapter class""" ... """ if question is not None: q = question.__dict__ else: q = Question(question_text).__dict__ r = requests.post(self.url + '/question', json=q) return Answer(r.json()) ...
82a00e48492f2d787c980c434d58e249c210818e
ffmpeg/_probe.py
ffmpeg/_probe.py
import json import subprocess from ._run import Error from ._utils import convert_kwargs_to_cmd_line_args def probe(filename, cmd='ffprobe', **kwargs): """Run ffprobe on the specified file and return a JSON representation of the output. Raises: :class:`ffmpeg.Error`: if ffprobe returns a non-zero exit code, an :class:`Error` is returned with a generic error message. The stderr output can be retrieved by accessing the ``stderr`` property of the exception. """ args = [cmd, '-show_format', '-show_streams', '-of', 'json'] args += convert_kwargs_to_cmd_line_args(kwargs) args += [filename] p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() if p.returncode != 0: raise Error('ffprobe', out, err) return json.loads(out.decode('utf-8')) __all__ = ['probe']
import json import subprocess from ._run import Error from ._utils import convert_kwargs_to_cmd_line_args def probe(filename, cmd='ffprobe', timeout=None, **kwargs): """Run ffprobe on the specified file and return a JSON representation of the output. Raises: :class:`ffmpeg.Error`: if ffprobe returns a non-zero exit code, an :class:`Error` is returned with a generic error message. The stderr output can be retrieved by accessing the ``stderr`` property of the exception. """ args = [cmd, '-show_format', '-show_streams', '-of', 'json'] args += convert_kwargs_to_cmd_line_args(kwargs) args += [filename] p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate(timeout=timeout) if p.returncode != 0: raise Error('ffprobe', out, err) return json.loads(out.decode('utf-8')) __all__ = ['probe']
Add optional timeout argument to probe
Add optional timeout argument to probe Popen.communicate() supports a timeout argument which is useful in case there is a risk that the probe hangs.
Python
apache-2.0
kkroening/ffmpeg-python
import json import subprocess from ._run import Error from ._utils import convert_kwargs_to_cmd_line_args - def probe(filename, cmd='ffprobe', **kwargs): + def probe(filename, cmd='ffprobe', timeout=None, **kwargs): """Run ffprobe on the specified file and return a JSON representation of the output. Raises: :class:`ffmpeg.Error`: if ffprobe returns a non-zero exit code, an :class:`Error` is returned with a generic error message. The stderr output can be retrieved by accessing the ``stderr`` property of the exception. """ args = [cmd, '-show_format', '-show_streams', '-of', 'json'] args += convert_kwargs_to_cmd_line_args(kwargs) args += [filename] p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - out, err = p.communicate() + out, err = p.communicate(timeout=timeout) if p.returncode != 0: raise Error('ffprobe', out, err) return json.loads(out.decode('utf-8')) __all__ = ['probe']
Add optional timeout argument to probe
## Code Before: import json import subprocess from ._run import Error from ._utils import convert_kwargs_to_cmd_line_args def probe(filename, cmd='ffprobe', **kwargs): """Run ffprobe on the specified file and return a JSON representation of the output. Raises: :class:`ffmpeg.Error`: if ffprobe returns a non-zero exit code, an :class:`Error` is returned with a generic error message. The stderr output can be retrieved by accessing the ``stderr`` property of the exception. """ args = [cmd, '-show_format', '-show_streams', '-of', 'json'] args += convert_kwargs_to_cmd_line_args(kwargs) args += [filename] p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() if p.returncode != 0: raise Error('ffprobe', out, err) return json.loads(out.decode('utf-8')) __all__ = ['probe'] ## Instruction: Add optional timeout argument to probe ## Code After: import json import subprocess from ._run import Error from ._utils import convert_kwargs_to_cmd_line_args def probe(filename, cmd='ffprobe', timeout=None, **kwargs): """Run ffprobe on the specified file and return a JSON representation of the output. Raises: :class:`ffmpeg.Error`: if ffprobe returns a non-zero exit code, an :class:`Error` is returned with a generic error message. The stderr output can be retrieved by accessing the ``stderr`` property of the exception. """ args = [cmd, '-show_format', '-show_streams', '-of', 'json'] args += convert_kwargs_to_cmd_line_args(kwargs) args += [filename] p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate(timeout=timeout) if p.returncode != 0: raise Error('ffprobe', out, err) return json.loads(out.decode('utf-8')) __all__ = ['probe']
... def probe(filename, cmd='ffprobe', timeout=None, **kwargs): """Run ffprobe on the specified file and return a JSON representation of the output. ... p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate(timeout=timeout) if p.returncode != 0: raise Error('ffprobe', out, err) ...
66aa43a5e8963c440261128e5b317679d01917e6
server/routes.py
server/routes.py
from __init__ import app, db from subprocess import call from models import User from flask import request from flask import abort from flask import jsonify @app.route('/register', methods=['POST']) def register(): if not request.json or not 'guid' in request.json: abort(400) # Malformed Packet guid = request.json['guid'] user = User(guid) db.session.add(user) db.session.commit() registerObject = { 'id': user.guid } return jsonify(registerObject), 201 @app.route('/phone', methods=['POST']) def phone(): if not request.json or (not ('call-time' in request.json)) or (not ('id' in request.json)): abort(400) # Malformed Packet user = User.query.filter_by(id=request.json["id"]).first() if not user: #Check database for id to make sure it exists abort(401) # Todo Steve will do this return "", 201 @app.route('/') def landing_page(): return 'Nothing seems to be here' @app.route('/update-server', methods=['GET', 'POST']) def update(): call(["git pull"], shell=True) return 'Success!'
from __init__ import app, db from subprocess import call from models import User from flask import request from flask import abort from flask import jsonify @app.route('/register', methods=['POST']) def register(): if not request.json or not 'guid' in request.json: abort(400) # Malformed Packet guid = request.json['guid'] user = User(guid) db.session.add(user) db.session.commit() registerObject = { 'id': user.guid } return jsonify(registerObject), 201 @app.route('/phone', methods=['POST']) def phone(): if not request.json or (not ('call-time' in request.json)) or (not ('id' in request.json)): abort(400) # Malformed Packet user = User.query.filter_by(id=request.json["id"]).first() if not user: #Check database for id to make sure it exists abort(401) # Todo Steve will do this return "", 200 @app.route('/msg_to', methods=['POST']) def msg_to(): if not request.json or (not ('phone_number' in request.json)) or (not ('id' in request.json)): abort(400) # Malformed Packet user = User.query.filter_by(id=request.json["id"]).first() if not user: #Check database for id to make sure it exists abort(401) # Waiting on Steve's commit return "", 200 @app.route('/') def landing_page(): return 'Nothing seems to be here' @app.route('/update-server', methods=['GET', 'POST']) def update(): call(["git pull"], shell=True) return 'Success!'
Return header fix and msg_to route
Return header fix and msg_to route
Python
mit
stevex86/RandomActsOfKindness,stevex86/RandomActsOfKindness
from __init__ import app, db from subprocess import call from models import User from flask import request from flask import abort from flask import jsonify @app.route('/register', methods=['POST']) def register(): if not request.json or not 'guid' in request.json: abort(400) # Malformed Packet guid = request.json['guid'] user = User(guid) db.session.add(user) db.session.commit() registerObject = { 'id': user.guid } return jsonify(registerObject), 201 @app.route('/phone', methods=['POST']) def phone(): if not request.json or (not ('call-time' in request.json)) or (not ('id' in request.json)): abort(400) # Malformed Packet user = User.query.filter_by(id=request.json["id"]).first() if not user: #Check database for id to make sure it exists abort(401) # Todo Steve will do this - return "", 201 + return "", 200 + + @app.route('/msg_to', methods=['POST']) + def msg_to(): + if not request.json or (not ('phone_number' in request.json)) or (not ('id' in request.json)): + abort(400) # Malformed Packet + + user = User.query.filter_by(id=request.json["id"]).first() + + if not user: #Check database for id to make sure it exists + abort(401) + + # Waiting on Steve's commit + + return "", 200 @app.route('/') def landing_page(): return 'Nothing seems to be here' @app.route('/update-server', methods=['GET', 'POST']) def update(): call(["git pull"], shell=True) return 'Success!'
Return header fix and msg_to route
## Code Before: from __init__ import app, db from subprocess import call from models import User from flask import request from flask import abort from flask import jsonify @app.route('/register', methods=['POST']) def register(): if not request.json or not 'guid' in request.json: abort(400) # Malformed Packet guid = request.json['guid'] user = User(guid) db.session.add(user) db.session.commit() registerObject = { 'id': user.guid } return jsonify(registerObject), 201 @app.route('/phone', methods=['POST']) def phone(): if not request.json or (not ('call-time' in request.json)) or (not ('id' in request.json)): abort(400) # Malformed Packet user = User.query.filter_by(id=request.json["id"]).first() if not user: #Check database for id to make sure it exists abort(401) # Todo Steve will do this return "", 201 @app.route('/') def landing_page(): return 'Nothing seems to be here' @app.route('/update-server', methods=['GET', 'POST']) def update(): call(["git pull"], shell=True) return 'Success!' ## Instruction: Return header fix and msg_to route ## Code After: from __init__ import app, db from subprocess import call from models import User from flask import request from flask import abort from flask import jsonify @app.route('/register', methods=['POST']) def register(): if not request.json or not 'guid' in request.json: abort(400) # Malformed Packet guid = request.json['guid'] user = User(guid) db.session.add(user) db.session.commit() registerObject = { 'id': user.guid } return jsonify(registerObject), 201 @app.route('/phone', methods=['POST']) def phone(): if not request.json or (not ('call-time' in request.json)) or (not ('id' in request.json)): abort(400) # Malformed Packet user = User.query.filter_by(id=request.json["id"]).first() if not user: #Check database for id to make sure it exists abort(401) # Todo Steve will do this return "", 200 @app.route('/msg_to', methods=['POST']) def msg_to(): if not request.json or (not ('phone_number' in request.json)) or (not ('id' in request.json)): abort(400) # Malformed Packet user = User.query.filter_by(id=request.json["id"]).first() if not user: #Check database for id to make sure it exists abort(401) # Waiting on Steve's commit return "", 200 @app.route('/') def landing_page(): return 'Nothing seems to be here' @app.route('/update-server', methods=['GET', 'POST']) def update(): call(["git pull"], shell=True) return 'Success!'
# ... existing code ... # Todo Steve will do this return "", 200 @app.route('/msg_to', methods=['POST']) def msg_to(): if not request.json or (not ('phone_number' in request.json)) or (not ('id' in request.json)): abort(400) # Malformed Packet user = User.query.filter_by(id=request.json["id"]).first() if not user: #Check database for id to make sure it exists abort(401) # Waiting on Steve's commit return "", 200 @app.route('/') # ... rest of the code ...
eecb3468b581b4854f2162c2b62ac06ea744045e
malcolm/core/attributemeta.py
malcolm/core/attributemeta.py
from collections import OrderedDict from malcolm.core.serializable import Serializable class AttributeMeta(Serializable): """Abstract base class for Meta objects""" # Type constants SCALAR = "scalar" TABLE = "table" SCALARARRAY = "scalar_array" def __init__(self, name, description, *args): super(AttributeMeta, self).__init__(name, *args) self.description = description def validate(self, value): """ Abstract function to validate a given value Args: value(abstract): Value to validate """ raise NotImplementedError( "Abstract validate function must be implemented in child classes") def to_dict(self): """Convert object attributes into a dictionary""" d = OrderedDict() d["description"] = self.description d["typeid"] = self.typeid return d
from collections import OrderedDict from malcolm.core.serializable import Serializable class AttributeMeta(Serializable): """Abstract base class for Meta objects""" def __init__(self, name, description, *args): super(AttributeMeta, self).__init__(name, *args) self.description = description def validate(self, value): """ Abstract function to validate a given value Args: value(abstract): Value to validate """ raise NotImplementedError( "Abstract validate function must be implemented in child classes") def to_dict(self): """Convert object attributes into a dictionary""" d = OrderedDict() d["description"] = self.description d["typeid"] = self.typeid return d
Remove unused AttributeMeta type constants
Remove unused AttributeMeta type constants
Python
apache-2.0
dls-controls/pymalcolm,dls-controls/pymalcolm,dls-controls/pymalcolm
from collections import OrderedDict from malcolm.core.serializable import Serializable class AttributeMeta(Serializable): """Abstract base class for Meta objects""" - - # Type constants - SCALAR = "scalar" - TABLE = "table" - SCALARARRAY = "scalar_array" def __init__(self, name, description, *args): super(AttributeMeta, self).__init__(name, *args) self.description = description def validate(self, value): """ Abstract function to validate a given value Args: value(abstract): Value to validate """ raise NotImplementedError( "Abstract validate function must be implemented in child classes") def to_dict(self): """Convert object attributes into a dictionary""" d = OrderedDict() d["description"] = self.description d["typeid"] = self.typeid return d
Remove unused AttributeMeta type constants
## Code Before: from collections import OrderedDict from malcolm.core.serializable import Serializable class AttributeMeta(Serializable): """Abstract base class for Meta objects""" # Type constants SCALAR = "scalar" TABLE = "table" SCALARARRAY = "scalar_array" def __init__(self, name, description, *args): super(AttributeMeta, self).__init__(name, *args) self.description = description def validate(self, value): """ Abstract function to validate a given value Args: value(abstract): Value to validate """ raise NotImplementedError( "Abstract validate function must be implemented in child classes") def to_dict(self): """Convert object attributes into a dictionary""" d = OrderedDict() d["description"] = self.description d["typeid"] = self.typeid return d ## Instruction: Remove unused AttributeMeta type constants ## Code After: from collections import OrderedDict from malcolm.core.serializable import Serializable class AttributeMeta(Serializable): """Abstract base class for Meta objects""" def __init__(self, name, description, *args): super(AttributeMeta, self).__init__(name, *args) self.description = description def validate(self, value): """ Abstract function to validate a given value Args: value(abstract): Value to validate """ raise NotImplementedError( "Abstract validate function must be implemented in child classes") def to_dict(self): """Convert object attributes into a dictionary""" d = OrderedDict() d["description"] = self.description d["typeid"] = self.typeid return d
... class AttributeMeta(Serializable): """Abstract base class for Meta objects""" def __init__(self, name, description, *args): ...
053d6a2ca13b1f36a02fa3223092a10af35f6579
erpnext/patches/v10_0/item_barcode_childtable_migrate.py
erpnext/patches/v10_0/item_barcode_childtable_migrate.py
from __future__ import unicode_literals import frappe def execute(): items_barcode = frappe.get_all('Item', ['name', 'barcode'], { 'barcode': ('!=', '') }) frappe.reload_doc("stock", "doctype", "item") frappe.reload_doc("stock", "doctype", "item_barcode") for item in items_barcode: barcode = item.barcode.strip() if barcode and '<' not in barcode: try: frappe.get_doc({ 'idx': 0, 'doctype': 'Item Barcode', 'barcode': barcode, 'parenttype': 'Item', 'parent': item.name, 'parentfield': 'barcodes' }).insert() except frappe.DuplicateEntryError: continue
from __future__ import unicode_literals import frappe def execute(): frappe.reload_doc("stock", "doctype", "item_barcode") items_barcode = frappe.get_all('Item', ['name', 'barcode'], { 'barcode': ('!=', '') }) frappe.reload_doc("stock", "doctype", "item") for item in items_barcode: barcode = item.barcode.strip() if barcode and '<' not in barcode: try: frappe.get_doc({ 'idx': 0, 'doctype': 'Item Barcode', 'barcode': barcode, 'parenttype': 'Item', 'parent': item.name, 'parentfield': 'barcodes' }).insert() except frappe.DuplicateEntryError: continue
Move reload doc before get query
Move reload doc before get query
Python
agpl-3.0
gsnbng/erpnext,gsnbng/erpnext,gsnbng/erpnext,gsnbng/erpnext
from __future__ import unicode_literals import frappe def execute(): + frappe.reload_doc("stock", "doctype", "item_barcode") + items_barcode = frappe.get_all('Item', ['name', 'barcode'], { 'barcode': ('!=', '') }) + frappe.reload_doc("stock", "doctype", "item") + - frappe.reload_doc("stock", "doctype", "item") - frappe.reload_doc("stock", "doctype", "item_barcode") for item in items_barcode: barcode = item.barcode.strip() if barcode and '<' not in barcode: try: frappe.get_doc({ 'idx': 0, 'doctype': 'Item Barcode', 'barcode': barcode, 'parenttype': 'Item', 'parent': item.name, 'parentfield': 'barcodes' }).insert() except frappe.DuplicateEntryError: continue
Move reload doc before get query
## Code Before: from __future__ import unicode_literals import frappe def execute(): items_barcode = frappe.get_all('Item', ['name', 'barcode'], { 'barcode': ('!=', '') }) frappe.reload_doc("stock", "doctype", "item") frappe.reload_doc("stock", "doctype", "item_barcode") for item in items_barcode: barcode = item.barcode.strip() if barcode and '<' not in barcode: try: frappe.get_doc({ 'idx': 0, 'doctype': 'Item Barcode', 'barcode': barcode, 'parenttype': 'Item', 'parent': item.name, 'parentfield': 'barcodes' }).insert() except frappe.DuplicateEntryError: continue ## Instruction: Move reload doc before get query ## Code After: from __future__ import unicode_literals import frappe def execute(): frappe.reload_doc("stock", "doctype", "item_barcode") items_barcode = frappe.get_all('Item', ['name', 'barcode'], { 'barcode': ('!=', '') }) frappe.reload_doc("stock", "doctype", "item") for item in items_barcode: barcode = item.barcode.strip() if barcode and '<' not in barcode: try: frappe.get_doc({ 'idx': 0, 'doctype': 'Item Barcode', 'barcode': barcode, 'parenttype': 'Item', 'parent': item.name, 'parentfield': 'barcodes' }).insert() except frappe.DuplicateEntryError: continue
// ... existing code ... def execute(): frappe.reload_doc("stock", "doctype", "item_barcode") items_barcode = frappe.get_all('Item', ['name', 'barcode'], { 'barcode': ('!=', '') }) frappe.reload_doc("stock", "doctype", "item") for item in items_barcode: // ... rest of the code ...
80d671aa79f306bb17eed006bc99eaa6e6a17bd5
molecule/default/tests/test_default.py
molecule/default/tests/test_default.py
import datetime import os import pytest import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') @pytest.mark.parametrize("name", [ "lorem", "ipsum", ]) @pytest.mark.parametrize("dir", [ ".vimrc", ]) def test_backup_dirs(host, name, dir): t = datetime.datetime.today().isoformat()[:10] c = "find /home/{0} -name {1}.{2}* | sort -r | head -n1" b = host.run(c.format(name, dir, t)) d = host.file(b.stdout) assert b.rc == 0 assert d.exists assert d.user == name assert d.group == name @pytest.mark.parametrize("name", [ "lorem", "ipsum", ]) def test_janus_install(host, name): d = host.file("/home/{0}/.vim/janus/vim/".format(name)) assert d.exists assert d.user == name assert d.group == name @pytest.mark.parametrize("name", [ "lorem", "ipsum", ]) @pytest.mark.parametrize("plugin", [ "lightline.vim", "vim-surround", ]) def test_plugin_install(host, name, plugin): d = host.file("/home/{0}/.janus/{1}".format(name, plugin)) assert d.exists assert d.user == name assert d.group == name
import os import pytest import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') @pytest.mark.parametrize("name", [ "lorem", "ipsum", ]) @pytest.mark.parametrize("file", [ ".vimrc", ]) def test_backup_files(host, name, file): n = host.run("find . -type f -name '{}.*' | wc -l".format(file)) assert int(float(n.stdout)) > 0 @pytest.mark.parametrize("name", [ "lorem", "ipsum", ]) def test_janus_install(host, name): d = host.file("/home/{0}/.vim/janus/vim/".format(name)) assert d.exists assert d.user == name assert d.group == name @pytest.mark.parametrize("name", [ "lorem", "ipsum", ]) @pytest.mark.parametrize("plugin", [ "lightline.vim", "vim-surround", ]) def test_plugin_install(host, name, plugin): d = host.file("/home/{0}/.janus/{1}".format(name, plugin)) assert d.exists assert d.user == name assert d.group == name
Simplify backup-file test (and rename)
Simplify backup-file test (and rename)
Python
mit
ctorgalson/ansible-role-janus,ctorgalson/ansible-role-janus
- import datetime - import os import pytest import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') @pytest.mark.parametrize("name", [ "lorem", "ipsum", ]) - @pytest.mark.parametrize("dir", [ + @pytest.mark.parametrize("file", [ ".vimrc", ]) - def test_backup_dirs(host, name, dir): + def test_backup_files(host, name, file): + n = host.run("find . -type f -name '{}.*' | wc -l".format(file)) - t = datetime.datetime.today().isoformat()[:10] - c = "find /home/{0} -name {1}.{2}* | sort -r | head -n1" - b = host.run(c.format(name, dir, t)) - d = host.file(b.stdout) + assert int(float(n.stdout)) > 0 - assert b.rc == 0 - assert d.exists - assert d.user == name - assert d.group == name @pytest.mark.parametrize("name", [ "lorem", "ipsum", ]) def test_janus_install(host, name): d = host.file("/home/{0}/.vim/janus/vim/".format(name)) assert d.exists assert d.user == name assert d.group == name @pytest.mark.parametrize("name", [ "lorem", "ipsum", ]) @pytest.mark.parametrize("plugin", [ "lightline.vim", "vim-surround", ]) def test_plugin_install(host, name, plugin): d = host.file("/home/{0}/.janus/{1}".format(name, plugin)) assert d.exists assert d.user == name assert d.group == name
Simplify backup-file test (and rename)
## Code Before: import datetime import os import pytest import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') @pytest.mark.parametrize("name", [ "lorem", "ipsum", ]) @pytest.mark.parametrize("dir", [ ".vimrc", ]) def test_backup_dirs(host, name, dir): t = datetime.datetime.today().isoformat()[:10] c = "find /home/{0} -name {1}.{2}* | sort -r | head -n1" b = host.run(c.format(name, dir, t)) d = host.file(b.stdout) assert b.rc == 0 assert d.exists assert d.user == name assert d.group == name @pytest.mark.parametrize("name", [ "lorem", "ipsum", ]) def test_janus_install(host, name): d = host.file("/home/{0}/.vim/janus/vim/".format(name)) assert d.exists assert d.user == name assert d.group == name @pytest.mark.parametrize("name", [ "lorem", "ipsum", ]) @pytest.mark.parametrize("plugin", [ "lightline.vim", "vim-surround", ]) def test_plugin_install(host, name, plugin): d = host.file("/home/{0}/.janus/{1}".format(name, plugin)) assert d.exists assert d.user == name assert d.group == name ## Instruction: Simplify backup-file test (and rename) ## Code After: import os import pytest import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') @pytest.mark.parametrize("name", [ "lorem", "ipsum", ]) @pytest.mark.parametrize("file", [ ".vimrc", ]) def test_backup_files(host, name, file): n = host.run("find . -type f -name '{}.*' | wc -l".format(file)) assert int(float(n.stdout)) > 0 @pytest.mark.parametrize("name", [ "lorem", "ipsum", ]) def test_janus_install(host, name): d = host.file("/home/{0}/.vim/janus/vim/".format(name)) assert d.exists assert d.user == name assert d.group == name @pytest.mark.parametrize("name", [ "lorem", "ipsum", ]) @pytest.mark.parametrize("plugin", [ "lightline.vim", "vim-surround", ]) def test_plugin_install(host, name, plugin): d = host.file("/home/{0}/.janus/{1}".format(name, plugin)) assert d.exists assert d.user == name assert d.group == name
// ... existing code ... import os // ... modified code ... "ipsum", ]) @pytest.mark.parametrize("file", [ ".vimrc", ]) def test_backup_files(host, name, file): n = host.run("find . -type f -name '{}.*' | wc -l".format(file)) assert int(float(n.stdout)) > 0 // ... rest of the code ...
40711777de24d30cfe771f172b221cfdf460d8eb
rng.py
rng.py
from random import randint def get_random_number(start=1, end=10): """Generates and returns random number between :start: and :end:""" return randint(start, end)
def get_random_number(start=1, end=10): """https://xkcd.com/221/""" return 4
Revert "Fix python random number generator."
Revert "Fix python random number generator."
Python
mit
1yvT0s/illacceptanything,dushmis/illacceptanything,dushmis/illacceptanything,ultranaut/illacceptanything,caioproiete/illacceptanything,triggerNZ/illacceptanything,dushmis/illacceptanything,oneminot/illacceptanything,TheWhiteLlama/illacceptanything,ds84182/illacceptanything,caioproiete/illacceptanything,paladique/illacceptanything,ultranaut/illacceptanything,TheWhiteLlama/illacceptanything,oneminot/illacceptanything,TheWhiteLlama/illacceptanything,caioproiete/illacceptanything,caioproiete/illacceptanything,paladique/illacceptanything,ds84182/illacceptanything,illacceptanything/illacceptanything,oneminot/illacceptanything,paladique/illacceptanything,tjhorner/illacceptanything,triggerNZ/illacceptanything,tjhorner/illacceptanything,triggerNZ/illacceptanything,oneminot/illacceptanything,dushmis/illacceptanything,illacceptanything/illacceptanything,TheWhiteLlama/illacceptanything,triggerNZ/illacceptanything,JeffreyCA/illacceptanything,ultranaut/illacceptanything,1yvT0s/illacceptanything,ultranaut/illacceptanything,caioproiete/illacceptanything,JeffreyCA/illacceptanything,1yvT0s/illacceptanything,oneminot/illacceptanything,dushmis/illacceptanything,paladique/illacceptanything,JeffreyCA/illacceptanything,1yvT0s/illacceptanything,paladique/illacceptanything,JeffreyCA/illacceptanything,1yvT0s/illacceptanything,tjhorner/illacceptanything,oneminot/illacceptanything,paladique/illacceptanything,tjhorner/illacceptanything,dushmis/illacceptanything,JeffreyCA/illacceptanything,tjhorner/illacceptanything,1yvT0s/illacceptanything,tjhorner/illacceptanything,ultranaut/illacceptanything,oneminot/illacceptanything,paladique/illacceptanything,ds84182/illacceptanything,JeffreyCA/illacceptanything,illacceptanything/illacceptanything,paladique/illacceptanything,tjhorner/illacceptanything,TheWhiteLlama/illacceptanything,1yvT0s/illacceptanything,illacceptanything/illacceptanything,1yvT0s/illacceptanything,JeffreyCA/illacceptanything,TheWhiteLlama/illacceptanything,ds84182/illacceptanything,caioproiete/illacceptanything,ds84182/illacceptanything,paladique/illacceptanything,triggerNZ/illacceptanything,1yvT0s/illacceptanything,illacceptanything/illacceptanything,oneminot/illacceptanything,dushmis/illacceptanything,TheWhiteLlama/illacceptanything,dushmis/illacceptanything,dushmis/illacceptanything,illacceptanything/illacceptanything,JeffreyCA/illacceptanything,tjhorner/illacceptanything,illacceptanything/illacceptanything,ds84182/illacceptanything,tjhorner/illacceptanything,illacceptanything/illacceptanything,dushmis/illacceptanything,caioproiete/illacceptanything,oneminot/illacceptanything,JeffreyCA/illacceptanything,ds84182/illacceptanything,oneminot/illacceptanything,paladique/illacceptanything,1yvT0s/illacceptanything,triggerNZ/illacceptanything,paladique/illacceptanything,caioproiete/illacceptanything,TheWhiteLlama/illacceptanything,JeffreyCA/illacceptanything,triggerNZ/illacceptanything,illacceptanything/illacceptanything,caioproiete/illacceptanything,tjhorner/illacceptanything,TheWhiteLlama/illacceptanything,1yvT0s/illacceptanything,ultranaut/illacceptanything,ultranaut/illacceptanything,paladique/illacceptanything,dushmis/illacceptanything,triggerNZ/illacceptanything,TheWhiteLlama/illacceptanything,TheWhiteLlama/illacceptanything,tjhorner/illacceptanything,ultranaut/illacceptanything,TheWhiteLlama/illacceptanything,caioproiete/illacceptanything,paladique/illacceptanything,JeffreyCA/illacceptanything,caioproiete/illacceptanything,oneminot/illacceptanything,triggerNZ/illacceptanything,ds84182/illacceptanything,ds84182/illacceptanything,oneminot/illacceptanything,ultranaut/illacceptanything,caioproiete/illacceptanything,1yvT0s/illacceptanything,caioproiete/illacceptanything,paladique/illacceptanything,ds84182/illacceptanything,illacceptanything/illacceptanything,triggerNZ/illacceptanything,JeffreyCA/illacceptanything,JeffreyCA/illacceptanything,tjhorner/illacceptanything,caioproiete/illacceptanything,ds84182/illacceptanything,ds84182/illacceptanything,triggerNZ/illacceptanything,tjhorner/illacceptanything,TheWhiteLlama/illacceptanything,ds84182/illacceptanything,ultranaut/illacceptanything,ds84182/illacceptanything,ultranaut/illacceptanything,tjhorner/illacceptanything,TheWhiteLlama/illacceptanything,1yvT0s/illacceptanything,JeffreyCA/illacceptanything,illacceptanything/illacceptanything,illacceptanything/illacceptanything,dushmis/illacceptanything,oneminot/illacceptanything,triggerNZ/illacceptanything,tjhorner/illacceptanything,TheWhiteLlama/illacceptanything,illacceptanything/illacceptanything,illacceptanything/illacceptanything,paladique/illacceptanything,1yvT0s/illacceptanything,oneminot/illacceptanything,oneminot/illacceptanything,ultranaut/illacceptanything,triggerNZ/illacceptanything,ultranaut/illacceptanything,triggerNZ/illacceptanything,JeffreyCA/illacceptanything,dushmis/illacceptanything,ultranaut/illacceptanything,ds84182/illacceptanything,1yvT0s/illacceptanything,caioproiete/illacceptanything,ultranaut/illacceptanything,dushmis/illacceptanything,illacceptanything/illacceptanything,triggerNZ/illacceptanything,dushmis/illacceptanything
- from random import randint + def get_random_number(start=1, end=10): + """https://xkcd.com/221/""" + return 4 - def get_random_number(start=1, end=10): - """Generates and returns random number between :start: and :end:""" - return randint(start, end) -
Revert "Fix python random number generator."
## Code Before: from random import randint def get_random_number(start=1, end=10): """Generates and returns random number between :start: and :end:""" return randint(start, end) ## Instruction: Revert "Fix python random number generator." ## Code After: def get_random_number(start=1, end=10): """https://xkcd.com/221/""" return 4
... def get_random_number(start=1, end=10): """https://xkcd.com/221/""" return 4 ...
93acb34d999f89d23d2b613f12c1c767304c2ad6
gor/middleware.py
gor/middleware.py
import os, sys from .base import Gor from tornado import gen, ioloop, queues class TornadoGor(Gor): def __init__(self, *args, **kwargs): super(TornadoGor, self).__init__(*args, **kwargs) self.q = queues.Queue() self.concurrency = kwargs.get('concurrency', 2) @gen.coroutine def _process(self): line = yield self.q.get() try: msg = self.parse_message(line) if msg: self.emit(msg, line) finally: self.q.task_done() @gen.coroutine def _worker(self): while True: yield self._process() @gen.coroutine def _run(self): for _ in range(self.concurrency): self._worker() while True: try: line = sys.stdin.readline() except KeyboardInterrupt: try: sys.exit(0) except SystemExit: os._exit(0) self.q.put(line) yield def run(self): self.io_loop = ioloop.IOLoop.current() self.io_loop.run_sync(self._run)
import sys import errno import logging from .base import Gor from tornado import gen, ioloop, queues import contextlib from tornado.stack_context import StackContext @contextlib.contextmanager def die_on_error(): try: yield except Exception: logging.error("exception in asynchronous operation", exc_info=True) sys.exit(1) class TornadoGor(Gor): def __init__(self, *args, **kwargs): super(TornadoGor, self).__init__(*args, **kwargs) self.q = queues.Queue() self.concurrency = kwargs.get('concurrency', 2) @gen.coroutine def _process(self): line = yield self.q.get() try: msg = self.parse_message(line) if msg: self.emit(msg, line) finally: self.q.task_done() @gen.coroutine def _worker(self): while True: yield self._process() @gen.coroutine def _run(self): for _ in range(self.concurrency): self._worker() while True: try: line = sys.stdin.readline() except KeyboardInterrupt: ioloop.IOLoop.instance().stop() break self.q.put(line) yield def run(self): with StackContext(die_on_error): self.io_loop = ioloop.IOLoop.current() self.io_loop.run_sync(self._run) sys.exit(errno.EINTR)
Exit as soon as KeyboardInterrupt catched
Exit as soon as KeyboardInterrupt catched
Python
mit
amyangfei/GorMW
- import os, sys + import sys + import errno + import logging from .base import Gor from tornado import gen, ioloop, queues + + + import contextlib + from tornado.stack_context import StackContext + + @contextlib.contextmanager + def die_on_error(): + try: + yield + except Exception: + logging.error("exception in asynchronous operation", exc_info=True) + sys.exit(1) class TornadoGor(Gor): def __init__(self, *args, **kwargs): super(TornadoGor, self).__init__(*args, **kwargs) self.q = queues.Queue() self.concurrency = kwargs.get('concurrency', 2) @gen.coroutine def _process(self): line = yield self.q.get() try: msg = self.parse_message(line) if msg: self.emit(msg, line) finally: self.q.task_done() @gen.coroutine def _worker(self): while True: yield self._process() @gen.coroutine def _run(self): for _ in range(self.concurrency): self._worker() while True: try: line = sys.stdin.readline() except KeyboardInterrupt: + ioloop.IOLoop.instance().stop() - try: + break - sys.exit(0) - except SystemExit: - os._exit(0) self.q.put(line) yield def run(self): + with StackContext(die_on_error): - self.io_loop = ioloop.IOLoop.current() + self.io_loop = ioloop.IOLoop.current() - self.io_loop.run_sync(self._run) + self.io_loop.run_sync(self._run) + sys.exit(errno.EINTR)
Exit as soon as KeyboardInterrupt catched
## Code Before: import os, sys from .base import Gor from tornado import gen, ioloop, queues class TornadoGor(Gor): def __init__(self, *args, **kwargs): super(TornadoGor, self).__init__(*args, **kwargs) self.q = queues.Queue() self.concurrency = kwargs.get('concurrency', 2) @gen.coroutine def _process(self): line = yield self.q.get() try: msg = self.parse_message(line) if msg: self.emit(msg, line) finally: self.q.task_done() @gen.coroutine def _worker(self): while True: yield self._process() @gen.coroutine def _run(self): for _ in range(self.concurrency): self._worker() while True: try: line = sys.stdin.readline() except KeyboardInterrupt: try: sys.exit(0) except SystemExit: os._exit(0) self.q.put(line) yield def run(self): self.io_loop = ioloop.IOLoop.current() self.io_loop.run_sync(self._run) ## Instruction: Exit as soon as KeyboardInterrupt catched ## Code After: import sys import errno import logging from .base import Gor from tornado import gen, ioloop, queues import contextlib from tornado.stack_context import StackContext @contextlib.contextmanager def die_on_error(): try: yield except Exception: logging.error("exception in asynchronous operation", exc_info=True) sys.exit(1) class TornadoGor(Gor): def __init__(self, *args, **kwargs): super(TornadoGor, self).__init__(*args, **kwargs) self.q = queues.Queue() self.concurrency = kwargs.get('concurrency', 2) @gen.coroutine def _process(self): line = yield self.q.get() try: msg = self.parse_message(line) if msg: self.emit(msg, line) finally: self.q.task_done() @gen.coroutine def _worker(self): while True: yield self._process() @gen.coroutine def _run(self): for _ in range(self.concurrency): self._worker() while True: try: line = sys.stdin.readline() except KeyboardInterrupt: ioloop.IOLoop.instance().stop() break self.q.put(line) yield def run(self): with StackContext(die_on_error): self.io_loop = ioloop.IOLoop.current() self.io_loop.run_sync(self._run) sys.exit(errno.EINTR)
# ... existing code ... import sys import errno import logging from .base import Gor # ... modified code ... from tornado import gen, ioloop, queues import contextlib from tornado.stack_context import StackContext @contextlib.contextmanager def die_on_error(): try: yield except Exception: logging.error("exception in asynchronous operation", exc_info=True) sys.exit(1) ... line = sys.stdin.readline() except KeyboardInterrupt: ioloop.IOLoop.instance().stop() break self.q.put(line) yield ... def run(self): with StackContext(die_on_error): self.io_loop = ioloop.IOLoop.current() self.io_loop.run_sync(self._run) sys.exit(errno.EINTR) # ... rest of the code ...
6cb38efab37f8953c8ba56662ba512af0f84432f
tests/semver_test.py
tests/semver_test.py
from unittest import TestCase from semver import compare from semver import match from semver import parse class TestSemver(TestCase): def test_should_parse_version(self): self.assertEquals( parse("1.2.3-alpha.1.2+build.11.e0f985a"), {'major': 1, 'minor': 2, 'patch': 3, 'prerelease': 'alpha.1.2', 'build': 'build.11.e0f985a'}) def test_should_get_less(self): self.assertEquals( compare("1.0.0", "2.0.0"), -1) def test_should_get_greater(self): self.assertEquals( compare("2.0.0", "1.0.0"), 1) def test_should_match_simple(self): self.assertEquals( match("2.3.7", ">=2.3.6"), True) def test_should_no_match_simple(self): self.assertEquals( match("2.3.7", ">=2.3.8"), False)
from unittest import TestCase from semver import compare from semver import match from semver import parse class TestSemver(TestCase): def test_should_parse_version(self): self.assertEquals( parse("1.2.3-alpha.1.2+build.11.e0f985a"), {'major': 1, 'minor': 2, 'patch': 3, 'prerelease': 'alpha.1.2', 'build': 'build.11.e0f985a'}) def test_should_get_less(self): self.assertEquals( compare("1.0.0", "2.0.0"), -1) def test_should_get_greater(self): self.assertEquals( compare("2.0.0", "1.0.0"), 1) def test_should_match_simple(self): self.assertEquals( match("2.3.7", ">=2.3.6"), True) def test_should_no_match_simple(self): self.assertEquals( match("2.3.7", ">=2.3.8"), False) def test_should_raise_value_error_for_invalid_value(self): self.assertRaises(ValueError, compare, 'foo', 'bar') self.assertRaises(ValueError, compare, '1.0', '1.0.0') self.assertRaises(ValueError, compare, '1.x', '1.0.0') def test_should_raise_value_error_for_invalid_match_expression(self): self.assertRaises(ValueError, match, '1.0.0', '') self.assertRaises(ValueError, match, '1.0.0', '!') self.assertRaises(ValueError, match, '1.0.0', '1.0.0')
Add tests for error cases that proves incompatibility with Python 2.5 and early versions.
Add tests for error cases that proves incompatibility with Python 2.5 and early versions.
Python
bsd-3-clause
python-semver/python-semver,k-bx/python-semver
from unittest import TestCase - from semver import compare from semver import match from semver import parse class TestSemver(TestCase): def test_should_parse_version(self): self.assertEquals( parse("1.2.3-alpha.1.2+build.11.e0f985a"), {'major': 1, 'minor': 2, 'patch': 3, 'prerelease': 'alpha.1.2', 'build': 'build.11.e0f985a'}) def test_should_get_less(self): self.assertEquals( compare("1.0.0", "2.0.0"), -1) def test_should_get_greater(self): self.assertEquals( compare("2.0.0", "1.0.0"), 1) def test_should_match_simple(self): self.assertEquals( match("2.3.7", ">=2.3.6"), True) def test_should_no_match_simple(self): self.assertEquals( match("2.3.7", ">=2.3.8"), False) + def test_should_raise_value_error_for_invalid_value(self): + self.assertRaises(ValueError, compare, 'foo', 'bar') + self.assertRaises(ValueError, compare, '1.0', '1.0.0') + self.assertRaises(ValueError, compare, '1.x', '1.0.0') + + def test_should_raise_value_error_for_invalid_match_expression(self): + self.assertRaises(ValueError, match, '1.0.0', '') + self.assertRaises(ValueError, match, '1.0.0', '!') + self.assertRaises(ValueError, match, '1.0.0', '1.0.0') +
Add tests for error cases that proves incompatibility with Python 2.5 and early versions.
## Code Before: from unittest import TestCase from semver import compare from semver import match from semver import parse class TestSemver(TestCase): def test_should_parse_version(self): self.assertEquals( parse("1.2.3-alpha.1.2+build.11.e0f985a"), {'major': 1, 'minor': 2, 'patch': 3, 'prerelease': 'alpha.1.2', 'build': 'build.11.e0f985a'}) def test_should_get_less(self): self.assertEquals( compare("1.0.0", "2.0.0"), -1) def test_should_get_greater(self): self.assertEquals( compare("2.0.0", "1.0.0"), 1) def test_should_match_simple(self): self.assertEquals( match("2.3.7", ">=2.3.6"), True) def test_should_no_match_simple(self): self.assertEquals( match("2.3.7", ">=2.3.8"), False) ## Instruction: Add tests for error cases that proves incompatibility with Python 2.5 and early versions. ## Code After: from unittest import TestCase from semver import compare from semver import match from semver import parse class TestSemver(TestCase): def test_should_parse_version(self): self.assertEquals( parse("1.2.3-alpha.1.2+build.11.e0f985a"), {'major': 1, 'minor': 2, 'patch': 3, 'prerelease': 'alpha.1.2', 'build': 'build.11.e0f985a'}) def test_should_get_less(self): self.assertEquals( compare("1.0.0", "2.0.0"), -1) def test_should_get_greater(self): self.assertEquals( compare("2.0.0", "1.0.0"), 1) def test_should_match_simple(self): self.assertEquals( match("2.3.7", ">=2.3.6"), True) def test_should_no_match_simple(self): self.assertEquals( match("2.3.7", ">=2.3.8"), False) def test_should_raise_value_error_for_invalid_value(self): self.assertRaises(ValueError, compare, 'foo', 'bar') self.assertRaises(ValueError, compare, '1.0', '1.0.0') self.assertRaises(ValueError, compare, '1.x', '1.0.0') def test_should_raise_value_error_for_invalid_match_expression(self): self.assertRaises(ValueError, match, '1.0.0', '') self.assertRaises(ValueError, match, '1.0.0', '!') self.assertRaises(ValueError, match, '1.0.0', '1.0.0')
... from unittest import TestCase from semver import compare from semver import match ... match("2.3.7", ">=2.3.8"), False) def test_should_raise_value_error_for_invalid_value(self): self.assertRaises(ValueError, compare, 'foo', 'bar') self.assertRaises(ValueError, compare, '1.0', '1.0.0') self.assertRaises(ValueError, compare, '1.x', '1.0.0') def test_should_raise_value_error_for_invalid_match_expression(self): self.assertRaises(ValueError, match, '1.0.0', '') self.assertRaises(ValueError, match, '1.0.0', '!') self.assertRaises(ValueError, match, '1.0.0', '1.0.0') ...
e05093338c6c2fa155ea4ffe102bb6fa9a9b5e0e
__init__.py
__init__.py
import spyral.memoize import spyral.point import spyral.camera import spyral.util import spyral.sprite import spyral.gui import spyral.scene import spyral._lib import spyral.event import pygame director = scene.Director() def init(): pygame.init() pygame.font.init() def quit(): pygame.quit() spyral.director._stack = []
__version__ = '0.1' __license__ = 'LGPLv2' __author__ = 'Robert Deaton' import spyral.memoize import spyral.point import spyral.camera import spyral.util import spyral.sprite import spyral.gui import spyral.scene import spyral._lib import spyral.event import pygame director = scene.Director() def init(): pygame.init() pygame.font.init() def quit(): pygame.quit() spyral.director._stack = []
Make this more like a real python module.
Make this more like a real python module.
Python
lgpl-2.1
platipy/spyral
+ + __version__ = '0.1' + __license__ = 'LGPLv2' + __author__ = 'Robert Deaton' + import spyral.memoize import spyral.point import spyral.camera import spyral.util import spyral.sprite import spyral.gui import spyral.scene import spyral._lib import spyral.event import pygame director = scene.Director() def init(): pygame.init() pygame.font.init() def quit(): pygame.quit() spyral.director._stack = []
Make this more like a real python module.
## Code Before: import spyral.memoize import spyral.point import spyral.camera import spyral.util import spyral.sprite import spyral.gui import spyral.scene import spyral._lib import spyral.event import pygame director = scene.Director() def init(): pygame.init() pygame.font.init() def quit(): pygame.quit() spyral.director._stack = [] ## Instruction: Make this more like a real python module. ## Code After: __version__ = '0.1' __license__ = 'LGPLv2' __author__ = 'Robert Deaton' import spyral.memoize import spyral.point import spyral.camera import spyral.util import spyral.sprite import spyral.gui import spyral.scene import spyral._lib import spyral.event import pygame director = scene.Director() def init(): pygame.init() pygame.font.init() def quit(): pygame.quit() spyral.director._stack = []
... __version__ = '0.1' __license__ = 'LGPLv2' __author__ = 'Robert Deaton' import spyral.memoize import spyral.point ...
d12fecd2eb012862b8d7654c879dccf5ccce833f
jose/backends/__init__.py
jose/backends/__init__.py
try: from jose.backends.pycrypto_backend import RSAKey except ImportError: from jose.backends.cryptography_backend import CryptographyRSAKey as RSAKey try: from jose.backends.cryptography_backend import CryptographyECKey as ECKey except ImportError: from jose.backends.ecdsa_backend import ECDSAECKey as ECKey
try: from jose.backends.pycrypto_backend import RSAKey except ImportError: try: from jose.backends.cryptography_backend import CryptographyRSAKey as RSAKey except ImportError: from jose.backends.rsa_backend import RSAKey try: from jose.backends.cryptography_backend import CryptographyECKey as ECKey except ImportError: from jose.backends.ecdsa_backend import ECDSAECKey as ECKey
Enable Python RSA backend as a fallback.
Enable Python RSA backend as a fallback.
Python
mit
mpdavis/python-jose
try: from jose.backends.pycrypto_backend import RSAKey except ImportError: + try: - from jose.backends.cryptography_backend import CryptographyRSAKey as RSAKey + from jose.backends.cryptography_backend import CryptographyRSAKey as RSAKey + except ImportError: + from jose.backends.rsa_backend import RSAKey try: from jose.backends.cryptography_backend import CryptographyECKey as ECKey except ImportError: from jose.backends.ecdsa_backend import ECDSAECKey as ECKey
Enable Python RSA backend as a fallback.
## Code Before: try: from jose.backends.pycrypto_backend import RSAKey except ImportError: from jose.backends.cryptography_backend import CryptographyRSAKey as RSAKey try: from jose.backends.cryptography_backend import CryptographyECKey as ECKey except ImportError: from jose.backends.ecdsa_backend import ECDSAECKey as ECKey ## Instruction: Enable Python RSA backend as a fallback. ## Code After: try: from jose.backends.pycrypto_backend import RSAKey except ImportError: try: from jose.backends.cryptography_backend import CryptographyRSAKey as RSAKey except ImportError: from jose.backends.rsa_backend import RSAKey try: from jose.backends.cryptography_backend import CryptographyECKey as ECKey except ImportError: from jose.backends.ecdsa_backend import ECDSAECKey as ECKey
... from jose.backends.pycrypto_backend import RSAKey except ImportError: try: from jose.backends.cryptography_backend import CryptographyRSAKey as RSAKey except ImportError: from jose.backends.rsa_backend import RSAKey try: ...
52f38cd00db200d0520062c27f0d305827edb7d2
eventkit_cloud/auth/models.py
eventkit_cloud/auth/models.py
from django.contrib.auth.models import User,Group from django.db import models from django.contrib.postgres.fields import JSONField from ..core.models import TimeStampedModelMixin, UIDMixin class OAuth(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, blank=False) identification = models.CharField(max_length=200, unique=True, blank=False) commonname = models.CharField(max_length=100, blank=False) user_info = JSONField(default={}) class Meta: # pragma: no cover managed = True db_table = 'auth_oauth' # https://stackoverflow.com/questions/12754024/onetoonefield-and-deleting def delete(self, *args, **kwargs): self.user.delete() return super(self.__class__, self).delete(*args, **kwargs) def __str__(self): return '{0}'.format(self.commonname)
from django.contrib.auth.models import User,Group from django.db import models from django.contrib.postgres.fields import JSONField from ..core.models import TimeStampedModelMixin, UIDMixin class OAuth(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, blank=False) identification = models.CharField(max_length=200, unique=True, blank=False) commonname = models.CharField(max_length=100, blank=False) user_info = JSONField(default={}) class Meta: # pragma: no cover managed = True db_table = 'auth_oauth' def __str__(self): return '{0}'.format(self.commonname)
Revert "adding delete hook so the attached User object is deleted properly when and OAuth object is deleted."
Revert "adding delete hook so the attached User object is deleted properly when and OAuth object is deleted." This reverts commit 4c77c36f447d104f492e320ca684e9a737f2b803.
Python
bsd-3-clause
venicegeo/eventkit-cloud,venicegeo/eventkit-cloud,terranodo/eventkit-cloud,venicegeo/eventkit-cloud,venicegeo/eventkit-cloud,terranodo/eventkit-cloud,venicegeo/eventkit-cloud,terranodo/eventkit-cloud,terranodo/eventkit-cloud,venicegeo/eventkit-cloud
from django.contrib.auth.models import User,Group from django.db import models from django.contrib.postgres.fields import JSONField from ..core.models import TimeStampedModelMixin, UIDMixin class OAuth(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, blank=False) identification = models.CharField(max_length=200, unique=True, blank=False) commonname = models.CharField(max_length=100, blank=False) user_info = JSONField(default={}) class Meta: # pragma: no cover managed = True db_table = 'auth_oauth' - # https://stackoverflow.com/questions/12754024/onetoonefield-and-deleting - def delete(self, *args, **kwargs): - self.user.delete() - return super(self.__class__, self).delete(*args, **kwargs) - def __str__(self): return '{0}'.format(self.commonname)
Revert "adding delete hook so the attached User object is deleted properly when and OAuth object is deleted."
## Code Before: from django.contrib.auth.models import User,Group from django.db import models from django.contrib.postgres.fields import JSONField from ..core.models import TimeStampedModelMixin, UIDMixin class OAuth(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, blank=False) identification = models.CharField(max_length=200, unique=True, blank=False) commonname = models.CharField(max_length=100, blank=False) user_info = JSONField(default={}) class Meta: # pragma: no cover managed = True db_table = 'auth_oauth' # https://stackoverflow.com/questions/12754024/onetoonefield-and-deleting def delete(self, *args, **kwargs): self.user.delete() return super(self.__class__, self).delete(*args, **kwargs) def __str__(self): return '{0}'.format(self.commonname) ## Instruction: Revert "adding delete hook so the attached User object is deleted properly when and OAuth object is deleted." ## Code After: from django.contrib.auth.models import User,Group from django.db import models from django.contrib.postgres.fields import JSONField from ..core.models import TimeStampedModelMixin, UIDMixin class OAuth(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, blank=False) identification = models.CharField(max_length=200, unique=True, blank=False) commonname = models.CharField(max_length=100, blank=False) user_info = JSONField(default={}) class Meta: # pragma: no cover managed = True db_table = 'auth_oauth' def __str__(self): return '{0}'.format(self.commonname)
... db_table = 'auth_oauth' def __str__(self): return '{0}'.format(self.commonname) ...