commit
stringlengths
40
40
old_file
stringlengths
4
118
new_file
stringlengths
4
118
old_contents
stringlengths
0
2.94k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
444
message
stringlengths
16
3.45k
lang
stringclasses
1 value
license
stringclasses
13 values
repos
stringlengths
5
43.2k
prompt
stringlengths
17
4.58k
response
stringlengths
1
4.43k
prompt_tagged
stringlengths
58
4.62k
response_tagged
stringlengths
1
4.43k
text
stringlengths
132
7.29k
text_tagged
stringlengths
173
7.33k
4f8267c0d3bc24c60c1236fda4dc83ee975361c8
us_ignite/events/tests/managers_tests.py
us_ignite/events/tests/managers_tests.py
from nose.tools import eq_ from django.contrib.auth.models import User from django.test import TestCase from us_ignite.events.tests import fixtures from us_ignite.events.models import Event from us_ignite.profiles.tests.fixtures import get_user class TestEventPublishedManager(TestCase): def tearDown(self): for model in [User]: model.objects.all().delete() def test_published_events_are_shown(self): user = get_user('ignite-user') event = fixtures.get_event(user=user, status=Event.PUBLISHED) eq_(list(Event.published.all()), [event]) def test_unpublished_events_are_not_shown(self): user = get_user('ignite-user') event = fixtures.get_event(user=user, status=Event.DRAFT) eq_(list(Event.published.all()), [])
from nose.tools import eq_ from django.contrib.auth.models import User from django.test import TestCase from us_ignite.events.tests import fixtures from us_ignite.events.models import Event from us_ignite.profiles.tests.fixtures import get_user class TestEventPublishedManager(TestCase): def tearDown(self): for model in [Event, User]: model.objects.all().delete() def test_published_events_are_shown(self): user = get_user('ignite-user') event = fixtures.get_event(user=user, status=Event.PUBLISHED) eq_(list(Event.published.all()), [event]) def test_unpublished_events_are_not_shown(self): user = get_user('ignite-user') event = fixtures.get_event(user=user, status=Event.DRAFT) eq_(list(Event.published.all()), [])
Clean up model data after tests have been executed.
Clean up model data after tests have been executed.
Python
bsd-3-clause
us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite
from nose.tools import eq_ from django.contrib.auth.models import User from django.test import TestCase from us_ignite.events.tests import fixtures from us_ignite.events.models import Event from us_ignite.profiles.tests.fixtures import get_user class TestEventPublishedManager(TestCase): def tearDown(self): for model in [User]: model.objects.all().delete() def test_published_events_are_shown(self): user = get_user('ignite-user') event = fixtures.get_event(user=user, status=Event.PUBLISHED) eq_(list(Event.published.all()), [event]) def test_unpublished_events_are_not_shown(self): user = get_user('ignite-user') event = fixtures.get_event(user=user, status=Event.DRAFT) eq_(list(Event.published.all()), []) Clean up model data after tests have been executed.
from nose.tools import eq_ from django.contrib.auth.models import User from django.test import TestCase from us_ignite.events.tests import fixtures from us_ignite.events.models import Event from us_ignite.profiles.tests.fixtures import get_user class TestEventPublishedManager(TestCase): def tearDown(self): for model in [Event, User]: model.objects.all().delete() def test_published_events_are_shown(self): user = get_user('ignite-user') event = fixtures.get_event(user=user, status=Event.PUBLISHED) eq_(list(Event.published.all()), [event]) def test_unpublished_events_are_not_shown(self): user = get_user('ignite-user') event = fixtures.get_event(user=user, status=Event.DRAFT) eq_(list(Event.published.all()), [])
<commit_before>from nose.tools import eq_ from django.contrib.auth.models import User from django.test import TestCase from us_ignite.events.tests import fixtures from us_ignite.events.models import Event from us_ignite.profiles.tests.fixtures import get_user class TestEventPublishedManager(TestCase): def tearDown(self): for model in [User]: model.objects.all().delete() def test_published_events_are_shown(self): user = get_user('ignite-user') event = fixtures.get_event(user=user, status=Event.PUBLISHED) eq_(list(Event.published.all()), [event]) def test_unpublished_events_are_not_shown(self): user = get_user('ignite-user') event = fixtures.get_event(user=user, status=Event.DRAFT) eq_(list(Event.published.all()), []) <commit_msg>Clean up model data after tests have been executed.<commit_after>
from nose.tools import eq_ from django.contrib.auth.models import User from django.test import TestCase from us_ignite.events.tests import fixtures from us_ignite.events.models import Event from us_ignite.profiles.tests.fixtures import get_user class TestEventPublishedManager(TestCase): def tearDown(self): for model in [Event, User]: model.objects.all().delete() def test_published_events_are_shown(self): user = get_user('ignite-user') event = fixtures.get_event(user=user, status=Event.PUBLISHED) eq_(list(Event.published.all()), [event]) def test_unpublished_events_are_not_shown(self): user = get_user('ignite-user') event = fixtures.get_event(user=user, status=Event.DRAFT) eq_(list(Event.published.all()), [])
from nose.tools import eq_ from django.contrib.auth.models import User from django.test import TestCase from us_ignite.events.tests import fixtures from us_ignite.events.models import Event from us_ignite.profiles.tests.fixtures import get_user class TestEventPublishedManager(TestCase): def tearDown(self): for model in [User]: model.objects.all().delete() def test_published_events_are_shown(self): user = get_user('ignite-user') event = fixtures.get_event(user=user, status=Event.PUBLISHED) eq_(list(Event.published.all()), [event]) def test_unpublished_events_are_not_shown(self): user = get_user('ignite-user') event = fixtures.get_event(user=user, status=Event.DRAFT) eq_(list(Event.published.all()), []) Clean up model data after tests have been executed.from nose.tools import eq_ from django.contrib.auth.models import User from django.test import TestCase from us_ignite.events.tests import fixtures from us_ignite.events.models import Event from us_ignite.profiles.tests.fixtures import get_user class TestEventPublishedManager(TestCase): def tearDown(self): for model in [Event, User]: model.objects.all().delete() def test_published_events_are_shown(self): user = get_user('ignite-user') event = fixtures.get_event(user=user, status=Event.PUBLISHED) eq_(list(Event.published.all()), [event]) def test_unpublished_events_are_not_shown(self): user = get_user('ignite-user') event = fixtures.get_event(user=user, status=Event.DRAFT) eq_(list(Event.published.all()), [])
<commit_before>from nose.tools import eq_ from django.contrib.auth.models import User from django.test import TestCase from us_ignite.events.tests import fixtures from us_ignite.events.models import Event from us_ignite.profiles.tests.fixtures import get_user class TestEventPublishedManager(TestCase): def tearDown(self): for model in [User]: model.objects.all().delete() def test_published_events_are_shown(self): user = get_user('ignite-user') event = fixtures.get_event(user=user, status=Event.PUBLISHED) eq_(list(Event.published.all()), [event]) def test_unpublished_events_are_not_shown(self): user = get_user('ignite-user') event = fixtures.get_event(user=user, status=Event.DRAFT) eq_(list(Event.published.all()), []) <commit_msg>Clean up model data after tests have been executed.<commit_after>from nose.tools import eq_ from django.contrib.auth.models import User from django.test import TestCase from us_ignite.events.tests import fixtures from us_ignite.events.models import Event from us_ignite.profiles.tests.fixtures import get_user class TestEventPublishedManager(TestCase): def tearDown(self): for model in [Event, User]: model.objects.all().delete() def test_published_events_are_shown(self): user = get_user('ignite-user') event = fixtures.get_event(user=user, status=Event.PUBLISHED) eq_(list(Event.published.all()), [event]) def test_unpublished_events_are_not_shown(self): user = get_user('ignite-user') event = fixtures.get_event(user=user, status=Event.DRAFT) eq_(list(Event.published.all()), [])
5a9f027bb3e660cd0146c4483c70e54a76332048
makerscience_profile/api.py
makerscience_profile/api.py
from .models import MakerScienceProfile from tastypie.resources import ModelResource from tastypie.authorization import DjangoAuthorization from tastypie import fields from tastypie.constants import ALL_WITH_RELATIONS from dataserver.authentication import AnonymousApiKeyAuthentication from accounts.api import ProfileResource from scout.api import PostalAddressResource class MakerScienceProfileResource(ModelResource): parent = fields.OneToOneField(ProfileResource, 'parent') location = fields.ToOneField(PostalAddressResource, 'location', null=True, blank=True) class Meta: queryset = MakerScienceProfile.objects.all() allowed_methods = ['get', 'post', 'put', 'patch'] resource_name = 'makerscience/profile' authentication = AnonymousApiKeyAuthentication() authorization = DjangoAuthorization() always_return_data = True filtering = { 'parent' : ALL_WITH_RELATIONS, } def dehydrate(self, bundle): bundle.data["first_name"] = bundle.obj.parent.user.first_name bundle.data["last_name"] = bundle.obj.parent.user.last_name return bundle
from .models import MakerScienceProfile from tastypie.resources import ModelResource from tastypie.authorization import DjangoAuthorization from tastypie import fields from tastypie.constants import ALL_WITH_RELATIONS from dataserver.authentication import AnonymousApiKeyAuthentication from accounts.api import ProfileResource from scout.api import PostalAddressResource class MakerScienceProfileResource(ModelResource): parent = fields.OneToOneField(ProfileResource, 'parent') location = fields.ToOneField(PostalAddressResource, 'location', null=True, blank=True, full=True) class Meta: queryset = MakerScienceProfile.objects.all() allowed_methods = ['get', 'post', 'put', 'patch'] resource_name = 'makerscience/profile' authentication = AnonymousApiKeyAuthentication() authorization = DjangoAuthorization() always_return_data = True filtering = { 'parent' : ALL_WITH_RELATIONS, } def dehydrate(self, bundle): bundle.data["first_name"] = bundle.obj.parent.user.first_name bundle.data["last_name"] = bundle.obj.parent.user.last_name return bundle
Enable full location for profile
Enable full location for profile
Python
agpl-3.0
atiberghien/makerscience-server,atiberghien/makerscience-server
from .models import MakerScienceProfile from tastypie.resources import ModelResource from tastypie.authorization import DjangoAuthorization from tastypie import fields from tastypie.constants import ALL_WITH_RELATIONS from dataserver.authentication import AnonymousApiKeyAuthentication from accounts.api import ProfileResource from scout.api import PostalAddressResource class MakerScienceProfileResource(ModelResource): parent = fields.OneToOneField(ProfileResource, 'parent') location = fields.ToOneField(PostalAddressResource, 'location', null=True, blank=True) class Meta: queryset = MakerScienceProfile.objects.all() allowed_methods = ['get', 'post', 'put', 'patch'] resource_name = 'makerscience/profile' authentication = AnonymousApiKeyAuthentication() authorization = DjangoAuthorization() always_return_data = True filtering = { 'parent' : ALL_WITH_RELATIONS, } def dehydrate(self, bundle): bundle.data["first_name"] = bundle.obj.parent.user.first_name bundle.data["last_name"] = bundle.obj.parent.user.last_name return bundleEnable full location for profile
from .models import MakerScienceProfile from tastypie.resources import ModelResource from tastypie.authorization import DjangoAuthorization from tastypie import fields from tastypie.constants import ALL_WITH_RELATIONS from dataserver.authentication import AnonymousApiKeyAuthentication from accounts.api import ProfileResource from scout.api import PostalAddressResource class MakerScienceProfileResource(ModelResource): parent = fields.OneToOneField(ProfileResource, 'parent') location = fields.ToOneField(PostalAddressResource, 'location', null=True, blank=True, full=True) class Meta: queryset = MakerScienceProfile.objects.all() allowed_methods = ['get', 'post', 'put', 'patch'] resource_name = 'makerscience/profile' authentication = AnonymousApiKeyAuthentication() authorization = DjangoAuthorization() always_return_data = True filtering = { 'parent' : ALL_WITH_RELATIONS, } def dehydrate(self, bundle): bundle.data["first_name"] = bundle.obj.parent.user.first_name bundle.data["last_name"] = bundle.obj.parent.user.last_name return bundle
<commit_before>from .models import MakerScienceProfile from tastypie.resources import ModelResource from tastypie.authorization import DjangoAuthorization from tastypie import fields from tastypie.constants import ALL_WITH_RELATIONS from dataserver.authentication import AnonymousApiKeyAuthentication from accounts.api import ProfileResource from scout.api import PostalAddressResource class MakerScienceProfileResource(ModelResource): parent = fields.OneToOneField(ProfileResource, 'parent') location = fields.ToOneField(PostalAddressResource, 'location', null=True, blank=True) class Meta: queryset = MakerScienceProfile.objects.all() allowed_methods = ['get', 'post', 'put', 'patch'] resource_name = 'makerscience/profile' authentication = AnonymousApiKeyAuthentication() authorization = DjangoAuthorization() always_return_data = True filtering = { 'parent' : ALL_WITH_RELATIONS, } def dehydrate(self, bundle): bundle.data["first_name"] = bundle.obj.parent.user.first_name bundle.data["last_name"] = bundle.obj.parent.user.last_name return bundle<commit_msg>Enable full location for profile<commit_after>
from .models import MakerScienceProfile from tastypie.resources import ModelResource from tastypie.authorization import DjangoAuthorization from tastypie import fields from tastypie.constants import ALL_WITH_RELATIONS from dataserver.authentication import AnonymousApiKeyAuthentication from accounts.api import ProfileResource from scout.api import PostalAddressResource class MakerScienceProfileResource(ModelResource): parent = fields.OneToOneField(ProfileResource, 'parent') location = fields.ToOneField(PostalAddressResource, 'location', null=True, blank=True, full=True) class Meta: queryset = MakerScienceProfile.objects.all() allowed_methods = ['get', 'post', 'put', 'patch'] resource_name = 'makerscience/profile' authentication = AnonymousApiKeyAuthentication() authorization = DjangoAuthorization() always_return_data = True filtering = { 'parent' : ALL_WITH_RELATIONS, } def dehydrate(self, bundle): bundle.data["first_name"] = bundle.obj.parent.user.first_name bundle.data["last_name"] = bundle.obj.parent.user.last_name return bundle
from .models import MakerScienceProfile from tastypie.resources import ModelResource from tastypie.authorization import DjangoAuthorization from tastypie import fields from tastypie.constants import ALL_WITH_RELATIONS from dataserver.authentication import AnonymousApiKeyAuthentication from accounts.api import ProfileResource from scout.api import PostalAddressResource class MakerScienceProfileResource(ModelResource): parent = fields.OneToOneField(ProfileResource, 'parent') location = fields.ToOneField(PostalAddressResource, 'location', null=True, blank=True) class Meta: queryset = MakerScienceProfile.objects.all() allowed_methods = ['get', 'post', 'put', 'patch'] resource_name = 'makerscience/profile' authentication = AnonymousApiKeyAuthentication() authorization = DjangoAuthorization() always_return_data = True filtering = { 'parent' : ALL_WITH_RELATIONS, } def dehydrate(self, bundle): bundle.data["first_name"] = bundle.obj.parent.user.first_name bundle.data["last_name"] = bundle.obj.parent.user.last_name return bundleEnable full location for profilefrom .models import MakerScienceProfile from tastypie.resources import ModelResource from tastypie.authorization import DjangoAuthorization from tastypie import fields from tastypie.constants import ALL_WITH_RELATIONS from dataserver.authentication import AnonymousApiKeyAuthentication from accounts.api import ProfileResource from scout.api import PostalAddressResource class MakerScienceProfileResource(ModelResource): parent = fields.OneToOneField(ProfileResource, 'parent') location = fields.ToOneField(PostalAddressResource, 'location', null=True, blank=True, full=True) class Meta: queryset = MakerScienceProfile.objects.all() allowed_methods = ['get', 'post', 'put', 'patch'] resource_name = 'makerscience/profile' authentication = AnonymousApiKeyAuthentication() authorization = DjangoAuthorization() always_return_data = True filtering = { 'parent' : ALL_WITH_RELATIONS, } def dehydrate(self, bundle): bundle.data["first_name"] = bundle.obj.parent.user.first_name bundle.data["last_name"] = bundle.obj.parent.user.last_name return bundle
<commit_before>from .models import MakerScienceProfile from tastypie.resources import ModelResource from tastypie.authorization import DjangoAuthorization from tastypie import fields from tastypie.constants import ALL_WITH_RELATIONS from dataserver.authentication import AnonymousApiKeyAuthentication from accounts.api import ProfileResource from scout.api import PostalAddressResource class MakerScienceProfileResource(ModelResource): parent = fields.OneToOneField(ProfileResource, 'parent') location = fields.ToOneField(PostalAddressResource, 'location', null=True, blank=True) class Meta: queryset = MakerScienceProfile.objects.all() allowed_methods = ['get', 'post', 'put', 'patch'] resource_name = 'makerscience/profile' authentication = AnonymousApiKeyAuthentication() authorization = DjangoAuthorization() always_return_data = True filtering = { 'parent' : ALL_WITH_RELATIONS, } def dehydrate(self, bundle): bundle.data["first_name"] = bundle.obj.parent.user.first_name bundle.data["last_name"] = bundle.obj.parent.user.last_name return bundle<commit_msg>Enable full location for profile<commit_after>from .models import MakerScienceProfile from tastypie.resources import ModelResource from tastypie.authorization import DjangoAuthorization from tastypie import fields from tastypie.constants import ALL_WITH_RELATIONS from dataserver.authentication import AnonymousApiKeyAuthentication from accounts.api import ProfileResource from scout.api import PostalAddressResource class MakerScienceProfileResource(ModelResource): parent = fields.OneToOneField(ProfileResource, 'parent') location = fields.ToOneField(PostalAddressResource, 'location', null=True, blank=True, full=True) class Meta: queryset = MakerScienceProfile.objects.all() allowed_methods = ['get', 'post', 'put', 'patch'] resource_name = 'makerscience/profile' authentication = AnonymousApiKeyAuthentication() authorization = DjangoAuthorization() always_return_data = True filtering = { 'parent' : ALL_WITH_RELATIONS, } def dehydrate(self, bundle): bundle.data["first_name"] = bundle.obj.parent.user.first_name bundle.data["last_name"] = bundle.obj.parent.user.last_name return bundle
58f982d01a7c47a12a7ae600c2ca17cb6c5c7ed9
monitor/runner.py
monitor/runner.py
from time import sleep from monitor.camera import Camera from monitor.plotter_pygame import PyGamePlotter def run(plotter, camera): while True: plotter.show(camera.get_image_data()) sleep(1.0) if __name__ == "main": cam_ioc = "X1-CAM" plo = PyGamePlotter() cam = Camera(cam_ioc) run(plo, cam)
import sys from time import sleep from camera import Camera from plotter_pygame import PyGamePlotter def run(plotter, camera): old_timestamp = -1 while True: data, timestamp = camera.get_image_data() if timestamp != old_timestamp: plotter.show(data) old_timestamp = timestamp sleep(1.0) if __name__ == "__main__": cam_ioc = sys.argv[1] # "X1-CAM" cam = Camera(cam_ioc) plo = PyGamePlotter() plo.set_screensize(cam.xsize, cam.ysize) run(plo, cam)
Update to set screensize and take camera IOC as arg
Update to set screensize and take camera IOC as arg
Python
apache-2.0
nickbattam/picamon,nickbattam/picamon,nickbattam/picamon,nickbattam/picamon
from time import sleep from monitor.camera import Camera from monitor.plotter_pygame import PyGamePlotter def run(plotter, camera): while True: plotter.show(camera.get_image_data()) sleep(1.0) if __name__ == "main": cam_ioc = "X1-CAM" plo = PyGamePlotter() cam = Camera(cam_ioc) run(plo, cam) Update to set screensize and take camera IOC as arg
import sys from time import sleep from camera import Camera from plotter_pygame import PyGamePlotter def run(plotter, camera): old_timestamp = -1 while True: data, timestamp = camera.get_image_data() if timestamp != old_timestamp: plotter.show(data) old_timestamp = timestamp sleep(1.0) if __name__ == "__main__": cam_ioc = sys.argv[1] # "X1-CAM" cam = Camera(cam_ioc) plo = PyGamePlotter() plo.set_screensize(cam.xsize, cam.ysize) run(plo, cam)
<commit_before>from time import sleep from monitor.camera import Camera from monitor.plotter_pygame import PyGamePlotter def run(plotter, camera): while True: plotter.show(camera.get_image_data()) sleep(1.0) if __name__ == "main": cam_ioc = "X1-CAM" plo = PyGamePlotter() cam = Camera(cam_ioc) run(plo, cam) <commit_msg>Update to set screensize and take camera IOC as arg<commit_after>
import sys from time import sleep from camera import Camera from plotter_pygame import PyGamePlotter def run(plotter, camera): old_timestamp = -1 while True: data, timestamp = camera.get_image_data() if timestamp != old_timestamp: plotter.show(data) old_timestamp = timestamp sleep(1.0) if __name__ == "__main__": cam_ioc = sys.argv[1] # "X1-CAM" cam = Camera(cam_ioc) plo = PyGamePlotter() plo.set_screensize(cam.xsize, cam.ysize) run(plo, cam)
from time import sleep from monitor.camera import Camera from monitor.plotter_pygame import PyGamePlotter def run(plotter, camera): while True: plotter.show(camera.get_image_data()) sleep(1.0) if __name__ == "main": cam_ioc = "X1-CAM" plo = PyGamePlotter() cam = Camera(cam_ioc) run(plo, cam) Update to set screensize and take camera IOC as argimport sys from time import sleep from camera import Camera from plotter_pygame import PyGamePlotter def run(plotter, camera): old_timestamp = -1 while True: data, timestamp = camera.get_image_data() if timestamp != old_timestamp: plotter.show(data) old_timestamp = timestamp sleep(1.0) if __name__ == "__main__": cam_ioc = sys.argv[1] # "X1-CAM" cam = Camera(cam_ioc) plo = PyGamePlotter() plo.set_screensize(cam.xsize, cam.ysize) run(plo, cam)
<commit_before>from time import sleep from monitor.camera import Camera from monitor.plotter_pygame import PyGamePlotter def run(plotter, camera): while True: plotter.show(camera.get_image_data()) sleep(1.0) if __name__ == "main": cam_ioc = "X1-CAM" plo = PyGamePlotter() cam = Camera(cam_ioc) run(plo, cam) <commit_msg>Update to set screensize and take camera IOC as arg<commit_after>import sys from time import sleep from camera import Camera from plotter_pygame import PyGamePlotter def run(plotter, camera): old_timestamp = -1 while True: data, timestamp = camera.get_image_data() if timestamp != old_timestamp: plotter.show(data) old_timestamp = timestamp sleep(1.0) if __name__ == "__main__": cam_ioc = sys.argv[1] # "X1-CAM" cam = Camera(cam_ioc) plo = PyGamePlotter() plo.set_screensize(cam.xsize, cam.ysize) run(plo, cam)
2917f396f52eb042f2354f0a7e1d05dd59b819e3
aids/strings/reverse_string.py
aids/strings/reverse_string.py
''' Reverse a string ''' def reverse_string_iterative(string): pass def reverse_string_recursive(string): pass def reverse_string_pythonic(string): return string[::-1]
''' Reverse a string ''' def reverse_string_iterative(string): result = '' for char in range(len(string) - 1, -1 , -1): result += char return result def reverse_string_recursive(string): if string: return reverse_string_recursive(string[1:]) + string[0] return '' def reverse_string_pythonic(string): return string[::-1]
Add iterative and recursive solutions to reverse strings
Add iterative and recursive solutions to reverse strings
Python
mit
ueg1990/aids
''' Reverse a string ''' def reverse_string_iterative(string): pass def reverse_string_recursive(string): pass def reverse_string_pythonic(string): return string[::-1]Add iterative and recursive solutions to reverse strings
''' Reverse a string ''' def reverse_string_iterative(string): result = '' for char in range(len(string) - 1, -1 , -1): result += char return result def reverse_string_recursive(string): if string: return reverse_string_recursive(string[1:]) + string[0] return '' def reverse_string_pythonic(string): return string[::-1]
<commit_before>''' Reverse a string ''' def reverse_string_iterative(string): pass def reverse_string_recursive(string): pass def reverse_string_pythonic(string): return string[::-1]<commit_msg>Add iterative and recursive solutions to reverse strings<commit_after>
''' Reverse a string ''' def reverse_string_iterative(string): result = '' for char in range(len(string) - 1, -1 , -1): result += char return result def reverse_string_recursive(string): if string: return reverse_string_recursive(string[1:]) + string[0] return '' def reverse_string_pythonic(string): return string[::-1]
''' Reverse a string ''' def reverse_string_iterative(string): pass def reverse_string_recursive(string): pass def reverse_string_pythonic(string): return string[::-1]Add iterative and recursive solutions to reverse strings''' Reverse a string ''' def reverse_string_iterative(string): result = '' for char in range(len(string) - 1, -1 , -1): result += char return result def reverse_string_recursive(string): if string: return reverse_string_recursive(string[1:]) + string[0] return '' def reverse_string_pythonic(string): return string[::-1]
<commit_before>''' Reverse a string ''' def reverse_string_iterative(string): pass def reverse_string_recursive(string): pass def reverse_string_pythonic(string): return string[::-1]<commit_msg>Add iterative and recursive solutions to reverse strings<commit_after>''' Reverse a string ''' def reverse_string_iterative(string): result = '' for char in range(len(string) - 1, -1 , -1): result += char return result def reverse_string_recursive(string): if string: return reverse_string_recursive(string[1:]) + string[0] return '' def reverse_string_pythonic(string): return string[::-1]
8af5aaee0aad575c9f1039a2943aff986a501747
tests/manage.py
tests/manage.py
#!/usr/bin/env python import channels.log import logging import os import sys PROJECT_ROOT = os.path.dirname(os.path.abspath(os.path.dirname(__file__))) sys.path.insert(0, PROJECT_ROOT) def get_channels_logger(*args, **kwargs): """Return logger for channels.""" return logging.getLogger("django.channels") # Force channels to respect logging configurations from settings: # https://github.com/django/channels/issues/520 channels.log.setup_logger = get_channels_logger if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tests.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
#!/usr/bin/env python import logging import os import sys PROJECT_ROOT = os.path.dirname(os.path.abspath(os.path.dirname(__file__))) sys.path.insert(0, PROJECT_ROOT) if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tests.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
Fix logging compatibility with the latest Channels
Fix logging compatibility with the latest Channels
Python
apache-2.0
genialis/resolwe-bio,genialis/resolwe-bio,genialis/resolwe-bio,genialis/resolwe-bio
#!/usr/bin/env python import channels.log import logging import os import sys PROJECT_ROOT = os.path.dirname(os.path.abspath(os.path.dirname(__file__))) sys.path.insert(0, PROJECT_ROOT) def get_channels_logger(*args, **kwargs): """Return logger for channels.""" return logging.getLogger("django.channels") # Force channels to respect logging configurations from settings: # https://github.com/django/channels/issues/520 channels.log.setup_logger = get_channels_logger if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tests.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) Fix logging compatibility with the latest Channels
#!/usr/bin/env python import logging import os import sys PROJECT_ROOT = os.path.dirname(os.path.abspath(os.path.dirname(__file__))) sys.path.insert(0, PROJECT_ROOT) if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tests.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
<commit_before>#!/usr/bin/env python import channels.log import logging import os import sys PROJECT_ROOT = os.path.dirname(os.path.abspath(os.path.dirname(__file__))) sys.path.insert(0, PROJECT_ROOT) def get_channels_logger(*args, **kwargs): """Return logger for channels.""" return logging.getLogger("django.channels") # Force channels to respect logging configurations from settings: # https://github.com/django/channels/issues/520 channels.log.setup_logger = get_channels_logger if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tests.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) <commit_msg>Fix logging compatibility with the latest Channels<commit_after>
#!/usr/bin/env python import logging import os import sys PROJECT_ROOT = os.path.dirname(os.path.abspath(os.path.dirname(__file__))) sys.path.insert(0, PROJECT_ROOT) if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tests.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
#!/usr/bin/env python import channels.log import logging import os import sys PROJECT_ROOT = os.path.dirname(os.path.abspath(os.path.dirname(__file__))) sys.path.insert(0, PROJECT_ROOT) def get_channels_logger(*args, **kwargs): """Return logger for channels.""" return logging.getLogger("django.channels") # Force channels to respect logging configurations from settings: # https://github.com/django/channels/issues/520 channels.log.setup_logger = get_channels_logger if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tests.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) Fix logging compatibility with the latest Channels#!/usr/bin/env python import logging import os import sys PROJECT_ROOT = os.path.dirname(os.path.abspath(os.path.dirname(__file__))) sys.path.insert(0, PROJECT_ROOT) if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tests.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
<commit_before>#!/usr/bin/env python import channels.log import logging import os import sys PROJECT_ROOT = os.path.dirname(os.path.abspath(os.path.dirname(__file__))) sys.path.insert(0, PROJECT_ROOT) def get_channels_logger(*args, **kwargs): """Return logger for channels.""" return logging.getLogger("django.channels") # Force channels to respect logging configurations from settings: # https://github.com/django/channels/issues/520 channels.log.setup_logger = get_channels_logger if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tests.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) <commit_msg>Fix logging compatibility with the latest Channels<commit_after>#!/usr/bin/env python import logging import os import sys PROJECT_ROOT = os.path.dirname(os.path.abspath(os.path.dirname(__file__))) sys.path.insert(0, PROJECT_ROOT) if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tests.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
f4695f43e9eae5740efc303374c892850dfea1a2
trade_server.py
trade_server.py
import json import threading import socket import SocketServer from orderbook import asks, bids class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler): def handle(self): try: while True: data = self.request.recv(1024) if data: response = handle_data(data) cur_thread = threading.current_thread() response = "\n{}: {}".format(cur_thread.name, data) self.request.sendall(response) except socket.error: # Surpress errno 13 Broken Pipe pass class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): pass def create_server(host="localhost", port=0): server = ThreadedTCPServer((host, port), ThreadedTCPRequestHandler) server_thread = threading.Thread(target=server.serve_forever) server_thread.daemon = True server_thread.start() return server def handle_data(data): data = json.loads(data) if data['type'] == 'ask': handle_ask(data) elif data['type'] == 'bid': handle_bid(data) elif data['type'] == 'greeting': handle_greeting(data) def handle_ask(ask): asks.append(ask) def handle_bid(bid): bids.append(bid) def handle_greeting(greeting): pass
import json import threading import socket import SocketServer from orderbook import asks, bids class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler): def handle(self): try: while True: data = self.request.recv(1024) response = '' if data: response += handle_data(data) cur_thread = threading.current_thread() response += "\n{}: {}".format(cur_thread.name, data) self.request.sendall(response) except socket.error: # Surpress errno 13 Broken Pipe pass class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): pass def create_server(host="localhost", port=0): server = ThreadedTCPServer((host, port), ThreadedTCPRequestHandler) server_thread = threading.Thread(target=server.serve_forever) server_thread.daemon = True server_thread.start() return server def handle_data(data): data = json.loads(data) if data['type'] == 'ask': handle_ask(data) elif data['type'] == 'bid': handle_bid(data) elif data['type'] == 'greeting': handle_greeting(data) def handle_ask(ask): asks.append(ask) def handle_bid(bid): bids.append(bid) def handle_greeting(greeting): pass
Fix bugs occuring when no response is given.
Fix bugs occuring when no response is given.
Python
mit
Tribler/decentral-market
import json import threading import socket import SocketServer from orderbook import asks, bids class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler): def handle(self): try: while True: data = self.request.recv(1024) if data: response = handle_data(data) cur_thread = threading.current_thread() response = "\n{}: {}".format(cur_thread.name, data) self.request.sendall(response) except socket.error: # Surpress errno 13 Broken Pipe pass class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): pass def create_server(host="localhost", port=0): server = ThreadedTCPServer((host, port), ThreadedTCPRequestHandler) server_thread = threading.Thread(target=server.serve_forever) server_thread.daemon = True server_thread.start() return server def handle_data(data): data = json.loads(data) if data['type'] == 'ask': handle_ask(data) elif data['type'] == 'bid': handle_bid(data) elif data['type'] == 'greeting': handle_greeting(data) def handle_ask(ask): asks.append(ask) def handle_bid(bid): bids.append(bid) def handle_greeting(greeting): pass Fix bugs occuring when no response is given.
import json import threading import socket import SocketServer from orderbook import asks, bids class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler): def handle(self): try: while True: data = self.request.recv(1024) response = '' if data: response += handle_data(data) cur_thread = threading.current_thread() response += "\n{}: {}".format(cur_thread.name, data) self.request.sendall(response) except socket.error: # Surpress errno 13 Broken Pipe pass class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): pass def create_server(host="localhost", port=0): server = ThreadedTCPServer((host, port), ThreadedTCPRequestHandler) server_thread = threading.Thread(target=server.serve_forever) server_thread.daemon = True server_thread.start() return server def handle_data(data): data = json.loads(data) if data['type'] == 'ask': handle_ask(data) elif data['type'] == 'bid': handle_bid(data) elif data['type'] == 'greeting': handle_greeting(data) def handle_ask(ask): asks.append(ask) def handle_bid(bid): bids.append(bid) def handle_greeting(greeting): pass
<commit_before>import json import threading import socket import SocketServer from orderbook import asks, bids class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler): def handle(self): try: while True: data = self.request.recv(1024) if data: response = handle_data(data) cur_thread = threading.current_thread() response = "\n{}: {}".format(cur_thread.name, data) self.request.sendall(response) except socket.error: # Surpress errno 13 Broken Pipe pass class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): pass def create_server(host="localhost", port=0): server = ThreadedTCPServer((host, port), ThreadedTCPRequestHandler) server_thread = threading.Thread(target=server.serve_forever) server_thread.daemon = True server_thread.start() return server def handle_data(data): data = json.loads(data) if data['type'] == 'ask': handle_ask(data) elif data['type'] == 'bid': handle_bid(data) elif data['type'] == 'greeting': handle_greeting(data) def handle_ask(ask): asks.append(ask) def handle_bid(bid): bids.append(bid) def handle_greeting(greeting): pass <commit_msg>Fix bugs occuring when no response is given.<commit_after>
import json import threading import socket import SocketServer from orderbook import asks, bids class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler): def handle(self): try: while True: data = self.request.recv(1024) response = '' if data: response += handle_data(data) cur_thread = threading.current_thread() response += "\n{}: {}".format(cur_thread.name, data) self.request.sendall(response) except socket.error: # Surpress errno 13 Broken Pipe pass class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): pass def create_server(host="localhost", port=0): server = ThreadedTCPServer((host, port), ThreadedTCPRequestHandler) server_thread = threading.Thread(target=server.serve_forever) server_thread.daemon = True server_thread.start() return server def handle_data(data): data = json.loads(data) if data['type'] == 'ask': handle_ask(data) elif data['type'] == 'bid': handle_bid(data) elif data['type'] == 'greeting': handle_greeting(data) def handle_ask(ask): asks.append(ask) def handle_bid(bid): bids.append(bid) def handle_greeting(greeting): pass
import json import threading import socket import SocketServer from orderbook import asks, bids class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler): def handle(self): try: while True: data = self.request.recv(1024) if data: response = handle_data(data) cur_thread = threading.current_thread() response = "\n{}: {}".format(cur_thread.name, data) self.request.sendall(response) except socket.error: # Surpress errno 13 Broken Pipe pass class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): pass def create_server(host="localhost", port=0): server = ThreadedTCPServer((host, port), ThreadedTCPRequestHandler) server_thread = threading.Thread(target=server.serve_forever) server_thread.daemon = True server_thread.start() return server def handle_data(data): data = json.loads(data) if data['type'] == 'ask': handle_ask(data) elif data['type'] == 'bid': handle_bid(data) elif data['type'] == 'greeting': handle_greeting(data) def handle_ask(ask): asks.append(ask) def handle_bid(bid): bids.append(bid) def handle_greeting(greeting): pass Fix bugs occuring when no response is given.import json import threading import socket import SocketServer from orderbook import asks, bids class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler): def handle(self): try: while True: data = self.request.recv(1024) response = '' if data: response += handle_data(data) cur_thread = threading.current_thread() response += "\n{}: {}".format(cur_thread.name, data) self.request.sendall(response) except socket.error: # Surpress errno 13 Broken Pipe pass class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): pass def create_server(host="localhost", port=0): server = ThreadedTCPServer((host, port), ThreadedTCPRequestHandler) server_thread = threading.Thread(target=server.serve_forever) server_thread.daemon = True server_thread.start() return server def handle_data(data): data = json.loads(data) if data['type'] == 'ask': handle_ask(data) elif data['type'] == 'bid': handle_bid(data) elif data['type'] == 'greeting': handle_greeting(data) def handle_ask(ask): asks.append(ask) def handle_bid(bid): bids.append(bid) def handle_greeting(greeting): pass
<commit_before>import json import threading import socket import SocketServer from orderbook import asks, bids class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler): def handle(self): try: while True: data = self.request.recv(1024) if data: response = handle_data(data) cur_thread = threading.current_thread() response = "\n{}: {}".format(cur_thread.name, data) self.request.sendall(response) except socket.error: # Surpress errno 13 Broken Pipe pass class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): pass def create_server(host="localhost", port=0): server = ThreadedTCPServer((host, port), ThreadedTCPRequestHandler) server_thread = threading.Thread(target=server.serve_forever) server_thread.daemon = True server_thread.start() return server def handle_data(data): data = json.loads(data) if data['type'] == 'ask': handle_ask(data) elif data['type'] == 'bid': handle_bid(data) elif data['type'] == 'greeting': handle_greeting(data) def handle_ask(ask): asks.append(ask) def handle_bid(bid): bids.append(bid) def handle_greeting(greeting): pass <commit_msg>Fix bugs occuring when no response is given.<commit_after>import json import threading import socket import SocketServer from orderbook import asks, bids class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler): def handle(self): try: while True: data = self.request.recv(1024) response = '' if data: response += handle_data(data) cur_thread = threading.current_thread() response += "\n{}: {}".format(cur_thread.name, data) self.request.sendall(response) except socket.error: # Surpress errno 13 Broken Pipe pass class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): pass def create_server(host="localhost", port=0): server = ThreadedTCPServer((host, port), ThreadedTCPRequestHandler) server_thread = threading.Thread(target=server.serve_forever) server_thread.daemon = True server_thread.start() return server def handle_data(data): data = json.loads(data) if data['type'] == 'ask': handle_ask(data) elif data['type'] == 'bid': handle_bid(data) elif data['type'] == 'greeting': handle_greeting(data) def handle_ask(ask): asks.append(ask) def handle_bid(bid): bids.append(bid) def handle_greeting(greeting): pass
e98eeadb9d5906bf65efc7a17658ae498cfcf27d
chainer/utils/__init__.py
chainer/utils/__init__.py
import contextlib import shutil import tempfile import numpy from chainer.utils import walker_alias # NOQA # import class and function from chainer.utils.conv import get_conv_outsize # NOQA from chainer.utils.conv import get_deconv_outsize # NOQA from chainer.utils.experimental import experimental # NOQA from chainer.utils.walker_alias import WalkerAlias # NOQA def force_array(x, dtype=None): # numpy returns a float value (scalar) when a return value of an operator # is a 0-dimension array. # We need to convert such a value to a 0-dimension array because `Function` # object needs to return an `numpy.ndarray`. if numpy.isscalar(x): if dtype is None: return numpy.array(x) else: return numpy.array(x, dtype) else: if dtype is None: return x else: return x.astype(dtype, copy=False) def force_type(dtype, value): if numpy.isscalar(value): return dtype.type(value) elif value.dtype != dtype: return value.astype(dtype, copy=False) else: return value @contextlib.contextmanager def tempdir(**kwargs): # A context manager that defines a lifetime of a temporary directory. temp_dir = tempfile.mkdtemp(**kwargs) try: yield temp_dir finally: shutil.rmtree(temp_dir, ignore_errors=True)
import contextlib import shutil import tempfile import numpy from chainer.utils import walker_alias # NOQA # import class and function from chainer.utils.conv import get_conv_outsize # NOQA from chainer.utils.conv import get_deconv_outsize # NOQA from chainer.utils.experimental import experimental # NOQA from chainer.utils.walker_alias import WalkerAlias # NOQA def force_array(x, dtype=None): # numpy returns a float value (scalar) when a return value of an operator # is a 0-dimension array. # We need to convert such a value to a 0-dimension array because `Function` # object needs to return an `numpy.ndarray`. if numpy.isscalar(x): if dtype is None: return numpy.array(x) else: return numpy.array(x, dtype) else: if dtype is None: return x else: return x.astype(dtype, copy=False) def force_type(dtype, value): if numpy.isscalar(value): return dtype.type(value) elif value.dtype != dtype: return value.astype(dtype, copy=False) else: return value @contextlib.contextmanager def tempdir(**kwargs): # A context manager that defines a lifetime of a temporary directory. ignore_errors = kwargs.pop('ignore_errors', False) temp_dir = tempfile.mkdtemp(**kwargs) try: yield temp_dir finally: shutil.rmtree(temp_dir, ignore_errors=ignore_errors)
Make ignore_errors False by default
Make ignore_errors False by default
Python
mit
ronekko/chainer,chainer/chainer,okuta/chainer,wkentaro/chainer,ktnyt/chainer,chainer/chainer,okuta/chainer,niboshi/chainer,chainer/chainer,hvy/chainer,chainer/chainer,rezoo/chainer,keisuke-umezawa/chainer,anaruse/chainer,okuta/chainer,hvy/chainer,keisuke-umezawa/chainer,ktnyt/chainer,jnishi/chainer,niboshi/chainer,keisuke-umezawa/chainer,wkentaro/chainer,jnishi/chainer,pfnet/chainer,tkerola/chainer,hvy/chainer,jnishi/chainer,wkentaro/chainer,okuta/chainer,niboshi/chainer,keisuke-umezawa/chainer,ktnyt/chainer,jnishi/chainer,wkentaro/chainer,hvy/chainer,niboshi/chainer,ktnyt/chainer
import contextlib import shutil import tempfile import numpy from chainer.utils import walker_alias # NOQA # import class and function from chainer.utils.conv import get_conv_outsize # NOQA from chainer.utils.conv import get_deconv_outsize # NOQA from chainer.utils.experimental import experimental # NOQA from chainer.utils.walker_alias import WalkerAlias # NOQA def force_array(x, dtype=None): # numpy returns a float value (scalar) when a return value of an operator # is a 0-dimension array. # We need to convert such a value to a 0-dimension array because `Function` # object needs to return an `numpy.ndarray`. if numpy.isscalar(x): if dtype is None: return numpy.array(x) else: return numpy.array(x, dtype) else: if dtype is None: return x else: return x.astype(dtype, copy=False) def force_type(dtype, value): if numpy.isscalar(value): return dtype.type(value) elif value.dtype != dtype: return value.astype(dtype, copy=False) else: return value @contextlib.contextmanager def tempdir(**kwargs): # A context manager that defines a lifetime of a temporary directory. temp_dir = tempfile.mkdtemp(**kwargs) try: yield temp_dir finally: shutil.rmtree(temp_dir, ignore_errors=True) Make ignore_errors False by default
import contextlib import shutil import tempfile import numpy from chainer.utils import walker_alias # NOQA # import class and function from chainer.utils.conv import get_conv_outsize # NOQA from chainer.utils.conv import get_deconv_outsize # NOQA from chainer.utils.experimental import experimental # NOQA from chainer.utils.walker_alias import WalkerAlias # NOQA def force_array(x, dtype=None): # numpy returns a float value (scalar) when a return value of an operator # is a 0-dimension array. # We need to convert such a value to a 0-dimension array because `Function` # object needs to return an `numpy.ndarray`. if numpy.isscalar(x): if dtype is None: return numpy.array(x) else: return numpy.array(x, dtype) else: if dtype is None: return x else: return x.astype(dtype, copy=False) def force_type(dtype, value): if numpy.isscalar(value): return dtype.type(value) elif value.dtype != dtype: return value.astype(dtype, copy=False) else: return value @contextlib.contextmanager def tempdir(**kwargs): # A context manager that defines a lifetime of a temporary directory. ignore_errors = kwargs.pop('ignore_errors', False) temp_dir = tempfile.mkdtemp(**kwargs) try: yield temp_dir finally: shutil.rmtree(temp_dir, ignore_errors=ignore_errors)
<commit_before>import contextlib import shutil import tempfile import numpy from chainer.utils import walker_alias # NOQA # import class and function from chainer.utils.conv import get_conv_outsize # NOQA from chainer.utils.conv import get_deconv_outsize # NOQA from chainer.utils.experimental import experimental # NOQA from chainer.utils.walker_alias import WalkerAlias # NOQA def force_array(x, dtype=None): # numpy returns a float value (scalar) when a return value of an operator # is a 0-dimension array. # We need to convert such a value to a 0-dimension array because `Function` # object needs to return an `numpy.ndarray`. if numpy.isscalar(x): if dtype is None: return numpy.array(x) else: return numpy.array(x, dtype) else: if dtype is None: return x else: return x.astype(dtype, copy=False) def force_type(dtype, value): if numpy.isscalar(value): return dtype.type(value) elif value.dtype != dtype: return value.astype(dtype, copy=False) else: return value @contextlib.contextmanager def tempdir(**kwargs): # A context manager that defines a lifetime of a temporary directory. temp_dir = tempfile.mkdtemp(**kwargs) try: yield temp_dir finally: shutil.rmtree(temp_dir, ignore_errors=True) <commit_msg>Make ignore_errors False by default<commit_after>
import contextlib import shutil import tempfile import numpy from chainer.utils import walker_alias # NOQA # import class and function from chainer.utils.conv import get_conv_outsize # NOQA from chainer.utils.conv import get_deconv_outsize # NOQA from chainer.utils.experimental import experimental # NOQA from chainer.utils.walker_alias import WalkerAlias # NOQA def force_array(x, dtype=None): # numpy returns a float value (scalar) when a return value of an operator # is a 0-dimension array. # We need to convert such a value to a 0-dimension array because `Function` # object needs to return an `numpy.ndarray`. if numpy.isscalar(x): if dtype is None: return numpy.array(x) else: return numpy.array(x, dtype) else: if dtype is None: return x else: return x.astype(dtype, copy=False) def force_type(dtype, value): if numpy.isscalar(value): return dtype.type(value) elif value.dtype != dtype: return value.astype(dtype, copy=False) else: return value @contextlib.contextmanager def tempdir(**kwargs): # A context manager that defines a lifetime of a temporary directory. ignore_errors = kwargs.pop('ignore_errors', False) temp_dir = tempfile.mkdtemp(**kwargs) try: yield temp_dir finally: shutil.rmtree(temp_dir, ignore_errors=ignore_errors)
import contextlib import shutil import tempfile import numpy from chainer.utils import walker_alias # NOQA # import class and function from chainer.utils.conv import get_conv_outsize # NOQA from chainer.utils.conv import get_deconv_outsize # NOQA from chainer.utils.experimental import experimental # NOQA from chainer.utils.walker_alias import WalkerAlias # NOQA def force_array(x, dtype=None): # numpy returns a float value (scalar) when a return value of an operator # is a 0-dimension array. # We need to convert such a value to a 0-dimension array because `Function` # object needs to return an `numpy.ndarray`. if numpy.isscalar(x): if dtype is None: return numpy.array(x) else: return numpy.array(x, dtype) else: if dtype is None: return x else: return x.astype(dtype, copy=False) def force_type(dtype, value): if numpy.isscalar(value): return dtype.type(value) elif value.dtype != dtype: return value.astype(dtype, copy=False) else: return value @contextlib.contextmanager def tempdir(**kwargs): # A context manager that defines a lifetime of a temporary directory. temp_dir = tempfile.mkdtemp(**kwargs) try: yield temp_dir finally: shutil.rmtree(temp_dir, ignore_errors=True) Make ignore_errors False by defaultimport contextlib import shutil import tempfile import numpy from chainer.utils import walker_alias # NOQA # import class and function from chainer.utils.conv import get_conv_outsize # NOQA from chainer.utils.conv import get_deconv_outsize # NOQA from chainer.utils.experimental import experimental # NOQA from chainer.utils.walker_alias import WalkerAlias # NOQA def force_array(x, dtype=None): # numpy returns a float value (scalar) when a return value of an operator # is a 0-dimension array. # We need to convert such a value to a 0-dimension array because `Function` # object needs to return an `numpy.ndarray`. if numpy.isscalar(x): if dtype is None: return numpy.array(x) else: return numpy.array(x, dtype) else: if dtype is None: return x else: return x.astype(dtype, copy=False) def force_type(dtype, value): if numpy.isscalar(value): return dtype.type(value) elif value.dtype != dtype: return value.astype(dtype, copy=False) else: return value @contextlib.contextmanager def tempdir(**kwargs): # A context manager that defines a lifetime of a temporary directory. ignore_errors = kwargs.pop('ignore_errors', False) temp_dir = tempfile.mkdtemp(**kwargs) try: yield temp_dir finally: shutil.rmtree(temp_dir, ignore_errors=ignore_errors)
<commit_before>import contextlib import shutil import tempfile import numpy from chainer.utils import walker_alias # NOQA # import class and function from chainer.utils.conv import get_conv_outsize # NOQA from chainer.utils.conv import get_deconv_outsize # NOQA from chainer.utils.experimental import experimental # NOQA from chainer.utils.walker_alias import WalkerAlias # NOQA def force_array(x, dtype=None): # numpy returns a float value (scalar) when a return value of an operator # is a 0-dimension array. # We need to convert such a value to a 0-dimension array because `Function` # object needs to return an `numpy.ndarray`. if numpy.isscalar(x): if dtype is None: return numpy.array(x) else: return numpy.array(x, dtype) else: if dtype is None: return x else: return x.astype(dtype, copy=False) def force_type(dtype, value): if numpy.isscalar(value): return dtype.type(value) elif value.dtype != dtype: return value.astype(dtype, copy=False) else: return value @contextlib.contextmanager def tempdir(**kwargs): # A context manager that defines a lifetime of a temporary directory. temp_dir = tempfile.mkdtemp(**kwargs) try: yield temp_dir finally: shutil.rmtree(temp_dir, ignore_errors=True) <commit_msg>Make ignore_errors False by default<commit_after>import contextlib import shutil import tempfile import numpy from chainer.utils import walker_alias # NOQA # import class and function from chainer.utils.conv import get_conv_outsize # NOQA from chainer.utils.conv import get_deconv_outsize # NOQA from chainer.utils.experimental import experimental # NOQA from chainer.utils.walker_alias import WalkerAlias # NOQA def force_array(x, dtype=None): # numpy returns a float value (scalar) when a return value of an operator # is a 0-dimension array. # We need to convert such a value to a 0-dimension array because `Function` # object needs to return an `numpy.ndarray`. if numpy.isscalar(x): if dtype is None: return numpy.array(x) else: return numpy.array(x, dtype) else: if dtype is None: return x else: return x.astype(dtype, copy=False) def force_type(dtype, value): if numpy.isscalar(value): return dtype.type(value) elif value.dtype != dtype: return value.astype(dtype, copy=False) else: return value @contextlib.contextmanager def tempdir(**kwargs): # A context manager that defines a lifetime of a temporary directory. ignore_errors = kwargs.pop('ignore_errors', False) temp_dir = tempfile.mkdtemp(**kwargs) try: yield temp_dir finally: shutil.rmtree(temp_dir, ignore_errors=ignore_errors)
b423e73ec440d10ff80110c998d13ea8c2b5a764
stock_request_picking_type/models/stock_request_order.py
stock_request_picking_type/models/stock_request_order.py
# Copyright 2019 Open Source Integrators # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import api, fields, models class StockRequestOrder(models.Model): _inherit = 'stock.request.order' @api.model def _get_default_picking_type(self): return self.env['stock.picking.type'].search([ ('code', '=', 'stock_request_order'), ('warehouse_id.company_id', 'in', [self.env.context.get('company_id', self.env.user.company_id.id), False])], limit=1).id picking_type_id = fields.Many2one( 'stock.picking.type', 'Operation Type', default=_get_default_picking_type, required=True)
# Copyright 2019 Open Source Integrators # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import api, fields, models class StockRequestOrder(models.Model): _inherit = 'stock.request.order' @api.model def _get_default_picking_type(self): return self.env['stock.picking.type'].search([ ('code', '=', 'stock_request_order'), ('warehouse_id.company_id', 'in', [self.env.context.get('company_id', self.env.user.company_id.id), False])], limit=1).id picking_type_id = fields.Many2one( 'stock.picking.type', 'Operation Type', default=_get_default_picking_type, required=True) @api.onchange('warehouse_id') def onchange_warehouse_picking_id(self): if self.warehouse_id: picking_type_id = self.env['stock.picking.type'].\ search([('code', '=', 'stock_request_order'), ('warehouse_id', '=', self.warehouse_id.id)], limit=1) if picking_type_id: self._origin.write({'picking_type_id': picking_type_id.id})
Synchronize Picking Type and Warehouse
[IMP] Synchronize Picking Type and Warehouse [IMP] User write()
Python
agpl-3.0
OCA/stock-logistics-warehouse,OCA/stock-logistics-warehouse,OCA/stock-logistics-warehouse,OCA/stock-logistics-warehouse
# Copyright 2019 Open Source Integrators # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import api, fields, models class StockRequestOrder(models.Model): _inherit = 'stock.request.order' @api.model def _get_default_picking_type(self): return self.env['stock.picking.type'].search([ ('code', '=', 'stock_request_order'), ('warehouse_id.company_id', 'in', [self.env.context.get('company_id', self.env.user.company_id.id), False])], limit=1).id picking_type_id = fields.Many2one( 'stock.picking.type', 'Operation Type', default=_get_default_picking_type, required=True) [IMP] Synchronize Picking Type and Warehouse [IMP] User write()
# Copyright 2019 Open Source Integrators # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import api, fields, models class StockRequestOrder(models.Model): _inherit = 'stock.request.order' @api.model def _get_default_picking_type(self): return self.env['stock.picking.type'].search([ ('code', '=', 'stock_request_order'), ('warehouse_id.company_id', 'in', [self.env.context.get('company_id', self.env.user.company_id.id), False])], limit=1).id picking_type_id = fields.Many2one( 'stock.picking.type', 'Operation Type', default=_get_default_picking_type, required=True) @api.onchange('warehouse_id') def onchange_warehouse_picking_id(self): if self.warehouse_id: picking_type_id = self.env['stock.picking.type'].\ search([('code', '=', 'stock_request_order'), ('warehouse_id', '=', self.warehouse_id.id)], limit=1) if picking_type_id: self._origin.write({'picking_type_id': picking_type_id.id})
<commit_before># Copyright 2019 Open Source Integrators # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import api, fields, models class StockRequestOrder(models.Model): _inherit = 'stock.request.order' @api.model def _get_default_picking_type(self): return self.env['stock.picking.type'].search([ ('code', '=', 'stock_request_order'), ('warehouse_id.company_id', 'in', [self.env.context.get('company_id', self.env.user.company_id.id), False])], limit=1).id picking_type_id = fields.Many2one( 'stock.picking.type', 'Operation Type', default=_get_default_picking_type, required=True) <commit_msg>[IMP] Synchronize Picking Type and Warehouse [IMP] User write()<commit_after>
# Copyright 2019 Open Source Integrators # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import api, fields, models class StockRequestOrder(models.Model): _inherit = 'stock.request.order' @api.model def _get_default_picking_type(self): return self.env['stock.picking.type'].search([ ('code', '=', 'stock_request_order'), ('warehouse_id.company_id', 'in', [self.env.context.get('company_id', self.env.user.company_id.id), False])], limit=1).id picking_type_id = fields.Many2one( 'stock.picking.type', 'Operation Type', default=_get_default_picking_type, required=True) @api.onchange('warehouse_id') def onchange_warehouse_picking_id(self): if self.warehouse_id: picking_type_id = self.env['stock.picking.type'].\ search([('code', '=', 'stock_request_order'), ('warehouse_id', '=', self.warehouse_id.id)], limit=1) if picking_type_id: self._origin.write({'picking_type_id': picking_type_id.id})
# Copyright 2019 Open Source Integrators # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import api, fields, models class StockRequestOrder(models.Model): _inherit = 'stock.request.order' @api.model def _get_default_picking_type(self): return self.env['stock.picking.type'].search([ ('code', '=', 'stock_request_order'), ('warehouse_id.company_id', 'in', [self.env.context.get('company_id', self.env.user.company_id.id), False])], limit=1).id picking_type_id = fields.Many2one( 'stock.picking.type', 'Operation Type', default=_get_default_picking_type, required=True) [IMP] Synchronize Picking Type and Warehouse [IMP] User write()# Copyright 2019 Open Source Integrators # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import api, fields, models class StockRequestOrder(models.Model): _inherit = 'stock.request.order' @api.model def _get_default_picking_type(self): return self.env['stock.picking.type'].search([ ('code', '=', 'stock_request_order'), ('warehouse_id.company_id', 'in', [self.env.context.get('company_id', self.env.user.company_id.id), False])], limit=1).id picking_type_id = fields.Many2one( 'stock.picking.type', 'Operation Type', default=_get_default_picking_type, required=True) @api.onchange('warehouse_id') def onchange_warehouse_picking_id(self): if self.warehouse_id: picking_type_id = self.env['stock.picking.type'].\ search([('code', '=', 'stock_request_order'), ('warehouse_id', '=', self.warehouse_id.id)], limit=1) if picking_type_id: self._origin.write({'picking_type_id': picking_type_id.id})
<commit_before># Copyright 2019 Open Source Integrators # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import api, fields, models class StockRequestOrder(models.Model): _inherit = 'stock.request.order' @api.model def _get_default_picking_type(self): return self.env['stock.picking.type'].search([ ('code', '=', 'stock_request_order'), ('warehouse_id.company_id', 'in', [self.env.context.get('company_id', self.env.user.company_id.id), False])], limit=1).id picking_type_id = fields.Many2one( 'stock.picking.type', 'Operation Type', default=_get_default_picking_type, required=True) <commit_msg>[IMP] Synchronize Picking Type and Warehouse [IMP] User write()<commit_after># Copyright 2019 Open Source Integrators # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import api, fields, models class StockRequestOrder(models.Model): _inherit = 'stock.request.order' @api.model def _get_default_picking_type(self): return self.env['stock.picking.type'].search([ ('code', '=', 'stock_request_order'), ('warehouse_id.company_id', 'in', [self.env.context.get('company_id', self.env.user.company_id.id), False])], limit=1).id picking_type_id = fields.Many2one( 'stock.picking.type', 'Operation Type', default=_get_default_picking_type, required=True) @api.onchange('warehouse_id') def onchange_warehouse_picking_id(self): if self.warehouse_id: picking_type_id = self.env['stock.picking.type'].\ search([('code', '=', 'stock_request_order'), ('warehouse_id', '=', self.warehouse_id.id)], limit=1) if picking_type_id: self._origin.write({'picking_type_id': picking_type_id.id})
d5a2f336d0ea49d68268b355606f69aef8770b24
acute/__init__.py
acute/__init__.py
""" acute - Our OPAL Application """ from opal.core import application class Application(application.OpalApplication): schema_module = 'acute.schema' flow_module = 'acute.flow' javascripts = [ 'js/acute/routes.js', 'js/acute/controllers/acute_take_discharge.js', 'js/opal/controllers/discharge.js', ] menuitems = [ dict( href='/referrals/#/acute_take', display='Clerking', icon='fa fa-mail-forward', activepattern='/referrals/#/acute_take') ]
""" acute - Our OPAL Application """ from opal.core import application class Application(application.OpalApplication): schema_module = 'acute.schema' flow_module = 'acute.flow' javascripts = [ 'js/acute/routes.js', 'js/acute/controllers/acute_take_discharge.js', 'js/opal/controllers/discharge.js', ] menuitems = [ dict( href='/referrals/#/acute_take', display='Admissions', icon='fa fa-mail-forward', activepattern='/referrals/#/acute_take') ]
Rename clerking -> Book in
Rename clerking -> Book in
Python
agpl-3.0
openhealthcare/acute,openhealthcare/acute,openhealthcare/acute
""" acute - Our OPAL Application """ from opal.core import application class Application(application.OpalApplication): schema_module = 'acute.schema' flow_module = 'acute.flow' javascripts = [ 'js/acute/routes.js', 'js/acute/controllers/acute_take_discharge.js', 'js/opal/controllers/discharge.js', ] menuitems = [ dict( href='/referrals/#/acute_take', display='Clerking', icon='fa fa-mail-forward', activepattern='/referrals/#/acute_take') ] Rename clerking -> Book in
""" acute - Our OPAL Application """ from opal.core import application class Application(application.OpalApplication): schema_module = 'acute.schema' flow_module = 'acute.flow' javascripts = [ 'js/acute/routes.js', 'js/acute/controllers/acute_take_discharge.js', 'js/opal/controllers/discharge.js', ] menuitems = [ dict( href='/referrals/#/acute_take', display='Admissions', icon='fa fa-mail-forward', activepattern='/referrals/#/acute_take') ]
<commit_before>""" acute - Our OPAL Application """ from opal.core import application class Application(application.OpalApplication): schema_module = 'acute.schema' flow_module = 'acute.flow' javascripts = [ 'js/acute/routes.js', 'js/acute/controllers/acute_take_discharge.js', 'js/opal/controllers/discharge.js', ] menuitems = [ dict( href='/referrals/#/acute_take', display='Clerking', icon='fa fa-mail-forward', activepattern='/referrals/#/acute_take') ] <commit_msg>Rename clerking -> Book in<commit_after>
""" acute - Our OPAL Application """ from opal.core import application class Application(application.OpalApplication): schema_module = 'acute.schema' flow_module = 'acute.flow' javascripts = [ 'js/acute/routes.js', 'js/acute/controllers/acute_take_discharge.js', 'js/opal/controllers/discharge.js', ] menuitems = [ dict( href='/referrals/#/acute_take', display='Admissions', icon='fa fa-mail-forward', activepattern='/referrals/#/acute_take') ]
""" acute - Our OPAL Application """ from opal.core import application class Application(application.OpalApplication): schema_module = 'acute.schema' flow_module = 'acute.flow' javascripts = [ 'js/acute/routes.js', 'js/acute/controllers/acute_take_discharge.js', 'js/opal/controllers/discharge.js', ] menuitems = [ dict( href='/referrals/#/acute_take', display='Clerking', icon='fa fa-mail-forward', activepattern='/referrals/#/acute_take') ] Rename clerking -> Book in""" acute - Our OPAL Application """ from opal.core import application class Application(application.OpalApplication): schema_module = 'acute.schema' flow_module = 'acute.flow' javascripts = [ 'js/acute/routes.js', 'js/acute/controllers/acute_take_discharge.js', 'js/opal/controllers/discharge.js', ] menuitems = [ dict( href='/referrals/#/acute_take', display='Admissions', icon='fa fa-mail-forward', activepattern='/referrals/#/acute_take') ]
<commit_before>""" acute - Our OPAL Application """ from opal.core import application class Application(application.OpalApplication): schema_module = 'acute.schema' flow_module = 'acute.flow' javascripts = [ 'js/acute/routes.js', 'js/acute/controllers/acute_take_discharge.js', 'js/opal/controllers/discharge.js', ] menuitems = [ dict( href='/referrals/#/acute_take', display='Clerking', icon='fa fa-mail-forward', activepattern='/referrals/#/acute_take') ] <commit_msg>Rename clerking -> Book in<commit_after>""" acute - Our OPAL Application """ from opal.core import application class Application(application.OpalApplication): schema_module = 'acute.schema' flow_module = 'acute.flow' javascripts = [ 'js/acute/routes.js', 'js/acute/controllers/acute_take_discharge.js', 'js/opal/controllers/discharge.js', ] menuitems = [ dict( href='/referrals/#/acute_take', display='Admissions', icon='fa fa-mail-forward', activepattern='/referrals/#/acute_take') ]
8fd395e1085f0508da401186b09f7487b3f9ae64
odbc2csv.py
odbc2csv.py
import pypyodbc import csv conn = pypyodbc.connect("DSN=") cur = conn.cursor() tables = [] cur.tables("%", "", "") for row in cur.fetchall(): tables.append(row[2]) for table in tables: cur.execute("select * from %s" % table) column_names = [] for d in cur.description: column_names.append(d[0]) file = open("%s.csv" % table, "w") writer = csv.writer(file) writer.writerow(column_names) for row in cur.fetchall(): writer.writerow(row) file.close()
import pypyodbc import csv conn = pypyodbc.connect("DSN=") cur = conn.cursor() tables = [] cur.execute("select * from sys.tables") for row in cur.fetchall(): tables.append(row[0]) for table in tables: cur.execute("select * from %s" % table) column_names = [] for d in cur.description: column_names.append(d[0]) file = open("%s.csv" % table, "w") writer = csv.writer(file) writer.writerow(column_names) for row in cur.fetchall(): writer.writerow(row) file.close()
Fix to fetching tables from MS SQL Server.
Fix to fetching tables from MS SQL Server.
Python
isc
wablair/misc_scripts,wablair/misc_scripts,wablair/misc_scripts,wablair/misc_scripts
import pypyodbc import csv conn = pypyodbc.connect("DSN=") cur = conn.cursor() tables = [] cur.tables("%", "", "") for row in cur.fetchall(): tables.append(row[2]) for table in tables: cur.execute("select * from %s" % table) column_names = [] for d in cur.description: column_names.append(d[0]) file = open("%s.csv" % table, "w") writer = csv.writer(file) writer.writerow(column_names) for row in cur.fetchall(): writer.writerow(row) file.close() Fix to fetching tables from MS SQL Server.
import pypyodbc import csv conn = pypyodbc.connect("DSN=") cur = conn.cursor() tables = [] cur.execute("select * from sys.tables") for row in cur.fetchall(): tables.append(row[0]) for table in tables: cur.execute("select * from %s" % table) column_names = [] for d in cur.description: column_names.append(d[0]) file = open("%s.csv" % table, "w") writer = csv.writer(file) writer.writerow(column_names) for row in cur.fetchall(): writer.writerow(row) file.close()
<commit_before>import pypyodbc import csv conn = pypyodbc.connect("DSN=") cur = conn.cursor() tables = [] cur.tables("%", "", "") for row in cur.fetchall(): tables.append(row[2]) for table in tables: cur.execute("select * from %s" % table) column_names = [] for d in cur.description: column_names.append(d[0]) file = open("%s.csv" % table, "w") writer = csv.writer(file) writer.writerow(column_names) for row in cur.fetchall(): writer.writerow(row) file.close() <commit_msg>Fix to fetching tables from MS SQL Server.<commit_after>
import pypyodbc import csv conn = pypyodbc.connect("DSN=") cur = conn.cursor() tables = [] cur.execute("select * from sys.tables") for row in cur.fetchall(): tables.append(row[0]) for table in tables: cur.execute("select * from %s" % table) column_names = [] for d in cur.description: column_names.append(d[0]) file = open("%s.csv" % table, "w") writer = csv.writer(file) writer.writerow(column_names) for row in cur.fetchall(): writer.writerow(row) file.close()
import pypyodbc import csv conn = pypyodbc.connect("DSN=") cur = conn.cursor() tables = [] cur.tables("%", "", "") for row in cur.fetchall(): tables.append(row[2]) for table in tables: cur.execute("select * from %s" % table) column_names = [] for d in cur.description: column_names.append(d[0]) file = open("%s.csv" % table, "w") writer = csv.writer(file) writer.writerow(column_names) for row in cur.fetchall(): writer.writerow(row) file.close() Fix to fetching tables from MS SQL Server.import pypyodbc import csv conn = pypyodbc.connect("DSN=") cur = conn.cursor() tables = [] cur.execute("select * from sys.tables") for row in cur.fetchall(): tables.append(row[0]) for table in tables: cur.execute("select * from %s" % table) column_names = [] for d in cur.description: column_names.append(d[0]) file = open("%s.csv" % table, "w") writer = csv.writer(file) writer.writerow(column_names) for row in cur.fetchall(): writer.writerow(row) file.close()
<commit_before>import pypyodbc import csv conn = pypyodbc.connect("DSN=") cur = conn.cursor() tables = [] cur.tables("%", "", "") for row in cur.fetchall(): tables.append(row[2]) for table in tables: cur.execute("select * from %s" % table) column_names = [] for d in cur.description: column_names.append(d[0]) file = open("%s.csv" % table, "w") writer = csv.writer(file) writer.writerow(column_names) for row in cur.fetchall(): writer.writerow(row) file.close() <commit_msg>Fix to fetching tables from MS SQL Server.<commit_after>import pypyodbc import csv conn = pypyodbc.connect("DSN=") cur = conn.cursor() tables = [] cur.execute("select * from sys.tables") for row in cur.fetchall(): tables.append(row[0]) for table in tables: cur.execute("select * from %s" % table) column_names = [] for d in cur.description: column_names.append(d[0]) file = open("%s.csv" % table, "w") writer = csv.writer(file) writer.writerow(column_names) for row in cur.fetchall(): writer.writerow(row) file.close()
6a8fadc2d607adaf89e6ea15fca65136fac651c6
src/auspex/instruments/utils.py
src/auspex/instruments/utils.py
from . import bbn import auspex.config from auspex.log import logger from QGL import * ChannelLibrary() def pulse_marker(marker_name, length = 100e-9): """ Utility to generate a square pulse on a APS2 marker. Used for instance to switch a signal between spectrum analyzer and input line marker_name as defined in measure.yaml """ settings = auspex.config.load_meas_file(auspex.config.find_meas_file()) mkr = settings['markers'][marker_name] marker = MarkerFactory(marker_name) APS_name = mkr.split()[0] APS = bbn.APS2() APS.connect(settings['instruments'][APS_name]['address']) APS.set_trigger_source('Software') seq = [[TRIG(marker,length)]] APS.set_seq_file(compile_to_hardware(seq, 'Switch\Switch').replace('meta.json', APS_name+'.h5')) APS.run() APS.trigger() APS.stop() APS.disconnect() logger.info('Switched marker {} ({})'.format(marker_name, mkr))
from . import bbn import auspex.config from auspex.log import logger def pulse_marker(marker_name, length = 100e-9): """ Utility to generate a square pulse on a APS2 marker. Used for instance to switch a signal between spectrum analyzer and input line marker_name as defined in measure.yaml """ from QGL import * ChannelLibrary() settings = auspex.config.load_meas_file(auspex.config.find_meas_file()) mkr = settings['markers'][marker_name] marker = MarkerFactory(marker_name) APS_name = mkr.split()[0] APS = bbn.APS2() APS.connect(settings['instruments'][APS_name]['address']) APS.set_trigger_source('Software') seq = [[TRIG(marker,length)]] APS.set_seq_file(compile_to_hardware(seq, 'Switch\Switch').replace('meta.json', APS_name+'.h5')) APS.run() APS.trigger() APS.stop() APS.disconnect() logger.info('Switched marker {} ({})'.format(marker_name, mkr))
Move QGL import inside function
Move QGL import inside function A channel library is not always available
Python
apache-2.0
BBN-Q/Auspex,BBN-Q/Auspex,BBN-Q/Auspex,BBN-Q/Auspex
from . import bbn import auspex.config from auspex.log import logger from QGL import * ChannelLibrary() def pulse_marker(marker_name, length = 100e-9): """ Utility to generate a square pulse on a APS2 marker. Used for instance to switch a signal between spectrum analyzer and input line marker_name as defined in measure.yaml """ settings = auspex.config.load_meas_file(auspex.config.find_meas_file()) mkr = settings['markers'][marker_name] marker = MarkerFactory(marker_name) APS_name = mkr.split()[0] APS = bbn.APS2() APS.connect(settings['instruments'][APS_name]['address']) APS.set_trigger_source('Software') seq = [[TRIG(marker,length)]] APS.set_seq_file(compile_to_hardware(seq, 'Switch\Switch').replace('meta.json', APS_name+'.h5')) APS.run() APS.trigger() APS.stop() APS.disconnect() logger.info('Switched marker {} ({})'.format(marker_name, mkr)) Move QGL import inside function A channel library is not always available
from . import bbn import auspex.config from auspex.log import logger def pulse_marker(marker_name, length = 100e-9): """ Utility to generate a square pulse on a APS2 marker. Used for instance to switch a signal between spectrum analyzer and input line marker_name as defined in measure.yaml """ from QGL import * ChannelLibrary() settings = auspex.config.load_meas_file(auspex.config.find_meas_file()) mkr = settings['markers'][marker_name] marker = MarkerFactory(marker_name) APS_name = mkr.split()[0] APS = bbn.APS2() APS.connect(settings['instruments'][APS_name]['address']) APS.set_trigger_source('Software') seq = [[TRIG(marker,length)]] APS.set_seq_file(compile_to_hardware(seq, 'Switch\Switch').replace('meta.json', APS_name+'.h5')) APS.run() APS.trigger() APS.stop() APS.disconnect() logger.info('Switched marker {} ({})'.format(marker_name, mkr))
<commit_before>from . import bbn import auspex.config from auspex.log import logger from QGL import * ChannelLibrary() def pulse_marker(marker_name, length = 100e-9): """ Utility to generate a square pulse on a APS2 marker. Used for instance to switch a signal between spectrum analyzer and input line marker_name as defined in measure.yaml """ settings = auspex.config.load_meas_file(auspex.config.find_meas_file()) mkr = settings['markers'][marker_name] marker = MarkerFactory(marker_name) APS_name = mkr.split()[0] APS = bbn.APS2() APS.connect(settings['instruments'][APS_name]['address']) APS.set_trigger_source('Software') seq = [[TRIG(marker,length)]] APS.set_seq_file(compile_to_hardware(seq, 'Switch\Switch').replace('meta.json', APS_name+'.h5')) APS.run() APS.trigger() APS.stop() APS.disconnect() logger.info('Switched marker {} ({})'.format(marker_name, mkr)) <commit_msg>Move QGL import inside function A channel library is not always available<commit_after>
from . import bbn import auspex.config from auspex.log import logger def pulse_marker(marker_name, length = 100e-9): """ Utility to generate a square pulse on a APS2 marker. Used for instance to switch a signal between spectrum analyzer and input line marker_name as defined in measure.yaml """ from QGL import * ChannelLibrary() settings = auspex.config.load_meas_file(auspex.config.find_meas_file()) mkr = settings['markers'][marker_name] marker = MarkerFactory(marker_name) APS_name = mkr.split()[0] APS = bbn.APS2() APS.connect(settings['instruments'][APS_name]['address']) APS.set_trigger_source('Software') seq = [[TRIG(marker,length)]] APS.set_seq_file(compile_to_hardware(seq, 'Switch\Switch').replace('meta.json', APS_name+'.h5')) APS.run() APS.trigger() APS.stop() APS.disconnect() logger.info('Switched marker {} ({})'.format(marker_name, mkr))
from . import bbn import auspex.config from auspex.log import logger from QGL import * ChannelLibrary() def pulse_marker(marker_name, length = 100e-9): """ Utility to generate a square pulse on a APS2 marker. Used for instance to switch a signal between spectrum analyzer and input line marker_name as defined in measure.yaml """ settings = auspex.config.load_meas_file(auspex.config.find_meas_file()) mkr = settings['markers'][marker_name] marker = MarkerFactory(marker_name) APS_name = mkr.split()[0] APS = bbn.APS2() APS.connect(settings['instruments'][APS_name]['address']) APS.set_trigger_source('Software') seq = [[TRIG(marker,length)]] APS.set_seq_file(compile_to_hardware(seq, 'Switch\Switch').replace('meta.json', APS_name+'.h5')) APS.run() APS.trigger() APS.stop() APS.disconnect() logger.info('Switched marker {} ({})'.format(marker_name, mkr)) Move QGL import inside function A channel library is not always availablefrom . import bbn import auspex.config from auspex.log import logger def pulse_marker(marker_name, length = 100e-9): """ Utility to generate a square pulse on a APS2 marker. Used for instance to switch a signal between spectrum analyzer and input line marker_name as defined in measure.yaml """ from QGL import * ChannelLibrary() settings = auspex.config.load_meas_file(auspex.config.find_meas_file()) mkr = settings['markers'][marker_name] marker = MarkerFactory(marker_name) APS_name = mkr.split()[0] APS = bbn.APS2() APS.connect(settings['instruments'][APS_name]['address']) APS.set_trigger_source('Software') seq = [[TRIG(marker,length)]] APS.set_seq_file(compile_to_hardware(seq, 'Switch\Switch').replace('meta.json', APS_name+'.h5')) APS.run() APS.trigger() APS.stop() APS.disconnect() logger.info('Switched marker {} ({})'.format(marker_name, mkr))
<commit_before>from . import bbn import auspex.config from auspex.log import logger from QGL import * ChannelLibrary() def pulse_marker(marker_name, length = 100e-9): """ Utility to generate a square pulse on a APS2 marker. Used for instance to switch a signal between spectrum analyzer and input line marker_name as defined in measure.yaml """ settings = auspex.config.load_meas_file(auspex.config.find_meas_file()) mkr = settings['markers'][marker_name] marker = MarkerFactory(marker_name) APS_name = mkr.split()[0] APS = bbn.APS2() APS.connect(settings['instruments'][APS_name]['address']) APS.set_trigger_source('Software') seq = [[TRIG(marker,length)]] APS.set_seq_file(compile_to_hardware(seq, 'Switch\Switch').replace('meta.json', APS_name+'.h5')) APS.run() APS.trigger() APS.stop() APS.disconnect() logger.info('Switched marker {} ({})'.format(marker_name, mkr)) <commit_msg>Move QGL import inside function A channel library is not always available<commit_after>from . import bbn import auspex.config from auspex.log import logger def pulse_marker(marker_name, length = 100e-9): """ Utility to generate a square pulse on a APS2 marker. Used for instance to switch a signal between spectrum analyzer and input line marker_name as defined in measure.yaml """ from QGL import * ChannelLibrary() settings = auspex.config.load_meas_file(auspex.config.find_meas_file()) mkr = settings['markers'][marker_name] marker = MarkerFactory(marker_name) APS_name = mkr.split()[0] APS = bbn.APS2() APS.connect(settings['instruments'][APS_name]['address']) APS.set_trigger_source('Software') seq = [[TRIG(marker,length)]] APS.set_seq_file(compile_to_hardware(seq, 'Switch\Switch').replace('meta.json', APS_name+'.h5')) APS.run() APS.trigger() APS.stop() APS.disconnect() logger.info('Switched marker {} ({})'.format(marker_name, mkr))
89ee95bf33ce504377087de383f56e8582623738
pylab/website/tests/test_comments.py
pylab/website/tests/test_comments.py
import datetime from django_webtest import WebTest from django.contrib.auth.models import User from django_comments.models import Comment from pylab.core.models import Project class CommentsTests(WebTest): def setUp(self): self.user = User.objects.create_user('u1') self.project = Project.objects.create( author=self.user, title='Test project', description='Description', created='2015-08-13' ) def test_add_comment(self): resp = self.app.get('/projects/test-project/', user=self.user) now = datetime.datetime.now() comment = Comment.objects.create( user=self.user, comment='new comment', submit_date=now, object_pk=self.project.id, content_type_id=self.project.id, site_id=1, ) comment.save() resp = self.app.get('/projects/test-project/', user=self.user) self.assertEqual(resp.status_int, 200) self.assertEqual( list(Comment.objects.values_list('comment')), [('new comment',)] )
from django_webtest import WebTest from django.contrib.auth.models import User from django_comments.models import Comment from pylab.core.models import Project class CommentsTests(WebTest): def setUp(self): self.user = User.objects.create_user('u1', email='test@example.com') self.project = Project.objects.create( author=self.user, title='Test project', description='Description', created='2015-08-13' ) def test_add_comment(self): resp = self.app.get('/projects/test-project/', user=self.user) resp.form['comment'] = 'new comment' resp = resp.form.submit() resp = self.app.get('/projects/test-project/', user=self.user) self.assertEqual(resp.status_int, 200) self.assertEqual( list(Comment.objects.values_list('comment')), [('new comment',)] )
Add email parameter for creating test user
Add email parameter for creating test user
Python
agpl-3.0
python-dirbtuves/website,python-dirbtuves/website,python-dirbtuves/website
import datetime from django_webtest import WebTest from django.contrib.auth.models import User from django_comments.models import Comment from pylab.core.models import Project class CommentsTests(WebTest): def setUp(self): self.user = User.objects.create_user('u1') self.project = Project.objects.create( author=self.user, title='Test project', description='Description', created='2015-08-13' ) def test_add_comment(self): resp = self.app.get('/projects/test-project/', user=self.user) now = datetime.datetime.now() comment = Comment.objects.create( user=self.user, comment='new comment', submit_date=now, object_pk=self.project.id, content_type_id=self.project.id, site_id=1, ) comment.save() resp = self.app.get('/projects/test-project/', user=self.user) self.assertEqual(resp.status_int, 200) self.assertEqual( list(Comment.objects.values_list('comment')), [('new comment',)] ) Add email parameter for creating test user
from django_webtest import WebTest from django.contrib.auth.models import User from django_comments.models import Comment from pylab.core.models import Project class CommentsTests(WebTest): def setUp(self): self.user = User.objects.create_user('u1', email='test@example.com') self.project = Project.objects.create( author=self.user, title='Test project', description='Description', created='2015-08-13' ) def test_add_comment(self): resp = self.app.get('/projects/test-project/', user=self.user) resp.form['comment'] = 'new comment' resp = resp.form.submit() resp = self.app.get('/projects/test-project/', user=self.user) self.assertEqual(resp.status_int, 200) self.assertEqual( list(Comment.objects.values_list('comment')), [('new comment',)] )
<commit_before>import datetime from django_webtest import WebTest from django.contrib.auth.models import User from django_comments.models import Comment from pylab.core.models import Project class CommentsTests(WebTest): def setUp(self): self.user = User.objects.create_user('u1') self.project = Project.objects.create( author=self.user, title='Test project', description='Description', created='2015-08-13' ) def test_add_comment(self): resp = self.app.get('/projects/test-project/', user=self.user) now = datetime.datetime.now() comment = Comment.objects.create( user=self.user, comment='new comment', submit_date=now, object_pk=self.project.id, content_type_id=self.project.id, site_id=1, ) comment.save() resp = self.app.get('/projects/test-project/', user=self.user) self.assertEqual(resp.status_int, 200) self.assertEqual( list(Comment.objects.values_list('comment')), [('new comment',)] ) <commit_msg>Add email parameter for creating test user<commit_after>
from django_webtest import WebTest from django.contrib.auth.models import User from django_comments.models import Comment from pylab.core.models import Project class CommentsTests(WebTest): def setUp(self): self.user = User.objects.create_user('u1', email='test@example.com') self.project = Project.objects.create( author=self.user, title='Test project', description='Description', created='2015-08-13' ) def test_add_comment(self): resp = self.app.get('/projects/test-project/', user=self.user) resp.form['comment'] = 'new comment' resp = resp.form.submit() resp = self.app.get('/projects/test-project/', user=self.user) self.assertEqual(resp.status_int, 200) self.assertEqual( list(Comment.objects.values_list('comment')), [('new comment',)] )
import datetime from django_webtest import WebTest from django.contrib.auth.models import User from django_comments.models import Comment from pylab.core.models import Project class CommentsTests(WebTest): def setUp(self): self.user = User.objects.create_user('u1') self.project = Project.objects.create( author=self.user, title='Test project', description='Description', created='2015-08-13' ) def test_add_comment(self): resp = self.app.get('/projects/test-project/', user=self.user) now = datetime.datetime.now() comment = Comment.objects.create( user=self.user, comment='new comment', submit_date=now, object_pk=self.project.id, content_type_id=self.project.id, site_id=1, ) comment.save() resp = self.app.get('/projects/test-project/', user=self.user) self.assertEqual(resp.status_int, 200) self.assertEqual( list(Comment.objects.values_list('comment')), [('new comment',)] ) Add email parameter for creating test userfrom django_webtest import WebTest from django.contrib.auth.models import User from django_comments.models import Comment from pylab.core.models import Project class CommentsTests(WebTest): def setUp(self): self.user = User.objects.create_user('u1', email='test@example.com') self.project = Project.objects.create( author=self.user, title='Test project', description='Description', created='2015-08-13' ) def test_add_comment(self): resp = self.app.get('/projects/test-project/', user=self.user) resp.form['comment'] = 'new comment' resp = resp.form.submit() resp = self.app.get('/projects/test-project/', user=self.user) self.assertEqual(resp.status_int, 200) self.assertEqual( list(Comment.objects.values_list('comment')), [('new comment',)] )
<commit_before>import datetime from django_webtest import WebTest from django.contrib.auth.models import User from django_comments.models import Comment from pylab.core.models import Project class CommentsTests(WebTest): def setUp(self): self.user = User.objects.create_user('u1') self.project = Project.objects.create( author=self.user, title='Test project', description='Description', created='2015-08-13' ) def test_add_comment(self): resp = self.app.get('/projects/test-project/', user=self.user) now = datetime.datetime.now() comment = Comment.objects.create( user=self.user, comment='new comment', submit_date=now, object_pk=self.project.id, content_type_id=self.project.id, site_id=1, ) comment.save() resp = self.app.get('/projects/test-project/', user=self.user) self.assertEqual(resp.status_int, 200) self.assertEqual( list(Comment.objects.values_list('comment')), [('new comment',)] ) <commit_msg>Add email parameter for creating test user<commit_after>from django_webtest import WebTest from django.contrib.auth.models import User from django_comments.models import Comment from pylab.core.models import Project class CommentsTests(WebTest): def setUp(self): self.user = User.objects.create_user('u1', email='test@example.com') self.project = Project.objects.create( author=self.user, title='Test project', description='Description', created='2015-08-13' ) def test_add_comment(self): resp = self.app.get('/projects/test-project/', user=self.user) resp.form['comment'] = 'new comment' resp = resp.form.submit() resp = self.app.get('/projects/test-project/', user=self.user) self.assertEqual(resp.status_int, 200) self.assertEqual( list(Comment.objects.values_list('comment')), [('new comment',)] )
11d9225871fa4980c7782a849c3ecd425edbe806
git_helper.py
git_helper.py
import os def git_file_path(view, git_path): if not git_path: return False full_file_path = view.file_name() git_path_to_file = full_file_path.replace(git_path,'') if git_path_to_file[0] == "/": git_path_to_file = git_path_to_file[1:] return git_path_to_file def git_root(directory): if os.path.exists(os.path.join(directory, '.git')): return directory else: parent = os.path.realpath(os.path.join(directory, os.path.pardir)) if parent == directory: # we have reached root dir return False else: return git_root(parent) def git_tree(view): full_file_path = view.file_name() file_parent_dir = os.path.realpath(os.path.dirname(full_file_path)) return git_root(file_parent_dir) def git_dir(directory): return os.path.join(directory, '.git')
import os def git_file_path(view, git_path): if not git_path: return False full_file_path = view.file_name() git_path_to_file = full_file_path.replace(git_path,'') if git_path_to_file[0] == "/": git_path_to_file = git_path_to_file[1:] return git_path_to_file def git_root(directory): if os.path.exists(os.path.join(directory, '.git')): return directory else: parent = os.path.realpath(os.path.join(directory, os.path.pardir)) if parent == directory: # we have reached root dir return False else: return git_root(parent) def git_tree(view): full_file_path = view.file_name() file_parent_dir = os.path.realpath(os.path.dirname(full_file_path)) return git_root(file_parent_dir) def git_dir(directory): if not directory: return False return os.path.join(directory, '.git')
Fix error when there is no git
Fix error when there is no git
Python
mit
bradsokol/VcsGutter,biodamasceno/GitGutter,biodamasceno/GitGutter,bradsokol/VcsGutter,robfrawley/sublime-git-gutter,robfrawley/sublime-git-gutter,tushortz/GitGutter,akpersad/GitGutter,michaelhogg/GitGutter,robfrawley/sublime-git-gutter,biodamasceno/GitGutter,akpersad/GitGutter,biodamasceno/GitGutter,natecavanaugh/GitGutter,robfrawley/sublime-git-gutter,tushortz/GitGutter,akpersad/GitGutter,jisaacks/GitGutter,michaelhogg/GitGutter,tushortz/GitGutter,natecavanaugh/GitGutter,michaelhogg/GitGutter,michaelhogg/GitGutter,tushortz/GitGutter,akpersad/GitGutter,natecavanaugh/GitGutter,natecavanaugh/GitGutter,ariofrio/VcsGutter,ariofrio/VcsGutter
import os def git_file_path(view, git_path): if not git_path: return False full_file_path = view.file_name() git_path_to_file = full_file_path.replace(git_path,'') if git_path_to_file[0] == "/": git_path_to_file = git_path_to_file[1:] return git_path_to_file def git_root(directory): if os.path.exists(os.path.join(directory, '.git')): return directory else: parent = os.path.realpath(os.path.join(directory, os.path.pardir)) if parent == directory: # we have reached root dir return False else: return git_root(parent) def git_tree(view): full_file_path = view.file_name() file_parent_dir = os.path.realpath(os.path.dirname(full_file_path)) return git_root(file_parent_dir) def git_dir(directory): return os.path.join(directory, '.git') Fix error when there is no git
import os def git_file_path(view, git_path): if not git_path: return False full_file_path = view.file_name() git_path_to_file = full_file_path.replace(git_path,'') if git_path_to_file[0] == "/": git_path_to_file = git_path_to_file[1:] return git_path_to_file def git_root(directory): if os.path.exists(os.path.join(directory, '.git')): return directory else: parent = os.path.realpath(os.path.join(directory, os.path.pardir)) if parent == directory: # we have reached root dir return False else: return git_root(parent) def git_tree(view): full_file_path = view.file_name() file_parent_dir = os.path.realpath(os.path.dirname(full_file_path)) return git_root(file_parent_dir) def git_dir(directory): if not directory: return False return os.path.join(directory, '.git')
<commit_before>import os def git_file_path(view, git_path): if not git_path: return False full_file_path = view.file_name() git_path_to_file = full_file_path.replace(git_path,'') if git_path_to_file[0] == "/": git_path_to_file = git_path_to_file[1:] return git_path_to_file def git_root(directory): if os.path.exists(os.path.join(directory, '.git')): return directory else: parent = os.path.realpath(os.path.join(directory, os.path.pardir)) if parent == directory: # we have reached root dir return False else: return git_root(parent) def git_tree(view): full_file_path = view.file_name() file_parent_dir = os.path.realpath(os.path.dirname(full_file_path)) return git_root(file_parent_dir) def git_dir(directory): return os.path.join(directory, '.git') <commit_msg>Fix error when there is no git<commit_after>
import os def git_file_path(view, git_path): if not git_path: return False full_file_path = view.file_name() git_path_to_file = full_file_path.replace(git_path,'') if git_path_to_file[0] == "/": git_path_to_file = git_path_to_file[1:] return git_path_to_file def git_root(directory): if os.path.exists(os.path.join(directory, '.git')): return directory else: parent = os.path.realpath(os.path.join(directory, os.path.pardir)) if parent == directory: # we have reached root dir return False else: return git_root(parent) def git_tree(view): full_file_path = view.file_name() file_parent_dir = os.path.realpath(os.path.dirname(full_file_path)) return git_root(file_parent_dir) def git_dir(directory): if not directory: return False return os.path.join(directory, '.git')
import os def git_file_path(view, git_path): if not git_path: return False full_file_path = view.file_name() git_path_to_file = full_file_path.replace(git_path,'') if git_path_to_file[0] == "/": git_path_to_file = git_path_to_file[1:] return git_path_to_file def git_root(directory): if os.path.exists(os.path.join(directory, '.git')): return directory else: parent = os.path.realpath(os.path.join(directory, os.path.pardir)) if parent == directory: # we have reached root dir return False else: return git_root(parent) def git_tree(view): full_file_path = view.file_name() file_parent_dir = os.path.realpath(os.path.dirname(full_file_path)) return git_root(file_parent_dir) def git_dir(directory): return os.path.join(directory, '.git') Fix error when there is no gitimport os def git_file_path(view, git_path): if not git_path: return False full_file_path = view.file_name() git_path_to_file = full_file_path.replace(git_path,'') if git_path_to_file[0] == "/": git_path_to_file = git_path_to_file[1:] return git_path_to_file def git_root(directory): if os.path.exists(os.path.join(directory, '.git')): return directory else: parent = os.path.realpath(os.path.join(directory, os.path.pardir)) if parent == directory: # we have reached root dir return False else: return git_root(parent) def git_tree(view): full_file_path = view.file_name() file_parent_dir = os.path.realpath(os.path.dirname(full_file_path)) return git_root(file_parent_dir) def git_dir(directory): if not directory: return False return os.path.join(directory, '.git')
<commit_before>import os def git_file_path(view, git_path): if not git_path: return False full_file_path = view.file_name() git_path_to_file = full_file_path.replace(git_path,'') if git_path_to_file[0] == "/": git_path_to_file = git_path_to_file[1:] return git_path_to_file def git_root(directory): if os.path.exists(os.path.join(directory, '.git')): return directory else: parent = os.path.realpath(os.path.join(directory, os.path.pardir)) if parent == directory: # we have reached root dir return False else: return git_root(parent) def git_tree(view): full_file_path = view.file_name() file_parent_dir = os.path.realpath(os.path.dirname(full_file_path)) return git_root(file_parent_dir) def git_dir(directory): return os.path.join(directory, '.git') <commit_msg>Fix error when there is no git<commit_after>import os def git_file_path(view, git_path): if not git_path: return False full_file_path = view.file_name() git_path_to_file = full_file_path.replace(git_path,'') if git_path_to_file[0] == "/": git_path_to_file = git_path_to_file[1:] return git_path_to_file def git_root(directory): if os.path.exists(os.path.join(directory, '.git')): return directory else: parent = os.path.realpath(os.path.join(directory, os.path.pardir)) if parent == directory: # we have reached root dir return False else: return git_root(parent) def git_tree(view): full_file_path = view.file_name() file_parent_dir = os.path.realpath(os.path.dirname(full_file_path)) return git_root(file_parent_dir) def git_dir(directory): if not directory: return False return os.path.join(directory, '.git')
81880206be25cddc5d47a249eae3975e5070c3f0
haas/utils.py
haas/utils.py
# -*- coding: utf-8 -*- # Copyright (c) 2013-2014 Simon Jagoe # All rights reserved. # # This software may be modified and distributed under the terms # of the 3-clause BSD license. See the LICENSE.txt file for details. from __future__ import absolute_import, unicode_literals import importlib import logging import haas LEVELS = { 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'fatal': logging.FATAL, 'critical': logging.CRITICAL, } def configure_logging(level): actual_level = LEVELS.get(level, logging.WARNING) format_ = '%(asctime)s %(levelname)-8.8s [%(name)s:%(lineno)s] %(message)s' formatter = logging.Formatter(format_) handler = logging.StreamHandler() handler.setFormatter(formatter) handler.setLevel(actual_level) logger = logging.getLogger(haas.__name__) logger.addHandler(handler) logger.setLevel(actual_level) logger.info('Logging configured for haas at level %r', logging.getLevelName(actual_level)) def get_module_by_name(name): """Import a module and return the imported module object. """ return importlib.import_module(name)
# -*- coding: utf-8 -*- # Copyright (c) 2013-2014 Simon Jagoe # All rights reserved. # # This software may be modified and distributed under the terms # of the 3-clause BSD license. See the LICENSE.txt file for details. from __future__ import absolute_import, unicode_literals import haas import logging import sys LEVELS = { 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'fatal': logging.FATAL, 'critical': logging.CRITICAL, } def configure_logging(level): actual_level = LEVELS.get(level, logging.WARNING) format_ = '%(asctime)s %(levelname)-8.8s [%(name)s:%(lineno)s] %(message)s' formatter = logging.Formatter(format_) handler = logging.StreamHandler() handler.setFormatter(formatter) handler.setLevel(actual_level) logger = logging.getLogger(haas.__name__) logger.addHandler(handler) logger.setLevel(actual_level) logger.info('Logging configured for haas at level %r', logging.getLevelName(actual_level)) def get_module_by_name(name): """Import a module and return the imported module object. """ __import__(name) return sys.modules[name]
Revert "Use importlib instead of __import__"
Revert "Use importlib instead of __import__" This reverts commit 1c40e03b487ae3dcef9a683de960f9895936d370.
Python
bsd-3-clause
itziakos/haas,scalative/haas,sjagoe/haas,scalative/haas,sjagoe/haas,itziakos/haas
# -*- coding: utf-8 -*- # Copyright (c) 2013-2014 Simon Jagoe # All rights reserved. # # This software may be modified and distributed under the terms # of the 3-clause BSD license. See the LICENSE.txt file for details. from __future__ import absolute_import, unicode_literals import importlib import logging import haas LEVELS = { 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'fatal': logging.FATAL, 'critical': logging.CRITICAL, } def configure_logging(level): actual_level = LEVELS.get(level, logging.WARNING) format_ = '%(asctime)s %(levelname)-8.8s [%(name)s:%(lineno)s] %(message)s' formatter = logging.Formatter(format_) handler = logging.StreamHandler() handler.setFormatter(formatter) handler.setLevel(actual_level) logger = logging.getLogger(haas.__name__) logger.addHandler(handler) logger.setLevel(actual_level) logger.info('Logging configured for haas at level %r', logging.getLevelName(actual_level)) def get_module_by_name(name): """Import a module and return the imported module object. """ return importlib.import_module(name) Revert "Use importlib instead of __import__" This reverts commit 1c40e03b487ae3dcef9a683de960f9895936d370.
# -*- coding: utf-8 -*- # Copyright (c) 2013-2014 Simon Jagoe # All rights reserved. # # This software may be modified and distributed under the terms # of the 3-clause BSD license. See the LICENSE.txt file for details. from __future__ import absolute_import, unicode_literals import haas import logging import sys LEVELS = { 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'fatal': logging.FATAL, 'critical': logging.CRITICAL, } def configure_logging(level): actual_level = LEVELS.get(level, logging.WARNING) format_ = '%(asctime)s %(levelname)-8.8s [%(name)s:%(lineno)s] %(message)s' formatter = logging.Formatter(format_) handler = logging.StreamHandler() handler.setFormatter(formatter) handler.setLevel(actual_level) logger = logging.getLogger(haas.__name__) logger.addHandler(handler) logger.setLevel(actual_level) logger.info('Logging configured for haas at level %r', logging.getLevelName(actual_level)) def get_module_by_name(name): """Import a module and return the imported module object. """ __import__(name) return sys.modules[name]
<commit_before># -*- coding: utf-8 -*- # Copyright (c) 2013-2014 Simon Jagoe # All rights reserved. # # This software may be modified and distributed under the terms # of the 3-clause BSD license. See the LICENSE.txt file for details. from __future__ import absolute_import, unicode_literals import importlib import logging import haas LEVELS = { 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'fatal': logging.FATAL, 'critical': logging.CRITICAL, } def configure_logging(level): actual_level = LEVELS.get(level, logging.WARNING) format_ = '%(asctime)s %(levelname)-8.8s [%(name)s:%(lineno)s] %(message)s' formatter = logging.Formatter(format_) handler = logging.StreamHandler() handler.setFormatter(formatter) handler.setLevel(actual_level) logger = logging.getLogger(haas.__name__) logger.addHandler(handler) logger.setLevel(actual_level) logger.info('Logging configured for haas at level %r', logging.getLevelName(actual_level)) def get_module_by_name(name): """Import a module and return the imported module object. """ return importlib.import_module(name) <commit_msg>Revert "Use importlib instead of __import__" This reverts commit 1c40e03b487ae3dcef9a683de960f9895936d370.<commit_after>
# -*- coding: utf-8 -*- # Copyright (c) 2013-2014 Simon Jagoe # All rights reserved. # # This software may be modified and distributed under the terms # of the 3-clause BSD license. See the LICENSE.txt file for details. from __future__ import absolute_import, unicode_literals import haas import logging import sys LEVELS = { 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'fatal': logging.FATAL, 'critical': logging.CRITICAL, } def configure_logging(level): actual_level = LEVELS.get(level, logging.WARNING) format_ = '%(asctime)s %(levelname)-8.8s [%(name)s:%(lineno)s] %(message)s' formatter = logging.Formatter(format_) handler = logging.StreamHandler() handler.setFormatter(formatter) handler.setLevel(actual_level) logger = logging.getLogger(haas.__name__) logger.addHandler(handler) logger.setLevel(actual_level) logger.info('Logging configured for haas at level %r', logging.getLevelName(actual_level)) def get_module_by_name(name): """Import a module and return the imported module object. """ __import__(name) return sys.modules[name]
# -*- coding: utf-8 -*- # Copyright (c) 2013-2014 Simon Jagoe # All rights reserved. # # This software may be modified and distributed under the terms # of the 3-clause BSD license. See the LICENSE.txt file for details. from __future__ import absolute_import, unicode_literals import importlib import logging import haas LEVELS = { 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'fatal': logging.FATAL, 'critical': logging.CRITICAL, } def configure_logging(level): actual_level = LEVELS.get(level, logging.WARNING) format_ = '%(asctime)s %(levelname)-8.8s [%(name)s:%(lineno)s] %(message)s' formatter = logging.Formatter(format_) handler = logging.StreamHandler() handler.setFormatter(formatter) handler.setLevel(actual_level) logger = logging.getLogger(haas.__name__) logger.addHandler(handler) logger.setLevel(actual_level) logger.info('Logging configured for haas at level %r', logging.getLevelName(actual_level)) def get_module_by_name(name): """Import a module and return the imported module object. """ return importlib.import_module(name) Revert "Use importlib instead of __import__" This reverts commit 1c40e03b487ae3dcef9a683de960f9895936d370.# -*- coding: utf-8 -*- # Copyright (c) 2013-2014 Simon Jagoe # All rights reserved. # # This software may be modified and distributed under the terms # of the 3-clause BSD license. See the LICENSE.txt file for details. from __future__ import absolute_import, unicode_literals import haas import logging import sys LEVELS = { 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'fatal': logging.FATAL, 'critical': logging.CRITICAL, } def configure_logging(level): actual_level = LEVELS.get(level, logging.WARNING) format_ = '%(asctime)s %(levelname)-8.8s [%(name)s:%(lineno)s] %(message)s' formatter = logging.Formatter(format_) handler = logging.StreamHandler() handler.setFormatter(formatter) handler.setLevel(actual_level) logger = logging.getLogger(haas.__name__) logger.addHandler(handler) logger.setLevel(actual_level) logger.info('Logging configured for haas at level %r', logging.getLevelName(actual_level)) def get_module_by_name(name): """Import a module and return the imported module object. """ __import__(name) return sys.modules[name]
<commit_before># -*- coding: utf-8 -*- # Copyright (c) 2013-2014 Simon Jagoe # All rights reserved. # # This software may be modified and distributed under the terms # of the 3-clause BSD license. See the LICENSE.txt file for details. from __future__ import absolute_import, unicode_literals import importlib import logging import haas LEVELS = { 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'fatal': logging.FATAL, 'critical': logging.CRITICAL, } def configure_logging(level): actual_level = LEVELS.get(level, logging.WARNING) format_ = '%(asctime)s %(levelname)-8.8s [%(name)s:%(lineno)s] %(message)s' formatter = logging.Formatter(format_) handler = logging.StreamHandler() handler.setFormatter(formatter) handler.setLevel(actual_level) logger = logging.getLogger(haas.__name__) logger.addHandler(handler) logger.setLevel(actual_level) logger.info('Logging configured for haas at level %r', logging.getLevelName(actual_level)) def get_module_by_name(name): """Import a module and return the imported module object. """ return importlib.import_module(name) <commit_msg>Revert "Use importlib instead of __import__" This reverts commit 1c40e03b487ae3dcef9a683de960f9895936d370.<commit_after># -*- coding: utf-8 -*- # Copyright (c) 2013-2014 Simon Jagoe # All rights reserved. # # This software may be modified and distributed under the terms # of the 3-clause BSD license. See the LICENSE.txt file for details. from __future__ import absolute_import, unicode_literals import haas import logging import sys LEVELS = { 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'fatal': logging.FATAL, 'critical': logging.CRITICAL, } def configure_logging(level): actual_level = LEVELS.get(level, logging.WARNING) format_ = '%(asctime)s %(levelname)-8.8s [%(name)s:%(lineno)s] %(message)s' formatter = logging.Formatter(format_) handler = logging.StreamHandler() handler.setFormatter(formatter) handler.setLevel(actual_level) logger = logging.getLogger(haas.__name__) logger.addHandler(handler) logger.setLevel(actual_level) logger.info('Logging configured for haas at level %r', logging.getLevelName(actual_level)) def get_module_by_name(name): """Import a module and return the imported module object. """ __import__(name) return sys.modules[name]
d7a77380ad95e316efb73a7be485d9b882fd64e9
Core/models.py
Core/models.py
from django.db import models ## # Location Types ## class World(models.Model): name = models.CharField(max_length=30) homes = models.ManyToManyField(Home) class Home(models.Model): name = models.CharField(max_length=30) rooms = models.ManyToManyField(Room) class Room(models.Model): name = models.CharField(max_length=30) ## # Device Types ## class Device(models.Model): name = models.CharField(max_length=30) class Meta: abstract = True class OutputDevice(Device): actions = models.ManyToManyField(Action) class Meta: abstract = True class InputDevice(Device): events = models.ManyToManyField(Event) class Meta: abstract = True ## # Input/Output ## class Action(models.Model): name = models.CharField(max_length=30) def run() class Meta: abstract = True class Event(models.Model): name = models.CharField(max_length=30) actions = models.ManyToMany(Action) def call(): for (action in self.actions): action.run() class Meta: abstract = True
from django.db import models ## # Location Types ## class World(models.Model): name = models.CharField(max_length=30) homes = models.ManyToManyField(Home) class Meta: db_table = u'Worlds' class Home(models.Model): name = models.CharField(max_length=30) rooms = models.ManyToManyField(Room) class Meta: db_table = u'Homes' class Room(models.Model): name = models.CharField(max_length=30) class Meta: db_table = u'Rooms' ## # Device Types ## class Device(models.Model): name = models.CharField(max_length=30) class Meta: abstract = True class OutputDevice(Device): actions = models.ManyToManyField(Action) class Meta: abstract = True class InputDevice(Device): events = models.ManyToManyField(Event) class Meta: abstract = True ## # Input/Output ## class Action(models.Model): name = models.CharField(max_length=30) def run() class Meta: abstract = True class Event(models.Model): name = models.CharField(max_length=30) actions = models.ManyToMany(Action) def call(): for (action in self.actions): action.run() class Meta: abstract = True
Add table names to core model items
Add table names to core model items
Python
mit
Tomcuzz/OctaHomeAutomation,Tomcuzz/OctaHomeAutomation,Tomcuzz/OctaHomeAutomation,Tomcuzz/OctaHomeAutomation
from django.db import models ## # Location Types ## class World(models.Model): name = models.CharField(max_length=30) homes = models.ManyToManyField(Home) class Home(models.Model): name = models.CharField(max_length=30) rooms = models.ManyToManyField(Room) class Room(models.Model): name = models.CharField(max_length=30) ## # Device Types ## class Device(models.Model): name = models.CharField(max_length=30) class Meta: abstract = True class OutputDevice(Device): actions = models.ManyToManyField(Action) class Meta: abstract = True class InputDevice(Device): events = models.ManyToManyField(Event) class Meta: abstract = True ## # Input/Output ## class Action(models.Model): name = models.CharField(max_length=30) def run() class Meta: abstract = True class Event(models.Model): name = models.CharField(max_length=30) actions = models.ManyToMany(Action) def call(): for (action in self.actions): action.run() class Meta: abstract = True Add table names to core model items
from django.db import models ## # Location Types ## class World(models.Model): name = models.CharField(max_length=30) homes = models.ManyToManyField(Home) class Meta: db_table = u'Worlds' class Home(models.Model): name = models.CharField(max_length=30) rooms = models.ManyToManyField(Room) class Meta: db_table = u'Homes' class Room(models.Model): name = models.CharField(max_length=30) class Meta: db_table = u'Rooms' ## # Device Types ## class Device(models.Model): name = models.CharField(max_length=30) class Meta: abstract = True class OutputDevice(Device): actions = models.ManyToManyField(Action) class Meta: abstract = True class InputDevice(Device): events = models.ManyToManyField(Event) class Meta: abstract = True ## # Input/Output ## class Action(models.Model): name = models.CharField(max_length=30) def run() class Meta: abstract = True class Event(models.Model): name = models.CharField(max_length=30) actions = models.ManyToMany(Action) def call(): for (action in self.actions): action.run() class Meta: abstract = True
<commit_before>from django.db import models ## # Location Types ## class World(models.Model): name = models.CharField(max_length=30) homes = models.ManyToManyField(Home) class Home(models.Model): name = models.CharField(max_length=30) rooms = models.ManyToManyField(Room) class Room(models.Model): name = models.CharField(max_length=30) ## # Device Types ## class Device(models.Model): name = models.CharField(max_length=30) class Meta: abstract = True class OutputDevice(Device): actions = models.ManyToManyField(Action) class Meta: abstract = True class InputDevice(Device): events = models.ManyToManyField(Event) class Meta: abstract = True ## # Input/Output ## class Action(models.Model): name = models.CharField(max_length=30) def run() class Meta: abstract = True class Event(models.Model): name = models.CharField(max_length=30) actions = models.ManyToMany(Action) def call(): for (action in self.actions): action.run() class Meta: abstract = True <commit_msg>Add table names to core model items<commit_after>
from django.db import models ## # Location Types ## class World(models.Model): name = models.CharField(max_length=30) homes = models.ManyToManyField(Home) class Meta: db_table = u'Worlds' class Home(models.Model): name = models.CharField(max_length=30) rooms = models.ManyToManyField(Room) class Meta: db_table = u'Homes' class Room(models.Model): name = models.CharField(max_length=30) class Meta: db_table = u'Rooms' ## # Device Types ## class Device(models.Model): name = models.CharField(max_length=30) class Meta: abstract = True class OutputDevice(Device): actions = models.ManyToManyField(Action) class Meta: abstract = True class InputDevice(Device): events = models.ManyToManyField(Event) class Meta: abstract = True ## # Input/Output ## class Action(models.Model): name = models.CharField(max_length=30) def run() class Meta: abstract = True class Event(models.Model): name = models.CharField(max_length=30) actions = models.ManyToMany(Action) def call(): for (action in self.actions): action.run() class Meta: abstract = True
from django.db import models ## # Location Types ## class World(models.Model): name = models.CharField(max_length=30) homes = models.ManyToManyField(Home) class Home(models.Model): name = models.CharField(max_length=30) rooms = models.ManyToManyField(Room) class Room(models.Model): name = models.CharField(max_length=30) ## # Device Types ## class Device(models.Model): name = models.CharField(max_length=30) class Meta: abstract = True class OutputDevice(Device): actions = models.ManyToManyField(Action) class Meta: abstract = True class InputDevice(Device): events = models.ManyToManyField(Event) class Meta: abstract = True ## # Input/Output ## class Action(models.Model): name = models.CharField(max_length=30) def run() class Meta: abstract = True class Event(models.Model): name = models.CharField(max_length=30) actions = models.ManyToMany(Action) def call(): for (action in self.actions): action.run() class Meta: abstract = True Add table names to core model itemsfrom django.db import models ## # Location Types ## class World(models.Model): name = models.CharField(max_length=30) homes = models.ManyToManyField(Home) class Meta: db_table = u'Worlds' class Home(models.Model): name = models.CharField(max_length=30) rooms = models.ManyToManyField(Room) class Meta: db_table = u'Homes' class Room(models.Model): name = models.CharField(max_length=30) class Meta: db_table = u'Rooms' ## # Device Types ## class Device(models.Model): name = models.CharField(max_length=30) class Meta: abstract = True class OutputDevice(Device): actions = models.ManyToManyField(Action) class Meta: abstract = True class InputDevice(Device): events = models.ManyToManyField(Event) class Meta: abstract = True ## # Input/Output ## class Action(models.Model): name = models.CharField(max_length=30) def run() class Meta: abstract = True class Event(models.Model): name = models.CharField(max_length=30) actions = models.ManyToMany(Action) def call(): for (action in self.actions): action.run() class Meta: abstract = True
<commit_before>from django.db import models ## # Location Types ## class World(models.Model): name = models.CharField(max_length=30) homes = models.ManyToManyField(Home) class Home(models.Model): name = models.CharField(max_length=30) rooms = models.ManyToManyField(Room) class Room(models.Model): name = models.CharField(max_length=30) ## # Device Types ## class Device(models.Model): name = models.CharField(max_length=30) class Meta: abstract = True class OutputDevice(Device): actions = models.ManyToManyField(Action) class Meta: abstract = True class InputDevice(Device): events = models.ManyToManyField(Event) class Meta: abstract = True ## # Input/Output ## class Action(models.Model): name = models.CharField(max_length=30) def run() class Meta: abstract = True class Event(models.Model): name = models.CharField(max_length=30) actions = models.ManyToMany(Action) def call(): for (action in self.actions): action.run() class Meta: abstract = True <commit_msg>Add table names to core model items<commit_after>from django.db import models ## # Location Types ## class World(models.Model): name = models.CharField(max_length=30) homes = models.ManyToManyField(Home) class Meta: db_table = u'Worlds' class Home(models.Model): name = models.CharField(max_length=30) rooms = models.ManyToManyField(Room) class Meta: db_table = u'Homes' class Room(models.Model): name = models.CharField(max_length=30) class Meta: db_table = u'Rooms' ## # Device Types ## class Device(models.Model): name = models.CharField(max_length=30) class Meta: abstract = True class OutputDevice(Device): actions = models.ManyToManyField(Action) class Meta: abstract = True class InputDevice(Device): events = models.ManyToManyField(Event) class Meta: abstract = True ## # Input/Output ## class Action(models.Model): name = models.CharField(max_length=30) def run() class Meta: abstract = True class Event(models.Model): name = models.CharField(max_length=30) actions = models.ManyToMany(Action) def call(): for (action in self.actions): action.run() class Meta: abstract = True
239f24cc5dc5c0f25436ca1bfcfc536e30d62587
menu_generator/templatetags/menu_generator.py
menu_generator/templatetags/menu_generator.py
from django import template from django.conf import settings from .utils import get_menu_from_apps from .. import defaults from ..menu import generate_menu register = template.Library() @register.assignment_tag(takes_context=True) def get_menu(context, menu_name): """ Returns a consumable menu list for a given menu_name found in settings.py. Else it returns an empty list. Update, March 18 2017: Now the function get the menu list from settings and append more items if found on the menus.py's 'MENUS' dict. :param context: Template context :param menu_name: String, name of the menu to be found :return: Generated menu """ menu_list = getattr(settings, menu_name, defaults.MENU_NOT_FOUND) menu_from_apps = get_menu_from_apps(menu_name) # If there isn't a menu on settings but there is menu from apps we built menu from apps if menu_list == defaults.MENU_NOT_FOUND and menu_from_apps: menu_list = menu_from_apps # It there is a menu on settings and also on apps we merge both menus elif menu_list != defaults.MENU_NOT_FOUND and menu_from_apps: menu_list += menu_from_apps return generate_menu(context['request'], menu_list)
from django import template from django.conf import settings from .utils import get_menu_from_apps from .. import defaults from ..menu import generate_menu register = template.Library() @register.simple_tag(takes_context=True) def get_menu(context, menu_name): """ Returns a consumable menu list for a given menu_name found in settings.py. Else it returns an empty list. Update, March 18 2017: Now the function get the menu list from settings and append more items if found on the menus.py's 'MENUS' dict. :param context: Template context :param menu_name: String, name of the menu to be found :return: Generated menu """ menu_list = getattr(settings, menu_name, defaults.MENU_NOT_FOUND) menu_from_apps = get_menu_from_apps(menu_name) # If there isn't a menu on settings but there is menu from apps we built menu from apps if menu_list == defaults.MENU_NOT_FOUND and menu_from_apps: menu_list = menu_from_apps # It there is a menu on settings and also on apps we merge both menus elif menu_list != defaults.MENU_NOT_FOUND and menu_from_apps: menu_list += menu_from_apps return generate_menu(context['request'], menu_list)
Use simple_tag instead of assignment_tag
Use simple_tag instead of assignment_tag The assignment_tag is depraceted and in django-2.0 removed. Signed-off-by: Frantisek Lachman <bae095a6f6bdabf882218c81fdc3947ea1c10590@gmail.com>
Python
mit
yamijuan/django-menu-generator,RADYConsultores/django-menu-generator
from django import template from django.conf import settings from .utils import get_menu_from_apps from .. import defaults from ..menu import generate_menu register = template.Library() @register.assignment_tag(takes_context=True) def get_menu(context, menu_name): """ Returns a consumable menu list for a given menu_name found in settings.py. Else it returns an empty list. Update, March 18 2017: Now the function get the menu list from settings and append more items if found on the menus.py's 'MENUS' dict. :param context: Template context :param menu_name: String, name of the menu to be found :return: Generated menu """ menu_list = getattr(settings, menu_name, defaults.MENU_NOT_FOUND) menu_from_apps = get_menu_from_apps(menu_name) # If there isn't a menu on settings but there is menu from apps we built menu from apps if menu_list == defaults.MENU_NOT_FOUND and menu_from_apps: menu_list = menu_from_apps # It there is a menu on settings and also on apps we merge both menus elif menu_list != defaults.MENU_NOT_FOUND and menu_from_apps: menu_list += menu_from_apps return generate_menu(context['request'], menu_list) Use simple_tag instead of assignment_tag The assignment_tag is depraceted and in django-2.0 removed. Signed-off-by: Frantisek Lachman <bae095a6f6bdabf882218c81fdc3947ea1c10590@gmail.com>
from django import template from django.conf import settings from .utils import get_menu_from_apps from .. import defaults from ..menu import generate_menu register = template.Library() @register.simple_tag(takes_context=True) def get_menu(context, menu_name): """ Returns a consumable menu list for a given menu_name found in settings.py. Else it returns an empty list. Update, March 18 2017: Now the function get the menu list from settings and append more items if found on the menus.py's 'MENUS' dict. :param context: Template context :param menu_name: String, name of the menu to be found :return: Generated menu """ menu_list = getattr(settings, menu_name, defaults.MENU_NOT_FOUND) menu_from_apps = get_menu_from_apps(menu_name) # If there isn't a menu on settings but there is menu from apps we built menu from apps if menu_list == defaults.MENU_NOT_FOUND and menu_from_apps: menu_list = menu_from_apps # It there is a menu on settings and also on apps we merge both menus elif menu_list != defaults.MENU_NOT_FOUND and menu_from_apps: menu_list += menu_from_apps return generate_menu(context['request'], menu_list)
<commit_before>from django import template from django.conf import settings from .utils import get_menu_from_apps from .. import defaults from ..menu import generate_menu register = template.Library() @register.assignment_tag(takes_context=True) def get_menu(context, menu_name): """ Returns a consumable menu list for a given menu_name found in settings.py. Else it returns an empty list. Update, March 18 2017: Now the function get the menu list from settings and append more items if found on the menus.py's 'MENUS' dict. :param context: Template context :param menu_name: String, name of the menu to be found :return: Generated menu """ menu_list = getattr(settings, menu_name, defaults.MENU_NOT_FOUND) menu_from_apps = get_menu_from_apps(menu_name) # If there isn't a menu on settings but there is menu from apps we built menu from apps if menu_list == defaults.MENU_NOT_FOUND and menu_from_apps: menu_list = menu_from_apps # It there is a menu on settings and also on apps we merge both menus elif menu_list != defaults.MENU_NOT_FOUND and menu_from_apps: menu_list += menu_from_apps return generate_menu(context['request'], menu_list) <commit_msg>Use simple_tag instead of assignment_tag The assignment_tag is depraceted and in django-2.0 removed. Signed-off-by: Frantisek Lachman <bae095a6f6bdabf882218c81fdc3947ea1c10590@gmail.com><commit_after>
from django import template from django.conf import settings from .utils import get_menu_from_apps from .. import defaults from ..menu import generate_menu register = template.Library() @register.simple_tag(takes_context=True) def get_menu(context, menu_name): """ Returns a consumable menu list for a given menu_name found in settings.py. Else it returns an empty list. Update, March 18 2017: Now the function get the menu list from settings and append more items if found on the menus.py's 'MENUS' dict. :param context: Template context :param menu_name: String, name of the menu to be found :return: Generated menu """ menu_list = getattr(settings, menu_name, defaults.MENU_NOT_FOUND) menu_from_apps = get_menu_from_apps(menu_name) # If there isn't a menu on settings but there is menu from apps we built menu from apps if menu_list == defaults.MENU_NOT_FOUND and menu_from_apps: menu_list = menu_from_apps # It there is a menu on settings and also on apps we merge both menus elif menu_list != defaults.MENU_NOT_FOUND and menu_from_apps: menu_list += menu_from_apps return generate_menu(context['request'], menu_list)
from django import template from django.conf import settings from .utils import get_menu_from_apps from .. import defaults from ..menu import generate_menu register = template.Library() @register.assignment_tag(takes_context=True) def get_menu(context, menu_name): """ Returns a consumable menu list for a given menu_name found in settings.py. Else it returns an empty list. Update, March 18 2017: Now the function get the menu list from settings and append more items if found on the menus.py's 'MENUS' dict. :param context: Template context :param menu_name: String, name of the menu to be found :return: Generated menu """ menu_list = getattr(settings, menu_name, defaults.MENU_NOT_FOUND) menu_from_apps = get_menu_from_apps(menu_name) # If there isn't a menu on settings but there is menu from apps we built menu from apps if menu_list == defaults.MENU_NOT_FOUND and menu_from_apps: menu_list = menu_from_apps # It there is a menu on settings and also on apps we merge both menus elif menu_list != defaults.MENU_NOT_FOUND and menu_from_apps: menu_list += menu_from_apps return generate_menu(context['request'], menu_list) Use simple_tag instead of assignment_tag The assignment_tag is depraceted and in django-2.0 removed. Signed-off-by: Frantisek Lachman <bae095a6f6bdabf882218c81fdc3947ea1c10590@gmail.com>from django import template from django.conf import settings from .utils import get_menu_from_apps from .. import defaults from ..menu import generate_menu register = template.Library() @register.simple_tag(takes_context=True) def get_menu(context, menu_name): """ Returns a consumable menu list for a given menu_name found in settings.py. Else it returns an empty list. Update, March 18 2017: Now the function get the menu list from settings and append more items if found on the menus.py's 'MENUS' dict. :param context: Template context :param menu_name: String, name of the menu to be found :return: Generated menu """ menu_list = getattr(settings, menu_name, defaults.MENU_NOT_FOUND) menu_from_apps = get_menu_from_apps(menu_name) # If there isn't a menu on settings but there is menu from apps we built menu from apps if menu_list == defaults.MENU_NOT_FOUND and menu_from_apps: menu_list = menu_from_apps # It there is a menu on settings and also on apps we merge both menus elif menu_list != defaults.MENU_NOT_FOUND and menu_from_apps: menu_list += menu_from_apps return generate_menu(context['request'], menu_list)
<commit_before>from django import template from django.conf import settings from .utils import get_menu_from_apps from .. import defaults from ..menu import generate_menu register = template.Library() @register.assignment_tag(takes_context=True) def get_menu(context, menu_name): """ Returns a consumable menu list for a given menu_name found in settings.py. Else it returns an empty list. Update, March 18 2017: Now the function get the menu list from settings and append more items if found on the menus.py's 'MENUS' dict. :param context: Template context :param menu_name: String, name of the menu to be found :return: Generated menu """ menu_list = getattr(settings, menu_name, defaults.MENU_NOT_FOUND) menu_from_apps = get_menu_from_apps(menu_name) # If there isn't a menu on settings but there is menu from apps we built menu from apps if menu_list == defaults.MENU_NOT_FOUND and menu_from_apps: menu_list = menu_from_apps # It there is a menu on settings and also on apps we merge both menus elif menu_list != defaults.MENU_NOT_FOUND and menu_from_apps: menu_list += menu_from_apps return generate_menu(context['request'], menu_list) <commit_msg>Use simple_tag instead of assignment_tag The assignment_tag is depraceted and in django-2.0 removed. Signed-off-by: Frantisek Lachman <bae095a6f6bdabf882218c81fdc3947ea1c10590@gmail.com><commit_after>from django import template from django.conf import settings from .utils import get_menu_from_apps from .. import defaults from ..menu import generate_menu register = template.Library() @register.simple_tag(takes_context=True) def get_menu(context, menu_name): """ Returns a consumable menu list for a given menu_name found in settings.py. Else it returns an empty list. Update, March 18 2017: Now the function get the menu list from settings and append more items if found on the menus.py's 'MENUS' dict. :param context: Template context :param menu_name: String, name of the menu to be found :return: Generated menu """ menu_list = getattr(settings, menu_name, defaults.MENU_NOT_FOUND) menu_from_apps = get_menu_from_apps(menu_name) # If there isn't a menu on settings but there is menu from apps we built menu from apps if menu_list == defaults.MENU_NOT_FOUND and menu_from_apps: menu_list = menu_from_apps # It there is a menu on settings and also on apps we merge both menus elif menu_list != defaults.MENU_NOT_FOUND and menu_from_apps: menu_list += menu_from_apps return generate_menu(context['request'], menu_list)
3d0adce620606e4d997946f6ad886dee0403a7dd
pip_package/rlds_version.py
pip_package/rlds_version.py
# Copyright 2021 Google LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # coding=utf-8 # python3 """Package metadata for RLDS. This is kept in a separate module so that it can be imported from setup.py, at a time when RLDS's dependencies may not have been installed yet. """ # We follow Semantic Versioning (https://semver.org/) _MAJOR_VERSION = '0' _MINOR_VERSION = '1' _PATCH_VERSION = '0' # Example: '0.4.2' __version__ = '.'.join([_MAJOR_VERSION, _MINOR_VERSION, _PATCH_VERSION])
# Copyright 2021 Google LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # coding=utf-8 # python3 """Package metadata for RLDS. This is kept in a separate module so that it can be imported from setup.py, at a time when RLDS's dependencies may not have been installed yet. """ # We follow Semantic Versioning (https://semver.org/) _MAJOR_VERSION = '0' _MINOR_VERSION = '1' _PATCH_VERSION = '1' # Example: '0.4.2' __version__ = '.'.join([_MAJOR_VERSION, _MINOR_VERSION, _PATCH_VERSION])
Update to version 0.1.1 (already in pypi).
Update to version 0.1.1 (already in pypi). PiperOrigin-RevId: 391948484 Change-Id: Idf5c7f00dbba8ffe2ca292961d4e0e0e26bcd1cb
Python
apache-2.0
google-research/rlds,google-research/rlds
# Copyright 2021 Google LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # coding=utf-8 # python3 """Package metadata for RLDS. This is kept in a separate module so that it can be imported from setup.py, at a time when RLDS's dependencies may not have been installed yet. """ # We follow Semantic Versioning (https://semver.org/) _MAJOR_VERSION = '0' _MINOR_VERSION = '1' _PATCH_VERSION = '0' # Example: '0.4.2' __version__ = '.'.join([_MAJOR_VERSION, _MINOR_VERSION, _PATCH_VERSION]) Update to version 0.1.1 (already in pypi). PiperOrigin-RevId: 391948484 Change-Id: Idf5c7f00dbba8ffe2ca292961d4e0e0e26bcd1cb
# Copyright 2021 Google LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # coding=utf-8 # python3 """Package metadata for RLDS. This is kept in a separate module so that it can be imported from setup.py, at a time when RLDS's dependencies may not have been installed yet. """ # We follow Semantic Versioning (https://semver.org/) _MAJOR_VERSION = '0' _MINOR_VERSION = '1' _PATCH_VERSION = '1' # Example: '0.4.2' __version__ = '.'.join([_MAJOR_VERSION, _MINOR_VERSION, _PATCH_VERSION])
<commit_before># Copyright 2021 Google LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # coding=utf-8 # python3 """Package metadata for RLDS. This is kept in a separate module so that it can be imported from setup.py, at a time when RLDS's dependencies may not have been installed yet. """ # We follow Semantic Versioning (https://semver.org/) _MAJOR_VERSION = '0' _MINOR_VERSION = '1' _PATCH_VERSION = '0' # Example: '0.4.2' __version__ = '.'.join([_MAJOR_VERSION, _MINOR_VERSION, _PATCH_VERSION]) <commit_msg>Update to version 0.1.1 (already in pypi). PiperOrigin-RevId: 391948484 Change-Id: Idf5c7f00dbba8ffe2ca292961d4e0e0e26bcd1cb<commit_after>
# Copyright 2021 Google LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # coding=utf-8 # python3 """Package metadata for RLDS. This is kept in a separate module so that it can be imported from setup.py, at a time when RLDS's dependencies may not have been installed yet. """ # We follow Semantic Versioning (https://semver.org/) _MAJOR_VERSION = '0' _MINOR_VERSION = '1' _PATCH_VERSION = '1' # Example: '0.4.2' __version__ = '.'.join([_MAJOR_VERSION, _MINOR_VERSION, _PATCH_VERSION])
# Copyright 2021 Google LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # coding=utf-8 # python3 """Package metadata for RLDS. This is kept in a separate module so that it can be imported from setup.py, at a time when RLDS's dependencies may not have been installed yet. """ # We follow Semantic Versioning (https://semver.org/) _MAJOR_VERSION = '0' _MINOR_VERSION = '1' _PATCH_VERSION = '0' # Example: '0.4.2' __version__ = '.'.join([_MAJOR_VERSION, _MINOR_VERSION, _PATCH_VERSION]) Update to version 0.1.1 (already in pypi). PiperOrigin-RevId: 391948484 Change-Id: Idf5c7f00dbba8ffe2ca292961d4e0e0e26bcd1cb# Copyright 2021 Google LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # coding=utf-8 # python3 """Package metadata for RLDS. This is kept in a separate module so that it can be imported from setup.py, at a time when RLDS's dependencies may not have been installed yet. """ # We follow Semantic Versioning (https://semver.org/) _MAJOR_VERSION = '0' _MINOR_VERSION = '1' _PATCH_VERSION = '1' # Example: '0.4.2' __version__ = '.'.join([_MAJOR_VERSION, _MINOR_VERSION, _PATCH_VERSION])
<commit_before># Copyright 2021 Google LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # coding=utf-8 # python3 """Package metadata for RLDS. This is kept in a separate module so that it can be imported from setup.py, at a time when RLDS's dependencies may not have been installed yet. """ # We follow Semantic Versioning (https://semver.org/) _MAJOR_VERSION = '0' _MINOR_VERSION = '1' _PATCH_VERSION = '0' # Example: '0.4.2' __version__ = '.'.join([_MAJOR_VERSION, _MINOR_VERSION, _PATCH_VERSION]) <commit_msg>Update to version 0.1.1 (already in pypi). PiperOrigin-RevId: 391948484 Change-Id: Idf5c7f00dbba8ffe2ca292961d4e0e0e26bcd1cb<commit_after># Copyright 2021 Google LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # coding=utf-8 # python3 """Package metadata for RLDS. This is kept in a separate module so that it can be imported from setup.py, at a time when RLDS's dependencies may not have been installed yet. """ # We follow Semantic Versioning (https://semver.org/) _MAJOR_VERSION = '0' _MINOR_VERSION = '1' _PATCH_VERSION = '1' # Example: '0.4.2' __version__ = '.'.join([_MAJOR_VERSION, _MINOR_VERSION, _PATCH_VERSION])
6a856e613248e32bd7fc8027adfb9df4d74b2357
candidates/management/commands/candidates_make_party_sets_lookup.py
candidates/management/commands/candidates_make_party_sets_lookup.py
import json from os.path import dirname, join, realpath from django.conf import settings from django.core.management.base import BaseCommand from candidates.election_specific import AREA_POST_DATA from candidates.popit import get_all_posts class Command(BaseCommand): def handle(self, **options): repo_root = realpath(join(dirname(__file__), '..', '..', '..')) output_filename = join( repo_root, 'elections', settings.ELECTION_APP, 'static', 'js', 'post-to-party-set.js', ) with open(output_filename, 'w') as f: f.write('var postIDToPartySet = ') mapping = { post['id']: AREA_POST_DATA.post_id_to_party_set(post['id']) for election, election_data in settings.ELECTIONS_CURRENT for post in get_all_posts(election_data['for_post_role']) } unknown_post_ids = [ k for k, v in mapping.items() if v is None ] f.write(json.dumps(mapping)) f.write(';\n') if unknown_post_ids: print "Warning: no party set could be found for these post IDs:" print unknown_post_ids
import json from os.path import dirname, join, realpath from django.conf import settings from django.core.management.base import BaseCommand from candidates.election_specific import AREA_POST_DATA from candidates.popit import get_all_posts class Command(BaseCommand): def handle(self, **options): repo_root = realpath(join(dirname(__file__), '..', '..', '..')) output_filename = join( repo_root, 'elections', settings.ELECTION_APP, 'static', 'js', 'post-to-party-set.js', ) with open(output_filename, 'w') as f: f.write('var postIDToPartySet = ') mapping = { post['id']: AREA_POST_DATA.post_id_to_party_set(post['id']) for election, election_data in settings.ELECTIONS_CURRENT for post in get_all_posts(election_data['for_post_role']) } unknown_post_ids = [ k for k, v in mapping.items() if v is None ] f.write(json.dumps(mapping, sort_keys=True)) f.write(';\n') if unknown_post_ids: print "Warning: no party set could be found for these post IDs:" print unknown_post_ids
Make the party set JS generator output keys in a predictable order
Make the party set JS generator output keys in a predictable order This makes it easier to check with "git diff" if there have been any changes.
Python
agpl-3.0
neavouli/yournextrepresentative,neavouli/yournextrepresentative,mysociety/yournextmp-popit,neavouli/yournextrepresentative,DemocracyClub/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextmp-popit,mysociety/yournextrepresentative,mysociety/yournextmp-popit,datamade/yournextmp-popit,neavouli/yournextrepresentative,datamade/yournextmp-popit,DemocracyClub/yournextrepresentative,datamade/yournextmp-popit,DemocracyClub/yournextrepresentative,datamade/yournextmp-popit,mysociety/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextmp-popit,datamade/yournextmp-popit,neavouli/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextmp-popit
import json from os.path import dirname, join, realpath from django.conf import settings from django.core.management.base import BaseCommand from candidates.election_specific import AREA_POST_DATA from candidates.popit import get_all_posts class Command(BaseCommand): def handle(self, **options): repo_root = realpath(join(dirname(__file__), '..', '..', '..')) output_filename = join( repo_root, 'elections', settings.ELECTION_APP, 'static', 'js', 'post-to-party-set.js', ) with open(output_filename, 'w') as f: f.write('var postIDToPartySet = ') mapping = { post['id']: AREA_POST_DATA.post_id_to_party_set(post['id']) for election, election_data in settings.ELECTIONS_CURRENT for post in get_all_posts(election_data['for_post_role']) } unknown_post_ids = [ k for k, v in mapping.items() if v is None ] f.write(json.dumps(mapping)) f.write(';\n') if unknown_post_ids: print "Warning: no party set could be found for these post IDs:" print unknown_post_ids Make the party set JS generator output keys in a predictable order This makes it easier to check with "git diff" if there have been any changes.
import json from os.path import dirname, join, realpath from django.conf import settings from django.core.management.base import BaseCommand from candidates.election_specific import AREA_POST_DATA from candidates.popit import get_all_posts class Command(BaseCommand): def handle(self, **options): repo_root = realpath(join(dirname(__file__), '..', '..', '..')) output_filename = join( repo_root, 'elections', settings.ELECTION_APP, 'static', 'js', 'post-to-party-set.js', ) with open(output_filename, 'w') as f: f.write('var postIDToPartySet = ') mapping = { post['id']: AREA_POST_DATA.post_id_to_party_set(post['id']) for election, election_data in settings.ELECTIONS_CURRENT for post in get_all_posts(election_data['for_post_role']) } unknown_post_ids = [ k for k, v in mapping.items() if v is None ] f.write(json.dumps(mapping, sort_keys=True)) f.write(';\n') if unknown_post_ids: print "Warning: no party set could be found for these post IDs:" print unknown_post_ids
<commit_before>import json from os.path import dirname, join, realpath from django.conf import settings from django.core.management.base import BaseCommand from candidates.election_specific import AREA_POST_DATA from candidates.popit import get_all_posts class Command(BaseCommand): def handle(self, **options): repo_root = realpath(join(dirname(__file__), '..', '..', '..')) output_filename = join( repo_root, 'elections', settings.ELECTION_APP, 'static', 'js', 'post-to-party-set.js', ) with open(output_filename, 'w') as f: f.write('var postIDToPartySet = ') mapping = { post['id']: AREA_POST_DATA.post_id_to_party_set(post['id']) for election, election_data in settings.ELECTIONS_CURRENT for post in get_all_posts(election_data['for_post_role']) } unknown_post_ids = [ k for k, v in mapping.items() if v is None ] f.write(json.dumps(mapping)) f.write(';\n') if unknown_post_ids: print "Warning: no party set could be found for these post IDs:" print unknown_post_ids <commit_msg>Make the party set JS generator output keys in a predictable order This makes it easier to check with "git diff" if there have been any changes.<commit_after>
import json from os.path import dirname, join, realpath from django.conf import settings from django.core.management.base import BaseCommand from candidates.election_specific import AREA_POST_DATA from candidates.popit import get_all_posts class Command(BaseCommand): def handle(self, **options): repo_root = realpath(join(dirname(__file__), '..', '..', '..')) output_filename = join( repo_root, 'elections', settings.ELECTION_APP, 'static', 'js', 'post-to-party-set.js', ) with open(output_filename, 'w') as f: f.write('var postIDToPartySet = ') mapping = { post['id']: AREA_POST_DATA.post_id_to_party_set(post['id']) for election, election_data in settings.ELECTIONS_CURRENT for post in get_all_posts(election_data['for_post_role']) } unknown_post_ids = [ k for k, v in mapping.items() if v is None ] f.write(json.dumps(mapping, sort_keys=True)) f.write(';\n') if unknown_post_ids: print "Warning: no party set could be found for these post IDs:" print unknown_post_ids
import json from os.path import dirname, join, realpath from django.conf import settings from django.core.management.base import BaseCommand from candidates.election_specific import AREA_POST_DATA from candidates.popit import get_all_posts class Command(BaseCommand): def handle(self, **options): repo_root = realpath(join(dirname(__file__), '..', '..', '..')) output_filename = join( repo_root, 'elections', settings.ELECTION_APP, 'static', 'js', 'post-to-party-set.js', ) with open(output_filename, 'w') as f: f.write('var postIDToPartySet = ') mapping = { post['id']: AREA_POST_DATA.post_id_to_party_set(post['id']) for election, election_data in settings.ELECTIONS_CURRENT for post in get_all_posts(election_data['for_post_role']) } unknown_post_ids = [ k for k, v in mapping.items() if v is None ] f.write(json.dumps(mapping)) f.write(';\n') if unknown_post_ids: print "Warning: no party set could be found for these post IDs:" print unknown_post_ids Make the party set JS generator output keys in a predictable order This makes it easier to check with "git diff" if there have been any changes.import json from os.path import dirname, join, realpath from django.conf import settings from django.core.management.base import BaseCommand from candidates.election_specific import AREA_POST_DATA from candidates.popit import get_all_posts class Command(BaseCommand): def handle(self, **options): repo_root = realpath(join(dirname(__file__), '..', '..', '..')) output_filename = join( repo_root, 'elections', settings.ELECTION_APP, 'static', 'js', 'post-to-party-set.js', ) with open(output_filename, 'w') as f: f.write('var postIDToPartySet = ') mapping = { post['id']: AREA_POST_DATA.post_id_to_party_set(post['id']) for election, election_data in settings.ELECTIONS_CURRENT for post in get_all_posts(election_data['for_post_role']) } unknown_post_ids = [ k for k, v in mapping.items() if v is None ] f.write(json.dumps(mapping, sort_keys=True)) f.write(';\n') if unknown_post_ids: print "Warning: no party set could be found for these post IDs:" print unknown_post_ids
<commit_before>import json from os.path import dirname, join, realpath from django.conf import settings from django.core.management.base import BaseCommand from candidates.election_specific import AREA_POST_DATA from candidates.popit import get_all_posts class Command(BaseCommand): def handle(self, **options): repo_root = realpath(join(dirname(__file__), '..', '..', '..')) output_filename = join( repo_root, 'elections', settings.ELECTION_APP, 'static', 'js', 'post-to-party-set.js', ) with open(output_filename, 'w') as f: f.write('var postIDToPartySet = ') mapping = { post['id']: AREA_POST_DATA.post_id_to_party_set(post['id']) for election, election_data in settings.ELECTIONS_CURRENT for post in get_all_posts(election_data['for_post_role']) } unknown_post_ids = [ k for k, v in mapping.items() if v is None ] f.write(json.dumps(mapping)) f.write(';\n') if unknown_post_ids: print "Warning: no party set could be found for these post IDs:" print unknown_post_ids <commit_msg>Make the party set JS generator output keys in a predictable order This makes it easier to check with "git diff" if there have been any changes.<commit_after>import json from os.path import dirname, join, realpath from django.conf import settings from django.core.management.base import BaseCommand from candidates.election_specific import AREA_POST_DATA from candidates.popit import get_all_posts class Command(BaseCommand): def handle(self, **options): repo_root = realpath(join(dirname(__file__), '..', '..', '..')) output_filename = join( repo_root, 'elections', settings.ELECTION_APP, 'static', 'js', 'post-to-party-set.js', ) with open(output_filename, 'w') as f: f.write('var postIDToPartySet = ') mapping = { post['id']: AREA_POST_DATA.post_id_to_party_set(post['id']) for election, election_data in settings.ELECTIONS_CURRENT for post in get_all_posts(election_data['for_post_role']) } unknown_post_ids = [ k for k, v in mapping.items() if v is None ] f.write(json.dumps(mapping, sort_keys=True)) f.write(';\n') if unknown_post_ids: print "Warning: no party set could be found for these post IDs:" print unknown_post_ids
c126b7a6b060a30e5d5c698dfa3210786f169b92
camoco/cli/commands/remove.py
camoco/cli/commands/remove.py
import camoco as co def remove(args): print(co.del_dataset(args.type,args.name,safe=args.force))
import camoco as co def remove(args): co.del_dataset(args.type,args.name,safe=args.force) print('Done')
Make stderr messages more interpretable
Make stderr messages more interpretable
Python
mit
schae234/Camoco,schae234/Camoco
import camoco as co def remove(args): print(co.del_dataset(args.type,args.name,safe=args.force)) Make stderr messages more interpretable
import camoco as co def remove(args): co.del_dataset(args.type,args.name,safe=args.force) print('Done')
<commit_before>import camoco as co def remove(args): print(co.del_dataset(args.type,args.name,safe=args.force)) <commit_msg>Make stderr messages more interpretable<commit_after>
import camoco as co def remove(args): co.del_dataset(args.type,args.name,safe=args.force) print('Done')
import camoco as co def remove(args): print(co.del_dataset(args.type,args.name,safe=args.force)) Make stderr messages more interpretableimport camoco as co def remove(args): co.del_dataset(args.type,args.name,safe=args.force) print('Done')
<commit_before>import camoco as co def remove(args): print(co.del_dataset(args.type,args.name,safe=args.force)) <commit_msg>Make stderr messages more interpretable<commit_after>import camoco as co def remove(args): co.del_dataset(args.type,args.name,safe=args.force) print('Done')
fab561da9c54e278e7762380bf043a2fe03e39da
xerox/darwin.py
xerox/darwin.py
# -*- coding: utf-8 -*- """ Copy + Paste in OS X """ import subprocess import commands from .base import * def copy(string): """Copy given string into system clipboard.""" try: subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE).communicate(str(unicode(string))) except OSError as why: raise XcodeNotFound return def paste(): """Returns system clipboard contents.""" try: return unicode(commands.getoutput('pbpaste')) except OSError as why: raise XcodeNotFound
# -*- coding: utf-8 -*- """ Copy + Paste in OS X """ import subprocess from .base import * def copy(string): """Copy given string into system clipboard.""" try: subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE).communicate(str(unicode(string))) except OSError as why: raise XcodeNotFound return def paste(): """Returns system clipboard contents.""" try: return unicode(subprocess.check_output('pbpaste')) except OSError as why: raise XcodeNotFound
Use `subprocess.check_output` rather than `commands.getoutput`.
Use `subprocess.check_output` rather than `commands.getoutput`. `commands` is deprecated.
Python
mit
solarce/xerox,kennethreitz/xerox
# -*- coding: utf-8 -*- """ Copy + Paste in OS X """ import subprocess import commands from .base import * def copy(string): """Copy given string into system clipboard.""" try: subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE).communicate(str(unicode(string))) except OSError as why: raise XcodeNotFound return def paste(): """Returns system clipboard contents.""" try: return unicode(commands.getoutput('pbpaste')) except OSError as why: raise XcodeNotFound Use `subprocess.check_output` rather than `commands.getoutput`. `commands` is deprecated.
# -*- coding: utf-8 -*- """ Copy + Paste in OS X """ import subprocess from .base import * def copy(string): """Copy given string into system clipboard.""" try: subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE).communicate(str(unicode(string))) except OSError as why: raise XcodeNotFound return def paste(): """Returns system clipboard contents.""" try: return unicode(subprocess.check_output('pbpaste')) except OSError as why: raise XcodeNotFound
<commit_before># -*- coding: utf-8 -*- """ Copy + Paste in OS X """ import subprocess import commands from .base import * def copy(string): """Copy given string into system clipboard.""" try: subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE).communicate(str(unicode(string))) except OSError as why: raise XcodeNotFound return def paste(): """Returns system clipboard contents.""" try: return unicode(commands.getoutput('pbpaste')) except OSError as why: raise XcodeNotFound <commit_msg>Use `subprocess.check_output` rather than `commands.getoutput`. `commands` is deprecated.<commit_after>
# -*- coding: utf-8 -*- """ Copy + Paste in OS X """ import subprocess from .base import * def copy(string): """Copy given string into system clipboard.""" try: subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE).communicate(str(unicode(string))) except OSError as why: raise XcodeNotFound return def paste(): """Returns system clipboard contents.""" try: return unicode(subprocess.check_output('pbpaste')) except OSError as why: raise XcodeNotFound
# -*- coding: utf-8 -*- """ Copy + Paste in OS X """ import subprocess import commands from .base import * def copy(string): """Copy given string into system clipboard.""" try: subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE).communicate(str(unicode(string))) except OSError as why: raise XcodeNotFound return def paste(): """Returns system clipboard contents.""" try: return unicode(commands.getoutput('pbpaste')) except OSError as why: raise XcodeNotFound Use `subprocess.check_output` rather than `commands.getoutput`. `commands` is deprecated.# -*- coding: utf-8 -*- """ Copy + Paste in OS X """ import subprocess from .base import * def copy(string): """Copy given string into system clipboard.""" try: subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE).communicate(str(unicode(string))) except OSError as why: raise XcodeNotFound return def paste(): """Returns system clipboard contents.""" try: return unicode(subprocess.check_output('pbpaste')) except OSError as why: raise XcodeNotFound
<commit_before># -*- coding: utf-8 -*- """ Copy + Paste in OS X """ import subprocess import commands from .base import * def copy(string): """Copy given string into system clipboard.""" try: subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE).communicate(str(unicode(string))) except OSError as why: raise XcodeNotFound return def paste(): """Returns system clipboard contents.""" try: return unicode(commands.getoutput('pbpaste')) except OSError as why: raise XcodeNotFound <commit_msg>Use `subprocess.check_output` rather than `commands.getoutput`. `commands` is deprecated.<commit_after># -*- coding: utf-8 -*- """ Copy + Paste in OS X """ import subprocess from .base import * def copy(string): """Copy given string into system clipboard.""" try: subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE).communicate(str(unicode(string))) except OSError as why: raise XcodeNotFound return def paste(): """Returns system clipboard contents.""" try: return unicode(subprocess.check_output('pbpaste')) except OSError as why: raise XcodeNotFound
7816cf0562435176a33add229942ac3ee8e7b94c
yolodex/urls.py
yolodex/urls.py
from django.conf.urls import patterns, url from django.utils.translation import ugettext_lazy as _ from .views import ( RealmView, RealmCorrectionsView, EntitySearchView, EntityListView, EntityDetailView, EntityDetailNetworkEmbedView, ) from .api_views import ( YolodexRouter, EntityViewSet, EntityTypeViewSet ) router = YolodexRouter() router.register(r'api/entity', EntityViewSet, 'entity') router.register(r'api/entitytype', EntityTypeViewSet, 'entitytype') entity_urls = [ url(r'^$', RealmView.as_view(), name='overview'), url(_(r'^corrections/$'), RealmCorrectionsView.as_view(), name='corrections'), url(_(r'^search/$'), EntitySearchView.as_view(), name='search'), url(r'^(?P<type>[\w-]+)/$', EntityListView.as_view(), name='entity_list'), url(r'^(?P<type>[\w-]+)/(?P<slug>[\w-]+)/$', EntityDetailView.as_view(), name='entity_detail'), url(r'^(?P<type>[\w-]+)/(?P<slug>[\w-]+)/embed/$', EntityDetailNetworkEmbedView.as_view(), name='entity_detail_embed'), ] urlpatterns = router.urls urlpatterns += patterns('', *entity_urls)
from django.conf.urls import url from django.utils.translation import ugettext_lazy as _ from .views import ( RealmView, RealmCorrectionsView, EntitySearchView, EntityListView, EntityDetailView, EntityDetailNetworkEmbedView, ) from .api_views import ( YolodexRouter, EntityViewSet, EntityTypeViewSet ) router = YolodexRouter() router.register(r'api/entity', EntityViewSet, 'entity') router.register(r'api/entitytype', EntityTypeViewSet, 'entitytype') entity_urls = [ url(r'^$', RealmView.as_view(), name='overview'), url(_(r'^corrections/$'), RealmCorrectionsView.as_view(), name='corrections'), url(_(r'^search/$'), EntitySearchView.as_view(), name='search'), url(r'^(?P<type>[\w-]+)/$', EntityListView.as_view(), name='entity_list'), url(r'^(?P<type>[\w-]+)/(?P<slug>[\w-]+)/$', EntityDetailView.as_view(), name='entity_detail'), url(r'^(?P<type>[\w-]+)/(?P<slug>[\w-]+)/embed/$', EntityDetailNetworkEmbedView.as_view(), name='entity_detail_embed'), ] urlpatterns = router.urls urlpatterns += entity_urls
Update urlpatterns and remove old patterns pattern
Update urlpatterns and remove old patterns pattern
Python
mit
correctiv/django-yolodex,correctiv/django-yolodex,correctiv/django-yolodex
from django.conf.urls import patterns, url from django.utils.translation import ugettext_lazy as _ from .views import ( RealmView, RealmCorrectionsView, EntitySearchView, EntityListView, EntityDetailView, EntityDetailNetworkEmbedView, ) from .api_views import ( YolodexRouter, EntityViewSet, EntityTypeViewSet ) router = YolodexRouter() router.register(r'api/entity', EntityViewSet, 'entity') router.register(r'api/entitytype', EntityTypeViewSet, 'entitytype') entity_urls = [ url(r'^$', RealmView.as_view(), name='overview'), url(_(r'^corrections/$'), RealmCorrectionsView.as_view(), name='corrections'), url(_(r'^search/$'), EntitySearchView.as_view(), name='search'), url(r'^(?P<type>[\w-]+)/$', EntityListView.as_view(), name='entity_list'), url(r'^(?P<type>[\w-]+)/(?P<slug>[\w-]+)/$', EntityDetailView.as_view(), name='entity_detail'), url(r'^(?P<type>[\w-]+)/(?P<slug>[\w-]+)/embed/$', EntityDetailNetworkEmbedView.as_view(), name='entity_detail_embed'), ] urlpatterns = router.urls urlpatterns += patterns('', *entity_urls) Update urlpatterns and remove old patterns pattern
from django.conf.urls import url from django.utils.translation import ugettext_lazy as _ from .views import ( RealmView, RealmCorrectionsView, EntitySearchView, EntityListView, EntityDetailView, EntityDetailNetworkEmbedView, ) from .api_views import ( YolodexRouter, EntityViewSet, EntityTypeViewSet ) router = YolodexRouter() router.register(r'api/entity', EntityViewSet, 'entity') router.register(r'api/entitytype', EntityTypeViewSet, 'entitytype') entity_urls = [ url(r'^$', RealmView.as_view(), name='overview'), url(_(r'^corrections/$'), RealmCorrectionsView.as_view(), name='corrections'), url(_(r'^search/$'), EntitySearchView.as_view(), name='search'), url(r'^(?P<type>[\w-]+)/$', EntityListView.as_view(), name='entity_list'), url(r'^(?P<type>[\w-]+)/(?P<slug>[\w-]+)/$', EntityDetailView.as_view(), name='entity_detail'), url(r'^(?P<type>[\w-]+)/(?P<slug>[\w-]+)/embed/$', EntityDetailNetworkEmbedView.as_view(), name='entity_detail_embed'), ] urlpatterns = router.urls urlpatterns += entity_urls
<commit_before>from django.conf.urls import patterns, url from django.utils.translation import ugettext_lazy as _ from .views import ( RealmView, RealmCorrectionsView, EntitySearchView, EntityListView, EntityDetailView, EntityDetailNetworkEmbedView, ) from .api_views import ( YolodexRouter, EntityViewSet, EntityTypeViewSet ) router = YolodexRouter() router.register(r'api/entity', EntityViewSet, 'entity') router.register(r'api/entitytype', EntityTypeViewSet, 'entitytype') entity_urls = [ url(r'^$', RealmView.as_view(), name='overview'), url(_(r'^corrections/$'), RealmCorrectionsView.as_view(), name='corrections'), url(_(r'^search/$'), EntitySearchView.as_view(), name='search'), url(r'^(?P<type>[\w-]+)/$', EntityListView.as_view(), name='entity_list'), url(r'^(?P<type>[\w-]+)/(?P<slug>[\w-]+)/$', EntityDetailView.as_view(), name='entity_detail'), url(r'^(?P<type>[\w-]+)/(?P<slug>[\w-]+)/embed/$', EntityDetailNetworkEmbedView.as_view(), name='entity_detail_embed'), ] urlpatterns = router.urls urlpatterns += patterns('', *entity_urls) <commit_msg>Update urlpatterns and remove old patterns pattern<commit_after>
from django.conf.urls import url from django.utils.translation import ugettext_lazy as _ from .views import ( RealmView, RealmCorrectionsView, EntitySearchView, EntityListView, EntityDetailView, EntityDetailNetworkEmbedView, ) from .api_views import ( YolodexRouter, EntityViewSet, EntityTypeViewSet ) router = YolodexRouter() router.register(r'api/entity', EntityViewSet, 'entity') router.register(r'api/entitytype', EntityTypeViewSet, 'entitytype') entity_urls = [ url(r'^$', RealmView.as_view(), name='overview'), url(_(r'^corrections/$'), RealmCorrectionsView.as_view(), name='corrections'), url(_(r'^search/$'), EntitySearchView.as_view(), name='search'), url(r'^(?P<type>[\w-]+)/$', EntityListView.as_view(), name='entity_list'), url(r'^(?P<type>[\w-]+)/(?P<slug>[\w-]+)/$', EntityDetailView.as_view(), name='entity_detail'), url(r'^(?P<type>[\w-]+)/(?P<slug>[\w-]+)/embed/$', EntityDetailNetworkEmbedView.as_view(), name='entity_detail_embed'), ] urlpatterns = router.urls urlpatterns += entity_urls
from django.conf.urls import patterns, url from django.utils.translation import ugettext_lazy as _ from .views import ( RealmView, RealmCorrectionsView, EntitySearchView, EntityListView, EntityDetailView, EntityDetailNetworkEmbedView, ) from .api_views import ( YolodexRouter, EntityViewSet, EntityTypeViewSet ) router = YolodexRouter() router.register(r'api/entity', EntityViewSet, 'entity') router.register(r'api/entitytype', EntityTypeViewSet, 'entitytype') entity_urls = [ url(r'^$', RealmView.as_view(), name='overview'), url(_(r'^corrections/$'), RealmCorrectionsView.as_view(), name='corrections'), url(_(r'^search/$'), EntitySearchView.as_view(), name='search'), url(r'^(?P<type>[\w-]+)/$', EntityListView.as_view(), name='entity_list'), url(r'^(?P<type>[\w-]+)/(?P<slug>[\w-]+)/$', EntityDetailView.as_view(), name='entity_detail'), url(r'^(?P<type>[\w-]+)/(?P<slug>[\w-]+)/embed/$', EntityDetailNetworkEmbedView.as_view(), name='entity_detail_embed'), ] urlpatterns = router.urls urlpatterns += patterns('', *entity_urls) Update urlpatterns and remove old patterns patternfrom django.conf.urls import url from django.utils.translation import ugettext_lazy as _ from .views import ( RealmView, RealmCorrectionsView, EntitySearchView, EntityListView, EntityDetailView, EntityDetailNetworkEmbedView, ) from .api_views import ( YolodexRouter, EntityViewSet, EntityTypeViewSet ) router = YolodexRouter() router.register(r'api/entity', EntityViewSet, 'entity') router.register(r'api/entitytype', EntityTypeViewSet, 'entitytype') entity_urls = [ url(r'^$', RealmView.as_view(), name='overview'), url(_(r'^corrections/$'), RealmCorrectionsView.as_view(), name='corrections'), url(_(r'^search/$'), EntitySearchView.as_view(), name='search'), url(r'^(?P<type>[\w-]+)/$', EntityListView.as_view(), name='entity_list'), url(r'^(?P<type>[\w-]+)/(?P<slug>[\w-]+)/$', EntityDetailView.as_view(), name='entity_detail'), url(r'^(?P<type>[\w-]+)/(?P<slug>[\w-]+)/embed/$', EntityDetailNetworkEmbedView.as_view(), name='entity_detail_embed'), ] urlpatterns = router.urls urlpatterns += entity_urls
<commit_before>from django.conf.urls import patterns, url from django.utils.translation import ugettext_lazy as _ from .views import ( RealmView, RealmCorrectionsView, EntitySearchView, EntityListView, EntityDetailView, EntityDetailNetworkEmbedView, ) from .api_views import ( YolodexRouter, EntityViewSet, EntityTypeViewSet ) router = YolodexRouter() router.register(r'api/entity', EntityViewSet, 'entity') router.register(r'api/entitytype', EntityTypeViewSet, 'entitytype') entity_urls = [ url(r'^$', RealmView.as_view(), name='overview'), url(_(r'^corrections/$'), RealmCorrectionsView.as_view(), name='corrections'), url(_(r'^search/$'), EntitySearchView.as_view(), name='search'), url(r'^(?P<type>[\w-]+)/$', EntityListView.as_view(), name='entity_list'), url(r'^(?P<type>[\w-]+)/(?P<slug>[\w-]+)/$', EntityDetailView.as_view(), name='entity_detail'), url(r'^(?P<type>[\w-]+)/(?P<slug>[\w-]+)/embed/$', EntityDetailNetworkEmbedView.as_view(), name='entity_detail_embed'), ] urlpatterns = router.urls urlpatterns += patterns('', *entity_urls) <commit_msg>Update urlpatterns and remove old patterns pattern<commit_after>from django.conf.urls import url from django.utils.translation import ugettext_lazy as _ from .views import ( RealmView, RealmCorrectionsView, EntitySearchView, EntityListView, EntityDetailView, EntityDetailNetworkEmbedView, ) from .api_views import ( YolodexRouter, EntityViewSet, EntityTypeViewSet ) router = YolodexRouter() router.register(r'api/entity', EntityViewSet, 'entity') router.register(r'api/entitytype', EntityTypeViewSet, 'entitytype') entity_urls = [ url(r'^$', RealmView.as_view(), name='overview'), url(_(r'^corrections/$'), RealmCorrectionsView.as_view(), name='corrections'), url(_(r'^search/$'), EntitySearchView.as_view(), name='search'), url(r'^(?P<type>[\w-]+)/$', EntityListView.as_view(), name='entity_list'), url(r'^(?P<type>[\w-]+)/(?P<slug>[\w-]+)/$', EntityDetailView.as_view(), name='entity_detail'), url(r'^(?P<type>[\w-]+)/(?P<slug>[\w-]+)/embed/$', EntityDetailNetworkEmbedView.as_view(), name='entity_detail_embed'), ] urlpatterns = router.urls urlpatterns += entity_urls
57810d41ac50284341c42217cfa6ea0917d10f21
zephyr/forms.py
zephyr/forms.py
from django import forms class RegistrationForm(forms.Form): full_name = forms.CharField(max_length=100) email = forms.EmailField() password = forms.CharField(widget=forms.PasswordInput, max_length=100)
from django import forms from django.core import validators from django.core.exceptions import ValidationError from django.contrib.auth.models import User def is_unique(value): try: print "foo + " + value User.objects.get(email=value) raise ValidationError(u'%s is already registered' % value) except User.DoesNotExist: pass class UniqueEmailField(forms.EmailField): default_validators = [validators.validate_email, is_unique] class RegistrationForm(forms.Form): full_name = forms.CharField(max_length=100) email = UniqueEmailField() password = forms.CharField(widget=forms.PasswordInput, max_length=100) domain = forms.CharField(max_length=100)
Add a custom validator to ensure email uniqueness, include ommitted fields.
Add a custom validator to ensure email uniqueness, include ommitted fields. Previously no check was performed to ensure that the same email wasn't used to register twice. Here we add a validator to perform that check. We also noted that the domain field was omitted, but checked by a client of this class. Therefore, we add it directly. (imported from commit 1411bf0adeb3cd048278376b059a26a0da4c54df)
Python
apache-2.0
umkay/zulip,jeffcao/zulip,hafeez3000/zulip,dawran6/zulip,RobotCaleb/zulip,bastianh/zulip,brockwhittaker/zulip,hustlzp/zulip,littledogboy/zulip,aliceriot/zulip,MariaFaBella85/zulip,m1ssou/zulip,Gabriel0402/zulip,JanzTam/zulip,bitemyapp/zulip,amyliu345/zulip,alliejones/zulip,hayderimran7/zulip,dwrpayne/zulip,bastianh/zulip,isht3/zulip,krtkmj/zulip,ericzhou2008/zulip,TigorC/zulip,alliejones/zulip,ryansnowboarder/zulip,he15his/zulip,jphilipsen05/zulip,shaunstanislaus/zulip,akuseru/zulip,adnanh/zulip,alliejones/zulip,itnihao/zulip,yuvipanda/zulip,xuanhan863/zulip,kokoar/zulip,verma-varsha/zulip,PaulPetring/zulip,bowlofstew/zulip,Jianchun1/zulip,luyifan/zulip,xuxiao/zulip,Gabriel0402/zulip,hackerkid/zulip,shaunstanislaus/zulip,ryanbackman/zulip,saitodisse/zulip,bowlofstew/zulip,praveenaki/zulip,bowlofstew/zulip,Qgap/zulip,mahim97/zulip,yuvipanda/zulip,tommyip/zulip,peguin40/zulip,armooo/zulip,sonali0901/zulip,kokoar/zulip,easyfmxu/zulip,seapasulli/zulip,joshisa/zulip,EasonYi/zulip,lfranchi/zulip,souravbadami/zulip,ashwinirudrappa/zulip,so0k/zulip,niftynei/zulip,KingxBanana/zulip,ryansnowboarder/zulip,saitodisse/zulip,bowlofstew/zulip,bssrdf/zulip,jrowan/zulip,EasonYi/zulip,showell/zulip,deer-hope/zulip,wangdeshui/zulip,RobotCaleb/zulip,bluesea/zulip,m1ssou/zulip,TigorC/zulip,zachallaun/zulip,aps-sids/zulip,ufosky-server/zulip,zacps/zulip,Jianchun1/zulip,pradiptad/zulip,easyfmxu/zulip,ipernet/zulip,wdaher/zulip,jainayush975/zulip,tdr130/zulip,shaunstanislaus/zulip,ApsOps/zulip,reyha/zulip,kou/zulip,sup95/zulip,thomasboyt/zulip,gigawhitlocks/zulip,zorojean/zulip,LeeRisk/zulip,hafeez3000/zulip,babbage/zulip,eastlhu/zulip,karamcnair/zulip,grave-w-grave/zulip,eastlhu/zulip,lfranchi/zulip,zhaoweigg/zulip,jessedhillon/zulip,zhaoweigg/zulip,noroot/zulip,christi3k/zulip,joshisa/zulip,noroot/zulip,atomic-labs/zulip,dwrpayne/zulip,bluesea/zulip,verma-varsha/zulip,jimmy54/zulip,arpitpanwar/zulip,ashwinirudrappa/zulip,KingxBanana/zulip,LAndreas/zulip,TigorC/zulip,yuvipanda/zulip,synicalsyntax/zulip,proliming/zulip,pradiptad/zulip,dnmfarrell/zulip,Juanvulcano/zulip,tiansiyuan/zulip,zacps/zulip,shaunstanislaus/zulip,levixie/zulip,lfranchi/zulip,yocome/zulip,mdavid/zulip,shrikrishnaholla/zulip,PaulPetring/zulip,hustlzp/zulip,wweiradio/zulip,andersk/zulip,wweiradio/zulip,jonesgithub/zulip,aliceriot/zulip,jonesgithub/zulip,bssrdf/zulip,LeeRisk/zulip,Batterfii/zulip,christi3k/zulip,SmartPeople/zulip,yuvipanda/zulip,dwrpayne/zulip,jeffcao/zulip,jphilipsen05/zulip,vikas-parashar/zulip,rishig/zulip,hayderimran7/zulip,blaze225/zulip,natanovia/zulip,ApsOps/zulip,punchagan/zulip,ericzhou2008/zulip,Drooids/zulip,rishig/zulip,Qgap/zulip,dattatreya303/zulip,ashwinirudrappa/zulip,m1ssou/zulip,mahim97/zulip,jerryge/zulip,adnanh/zulip,glovebx/zulip,dwrpayne/zulip,amyliu345/zulip,peiwei/zulip,jessedhillon/zulip,susansls/zulip,arpith/zulip,Galexrt/zulip,ashwinirudrappa/zulip,RobotCaleb/zulip,ericzhou2008/zulip,voidException/zulip,lfranchi/zulip,ApsOps/zulip,shubhamdhama/zulip,levixie/zulip,yuvipanda/zulip,timabbott/zulip,zachallaun/zulip,mansilladev/zulip,bitemyapp/zulip,natanovia/zulip,itnihao/zulip,dnmfarrell/zulip,dwrpayne/zulip,andersk/zulip,aliceriot/zulip,codeKonami/zulip,Suninus/zulip,vaidap/zulip,moria/zulip,amyliu345/zulip,MariaFaBella85/zulip,shaunstanislaus/zulip,punchagan/zulip,levixie/zulip,niftynei/zulip,ufosky-server/zulip,mdavid/zulip,umkay/zulip,guiquanz/zulip,Jianchun1/zulip,Drooids/zulip,praveenaki/zulip,dawran6/zulip,bitemyapp/zulip,noroot/zulip,Frouk/zulip,glovebx/zulip,kokoar/zulip,schatt/zulip,wangdeshui/zulip,hafeez3000/zulip,wangdeshui/zulip,zorojean/zulip,aakash-cr7/zulip,dotcool/zulip,paxapy/zulip,atomic-labs/zulip,PaulPetring/zulip,dxq-git/zulip,hafeez3000/zulip,wweiradio/zulip,saitodisse/zulip,SmartPeople/zulip,guiquanz/zulip,ApsOps/zulip,esander91/zulip,blaze225/zulip,ipernet/zulip,paxapy/zulip,zwily/zulip,Frouk/zulip,bowlofstew/zulip,calvinleenyc/zulip,Diptanshu8/zulip,eeshangarg/zulip,KJin99/zulip,Juanvulcano/zulip,amanharitsh123/zulip,luyifan/zulip,yocome/zulip,adnanh/zulip,blaze225/zulip,tommyip/zulip,aps-sids/zulip,susansls/zulip,willingc/zulip,jackrzhang/zulip,Suninus/zulip,JanzTam/zulip,Juanvulcano/zulip,suxinde2009/zulip,dhcrzf/zulip,lfranchi/zulip,gigawhitlocks/zulip,SmartPeople/zulip,aakash-cr7/zulip,paxapy/zulip,littledogboy/zulip,punchagan/zulip,akuseru/zulip,bastianh/zulip,MariaFaBella85/zulip,adnanh/zulip,so0k/zulip,vaidap/zulip,technicalpickles/zulip,m1ssou/zulip,rishig/zulip,shubhamdhama/zulip,rishig/zulip,noroot/zulip,krtkmj/zulip,bastianh/zulip,JanzTam/zulip,Gabriel0402/zulip,KingxBanana/zulip,jeffcao/zulip,zachallaun/zulip,glovebx/zulip,johnnygaddarr/zulip,eastlhu/zulip,aakash-cr7/zulip,KJin99/zulip,amanharitsh123/zulip,aliceriot/zulip,adnanh/zulip,mohsenSy/zulip,KingxBanana/zulip,samatdav/zulip,bluesea/zulip,joyhchen/zulip,zofuthan/zulip,EasonYi/zulip,wangdeshui/zulip,sonali0901/zulip,zofuthan/zulip,bssrdf/zulip,nicholasbs/zulip,gkotian/zulip,esander91/zulip,fw1121/zulip,karamcnair/zulip,hustlzp/zulip,johnnygaddarr/zulip,xuxiao/zulip,eeshangarg/zulip,guiquanz/zulip,hj3938/zulip,blaze225/zulip,Gabriel0402/zulip,souravbadami/zulip,pradiptad/zulip,jackrzhang/zulip,littledogboy/zulip,sup95/zulip,Drooids/zulip,andersk/zulip,Diptanshu8/zulip,bastianh/zulip,tdr130/zulip,mdavid/zulip,dattatreya303/zulip,hafeez3000/zulip,lfranchi/zulip,eeshangarg/zulip,bitemyapp/zulip,sharmaeklavya2/zulip,grave-w-grave/zulip,andersk/zulip,glovebx/zulip,hengqujushi/zulip,jessedhillon/zulip,dhcrzf/zulip,mdavid/zulip,Galexrt/zulip,praveenaki/zulip,jonesgithub/zulip,hafeez3000/zulip,ahmadassaf/zulip,JPJPJPOPOP/zulip,stamhe/zulip,Diptanshu8/zulip,Juanvulcano/zulip,jeffcao/zulip,hayderimran7/zulip,qq1012803704/zulip,aps-sids/zulip,jphilipsen05/zulip,vakila/zulip,arpitpanwar/zulip,qq1012803704/zulip,ipernet/zulip,itnihao/zulip,PaulPetring/zulip,stamhe/zulip,niftynei/zulip,AZtheAsian/zulip,johnnygaddarr/zulip,hj3938/zulip,samatdav/zulip,sup95/zulip,vakila/zulip,Qgap/zulip,dotcool/zulip,deer-hope/zulip,sharmaeklavya2/zulip,armooo/zulip,swinghu/zulip,vakila/zulip,vikas-parashar/zulip,eastlhu/zulip,vabs22/zulip,alliejones/zulip,jainayush975/zulip,zofuthan/zulip,joyhchen/zulip,developerfm/zulip,swinghu/zulip,RobotCaleb/zulip,johnnygaddarr/zulip,tbutter/zulip,vaidap/zulip,nicholasbs/zulip,voidException/zulip,ikasumiwt/zulip,MariaFaBella85/zulip,praveenaki/zulip,ahmadassaf/zulip,Batterfii/zulip,noroot/zulip,zwily/zulip,PaulPetring/zulip,andersk/zulip,j831/zulip,Drooids/zulip,firstblade/zulip,stamhe/zulip,sonali0901/zulip,jainayush975/zulip,tommyip/zulip,EasonYi/zulip,mohsenSy/zulip,dnmfarrell/zulip,niftynei/zulip,ashwinirudrappa/zulip,DazWorrall/zulip,JanzTam/zulip,brockwhittaker/zulip,luyifan/zulip,Qgap/zulip,sharmaeklavya2/zulip,jimmy54/zulip,jimmy54/zulip,umkay/zulip,stamhe/zulip,kokoar/zulip,Cheppers/zulip,zorojean/zulip,qq1012803704/zulip,vabs22/zulip,jonesgithub/zulip,firstblade/zulip,xuanhan863/zulip,hayderimran7/zulip,rht/zulip,karamcnair/zulip,joshisa/zulip,glovebx/zulip,paxapy/zulip,akuseru/zulip,jerryge/zulip,armooo/zulip,PhilSk/zulip,eeshangarg/zulip,calvinleenyc/zulip,EasonYi/zulip,aps-sids/zulip,jessedhillon/zulip,dhcrzf/zulip,timabbott/zulip,zulip/zulip,RobotCaleb/zulip,avastu/zulip,bowlofstew/zulip,atomic-labs/zulip,mansilladev/zulip,yuvipanda/zulip,jimmy54/zulip,dwrpayne/zulip,voidException/zulip,glovebx/zulip,rht/zulip,samatdav/zulip,souravbadami/zulip,brockwhittaker/zulip,yuvipanda/zulip,kou/zulip,aakash-cr7/zulip,ahmadassaf/zulip,wdaher/zulip,umkay/zulip,seapasulli/zulip,wavelets/zulip,babbage/zulip,LAndreas/zulip,yocome/zulip,hustlzp/zulip,ikasumiwt/zulip,jerryge/zulip,krtkmj/zulip,vikas-parashar/zulip,moria/zulip,jackrzhang/zulip,MayB/zulip,sonali0901/zulip,tommyip/zulip,mdavid/zulip,tdr130/zulip,hackerkid/zulip,ryansnowboarder/zulip,peiwei/zulip,luyifan/zulip,voidException/zulip,zofuthan/zulip,pradiptad/zulip,synicalsyntax/zulip,grave-w-grave/zulip,ahmadassaf/zulip,adnanh/zulip,jainayush975/zulip,mohsenSy/zulip,johnnygaddarr/zulip,technicalpickles/zulip,JanzTam/zulip,huangkebo/zulip,babbage/zulip,punchagan/zulip,he15his/zulip,hj3938/zulip,kou/zulip,showell/zulip,vakila/zulip,verma-varsha/zulip,johnny9/zulip,moria/zulip,tbutter/zulip,johnnygaddarr/zulip,ipernet/zulip,stamhe/zulip,armooo/zulip,showell/zulip,deer-hope/zulip,eeshangarg/zulip,babbage/zulip,christi3k/zulip,TigorC/zulip,gkotian/zulip,esander91/zulip,swinghu/zulip,ericzhou2008/zulip,saitodisse/zulip,shubhamdhama/zulip,peguin40/zulip,AZtheAsian/zulip,udxxabp/zulip,qq1012803704/zulip,willingc/zulip,umkay/zulip,ashwinirudrappa/zulip,tiansiyuan/zulip,souravbadami/zulip,eastlhu/zulip,saitodisse/zulip,bssrdf/zulip,jonesgithub/zulip,joyhchen/zulip,Galexrt/zulip,ryanbackman/zulip,vabs22/zulip,xuanhan863/zulip,Cheppers/zulip,voidException/zulip,amanharitsh123/zulip,Jianchun1/zulip,tdr130/zulip,kaiyuanheshang/zulip,gkotian/zulip,arpitpanwar/zulip,codeKonami/zulip,willingc/zulip,armooo/zulip,suxinde2009/zulip,shubhamdhama/zulip,Frouk/zulip,dnmfarrell/zulip,shrikrishnaholla/zulip,Batterfii/zulip,kaiyuanheshang/zulip,avastu/zulip,natanovia/zulip,dattatreya303/zulip,deer-hope/zulip,akuseru/zulip,levixie/zulip,Galexrt/zulip,MayB/zulip,MariaFaBella85/zulip,mohsenSy/zulip,LeeRisk/zulip,dxq-git/zulip,zachallaun/zulip,firstblade/zulip,thomasboyt/zulip,reyha/zulip,hengqujushi/zulip,aliceriot/zulip,nicholasbs/zulip,cosmicAsymmetry/zulip,jimmy54/zulip,brockwhittaker/zulip,showell/zulip,shrikrishnaholla/zulip,johnny9/zulip,wweiradio/zulip,hafeez3000/zulip,zachallaun/zulip,ryanbackman/zulip,timabbott/zulip,cosmicAsymmetry/zulip,voidException/zulip,tommyip/zulip,proliming/zulip,jessedhillon/zulip,dattatreya303/zulip,hustlzp/zulip,Cheppers/zulip,johnny9/zulip,jerryge/zulip,DazWorrall/zulip,blaze225/zulip,brockwhittaker/zulip,luyifan/zulip,ipernet/zulip,themass/zulip,dotcool/zulip,zulip/zulip,thomasboyt/zulip,wdaher/zulip,MayB/zulip,vabs22/zulip,developerfm/zulip,huangkebo/zulip,zofuthan/zulip,JPJPJPOPOP/zulip,grave-w-grave/zulip,zorojean/zulip,arpith/zulip,Batterfii/zulip,arpith/zulip,Frouk/zulip,AZtheAsian/zulip,easyfmxu/zulip,kaiyuanheshang/zulip,levixie/zulip,willingc/zulip,tbutter/zulip,ApsOps/zulip,itnihao/zulip,pradiptad/zulip,developerfm/zulip,dattatreya303/zulip,PhilSk/zulip,MayB/zulip,shrikrishnaholla/zulip,LAndreas/zulip,MayB/zulip,codeKonami/zulip,reyha/zulip,SmartPeople/zulip,pradiptad/zulip,Qgap/zulip,synicalsyntax/zulip,AZtheAsian/zulip,zwily/zulip,pradiptad/zulip,praveenaki/zulip,ufosky-server/zulip,wdaher/zulip,easyfmxu/zulip,paxapy/zulip,zhaoweigg/zulip,Galexrt/zulip,huangkebo/zulip,mahim97/zulip,amyliu345/zulip,peguin40/zulip,xuanhan863/zulip,Suninus/zulip,johnny9/zulip,synicalsyntax/zulip,niftynei/zulip,ahmadassaf/zulip,ikasumiwt/zulip,PhilSk/zulip,yocome/zulip,udxxabp/zulip,dhcrzf/zulip,so0k/zulip,calvinleenyc/zulip,JPJPJPOPOP/zulip,codeKonami/zulip,vakila/zulip,seapasulli/zulip,tiansiyuan/zulip,MariaFaBella85/zulip,umkay/zulip,zulip/zulip,LeeRisk/zulip,zacps/zulip,hayderimran7/zulip,PhilSk/zulip,susansls/zulip,ryansnowboarder/zulip,SmartPeople/zulip,kou/zulip,wweiradio/zulip,technicalpickles/zulip,krtkmj/zulip,proliming/zulip,littledogboy/zulip,zofuthan/zulip,punchagan/zulip,gigawhitlocks/zulip,j831/zulip,ryansnowboarder/zulip,xuanhan863/zulip,brainwane/zulip,saitodisse/zulip,calvinleenyc/zulip,DazWorrall/zulip,amallia/zulip,hengqujushi/zulip,jessedhillon/zulip,mahim97/zulip,sonali0901/zulip,moria/zulip,vaidap/zulip,atomic-labs/zulip,so0k/zulip,ericzhou2008/zulip,hj3938/zulip,Batterfii/zulip,firstblade/zulip,yocome/zulip,hackerkid/zulip,willingc/zulip,isht3/zulip,zacps/zulip,alliejones/zulip,Batterfii/zulip,KingxBanana/zulip,brainwane/zulip,sup95/zulip,sup95/zulip,shaunstanislaus/zulip,wangdeshui/zulip,vaidap/zulip,rht/zulip,thomasboyt/zulip,wangdeshui/zulip,shubhamdhama/zulip,m1ssou/zulip,bluesea/zulip,LAndreas/zulip,huangkebo/zulip,dxq-git/zulip,zulip/zulip,aakash-cr7/zulip,ufosky-server/zulip,alliejones/zulip,gigawhitlocks/zulip,zhaoweigg/zulip,ufosky-server/zulip,sharmaeklavya2/zulip,synicalsyntax/zulip,deer-hope/zulip,suxinde2009/zulip,j831/zulip,gigawhitlocks/zulip,luyifan/zulip,jeffcao/zulip,ikasumiwt/zulip,guiquanz/zulip,udxxabp/zulip,udxxabp/zulip,blaze225/zulip,bitemyapp/zulip,willingc/zulip,johnny9/zulip,nicholasbs/zulip,KingxBanana/zulip,AZtheAsian/zulip,he15his/zulip,zwily/zulip,so0k/zulip,avastu/zulip,ikasumiwt/zulip,tiansiyuan/zulip,jackrzhang/zulip,Drooids/zulip,suxinde2009/zulip,punchagan/zulip,levixie/zulip,themass/zulip,wweiradio/zulip,lfranchi/zulip,JPJPJPOPOP/zulip,shrikrishnaholla/zulip,cosmicAsymmetry/zulip,fw1121/zulip,zhaoweigg/zulip,amallia/zulip,guiquanz/zulip,EasonYi/zulip,levixie/zulip,xuxiao/zulip,developerfm/zulip,joyhchen/zulip,zachallaun/zulip,suxinde2009/zulip,huangkebo/zulip,krtkmj/zulip,so0k/zulip,codeKonami/zulip,Vallher/zulip,proliming/zulip,PhilSk/zulip,synicalsyntax/zulip,jeffcao/zulip,xuanhan863/zulip,thomasboyt/zulip,rishig/zulip,sup95/zulip,mdavid/zulip,PhilSk/zulip,wavelets/zulip,grave-w-grave/zulip,KJin99/zulip,peiwei/zulip,gkotian/zulip,jrowan/zulip,tiansiyuan/zulip,bowlofstew/zulip,vabs22/zulip,suxinde2009/zulip,ipernet/zulip,firstblade/zulip,tiansiyuan/zulip,wweiradio/zulip,tdr130/zulip,jimmy54/zulip,kokoar/zulip,souravbadami/zulip,Cheppers/zulip,so0k/zulip,DazWorrall/zulip,hengqujushi/zulip,zulip/zulip,jimmy54/zulip,armooo/zulip,timabbott/zulip,timabbott/zulip,stamhe/zulip,Suninus/zulip,jainayush975/zulip,Jianchun1/zulip,huangkebo/zulip,littledogboy/zulip,jainayush975/zulip,dawran6/zulip,souravbadami/zulip,bluesea/zulip,j831/zulip,zachallaun/zulip,zorojean/zulip,Gabriel0402/zulip,dattatreya303/zulip,fw1121/zulip,arpith/zulip,dnmfarrell/zulip,stamhe/zulip,avastu/zulip,krtkmj/zulip,xuxiao/zulip,peguin40/zulip,Galexrt/zulip,verma-varsha/zulip,tbutter/zulip,esander91/zulip,JanzTam/zulip,deer-hope/zulip,johnny9/zulip,showell/zulip,tdr130/zulip,KJin99/zulip,shubhamdhama/zulip,wavelets/zulip,ryanbackman/zulip,m1ssou/zulip,rishig/zulip,karamcnair/zulip,christi3k/zulip,aliceriot/zulip,glovebx/zulip,codeKonami/zulip,natanovia/zulip,developerfm/zulip,hackerkid/zulip,arpitpanwar/zulip,bssrdf/zulip,itnihao/zulip,verma-varsha/zulip,jphilipsen05/zulip,noroot/zulip,brockwhittaker/zulip,cosmicAsymmetry/zulip,Vallher/zulip,sonali0901/zulip,Diptanshu8/zulip,hengqujushi/zulip,natanovia/zulip,samatdav/zulip,JPJPJPOPOP/zulip,fw1121/zulip,dawran6/zulip,jonesgithub/zulip,tommyip/zulip,eastlhu/zulip,deer-hope/zulip,technicalpickles/zulip,Cheppers/zulip,dotcool/zulip,Juanvulcano/zulip,kokoar/zulip,Frouk/zulip,PaulPetring/zulip,Suninus/zulip,atomic-labs/zulip,mansilladev/zulip,dxq-git/zulip,tdr130/zulip,joyhchen/zulip,firstblade/zulip,dhcrzf/zulip,arpith/zulip,shaunstanislaus/zulip,PaulPetring/zulip,KJin99/zulip,ryanbackman/zulip,zwily/zulip,peguin40/zulip,moria/zulip,wavelets/zulip,dnmfarrell/zulip,calvinleenyc/zulip,jrowan/zulip,technicalpickles/zulip,jackrzhang/zulip,zorojean/zulip,tbutter/zulip,LAndreas/zulip,vikas-parashar/zulip,KJin99/zulip,natanovia/zulip,christi3k/zulip,kou/zulip,isht3/zulip,rht/zulip,Diptanshu8/zulip,easyfmxu/zulip,jerryge/zulip,samatdav/zulip,Qgap/zulip,susansls/zulip,udxxabp/zulip,DazWorrall/zulip,esander91/zulip,ikasumiwt/zulip,vikas-parashar/zulip,amallia/zulip,themass/zulip,joyhchen/zulip,dxq-git/zulip,shrikrishnaholla/zulip,vakila/zulip,luyifan/zulip,swinghu/zulip,seapasulli/zulip,JPJPJPOPOP/zulip,easyfmxu/zulip,schatt/zulip,themass/zulip,zofuthan/zulip,aps-sids/zulip,Gabriel0402/zulip,ericzhou2008/zulip,mohsenSy/zulip,developerfm/zulip,isht3/zulip,mahim97/zulip,tbutter/zulip,voidException/zulip,sharmaeklavya2/zulip,eeshangarg/zulip,peiwei/zulip,dawran6/zulip,reyha/zulip,andersk/zulip,kou/zulip,MayB/zulip,MariaFaBella85/zulip,amallia/zulip,technicalpickles/zulip,he15his/zulip,zacps/zulip,dotcool/zulip,RobotCaleb/zulip,bluesea/zulip,samatdav/zulip,wdaher/zulip,aakash-cr7/zulip,mdavid/zulip,saitodisse/zulip,schatt/zulip,j831/zulip,itnihao/zulip,bluesea/zulip,yocome/zulip,suxinde2009/zulip,zulip/zulip,praveenaki/zulip,bssrdf/zulip,grave-w-grave/zulip,peiwei/zulip,ahmadassaf/zulip,jrowan/zulip,easyfmxu/zulip,mahim97/zulip,littledogboy/zulip,Frouk/zulip,LAndreas/zulip,bitemyapp/zulip,Vallher/zulip,zwily/zulip,arpith/zulip,dxq-git/zulip,TigorC/zulip,shrikrishnaholla/zulip,avastu/zulip,dwrpayne/zulip,SmartPeople/zulip,schatt/zulip,Galexrt/zulip,tbutter/zulip,ApsOps/zulip,jeffcao/zulip,showell/zulip,jessedhillon/zulip,willingc/zulip,Jianchun1/zulip,joshisa/zulip,fw1121/zulip,schatt/zulip,gigawhitlocks/zulip,amanharitsh123/zulip,MayB/zulip,noroot/zulip,punchagan/zulip,kaiyuanheshang/zulip,cosmicAsymmetry/zulip,brainwane/zulip,seapasulli/zulip,babbage/zulip,dnmfarrell/zulip,showell/zulip,ufosky-server/zulip,fw1121/zulip,brainwane/zulip,LeeRisk/zulip,Drooids/zulip,moria/zulip,brainwane/zulip,nicholasbs/zulip,swinghu/zulip,kaiyuanheshang/zulip,ikasumiwt/zulip,isht3/zulip,bastianh/zulip,ashwinirudrappa/zulip,joshisa/zulip,wavelets/zulip,kou/zulip,ApsOps/zulip,rht/zulip,Vallher/zulip,Juanvulcano/zulip,joshisa/zulip,timabbott/zulip,he15his/zulip,hj3938/zulip,amyliu345/zulip,zhaoweigg/zulip,gigawhitlocks/zulip,avastu/zulip,alliejones/zulip,swinghu/zulip,proliming/zulip,Gabriel0402/zulip,Suninus/zulip,peiwei/zulip,calvinleenyc/zulip,ericzhou2008/zulip,guiquanz/zulip,niftynei/zulip,jphilipsen05/zulip,brainwane/zulip,mohsenSy/zulip,Vallher/zulip,johnnygaddarr/zulip,cosmicAsymmetry/zulip,yocome/zulip,paxapy/zulip,themass/zulip,ryanbackman/zulip,karamcnair/zulip,eeshangarg/zulip,KJin99/zulip,vabs22/zulip,zulip/zulip,arpitpanwar/zulip,themass/zulip,huangkebo/zulip,ryansnowboarder/zulip,amanharitsh123/zulip,dhcrzf/zulip,developerfm/zulip,bastianh/zulip,xuanhan863/zulip,amallia/zulip,gkotian/zulip,eastlhu/zulip,sharmaeklavya2/zulip,christi3k/zulip,xuxiao/zulip,Qgap/zulip,xuxiao/zulip,guiquanz/zulip,susansls/zulip,bitemyapp/zulip,themass/zulip,itnihao/zulip,jerryge/zulip,wangdeshui/zulip,thomasboyt/zulip,krtkmj/zulip,technicalpickles/zulip,susansls/zulip,zorojean/zulip,hayderimran7/zulip,kokoar/zulip,hackerkid/zulip,Frouk/zulip,JanzTam/zulip,arpitpanwar/zulip,mansilladev/zulip,proliming/zulip,wavelets/zulip,praveenaki/zulip,aliceriot/zulip,ryansnowboarder/zulip,johnny9/zulip,gkotian/zulip,dxq-git/zulip,verma-varsha/zulip,rht/zulip,hj3938/zulip,m1ssou/zulip,hustlzp/zulip,dotcool/zulip,vikas-parashar/zulip,mansilladev/zulip,DazWorrall/zulip,jackrzhang/zulip,ahmadassaf/zulip,schatt/zulip,synicalsyntax/zulip,qq1012803704/zulip,amyliu345/zulip,armooo/zulip,Suninus/zulip,aps-sids/zulip,aps-sids/zulip,seapasulli/zulip,LeeRisk/zulip,udxxabp/zulip,esander91/zulip,zacps/zulip,udxxabp/zulip,amallia/zulip,RobotCaleb/zulip,kaiyuanheshang/zulip,ufosky-server/zulip,hustlzp/zulip,Diptanshu8/zulip,j831/zulip,jphilipsen05/zulip,atomic-labs/zulip,vaidap/zulip,bssrdf/zulip,reyha/zulip,kaiyuanheshang/zulip,Cheppers/zulip,xuxiao/zulip,swinghu/zulip,hengqujushi/zulip,AZtheAsian/zulip,arpitpanwar/zulip,rht/zulip,jrowan/zulip,hj3938/zulip,wdaher/zulip,dotcool/zulip,mansilladev/zulip,wavelets/zulip,wdaher/zulip,akuseru/zulip,TigorC/zulip,qq1012803704/zulip,qq1012803704/zulip,LeeRisk/zulip,hengqujushi/zulip,shubhamdhama/zulip,schatt/zulip,thomasboyt/zulip,esander91/zulip,zhaoweigg/zulip,ipernet/zulip,he15his/zulip,adnanh/zulip,jerryge/zulip,dhcrzf/zulip,littledogboy/zulip,jonesgithub/zulip,nicholasbs/zulip,andersk/zulip,hackerkid/zulip,akuseru/zulip,avastu/zulip,LAndreas/zulip,vakila/zulip,brainwane/zulip,tommyip/zulip,karamcnair/zulip,amanharitsh123/zulip,codeKonami/zulip,amallia/zulip,joshisa/zulip,hayderimran7/zulip,umkay/zulip,tiansiyuan/zulip,rishig/zulip,reyha/zulip,isht3/zulip,he15his/zulip,babbage/zulip,jrowan/zulip,proliming/zulip,mansilladev/zulip,jackrzhang/zulip,moria/zulip,timabbott/zulip,Drooids/zulip,Vallher/zulip,hackerkid/zulip,Vallher/zulip,firstblade/zulip,fw1121/zulip,EasonYi/zulip,nicholasbs/zulip,akuseru/zulip,Cheppers/zulip,atomic-labs/zulip,peguin40/zulip,peiwei/zulip,natanovia/zulip,DazWorrall/zulip,dawran6/zulip,babbage/zulip,karamcnair/zulip,gkotian/zulip,zwily/zulip,seapasulli/zulip,Batterfii/zulip
from django import forms class RegistrationForm(forms.Form): full_name = forms.CharField(max_length=100) email = forms.EmailField() password = forms.CharField(widget=forms.PasswordInput, max_length=100) Add a custom validator to ensure email uniqueness, include ommitted fields. Previously no check was performed to ensure that the same email wasn't used to register twice. Here we add a validator to perform that check. We also noted that the domain field was omitted, but checked by a client of this class. Therefore, we add it directly. (imported from commit 1411bf0adeb3cd048278376b059a26a0da4c54df)
from django import forms from django.core import validators from django.core.exceptions import ValidationError from django.contrib.auth.models import User def is_unique(value): try: print "foo + " + value User.objects.get(email=value) raise ValidationError(u'%s is already registered' % value) except User.DoesNotExist: pass class UniqueEmailField(forms.EmailField): default_validators = [validators.validate_email, is_unique] class RegistrationForm(forms.Form): full_name = forms.CharField(max_length=100) email = UniqueEmailField() password = forms.CharField(widget=forms.PasswordInput, max_length=100) domain = forms.CharField(max_length=100)
<commit_before>from django import forms class RegistrationForm(forms.Form): full_name = forms.CharField(max_length=100) email = forms.EmailField() password = forms.CharField(widget=forms.PasswordInput, max_length=100) <commit_msg>Add a custom validator to ensure email uniqueness, include ommitted fields. Previously no check was performed to ensure that the same email wasn't used to register twice. Here we add a validator to perform that check. We also noted that the domain field was omitted, but checked by a client of this class. Therefore, we add it directly. (imported from commit 1411bf0adeb3cd048278376b059a26a0da4c54df)<commit_after>
from django import forms from django.core import validators from django.core.exceptions import ValidationError from django.contrib.auth.models import User def is_unique(value): try: print "foo + " + value User.objects.get(email=value) raise ValidationError(u'%s is already registered' % value) except User.DoesNotExist: pass class UniqueEmailField(forms.EmailField): default_validators = [validators.validate_email, is_unique] class RegistrationForm(forms.Form): full_name = forms.CharField(max_length=100) email = UniqueEmailField() password = forms.CharField(widget=forms.PasswordInput, max_length=100) domain = forms.CharField(max_length=100)
from django import forms class RegistrationForm(forms.Form): full_name = forms.CharField(max_length=100) email = forms.EmailField() password = forms.CharField(widget=forms.PasswordInput, max_length=100) Add a custom validator to ensure email uniqueness, include ommitted fields. Previously no check was performed to ensure that the same email wasn't used to register twice. Here we add a validator to perform that check. We also noted that the domain field was omitted, but checked by a client of this class. Therefore, we add it directly. (imported from commit 1411bf0adeb3cd048278376b059a26a0da4c54df)from django import forms from django.core import validators from django.core.exceptions import ValidationError from django.contrib.auth.models import User def is_unique(value): try: print "foo + " + value User.objects.get(email=value) raise ValidationError(u'%s is already registered' % value) except User.DoesNotExist: pass class UniqueEmailField(forms.EmailField): default_validators = [validators.validate_email, is_unique] class RegistrationForm(forms.Form): full_name = forms.CharField(max_length=100) email = UniqueEmailField() password = forms.CharField(widget=forms.PasswordInput, max_length=100) domain = forms.CharField(max_length=100)
<commit_before>from django import forms class RegistrationForm(forms.Form): full_name = forms.CharField(max_length=100) email = forms.EmailField() password = forms.CharField(widget=forms.PasswordInput, max_length=100) <commit_msg>Add a custom validator to ensure email uniqueness, include ommitted fields. Previously no check was performed to ensure that the same email wasn't used to register twice. Here we add a validator to perform that check. We also noted that the domain field was omitted, but checked by a client of this class. Therefore, we add it directly. (imported from commit 1411bf0adeb3cd048278376b059a26a0da4c54df)<commit_after>from django import forms from django.core import validators from django.core.exceptions import ValidationError from django.contrib.auth.models import User def is_unique(value): try: print "foo + " + value User.objects.get(email=value) raise ValidationError(u'%s is already registered' % value) except User.DoesNotExist: pass class UniqueEmailField(forms.EmailField): default_validators = [validators.validate_email, is_unique] class RegistrationForm(forms.Form): full_name = forms.CharField(max_length=100) email = UniqueEmailField() password = forms.CharField(widget=forms.PasswordInput, max_length=100) domain = forms.CharField(max_length=100)
325fed2ef774e708e96d1b123672e1be238d7d21
nailgun/nailgun/models.py
nailgun/nailgun/models.py
from django.db import models from django.contrib.auth.models import User from jsonfield import JSONField class Environment(models.Model): #user = models.ForeignKey(User, related_name='environments') name = models.CharField(max_length=100) class Role(models.Model): id = models.CharField(max_length=30, primary_key=True) name = models.CharField(max_length=50) class Node(models.Model): NODE_STATUSES = ( ('online', 'online'), ('offline', 'offline'), ('busy', 'busy'), ) environment = models.ForeignKey(Environment, related_name='nodes') name = models.CharField(max_length=100, primary_key=True) status = models.CharField(max_length=30, choices=NODE_STATUSES, default='online') metadata = JSONField() roles = models.ManyToManyField(Role, related_name='nodes')
from django.db import models from django.contrib.auth.models import User from jsonfield import JSONField class Environment(models.Model): #user = models.ForeignKey(User, related_name='environments') name = models.CharField(max_length=100) class Role(models.Model): id = models.CharField(max_length=30, primary_key=True) name = models.CharField(max_length=50) class Node(models.Model): NODE_STATUSES = ( ('online', 'online'), ('offline', 'offline'), ('busy', 'busy'), ) environment = models.ForeignKey(Environment, related_name='nodes', null=True, blank=True, on_delete=models.SET_NULL) name = models.CharField(max_length=100, primary_key=True) status = models.CharField(max_length=30, choices=NODE_STATUSES, default='online') metadata = JSONField() roles = models.ManyToManyField(Role, related_name='nodes')
Allow nodes not to have related environment
Allow nodes not to have related environment
Python
apache-2.0
SmartInfrastructures/fuel-main-dev,nebril/fuel-web,dancn/fuel-main-dev,SergK/fuel-main,zhaochao/fuel-main,nebril/fuel-web,prmtl/fuel-web,zhaochao/fuel-main,eayunstack/fuel-web,nebril/fuel-web,SmartInfrastructures/fuel-main-dev,SmartInfrastructures/fuel-main-dev,teselkin/fuel-main,Fiware/ops.Fuel-main-dev,teselkin/fuel-main,zhaochao/fuel-web,dancn/fuel-main-dev,eayunstack/fuel-web,stackforge/fuel-web,huntxu/fuel-web,SmartInfrastructures/fuel-web-dev,prmtl/fuel-web,eayunstack/fuel-web,zhaochao/fuel-main,teselkin/fuel-main,SmartInfrastructures/fuel-web-dev,SmartInfrastructures/fuel-web-dev,stackforge/fuel-web,Fiware/ops.Fuel-main-dev,AnselZhangGit/fuel-main,nebril/fuel-web,SmartInfrastructures/fuel-web-dev,eayunstack/fuel-web,dancn/fuel-main-dev,zhaochao/fuel-web,dancn/fuel-main-dev,koder-ua/nailgun-fcert,zhaochao/fuel-main,AnselZhangGit/fuel-main,teselkin/fuel-main,prmtl/fuel-web,huntxu/fuel-web,koder-ua/nailgun-fcert,SergK/fuel-main,huntxu/fuel-main,koder-ua/nailgun-fcert,huntxu/fuel-main,huntxu/fuel-main,stackforge/fuel-main,eayunstack/fuel-main,SmartInfrastructures/fuel-main-dev,ddepaoli3/fuel-main-dev,Fiware/ops.Fuel-main-dev,AnselZhangGit/fuel-main,stackforge/fuel-web,SergK/fuel-main,zhaochao/fuel-web,ddepaoli3/fuel-main-dev,SmartInfrastructures/fuel-web-dev,ddepaoli3/fuel-main-dev,AnselZhangGit/fuel-main,huntxu/fuel-web,nebril/fuel-web,prmtl/fuel-web,huntxu/fuel-web,eayunstack/fuel-main,huntxu/fuel-web,zhaochao/fuel-main,zhaochao/fuel-web,stackforge/fuel-main,ddepaoli3/fuel-main-dev,prmtl/fuel-web,zhaochao/fuel-web,stackforge/fuel-main,koder-ua/nailgun-fcert,eayunstack/fuel-web,eayunstack/fuel-main,Fiware/ops.Fuel-main-dev
from django.db import models from django.contrib.auth.models import User from jsonfield import JSONField class Environment(models.Model): #user = models.ForeignKey(User, related_name='environments') name = models.CharField(max_length=100) class Role(models.Model): id = models.CharField(max_length=30, primary_key=True) name = models.CharField(max_length=50) class Node(models.Model): NODE_STATUSES = ( ('online', 'online'), ('offline', 'offline'), ('busy', 'busy'), ) environment = models.ForeignKey(Environment, related_name='nodes') name = models.CharField(max_length=100, primary_key=True) status = models.CharField(max_length=30, choices=NODE_STATUSES, default='online') metadata = JSONField() roles = models.ManyToManyField(Role, related_name='nodes') Allow nodes not to have related environment
from django.db import models from django.contrib.auth.models import User from jsonfield import JSONField class Environment(models.Model): #user = models.ForeignKey(User, related_name='environments') name = models.CharField(max_length=100) class Role(models.Model): id = models.CharField(max_length=30, primary_key=True) name = models.CharField(max_length=50) class Node(models.Model): NODE_STATUSES = ( ('online', 'online'), ('offline', 'offline'), ('busy', 'busy'), ) environment = models.ForeignKey(Environment, related_name='nodes', null=True, blank=True, on_delete=models.SET_NULL) name = models.CharField(max_length=100, primary_key=True) status = models.CharField(max_length=30, choices=NODE_STATUSES, default='online') metadata = JSONField() roles = models.ManyToManyField(Role, related_name='nodes')
<commit_before>from django.db import models from django.contrib.auth.models import User from jsonfield import JSONField class Environment(models.Model): #user = models.ForeignKey(User, related_name='environments') name = models.CharField(max_length=100) class Role(models.Model): id = models.CharField(max_length=30, primary_key=True) name = models.CharField(max_length=50) class Node(models.Model): NODE_STATUSES = ( ('online', 'online'), ('offline', 'offline'), ('busy', 'busy'), ) environment = models.ForeignKey(Environment, related_name='nodes') name = models.CharField(max_length=100, primary_key=True) status = models.CharField(max_length=30, choices=NODE_STATUSES, default='online') metadata = JSONField() roles = models.ManyToManyField(Role, related_name='nodes') <commit_msg>Allow nodes not to have related environment<commit_after>
from django.db import models from django.contrib.auth.models import User from jsonfield import JSONField class Environment(models.Model): #user = models.ForeignKey(User, related_name='environments') name = models.CharField(max_length=100) class Role(models.Model): id = models.CharField(max_length=30, primary_key=True) name = models.CharField(max_length=50) class Node(models.Model): NODE_STATUSES = ( ('online', 'online'), ('offline', 'offline'), ('busy', 'busy'), ) environment = models.ForeignKey(Environment, related_name='nodes', null=True, blank=True, on_delete=models.SET_NULL) name = models.CharField(max_length=100, primary_key=True) status = models.CharField(max_length=30, choices=NODE_STATUSES, default='online') metadata = JSONField() roles = models.ManyToManyField(Role, related_name='nodes')
from django.db import models from django.contrib.auth.models import User from jsonfield import JSONField class Environment(models.Model): #user = models.ForeignKey(User, related_name='environments') name = models.CharField(max_length=100) class Role(models.Model): id = models.CharField(max_length=30, primary_key=True) name = models.CharField(max_length=50) class Node(models.Model): NODE_STATUSES = ( ('online', 'online'), ('offline', 'offline'), ('busy', 'busy'), ) environment = models.ForeignKey(Environment, related_name='nodes') name = models.CharField(max_length=100, primary_key=True) status = models.CharField(max_length=30, choices=NODE_STATUSES, default='online') metadata = JSONField() roles = models.ManyToManyField(Role, related_name='nodes') Allow nodes not to have related environmentfrom django.db import models from django.contrib.auth.models import User from jsonfield import JSONField class Environment(models.Model): #user = models.ForeignKey(User, related_name='environments') name = models.CharField(max_length=100) class Role(models.Model): id = models.CharField(max_length=30, primary_key=True) name = models.CharField(max_length=50) class Node(models.Model): NODE_STATUSES = ( ('online', 'online'), ('offline', 'offline'), ('busy', 'busy'), ) environment = models.ForeignKey(Environment, related_name='nodes', null=True, blank=True, on_delete=models.SET_NULL) name = models.CharField(max_length=100, primary_key=True) status = models.CharField(max_length=30, choices=NODE_STATUSES, default='online') metadata = JSONField() roles = models.ManyToManyField(Role, related_name='nodes')
<commit_before>from django.db import models from django.contrib.auth.models import User from jsonfield import JSONField class Environment(models.Model): #user = models.ForeignKey(User, related_name='environments') name = models.CharField(max_length=100) class Role(models.Model): id = models.CharField(max_length=30, primary_key=True) name = models.CharField(max_length=50) class Node(models.Model): NODE_STATUSES = ( ('online', 'online'), ('offline', 'offline'), ('busy', 'busy'), ) environment = models.ForeignKey(Environment, related_name='nodes') name = models.CharField(max_length=100, primary_key=True) status = models.CharField(max_length=30, choices=NODE_STATUSES, default='online') metadata = JSONField() roles = models.ManyToManyField(Role, related_name='nodes') <commit_msg>Allow nodes not to have related environment<commit_after>from django.db import models from django.contrib.auth.models import User from jsonfield import JSONField class Environment(models.Model): #user = models.ForeignKey(User, related_name='environments') name = models.CharField(max_length=100) class Role(models.Model): id = models.CharField(max_length=30, primary_key=True) name = models.CharField(max_length=50) class Node(models.Model): NODE_STATUSES = ( ('online', 'online'), ('offline', 'offline'), ('busy', 'busy'), ) environment = models.ForeignKey(Environment, related_name='nodes', null=True, blank=True, on_delete=models.SET_NULL) name = models.CharField(max_length=100, primary_key=True) status = models.CharField(max_length=30, choices=NODE_STATUSES, default='online') metadata = JSONField() roles = models.ManyToManyField(Role, related_name='nodes')
23456a32038f13c6219b6af5ff9fff7e1daae242
abusehelper/core/tests/test_utils.py
abusehelper/core/tests/test_utils.py
import pickle import unittest from .. import utils class TestCompressedCollection(unittest.TestCase): def test_collection_can_be_pickled_and_unpickled(self): original = utils.CompressedCollection() original.append("ab") original.append("cd") unpickled = pickle.loads(pickle.dumps(original)) self.assertEqual(["ab", "cd"], list(unpickled)) def test_objects_can_be_appended_to_an_unpickled_collection(self): original = utils.CompressedCollection() original.append("ab") unpickled = pickle.loads(pickle.dumps(original)) self.assertEqual(["ab"], list(unpickled)) unpickled.append("cd") self.assertEqual(["ab", "cd"], list(unpickled)) def test_objects_can_be_appended_a_collection_after_pickling(self): original = utils.CompressedCollection() original.append("ab") pickle.dumps(original) original.append("cd") self.assertEqual(["ab", "cd"], list(original))
import socket import pickle import urllib2 import unittest import idiokit from .. import utils class TestFetchUrl(unittest.TestCase): def test_should_raise_TypeError_when_passing_in_an_opener(self): sock = socket.socket() try: sock.bind(("localhost", 0)) sock.listen(1) _, port = sock.getsockname() opener = urllib2.build_opener() fetch = utils.fetch_url("http://localhost:{0}".format(port), opener=opener) self.assertRaises(TypeError, idiokit.main_loop, fetch) finally: sock.close() class TestCompressedCollection(unittest.TestCase): def test_collection_can_be_pickled_and_unpickled(self): original = utils.CompressedCollection() original.append("ab") original.append("cd") unpickled = pickle.loads(pickle.dumps(original)) self.assertEqual(["ab", "cd"], list(unpickled)) def test_objects_can_be_appended_to_an_unpickled_collection(self): original = utils.CompressedCollection() original.append("ab") unpickled = pickle.loads(pickle.dumps(original)) self.assertEqual(["ab"], list(unpickled)) unpickled.append("cd") self.assertEqual(["ab", "cd"], list(unpickled)) def test_objects_can_be_appended_a_collection_after_pickling(self): original = utils.CompressedCollection() original.append("ab") pickle.dumps(original) original.append("cd") self.assertEqual(["ab", "cd"], list(original))
Add a test for utils.fetch_url(..., opener=...)
Add a test for utils.fetch_url(..., opener=...) Signed-off-by: Ossi Herrala <37524b811d80bbe1732e3577b04d7a5fd222cfc5@gmail.com>
Python
mit
abusesa/abusehelper
import pickle import unittest from .. import utils class TestCompressedCollection(unittest.TestCase): def test_collection_can_be_pickled_and_unpickled(self): original = utils.CompressedCollection() original.append("ab") original.append("cd") unpickled = pickle.loads(pickle.dumps(original)) self.assertEqual(["ab", "cd"], list(unpickled)) def test_objects_can_be_appended_to_an_unpickled_collection(self): original = utils.CompressedCollection() original.append("ab") unpickled = pickle.loads(pickle.dumps(original)) self.assertEqual(["ab"], list(unpickled)) unpickled.append("cd") self.assertEqual(["ab", "cd"], list(unpickled)) def test_objects_can_be_appended_a_collection_after_pickling(self): original = utils.CompressedCollection() original.append("ab") pickle.dumps(original) original.append("cd") self.assertEqual(["ab", "cd"], list(original)) Add a test for utils.fetch_url(..., opener=...) Signed-off-by: Ossi Herrala <37524b811d80bbe1732e3577b04d7a5fd222cfc5@gmail.com>
import socket import pickle import urllib2 import unittest import idiokit from .. import utils class TestFetchUrl(unittest.TestCase): def test_should_raise_TypeError_when_passing_in_an_opener(self): sock = socket.socket() try: sock.bind(("localhost", 0)) sock.listen(1) _, port = sock.getsockname() opener = urllib2.build_opener() fetch = utils.fetch_url("http://localhost:{0}".format(port), opener=opener) self.assertRaises(TypeError, idiokit.main_loop, fetch) finally: sock.close() class TestCompressedCollection(unittest.TestCase): def test_collection_can_be_pickled_and_unpickled(self): original = utils.CompressedCollection() original.append("ab") original.append("cd") unpickled = pickle.loads(pickle.dumps(original)) self.assertEqual(["ab", "cd"], list(unpickled)) def test_objects_can_be_appended_to_an_unpickled_collection(self): original = utils.CompressedCollection() original.append("ab") unpickled = pickle.loads(pickle.dumps(original)) self.assertEqual(["ab"], list(unpickled)) unpickled.append("cd") self.assertEqual(["ab", "cd"], list(unpickled)) def test_objects_can_be_appended_a_collection_after_pickling(self): original = utils.CompressedCollection() original.append("ab") pickle.dumps(original) original.append("cd") self.assertEqual(["ab", "cd"], list(original))
<commit_before>import pickle import unittest from .. import utils class TestCompressedCollection(unittest.TestCase): def test_collection_can_be_pickled_and_unpickled(self): original = utils.CompressedCollection() original.append("ab") original.append("cd") unpickled = pickle.loads(pickle.dumps(original)) self.assertEqual(["ab", "cd"], list(unpickled)) def test_objects_can_be_appended_to_an_unpickled_collection(self): original = utils.CompressedCollection() original.append("ab") unpickled = pickle.loads(pickle.dumps(original)) self.assertEqual(["ab"], list(unpickled)) unpickled.append("cd") self.assertEqual(["ab", "cd"], list(unpickled)) def test_objects_can_be_appended_a_collection_after_pickling(self): original = utils.CompressedCollection() original.append("ab") pickle.dumps(original) original.append("cd") self.assertEqual(["ab", "cd"], list(original)) <commit_msg>Add a test for utils.fetch_url(..., opener=...) Signed-off-by: Ossi Herrala <37524b811d80bbe1732e3577b04d7a5fd222cfc5@gmail.com><commit_after>
import socket import pickle import urllib2 import unittest import idiokit from .. import utils class TestFetchUrl(unittest.TestCase): def test_should_raise_TypeError_when_passing_in_an_opener(self): sock = socket.socket() try: sock.bind(("localhost", 0)) sock.listen(1) _, port = sock.getsockname() opener = urllib2.build_opener() fetch = utils.fetch_url("http://localhost:{0}".format(port), opener=opener) self.assertRaises(TypeError, idiokit.main_loop, fetch) finally: sock.close() class TestCompressedCollection(unittest.TestCase): def test_collection_can_be_pickled_and_unpickled(self): original = utils.CompressedCollection() original.append("ab") original.append("cd") unpickled = pickle.loads(pickle.dumps(original)) self.assertEqual(["ab", "cd"], list(unpickled)) def test_objects_can_be_appended_to_an_unpickled_collection(self): original = utils.CompressedCollection() original.append("ab") unpickled = pickle.loads(pickle.dumps(original)) self.assertEqual(["ab"], list(unpickled)) unpickled.append("cd") self.assertEqual(["ab", "cd"], list(unpickled)) def test_objects_can_be_appended_a_collection_after_pickling(self): original = utils.CompressedCollection() original.append("ab") pickle.dumps(original) original.append("cd") self.assertEqual(["ab", "cd"], list(original))
import pickle import unittest from .. import utils class TestCompressedCollection(unittest.TestCase): def test_collection_can_be_pickled_and_unpickled(self): original = utils.CompressedCollection() original.append("ab") original.append("cd") unpickled = pickle.loads(pickle.dumps(original)) self.assertEqual(["ab", "cd"], list(unpickled)) def test_objects_can_be_appended_to_an_unpickled_collection(self): original = utils.CompressedCollection() original.append("ab") unpickled = pickle.loads(pickle.dumps(original)) self.assertEqual(["ab"], list(unpickled)) unpickled.append("cd") self.assertEqual(["ab", "cd"], list(unpickled)) def test_objects_can_be_appended_a_collection_after_pickling(self): original = utils.CompressedCollection() original.append("ab") pickle.dumps(original) original.append("cd") self.assertEqual(["ab", "cd"], list(original)) Add a test for utils.fetch_url(..., opener=...) Signed-off-by: Ossi Herrala <37524b811d80bbe1732e3577b04d7a5fd222cfc5@gmail.com>import socket import pickle import urllib2 import unittest import idiokit from .. import utils class TestFetchUrl(unittest.TestCase): def test_should_raise_TypeError_when_passing_in_an_opener(self): sock = socket.socket() try: sock.bind(("localhost", 0)) sock.listen(1) _, port = sock.getsockname() opener = urllib2.build_opener() fetch = utils.fetch_url("http://localhost:{0}".format(port), opener=opener) self.assertRaises(TypeError, idiokit.main_loop, fetch) finally: sock.close() class TestCompressedCollection(unittest.TestCase): def test_collection_can_be_pickled_and_unpickled(self): original = utils.CompressedCollection() original.append("ab") original.append("cd") unpickled = pickle.loads(pickle.dumps(original)) self.assertEqual(["ab", "cd"], list(unpickled)) def test_objects_can_be_appended_to_an_unpickled_collection(self): original = utils.CompressedCollection() original.append("ab") unpickled = pickle.loads(pickle.dumps(original)) self.assertEqual(["ab"], list(unpickled)) unpickled.append("cd") self.assertEqual(["ab", "cd"], list(unpickled)) def test_objects_can_be_appended_a_collection_after_pickling(self): original = utils.CompressedCollection() original.append("ab") pickle.dumps(original) original.append("cd") self.assertEqual(["ab", "cd"], list(original))
<commit_before>import pickle import unittest from .. import utils class TestCompressedCollection(unittest.TestCase): def test_collection_can_be_pickled_and_unpickled(self): original = utils.CompressedCollection() original.append("ab") original.append("cd") unpickled = pickle.loads(pickle.dumps(original)) self.assertEqual(["ab", "cd"], list(unpickled)) def test_objects_can_be_appended_to_an_unpickled_collection(self): original = utils.CompressedCollection() original.append("ab") unpickled = pickle.loads(pickle.dumps(original)) self.assertEqual(["ab"], list(unpickled)) unpickled.append("cd") self.assertEqual(["ab", "cd"], list(unpickled)) def test_objects_can_be_appended_a_collection_after_pickling(self): original = utils.CompressedCollection() original.append("ab") pickle.dumps(original) original.append("cd") self.assertEqual(["ab", "cd"], list(original)) <commit_msg>Add a test for utils.fetch_url(..., opener=...) Signed-off-by: Ossi Herrala <37524b811d80bbe1732e3577b04d7a5fd222cfc5@gmail.com><commit_after>import socket import pickle import urllib2 import unittest import idiokit from .. import utils class TestFetchUrl(unittest.TestCase): def test_should_raise_TypeError_when_passing_in_an_opener(self): sock = socket.socket() try: sock.bind(("localhost", 0)) sock.listen(1) _, port = sock.getsockname() opener = urllib2.build_opener() fetch = utils.fetch_url("http://localhost:{0}".format(port), opener=opener) self.assertRaises(TypeError, idiokit.main_loop, fetch) finally: sock.close() class TestCompressedCollection(unittest.TestCase): def test_collection_can_be_pickled_and_unpickled(self): original = utils.CompressedCollection() original.append("ab") original.append("cd") unpickled = pickle.loads(pickle.dumps(original)) self.assertEqual(["ab", "cd"], list(unpickled)) def test_objects_can_be_appended_to_an_unpickled_collection(self): original = utils.CompressedCollection() original.append("ab") unpickled = pickle.loads(pickle.dumps(original)) self.assertEqual(["ab"], list(unpickled)) unpickled.append("cd") self.assertEqual(["ab", "cd"], list(unpickled)) def test_objects_can_be_appended_a_collection_after_pickling(self): original = utils.CompressedCollection() original.append("ab") pickle.dumps(original) original.append("cd") self.assertEqual(["ab", "cd"], list(original))
567925c770f965c7440b13b63b11b5615bf3c141
src/connection.py
src/connection.py
from . import output import json import sys import urllib.parse import http.client def getRequest(id, conf): db = conf['db'] headers = conf['headers'] test = db[id] method = test['method'].upper() fullpath = conf['path'] + test['path'] desc = test['desc'] params = '' server = conf['domain'] + ':' + conf['port'] try: conn = http.client.HTTPConnection(server) except IOError as err: conf['errors'].append("Server " + server + " not found!") output.validationError(conf) sys.exit(1) if method == 'GET': conn.request(method, fullpath) else: params = urllib.parse.urlencode(test['data']) res = conn.request(method, fullpath, params, headers) res = conn.getresponse() data = res.read().decode("utf-8").strip() if len(data) > 60: data = data[0:60] + '...' output.printRequest(method, conf['domain'], fullpath, params, desc, data, res.status) result = {} result['status'] = res.status result['header'] = res.getheaders() try: result['data'] = json.loads(data) except ValueError: print("Invalid JSON outout") # finally: # result['data'] = None return result
from . import output import json import sys import urllib.parse import http.client def getRequest(id, conf): db = conf['db'] headers = conf['headers'] test = db[id] method = test['method'].upper() fullpath = conf['path'] + test['path'] desc = test['desc'] params = '' server = conf['domain'] + ':' + conf['port'] try: conn = http.client.HTTPConnection(server) except IOError as err: conf['errors'].append("Server " + server + " not found!") output.validationError(conf) sys.exit(1) if method == 'GET': conn.request(method, fullpath) else: params = urllib.parse.urlencode(test['data']) res = conn.request(method, fullpath, params, headers) res = conn.getresponse() data = res.read().decode("utf-8").strip() if len(data) > 60: output_data = data.replace("\n", '') output_data = output_data[0:60] + '...' else: output_data = data output.printRequest(method, conf['domain'], fullpath, params, desc, output_data, res.status) result = {} result['status'] = res.status result['header'] = res.getheaders() try: result['data'] = json.loads(data) except ValueError: print("Invalid JSON outout") # finally: # result['data'] = None return result
Add a properly string for outputing
Add a properly string for outputing
Python
mit
manoelhc/restafari,manoelhc/restafari
from . import output import json import sys import urllib.parse import http.client def getRequest(id, conf): db = conf['db'] headers = conf['headers'] test = db[id] method = test['method'].upper() fullpath = conf['path'] + test['path'] desc = test['desc'] params = '' server = conf['domain'] + ':' + conf['port'] try: conn = http.client.HTTPConnection(server) except IOError as err: conf['errors'].append("Server " + server + " not found!") output.validationError(conf) sys.exit(1) if method == 'GET': conn.request(method, fullpath) else: params = urllib.parse.urlencode(test['data']) res = conn.request(method, fullpath, params, headers) res = conn.getresponse() data = res.read().decode("utf-8").strip() if len(data) > 60: data = data[0:60] + '...' output.printRequest(method, conf['domain'], fullpath, params, desc, data, res.status) result = {} result['status'] = res.status result['header'] = res.getheaders() try: result['data'] = json.loads(data) except ValueError: print("Invalid JSON outout") # finally: # result['data'] = None return result Add a properly string for outputing
from . import output import json import sys import urllib.parse import http.client def getRequest(id, conf): db = conf['db'] headers = conf['headers'] test = db[id] method = test['method'].upper() fullpath = conf['path'] + test['path'] desc = test['desc'] params = '' server = conf['domain'] + ':' + conf['port'] try: conn = http.client.HTTPConnection(server) except IOError as err: conf['errors'].append("Server " + server + " not found!") output.validationError(conf) sys.exit(1) if method == 'GET': conn.request(method, fullpath) else: params = urllib.parse.urlencode(test['data']) res = conn.request(method, fullpath, params, headers) res = conn.getresponse() data = res.read().decode("utf-8").strip() if len(data) > 60: output_data = data.replace("\n", '') output_data = output_data[0:60] + '...' else: output_data = data output.printRequest(method, conf['domain'], fullpath, params, desc, output_data, res.status) result = {} result['status'] = res.status result['header'] = res.getheaders() try: result['data'] = json.loads(data) except ValueError: print("Invalid JSON outout") # finally: # result['data'] = None return result
<commit_before>from . import output import json import sys import urllib.parse import http.client def getRequest(id, conf): db = conf['db'] headers = conf['headers'] test = db[id] method = test['method'].upper() fullpath = conf['path'] + test['path'] desc = test['desc'] params = '' server = conf['domain'] + ':' + conf['port'] try: conn = http.client.HTTPConnection(server) except IOError as err: conf['errors'].append("Server " + server + " not found!") output.validationError(conf) sys.exit(1) if method == 'GET': conn.request(method, fullpath) else: params = urllib.parse.urlencode(test['data']) res = conn.request(method, fullpath, params, headers) res = conn.getresponse() data = res.read().decode("utf-8").strip() if len(data) > 60: data = data[0:60] + '...' output.printRequest(method, conf['domain'], fullpath, params, desc, data, res.status) result = {} result['status'] = res.status result['header'] = res.getheaders() try: result['data'] = json.loads(data) except ValueError: print("Invalid JSON outout") # finally: # result['data'] = None return result <commit_msg>Add a properly string for outputing<commit_after>
from . import output import json import sys import urllib.parse import http.client def getRequest(id, conf): db = conf['db'] headers = conf['headers'] test = db[id] method = test['method'].upper() fullpath = conf['path'] + test['path'] desc = test['desc'] params = '' server = conf['domain'] + ':' + conf['port'] try: conn = http.client.HTTPConnection(server) except IOError as err: conf['errors'].append("Server " + server + " not found!") output.validationError(conf) sys.exit(1) if method == 'GET': conn.request(method, fullpath) else: params = urllib.parse.urlencode(test['data']) res = conn.request(method, fullpath, params, headers) res = conn.getresponse() data = res.read().decode("utf-8").strip() if len(data) > 60: output_data = data.replace("\n", '') output_data = output_data[0:60] + '...' else: output_data = data output.printRequest(method, conf['domain'], fullpath, params, desc, output_data, res.status) result = {} result['status'] = res.status result['header'] = res.getheaders() try: result['data'] = json.loads(data) except ValueError: print("Invalid JSON outout") # finally: # result['data'] = None return result
from . import output import json import sys import urllib.parse import http.client def getRequest(id, conf): db = conf['db'] headers = conf['headers'] test = db[id] method = test['method'].upper() fullpath = conf['path'] + test['path'] desc = test['desc'] params = '' server = conf['domain'] + ':' + conf['port'] try: conn = http.client.HTTPConnection(server) except IOError as err: conf['errors'].append("Server " + server + " not found!") output.validationError(conf) sys.exit(1) if method == 'GET': conn.request(method, fullpath) else: params = urllib.parse.urlencode(test['data']) res = conn.request(method, fullpath, params, headers) res = conn.getresponse() data = res.read().decode("utf-8").strip() if len(data) > 60: data = data[0:60] + '...' output.printRequest(method, conf['domain'], fullpath, params, desc, data, res.status) result = {} result['status'] = res.status result['header'] = res.getheaders() try: result['data'] = json.loads(data) except ValueError: print("Invalid JSON outout") # finally: # result['data'] = None return result Add a properly string for outputingfrom . import output import json import sys import urllib.parse import http.client def getRequest(id, conf): db = conf['db'] headers = conf['headers'] test = db[id] method = test['method'].upper() fullpath = conf['path'] + test['path'] desc = test['desc'] params = '' server = conf['domain'] + ':' + conf['port'] try: conn = http.client.HTTPConnection(server) except IOError as err: conf['errors'].append("Server " + server + " not found!") output.validationError(conf) sys.exit(1) if method == 'GET': conn.request(method, fullpath) else: params = urllib.parse.urlencode(test['data']) res = conn.request(method, fullpath, params, headers) res = conn.getresponse() data = res.read().decode("utf-8").strip() if len(data) > 60: output_data = data.replace("\n", '') output_data = output_data[0:60] + '...' else: output_data = data output.printRequest(method, conf['domain'], fullpath, params, desc, output_data, res.status) result = {} result['status'] = res.status result['header'] = res.getheaders() try: result['data'] = json.loads(data) except ValueError: print("Invalid JSON outout") # finally: # result['data'] = None return result
<commit_before>from . import output import json import sys import urllib.parse import http.client def getRequest(id, conf): db = conf['db'] headers = conf['headers'] test = db[id] method = test['method'].upper() fullpath = conf['path'] + test['path'] desc = test['desc'] params = '' server = conf['domain'] + ':' + conf['port'] try: conn = http.client.HTTPConnection(server) except IOError as err: conf['errors'].append("Server " + server + " not found!") output.validationError(conf) sys.exit(1) if method == 'GET': conn.request(method, fullpath) else: params = urllib.parse.urlencode(test['data']) res = conn.request(method, fullpath, params, headers) res = conn.getresponse() data = res.read().decode("utf-8").strip() if len(data) > 60: data = data[0:60] + '...' output.printRequest(method, conf['domain'], fullpath, params, desc, data, res.status) result = {} result['status'] = res.status result['header'] = res.getheaders() try: result['data'] = json.loads(data) except ValueError: print("Invalid JSON outout") # finally: # result['data'] = None return result <commit_msg>Add a properly string for outputing<commit_after>from . import output import json import sys import urllib.parse import http.client def getRequest(id, conf): db = conf['db'] headers = conf['headers'] test = db[id] method = test['method'].upper() fullpath = conf['path'] + test['path'] desc = test['desc'] params = '' server = conf['domain'] + ':' + conf['port'] try: conn = http.client.HTTPConnection(server) except IOError as err: conf['errors'].append("Server " + server + " not found!") output.validationError(conf) sys.exit(1) if method == 'GET': conn.request(method, fullpath) else: params = urllib.parse.urlencode(test['data']) res = conn.request(method, fullpath, params, headers) res = conn.getresponse() data = res.read().decode("utf-8").strip() if len(data) > 60: output_data = data.replace("\n", '') output_data = output_data[0:60] + '...' else: output_data = data output.printRequest(method, conf['domain'], fullpath, params, desc, output_data, res.status) result = {} result['status'] = res.status result['header'] = res.getheaders() try: result['data'] = json.loads(data) except ValueError: print("Invalid JSON outout") # finally: # result['data'] = None return result
a81f78385f8ec9a94d0d511805801d1f0a6f17ed
drogher/shippers/fedex.py
drogher/shippers/fedex.py
from .base import Shipper class FedEx(Shipper): shipper = 'FedEx' class FedExExpress(FedEx): barcode_pattern = r'^\d{34}$' @property def tracking_number(self): return self.barcode[20:].lstrip('0') @property def valid_checksum(self): chars, check_digit = self.tracking_number[:-1], self.tracking_number[-1] total = 0 for digit, char in zip([1, 3, 7, 1, 3, 7, 1, 3, 7, 1, 3], reversed(chars)): total += int(char) * digit return total % 11 % 10 == int(check_digit) class FedExGround96(FedEx): barcode_pattern = r'^96\d{20}$' @property def tracking_number(self): return self.barcode[7:] @property def valid_checksum(self): chars, check_digit = self.tracking_number[:-1], self.tracking_number[-1] odd = even = 0 for i, char in enumerate(reversed(chars)): if i & 0x1: odd += int(char) else: even += int(char) check = ((even * 3) + odd) % 10 if check != 0: check = 10 - check return check == int(check_digit)
import itertools from .base import Shipper class FedEx(Shipper): shipper = 'FedEx' class FedExExpress(FedEx): barcode_pattern = r'^\d{34}$' @property def tracking_number(self): return self.barcode[20:].lstrip('0') @property def valid_checksum(self): chars, check_digit = self.tracking_number[:-1], self.tracking_number[-1] total = 0 for digit, char in zip(itertools.cycle([1, 3, 7]), reversed(chars)): total += int(char) * digit return total % 11 % 10 == int(check_digit) class FedExGround96(FedEx): barcode_pattern = r'^96\d{20}$' @property def tracking_number(self): return self.barcode[7:] @property def valid_checksum(self): chars, check_digit = self.tracking_number[:-1], self.tracking_number[-1] odd = even = 0 for i, char in enumerate(reversed(chars)): if i & 0x1: odd += int(char) else: even += int(char) check = ((even * 3) + odd) % 10 if check != 0: check = 10 - check return check == int(check_digit)
Use itertools.cycle for repeating digits
Use itertools.cycle for repeating digits
Python
bsd-3-clause
jbittel/drogher
from .base import Shipper class FedEx(Shipper): shipper = 'FedEx' class FedExExpress(FedEx): barcode_pattern = r'^\d{34}$' @property def tracking_number(self): return self.barcode[20:].lstrip('0') @property def valid_checksum(self): chars, check_digit = self.tracking_number[:-1], self.tracking_number[-1] total = 0 for digit, char in zip([1, 3, 7, 1, 3, 7, 1, 3, 7, 1, 3], reversed(chars)): total += int(char) * digit return total % 11 % 10 == int(check_digit) class FedExGround96(FedEx): barcode_pattern = r'^96\d{20}$' @property def tracking_number(self): return self.barcode[7:] @property def valid_checksum(self): chars, check_digit = self.tracking_number[:-1], self.tracking_number[-1] odd = even = 0 for i, char in enumerate(reversed(chars)): if i & 0x1: odd += int(char) else: even += int(char) check = ((even * 3) + odd) % 10 if check != 0: check = 10 - check return check == int(check_digit) Use itertools.cycle for repeating digits
import itertools from .base import Shipper class FedEx(Shipper): shipper = 'FedEx' class FedExExpress(FedEx): barcode_pattern = r'^\d{34}$' @property def tracking_number(self): return self.barcode[20:].lstrip('0') @property def valid_checksum(self): chars, check_digit = self.tracking_number[:-1], self.tracking_number[-1] total = 0 for digit, char in zip(itertools.cycle([1, 3, 7]), reversed(chars)): total += int(char) * digit return total % 11 % 10 == int(check_digit) class FedExGround96(FedEx): barcode_pattern = r'^96\d{20}$' @property def tracking_number(self): return self.barcode[7:] @property def valid_checksum(self): chars, check_digit = self.tracking_number[:-1], self.tracking_number[-1] odd = even = 0 for i, char in enumerate(reversed(chars)): if i & 0x1: odd += int(char) else: even += int(char) check = ((even * 3) + odd) % 10 if check != 0: check = 10 - check return check == int(check_digit)
<commit_before>from .base import Shipper class FedEx(Shipper): shipper = 'FedEx' class FedExExpress(FedEx): barcode_pattern = r'^\d{34}$' @property def tracking_number(self): return self.barcode[20:].lstrip('0') @property def valid_checksum(self): chars, check_digit = self.tracking_number[:-1], self.tracking_number[-1] total = 0 for digit, char in zip([1, 3, 7, 1, 3, 7, 1, 3, 7, 1, 3], reversed(chars)): total += int(char) * digit return total % 11 % 10 == int(check_digit) class FedExGround96(FedEx): barcode_pattern = r'^96\d{20}$' @property def tracking_number(self): return self.barcode[7:] @property def valid_checksum(self): chars, check_digit = self.tracking_number[:-1], self.tracking_number[-1] odd = even = 0 for i, char in enumerate(reversed(chars)): if i & 0x1: odd += int(char) else: even += int(char) check = ((even * 3) + odd) % 10 if check != 0: check = 10 - check return check == int(check_digit) <commit_msg>Use itertools.cycle for repeating digits<commit_after>
import itertools from .base import Shipper class FedEx(Shipper): shipper = 'FedEx' class FedExExpress(FedEx): barcode_pattern = r'^\d{34}$' @property def tracking_number(self): return self.barcode[20:].lstrip('0') @property def valid_checksum(self): chars, check_digit = self.tracking_number[:-1], self.tracking_number[-1] total = 0 for digit, char in zip(itertools.cycle([1, 3, 7]), reversed(chars)): total += int(char) * digit return total % 11 % 10 == int(check_digit) class FedExGround96(FedEx): barcode_pattern = r'^96\d{20}$' @property def tracking_number(self): return self.barcode[7:] @property def valid_checksum(self): chars, check_digit = self.tracking_number[:-1], self.tracking_number[-1] odd = even = 0 for i, char in enumerate(reversed(chars)): if i & 0x1: odd += int(char) else: even += int(char) check = ((even * 3) + odd) % 10 if check != 0: check = 10 - check return check == int(check_digit)
from .base import Shipper class FedEx(Shipper): shipper = 'FedEx' class FedExExpress(FedEx): barcode_pattern = r'^\d{34}$' @property def tracking_number(self): return self.barcode[20:].lstrip('0') @property def valid_checksum(self): chars, check_digit = self.tracking_number[:-1], self.tracking_number[-1] total = 0 for digit, char in zip([1, 3, 7, 1, 3, 7, 1, 3, 7, 1, 3], reversed(chars)): total += int(char) * digit return total % 11 % 10 == int(check_digit) class FedExGround96(FedEx): barcode_pattern = r'^96\d{20}$' @property def tracking_number(self): return self.barcode[7:] @property def valid_checksum(self): chars, check_digit = self.tracking_number[:-1], self.tracking_number[-1] odd = even = 0 for i, char in enumerate(reversed(chars)): if i & 0x1: odd += int(char) else: even += int(char) check = ((even * 3) + odd) % 10 if check != 0: check = 10 - check return check == int(check_digit) Use itertools.cycle for repeating digitsimport itertools from .base import Shipper class FedEx(Shipper): shipper = 'FedEx' class FedExExpress(FedEx): barcode_pattern = r'^\d{34}$' @property def tracking_number(self): return self.barcode[20:].lstrip('0') @property def valid_checksum(self): chars, check_digit = self.tracking_number[:-1], self.tracking_number[-1] total = 0 for digit, char in zip(itertools.cycle([1, 3, 7]), reversed(chars)): total += int(char) * digit return total % 11 % 10 == int(check_digit) class FedExGround96(FedEx): barcode_pattern = r'^96\d{20}$' @property def tracking_number(self): return self.barcode[7:] @property def valid_checksum(self): chars, check_digit = self.tracking_number[:-1], self.tracking_number[-1] odd = even = 0 for i, char in enumerate(reversed(chars)): if i & 0x1: odd += int(char) else: even += int(char) check = ((even * 3) + odd) % 10 if check != 0: check = 10 - check return check == int(check_digit)
<commit_before>from .base import Shipper class FedEx(Shipper): shipper = 'FedEx' class FedExExpress(FedEx): barcode_pattern = r'^\d{34}$' @property def tracking_number(self): return self.barcode[20:].lstrip('0') @property def valid_checksum(self): chars, check_digit = self.tracking_number[:-1], self.tracking_number[-1] total = 0 for digit, char in zip([1, 3, 7, 1, 3, 7, 1, 3, 7, 1, 3], reversed(chars)): total += int(char) * digit return total % 11 % 10 == int(check_digit) class FedExGround96(FedEx): barcode_pattern = r'^96\d{20}$' @property def tracking_number(self): return self.barcode[7:] @property def valid_checksum(self): chars, check_digit = self.tracking_number[:-1], self.tracking_number[-1] odd = even = 0 for i, char in enumerate(reversed(chars)): if i & 0x1: odd += int(char) else: even += int(char) check = ((even * 3) + odd) % 10 if check != 0: check = 10 - check return check == int(check_digit) <commit_msg>Use itertools.cycle for repeating digits<commit_after>import itertools from .base import Shipper class FedEx(Shipper): shipper = 'FedEx' class FedExExpress(FedEx): barcode_pattern = r'^\d{34}$' @property def tracking_number(self): return self.barcode[20:].lstrip('0') @property def valid_checksum(self): chars, check_digit = self.tracking_number[:-1], self.tracking_number[-1] total = 0 for digit, char in zip(itertools.cycle([1, 3, 7]), reversed(chars)): total += int(char) * digit return total % 11 % 10 == int(check_digit) class FedExGround96(FedEx): barcode_pattern = r'^96\d{20}$' @property def tracking_number(self): return self.barcode[7:] @property def valid_checksum(self): chars, check_digit = self.tracking_number[:-1], self.tracking_number[-1] odd = even = 0 for i, char in enumerate(reversed(chars)): if i & 0x1: odd += int(char) else: even += int(char) check = ((even * 3) + odd) % 10 if check != 0: check = 10 - check return check == int(check_digit)
b7fcbc3a2117f00177ddd7a353eb6a4dee5bc777
stat_retriever.py
stat_retriever.py
""" stat-retriever by Team-95 stat_retriever.py """ import requests def main(): url = "http://stats.nba.com/stats/leaguedashplayerbiostats?College=&Conference=" "&Country=&DateFrom=&DateTo=&Division=&DraftPick=&DraftYear=&GameScope=&GameSegment=" "&Height=&LastNGames=0&LeagueID=00&Location=&Month=0&OpponentTeamID=0&Outcome=&PORound=" "0&PerMode=PerGame&Period=0&PlayerExperience=&PlayerPosition=&Season=2014-15&SeasonSegment=" "&SeasonType=Regular+Season&ShotClockRange=&StarterBench=&TeamID=0&VsConference=&VsDivision=&Weight=" if __name__ == "__main__": main()
""" stat-retriever by Team-95 stat_retriever.py """ import requests import json def main(): season = "2014-15" url = ("http://stats.nba.com/stats/leaguedashplayerbiostats?College=&Conference=" "&Country=&DateFrom=&DateTo=&Division=&DraftPick=&DraftYear=&GameScope=&GameSegment=" "&Height=&LastNGames=0&LeagueID=00&Location=&Month=0&OpponentTeamID=0&Outcome=&PORound=" "0&PerMode=PerGame&Period=0&PlayerExperience=&PlayerPosition=&Season=%s&SeasonSegment=" "&SeasonType=Regular+Season&ShotClockRange=&StarterBench=&TeamID=0&VsConference=" "&VsDivision=&Weight=") % season response = requests.get(url) stats = json.loads(response.text) if __name__ == "__main__": main()
Fix formatting once more, added response parsing
Fix formatting once more, added response parsing
Python
mit
Team-95/stat-retriever
""" stat-retriever by Team-95 stat_retriever.py """ import requests def main(): url = "http://stats.nba.com/stats/leaguedashplayerbiostats?College=&Conference=" "&Country=&DateFrom=&DateTo=&Division=&DraftPick=&DraftYear=&GameScope=&GameSegment=" "&Height=&LastNGames=0&LeagueID=00&Location=&Month=0&OpponentTeamID=0&Outcome=&PORound=" "0&PerMode=PerGame&Period=0&PlayerExperience=&PlayerPosition=&Season=2014-15&SeasonSegment=" "&SeasonType=Regular+Season&ShotClockRange=&StarterBench=&TeamID=0&VsConference=&VsDivision=&Weight=" if __name__ == "__main__": main() Fix formatting once more, added response parsing
""" stat-retriever by Team-95 stat_retriever.py """ import requests import json def main(): season = "2014-15" url = ("http://stats.nba.com/stats/leaguedashplayerbiostats?College=&Conference=" "&Country=&DateFrom=&DateTo=&Division=&DraftPick=&DraftYear=&GameScope=&GameSegment=" "&Height=&LastNGames=0&LeagueID=00&Location=&Month=0&OpponentTeamID=0&Outcome=&PORound=" "0&PerMode=PerGame&Period=0&PlayerExperience=&PlayerPosition=&Season=%s&SeasonSegment=" "&SeasonType=Regular+Season&ShotClockRange=&StarterBench=&TeamID=0&VsConference=" "&VsDivision=&Weight=") % season response = requests.get(url) stats = json.loads(response.text) if __name__ == "__main__": main()
<commit_before>""" stat-retriever by Team-95 stat_retriever.py """ import requests def main(): url = "http://stats.nba.com/stats/leaguedashplayerbiostats?College=&Conference=" "&Country=&DateFrom=&DateTo=&Division=&DraftPick=&DraftYear=&GameScope=&GameSegment=" "&Height=&LastNGames=0&LeagueID=00&Location=&Month=0&OpponentTeamID=0&Outcome=&PORound=" "0&PerMode=PerGame&Period=0&PlayerExperience=&PlayerPosition=&Season=2014-15&SeasonSegment=" "&SeasonType=Regular+Season&ShotClockRange=&StarterBench=&TeamID=0&VsConference=&VsDivision=&Weight=" if __name__ == "__main__": main() <commit_msg>Fix formatting once more, added response parsing<commit_after>
""" stat-retriever by Team-95 stat_retriever.py """ import requests import json def main(): season = "2014-15" url = ("http://stats.nba.com/stats/leaguedashplayerbiostats?College=&Conference=" "&Country=&DateFrom=&DateTo=&Division=&DraftPick=&DraftYear=&GameScope=&GameSegment=" "&Height=&LastNGames=0&LeagueID=00&Location=&Month=0&OpponentTeamID=0&Outcome=&PORound=" "0&PerMode=PerGame&Period=0&PlayerExperience=&PlayerPosition=&Season=%s&SeasonSegment=" "&SeasonType=Regular+Season&ShotClockRange=&StarterBench=&TeamID=0&VsConference=" "&VsDivision=&Weight=") % season response = requests.get(url) stats = json.loads(response.text) if __name__ == "__main__": main()
""" stat-retriever by Team-95 stat_retriever.py """ import requests def main(): url = "http://stats.nba.com/stats/leaguedashplayerbiostats?College=&Conference=" "&Country=&DateFrom=&DateTo=&Division=&DraftPick=&DraftYear=&GameScope=&GameSegment=" "&Height=&LastNGames=0&LeagueID=00&Location=&Month=0&OpponentTeamID=0&Outcome=&PORound=" "0&PerMode=PerGame&Period=0&PlayerExperience=&PlayerPosition=&Season=2014-15&SeasonSegment=" "&SeasonType=Regular+Season&ShotClockRange=&StarterBench=&TeamID=0&VsConference=&VsDivision=&Weight=" if __name__ == "__main__": main() Fix formatting once more, added response parsing""" stat-retriever by Team-95 stat_retriever.py """ import requests import json def main(): season = "2014-15" url = ("http://stats.nba.com/stats/leaguedashplayerbiostats?College=&Conference=" "&Country=&DateFrom=&DateTo=&Division=&DraftPick=&DraftYear=&GameScope=&GameSegment=" "&Height=&LastNGames=0&LeagueID=00&Location=&Month=0&OpponentTeamID=0&Outcome=&PORound=" "0&PerMode=PerGame&Period=0&PlayerExperience=&PlayerPosition=&Season=%s&SeasonSegment=" "&SeasonType=Regular+Season&ShotClockRange=&StarterBench=&TeamID=0&VsConference=" "&VsDivision=&Weight=") % season response = requests.get(url) stats = json.loads(response.text) if __name__ == "__main__": main()
<commit_before>""" stat-retriever by Team-95 stat_retriever.py """ import requests def main(): url = "http://stats.nba.com/stats/leaguedashplayerbiostats?College=&Conference=" "&Country=&DateFrom=&DateTo=&Division=&DraftPick=&DraftYear=&GameScope=&GameSegment=" "&Height=&LastNGames=0&LeagueID=00&Location=&Month=0&OpponentTeamID=0&Outcome=&PORound=" "0&PerMode=PerGame&Period=0&PlayerExperience=&PlayerPosition=&Season=2014-15&SeasonSegment=" "&SeasonType=Regular+Season&ShotClockRange=&StarterBench=&TeamID=0&VsConference=&VsDivision=&Weight=" if __name__ == "__main__": main() <commit_msg>Fix formatting once more, added response parsing<commit_after>""" stat-retriever by Team-95 stat_retriever.py """ import requests import json def main(): season = "2014-15" url = ("http://stats.nba.com/stats/leaguedashplayerbiostats?College=&Conference=" "&Country=&DateFrom=&DateTo=&Division=&DraftPick=&DraftYear=&GameScope=&GameSegment=" "&Height=&LastNGames=0&LeagueID=00&Location=&Month=0&OpponentTeamID=0&Outcome=&PORound=" "0&PerMode=PerGame&Period=0&PlayerExperience=&PlayerPosition=&Season=%s&SeasonSegment=" "&SeasonType=Regular+Season&ShotClockRange=&StarterBench=&TeamID=0&VsConference=" "&VsDivision=&Weight=") % season response = requests.get(url) stats = json.loads(response.text) if __name__ == "__main__": main()
ce3249dea725d40d5e0916b344cdde53ab6d53dc
src/satosa/micro_services/processors/scope_extractor_processor.py
src/satosa/micro_services/processors/scope_extractor_processor.py
from ..attribute_processor import AttributeProcessorError, AttributeProcessorWarning from .base_processor import BaseProcessor CONFIG_KEY_MAPPEDATTRIBUTE = 'mapped_attribute' CONFIG_DEFAULT_MAPPEDATTRIBUTE = '' class ScopeExtractorProcessor(BaseProcessor): """ Extracts the scope from a scoped attribute and maps that to another attribute Example configuration: module: satosa.micro_services.attribute_processor.AttributeProcessor name: AttributeProcessor config: process: - attribute: scoped_affiliation processors: - name: ScopeExtractorProcessor module: satosa.micro_services.processors.scope_extractor_processor mapped_attribute: domain """ def process(self, internal_data, attribute, **kwargs): mapped_attribute = kwargs.get(CONFIG_KEY_MAPPEDATTRIBUTE, CONFIG_DEFAULT_MAPPEDATTRIBUTE) if mapped_attribute is None or mapped_attribute == '': raise AttributeProcessorError("The mapped_attribute needs to be set") attributes = internal_data.attributes values = attributes.get(attribute, []) if not values: raise AttributeProcessorWarning("Cannot apply scope_extractor to {}, it has no values".format(attribute)) if not any('@' in val for val in values): raise AttributeProcessorWarning("Cannot apply scope_extractor to {}, it's values are not scoped".format(attribute)) for value in values: if '@' in value: scope = value.split('@')[1] attributes[mapped_attribute] = [scope] break
from ..attribute_processor import AttributeProcessorError, AttributeProcessorWarning from .base_processor import BaseProcessor CONFIG_KEY_MAPPEDATTRIBUTE = 'mapped_attribute' CONFIG_DEFAULT_MAPPEDATTRIBUTE = '' class ScopeExtractorProcessor(BaseProcessor): """ Extracts the scope from a scoped attribute and maps that to another attribute Example configuration: module: satosa.micro_services.attribute_processor.AttributeProcessor name: AttributeProcessor config: process: - attribute: scoped_affiliation processors: - name: ScopeExtractorProcessor module: satosa.micro_services.processors.scope_extractor_processor mapped_attribute: domain """ def process(self, internal_data, attribute, **kwargs): mapped_attribute = kwargs.get(CONFIG_KEY_MAPPEDATTRIBUTE, CONFIG_DEFAULT_MAPPEDATTRIBUTE) if mapped_attribute is None or mapped_attribute == '': raise AttributeProcessorError("The mapped_attribute needs to be set") attributes = internal_data.attributes values = attributes.get(attribute, []) if not values: raise AttributeProcessorWarning("Cannot apply scope_extractor to {}, it has no values".format(attribute)) if not isinstance(values, list): values = [values] if not any('@' in val for val in values): raise AttributeProcessorWarning("Cannot apply scope_extractor to {}, it's values are not scoped".format(attribute)) for value in values: if '@' in value: scope = value.split('@')[1] attributes[mapped_attribute] = [scope] break
Make the ScopeExtractorProcessor usable for the Primary Identifier
Make the ScopeExtractorProcessor usable for the Primary Identifier This patch adds support to use the ScopeExtractorProcessor on the Primary Identifiert which is, in contrast to the other values, a string. Closes #348
Python
apache-2.0
SUNET/SATOSA,SUNET/SATOSA,its-dirg/SATOSA
from ..attribute_processor import AttributeProcessorError, AttributeProcessorWarning from .base_processor import BaseProcessor CONFIG_KEY_MAPPEDATTRIBUTE = 'mapped_attribute' CONFIG_DEFAULT_MAPPEDATTRIBUTE = '' class ScopeExtractorProcessor(BaseProcessor): """ Extracts the scope from a scoped attribute and maps that to another attribute Example configuration: module: satosa.micro_services.attribute_processor.AttributeProcessor name: AttributeProcessor config: process: - attribute: scoped_affiliation processors: - name: ScopeExtractorProcessor module: satosa.micro_services.processors.scope_extractor_processor mapped_attribute: domain """ def process(self, internal_data, attribute, **kwargs): mapped_attribute = kwargs.get(CONFIG_KEY_MAPPEDATTRIBUTE, CONFIG_DEFAULT_MAPPEDATTRIBUTE) if mapped_attribute is None or mapped_attribute == '': raise AttributeProcessorError("The mapped_attribute needs to be set") attributes = internal_data.attributes values = attributes.get(attribute, []) if not values: raise AttributeProcessorWarning("Cannot apply scope_extractor to {}, it has no values".format(attribute)) if not any('@' in val for val in values): raise AttributeProcessorWarning("Cannot apply scope_extractor to {}, it's values are not scoped".format(attribute)) for value in values: if '@' in value: scope = value.split('@')[1] attributes[mapped_attribute] = [scope] break Make the ScopeExtractorProcessor usable for the Primary Identifier This patch adds support to use the ScopeExtractorProcessor on the Primary Identifiert which is, in contrast to the other values, a string. Closes #348
from ..attribute_processor import AttributeProcessorError, AttributeProcessorWarning from .base_processor import BaseProcessor CONFIG_KEY_MAPPEDATTRIBUTE = 'mapped_attribute' CONFIG_DEFAULT_MAPPEDATTRIBUTE = '' class ScopeExtractorProcessor(BaseProcessor): """ Extracts the scope from a scoped attribute and maps that to another attribute Example configuration: module: satosa.micro_services.attribute_processor.AttributeProcessor name: AttributeProcessor config: process: - attribute: scoped_affiliation processors: - name: ScopeExtractorProcessor module: satosa.micro_services.processors.scope_extractor_processor mapped_attribute: domain """ def process(self, internal_data, attribute, **kwargs): mapped_attribute = kwargs.get(CONFIG_KEY_MAPPEDATTRIBUTE, CONFIG_DEFAULT_MAPPEDATTRIBUTE) if mapped_attribute is None or mapped_attribute == '': raise AttributeProcessorError("The mapped_attribute needs to be set") attributes = internal_data.attributes values = attributes.get(attribute, []) if not values: raise AttributeProcessorWarning("Cannot apply scope_extractor to {}, it has no values".format(attribute)) if not isinstance(values, list): values = [values] if not any('@' in val for val in values): raise AttributeProcessorWarning("Cannot apply scope_extractor to {}, it's values are not scoped".format(attribute)) for value in values: if '@' in value: scope = value.split('@')[1] attributes[mapped_attribute] = [scope] break
<commit_before>from ..attribute_processor import AttributeProcessorError, AttributeProcessorWarning from .base_processor import BaseProcessor CONFIG_KEY_MAPPEDATTRIBUTE = 'mapped_attribute' CONFIG_DEFAULT_MAPPEDATTRIBUTE = '' class ScopeExtractorProcessor(BaseProcessor): """ Extracts the scope from a scoped attribute and maps that to another attribute Example configuration: module: satosa.micro_services.attribute_processor.AttributeProcessor name: AttributeProcessor config: process: - attribute: scoped_affiliation processors: - name: ScopeExtractorProcessor module: satosa.micro_services.processors.scope_extractor_processor mapped_attribute: domain """ def process(self, internal_data, attribute, **kwargs): mapped_attribute = kwargs.get(CONFIG_KEY_MAPPEDATTRIBUTE, CONFIG_DEFAULT_MAPPEDATTRIBUTE) if mapped_attribute is None or mapped_attribute == '': raise AttributeProcessorError("The mapped_attribute needs to be set") attributes = internal_data.attributes values = attributes.get(attribute, []) if not values: raise AttributeProcessorWarning("Cannot apply scope_extractor to {}, it has no values".format(attribute)) if not any('@' in val for val in values): raise AttributeProcessorWarning("Cannot apply scope_extractor to {}, it's values are not scoped".format(attribute)) for value in values: if '@' in value: scope = value.split('@')[1] attributes[mapped_attribute] = [scope] break <commit_msg>Make the ScopeExtractorProcessor usable for the Primary Identifier This patch adds support to use the ScopeExtractorProcessor on the Primary Identifiert which is, in contrast to the other values, a string. Closes #348<commit_after>
from ..attribute_processor import AttributeProcessorError, AttributeProcessorWarning from .base_processor import BaseProcessor CONFIG_KEY_MAPPEDATTRIBUTE = 'mapped_attribute' CONFIG_DEFAULT_MAPPEDATTRIBUTE = '' class ScopeExtractorProcessor(BaseProcessor): """ Extracts the scope from a scoped attribute and maps that to another attribute Example configuration: module: satosa.micro_services.attribute_processor.AttributeProcessor name: AttributeProcessor config: process: - attribute: scoped_affiliation processors: - name: ScopeExtractorProcessor module: satosa.micro_services.processors.scope_extractor_processor mapped_attribute: domain """ def process(self, internal_data, attribute, **kwargs): mapped_attribute = kwargs.get(CONFIG_KEY_MAPPEDATTRIBUTE, CONFIG_DEFAULT_MAPPEDATTRIBUTE) if mapped_attribute is None or mapped_attribute == '': raise AttributeProcessorError("The mapped_attribute needs to be set") attributes = internal_data.attributes values = attributes.get(attribute, []) if not values: raise AttributeProcessorWarning("Cannot apply scope_extractor to {}, it has no values".format(attribute)) if not isinstance(values, list): values = [values] if not any('@' in val for val in values): raise AttributeProcessorWarning("Cannot apply scope_extractor to {}, it's values are not scoped".format(attribute)) for value in values: if '@' in value: scope = value.split('@')[1] attributes[mapped_attribute] = [scope] break
from ..attribute_processor import AttributeProcessorError, AttributeProcessorWarning from .base_processor import BaseProcessor CONFIG_KEY_MAPPEDATTRIBUTE = 'mapped_attribute' CONFIG_DEFAULT_MAPPEDATTRIBUTE = '' class ScopeExtractorProcessor(BaseProcessor): """ Extracts the scope from a scoped attribute and maps that to another attribute Example configuration: module: satosa.micro_services.attribute_processor.AttributeProcessor name: AttributeProcessor config: process: - attribute: scoped_affiliation processors: - name: ScopeExtractorProcessor module: satosa.micro_services.processors.scope_extractor_processor mapped_attribute: domain """ def process(self, internal_data, attribute, **kwargs): mapped_attribute = kwargs.get(CONFIG_KEY_MAPPEDATTRIBUTE, CONFIG_DEFAULT_MAPPEDATTRIBUTE) if mapped_attribute is None or mapped_attribute == '': raise AttributeProcessorError("The mapped_attribute needs to be set") attributes = internal_data.attributes values = attributes.get(attribute, []) if not values: raise AttributeProcessorWarning("Cannot apply scope_extractor to {}, it has no values".format(attribute)) if not any('@' in val for val in values): raise AttributeProcessorWarning("Cannot apply scope_extractor to {}, it's values are not scoped".format(attribute)) for value in values: if '@' in value: scope = value.split('@')[1] attributes[mapped_attribute] = [scope] break Make the ScopeExtractorProcessor usable for the Primary Identifier This patch adds support to use the ScopeExtractorProcessor on the Primary Identifiert which is, in contrast to the other values, a string. Closes #348from ..attribute_processor import AttributeProcessorError, AttributeProcessorWarning from .base_processor import BaseProcessor CONFIG_KEY_MAPPEDATTRIBUTE = 'mapped_attribute' CONFIG_DEFAULT_MAPPEDATTRIBUTE = '' class ScopeExtractorProcessor(BaseProcessor): """ Extracts the scope from a scoped attribute and maps that to another attribute Example configuration: module: satosa.micro_services.attribute_processor.AttributeProcessor name: AttributeProcessor config: process: - attribute: scoped_affiliation processors: - name: ScopeExtractorProcessor module: satosa.micro_services.processors.scope_extractor_processor mapped_attribute: domain """ def process(self, internal_data, attribute, **kwargs): mapped_attribute = kwargs.get(CONFIG_KEY_MAPPEDATTRIBUTE, CONFIG_DEFAULT_MAPPEDATTRIBUTE) if mapped_attribute is None or mapped_attribute == '': raise AttributeProcessorError("The mapped_attribute needs to be set") attributes = internal_data.attributes values = attributes.get(attribute, []) if not values: raise AttributeProcessorWarning("Cannot apply scope_extractor to {}, it has no values".format(attribute)) if not isinstance(values, list): values = [values] if not any('@' in val for val in values): raise AttributeProcessorWarning("Cannot apply scope_extractor to {}, it's values are not scoped".format(attribute)) for value in values: if '@' in value: scope = value.split('@')[1] attributes[mapped_attribute] = [scope] break
<commit_before>from ..attribute_processor import AttributeProcessorError, AttributeProcessorWarning from .base_processor import BaseProcessor CONFIG_KEY_MAPPEDATTRIBUTE = 'mapped_attribute' CONFIG_DEFAULT_MAPPEDATTRIBUTE = '' class ScopeExtractorProcessor(BaseProcessor): """ Extracts the scope from a scoped attribute and maps that to another attribute Example configuration: module: satosa.micro_services.attribute_processor.AttributeProcessor name: AttributeProcessor config: process: - attribute: scoped_affiliation processors: - name: ScopeExtractorProcessor module: satosa.micro_services.processors.scope_extractor_processor mapped_attribute: domain """ def process(self, internal_data, attribute, **kwargs): mapped_attribute = kwargs.get(CONFIG_KEY_MAPPEDATTRIBUTE, CONFIG_DEFAULT_MAPPEDATTRIBUTE) if mapped_attribute is None or mapped_attribute == '': raise AttributeProcessorError("The mapped_attribute needs to be set") attributes = internal_data.attributes values = attributes.get(attribute, []) if not values: raise AttributeProcessorWarning("Cannot apply scope_extractor to {}, it has no values".format(attribute)) if not any('@' in val for val in values): raise AttributeProcessorWarning("Cannot apply scope_extractor to {}, it's values are not scoped".format(attribute)) for value in values: if '@' in value: scope = value.split('@')[1] attributes[mapped_attribute] = [scope] break <commit_msg>Make the ScopeExtractorProcessor usable for the Primary Identifier This patch adds support to use the ScopeExtractorProcessor on the Primary Identifiert which is, in contrast to the other values, a string. Closes #348<commit_after>from ..attribute_processor import AttributeProcessorError, AttributeProcessorWarning from .base_processor import BaseProcessor CONFIG_KEY_MAPPEDATTRIBUTE = 'mapped_attribute' CONFIG_DEFAULT_MAPPEDATTRIBUTE = '' class ScopeExtractorProcessor(BaseProcessor): """ Extracts the scope from a scoped attribute and maps that to another attribute Example configuration: module: satosa.micro_services.attribute_processor.AttributeProcessor name: AttributeProcessor config: process: - attribute: scoped_affiliation processors: - name: ScopeExtractorProcessor module: satosa.micro_services.processors.scope_extractor_processor mapped_attribute: domain """ def process(self, internal_data, attribute, **kwargs): mapped_attribute = kwargs.get(CONFIG_KEY_MAPPEDATTRIBUTE, CONFIG_DEFAULT_MAPPEDATTRIBUTE) if mapped_attribute is None or mapped_attribute == '': raise AttributeProcessorError("The mapped_attribute needs to be set") attributes = internal_data.attributes values = attributes.get(attribute, []) if not values: raise AttributeProcessorWarning("Cannot apply scope_extractor to {}, it has no values".format(attribute)) if not isinstance(values, list): values = [values] if not any('@' in val for val in values): raise AttributeProcessorWarning("Cannot apply scope_extractor to {}, it's values are not scoped".format(attribute)) for value in values: if '@' in value: scope = value.split('@')[1] attributes[mapped_attribute] = [scope] break
8445d491030be7fb2fa1175140a4b022b2690425
conman/cms/tests/test_urls.py
conman/cms/tests/test_urls.py
from incuna_test_utils.testcases.urls import URLTestCase from .. import views class TestCMSIndexURL(URLTestCase): """Make sure that the CMSIndex view has a URL""" def test_url(self): self.assert_url_matches_view( views.CMSIndex, '/cms/', 'cms:index', )
from unittest import mock from django.test import TestCase from incuna_test_utils.testcases.urls import URLTestCase from .. import urls, views class TestCMSIndexURL(URLTestCase): """Make sure that the CMSIndex view has a URL""" def test_url(self): self.assert_url_matches_view( views.CMSIndex, '/cms/', 'cms:index', ) class TestCMSURLs(TestCase): @mock.patch('conman.cms.urls.url') @mock.patch('conman.cms.urls.include') @mock.patch('django.apps.apps.get_app_config') def test_urls(self, get_app_config, include, url): fake_config = mock.Mock() fake_config.cms_urls = 'example.path.to.urls' fake_config.label = 'example' fake_config.managed_apps = {fake_config} get_app_config.return_value = fake_config cms_urls = list(urls.urls()) expected = [ url(r'^$', views.CMSIndex.as_view, name='index'), url(r'^example', include(fake_config.cms_urls)) ] self.assertSequenceEqual(cms_urls, expected)
Add further tests of the cms urls
Add further tests of the cms urls
Python
bsd-2-clause
meshy/django-conman,Ian-Foote/django-conman,meshy/django-conman
from incuna_test_utils.testcases.urls import URLTestCase from .. import views class TestCMSIndexURL(URLTestCase): """Make sure that the CMSIndex view has a URL""" def test_url(self): self.assert_url_matches_view( views.CMSIndex, '/cms/', 'cms:index', ) Add further tests of the cms urls
from unittest import mock from django.test import TestCase from incuna_test_utils.testcases.urls import URLTestCase from .. import urls, views class TestCMSIndexURL(URLTestCase): """Make sure that the CMSIndex view has a URL""" def test_url(self): self.assert_url_matches_view( views.CMSIndex, '/cms/', 'cms:index', ) class TestCMSURLs(TestCase): @mock.patch('conman.cms.urls.url') @mock.patch('conman.cms.urls.include') @mock.patch('django.apps.apps.get_app_config') def test_urls(self, get_app_config, include, url): fake_config = mock.Mock() fake_config.cms_urls = 'example.path.to.urls' fake_config.label = 'example' fake_config.managed_apps = {fake_config} get_app_config.return_value = fake_config cms_urls = list(urls.urls()) expected = [ url(r'^$', views.CMSIndex.as_view, name='index'), url(r'^example', include(fake_config.cms_urls)) ] self.assertSequenceEqual(cms_urls, expected)
<commit_before>from incuna_test_utils.testcases.urls import URLTestCase from .. import views class TestCMSIndexURL(URLTestCase): """Make sure that the CMSIndex view has a URL""" def test_url(self): self.assert_url_matches_view( views.CMSIndex, '/cms/', 'cms:index', ) <commit_msg>Add further tests of the cms urls<commit_after>
from unittest import mock from django.test import TestCase from incuna_test_utils.testcases.urls import URLTestCase from .. import urls, views class TestCMSIndexURL(URLTestCase): """Make sure that the CMSIndex view has a URL""" def test_url(self): self.assert_url_matches_view( views.CMSIndex, '/cms/', 'cms:index', ) class TestCMSURLs(TestCase): @mock.patch('conman.cms.urls.url') @mock.patch('conman.cms.urls.include') @mock.patch('django.apps.apps.get_app_config') def test_urls(self, get_app_config, include, url): fake_config = mock.Mock() fake_config.cms_urls = 'example.path.to.urls' fake_config.label = 'example' fake_config.managed_apps = {fake_config} get_app_config.return_value = fake_config cms_urls = list(urls.urls()) expected = [ url(r'^$', views.CMSIndex.as_view, name='index'), url(r'^example', include(fake_config.cms_urls)) ] self.assertSequenceEqual(cms_urls, expected)
from incuna_test_utils.testcases.urls import URLTestCase from .. import views class TestCMSIndexURL(URLTestCase): """Make sure that the CMSIndex view has a URL""" def test_url(self): self.assert_url_matches_view( views.CMSIndex, '/cms/', 'cms:index', ) Add further tests of the cms urlsfrom unittest import mock from django.test import TestCase from incuna_test_utils.testcases.urls import URLTestCase from .. import urls, views class TestCMSIndexURL(URLTestCase): """Make sure that the CMSIndex view has a URL""" def test_url(self): self.assert_url_matches_view( views.CMSIndex, '/cms/', 'cms:index', ) class TestCMSURLs(TestCase): @mock.patch('conman.cms.urls.url') @mock.patch('conman.cms.urls.include') @mock.patch('django.apps.apps.get_app_config') def test_urls(self, get_app_config, include, url): fake_config = mock.Mock() fake_config.cms_urls = 'example.path.to.urls' fake_config.label = 'example' fake_config.managed_apps = {fake_config} get_app_config.return_value = fake_config cms_urls = list(urls.urls()) expected = [ url(r'^$', views.CMSIndex.as_view, name='index'), url(r'^example', include(fake_config.cms_urls)) ] self.assertSequenceEqual(cms_urls, expected)
<commit_before>from incuna_test_utils.testcases.urls import URLTestCase from .. import views class TestCMSIndexURL(URLTestCase): """Make sure that the CMSIndex view has a URL""" def test_url(self): self.assert_url_matches_view( views.CMSIndex, '/cms/', 'cms:index', ) <commit_msg>Add further tests of the cms urls<commit_after>from unittest import mock from django.test import TestCase from incuna_test_utils.testcases.urls import URLTestCase from .. import urls, views class TestCMSIndexURL(URLTestCase): """Make sure that the CMSIndex view has a URL""" def test_url(self): self.assert_url_matches_view( views.CMSIndex, '/cms/', 'cms:index', ) class TestCMSURLs(TestCase): @mock.patch('conman.cms.urls.url') @mock.patch('conman.cms.urls.include') @mock.patch('django.apps.apps.get_app_config') def test_urls(self, get_app_config, include, url): fake_config = mock.Mock() fake_config.cms_urls = 'example.path.to.urls' fake_config.label = 'example' fake_config.managed_apps = {fake_config} get_app_config.return_value = fake_config cms_urls = list(urls.urls()) expected = [ url(r'^$', views.CMSIndex.as_view, name='index'), url(r'^example', include(fake_config.cms_urls)) ] self.assertSequenceEqual(cms_urls, expected)
748c9728b4de0d19b4e18e3c0e0763dc8d20ba37
queue_job/tests/__init__.py
queue_job/tests/__init__.py
# -*- coding: utf-8 -*- ############################################################################## # # Author: Guewen Baconnier # Copyright 2012 Camptocamp SA # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from . import test_session from . import test_event from . import test_job from . import test_queue from . import test_worker from . import test_backend from . import test_producer from . import test_connector from . import test_mapper from . import test_related_action fast_suite = [ ] checks = [ test_session, test_event, test_job, test_queue, test_worker, test_backend, test_producer, test_connector, test_mapper, test_related_action, ]
# -*- coding: utf-8 -*- ############################################################################## # # Author: Guewen Baconnier # Copyright 2012 Camptocamp SA # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from . import test_session from . import test_event from . import test_job from . import test_queue from . import test_worker from . import test_backend from . import test_producer from . import test_connector from . import test_mapper from . import test_related_action
Remove deprecated fast_suite and check list for unit tests
Remove deprecated fast_suite and check list for unit tests
Python
agpl-3.0
leorochael/queue
# -*- coding: utf-8 -*- ############################################################################## # # Author: Guewen Baconnier # Copyright 2012 Camptocamp SA # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from . import test_session from . import test_event from . import test_job from . import test_queue from . import test_worker from . import test_backend from . import test_producer from . import test_connector from . import test_mapper from . import test_related_action fast_suite = [ ] checks = [ test_session, test_event, test_job, test_queue, test_worker, test_backend, test_producer, test_connector, test_mapper, test_related_action, ] Remove deprecated fast_suite and check list for unit tests
# -*- coding: utf-8 -*- ############################################################################## # # Author: Guewen Baconnier # Copyright 2012 Camptocamp SA # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from . import test_session from . import test_event from . import test_job from . import test_queue from . import test_worker from . import test_backend from . import test_producer from . import test_connector from . import test_mapper from . import test_related_action
<commit_before># -*- coding: utf-8 -*- ############################################################################## # # Author: Guewen Baconnier # Copyright 2012 Camptocamp SA # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from . import test_session from . import test_event from . import test_job from . import test_queue from . import test_worker from . import test_backend from . import test_producer from . import test_connector from . import test_mapper from . import test_related_action fast_suite = [ ] checks = [ test_session, test_event, test_job, test_queue, test_worker, test_backend, test_producer, test_connector, test_mapper, test_related_action, ] <commit_msg>Remove deprecated fast_suite and check list for unit tests<commit_after>
# -*- coding: utf-8 -*- ############################################################################## # # Author: Guewen Baconnier # Copyright 2012 Camptocamp SA # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from . import test_session from . import test_event from . import test_job from . import test_queue from . import test_worker from . import test_backend from . import test_producer from . import test_connector from . import test_mapper from . import test_related_action
# -*- coding: utf-8 -*- ############################################################################## # # Author: Guewen Baconnier # Copyright 2012 Camptocamp SA # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from . import test_session from . import test_event from . import test_job from . import test_queue from . import test_worker from . import test_backend from . import test_producer from . import test_connector from . import test_mapper from . import test_related_action fast_suite = [ ] checks = [ test_session, test_event, test_job, test_queue, test_worker, test_backend, test_producer, test_connector, test_mapper, test_related_action, ] Remove deprecated fast_suite and check list for unit tests# -*- coding: utf-8 -*- ############################################################################## # # Author: Guewen Baconnier # Copyright 2012 Camptocamp SA # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from . import test_session from . import test_event from . import test_job from . import test_queue from . import test_worker from . import test_backend from . import test_producer from . import test_connector from . import test_mapper from . import test_related_action
<commit_before># -*- coding: utf-8 -*- ############################################################################## # # Author: Guewen Baconnier # Copyright 2012 Camptocamp SA # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from . import test_session from . import test_event from . import test_job from . import test_queue from . import test_worker from . import test_backend from . import test_producer from . import test_connector from . import test_mapper from . import test_related_action fast_suite = [ ] checks = [ test_session, test_event, test_job, test_queue, test_worker, test_backend, test_producer, test_connector, test_mapper, test_related_action, ] <commit_msg>Remove deprecated fast_suite and check list for unit tests<commit_after># -*- coding: utf-8 -*- ############################################################################## # # Author: Guewen Baconnier # Copyright 2012 Camptocamp SA # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from . import test_session from . import test_event from . import test_job from . import test_queue from . import test_worker from . import test_backend from . import test_producer from . import test_connector from . import test_mapper from . import test_related_action
3986476071b1c8d2808c02a6885643c509e64456
cymbology/identifiers/cusip.py
cymbology/identifiers/cusip.py
from itertools import chain import string from cymbology.alphanum import CHAR_MAP from cymbology.codes import CINS_CODES from cymbology.exceptions import CountryCodeError from cymbology.luhn import _luhnify from cymbology.validation import SecurityId CUSIP_FIRST_CHAR = set(chain((c[0] for c in CINS_CODES), string.digits)) class Cusip(SecurityId): """CUSIP identification number. References ---------- https://www.cusip.com/pdf/CUSIP_Intro_03.14.11.pdf """ MAX_LEN = 9 def _calculate_checksum(self, sid_): return _luhnify((CHAR_MAP[c] for c in reversed(sid_))) def _additional_checks(self, sid_): if sid_[0] not in CUSIP_FIRST_CHAR: raise CountryCodeError def cusip_from_isin(isin): """Convert ISIN security identifiers to CUSIP identifiers.""" if not isin.startswith('US'): raise CountryCodeError return Cusip().validate(isin[2:-1])
from itertools import chain import string from cymbology.alphanum import CHAR_MAP from cymbology.codes import CINS_CODES from cymbology.exceptions import CountryCodeError from cymbology.luhn import _luhnify from cymbology.validation import SecurityId CUSIP_FIRST_CHAR = frozenset(chain((c[0] for c in CINS_CODES), string.digits)) class Cusip(SecurityId): """CUSIP identification number. References ---------- https://www.cusip.com/pdf/CUSIP_Intro_03.14.11.pdf """ MAX_LEN = 9 def _calculate_checksum(self, sid_): return _luhnify((CHAR_MAP[c] for c in reversed(sid_))) def _additional_checks(self, sid_): if sid_[0] not in CUSIP_FIRST_CHAR: raise CountryCodeError def cusip_from_isin(isin): """Convert ISIN security identifiers to CUSIP identifiers.""" if not isin.startswith('US'): raise CountryCodeError return Cusip().validate(isin[2:-1])
Use a frozen set for constant.
Use a frozen set for constant.
Python
bsd-2-clause
pmart123/cymbology,pmart123/security_id
from itertools import chain import string from cymbology.alphanum import CHAR_MAP from cymbology.codes import CINS_CODES from cymbology.exceptions import CountryCodeError from cymbology.luhn import _luhnify from cymbology.validation import SecurityId CUSIP_FIRST_CHAR = set(chain((c[0] for c in CINS_CODES), string.digits)) class Cusip(SecurityId): """CUSIP identification number. References ---------- https://www.cusip.com/pdf/CUSIP_Intro_03.14.11.pdf """ MAX_LEN = 9 def _calculate_checksum(self, sid_): return _luhnify((CHAR_MAP[c] for c in reversed(sid_))) def _additional_checks(self, sid_): if sid_[0] not in CUSIP_FIRST_CHAR: raise CountryCodeError def cusip_from_isin(isin): """Convert ISIN security identifiers to CUSIP identifiers.""" if not isin.startswith('US'): raise CountryCodeError return Cusip().validate(isin[2:-1]) Use a frozen set for constant.
from itertools import chain import string from cymbology.alphanum import CHAR_MAP from cymbology.codes import CINS_CODES from cymbology.exceptions import CountryCodeError from cymbology.luhn import _luhnify from cymbology.validation import SecurityId CUSIP_FIRST_CHAR = frozenset(chain((c[0] for c in CINS_CODES), string.digits)) class Cusip(SecurityId): """CUSIP identification number. References ---------- https://www.cusip.com/pdf/CUSIP_Intro_03.14.11.pdf """ MAX_LEN = 9 def _calculate_checksum(self, sid_): return _luhnify((CHAR_MAP[c] for c in reversed(sid_))) def _additional_checks(self, sid_): if sid_[0] not in CUSIP_FIRST_CHAR: raise CountryCodeError def cusip_from_isin(isin): """Convert ISIN security identifiers to CUSIP identifiers.""" if not isin.startswith('US'): raise CountryCodeError return Cusip().validate(isin[2:-1])
<commit_before>from itertools import chain import string from cymbology.alphanum import CHAR_MAP from cymbology.codes import CINS_CODES from cymbology.exceptions import CountryCodeError from cymbology.luhn import _luhnify from cymbology.validation import SecurityId CUSIP_FIRST_CHAR = set(chain((c[0] for c in CINS_CODES), string.digits)) class Cusip(SecurityId): """CUSIP identification number. References ---------- https://www.cusip.com/pdf/CUSIP_Intro_03.14.11.pdf """ MAX_LEN = 9 def _calculate_checksum(self, sid_): return _luhnify((CHAR_MAP[c] for c in reversed(sid_))) def _additional_checks(self, sid_): if sid_[0] not in CUSIP_FIRST_CHAR: raise CountryCodeError def cusip_from_isin(isin): """Convert ISIN security identifiers to CUSIP identifiers.""" if not isin.startswith('US'): raise CountryCodeError return Cusip().validate(isin[2:-1]) <commit_msg>Use a frozen set for constant.<commit_after>
from itertools import chain import string from cymbology.alphanum import CHAR_MAP from cymbology.codes import CINS_CODES from cymbology.exceptions import CountryCodeError from cymbology.luhn import _luhnify from cymbology.validation import SecurityId CUSIP_FIRST_CHAR = frozenset(chain((c[0] for c in CINS_CODES), string.digits)) class Cusip(SecurityId): """CUSIP identification number. References ---------- https://www.cusip.com/pdf/CUSIP_Intro_03.14.11.pdf """ MAX_LEN = 9 def _calculate_checksum(self, sid_): return _luhnify((CHAR_MAP[c] for c in reversed(sid_))) def _additional_checks(self, sid_): if sid_[0] not in CUSIP_FIRST_CHAR: raise CountryCodeError def cusip_from_isin(isin): """Convert ISIN security identifiers to CUSIP identifiers.""" if not isin.startswith('US'): raise CountryCodeError return Cusip().validate(isin[2:-1])
from itertools import chain import string from cymbology.alphanum import CHAR_MAP from cymbology.codes import CINS_CODES from cymbology.exceptions import CountryCodeError from cymbology.luhn import _luhnify from cymbology.validation import SecurityId CUSIP_FIRST_CHAR = set(chain((c[0] for c in CINS_CODES), string.digits)) class Cusip(SecurityId): """CUSIP identification number. References ---------- https://www.cusip.com/pdf/CUSIP_Intro_03.14.11.pdf """ MAX_LEN = 9 def _calculate_checksum(self, sid_): return _luhnify((CHAR_MAP[c] for c in reversed(sid_))) def _additional_checks(self, sid_): if sid_[0] not in CUSIP_FIRST_CHAR: raise CountryCodeError def cusip_from_isin(isin): """Convert ISIN security identifiers to CUSIP identifiers.""" if not isin.startswith('US'): raise CountryCodeError return Cusip().validate(isin[2:-1]) Use a frozen set for constant.from itertools import chain import string from cymbology.alphanum import CHAR_MAP from cymbology.codes import CINS_CODES from cymbology.exceptions import CountryCodeError from cymbology.luhn import _luhnify from cymbology.validation import SecurityId CUSIP_FIRST_CHAR = frozenset(chain((c[0] for c in CINS_CODES), string.digits)) class Cusip(SecurityId): """CUSIP identification number. References ---------- https://www.cusip.com/pdf/CUSIP_Intro_03.14.11.pdf """ MAX_LEN = 9 def _calculate_checksum(self, sid_): return _luhnify((CHAR_MAP[c] for c in reversed(sid_))) def _additional_checks(self, sid_): if sid_[0] not in CUSIP_FIRST_CHAR: raise CountryCodeError def cusip_from_isin(isin): """Convert ISIN security identifiers to CUSIP identifiers.""" if not isin.startswith('US'): raise CountryCodeError return Cusip().validate(isin[2:-1])
<commit_before>from itertools import chain import string from cymbology.alphanum import CHAR_MAP from cymbology.codes import CINS_CODES from cymbology.exceptions import CountryCodeError from cymbology.luhn import _luhnify from cymbology.validation import SecurityId CUSIP_FIRST_CHAR = set(chain((c[0] for c in CINS_CODES), string.digits)) class Cusip(SecurityId): """CUSIP identification number. References ---------- https://www.cusip.com/pdf/CUSIP_Intro_03.14.11.pdf """ MAX_LEN = 9 def _calculate_checksum(self, sid_): return _luhnify((CHAR_MAP[c] for c in reversed(sid_))) def _additional_checks(self, sid_): if sid_[0] not in CUSIP_FIRST_CHAR: raise CountryCodeError def cusip_from_isin(isin): """Convert ISIN security identifiers to CUSIP identifiers.""" if not isin.startswith('US'): raise CountryCodeError return Cusip().validate(isin[2:-1]) <commit_msg>Use a frozen set for constant.<commit_after>from itertools import chain import string from cymbology.alphanum import CHAR_MAP from cymbology.codes import CINS_CODES from cymbology.exceptions import CountryCodeError from cymbology.luhn import _luhnify from cymbology.validation import SecurityId CUSIP_FIRST_CHAR = frozenset(chain((c[0] for c in CINS_CODES), string.digits)) class Cusip(SecurityId): """CUSIP identification number. References ---------- https://www.cusip.com/pdf/CUSIP_Intro_03.14.11.pdf """ MAX_LEN = 9 def _calculate_checksum(self, sid_): return _luhnify((CHAR_MAP[c] for c in reversed(sid_))) def _additional_checks(self, sid_): if sid_[0] not in CUSIP_FIRST_CHAR: raise CountryCodeError def cusip_from_isin(isin): """Convert ISIN security identifiers to CUSIP identifiers.""" if not isin.startswith('US'): raise CountryCodeError return Cusip().validate(isin[2:-1])
23fa1c55ec9fcbc595260be1039a4b8481cb4f13
api/comments/views.py
api/comments/views.py
from rest_framework import generics from api.comments.serializers import CommentSerializer, CommentDetailSerializer from website.project.model import Comment from api.base.utils import get_object_or_error class CommentMixin(object): """Mixin with convenience methods for retrieving the current comment based on the current URL. By default, fetches the comment based on the comment_id kwarg. """ serializer_class = CommentSerializer comment_lookup_url_kwarg = 'comment_id' def get_comment(self, check_permissions=True): comment = get_object_or_error(Comment, self.kwargs[self.comment_lookup_url_kwarg]) if check_permissions: # May raise a permission denied self.check_object_permissions(self.request, comment) return comment class CommentDetail(generics.RetrieveUpdateAPIView, CommentMixin): """Details about a specific comment. """ # permission classes # required scopes serializer_class = CommentDetailSerializer # overrides RetrieveAPIView def get_object(self): return self.get_comment()
from modularodm import Q from modularodm.exceptions import NoResultsFound from rest_framework import generics from rest_framework.exceptions import NotFound from api.comments.serializers import CommentSerializer, CommentDetailSerializer from website.project.model import Comment class CommentMixin(object): """Mixin with convenience methods for retrieving the current comment based on the current URL. By default, fetches the comment based on the comment_id kwarg. """ serializer_class = CommentSerializer comment_lookup_url_kwarg = 'comment_id' def get_comment(self, check_permissions=True): pk = self.kwargs[self.comment_lookup_url_kwarg] query = Q('_id', 'eq', pk) try: comment = Comment.find_one(query) except NoResultsFound: raise NotFound if check_permissions: # May raise a permission denied self.check_object_permissions(self.request, comment) return comment class CommentDetail(generics.RetrieveUpdateAPIView, CommentMixin): """Details about a specific comment. """ # permission classes # required scopes serializer_class = CommentDetailSerializer # overrides RetrieveAPIView def get_object(self): return self.get_comment()
Return deleted comments instead of throwing error
Return deleted comments instead of throwing error
Python
apache-2.0
kch8qx/osf.io,CenterForOpenScience/osf.io,Johnetordoff/osf.io,kch8qx/osf.io,ZobairAlijan/osf.io,acshi/osf.io,DanielSBrown/osf.io,GageGaskins/osf.io,icereval/osf.io,wearpants/osf.io,mfraezz/osf.io,acshi/osf.io,jnayak1/osf.io,crcresearch/osf.io,danielneis/osf.io,brandonPurvis/osf.io,samanehsan/osf.io,samanehsan/osf.io,SSJohns/osf.io,samanehsan/osf.io,hmoco/osf.io,aaxelb/osf.io,zachjanicki/osf.io,monikagrabowska/osf.io,baylee-d/osf.io,rdhyee/osf.io,HalcyonChimera/osf.io,caseyrollins/osf.io,brandonPurvis/osf.io,ticklemepierce/osf.io,leb2dg/osf.io,brandonPurvis/osf.io,TomBaxter/osf.io,kch8qx/osf.io,monikagrabowska/osf.io,CenterForOpenScience/osf.io,baylee-d/osf.io,cwisecarver/osf.io,KAsante95/osf.io,felliott/osf.io,erinspace/osf.io,Nesiehr/osf.io,alexschiller/osf.io,baylee-d/osf.io,brianjgeiger/osf.io,abought/osf.io,Johnetordoff/osf.io,aaxelb/osf.io,samanehsan/osf.io,HalcyonChimera/osf.io,jnayak1/osf.io,emetsger/osf.io,rdhyee/osf.io,cslzchen/osf.io,ZobairAlijan/osf.io,abought/osf.io,alexschiller/osf.io,sloria/osf.io,doublebits/osf.io,KAsante95/osf.io,brianjgeiger/osf.io,jnayak1/osf.io,samchrisinger/osf.io,RomanZWang/osf.io,mattclark/osf.io,mluo613/osf.io,GageGaskins/osf.io,DanielSBrown/osf.io,leb2dg/osf.io,binoculars/osf.io,Nesiehr/osf.io,hmoco/osf.io,TomHeatwole/osf.io,doublebits/osf.io,caneruguz/osf.io,KAsante95/osf.io,mluo613/osf.io,kwierman/osf.io,crcresearch/osf.io,abought/osf.io,caseyrollins/osf.io,saradbowman/osf.io,saradbowman/osf.io,chrisseto/osf.io,danielneis/osf.io,Johnetordoff/osf.io,brianjgeiger/osf.io,SSJohns/osf.io,caneruguz/osf.io,mluo613/osf.io,mluo613/osf.io,amyshi188/osf.io,adlius/osf.io,RomanZWang/osf.io,DanielSBrown/osf.io,monikagrabowska/osf.io,TomBaxter/osf.io,pattisdr/osf.io,Ghalko/osf.io,HalcyonChimera/osf.io,zamattiac/osf.io,mfraezz/osf.io,Nesiehr/osf.io,SSJohns/osf.io,caneruguz/osf.io,hmoco/osf.io,emetsger/osf.io,brianjgeiger/osf.io,zachjanicki/osf.io,abought/osf.io,ticklemepierce/osf.io,brandonPurvis/osf.io,aaxelb/osf.io,kch8qx/osf.io,monikagrabowska/osf.io,asanfilippo7/osf.io,ticklemepierce/osf.io,caseyrygt/osf.io,hmoco/osf.io,monikagrabowska/osf.io,cslzchen/osf.io,caseyrollins/osf.io,wearpants/osf.io,leb2dg/osf.io,mluke93/osf.io,amyshi188/osf.io,zamattiac/osf.io,mfraezz/osf.io,mattclark/osf.io,RomanZWang/osf.io,wearpants/osf.io,samchrisinger/osf.io,TomHeatwole/osf.io,icereval/osf.io,amyshi188/osf.io,mattclark/osf.io,chennan47/osf.io,billyhunt/osf.io,wearpants/osf.io,alexschiller/osf.io,cslzchen/osf.io,KAsante95/osf.io,leb2dg/osf.io,billyhunt/osf.io,felliott/osf.io,erinspace/osf.io,cwisecarver/osf.io,CenterForOpenScience/osf.io,ZobairAlijan/osf.io,chennan47/osf.io,aaxelb/osf.io,ZobairAlijan/osf.io,cwisecarver/osf.io,acshi/osf.io,binoculars/osf.io,kch8qx/osf.io,danielneis/osf.io,acshi/osf.io,erinspace/osf.io,alexschiller/osf.io,cslzchen/osf.io,adlius/osf.io,billyhunt/osf.io,laurenrevere/osf.io,GageGaskins/osf.io,mfraezz/osf.io,samchrisinger/osf.io,laurenrevere/osf.io,crcresearch/osf.io,kwierman/osf.io,pattisdr/osf.io,asanfilippo7/osf.io,sloria/osf.io,samchrisinger/osf.io,doublebits/osf.io,asanfilippo7/osf.io,SSJohns/osf.io,mluo613/osf.io,brandonPurvis/osf.io,mluke93/osf.io,mluke93/osf.io,doublebits/osf.io,emetsger/osf.io,Ghalko/osf.io,caseyrygt/osf.io,chrisseto/osf.io,chennan47/osf.io,caseyrygt/osf.io,doublebits/osf.io,Ghalko/osf.io,zamattiac/osf.io,sloria/osf.io,Johnetordoff/osf.io,KAsante95/osf.io,pattisdr/osf.io,amyshi188/osf.io,asanfilippo7/osf.io,laurenrevere/osf.io,alexschiller/osf.io,HalcyonChimera/osf.io,chrisseto/osf.io,RomanZWang/osf.io,TomHeatwole/osf.io,GageGaskins/osf.io,GageGaskins/osf.io,Nesiehr/osf.io,RomanZWang/osf.io,billyhunt/osf.io,felliott/osf.io,rdhyee/osf.io,Ghalko/osf.io,ticklemepierce/osf.io,caseyrygt/osf.io,CenterForOpenScience/osf.io,DanielSBrown/osf.io,cwisecarver/osf.io,mluke93/osf.io,adlius/osf.io,danielneis/osf.io,billyhunt/osf.io,caneruguz/osf.io,kwierman/osf.io,zachjanicki/osf.io,chrisseto/osf.io,icereval/osf.io,felliott/osf.io,kwierman/osf.io,zachjanicki/osf.io,TomHeatwole/osf.io,zamattiac/osf.io,binoculars/osf.io,acshi/osf.io,emetsger/osf.io,rdhyee/osf.io,adlius/osf.io,TomBaxter/osf.io,jnayak1/osf.io
from rest_framework import generics from api.comments.serializers import CommentSerializer, CommentDetailSerializer from website.project.model import Comment from api.base.utils import get_object_or_error class CommentMixin(object): """Mixin with convenience methods for retrieving the current comment based on the current URL. By default, fetches the comment based on the comment_id kwarg. """ serializer_class = CommentSerializer comment_lookup_url_kwarg = 'comment_id' def get_comment(self, check_permissions=True): comment = get_object_or_error(Comment, self.kwargs[self.comment_lookup_url_kwarg]) if check_permissions: # May raise a permission denied self.check_object_permissions(self.request, comment) return comment class CommentDetail(generics.RetrieveUpdateAPIView, CommentMixin): """Details about a specific comment. """ # permission classes # required scopes serializer_class = CommentDetailSerializer # overrides RetrieveAPIView def get_object(self): return self.get_comment() Return deleted comments instead of throwing error
from modularodm import Q from modularodm.exceptions import NoResultsFound from rest_framework import generics from rest_framework.exceptions import NotFound from api.comments.serializers import CommentSerializer, CommentDetailSerializer from website.project.model import Comment class CommentMixin(object): """Mixin with convenience methods for retrieving the current comment based on the current URL. By default, fetches the comment based on the comment_id kwarg. """ serializer_class = CommentSerializer comment_lookup_url_kwarg = 'comment_id' def get_comment(self, check_permissions=True): pk = self.kwargs[self.comment_lookup_url_kwarg] query = Q('_id', 'eq', pk) try: comment = Comment.find_one(query) except NoResultsFound: raise NotFound if check_permissions: # May raise a permission denied self.check_object_permissions(self.request, comment) return comment class CommentDetail(generics.RetrieveUpdateAPIView, CommentMixin): """Details about a specific comment. """ # permission classes # required scopes serializer_class = CommentDetailSerializer # overrides RetrieveAPIView def get_object(self): return self.get_comment()
<commit_before>from rest_framework import generics from api.comments.serializers import CommentSerializer, CommentDetailSerializer from website.project.model import Comment from api.base.utils import get_object_or_error class CommentMixin(object): """Mixin with convenience methods for retrieving the current comment based on the current URL. By default, fetches the comment based on the comment_id kwarg. """ serializer_class = CommentSerializer comment_lookup_url_kwarg = 'comment_id' def get_comment(self, check_permissions=True): comment = get_object_or_error(Comment, self.kwargs[self.comment_lookup_url_kwarg]) if check_permissions: # May raise a permission denied self.check_object_permissions(self.request, comment) return comment class CommentDetail(generics.RetrieveUpdateAPIView, CommentMixin): """Details about a specific comment. """ # permission classes # required scopes serializer_class = CommentDetailSerializer # overrides RetrieveAPIView def get_object(self): return self.get_comment() <commit_msg>Return deleted comments instead of throwing error<commit_after>
from modularodm import Q from modularodm.exceptions import NoResultsFound from rest_framework import generics from rest_framework.exceptions import NotFound from api.comments.serializers import CommentSerializer, CommentDetailSerializer from website.project.model import Comment class CommentMixin(object): """Mixin with convenience methods for retrieving the current comment based on the current URL. By default, fetches the comment based on the comment_id kwarg. """ serializer_class = CommentSerializer comment_lookup_url_kwarg = 'comment_id' def get_comment(self, check_permissions=True): pk = self.kwargs[self.comment_lookup_url_kwarg] query = Q('_id', 'eq', pk) try: comment = Comment.find_one(query) except NoResultsFound: raise NotFound if check_permissions: # May raise a permission denied self.check_object_permissions(self.request, comment) return comment class CommentDetail(generics.RetrieveUpdateAPIView, CommentMixin): """Details about a specific comment. """ # permission classes # required scopes serializer_class = CommentDetailSerializer # overrides RetrieveAPIView def get_object(self): return self.get_comment()
from rest_framework import generics from api.comments.serializers import CommentSerializer, CommentDetailSerializer from website.project.model import Comment from api.base.utils import get_object_or_error class CommentMixin(object): """Mixin with convenience methods for retrieving the current comment based on the current URL. By default, fetches the comment based on the comment_id kwarg. """ serializer_class = CommentSerializer comment_lookup_url_kwarg = 'comment_id' def get_comment(self, check_permissions=True): comment = get_object_or_error(Comment, self.kwargs[self.comment_lookup_url_kwarg]) if check_permissions: # May raise a permission denied self.check_object_permissions(self.request, comment) return comment class CommentDetail(generics.RetrieveUpdateAPIView, CommentMixin): """Details about a specific comment. """ # permission classes # required scopes serializer_class = CommentDetailSerializer # overrides RetrieveAPIView def get_object(self): return self.get_comment() Return deleted comments instead of throwing errorfrom modularodm import Q from modularodm.exceptions import NoResultsFound from rest_framework import generics from rest_framework.exceptions import NotFound from api.comments.serializers import CommentSerializer, CommentDetailSerializer from website.project.model import Comment class CommentMixin(object): """Mixin with convenience methods for retrieving the current comment based on the current URL. By default, fetches the comment based on the comment_id kwarg. """ serializer_class = CommentSerializer comment_lookup_url_kwarg = 'comment_id' def get_comment(self, check_permissions=True): pk = self.kwargs[self.comment_lookup_url_kwarg] query = Q('_id', 'eq', pk) try: comment = Comment.find_one(query) except NoResultsFound: raise NotFound if check_permissions: # May raise a permission denied self.check_object_permissions(self.request, comment) return comment class CommentDetail(generics.RetrieveUpdateAPIView, CommentMixin): """Details about a specific comment. """ # permission classes # required scopes serializer_class = CommentDetailSerializer # overrides RetrieveAPIView def get_object(self): return self.get_comment()
<commit_before>from rest_framework import generics from api.comments.serializers import CommentSerializer, CommentDetailSerializer from website.project.model import Comment from api.base.utils import get_object_or_error class CommentMixin(object): """Mixin with convenience methods for retrieving the current comment based on the current URL. By default, fetches the comment based on the comment_id kwarg. """ serializer_class = CommentSerializer comment_lookup_url_kwarg = 'comment_id' def get_comment(self, check_permissions=True): comment = get_object_or_error(Comment, self.kwargs[self.comment_lookup_url_kwarg]) if check_permissions: # May raise a permission denied self.check_object_permissions(self.request, comment) return comment class CommentDetail(generics.RetrieveUpdateAPIView, CommentMixin): """Details about a specific comment. """ # permission classes # required scopes serializer_class = CommentDetailSerializer # overrides RetrieveAPIView def get_object(self): return self.get_comment() <commit_msg>Return deleted comments instead of throwing error<commit_after>from modularodm import Q from modularodm.exceptions import NoResultsFound from rest_framework import generics from rest_framework.exceptions import NotFound from api.comments.serializers import CommentSerializer, CommentDetailSerializer from website.project.model import Comment class CommentMixin(object): """Mixin with convenience methods for retrieving the current comment based on the current URL. By default, fetches the comment based on the comment_id kwarg. """ serializer_class = CommentSerializer comment_lookup_url_kwarg = 'comment_id' def get_comment(self, check_permissions=True): pk = self.kwargs[self.comment_lookup_url_kwarg] query = Q('_id', 'eq', pk) try: comment = Comment.find_one(query) except NoResultsFound: raise NotFound if check_permissions: # May raise a permission denied self.check_object_permissions(self.request, comment) return comment class CommentDetail(generics.RetrieveUpdateAPIView, CommentMixin): """Details about a specific comment. """ # permission classes # required scopes serializer_class = CommentDetailSerializer # overrides RetrieveAPIView def get_object(self): return self.get_comment()
f4b35615f772f695e5f87e11ecec7a07e751425d
bot/game/score.py
bot/game/score.py
import telegram from game.api import auth MAX_SCORE = 999999 class ScoreUpdater: def __init(self, bot: telegram.Bot): self.bot = bot def set_score(self, data, score): data = auth.decode(data) if data and score < MAX_SCORE: self._do_set_score(data["u"], data["i"], score) def _do_set_score(self, user_id, inline_message_id, score): self.bot.setGameScore(user_id, score, inline_message_id=inline_message_id)
import telegram from game.api import auth MAX_SCORE = 999999 class ScoreUpdater: def __init__(self, bot: telegram.Bot): self.bot = bot def set_score(self, data, score): data = auth.decode(data) if data and score < MAX_SCORE: self._do_set_score(data["u"], data["i"], score) def _do_set_score(self, user_id, inline_message_id, score): self.bot.setGameScore(user_id, score, inline_message_id=inline_message_id)
Fix missing trailing __ in init function
Fix missing trailing __ in init function
Python
apache-2.0
alvarogzp/telegram-games,alvarogzp/telegram-games,alvarogzp/telegram-games,alvarogzp/telegram-games
import telegram from game.api import auth MAX_SCORE = 999999 class ScoreUpdater: def __init(self, bot: telegram.Bot): self.bot = bot def set_score(self, data, score): data = auth.decode(data) if data and score < MAX_SCORE: self._do_set_score(data["u"], data["i"], score) def _do_set_score(self, user_id, inline_message_id, score): self.bot.setGameScore(user_id, score, inline_message_id=inline_message_id) Fix missing trailing __ in init function
import telegram from game.api import auth MAX_SCORE = 999999 class ScoreUpdater: def __init__(self, bot: telegram.Bot): self.bot = bot def set_score(self, data, score): data = auth.decode(data) if data and score < MAX_SCORE: self._do_set_score(data["u"], data["i"], score) def _do_set_score(self, user_id, inline_message_id, score): self.bot.setGameScore(user_id, score, inline_message_id=inline_message_id)
<commit_before>import telegram from game.api import auth MAX_SCORE = 999999 class ScoreUpdater: def __init(self, bot: telegram.Bot): self.bot = bot def set_score(self, data, score): data = auth.decode(data) if data and score < MAX_SCORE: self._do_set_score(data["u"], data["i"], score) def _do_set_score(self, user_id, inline_message_id, score): self.bot.setGameScore(user_id, score, inline_message_id=inline_message_id) <commit_msg>Fix missing trailing __ in init function<commit_after>
import telegram from game.api import auth MAX_SCORE = 999999 class ScoreUpdater: def __init__(self, bot: telegram.Bot): self.bot = bot def set_score(self, data, score): data = auth.decode(data) if data and score < MAX_SCORE: self._do_set_score(data["u"], data["i"], score) def _do_set_score(self, user_id, inline_message_id, score): self.bot.setGameScore(user_id, score, inline_message_id=inline_message_id)
import telegram from game.api import auth MAX_SCORE = 999999 class ScoreUpdater: def __init(self, bot: telegram.Bot): self.bot = bot def set_score(self, data, score): data = auth.decode(data) if data and score < MAX_SCORE: self._do_set_score(data["u"], data["i"], score) def _do_set_score(self, user_id, inline_message_id, score): self.bot.setGameScore(user_id, score, inline_message_id=inline_message_id) Fix missing trailing __ in init functionimport telegram from game.api import auth MAX_SCORE = 999999 class ScoreUpdater: def __init__(self, bot: telegram.Bot): self.bot = bot def set_score(self, data, score): data = auth.decode(data) if data and score < MAX_SCORE: self._do_set_score(data["u"], data["i"], score) def _do_set_score(self, user_id, inline_message_id, score): self.bot.setGameScore(user_id, score, inline_message_id=inline_message_id)
<commit_before>import telegram from game.api import auth MAX_SCORE = 999999 class ScoreUpdater: def __init(self, bot: telegram.Bot): self.bot = bot def set_score(self, data, score): data = auth.decode(data) if data and score < MAX_SCORE: self._do_set_score(data["u"], data["i"], score) def _do_set_score(self, user_id, inline_message_id, score): self.bot.setGameScore(user_id, score, inline_message_id=inline_message_id) <commit_msg>Fix missing trailing __ in init function<commit_after>import telegram from game.api import auth MAX_SCORE = 999999 class ScoreUpdater: def __init__(self, bot: telegram.Bot): self.bot = bot def set_score(self, data, score): data = auth.decode(data) if data and score < MAX_SCORE: self._do_set_score(data["u"], data["i"], score) def _do_set_score(self, user_id, inline_message_id, score): self.bot.setGameScore(user_id, score, inline_message_id=inline_message_id)
10aab1c427a82b4cfef6b07ae1103260e14ca322
geotrek/feedback/admin.py
geotrek/feedback/admin.py
from django.conf import settings from django.contrib import admin from geotrek.feedback import models as feedback_models if 'modeltranslation' in settings.INSTALLED_APPS: from modeltranslation.admin import TabbedTranslationAdmin else: from django.contrib.admin import ModelAdmin as TabbedTranslationAdmin class WorkflowManagerAdmin(admin.ModelAdmin): def has_add_permission(self, request): # There can be only one manager perms = super().has_add_permission(request) if perms and feedback_models.WorkflowManager.objects.exists(): perms = False return perms admin.site.register(feedback_models.ReportCategory, TabbedTranslationAdmin) admin.site.register(feedback_models.ReportStatus) admin.site.register(feedback_models.ReportActivity, TabbedTranslationAdmin) admin.site.register(feedback_models.ReportProblemMagnitude, TabbedTranslationAdmin)
from django.conf import settings from django.contrib import admin from geotrek.feedback import models as feedback_models if 'modeltranslation' in settings.INSTALLED_APPS: from modeltranslation.admin import TabbedTranslationAdmin else: from django.contrib.admin import ModelAdmin as TabbedTranslationAdmin class WorkflowManagerAdmin(admin.ModelAdmin): def has_add_permission(self, request): # There can be only one manager perms = super().has_add_permission(request) if perms and feedback_models.WorkflowManager.objects.exists(): perms = False return perms admin.site.register(feedback_models.WorkflowManager, WorkflowManagerAdmin) admin.site.register(feedback_models.ReportCategory, TabbedTranslationAdmin) admin.site.register(feedback_models.ReportStatus) admin.site.register(feedback_models.ReportActivity, TabbedTranslationAdmin) admin.site.register(feedback_models.ReportProblemMagnitude, TabbedTranslationAdmin)
Fix deleted line during merge
Fix deleted line during merge
Python
bsd-2-clause
makinacorpus/Geotrek,makinacorpus/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek
from django.conf import settings from django.contrib import admin from geotrek.feedback import models as feedback_models if 'modeltranslation' in settings.INSTALLED_APPS: from modeltranslation.admin import TabbedTranslationAdmin else: from django.contrib.admin import ModelAdmin as TabbedTranslationAdmin class WorkflowManagerAdmin(admin.ModelAdmin): def has_add_permission(self, request): # There can be only one manager perms = super().has_add_permission(request) if perms and feedback_models.WorkflowManager.objects.exists(): perms = False return perms admin.site.register(feedback_models.ReportCategory, TabbedTranslationAdmin) admin.site.register(feedback_models.ReportStatus) admin.site.register(feedback_models.ReportActivity, TabbedTranslationAdmin) admin.site.register(feedback_models.ReportProblemMagnitude, TabbedTranslationAdmin) Fix deleted line during merge
from django.conf import settings from django.contrib import admin from geotrek.feedback import models as feedback_models if 'modeltranslation' in settings.INSTALLED_APPS: from modeltranslation.admin import TabbedTranslationAdmin else: from django.contrib.admin import ModelAdmin as TabbedTranslationAdmin class WorkflowManagerAdmin(admin.ModelAdmin): def has_add_permission(self, request): # There can be only one manager perms = super().has_add_permission(request) if perms and feedback_models.WorkflowManager.objects.exists(): perms = False return perms admin.site.register(feedback_models.WorkflowManager, WorkflowManagerAdmin) admin.site.register(feedback_models.ReportCategory, TabbedTranslationAdmin) admin.site.register(feedback_models.ReportStatus) admin.site.register(feedback_models.ReportActivity, TabbedTranslationAdmin) admin.site.register(feedback_models.ReportProblemMagnitude, TabbedTranslationAdmin)
<commit_before>from django.conf import settings from django.contrib import admin from geotrek.feedback import models as feedback_models if 'modeltranslation' in settings.INSTALLED_APPS: from modeltranslation.admin import TabbedTranslationAdmin else: from django.contrib.admin import ModelAdmin as TabbedTranslationAdmin class WorkflowManagerAdmin(admin.ModelAdmin): def has_add_permission(self, request): # There can be only one manager perms = super().has_add_permission(request) if perms and feedback_models.WorkflowManager.objects.exists(): perms = False return perms admin.site.register(feedback_models.ReportCategory, TabbedTranslationAdmin) admin.site.register(feedback_models.ReportStatus) admin.site.register(feedback_models.ReportActivity, TabbedTranslationAdmin) admin.site.register(feedback_models.ReportProblemMagnitude, TabbedTranslationAdmin) <commit_msg>Fix deleted line during merge<commit_after>
from django.conf import settings from django.contrib import admin from geotrek.feedback import models as feedback_models if 'modeltranslation' in settings.INSTALLED_APPS: from modeltranslation.admin import TabbedTranslationAdmin else: from django.contrib.admin import ModelAdmin as TabbedTranslationAdmin class WorkflowManagerAdmin(admin.ModelAdmin): def has_add_permission(self, request): # There can be only one manager perms = super().has_add_permission(request) if perms and feedback_models.WorkflowManager.objects.exists(): perms = False return perms admin.site.register(feedback_models.WorkflowManager, WorkflowManagerAdmin) admin.site.register(feedback_models.ReportCategory, TabbedTranslationAdmin) admin.site.register(feedback_models.ReportStatus) admin.site.register(feedback_models.ReportActivity, TabbedTranslationAdmin) admin.site.register(feedback_models.ReportProblemMagnitude, TabbedTranslationAdmin)
from django.conf import settings from django.contrib import admin from geotrek.feedback import models as feedback_models if 'modeltranslation' in settings.INSTALLED_APPS: from modeltranslation.admin import TabbedTranslationAdmin else: from django.contrib.admin import ModelAdmin as TabbedTranslationAdmin class WorkflowManagerAdmin(admin.ModelAdmin): def has_add_permission(self, request): # There can be only one manager perms = super().has_add_permission(request) if perms and feedback_models.WorkflowManager.objects.exists(): perms = False return perms admin.site.register(feedback_models.ReportCategory, TabbedTranslationAdmin) admin.site.register(feedback_models.ReportStatus) admin.site.register(feedback_models.ReportActivity, TabbedTranslationAdmin) admin.site.register(feedback_models.ReportProblemMagnitude, TabbedTranslationAdmin) Fix deleted line during mergefrom django.conf import settings from django.contrib import admin from geotrek.feedback import models as feedback_models if 'modeltranslation' in settings.INSTALLED_APPS: from modeltranslation.admin import TabbedTranslationAdmin else: from django.contrib.admin import ModelAdmin as TabbedTranslationAdmin class WorkflowManagerAdmin(admin.ModelAdmin): def has_add_permission(self, request): # There can be only one manager perms = super().has_add_permission(request) if perms and feedback_models.WorkflowManager.objects.exists(): perms = False return perms admin.site.register(feedback_models.WorkflowManager, WorkflowManagerAdmin) admin.site.register(feedback_models.ReportCategory, TabbedTranslationAdmin) admin.site.register(feedback_models.ReportStatus) admin.site.register(feedback_models.ReportActivity, TabbedTranslationAdmin) admin.site.register(feedback_models.ReportProblemMagnitude, TabbedTranslationAdmin)
<commit_before>from django.conf import settings from django.contrib import admin from geotrek.feedback import models as feedback_models if 'modeltranslation' in settings.INSTALLED_APPS: from modeltranslation.admin import TabbedTranslationAdmin else: from django.contrib.admin import ModelAdmin as TabbedTranslationAdmin class WorkflowManagerAdmin(admin.ModelAdmin): def has_add_permission(self, request): # There can be only one manager perms = super().has_add_permission(request) if perms and feedback_models.WorkflowManager.objects.exists(): perms = False return perms admin.site.register(feedback_models.ReportCategory, TabbedTranslationAdmin) admin.site.register(feedback_models.ReportStatus) admin.site.register(feedback_models.ReportActivity, TabbedTranslationAdmin) admin.site.register(feedback_models.ReportProblemMagnitude, TabbedTranslationAdmin) <commit_msg>Fix deleted line during merge<commit_after>from django.conf import settings from django.contrib import admin from geotrek.feedback import models as feedback_models if 'modeltranslation' in settings.INSTALLED_APPS: from modeltranslation.admin import TabbedTranslationAdmin else: from django.contrib.admin import ModelAdmin as TabbedTranslationAdmin class WorkflowManagerAdmin(admin.ModelAdmin): def has_add_permission(self, request): # There can be only one manager perms = super().has_add_permission(request) if perms and feedback_models.WorkflowManager.objects.exists(): perms = False return perms admin.site.register(feedback_models.WorkflowManager, WorkflowManagerAdmin) admin.site.register(feedback_models.ReportCategory, TabbedTranslationAdmin) admin.site.register(feedback_models.ReportStatus) admin.site.register(feedback_models.ReportActivity, TabbedTranslationAdmin) admin.site.register(feedback_models.ReportProblemMagnitude, TabbedTranslationAdmin)
d7c4f0471271d104c0ff3500033e425547ca6c27
notification/context_processors.py
notification/context_processors.py
from notification.models import Notice def notification(request): if request.user.is_authenticated(): return { "notice_unseen_count": Notice.objects.unseen_count_for(request.user, on_site=True), } else: return {}
from notification.models import Notice def notification(request): if request.user.is_authenticated(): return { "notice_unseen_count": Notice.objects.unseen_count_for(request.user, on_site=True), "notifications": Notice.objects.filter(user=request.user.id) } else: return {}
Add user notifications to context processor
Add user notifications to context processor
Python
mit
affan2/django-notification,affan2/django-notification
from notification.models import Notice def notification(request): if request.user.is_authenticated(): return { "notice_unseen_count": Notice.objects.unseen_count_for(request.user, on_site=True), } else: return {}Add user notifications to context processor
from notification.models import Notice def notification(request): if request.user.is_authenticated(): return { "notice_unseen_count": Notice.objects.unseen_count_for(request.user, on_site=True), "notifications": Notice.objects.filter(user=request.user.id) } else: return {}
<commit_before>from notification.models import Notice def notification(request): if request.user.is_authenticated(): return { "notice_unseen_count": Notice.objects.unseen_count_for(request.user, on_site=True), } else: return {}<commit_msg>Add user notifications to context processor<commit_after>
from notification.models import Notice def notification(request): if request.user.is_authenticated(): return { "notice_unseen_count": Notice.objects.unseen_count_for(request.user, on_site=True), "notifications": Notice.objects.filter(user=request.user.id) } else: return {}
from notification.models import Notice def notification(request): if request.user.is_authenticated(): return { "notice_unseen_count": Notice.objects.unseen_count_for(request.user, on_site=True), } else: return {}Add user notifications to context processorfrom notification.models import Notice def notification(request): if request.user.is_authenticated(): return { "notice_unseen_count": Notice.objects.unseen_count_for(request.user, on_site=True), "notifications": Notice.objects.filter(user=request.user.id) } else: return {}
<commit_before>from notification.models import Notice def notification(request): if request.user.is_authenticated(): return { "notice_unseen_count": Notice.objects.unseen_count_for(request.user, on_site=True), } else: return {}<commit_msg>Add user notifications to context processor<commit_after>from notification.models import Notice def notification(request): if request.user.is_authenticated(): return { "notice_unseen_count": Notice.objects.unseen_count_for(request.user, on_site=True), "notifications": Notice.objects.filter(user=request.user.id) } else: return {}
7b681bfd34a24dc15b219dd355db2557914b7b49
tests/conftest.py
tests/conftest.py
import arrayfire import pytest backends = arrayfire.library.get_available_backends() # do not use opencl backend, it's kinda broken #backends = [x for x in backends if x != 'opencl'] # This will set the different backends before each test is executed @pytest.fixture(scope="function", params=backends, autouse=True) def set_backend(request): arrayfire.library.set_backend(request.param)
import arrayfire import pytest backends = arrayfire.library.get_available_backends() # do not use opencl backend, it's kinda broken #backends = [x for x in backends if x != 'opencl'] # This will set the different backends before each test is executed @pytest.fixture(scope="function", params=backends, autouse=True) def set_backend(request): arrayfire.library.set_backend(request.param, unsafe=True)
Revert previous commit due to arrayfire-python bug.
Revert previous commit due to arrayfire-python bug.
Python
bsd-2-clause
daurer/afnumpy,FilipeMaia/afnumpy
import arrayfire import pytest backends = arrayfire.library.get_available_backends() # do not use opencl backend, it's kinda broken #backends = [x for x in backends if x != 'opencl'] # This will set the different backends before each test is executed @pytest.fixture(scope="function", params=backends, autouse=True) def set_backend(request): arrayfire.library.set_backend(request.param) Revert previous commit due to arrayfire-python bug.
import arrayfire import pytest backends = arrayfire.library.get_available_backends() # do not use opencl backend, it's kinda broken #backends = [x for x in backends if x != 'opencl'] # This will set the different backends before each test is executed @pytest.fixture(scope="function", params=backends, autouse=True) def set_backend(request): arrayfire.library.set_backend(request.param, unsafe=True)
<commit_before>import arrayfire import pytest backends = arrayfire.library.get_available_backends() # do not use opencl backend, it's kinda broken #backends = [x for x in backends if x != 'opencl'] # This will set the different backends before each test is executed @pytest.fixture(scope="function", params=backends, autouse=True) def set_backend(request): arrayfire.library.set_backend(request.param) <commit_msg>Revert previous commit due to arrayfire-python bug.<commit_after>
import arrayfire import pytest backends = arrayfire.library.get_available_backends() # do not use opencl backend, it's kinda broken #backends = [x for x in backends if x != 'opencl'] # This will set the different backends before each test is executed @pytest.fixture(scope="function", params=backends, autouse=True) def set_backend(request): arrayfire.library.set_backend(request.param, unsafe=True)
import arrayfire import pytest backends = arrayfire.library.get_available_backends() # do not use opencl backend, it's kinda broken #backends = [x for x in backends if x != 'opencl'] # This will set the different backends before each test is executed @pytest.fixture(scope="function", params=backends, autouse=True) def set_backend(request): arrayfire.library.set_backend(request.param) Revert previous commit due to arrayfire-python bug.import arrayfire import pytest backends = arrayfire.library.get_available_backends() # do not use opencl backend, it's kinda broken #backends = [x for x in backends if x != 'opencl'] # This will set the different backends before each test is executed @pytest.fixture(scope="function", params=backends, autouse=True) def set_backend(request): arrayfire.library.set_backend(request.param, unsafe=True)
<commit_before>import arrayfire import pytest backends = arrayfire.library.get_available_backends() # do not use opencl backend, it's kinda broken #backends = [x for x in backends if x != 'opencl'] # This will set the different backends before each test is executed @pytest.fixture(scope="function", params=backends, autouse=True) def set_backend(request): arrayfire.library.set_backend(request.param) <commit_msg>Revert previous commit due to arrayfire-python bug.<commit_after>import arrayfire import pytest backends = arrayfire.library.get_available_backends() # do not use opencl backend, it's kinda broken #backends = [x for x in backends if x != 'opencl'] # This will set the different backends before each test is executed @pytest.fixture(scope="function", params=backends, autouse=True) def set_backend(request): arrayfire.library.set_backend(request.param, unsafe=True)
a94a8f0e5c773995da710bb8e90839c7b697db96
cobe/tokenizer.py
cobe/tokenizer.py
# Copyright (C) 2010 Peter Teichman import re class MegaHALTokenizer: def split(self, phrase): if len(phrase) == 0: return [] # add ending punctuation if it is missing if phrase[-1] not in ".!?": phrase = phrase + "." # megahal traditionally considers [a-z0-9] as word characters. # Let's see what happens if we add [_'] words = re.findall("([\w']+|[^\w']+)", phrase.upper()) return words
# Copyright (C) 2010 Peter Teichman import re class MegaHALTokenizer: def split(self, phrase): if len(phrase) == 0: return [] # add ending punctuation if it is missing if phrase[-1] not in ".!?": phrase = phrase + "." # megahal traditionally considers [a-z0-9] as word characters. # Let's see what happens if we add [_'] words = re.findall("([\w']+|[^\w']+)", phrase.upper(), re.UNICODE) return words
Use the re.UNICODE flag (i.e., Python character tables) in findall()
Use the re.UNICODE flag (i.e., Python character tables) in findall()
Python
mit
LeMagnesium/cobe,meska/cobe,wodim/cobe-ng,wodim/cobe-ng,LeMagnesium/cobe,pteichman/cobe,tiagochiavericosta/cobe,pteichman/cobe,meska/cobe,DarkMio/cobe,tiagochiavericosta/cobe,DarkMio/cobe
# Copyright (C) 2010 Peter Teichman import re class MegaHALTokenizer: def split(self, phrase): if len(phrase) == 0: return [] # add ending punctuation if it is missing if phrase[-1] not in ".!?": phrase = phrase + "." # megahal traditionally considers [a-z0-9] as word characters. # Let's see what happens if we add [_'] words = re.findall("([\w']+|[^\w']+)", phrase.upper()) return words Use the re.UNICODE flag (i.e., Python character tables) in findall()
# Copyright (C) 2010 Peter Teichman import re class MegaHALTokenizer: def split(self, phrase): if len(phrase) == 0: return [] # add ending punctuation if it is missing if phrase[-1] not in ".!?": phrase = phrase + "." # megahal traditionally considers [a-z0-9] as word characters. # Let's see what happens if we add [_'] words = re.findall("([\w']+|[^\w']+)", phrase.upper(), re.UNICODE) return words
<commit_before># Copyright (C) 2010 Peter Teichman import re class MegaHALTokenizer: def split(self, phrase): if len(phrase) == 0: return [] # add ending punctuation if it is missing if phrase[-1] not in ".!?": phrase = phrase + "." # megahal traditionally considers [a-z0-9] as word characters. # Let's see what happens if we add [_'] words = re.findall("([\w']+|[^\w']+)", phrase.upper()) return words <commit_msg>Use the re.UNICODE flag (i.e., Python character tables) in findall()<commit_after>
# Copyright (C) 2010 Peter Teichman import re class MegaHALTokenizer: def split(self, phrase): if len(phrase) == 0: return [] # add ending punctuation if it is missing if phrase[-1] not in ".!?": phrase = phrase + "." # megahal traditionally considers [a-z0-9] as word characters. # Let's see what happens if we add [_'] words = re.findall("([\w']+|[^\w']+)", phrase.upper(), re.UNICODE) return words
# Copyright (C) 2010 Peter Teichman import re class MegaHALTokenizer: def split(self, phrase): if len(phrase) == 0: return [] # add ending punctuation if it is missing if phrase[-1] not in ".!?": phrase = phrase + "." # megahal traditionally considers [a-z0-9] as word characters. # Let's see what happens if we add [_'] words = re.findall("([\w']+|[^\w']+)", phrase.upper()) return words Use the re.UNICODE flag (i.e., Python character tables) in findall()# Copyright (C) 2010 Peter Teichman import re class MegaHALTokenizer: def split(self, phrase): if len(phrase) == 0: return [] # add ending punctuation if it is missing if phrase[-1] not in ".!?": phrase = phrase + "." # megahal traditionally considers [a-z0-9] as word characters. # Let's see what happens if we add [_'] words = re.findall("([\w']+|[^\w']+)", phrase.upper(), re.UNICODE) return words
<commit_before># Copyright (C) 2010 Peter Teichman import re class MegaHALTokenizer: def split(self, phrase): if len(phrase) == 0: return [] # add ending punctuation if it is missing if phrase[-1] not in ".!?": phrase = phrase + "." # megahal traditionally considers [a-z0-9] as word characters. # Let's see what happens if we add [_'] words = re.findall("([\w']+|[^\w']+)", phrase.upper()) return words <commit_msg>Use the re.UNICODE flag (i.e., Python character tables) in findall()<commit_after># Copyright (C) 2010 Peter Teichman import re class MegaHALTokenizer: def split(self, phrase): if len(phrase) == 0: return [] # add ending punctuation if it is missing if phrase[-1] not in ".!?": phrase = phrase + "." # megahal traditionally considers [a-z0-9] as word characters. # Let's see what happens if we add [_'] words = re.findall("([\w']+|[^\w']+)", phrase.upper(), re.UNICODE) return words
b7c95f6eed786000278f5719fbf4ac037af20e50
{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/users/tests/factories.py
{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/users/tests/factories.py
from typing import Any, Sequence from django.contrib.auth import get_user_model from factory import Faker, post_generation from factory.django import DjangoModelFactory class UserFactory(DjangoModelFactory): username = Faker("user_name") email = Faker("email") name = Faker("name") @post_generation def password(self, create: bool, extracted: Sequence[Any], **kwargs): password = ( extracted if extracted else Faker( "password", length=42, special_chars=True, digits=True, upper_case=True, lower_case=True, ).generate(params={"locale": None}) ) self.set_password(password) class Meta: model = get_user_model() django_get_or_create = ["username"]
from typing import Any, Sequence from django.contrib.auth import get_user_model from factory import Faker, post_generation from factory.django import DjangoModelFactory class UserFactory(DjangoModelFactory): username = Faker("user_name") email = Faker("email") name = Faker("name") @post_generation def password(self, create: bool, extracted: Sequence[Any], **kwargs): password = ( extracted if extracted else Faker( "password", length=42, special_chars=True, digits=True, upper_case=True, lower_case=True, ).evaluate(None, None, extra={"locale": None}) ) self.set_password(password) class Meta: model = get_user_model() django_get_or_create = ["username"]
Update factory-boy's .generate to evaluate
Update factory-boy's .generate to evaluate Co-Authored-By: Timo Halbesma <98c2d5a1e48c998bd9ba9dbc53d6857beae1c9bd@halbesma.com>
Python
bsd-3-clause
pydanny/cookiecutter-django,pydanny/cookiecutter-django,ryankanno/cookiecutter-django,trungdong/cookiecutter-django,ryankanno/cookiecutter-django,trungdong/cookiecutter-django,ryankanno/cookiecutter-django,ryankanno/cookiecutter-django,trungdong/cookiecutter-django,pydanny/cookiecutter-django,trungdong/cookiecutter-django,pydanny/cookiecutter-django
from typing import Any, Sequence from django.contrib.auth import get_user_model from factory import Faker, post_generation from factory.django import DjangoModelFactory class UserFactory(DjangoModelFactory): username = Faker("user_name") email = Faker("email") name = Faker("name") @post_generation def password(self, create: bool, extracted: Sequence[Any], **kwargs): password = ( extracted if extracted else Faker( "password", length=42, special_chars=True, digits=True, upper_case=True, lower_case=True, ).generate(params={"locale": None}) ) self.set_password(password) class Meta: model = get_user_model() django_get_or_create = ["username"] Update factory-boy's .generate to evaluate Co-Authored-By: Timo Halbesma <98c2d5a1e48c998bd9ba9dbc53d6857beae1c9bd@halbesma.com>
from typing import Any, Sequence from django.contrib.auth import get_user_model from factory import Faker, post_generation from factory.django import DjangoModelFactory class UserFactory(DjangoModelFactory): username = Faker("user_name") email = Faker("email") name = Faker("name") @post_generation def password(self, create: bool, extracted: Sequence[Any], **kwargs): password = ( extracted if extracted else Faker( "password", length=42, special_chars=True, digits=True, upper_case=True, lower_case=True, ).evaluate(None, None, extra={"locale": None}) ) self.set_password(password) class Meta: model = get_user_model() django_get_or_create = ["username"]
<commit_before>from typing import Any, Sequence from django.contrib.auth import get_user_model from factory import Faker, post_generation from factory.django import DjangoModelFactory class UserFactory(DjangoModelFactory): username = Faker("user_name") email = Faker("email") name = Faker("name") @post_generation def password(self, create: bool, extracted: Sequence[Any], **kwargs): password = ( extracted if extracted else Faker( "password", length=42, special_chars=True, digits=True, upper_case=True, lower_case=True, ).generate(params={"locale": None}) ) self.set_password(password) class Meta: model = get_user_model() django_get_or_create = ["username"] <commit_msg>Update factory-boy's .generate to evaluate Co-Authored-By: Timo Halbesma <98c2d5a1e48c998bd9ba9dbc53d6857beae1c9bd@halbesma.com><commit_after>
from typing import Any, Sequence from django.contrib.auth import get_user_model from factory import Faker, post_generation from factory.django import DjangoModelFactory class UserFactory(DjangoModelFactory): username = Faker("user_name") email = Faker("email") name = Faker("name") @post_generation def password(self, create: bool, extracted: Sequence[Any], **kwargs): password = ( extracted if extracted else Faker( "password", length=42, special_chars=True, digits=True, upper_case=True, lower_case=True, ).evaluate(None, None, extra={"locale": None}) ) self.set_password(password) class Meta: model = get_user_model() django_get_or_create = ["username"]
from typing import Any, Sequence from django.contrib.auth import get_user_model from factory import Faker, post_generation from factory.django import DjangoModelFactory class UserFactory(DjangoModelFactory): username = Faker("user_name") email = Faker("email") name = Faker("name") @post_generation def password(self, create: bool, extracted: Sequence[Any], **kwargs): password = ( extracted if extracted else Faker( "password", length=42, special_chars=True, digits=True, upper_case=True, lower_case=True, ).generate(params={"locale": None}) ) self.set_password(password) class Meta: model = get_user_model() django_get_or_create = ["username"] Update factory-boy's .generate to evaluate Co-Authored-By: Timo Halbesma <98c2d5a1e48c998bd9ba9dbc53d6857beae1c9bd@halbesma.com>from typing import Any, Sequence from django.contrib.auth import get_user_model from factory import Faker, post_generation from factory.django import DjangoModelFactory class UserFactory(DjangoModelFactory): username = Faker("user_name") email = Faker("email") name = Faker("name") @post_generation def password(self, create: bool, extracted: Sequence[Any], **kwargs): password = ( extracted if extracted else Faker( "password", length=42, special_chars=True, digits=True, upper_case=True, lower_case=True, ).evaluate(None, None, extra={"locale": None}) ) self.set_password(password) class Meta: model = get_user_model() django_get_or_create = ["username"]
<commit_before>from typing import Any, Sequence from django.contrib.auth import get_user_model from factory import Faker, post_generation from factory.django import DjangoModelFactory class UserFactory(DjangoModelFactory): username = Faker("user_name") email = Faker("email") name = Faker("name") @post_generation def password(self, create: bool, extracted: Sequence[Any], **kwargs): password = ( extracted if extracted else Faker( "password", length=42, special_chars=True, digits=True, upper_case=True, lower_case=True, ).generate(params={"locale": None}) ) self.set_password(password) class Meta: model = get_user_model() django_get_or_create = ["username"] <commit_msg>Update factory-boy's .generate to evaluate Co-Authored-By: Timo Halbesma <98c2d5a1e48c998bd9ba9dbc53d6857beae1c9bd@halbesma.com><commit_after>from typing import Any, Sequence from django.contrib.auth import get_user_model from factory import Faker, post_generation from factory.django import DjangoModelFactory class UserFactory(DjangoModelFactory): username = Faker("user_name") email = Faker("email") name = Faker("name") @post_generation def password(self, create: bool, extracted: Sequence[Any], **kwargs): password = ( extracted if extracted else Faker( "password", length=42, special_chars=True, digits=True, upper_case=True, lower_case=True, ).evaluate(None, None, extra={"locale": None}) ) self.set_password(password) class Meta: model = get_user_model() django_get_or_create = ["username"]
32b35f49c525d6b527de325ecc4837ab7c18b5ad
apiserver/alembic/versions/201711101357_451d4bb125cb_add_ranking_data_to_participants_table.py
apiserver/alembic/versions/201711101357_451d4bb125cb_add_ranking_data_to_participants_table.py
"""Add ranking data to participants table Revision ID: 451d4bb125cb Revises: 49be2190c22d Create Date: 2017-11-10 13:57:37.807238+00:00 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import mysql # revision identifiers, used by Alembic. revision = '451d4bb125cb' down_revision = '49be2190c22d' branch_labels = None depends_on = None def upgrade(): op.add_column( "game_participant", sa.Column('mu', mysql.FLOAT(), nullable=True), ) op.add_column( "game_participant", sa.Column('sigma', mysql.FLOAT(unsigned=True), nullable=True), ) op.add_column( "game_participant", sa.Column('rank', mysql.SMALLINT(display_width=5), autoincrement=False, nullable=True), ) def downgrade(): op.drop_column("game_participant", "mu") op.drop_column("game_participant", "sigma") op.drop_column("game_participant", "rank")
"""Add ranking data to participants table Revision ID: 451d4bb125cb Revises: 49be2190c22d Create Date: 2017-11-10 13:57:37.807238+00:00 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import mysql # revision identifiers, used by Alembic. revision = '451d4bb125cb' down_revision = '49be2190c22d' branch_labels = None depends_on = None def upgrade(): op.add_column( "game_participant", sa.Column('mu', mysql.FLOAT(), nullable=True), ) op.add_column( "game_participant", sa.Column('sigma', mysql.FLOAT(unsigned=True), nullable=True), ) op.add_column( "game_participant", sa.Column('leaderboard_rank', mysql.SMALLINT(display_width=5), autoincrement=False, nullable=True), ) def downgrade(): op.drop_column("game_participant", "mu") op.drop_column("game_participant", "sigma") op.drop_column("game_participant", "leaderboard_rank")
Rename rank field to avoid column name clash
Rename rank field to avoid column name clash
Python
mit
HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II
"""Add ranking data to participants table Revision ID: 451d4bb125cb Revises: 49be2190c22d Create Date: 2017-11-10 13:57:37.807238+00:00 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import mysql # revision identifiers, used by Alembic. revision = '451d4bb125cb' down_revision = '49be2190c22d' branch_labels = None depends_on = None def upgrade(): op.add_column( "game_participant", sa.Column('mu', mysql.FLOAT(), nullable=True), ) op.add_column( "game_participant", sa.Column('sigma', mysql.FLOAT(unsigned=True), nullable=True), ) op.add_column( "game_participant", sa.Column('rank', mysql.SMALLINT(display_width=5), autoincrement=False, nullable=True), ) def downgrade(): op.drop_column("game_participant", "mu") op.drop_column("game_participant", "sigma") op.drop_column("game_participant", "rank") Rename rank field to avoid column name clash
"""Add ranking data to participants table Revision ID: 451d4bb125cb Revises: 49be2190c22d Create Date: 2017-11-10 13:57:37.807238+00:00 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import mysql # revision identifiers, used by Alembic. revision = '451d4bb125cb' down_revision = '49be2190c22d' branch_labels = None depends_on = None def upgrade(): op.add_column( "game_participant", sa.Column('mu', mysql.FLOAT(), nullable=True), ) op.add_column( "game_participant", sa.Column('sigma', mysql.FLOAT(unsigned=True), nullable=True), ) op.add_column( "game_participant", sa.Column('leaderboard_rank', mysql.SMALLINT(display_width=5), autoincrement=False, nullable=True), ) def downgrade(): op.drop_column("game_participant", "mu") op.drop_column("game_participant", "sigma") op.drop_column("game_participant", "leaderboard_rank")
<commit_before>"""Add ranking data to participants table Revision ID: 451d4bb125cb Revises: 49be2190c22d Create Date: 2017-11-10 13:57:37.807238+00:00 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import mysql # revision identifiers, used by Alembic. revision = '451d4bb125cb' down_revision = '49be2190c22d' branch_labels = None depends_on = None def upgrade(): op.add_column( "game_participant", sa.Column('mu', mysql.FLOAT(), nullable=True), ) op.add_column( "game_participant", sa.Column('sigma', mysql.FLOAT(unsigned=True), nullable=True), ) op.add_column( "game_participant", sa.Column('rank', mysql.SMALLINT(display_width=5), autoincrement=False, nullable=True), ) def downgrade(): op.drop_column("game_participant", "mu") op.drop_column("game_participant", "sigma") op.drop_column("game_participant", "rank") <commit_msg>Rename rank field to avoid column name clash<commit_after>
"""Add ranking data to participants table Revision ID: 451d4bb125cb Revises: 49be2190c22d Create Date: 2017-11-10 13:57:37.807238+00:00 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import mysql # revision identifiers, used by Alembic. revision = '451d4bb125cb' down_revision = '49be2190c22d' branch_labels = None depends_on = None def upgrade(): op.add_column( "game_participant", sa.Column('mu', mysql.FLOAT(), nullable=True), ) op.add_column( "game_participant", sa.Column('sigma', mysql.FLOAT(unsigned=True), nullable=True), ) op.add_column( "game_participant", sa.Column('leaderboard_rank', mysql.SMALLINT(display_width=5), autoincrement=False, nullable=True), ) def downgrade(): op.drop_column("game_participant", "mu") op.drop_column("game_participant", "sigma") op.drop_column("game_participant", "leaderboard_rank")
"""Add ranking data to participants table Revision ID: 451d4bb125cb Revises: 49be2190c22d Create Date: 2017-11-10 13:57:37.807238+00:00 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import mysql # revision identifiers, used by Alembic. revision = '451d4bb125cb' down_revision = '49be2190c22d' branch_labels = None depends_on = None def upgrade(): op.add_column( "game_participant", sa.Column('mu', mysql.FLOAT(), nullable=True), ) op.add_column( "game_participant", sa.Column('sigma', mysql.FLOAT(unsigned=True), nullable=True), ) op.add_column( "game_participant", sa.Column('rank', mysql.SMALLINT(display_width=5), autoincrement=False, nullable=True), ) def downgrade(): op.drop_column("game_participant", "mu") op.drop_column("game_participant", "sigma") op.drop_column("game_participant", "rank") Rename rank field to avoid column name clash"""Add ranking data to participants table Revision ID: 451d4bb125cb Revises: 49be2190c22d Create Date: 2017-11-10 13:57:37.807238+00:00 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import mysql # revision identifiers, used by Alembic. revision = '451d4bb125cb' down_revision = '49be2190c22d' branch_labels = None depends_on = None def upgrade(): op.add_column( "game_participant", sa.Column('mu', mysql.FLOAT(), nullable=True), ) op.add_column( "game_participant", sa.Column('sigma', mysql.FLOAT(unsigned=True), nullable=True), ) op.add_column( "game_participant", sa.Column('leaderboard_rank', mysql.SMALLINT(display_width=5), autoincrement=False, nullable=True), ) def downgrade(): op.drop_column("game_participant", "mu") op.drop_column("game_participant", "sigma") op.drop_column("game_participant", "leaderboard_rank")
<commit_before>"""Add ranking data to participants table Revision ID: 451d4bb125cb Revises: 49be2190c22d Create Date: 2017-11-10 13:57:37.807238+00:00 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import mysql # revision identifiers, used by Alembic. revision = '451d4bb125cb' down_revision = '49be2190c22d' branch_labels = None depends_on = None def upgrade(): op.add_column( "game_participant", sa.Column('mu', mysql.FLOAT(), nullable=True), ) op.add_column( "game_participant", sa.Column('sigma', mysql.FLOAT(unsigned=True), nullable=True), ) op.add_column( "game_participant", sa.Column('rank', mysql.SMALLINT(display_width=5), autoincrement=False, nullable=True), ) def downgrade(): op.drop_column("game_participant", "mu") op.drop_column("game_participant", "sigma") op.drop_column("game_participant", "rank") <commit_msg>Rename rank field to avoid column name clash<commit_after>"""Add ranking data to participants table Revision ID: 451d4bb125cb Revises: 49be2190c22d Create Date: 2017-11-10 13:57:37.807238+00:00 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import mysql # revision identifiers, used by Alembic. revision = '451d4bb125cb' down_revision = '49be2190c22d' branch_labels = None depends_on = None def upgrade(): op.add_column( "game_participant", sa.Column('mu', mysql.FLOAT(), nullable=True), ) op.add_column( "game_participant", sa.Column('sigma', mysql.FLOAT(unsigned=True), nullable=True), ) op.add_column( "game_participant", sa.Column('leaderboard_rank', mysql.SMALLINT(display_width=5), autoincrement=False, nullable=True), ) def downgrade(): op.drop_column("game_participant", "mu") op.drop_column("game_participant", "sigma") op.drop_column("game_participant", "leaderboard_rank")
c291d032f7b6fba4fcc28ce8495b482d3e93406b
tests/test_ops.py
tests/test_ops.py
# -*- coding: utf-8 -*- import pytest from epo_ops.middlewares import Dogpile, Throttler from epo_ops.middlewares.throttle.storages import sqlite from inet.sources.ops import OpsClient from secrets import OPS_KEY, OPS_SECRET def test_ops_client_instantiated(): """Test our subclass od epo_ops.RegisteredClient to ensure it is instantiatied correctly.""" client = OpsClient(OPS_KEY, OPS_SECRET) assert len(client.middlewares) == 1 assert client.middlewares[0].history.db_path == sqlite.DEFAULT_DB_PATH middlewares = [ Dogpile(), Throttler(), ] client = OpsClient(OPS_KEY, OPS_SECRET, accept_type='JSON', middlewares=middlewares) assert len(client.middlewares) == 2 if __name__ == '__main__': pytest.main()
# -*- coding: utf-8 -*- import pytest from epo_ops.middlewares import Dogpile, Throttler from epo_ops.middlewares.throttle.storages import sqlite from inet.sources.ops import OpsClient from .secrets import OPS_KEY, OPS_SECRET def test_ops_client_instantiated(): """Test our subclass od epo_ops.RegisteredClient to ensure it is instantiatied correctly.""" client = OpsClient(OPS_KEY, OPS_SECRET) assert len(client.middlewares) == 1 assert client.middlewares[0].history.db_path == sqlite.DEFAULT_DB_PATH middlewares = [ Dogpile(), Throttler(), ] client = OpsClient(OPS_KEY, OPS_SECRET, accept_type='JSON', middlewares=middlewares) assert len(client.middlewares) == 2 if __name__ == '__main__': pytest.main()
Make importing secrets explicitly relative
Make importing secrets explicitly relative
Python
mit
nestauk/inet
# -*- coding: utf-8 -*- import pytest from epo_ops.middlewares import Dogpile, Throttler from epo_ops.middlewares.throttle.storages import sqlite from inet.sources.ops import OpsClient from secrets import OPS_KEY, OPS_SECRET def test_ops_client_instantiated(): """Test our subclass od epo_ops.RegisteredClient to ensure it is instantiatied correctly.""" client = OpsClient(OPS_KEY, OPS_SECRET) assert len(client.middlewares) == 1 assert client.middlewares[0].history.db_path == sqlite.DEFAULT_DB_PATH middlewares = [ Dogpile(), Throttler(), ] client = OpsClient(OPS_KEY, OPS_SECRET, accept_type='JSON', middlewares=middlewares) assert len(client.middlewares) == 2 if __name__ == '__main__': pytest.main() Make importing secrets explicitly relative
# -*- coding: utf-8 -*- import pytest from epo_ops.middlewares import Dogpile, Throttler from epo_ops.middlewares.throttle.storages import sqlite from inet.sources.ops import OpsClient from .secrets import OPS_KEY, OPS_SECRET def test_ops_client_instantiated(): """Test our subclass od epo_ops.RegisteredClient to ensure it is instantiatied correctly.""" client = OpsClient(OPS_KEY, OPS_SECRET) assert len(client.middlewares) == 1 assert client.middlewares[0].history.db_path == sqlite.DEFAULT_DB_PATH middlewares = [ Dogpile(), Throttler(), ] client = OpsClient(OPS_KEY, OPS_SECRET, accept_type='JSON', middlewares=middlewares) assert len(client.middlewares) == 2 if __name__ == '__main__': pytest.main()
<commit_before># -*- coding: utf-8 -*- import pytest from epo_ops.middlewares import Dogpile, Throttler from epo_ops.middlewares.throttle.storages import sqlite from inet.sources.ops import OpsClient from secrets import OPS_KEY, OPS_SECRET def test_ops_client_instantiated(): """Test our subclass od epo_ops.RegisteredClient to ensure it is instantiatied correctly.""" client = OpsClient(OPS_KEY, OPS_SECRET) assert len(client.middlewares) == 1 assert client.middlewares[0].history.db_path == sqlite.DEFAULT_DB_PATH middlewares = [ Dogpile(), Throttler(), ] client = OpsClient(OPS_KEY, OPS_SECRET, accept_type='JSON', middlewares=middlewares) assert len(client.middlewares) == 2 if __name__ == '__main__': pytest.main() <commit_msg>Make importing secrets explicitly relative<commit_after>
# -*- coding: utf-8 -*- import pytest from epo_ops.middlewares import Dogpile, Throttler from epo_ops.middlewares.throttle.storages import sqlite from inet.sources.ops import OpsClient from .secrets import OPS_KEY, OPS_SECRET def test_ops_client_instantiated(): """Test our subclass od epo_ops.RegisteredClient to ensure it is instantiatied correctly.""" client = OpsClient(OPS_KEY, OPS_SECRET) assert len(client.middlewares) == 1 assert client.middlewares[0].history.db_path == sqlite.DEFAULT_DB_PATH middlewares = [ Dogpile(), Throttler(), ] client = OpsClient(OPS_KEY, OPS_SECRET, accept_type='JSON', middlewares=middlewares) assert len(client.middlewares) == 2 if __name__ == '__main__': pytest.main()
# -*- coding: utf-8 -*- import pytest from epo_ops.middlewares import Dogpile, Throttler from epo_ops.middlewares.throttle.storages import sqlite from inet.sources.ops import OpsClient from secrets import OPS_KEY, OPS_SECRET def test_ops_client_instantiated(): """Test our subclass od epo_ops.RegisteredClient to ensure it is instantiatied correctly.""" client = OpsClient(OPS_KEY, OPS_SECRET) assert len(client.middlewares) == 1 assert client.middlewares[0].history.db_path == sqlite.DEFAULT_DB_PATH middlewares = [ Dogpile(), Throttler(), ] client = OpsClient(OPS_KEY, OPS_SECRET, accept_type='JSON', middlewares=middlewares) assert len(client.middlewares) == 2 if __name__ == '__main__': pytest.main() Make importing secrets explicitly relative# -*- coding: utf-8 -*- import pytest from epo_ops.middlewares import Dogpile, Throttler from epo_ops.middlewares.throttle.storages import sqlite from inet.sources.ops import OpsClient from .secrets import OPS_KEY, OPS_SECRET def test_ops_client_instantiated(): """Test our subclass od epo_ops.RegisteredClient to ensure it is instantiatied correctly.""" client = OpsClient(OPS_KEY, OPS_SECRET) assert len(client.middlewares) == 1 assert client.middlewares[0].history.db_path == sqlite.DEFAULT_DB_PATH middlewares = [ Dogpile(), Throttler(), ] client = OpsClient(OPS_KEY, OPS_SECRET, accept_type='JSON', middlewares=middlewares) assert len(client.middlewares) == 2 if __name__ == '__main__': pytest.main()
<commit_before># -*- coding: utf-8 -*- import pytest from epo_ops.middlewares import Dogpile, Throttler from epo_ops.middlewares.throttle.storages import sqlite from inet.sources.ops import OpsClient from secrets import OPS_KEY, OPS_SECRET def test_ops_client_instantiated(): """Test our subclass od epo_ops.RegisteredClient to ensure it is instantiatied correctly.""" client = OpsClient(OPS_KEY, OPS_SECRET) assert len(client.middlewares) == 1 assert client.middlewares[0].history.db_path == sqlite.DEFAULT_DB_PATH middlewares = [ Dogpile(), Throttler(), ] client = OpsClient(OPS_KEY, OPS_SECRET, accept_type='JSON', middlewares=middlewares) assert len(client.middlewares) == 2 if __name__ == '__main__': pytest.main() <commit_msg>Make importing secrets explicitly relative<commit_after># -*- coding: utf-8 -*- import pytest from epo_ops.middlewares import Dogpile, Throttler from epo_ops.middlewares.throttle.storages import sqlite from inet.sources.ops import OpsClient from .secrets import OPS_KEY, OPS_SECRET def test_ops_client_instantiated(): """Test our subclass od epo_ops.RegisteredClient to ensure it is instantiatied correctly.""" client = OpsClient(OPS_KEY, OPS_SECRET) assert len(client.middlewares) == 1 assert client.middlewares[0].history.db_path == sqlite.DEFAULT_DB_PATH middlewares = [ Dogpile(), Throttler(), ] client = OpsClient(OPS_KEY, OPS_SECRET, accept_type='JSON', middlewares=middlewares) assert len(client.middlewares) == 2 if __name__ == '__main__': pytest.main()
e9709abadb2daa1a0752fa12b8e017074f0fb098
classes/person.py
classes/person.py
class Person(object): def __init__(self, person_type, person_name, person_surname="", wants_accommodation="N"): self.person_name = person_name self.person_surname = person_surname self.person_type = person_type self.wants_accommodation = wants_accommodation def full_name(self): if not isinstance(self.person_name, str) or not isinstance(self.person_surname, str): raise ValueError('Only strings are allowed as names') else: self.full_name = self.person_name + " " + self.person_surname return self.full_name
class Person(object): def __init__(self, person_type, person_name, person_surname="", wants_accommodation="N"): self.person_name = person_name self.person_surname = person_surname self.person_type = person_type self.wants_accommodation = wants_accommodation def full_name(self): self.full_name = self.person_name + " " + self.person_surname return self.full_name
Change full name method to stop validating for str type which is repetitive and has been tested elsewhere
Change full name method to stop validating for str type which is repetitive and has been tested elsewhere
Python
mit
peterpaints/room-allocator
class Person(object): def __init__(self, person_type, person_name, person_surname="", wants_accommodation="N"): self.person_name = person_name self.person_surname = person_surname self.person_type = person_type self.wants_accommodation = wants_accommodation def full_name(self): if not isinstance(self.person_name, str) or not isinstance(self.person_surname, str): raise ValueError('Only strings are allowed as names') else: self.full_name = self.person_name + " " + self.person_surname return self.full_name Change full name method to stop validating for str type which is repetitive and has been tested elsewhere
class Person(object): def __init__(self, person_type, person_name, person_surname="", wants_accommodation="N"): self.person_name = person_name self.person_surname = person_surname self.person_type = person_type self.wants_accommodation = wants_accommodation def full_name(self): self.full_name = self.person_name + " " + self.person_surname return self.full_name
<commit_before>class Person(object): def __init__(self, person_type, person_name, person_surname="", wants_accommodation="N"): self.person_name = person_name self.person_surname = person_surname self.person_type = person_type self.wants_accommodation = wants_accommodation def full_name(self): if not isinstance(self.person_name, str) or not isinstance(self.person_surname, str): raise ValueError('Only strings are allowed as names') else: self.full_name = self.person_name + " " + self.person_surname return self.full_name <commit_msg>Change full name method to stop validating for str type which is repetitive and has been tested elsewhere<commit_after>
class Person(object): def __init__(self, person_type, person_name, person_surname="", wants_accommodation="N"): self.person_name = person_name self.person_surname = person_surname self.person_type = person_type self.wants_accommodation = wants_accommodation def full_name(self): self.full_name = self.person_name + " " + self.person_surname return self.full_name
class Person(object): def __init__(self, person_type, person_name, person_surname="", wants_accommodation="N"): self.person_name = person_name self.person_surname = person_surname self.person_type = person_type self.wants_accommodation = wants_accommodation def full_name(self): if not isinstance(self.person_name, str) or not isinstance(self.person_surname, str): raise ValueError('Only strings are allowed as names') else: self.full_name = self.person_name + " " + self.person_surname return self.full_name Change full name method to stop validating for str type which is repetitive and has been tested elsewhereclass Person(object): def __init__(self, person_type, person_name, person_surname="", wants_accommodation="N"): self.person_name = person_name self.person_surname = person_surname self.person_type = person_type self.wants_accommodation = wants_accommodation def full_name(self): self.full_name = self.person_name + " " + self.person_surname return self.full_name
<commit_before>class Person(object): def __init__(self, person_type, person_name, person_surname="", wants_accommodation="N"): self.person_name = person_name self.person_surname = person_surname self.person_type = person_type self.wants_accommodation = wants_accommodation def full_name(self): if not isinstance(self.person_name, str) or not isinstance(self.person_surname, str): raise ValueError('Only strings are allowed as names') else: self.full_name = self.person_name + " " + self.person_surname return self.full_name <commit_msg>Change full name method to stop validating for str type which is repetitive and has been tested elsewhere<commit_after>class Person(object): def __init__(self, person_type, person_name, person_surname="", wants_accommodation="N"): self.person_name = person_name self.person_surname = person_surname self.person_type = person_type self.wants_accommodation = wants_accommodation def full_name(self): self.full_name = self.person_name + " " + self.person_surname return self.full_name
8d43061490c32b204505382ec7b77c18ddc32d9d
conf_site/apps.py
conf_site/apps.py
from django.apps import AppConfig as BaseAppConfig from django.utils.importlib import import_module class AppConfig(BaseAppConfig): name = "conf_site" def ready(self): import_module("conf_site.receivers")
from importlib import import_module from django.apps import AppConfig as BaseAppConfig class AppConfig(BaseAppConfig): name = "conf_site" def ready(self): import_module("conf_site.receivers")
Remove Django importlib in favor of stdlib.
Remove Django importlib in favor of stdlib. Django's copy of importlib was deprecated in 1.7 and therefore removed in Django 1.9: https://docs.djangoproject.com/en/1.10/releases/1.7/#django-utils-dictconfig-django-utils-importlib This is okay, since we are using Python 2.7 and can rely on the copy in the standard library.
Python
mit
pydata/conf_site,pydata/conf_site,pydata/conf_site
from django.apps import AppConfig as BaseAppConfig from django.utils.importlib import import_module class AppConfig(BaseAppConfig): name = "conf_site" def ready(self): import_module("conf_site.receivers") Remove Django importlib in favor of stdlib. Django's copy of importlib was deprecated in 1.7 and therefore removed in Django 1.9: https://docs.djangoproject.com/en/1.10/releases/1.7/#django-utils-dictconfig-django-utils-importlib This is okay, since we are using Python 2.7 and can rely on the copy in the standard library.
from importlib import import_module from django.apps import AppConfig as BaseAppConfig class AppConfig(BaseAppConfig): name = "conf_site" def ready(self): import_module("conf_site.receivers")
<commit_before>from django.apps import AppConfig as BaseAppConfig from django.utils.importlib import import_module class AppConfig(BaseAppConfig): name = "conf_site" def ready(self): import_module("conf_site.receivers") <commit_msg>Remove Django importlib in favor of stdlib. Django's copy of importlib was deprecated in 1.7 and therefore removed in Django 1.9: https://docs.djangoproject.com/en/1.10/releases/1.7/#django-utils-dictconfig-django-utils-importlib This is okay, since we are using Python 2.7 and can rely on the copy in the standard library.<commit_after>
from importlib import import_module from django.apps import AppConfig as BaseAppConfig class AppConfig(BaseAppConfig): name = "conf_site" def ready(self): import_module("conf_site.receivers")
from django.apps import AppConfig as BaseAppConfig from django.utils.importlib import import_module class AppConfig(BaseAppConfig): name = "conf_site" def ready(self): import_module("conf_site.receivers") Remove Django importlib in favor of stdlib. Django's copy of importlib was deprecated in 1.7 and therefore removed in Django 1.9: https://docs.djangoproject.com/en/1.10/releases/1.7/#django-utils-dictconfig-django-utils-importlib This is okay, since we are using Python 2.7 and can rely on the copy in the standard library.from importlib import import_module from django.apps import AppConfig as BaseAppConfig class AppConfig(BaseAppConfig): name = "conf_site" def ready(self): import_module("conf_site.receivers")
<commit_before>from django.apps import AppConfig as BaseAppConfig from django.utils.importlib import import_module class AppConfig(BaseAppConfig): name = "conf_site" def ready(self): import_module("conf_site.receivers") <commit_msg>Remove Django importlib in favor of stdlib. Django's copy of importlib was deprecated in 1.7 and therefore removed in Django 1.9: https://docs.djangoproject.com/en/1.10/releases/1.7/#django-utils-dictconfig-django-utils-importlib This is okay, since we are using Python 2.7 and can rely on the copy in the standard library.<commit_after>from importlib import import_module from django.apps import AppConfig as BaseAppConfig class AppConfig(BaseAppConfig): name = "conf_site" def ready(self): import_module("conf_site.receivers")
858f993ceffb497bee12457d1d4102339af410a4
typer/__init__.py
typer/__init__.py
"""Typer, build great CLIs. Easy to code. Based on Python type hints.""" __version__ = "0.0.4" from click.exceptions import ( # noqa Abort, BadArgumentUsage, BadOptionUsage, BadParameter, ClickException, FileError, MissingParameter, NoSuchOption, UsageError, ) from click.termui import ( # noqa clear, confirm, echo_via_pager, edit, get_terminal_size, getchar, launch, pause, progressbar, prompt, secho, style, unstyle, ) from click.utils import ( # noqa echo, format_filename, get_app_dir, get_binary_stream, get_os_args, get_text_stream, open_file, ) from .main import Typer, run # noqa from .models import BinaryFileRead, BinaryFileWrite, Context, TextFile # noqa from .params import Argument, Option # noqa
"""Typer, build great CLIs. Easy to code. Based on Python type hints.""" __version__ = "0.0.4" from click.exceptions import ( # noqa Abort, Exit, ) from click.termui import ( # noqa clear, confirm, echo_via_pager, edit, get_terminal_size, getchar, launch, pause, progressbar, prompt, secho, style, unstyle, ) from click.utils import ( # noqa echo, format_filename, get_app_dir, get_binary_stream, get_text_stream, open_file, ) from .main import Typer, run # noqa from .models import BinaryFileRead, BinaryFileWrite, Context, TextFile # noqa from .params import Argument, Option # noqa
Clean exports from typer, remove unneeded Click components
:fire: Clean exports from typer, remove unneeded Click components and add Exit exception
Python
mit
tiangolo/typer,tiangolo/typer
"""Typer, build great CLIs. Easy to code. Based on Python type hints.""" __version__ = "0.0.4" from click.exceptions import ( # noqa Abort, BadArgumentUsage, BadOptionUsage, BadParameter, ClickException, FileError, MissingParameter, NoSuchOption, UsageError, ) from click.termui import ( # noqa clear, confirm, echo_via_pager, edit, get_terminal_size, getchar, launch, pause, progressbar, prompt, secho, style, unstyle, ) from click.utils import ( # noqa echo, format_filename, get_app_dir, get_binary_stream, get_os_args, get_text_stream, open_file, ) from .main import Typer, run # noqa from .models import BinaryFileRead, BinaryFileWrite, Context, TextFile # noqa from .params import Argument, Option # noqa :fire: Clean exports from typer, remove unneeded Click components and add Exit exception
"""Typer, build great CLIs. Easy to code. Based on Python type hints.""" __version__ = "0.0.4" from click.exceptions import ( # noqa Abort, Exit, ) from click.termui import ( # noqa clear, confirm, echo_via_pager, edit, get_terminal_size, getchar, launch, pause, progressbar, prompt, secho, style, unstyle, ) from click.utils import ( # noqa echo, format_filename, get_app_dir, get_binary_stream, get_text_stream, open_file, ) from .main import Typer, run # noqa from .models import BinaryFileRead, BinaryFileWrite, Context, TextFile # noqa from .params import Argument, Option # noqa
<commit_before>"""Typer, build great CLIs. Easy to code. Based on Python type hints.""" __version__ = "0.0.4" from click.exceptions import ( # noqa Abort, BadArgumentUsage, BadOptionUsage, BadParameter, ClickException, FileError, MissingParameter, NoSuchOption, UsageError, ) from click.termui import ( # noqa clear, confirm, echo_via_pager, edit, get_terminal_size, getchar, launch, pause, progressbar, prompt, secho, style, unstyle, ) from click.utils import ( # noqa echo, format_filename, get_app_dir, get_binary_stream, get_os_args, get_text_stream, open_file, ) from .main import Typer, run # noqa from .models import BinaryFileRead, BinaryFileWrite, Context, TextFile # noqa from .params import Argument, Option # noqa <commit_msg>:fire: Clean exports from typer, remove unneeded Click components and add Exit exception<commit_after>
"""Typer, build great CLIs. Easy to code. Based on Python type hints.""" __version__ = "0.0.4" from click.exceptions import ( # noqa Abort, Exit, ) from click.termui import ( # noqa clear, confirm, echo_via_pager, edit, get_terminal_size, getchar, launch, pause, progressbar, prompt, secho, style, unstyle, ) from click.utils import ( # noqa echo, format_filename, get_app_dir, get_binary_stream, get_text_stream, open_file, ) from .main import Typer, run # noqa from .models import BinaryFileRead, BinaryFileWrite, Context, TextFile # noqa from .params import Argument, Option # noqa
"""Typer, build great CLIs. Easy to code. Based on Python type hints.""" __version__ = "0.0.4" from click.exceptions import ( # noqa Abort, BadArgumentUsage, BadOptionUsage, BadParameter, ClickException, FileError, MissingParameter, NoSuchOption, UsageError, ) from click.termui import ( # noqa clear, confirm, echo_via_pager, edit, get_terminal_size, getchar, launch, pause, progressbar, prompt, secho, style, unstyle, ) from click.utils import ( # noqa echo, format_filename, get_app_dir, get_binary_stream, get_os_args, get_text_stream, open_file, ) from .main import Typer, run # noqa from .models import BinaryFileRead, BinaryFileWrite, Context, TextFile # noqa from .params import Argument, Option # noqa :fire: Clean exports from typer, remove unneeded Click components and add Exit exception"""Typer, build great CLIs. Easy to code. Based on Python type hints.""" __version__ = "0.0.4" from click.exceptions import ( # noqa Abort, Exit, ) from click.termui import ( # noqa clear, confirm, echo_via_pager, edit, get_terminal_size, getchar, launch, pause, progressbar, prompt, secho, style, unstyle, ) from click.utils import ( # noqa echo, format_filename, get_app_dir, get_binary_stream, get_text_stream, open_file, ) from .main import Typer, run # noqa from .models import BinaryFileRead, BinaryFileWrite, Context, TextFile # noqa from .params import Argument, Option # noqa
<commit_before>"""Typer, build great CLIs. Easy to code. Based on Python type hints.""" __version__ = "0.0.4" from click.exceptions import ( # noqa Abort, BadArgumentUsage, BadOptionUsage, BadParameter, ClickException, FileError, MissingParameter, NoSuchOption, UsageError, ) from click.termui import ( # noqa clear, confirm, echo_via_pager, edit, get_terminal_size, getchar, launch, pause, progressbar, prompt, secho, style, unstyle, ) from click.utils import ( # noqa echo, format_filename, get_app_dir, get_binary_stream, get_os_args, get_text_stream, open_file, ) from .main import Typer, run # noqa from .models import BinaryFileRead, BinaryFileWrite, Context, TextFile # noqa from .params import Argument, Option # noqa <commit_msg>:fire: Clean exports from typer, remove unneeded Click components and add Exit exception<commit_after>"""Typer, build great CLIs. Easy to code. Based on Python type hints.""" __version__ = "0.0.4" from click.exceptions import ( # noqa Abort, Exit, ) from click.termui import ( # noqa clear, confirm, echo_via_pager, edit, get_terminal_size, getchar, launch, pause, progressbar, prompt, secho, style, unstyle, ) from click.utils import ( # noqa echo, format_filename, get_app_dir, get_binary_stream, get_text_stream, open_file, ) from .main import Typer, run # noqa from .models import BinaryFileRead, BinaryFileWrite, Context, TextFile # noqa from .params import Argument, Option # noqa
2833e2296cff6a52ab75c2c88563e81372902035
src/heartbeat/checkers/build.py
src/heartbeat/checkers/build.py
from django.conf import settings from django.core.exceptions import ImproperlyConfigured from pkg_resources import get_distribution, DistributionNotFound def check(request): package_name = settings.HEARTBEAT.get('package_name') if not package_name: raise ImproperlyConfigured( 'Missing package_name key from heartbeat configuration') try: distro = get_distribution(package_name) except DistributionNotFound: return dict(error='no distribution found for {}'.format(package_name)) return dict(name=distro.project_name, version=distro.version)
from pkg_resources import Requirement, WorkingSet from django.conf import settings from django.core.exceptions import ImproperlyConfigured def check(request): package_name = settings.HEARTBEAT.get('package_name') if not package_name: raise ImproperlyConfigured( 'Missing package_name key from heartbeat configuration') sys_path_distros = WorkingSet() package_req = Requirement.parse(package_name) distro = sys_path_distros.find(package_req) if not distro: return dict(error='no distribution found for {}'.format(package_name)) return dict(name=distro.project_name, version=distro.version)
Package name should be searched through the same distros list we use for listing installed packages. get_distribution is using the global working_set which may not contain the requested package if the initialization(pkg_resources import time) happened before the project name to appear in the sys.path.
Package name should be searched through the same distros list we use for listing installed packages. get_distribution is using the global working_set which may not contain the requested package if the initialization(pkg_resources import time) happened before the project name to appear in the sys.path.
Python
mit
pbs/django-heartbeat
from django.conf import settings from django.core.exceptions import ImproperlyConfigured from pkg_resources import get_distribution, DistributionNotFound def check(request): package_name = settings.HEARTBEAT.get('package_name') if not package_name: raise ImproperlyConfigured( 'Missing package_name key from heartbeat configuration') try: distro = get_distribution(package_name) except DistributionNotFound: return dict(error='no distribution found for {}'.format(package_name)) return dict(name=distro.project_name, version=distro.version) Package name should be searched through the same distros list we use for listing installed packages. get_distribution is using the global working_set which may not contain the requested package if the initialization(pkg_resources import time) happened before the project name to appear in the sys.path.
from pkg_resources import Requirement, WorkingSet from django.conf import settings from django.core.exceptions import ImproperlyConfigured def check(request): package_name = settings.HEARTBEAT.get('package_name') if not package_name: raise ImproperlyConfigured( 'Missing package_name key from heartbeat configuration') sys_path_distros = WorkingSet() package_req = Requirement.parse(package_name) distro = sys_path_distros.find(package_req) if not distro: return dict(error='no distribution found for {}'.format(package_name)) return dict(name=distro.project_name, version=distro.version)
<commit_before>from django.conf import settings from django.core.exceptions import ImproperlyConfigured from pkg_resources import get_distribution, DistributionNotFound def check(request): package_name = settings.HEARTBEAT.get('package_name') if not package_name: raise ImproperlyConfigured( 'Missing package_name key from heartbeat configuration') try: distro = get_distribution(package_name) except DistributionNotFound: return dict(error='no distribution found for {}'.format(package_name)) return dict(name=distro.project_name, version=distro.version) <commit_msg>Package name should be searched through the same distros list we use for listing installed packages. get_distribution is using the global working_set which may not contain the requested package if the initialization(pkg_resources import time) happened before the project name to appear in the sys.path.<commit_after>
from pkg_resources import Requirement, WorkingSet from django.conf import settings from django.core.exceptions import ImproperlyConfigured def check(request): package_name = settings.HEARTBEAT.get('package_name') if not package_name: raise ImproperlyConfigured( 'Missing package_name key from heartbeat configuration') sys_path_distros = WorkingSet() package_req = Requirement.parse(package_name) distro = sys_path_distros.find(package_req) if not distro: return dict(error='no distribution found for {}'.format(package_name)) return dict(name=distro.project_name, version=distro.version)
from django.conf import settings from django.core.exceptions import ImproperlyConfigured from pkg_resources import get_distribution, DistributionNotFound def check(request): package_name = settings.HEARTBEAT.get('package_name') if not package_name: raise ImproperlyConfigured( 'Missing package_name key from heartbeat configuration') try: distro = get_distribution(package_name) except DistributionNotFound: return dict(error='no distribution found for {}'.format(package_name)) return dict(name=distro.project_name, version=distro.version) Package name should be searched through the same distros list we use for listing installed packages. get_distribution is using the global working_set which may not contain the requested package if the initialization(pkg_resources import time) happened before the project name to appear in the sys.path.from pkg_resources import Requirement, WorkingSet from django.conf import settings from django.core.exceptions import ImproperlyConfigured def check(request): package_name = settings.HEARTBEAT.get('package_name') if not package_name: raise ImproperlyConfigured( 'Missing package_name key from heartbeat configuration') sys_path_distros = WorkingSet() package_req = Requirement.parse(package_name) distro = sys_path_distros.find(package_req) if not distro: return dict(error='no distribution found for {}'.format(package_name)) return dict(name=distro.project_name, version=distro.version)
<commit_before>from django.conf import settings from django.core.exceptions import ImproperlyConfigured from pkg_resources import get_distribution, DistributionNotFound def check(request): package_name = settings.HEARTBEAT.get('package_name') if not package_name: raise ImproperlyConfigured( 'Missing package_name key from heartbeat configuration') try: distro = get_distribution(package_name) except DistributionNotFound: return dict(error='no distribution found for {}'.format(package_name)) return dict(name=distro.project_name, version=distro.version) <commit_msg>Package name should be searched through the same distros list we use for listing installed packages. get_distribution is using the global working_set which may not contain the requested package if the initialization(pkg_resources import time) happened before the project name to appear in the sys.path.<commit_after>from pkg_resources import Requirement, WorkingSet from django.conf import settings from django.core.exceptions import ImproperlyConfigured def check(request): package_name = settings.HEARTBEAT.get('package_name') if not package_name: raise ImproperlyConfigured( 'Missing package_name key from heartbeat configuration') sys_path_distros = WorkingSet() package_req = Requirement.parse(package_name) distro = sys_path_distros.find(package_req) if not distro: return dict(error='no distribution found for {}'.format(package_name)) return dict(name=distro.project_name, version=distro.version)
fa776fc0d3c568bda7d84ccd9b345e34c3fcf312
ideascube/mediacenter/tests/factories.py
ideascube/mediacenter/tests/factories.py
from django.conf import settings import factory from ..models import Document class DocumentFactory(factory.django.DjangoModelFactory): title = factory.Sequence(lambda n: "Test document {0}".format(n)) summary = "This is a test summary" lang = settings.LANGUAGE_CODE original = factory.django.FileField() credits = "Document credits" package_id = "" @factory.post_generation def tags(self, create, extracted, **kwargs): if extracted: self.tags.add(*extracted) class Meta: model = Document
from django.conf import settings import factory from ..models import Document class EmptyFileField(factory.django.FileField): DEFAULT_FILENAME = None class DocumentFactory(factory.django.DjangoModelFactory): title = factory.Sequence(lambda n: "Test document {0}".format(n)) summary = "This is a test summary" lang = settings.LANGUAGE_CODE original = factory.django.FileField() preview = EmptyFileField() credits = "Document credits" package_id = "" @factory.post_generation def tags(self, create, extracted, **kwargs): if extracted: self.tags.add(*extracted) class Meta: model = Document
Allow DocumentFactory to handle preview field.
Allow DocumentFactory to handle preview field. The factory.django.FileField.DEFAULT_FILENAME == 'example.dat'. It means that by default a FileField created by factoryboy is considered as a True value. Before this commit, we were not defining a Document.preview field in the factory so factoryboy created a empty FileField. To not break the API for other tests, we need to create a "False" FileField by default. To do so, we need to change the DEFAULT_FILENAME to None.
Python
agpl-3.0
ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,ideascube/ideascube
from django.conf import settings import factory from ..models import Document class DocumentFactory(factory.django.DjangoModelFactory): title = factory.Sequence(lambda n: "Test document {0}".format(n)) summary = "This is a test summary" lang = settings.LANGUAGE_CODE original = factory.django.FileField() credits = "Document credits" package_id = "" @factory.post_generation def tags(self, create, extracted, **kwargs): if extracted: self.tags.add(*extracted) class Meta: model = Document Allow DocumentFactory to handle preview field. The factory.django.FileField.DEFAULT_FILENAME == 'example.dat'. It means that by default a FileField created by factoryboy is considered as a True value. Before this commit, we were not defining a Document.preview field in the factory so factoryboy created a empty FileField. To not break the API for other tests, we need to create a "False" FileField by default. To do so, we need to change the DEFAULT_FILENAME to None.
from django.conf import settings import factory from ..models import Document class EmptyFileField(factory.django.FileField): DEFAULT_FILENAME = None class DocumentFactory(factory.django.DjangoModelFactory): title = factory.Sequence(lambda n: "Test document {0}".format(n)) summary = "This is a test summary" lang = settings.LANGUAGE_CODE original = factory.django.FileField() preview = EmptyFileField() credits = "Document credits" package_id = "" @factory.post_generation def tags(self, create, extracted, **kwargs): if extracted: self.tags.add(*extracted) class Meta: model = Document
<commit_before>from django.conf import settings import factory from ..models import Document class DocumentFactory(factory.django.DjangoModelFactory): title = factory.Sequence(lambda n: "Test document {0}".format(n)) summary = "This is a test summary" lang = settings.LANGUAGE_CODE original = factory.django.FileField() credits = "Document credits" package_id = "" @factory.post_generation def tags(self, create, extracted, **kwargs): if extracted: self.tags.add(*extracted) class Meta: model = Document <commit_msg>Allow DocumentFactory to handle preview field. The factory.django.FileField.DEFAULT_FILENAME == 'example.dat'. It means that by default a FileField created by factoryboy is considered as a True value. Before this commit, we were not defining a Document.preview field in the factory so factoryboy created a empty FileField. To not break the API for other tests, we need to create a "False" FileField by default. To do so, we need to change the DEFAULT_FILENAME to None.<commit_after>
from django.conf import settings import factory from ..models import Document class EmptyFileField(factory.django.FileField): DEFAULT_FILENAME = None class DocumentFactory(factory.django.DjangoModelFactory): title = factory.Sequence(lambda n: "Test document {0}".format(n)) summary = "This is a test summary" lang = settings.LANGUAGE_CODE original = factory.django.FileField() preview = EmptyFileField() credits = "Document credits" package_id = "" @factory.post_generation def tags(self, create, extracted, **kwargs): if extracted: self.tags.add(*extracted) class Meta: model = Document
from django.conf import settings import factory from ..models import Document class DocumentFactory(factory.django.DjangoModelFactory): title = factory.Sequence(lambda n: "Test document {0}".format(n)) summary = "This is a test summary" lang = settings.LANGUAGE_CODE original = factory.django.FileField() credits = "Document credits" package_id = "" @factory.post_generation def tags(self, create, extracted, **kwargs): if extracted: self.tags.add(*extracted) class Meta: model = Document Allow DocumentFactory to handle preview field. The factory.django.FileField.DEFAULT_FILENAME == 'example.dat'. It means that by default a FileField created by factoryboy is considered as a True value. Before this commit, we were not defining a Document.preview field in the factory so factoryboy created a empty FileField. To not break the API for other tests, we need to create a "False" FileField by default. To do so, we need to change the DEFAULT_FILENAME to None.from django.conf import settings import factory from ..models import Document class EmptyFileField(factory.django.FileField): DEFAULT_FILENAME = None class DocumentFactory(factory.django.DjangoModelFactory): title = factory.Sequence(lambda n: "Test document {0}".format(n)) summary = "This is a test summary" lang = settings.LANGUAGE_CODE original = factory.django.FileField() preview = EmptyFileField() credits = "Document credits" package_id = "" @factory.post_generation def tags(self, create, extracted, **kwargs): if extracted: self.tags.add(*extracted) class Meta: model = Document
<commit_before>from django.conf import settings import factory from ..models import Document class DocumentFactory(factory.django.DjangoModelFactory): title = factory.Sequence(lambda n: "Test document {0}".format(n)) summary = "This is a test summary" lang = settings.LANGUAGE_CODE original = factory.django.FileField() credits = "Document credits" package_id = "" @factory.post_generation def tags(self, create, extracted, **kwargs): if extracted: self.tags.add(*extracted) class Meta: model = Document <commit_msg>Allow DocumentFactory to handle preview field. The factory.django.FileField.DEFAULT_FILENAME == 'example.dat'. It means that by default a FileField created by factoryboy is considered as a True value. Before this commit, we were not defining a Document.preview field in the factory so factoryboy created a empty FileField. To not break the API for other tests, we need to create a "False" FileField by default. To do so, we need to change the DEFAULT_FILENAME to None.<commit_after>from django.conf import settings import factory from ..models import Document class EmptyFileField(factory.django.FileField): DEFAULT_FILENAME = None class DocumentFactory(factory.django.DjangoModelFactory): title = factory.Sequence(lambda n: "Test document {0}".format(n)) summary = "This is a test summary" lang = settings.LANGUAGE_CODE original = factory.django.FileField() preview = EmptyFileField() credits = "Document credits" package_id = "" @factory.post_generation def tags(self, create, extracted, **kwargs): if extracted: self.tags.add(*extracted) class Meta: model = Document
e0607c27cf990f893d837af5717de684bb62aa63
plugins/spark/__init__.py
plugins/spark/__init__.py
import os import romanesco from . import pyspark_executor, spark SC_KEY = '_romanesco_spark_context' def setup_pyspark_task(event): """ This is executed before a task execution. If it is a pyspark task, we create the spark context here so it can be used for any input conversion. """ info = event.info if info['mode'] == 'spark.python' and SC_KEY not in info['kwargs']: spark_conf = info['task'].get('spark_conf', {}) info['kwargs'][SC_KEY] = spark.create_spark_context(spark_conf) def pyspark_run_cleanup(event): if SC_KEY in event.info['kwargs']: event.info['kwargs'][SC_KEY].stop() def load(params): # If we have a spark config section then try to setup spark environment if romanesco.config.has_section('spark') or 'SPARK_HOME' in os.environ: spark.setup_spark_env() romanesco.register_executor('spark.python', pyspark_executor.run) romanesco.events.bind('run.before', 'spark', setup_pyspark_task) romanesco.events.bind('run.finally', 'spark', pyspark_run_cleanup)
import os import romanesco from . import pyspark_executor, spark SC_KEY = '_romanesco_spark_context' def setup_pyspark_task(event): """ This is executed before a task execution. If it is a pyspark task, we create the spark context here so it can be used for any input conversion. """ info = event.info if info['mode'] == 'spark.python' and SC_KEY not in info['kwargs']: spark_conf = info['task'].get('spark_conf', {}) info['kwargs'][SC_KEY] = spark.create_spark_context(spark_conf) info['cleanup_spark'] = True def pyspark_run_cleanup(event): if event.info.get('cleanup_spark'): event.info['kwargs'][SC_KEY].stop() def load(params): # If we have a spark config section then try to setup spark environment if romanesco.config.has_section('spark') or 'SPARK_HOME' in os.environ: spark.setup_spark_env() romanesco.register_executor('spark.python', pyspark_executor.run) romanesco.events.bind('run.before', 'spark', setup_pyspark_task) romanesco.events.bind('run.finally', 'spark', pyspark_run_cleanup)
Fix spark mode (faulty shutdown conditional logic)
Fix spark mode (faulty shutdown conditional logic)
Python
apache-2.0
Kitware/romanesco,girder/girder_worker,girder/girder_worker,Kitware/romanesco,girder/girder_worker,Kitware/romanesco,Kitware/romanesco
import os import romanesco from . import pyspark_executor, spark SC_KEY = '_romanesco_spark_context' def setup_pyspark_task(event): """ This is executed before a task execution. If it is a pyspark task, we create the spark context here so it can be used for any input conversion. """ info = event.info if info['mode'] == 'spark.python' and SC_KEY not in info['kwargs']: spark_conf = info['task'].get('spark_conf', {}) info['kwargs'][SC_KEY] = spark.create_spark_context(spark_conf) def pyspark_run_cleanup(event): if SC_KEY in event.info['kwargs']: event.info['kwargs'][SC_KEY].stop() def load(params): # If we have a spark config section then try to setup spark environment if romanesco.config.has_section('spark') or 'SPARK_HOME' in os.environ: spark.setup_spark_env() romanesco.register_executor('spark.python', pyspark_executor.run) romanesco.events.bind('run.before', 'spark', setup_pyspark_task) romanesco.events.bind('run.finally', 'spark', pyspark_run_cleanup) Fix spark mode (faulty shutdown conditional logic)
import os import romanesco from . import pyspark_executor, spark SC_KEY = '_romanesco_spark_context' def setup_pyspark_task(event): """ This is executed before a task execution. If it is a pyspark task, we create the spark context here so it can be used for any input conversion. """ info = event.info if info['mode'] == 'spark.python' and SC_KEY not in info['kwargs']: spark_conf = info['task'].get('spark_conf', {}) info['kwargs'][SC_KEY] = spark.create_spark_context(spark_conf) info['cleanup_spark'] = True def pyspark_run_cleanup(event): if event.info.get('cleanup_spark'): event.info['kwargs'][SC_KEY].stop() def load(params): # If we have a spark config section then try to setup spark environment if romanesco.config.has_section('spark') or 'SPARK_HOME' in os.environ: spark.setup_spark_env() romanesco.register_executor('spark.python', pyspark_executor.run) romanesco.events.bind('run.before', 'spark', setup_pyspark_task) romanesco.events.bind('run.finally', 'spark', pyspark_run_cleanup)
<commit_before>import os import romanesco from . import pyspark_executor, spark SC_KEY = '_romanesco_spark_context' def setup_pyspark_task(event): """ This is executed before a task execution. If it is a pyspark task, we create the spark context here so it can be used for any input conversion. """ info = event.info if info['mode'] == 'spark.python' and SC_KEY not in info['kwargs']: spark_conf = info['task'].get('spark_conf', {}) info['kwargs'][SC_KEY] = spark.create_spark_context(spark_conf) def pyspark_run_cleanup(event): if SC_KEY in event.info['kwargs']: event.info['kwargs'][SC_KEY].stop() def load(params): # If we have a spark config section then try to setup spark environment if romanesco.config.has_section('spark') or 'SPARK_HOME' in os.environ: spark.setup_spark_env() romanesco.register_executor('spark.python', pyspark_executor.run) romanesco.events.bind('run.before', 'spark', setup_pyspark_task) romanesco.events.bind('run.finally', 'spark', pyspark_run_cleanup) <commit_msg>Fix spark mode (faulty shutdown conditional logic)<commit_after>
import os import romanesco from . import pyspark_executor, spark SC_KEY = '_romanesco_spark_context' def setup_pyspark_task(event): """ This is executed before a task execution. If it is a pyspark task, we create the spark context here so it can be used for any input conversion. """ info = event.info if info['mode'] == 'spark.python' and SC_KEY not in info['kwargs']: spark_conf = info['task'].get('spark_conf', {}) info['kwargs'][SC_KEY] = spark.create_spark_context(spark_conf) info['cleanup_spark'] = True def pyspark_run_cleanup(event): if event.info.get('cleanup_spark'): event.info['kwargs'][SC_KEY].stop() def load(params): # If we have a spark config section then try to setup spark environment if romanesco.config.has_section('spark') or 'SPARK_HOME' in os.environ: spark.setup_spark_env() romanesco.register_executor('spark.python', pyspark_executor.run) romanesco.events.bind('run.before', 'spark', setup_pyspark_task) romanesco.events.bind('run.finally', 'spark', pyspark_run_cleanup)
import os import romanesco from . import pyspark_executor, spark SC_KEY = '_romanesco_spark_context' def setup_pyspark_task(event): """ This is executed before a task execution. If it is a pyspark task, we create the spark context here so it can be used for any input conversion. """ info = event.info if info['mode'] == 'spark.python' and SC_KEY not in info['kwargs']: spark_conf = info['task'].get('spark_conf', {}) info['kwargs'][SC_KEY] = spark.create_spark_context(spark_conf) def pyspark_run_cleanup(event): if SC_KEY in event.info['kwargs']: event.info['kwargs'][SC_KEY].stop() def load(params): # If we have a spark config section then try to setup spark environment if romanesco.config.has_section('spark') or 'SPARK_HOME' in os.environ: spark.setup_spark_env() romanesco.register_executor('spark.python', pyspark_executor.run) romanesco.events.bind('run.before', 'spark', setup_pyspark_task) romanesco.events.bind('run.finally', 'spark', pyspark_run_cleanup) Fix spark mode (faulty shutdown conditional logic)import os import romanesco from . import pyspark_executor, spark SC_KEY = '_romanesco_spark_context' def setup_pyspark_task(event): """ This is executed before a task execution. If it is a pyspark task, we create the spark context here so it can be used for any input conversion. """ info = event.info if info['mode'] == 'spark.python' and SC_KEY not in info['kwargs']: spark_conf = info['task'].get('spark_conf', {}) info['kwargs'][SC_KEY] = spark.create_spark_context(spark_conf) info['cleanup_spark'] = True def pyspark_run_cleanup(event): if event.info.get('cleanup_spark'): event.info['kwargs'][SC_KEY].stop() def load(params): # If we have a spark config section then try to setup spark environment if romanesco.config.has_section('spark') or 'SPARK_HOME' in os.environ: spark.setup_spark_env() romanesco.register_executor('spark.python', pyspark_executor.run) romanesco.events.bind('run.before', 'spark', setup_pyspark_task) romanesco.events.bind('run.finally', 'spark', pyspark_run_cleanup)
<commit_before>import os import romanesco from . import pyspark_executor, spark SC_KEY = '_romanesco_spark_context' def setup_pyspark_task(event): """ This is executed before a task execution. If it is a pyspark task, we create the spark context here so it can be used for any input conversion. """ info = event.info if info['mode'] == 'spark.python' and SC_KEY not in info['kwargs']: spark_conf = info['task'].get('spark_conf', {}) info['kwargs'][SC_KEY] = spark.create_spark_context(spark_conf) def pyspark_run_cleanup(event): if SC_KEY in event.info['kwargs']: event.info['kwargs'][SC_KEY].stop() def load(params): # If we have a spark config section then try to setup spark environment if romanesco.config.has_section('spark') or 'SPARK_HOME' in os.environ: spark.setup_spark_env() romanesco.register_executor('spark.python', pyspark_executor.run) romanesco.events.bind('run.before', 'spark', setup_pyspark_task) romanesco.events.bind('run.finally', 'spark', pyspark_run_cleanup) <commit_msg>Fix spark mode (faulty shutdown conditional logic)<commit_after>import os import romanesco from . import pyspark_executor, spark SC_KEY = '_romanesco_spark_context' def setup_pyspark_task(event): """ This is executed before a task execution. If it is a pyspark task, we create the spark context here so it can be used for any input conversion. """ info = event.info if info['mode'] == 'spark.python' and SC_KEY not in info['kwargs']: spark_conf = info['task'].get('spark_conf', {}) info['kwargs'][SC_KEY] = spark.create_spark_context(spark_conf) info['cleanup_spark'] = True def pyspark_run_cleanup(event): if event.info.get('cleanup_spark'): event.info['kwargs'][SC_KEY].stop() def load(params): # If we have a spark config section then try to setup spark environment if romanesco.config.has_section('spark') or 'SPARK_HOME' in os.environ: spark.setup_spark_env() romanesco.register_executor('spark.python', pyspark_executor.run) romanesco.events.bind('run.before', 'spark', setup_pyspark_task) romanesco.events.bind('run.finally', 'spark', pyspark_run_cleanup)
e771eeb4595197ae4c147f617c4cf7e5825f279c
object_extractor/named_object.py
object_extractor/named_object.py
from collections import defaultdict class EntityForm: def __init__(self): self._score = 0. self.forms = defaultdict(float) def add_form(self, score, normal_form): self._score += score self.forms[normal_form] += score def normal_form(self): return max(self.forms.items(), key=lambda x: x[1])[0] def score(self): return self._score class NamedObject: def __init__(self): self._entities = [] def __bool__(self): return bool(self._entities) def add(self, object_type, score, normal_form): self._entities.append((object_type, score, normal_form)) def calc_entities(self): forms = defaultdict(EntityForm) forms['object'] = self._make_global_entity() for object_type, score, normal_form in self._entities: forms[object_type].add_form(score, normal_form) return forms def _make_global_entity(self): global_form = EntityForm() for _, score, form in self._entities: global_form.add_form(score, form) return global_form
from collections import defaultdict class EntityForm: def __init__(self): self._score = 0. self.forms = defaultdict(float) def add_form(self, score, normal_form): self._score += score self.forms[normal_form] += score def normal_form(self): return max(self.forms.items(), key=lambda x: x[1])[0] def score(self): return self._score class NamedObject: def __init__(self): self._entities = [] def __bool__(self): return bool(self._entities) def add(self, object_type, score, normal_form): self._entities.append((object_type, score, normal_form)) def calc_entities(self): forms = defaultdict(EntityForm) for object_type, score, normal_form in self._entities: forms[object_type].add_form(score, normal_form) return forms
Remove `objects' group as useless
Remove `objects' group as useless
Python
mit
Lol4t0/named-objects-extractor
from collections import defaultdict class EntityForm: def __init__(self): self._score = 0. self.forms = defaultdict(float) def add_form(self, score, normal_form): self._score += score self.forms[normal_form] += score def normal_form(self): return max(self.forms.items(), key=lambda x: x[1])[0] def score(self): return self._score class NamedObject: def __init__(self): self._entities = [] def __bool__(self): return bool(self._entities) def add(self, object_type, score, normal_form): self._entities.append((object_type, score, normal_form)) def calc_entities(self): forms = defaultdict(EntityForm) forms['object'] = self._make_global_entity() for object_type, score, normal_form in self._entities: forms[object_type].add_form(score, normal_form) return forms def _make_global_entity(self): global_form = EntityForm() for _, score, form in self._entities: global_form.add_form(score, form) return global_form Remove `objects' group as useless
from collections import defaultdict class EntityForm: def __init__(self): self._score = 0. self.forms = defaultdict(float) def add_form(self, score, normal_form): self._score += score self.forms[normal_form] += score def normal_form(self): return max(self.forms.items(), key=lambda x: x[1])[0] def score(self): return self._score class NamedObject: def __init__(self): self._entities = [] def __bool__(self): return bool(self._entities) def add(self, object_type, score, normal_form): self._entities.append((object_type, score, normal_form)) def calc_entities(self): forms = defaultdict(EntityForm) for object_type, score, normal_form in self._entities: forms[object_type].add_form(score, normal_form) return forms
<commit_before>from collections import defaultdict class EntityForm: def __init__(self): self._score = 0. self.forms = defaultdict(float) def add_form(self, score, normal_form): self._score += score self.forms[normal_form] += score def normal_form(self): return max(self.forms.items(), key=lambda x: x[1])[0] def score(self): return self._score class NamedObject: def __init__(self): self._entities = [] def __bool__(self): return bool(self._entities) def add(self, object_type, score, normal_form): self._entities.append((object_type, score, normal_form)) def calc_entities(self): forms = defaultdict(EntityForm) forms['object'] = self._make_global_entity() for object_type, score, normal_form in self._entities: forms[object_type].add_form(score, normal_form) return forms def _make_global_entity(self): global_form = EntityForm() for _, score, form in self._entities: global_form.add_form(score, form) return global_form <commit_msg>Remove `objects' group as useless<commit_after>
from collections import defaultdict class EntityForm: def __init__(self): self._score = 0. self.forms = defaultdict(float) def add_form(self, score, normal_form): self._score += score self.forms[normal_form] += score def normal_form(self): return max(self.forms.items(), key=lambda x: x[1])[0] def score(self): return self._score class NamedObject: def __init__(self): self._entities = [] def __bool__(self): return bool(self._entities) def add(self, object_type, score, normal_form): self._entities.append((object_type, score, normal_form)) def calc_entities(self): forms = defaultdict(EntityForm) for object_type, score, normal_form in self._entities: forms[object_type].add_form(score, normal_form) return forms
from collections import defaultdict class EntityForm: def __init__(self): self._score = 0. self.forms = defaultdict(float) def add_form(self, score, normal_form): self._score += score self.forms[normal_form] += score def normal_form(self): return max(self.forms.items(), key=lambda x: x[1])[0] def score(self): return self._score class NamedObject: def __init__(self): self._entities = [] def __bool__(self): return bool(self._entities) def add(self, object_type, score, normal_form): self._entities.append((object_type, score, normal_form)) def calc_entities(self): forms = defaultdict(EntityForm) forms['object'] = self._make_global_entity() for object_type, score, normal_form in self._entities: forms[object_type].add_form(score, normal_form) return forms def _make_global_entity(self): global_form = EntityForm() for _, score, form in self._entities: global_form.add_form(score, form) return global_form Remove `objects' group as uselessfrom collections import defaultdict class EntityForm: def __init__(self): self._score = 0. self.forms = defaultdict(float) def add_form(self, score, normal_form): self._score += score self.forms[normal_form] += score def normal_form(self): return max(self.forms.items(), key=lambda x: x[1])[0] def score(self): return self._score class NamedObject: def __init__(self): self._entities = [] def __bool__(self): return bool(self._entities) def add(self, object_type, score, normal_form): self._entities.append((object_type, score, normal_form)) def calc_entities(self): forms = defaultdict(EntityForm) for object_type, score, normal_form in self._entities: forms[object_type].add_form(score, normal_form) return forms
<commit_before>from collections import defaultdict class EntityForm: def __init__(self): self._score = 0. self.forms = defaultdict(float) def add_form(self, score, normal_form): self._score += score self.forms[normal_form] += score def normal_form(self): return max(self.forms.items(), key=lambda x: x[1])[0] def score(self): return self._score class NamedObject: def __init__(self): self._entities = [] def __bool__(self): return bool(self._entities) def add(self, object_type, score, normal_form): self._entities.append((object_type, score, normal_form)) def calc_entities(self): forms = defaultdict(EntityForm) forms['object'] = self._make_global_entity() for object_type, score, normal_form in self._entities: forms[object_type].add_form(score, normal_form) return forms def _make_global_entity(self): global_form = EntityForm() for _, score, form in self._entities: global_form.add_form(score, form) return global_form <commit_msg>Remove `objects' group as useless<commit_after>from collections import defaultdict class EntityForm: def __init__(self): self._score = 0. self.forms = defaultdict(float) def add_form(self, score, normal_form): self._score += score self.forms[normal_form] += score def normal_form(self): return max(self.forms.items(), key=lambda x: x[1])[0] def score(self): return self._score class NamedObject: def __init__(self): self._entities = [] def __bool__(self): return bool(self._entities) def add(self, object_type, score, normal_form): self._entities.append((object_type, score, normal_form)) def calc_entities(self): forms = defaultdict(EntityForm) for object_type, score, normal_form in self._entities: forms[object_type].add_form(score, normal_form) return forms
c6427c035b9d1d38618ebfed33f729e3d10f270d
config.py
config.py
from katagawa.kg import Katagawa from schema.config import Guild class Config: def __init__(self, bot): dsn = f'postgresql://beattie:passwd@localhost/config' self.db = Katagawa(dsn) self.bot = bot self.bot.loop.create_task(self.db.connect()) def __del__(self): self.bot.loop.create_task(self.db.close()) async def get(self, key): async with self.db.get_session() as s: query = s.select(Guild).where(Guild.id == key) guild = await query.first() return {k.name: v for k, v in guild.to_dict().items()} async def set(self, gid, **kwargs): async with self.db.get_session() as s: s.merge(Guild(id=gid, **kwargs)) async def add(self, gid, **kwargs): async with self.db.get_session() as s: s.add(Guild(id=gid, **kwargs)) async def remove(self, gid): async with self.db.get_session() as s: await s.execute(f'delete from guild where id = {gid}')
from katagawa.kg import Katagawa from schema.config import Guild class Config: def __init__(self, bot): dsn = f'postgresql://beattie:passwd@localhost/config' self.db = Katagawa(dsn) self.bot = bot self.bot.loop.create_task(self.db.connect()) def __del__(self): self.bot.loop.create_task(self.db.close()) async def get(self, key): async with self.db.get_session() as s: query = s.select(Guild).where(Guild.id == key) guild = await query.first() return {k.name: v for k, v in guild.to_dict().items()} async def set(self, gid, **kwargs): async with self.db.get_session() as s: guild = await s.select(Guild).where(Guild.id == gid).first() for key, value in kwargs.items(): setattr(guild, key, value) s.merge(guild) async def add(self, gid, **kwargs): async with self.db.get_session() as s: s.add(Guild(id=gid, **kwargs)) async def remove(self, gid): async with self.db.get_session() as s: await s.execute(f'delete from guild where id = {gid}')
Change set to merge correctly
Change set to merge correctly
Python
mit
BeatButton/beattie,BeatButton/beattie-bot
from katagawa.kg import Katagawa from schema.config import Guild class Config: def __init__(self, bot): dsn = f'postgresql://beattie:passwd@localhost/config' self.db = Katagawa(dsn) self.bot = bot self.bot.loop.create_task(self.db.connect()) def __del__(self): self.bot.loop.create_task(self.db.close()) async def get(self, key): async with self.db.get_session() as s: query = s.select(Guild).where(Guild.id == key) guild = await query.first() return {k.name: v for k, v in guild.to_dict().items()} async def set(self, gid, **kwargs): async with self.db.get_session() as s: s.merge(Guild(id=gid, **kwargs)) async def add(self, gid, **kwargs): async with self.db.get_session() as s: s.add(Guild(id=gid, **kwargs)) async def remove(self, gid): async with self.db.get_session() as s: await s.execute(f'delete from guild where id = {gid}') Change set to merge correctly
from katagawa.kg import Katagawa from schema.config import Guild class Config: def __init__(self, bot): dsn = f'postgresql://beattie:passwd@localhost/config' self.db = Katagawa(dsn) self.bot = bot self.bot.loop.create_task(self.db.connect()) def __del__(self): self.bot.loop.create_task(self.db.close()) async def get(self, key): async with self.db.get_session() as s: query = s.select(Guild).where(Guild.id == key) guild = await query.first() return {k.name: v for k, v in guild.to_dict().items()} async def set(self, gid, **kwargs): async with self.db.get_session() as s: guild = await s.select(Guild).where(Guild.id == gid).first() for key, value in kwargs.items(): setattr(guild, key, value) s.merge(guild) async def add(self, gid, **kwargs): async with self.db.get_session() as s: s.add(Guild(id=gid, **kwargs)) async def remove(self, gid): async with self.db.get_session() as s: await s.execute(f'delete from guild where id = {gid}')
<commit_before>from katagawa.kg import Katagawa from schema.config import Guild class Config: def __init__(self, bot): dsn = f'postgresql://beattie:passwd@localhost/config' self.db = Katagawa(dsn) self.bot = bot self.bot.loop.create_task(self.db.connect()) def __del__(self): self.bot.loop.create_task(self.db.close()) async def get(self, key): async with self.db.get_session() as s: query = s.select(Guild).where(Guild.id == key) guild = await query.first() return {k.name: v for k, v in guild.to_dict().items()} async def set(self, gid, **kwargs): async with self.db.get_session() as s: s.merge(Guild(id=gid, **kwargs)) async def add(self, gid, **kwargs): async with self.db.get_session() as s: s.add(Guild(id=gid, **kwargs)) async def remove(self, gid): async with self.db.get_session() as s: await s.execute(f'delete from guild where id = {gid}') <commit_msg>Change set to merge correctly<commit_after>
from katagawa.kg import Katagawa from schema.config import Guild class Config: def __init__(self, bot): dsn = f'postgresql://beattie:passwd@localhost/config' self.db = Katagawa(dsn) self.bot = bot self.bot.loop.create_task(self.db.connect()) def __del__(self): self.bot.loop.create_task(self.db.close()) async def get(self, key): async with self.db.get_session() as s: query = s.select(Guild).where(Guild.id == key) guild = await query.first() return {k.name: v for k, v in guild.to_dict().items()} async def set(self, gid, **kwargs): async with self.db.get_session() as s: guild = await s.select(Guild).where(Guild.id == gid).first() for key, value in kwargs.items(): setattr(guild, key, value) s.merge(guild) async def add(self, gid, **kwargs): async with self.db.get_session() as s: s.add(Guild(id=gid, **kwargs)) async def remove(self, gid): async with self.db.get_session() as s: await s.execute(f'delete from guild where id = {gid}')
from katagawa.kg import Katagawa from schema.config import Guild class Config: def __init__(self, bot): dsn = f'postgresql://beattie:passwd@localhost/config' self.db = Katagawa(dsn) self.bot = bot self.bot.loop.create_task(self.db.connect()) def __del__(self): self.bot.loop.create_task(self.db.close()) async def get(self, key): async with self.db.get_session() as s: query = s.select(Guild).where(Guild.id == key) guild = await query.first() return {k.name: v for k, v in guild.to_dict().items()} async def set(self, gid, **kwargs): async with self.db.get_session() as s: s.merge(Guild(id=gid, **kwargs)) async def add(self, gid, **kwargs): async with self.db.get_session() as s: s.add(Guild(id=gid, **kwargs)) async def remove(self, gid): async with self.db.get_session() as s: await s.execute(f'delete from guild where id = {gid}') Change set to merge correctlyfrom katagawa.kg import Katagawa from schema.config import Guild class Config: def __init__(self, bot): dsn = f'postgresql://beattie:passwd@localhost/config' self.db = Katagawa(dsn) self.bot = bot self.bot.loop.create_task(self.db.connect()) def __del__(self): self.bot.loop.create_task(self.db.close()) async def get(self, key): async with self.db.get_session() as s: query = s.select(Guild).where(Guild.id == key) guild = await query.first() return {k.name: v for k, v in guild.to_dict().items()} async def set(self, gid, **kwargs): async with self.db.get_session() as s: guild = await s.select(Guild).where(Guild.id == gid).first() for key, value in kwargs.items(): setattr(guild, key, value) s.merge(guild) async def add(self, gid, **kwargs): async with self.db.get_session() as s: s.add(Guild(id=gid, **kwargs)) async def remove(self, gid): async with self.db.get_session() as s: await s.execute(f'delete from guild where id = {gid}')
<commit_before>from katagawa.kg import Katagawa from schema.config import Guild class Config: def __init__(self, bot): dsn = f'postgresql://beattie:passwd@localhost/config' self.db = Katagawa(dsn) self.bot = bot self.bot.loop.create_task(self.db.connect()) def __del__(self): self.bot.loop.create_task(self.db.close()) async def get(self, key): async with self.db.get_session() as s: query = s.select(Guild).where(Guild.id == key) guild = await query.first() return {k.name: v for k, v in guild.to_dict().items()} async def set(self, gid, **kwargs): async with self.db.get_session() as s: s.merge(Guild(id=gid, **kwargs)) async def add(self, gid, **kwargs): async with self.db.get_session() as s: s.add(Guild(id=gid, **kwargs)) async def remove(self, gid): async with self.db.get_session() as s: await s.execute(f'delete from guild where id = {gid}') <commit_msg>Change set to merge correctly<commit_after>from katagawa.kg import Katagawa from schema.config import Guild class Config: def __init__(self, bot): dsn = f'postgresql://beattie:passwd@localhost/config' self.db = Katagawa(dsn) self.bot = bot self.bot.loop.create_task(self.db.connect()) def __del__(self): self.bot.loop.create_task(self.db.close()) async def get(self, key): async with self.db.get_session() as s: query = s.select(Guild).where(Guild.id == key) guild = await query.first() return {k.name: v for k, v in guild.to_dict().items()} async def set(self, gid, **kwargs): async with self.db.get_session() as s: guild = await s.select(Guild).where(Guild.id == gid).first() for key, value in kwargs.items(): setattr(guild, key, value) s.merge(guild) async def add(self, gid, **kwargs): async with self.db.get_session() as s: s.add(Guild(id=gid, **kwargs)) async def remove(self, gid): async with self.db.get_session() as s: await s.execute(f'delete from guild where id = {gid}')
dbda7d542c2f9353a57b63b7508afbf9bc2397cd
examples/address_validation.py
examples/address_validation.py
#!/usr/bin/env python """ This example shows how to validate addresses. Note that the validation class can handle up to 100 addresses for validation. """ import logging import binascii from example_config import CONFIG_OBJ from fedex.services.address_validation_service import FedexAddressValidationRequest # Set this to the INFO level to see the response from Fedex printed in stdout. logging.basicConfig(level=logging.INFO) # This is the object that will be handling our tracking request. # We're using the FedexConfig object from example_config.py in this dir. address = FedexAddressValidationRequest(CONFIG_OBJ) address1 = address.create_wsdl_object_of_type('AddressToValidate') address1.CompanyName = 'International Paper' address1.Address.StreetLines = ['155 Old Greenville Hwy', 'Suite 103'] address1.Address.City = 'Clemson' address1.Address.StateOrProvinceCode = 'SC' address1.Address.PostalCode = 29631 address1.Address.CountryCode = 'US' address1.Address.Residential = False address.add_address(address1) address.send_request() print address.response
#!/usr/bin/env python """ This example shows how to validate addresses. Note that the validation class can handle up to 100 addresses for validation. """ import logging from example_config import CONFIG_OBJ from fedex.services.address_validation_service import FedexAddressValidationRequest # Set this to the INFO level to see the response from Fedex printed in stdout. logging.basicConfig(level=logging.INFO) # This is the object that will be handling our tracking request. # We're using the FedexConfig object from example_config.py in this dir. address = FedexAddressValidationRequest(CONFIG_OBJ) address1 = address.create_wsdl_object_of_type('AddressToValidate') address1.CompanyName = 'International Paper' address1.Address.StreetLines = ['155 Old Greenville Hwy', 'Suite 103'] address1.Address.City = 'Clemson' address1.Address.StateOrProvinceCode = 'SC' address1.Address.PostalCode = 29631 address1.Address.CountryCode = 'US' address1.Address.Residential = False address.add_address(address1) address.send_request() print address.response
Remove un-necessary binascii module import.
Remove un-necessary binascii module import.
Python
bsd-3-clause
gtaylor/python-fedex,gtaylor/python-fedex,python-fedex-devs/python-fedex,AxiaCore/python-fedex,obr/python-fedex,python-fedex-devs/python-fedex,python-fedex-devs/python-fedex,obr/python-fedex,gtaylor/python-fedex,gtaylor/python-fedex,python-fedex-devs/python-fedex,AxiaCore/python-fedex
#!/usr/bin/env python """ This example shows how to validate addresses. Note that the validation class can handle up to 100 addresses for validation. """ import logging import binascii from example_config import CONFIG_OBJ from fedex.services.address_validation_service import FedexAddressValidationRequest # Set this to the INFO level to see the response from Fedex printed in stdout. logging.basicConfig(level=logging.INFO) # This is the object that will be handling our tracking request. # We're using the FedexConfig object from example_config.py in this dir. address = FedexAddressValidationRequest(CONFIG_OBJ) address1 = address.create_wsdl_object_of_type('AddressToValidate') address1.CompanyName = 'International Paper' address1.Address.StreetLines = ['155 Old Greenville Hwy', 'Suite 103'] address1.Address.City = 'Clemson' address1.Address.StateOrProvinceCode = 'SC' address1.Address.PostalCode = 29631 address1.Address.CountryCode = 'US' address1.Address.Residential = False address.add_address(address1) address.send_request() print address.response Remove un-necessary binascii module import.
#!/usr/bin/env python """ This example shows how to validate addresses. Note that the validation class can handle up to 100 addresses for validation. """ import logging from example_config import CONFIG_OBJ from fedex.services.address_validation_service import FedexAddressValidationRequest # Set this to the INFO level to see the response from Fedex printed in stdout. logging.basicConfig(level=logging.INFO) # This is the object that will be handling our tracking request. # We're using the FedexConfig object from example_config.py in this dir. address = FedexAddressValidationRequest(CONFIG_OBJ) address1 = address.create_wsdl_object_of_type('AddressToValidate') address1.CompanyName = 'International Paper' address1.Address.StreetLines = ['155 Old Greenville Hwy', 'Suite 103'] address1.Address.City = 'Clemson' address1.Address.StateOrProvinceCode = 'SC' address1.Address.PostalCode = 29631 address1.Address.CountryCode = 'US' address1.Address.Residential = False address.add_address(address1) address.send_request() print address.response
<commit_before>#!/usr/bin/env python """ This example shows how to validate addresses. Note that the validation class can handle up to 100 addresses for validation. """ import logging import binascii from example_config import CONFIG_OBJ from fedex.services.address_validation_service import FedexAddressValidationRequest # Set this to the INFO level to see the response from Fedex printed in stdout. logging.basicConfig(level=logging.INFO) # This is the object that will be handling our tracking request. # We're using the FedexConfig object from example_config.py in this dir. address = FedexAddressValidationRequest(CONFIG_OBJ) address1 = address.create_wsdl_object_of_type('AddressToValidate') address1.CompanyName = 'International Paper' address1.Address.StreetLines = ['155 Old Greenville Hwy', 'Suite 103'] address1.Address.City = 'Clemson' address1.Address.StateOrProvinceCode = 'SC' address1.Address.PostalCode = 29631 address1.Address.CountryCode = 'US' address1.Address.Residential = False address.add_address(address1) address.send_request() print address.response <commit_msg>Remove un-necessary binascii module import.<commit_after>
#!/usr/bin/env python """ This example shows how to validate addresses. Note that the validation class can handle up to 100 addresses for validation. """ import logging from example_config import CONFIG_OBJ from fedex.services.address_validation_service import FedexAddressValidationRequest # Set this to the INFO level to see the response from Fedex printed in stdout. logging.basicConfig(level=logging.INFO) # This is the object that will be handling our tracking request. # We're using the FedexConfig object from example_config.py in this dir. address = FedexAddressValidationRequest(CONFIG_OBJ) address1 = address.create_wsdl_object_of_type('AddressToValidate') address1.CompanyName = 'International Paper' address1.Address.StreetLines = ['155 Old Greenville Hwy', 'Suite 103'] address1.Address.City = 'Clemson' address1.Address.StateOrProvinceCode = 'SC' address1.Address.PostalCode = 29631 address1.Address.CountryCode = 'US' address1.Address.Residential = False address.add_address(address1) address.send_request() print address.response
#!/usr/bin/env python """ This example shows how to validate addresses. Note that the validation class can handle up to 100 addresses for validation. """ import logging import binascii from example_config import CONFIG_OBJ from fedex.services.address_validation_service import FedexAddressValidationRequest # Set this to the INFO level to see the response from Fedex printed in stdout. logging.basicConfig(level=logging.INFO) # This is the object that will be handling our tracking request. # We're using the FedexConfig object from example_config.py in this dir. address = FedexAddressValidationRequest(CONFIG_OBJ) address1 = address.create_wsdl_object_of_type('AddressToValidate') address1.CompanyName = 'International Paper' address1.Address.StreetLines = ['155 Old Greenville Hwy', 'Suite 103'] address1.Address.City = 'Clemson' address1.Address.StateOrProvinceCode = 'SC' address1.Address.PostalCode = 29631 address1.Address.CountryCode = 'US' address1.Address.Residential = False address.add_address(address1) address.send_request() print address.response Remove un-necessary binascii module import.#!/usr/bin/env python """ This example shows how to validate addresses. Note that the validation class can handle up to 100 addresses for validation. """ import logging from example_config import CONFIG_OBJ from fedex.services.address_validation_service import FedexAddressValidationRequest # Set this to the INFO level to see the response from Fedex printed in stdout. logging.basicConfig(level=logging.INFO) # This is the object that will be handling our tracking request. # We're using the FedexConfig object from example_config.py in this dir. address = FedexAddressValidationRequest(CONFIG_OBJ) address1 = address.create_wsdl_object_of_type('AddressToValidate') address1.CompanyName = 'International Paper' address1.Address.StreetLines = ['155 Old Greenville Hwy', 'Suite 103'] address1.Address.City = 'Clemson' address1.Address.StateOrProvinceCode = 'SC' address1.Address.PostalCode = 29631 address1.Address.CountryCode = 'US' address1.Address.Residential = False address.add_address(address1) address.send_request() print address.response
<commit_before>#!/usr/bin/env python """ This example shows how to validate addresses. Note that the validation class can handle up to 100 addresses for validation. """ import logging import binascii from example_config import CONFIG_OBJ from fedex.services.address_validation_service import FedexAddressValidationRequest # Set this to the INFO level to see the response from Fedex printed in stdout. logging.basicConfig(level=logging.INFO) # This is the object that will be handling our tracking request. # We're using the FedexConfig object from example_config.py in this dir. address = FedexAddressValidationRequest(CONFIG_OBJ) address1 = address.create_wsdl_object_of_type('AddressToValidate') address1.CompanyName = 'International Paper' address1.Address.StreetLines = ['155 Old Greenville Hwy', 'Suite 103'] address1.Address.City = 'Clemson' address1.Address.StateOrProvinceCode = 'SC' address1.Address.PostalCode = 29631 address1.Address.CountryCode = 'US' address1.Address.Residential = False address.add_address(address1) address.send_request() print address.response <commit_msg>Remove un-necessary binascii module import.<commit_after>#!/usr/bin/env python """ This example shows how to validate addresses. Note that the validation class can handle up to 100 addresses for validation. """ import logging from example_config import CONFIG_OBJ from fedex.services.address_validation_service import FedexAddressValidationRequest # Set this to the INFO level to see the response from Fedex printed in stdout. logging.basicConfig(level=logging.INFO) # This is the object that will be handling our tracking request. # We're using the FedexConfig object from example_config.py in this dir. address = FedexAddressValidationRequest(CONFIG_OBJ) address1 = address.create_wsdl_object_of_type('AddressToValidate') address1.CompanyName = 'International Paper' address1.Address.StreetLines = ['155 Old Greenville Hwy', 'Suite 103'] address1.Address.City = 'Clemson' address1.Address.StateOrProvinceCode = 'SC' address1.Address.PostalCode = 29631 address1.Address.CountryCode = 'US' address1.Address.Residential = False address.add_address(address1) address.send_request() print address.response
0fe2cf6b03c6eb11a7cabed9302a1aa312a33b31
django/projects/mysite/run-gevent.py
django/projects/mysite/run-gevent.py
#!/usr/bin/env python # Import gevent monkey and patch everything from gevent import monkey monkey.patch_all(httplib=True) # Import the rest from django.core.handlers.wsgi import WSGIHandler as DjangoWSGIApp from django.core.management import setup_environ from gevent.wsgi import WSGIServer import sys import settings setup_environ(settings) def runserver(): # Create the server application = DjangoWSGIApp() address = "127.0.0.1", 8080 server = WSGIServer( address, application ) # Run the server try: server.serve_forever() except KeyboardInterrupt: server.stop() sys.exit(0) if __name__ == '__main__': runserver()
#!/usr/bin/env python # Import gevent monkey and patch everything from gevent import monkey monkey.patch_all(httplib=True) # Import the rest from django.core.handlers.wsgi import WSGIHandler as DjangoWSGIApp from django.core.management import setup_environ from gevent.wsgi import WSGIServer import sys import settings setup_environ(settings) # Configure host and port for the WSGI server host = getattr(settings, 'WSGI_HOST', '127.0.0.1') port = getattr(settings, 'WSGI_PORT', 8080) def runserver(): # Create the server application = DjangoWSGIApp() address = host, port server = WSGIServer( address, application ) # Run the server try: server.serve_forever() except KeyboardInterrupt: server.stop() sys.exit(0) if __name__ == '__main__': runserver()
Allow host/port config in settings file for gevent run script
Allow host/port config in settings file for gevent run script
Python
agpl-3.0
fzadow/CATMAID,htem/CATMAID,htem/CATMAID,fzadow/CATMAID,htem/CATMAID,fzadow/CATMAID,fzadow/CATMAID,htem/CATMAID
#!/usr/bin/env python # Import gevent monkey and patch everything from gevent import monkey monkey.patch_all(httplib=True) # Import the rest from django.core.handlers.wsgi import WSGIHandler as DjangoWSGIApp from django.core.management import setup_environ from gevent.wsgi import WSGIServer import sys import settings setup_environ(settings) def runserver(): # Create the server application = DjangoWSGIApp() address = "127.0.0.1", 8080 server = WSGIServer( address, application ) # Run the server try: server.serve_forever() except KeyboardInterrupt: server.stop() sys.exit(0) if __name__ == '__main__': runserver() Allow host/port config in settings file for gevent run script
#!/usr/bin/env python # Import gevent monkey and patch everything from gevent import monkey monkey.patch_all(httplib=True) # Import the rest from django.core.handlers.wsgi import WSGIHandler as DjangoWSGIApp from django.core.management import setup_environ from gevent.wsgi import WSGIServer import sys import settings setup_environ(settings) # Configure host and port for the WSGI server host = getattr(settings, 'WSGI_HOST', '127.0.0.1') port = getattr(settings, 'WSGI_PORT', 8080) def runserver(): # Create the server application = DjangoWSGIApp() address = host, port server = WSGIServer( address, application ) # Run the server try: server.serve_forever() except KeyboardInterrupt: server.stop() sys.exit(0) if __name__ == '__main__': runserver()
<commit_before>#!/usr/bin/env python # Import gevent monkey and patch everything from gevent import monkey monkey.patch_all(httplib=True) # Import the rest from django.core.handlers.wsgi import WSGIHandler as DjangoWSGIApp from django.core.management import setup_environ from gevent.wsgi import WSGIServer import sys import settings setup_environ(settings) def runserver(): # Create the server application = DjangoWSGIApp() address = "127.0.0.1", 8080 server = WSGIServer( address, application ) # Run the server try: server.serve_forever() except KeyboardInterrupt: server.stop() sys.exit(0) if __name__ == '__main__': runserver() <commit_msg>Allow host/port config in settings file for gevent run script<commit_after>
#!/usr/bin/env python # Import gevent monkey and patch everything from gevent import monkey monkey.patch_all(httplib=True) # Import the rest from django.core.handlers.wsgi import WSGIHandler as DjangoWSGIApp from django.core.management import setup_environ from gevent.wsgi import WSGIServer import sys import settings setup_environ(settings) # Configure host and port for the WSGI server host = getattr(settings, 'WSGI_HOST', '127.0.0.1') port = getattr(settings, 'WSGI_PORT', 8080) def runserver(): # Create the server application = DjangoWSGIApp() address = host, port server = WSGIServer( address, application ) # Run the server try: server.serve_forever() except KeyboardInterrupt: server.stop() sys.exit(0) if __name__ == '__main__': runserver()
#!/usr/bin/env python # Import gevent monkey and patch everything from gevent import monkey monkey.patch_all(httplib=True) # Import the rest from django.core.handlers.wsgi import WSGIHandler as DjangoWSGIApp from django.core.management import setup_environ from gevent.wsgi import WSGIServer import sys import settings setup_environ(settings) def runserver(): # Create the server application = DjangoWSGIApp() address = "127.0.0.1", 8080 server = WSGIServer( address, application ) # Run the server try: server.serve_forever() except KeyboardInterrupt: server.stop() sys.exit(0) if __name__ == '__main__': runserver() Allow host/port config in settings file for gevent run script#!/usr/bin/env python # Import gevent monkey and patch everything from gevent import monkey monkey.patch_all(httplib=True) # Import the rest from django.core.handlers.wsgi import WSGIHandler as DjangoWSGIApp from django.core.management import setup_environ from gevent.wsgi import WSGIServer import sys import settings setup_environ(settings) # Configure host and port for the WSGI server host = getattr(settings, 'WSGI_HOST', '127.0.0.1') port = getattr(settings, 'WSGI_PORT', 8080) def runserver(): # Create the server application = DjangoWSGIApp() address = host, port server = WSGIServer( address, application ) # Run the server try: server.serve_forever() except KeyboardInterrupt: server.stop() sys.exit(0) if __name__ == '__main__': runserver()
<commit_before>#!/usr/bin/env python # Import gevent monkey and patch everything from gevent import monkey monkey.patch_all(httplib=True) # Import the rest from django.core.handlers.wsgi import WSGIHandler as DjangoWSGIApp from django.core.management import setup_environ from gevent.wsgi import WSGIServer import sys import settings setup_environ(settings) def runserver(): # Create the server application = DjangoWSGIApp() address = "127.0.0.1", 8080 server = WSGIServer( address, application ) # Run the server try: server.serve_forever() except KeyboardInterrupt: server.stop() sys.exit(0) if __name__ == '__main__': runserver() <commit_msg>Allow host/port config in settings file for gevent run script<commit_after>#!/usr/bin/env python # Import gevent monkey and patch everything from gevent import monkey monkey.patch_all(httplib=True) # Import the rest from django.core.handlers.wsgi import WSGIHandler as DjangoWSGIApp from django.core.management import setup_environ from gevent.wsgi import WSGIServer import sys import settings setup_environ(settings) # Configure host and port for the WSGI server host = getattr(settings, 'WSGI_HOST', '127.0.0.1') port = getattr(settings, 'WSGI_PORT', 8080) def runserver(): # Create the server application = DjangoWSGIApp() address = host, port server = WSGIServer( address, application ) # Run the server try: server.serve_forever() except KeyboardInterrupt: server.stop() sys.exit(0) if __name__ == '__main__': runserver()
b1bb08a8ee246774b43e521e8f754cdcc88c418b
gasistafelice/gas/management.py
gasistafelice/gas/management.py
from django.db.models.signals import post_syncdb from gasistafelice.gas.workflow_data import workflow_dict def init_workflows(app, created_models, verbosity, **kwargs): app_label = app.__name__.split('.')[-2] if app_label == 'workflows' and created_models: # `worklows` app was syncronized for the first time # now that all necessary tables are in the DB, we can register our workflows for name, w in workflow_dict.items(): w.register_workflow() if verbosity == 2: # give some feedback to the user print "Workflow %s was successfully registered." % name return post_syncdb.connect(init_workflows)
from django.db.models.signals import post_syncdb from gasistafelice.gas.workflow_data import workflow_dict def init_workflows(app, created_models, verbosity, **kwargs): app_label = app.__name__.split('.')[-2] if app_label == 'workflows' and "Workflow" in created_models: # `worklows` app was syncronized for the first time # now that all necessary tables are in the DB, we can register our workflows for name, w in workflow_dict.items(): w.register_workflow() if verbosity == 2: # give some feedback to the user print "Workflow %s was successfully registered." % name return post_syncdb.connect(init_workflows)
Fix in post_syncdb workflow registration
Fix in post_syncdb workflow registration
Python
agpl-3.0
michelesr/gasistafelice,befair/gasistafelice,matteo88/gasistafelice,matteo88/gasistafelice,OrlyMar/gasistafelice,kobe25/gasistafelice,michelesr/gasistafelice,kobe25/gasistafelice,befair/gasistafelice,michelesr/gasistafelice,matteo88/gasistafelice,kobe25/gasistafelice,feroda/gasistafelice,OrlyMar/gasistafelice,michelesr/gasistafelice,OrlyMar/gasistafelice,feroda/gasistafelice,OrlyMar/gasistafelice,kobe25/gasistafelice,matteo88/gasistafelice,befair/gasistafelice,feroda/gasistafelice,befair/gasistafelice,feroda/gasistafelice
from django.db.models.signals import post_syncdb from gasistafelice.gas.workflow_data import workflow_dict def init_workflows(app, created_models, verbosity, **kwargs): app_label = app.__name__.split('.')[-2] if app_label == 'workflows' and created_models: # `worklows` app was syncronized for the first time # now that all necessary tables are in the DB, we can register our workflows for name, w in workflow_dict.items(): w.register_workflow() if verbosity == 2: # give some feedback to the user print "Workflow %s was successfully registered." % name return post_syncdb.connect(init_workflows) Fix in post_syncdb workflow registration
from django.db.models.signals import post_syncdb from gasistafelice.gas.workflow_data import workflow_dict def init_workflows(app, created_models, verbosity, **kwargs): app_label = app.__name__.split('.')[-2] if app_label == 'workflows' and "Workflow" in created_models: # `worklows` app was syncronized for the first time # now that all necessary tables are in the DB, we can register our workflows for name, w in workflow_dict.items(): w.register_workflow() if verbosity == 2: # give some feedback to the user print "Workflow %s was successfully registered." % name return post_syncdb.connect(init_workflows)
<commit_before>from django.db.models.signals import post_syncdb from gasistafelice.gas.workflow_data import workflow_dict def init_workflows(app, created_models, verbosity, **kwargs): app_label = app.__name__.split('.')[-2] if app_label == 'workflows' and created_models: # `worklows` app was syncronized for the first time # now that all necessary tables are in the DB, we can register our workflows for name, w in workflow_dict.items(): w.register_workflow() if verbosity == 2: # give some feedback to the user print "Workflow %s was successfully registered." % name return post_syncdb.connect(init_workflows) <commit_msg>Fix in post_syncdb workflow registration<commit_after>
from django.db.models.signals import post_syncdb from gasistafelice.gas.workflow_data import workflow_dict def init_workflows(app, created_models, verbosity, **kwargs): app_label = app.__name__.split('.')[-2] if app_label == 'workflows' and "Workflow" in created_models: # `worklows` app was syncronized for the first time # now that all necessary tables are in the DB, we can register our workflows for name, w in workflow_dict.items(): w.register_workflow() if verbosity == 2: # give some feedback to the user print "Workflow %s was successfully registered." % name return post_syncdb.connect(init_workflows)
from django.db.models.signals import post_syncdb from gasistafelice.gas.workflow_data import workflow_dict def init_workflows(app, created_models, verbosity, **kwargs): app_label = app.__name__.split('.')[-2] if app_label == 'workflows' and created_models: # `worklows` app was syncronized for the first time # now that all necessary tables are in the DB, we can register our workflows for name, w in workflow_dict.items(): w.register_workflow() if verbosity == 2: # give some feedback to the user print "Workflow %s was successfully registered." % name return post_syncdb.connect(init_workflows) Fix in post_syncdb workflow registrationfrom django.db.models.signals import post_syncdb from gasistafelice.gas.workflow_data import workflow_dict def init_workflows(app, created_models, verbosity, **kwargs): app_label = app.__name__.split('.')[-2] if app_label == 'workflows' and "Workflow" in created_models: # `worklows` app was syncronized for the first time # now that all necessary tables are in the DB, we can register our workflows for name, w in workflow_dict.items(): w.register_workflow() if verbosity == 2: # give some feedback to the user print "Workflow %s was successfully registered." % name return post_syncdb.connect(init_workflows)
<commit_before>from django.db.models.signals import post_syncdb from gasistafelice.gas.workflow_data import workflow_dict def init_workflows(app, created_models, verbosity, **kwargs): app_label = app.__name__.split('.')[-2] if app_label == 'workflows' and created_models: # `worklows` app was syncronized for the first time # now that all necessary tables are in the DB, we can register our workflows for name, w in workflow_dict.items(): w.register_workflow() if verbosity == 2: # give some feedback to the user print "Workflow %s was successfully registered." % name return post_syncdb.connect(init_workflows) <commit_msg>Fix in post_syncdb workflow registration<commit_after>from django.db.models.signals import post_syncdb from gasistafelice.gas.workflow_data import workflow_dict def init_workflows(app, created_models, verbosity, **kwargs): app_label = app.__name__.split('.')[-2] if app_label == 'workflows' and "Workflow" in created_models: # `worklows` app was syncronized for the first time # now that all necessary tables are in the DB, we can register our workflows for name, w in workflow_dict.items(): w.register_workflow() if verbosity == 2: # give some feedback to the user print "Workflow %s was successfully registered." % name return post_syncdb.connect(init_workflows)
7080057c9abc6e455222e057315055b3e9965cc9
runtests.py
runtests.py
#!/usr/bin/env python import django from django.conf import settings from django.core.management import call_command settings.configure( DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', } }, ALLOWED_HOSTS=[ 'testserver', ], INSTALLED_APPS=[ 'django.contrib.auth', 'django.contrib.contenttypes', 'permissions', 'permissions.tests', ], MIDDLEWARE_CLASSES=[], PERMISSIONS={ 'allow_staff': False, }, ROOT_URLCONF='permissions.tests.urls', TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, }], TEST_RUNNER='django.test.runner.DiscoverRunner', ) if django.VERSION[:2] >= (1, 7): from django import setup else: setup = lambda: None setup() call_command("test")
#!/usr/bin/env python import django from django.conf import settings from django.core.management import call_command TEST_SETTINGS = { 'DATABASES': { 'default': { 'ENGINE': 'django.db.backends.sqlite3', } }, 'ALLOWED_HOSTS': [ 'testserver', ], 'INSTALLED_APPS': [ 'django.contrib.auth', 'django.contrib.contenttypes', 'permissions', 'permissions.tests', ], 'PERMISSIONS': { 'allow_staff': False, }, 'ROOT_URLCONF': 'permissions.tests.urls', 'TEMPLATES': [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, }], 'TEST_RUNNER': 'django.test.runner.DiscoverRunner', } if django.VERSION < (1, 10): TEST_SETTINGS['MIDDLEWARE_CLASSES'] = [] else: TEST_SETTINGS['MIDDLEWARE'] = [] settings.configure(**TEST_SETTINGS) if django.VERSION[:2] >= (1, 7): from django import setup else: setup = lambda: None setup() call_command("test")
Set middleware setting according to Django version in test settings
Set middleware setting according to Django version in test settings Django 1.10 introduced new-style middleware and the corresponding MIDDLEWARE setting and deprecated MIDDLEWARE_CLASSES. The latter is ignored on Django 2.
Python
mit
wylee/django-perms
#!/usr/bin/env python import django from django.conf import settings from django.core.management import call_command settings.configure( DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', } }, ALLOWED_HOSTS=[ 'testserver', ], INSTALLED_APPS=[ 'django.contrib.auth', 'django.contrib.contenttypes', 'permissions', 'permissions.tests', ], MIDDLEWARE_CLASSES=[], PERMISSIONS={ 'allow_staff': False, }, ROOT_URLCONF='permissions.tests.urls', TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, }], TEST_RUNNER='django.test.runner.DiscoverRunner', ) if django.VERSION[:2] >= (1, 7): from django import setup else: setup = lambda: None setup() call_command("test") Set middleware setting according to Django version in test settings Django 1.10 introduced new-style middleware and the corresponding MIDDLEWARE setting and deprecated MIDDLEWARE_CLASSES. The latter is ignored on Django 2.
#!/usr/bin/env python import django from django.conf import settings from django.core.management import call_command TEST_SETTINGS = { 'DATABASES': { 'default': { 'ENGINE': 'django.db.backends.sqlite3', } }, 'ALLOWED_HOSTS': [ 'testserver', ], 'INSTALLED_APPS': [ 'django.contrib.auth', 'django.contrib.contenttypes', 'permissions', 'permissions.tests', ], 'PERMISSIONS': { 'allow_staff': False, }, 'ROOT_URLCONF': 'permissions.tests.urls', 'TEMPLATES': [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, }], 'TEST_RUNNER': 'django.test.runner.DiscoverRunner', } if django.VERSION < (1, 10): TEST_SETTINGS['MIDDLEWARE_CLASSES'] = [] else: TEST_SETTINGS['MIDDLEWARE'] = [] settings.configure(**TEST_SETTINGS) if django.VERSION[:2] >= (1, 7): from django import setup else: setup = lambda: None setup() call_command("test")
<commit_before>#!/usr/bin/env python import django from django.conf import settings from django.core.management import call_command settings.configure( DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', } }, ALLOWED_HOSTS=[ 'testserver', ], INSTALLED_APPS=[ 'django.contrib.auth', 'django.contrib.contenttypes', 'permissions', 'permissions.tests', ], MIDDLEWARE_CLASSES=[], PERMISSIONS={ 'allow_staff': False, }, ROOT_URLCONF='permissions.tests.urls', TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, }], TEST_RUNNER='django.test.runner.DiscoverRunner', ) if django.VERSION[:2] >= (1, 7): from django import setup else: setup = lambda: None setup() call_command("test") <commit_msg>Set middleware setting according to Django version in test settings Django 1.10 introduced new-style middleware and the corresponding MIDDLEWARE setting and deprecated MIDDLEWARE_CLASSES. The latter is ignored on Django 2.<commit_after>
#!/usr/bin/env python import django from django.conf import settings from django.core.management import call_command TEST_SETTINGS = { 'DATABASES': { 'default': { 'ENGINE': 'django.db.backends.sqlite3', } }, 'ALLOWED_HOSTS': [ 'testserver', ], 'INSTALLED_APPS': [ 'django.contrib.auth', 'django.contrib.contenttypes', 'permissions', 'permissions.tests', ], 'PERMISSIONS': { 'allow_staff': False, }, 'ROOT_URLCONF': 'permissions.tests.urls', 'TEMPLATES': [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, }], 'TEST_RUNNER': 'django.test.runner.DiscoverRunner', } if django.VERSION < (1, 10): TEST_SETTINGS['MIDDLEWARE_CLASSES'] = [] else: TEST_SETTINGS['MIDDLEWARE'] = [] settings.configure(**TEST_SETTINGS) if django.VERSION[:2] >= (1, 7): from django import setup else: setup = lambda: None setup() call_command("test")
#!/usr/bin/env python import django from django.conf import settings from django.core.management import call_command settings.configure( DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', } }, ALLOWED_HOSTS=[ 'testserver', ], INSTALLED_APPS=[ 'django.contrib.auth', 'django.contrib.contenttypes', 'permissions', 'permissions.tests', ], MIDDLEWARE_CLASSES=[], PERMISSIONS={ 'allow_staff': False, }, ROOT_URLCONF='permissions.tests.urls', TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, }], TEST_RUNNER='django.test.runner.DiscoverRunner', ) if django.VERSION[:2] >= (1, 7): from django import setup else: setup = lambda: None setup() call_command("test") Set middleware setting according to Django version in test settings Django 1.10 introduced new-style middleware and the corresponding MIDDLEWARE setting and deprecated MIDDLEWARE_CLASSES. The latter is ignored on Django 2.#!/usr/bin/env python import django from django.conf import settings from django.core.management import call_command TEST_SETTINGS = { 'DATABASES': { 'default': { 'ENGINE': 'django.db.backends.sqlite3', } }, 'ALLOWED_HOSTS': [ 'testserver', ], 'INSTALLED_APPS': [ 'django.contrib.auth', 'django.contrib.contenttypes', 'permissions', 'permissions.tests', ], 'PERMISSIONS': { 'allow_staff': False, }, 'ROOT_URLCONF': 'permissions.tests.urls', 'TEMPLATES': [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, }], 'TEST_RUNNER': 'django.test.runner.DiscoverRunner', } if django.VERSION < (1, 10): TEST_SETTINGS['MIDDLEWARE_CLASSES'] = [] else: TEST_SETTINGS['MIDDLEWARE'] = [] settings.configure(**TEST_SETTINGS) if django.VERSION[:2] >= (1, 7): from django import setup else: setup = lambda: None setup() call_command("test")
<commit_before>#!/usr/bin/env python import django from django.conf import settings from django.core.management import call_command settings.configure( DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', } }, ALLOWED_HOSTS=[ 'testserver', ], INSTALLED_APPS=[ 'django.contrib.auth', 'django.contrib.contenttypes', 'permissions', 'permissions.tests', ], MIDDLEWARE_CLASSES=[], PERMISSIONS={ 'allow_staff': False, }, ROOT_URLCONF='permissions.tests.urls', TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, }], TEST_RUNNER='django.test.runner.DiscoverRunner', ) if django.VERSION[:2] >= (1, 7): from django import setup else: setup = lambda: None setup() call_command("test") <commit_msg>Set middleware setting according to Django version in test settings Django 1.10 introduced new-style middleware and the corresponding MIDDLEWARE setting and deprecated MIDDLEWARE_CLASSES. The latter is ignored on Django 2.<commit_after>#!/usr/bin/env python import django from django.conf import settings from django.core.management import call_command TEST_SETTINGS = { 'DATABASES': { 'default': { 'ENGINE': 'django.db.backends.sqlite3', } }, 'ALLOWED_HOSTS': [ 'testserver', ], 'INSTALLED_APPS': [ 'django.contrib.auth', 'django.contrib.contenttypes', 'permissions', 'permissions.tests', ], 'PERMISSIONS': { 'allow_staff': False, }, 'ROOT_URLCONF': 'permissions.tests.urls', 'TEMPLATES': [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, }], 'TEST_RUNNER': 'django.test.runner.DiscoverRunner', } if django.VERSION < (1, 10): TEST_SETTINGS['MIDDLEWARE_CLASSES'] = [] else: TEST_SETTINGS['MIDDLEWARE'] = [] settings.configure(**TEST_SETTINGS) if django.VERSION[:2] >= (1, 7): from django import setup else: setup = lambda: None setup() call_command("test")
4dbc42b0516578d59b315b1ac1fa6ccf3e262f1e
seo/escaped_fragment/app.py
seo/escaped_fragment/app.py
# Copyright (C) Ivan Kravets <me@ikravets.com> # See LICENSE for details. from subprocess import check_output, CalledProcessError from urllib import unquote def application(env, start_response): status = "200 OK" response = "" qs = env.get("QUERY_STRING", None) if not qs or not qs.startswith("_escaped_fragment_="): status = "500 Internal Server Error" else: url = "http://platformio.org/#!" + unquote(qs[19:]) try: response = get_webcontent(url) if "404 Not Found" in response: status = "404 Not Found" except Exception: status = "500 Internal Server Error" start_response(status, [("Content-Type", "text/html"), ("Content-Length", str(len(response)))]) return response def get_webcontent(url): retrynums = 0 while retrynums < 5: try: response = check_output([ "phantomjs", "--disk-cache=true", "--load-images=false", "crawler.js", url ]) if 'class="ng-scope"' not in response: raise CalledProcessError() return response except CalledProcessError: retrynums += 1 raise Exception("Could not retrieve content from %s" % url)
# Copyright (C) Ivan Kravets <me@ikravets.com> # See LICENSE for details. from subprocess import check_output, CalledProcessError from urllib import unquote def application(env, start_response): status = "200 OK" response = "" qs = env.get("QUERY_STRING", None) if not qs or not qs.startswith("_escaped_fragment_="): status = "500 Internal Server Error" else: url = "http://platformio.org/#!" + unquote(qs[19:]) try: response = get_webcontent(url) if "404 Not Found" in response: status = "404 Not Found" except Exception: status = "500 Internal Server Error" start_response(status, [("Content-Type", "text/html"), ("Content-Length", str(len(response)))]) return response def get_webcontent(url): retrynums = 0 while retrynums < 5: try: response = check_output([ "phantomjs", "--disk-cache=true", "--load-images=false", "crawler.js", url ]) if 'ng-view=' not in response: raise CalledProcessError() return response except CalledProcessError: retrynums += 1 raise Exception("Could not retrieve content from %s" % url)
Fix broken content from PhJS
Fix broken content from PhJS
Python
apache-2.0
platformio/platformio-web,orgkhnargh/platformio-web,orgkhnargh/platformio-web,orgkhnargh/platformio-web,platformio/platformio-web
# Copyright (C) Ivan Kravets <me@ikravets.com> # See LICENSE for details. from subprocess import check_output, CalledProcessError from urllib import unquote def application(env, start_response): status = "200 OK" response = "" qs = env.get("QUERY_STRING", None) if not qs or not qs.startswith("_escaped_fragment_="): status = "500 Internal Server Error" else: url = "http://platformio.org/#!" + unquote(qs[19:]) try: response = get_webcontent(url) if "404 Not Found" in response: status = "404 Not Found" except Exception: status = "500 Internal Server Error" start_response(status, [("Content-Type", "text/html"), ("Content-Length", str(len(response)))]) return response def get_webcontent(url): retrynums = 0 while retrynums < 5: try: response = check_output([ "phantomjs", "--disk-cache=true", "--load-images=false", "crawler.js", url ]) if 'class="ng-scope"' not in response: raise CalledProcessError() return response except CalledProcessError: retrynums += 1 raise Exception("Could not retrieve content from %s" % url) Fix broken content from PhJS
# Copyright (C) Ivan Kravets <me@ikravets.com> # See LICENSE for details. from subprocess import check_output, CalledProcessError from urllib import unquote def application(env, start_response): status = "200 OK" response = "" qs = env.get("QUERY_STRING", None) if not qs or not qs.startswith("_escaped_fragment_="): status = "500 Internal Server Error" else: url = "http://platformio.org/#!" + unquote(qs[19:]) try: response = get_webcontent(url) if "404 Not Found" in response: status = "404 Not Found" except Exception: status = "500 Internal Server Error" start_response(status, [("Content-Type", "text/html"), ("Content-Length", str(len(response)))]) return response def get_webcontent(url): retrynums = 0 while retrynums < 5: try: response = check_output([ "phantomjs", "--disk-cache=true", "--load-images=false", "crawler.js", url ]) if 'ng-view=' not in response: raise CalledProcessError() return response except CalledProcessError: retrynums += 1 raise Exception("Could not retrieve content from %s" % url)
<commit_before># Copyright (C) Ivan Kravets <me@ikravets.com> # See LICENSE for details. from subprocess import check_output, CalledProcessError from urllib import unquote def application(env, start_response): status = "200 OK" response = "" qs = env.get("QUERY_STRING", None) if not qs or not qs.startswith("_escaped_fragment_="): status = "500 Internal Server Error" else: url = "http://platformio.org/#!" + unquote(qs[19:]) try: response = get_webcontent(url) if "404 Not Found" in response: status = "404 Not Found" except Exception: status = "500 Internal Server Error" start_response(status, [("Content-Type", "text/html"), ("Content-Length", str(len(response)))]) return response def get_webcontent(url): retrynums = 0 while retrynums < 5: try: response = check_output([ "phantomjs", "--disk-cache=true", "--load-images=false", "crawler.js", url ]) if 'class="ng-scope"' not in response: raise CalledProcessError() return response except CalledProcessError: retrynums += 1 raise Exception("Could not retrieve content from %s" % url) <commit_msg>Fix broken content from PhJS<commit_after>
# Copyright (C) Ivan Kravets <me@ikravets.com> # See LICENSE for details. from subprocess import check_output, CalledProcessError from urllib import unquote def application(env, start_response): status = "200 OK" response = "" qs = env.get("QUERY_STRING", None) if not qs or not qs.startswith("_escaped_fragment_="): status = "500 Internal Server Error" else: url = "http://platformio.org/#!" + unquote(qs[19:]) try: response = get_webcontent(url) if "404 Not Found" in response: status = "404 Not Found" except Exception: status = "500 Internal Server Error" start_response(status, [("Content-Type", "text/html"), ("Content-Length", str(len(response)))]) return response def get_webcontent(url): retrynums = 0 while retrynums < 5: try: response = check_output([ "phantomjs", "--disk-cache=true", "--load-images=false", "crawler.js", url ]) if 'ng-view=' not in response: raise CalledProcessError() return response except CalledProcessError: retrynums += 1 raise Exception("Could not retrieve content from %s" % url)
# Copyright (C) Ivan Kravets <me@ikravets.com> # See LICENSE for details. from subprocess import check_output, CalledProcessError from urllib import unquote def application(env, start_response): status = "200 OK" response = "" qs = env.get("QUERY_STRING", None) if not qs or not qs.startswith("_escaped_fragment_="): status = "500 Internal Server Error" else: url = "http://platformio.org/#!" + unquote(qs[19:]) try: response = get_webcontent(url) if "404 Not Found" in response: status = "404 Not Found" except Exception: status = "500 Internal Server Error" start_response(status, [("Content-Type", "text/html"), ("Content-Length", str(len(response)))]) return response def get_webcontent(url): retrynums = 0 while retrynums < 5: try: response = check_output([ "phantomjs", "--disk-cache=true", "--load-images=false", "crawler.js", url ]) if 'class="ng-scope"' not in response: raise CalledProcessError() return response except CalledProcessError: retrynums += 1 raise Exception("Could not retrieve content from %s" % url) Fix broken content from PhJS# Copyright (C) Ivan Kravets <me@ikravets.com> # See LICENSE for details. from subprocess import check_output, CalledProcessError from urllib import unquote def application(env, start_response): status = "200 OK" response = "" qs = env.get("QUERY_STRING", None) if not qs or not qs.startswith("_escaped_fragment_="): status = "500 Internal Server Error" else: url = "http://platformio.org/#!" + unquote(qs[19:]) try: response = get_webcontent(url) if "404 Not Found" in response: status = "404 Not Found" except Exception: status = "500 Internal Server Error" start_response(status, [("Content-Type", "text/html"), ("Content-Length", str(len(response)))]) return response def get_webcontent(url): retrynums = 0 while retrynums < 5: try: response = check_output([ "phantomjs", "--disk-cache=true", "--load-images=false", "crawler.js", url ]) if 'ng-view=' not in response: raise CalledProcessError() return response except CalledProcessError: retrynums += 1 raise Exception("Could not retrieve content from %s" % url)
<commit_before># Copyright (C) Ivan Kravets <me@ikravets.com> # See LICENSE for details. from subprocess import check_output, CalledProcessError from urllib import unquote def application(env, start_response): status = "200 OK" response = "" qs = env.get("QUERY_STRING", None) if not qs or not qs.startswith("_escaped_fragment_="): status = "500 Internal Server Error" else: url = "http://platformio.org/#!" + unquote(qs[19:]) try: response = get_webcontent(url) if "404 Not Found" in response: status = "404 Not Found" except Exception: status = "500 Internal Server Error" start_response(status, [("Content-Type", "text/html"), ("Content-Length", str(len(response)))]) return response def get_webcontent(url): retrynums = 0 while retrynums < 5: try: response = check_output([ "phantomjs", "--disk-cache=true", "--load-images=false", "crawler.js", url ]) if 'class="ng-scope"' not in response: raise CalledProcessError() return response except CalledProcessError: retrynums += 1 raise Exception("Could not retrieve content from %s" % url) <commit_msg>Fix broken content from PhJS<commit_after># Copyright (C) Ivan Kravets <me@ikravets.com> # See LICENSE for details. from subprocess import check_output, CalledProcessError from urllib import unquote def application(env, start_response): status = "200 OK" response = "" qs = env.get("QUERY_STRING", None) if not qs or not qs.startswith("_escaped_fragment_="): status = "500 Internal Server Error" else: url = "http://platformio.org/#!" + unquote(qs[19:]) try: response = get_webcontent(url) if "404 Not Found" in response: status = "404 Not Found" except Exception: status = "500 Internal Server Error" start_response(status, [("Content-Type", "text/html"), ("Content-Length", str(len(response)))]) return response def get_webcontent(url): retrynums = 0 while retrynums < 5: try: response = check_output([ "phantomjs", "--disk-cache=true", "--load-images=false", "crawler.js", url ]) if 'ng-view=' not in response: raise CalledProcessError() return response except CalledProcessError: retrynums += 1 raise Exception("Could not retrieve content from %s" % url)
fd061738d025b5371c1415a1f5466bcf5f6476b7
py2deb/config/__init__.py
py2deb/config/__init__.py
import os config_dir = os.path.dirname(os.path.abspath(__file__)) # Destination of built packages. PKG_REPO = '/tmp/'
import os config_dir = os.path.dirname(os.path.abspath(__file__)) # Destination of built packages. if os.getuid() == 0: PKG_REPO = '/var/repos/deb-repo/repository/pl-py2deb' else: PKG_REPO = '/tmp'
Make it work out of the box on the build-server and locally
Make it work out of the box on the build-server and locally
Python
mit
paylogic/py2deb,paylogic/py2deb
import os config_dir = os.path.dirname(os.path.abspath(__file__)) # Destination of built packages. PKG_REPO = '/tmp/' Make it work out of the box on the build-server and locally
import os config_dir = os.path.dirname(os.path.abspath(__file__)) # Destination of built packages. if os.getuid() == 0: PKG_REPO = '/var/repos/deb-repo/repository/pl-py2deb' else: PKG_REPO = '/tmp'
<commit_before>import os config_dir = os.path.dirname(os.path.abspath(__file__)) # Destination of built packages. PKG_REPO = '/tmp/' <commit_msg>Make it work out of the box on the build-server and locally<commit_after>
import os config_dir = os.path.dirname(os.path.abspath(__file__)) # Destination of built packages. if os.getuid() == 0: PKG_REPO = '/var/repos/deb-repo/repository/pl-py2deb' else: PKG_REPO = '/tmp'
import os config_dir = os.path.dirname(os.path.abspath(__file__)) # Destination of built packages. PKG_REPO = '/tmp/' Make it work out of the box on the build-server and locallyimport os config_dir = os.path.dirname(os.path.abspath(__file__)) # Destination of built packages. if os.getuid() == 0: PKG_REPO = '/var/repos/deb-repo/repository/pl-py2deb' else: PKG_REPO = '/tmp'
<commit_before>import os config_dir = os.path.dirname(os.path.abspath(__file__)) # Destination of built packages. PKG_REPO = '/tmp/' <commit_msg>Make it work out of the box on the build-server and locally<commit_after>import os config_dir = os.path.dirname(os.path.abspath(__file__)) # Destination of built packages. if os.getuid() == 0: PKG_REPO = '/var/repos/deb-repo/repository/pl-py2deb' else: PKG_REPO = '/tmp'
7fa074929301d610bdba6186267eb0659aed9dd8
python/app/models/game.py
python/app/models/game.py
from datetime import datetime from sqlalchemy import Table, Column, Integer, String, DateTime, ForeignKey from sqlalchemy.orm import relationship from sqlalchemy.ext.hybrid import hybrid_property, hybrid_method from .base import Base class Game(Base): # Table name __tablename__ = 'sp_games' # # Columns # ------------- id = Column(Integer, primary_key=True) game_id = Column(Integer) game_host = Column(String) start_at = Column(DateTime) end_at = Column(DateTime) # # Relationships # ------------- map_id = Column(Integer, ForeignKey('sp_maps.id')) map = relationship("Map", back_populates="games") players = relationship("Player", back_populates="game", lazy="dynamic") days = relationship("Day", back_populates="game") relations = relationship("Relation", back_populates="game", lazy="dynamic") coalitions = relationship("Coalition", back_populates="game") # # Attributes # ------------- @hybrid_method def day(self): delta = datetime.today() - self.start_at return delta.days # # Representation # ------------- def __repr__(self): return "<Game(%s)>" % (self.id)
from datetime import datetime from sqlalchemy import Table, Column, Integer, String, DateTime, ForeignKey from sqlalchemy.orm import relationship from sqlalchemy.ext.hybrid import hybrid_property, hybrid_method from .base import Base class Game(Base): # Table name __tablename__ = 'sp_games' # # Columns # ------------- id = Column(Integer, primary_key=True) game_id = Column(Integer) game_host = Column(String) start_at = Column(DateTime) end_at = Column(DateTime) # # Relationships # ------------- map_id = Column(Integer, ForeignKey('sp_maps.id')) map = relationship("Map", back_populates="games") players = relationship("Player", back_populates="game", lazy="dynamic") days = relationship("Day", back_populates="game") relations = relationship("Relation", back_populates="game", lazy="dynamic") coalitions = relationship("Coalition", back_populates="game") # # Attributes # ------------- @hybrid_method def day(self): delta = datetime.today() - self.start_at return delta.days + 1 # # Representation # ------------- def __repr__(self): return "<Game(%s)>" % (self.id)
Fix issue with returning wrong date
Fix issue with returning wrong date
Python
apache-2.0
joostsijm/Supremacy1914,joostsijm/Supremacy1914
from datetime import datetime from sqlalchemy import Table, Column, Integer, String, DateTime, ForeignKey from sqlalchemy.orm import relationship from sqlalchemy.ext.hybrid import hybrid_property, hybrid_method from .base import Base class Game(Base): # Table name __tablename__ = 'sp_games' # # Columns # ------------- id = Column(Integer, primary_key=True) game_id = Column(Integer) game_host = Column(String) start_at = Column(DateTime) end_at = Column(DateTime) # # Relationships # ------------- map_id = Column(Integer, ForeignKey('sp_maps.id')) map = relationship("Map", back_populates="games") players = relationship("Player", back_populates="game", lazy="dynamic") days = relationship("Day", back_populates="game") relations = relationship("Relation", back_populates="game", lazy="dynamic") coalitions = relationship("Coalition", back_populates="game") # # Attributes # ------------- @hybrid_method def day(self): delta = datetime.today() - self.start_at return delta.days # # Representation # ------------- def __repr__(self): return "<Game(%s)>" % (self.id) Fix issue with returning wrong date
from datetime import datetime from sqlalchemy import Table, Column, Integer, String, DateTime, ForeignKey from sqlalchemy.orm import relationship from sqlalchemy.ext.hybrid import hybrid_property, hybrid_method from .base import Base class Game(Base): # Table name __tablename__ = 'sp_games' # # Columns # ------------- id = Column(Integer, primary_key=True) game_id = Column(Integer) game_host = Column(String) start_at = Column(DateTime) end_at = Column(DateTime) # # Relationships # ------------- map_id = Column(Integer, ForeignKey('sp_maps.id')) map = relationship("Map", back_populates="games") players = relationship("Player", back_populates="game", lazy="dynamic") days = relationship("Day", back_populates="game") relations = relationship("Relation", back_populates="game", lazy="dynamic") coalitions = relationship("Coalition", back_populates="game") # # Attributes # ------------- @hybrid_method def day(self): delta = datetime.today() - self.start_at return delta.days + 1 # # Representation # ------------- def __repr__(self): return "<Game(%s)>" % (self.id)
<commit_before>from datetime import datetime from sqlalchemy import Table, Column, Integer, String, DateTime, ForeignKey from sqlalchemy.orm import relationship from sqlalchemy.ext.hybrid import hybrid_property, hybrid_method from .base import Base class Game(Base): # Table name __tablename__ = 'sp_games' # # Columns # ------------- id = Column(Integer, primary_key=True) game_id = Column(Integer) game_host = Column(String) start_at = Column(DateTime) end_at = Column(DateTime) # # Relationships # ------------- map_id = Column(Integer, ForeignKey('sp_maps.id')) map = relationship("Map", back_populates="games") players = relationship("Player", back_populates="game", lazy="dynamic") days = relationship("Day", back_populates="game") relations = relationship("Relation", back_populates="game", lazy="dynamic") coalitions = relationship("Coalition", back_populates="game") # # Attributes # ------------- @hybrid_method def day(self): delta = datetime.today() - self.start_at return delta.days # # Representation # ------------- def __repr__(self): return "<Game(%s)>" % (self.id) <commit_msg>Fix issue with returning wrong date<commit_after>
from datetime import datetime from sqlalchemy import Table, Column, Integer, String, DateTime, ForeignKey from sqlalchemy.orm import relationship from sqlalchemy.ext.hybrid import hybrid_property, hybrid_method from .base import Base class Game(Base): # Table name __tablename__ = 'sp_games' # # Columns # ------------- id = Column(Integer, primary_key=True) game_id = Column(Integer) game_host = Column(String) start_at = Column(DateTime) end_at = Column(DateTime) # # Relationships # ------------- map_id = Column(Integer, ForeignKey('sp_maps.id')) map = relationship("Map", back_populates="games") players = relationship("Player", back_populates="game", lazy="dynamic") days = relationship("Day", back_populates="game") relations = relationship("Relation", back_populates="game", lazy="dynamic") coalitions = relationship("Coalition", back_populates="game") # # Attributes # ------------- @hybrid_method def day(self): delta = datetime.today() - self.start_at return delta.days + 1 # # Representation # ------------- def __repr__(self): return "<Game(%s)>" % (self.id)
from datetime import datetime from sqlalchemy import Table, Column, Integer, String, DateTime, ForeignKey from sqlalchemy.orm import relationship from sqlalchemy.ext.hybrid import hybrid_property, hybrid_method from .base import Base class Game(Base): # Table name __tablename__ = 'sp_games' # # Columns # ------------- id = Column(Integer, primary_key=True) game_id = Column(Integer) game_host = Column(String) start_at = Column(DateTime) end_at = Column(DateTime) # # Relationships # ------------- map_id = Column(Integer, ForeignKey('sp_maps.id')) map = relationship("Map", back_populates="games") players = relationship("Player", back_populates="game", lazy="dynamic") days = relationship("Day", back_populates="game") relations = relationship("Relation", back_populates="game", lazy="dynamic") coalitions = relationship("Coalition", back_populates="game") # # Attributes # ------------- @hybrid_method def day(self): delta = datetime.today() - self.start_at return delta.days # # Representation # ------------- def __repr__(self): return "<Game(%s)>" % (self.id) Fix issue with returning wrong datefrom datetime import datetime from sqlalchemy import Table, Column, Integer, String, DateTime, ForeignKey from sqlalchemy.orm import relationship from sqlalchemy.ext.hybrid import hybrid_property, hybrid_method from .base import Base class Game(Base): # Table name __tablename__ = 'sp_games' # # Columns # ------------- id = Column(Integer, primary_key=True) game_id = Column(Integer) game_host = Column(String) start_at = Column(DateTime) end_at = Column(DateTime) # # Relationships # ------------- map_id = Column(Integer, ForeignKey('sp_maps.id')) map = relationship("Map", back_populates="games") players = relationship("Player", back_populates="game", lazy="dynamic") days = relationship("Day", back_populates="game") relations = relationship("Relation", back_populates="game", lazy="dynamic") coalitions = relationship("Coalition", back_populates="game") # # Attributes # ------------- @hybrid_method def day(self): delta = datetime.today() - self.start_at return delta.days + 1 # # Representation # ------------- def __repr__(self): return "<Game(%s)>" % (self.id)
<commit_before>from datetime import datetime from sqlalchemy import Table, Column, Integer, String, DateTime, ForeignKey from sqlalchemy.orm import relationship from sqlalchemy.ext.hybrid import hybrid_property, hybrid_method from .base import Base class Game(Base): # Table name __tablename__ = 'sp_games' # # Columns # ------------- id = Column(Integer, primary_key=True) game_id = Column(Integer) game_host = Column(String) start_at = Column(DateTime) end_at = Column(DateTime) # # Relationships # ------------- map_id = Column(Integer, ForeignKey('sp_maps.id')) map = relationship("Map", back_populates="games") players = relationship("Player", back_populates="game", lazy="dynamic") days = relationship("Day", back_populates="game") relations = relationship("Relation", back_populates="game", lazy="dynamic") coalitions = relationship("Coalition", back_populates="game") # # Attributes # ------------- @hybrid_method def day(self): delta = datetime.today() - self.start_at return delta.days # # Representation # ------------- def __repr__(self): return "<Game(%s)>" % (self.id) <commit_msg>Fix issue with returning wrong date<commit_after>from datetime import datetime from sqlalchemy import Table, Column, Integer, String, DateTime, ForeignKey from sqlalchemy.orm import relationship from sqlalchemy.ext.hybrid import hybrid_property, hybrid_method from .base import Base class Game(Base): # Table name __tablename__ = 'sp_games' # # Columns # ------------- id = Column(Integer, primary_key=True) game_id = Column(Integer) game_host = Column(String) start_at = Column(DateTime) end_at = Column(DateTime) # # Relationships # ------------- map_id = Column(Integer, ForeignKey('sp_maps.id')) map = relationship("Map", back_populates="games") players = relationship("Player", back_populates="game", lazy="dynamic") days = relationship("Day", back_populates="game") relations = relationship("Relation", back_populates="game", lazy="dynamic") coalitions = relationship("Coalition", back_populates="game") # # Attributes # ------------- @hybrid_method def day(self): delta = datetime.today() - self.start_at return delta.days + 1 # # Representation # ------------- def __repr__(self): return "<Game(%s)>" % (self.id)
b986b437495b4406936b2a139e4e027f6275c9eb
boussole/logs.py
boussole/logs.py
""" Logging ======= """ import logging import colorlog def init_logger(level, printout=True): """ Initialize app logger to configure its level/handler/formatter/etc.. Todo: * A mean to raise click.Abort or sys.exit when CRITICAL is used; Args: level (str): Level name (``debug``, ``info``, etc..). Keyword Arguments: printout (bool): If False, logs will never be outputed. Returns: logging.Logger: Application logger. """ root_logger = logging.getLogger("boussole") root_logger.setLevel(level) # Redirect outputs to the void space, mostly for usage within unittests if not printout: from StringIO import StringIO dummystream = StringIO() handler = logging.StreamHandler(dummystream) # Standard output with colored messages else: handler = logging.StreamHandler() handler.setFormatter( colorlog.ColoredFormatter( '%(asctime)s - %(log_color)s%(message)s', datefmt="%H:%M:%S" ) ) root_logger.addHandler(handler) return root_logger
""" Logging ======= """ import logging import colorlog def init_logger(level, printout=True): """ Initialize app logger to configure its level/handler/formatter/etc.. Todo: * A mean to raise click.Abort or sys.exit when CRITICAL is used; Args: level (str): Level name (``debug``, ``info``, etc..). Keyword Arguments: printout (bool): If False, logs will never be outputed. Returns: logging.Logger: Application logger. """ root_logger = logging.getLogger("boussole") root_logger.setLevel(level) # Redirect outputs to the void space, mostly for usage within unittests if not printout: from io import StringIO dummystream = StringIO() handler = logging.StreamHandler(dummystream) # Standard output with colored messages else: handler = logging.StreamHandler() handler.setFormatter( colorlog.ColoredFormatter( '%(asctime)s - %(log_color)s%(message)s', datefmt="%H:%M:%S" ) ) root_logger.addHandler(handler) return root_logger
Use StringIO object from 'io' module instead of deprecated 'StringIO' module
Use StringIO object from 'io' module instead of deprecated 'StringIO' module
Python
mit
sveetch/boussole
""" Logging ======= """ import logging import colorlog def init_logger(level, printout=True): """ Initialize app logger to configure its level/handler/formatter/etc.. Todo: * A mean to raise click.Abort or sys.exit when CRITICAL is used; Args: level (str): Level name (``debug``, ``info``, etc..). Keyword Arguments: printout (bool): If False, logs will never be outputed. Returns: logging.Logger: Application logger. """ root_logger = logging.getLogger("boussole") root_logger.setLevel(level) # Redirect outputs to the void space, mostly for usage within unittests if not printout: from StringIO import StringIO dummystream = StringIO() handler = logging.StreamHandler(dummystream) # Standard output with colored messages else: handler = logging.StreamHandler() handler.setFormatter( colorlog.ColoredFormatter( '%(asctime)s - %(log_color)s%(message)s', datefmt="%H:%M:%S" ) ) root_logger.addHandler(handler) return root_logger Use StringIO object from 'io' module instead of deprecated 'StringIO' module
""" Logging ======= """ import logging import colorlog def init_logger(level, printout=True): """ Initialize app logger to configure its level/handler/formatter/etc.. Todo: * A mean to raise click.Abort or sys.exit when CRITICAL is used; Args: level (str): Level name (``debug``, ``info``, etc..). Keyword Arguments: printout (bool): If False, logs will never be outputed. Returns: logging.Logger: Application logger. """ root_logger = logging.getLogger("boussole") root_logger.setLevel(level) # Redirect outputs to the void space, mostly for usage within unittests if not printout: from io import StringIO dummystream = StringIO() handler = logging.StreamHandler(dummystream) # Standard output with colored messages else: handler = logging.StreamHandler() handler.setFormatter( colorlog.ColoredFormatter( '%(asctime)s - %(log_color)s%(message)s', datefmt="%H:%M:%S" ) ) root_logger.addHandler(handler) return root_logger
<commit_before>""" Logging ======= """ import logging import colorlog def init_logger(level, printout=True): """ Initialize app logger to configure its level/handler/formatter/etc.. Todo: * A mean to raise click.Abort or sys.exit when CRITICAL is used; Args: level (str): Level name (``debug``, ``info``, etc..). Keyword Arguments: printout (bool): If False, logs will never be outputed. Returns: logging.Logger: Application logger. """ root_logger = logging.getLogger("boussole") root_logger.setLevel(level) # Redirect outputs to the void space, mostly for usage within unittests if not printout: from StringIO import StringIO dummystream = StringIO() handler = logging.StreamHandler(dummystream) # Standard output with colored messages else: handler = logging.StreamHandler() handler.setFormatter( colorlog.ColoredFormatter( '%(asctime)s - %(log_color)s%(message)s', datefmt="%H:%M:%S" ) ) root_logger.addHandler(handler) return root_logger <commit_msg>Use StringIO object from 'io' module instead of deprecated 'StringIO' module<commit_after>
""" Logging ======= """ import logging import colorlog def init_logger(level, printout=True): """ Initialize app logger to configure its level/handler/formatter/etc.. Todo: * A mean to raise click.Abort or sys.exit when CRITICAL is used; Args: level (str): Level name (``debug``, ``info``, etc..). Keyword Arguments: printout (bool): If False, logs will never be outputed. Returns: logging.Logger: Application logger. """ root_logger = logging.getLogger("boussole") root_logger.setLevel(level) # Redirect outputs to the void space, mostly for usage within unittests if not printout: from io import StringIO dummystream = StringIO() handler = logging.StreamHandler(dummystream) # Standard output with colored messages else: handler = logging.StreamHandler() handler.setFormatter( colorlog.ColoredFormatter( '%(asctime)s - %(log_color)s%(message)s', datefmt="%H:%M:%S" ) ) root_logger.addHandler(handler) return root_logger
""" Logging ======= """ import logging import colorlog def init_logger(level, printout=True): """ Initialize app logger to configure its level/handler/formatter/etc.. Todo: * A mean to raise click.Abort or sys.exit when CRITICAL is used; Args: level (str): Level name (``debug``, ``info``, etc..). Keyword Arguments: printout (bool): If False, logs will never be outputed. Returns: logging.Logger: Application logger. """ root_logger = logging.getLogger("boussole") root_logger.setLevel(level) # Redirect outputs to the void space, mostly for usage within unittests if not printout: from StringIO import StringIO dummystream = StringIO() handler = logging.StreamHandler(dummystream) # Standard output with colored messages else: handler = logging.StreamHandler() handler.setFormatter( colorlog.ColoredFormatter( '%(asctime)s - %(log_color)s%(message)s', datefmt="%H:%M:%S" ) ) root_logger.addHandler(handler) return root_logger Use StringIO object from 'io' module instead of deprecated 'StringIO' module""" Logging ======= """ import logging import colorlog def init_logger(level, printout=True): """ Initialize app logger to configure its level/handler/formatter/etc.. Todo: * A mean to raise click.Abort or sys.exit when CRITICAL is used; Args: level (str): Level name (``debug``, ``info``, etc..). Keyword Arguments: printout (bool): If False, logs will never be outputed. Returns: logging.Logger: Application logger. """ root_logger = logging.getLogger("boussole") root_logger.setLevel(level) # Redirect outputs to the void space, mostly for usage within unittests if not printout: from io import StringIO dummystream = StringIO() handler = logging.StreamHandler(dummystream) # Standard output with colored messages else: handler = logging.StreamHandler() handler.setFormatter( colorlog.ColoredFormatter( '%(asctime)s - %(log_color)s%(message)s', datefmt="%H:%M:%S" ) ) root_logger.addHandler(handler) return root_logger
<commit_before>""" Logging ======= """ import logging import colorlog def init_logger(level, printout=True): """ Initialize app logger to configure its level/handler/formatter/etc.. Todo: * A mean to raise click.Abort or sys.exit when CRITICAL is used; Args: level (str): Level name (``debug``, ``info``, etc..). Keyword Arguments: printout (bool): If False, logs will never be outputed. Returns: logging.Logger: Application logger. """ root_logger = logging.getLogger("boussole") root_logger.setLevel(level) # Redirect outputs to the void space, mostly for usage within unittests if not printout: from StringIO import StringIO dummystream = StringIO() handler = logging.StreamHandler(dummystream) # Standard output with colored messages else: handler = logging.StreamHandler() handler.setFormatter( colorlog.ColoredFormatter( '%(asctime)s - %(log_color)s%(message)s', datefmt="%H:%M:%S" ) ) root_logger.addHandler(handler) return root_logger <commit_msg>Use StringIO object from 'io' module instead of deprecated 'StringIO' module<commit_after>""" Logging ======= """ import logging import colorlog def init_logger(level, printout=True): """ Initialize app logger to configure its level/handler/formatter/etc.. Todo: * A mean to raise click.Abort or sys.exit when CRITICAL is used; Args: level (str): Level name (``debug``, ``info``, etc..). Keyword Arguments: printout (bool): If False, logs will never be outputed. Returns: logging.Logger: Application logger. """ root_logger = logging.getLogger("boussole") root_logger.setLevel(level) # Redirect outputs to the void space, mostly for usage within unittests if not printout: from io import StringIO dummystream = StringIO() handler = logging.StreamHandler(dummystream) # Standard output with colored messages else: handler = logging.StreamHandler() handler.setFormatter( colorlog.ColoredFormatter( '%(asctime)s - %(log_color)s%(message)s', datefmt="%H:%M:%S" ) ) root_logger.addHandler(handler) return root_logger
16ea4f3ca1622604fd79e22b4b674d1dd9e11779
conveyor/store.py
conveyor/store.py
class BaseStore(object): def set(self, key, value): raise NotImplementedError def get(self, key): raise NotImplementedError class InMemoryStore(object): def __init__(self, *args, **kwargs): super(InMemoryStore, self).__init__(*args, **kwargs) self._data = {} def set(self, key, value): self._data[key] = value def get(self, key): return self._data[key]
class BaseStore(object): def set(self, key, value): raise NotImplementedError def get(self, key): raise NotImplementedError class InMemoryStore(BaseStore): def __init__(self, *args, **kwargs): super(InMemoryStore, self).__init__(*args, **kwargs) self._data = {} def set(self, key, value): self._data[key] = value def get(self, key): return self._data[key]
Fix the inheritence of InMemoryStore
Fix the inheritence of InMemoryStore
Python
bsd-2-clause
crateio/carrier
class BaseStore(object): def set(self, key, value): raise NotImplementedError def get(self, key): raise NotImplementedError class InMemoryStore(object): def __init__(self, *args, **kwargs): super(InMemoryStore, self).__init__(*args, **kwargs) self._data = {} def set(self, key, value): self._data[key] = value def get(self, key): return self._data[key] Fix the inheritence of InMemoryStore
class BaseStore(object): def set(self, key, value): raise NotImplementedError def get(self, key): raise NotImplementedError class InMemoryStore(BaseStore): def __init__(self, *args, **kwargs): super(InMemoryStore, self).__init__(*args, **kwargs) self._data = {} def set(self, key, value): self._data[key] = value def get(self, key): return self._data[key]
<commit_before>class BaseStore(object): def set(self, key, value): raise NotImplementedError def get(self, key): raise NotImplementedError class InMemoryStore(object): def __init__(self, *args, **kwargs): super(InMemoryStore, self).__init__(*args, **kwargs) self._data = {} def set(self, key, value): self._data[key] = value def get(self, key): return self._data[key] <commit_msg>Fix the inheritence of InMemoryStore<commit_after>
class BaseStore(object): def set(self, key, value): raise NotImplementedError def get(self, key): raise NotImplementedError class InMemoryStore(BaseStore): def __init__(self, *args, **kwargs): super(InMemoryStore, self).__init__(*args, **kwargs) self._data = {} def set(self, key, value): self._data[key] = value def get(self, key): return self._data[key]
class BaseStore(object): def set(self, key, value): raise NotImplementedError def get(self, key): raise NotImplementedError class InMemoryStore(object): def __init__(self, *args, **kwargs): super(InMemoryStore, self).__init__(*args, **kwargs) self._data = {} def set(self, key, value): self._data[key] = value def get(self, key): return self._data[key] Fix the inheritence of InMemoryStoreclass BaseStore(object): def set(self, key, value): raise NotImplementedError def get(self, key): raise NotImplementedError class InMemoryStore(BaseStore): def __init__(self, *args, **kwargs): super(InMemoryStore, self).__init__(*args, **kwargs) self._data = {} def set(self, key, value): self._data[key] = value def get(self, key): return self._data[key]
<commit_before>class BaseStore(object): def set(self, key, value): raise NotImplementedError def get(self, key): raise NotImplementedError class InMemoryStore(object): def __init__(self, *args, **kwargs): super(InMemoryStore, self).__init__(*args, **kwargs) self._data = {} def set(self, key, value): self._data[key] = value def get(self, key): return self._data[key] <commit_msg>Fix the inheritence of InMemoryStore<commit_after>class BaseStore(object): def set(self, key, value): raise NotImplementedError def get(self, key): raise NotImplementedError class InMemoryStore(BaseStore): def __init__(self, *args, **kwargs): super(InMemoryStore, self).__init__(*args, **kwargs) self._data = {} def set(self, key, value): self._data[key] = value def get(self, key): return self._data[key]
8d9b50b2cd8b0235863c48a84ba5f23af4531765
ynr/apps/parties/tests/test_models.py
ynr/apps/parties/tests/test_models.py
""" Test some of the basic model use cases """ from django.test import TestCase from .factories import PartyFactory, PartyEmblemFactory class TestPartyModels(TestCase): def setUp(self): PartyFactory.reset_sequence() def test_party_str(self): party = PartyFactory() self.assertEqual(str(party), "Party 0 (PP0)") def test_party_emblem(self): party = PartyFactory() PartyEmblemFactory.create_batch(3, party=party) self.assertEqual(party.emblems.count(), 3) self.assertTrue( party.emblems.first().image.url.startswith( "/media/emblems/PP0/0_example" ) ) # Add a default image and assert it's the deafult on the party PartyEmblemFactory(party=party, __sequence=99, default=True) self.assertTrue( party.default_emblem.image.url.startswith( "/media/emblems/PP0/99_example" ) )
""" Test some of the basic model use cases """ from django.test import TestCase from django.core.files.storage import DefaultStorage from candidates.tests.helpers import TmpMediaRootMixin from .factories import PartyFactory, PartyEmblemFactory class TestPartyModels(TmpMediaRootMixin, TestCase): def setUp(self): self.storage = DefaultStorage() PartyFactory.reset_sequence() def test_party_str(self): party = PartyFactory() self.assertEqual(str(party), "Party 0 (PP0)") def test_party_emblem(self): party = PartyFactory() PartyEmblemFactory.create_batch(3, party=party) self.assertEqual(party.emblems.count(), 3) self.assertTrue( party.emblems.first().image.url.startswith( "/media/emblems/PP0/0_example" ) ) # Add a default image and assert it's the deafult on the party PartyEmblemFactory(party=party, __sequence=99, default=True) self.assertTrue( party.default_emblem.image.url.startswith( "/media/emblems/PP0/99_example" ) )
Test using tmp media root
Test using tmp media root
Python
agpl-3.0
DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative
""" Test some of the basic model use cases """ from django.test import TestCase from .factories import PartyFactory, PartyEmblemFactory class TestPartyModels(TestCase): def setUp(self): PartyFactory.reset_sequence() def test_party_str(self): party = PartyFactory() self.assertEqual(str(party), "Party 0 (PP0)") def test_party_emblem(self): party = PartyFactory() PartyEmblemFactory.create_batch(3, party=party) self.assertEqual(party.emblems.count(), 3) self.assertTrue( party.emblems.first().image.url.startswith( "/media/emblems/PP0/0_example" ) ) # Add a default image and assert it's the deafult on the party PartyEmblemFactory(party=party, __sequence=99, default=True) self.assertTrue( party.default_emblem.image.url.startswith( "/media/emblems/PP0/99_example" ) ) Test using tmp media root
""" Test some of the basic model use cases """ from django.test import TestCase from django.core.files.storage import DefaultStorage from candidates.tests.helpers import TmpMediaRootMixin from .factories import PartyFactory, PartyEmblemFactory class TestPartyModels(TmpMediaRootMixin, TestCase): def setUp(self): self.storage = DefaultStorage() PartyFactory.reset_sequence() def test_party_str(self): party = PartyFactory() self.assertEqual(str(party), "Party 0 (PP0)") def test_party_emblem(self): party = PartyFactory() PartyEmblemFactory.create_batch(3, party=party) self.assertEqual(party.emblems.count(), 3) self.assertTrue( party.emblems.first().image.url.startswith( "/media/emblems/PP0/0_example" ) ) # Add a default image and assert it's the deafult on the party PartyEmblemFactory(party=party, __sequence=99, default=True) self.assertTrue( party.default_emblem.image.url.startswith( "/media/emblems/PP0/99_example" ) )
<commit_before>""" Test some of the basic model use cases """ from django.test import TestCase from .factories import PartyFactory, PartyEmblemFactory class TestPartyModels(TestCase): def setUp(self): PartyFactory.reset_sequence() def test_party_str(self): party = PartyFactory() self.assertEqual(str(party), "Party 0 (PP0)") def test_party_emblem(self): party = PartyFactory() PartyEmblemFactory.create_batch(3, party=party) self.assertEqual(party.emblems.count(), 3) self.assertTrue( party.emblems.first().image.url.startswith( "/media/emblems/PP0/0_example" ) ) # Add a default image and assert it's the deafult on the party PartyEmblemFactory(party=party, __sequence=99, default=True) self.assertTrue( party.default_emblem.image.url.startswith( "/media/emblems/PP0/99_example" ) ) <commit_msg>Test using tmp media root<commit_after>
""" Test some of the basic model use cases """ from django.test import TestCase from django.core.files.storage import DefaultStorage from candidates.tests.helpers import TmpMediaRootMixin from .factories import PartyFactory, PartyEmblemFactory class TestPartyModels(TmpMediaRootMixin, TestCase): def setUp(self): self.storage = DefaultStorage() PartyFactory.reset_sequence() def test_party_str(self): party = PartyFactory() self.assertEqual(str(party), "Party 0 (PP0)") def test_party_emblem(self): party = PartyFactory() PartyEmblemFactory.create_batch(3, party=party) self.assertEqual(party.emblems.count(), 3) self.assertTrue( party.emblems.first().image.url.startswith( "/media/emblems/PP0/0_example" ) ) # Add a default image and assert it's the deafult on the party PartyEmblemFactory(party=party, __sequence=99, default=True) self.assertTrue( party.default_emblem.image.url.startswith( "/media/emblems/PP0/99_example" ) )
""" Test some of the basic model use cases """ from django.test import TestCase from .factories import PartyFactory, PartyEmblemFactory class TestPartyModels(TestCase): def setUp(self): PartyFactory.reset_sequence() def test_party_str(self): party = PartyFactory() self.assertEqual(str(party), "Party 0 (PP0)") def test_party_emblem(self): party = PartyFactory() PartyEmblemFactory.create_batch(3, party=party) self.assertEqual(party.emblems.count(), 3) self.assertTrue( party.emblems.first().image.url.startswith( "/media/emblems/PP0/0_example" ) ) # Add a default image and assert it's the deafult on the party PartyEmblemFactory(party=party, __sequence=99, default=True) self.assertTrue( party.default_emblem.image.url.startswith( "/media/emblems/PP0/99_example" ) ) Test using tmp media root""" Test some of the basic model use cases """ from django.test import TestCase from django.core.files.storage import DefaultStorage from candidates.tests.helpers import TmpMediaRootMixin from .factories import PartyFactory, PartyEmblemFactory class TestPartyModels(TmpMediaRootMixin, TestCase): def setUp(self): self.storage = DefaultStorage() PartyFactory.reset_sequence() def test_party_str(self): party = PartyFactory() self.assertEqual(str(party), "Party 0 (PP0)") def test_party_emblem(self): party = PartyFactory() PartyEmblemFactory.create_batch(3, party=party) self.assertEqual(party.emblems.count(), 3) self.assertTrue( party.emblems.first().image.url.startswith( "/media/emblems/PP0/0_example" ) ) # Add a default image and assert it's the deafult on the party PartyEmblemFactory(party=party, __sequence=99, default=True) self.assertTrue( party.default_emblem.image.url.startswith( "/media/emblems/PP0/99_example" ) )
<commit_before>""" Test some of the basic model use cases """ from django.test import TestCase from .factories import PartyFactory, PartyEmblemFactory class TestPartyModels(TestCase): def setUp(self): PartyFactory.reset_sequence() def test_party_str(self): party = PartyFactory() self.assertEqual(str(party), "Party 0 (PP0)") def test_party_emblem(self): party = PartyFactory() PartyEmblemFactory.create_batch(3, party=party) self.assertEqual(party.emblems.count(), 3) self.assertTrue( party.emblems.first().image.url.startswith( "/media/emblems/PP0/0_example" ) ) # Add a default image and assert it's the deafult on the party PartyEmblemFactory(party=party, __sequence=99, default=True) self.assertTrue( party.default_emblem.image.url.startswith( "/media/emblems/PP0/99_example" ) ) <commit_msg>Test using tmp media root<commit_after>""" Test some of the basic model use cases """ from django.test import TestCase from django.core.files.storage import DefaultStorage from candidates.tests.helpers import TmpMediaRootMixin from .factories import PartyFactory, PartyEmblemFactory class TestPartyModels(TmpMediaRootMixin, TestCase): def setUp(self): self.storage = DefaultStorage() PartyFactory.reset_sequence() def test_party_str(self): party = PartyFactory() self.assertEqual(str(party), "Party 0 (PP0)") def test_party_emblem(self): party = PartyFactory() PartyEmblemFactory.create_batch(3, party=party) self.assertEqual(party.emblems.count(), 3) self.assertTrue( party.emblems.first().image.url.startswith( "/media/emblems/PP0/0_example" ) ) # Add a default image and assert it's the deafult on the party PartyEmblemFactory(party=party, __sequence=99, default=True) self.assertTrue( party.default_emblem.image.url.startswith( "/media/emblems/PP0/99_example" ) )
b6a2ba81c9ddd642cfa271cab809a5c2511f7204
app/auth/forms.py
app/auth/forms.py
from flask_wtf import Form from wtforms import ( StringField, PasswordField, BooleanField, SubmitField, ValidationError, ) from wtforms.validators import ( InputRequired, Length, Email, Regexp, EqualTo, ) from app.models import User class LoginForm(Form): email = StringField('Email', validators=[ InputRequired(), Length(1, 64), Email()]) password = PasswordField('Senha', validators=[InputRequired()]) remember_me = BooleanField('Lembrar') submit = SubmitField('Log In') class RegistrationForm(Form): email = StringField('Email', validators=[ InputRequired(), Length(1, 64), Email()]) username = StringField('Username', validators=[ InputRequired(), Length(1, 64)]) password = PasswordField('Senha', validators=[ InputRequired(), EqualTo('password2', message='Senhas devem ser iguais')]) password2 = PasswordField('Confirmar senha', validators=[InputRequired()]) submit = SubmitField('Registrar') def validate_email(self, field): if User.query.filter_by(email=field.data).first(): raise ValidationError('Esse email já está em uso!') def validate_username(self, field): if User.query.filter_by(username=field.data).first(): raise ValidationError('Esse usuário já está em uso!')
from flask_wtf import FlaskForm from wtforms import ( StringField, PasswordField, BooleanField, SubmitField, ValidationError, ) from wtforms.validators import ( InputRequired, Length, Email, Regexp, EqualTo, ) from app.models import User class LoginForm(FlaskForm): email = StringField('Email', validators=[ InputRequired(), Length(1, 64), Email()]) password = PasswordField('Senha', validators=[InputRequired()]) remember_me = BooleanField('Lembrar') submit = SubmitField('Log In') class RegistrationForm(FlaskForm): email = StringField('Email', validators=[ InputRequired(), Length(1, 64), Email()]) username = StringField('Username', validators=[ InputRequired(), Length(1, 64)]) password = PasswordField('Senha', validators=[ InputRequired(), EqualTo('password2', message='Senhas devem ser iguais')]) password2 = PasswordField('Confirmar senha', validators=[InputRequired()]) submit = SubmitField('Registrar') def validate_email(self, field): if User.query.filter_by(email=field.data).first(): raise ValidationError('Esse email já está em uso!') def validate_username(self, field): if User.query.filter_by(username=field.data).first(): raise ValidationError('Esse usuário já está em uso!')
Change Form to FlaskForm (previous is deprecated)
:art: Change Form to FlaskForm (previous is deprecated)
Python
mit
gems-uff/labsys,gems-uff/labsys,gems-uff/labsys
from flask_wtf import Form from wtforms import ( StringField, PasswordField, BooleanField, SubmitField, ValidationError, ) from wtforms.validators import ( InputRequired, Length, Email, Regexp, EqualTo, ) from app.models import User class LoginForm(Form): email = StringField('Email', validators=[ InputRequired(), Length(1, 64), Email()]) password = PasswordField('Senha', validators=[InputRequired()]) remember_me = BooleanField('Lembrar') submit = SubmitField('Log In') class RegistrationForm(Form): email = StringField('Email', validators=[ InputRequired(), Length(1, 64), Email()]) username = StringField('Username', validators=[ InputRequired(), Length(1, 64)]) password = PasswordField('Senha', validators=[ InputRequired(), EqualTo('password2', message='Senhas devem ser iguais')]) password2 = PasswordField('Confirmar senha', validators=[InputRequired()]) submit = SubmitField('Registrar') def validate_email(self, field): if User.query.filter_by(email=field.data).first(): raise ValidationError('Esse email já está em uso!') def validate_username(self, field): if User.query.filter_by(username=field.data).first(): raise ValidationError('Esse usuário já está em uso!') :art: Change Form to FlaskForm (previous is deprecated)
from flask_wtf import FlaskForm from wtforms import ( StringField, PasswordField, BooleanField, SubmitField, ValidationError, ) from wtforms.validators import ( InputRequired, Length, Email, Regexp, EqualTo, ) from app.models import User class LoginForm(FlaskForm): email = StringField('Email', validators=[ InputRequired(), Length(1, 64), Email()]) password = PasswordField('Senha', validators=[InputRequired()]) remember_me = BooleanField('Lembrar') submit = SubmitField('Log In') class RegistrationForm(FlaskForm): email = StringField('Email', validators=[ InputRequired(), Length(1, 64), Email()]) username = StringField('Username', validators=[ InputRequired(), Length(1, 64)]) password = PasswordField('Senha', validators=[ InputRequired(), EqualTo('password2', message='Senhas devem ser iguais')]) password2 = PasswordField('Confirmar senha', validators=[InputRequired()]) submit = SubmitField('Registrar') def validate_email(self, field): if User.query.filter_by(email=field.data).first(): raise ValidationError('Esse email já está em uso!') def validate_username(self, field): if User.query.filter_by(username=field.data).first(): raise ValidationError('Esse usuário já está em uso!')
<commit_before>from flask_wtf import Form from wtforms import ( StringField, PasswordField, BooleanField, SubmitField, ValidationError, ) from wtforms.validators import ( InputRequired, Length, Email, Regexp, EqualTo, ) from app.models import User class LoginForm(Form): email = StringField('Email', validators=[ InputRequired(), Length(1, 64), Email()]) password = PasswordField('Senha', validators=[InputRequired()]) remember_me = BooleanField('Lembrar') submit = SubmitField('Log In') class RegistrationForm(Form): email = StringField('Email', validators=[ InputRequired(), Length(1, 64), Email()]) username = StringField('Username', validators=[ InputRequired(), Length(1, 64)]) password = PasswordField('Senha', validators=[ InputRequired(), EqualTo('password2', message='Senhas devem ser iguais')]) password2 = PasswordField('Confirmar senha', validators=[InputRequired()]) submit = SubmitField('Registrar') def validate_email(self, field): if User.query.filter_by(email=field.data).first(): raise ValidationError('Esse email já está em uso!') def validate_username(self, field): if User.query.filter_by(username=field.data).first(): raise ValidationError('Esse usuário já está em uso!') <commit_msg>:art: Change Form to FlaskForm (previous is deprecated)<commit_after>
from flask_wtf import FlaskForm from wtforms import ( StringField, PasswordField, BooleanField, SubmitField, ValidationError, ) from wtforms.validators import ( InputRequired, Length, Email, Regexp, EqualTo, ) from app.models import User class LoginForm(FlaskForm): email = StringField('Email', validators=[ InputRequired(), Length(1, 64), Email()]) password = PasswordField('Senha', validators=[InputRequired()]) remember_me = BooleanField('Lembrar') submit = SubmitField('Log In') class RegistrationForm(FlaskForm): email = StringField('Email', validators=[ InputRequired(), Length(1, 64), Email()]) username = StringField('Username', validators=[ InputRequired(), Length(1, 64)]) password = PasswordField('Senha', validators=[ InputRequired(), EqualTo('password2', message='Senhas devem ser iguais')]) password2 = PasswordField('Confirmar senha', validators=[InputRequired()]) submit = SubmitField('Registrar') def validate_email(self, field): if User.query.filter_by(email=field.data).first(): raise ValidationError('Esse email já está em uso!') def validate_username(self, field): if User.query.filter_by(username=field.data).first(): raise ValidationError('Esse usuário já está em uso!')
from flask_wtf import Form from wtforms import ( StringField, PasswordField, BooleanField, SubmitField, ValidationError, ) from wtforms.validators import ( InputRequired, Length, Email, Regexp, EqualTo, ) from app.models import User class LoginForm(Form): email = StringField('Email', validators=[ InputRequired(), Length(1, 64), Email()]) password = PasswordField('Senha', validators=[InputRequired()]) remember_me = BooleanField('Lembrar') submit = SubmitField('Log In') class RegistrationForm(Form): email = StringField('Email', validators=[ InputRequired(), Length(1, 64), Email()]) username = StringField('Username', validators=[ InputRequired(), Length(1, 64)]) password = PasswordField('Senha', validators=[ InputRequired(), EqualTo('password2', message='Senhas devem ser iguais')]) password2 = PasswordField('Confirmar senha', validators=[InputRequired()]) submit = SubmitField('Registrar') def validate_email(self, field): if User.query.filter_by(email=field.data).first(): raise ValidationError('Esse email já está em uso!') def validate_username(self, field): if User.query.filter_by(username=field.data).first(): raise ValidationError('Esse usuário já está em uso!') :art: Change Form to FlaskForm (previous is deprecated)from flask_wtf import FlaskForm from wtforms import ( StringField, PasswordField, BooleanField, SubmitField, ValidationError, ) from wtforms.validators import ( InputRequired, Length, Email, Regexp, EqualTo, ) from app.models import User class LoginForm(FlaskForm): email = StringField('Email', validators=[ InputRequired(), Length(1, 64), Email()]) password = PasswordField('Senha', validators=[InputRequired()]) remember_me = BooleanField('Lembrar') submit = SubmitField('Log In') class RegistrationForm(FlaskForm): email = StringField('Email', validators=[ InputRequired(), Length(1, 64), Email()]) username = StringField('Username', validators=[ InputRequired(), Length(1, 64)]) password = PasswordField('Senha', validators=[ InputRequired(), EqualTo('password2', message='Senhas devem ser iguais')]) password2 = PasswordField('Confirmar senha', validators=[InputRequired()]) submit = SubmitField('Registrar') def validate_email(self, field): if User.query.filter_by(email=field.data).first(): raise ValidationError('Esse email já está em uso!') def validate_username(self, field): if User.query.filter_by(username=field.data).first(): raise ValidationError('Esse usuário já está em uso!')
<commit_before>from flask_wtf import Form from wtforms import ( StringField, PasswordField, BooleanField, SubmitField, ValidationError, ) from wtforms.validators import ( InputRequired, Length, Email, Regexp, EqualTo, ) from app.models import User class LoginForm(Form): email = StringField('Email', validators=[ InputRequired(), Length(1, 64), Email()]) password = PasswordField('Senha', validators=[InputRequired()]) remember_me = BooleanField('Lembrar') submit = SubmitField('Log In') class RegistrationForm(Form): email = StringField('Email', validators=[ InputRequired(), Length(1, 64), Email()]) username = StringField('Username', validators=[ InputRequired(), Length(1, 64)]) password = PasswordField('Senha', validators=[ InputRequired(), EqualTo('password2', message='Senhas devem ser iguais')]) password2 = PasswordField('Confirmar senha', validators=[InputRequired()]) submit = SubmitField('Registrar') def validate_email(self, field): if User.query.filter_by(email=field.data).first(): raise ValidationError('Esse email já está em uso!') def validate_username(self, field): if User.query.filter_by(username=field.data).first(): raise ValidationError('Esse usuário já está em uso!') <commit_msg>:art: Change Form to FlaskForm (previous is deprecated)<commit_after>from flask_wtf import FlaskForm from wtforms import ( StringField, PasswordField, BooleanField, SubmitField, ValidationError, ) from wtforms.validators import ( InputRequired, Length, Email, Regexp, EqualTo, ) from app.models import User class LoginForm(FlaskForm): email = StringField('Email', validators=[ InputRequired(), Length(1, 64), Email()]) password = PasswordField('Senha', validators=[InputRequired()]) remember_me = BooleanField('Lembrar') submit = SubmitField('Log In') class RegistrationForm(FlaskForm): email = StringField('Email', validators=[ InputRequired(), Length(1, 64), Email()]) username = StringField('Username', validators=[ InputRequired(), Length(1, 64)]) password = PasswordField('Senha', validators=[ InputRequired(), EqualTo('password2', message='Senhas devem ser iguais')]) password2 = PasswordField('Confirmar senha', validators=[InputRequired()]) submit = SubmitField('Registrar') def validate_email(self, field): if User.query.filter_by(email=field.data).first(): raise ValidationError('Esse email já está em uso!') def validate_username(self, field): if User.query.filter_by(username=field.data).first(): raise ValidationError('Esse usuário já está em uso!')
58544043b8dee4e55bad0be5d889a40c0ae88960
tests/__init__.py
tests/__init__.py
import logging import os import re import unittest.mock # Default to turning off all but critical logging messages logging.basicConfig(level=logging.CRITICAL) def mock_open_url(url, allow_local=False, timeout=None, verify_ssl=True, http_headers=None): """Open local files instead of URLs. If it's a local file path, leave it alone; otherwise, open as a file under ./files/ This is meant as a side effect for unittest.mock.Mock """ if re.match(r'https?:', url): # Looks like a URL filename = re.sub(r'^.*/([^/]+)$', '\\1', url) path = resolve_path('files/mock/' + filename) else: # Assume it's a file path = url return (open(path, 'rb'), None, None, None) def resolve_path(filename): """Resolve a pathname for a test input file.""" return os.path.join(os.path.dirname(__file__), filename) # Target function to replace for mocking URL access. URL_MOCK_TARGET = 'hxl.io.open_url_or_file' # Mock object to replace hxl.io.make_stream URL_MOCK_OBJECT = unittest.mock.Mock() URL_MOCK_OBJECT.side_effect = mock_open_url
import logging import os import re import io import unittest.mock # Default to turning off all but critical logging messages logging.basicConfig(level=logging.CRITICAL) def mock_open_url(url, allow_local=False, timeout=None, verify_ssl=True, http_headers=None): """Open local files instead of URLs. If it's a local file path, leave it alone; otherwise, open as a file under ./files/ This is meant as a side effect for unittest.mock.Mock """ if re.match(r'https?:', url): # Looks like a URL filename = re.sub(r'^.*/([^/]+)$', '\\1', url) path = resolve_path('files/mock/' + filename) else: # Assume it's a file path = url with open(path, 'rb') as input: data = input.read() return (io.BytesIO(data), None, None, None) def resolve_path(filename): """Resolve a pathname for a test input file.""" return os.path.join(os.path.dirname(__file__), filename) # Target function to replace for mocking URL access. URL_MOCK_TARGET = 'hxl.io.open_url_or_file' # Mock object to replace hxl.io.make_stream URL_MOCK_OBJECT = unittest.mock.Mock() URL_MOCK_OBJECT.side_effect = mock_open_url
Fix intermittent errors during test runs.
Fix intermittent errors during test runs.
Python
unlicense
HXLStandard/libhxl-python,HXLStandard/libhxl-python
import logging import os import re import unittest.mock # Default to turning off all but critical logging messages logging.basicConfig(level=logging.CRITICAL) def mock_open_url(url, allow_local=False, timeout=None, verify_ssl=True, http_headers=None): """Open local files instead of URLs. If it's a local file path, leave it alone; otherwise, open as a file under ./files/ This is meant as a side effect for unittest.mock.Mock """ if re.match(r'https?:', url): # Looks like a URL filename = re.sub(r'^.*/([^/]+)$', '\\1', url) path = resolve_path('files/mock/' + filename) else: # Assume it's a file path = url return (open(path, 'rb'), None, None, None) def resolve_path(filename): """Resolve a pathname for a test input file.""" return os.path.join(os.path.dirname(__file__), filename) # Target function to replace for mocking URL access. URL_MOCK_TARGET = 'hxl.io.open_url_or_file' # Mock object to replace hxl.io.make_stream URL_MOCK_OBJECT = unittest.mock.Mock() URL_MOCK_OBJECT.side_effect = mock_open_url Fix intermittent errors during test runs.
import logging import os import re import io import unittest.mock # Default to turning off all but critical logging messages logging.basicConfig(level=logging.CRITICAL) def mock_open_url(url, allow_local=False, timeout=None, verify_ssl=True, http_headers=None): """Open local files instead of URLs. If it's a local file path, leave it alone; otherwise, open as a file under ./files/ This is meant as a side effect for unittest.mock.Mock """ if re.match(r'https?:', url): # Looks like a URL filename = re.sub(r'^.*/([^/]+)$', '\\1', url) path = resolve_path('files/mock/' + filename) else: # Assume it's a file path = url with open(path, 'rb') as input: data = input.read() return (io.BytesIO(data), None, None, None) def resolve_path(filename): """Resolve a pathname for a test input file.""" return os.path.join(os.path.dirname(__file__), filename) # Target function to replace for mocking URL access. URL_MOCK_TARGET = 'hxl.io.open_url_or_file' # Mock object to replace hxl.io.make_stream URL_MOCK_OBJECT = unittest.mock.Mock() URL_MOCK_OBJECT.side_effect = mock_open_url
<commit_before>import logging import os import re import unittest.mock # Default to turning off all but critical logging messages logging.basicConfig(level=logging.CRITICAL) def mock_open_url(url, allow_local=False, timeout=None, verify_ssl=True, http_headers=None): """Open local files instead of URLs. If it's a local file path, leave it alone; otherwise, open as a file under ./files/ This is meant as a side effect for unittest.mock.Mock """ if re.match(r'https?:', url): # Looks like a URL filename = re.sub(r'^.*/([^/]+)$', '\\1', url) path = resolve_path('files/mock/' + filename) else: # Assume it's a file path = url return (open(path, 'rb'), None, None, None) def resolve_path(filename): """Resolve a pathname for a test input file.""" return os.path.join(os.path.dirname(__file__), filename) # Target function to replace for mocking URL access. URL_MOCK_TARGET = 'hxl.io.open_url_or_file' # Mock object to replace hxl.io.make_stream URL_MOCK_OBJECT = unittest.mock.Mock() URL_MOCK_OBJECT.side_effect = mock_open_url <commit_msg>Fix intermittent errors during test runs.<commit_after>
import logging import os import re import io import unittest.mock # Default to turning off all but critical logging messages logging.basicConfig(level=logging.CRITICAL) def mock_open_url(url, allow_local=False, timeout=None, verify_ssl=True, http_headers=None): """Open local files instead of URLs. If it's a local file path, leave it alone; otherwise, open as a file under ./files/ This is meant as a side effect for unittest.mock.Mock """ if re.match(r'https?:', url): # Looks like a URL filename = re.sub(r'^.*/([^/]+)$', '\\1', url) path = resolve_path('files/mock/' + filename) else: # Assume it's a file path = url with open(path, 'rb') as input: data = input.read() return (io.BytesIO(data), None, None, None) def resolve_path(filename): """Resolve a pathname for a test input file.""" return os.path.join(os.path.dirname(__file__), filename) # Target function to replace for mocking URL access. URL_MOCK_TARGET = 'hxl.io.open_url_or_file' # Mock object to replace hxl.io.make_stream URL_MOCK_OBJECT = unittest.mock.Mock() URL_MOCK_OBJECT.side_effect = mock_open_url
import logging import os import re import unittest.mock # Default to turning off all but critical logging messages logging.basicConfig(level=logging.CRITICAL) def mock_open_url(url, allow_local=False, timeout=None, verify_ssl=True, http_headers=None): """Open local files instead of URLs. If it's a local file path, leave it alone; otherwise, open as a file under ./files/ This is meant as a side effect for unittest.mock.Mock """ if re.match(r'https?:', url): # Looks like a URL filename = re.sub(r'^.*/([^/]+)$', '\\1', url) path = resolve_path('files/mock/' + filename) else: # Assume it's a file path = url return (open(path, 'rb'), None, None, None) def resolve_path(filename): """Resolve a pathname for a test input file.""" return os.path.join(os.path.dirname(__file__), filename) # Target function to replace for mocking URL access. URL_MOCK_TARGET = 'hxl.io.open_url_or_file' # Mock object to replace hxl.io.make_stream URL_MOCK_OBJECT = unittest.mock.Mock() URL_MOCK_OBJECT.side_effect = mock_open_url Fix intermittent errors during test runs.import logging import os import re import io import unittest.mock # Default to turning off all but critical logging messages logging.basicConfig(level=logging.CRITICAL) def mock_open_url(url, allow_local=False, timeout=None, verify_ssl=True, http_headers=None): """Open local files instead of URLs. If it's a local file path, leave it alone; otherwise, open as a file under ./files/ This is meant as a side effect for unittest.mock.Mock """ if re.match(r'https?:', url): # Looks like a URL filename = re.sub(r'^.*/([^/]+)$', '\\1', url) path = resolve_path('files/mock/' + filename) else: # Assume it's a file path = url with open(path, 'rb') as input: data = input.read() return (io.BytesIO(data), None, None, None) def resolve_path(filename): """Resolve a pathname for a test input file.""" return os.path.join(os.path.dirname(__file__), filename) # Target function to replace for mocking URL access. URL_MOCK_TARGET = 'hxl.io.open_url_or_file' # Mock object to replace hxl.io.make_stream URL_MOCK_OBJECT = unittest.mock.Mock() URL_MOCK_OBJECT.side_effect = mock_open_url
<commit_before>import logging import os import re import unittest.mock # Default to turning off all but critical logging messages logging.basicConfig(level=logging.CRITICAL) def mock_open_url(url, allow_local=False, timeout=None, verify_ssl=True, http_headers=None): """Open local files instead of URLs. If it's a local file path, leave it alone; otherwise, open as a file under ./files/ This is meant as a side effect for unittest.mock.Mock """ if re.match(r'https?:', url): # Looks like a URL filename = re.sub(r'^.*/([^/]+)$', '\\1', url) path = resolve_path('files/mock/' + filename) else: # Assume it's a file path = url return (open(path, 'rb'), None, None, None) def resolve_path(filename): """Resolve a pathname for a test input file.""" return os.path.join(os.path.dirname(__file__), filename) # Target function to replace for mocking URL access. URL_MOCK_TARGET = 'hxl.io.open_url_or_file' # Mock object to replace hxl.io.make_stream URL_MOCK_OBJECT = unittest.mock.Mock() URL_MOCK_OBJECT.side_effect = mock_open_url <commit_msg>Fix intermittent errors during test runs.<commit_after>import logging import os import re import io import unittest.mock # Default to turning off all but critical logging messages logging.basicConfig(level=logging.CRITICAL) def mock_open_url(url, allow_local=False, timeout=None, verify_ssl=True, http_headers=None): """Open local files instead of URLs. If it's a local file path, leave it alone; otherwise, open as a file under ./files/ This is meant as a side effect for unittest.mock.Mock """ if re.match(r'https?:', url): # Looks like a URL filename = re.sub(r'^.*/([^/]+)$', '\\1', url) path = resolve_path('files/mock/' + filename) else: # Assume it's a file path = url with open(path, 'rb') as input: data = input.read() return (io.BytesIO(data), None, None, None) def resolve_path(filename): """Resolve a pathname for a test input file.""" return os.path.join(os.path.dirname(__file__), filename) # Target function to replace for mocking URL access. URL_MOCK_TARGET = 'hxl.io.open_url_or_file' # Mock object to replace hxl.io.make_stream URL_MOCK_OBJECT = unittest.mock.Mock() URL_MOCK_OBJECT.side_effect = mock_open_url
2f2b64321a54c93a109c0b65866d724227db9399
tests/conftest.py
tests/conftest.py
from unittest.mock import MagicMock import pytest from rocketchat_API.rocketchat import RocketChat @pytest.fixture(scope="session") def rocket(): _rocket = RocketChat() return _rocket @pytest.fixture(scope="session") def create_user(rocket): def _create_user(name="user1", password="password", email="email@domain.com"): user = MagicMock() user.name = name user.password = password user.email = email rocket.users_register( email=user.email, name=user.name, password=user.password, username=user.name ) return user return _create_user @pytest.fixture(scope="session") def user(create_user): _user = create_user() return _user @pytest.fixture(scope="session") def logged_rocket(user): _rocket = RocketChat(user.name, user.password) return _rocket
import pytest from rocketchat_API.rocketchat import RocketChat @pytest.fixture(scope="session") def rocket(): _rocket = RocketChat() return _rocket @pytest.fixture(scope="session") def create_user(rocket): def _create_user(name="user1", password="password", email="email@domain.com"): # create empty object, because Mock not included to python2 user = type('test', (object,), {})() user.name = name user.password = password user.email = email rocket.users_register( email=user.email, name=user.name, password=user.password, username=user.name ) return user return _create_user @pytest.fixture(scope="session") def user(create_user): _user = create_user() return _user @pytest.fixture(scope="session") def logged_rocket(user): _rocket = RocketChat(user.name, user.password) return _rocket
Remove Mock and create "empty" object on the fly
Remove Mock and create "empty" object on the fly
Python
mit
jadolg/rocketchat_API
from unittest.mock import MagicMock import pytest from rocketchat_API.rocketchat import RocketChat @pytest.fixture(scope="session") def rocket(): _rocket = RocketChat() return _rocket @pytest.fixture(scope="session") def create_user(rocket): def _create_user(name="user1", password="password", email="email@domain.com"): user = MagicMock() user.name = name user.password = password user.email = email rocket.users_register( email=user.email, name=user.name, password=user.password, username=user.name ) return user return _create_user @pytest.fixture(scope="session") def user(create_user): _user = create_user() return _user @pytest.fixture(scope="session") def logged_rocket(user): _rocket = RocketChat(user.name, user.password) return _rocket Remove Mock and create "empty" object on the fly
import pytest from rocketchat_API.rocketchat import RocketChat @pytest.fixture(scope="session") def rocket(): _rocket = RocketChat() return _rocket @pytest.fixture(scope="session") def create_user(rocket): def _create_user(name="user1", password="password", email="email@domain.com"): # create empty object, because Mock not included to python2 user = type('test', (object,), {})() user.name = name user.password = password user.email = email rocket.users_register( email=user.email, name=user.name, password=user.password, username=user.name ) return user return _create_user @pytest.fixture(scope="session") def user(create_user): _user = create_user() return _user @pytest.fixture(scope="session") def logged_rocket(user): _rocket = RocketChat(user.name, user.password) return _rocket
<commit_before>from unittest.mock import MagicMock import pytest from rocketchat_API.rocketchat import RocketChat @pytest.fixture(scope="session") def rocket(): _rocket = RocketChat() return _rocket @pytest.fixture(scope="session") def create_user(rocket): def _create_user(name="user1", password="password", email="email@domain.com"): user = MagicMock() user.name = name user.password = password user.email = email rocket.users_register( email=user.email, name=user.name, password=user.password, username=user.name ) return user return _create_user @pytest.fixture(scope="session") def user(create_user): _user = create_user() return _user @pytest.fixture(scope="session") def logged_rocket(user): _rocket = RocketChat(user.name, user.password) return _rocket <commit_msg>Remove Mock and create "empty" object on the fly<commit_after>
import pytest from rocketchat_API.rocketchat import RocketChat @pytest.fixture(scope="session") def rocket(): _rocket = RocketChat() return _rocket @pytest.fixture(scope="session") def create_user(rocket): def _create_user(name="user1", password="password", email="email@domain.com"): # create empty object, because Mock not included to python2 user = type('test', (object,), {})() user.name = name user.password = password user.email = email rocket.users_register( email=user.email, name=user.name, password=user.password, username=user.name ) return user return _create_user @pytest.fixture(scope="session") def user(create_user): _user = create_user() return _user @pytest.fixture(scope="session") def logged_rocket(user): _rocket = RocketChat(user.name, user.password) return _rocket
from unittest.mock import MagicMock import pytest from rocketchat_API.rocketchat import RocketChat @pytest.fixture(scope="session") def rocket(): _rocket = RocketChat() return _rocket @pytest.fixture(scope="session") def create_user(rocket): def _create_user(name="user1", password="password", email="email@domain.com"): user = MagicMock() user.name = name user.password = password user.email = email rocket.users_register( email=user.email, name=user.name, password=user.password, username=user.name ) return user return _create_user @pytest.fixture(scope="session") def user(create_user): _user = create_user() return _user @pytest.fixture(scope="session") def logged_rocket(user): _rocket = RocketChat(user.name, user.password) return _rocket Remove Mock and create "empty" object on the flyimport pytest from rocketchat_API.rocketchat import RocketChat @pytest.fixture(scope="session") def rocket(): _rocket = RocketChat() return _rocket @pytest.fixture(scope="session") def create_user(rocket): def _create_user(name="user1", password="password", email="email@domain.com"): # create empty object, because Mock not included to python2 user = type('test', (object,), {})() user.name = name user.password = password user.email = email rocket.users_register( email=user.email, name=user.name, password=user.password, username=user.name ) return user return _create_user @pytest.fixture(scope="session") def user(create_user): _user = create_user() return _user @pytest.fixture(scope="session") def logged_rocket(user): _rocket = RocketChat(user.name, user.password) return _rocket
<commit_before>from unittest.mock import MagicMock import pytest from rocketchat_API.rocketchat import RocketChat @pytest.fixture(scope="session") def rocket(): _rocket = RocketChat() return _rocket @pytest.fixture(scope="session") def create_user(rocket): def _create_user(name="user1", password="password", email="email@domain.com"): user = MagicMock() user.name = name user.password = password user.email = email rocket.users_register( email=user.email, name=user.name, password=user.password, username=user.name ) return user return _create_user @pytest.fixture(scope="session") def user(create_user): _user = create_user() return _user @pytest.fixture(scope="session") def logged_rocket(user): _rocket = RocketChat(user.name, user.password) return _rocket <commit_msg>Remove Mock and create "empty" object on the fly<commit_after>import pytest from rocketchat_API.rocketchat import RocketChat @pytest.fixture(scope="session") def rocket(): _rocket = RocketChat() return _rocket @pytest.fixture(scope="session") def create_user(rocket): def _create_user(name="user1", password="password", email="email@domain.com"): # create empty object, because Mock not included to python2 user = type('test', (object,), {})() user.name = name user.password = password user.email = email rocket.users_register( email=user.email, name=user.name, password=user.password, username=user.name ) return user return _create_user @pytest.fixture(scope="session") def user(create_user): _user = create_user() return _user @pytest.fixture(scope="session") def logged_rocket(user): _rocket = RocketChat(user.name, user.password) return _rocket
00f1ff26fcd7d0398d057eee2c7c6f6b2002e959
tests/conftest.py
tests/conftest.py
import pytest @pytest.fixture def event_loop(): print("in event_loop") try: import asyncio import uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) except ImportError: pass loop = asyncio.new_event_loop() yield loop loop.close()
import pytest @pytest.fixture def event_loop(): try: import asyncio import uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) except ImportError: pass loop = asyncio.new_event_loop() yield loop loop.close()
Remove accidentally left in print statement
Remove accidentally left in print statement
Python
mit
kura/blackhole,kura/blackhole
import pytest @pytest.fixture def event_loop(): print("in event_loop") try: import asyncio import uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) except ImportError: pass loop = asyncio.new_event_loop() yield loop loop.close() Remove accidentally left in print statement
import pytest @pytest.fixture def event_loop(): try: import asyncio import uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) except ImportError: pass loop = asyncio.new_event_loop() yield loop loop.close()
<commit_before>import pytest @pytest.fixture def event_loop(): print("in event_loop") try: import asyncio import uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) except ImportError: pass loop = asyncio.new_event_loop() yield loop loop.close() <commit_msg>Remove accidentally left in print statement<commit_after>
import pytest @pytest.fixture def event_loop(): try: import asyncio import uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) except ImportError: pass loop = asyncio.new_event_loop() yield loop loop.close()
import pytest @pytest.fixture def event_loop(): print("in event_loop") try: import asyncio import uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) except ImportError: pass loop = asyncio.new_event_loop() yield loop loop.close() Remove accidentally left in print statementimport pytest @pytest.fixture def event_loop(): try: import asyncio import uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) except ImportError: pass loop = asyncio.new_event_loop() yield loop loop.close()
<commit_before>import pytest @pytest.fixture def event_loop(): print("in event_loop") try: import asyncio import uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) except ImportError: pass loop = asyncio.new_event_loop() yield loop loop.close() <commit_msg>Remove accidentally left in print statement<commit_after>import pytest @pytest.fixture def event_loop(): try: import asyncio import uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) except ImportError: pass loop = asyncio.new_event_loop() yield loop loop.close()
dcebceec83c31fc9b99cb5e232ae066ee229c3bf
tests/conftest.py
tests/conftest.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # type: ignore """Shared fixture functions.""" import pathlib import pytest # pylint: disable=E0401 import spacy # pylint: disable=E0401 from spacy.language import Language # pylint: disable=E0401 from spacy.tokens import Doc # pylint: disable=E0401 @pytest.fixture(scope="session") def nlp () -> Language: """ Language shared fixture. """ nlp = spacy.load("en_core_web_sm") # pylint: disable=W0621 return nlp @pytest.fixture(scope="session") def doc (nlp: Language) -> Doc: # pylint: disable=W0621 """ Doc shared fixture. returns: spaCy EN doc containing a piece of football news. """ text = pathlib.Path("dat/cfc.txt").read_text() doc = nlp(text) # pylint: disable=W0621 return doc @pytest.fixture(scope="session") def long_doc (nlp: Language) -> Doc: # pylint: disable=W0621 """ Doc shared fixture. returns: spaCy EN doc containing a long text. """ text = pathlib.Path("dat/lee.txt").read_text() doc = nlp(text) # pylint: disable=W0621 return doc
#!/usr/bin/env python # -*- coding: utf-8 -*- # type: ignore """Shared fixture functions.""" import pathlib import pytest # pylint: disable=E0401 import spacy # pylint: disable=E0401 from spacy.language import Language # pylint: disable=E0401 from spacy.tokens import Doc # pylint: disable=E0401 @pytest.fixture(scope="module") def nlp () -> Language: """ Language shared fixture. """ nlp = spacy.load("en_core_web_sm") # pylint: disable=W0621 return nlp @pytest.fixture(scope="module") def doc (nlp: Language) -> Doc: # pylint: disable=W0621 """ Doc shared fixture. returns: spaCy EN doc containing a piece of football news. """ text = pathlib.Path("dat/cfc.txt").read_text() doc = nlp(text) # pylint: disable=W0621 return doc @pytest.fixture(scope="module") def long_doc (nlp: Language) -> Doc: # pylint: disable=W0621 """ Doc shared fixture. returns: spaCy EN doc containing a long text. """ text = pathlib.Path("dat/lee.txt").read_text() doc = nlp(text) # pylint: disable=W0621 return doc
Set fixture scope to module, so that pipes from one file dont influence tests from another
Set fixture scope to module, so that pipes from one file dont influence tests from another
Python
apache-2.0
ceteri/pytextrank,ceteri/pytextrank
#!/usr/bin/env python # -*- coding: utf-8 -*- # type: ignore """Shared fixture functions.""" import pathlib import pytest # pylint: disable=E0401 import spacy # pylint: disable=E0401 from spacy.language import Language # pylint: disable=E0401 from spacy.tokens import Doc # pylint: disable=E0401 @pytest.fixture(scope="session") def nlp () -> Language: """ Language shared fixture. """ nlp = spacy.load("en_core_web_sm") # pylint: disable=W0621 return nlp @pytest.fixture(scope="session") def doc (nlp: Language) -> Doc: # pylint: disable=W0621 """ Doc shared fixture. returns: spaCy EN doc containing a piece of football news. """ text = pathlib.Path("dat/cfc.txt").read_text() doc = nlp(text) # pylint: disable=W0621 return doc @pytest.fixture(scope="session") def long_doc (nlp: Language) -> Doc: # pylint: disable=W0621 """ Doc shared fixture. returns: spaCy EN doc containing a long text. """ text = pathlib.Path("dat/lee.txt").read_text() doc = nlp(text) # pylint: disable=W0621 return doc Set fixture scope to module, so that pipes from one file dont influence tests from another
#!/usr/bin/env python # -*- coding: utf-8 -*- # type: ignore """Shared fixture functions.""" import pathlib import pytest # pylint: disable=E0401 import spacy # pylint: disable=E0401 from spacy.language import Language # pylint: disable=E0401 from spacy.tokens import Doc # pylint: disable=E0401 @pytest.fixture(scope="module") def nlp () -> Language: """ Language shared fixture. """ nlp = spacy.load("en_core_web_sm") # pylint: disable=W0621 return nlp @pytest.fixture(scope="module") def doc (nlp: Language) -> Doc: # pylint: disable=W0621 """ Doc shared fixture. returns: spaCy EN doc containing a piece of football news. """ text = pathlib.Path("dat/cfc.txt").read_text() doc = nlp(text) # pylint: disable=W0621 return doc @pytest.fixture(scope="module") def long_doc (nlp: Language) -> Doc: # pylint: disable=W0621 """ Doc shared fixture. returns: spaCy EN doc containing a long text. """ text = pathlib.Path("dat/lee.txt").read_text() doc = nlp(text) # pylint: disable=W0621 return doc
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- # type: ignore """Shared fixture functions.""" import pathlib import pytest # pylint: disable=E0401 import spacy # pylint: disable=E0401 from spacy.language import Language # pylint: disable=E0401 from spacy.tokens import Doc # pylint: disable=E0401 @pytest.fixture(scope="session") def nlp () -> Language: """ Language shared fixture. """ nlp = spacy.load("en_core_web_sm") # pylint: disable=W0621 return nlp @pytest.fixture(scope="session") def doc (nlp: Language) -> Doc: # pylint: disable=W0621 """ Doc shared fixture. returns: spaCy EN doc containing a piece of football news. """ text = pathlib.Path("dat/cfc.txt").read_text() doc = nlp(text) # pylint: disable=W0621 return doc @pytest.fixture(scope="session") def long_doc (nlp: Language) -> Doc: # pylint: disable=W0621 """ Doc shared fixture. returns: spaCy EN doc containing a long text. """ text = pathlib.Path("dat/lee.txt").read_text() doc = nlp(text) # pylint: disable=W0621 return doc <commit_msg>Set fixture scope to module, so that pipes from one file dont influence tests from another<commit_after>
#!/usr/bin/env python # -*- coding: utf-8 -*- # type: ignore """Shared fixture functions.""" import pathlib import pytest # pylint: disable=E0401 import spacy # pylint: disable=E0401 from spacy.language import Language # pylint: disable=E0401 from spacy.tokens import Doc # pylint: disable=E0401 @pytest.fixture(scope="module") def nlp () -> Language: """ Language shared fixture. """ nlp = spacy.load("en_core_web_sm") # pylint: disable=W0621 return nlp @pytest.fixture(scope="module") def doc (nlp: Language) -> Doc: # pylint: disable=W0621 """ Doc shared fixture. returns: spaCy EN doc containing a piece of football news. """ text = pathlib.Path("dat/cfc.txt").read_text() doc = nlp(text) # pylint: disable=W0621 return doc @pytest.fixture(scope="module") def long_doc (nlp: Language) -> Doc: # pylint: disable=W0621 """ Doc shared fixture. returns: spaCy EN doc containing a long text. """ text = pathlib.Path("dat/lee.txt").read_text() doc = nlp(text) # pylint: disable=W0621 return doc
#!/usr/bin/env python # -*- coding: utf-8 -*- # type: ignore """Shared fixture functions.""" import pathlib import pytest # pylint: disable=E0401 import spacy # pylint: disable=E0401 from spacy.language import Language # pylint: disable=E0401 from spacy.tokens import Doc # pylint: disable=E0401 @pytest.fixture(scope="session") def nlp () -> Language: """ Language shared fixture. """ nlp = spacy.load("en_core_web_sm") # pylint: disable=W0621 return nlp @pytest.fixture(scope="session") def doc (nlp: Language) -> Doc: # pylint: disable=W0621 """ Doc shared fixture. returns: spaCy EN doc containing a piece of football news. """ text = pathlib.Path("dat/cfc.txt").read_text() doc = nlp(text) # pylint: disable=W0621 return doc @pytest.fixture(scope="session") def long_doc (nlp: Language) -> Doc: # pylint: disable=W0621 """ Doc shared fixture. returns: spaCy EN doc containing a long text. """ text = pathlib.Path("dat/lee.txt").read_text() doc = nlp(text) # pylint: disable=W0621 return doc Set fixture scope to module, so that pipes from one file dont influence tests from another#!/usr/bin/env python # -*- coding: utf-8 -*- # type: ignore """Shared fixture functions.""" import pathlib import pytest # pylint: disable=E0401 import spacy # pylint: disable=E0401 from spacy.language import Language # pylint: disable=E0401 from spacy.tokens import Doc # pylint: disable=E0401 @pytest.fixture(scope="module") def nlp () -> Language: """ Language shared fixture. """ nlp = spacy.load("en_core_web_sm") # pylint: disable=W0621 return nlp @pytest.fixture(scope="module") def doc (nlp: Language) -> Doc: # pylint: disable=W0621 """ Doc shared fixture. returns: spaCy EN doc containing a piece of football news. """ text = pathlib.Path("dat/cfc.txt").read_text() doc = nlp(text) # pylint: disable=W0621 return doc @pytest.fixture(scope="module") def long_doc (nlp: Language) -> Doc: # pylint: disable=W0621 """ Doc shared fixture. returns: spaCy EN doc containing a long text. """ text = pathlib.Path("dat/lee.txt").read_text() doc = nlp(text) # pylint: disable=W0621 return doc
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- # type: ignore """Shared fixture functions.""" import pathlib import pytest # pylint: disable=E0401 import spacy # pylint: disable=E0401 from spacy.language import Language # pylint: disable=E0401 from spacy.tokens import Doc # pylint: disable=E0401 @pytest.fixture(scope="session") def nlp () -> Language: """ Language shared fixture. """ nlp = spacy.load("en_core_web_sm") # pylint: disable=W0621 return nlp @pytest.fixture(scope="session") def doc (nlp: Language) -> Doc: # pylint: disable=W0621 """ Doc shared fixture. returns: spaCy EN doc containing a piece of football news. """ text = pathlib.Path("dat/cfc.txt").read_text() doc = nlp(text) # pylint: disable=W0621 return doc @pytest.fixture(scope="session") def long_doc (nlp: Language) -> Doc: # pylint: disable=W0621 """ Doc shared fixture. returns: spaCy EN doc containing a long text. """ text = pathlib.Path("dat/lee.txt").read_text() doc = nlp(text) # pylint: disable=W0621 return doc <commit_msg>Set fixture scope to module, so that pipes from one file dont influence tests from another<commit_after>#!/usr/bin/env python # -*- coding: utf-8 -*- # type: ignore """Shared fixture functions.""" import pathlib import pytest # pylint: disable=E0401 import spacy # pylint: disable=E0401 from spacy.language import Language # pylint: disable=E0401 from spacy.tokens import Doc # pylint: disable=E0401 @pytest.fixture(scope="module") def nlp () -> Language: """ Language shared fixture. """ nlp = spacy.load("en_core_web_sm") # pylint: disable=W0621 return nlp @pytest.fixture(scope="module") def doc (nlp: Language) -> Doc: # pylint: disable=W0621 """ Doc shared fixture. returns: spaCy EN doc containing a piece of football news. """ text = pathlib.Path("dat/cfc.txt").read_text() doc = nlp(text) # pylint: disable=W0621 return doc @pytest.fixture(scope="module") def long_doc (nlp: Language) -> Doc: # pylint: disable=W0621 """ Doc shared fixture. returns: spaCy EN doc containing a long text. """ text = pathlib.Path("dat/lee.txt").read_text() doc = nlp(text) # pylint: disable=W0621 return doc
6b148e4c98628e9ef60cc3ce70c7cdeb8a215c49
scarplet/datasets/base.py
scarplet/datasets/base.py
""" Convenience functions to load example datasets """ import os import scarplet as sl EXAMPLE_DIRECTORY = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data/') def load_carrizo(): path = os.path.join(EXAMPLE_DIRECTORY, 'carrizo.tif') data = sl.load(path) return data def load_grandcanyon(): path = os.path.join(EXAMPLE_DIRECTORY, 'grandcanyon.tif') data = sl.load(path) return data def load_synthetic(): path = os.path.join(EXAMPLE_DIRECTORY, 'synthetic.tif') data = sl.load(path) return data
""" Convenience functions to load example datasets """ import os import scarplet as sl EXAMPLE_DIRECTORY = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data/') def load_carrizo(): """ Load sample dataset containing fault scarps along the San Andreas Fault from the Wallace Creek section on the Carrizo Plain, California, USA Data downloaded from OpenTopography and collected by the B4 Lidar Project: https://catalog.data.gov/dataset/b4-project-southern-san-andreas-and-san-jacinto-faults """ path = os.path.join(EXAMPLE_DIRECTORY, 'carrizo.tif') data = sl.load(path) return data def load_grandcanyon(): """ Load sample dataset containing part of channel network in the Grand Canyon Arizona, USA Data downloaded from the Terrain Tile dataset, part of Amazon Earth on AWS https://registry.opendata.aws/terrain-tiles/ """ path = os.path.join(EXAMPLE_DIRECTORY, 'grandcanyon.tif') data = sl.load(path) return data def load_synthetic(): """ Load sample dataset of synthetic fault scarp of morphologic age 10 m2 """ path = os.path.join(EXAMPLE_DIRECTORY, 'synthetic.tif') data = sl.load(path) return data
Add docstrings for load functions
Add docstrings for load functions
Python
mit
rmsare/scarplet,stgl/scarplet
""" Convenience functions to load example datasets """ import os import scarplet as sl EXAMPLE_DIRECTORY = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data/') def load_carrizo(): path = os.path.join(EXAMPLE_DIRECTORY, 'carrizo.tif') data = sl.load(path) return data def load_grandcanyon(): path = os.path.join(EXAMPLE_DIRECTORY, 'grandcanyon.tif') data = sl.load(path) return data def load_synthetic(): path = os.path.join(EXAMPLE_DIRECTORY, 'synthetic.tif') data = sl.load(path) return data Add docstrings for load functions
""" Convenience functions to load example datasets """ import os import scarplet as sl EXAMPLE_DIRECTORY = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data/') def load_carrizo(): """ Load sample dataset containing fault scarps along the San Andreas Fault from the Wallace Creek section on the Carrizo Plain, California, USA Data downloaded from OpenTopography and collected by the B4 Lidar Project: https://catalog.data.gov/dataset/b4-project-southern-san-andreas-and-san-jacinto-faults """ path = os.path.join(EXAMPLE_DIRECTORY, 'carrizo.tif') data = sl.load(path) return data def load_grandcanyon(): """ Load sample dataset containing part of channel network in the Grand Canyon Arizona, USA Data downloaded from the Terrain Tile dataset, part of Amazon Earth on AWS https://registry.opendata.aws/terrain-tiles/ """ path = os.path.join(EXAMPLE_DIRECTORY, 'grandcanyon.tif') data = sl.load(path) return data def load_synthetic(): """ Load sample dataset of synthetic fault scarp of morphologic age 10 m2 """ path = os.path.join(EXAMPLE_DIRECTORY, 'synthetic.tif') data = sl.load(path) return data
<commit_before>""" Convenience functions to load example datasets """ import os import scarplet as sl EXAMPLE_DIRECTORY = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data/') def load_carrizo(): path = os.path.join(EXAMPLE_DIRECTORY, 'carrizo.tif') data = sl.load(path) return data def load_grandcanyon(): path = os.path.join(EXAMPLE_DIRECTORY, 'grandcanyon.tif') data = sl.load(path) return data def load_synthetic(): path = os.path.join(EXAMPLE_DIRECTORY, 'synthetic.tif') data = sl.load(path) return data <commit_msg>Add docstrings for load functions<commit_after>
""" Convenience functions to load example datasets """ import os import scarplet as sl EXAMPLE_DIRECTORY = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data/') def load_carrizo(): """ Load sample dataset containing fault scarps along the San Andreas Fault from the Wallace Creek section on the Carrizo Plain, California, USA Data downloaded from OpenTopography and collected by the B4 Lidar Project: https://catalog.data.gov/dataset/b4-project-southern-san-andreas-and-san-jacinto-faults """ path = os.path.join(EXAMPLE_DIRECTORY, 'carrizo.tif') data = sl.load(path) return data def load_grandcanyon(): """ Load sample dataset containing part of channel network in the Grand Canyon Arizona, USA Data downloaded from the Terrain Tile dataset, part of Amazon Earth on AWS https://registry.opendata.aws/terrain-tiles/ """ path = os.path.join(EXAMPLE_DIRECTORY, 'grandcanyon.tif') data = sl.load(path) return data def load_synthetic(): """ Load sample dataset of synthetic fault scarp of morphologic age 10 m2 """ path = os.path.join(EXAMPLE_DIRECTORY, 'synthetic.tif') data = sl.load(path) return data
""" Convenience functions to load example datasets """ import os import scarplet as sl EXAMPLE_DIRECTORY = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data/') def load_carrizo(): path = os.path.join(EXAMPLE_DIRECTORY, 'carrizo.tif') data = sl.load(path) return data def load_grandcanyon(): path = os.path.join(EXAMPLE_DIRECTORY, 'grandcanyon.tif') data = sl.load(path) return data def load_synthetic(): path = os.path.join(EXAMPLE_DIRECTORY, 'synthetic.tif') data = sl.load(path) return data Add docstrings for load functions""" Convenience functions to load example datasets """ import os import scarplet as sl EXAMPLE_DIRECTORY = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data/') def load_carrizo(): """ Load sample dataset containing fault scarps along the San Andreas Fault from the Wallace Creek section on the Carrizo Plain, California, USA Data downloaded from OpenTopography and collected by the B4 Lidar Project: https://catalog.data.gov/dataset/b4-project-southern-san-andreas-and-san-jacinto-faults """ path = os.path.join(EXAMPLE_DIRECTORY, 'carrizo.tif') data = sl.load(path) return data def load_grandcanyon(): """ Load sample dataset containing part of channel network in the Grand Canyon Arizona, USA Data downloaded from the Terrain Tile dataset, part of Amazon Earth on AWS https://registry.opendata.aws/terrain-tiles/ """ path = os.path.join(EXAMPLE_DIRECTORY, 'grandcanyon.tif') data = sl.load(path) return data def load_synthetic(): """ Load sample dataset of synthetic fault scarp of morphologic age 10 m2 """ path = os.path.join(EXAMPLE_DIRECTORY, 'synthetic.tif') data = sl.load(path) return data
<commit_before>""" Convenience functions to load example datasets """ import os import scarplet as sl EXAMPLE_DIRECTORY = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data/') def load_carrizo(): path = os.path.join(EXAMPLE_DIRECTORY, 'carrizo.tif') data = sl.load(path) return data def load_grandcanyon(): path = os.path.join(EXAMPLE_DIRECTORY, 'grandcanyon.tif') data = sl.load(path) return data def load_synthetic(): path = os.path.join(EXAMPLE_DIRECTORY, 'synthetic.tif') data = sl.load(path) return data <commit_msg>Add docstrings for load functions<commit_after>""" Convenience functions to load example datasets """ import os import scarplet as sl EXAMPLE_DIRECTORY = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data/') def load_carrizo(): """ Load sample dataset containing fault scarps along the San Andreas Fault from the Wallace Creek section on the Carrizo Plain, California, USA Data downloaded from OpenTopography and collected by the B4 Lidar Project: https://catalog.data.gov/dataset/b4-project-southern-san-andreas-and-san-jacinto-faults """ path = os.path.join(EXAMPLE_DIRECTORY, 'carrizo.tif') data = sl.load(path) return data def load_grandcanyon(): """ Load sample dataset containing part of channel network in the Grand Canyon Arizona, USA Data downloaded from the Terrain Tile dataset, part of Amazon Earth on AWS https://registry.opendata.aws/terrain-tiles/ """ path = os.path.join(EXAMPLE_DIRECTORY, 'grandcanyon.tif') data = sl.load(path) return data def load_synthetic(): """ Load sample dataset of synthetic fault scarp of morphologic age 10 m2 """ path = os.path.join(EXAMPLE_DIRECTORY, 'synthetic.tif') data = sl.load(path) return data
39acab842be6a82d687d4edf6c1d29e7bf293fae
udp_logger.py
udp_logger.py
#!/usr/bin/python # -*- coding: utf-8 -*- from socket import socket, AF_INET, SOCK_DGRAM def create_udp_server_socket(endpoint): skt = socket(AF_INET, SOCK_DGRAM) skt.bind(endpoint) return skt if __name__ == '__main__': ENDPOINT = ("", 3000) # empty string == INADDR_ANY skt = create_udp_server_socket(ENDPOINT) while True: data, (host, port) = skt.recvfrom(1500) print "(%s:%i) %s" % (host, port, data)
#!/usr/bin/python # -*- coding: utf-8 -*- from socket import socket, AF_INET, SOCK_DGRAM from optparse import OptionParser def create_udp_server_socket(endpoint): skt = socket(AF_INET, SOCK_DGRAM) skt.bind(endpoint) return skt def MakeOptionParser(): parser = OptionParser() parser.add_option('-a', '--append', dest='append', metavar="FILE", help="Append log data to this file") return parser if __name__ == '__main__': parser = MakeOptionParser() options, args = parser.parse_args() append_file = None if options.append: append_file = open(options.append, 'a', 0) ENDPOINT = ("", 3000) # empty string == INADDR_ANY skt = create_udp_server_socket(ENDPOINT) while True: data, (host, port) = skt.recvfrom(1500) log_line = "(%s:%i) %s\n" % (host, port, data) print log_line, if append_file: append_file.write(log_line)
Support for appending to a file
Support for appending to a file
Python
mit
tmacam/remote_logging_cpp,tmacam/remote_logging_cpp
#!/usr/bin/python # -*- coding: utf-8 -*- from socket import socket, AF_INET, SOCK_DGRAM def create_udp_server_socket(endpoint): skt = socket(AF_INET, SOCK_DGRAM) skt.bind(endpoint) return skt if __name__ == '__main__': ENDPOINT = ("", 3000) # empty string == INADDR_ANY skt = create_udp_server_socket(ENDPOINT) while True: data, (host, port) = skt.recvfrom(1500) print "(%s:%i) %s" % (host, port, data) Support for appending to a file
#!/usr/bin/python # -*- coding: utf-8 -*- from socket import socket, AF_INET, SOCK_DGRAM from optparse import OptionParser def create_udp_server_socket(endpoint): skt = socket(AF_INET, SOCK_DGRAM) skt.bind(endpoint) return skt def MakeOptionParser(): parser = OptionParser() parser.add_option('-a', '--append', dest='append', metavar="FILE", help="Append log data to this file") return parser if __name__ == '__main__': parser = MakeOptionParser() options, args = parser.parse_args() append_file = None if options.append: append_file = open(options.append, 'a', 0) ENDPOINT = ("", 3000) # empty string == INADDR_ANY skt = create_udp_server_socket(ENDPOINT) while True: data, (host, port) = skt.recvfrom(1500) log_line = "(%s:%i) %s\n" % (host, port, data) print log_line, if append_file: append_file.write(log_line)
<commit_before>#!/usr/bin/python # -*- coding: utf-8 -*- from socket import socket, AF_INET, SOCK_DGRAM def create_udp_server_socket(endpoint): skt = socket(AF_INET, SOCK_DGRAM) skt.bind(endpoint) return skt if __name__ == '__main__': ENDPOINT = ("", 3000) # empty string == INADDR_ANY skt = create_udp_server_socket(ENDPOINT) while True: data, (host, port) = skt.recvfrom(1500) print "(%s:%i) %s" % (host, port, data) <commit_msg>Support for appending to a file<commit_after>
#!/usr/bin/python # -*- coding: utf-8 -*- from socket import socket, AF_INET, SOCK_DGRAM from optparse import OptionParser def create_udp_server_socket(endpoint): skt = socket(AF_INET, SOCK_DGRAM) skt.bind(endpoint) return skt def MakeOptionParser(): parser = OptionParser() parser.add_option('-a', '--append', dest='append', metavar="FILE", help="Append log data to this file") return parser if __name__ == '__main__': parser = MakeOptionParser() options, args = parser.parse_args() append_file = None if options.append: append_file = open(options.append, 'a', 0) ENDPOINT = ("", 3000) # empty string == INADDR_ANY skt = create_udp_server_socket(ENDPOINT) while True: data, (host, port) = skt.recvfrom(1500) log_line = "(%s:%i) %s\n" % (host, port, data) print log_line, if append_file: append_file.write(log_line)
#!/usr/bin/python # -*- coding: utf-8 -*- from socket import socket, AF_INET, SOCK_DGRAM def create_udp_server_socket(endpoint): skt = socket(AF_INET, SOCK_DGRAM) skt.bind(endpoint) return skt if __name__ == '__main__': ENDPOINT = ("", 3000) # empty string == INADDR_ANY skt = create_udp_server_socket(ENDPOINT) while True: data, (host, port) = skt.recvfrom(1500) print "(%s:%i) %s" % (host, port, data) Support for appending to a file#!/usr/bin/python # -*- coding: utf-8 -*- from socket import socket, AF_INET, SOCK_DGRAM from optparse import OptionParser def create_udp_server_socket(endpoint): skt = socket(AF_INET, SOCK_DGRAM) skt.bind(endpoint) return skt def MakeOptionParser(): parser = OptionParser() parser.add_option('-a', '--append', dest='append', metavar="FILE", help="Append log data to this file") return parser if __name__ == '__main__': parser = MakeOptionParser() options, args = parser.parse_args() append_file = None if options.append: append_file = open(options.append, 'a', 0) ENDPOINT = ("", 3000) # empty string == INADDR_ANY skt = create_udp_server_socket(ENDPOINT) while True: data, (host, port) = skt.recvfrom(1500) log_line = "(%s:%i) %s\n" % (host, port, data) print log_line, if append_file: append_file.write(log_line)
<commit_before>#!/usr/bin/python # -*- coding: utf-8 -*- from socket import socket, AF_INET, SOCK_DGRAM def create_udp_server_socket(endpoint): skt = socket(AF_INET, SOCK_DGRAM) skt.bind(endpoint) return skt if __name__ == '__main__': ENDPOINT = ("", 3000) # empty string == INADDR_ANY skt = create_udp_server_socket(ENDPOINT) while True: data, (host, port) = skt.recvfrom(1500) print "(%s:%i) %s" % (host, port, data) <commit_msg>Support for appending to a file<commit_after>#!/usr/bin/python # -*- coding: utf-8 -*- from socket import socket, AF_INET, SOCK_DGRAM from optparse import OptionParser def create_udp_server_socket(endpoint): skt = socket(AF_INET, SOCK_DGRAM) skt.bind(endpoint) return skt def MakeOptionParser(): parser = OptionParser() parser.add_option('-a', '--append', dest='append', metavar="FILE", help="Append log data to this file") return parser if __name__ == '__main__': parser = MakeOptionParser() options, args = parser.parse_args() append_file = None if options.append: append_file = open(options.append, 'a', 0) ENDPOINT = ("", 3000) # empty string == INADDR_ANY skt = create_udp_server_socket(ENDPOINT) while True: data, (host, port) = skt.recvfrom(1500) log_line = "(%s:%i) %s\n" % (host, port, data) print log_line, if append_file: append_file.write(log_line)
3a74774a42521f4b68e484855d103495438095c3
examples/schema/targetinfo.py
examples/schema/targetinfo.py
import jsl class TargetInfo(jsl.Document): docker = jsl.ArrayField(jsl.StringField(), max_items=2) rsync = jsl.ArrayField(jsl.StringField(), max_items=2) containers = jsl.ArrayField([ jsl.StringField(), jsl.ArrayField(jsl.StringField()) ])
import jsl class TargetInfo(jsl.Document): docker = jsl.ArrayField([ jsl.StringField(), jsl.OneOfField([jsl.StringField(), jsl.NullField()]) ]) rsync = jsl.ArrayField([ jsl.StringField(), jsl.OneOfField([jsl.StringField(), jsl.NullField()]) ]) containers = jsl.ArrayField([ jsl.StringField(), jsl.ArrayField(jsl.StringField()) ])
Correct the target info schema: docker and rsync messages are Null in case of success. Suggested by @vinzenz and corrected by @artmello.
Correct the target info schema: docker and rsync messages are Null in case of success. Suggested by @vinzenz and corrected by @artmello.
Python
apache-2.0
leapp-to/snactor
import jsl class TargetInfo(jsl.Document): docker = jsl.ArrayField(jsl.StringField(), max_items=2) rsync = jsl.ArrayField(jsl.StringField(), max_items=2) containers = jsl.ArrayField([ jsl.StringField(), jsl.ArrayField(jsl.StringField()) ]) Correct the target info schema: docker and rsync messages are Null in case of success. Suggested by @vinzenz and corrected by @artmello.
import jsl class TargetInfo(jsl.Document): docker = jsl.ArrayField([ jsl.StringField(), jsl.OneOfField([jsl.StringField(), jsl.NullField()]) ]) rsync = jsl.ArrayField([ jsl.StringField(), jsl.OneOfField([jsl.StringField(), jsl.NullField()]) ]) containers = jsl.ArrayField([ jsl.StringField(), jsl.ArrayField(jsl.StringField()) ])
<commit_before>import jsl class TargetInfo(jsl.Document): docker = jsl.ArrayField(jsl.StringField(), max_items=2) rsync = jsl.ArrayField(jsl.StringField(), max_items=2) containers = jsl.ArrayField([ jsl.StringField(), jsl.ArrayField(jsl.StringField()) ]) <commit_msg>Correct the target info schema: docker and rsync messages are Null in case of success. Suggested by @vinzenz and corrected by @artmello.<commit_after>
import jsl class TargetInfo(jsl.Document): docker = jsl.ArrayField([ jsl.StringField(), jsl.OneOfField([jsl.StringField(), jsl.NullField()]) ]) rsync = jsl.ArrayField([ jsl.StringField(), jsl.OneOfField([jsl.StringField(), jsl.NullField()]) ]) containers = jsl.ArrayField([ jsl.StringField(), jsl.ArrayField(jsl.StringField()) ])
import jsl class TargetInfo(jsl.Document): docker = jsl.ArrayField(jsl.StringField(), max_items=2) rsync = jsl.ArrayField(jsl.StringField(), max_items=2) containers = jsl.ArrayField([ jsl.StringField(), jsl.ArrayField(jsl.StringField()) ]) Correct the target info schema: docker and rsync messages are Null in case of success. Suggested by @vinzenz and corrected by @artmello.import jsl class TargetInfo(jsl.Document): docker = jsl.ArrayField([ jsl.StringField(), jsl.OneOfField([jsl.StringField(), jsl.NullField()]) ]) rsync = jsl.ArrayField([ jsl.StringField(), jsl.OneOfField([jsl.StringField(), jsl.NullField()]) ]) containers = jsl.ArrayField([ jsl.StringField(), jsl.ArrayField(jsl.StringField()) ])
<commit_before>import jsl class TargetInfo(jsl.Document): docker = jsl.ArrayField(jsl.StringField(), max_items=2) rsync = jsl.ArrayField(jsl.StringField(), max_items=2) containers = jsl.ArrayField([ jsl.StringField(), jsl.ArrayField(jsl.StringField()) ]) <commit_msg>Correct the target info schema: docker and rsync messages are Null in case of success. Suggested by @vinzenz and corrected by @artmello.<commit_after>import jsl class TargetInfo(jsl.Document): docker = jsl.ArrayField([ jsl.StringField(), jsl.OneOfField([jsl.StringField(), jsl.NullField()]) ]) rsync = jsl.ArrayField([ jsl.StringField(), jsl.OneOfField([jsl.StringField(), jsl.NullField()]) ]) containers = jsl.ArrayField([ jsl.StringField(), jsl.ArrayField(jsl.StringField()) ])
74260bc1b401d9ec500fba1eae72b99c2a2db147
github.py
github.py
import requests GITHUB_API_URL = "https://api.github.com/graphql" QUERY = """ query($repository_owner:String!, $repository_name: String!, $count: Int!) { repository( owner: $repository_owner, name: $repository_name) { refs(last: $count,refPrefix:"refs/tags/") { edges { node{ name } } } releases(last: $count) { edges { node { name } } } } } """ class Github: def __authorization_header(self): return "token " + self.token def __request_headers(self): return { 'authorization': self.__authorization_header(), } def __init__(self, token): self.token = token def getTagsAndReleases(self, repository_owner, repository_name, count): payload = {"query": QUERY, "variables": { "repository_owner": repository_owner, "repository_name": repository_name, "count": count }} print "Requesting for", repository_name response = requests.post(GITHUB_API_URL, json=payload, headers=self.__request_headers()) print "Got status code for", repository_name, response.status_code return response.json()
import requests GITHUB_API_URL = "https://api.github.com/graphql" QUERY = """ query($repository_owner:String!, $repository_name: String!, $count: Int!) { repository(owner: $repository_owner, name: $repository_name) { refs(last: $count,refPrefix:"refs/tags/") { nodes { name target { commitUrl } } } releases(last: $count) { nodes { tag { name prefix } } } } } """ class Github: def __authorization_header(self): return "token " + self.token def __request_headers(self): return { 'authorization': self.__authorization_header(), } def __init__(self, token): self.token = token def getTagsAndReleases(self, repository_owner, repository_name, count): payload = {"query": QUERY, "variables": { "repository_owner": repository_owner, "repository_name": repository_name, "count": count }} print "Requesting for", repository_name response = requests.post(GITHUB_API_URL, json=payload, headers=self.__request_headers()) print "Got status code for", repository_name, response.status_code return response.json()
Update query to use nodes
Update query to use nodes
Python
mit
ayushgoel/LongShot
import requests GITHUB_API_URL = "https://api.github.com/graphql" QUERY = """ query($repository_owner:String!, $repository_name: String!, $count: Int!) { repository( owner: $repository_owner, name: $repository_name) { refs(last: $count,refPrefix:"refs/tags/") { edges { node{ name } } } releases(last: $count) { edges { node { name } } } } } """ class Github: def __authorization_header(self): return "token " + self.token def __request_headers(self): return { 'authorization': self.__authorization_header(), } def __init__(self, token): self.token = token def getTagsAndReleases(self, repository_owner, repository_name, count): payload = {"query": QUERY, "variables": { "repository_owner": repository_owner, "repository_name": repository_name, "count": count }} print "Requesting for", repository_name response = requests.post(GITHUB_API_URL, json=payload, headers=self.__request_headers()) print "Got status code for", repository_name, response.status_code return response.json()Update query to use nodes
import requests GITHUB_API_URL = "https://api.github.com/graphql" QUERY = """ query($repository_owner:String!, $repository_name: String!, $count: Int!) { repository(owner: $repository_owner, name: $repository_name) { refs(last: $count,refPrefix:"refs/tags/") { nodes { name target { commitUrl } } } releases(last: $count) { nodes { tag { name prefix } } } } } """ class Github: def __authorization_header(self): return "token " + self.token def __request_headers(self): return { 'authorization': self.__authorization_header(), } def __init__(self, token): self.token = token def getTagsAndReleases(self, repository_owner, repository_name, count): payload = {"query": QUERY, "variables": { "repository_owner": repository_owner, "repository_name": repository_name, "count": count }} print "Requesting for", repository_name response = requests.post(GITHUB_API_URL, json=payload, headers=self.__request_headers()) print "Got status code for", repository_name, response.status_code return response.json()
<commit_before>import requests GITHUB_API_URL = "https://api.github.com/graphql" QUERY = """ query($repository_owner:String!, $repository_name: String!, $count: Int!) { repository( owner: $repository_owner, name: $repository_name) { refs(last: $count,refPrefix:"refs/tags/") { edges { node{ name } } } releases(last: $count) { edges { node { name } } } } } """ class Github: def __authorization_header(self): return "token " + self.token def __request_headers(self): return { 'authorization': self.__authorization_header(), } def __init__(self, token): self.token = token def getTagsAndReleases(self, repository_owner, repository_name, count): payload = {"query": QUERY, "variables": { "repository_owner": repository_owner, "repository_name": repository_name, "count": count }} print "Requesting for", repository_name response = requests.post(GITHUB_API_URL, json=payload, headers=self.__request_headers()) print "Got status code for", repository_name, response.status_code return response.json()<commit_msg>Update query to use nodes<commit_after>
import requests GITHUB_API_URL = "https://api.github.com/graphql" QUERY = """ query($repository_owner:String!, $repository_name: String!, $count: Int!) { repository(owner: $repository_owner, name: $repository_name) { refs(last: $count,refPrefix:"refs/tags/") { nodes { name target { commitUrl } } } releases(last: $count) { nodes { tag { name prefix } } } } } """ class Github: def __authorization_header(self): return "token " + self.token def __request_headers(self): return { 'authorization': self.__authorization_header(), } def __init__(self, token): self.token = token def getTagsAndReleases(self, repository_owner, repository_name, count): payload = {"query": QUERY, "variables": { "repository_owner": repository_owner, "repository_name": repository_name, "count": count }} print "Requesting for", repository_name response = requests.post(GITHUB_API_URL, json=payload, headers=self.__request_headers()) print "Got status code for", repository_name, response.status_code return response.json()
import requests GITHUB_API_URL = "https://api.github.com/graphql" QUERY = """ query($repository_owner:String!, $repository_name: String!, $count: Int!) { repository( owner: $repository_owner, name: $repository_name) { refs(last: $count,refPrefix:"refs/tags/") { edges { node{ name } } } releases(last: $count) { edges { node { name } } } } } """ class Github: def __authorization_header(self): return "token " + self.token def __request_headers(self): return { 'authorization': self.__authorization_header(), } def __init__(self, token): self.token = token def getTagsAndReleases(self, repository_owner, repository_name, count): payload = {"query": QUERY, "variables": { "repository_owner": repository_owner, "repository_name": repository_name, "count": count }} print "Requesting for", repository_name response = requests.post(GITHUB_API_URL, json=payload, headers=self.__request_headers()) print "Got status code for", repository_name, response.status_code return response.json()Update query to use nodesimport requests GITHUB_API_URL = "https://api.github.com/graphql" QUERY = """ query($repository_owner:String!, $repository_name: String!, $count: Int!) { repository(owner: $repository_owner, name: $repository_name) { refs(last: $count,refPrefix:"refs/tags/") { nodes { name target { commitUrl } } } releases(last: $count) { nodes { tag { name prefix } } } } } """ class Github: def __authorization_header(self): return "token " + self.token def __request_headers(self): return { 'authorization': self.__authorization_header(), } def __init__(self, token): self.token = token def getTagsAndReleases(self, repository_owner, repository_name, count): payload = {"query": QUERY, "variables": { "repository_owner": repository_owner, "repository_name": repository_name, "count": count }} print "Requesting for", repository_name response = requests.post(GITHUB_API_URL, json=payload, headers=self.__request_headers()) print "Got status code for", repository_name, response.status_code return response.json()
<commit_before>import requests GITHUB_API_URL = "https://api.github.com/graphql" QUERY = """ query($repository_owner:String!, $repository_name: String!, $count: Int!) { repository( owner: $repository_owner, name: $repository_name) { refs(last: $count,refPrefix:"refs/tags/") { edges { node{ name } } } releases(last: $count) { edges { node { name } } } } } """ class Github: def __authorization_header(self): return "token " + self.token def __request_headers(self): return { 'authorization': self.__authorization_header(), } def __init__(self, token): self.token = token def getTagsAndReleases(self, repository_owner, repository_name, count): payload = {"query": QUERY, "variables": { "repository_owner": repository_owner, "repository_name": repository_name, "count": count }} print "Requesting for", repository_name response = requests.post(GITHUB_API_URL, json=payload, headers=self.__request_headers()) print "Got status code for", repository_name, response.status_code return response.json()<commit_msg>Update query to use nodes<commit_after>import requests GITHUB_API_URL = "https://api.github.com/graphql" QUERY = """ query($repository_owner:String!, $repository_name: String!, $count: Int!) { repository(owner: $repository_owner, name: $repository_name) { refs(last: $count,refPrefix:"refs/tags/") { nodes { name target { commitUrl } } } releases(last: $count) { nodes { tag { name prefix } } } } } """ class Github: def __authorization_header(self): return "token " + self.token def __request_headers(self): return { 'authorization': self.__authorization_header(), } def __init__(self, token): self.token = token def getTagsAndReleases(self, repository_owner, repository_name, count): payload = {"query": QUERY, "variables": { "repository_owner": repository_owner, "repository_name": repository_name, "count": count }} print "Requesting for", repository_name response = requests.post(GITHUB_API_URL, json=payload, headers=self.__request_headers()) print "Got status code for", repository_name, response.status_code return response.json()
05e62b96cfa50934d98d78a86307d94239dd7a4b
Orange/__init__.py
Orange/__init__.py
from .misc.lazy_module import LazyModule from .version import \ short_version as __version__, git_revision as __git_version__ ADDONS_ENTRY_POINT = 'orange.addons' from Orange import data for mod_name in ['classification', 'clustering', 'distance', 'evaluation', 'feature', 'misc', 'regression', 'statistics', 'widgets']: globals()[mod_name] = LazyModule(mod_name) del mod_name del LazyModule
from .misc.lazy_module import LazyModule from .version import \ short_version as __version__, git_revision as __git_version__ ADDONS_ENTRY_POINT = 'orange.addons' from Orange import data for mod_name in ['classification', 'clustering', 'distance', 'evaluation', 'feature', 'misc', 'regression', 'statistics', 'widgets', 'preprocess']: globals()[mod_name] = LazyModule(mod_name) del mod_name del LazyModule
Add preprocess to the list of modules lazy-imported in Orange
Add preprocess to the list of modules lazy-imported in Orange
Python
bsd-2-clause
cheral/orange3,qPCR4vir/orange3,kwikadi/orange3,qusp/orange3,cheral/orange3,cheral/orange3,marinkaz/orange3,kwikadi/orange3,kwikadi/orange3,cheral/orange3,qPCR4vir/orange3,qPCR4vir/orange3,qusp/orange3,kwikadi/orange3,marinkaz/orange3,marinkaz/orange3,kwikadi/orange3,qusp/orange3,marinkaz/orange3,qusp/orange3,qPCR4vir/orange3,cheral/orange3,marinkaz/orange3,cheral/orange3,qPCR4vir/orange3,marinkaz/orange3,qPCR4vir/orange3,kwikadi/orange3
from .misc.lazy_module import LazyModule from .version import \ short_version as __version__, git_revision as __git_version__ ADDONS_ENTRY_POINT = 'orange.addons' from Orange import data for mod_name in ['classification', 'clustering', 'distance', 'evaluation', 'feature', 'misc', 'regression', 'statistics', 'widgets']: globals()[mod_name] = LazyModule(mod_name) del mod_name del LazyModule Add preprocess to the list of modules lazy-imported in Orange
from .misc.lazy_module import LazyModule from .version import \ short_version as __version__, git_revision as __git_version__ ADDONS_ENTRY_POINT = 'orange.addons' from Orange import data for mod_name in ['classification', 'clustering', 'distance', 'evaluation', 'feature', 'misc', 'regression', 'statistics', 'widgets', 'preprocess']: globals()[mod_name] = LazyModule(mod_name) del mod_name del LazyModule
<commit_before>from .misc.lazy_module import LazyModule from .version import \ short_version as __version__, git_revision as __git_version__ ADDONS_ENTRY_POINT = 'orange.addons' from Orange import data for mod_name in ['classification', 'clustering', 'distance', 'evaluation', 'feature', 'misc', 'regression', 'statistics', 'widgets']: globals()[mod_name] = LazyModule(mod_name) del mod_name del LazyModule <commit_msg>Add preprocess to the list of modules lazy-imported in Orange<commit_after>
from .misc.lazy_module import LazyModule from .version import \ short_version as __version__, git_revision as __git_version__ ADDONS_ENTRY_POINT = 'orange.addons' from Orange import data for mod_name in ['classification', 'clustering', 'distance', 'evaluation', 'feature', 'misc', 'regression', 'statistics', 'widgets', 'preprocess']: globals()[mod_name] = LazyModule(mod_name) del mod_name del LazyModule
from .misc.lazy_module import LazyModule from .version import \ short_version as __version__, git_revision as __git_version__ ADDONS_ENTRY_POINT = 'orange.addons' from Orange import data for mod_name in ['classification', 'clustering', 'distance', 'evaluation', 'feature', 'misc', 'regression', 'statistics', 'widgets']: globals()[mod_name] = LazyModule(mod_name) del mod_name del LazyModule Add preprocess to the list of modules lazy-imported in Orangefrom .misc.lazy_module import LazyModule from .version import \ short_version as __version__, git_revision as __git_version__ ADDONS_ENTRY_POINT = 'orange.addons' from Orange import data for mod_name in ['classification', 'clustering', 'distance', 'evaluation', 'feature', 'misc', 'regression', 'statistics', 'widgets', 'preprocess']: globals()[mod_name] = LazyModule(mod_name) del mod_name del LazyModule
<commit_before>from .misc.lazy_module import LazyModule from .version import \ short_version as __version__, git_revision as __git_version__ ADDONS_ENTRY_POINT = 'orange.addons' from Orange import data for mod_name in ['classification', 'clustering', 'distance', 'evaluation', 'feature', 'misc', 'regression', 'statistics', 'widgets']: globals()[mod_name] = LazyModule(mod_name) del mod_name del LazyModule <commit_msg>Add preprocess to the list of modules lazy-imported in Orange<commit_after>from .misc.lazy_module import LazyModule from .version import \ short_version as __version__, git_revision as __git_version__ ADDONS_ENTRY_POINT = 'orange.addons' from Orange import data for mod_name in ['classification', 'clustering', 'distance', 'evaluation', 'feature', 'misc', 'regression', 'statistics', 'widgets', 'preprocess']: globals()[mod_name] = LazyModule(mod_name) del mod_name del LazyModule
896a9b3d116a6ac2d313c5ea8dbc16345a097138
linguine/ops/StanfordCoreNLP.py
linguine/ops/StanfordCoreNLP.py
#!/usr/bin/env python import os """ Performs some core NLP operations as a proof of concept for the library. """ from stanford_corenlp_pywrapper import CoreNLP class StanfordCoreNLP: def __init__(self): # I don't see anywhere to put properties like this path... # For now it's hardcoded and would need to be changed when deployed... coreNLPPath = os.path.join(os.path.dirname(__file__), '../../lib/stanfordCoreNLP.jar') coreNLPModelsPath = os.path.join(os.path.dirname(__file__), '../../lib/stanfordCoreNLPModels.jar') self.proc = CoreNLP('pos', corenlp_jars=[coreNLPPath, coreNLPModelsPath]) def run(self, data): results = [] for corpus in data: results.append(self.proc.parse_doc(corpus.contents)) return results
#!/usr/bin/env python import os """ Performs some core NLP operations as a proof of concept for the library. """ from stanford_corenlp_pywrapper import CoreNLP class StanfordCoreNLP: """ When the JSON segments return from the CoreNLP library, they separate the data acquired from each word into their own element. For readability's sake, it would be nice to pair all of the information for a given word with that word, making a list of words with their part of speech tags """ def jsonCleanup(self, data): for corpus in data: res = self.proc.parse_doc(corpus.contents) for sentence in res["sentences"]: words = [] for index, token in enumerate(sentence["tokens"]): word = {} word["token"] = sentence["tokens"][index] word["lemma"] = sentence["lemmas"][index] word["part-of-speech"] = sentence["pos"][index] words.append(word) return words def __init__(self): coreNLPPath = os.path.join(os.path.dirname(__file__), '../../lib/stanfordCoreNLP.jar') coreNLPModelsPath = os.path.join(os.path.dirname(__file__), '../../lib/stanfordCoreNLPModels.jar') self.proc = CoreNLP('pos', corenlp_jars=[coreNLPPath, coreNLPModelsPath]) def run(self, data): return self.jsonCleanup(data)
Format JSON to be collections of tokens
Format JSON to be collections of tokens When coreNLP returns the JSON payload, it is in an unmanageable format where multiple arrays are made for all parts of speech, tokens, and lemmas. It's much easier to manage when the response is formatted as a list of objects: { "token": "Pineapple", "lemma": "Pineapple", "part-of-speech": "DT" }
Python
mit
rigatoni/linguine-python,Pastafarians/linguine-python
#!/usr/bin/env python import os """ Performs some core NLP operations as a proof of concept for the library. """ from stanford_corenlp_pywrapper import CoreNLP class StanfordCoreNLP: def __init__(self): # I don't see anywhere to put properties like this path... # For now it's hardcoded and would need to be changed when deployed... coreNLPPath = os.path.join(os.path.dirname(__file__), '../../lib/stanfordCoreNLP.jar') coreNLPModelsPath = os.path.join(os.path.dirname(__file__), '../../lib/stanfordCoreNLPModels.jar') self.proc = CoreNLP('pos', corenlp_jars=[coreNLPPath, coreNLPModelsPath]) def run(self, data): results = [] for corpus in data: results.append(self.proc.parse_doc(corpus.contents)) return results Format JSON to be collections of tokens When coreNLP returns the JSON payload, it is in an unmanageable format where multiple arrays are made for all parts of speech, tokens, and lemmas. It's much easier to manage when the response is formatted as a list of objects: { "token": "Pineapple", "lemma": "Pineapple", "part-of-speech": "DT" }
#!/usr/bin/env python import os """ Performs some core NLP operations as a proof of concept for the library. """ from stanford_corenlp_pywrapper import CoreNLP class StanfordCoreNLP: """ When the JSON segments return from the CoreNLP library, they separate the data acquired from each word into their own element. For readability's sake, it would be nice to pair all of the information for a given word with that word, making a list of words with their part of speech tags """ def jsonCleanup(self, data): for corpus in data: res = self.proc.parse_doc(corpus.contents) for sentence in res["sentences"]: words = [] for index, token in enumerate(sentence["tokens"]): word = {} word["token"] = sentence["tokens"][index] word["lemma"] = sentence["lemmas"][index] word["part-of-speech"] = sentence["pos"][index] words.append(word) return words def __init__(self): coreNLPPath = os.path.join(os.path.dirname(__file__), '../../lib/stanfordCoreNLP.jar') coreNLPModelsPath = os.path.join(os.path.dirname(__file__), '../../lib/stanfordCoreNLPModels.jar') self.proc = CoreNLP('pos', corenlp_jars=[coreNLPPath, coreNLPModelsPath]) def run(self, data): return self.jsonCleanup(data)
<commit_before>#!/usr/bin/env python import os """ Performs some core NLP operations as a proof of concept for the library. """ from stanford_corenlp_pywrapper import CoreNLP class StanfordCoreNLP: def __init__(self): # I don't see anywhere to put properties like this path... # For now it's hardcoded and would need to be changed when deployed... coreNLPPath = os.path.join(os.path.dirname(__file__), '../../lib/stanfordCoreNLP.jar') coreNLPModelsPath = os.path.join(os.path.dirname(__file__), '../../lib/stanfordCoreNLPModels.jar') self.proc = CoreNLP('pos', corenlp_jars=[coreNLPPath, coreNLPModelsPath]) def run(self, data): results = [] for corpus in data: results.append(self.proc.parse_doc(corpus.contents)) return results <commit_msg>Format JSON to be collections of tokens When coreNLP returns the JSON payload, it is in an unmanageable format where multiple arrays are made for all parts of speech, tokens, and lemmas. It's much easier to manage when the response is formatted as a list of objects: { "token": "Pineapple", "lemma": "Pineapple", "part-of-speech": "DT" }<commit_after>
#!/usr/bin/env python import os """ Performs some core NLP operations as a proof of concept for the library. """ from stanford_corenlp_pywrapper import CoreNLP class StanfordCoreNLP: """ When the JSON segments return from the CoreNLP library, they separate the data acquired from each word into their own element. For readability's sake, it would be nice to pair all of the information for a given word with that word, making a list of words with their part of speech tags """ def jsonCleanup(self, data): for corpus in data: res = self.proc.parse_doc(corpus.contents) for sentence in res["sentences"]: words = [] for index, token in enumerate(sentence["tokens"]): word = {} word["token"] = sentence["tokens"][index] word["lemma"] = sentence["lemmas"][index] word["part-of-speech"] = sentence["pos"][index] words.append(word) return words def __init__(self): coreNLPPath = os.path.join(os.path.dirname(__file__), '../../lib/stanfordCoreNLP.jar') coreNLPModelsPath = os.path.join(os.path.dirname(__file__), '../../lib/stanfordCoreNLPModels.jar') self.proc = CoreNLP('pos', corenlp_jars=[coreNLPPath, coreNLPModelsPath]) def run(self, data): return self.jsonCleanup(data)
#!/usr/bin/env python import os """ Performs some core NLP operations as a proof of concept for the library. """ from stanford_corenlp_pywrapper import CoreNLP class StanfordCoreNLP: def __init__(self): # I don't see anywhere to put properties like this path... # For now it's hardcoded and would need to be changed when deployed... coreNLPPath = os.path.join(os.path.dirname(__file__), '../../lib/stanfordCoreNLP.jar') coreNLPModelsPath = os.path.join(os.path.dirname(__file__), '../../lib/stanfordCoreNLPModels.jar') self.proc = CoreNLP('pos', corenlp_jars=[coreNLPPath, coreNLPModelsPath]) def run(self, data): results = [] for corpus in data: results.append(self.proc.parse_doc(corpus.contents)) return results Format JSON to be collections of tokens When coreNLP returns the JSON payload, it is in an unmanageable format where multiple arrays are made for all parts of speech, tokens, and lemmas. It's much easier to manage when the response is formatted as a list of objects: { "token": "Pineapple", "lemma": "Pineapple", "part-of-speech": "DT" }#!/usr/bin/env python import os """ Performs some core NLP operations as a proof of concept for the library. """ from stanford_corenlp_pywrapper import CoreNLP class StanfordCoreNLP: """ When the JSON segments return from the CoreNLP library, they separate the data acquired from each word into their own element. For readability's sake, it would be nice to pair all of the information for a given word with that word, making a list of words with their part of speech tags """ def jsonCleanup(self, data): for corpus in data: res = self.proc.parse_doc(corpus.contents) for sentence in res["sentences"]: words = [] for index, token in enumerate(sentence["tokens"]): word = {} word["token"] = sentence["tokens"][index] word["lemma"] = sentence["lemmas"][index] word["part-of-speech"] = sentence["pos"][index] words.append(word) return words def __init__(self): coreNLPPath = os.path.join(os.path.dirname(__file__), '../../lib/stanfordCoreNLP.jar') coreNLPModelsPath = os.path.join(os.path.dirname(__file__), '../../lib/stanfordCoreNLPModels.jar') self.proc = CoreNLP('pos', corenlp_jars=[coreNLPPath, coreNLPModelsPath]) def run(self, data): return self.jsonCleanup(data)
<commit_before>#!/usr/bin/env python import os """ Performs some core NLP operations as a proof of concept for the library. """ from stanford_corenlp_pywrapper import CoreNLP class StanfordCoreNLP: def __init__(self): # I don't see anywhere to put properties like this path... # For now it's hardcoded and would need to be changed when deployed... coreNLPPath = os.path.join(os.path.dirname(__file__), '../../lib/stanfordCoreNLP.jar') coreNLPModelsPath = os.path.join(os.path.dirname(__file__), '../../lib/stanfordCoreNLPModels.jar') self.proc = CoreNLP('pos', corenlp_jars=[coreNLPPath, coreNLPModelsPath]) def run(self, data): results = [] for corpus in data: results.append(self.proc.parse_doc(corpus.contents)) return results <commit_msg>Format JSON to be collections of tokens When coreNLP returns the JSON payload, it is in an unmanageable format where multiple arrays are made for all parts of speech, tokens, and lemmas. It's much easier to manage when the response is formatted as a list of objects: { "token": "Pineapple", "lemma": "Pineapple", "part-of-speech": "DT" }<commit_after>#!/usr/bin/env python import os """ Performs some core NLP operations as a proof of concept for the library. """ from stanford_corenlp_pywrapper import CoreNLP class StanfordCoreNLP: """ When the JSON segments return from the CoreNLP library, they separate the data acquired from each word into their own element. For readability's sake, it would be nice to pair all of the information for a given word with that word, making a list of words with their part of speech tags """ def jsonCleanup(self, data): for corpus in data: res = self.proc.parse_doc(corpus.contents) for sentence in res["sentences"]: words = [] for index, token in enumerate(sentence["tokens"]): word = {} word["token"] = sentence["tokens"][index] word["lemma"] = sentence["lemmas"][index] word["part-of-speech"] = sentence["pos"][index] words.append(word) return words def __init__(self): coreNLPPath = os.path.join(os.path.dirname(__file__), '../../lib/stanfordCoreNLP.jar') coreNLPModelsPath = os.path.join(os.path.dirname(__file__), '../../lib/stanfordCoreNLPModels.jar') self.proc = CoreNLP('pos', corenlp_jars=[coreNLPPath, coreNLPModelsPath]) def run(self, data): return self.jsonCleanup(data)
f473cc24e0f2a41699ed9e684b400cb5cb562ce6
go_contacts/backends/utils.py
go_contacts/backends/utils.py
from vumi.persist.model import VumiRiakError from go_api.collections.errors import CollectionUsageError from go_api.queue import PausingQueueCloseMarker from twisted.internet.defer import inlineCallbacks, returnValue @inlineCallbacks def _get_page_of_keys(model_proxy, user_account_key, max_results, cursor): try: contact_keys = yield model_proxy.index_keys_page( 'user_account', user_account_key, max_results=max_results, continuation=cursor) except VumiRiakError: raise CollectionUsageError( "Riak error, possible invalid cursor: %r" % (cursor,)) cursor = contact_keys.continuation returnValue((cursor, contact_keys)) @inlineCallbacks def _fill_queue(q, get_page, get_dict): keys_deferred = get_page(None) while True: cursor, keys = yield keys_deferred if cursor is not None: # Get the next page of keys while we fetch the contacts keys_deferred = get_page(cursor) for key in keys: contact = yield get_dict(key) yield q.put(contact) if cursor is None: break q.put(PausingQueueCloseMarker())
from vumi.persist.model import VumiRiakError from go_api.collections.errors import CollectionUsageError from go_api.queue import PausingQueueCloseMarker from twisted.internet.defer import inlineCallbacks, returnValue @inlineCallbacks def _get_page_of_keys(model_proxy, user_account_key, max_results, cursor): try: contact_keys = yield model_proxy.index_keys_page( 'user_account', user_account_key, max_results=max_results, continuation=cursor) except VumiRiakError: raise CollectionUsageError( "Riak error, possible invalid cursor: %r" % (cursor,)) cursor = contact_keys.continuation returnValue((cursor, contact_keys)) @inlineCallbacks def _fill_queue(q, get_page, get_dict): keys_deferred = get_page(None) while True: cursor, keys = yield keys_deferred if cursor is not None: # Get the next page of keys while we fetch the objects keys_deferred = get_page(cursor) for key in keys: obj = yield get_dict(key) yield q.put(obj) if cursor is None: break q.put(PausingQueueCloseMarker())
Change to more generic variable names in _fill_queue
Change to more generic variable names in _fill_queue
Python
bsd-3-clause
praekelt/go-contacts-api,praekelt/go-contacts-api
from vumi.persist.model import VumiRiakError from go_api.collections.errors import CollectionUsageError from go_api.queue import PausingQueueCloseMarker from twisted.internet.defer import inlineCallbacks, returnValue @inlineCallbacks def _get_page_of_keys(model_proxy, user_account_key, max_results, cursor): try: contact_keys = yield model_proxy.index_keys_page( 'user_account', user_account_key, max_results=max_results, continuation=cursor) except VumiRiakError: raise CollectionUsageError( "Riak error, possible invalid cursor: %r" % (cursor,)) cursor = contact_keys.continuation returnValue((cursor, contact_keys)) @inlineCallbacks def _fill_queue(q, get_page, get_dict): keys_deferred = get_page(None) while True: cursor, keys = yield keys_deferred if cursor is not None: # Get the next page of keys while we fetch the contacts keys_deferred = get_page(cursor) for key in keys: contact = yield get_dict(key) yield q.put(contact) if cursor is None: break q.put(PausingQueueCloseMarker()) Change to more generic variable names in _fill_queue
from vumi.persist.model import VumiRiakError from go_api.collections.errors import CollectionUsageError from go_api.queue import PausingQueueCloseMarker from twisted.internet.defer import inlineCallbacks, returnValue @inlineCallbacks def _get_page_of_keys(model_proxy, user_account_key, max_results, cursor): try: contact_keys = yield model_proxy.index_keys_page( 'user_account', user_account_key, max_results=max_results, continuation=cursor) except VumiRiakError: raise CollectionUsageError( "Riak error, possible invalid cursor: %r" % (cursor,)) cursor = contact_keys.continuation returnValue((cursor, contact_keys)) @inlineCallbacks def _fill_queue(q, get_page, get_dict): keys_deferred = get_page(None) while True: cursor, keys = yield keys_deferred if cursor is not None: # Get the next page of keys while we fetch the objects keys_deferred = get_page(cursor) for key in keys: obj = yield get_dict(key) yield q.put(obj) if cursor is None: break q.put(PausingQueueCloseMarker())
<commit_before>from vumi.persist.model import VumiRiakError from go_api.collections.errors import CollectionUsageError from go_api.queue import PausingQueueCloseMarker from twisted.internet.defer import inlineCallbacks, returnValue @inlineCallbacks def _get_page_of_keys(model_proxy, user_account_key, max_results, cursor): try: contact_keys = yield model_proxy.index_keys_page( 'user_account', user_account_key, max_results=max_results, continuation=cursor) except VumiRiakError: raise CollectionUsageError( "Riak error, possible invalid cursor: %r" % (cursor,)) cursor = contact_keys.continuation returnValue((cursor, contact_keys)) @inlineCallbacks def _fill_queue(q, get_page, get_dict): keys_deferred = get_page(None) while True: cursor, keys = yield keys_deferred if cursor is not None: # Get the next page of keys while we fetch the contacts keys_deferred = get_page(cursor) for key in keys: contact = yield get_dict(key) yield q.put(contact) if cursor is None: break q.put(PausingQueueCloseMarker()) <commit_msg>Change to more generic variable names in _fill_queue<commit_after>
from vumi.persist.model import VumiRiakError from go_api.collections.errors import CollectionUsageError from go_api.queue import PausingQueueCloseMarker from twisted.internet.defer import inlineCallbacks, returnValue @inlineCallbacks def _get_page_of_keys(model_proxy, user_account_key, max_results, cursor): try: contact_keys = yield model_proxy.index_keys_page( 'user_account', user_account_key, max_results=max_results, continuation=cursor) except VumiRiakError: raise CollectionUsageError( "Riak error, possible invalid cursor: %r" % (cursor,)) cursor = contact_keys.continuation returnValue((cursor, contact_keys)) @inlineCallbacks def _fill_queue(q, get_page, get_dict): keys_deferred = get_page(None) while True: cursor, keys = yield keys_deferred if cursor is not None: # Get the next page of keys while we fetch the objects keys_deferred = get_page(cursor) for key in keys: obj = yield get_dict(key) yield q.put(obj) if cursor is None: break q.put(PausingQueueCloseMarker())
from vumi.persist.model import VumiRiakError from go_api.collections.errors import CollectionUsageError from go_api.queue import PausingQueueCloseMarker from twisted.internet.defer import inlineCallbacks, returnValue @inlineCallbacks def _get_page_of_keys(model_proxy, user_account_key, max_results, cursor): try: contact_keys = yield model_proxy.index_keys_page( 'user_account', user_account_key, max_results=max_results, continuation=cursor) except VumiRiakError: raise CollectionUsageError( "Riak error, possible invalid cursor: %r" % (cursor,)) cursor = contact_keys.continuation returnValue((cursor, contact_keys)) @inlineCallbacks def _fill_queue(q, get_page, get_dict): keys_deferred = get_page(None) while True: cursor, keys = yield keys_deferred if cursor is not None: # Get the next page of keys while we fetch the contacts keys_deferred = get_page(cursor) for key in keys: contact = yield get_dict(key) yield q.put(contact) if cursor is None: break q.put(PausingQueueCloseMarker()) Change to more generic variable names in _fill_queuefrom vumi.persist.model import VumiRiakError from go_api.collections.errors import CollectionUsageError from go_api.queue import PausingQueueCloseMarker from twisted.internet.defer import inlineCallbacks, returnValue @inlineCallbacks def _get_page_of_keys(model_proxy, user_account_key, max_results, cursor): try: contact_keys = yield model_proxy.index_keys_page( 'user_account', user_account_key, max_results=max_results, continuation=cursor) except VumiRiakError: raise CollectionUsageError( "Riak error, possible invalid cursor: %r" % (cursor,)) cursor = contact_keys.continuation returnValue((cursor, contact_keys)) @inlineCallbacks def _fill_queue(q, get_page, get_dict): keys_deferred = get_page(None) while True: cursor, keys = yield keys_deferred if cursor is not None: # Get the next page of keys while we fetch the objects keys_deferred = get_page(cursor) for key in keys: obj = yield get_dict(key) yield q.put(obj) if cursor is None: break q.put(PausingQueueCloseMarker())
<commit_before>from vumi.persist.model import VumiRiakError from go_api.collections.errors import CollectionUsageError from go_api.queue import PausingQueueCloseMarker from twisted.internet.defer import inlineCallbacks, returnValue @inlineCallbacks def _get_page_of_keys(model_proxy, user_account_key, max_results, cursor): try: contact_keys = yield model_proxy.index_keys_page( 'user_account', user_account_key, max_results=max_results, continuation=cursor) except VumiRiakError: raise CollectionUsageError( "Riak error, possible invalid cursor: %r" % (cursor,)) cursor = contact_keys.continuation returnValue((cursor, contact_keys)) @inlineCallbacks def _fill_queue(q, get_page, get_dict): keys_deferred = get_page(None) while True: cursor, keys = yield keys_deferred if cursor is not None: # Get the next page of keys while we fetch the contacts keys_deferred = get_page(cursor) for key in keys: contact = yield get_dict(key) yield q.put(contact) if cursor is None: break q.put(PausingQueueCloseMarker()) <commit_msg>Change to more generic variable names in _fill_queue<commit_after>from vumi.persist.model import VumiRiakError from go_api.collections.errors import CollectionUsageError from go_api.queue import PausingQueueCloseMarker from twisted.internet.defer import inlineCallbacks, returnValue @inlineCallbacks def _get_page_of_keys(model_proxy, user_account_key, max_results, cursor): try: contact_keys = yield model_proxy.index_keys_page( 'user_account', user_account_key, max_results=max_results, continuation=cursor) except VumiRiakError: raise CollectionUsageError( "Riak error, possible invalid cursor: %r" % (cursor,)) cursor = contact_keys.continuation returnValue((cursor, contact_keys)) @inlineCallbacks def _fill_queue(q, get_page, get_dict): keys_deferred = get_page(None) while True: cursor, keys = yield keys_deferred if cursor is not None: # Get the next page of keys while we fetch the objects keys_deferred = get_page(cursor) for key in keys: obj = yield get_dict(key) yield q.put(obj) if cursor is None: break q.put(PausingQueueCloseMarker())
b7b41a160294edd987f73be7817c8b08aa8ed70e
herders/templatetags/utils.py
herders/templatetags/utils.py
from django import template register = template.Library() @register.filter def get_range(value): return range(value) @register.filter def absolute(value): return abs(value) @register.filter def subtract(value, arg): return value - arg @register.filter def multiply(value, arg): return value * arg @register.filter def remove_extension(string): return string.replace('.png', '').replace("'", "").replace('(', '_').replace(')', '_')
from django import template register = template.Library() @register.filter def get_range(value): if value: return range(value) else: return 0 @register.filter def absolute(value): return abs(value) @register.filter def subtract(value, arg): return value - arg @register.filter def multiply(value, arg): return value * arg @register.filter def remove_extension(string): return string.replace('.png', '').replace("'", "").replace('(', '_').replace(')', '_')
Return 0 with the get_range filter if value is invalid instead of raise exception
Return 0 with the get_range filter if value is invalid instead of raise exception
Python
apache-2.0
porksmash/swarfarm,PeteAndersen/swarfarm,PeteAndersen/swarfarm,porksmash/swarfarm,PeteAndersen/swarfarm,porksmash/swarfarm,porksmash/swarfarm,PeteAndersen/swarfarm
from django import template register = template.Library() @register.filter def get_range(value): return range(value) @register.filter def absolute(value): return abs(value) @register.filter def subtract(value, arg): return value - arg @register.filter def multiply(value, arg): return value * arg @register.filter def remove_extension(string): return string.replace('.png', '').replace("'", "").replace('(', '_').replace(')', '_') Return 0 with the get_range filter if value is invalid instead of raise exception
from django import template register = template.Library() @register.filter def get_range(value): if value: return range(value) else: return 0 @register.filter def absolute(value): return abs(value) @register.filter def subtract(value, arg): return value - arg @register.filter def multiply(value, arg): return value * arg @register.filter def remove_extension(string): return string.replace('.png', '').replace("'", "").replace('(', '_').replace(')', '_')
<commit_before>from django import template register = template.Library() @register.filter def get_range(value): return range(value) @register.filter def absolute(value): return abs(value) @register.filter def subtract(value, arg): return value - arg @register.filter def multiply(value, arg): return value * arg @register.filter def remove_extension(string): return string.replace('.png', '').replace("'", "").replace('(', '_').replace(')', '_') <commit_msg>Return 0 with the get_range filter if value is invalid instead of raise exception<commit_after>
from django import template register = template.Library() @register.filter def get_range(value): if value: return range(value) else: return 0 @register.filter def absolute(value): return abs(value) @register.filter def subtract(value, arg): return value - arg @register.filter def multiply(value, arg): return value * arg @register.filter def remove_extension(string): return string.replace('.png', '').replace("'", "").replace('(', '_').replace(')', '_')
from django import template register = template.Library() @register.filter def get_range(value): return range(value) @register.filter def absolute(value): return abs(value) @register.filter def subtract(value, arg): return value - arg @register.filter def multiply(value, arg): return value * arg @register.filter def remove_extension(string): return string.replace('.png', '').replace("'", "").replace('(', '_').replace(')', '_') Return 0 with the get_range filter if value is invalid instead of raise exceptionfrom django import template register = template.Library() @register.filter def get_range(value): if value: return range(value) else: return 0 @register.filter def absolute(value): return abs(value) @register.filter def subtract(value, arg): return value - arg @register.filter def multiply(value, arg): return value * arg @register.filter def remove_extension(string): return string.replace('.png', '').replace("'", "").replace('(', '_').replace(')', '_')
<commit_before>from django import template register = template.Library() @register.filter def get_range(value): return range(value) @register.filter def absolute(value): return abs(value) @register.filter def subtract(value, arg): return value - arg @register.filter def multiply(value, arg): return value * arg @register.filter def remove_extension(string): return string.replace('.png', '').replace("'", "").replace('(', '_').replace(')', '_') <commit_msg>Return 0 with the get_range filter if value is invalid instead of raise exception<commit_after>from django import template register = template.Library() @register.filter def get_range(value): if value: return range(value) else: return 0 @register.filter def absolute(value): return abs(value) @register.filter def subtract(value, arg): return value - arg @register.filter def multiply(value, arg): return value * arg @register.filter def remove_extension(string): return string.replace('.png', '').replace("'", "").replace('(', '_').replace(')', '_')
5704912ea9ba866848b6942d6330d30203d90f8b
raven/__init__.py
raven/__init__.py
""" sentry ~~~~~~ :copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ __all__ = ('VERSION', 'Client', 'load') try: VERSION = __import__('pkg_resources') \ .get_distribution('raven').version except Exception, e: VERSION = 'unknown' from base import * from conf import *
""" raven ~~~~~ :copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ __all__ = ('VERSION', 'Client', 'load') try: VERSION = __import__('pkg_resources') \ .get_distribution('raven').version except Exception, e: VERSION = 'unknown' from base import * from conf import *
Correct module name in docstring
Correct module name in docstring
Python
bsd-3-clause
someonehan/raven-python,smarkets/raven-python,inspirehep/raven-python,jmagnusson/raven-python,ewdurbin/raven-python,inspirehep/raven-python,danriti/raven-python,openlabs/raven,daikeren/opbeat_python,arthurlogilab/raven-python,akalipetis/raven-python,beniwohli/apm-agent-python,Photonomie/raven-python,jmagnusson/raven-python,dbravender/raven-python,ronaldevers/raven-python,alex/raven,patrys/opbeat_python,jmp0xf/raven-python,hzy/raven-python,jbarbuto/raven-python,akheron/raven-python,johansteffner/raven-python,inspirehep/raven-python,icereval/raven-python,icereval/raven-python,smarkets/raven-python,jmp0xf/raven-python,ronaldevers/raven-python,recht/raven-python,inspirehep/raven-python,someonehan/raven-python,Photonomie/raven-python,beniwohli/apm-agent-python,akheron/raven-python,jmagnusson/raven-python,nikolas/raven-python,Goldmund-Wyldebeast-Wunderliebe/raven-python,tarkatronic/opbeat_python,lopter/raven-python-old,Goldmund-Wyldebeast-Wunderliebe/raven-python,nikolas/raven-python,patrys/opbeat_python,Goldmund-Wyldebeast-Wunderliebe/raven-python,collective/mr.poe,percipient/raven-python,getsentry/raven-python,icereval/raven-python,tarkatronic/opbeat_python,ticosax/opbeat_python,dirtycoder/opbeat_python,arthurlogilab/raven-python,lepture/raven-python,dbravender/raven-python,beniwohli/apm-agent-python,nikolas/raven-python,dirtycoder/opbeat_python,lepture/raven-python,getsentry/raven-python,akalipetis/raven-python,Goldmund-Wyldebeast-Wunderliebe/raven-python,jbarbuto/raven-python,ewdurbin/raven-python,daikeren/opbeat_python,danriti/raven-python,recht/raven-python,patrys/opbeat_python,getsentry/raven-python,nikolas/raven-python,percipient/raven-python,recht/raven-python,percipient/raven-python,ticosax/opbeat_python,akheron/raven-python,hzy/raven-python,beniwohli/apm-agent-python,akalipetis/raven-python,ticosax/opbeat_python,patrys/opbeat_python,arthurlogilab/raven-python,jmp0xf/raven-python,jbarbuto/raven-python,Photonomie/raven-python,icereval/raven-python,smarkets/raven-python,ewdurbin/raven-python,someonehan/raven-python,dbravender/raven-python,arthurlogilab/raven-python,ronaldevers/raven-python,hzy/raven-python,dirtycoder/opbeat_python,danriti/raven-python,johansteffner/raven-python,jbarbuto/raven-python,lepture/raven-python,smarkets/raven-python,johansteffner/raven-python,tarkatronic/opbeat_python,daikeren/opbeat_python
""" sentry ~~~~~~ :copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ __all__ = ('VERSION', 'Client', 'load') try: VERSION = __import__('pkg_resources') \ .get_distribution('raven').version except Exception, e: VERSION = 'unknown' from base import * from conf import * Correct module name in docstring
""" raven ~~~~~ :copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ __all__ = ('VERSION', 'Client', 'load') try: VERSION = __import__('pkg_resources') \ .get_distribution('raven').version except Exception, e: VERSION = 'unknown' from base import * from conf import *
<commit_before>""" sentry ~~~~~~ :copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ __all__ = ('VERSION', 'Client', 'load') try: VERSION = __import__('pkg_resources') \ .get_distribution('raven').version except Exception, e: VERSION = 'unknown' from base import * from conf import * <commit_msg>Correct module name in docstring<commit_after>
""" raven ~~~~~ :copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ __all__ = ('VERSION', 'Client', 'load') try: VERSION = __import__('pkg_resources') \ .get_distribution('raven').version except Exception, e: VERSION = 'unknown' from base import * from conf import *
""" sentry ~~~~~~ :copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ __all__ = ('VERSION', 'Client', 'load') try: VERSION = __import__('pkg_resources') \ .get_distribution('raven').version except Exception, e: VERSION = 'unknown' from base import * from conf import * Correct module name in docstring""" raven ~~~~~ :copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ __all__ = ('VERSION', 'Client', 'load') try: VERSION = __import__('pkg_resources') \ .get_distribution('raven').version except Exception, e: VERSION = 'unknown' from base import * from conf import *
<commit_before>""" sentry ~~~~~~ :copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ __all__ = ('VERSION', 'Client', 'load') try: VERSION = __import__('pkg_resources') \ .get_distribution('raven').version except Exception, e: VERSION = 'unknown' from base import * from conf import * <commit_msg>Correct module name in docstring<commit_after>""" raven ~~~~~ :copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ __all__ = ('VERSION', 'Client', 'load') try: VERSION = __import__('pkg_resources') \ .get_distribution('raven').version except Exception, e: VERSION = 'unknown' from base import * from conf import *
6d018ef0ac8bc020b38dab1dd29dd6e383be2e8e
src/sentry_heroku/plugin.py
src/sentry_heroku/plugin.py
""" sentry_heroku.plugin ~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2015 by Sentry Team, see AUTHORS for more details. :license: Apache 2.0, see LICENSE for more details. """ import sentry_heroku from sentry.plugins import ReleaseHook, ReleaseTrackingPlugin class HerokuReleaseHook(ReleaseHook): def handle(self, request): self.finish_release( version=request.POST['head_long'], ) class HerokuPlugin(ReleaseTrackingPlugin): author = 'Sentry Team' author_url = 'https://github.com/getsentry' resource_links = ( ('Bug Tracker', 'https://github.com/getsentry/sentry-heroku/issues'), ('Source', 'https://github.com/getsentry/sentry-heroku'), ) title = 'Heroku' slug = 'heroku' description = 'Integrate Heroku release tracking.' version = sentry_heroku.VERSION def get_release_doc_html(self, hook_url): return """ <p>Add Sentry as a deploy hook to automatically track new releases.</p> <pre class="clippy">heroku addons:create deployhooks:http --url={hook_url}</pre> """.format(hook_url=hook_url) def get_release_hook(self): return HerokuReleaseHook
""" sentry_heroku.plugin ~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2015 by Sentry Team, see AUTHORS for more details. :license: Apache 2.0, see LICENSE for more details. """ import sentry_heroku from sentry.plugins import ReleaseHook, ReleaseTrackingPlugin class HerokuReleaseHook(ReleaseHook): def handle(self, request): self.finish_release( version=request.POST['head_long'], url=request.POST['url'], environment=request.POST['app'], ) class HerokuPlugin(ReleaseTrackingPlugin): author = 'Sentry Team' author_url = 'https://github.com/getsentry' resource_links = ( ('Bug Tracker', 'https://github.com/getsentry/sentry-heroku/issues'), ('Source', 'https://github.com/getsentry/sentry-heroku'), ) title = 'Heroku' slug = 'heroku' description = 'Integrate Heroku release tracking.' version = sentry_heroku.VERSION def get_release_doc_html(self, hook_url): return """ <p>Add Sentry as a deploy hook to automatically track new releases.</p> <pre class="clippy">heroku addons:create deployhooks:http --url={hook_url}</pre> """.format(hook_url=hook_url) def get_release_hook(self): return HerokuReleaseHook
Add url and environment to payload
Add url and environment to payload
Python
apache-2.0
getsentry/sentry-heroku
""" sentry_heroku.plugin ~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2015 by Sentry Team, see AUTHORS for more details. :license: Apache 2.0, see LICENSE for more details. """ import sentry_heroku from sentry.plugins import ReleaseHook, ReleaseTrackingPlugin class HerokuReleaseHook(ReleaseHook): def handle(self, request): self.finish_release( version=request.POST['head_long'], ) class HerokuPlugin(ReleaseTrackingPlugin): author = 'Sentry Team' author_url = 'https://github.com/getsentry' resource_links = ( ('Bug Tracker', 'https://github.com/getsentry/sentry-heroku/issues'), ('Source', 'https://github.com/getsentry/sentry-heroku'), ) title = 'Heroku' slug = 'heroku' description = 'Integrate Heroku release tracking.' version = sentry_heroku.VERSION def get_release_doc_html(self, hook_url): return """ <p>Add Sentry as a deploy hook to automatically track new releases.</p> <pre class="clippy">heroku addons:create deployhooks:http --url={hook_url}</pre> """.format(hook_url=hook_url) def get_release_hook(self): return HerokuReleaseHook Add url and environment to payload
""" sentry_heroku.plugin ~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2015 by Sentry Team, see AUTHORS for more details. :license: Apache 2.0, see LICENSE for more details. """ import sentry_heroku from sentry.plugins import ReleaseHook, ReleaseTrackingPlugin class HerokuReleaseHook(ReleaseHook): def handle(self, request): self.finish_release( version=request.POST['head_long'], url=request.POST['url'], environment=request.POST['app'], ) class HerokuPlugin(ReleaseTrackingPlugin): author = 'Sentry Team' author_url = 'https://github.com/getsentry' resource_links = ( ('Bug Tracker', 'https://github.com/getsentry/sentry-heroku/issues'), ('Source', 'https://github.com/getsentry/sentry-heroku'), ) title = 'Heroku' slug = 'heroku' description = 'Integrate Heroku release tracking.' version = sentry_heroku.VERSION def get_release_doc_html(self, hook_url): return """ <p>Add Sentry as a deploy hook to automatically track new releases.</p> <pre class="clippy">heroku addons:create deployhooks:http --url={hook_url}</pre> """.format(hook_url=hook_url) def get_release_hook(self): return HerokuReleaseHook
<commit_before>""" sentry_heroku.plugin ~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2015 by Sentry Team, see AUTHORS for more details. :license: Apache 2.0, see LICENSE for more details. """ import sentry_heroku from sentry.plugins import ReleaseHook, ReleaseTrackingPlugin class HerokuReleaseHook(ReleaseHook): def handle(self, request): self.finish_release( version=request.POST['head_long'], ) class HerokuPlugin(ReleaseTrackingPlugin): author = 'Sentry Team' author_url = 'https://github.com/getsentry' resource_links = ( ('Bug Tracker', 'https://github.com/getsentry/sentry-heroku/issues'), ('Source', 'https://github.com/getsentry/sentry-heroku'), ) title = 'Heroku' slug = 'heroku' description = 'Integrate Heroku release tracking.' version = sentry_heroku.VERSION def get_release_doc_html(self, hook_url): return """ <p>Add Sentry as a deploy hook to automatically track new releases.</p> <pre class="clippy">heroku addons:create deployhooks:http --url={hook_url}</pre> """.format(hook_url=hook_url) def get_release_hook(self): return HerokuReleaseHook <commit_msg>Add url and environment to payload<commit_after>
""" sentry_heroku.plugin ~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2015 by Sentry Team, see AUTHORS for more details. :license: Apache 2.0, see LICENSE for more details. """ import sentry_heroku from sentry.plugins import ReleaseHook, ReleaseTrackingPlugin class HerokuReleaseHook(ReleaseHook): def handle(self, request): self.finish_release( version=request.POST['head_long'], url=request.POST['url'], environment=request.POST['app'], ) class HerokuPlugin(ReleaseTrackingPlugin): author = 'Sentry Team' author_url = 'https://github.com/getsentry' resource_links = ( ('Bug Tracker', 'https://github.com/getsentry/sentry-heroku/issues'), ('Source', 'https://github.com/getsentry/sentry-heroku'), ) title = 'Heroku' slug = 'heroku' description = 'Integrate Heroku release tracking.' version = sentry_heroku.VERSION def get_release_doc_html(self, hook_url): return """ <p>Add Sentry as a deploy hook to automatically track new releases.</p> <pre class="clippy">heroku addons:create deployhooks:http --url={hook_url}</pre> """.format(hook_url=hook_url) def get_release_hook(self): return HerokuReleaseHook
""" sentry_heroku.plugin ~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2015 by Sentry Team, see AUTHORS for more details. :license: Apache 2.0, see LICENSE for more details. """ import sentry_heroku from sentry.plugins import ReleaseHook, ReleaseTrackingPlugin class HerokuReleaseHook(ReleaseHook): def handle(self, request): self.finish_release( version=request.POST['head_long'], ) class HerokuPlugin(ReleaseTrackingPlugin): author = 'Sentry Team' author_url = 'https://github.com/getsentry' resource_links = ( ('Bug Tracker', 'https://github.com/getsentry/sentry-heroku/issues'), ('Source', 'https://github.com/getsentry/sentry-heroku'), ) title = 'Heroku' slug = 'heroku' description = 'Integrate Heroku release tracking.' version = sentry_heroku.VERSION def get_release_doc_html(self, hook_url): return """ <p>Add Sentry as a deploy hook to automatically track new releases.</p> <pre class="clippy">heroku addons:create deployhooks:http --url={hook_url}</pre> """.format(hook_url=hook_url) def get_release_hook(self): return HerokuReleaseHook Add url and environment to payload""" sentry_heroku.plugin ~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2015 by Sentry Team, see AUTHORS for more details. :license: Apache 2.0, see LICENSE for more details. """ import sentry_heroku from sentry.plugins import ReleaseHook, ReleaseTrackingPlugin class HerokuReleaseHook(ReleaseHook): def handle(self, request): self.finish_release( version=request.POST['head_long'], url=request.POST['url'], environment=request.POST['app'], ) class HerokuPlugin(ReleaseTrackingPlugin): author = 'Sentry Team' author_url = 'https://github.com/getsentry' resource_links = ( ('Bug Tracker', 'https://github.com/getsentry/sentry-heroku/issues'), ('Source', 'https://github.com/getsentry/sentry-heroku'), ) title = 'Heroku' slug = 'heroku' description = 'Integrate Heroku release tracking.' version = sentry_heroku.VERSION def get_release_doc_html(self, hook_url): return """ <p>Add Sentry as a deploy hook to automatically track new releases.</p> <pre class="clippy">heroku addons:create deployhooks:http --url={hook_url}</pre> """.format(hook_url=hook_url) def get_release_hook(self): return HerokuReleaseHook
<commit_before>""" sentry_heroku.plugin ~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2015 by Sentry Team, see AUTHORS for more details. :license: Apache 2.0, see LICENSE for more details. """ import sentry_heroku from sentry.plugins import ReleaseHook, ReleaseTrackingPlugin class HerokuReleaseHook(ReleaseHook): def handle(self, request): self.finish_release( version=request.POST['head_long'], ) class HerokuPlugin(ReleaseTrackingPlugin): author = 'Sentry Team' author_url = 'https://github.com/getsentry' resource_links = ( ('Bug Tracker', 'https://github.com/getsentry/sentry-heroku/issues'), ('Source', 'https://github.com/getsentry/sentry-heroku'), ) title = 'Heroku' slug = 'heroku' description = 'Integrate Heroku release tracking.' version = sentry_heroku.VERSION def get_release_doc_html(self, hook_url): return """ <p>Add Sentry as a deploy hook to automatically track new releases.</p> <pre class="clippy">heroku addons:create deployhooks:http --url={hook_url}</pre> """.format(hook_url=hook_url) def get_release_hook(self): return HerokuReleaseHook <commit_msg>Add url and environment to payload<commit_after>""" sentry_heroku.plugin ~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2015 by Sentry Team, see AUTHORS for more details. :license: Apache 2.0, see LICENSE for more details. """ import sentry_heroku from sentry.plugins import ReleaseHook, ReleaseTrackingPlugin class HerokuReleaseHook(ReleaseHook): def handle(self, request): self.finish_release( version=request.POST['head_long'], url=request.POST['url'], environment=request.POST['app'], ) class HerokuPlugin(ReleaseTrackingPlugin): author = 'Sentry Team' author_url = 'https://github.com/getsentry' resource_links = ( ('Bug Tracker', 'https://github.com/getsentry/sentry-heroku/issues'), ('Source', 'https://github.com/getsentry/sentry-heroku'), ) title = 'Heroku' slug = 'heroku' description = 'Integrate Heroku release tracking.' version = sentry_heroku.VERSION def get_release_doc_html(self, hook_url): return """ <p>Add Sentry as a deploy hook to automatically track new releases.</p> <pre class="clippy">heroku addons:create deployhooks:http --url={hook_url}</pre> """.format(hook_url=hook_url) def get_release_hook(self): return HerokuReleaseHook
400289449e164ff168372d9df286acba35926e61
map_points/oauth2/decorators.py
map_points/oauth2/decorators.py
import httplib2 from decorator import decorator from django.core.urlresolvers import reverse from django.shortcuts import redirect from googleapiclient import discovery from oauth2client.client import OAuth2Credentials @decorator def auth_required(f, request, *args, **kwargs): if 'credentials' not in request.session: return redirect(reverse('oauth2callback')) credentials = OAuth2Credentials.from_json(request.session['credentials']) if credentials.access_token_expired: return redirect(reverse('oauth2callback')) http_auth = credentials.authorize(httplib2.Http()) client = discovery.build('fusiontables', 'v1', http=http_auth) request.gapi_client = client return f(request, *args, **kwargs)
import httplib2 from decorator import decorator from django.core.urlresolvers import reverse from django.shortcuts import redirect from googleapiclient import discovery from oauth2client.client import OAuth2Credentials @decorator def auth_required(f, request, *args, **kwargs): """ Verify if request is authorized to communicate with Google's API. If so assign authorized Fusion Tables client to it as gapi attribute. """ if 'credentials' not in request.session: return redirect(reverse('oauth2callback')) credentials = OAuth2Credentials.from_json(request.session['credentials']) if credentials.access_token_expired: return redirect(reverse('oauth2callback')) http_auth = credentials.authorize(httplib2.Http()) client = discovery.build('fusiontables', 'v1', http=http_auth) request.gapi_client = client return f(request, *args, **kwargs)
Add docstr to auth_required decorator.
Add docstr to auth_required decorator.
Python
mit
nihn/map-points,nihn/map-points,nihn/map-points,nihn/map-points
import httplib2 from decorator import decorator from django.core.urlresolvers import reverse from django.shortcuts import redirect from googleapiclient import discovery from oauth2client.client import OAuth2Credentials @decorator def auth_required(f, request, *args, **kwargs): if 'credentials' not in request.session: return redirect(reverse('oauth2callback')) credentials = OAuth2Credentials.from_json(request.session['credentials']) if credentials.access_token_expired: return redirect(reverse('oauth2callback')) http_auth = credentials.authorize(httplib2.Http()) client = discovery.build('fusiontables', 'v1', http=http_auth) request.gapi_client = client return f(request, *args, **kwargs) Add docstr to auth_required decorator.
import httplib2 from decorator import decorator from django.core.urlresolvers import reverse from django.shortcuts import redirect from googleapiclient import discovery from oauth2client.client import OAuth2Credentials @decorator def auth_required(f, request, *args, **kwargs): """ Verify if request is authorized to communicate with Google's API. If so assign authorized Fusion Tables client to it as gapi attribute. """ if 'credentials' not in request.session: return redirect(reverse('oauth2callback')) credentials = OAuth2Credentials.from_json(request.session['credentials']) if credentials.access_token_expired: return redirect(reverse('oauth2callback')) http_auth = credentials.authorize(httplib2.Http()) client = discovery.build('fusiontables', 'v1', http=http_auth) request.gapi_client = client return f(request, *args, **kwargs)
<commit_before>import httplib2 from decorator import decorator from django.core.urlresolvers import reverse from django.shortcuts import redirect from googleapiclient import discovery from oauth2client.client import OAuth2Credentials @decorator def auth_required(f, request, *args, **kwargs): if 'credentials' not in request.session: return redirect(reverse('oauth2callback')) credentials = OAuth2Credentials.from_json(request.session['credentials']) if credentials.access_token_expired: return redirect(reverse('oauth2callback')) http_auth = credentials.authorize(httplib2.Http()) client = discovery.build('fusiontables', 'v1', http=http_auth) request.gapi_client = client return f(request, *args, **kwargs) <commit_msg>Add docstr to auth_required decorator.<commit_after>
import httplib2 from decorator import decorator from django.core.urlresolvers import reverse from django.shortcuts import redirect from googleapiclient import discovery from oauth2client.client import OAuth2Credentials @decorator def auth_required(f, request, *args, **kwargs): """ Verify if request is authorized to communicate with Google's API. If so assign authorized Fusion Tables client to it as gapi attribute. """ if 'credentials' not in request.session: return redirect(reverse('oauth2callback')) credentials = OAuth2Credentials.from_json(request.session['credentials']) if credentials.access_token_expired: return redirect(reverse('oauth2callback')) http_auth = credentials.authorize(httplib2.Http()) client = discovery.build('fusiontables', 'v1', http=http_auth) request.gapi_client = client return f(request, *args, **kwargs)
import httplib2 from decorator import decorator from django.core.urlresolvers import reverse from django.shortcuts import redirect from googleapiclient import discovery from oauth2client.client import OAuth2Credentials @decorator def auth_required(f, request, *args, **kwargs): if 'credentials' not in request.session: return redirect(reverse('oauth2callback')) credentials = OAuth2Credentials.from_json(request.session['credentials']) if credentials.access_token_expired: return redirect(reverse('oauth2callback')) http_auth = credentials.authorize(httplib2.Http()) client = discovery.build('fusiontables', 'v1', http=http_auth) request.gapi_client = client return f(request, *args, **kwargs) Add docstr to auth_required decorator.import httplib2 from decorator import decorator from django.core.urlresolvers import reverse from django.shortcuts import redirect from googleapiclient import discovery from oauth2client.client import OAuth2Credentials @decorator def auth_required(f, request, *args, **kwargs): """ Verify if request is authorized to communicate with Google's API. If so assign authorized Fusion Tables client to it as gapi attribute. """ if 'credentials' not in request.session: return redirect(reverse('oauth2callback')) credentials = OAuth2Credentials.from_json(request.session['credentials']) if credentials.access_token_expired: return redirect(reverse('oauth2callback')) http_auth = credentials.authorize(httplib2.Http()) client = discovery.build('fusiontables', 'v1', http=http_auth) request.gapi_client = client return f(request, *args, **kwargs)
<commit_before>import httplib2 from decorator import decorator from django.core.urlresolvers import reverse from django.shortcuts import redirect from googleapiclient import discovery from oauth2client.client import OAuth2Credentials @decorator def auth_required(f, request, *args, **kwargs): if 'credentials' not in request.session: return redirect(reverse('oauth2callback')) credentials = OAuth2Credentials.from_json(request.session['credentials']) if credentials.access_token_expired: return redirect(reverse('oauth2callback')) http_auth = credentials.authorize(httplib2.Http()) client = discovery.build('fusiontables', 'v1', http=http_auth) request.gapi_client = client return f(request, *args, **kwargs) <commit_msg>Add docstr to auth_required decorator.<commit_after>import httplib2 from decorator import decorator from django.core.urlresolvers import reverse from django.shortcuts import redirect from googleapiclient import discovery from oauth2client.client import OAuth2Credentials @decorator def auth_required(f, request, *args, **kwargs): """ Verify if request is authorized to communicate with Google's API. If so assign authorized Fusion Tables client to it as gapi attribute. """ if 'credentials' not in request.session: return redirect(reverse('oauth2callback')) credentials = OAuth2Credentials.from_json(request.session['credentials']) if credentials.access_token_expired: return redirect(reverse('oauth2callback')) http_auth = credentials.authorize(httplib2.Http()) client = discovery.build('fusiontables', 'v1', http=http_auth) request.gapi_client = client return f(request, *args, **kwargs)
2502a6c54e4f87d3d344077cce5029e4bbca58d5
taarifa_backend/__init__.py
taarifa_backend/__init__.py
from flask import Flask from flask.ext.mongoengine import MongoEngine import logging # configure the logging logging.basicConfig(level='DEBUG', format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') app = Flask(__name__) app.config["MONGODB_SETTINGS"] = {'DB': "taarifa_backend"} app.config["SECRET_KEY"] = "KeepThisS3cr3t" db = MongoEngine(app) def register_views(): """ to avoid circular dependencies and register the routes """ from api import receive_report pass register_views() app.logger.debug('Registered views are: \n' + app.view_functions.keys().__repr__()) if __name__ == '__main__': app.run()
from flask import Flask from flask.ext.mongoengine import MongoEngine import logging from os import environ import urlparse # configure the logging logging.basicConfig(level='DEBUG', format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') app = Flask(__name__) if environ.get('MONGOLAB_URI'): url = urlparse.urlparse(environ['MONGOLAB_URI']) app.config['MONGODB_SETTINGS'] = {'username': url.username, 'password': url.password, 'host': url.hostname, 'port': url.port, 'db': url.path[1:]} else: app.config['MONGODB_SETTINGS'] = {'db': "taarifa_backend"} db = MongoEngine(app) def register_views(): """ to avoid circular dependencies and register the routes """ from api import receive_report pass register_views() app.logger.debug('Registered views are: \n' + app.view_functions.keys().__repr__()) if __name__ == '__main__': app.run()
Use MongoLab configuration from environment if available
Use MongoLab configuration from environment if available
Python
bsd-3-clause
taarifa/taarifa_backend,taarifa/taarifa_backend,taarifa/taarifa_backend,taarifa/taarifa_backend
from flask import Flask from flask.ext.mongoengine import MongoEngine import logging # configure the logging logging.basicConfig(level='DEBUG', format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') app = Flask(__name__) app.config["MONGODB_SETTINGS"] = {'DB': "taarifa_backend"} app.config["SECRET_KEY"] = "KeepThisS3cr3t" db = MongoEngine(app) def register_views(): """ to avoid circular dependencies and register the routes """ from api import receive_report pass register_views() app.logger.debug('Registered views are: \n' + app.view_functions.keys().__repr__()) if __name__ == '__main__': app.run() Use MongoLab configuration from environment if available
from flask import Flask from flask.ext.mongoengine import MongoEngine import logging from os import environ import urlparse # configure the logging logging.basicConfig(level='DEBUG', format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') app = Flask(__name__) if environ.get('MONGOLAB_URI'): url = urlparse.urlparse(environ['MONGOLAB_URI']) app.config['MONGODB_SETTINGS'] = {'username': url.username, 'password': url.password, 'host': url.hostname, 'port': url.port, 'db': url.path[1:]} else: app.config['MONGODB_SETTINGS'] = {'db': "taarifa_backend"} db = MongoEngine(app) def register_views(): """ to avoid circular dependencies and register the routes """ from api import receive_report pass register_views() app.logger.debug('Registered views are: \n' + app.view_functions.keys().__repr__()) if __name__ == '__main__': app.run()
<commit_before>from flask import Flask from flask.ext.mongoengine import MongoEngine import logging # configure the logging logging.basicConfig(level='DEBUG', format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') app = Flask(__name__) app.config["MONGODB_SETTINGS"] = {'DB': "taarifa_backend"} app.config["SECRET_KEY"] = "KeepThisS3cr3t" db = MongoEngine(app) def register_views(): """ to avoid circular dependencies and register the routes """ from api import receive_report pass register_views() app.logger.debug('Registered views are: \n' + app.view_functions.keys().__repr__()) if __name__ == '__main__': app.run() <commit_msg>Use MongoLab configuration from environment if available<commit_after>
from flask import Flask from flask.ext.mongoengine import MongoEngine import logging from os import environ import urlparse # configure the logging logging.basicConfig(level='DEBUG', format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') app = Flask(__name__) if environ.get('MONGOLAB_URI'): url = urlparse.urlparse(environ['MONGOLAB_URI']) app.config['MONGODB_SETTINGS'] = {'username': url.username, 'password': url.password, 'host': url.hostname, 'port': url.port, 'db': url.path[1:]} else: app.config['MONGODB_SETTINGS'] = {'db': "taarifa_backend"} db = MongoEngine(app) def register_views(): """ to avoid circular dependencies and register the routes """ from api import receive_report pass register_views() app.logger.debug('Registered views are: \n' + app.view_functions.keys().__repr__()) if __name__ == '__main__': app.run()
from flask import Flask from flask.ext.mongoengine import MongoEngine import logging # configure the logging logging.basicConfig(level='DEBUG', format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') app = Flask(__name__) app.config["MONGODB_SETTINGS"] = {'DB': "taarifa_backend"} app.config["SECRET_KEY"] = "KeepThisS3cr3t" db = MongoEngine(app) def register_views(): """ to avoid circular dependencies and register the routes """ from api import receive_report pass register_views() app.logger.debug('Registered views are: \n' + app.view_functions.keys().__repr__()) if __name__ == '__main__': app.run() Use MongoLab configuration from environment if availablefrom flask import Flask from flask.ext.mongoengine import MongoEngine import logging from os import environ import urlparse # configure the logging logging.basicConfig(level='DEBUG', format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') app = Flask(__name__) if environ.get('MONGOLAB_URI'): url = urlparse.urlparse(environ['MONGOLAB_URI']) app.config['MONGODB_SETTINGS'] = {'username': url.username, 'password': url.password, 'host': url.hostname, 'port': url.port, 'db': url.path[1:]} else: app.config['MONGODB_SETTINGS'] = {'db': "taarifa_backend"} db = MongoEngine(app) def register_views(): """ to avoid circular dependencies and register the routes """ from api import receive_report pass register_views() app.logger.debug('Registered views are: \n' + app.view_functions.keys().__repr__()) if __name__ == '__main__': app.run()
<commit_before>from flask import Flask from flask.ext.mongoengine import MongoEngine import logging # configure the logging logging.basicConfig(level='DEBUG', format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') app = Flask(__name__) app.config["MONGODB_SETTINGS"] = {'DB': "taarifa_backend"} app.config["SECRET_KEY"] = "KeepThisS3cr3t" db = MongoEngine(app) def register_views(): """ to avoid circular dependencies and register the routes """ from api import receive_report pass register_views() app.logger.debug('Registered views are: \n' + app.view_functions.keys().__repr__()) if __name__ == '__main__': app.run() <commit_msg>Use MongoLab configuration from environment if available<commit_after>from flask import Flask from flask.ext.mongoengine import MongoEngine import logging from os import environ import urlparse # configure the logging logging.basicConfig(level='DEBUG', format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') app = Flask(__name__) if environ.get('MONGOLAB_URI'): url = urlparse.urlparse(environ['MONGOLAB_URI']) app.config['MONGODB_SETTINGS'] = {'username': url.username, 'password': url.password, 'host': url.hostname, 'port': url.port, 'db': url.path[1:]} else: app.config['MONGODB_SETTINGS'] = {'db': "taarifa_backend"} db = MongoEngine(app) def register_views(): """ to avoid circular dependencies and register the routes """ from api import receive_report pass register_views() app.logger.debug('Registered views are: \n' + app.view_functions.keys().__repr__()) if __name__ == '__main__': app.run()
389befbf655e6b1608aff79d176365c79c91fe2b
tests/fields/test_string.py
tests/fields/test_string.py
from protobuf3.fields.string import StringField from protobuf3.message import Message from unittest import TestCase class TestStringField(TestCase): def setUp(self): class StringTestMessage(Message): b = StringField(field_number=2) self.msg_cls = StringTestMessage def test_get(self): msg = self.msg_cls() msg.parse_from_bytes([0x12, 0x07, 0x74, 0x65, 0x73, 0x74, 0x69, 0x6E, 0x67]) self.assertEqual(msg.b, 'testing') def test_default_get(self): msg = self.msg_cls() self.assertEqual(msg.b, '') def test_set(self): msg = self.msg_cls() msg.b = 'test' self.assertEqual(msg.b, 'test') def test_invalid_set(self): msg = self.msg_cls() def failure(): msg.b = 123 self.assertRaises(ValueError, failure)
from protobuf3.fields.string import StringField from protobuf3.message import Message from unittest import TestCase class TestStringField(TestCase): def setUp(self): class StringTestMessage(Message): b = StringField(field_number=2) self.msg_cls = StringTestMessage def test_get(self): msg = self.msg_cls() msg.parse_from_bytes(bytes([0x12, 0x07, 0x74, 0x65, 0x73, 0x74, 0x69, 0x6E, 0x67])) self.assertEqual(msg.b, 'testing') def test_default_get(self): msg = self.msg_cls() self.assertEqual(msg.b, '') def test_set(self): msg = self.msg_cls() msg.b = 'test' self.assertEqual(msg.b, 'test') def test_invalid_set(self): msg = self.msg_cls() def failure(): msg.b = 123 self.assertRaises(ValueError, failure)
Update string tests to reflect new behaviour.
Update string tests to reflect new behaviour.
Python
mit
Pr0Ger/protobuf3
from protobuf3.fields.string import StringField from protobuf3.message import Message from unittest import TestCase class TestStringField(TestCase): def setUp(self): class StringTestMessage(Message): b = StringField(field_number=2) self.msg_cls = StringTestMessage def test_get(self): msg = self.msg_cls() msg.parse_from_bytes([0x12, 0x07, 0x74, 0x65, 0x73, 0x74, 0x69, 0x6E, 0x67]) self.assertEqual(msg.b, 'testing') def test_default_get(self): msg = self.msg_cls() self.assertEqual(msg.b, '') def test_set(self): msg = self.msg_cls() msg.b = 'test' self.assertEqual(msg.b, 'test') def test_invalid_set(self): msg = self.msg_cls() def failure(): msg.b = 123 self.assertRaises(ValueError, failure) Update string tests to reflect new behaviour.
from protobuf3.fields.string import StringField from protobuf3.message import Message from unittest import TestCase class TestStringField(TestCase): def setUp(self): class StringTestMessage(Message): b = StringField(field_number=2) self.msg_cls = StringTestMessage def test_get(self): msg = self.msg_cls() msg.parse_from_bytes(bytes([0x12, 0x07, 0x74, 0x65, 0x73, 0x74, 0x69, 0x6E, 0x67])) self.assertEqual(msg.b, 'testing') def test_default_get(self): msg = self.msg_cls() self.assertEqual(msg.b, '') def test_set(self): msg = self.msg_cls() msg.b = 'test' self.assertEqual(msg.b, 'test') def test_invalid_set(self): msg = self.msg_cls() def failure(): msg.b = 123 self.assertRaises(ValueError, failure)
<commit_before>from protobuf3.fields.string import StringField from protobuf3.message import Message from unittest import TestCase class TestStringField(TestCase): def setUp(self): class StringTestMessage(Message): b = StringField(field_number=2) self.msg_cls = StringTestMessage def test_get(self): msg = self.msg_cls() msg.parse_from_bytes([0x12, 0x07, 0x74, 0x65, 0x73, 0x74, 0x69, 0x6E, 0x67]) self.assertEqual(msg.b, 'testing') def test_default_get(self): msg = self.msg_cls() self.assertEqual(msg.b, '') def test_set(self): msg = self.msg_cls() msg.b = 'test' self.assertEqual(msg.b, 'test') def test_invalid_set(self): msg = self.msg_cls() def failure(): msg.b = 123 self.assertRaises(ValueError, failure) <commit_msg>Update string tests to reflect new behaviour.<commit_after>
from protobuf3.fields.string import StringField from protobuf3.message import Message from unittest import TestCase class TestStringField(TestCase): def setUp(self): class StringTestMessage(Message): b = StringField(field_number=2) self.msg_cls = StringTestMessage def test_get(self): msg = self.msg_cls() msg.parse_from_bytes(bytes([0x12, 0x07, 0x74, 0x65, 0x73, 0x74, 0x69, 0x6E, 0x67])) self.assertEqual(msg.b, 'testing') def test_default_get(self): msg = self.msg_cls() self.assertEqual(msg.b, '') def test_set(self): msg = self.msg_cls() msg.b = 'test' self.assertEqual(msg.b, 'test') def test_invalid_set(self): msg = self.msg_cls() def failure(): msg.b = 123 self.assertRaises(ValueError, failure)
from protobuf3.fields.string import StringField from protobuf3.message import Message from unittest import TestCase class TestStringField(TestCase): def setUp(self): class StringTestMessage(Message): b = StringField(field_number=2) self.msg_cls = StringTestMessage def test_get(self): msg = self.msg_cls() msg.parse_from_bytes([0x12, 0x07, 0x74, 0x65, 0x73, 0x74, 0x69, 0x6E, 0x67]) self.assertEqual(msg.b, 'testing') def test_default_get(self): msg = self.msg_cls() self.assertEqual(msg.b, '') def test_set(self): msg = self.msg_cls() msg.b = 'test' self.assertEqual(msg.b, 'test') def test_invalid_set(self): msg = self.msg_cls() def failure(): msg.b = 123 self.assertRaises(ValueError, failure) Update string tests to reflect new behaviour.from protobuf3.fields.string import StringField from protobuf3.message import Message from unittest import TestCase class TestStringField(TestCase): def setUp(self): class StringTestMessage(Message): b = StringField(field_number=2) self.msg_cls = StringTestMessage def test_get(self): msg = self.msg_cls() msg.parse_from_bytes(bytes([0x12, 0x07, 0x74, 0x65, 0x73, 0x74, 0x69, 0x6E, 0x67])) self.assertEqual(msg.b, 'testing') def test_default_get(self): msg = self.msg_cls() self.assertEqual(msg.b, '') def test_set(self): msg = self.msg_cls() msg.b = 'test' self.assertEqual(msg.b, 'test') def test_invalid_set(self): msg = self.msg_cls() def failure(): msg.b = 123 self.assertRaises(ValueError, failure)
<commit_before>from protobuf3.fields.string import StringField from protobuf3.message import Message from unittest import TestCase class TestStringField(TestCase): def setUp(self): class StringTestMessage(Message): b = StringField(field_number=2) self.msg_cls = StringTestMessage def test_get(self): msg = self.msg_cls() msg.parse_from_bytes([0x12, 0x07, 0x74, 0x65, 0x73, 0x74, 0x69, 0x6E, 0x67]) self.assertEqual(msg.b, 'testing') def test_default_get(self): msg = self.msg_cls() self.assertEqual(msg.b, '') def test_set(self): msg = self.msg_cls() msg.b = 'test' self.assertEqual(msg.b, 'test') def test_invalid_set(self): msg = self.msg_cls() def failure(): msg.b = 123 self.assertRaises(ValueError, failure) <commit_msg>Update string tests to reflect new behaviour.<commit_after>from protobuf3.fields.string import StringField from protobuf3.message import Message from unittest import TestCase class TestStringField(TestCase): def setUp(self): class StringTestMessage(Message): b = StringField(field_number=2) self.msg_cls = StringTestMessage def test_get(self): msg = self.msg_cls() msg.parse_from_bytes(bytes([0x12, 0x07, 0x74, 0x65, 0x73, 0x74, 0x69, 0x6E, 0x67])) self.assertEqual(msg.b, 'testing') def test_default_get(self): msg = self.msg_cls() self.assertEqual(msg.b, '') def test_set(self): msg = self.msg_cls() msg.b = 'test' self.assertEqual(msg.b, 'test') def test_invalid_set(self): msg = self.msg_cls() def failure(): msg.b = 123 self.assertRaises(ValueError, failure)
2d0b44d65a8167a105cbc63e704735b1c360e0c4
api/core/urls.py
api/core/urls.py
from django.urls import path, re_path from django.conf.urls.static import static from django.conf import settings from . import views urlpatterns = static('/compiled/', document_root=settings.BUILD_ROOT) + [ path('go/<path:path>', views.redirector, name='redirector'), re_path('^', views.index, name='index'), ]
from django.conf import settings from django.conf.urls.static import static from django.contrib.auth.views import logout from django.urls import path, re_path from . import views urlpatterns = static('/compiled/', document_root=settings.BUILD_ROOT) + [ path('go/<path:path>', views.redirector, name='redirector'), path('logout', logout, {'next_page': '/'}), re_path('^', views.index, name='index'), ]
Handle logout on the backend
Handle logout on the backend
Python
mit
citizenlabsgr/voter-engagement,citizenlabsgr/voter-engagement,citizenlabsgr/voter-engagement,citizenlabsgr/voter-engagement,citizenlabsgr/voter-engagement
from django.urls import path, re_path from django.conf.urls.static import static from django.conf import settings from . import views urlpatterns = static('/compiled/', document_root=settings.BUILD_ROOT) + [ path('go/<path:path>', views.redirector, name='redirector'), re_path('^', views.index, name='index'), ] Handle logout on the backend
from django.conf import settings from django.conf.urls.static import static from django.contrib.auth.views import logout from django.urls import path, re_path from . import views urlpatterns = static('/compiled/', document_root=settings.BUILD_ROOT) + [ path('go/<path:path>', views.redirector, name='redirector'), path('logout', logout, {'next_page': '/'}), re_path('^', views.index, name='index'), ]
<commit_before>from django.urls import path, re_path from django.conf.urls.static import static from django.conf import settings from . import views urlpatterns = static('/compiled/', document_root=settings.BUILD_ROOT) + [ path('go/<path:path>', views.redirector, name='redirector'), re_path('^', views.index, name='index'), ] <commit_msg>Handle logout on the backend<commit_after>
from django.conf import settings from django.conf.urls.static import static from django.contrib.auth.views import logout from django.urls import path, re_path from . import views urlpatterns = static('/compiled/', document_root=settings.BUILD_ROOT) + [ path('go/<path:path>', views.redirector, name='redirector'), path('logout', logout, {'next_page': '/'}), re_path('^', views.index, name='index'), ]
from django.urls import path, re_path from django.conf.urls.static import static from django.conf import settings from . import views urlpatterns = static('/compiled/', document_root=settings.BUILD_ROOT) + [ path('go/<path:path>', views.redirector, name='redirector'), re_path('^', views.index, name='index'), ] Handle logout on the backendfrom django.conf import settings from django.conf.urls.static import static from django.contrib.auth.views import logout from django.urls import path, re_path from . import views urlpatterns = static('/compiled/', document_root=settings.BUILD_ROOT) + [ path('go/<path:path>', views.redirector, name='redirector'), path('logout', logout, {'next_page': '/'}), re_path('^', views.index, name='index'), ]
<commit_before>from django.urls import path, re_path from django.conf.urls.static import static from django.conf import settings from . import views urlpatterns = static('/compiled/', document_root=settings.BUILD_ROOT) + [ path('go/<path:path>', views.redirector, name='redirector'), re_path('^', views.index, name='index'), ] <commit_msg>Handle logout on the backend<commit_after>from django.conf import settings from django.conf.urls.static import static from django.contrib.auth.views import logout from django.urls import path, re_path from . import views urlpatterns = static('/compiled/', document_root=settings.BUILD_ROOT) + [ path('go/<path:path>', views.redirector, name='redirector'), path('logout', logout, {'next_page': '/'}), re_path('^', views.index, name='index'), ]
e6ae7fc2c30aa8af087b803408359189ece58f30
keystone/common/policies/revoke_event.py
keystone/common/policies/revoke_event.py
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_policy import policy from keystone.common.policies import base revoke_event_policies = [ policy.RuleDefault( name=base.IDENTITY % 'list_revoke_events', check_str=base.RULE_SERVICE_OR_ADMIN) ] def list_rules(): return revoke_event_policies
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_policy import policy from keystone.common.policies import base revoke_event_policies = [ policy.DocumentedRuleDefault( name=base.IDENTITY % 'list_revoke_events', check_str=base.RULE_SERVICE_OR_ADMIN, description='List revocation events.', operations=[{'path': '/v3/OS-REVOKE/events', 'method': 'GET'}]) ] def list_rules(): return revoke_event_policies
Move revoke events to DocumentedRuleDefault
Move revoke events to DocumentedRuleDefault The overall goal is to define a richer policy for deployers and operators[0]. To achieve that goal a new policy class was introduce that requires additional parameters when defining policy objects. This patch switches our revoke events policy object to the policy.DocumentedRuleDefault and fills the required policy parameters as needed. [0] I2b59f92545c5ead2a883d358f72f3ad3b3dfe1a6 Change-Id: Idfa3e5cd373c560035d03dfdef4ea303e28a92fc Partially-Implements: bp policy-docs
Python
apache-2.0
rajalokan/keystone,mahak/keystone,rajalokan/keystone,ilay09/keystone,openstack/keystone,rajalokan/keystone,openstack/keystone,openstack/keystone,mahak/keystone,ilay09/keystone,mahak/keystone,ilay09/keystone
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_policy import policy from keystone.common.policies import base revoke_event_policies = [ policy.RuleDefault( name=base.IDENTITY % 'list_revoke_events', check_str=base.RULE_SERVICE_OR_ADMIN) ] def list_rules(): return revoke_event_policies Move revoke events to DocumentedRuleDefault The overall goal is to define a richer policy for deployers and operators[0]. To achieve that goal a new policy class was introduce that requires additional parameters when defining policy objects. This patch switches our revoke events policy object to the policy.DocumentedRuleDefault and fills the required policy parameters as needed. [0] I2b59f92545c5ead2a883d358f72f3ad3b3dfe1a6 Change-Id: Idfa3e5cd373c560035d03dfdef4ea303e28a92fc Partially-Implements: bp policy-docs
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_policy import policy from keystone.common.policies import base revoke_event_policies = [ policy.DocumentedRuleDefault( name=base.IDENTITY % 'list_revoke_events', check_str=base.RULE_SERVICE_OR_ADMIN, description='List revocation events.', operations=[{'path': '/v3/OS-REVOKE/events', 'method': 'GET'}]) ] def list_rules(): return revoke_event_policies
<commit_before># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_policy import policy from keystone.common.policies import base revoke_event_policies = [ policy.RuleDefault( name=base.IDENTITY % 'list_revoke_events', check_str=base.RULE_SERVICE_OR_ADMIN) ] def list_rules(): return revoke_event_policies <commit_msg>Move revoke events to DocumentedRuleDefault The overall goal is to define a richer policy for deployers and operators[0]. To achieve that goal a new policy class was introduce that requires additional parameters when defining policy objects. This patch switches our revoke events policy object to the policy.DocumentedRuleDefault and fills the required policy parameters as needed. [0] I2b59f92545c5ead2a883d358f72f3ad3b3dfe1a6 Change-Id: Idfa3e5cd373c560035d03dfdef4ea303e28a92fc Partially-Implements: bp policy-docs<commit_after>
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_policy import policy from keystone.common.policies import base revoke_event_policies = [ policy.DocumentedRuleDefault( name=base.IDENTITY % 'list_revoke_events', check_str=base.RULE_SERVICE_OR_ADMIN, description='List revocation events.', operations=[{'path': '/v3/OS-REVOKE/events', 'method': 'GET'}]) ] def list_rules(): return revoke_event_policies
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_policy import policy from keystone.common.policies import base revoke_event_policies = [ policy.RuleDefault( name=base.IDENTITY % 'list_revoke_events', check_str=base.RULE_SERVICE_OR_ADMIN) ] def list_rules(): return revoke_event_policies Move revoke events to DocumentedRuleDefault The overall goal is to define a richer policy for deployers and operators[0]. To achieve that goal a new policy class was introduce that requires additional parameters when defining policy objects. This patch switches our revoke events policy object to the policy.DocumentedRuleDefault and fills the required policy parameters as needed. [0] I2b59f92545c5ead2a883d358f72f3ad3b3dfe1a6 Change-Id: Idfa3e5cd373c560035d03dfdef4ea303e28a92fc Partially-Implements: bp policy-docs# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_policy import policy from keystone.common.policies import base revoke_event_policies = [ policy.DocumentedRuleDefault( name=base.IDENTITY % 'list_revoke_events', check_str=base.RULE_SERVICE_OR_ADMIN, description='List revocation events.', operations=[{'path': '/v3/OS-REVOKE/events', 'method': 'GET'}]) ] def list_rules(): return revoke_event_policies
<commit_before># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_policy import policy from keystone.common.policies import base revoke_event_policies = [ policy.RuleDefault( name=base.IDENTITY % 'list_revoke_events', check_str=base.RULE_SERVICE_OR_ADMIN) ] def list_rules(): return revoke_event_policies <commit_msg>Move revoke events to DocumentedRuleDefault The overall goal is to define a richer policy for deployers and operators[0]. To achieve that goal a new policy class was introduce that requires additional parameters when defining policy objects. This patch switches our revoke events policy object to the policy.DocumentedRuleDefault and fills the required policy parameters as needed. [0] I2b59f92545c5ead2a883d358f72f3ad3b3dfe1a6 Change-Id: Idfa3e5cd373c560035d03dfdef4ea303e28a92fc Partially-Implements: bp policy-docs<commit_after># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_policy import policy from keystone.common.policies import base revoke_event_policies = [ policy.DocumentedRuleDefault( name=base.IDENTITY % 'list_revoke_events', check_str=base.RULE_SERVICE_OR_ADMIN, description='List revocation events.', operations=[{'path': '/v3/OS-REVOKE/events', 'method': 'GET'}]) ] def list_rules(): return revoke_event_policies
5cb8d2a4187d867111b32491df6e53983f124d73
rawkit/raw.py
rawkit/raw.py
from rawkit.libraw import libraw class Raw(object): def __init__(self, filename=None): self.data = libraw.libraw_init(0) libraw.libraw_open_file(self.data, bytes(filename, 'utf-8')) def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): libraw.libraw_close(self.data) def process(self, options=None): libraw.libraw_unpack(self.data) libraw.libraw_dcraw_process(self.data) def save(self, filename=None): libraw.libraw_dcraw_ppm_tiff_writer( self.data, bytes(filename, 'utf-8'))
from rawkit.libraw import libraw class Raw(object): def __init__(self, filename=None): self.data = libraw.libraw_init(0) libraw.libraw_open_file(self.data, bytes(filename, 'utf-8')) def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): """Clean up after ourselves when leaving the context manager.""" self.close() def close(self): """Free the underlying raw representation.""" libraw.libraw_close(self.data) def process(self, options=None): """ Unpack and process the raw data into something more usable. """ libraw.libraw_unpack(self.data) libraw.libraw_dcraw_process(self.data) def save(self, filename=None): libraw.libraw_dcraw_ppm_tiff_writer( self.data, bytes(filename, 'utf-8'))
Add close method to Raw class
Add close method to Raw class Fixes #10
Python
mit
nagyistoce/rawkit,SamWhited/rawkit,photoshell/rawkit
from rawkit.libraw import libraw class Raw(object): def __init__(self, filename=None): self.data = libraw.libraw_init(0) libraw.libraw_open_file(self.data, bytes(filename, 'utf-8')) def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): libraw.libraw_close(self.data) def process(self, options=None): libraw.libraw_unpack(self.data) libraw.libraw_dcraw_process(self.data) def save(self, filename=None): libraw.libraw_dcraw_ppm_tiff_writer( self.data, bytes(filename, 'utf-8')) Add close method to Raw class Fixes #10
from rawkit.libraw import libraw class Raw(object): def __init__(self, filename=None): self.data = libraw.libraw_init(0) libraw.libraw_open_file(self.data, bytes(filename, 'utf-8')) def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): """Clean up after ourselves when leaving the context manager.""" self.close() def close(self): """Free the underlying raw representation.""" libraw.libraw_close(self.data) def process(self, options=None): """ Unpack and process the raw data into something more usable. """ libraw.libraw_unpack(self.data) libraw.libraw_dcraw_process(self.data) def save(self, filename=None): libraw.libraw_dcraw_ppm_tiff_writer( self.data, bytes(filename, 'utf-8'))
<commit_before>from rawkit.libraw import libraw class Raw(object): def __init__(self, filename=None): self.data = libraw.libraw_init(0) libraw.libraw_open_file(self.data, bytes(filename, 'utf-8')) def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): libraw.libraw_close(self.data) def process(self, options=None): libraw.libraw_unpack(self.data) libraw.libraw_dcraw_process(self.data) def save(self, filename=None): libraw.libraw_dcraw_ppm_tiff_writer( self.data, bytes(filename, 'utf-8')) <commit_msg>Add close method to Raw class Fixes #10<commit_after>
from rawkit.libraw import libraw class Raw(object): def __init__(self, filename=None): self.data = libraw.libraw_init(0) libraw.libraw_open_file(self.data, bytes(filename, 'utf-8')) def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): """Clean up after ourselves when leaving the context manager.""" self.close() def close(self): """Free the underlying raw representation.""" libraw.libraw_close(self.data) def process(self, options=None): """ Unpack and process the raw data into something more usable. """ libraw.libraw_unpack(self.data) libraw.libraw_dcraw_process(self.data) def save(self, filename=None): libraw.libraw_dcraw_ppm_tiff_writer( self.data, bytes(filename, 'utf-8'))
from rawkit.libraw import libraw class Raw(object): def __init__(self, filename=None): self.data = libraw.libraw_init(0) libraw.libraw_open_file(self.data, bytes(filename, 'utf-8')) def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): libraw.libraw_close(self.data) def process(self, options=None): libraw.libraw_unpack(self.data) libraw.libraw_dcraw_process(self.data) def save(self, filename=None): libraw.libraw_dcraw_ppm_tiff_writer( self.data, bytes(filename, 'utf-8')) Add close method to Raw class Fixes #10from rawkit.libraw import libraw class Raw(object): def __init__(self, filename=None): self.data = libraw.libraw_init(0) libraw.libraw_open_file(self.data, bytes(filename, 'utf-8')) def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): """Clean up after ourselves when leaving the context manager.""" self.close() def close(self): """Free the underlying raw representation.""" libraw.libraw_close(self.data) def process(self, options=None): """ Unpack and process the raw data into something more usable. """ libraw.libraw_unpack(self.data) libraw.libraw_dcraw_process(self.data) def save(self, filename=None): libraw.libraw_dcraw_ppm_tiff_writer( self.data, bytes(filename, 'utf-8'))
<commit_before>from rawkit.libraw import libraw class Raw(object): def __init__(self, filename=None): self.data = libraw.libraw_init(0) libraw.libraw_open_file(self.data, bytes(filename, 'utf-8')) def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): libraw.libraw_close(self.data) def process(self, options=None): libraw.libraw_unpack(self.data) libraw.libraw_dcraw_process(self.data) def save(self, filename=None): libraw.libraw_dcraw_ppm_tiff_writer( self.data, bytes(filename, 'utf-8')) <commit_msg>Add close method to Raw class Fixes #10<commit_after>from rawkit.libraw import libraw class Raw(object): def __init__(self, filename=None): self.data = libraw.libraw_init(0) libraw.libraw_open_file(self.data, bytes(filename, 'utf-8')) def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): """Clean up after ourselves when leaving the context manager.""" self.close() def close(self): """Free the underlying raw representation.""" libraw.libraw_close(self.data) def process(self, options=None): """ Unpack and process the raw data into something more usable. """ libraw.libraw_unpack(self.data) libraw.libraw_dcraw_process(self.data) def save(self, filename=None): libraw.libraw_dcraw_ppm_tiff_writer( self.data, bytes(filename, 'utf-8'))
abd5fcac1fa585daa73910273adf429baf671de3
contrib/runners/windows_runner/windows_runner/__init__.py
contrib/runners/windows_runner/windows_runner/__init__.py
# -*- coding: utf-8 -*- # Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Note: This is here for backward compatibility - in the past, runners were single module # packages, but now they are full blown Python packages. # This means you can either do "from runner_name import RunnerClass" (old way, don't do that) # or "from runner_name.runner_name import RunnerClass" from __future__ import absolute_import from .windows_command_runner import * # noqa from .windows_script_runner import * # noqa
# -*- coding: utf-8 -*- # Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
Remove code we dont need anymore.
Remove code we dont need anymore.
Python
apache-2.0
nzlosh/st2,StackStorm/st2,StackStorm/st2,StackStorm/st2,Plexxi/st2,Plexxi/st2,Plexxi/st2,nzlosh/st2,nzlosh/st2,nzlosh/st2,StackStorm/st2,Plexxi/st2
# -*- coding: utf-8 -*- # Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Note: This is here for backward compatibility - in the past, runners were single module # packages, but now they are full blown Python packages. # This means you can either do "from runner_name import RunnerClass" (old way, don't do that) # or "from runner_name.runner_name import RunnerClass" from __future__ import absolute_import from .windows_command_runner import * # noqa from .windows_script_runner import * # noqa Remove code we dont need anymore.
# -*- coding: utf-8 -*- # Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
<commit_before># -*- coding: utf-8 -*- # Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Note: This is here for backward compatibility - in the past, runners were single module # packages, but now they are full blown Python packages. # This means you can either do "from runner_name import RunnerClass" (old way, don't do that) # or "from runner_name.runner_name import RunnerClass" from __future__ import absolute_import from .windows_command_runner import * # noqa from .windows_script_runner import * # noqa <commit_msg>Remove code we dont need anymore.<commit_after>
# -*- coding: utf-8 -*- # Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
# -*- coding: utf-8 -*- # Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Note: This is here for backward compatibility - in the past, runners were single module # packages, but now they are full blown Python packages. # This means you can either do "from runner_name import RunnerClass" (old way, don't do that) # or "from runner_name.runner_name import RunnerClass" from __future__ import absolute_import from .windows_command_runner import * # noqa from .windows_script_runner import * # noqa Remove code we dont need anymore.# -*- coding: utf-8 -*- # Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
<commit_before># -*- coding: utf-8 -*- # Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Note: This is here for backward compatibility - in the past, runners were single module # packages, but now they are full blown Python packages. # This means you can either do "from runner_name import RunnerClass" (old way, don't do that) # or "from runner_name.runner_name import RunnerClass" from __future__ import absolute_import from .windows_command_runner import * # noqa from .windows_script_runner import * # noqa <commit_msg>Remove code we dont need anymore.<commit_after># -*- coding: utf-8 -*- # Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
139b0ae83ff4faa633a628c09f61b33b755b3502
dataset/print.py
dataset/print.py
import json with open('short_dataset_item.json') as dataset_file: dataset = json.load(dataset_file) for i in range(len(dataset)): if 'Continual' == dataset[i]['frequency']: print dataset[i]['name']
import json with open('dataset_item.json') as dataset_file: dataset = json.load(dataset_file) for i in range(len(dataset)): if 'Continual' == dataset[i]['frequency']: print dataset[i]['name']
Fix name to correct dataset JSON file
Fix name to correct dataset JSON file
Python
mit
MaxLikelihood/CODE
import json with open('short_dataset_item.json') as dataset_file: dataset = json.load(dataset_file) for i in range(len(dataset)): if 'Continual' == dataset[i]['frequency']: print dataset[i]['name'] Fix name to correct dataset JSON file
import json with open('dataset_item.json') as dataset_file: dataset = json.load(dataset_file) for i in range(len(dataset)): if 'Continual' == dataset[i]['frequency']: print dataset[i]['name']
<commit_before>import json with open('short_dataset_item.json') as dataset_file: dataset = json.load(dataset_file) for i in range(len(dataset)): if 'Continual' == dataset[i]['frequency']: print dataset[i]['name'] <commit_msg>Fix name to correct dataset JSON file<commit_after>
import json with open('dataset_item.json') as dataset_file: dataset = json.load(dataset_file) for i in range(len(dataset)): if 'Continual' == dataset[i]['frequency']: print dataset[i]['name']
import json with open('short_dataset_item.json') as dataset_file: dataset = json.load(dataset_file) for i in range(len(dataset)): if 'Continual' == dataset[i]['frequency']: print dataset[i]['name'] Fix name to correct dataset JSON fileimport json with open('dataset_item.json') as dataset_file: dataset = json.load(dataset_file) for i in range(len(dataset)): if 'Continual' == dataset[i]['frequency']: print dataset[i]['name']
<commit_before>import json with open('short_dataset_item.json') as dataset_file: dataset = json.load(dataset_file) for i in range(len(dataset)): if 'Continual' == dataset[i]['frequency']: print dataset[i]['name'] <commit_msg>Fix name to correct dataset JSON file<commit_after>import json with open('dataset_item.json') as dataset_file: dataset = json.load(dataset_file) for i in range(len(dataset)): if 'Continual' == dataset[i]['frequency']: print dataset[i]['name']
6e874375ee1d371a3e6ecb786ade4e1b16d84da5
wafer/kv/views.py
wafer/kv/views.py
from rest_framework import viewsets from wafer.kv.models import KeyValue from wafer.kv.serializers import KeyValueSerializer from wafer.kv.permissions import KeyValueGroupPermission class KeyValueViewSet(viewsets.ModelViewSet): """API endpoint that allows key-value pairs to be viewed or edited.""" queryset = KeyValue.objects.none() # Needed for the REST Permissions serializer_class = KeyValueSerializer permission_classes = (KeyValueGroupPermission, ) def get_queryset(self): # Restrict the list to only those that match the user's # groups if self.request.user.id is not None: grp_ids = [x.id for x in self.request.user.groups.all()] return KeyValue.objects.filter(group_id__in=grp_ids) return KeyValue.objects.none()
from rest_framework import viewsets from wafer.kv.models import KeyValue from wafer.kv.serializers import KeyValueSerializer from wafer.kv.permissions import KeyValueGroupPermission from wafer.utils import order_results_by class KeyValueViewSet(viewsets.ModelViewSet): """API endpoint that allows key-value pairs to be viewed or edited.""" queryset = KeyValue.objects.none() # Needed for the REST Permissions serializer_class = KeyValueSerializer permission_classes = (KeyValueGroupPermission, ) @order_results_by('key', 'id') def get_queryset(self): # Restrict the list to only those that match the user's # groups if self.request.user.id is not None: grp_ids = [x.id for x in self.request.user.groups.all()] return KeyValue.objects.filter(group_id__in=grp_ids) return KeyValue.objects.none()
Order paginated KV API results.
Order paginated KV API results.
Python
isc
CTPUG/wafer,CTPUG/wafer,CTPUG/wafer,CTPUG/wafer
from rest_framework import viewsets from wafer.kv.models import KeyValue from wafer.kv.serializers import KeyValueSerializer from wafer.kv.permissions import KeyValueGroupPermission class KeyValueViewSet(viewsets.ModelViewSet): """API endpoint that allows key-value pairs to be viewed or edited.""" queryset = KeyValue.objects.none() # Needed for the REST Permissions serializer_class = KeyValueSerializer permission_classes = (KeyValueGroupPermission, ) def get_queryset(self): # Restrict the list to only those that match the user's # groups if self.request.user.id is not None: grp_ids = [x.id for x in self.request.user.groups.all()] return KeyValue.objects.filter(group_id__in=grp_ids) return KeyValue.objects.none() Order paginated KV API results.
from rest_framework import viewsets from wafer.kv.models import KeyValue from wafer.kv.serializers import KeyValueSerializer from wafer.kv.permissions import KeyValueGroupPermission from wafer.utils import order_results_by class KeyValueViewSet(viewsets.ModelViewSet): """API endpoint that allows key-value pairs to be viewed or edited.""" queryset = KeyValue.objects.none() # Needed for the REST Permissions serializer_class = KeyValueSerializer permission_classes = (KeyValueGroupPermission, ) @order_results_by('key', 'id') def get_queryset(self): # Restrict the list to only those that match the user's # groups if self.request.user.id is not None: grp_ids = [x.id for x in self.request.user.groups.all()] return KeyValue.objects.filter(group_id__in=grp_ids) return KeyValue.objects.none()
<commit_before>from rest_framework import viewsets from wafer.kv.models import KeyValue from wafer.kv.serializers import KeyValueSerializer from wafer.kv.permissions import KeyValueGroupPermission class KeyValueViewSet(viewsets.ModelViewSet): """API endpoint that allows key-value pairs to be viewed or edited.""" queryset = KeyValue.objects.none() # Needed for the REST Permissions serializer_class = KeyValueSerializer permission_classes = (KeyValueGroupPermission, ) def get_queryset(self): # Restrict the list to only those that match the user's # groups if self.request.user.id is not None: grp_ids = [x.id for x in self.request.user.groups.all()] return KeyValue.objects.filter(group_id__in=grp_ids) return KeyValue.objects.none() <commit_msg>Order paginated KV API results.<commit_after>
from rest_framework import viewsets from wafer.kv.models import KeyValue from wafer.kv.serializers import KeyValueSerializer from wafer.kv.permissions import KeyValueGroupPermission from wafer.utils import order_results_by class KeyValueViewSet(viewsets.ModelViewSet): """API endpoint that allows key-value pairs to be viewed or edited.""" queryset = KeyValue.objects.none() # Needed for the REST Permissions serializer_class = KeyValueSerializer permission_classes = (KeyValueGroupPermission, ) @order_results_by('key', 'id') def get_queryset(self): # Restrict the list to only those that match the user's # groups if self.request.user.id is not None: grp_ids = [x.id for x in self.request.user.groups.all()] return KeyValue.objects.filter(group_id__in=grp_ids) return KeyValue.objects.none()
from rest_framework import viewsets from wafer.kv.models import KeyValue from wafer.kv.serializers import KeyValueSerializer from wafer.kv.permissions import KeyValueGroupPermission class KeyValueViewSet(viewsets.ModelViewSet): """API endpoint that allows key-value pairs to be viewed or edited.""" queryset = KeyValue.objects.none() # Needed for the REST Permissions serializer_class = KeyValueSerializer permission_classes = (KeyValueGroupPermission, ) def get_queryset(self): # Restrict the list to only those that match the user's # groups if self.request.user.id is not None: grp_ids = [x.id for x in self.request.user.groups.all()] return KeyValue.objects.filter(group_id__in=grp_ids) return KeyValue.objects.none() Order paginated KV API results.from rest_framework import viewsets from wafer.kv.models import KeyValue from wafer.kv.serializers import KeyValueSerializer from wafer.kv.permissions import KeyValueGroupPermission from wafer.utils import order_results_by class KeyValueViewSet(viewsets.ModelViewSet): """API endpoint that allows key-value pairs to be viewed or edited.""" queryset = KeyValue.objects.none() # Needed for the REST Permissions serializer_class = KeyValueSerializer permission_classes = (KeyValueGroupPermission, ) @order_results_by('key', 'id') def get_queryset(self): # Restrict the list to only those that match the user's # groups if self.request.user.id is not None: grp_ids = [x.id for x in self.request.user.groups.all()] return KeyValue.objects.filter(group_id__in=grp_ids) return KeyValue.objects.none()
<commit_before>from rest_framework import viewsets from wafer.kv.models import KeyValue from wafer.kv.serializers import KeyValueSerializer from wafer.kv.permissions import KeyValueGroupPermission class KeyValueViewSet(viewsets.ModelViewSet): """API endpoint that allows key-value pairs to be viewed or edited.""" queryset = KeyValue.objects.none() # Needed for the REST Permissions serializer_class = KeyValueSerializer permission_classes = (KeyValueGroupPermission, ) def get_queryset(self): # Restrict the list to only those that match the user's # groups if self.request.user.id is not None: grp_ids = [x.id for x in self.request.user.groups.all()] return KeyValue.objects.filter(group_id__in=grp_ids) return KeyValue.objects.none() <commit_msg>Order paginated KV API results.<commit_after>from rest_framework import viewsets from wafer.kv.models import KeyValue from wafer.kv.serializers import KeyValueSerializer from wafer.kv.permissions import KeyValueGroupPermission from wafer.utils import order_results_by class KeyValueViewSet(viewsets.ModelViewSet): """API endpoint that allows key-value pairs to be viewed or edited.""" queryset = KeyValue.objects.none() # Needed for the REST Permissions serializer_class = KeyValueSerializer permission_classes = (KeyValueGroupPermission, ) @order_results_by('key', 'id') def get_queryset(self): # Restrict the list to only those that match the user's # groups if self.request.user.id is not None: grp_ids = [x.id for x in self.request.user.groups.all()] return KeyValue.objects.filter(group_id__in=grp_ids) return KeyValue.objects.none()
d8872865cc7159ffeeae45a860b97cd241f95c6e
vispy/visuals/tests/test_arrows.py
vispy/visuals/tests/test_arrows.py
# -*- coding: utf-8 -*- # Copyright (c) 2015, Vispy Development Team. # Distributed under the (new) BSD License. See LICENSE.txt for more info. import numpy as np from vispy.visuals.line.arrow import ARROW_TYPES from vispy.scene import visuals, transforms from vispy.testing import (requires_application, TestingCanvas, run_tests_if_main, raises) from vispy.testing.image_tester import assert_image_approved @requires_application() def test_line_draw(): """Test drawing arrows without transforms""" vertices = np.array([ [25, 25], [25, 75], [50, 25], [50, 75], [75, 25], [75, 75] ]).astype('f32') arrows = np.array([ vertices[:2], vertices[3:1:-1], vertices[4:], vertices[-1:-3:-1] ]).reshape((4, 4)) with TestingCanvas() as c: for arrow_type in ARROW_TYPES: arrow = visuals.Arrow(pos=vertices, arrow_type=arrow_type, arrows=arrows, arrow_size=10, color='red', connect="segments", antialias=True, parent=c.scene) assert_image_approved(c.render(), 'visuals/arrow_type_%s.png' % arrow_type) arrow.parent = None run_tests_if_main()
# -*- coding: utf-8 -*- # Copyright (c) 2015, Vispy Development Team. # Distributed under the (new) BSD License. See LICENSE.txt for more info. import numpy as np from vispy.visuals.line.arrow import ARROW_TYPES from vispy.scene import visuals, transforms from vispy.testing import (requires_application, TestingCanvas, run_tests_if_main, raises) from vispy.testing.image_tester import assert_image_approved @requires_application() def test_line_draw(): """Test drawing arrows without transforms""" vertices = np.array([ [25, 25], [25, 75], [50, 25], [50, 75], [75, 25], [75, 75] ]).astype('f32') arrows = np.array([ vertices[:2], vertices[3:1:-1], vertices[4:], vertices[-1:-3:-1] ]).reshape((4, 4)) with TestingCanvas() as c: for arrow_type in ARROW_TYPES: arrow = visuals.Arrow(pos=vertices, arrow_type=arrow_type, arrows=arrows, arrow_size=10, color='red', connect="segments", parent=c.scene) assert_image_approved(c.render(), 'visuals/arrow_type_%s.png' % arrow_type) arrow.parent = None run_tests_if_main()
Disable antialias for GL drawing lines
Disable antialias for GL drawing lines
Python
bsd-3-clause
inclement/vispy,michaelaye/vispy,srinathv/vispy,jay3sh/vispy,julienr/vispy,QuLogic/vispy,jay3sh/vispy,julienr/vispy,ghisvail/vispy,drufat/vispy,Eric89GXL/vispy,inclement/vispy,RebeccaWPerry/vispy,michaelaye/vispy,kkuunnddaannkk/vispy,Eric89GXL/vispy,jdreaver/vispy,sbtlaarzc/vispy,srinathv/vispy,Eric89GXL/vispy,drufat/vispy,dchilds7/Deysha-Star-Formation,ghisvail/vispy,jay3sh/vispy,jdreaver/vispy,kkuunnddaannkk/vispy,drufat/vispy,inclement/vispy,QuLogic/vispy,ghisvail/vispy,sbtlaarzc/vispy,dchilds7/Deysha-Star-Formation,dchilds7/Deysha-Star-Formation,michaelaye/vispy,sbtlaarzc/vispy,srinathv/vispy,RebeccaWPerry/vispy,julienr/vispy,QuLogic/vispy,bollu/vispy,bollu/vispy,jdreaver/vispy,RebeccaWPerry/vispy,kkuunnddaannkk/vispy,bollu/vispy
# -*- coding: utf-8 -*- # Copyright (c) 2015, Vispy Development Team. # Distributed under the (new) BSD License. See LICENSE.txt for more info. import numpy as np from vispy.visuals.line.arrow import ARROW_TYPES from vispy.scene import visuals, transforms from vispy.testing import (requires_application, TestingCanvas, run_tests_if_main, raises) from vispy.testing.image_tester import assert_image_approved @requires_application() def test_line_draw(): """Test drawing arrows without transforms""" vertices = np.array([ [25, 25], [25, 75], [50, 25], [50, 75], [75, 25], [75, 75] ]).astype('f32') arrows = np.array([ vertices[:2], vertices[3:1:-1], vertices[4:], vertices[-1:-3:-1] ]).reshape((4, 4)) with TestingCanvas() as c: for arrow_type in ARROW_TYPES: arrow = visuals.Arrow(pos=vertices, arrow_type=arrow_type, arrows=arrows, arrow_size=10, color='red', connect="segments", antialias=True, parent=c.scene) assert_image_approved(c.render(), 'visuals/arrow_type_%s.png' % arrow_type) arrow.parent = None run_tests_if_main() Disable antialias for GL drawing lines
# -*- coding: utf-8 -*- # Copyright (c) 2015, Vispy Development Team. # Distributed under the (new) BSD License. See LICENSE.txt for more info. import numpy as np from vispy.visuals.line.arrow import ARROW_TYPES from vispy.scene import visuals, transforms from vispy.testing import (requires_application, TestingCanvas, run_tests_if_main, raises) from vispy.testing.image_tester import assert_image_approved @requires_application() def test_line_draw(): """Test drawing arrows without transforms""" vertices = np.array([ [25, 25], [25, 75], [50, 25], [50, 75], [75, 25], [75, 75] ]).astype('f32') arrows = np.array([ vertices[:2], vertices[3:1:-1], vertices[4:], vertices[-1:-3:-1] ]).reshape((4, 4)) with TestingCanvas() as c: for arrow_type in ARROW_TYPES: arrow = visuals.Arrow(pos=vertices, arrow_type=arrow_type, arrows=arrows, arrow_size=10, color='red', connect="segments", parent=c.scene) assert_image_approved(c.render(), 'visuals/arrow_type_%s.png' % arrow_type) arrow.parent = None run_tests_if_main()
<commit_before># -*- coding: utf-8 -*- # Copyright (c) 2015, Vispy Development Team. # Distributed under the (new) BSD License. See LICENSE.txt for more info. import numpy as np from vispy.visuals.line.arrow import ARROW_TYPES from vispy.scene import visuals, transforms from vispy.testing import (requires_application, TestingCanvas, run_tests_if_main, raises) from vispy.testing.image_tester import assert_image_approved @requires_application() def test_line_draw(): """Test drawing arrows without transforms""" vertices = np.array([ [25, 25], [25, 75], [50, 25], [50, 75], [75, 25], [75, 75] ]).astype('f32') arrows = np.array([ vertices[:2], vertices[3:1:-1], vertices[4:], vertices[-1:-3:-1] ]).reshape((4, 4)) with TestingCanvas() as c: for arrow_type in ARROW_TYPES: arrow = visuals.Arrow(pos=vertices, arrow_type=arrow_type, arrows=arrows, arrow_size=10, color='red', connect="segments", antialias=True, parent=c.scene) assert_image_approved(c.render(), 'visuals/arrow_type_%s.png' % arrow_type) arrow.parent = None run_tests_if_main() <commit_msg>Disable antialias for GL drawing lines<commit_after>
# -*- coding: utf-8 -*- # Copyright (c) 2015, Vispy Development Team. # Distributed under the (new) BSD License. See LICENSE.txt for more info. import numpy as np from vispy.visuals.line.arrow import ARROW_TYPES from vispy.scene import visuals, transforms from vispy.testing import (requires_application, TestingCanvas, run_tests_if_main, raises) from vispy.testing.image_tester import assert_image_approved @requires_application() def test_line_draw(): """Test drawing arrows without transforms""" vertices = np.array([ [25, 25], [25, 75], [50, 25], [50, 75], [75, 25], [75, 75] ]).astype('f32') arrows = np.array([ vertices[:2], vertices[3:1:-1], vertices[4:], vertices[-1:-3:-1] ]).reshape((4, 4)) with TestingCanvas() as c: for arrow_type in ARROW_TYPES: arrow = visuals.Arrow(pos=vertices, arrow_type=arrow_type, arrows=arrows, arrow_size=10, color='red', connect="segments", parent=c.scene) assert_image_approved(c.render(), 'visuals/arrow_type_%s.png' % arrow_type) arrow.parent = None run_tests_if_main()
# -*- coding: utf-8 -*- # Copyright (c) 2015, Vispy Development Team. # Distributed under the (new) BSD License. See LICENSE.txt for more info. import numpy as np from vispy.visuals.line.arrow import ARROW_TYPES from vispy.scene import visuals, transforms from vispy.testing import (requires_application, TestingCanvas, run_tests_if_main, raises) from vispy.testing.image_tester import assert_image_approved @requires_application() def test_line_draw(): """Test drawing arrows without transforms""" vertices = np.array([ [25, 25], [25, 75], [50, 25], [50, 75], [75, 25], [75, 75] ]).astype('f32') arrows = np.array([ vertices[:2], vertices[3:1:-1], vertices[4:], vertices[-1:-3:-1] ]).reshape((4, 4)) with TestingCanvas() as c: for arrow_type in ARROW_TYPES: arrow = visuals.Arrow(pos=vertices, arrow_type=arrow_type, arrows=arrows, arrow_size=10, color='red', connect="segments", antialias=True, parent=c.scene) assert_image_approved(c.render(), 'visuals/arrow_type_%s.png' % arrow_type) arrow.parent = None run_tests_if_main() Disable antialias for GL drawing lines# -*- coding: utf-8 -*- # Copyright (c) 2015, Vispy Development Team. # Distributed under the (new) BSD License. See LICENSE.txt for more info. import numpy as np from vispy.visuals.line.arrow import ARROW_TYPES from vispy.scene import visuals, transforms from vispy.testing import (requires_application, TestingCanvas, run_tests_if_main, raises) from vispy.testing.image_tester import assert_image_approved @requires_application() def test_line_draw(): """Test drawing arrows without transforms""" vertices = np.array([ [25, 25], [25, 75], [50, 25], [50, 75], [75, 25], [75, 75] ]).astype('f32') arrows = np.array([ vertices[:2], vertices[3:1:-1], vertices[4:], vertices[-1:-3:-1] ]).reshape((4, 4)) with TestingCanvas() as c: for arrow_type in ARROW_TYPES: arrow = visuals.Arrow(pos=vertices, arrow_type=arrow_type, arrows=arrows, arrow_size=10, color='red', connect="segments", parent=c.scene) assert_image_approved(c.render(), 'visuals/arrow_type_%s.png' % arrow_type) arrow.parent = None run_tests_if_main()
<commit_before># -*- coding: utf-8 -*- # Copyright (c) 2015, Vispy Development Team. # Distributed under the (new) BSD License. See LICENSE.txt for more info. import numpy as np from vispy.visuals.line.arrow import ARROW_TYPES from vispy.scene import visuals, transforms from vispy.testing import (requires_application, TestingCanvas, run_tests_if_main, raises) from vispy.testing.image_tester import assert_image_approved @requires_application() def test_line_draw(): """Test drawing arrows without transforms""" vertices = np.array([ [25, 25], [25, 75], [50, 25], [50, 75], [75, 25], [75, 75] ]).astype('f32') arrows = np.array([ vertices[:2], vertices[3:1:-1], vertices[4:], vertices[-1:-3:-1] ]).reshape((4, 4)) with TestingCanvas() as c: for arrow_type in ARROW_TYPES: arrow = visuals.Arrow(pos=vertices, arrow_type=arrow_type, arrows=arrows, arrow_size=10, color='red', connect="segments", antialias=True, parent=c.scene) assert_image_approved(c.render(), 'visuals/arrow_type_%s.png' % arrow_type) arrow.parent = None run_tests_if_main() <commit_msg>Disable antialias for GL drawing lines<commit_after># -*- coding: utf-8 -*- # Copyright (c) 2015, Vispy Development Team. # Distributed under the (new) BSD License. See LICENSE.txt for more info. import numpy as np from vispy.visuals.line.arrow import ARROW_TYPES from vispy.scene import visuals, transforms from vispy.testing import (requires_application, TestingCanvas, run_tests_if_main, raises) from vispy.testing.image_tester import assert_image_approved @requires_application() def test_line_draw(): """Test drawing arrows without transforms""" vertices = np.array([ [25, 25], [25, 75], [50, 25], [50, 75], [75, 25], [75, 75] ]).astype('f32') arrows = np.array([ vertices[:2], vertices[3:1:-1], vertices[4:], vertices[-1:-3:-1] ]).reshape((4, 4)) with TestingCanvas() as c: for arrow_type in ARROW_TYPES: arrow = visuals.Arrow(pos=vertices, arrow_type=arrow_type, arrows=arrows, arrow_size=10, color='red', connect="segments", parent=c.scene) assert_image_approved(c.render(), 'visuals/arrow_type_%s.png' % arrow_type) arrow.parent = None run_tests_if_main()
c5548840286084f477f689d87539be73751ab784
accio/users/models.py
accio/users/models.py
from django.contrib.auth.models import AbstractUser from django.utils.functional import cached_property from social.apps.django_app.default.models import UserSocialAuth class User(AbstractUser): def save(self, *args, **kwargs): if not self.pk: self.is_staff = True super().save(*args, **kwargs) @cached_property def github_token(self): try: return self.social_auth.get(provider='github').extra_data['access_token'] except UserSocialAuth.DoesNotExist: return
from django.contrib.auth.models import AbstractUser from django.utils.functional import cached_property from social.apps.django_app.default.models import UserSocialAuth class User(AbstractUser): def save(self, *args, **kwargs): if not self.pk: self.is_active = False super().save(*args, **kwargs) @cached_property def github_token(self): try: return self.social_auth.get(provider='github').extra_data['access_token'] except UserSocialAuth.DoesNotExist: return
Make users be inactive on creation
fix: Make users be inactive on creation
Python
mit
relekang/accio,relekang/accio,relekang/accio
from django.contrib.auth.models import AbstractUser from django.utils.functional import cached_property from social.apps.django_app.default.models import UserSocialAuth class User(AbstractUser): def save(self, *args, **kwargs): if not self.pk: self.is_staff = True super().save(*args, **kwargs) @cached_property def github_token(self): try: return self.social_auth.get(provider='github').extra_data['access_token'] except UserSocialAuth.DoesNotExist: return fix: Make users be inactive on creation
from django.contrib.auth.models import AbstractUser from django.utils.functional import cached_property from social.apps.django_app.default.models import UserSocialAuth class User(AbstractUser): def save(self, *args, **kwargs): if not self.pk: self.is_active = False super().save(*args, **kwargs) @cached_property def github_token(self): try: return self.social_auth.get(provider='github').extra_data['access_token'] except UserSocialAuth.DoesNotExist: return
<commit_before>from django.contrib.auth.models import AbstractUser from django.utils.functional import cached_property from social.apps.django_app.default.models import UserSocialAuth class User(AbstractUser): def save(self, *args, **kwargs): if not self.pk: self.is_staff = True super().save(*args, **kwargs) @cached_property def github_token(self): try: return self.social_auth.get(provider='github').extra_data['access_token'] except UserSocialAuth.DoesNotExist: return <commit_msg>fix: Make users be inactive on creation<commit_after>
from django.contrib.auth.models import AbstractUser from django.utils.functional import cached_property from social.apps.django_app.default.models import UserSocialAuth class User(AbstractUser): def save(self, *args, **kwargs): if not self.pk: self.is_active = False super().save(*args, **kwargs) @cached_property def github_token(self): try: return self.social_auth.get(provider='github').extra_data['access_token'] except UserSocialAuth.DoesNotExist: return
from django.contrib.auth.models import AbstractUser from django.utils.functional import cached_property from social.apps.django_app.default.models import UserSocialAuth class User(AbstractUser): def save(self, *args, **kwargs): if not self.pk: self.is_staff = True super().save(*args, **kwargs) @cached_property def github_token(self): try: return self.social_auth.get(provider='github').extra_data['access_token'] except UserSocialAuth.DoesNotExist: return fix: Make users be inactive on creationfrom django.contrib.auth.models import AbstractUser from django.utils.functional import cached_property from social.apps.django_app.default.models import UserSocialAuth class User(AbstractUser): def save(self, *args, **kwargs): if not self.pk: self.is_active = False super().save(*args, **kwargs) @cached_property def github_token(self): try: return self.social_auth.get(provider='github').extra_data['access_token'] except UserSocialAuth.DoesNotExist: return
<commit_before>from django.contrib.auth.models import AbstractUser from django.utils.functional import cached_property from social.apps.django_app.default.models import UserSocialAuth class User(AbstractUser): def save(self, *args, **kwargs): if not self.pk: self.is_staff = True super().save(*args, **kwargs) @cached_property def github_token(self): try: return self.social_auth.get(provider='github').extra_data['access_token'] except UserSocialAuth.DoesNotExist: return <commit_msg>fix: Make users be inactive on creation<commit_after>from django.contrib.auth.models import AbstractUser from django.utils.functional import cached_property from social.apps.django_app.default.models import UserSocialAuth class User(AbstractUser): def save(self, *args, **kwargs): if not self.pk: self.is_active = False super().save(*args, **kwargs) @cached_property def github_token(self): try: return self.social_auth.get(provider='github').extra_data['access_token'] except UserSocialAuth.DoesNotExist: return
a1be6021c4d13b1212dff74dc981a602951994fb
erpnext/patches/v4_0/customer_discount_to_pricing_rule.py
erpnext/patches/v4_0/customer_discount_to_pricing_rule.py
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.utils.nestedset import get_root_of def execute(): frappe.reload_doc("accounts", "doctype", "pricing_rule") frappe.db.auto_commit_on_many_writes = True default_item_group = get_root_of("Item Group") for d in frappe.db.sql("""select * from `tabCustomer Discount` where ifnull(parent, '') != ''""", as_dict=1): if not d.discount: continue frappe.get_doc({ "doctype": "Pricing Rule", "apply_on": "Item Group", "item_group": d.item_group or default_item_group, "applicable_for": "Customer", "customer": d.parent, "price_or_discount": "Discount Percentage", "discount_percentage": d.discount }).insert() frappe.db.auto_commit_on_many_writes = False frappe.delete_doc("DocType", "Customer Discount")
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.utils.nestedset import get_root_of def execute(): frappe.reload_doc("accounts", "doctype", "pricing_rule") frappe.db.auto_commit_on_many_writes = True default_item_group = get_root_of("Item Group") for d in frappe.db.sql("""select * from `tabCustomer Discount` where ifnull(parent, '') != ''""", as_dict=1): if not d.discount: continue frappe.get_doc({ "doctype": "Pricing Rule", "apply_on": "Item Group", "item_group": d.item_group or default_item_group, "applicable_for": "Customer", "customer": d.parent, "price_or_discount": "Discount Percentage", "discount_percentage": d.discount, "selling": 1 }).insert() frappe.db.auto_commit_on_many_writes = False frappe.delete_doc("DocType", "Customer Discount")
Fix in pricing rule patch
Fix in pricing rule patch
Python
agpl-3.0
mbauskar/omnitech-erpnext,indictranstech/internal-erpnext,pawaranand/phrerp,SPKian/Testing,indictranstech/reciphergroup-erpnext,Drooids/erpnext,suyashphadtare/gd-erp,shft117/SteckerApp,hernad/erpnext,pawaranand/phrerp,pombredanne/erpnext,rohitwaghchaure/digitales_erpnext,Tejal011089/trufil-erpnext,suyashphadtare/sajil-final-erp,gangadhar-kadam/latestchurcherp,netfirms/erpnext,gangadharkadam/saloon_erp_install,treejames/erpnext,indictranstech/trufil-erpnext,indictranstech/phrerp,geekroot/erpnext,sagar30051991/ozsmart-erp,Drooids/erpnext,indictranstech/focal-erpnext,gangadhar-kadam/laganerp,gangadharkadam/v4_erp,sheafferusa/erpnext,indictranstech/focal-erpnext,tmimori/erpnext,gangadharkadam/contributionerp,rohitwaghchaure/New_Theme_Erp,Tejal011089/digitales_erpnext,Suninus/erpnext,mbauskar/helpdesk-erpnext,mbauskar/helpdesk-erpnext,indictranstech/phrerp,gangadhar-kadam/helpdesk-erpnext,gangadharkadam/saloon_erp_install,Tejal011089/huntercamp_erpnext,hatwar/Das_erpnext,pombredanne/erpnext,ShashaQin/erpnext,indictranstech/internal-erpnext,aruizramon/alec_erpnext,Tejal011089/fbd_erpnext,indictranstech/fbd_erpnext,indictranstech/phrerp,mahabuber/erpnext,rohitwaghchaure/GenieManager-erpnext,SPKian/Testing,Tejal011089/huntercamp_erpnext,meisterkleister/erpnext,BhupeshGupta/erpnext,Tejal011089/digitales_erpnext,sheafferusa/erpnext,Tejal011089/digitales_erpnext,gangadhar-kadam/verve-erp,mbauskar/sapphire-erpnext,pawaranand/phrerp,hatwar/focal-erpnext,shitolepriya/test-erp,ThiagoGarciaAlves/erpnext,gangadharkadam/saloon_erp_install,gangadharkadam/sher,suyashphadtare/test,gangadhar-kadam/verve_live_erp,gangadharkadam/verveerp,gangadharkadam/saloon_erp,rohitwaghchaure/erpnext-receipher,ShashaQin/erpnext,suyashphadtare/test,gangadharkadam/v5_erp,indictranstech/phrerp,rohitwaghchaure/digitales_erpnext,mbauskar/Das_Erpnext,gangadharkadam/smrterp,rohitwaghchaure/New_Theme_Erp,MartinEnder/erpnext-de,Tejal011089/paypal_erpnext,gangadharkadam/saloon_erp,gsnbng/erpnext,hatwar/buyback-erpnext,gangadharkadam/contributionerp,gsnbng/erpnext,anandpdoshi/erpnext,indictranstech/Das_Erpnext,indictranstech/trufil-erpnext,indictranstech/osmosis-erpnext,suyashphadtare/gd-erp,mahabuber/erpnext,rohitwaghchaure/erpnext_smart,shft117/SteckerApp,Tejal011089/paypal_erpnext,rohitwaghchaure/erpnext_smart,gangadhar-kadam/verve_test_erp,mbauskar/alec_frappe5_erpnext,MartinEnder/erpnext-de,ShashaQin/erpnext,suyashphadtare/vestasi-erp-1,hatwar/Das_erpnext,indictranstech/erpnext,Tejal011089/digitales_erpnext,njmube/erpnext,gangadharkadam/saloon_erp,susuchina/ERPNEXT,gangadhar-kadam/helpdesk-erpnext,fuhongliang/erpnext,gangadharkadam/vlinkerp,gangadharkadam/saloon_erp,indictranstech/erpnext,hatwar/focal-erpnext,suyashphadtare/vestasi-erp-jan-end,Suninus/erpnext,SPKian/Testing2,gmarke/erpnext,gangadharkadam/letzerp,fuhongliang/erpnext,njmube/erpnext,mahabuber/erpnext,pombredanne/erpnext,indictranstech/osmosis-erpnext,shitolepriya/test-erp,gangadhar-kadam/helpdesk-erpnext,tmimori/erpnext,gangadharkadam/office_erp,gangadhar-kadam/verve_erp,hanselke/erpnext-1,gangadharkadam/letzerp,susuchina/ERPNEXT,indictranstech/Das_Erpnext,hatwar/buyback-erpnext,indictranstech/buyback-erp,gangadharkadam/johnerp,indictranstech/focal-erpnext,gangadharkadam/verveerp,BhupeshGupta/erpnext,hatwar/focal-erpnext,netfirms/erpnext,gangadharkadam/sterp,netfirms/erpnext,indictranstech/focal-erpnext,suyashphadtare/sajil-erp,suyashphadtare/vestasi-erp-final,Tejal011089/osmosis_erpnext,Tejal011089/trufil-erpnext,suyashphadtare/test,sagar30051991/ozsmart-erp,indictranstech/osmosis-erpnext,gangadharkadam/tailorerp,suyashphadtare/gd-erp,mbauskar/sapphire-erpnext,gangadharkadam/sher,gangadhar-kadam/laganerp,indictranstech/fbd_erpnext,Tejal011089/huntercamp_erpnext,Aptitudetech/ERPNext,tmimori/erpnext,Drooids/erpnext,sagar30051991/ozsmart-erp,gmarke/erpnext,indictranstech/internal-erpnext,shft117/SteckerApp,ShashaQin/erpnext,susuchina/ERPNEXT,mbauskar/phrerp,mbauskar/alec_frappe5_erpnext,mbauskar/helpdesk-erpnext,suyashphadtare/sajil-final-erp,indictranstech/internal-erpnext,MartinEnder/erpnext-de,Tejal011089/fbd_erpnext,gangadharkadam/sterp,fuhongliang/erpnext,suyashphadtare/sajil-erp,mbauskar/Das_Erpnext,BhupeshGupta/erpnext,dieface/erpnext,rohitwaghchaure/GenieManager-erpnext,saurabh6790/test-erp,gangadhar-kadam/verve_test_erp,mbauskar/omnitech-demo-erpnext,gangadharkadam/v5_erp,gangadhar-kadam/smrterp,suyashphadtare/sajil-final-erp,suyashphadtare/vestasi-erp-1,gsnbng/erpnext,4commerce-technologies-AG/erpnext,mbauskar/omnitech-demo-erpnext,meisterkleister/erpnext,aruizramon/alec_erpnext,hatwar/Das_erpnext,ThiagoGarciaAlves/erpnext,mbauskar/omnitech-erpnext,indictranstech/reciphergroup-erpnext,gangadhar-kadam/latestchurcherp,gangadhar-kadam/verve_erp,SPKian/Testing2,indictranstech/Das_Erpnext,shft117/SteckerApp,indictranstech/osmosis-erpnext,rohitwaghchaure/erpnext-receipher,indictranstech/erpnext,gangadharkadam/letzerp,rohitwaghchaure/erpnext_smart,tmimori/erpnext,sagar30051991/ozsmart-erp,gangadharkadam/contributionerp,suyashphadtare/vestasi-erp-final,mbauskar/sapphire-erpnext,indictranstech/vestasi-erpnext,mbauskar/Das_Erpnext,gangadharkadam/vlinkerp,gangadhar-kadam/verve_erp,saurabh6790/test-erp,njmube/erpnext,Suninus/erpnext,suyashphadtare/vestasi-erp-1,Tejal011089/fbd_erpnext,mbauskar/sapphire-erpnext,mbauskar/phrerp,dieface/erpnext,mbauskar/omnitech-demo-erpnext,indictranstech/buyback-erp,suyashphadtare/vestasi-erp-jan-end,pawaranand/phrerp,pombredanne/erpnext,hatwar/buyback-erpnext,rohitwaghchaure/New_Theme_Erp,4commerce-technologies-AG/erpnext,gangadharkadam/saloon_erp_install,suyashphadtare/vestasi-update-erp,SPKian/Testing,gangadharkadam/v4_erp,indictranstech/biggift-erpnext,indictranstech/trufil-erpnext,saurabh6790/test-erp,suyashphadtare/vestasi-erp-jan-end,anandpdoshi/erpnext,rohitwaghchaure/erpnext-receipher,mbauskar/alec_frappe5_erpnext,rohitwaghchaure/New_Theme_Erp,mbauskar/omnitech-erpnext,gangadhar-kadam/verve_live_erp,geekroot/erpnext,gangadharkadam/v4_erp,gangadharkadam/letzerp,dieface/erpnext,netfirms/erpnext,gangadharkadam/verveerp,anandpdoshi/erpnext,SPKian/Testing2,suyashphadtare/vestasi-update-erp,Tejal011089/osmosis_erpnext,gangadharkadam/verveerp,meisterkleister/erpnext,mbauskar/alec_frappe5_erpnext,Tejal011089/paypal_erpnext,suyashphadtare/gd-erp,indictranstech/tele-erpnext,gangadhar-kadam/verve_erp,susuchina/ERPNEXT,BhupeshGupta/erpnext,saurabh6790/test-erp,hernad/erpnext,indictranstech/biggift-erpnext,gmarke/erpnext,indictranstech/biggift-erpnext,hatwar/focal-erpnext,suyashphadtare/vestasi-erp-jan-end,rohitwaghchaure/erpnext-receipher,gangadhar-kadam/verve-erp,indictranstech/vestasi-erpnext,SPKian/Testing2,dieface/erpnext,indictranstech/trufil-erpnext,indictranstech/tele-erpnext,gangadharkadam/office_erp,mbauskar/phrerp,Drooids/erpnext,Tejal011089/huntercamp_erpnext,hanselke/erpnext-1,treejames/erpnext,indictranstech/vestasi-erpnext,indictranstech/erpnext,treejames/erpnext,gmarke/erpnext,aruizramon/alec_erpnext,sheafferusa/erpnext,gsnbng/erpnext,aruizramon/alec_erpnext,mahabuber/erpnext,mbauskar/helpdesk-erpnext,gangadharkadam/v5_erp,indictranstech/biggift-erpnext,hatwar/Das_erpnext,gangadharkadam/v6_erp,gangadharkadam/v6_erp,mbauskar/omnitech-erpnext,Tejal011089/paypal_erpnext,gangadhar-kadam/verve_test_erp,indictranstech/Das_Erpnext,njmube/erpnext,treejames/erpnext,ThiagoGarciaAlves/erpnext,indictranstech/fbd_erpnext,indictranstech/reciphergroup-erpnext,rohitwaghchaure/GenieManager-erpnext,gangadharkadam/v6_erp,gangadhar-kadam/helpdesk-erpnext,gangadhar-kadam/verve-erp,Suninus/erpnext,Tejal011089/trufil-erpnext,gangadhar-kadam/verve_live_erp,mbauskar/phrerp,gangadhar-kadam/laganerp,gangadharkadam/smrterp,gangadhar-kadam/latestchurcherp,gangadhar-kadam/smrterp,hernad/erpnext,Tejal011089/osmosis_erpnext,rohitwaghchaure/digitales_erpnext,ThiagoGarciaAlves/erpnext,Tejal011089/trufil-erpnext,gangadharkadam/vlinkerp,gangadhar-kadam/verve_test_erp,suyashphadtare/vestasi-erp-final,indictranstech/vestasi-erpnext,fuhongliang/erpnext,mbauskar/omnitech-demo-erpnext,sheafferusa/erpnext,gangadharkadam/office_erp,meisterkleister/erpnext,gangadhar-kadam/verve_live_erp,rohitwaghchaure/digitales_erpnext,shitolepriya/test-erp,gangadharkadam/tailorerp,indictranstech/buyback-erp,gangadharkadam/v4_erp,Tejal011089/osmosis_erpnext,indictranstech/tele-erpnext,4commerce-technologies-AG/erpnext,gangadharkadam/contributionerp,hanselke/erpnext-1,SPKian/Testing,rohitwaghchaure/GenieManager-erpnext,Tejal011089/fbd_erpnext,hernad/erpnext,gangadharkadam/johnerp,geekroot/erpnext,shitolepriya/test-erp,indictranstech/fbd_erpnext,hatwar/buyback-erpnext,suyashphadtare/sajil-erp,geekroot/erpnext,mbauskar/Das_Erpnext,indictranstech/tele-erpnext,hanselke/erpnext-1,anandpdoshi/erpnext,MartinEnder/erpnext-de,gangadharkadam/vlinkerp,suyashphadtare/vestasi-update-erp,gangadhar-kadam/latestchurcherp,indictranstech/reciphergroup-erpnext,gangadharkadam/v6_erp,gangadharkadam/v5_erp,indictranstech/buyback-erp
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.utils.nestedset import get_root_of def execute(): frappe.reload_doc("accounts", "doctype", "pricing_rule") frappe.db.auto_commit_on_many_writes = True default_item_group = get_root_of("Item Group") for d in frappe.db.sql("""select * from `tabCustomer Discount` where ifnull(parent, '') != ''""", as_dict=1): if not d.discount: continue frappe.get_doc({ "doctype": "Pricing Rule", "apply_on": "Item Group", "item_group": d.item_group or default_item_group, "applicable_for": "Customer", "customer": d.parent, "price_or_discount": "Discount Percentage", "discount_percentage": d.discount }).insert() frappe.db.auto_commit_on_many_writes = False frappe.delete_doc("DocType", "Customer Discount") Fix in pricing rule patch
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.utils.nestedset import get_root_of def execute(): frappe.reload_doc("accounts", "doctype", "pricing_rule") frappe.db.auto_commit_on_many_writes = True default_item_group = get_root_of("Item Group") for d in frappe.db.sql("""select * from `tabCustomer Discount` where ifnull(parent, '') != ''""", as_dict=1): if not d.discount: continue frappe.get_doc({ "doctype": "Pricing Rule", "apply_on": "Item Group", "item_group": d.item_group or default_item_group, "applicable_for": "Customer", "customer": d.parent, "price_or_discount": "Discount Percentage", "discount_percentage": d.discount, "selling": 1 }).insert() frappe.db.auto_commit_on_many_writes = False frappe.delete_doc("DocType", "Customer Discount")
<commit_before># Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.utils.nestedset import get_root_of def execute(): frappe.reload_doc("accounts", "doctype", "pricing_rule") frappe.db.auto_commit_on_many_writes = True default_item_group = get_root_of("Item Group") for d in frappe.db.sql("""select * from `tabCustomer Discount` where ifnull(parent, '') != ''""", as_dict=1): if not d.discount: continue frappe.get_doc({ "doctype": "Pricing Rule", "apply_on": "Item Group", "item_group": d.item_group or default_item_group, "applicable_for": "Customer", "customer": d.parent, "price_or_discount": "Discount Percentage", "discount_percentage": d.discount }).insert() frappe.db.auto_commit_on_many_writes = False frappe.delete_doc("DocType", "Customer Discount") <commit_msg>Fix in pricing rule patch<commit_after>
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.utils.nestedset import get_root_of def execute(): frappe.reload_doc("accounts", "doctype", "pricing_rule") frappe.db.auto_commit_on_many_writes = True default_item_group = get_root_of("Item Group") for d in frappe.db.sql("""select * from `tabCustomer Discount` where ifnull(parent, '') != ''""", as_dict=1): if not d.discount: continue frappe.get_doc({ "doctype": "Pricing Rule", "apply_on": "Item Group", "item_group": d.item_group or default_item_group, "applicable_for": "Customer", "customer": d.parent, "price_or_discount": "Discount Percentage", "discount_percentage": d.discount, "selling": 1 }).insert() frappe.db.auto_commit_on_many_writes = False frappe.delete_doc("DocType", "Customer Discount")
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.utils.nestedset import get_root_of def execute(): frappe.reload_doc("accounts", "doctype", "pricing_rule") frappe.db.auto_commit_on_many_writes = True default_item_group = get_root_of("Item Group") for d in frappe.db.sql("""select * from `tabCustomer Discount` where ifnull(parent, '') != ''""", as_dict=1): if not d.discount: continue frappe.get_doc({ "doctype": "Pricing Rule", "apply_on": "Item Group", "item_group": d.item_group or default_item_group, "applicable_for": "Customer", "customer": d.parent, "price_or_discount": "Discount Percentage", "discount_percentage": d.discount }).insert() frappe.db.auto_commit_on_many_writes = False frappe.delete_doc("DocType", "Customer Discount") Fix in pricing rule patch# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.utils.nestedset import get_root_of def execute(): frappe.reload_doc("accounts", "doctype", "pricing_rule") frappe.db.auto_commit_on_many_writes = True default_item_group = get_root_of("Item Group") for d in frappe.db.sql("""select * from `tabCustomer Discount` where ifnull(parent, '') != ''""", as_dict=1): if not d.discount: continue frappe.get_doc({ "doctype": "Pricing Rule", "apply_on": "Item Group", "item_group": d.item_group or default_item_group, "applicable_for": "Customer", "customer": d.parent, "price_or_discount": "Discount Percentage", "discount_percentage": d.discount, "selling": 1 }).insert() frappe.db.auto_commit_on_many_writes = False frappe.delete_doc("DocType", "Customer Discount")
<commit_before># Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.utils.nestedset import get_root_of def execute(): frappe.reload_doc("accounts", "doctype", "pricing_rule") frappe.db.auto_commit_on_many_writes = True default_item_group = get_root_of("Item Group") for d in frappe.db.sql("""select * from `tabCustomer Discount` where ifnull(parent, '') != ''""", as_dict=1): if not d.discount: continue frappe.get_doc({ "doctype": "Pricing Rule", "apply_on": "Item Group", "item_group": d.item_group or default_item_group, "applicable_for": "Customer", "customer": d.parent, "price_or_discount": "Discount Percentage", "discount_percentage": d.discount }).insert() frappe.db.auto_commit_on_many_writes = False frappe.delete_doc("DocType", "Customer Discount") <commit_msg>Fix in pricing rule patch<commit_after># Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.utils.nestedset import get_root_of def execute(): frappe.reload_doc("accounts", "doctype", "pricing_rule") frappe.db.auto_commit_on_many_writes = True default_item_group = get_root_of("Item Group") for d in frappe.db.sql("""select * from `tabCustomer Discount` where ifnull(parent, '') != ''""", as_dict=1): if not d.discount: continue frappe.get_doc({ "doctype": "Pricing Rule", "apply_on": "Item Group", "item_group": d.item_group or default_item_group, "applicable_for": "Customer", "customer": d.parent, "price_or_discount": "Discount Percentage", "discount_percentage": d.discount, "selling": 1 }).insert() frappe.db.auto_commit_on_many_writes = False frappe.delete_doc("DocType", "Customer Discount")
701d312815fe6f193e1e555abe9fc65f9cee0567
core/management/commands/send_tweets.py
core/management/commands/send_tweets.py
import twitter from django.core.management.base import BaseCommand from django.conf import settings from core.models import Tweet class Command(BaseCommand): help = "Send out tweets." def handle(self, *args, **options): for tweet in Tweet.objects.filter(was_sent=False, failed_trials__lte=5): if tweet.user: user_tokens = tweet.user.social_auth.all()[0].tokens access_token = user_tokens['oauth_token'] access_token_secret = user_tokens['oauth_token_secret'] elif tweet.access: access_token = tweet.access.access_token access_token_secret = tweet.access.access_token_secret api = twitter.Api(consumer_key=settings.SOCIAL_AUTH_TWITTER_KEY, consumer_secret=settings.SOCIAL_AUTH_TWITTER_SECRET, access_token_key=access_token, access_token_secret=access_token_secret,) try: if tweet.media_path: status = api.PostUpdate(tweet.text, media=tweet.media_path) else: status = api.PostUpdate(tweet.text) except twitter.TwitterError, e: print "Something went wrong with #{}: ".format(tweet.pk), e tweet.failed_trials += 1 tweet.save() continue tweet.tweet_id = status.id tweet.was_sent = True tweet.save()
import twitter from django.core.management.base import BaseCommand from django.conf import settings from core.models import Tweet class Command(BaseCommand): help = "Send out tweets." def handle(self, *args, **options): for tweet in Tweet.objects.filter(was_sent=False, failed_trials__lte=5): if tweet.user: user_tokens = tweet.user.social_auth.all()[0].tokens consumer_key = settings.SOCIAL_AUTH_TWITTER_KEY consumer_secret = settings.SOCIAL_AUTH_TWITTER_SECRET access_token = user_tokens['oauth_token'] access_token_secret = user_tokens['oauth_token_secret'] elif tweet.access: consumer_key = settings.ENJAZACCOUNTS_TWITTER_KEY consumer_secret = settings.ENJAZACCOUNTS_TWITTER_SECRET access_token = tweet.access.access_token access_token_secret = tweet.access.access_token_secret api = twitter.Api(consumer_key=consumer_key, consumer_secret=consumer_secret, access_token_key=access_token, access_token_secret=access_token_secret,) try: if tweet.media_path: status = api.PostUpdate(tweet.text, media=tweet.media_path) else: status = api.PostUpdate(tweet.text) except twitter.TwitterError, e: print "Something went wrong with #{}: ".format(tweet.pk), e tweet.failed_trials += 1 tweet.save() continue tweet.tweet_id = status.id tweet.was_sent = True tweet.save()
Use ENJAZACESSS when is access is provided
Use ENJAZACESSS when is access is provided
Python
agpl-3.0
enjaz/enjaz,enjaz/enjaz,osamak/student-portal,osamak/student-portal,enjaz/enjaz,enjaz/enjaz,enjaz/enjaz,osamak/student-portal,osamak/student-portal,osamak/student-portal
import twitter from django.core.management.base import BaseCommand from django.conf import settings from core.models import Tweet class Command(BaseCommand): help = "Send out tweets." def handle(self, *args, **options): for tweet in Tweet.objects.filter(was_sent=False, failed_trials__lte=5): if tweet.user: user_tokens = tweet.user.social_auth.all()[0].tokens access_token = user_tokens['oauth_token'] access_token_secret = user_tokens['oauth_token_secret'] elif tweet.access: access_token = tweet.access.access_token access_token_secret = tweet.access.access_token_secret api = twitter.Api(consumer_key=settings.SOCIAL_AUTH_TWITTER_KEY, consumer_secret=settings.SOCIAL_AUTH_TWITTER_SECRET, access_token_key=access_token, access_token_secret=access_token_secret,) try: if tweet.media_path: status = api.PostUpdate(tweet.text, media=tweet.media_path) else: status = api.PostUpdate(tweet.text) except twitter.TwitterError, e: print "Something went wrong with #{}: ".format(tweet.pk), e tweet.failed_trials += 1 tweet.save() continue tweet.tweet_id = status.id tweet.was_sent = True tweet.save() Use ENJAZACESSS when is access is provided
import twitter from django.core.management.base import BaseCommand from django.conf import settings from core.models import Tweet class Command(BaseCommand): help = "Send out tweets." def handle(self, *args, **options): for tweet in Tweet.objects.filter(was_sent=False, failed_trials__lte=5): if tweet.user: user_tokens = tweet.user.social_auth.all()[0].tokens consumer_key = settings.SOCIAL_AUTH_TWITTER_KEY consumer_secret = settings.SOCIAL_AUTH_TWITTER_SECRET access_token = user_tokens['oauth_token'] access_token_secret = user_tokens['oauth_token_secret'] elif tweet.access: consumer_key = settings.ENJAZACCOUNTS_TWITTER_KEY consumer_secret = settings.ENJAZACCOUNTS_TWITTER_SECRET access_token = tweet.access.access_token access_token_secret = tweet.access.access_token_secret api = twitter.Api(consumer_key=consumer_key, consumer_secret=consumer_secret, access_token_key=access_token, access_token_secret=access_token_secret,) try: if tweet.media_path: status = api.PostUpdate(tweet.text, media=tweet.media_path) else: status = api.PostUpdate(tweet.text) except twitter.TwitterError, e: print "Something went wrong with #{}: ".format(tweet.pk), e tweet.failed_trials += 1 tweet.save() continue tweet.tweet_id = status.id tweet.was_sent = True tweet.save()
<commit_before>import twitter from django.core.management.base import BaseCommand from django.conf import settings from core.models import Tweet class Command(BaseCommand): help = "Send out tweets." def handle(self, *args, **options): for tweet in Tweet.objects.filter(was_sent=False, failed_trials__lte=5): if tweet.user: user_tokens = tweet.user.social_auth.all()[0].tokens access_token = user_tokens['oauth_token'] access_token_secret = user_tokens['oauth_token_secret'] elif tweet.access: access_token = tweet.access.access_token access_token_secret = tweet.access.access_token_secret api = twitter.Api(consumer_key=settings.SOCIAL_AUTH_TWITTER_KEY, consumer_secret=settings.SOCIAL_AUTH_TWITTER_SECRET, access_token_key=access_token, access_token_secret=access_token_secret,) try: if tweet.media_path: status = api.PostUpdate(tweet.text, media=tweet.media_path) else: status = api.PostUpdate(tweet.text) except twitter.TwitterError, e: print "Something went wrong with #{}: ".format(tweet.pk), e tweet.failed_trials += 1 tweet.save() continue tweet.tweet_id = status.id tweet.was_sent = True tweet.save() <commit_msg>Use ENJAZACESSS when is access is provided<commit_after>
import twitter from django.core.management.base import BaseCommand from django.conf import settings from core.models import Tweet class Command(BaseCommand): help = "Send out tweets." def handle(self, *args, **options): for tweet in Tweet.objects.filter(was_sent=False, failed_trials__lte=5): if tweet.user: user_tokens = tweet.user.social_auth.all()[0].tokens consumer_key = settings.SOCIAL_AUTH_TWITTER_KEY consumer_secret = settings.SOCIAL_AUTH_TWITTER_SECRET access_token = user_tokens['oauth_token'] access_token_secret = user_tokens['oauth_token_secret'] elif tweet.access: consumer_key = settings.ENJAZACCOUNTS_TWITTER_KEY consumer_secret = settings.ENJAZACCOUNTS_TWITTER_SECRET access_token = tweet.access.access_token access_token_secret = tweet.access.access_token_secret api = twitter.Api(consumer_key=consumer_key, consumer_secret=consumer_secret, access_token_key=access_token, access_token_secret=access_token_secret,) try: if tweet.media_path: status = api.PostUpdate(tweet.text, media=tweet.media_path) else: status = api.PostUpdate(tweet.text) except twitter.TwitterError, e: print "Something went wrong with #{}: ".format(tweet.pk), e tweet.failed_trials += 1 tweet.save() continue tweet.tweet_id = status.id tweet.was_sent = True tweet.save()
import twitter from django.core.management.base import BaseCommand from django.conf import settings from core.models import Tweet class Command(BaseCommand): help = "Send out tweets." def handle(self, *args, **options): for tweet in Tweet.objects.filter(was_sent=False, failed_trials__lte=5): if tweet.user: user_tokens = tweet.user.social_auth.all()[0].tokens access_token = user_tokens['oauth_token'] access_token_secret = user_tokens['oauth_token_secret'] elif tweet.access: access_token = tweet.access.access_token access_token_secret = tweet.access.access_token_secret api = twitter.Api(consumer_key=settings.SOCIAL_AUTH_TWITTER_KEY, consumer_secret=settings.SOCIAL_AUTH_TWITTER_SECRET, access_token_key=access_token, access_token_secret=access_token_secret,) try: if tweet.media_path: status = api.PostUpdate(tweet.text, media=tweet.media_path) else: status = api.PostUpdate(tweet.text) except twitter.TwitterError, e: print "Something went wrong with #{}: ".format(tweet.pk), e tweet.failed_trials += 1 tweet.save() continue tweet.tweet_id = status.id tweet.was_sent = True tweet.save() Use ENJAZACESSS when is access is providedimport twitter from django.core.management.base import BaseCommand from django.conf import settings from core.models import Tweet class Command(BaseCommand): help = "Send out tweets." def handle(self, *args, **options): for tweet in Tweet.objects.filter(was_sent=False, failed_trials__lte=5): if tweet.user: user_tokens = tweet.user.social_auth.all()[0].tokens consumer_key = settings.SOCIAL_AUTH_TWITTER_KEY consumer_secret = settings.SOCIAL_AUTH_TWITTER_SECRET access_token = user_tokens['oauth_token'] access_token_secret = user_tokens['oauth_token_secret'] elif tweet.access: consumer_key = settings.ENJAZACCOUNTS_TWITTER_KEY consumer_secret = settings.ENJAZACCOUNTS_TWITTER_SECRET access_token = tweet.access.access_token access_token_secret = tweet.access.access_token_secret api = twitter.Api(consumer_key=consumer_key, consumer_secret=consumer_secret, access_token_key=access_token, access_token_secret=access_token_secret,) try: if tweet.media_path: status = api.PostUpdate(tweet.text, media=tweet.media_path) else: status = api.PostUpdate(tweet.text) except twitter.TwitterError, e: print "Something went wrong with #{}: ".format(tweet.pk), e tweet.failed_trials += 1 tweet.save() continue tweet.tweet_id = status.id tweet.was_sent = True tweet.save()
<commit_before>import twitter from django.core.management.base import BaseCommand from django.conf import settings from core.models import Tweet class Command(BaseCommand): help = "Send out tweets." def handle(self, *args, **options): for tweet in Tweet.objects.filter(was_sent=False, failed_trials__lte=5): if tweet.user: user_tokens = tweet.user.social_auth.all()[0].tokens access_token = user_tokens['oauth_token'] access_token_secret = user_tokens['oauth_token_secret'] elif tweet.access: access_token = tweet.access.access_token access_token_secret = tweet.access.access_token_secret api = twitter.Api(consumer_key=settings.SOCIAL_AUTH_TWITTER_KEY, consumer_secret=settings.SOCIAL_AUTH_TWITTER_SECRET, access_token_key=access_token, access_token_secret=access_token_secret,) try: if tweet.media_path: status = api.PostUpdate(tweet.text, media=tweet.media_path) else: status = api.PostUpdate(tweet.text) except twitter.TwitterError, e: print "Something went wrong with #{}: ".format(tweet.pk), e tweet.failed_trials += 1 tweet.save() continue tweet.tweet_id = status.id tweet.was_sent = True tweet.save() <commit_msg>Use ENJAZACESSS when is access is provided<commit_after>import twitter from django.core.management.base import BaseCommand from django.conf import settings from core.models import Tweet class Command(BaseCommand): help = "Send out tweets." def handle(self, *args, **options): for tweet in Tweet.objects.filter(was_sent=False, failed_trials__lte=5): if tweet.user: user_tokens = tweet.user.social_auth.all()[0].tokens consumer_key = settings.SOCIAL_AUTH_TWITTER_KEY consumer_secret = settings.SOCIAL_AUTH_TWITTER_SECRET access_token = user_tokens['oauth_token'] access_token_secret = user_tokens['oauth_token_secret'] elif tweet.access: consumer_key = settings.ENJAZACCOUNTS_TWITTER_KEY consumer_secret = settings.ENJAZACCOUNTS_TWITTER_SECRET access_token = tweet.access.access_token access_token_secret = tweet.access.access_token_secret api = twitter.Api(consumer_key=consumer_key, consumer_secret=consumer_secret, access_token_key=access_token, access_token_secret=access_token_secret,) try: if tweet.media_path: status = api.PostUpdate(tweet.text, media=tweet.media_path) else: status = api.PostUpdate(tweet.text) except twitter.TwitterError, e: print "Something went wrong with #{}: ".format(tweet.pk), e tweet.failed_trials += 1 tweet.save() continue tweet.tweet_id = status.id tweet.was_sent = True tweet.save()
7d271c3f221d5fade656cd94d2a56fab0fc3b928
dsub/_dsub_version.py
dsub/_dsub_version.py
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Single source of truth for dsub's version. This must remain small and dependency-free so that any dsub module may import it without creating circular dependencies. Note that this module is parsed as a text file by setup.py and changes to the format of this file could break setup.py. The version should follow formatting requirements specified in PEP-440. - https://www.python.org/dev/peps/pep-0440 A typical release sequence will be versioned as: 0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ... """ DSUB_VERSION = '0.4.4'
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Single source of truth for dsub's version. This must remain small and dependency-free so that any dsub module may import it without creating circular dependencies. Note that this module is parsed as a text file by setup.py and changes to the format of this file could break setup.py. The version should follow formatting requirements specified in PEP-440. - https://www.python.org/dev/peps/pep-0440 A typical release sequence will be versioned as: 0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ... """ DSUB_VERSION = '0.4.5.dev0'
Update dsub version to 0.4.5.dev0
Update dsub version to 0.4.5.dev0 PiperOrigin-RevId: 358198209
Python
apache-2.0
DataBiosphere/dsub,DataBiosphere/dsub
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Single source of truth for dsub's version. This must remain small and dependency-free so that any dsub module may import it without creating circular dependencies. Note that this module is parsed as a text file by setup.py and changes to the format of this file could break setup.py. The version should follow formatting requirements specified in PEP-440. - https://www.python.org/dev/peps/pep-0440 A typical release sequence will be versioned as: 0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ... """ DSUB_VERSION = '0.4.4' Update dsub version to 0.4.5.dev0 PiperOrigin-RevId: 358198209
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Single source of truth for dsub's version. This must remain small and dependency-free so that any dsub module may import it without creating circular dependencies. Note that this module is parsed as a text file by setup.py and changes to the format of this file could break setup.py. The version should follow formatting requirements specified in PEP-440. - https://www.python.org/dev/peps/pep-0440 A typical release sequence will be versioned as: 0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ... """ DSUB_VERSION = '0.4.5.dev0'
<commit_before># Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Single source of truth for dsub's version. This must remain small and dependency-free so that any dsub module may import it without creating circular dependencies. Note that this module is parsed as a text file by setup.py and changes to the format of this file could break setup.py. The version should follow formatting requirements specified in PEP-440. - https://www.python.org/dev/peps/pep-0440 A typical release sequence will be versioned as: 0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ... """ DSUB_VERSION = '0.4.4' <commit_msg>Update dsub version to 0.4.5.dev0 PiperOrigin-RevId: 358198209<commit_after>
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Single source of truth for dsub's version. This must remain small and dependency-free so that any dsub module may import it without creating circular dependencies. Note that this module is parsed as a text file by setup.py and changes to the format of this file could break setup.py. The version should follow formatting requirements specified in PEP-440. - https://www.python.org/dev/peps/pep-0440 A typical release sequence will be versioned as: 0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ... """ DSUB_VERSION = '0.4.5.dev0'
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Single source of truth for dsub's version. This must remain small and dependency-free so that any dsub module may import it without creating circular dependencies. Note that this module is parsed as a text file by setup.py and changes to the format of this file could break setup.py. The version should follow formatting requirements specified in PEP-440. - https://www.python.org/dev/peps/pep-0440 A typical release sequence will be versioned as: 0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ... """ DSUB_VERSION = '0.4.4' Update dsub version to 0.4.5.dev0 PiperOrigin-RevId: 358198209# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Single source of truth for dsub's version. This must remain small and dependency-free so that any dsub module may import it without creating circular dependencies. Note that this module is parsed as a text file by setup.py and changes to the format of this file could break setup.py. The version should follow formatting requirements specified in PEP-440. - https://www.python.org/dev/peps/pep-0440 A typical release sequence will be versioned as: 0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ... """ DSUB_VERSION = '0.4.5.dev0'
<commit_before># Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Single source of truth for dsub's version. This must remain small and dependency-free so that any dsub module may import it without creating circular dependencies. Note that this module is parsed as a text file by setup.py and changes to the format of this file could break setup.py. The version should follow formatting requirements specified in PEP-440. - https://www.python.org/dev/peps/pep-0440 A typical release sequence will be versioned as: 0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ... """ DSUB_VERSION = '0.4.4' <commit_msg>Update dsub version to 0.4.5.dev0 PiperOrigin-RevId: 358198209<commit_after># Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Single source of truth for dsub's version. This must remain small and dependency-free so that any dsub module may import it without creating circular dependencies. Note that this module is parsed as a text file by setup.py and changes to the format of this file could break setup.py. The version should follow formatting requirements specified in PEP-440. - https://www.python.org/dev/peps/pep-0440 A typical release sequence will be versioned as: 0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ... """ DSUB_VERSION = '0.4.5.dev0'
d324b27e41aee52b044e5647a4a13aecc9130c3e
tests/conftest.py
tests/conftest.py
import pytest from utils import * from pgcli.pgexecute import PGExecute @pytest.yield_fixture(scope="function") def connection(): create_db('_test_db') connection = db_connection('_test_db') yield connection drop_tables(connection) connection.close() @pytest.fixture def cursor(connection): with connection.cursor() as cur: return cur @pytest.fixture def executor(connection): return PGExecute(database='_test_db', user=POSTGRES_USER, host=POSTGRES_HOST, password=None, port=None)
import pytest from utils import (POSTGRES_HOST, POSTGRES_USER, create_db, db_connection, drop_tables) import pgcli.pgexecute @pytest.yield_fixture(scope="function") def connection(): create_db('_test_db') connection = db_connection('_test_db') yield connection drop_tables(connection) connection.close() @pytest.fixture def cursor(connection): with connection.cursor() as cur: return cur @pytest.fixture def executor(connection): return pgcli.pgexecute.PGExecute(database='_test_db', user=POSTGRES_USER, host=POSTGRES_HOST, password=None, port=None)
Replace splat import in tests.
Replace splat import in tests.
Python
bsd-3-clause
koljonen/pgcli,darikg/pgcli,n-someya/pgcli,thedrow/pgcli,dbcli/vcli,joewalnes/pgcli,zhiyuanshi/pgcli,thedrow/pgcli,darikg/pgcli,janusnic/pgcli,bitemyapp/pgcli,dbcli/pgcli,MattOates/pgcli,suzukaze/pgcli,bitmonk/pgcli,bitmonk/pgcli,johshoff/pgcli,nosun/pgcli,d33tah/pgcli,johshoff/pgcli,koljonen/pgcli,lk1ngaa7/pgcli,zhiyuanshi/pgcli,w4ngyi/pgcli,TamasNo1/pgcli,suzukaze/pgcli,lk1ngaa7/pgcli,j-bennet/pgcli,TamasNo1/pgcli,yx91490/pgcli,nosun/pgcli,MattOates/pgcli,yx91490/pgcli,joewalnes/pgcli,dbcli/vcli,janusnic/pgcli,w4ngyi/pgcli,j-bennet/pgcli,dbcli/pgcli,n-someya/pgcli,d33tah/pgcli,bitemyapp/pgcli
import pytest from utils import * from pgcli.pgexecute import PGExecute @pytest.yield_fixture(scope="function") def connection(): create_db('_test_db') connection = db_connection('_test_db') yield connection drop_tables(connection) connection.close() @pytest.fixture def cursor(connection): with connection.cursor() as cur: return cur @pytest.fixture def executor(connection): return PGExecute(database='_test_db', user=POSTGRES_USER, host=POSTGRES_HOST, password=None, port=None) Replace splat import in tests.
import pytest from utils import (POSTGRES_HOST, POSTGRES_USER, create_db, db_connection, drop_tables) import pgcli.pgexecute @pytest.yield_fixture(scope="function") def connection(): create_db('_test_db') connection = db_connection('_test_db') yield connection drop_tables(connection) connection.close() @pytest.fixture def cursor(connection): with connection.cursor() as cur: return cur @pytest.fixture def executor(connection): return pgcli.pgexecute.PGExecute(database='_test_db', user=POSTGRES_USER, host=POSTGRES_HOST, password=None, port=None)
<commit_before>import pytest from utils import * from pgcli.pgexecute import PGExecute @pytest.yield_fixture(scope="function") def connection(): create_db('_test_db') connection = db_connection('_test_db') yield connection drop_tables(connection) connection.close() @pytest.fixture def cursor(connection): with connection.cursor() as cur: return cur @pytest.fixture def executor(connection): return PGExecute(database='_test_db', user=POSTGRES_USER, host=POSTGRES_HOST, password=None, port=None) <commit_msg>Replace splat import in tests.<commit_after>
import pytest from utils import (POSTGRES_HOST, POSTGRES_USER, create_db, db_connection, drop_tables) import pgcli.pgexecute @pytest.yield_fixture(scope="function") def connection(): create_db('_test_db') connection = db_connection('_test_db') yield connection drop_tables(connection) connection.close() @pytest.fixture def cursor(connection): with connection.cursor() as cur: return cur @pytest.fixture def executor(connection): return pgcli.pgexecute.PGExecute(database='_test_db', user=POSTGRES_USER, host=POSTGRES_HOST, password=None, port=None)
import pytest from utils import * from pgcli.pgexecute import PGExecute @pytest.yield_fixture(scope="function") def connection(): create_db('_test_db') connection = db_connection('_test_db') yield connection drop_tables(connection) connection.close() @pytest.fixture def cursor(connection): with connection.cursor() as cur: return cur @pytest.fixture def executor(connection): return PGExecute(database='_test_db', user=POSTGRES_USER, host=POSTGRES_HOST, password=None, port=None) Replace splat import in tests.import pytest from utils import (POSTGRES_HOST, POSTGRES_USER, create_db, db_connection, drop_tables) import pgcli.pgexecute @pytest.yield_fixture(scope="function") def connection(): create_db('_test_db') connection = db_connection('_test_db') yield connection drop_tables(connection) connection.close() @pytest.fixture def cursor(connection): with connection.cursor() as cur: return cur @pytest.fixture def executor(connection): return pgcli.pgexecute.PGExecute(database='_test_db', user=POSTGRES_USER, host=POSTGRES_HOST, password=None, port=None)
<commit_before>import pytest from utils import * from pgcli.pgexecute import PGExecute @pytest.yield_fixture(scope="function") def connection(): create_db('_test_db') connection = db_connection('_test_db') yield connection drop_tables(connection) connection.close() @pytest.fixture def cursor(connection): with connection.cursor() as cur: return cur @pytest.fixture def executor(connection): return PGExecute(database='_test_db', user=POSTGRES_USER, host=POSTGRES_HOST, password=None, port=None) <commit_msg>Replace splat import in tests.<commit_after>import pytest from utils import (POSTGRES_HOST, POSTGRES_USER, create_db, db_connection, drop_tables) import pgcli.pgexecute @pytest.yield_fixture(scope="function") def connection(): create_db('_test_db') connection = db_connection('_test_db') yield connection drop_tables(connection) connection.close() @pytest.fixture def cursor(connection): with connection.cursor() as cur: return cur @pytest.fixture def executor(connection): return pgcli.pgexecute.PGExecute(database='_test_db', user=POSTGRES_USER, host=POSTGRES_HOST, password=None, port=None)
e5beaabc66cbb87f63e2648b277bada72ddec7dc
tests/conftest.py
tests/conftest.py
import arrayfire import pytest backends = arrayfire.library.get_available_backends() # do not use opencl backend, it's kinda broken #backends = [x for x in backends if x != 'opencl'] # This will set the different backends before each test is executed @pytest.fixture(scope="function", params=backends, autouse=True) def set_backend(request): arrayfire.library.set_backend(request.param)
import arrayfire import pytest backends = arrayfire.library.get_available_backends() # do not use opencl backend, it's kinda broken #backends = [x for x in backends if x != 'opencl'] # This will set the different backends before each test is executed @pytest.fixture(scope="function", params=backends, autouse=True) def set_backend(request): arrayfire.library.set_backend(request.param, unsafe=True)
Allow unsafe change of backend for testing
Allow unsafe change of backend for testing
Python
bsd-2-clause
FilipeMaia/afnumpy,daurer/afnumpy
import arrayfire import pytest backends = arrayfire.library.get_available_backends() # do not use opencl backend, it's kinda broken #backends = [x for x in backends if x != 'opencl'] # This will set the different backends before each test is executed @pytest.fixture(scope="function", params=backends, autouse=True) def set_backend(request): arrayfire.library.set_backend(request.param) Allow unsafe change of backend for testing
import arrayfire import pytest backends = arrayfire.library.get_available_backends() # do not use opencl backend, it's kinda broken #backends = [x for x in backends if x != 'opencl'] # This will set the different backends before each test is executed @pytest.fixture(scope="function", params=backends, autouse=True) def set_backend(request): arrayfire.library.set_backend(request.param, unsafe=True)
<commit_before>import arrayfire import pytest backends = arrayfire.library.get_available_backends() # do not use opencl backend, it's kinda broken #backends = [x for x in backends if x != 'opencl'] # This will set the different backends before each test is executed @pytest.fixture(scope="function", params=backends, autouse=True) def set_backend(request): arrayfire.library.set_backend(request.param) <commit_msg>Allow unsafe change of backend for testing<commit_after>
import arrayfire import pytest backends = arrayfire.library.get_available_backends() # do not use opencl backend, it's kinda broken #backends = [x for x in backends if x != 'opencl'] # This will set the different backends before each test is executed @pytest.fixture(scope="function", params=backends, autouse=True) def set_backend(request): arrayfire.library.set_backend(request.param, unsafe=True)
import arrayfire import pytest backends = arrayfire.library.get_available_backends() # do not use opencl backend, it's kinda broken #backends = [x for x in backends if x != 'opencl'] # This will set the different backends before each test is executed @pytest.fixture(scope="function", params=backends, autouse=True) def set_backend(request): arrayfire.library.set_backend(request.param) Allow unsafe change of backend for testingimport arrayfire import pytest backends = arrayfire.library.get_available_backends() # do not use opencl backend, it's kinda broken #backends = [x for x in backends if x != 'opencl'] # This will set the different backends before each test is executed @pytest.fixture(scope="function", params=backends, autouse=True) def set_backend(request): arrayfire.library.set_backend(request.param, unsafe=True)
<commit_before>import arrayfire import pytest backends = arrayfire.library.get_available_backends() # do not use opencl backend, it's kinda broken #backends = [x for x in backends if x != 'opencl'] # This will set the different backends before each test is executed @pytest.fixture(scope="function", params=backends, autouse=True) def set_backend(request): arrayfire.library.set_backend(request.param) <commit_msg>Allow unsafe change of backend for testing<commit_after>import arrayfire import pytest backends = arrayfire.library.get_available_backends() # do not use opencl backend, it's kinda broken #backends = [x for x in backends if x != 'opencl'] # This will set the different backends before each test is executed @pytest.fixture(scope="function", params=backends, autouse=True) def set_backend(request): arrayfire.library.set_backend(request.param, unsafe=True)
c5a617db987fda0302cf5963bbc41e8d0887347d
tests/conftest.py
tests/conftest.py
import pytest @pytest.fixture def observe(monkeypatch): def patch(module, func): original_func = getattr(module, func) def wrapper(*args, **kwargs): result = original_func(*args, **kwargs) self.calls[self.last_call] = (args, kwargs, result) self.last_call += 1 return result self = wrapper self.calls = {} self.last_call = 0 monkeypatch.setattr(module, func, wrapper) return wrapper return patch
import pytest @pytest.fixture def observe(monkeypatch): """ Wrap a function so its call history can be inspected. Example: # foo.py def func(bar): return 2 * bar # test.py import pytest import foo def test_func(observe): observer = observe(foo, "func") assert foo.func(3) == 6 assert foo.func(-5) == -10 assert len(observer.calls) == 2 """ class ObserverFactory: def __init__(self, module, func): self.original_func = getattr(module, func) self.calls = [] monkeypatch.setattr(module, func, self) def __call__(self, *args, **kwargs): result = self.original_func(*args, **kwargs) self.calls.append((args, kwargs, result)) return result return ObserverFactory
Clean up test helper, add example
Clean up test helper, add example
Python
mit
numberoverzero/pyservice
import pytest @pytest.fixture def observe(monkeypatch): def patch(module, func): original_func = getattr(module, func) def wrapper(*args, **kwargs): result = original_func(*args, **kwargs) self.calls[self.last_call] = (args, kwargs, result) self.last_call += 1 return result self = wrapper self.calls = {} self.last_call = 0 monkeypatch.setattr(module, func, wrapper) return wrapper return patch Clean up test helper, add example
import pytest @pytest.fixture def observe(monkeypatch): """ Wrap a function so its call history can be inspected. Example: # foo.py def func(bar): return 2 * bar # test.py import pytest import foo def test_func(observe): observer = observe(foo, "func") assert foo.func(3) == 6 assert foo.func(-5) == -10 assert len(observer.calls) == 2 """ class ObserverFactory: def __init__(self, module, func): self.original_func = getattr(module, func) self.calls = [] monkeypatch.setattr(module, func, self) def __call__(self, *args, **kwargs): result = self.original_func(*args, **kwargs) self.calls.append((args, kwargs, result)) return result return ObserverFactory
<commit_before>import pytest @pytest.fixture def observe(monkeypatch): def patch(module, func): original_func = getattr(module, func) def wrapper(*args, **kwargs): result = original_func(*args, **kwargs) self.calls[self.last_call] = (args, kwargs, result) self.last_call += 1 return result self = wrapper self.calls = {} self.last_call = 0 monkeypatch.setattr(module, func, wrapper) return wrapper return patch <commit_msg>Clean up test helper, add example<commit_after>
import pytest @pytest.fixture def observe(monkeypatch): """ Wrap a function so its call history can be inspected. Example: # foo.py def func(bar): return 2 * bar # test.py import pytest import foo def test_func(observe): observer = observe(foo, "func") assert foo.func(3) == 6 assert foo.func(-5) == -10 assert len(observer.calls) == 2 """ class ObserverFactory: def __init__(self, module, func): self.original_func = getattr(module, func) self.calls = [] monkeypatch.setattr(module, func, self) def __call__(self, *args, **kwargs): result = self.original_func(*args, **kwargs) self.calls.append((args, kwargs, result)) return result return ObserverFactory
import pytest @pytest.fixture def observe(monkeypatch): def patch(module, func): original_func = getattr(module, func) def wrapper(*args, **kwargs): result = original_func(*args, **kwargs) self.calls[self.last_call] = (args, kwargs, result) self.last_call += 1 return result self = wrapper self.calls = {} self.last_call = 0 monkeypatch.setattr(module, func, wrapper) return wrapper return patch Clean up test helper, add exampleimport pytest @pytest.fixture def observe(monkeypatch): """ Wrap a function so its call history can be inspected. Example: # foo.py def func(bar): return 2 * bar # test.py import pytest import foo def test_func(observe): observer = observe(foo, "func") assert foo.func(3) == 6 assert foo.func(-5) == -10 assert len(observer.calls) == 2 """ class ObserverFactory: def __init__(self, module, func): self.original_func = getattr(module, func) self.calls = [] monkeypatch.setattr(module, func, self) def __call__(self, *args, **kwargs): result = self.original_func(*args, **kwargs) self.calls.append((args, kwargs, result)) return result return ObserverFactory
<commit_before>import pytest @pytest.fixture def observe(monkeypatch): def patch(module, func): original_func = getattr(module, func) def wrapper(*args, **kwargs): result = original_func(*args, **kwargs) self.calls[self.last_call] = (args, kwargs, result) self.last_call += 1 return result self = wrapper self.calls = {} self.last_call = 0 monkeypatch.setattr(module, func, wrapper) return wrapper return patch <commit_msg>Clean up test helper, add example<commit_after>import pytest @pytest.fixture def observe(monkeypatch): """ Wrap a function so its call history can be inspected. Example: # foo.py def func(bar): return 2 * bar # test.py import pytest import foo def test_func(observe): observer = observe(foo, "func") assert foo.func(3) == 6 assert foo.func(-5) == -10 assert len(observer.calls) == 2 """ class ObserverFactory: def __init__(self, module, func): self.original_func = getattr(module, func) self.calls = [] monkeypatch.setattr(module, func, self) def __call__(self, *args, **kwargs): result = self.original_func(*args, **kwargs) self.calls.append((args, kwargs, result)) return result return ObserverFactory
dec3ec25739e78c465fd5e31a161a674331edbed
serpent/cv.py
serpent/cv.py
import numpy as np import skimage.io import skimage.util import os def extract_region_from_image(image, region_bounding_box): return image[region_bounding_box[0]:region_bounding_box[2], region_bounding_box[1]:region_bounding_box[3]] def isolate_sprite(image_region_path, output_file_path): result_image = None for root, directories, files in os.walk(image_region_path): for file in files: if not file.endswith(".png"): continue image = skimage.io.imread(f"{root}/{file}") image = np.concatenate((image, np.full((image.shape[0], image.shape[1], 1), 255, dtype="uint8")), axis=2) if result_image is None: result_image = image else: height, width, rgba = image.shape for i in range(height): for ii in range(width): if not np.array_equal(image[i, ii, :2], result_image[i, ii, :2]): result_image[i, ii, 3] = 0 skimage.io.imsave(output_file_path, result_image) def scale_range(n, minimum, maximum): n += -(np.min(n)) n /= np.max(n) / (maximum - minimum) n += minimum return n
import numpy as np import skimage.io import skimage.util import os def extract_region_from_image(image, region_bounding_box): return image[region_bounding_box[0]:region_bounding_box[2], region_bounding_box[1]:region_bounding_box[3]] def isolate_sprite(image_region_path, output_file_path): result_image = None for root, directories, files in os.walk(image_region_path): for file in files: if not file.endswith(".png"): continue image = skimage.io.imread(f"{root}/{file}") image = np.concatenate((image, np.full((image.shape[0], image.shape[1], 1), 255, dtype="uint8")), axis=2) if result_image is None: result_image = image else: height, width, rgba = image.shape for i in range(height): for ii in range(width): if not np.array_equal(image[i, ii, :2], result_image[i, ii, :2]): result_image[i, ii, 3] = 0 skimage.io.imsave(output_file_path, result_image) def normalize(n, source_min, source_max, target_min=0, target_max=1): return ((n - source_min) * (target_max - target_min) / (source_max - source_min)) + target_min
Change scale range to normalization with source and target min max
Change scale range to normalization with source and target min max
Python
mit
SerpentAI/SerpentAI
import numpy as np import skimage.io import skimage.util import os def extract_region_from_image(image, region_bounding_box): return image[region_bounding_box[0]:region_bounding_box[2], region_bounding_box[1]:region_bounding_box[3]] def isolate_sprite(image_region_path, output_file_path): result_image = None for root, directories, files in os.walk(image_region_path): for file in files: if not file.endswith(".png"): continue image = skimage.io.imread(f"{root}/{file}") image = np.concatenate((image, np.full((image.shape[0], image.shape[1], 1), 255, dtype="uint8")), axis=2) if result_image is None: result_image = image else: height, width, rgba = image.shape for i in range(height): for ii in range(width): if not np.array_equal(image[i, ii, :2], result_image[i, ii, :2]): result_image[i, ii, 3] = 0 skimage.io.imsave(output_file_path, result_image) def scale_range(n, minimum, maximum): n += -(np.min(n)) n /= np.max(n) / (maximum - minimum) n += minimum return n Change scale range to normalization with source and target min max
import numpy as np import skimage.io import skimage.util import os def extract_region_from_image(image, region_bounding_box): return image[region_bounding_box[0]:region_bounding_box[2], region_bounding_box[1]:region_bounding_box[3]] def isolate_sprite(image_region_path, output_file_path): result_image = None for root, directories, files in os.walk(image_region_path): for file in files: if not file.endswith(".png"): continue image = skimage.io.imread(f"{root}/{file}") image = np.concatenate((image, np.full((image.shape[0], image.shape[1], 1), 255, dtype="uint8")), axis=2) if result_image is None: result_image = image else: height, width, rgba = image.shape for i in range(height): for ii in range(width): if not np.array_equal(image[i, ii, :2], result_image[i, ii, :2]): result_image[i, ii, 3] = 0 skimage.io.imsave(output_file_path, result_image) def normalize(n, source_min, source_max, target_min=0, target_max=1): return ((n - source_min) * (target_max - target_min) / (source_max - source_min)) + target_min
<commit_before>import numpy as np import skimage.io import skimage.util import os def extract_region_from_image(image, region_bounding_box): return image[region_bounding_box[0]:region_bounding_box[2], region_bounding_box[1]:region_bounding_box[3]] def isolate_sprite(image_region_path, output_file_path): result_image = None for root, directories, files in os.walk(image_region_path): for file in files: if not file.endswith(".png"): continue image = skimage.io.imread(f"{root}/{file}") image = np.concatenate((image, np.full((image.shape[0], image.shape[1], 1), 255, dtype="uint8")), axis=2) if result_image is None: result_image = image else: height, width, rgba = image.shape for i in range(height): for ii in range(width): if not np.array_equal(image[i, ii, :2], result_image[i, ii, :2]): result_image[i, ii, 3] = 0 skimage.io.imsave(output_file_path, result_image) def scale_range(n, minimum, maximum): n += -(np.min(n)) n /= np.max(n) / (maximum - minimum) n += minimum return n <commit_msg>Change scale range to normalization with source and target min max<commit_after>
import numpy as np import skimage.io import skimage.util import os def extract_region_from_image(image, region_bounding_box): return image[region_bounding_box[0]:region_bounding_box[2], region_bounding_box[1]:region_bounding_box[3]] def isolate_sprite(image_region_path, output_file_path): result_image = None for root, directories, files in os.walk(image_region_path): for file in files: if not file.endswith(".png"): continue image = skimage.io.imread(f"{root}/{file}") image = np.concatenate((image, np.full((image.shape[0], image.shape[1], 1), 255, dtype="uint8")), axis=2) if result_image is None: result_image = image else: height, width, rgba = image.shape for i in range(height): for ii in range(width): if not np.array_equal(image[i, ii, :2], result_image[i, ii, :2]): result_image[i, ii, 3] = 0 skimage.io.imsave(output_file_path, result_image) def normalize(n, source_min, source_max, target_min=0, target_max=1): return ((n - source_min) * (target_max - target_min) / (source_max - source_min)) + target_min
import numpy as np import skimage.io import skimage.util import os def extract_region_from_image(image, region_bounding_box): return image[region_bounding_box[0]:region_bounding_box[2], region_bounding_box[1]:region_bounding_box[3]] def isolate_sprite(image_region_path, output_file_path): result_image = None for root, directories, files in os.walk(image_region_path): for file in files: if not file.endswith(".png"): continue image = skimage.io.imread(f"{root}/{file}") image = np.concatenate((image, np.full((image.shape[0], image.shape[1], 1), 255, dtype="uint8")), axis=2) if result_image is None: result_image = image else: height, width, rgba = image.shape for i in range(height): for ii in range(width): if not np.array_equal(image[i, ii, :2], result_image[i, ii, :2]): result_image[i, ii, 3] = 0 skimage.io.imsave(output_file_path, result_image) def scale_range(n, minimum, maximum): n += -(np.min(n)) n /= np.max(n) / (maximum - minimum) n += minimum return n Change scale range to normalization with source and target min maximport numpy as np import skimage.io import skimage.util import os def extract_region_from_image(image, region_bounding_box): return image[region_bounding_box[0]:region_bounding_box[2], region_bounding_box[1]:region_bounding_box[3]] def isolate_sprite(image_region_path, output_file_path): result_image = None for root, directories, files in os.walk(image_region_path): for file in files: if not file.endswith(".png"): continue image = skimage.io.imread(f"{root}/{file}") image = np.concatenate((image, np.full((image.shape[0], image.shape[1], 1), 255, dtype="uint8")), axis=2) if result_image is None: result_image = image else: height, width, rgba = image.shape for i in range(height): for ii in range(width): if not np.array_equal(image[i, ii, :2], result_image[i, ii, :2]): result_image[i, ii, 3] = 0 skimage.io.imsave(output_file_path, result_image) def normalize(n, source_min, source_max, target_min=0, target_max=1): return ((n - source_min) * (target_max - target_min) / (source_max - source_min)) + target_min
<commit_before>import numpy as np import skimage.io import skimage.util import os def extract_region_from_image(image, region_bounding_box): return image[region_bounding_box[0]:region_bounding_box[2], region_bounding_box[1]:region_bounding_box[3]] def isolate_sprite(image_region_path, output_file_path): result_image = None for root, directories, files in os.walk(image_region_path): for file in files: if not file.endswith(".png"): continue image = skimage.io.imread(f"{root}/{file}") image = np.concatenate((image, np.full((image.shape[0], image.shape[1], 1), 255, dtype="uint8")), axis=2) if result_image is None: result_image = image else: height, width, rgba = image.shape for i in range(height): for ii in range(width): if not np.array_equal(image[i, ii, :2], result_image[i, ii, :2]): result_image[i, ii, 3] = 0 skimage.io.imsave(output_file_path, result_image) def scale_range(n, minimum, maximum): n += -(np.min(n)) n /= np.max(n) / (maximum - minimum) n += minimum return n <commit_msg>Change scale range to normalization with source and target min max<commit_after>import numpy as np import skimage.io import skimage.util import os def extract_region_from_image(image, region_bounding_box): return image[region_bounding_box[0]:region_bounding_box[2], region_bounding_box[1]:region_bounding_box[3]] def isolate_sprite(image_region_path, output_file_path): result_image = None for root, directories, files in os.walk(image_region_path): for file in files: if not file.endswith(".png"): continue image = skimage.io.imread(f"{root}/{file}") image = np.concatenate((image, np.full((image.shape[0], image.shape[1], 1), 255, dtype="uint8")), axis=2) if result_image is None: result_image = image else: height, width, rgba = image.shape for i in range(height): for ii in range(width): if not np.array_equal(image[i, ii, :2], result_image[i, ii, :2]): result_image[i, ii, 3] = 0 skimage.io.imsave(output_file_path, result_image) def normalize(n, source_min, source_max, target_min=0, target_max=1): return ((n - source_min) * (target_max - target_min) / (source_max - source_min)) + target_min
7157843c2469fd837cb30df182ad69583790b9eb
makeaface/makeaface/urls.py
makeaface/makeaface/urls.py
from django.conf.urls.defaults import * from motion.feeds import PublicEventsFeed urlpatterns = patterns('', url(r'^$', 'makeaface.views.home', name='home'), url(r'^$', 'makeaface.views.home', name='group_events'), url(r'^authorize/?$', 'makeaface.views.authorize', name='authorize'), url(r'^entry/(?P<id>\w+)$', 'django.views.generic.simple.redirect_to', {'url': r'/photo/%(id)s'}), url(r'^photo/(?P<xid>\w+)$', 'makeaface.views.photo', name='photo'), url(r'^upload$', 'makeaface.views.upload_photo', name='upload_photo'), url(r'^favorite$', 'makeaface.views.favorite', name='favorite'), url(r'^flag$', 'makeaface.views.flag', name='flag'), url(r'^delete$', 'makeaface.views.delete', name='delete'), url(r'^asset_meta$', 'makeaface.views.asset_meta', name='asset_meta'), url(r'^grid$', 'makeaface.views.facegrid', name='facegrid'), ) urlpatterns += patterns('', url(r'^feeds/(?P<url>.*)/?$', 'django.contrib.syndication.views.feed', {'feed_dict': {'faces': PublicEventsFeed}}, name='feeds'), )
from django.conf.urls.defaults import * from motion.feeds import PublicEventsFeed urlpatterns = patterns('', url(r'^$', 'makeaface.views.home', name='home'), url(r'^$', 'makeaface.views.home', name='group_events'), url(r'^authorize/?$', 'makeaface.views.authorize', name='authorize'), url(r'^entry/(?P<id>\w+)$', 'django.views.generic.simple.redirect_to', {'url': r'/photo/%(id)s'}), url(r'^photo/(?P<xid>\w+)$', 'makeaface.views.photo', name='photo'), url(r'^upload$', 'makeaface.views.upload_photo', name='upload_photo'), url(r'^favorite$', 'makeaface.views.favorite', name='favorite'), url(r'^flag$', 'makeaface.views.flag', name='flag'), url(r'^delete$', 'makeaface.views.delete', name='delete'), url(r'^asset_meta$', 'makeaface.views.asset_meta', name='asset_meta'), url(r'^grid$', 'makeaface.views.facegrid', name='facegrid'), url(r'^grid\.$', 'django.views.generic.simple.redirect_to', {'url': r'/grid'}), ) urlpatterns += patterns('', url(r'^feeds/(?P<url>.*)/?$', 'django.contrib.syndication.views.feed', {'feed_dict': {'faces': PublicEventsFeed}}, name='feeds'), )
Handle when /grid ends with a period, since Twitter let apgwoz link to it that way
Handle when /grid ends with a period, since Twitter let apgwoz link to it that way
Python
mit
markpasc/make-a-face,markpasc/make-a-face
from django.conf.urls.defaults import * from motion.feeds import PublicEventsFeed urlpatterns = patterns('', url(r'^$', 'makeaface.views.home', name='home'), url(r'^$', 'makeaface.views.home', name='group_events'), url(r'^authorize/?$', 'makeaface.views.authorize', name='authorize'), url(r'^entry/(?P<id>\w+)$', 'django.views.generic.simple.redirect_to', {'url': r'/photo/%(id)s'}), url(r'^photo/(?P<xid>\w+)$', 'makeaface.views.photo', name='photo'), url(r'^upload$', 'makeaface.views.upload_photo', name='upload_photo'), url(r'^favorite$', 'makeaface.views.favorite', name='favorite'), url(r'^flag$', 'makeaface.views.flag', name='flag'), url(r'^delete$', 'makeaface.views.delete', name='delete'), url(r'^asset_meta$', 'makeaface.views.asset_meta', name='asset_meta'), url(r'^grid$', 'makeaface.views.facegrid', name='facegrid'), ) urlpatterns += patterns('', url(r'^feeds/(?P<url>.*)/?$', 'django.contrib.syndication.views.feed', {'feed_dict': {'faces': PublicEventsFeed}}, name='feeds'), ) Handle when /grid ends with a period, since Twitter let apgwoz link to it that way
from django.conf.urls.defaults import * from motion.feeds import PublicEventsFeed urlpatterns = patterns('', url(r'^$', 'makeaface.views.home', name='home'), url(r'^$', 'makeaface.views.home', name='group_events'), url(r'^authorize/?$', 'makeaface.views.authorize', name='authorize'), url(r'^entry/(?P<id>\w+)$', 'django.views.generic.simple.redirect_to', {'url': r'/photo/%(id)s'}), url(r'^photo/(?P<xid>\w+)$', 'makeaface.views.photo', name='photo'), url(r'^upload$', 'makeaface.views.upload_photo', name='upload_photo'), url(r'^favorite$', 'makeaface.views.favorite', name='favorite'), url(r'^flag$', 'makeaface.views.flag', name='flag'), url(r'^delete$', 'makeaface.views.delete', name='delete'), url(r'^asset_meta$', 'makeaface.views.asset_meta', name='asset_meta'), url(r'^grid$', 'makeaface.views.facegrid', name='facegrid'), url(r'^grid\.$', 'django.views.generic.simple.redirect_to', {'url': r'/grid'}), ) urlpatterns += patterns('', url(r'^feeds/(?P<url>.*)/?$', 'django.contrib.syndication.views.feed', {'feed_dict': {'faces': PublicEventsFeed}}, name='feeds'), )
<commit_before>from django.conf.urls.defaults import * from motion.feeds import PublicEventsFeed urlpatterns = patterns('', url(r'^$', 'makeaface.views.home', name='home'), url(r'^$', 'makeaface.views.home', name='group_events'), url(r'^authorize/?$', 'makeaface.views.authorize', name='authorize'), url(r'^entry/(?P<id>\w+)$', 'django.views.generic.simple.redirect_to', {'url': r'/photo/%(id)s'}), url(r'^photo/(?P<xid>\w+)$', 'makeaface.views.photo', name='photo'), url(r'^upload$', 'makeaface.views.upload_photo', name='upload_photo'), url(r'^favorite$', 'makeaface.views.favorite', name='favorite'), url(r'^flag$', 'makeaface.views.flag', name='flag'), url(r'^delete$', 'makeaface.views.delete', name='delete'), url(r'^asset_meta$', 'makeaface.views.asset_meta', name='asset_meta'), url(r'^grid$', 'makeaface.views.facegrid', name='facegrid'), ) urlpatterns += patterns('', url(r'^feeds/(?P<url>.*)/?$', 'django.contrib.syndication.views.feed', {'feed_dict': {'faces': PublicEventsFeed}}, name='feeds'), ) <commit_msg>Handle when /grid ends with a period, since Twitter let apgwoz link to it that way<commit_after>
from django.conf.urls.defaults import * from motion.feeds import PublicEventsFeed urlpatterns = patterns('', url(r'^$', 'makeaface.views.home', name='home'), url(r'^$', 'makeaface.views.home', name='group_events'), url(r'^authorize/?$', 'makeaface.views.authorize', name='authorize'), url(r'^entry/(?P<id>\w+)$', 'django.views.generic.simple.redirect_to', {'url': r'/photo/%(id)s'}), url(r'^photo/(?P<xid>\w+)$', 'makeaface.views.photo', name='photo'), url(r'^upload$', 'makeaface.views.upload_photo', name='upload_photo'), url(r'^favorite$', 'makeaface.views.favorite', name='favorite'), url(r'^flag$', 'makeaface.views.flag', name='flag'), url(r'^delete$', 'makeaface.views.delete', name='delete'), url(r'^asset_meta$', 'makeaface.views.asset_meta', name='asset_meta'), url(r'^grid$', 'makeaface.views.facegrid', name='facegrid'), url(r'^grid\.$', 'django.views.generic.simple.redirect_to', {'url': r'/grid'}), ) urlpatterns += patterns('', url(r'^feeds/(?P<url>.*)/?$', 'django.contrib.syndication.views.feed', {'feed_dict': {'faces': PublicEventsFeed}}, name='feeds'), )
from django.conf.urls.defaults import * from motion.feeds import PublicEventsFeed urlpatterns = patterns('', url(r'^$', 'makeaface.views.home', name='home'), url(r'^$', 'makeaface.views.home', name='group_events'), url(r'^authorize/?$', 'makeaface.views.authorize', name='authorize'), url(r'^entry/(?P<id>\w+)$', 'django.views.generic.simple.redirect_to', {'url': r'/photo/%(id)s'}), url(r'^photo/(?P<xid>\w+)$', 'makeaface.views.photo', name='photo'), url(r'^upload$', 'makeaface.views.upload_photo', name='upload_photo'), url(r'^favorite$', 'makeaface.views.favorite', name='favorite'), url(r'^flag$', 'makeaface.views.flag', name='flag'), url(r'^delete$', 'makeaface.views.delete', name='delete'), url(r'^asset_meta$', 'makeaface.views.asset_meta', name='asset_meta'), url(r'^grid$', 'makeaface.views.facegrid', name='facegrid'), ) urlpatterns += patterns('', url(r'^feeds/(?P<url>.*)/?$', 'django.contrib.syndication.views.feed', {'feed_dict': {'faces': PublicEventsFeed}}, name='feeds'), ) Handle when /grid ends with a period, since Twitter let apgwoz link to it that wayfrom django.conf.urls.defaults import * from motion.feeds import PublicEventsFeed urlpatterns = patterns('', url(r'^$', 'makeaface.views.home', name='home'), url(r'^$', 'makeaface.views.home', name='group_events'), url(r'^authorize/?$', 'makeaface.views.authorize', name='authorize'), url(r'^entry/(?P<id>\w+)$', 'django.views.generic.simple.redirect_to', {'url': r'/photo/%(id)s'}), url(r'^photo/(?P<xid>\w+)$', 'makeaface.views.photo', name='photo'), url(r'^upload$', 'makeaface.views.upload_photo', name='upload_photo'), url(r'^favorite$', 'makeaface.views.favorite', name='favorite'), url(r'^flag$', 'makeaface.views.flag', name='flag'), url(r'^delete$', 'makeaface.views.delete', name='delete'), url(r'^asset_meta$', 'makeaface.views.asset_meta', name='asset_meta'), url(r'^grid$', 'makeaface.views.facegrid', name='facegrid'), url(r'^grid\.$', 'django.views.generic.simple.redirect_to', {'url': r'/grid'}), ) urlpatterns += patterns('', url(r'^feeds/(?P<url>.*)/?$', 'django.contrib.syndication.views.feed', {'feed_dict': {'faces': PublicEventsFeed}}, name='feeds'), )
<commit_before>from django.conf.urls.defaults import * from motion.feeds import PublicEventsFeed urlpatterns = patterns('', url(r'^$', 'makeaface.views.home', name='home'), url(r'^$', 'makeaface.views.home', name='group_events'), url(r'^authorize/?$', 'makeaface.views.authorize', name='authorize'), url(r'^entry/(?P<id>\w+)$', 'django.views.generic.simple.redirect_to', {'url': r'/photo/%(id)s'}), url(r'^photo/(?P<xid>\w+)$', 'makeaface.views.photo', name='photo'), url(r'^upload$', 'makeaface.views.upload_photo', name='upload_photo'), url(r'^favorite$', 'makeaface.views.favorite', name='favorite'), url(r'^flag$', 'makeaface.views.flag', name='flag'), url(r'^delete$', 'makeaface.views.delete', name='delete'), url(r'^asset_meta$', 'makeaface.views.asset_meta', name='asset_meta'), url(r'^grid$', 'makeaface.views.facegrid', name='facegrid'), ) urlpatterns += patterns('', url(r'^feeds/(?P<url>.*)/?$', 'django.contrib.syndication.views.feed', {'feed_dict': {'faces': PublicEventsFeed}}, name='feeds'), ) <commit_msg>Handle when /grid ends with a period, since Twitter let apgwoz link to it that way<commit_after>from django.conf.urls.defaults import * from motion.feeds import PublicEventsFeed urlpatterns = patterns('', url(r'^$', 'makeaface.views.home', name='home'), url(r'^$', 'makeaface.views.home', name='group_events'), url(r'^authorize/?$', 'makeaface.views.authorize', name='authorize'), url(r'^entry/(?P<id>\w+)$', 'django.views.generic.simple.redirect_to', {'url': r'/photo/%(id)s'}), url(r'^photo/(?P<xid>\w+)$', 'makeaface.views.photo', name='photo'), url(r'^upload$', 'makeaface.views.upload_photo', name='upload_photo'), url(r'^favorite$', 'makeaface.views.favorite', name='favorite'), url(r'^flag$', 'makeaface.views.flag', name='flag'), url(r'^delete$', 'makeaface.views.delete', name='delete'), url(r'^asset_meta$', 'makeaface.views.asset_meta', name='asset_meta'), url(r'^grid$', 'makeaface.views.facegrid', name='facegrid'), url(r'^grid\.$', 'django.views.generic.simple.redirect_to', {'url': r'/grid'}), ) urlpatterns += patterns('', url(r'^feeds/(?P<url>.*)/?$', 'django.contrib.syndication.views.feed', {'feed_dict': {'faces': PublicEventsFeed}}, name='feeds'), )
4fda69c972f223354b27b89981751e2ae490a98e
plumeria/plugins/discord.py
plumeria/plugins/discord.py
from plumeria.command import commands, channel_only from plumeria.message import Response @commands.register('roles', category='Discord') @channel_only async def roles(message): """ Gets the roles in the current server, including their name and ID. Intended for development purposes. Example:: /roles Response:: bot (160143463784458624), admin (160143463784458624) """ roles = filter(lambda r: r.name != "@everyone", message.channel.server.roles) return Response(", ".join(["{} ({})".format(r.name, r.id) for r in roles])) @commands.register('user id', ''userid', category='Discord') async def userid(message): """ Gets your own Discord user ID for development purposes. Example:: /userid Response:: 43463109290000434 """ return Response(message.author.id)
from plumeria.command import commands, channel_only from plumeria.message import Response @commands.register('roles', category='Discord') @channel_only async def roles(message): """ Gets the roles in the current server, including their name and ID. Intended for development purposes. Example:: /roles Response:: bot (160143463784458624), admin (160143463784458624) """ roles = filter(lambda r: r.name != "@everyone", message.channel.server.roles) return Response(", ".join(["{} ({})".format(r.name, r.id) for r in roles])) @commands.register('user id', 'userid', category='Discord') async def userid(message): """ Gets your own Discord user ID for development purposes. Example:: /userid Response:: 43463109290000434 """ return Response(message.author.id)
Fix typo in the Discord plugin.
Fix typo in the Discord plugin.
Python
mit
sk89q/Plumeria,sk89q/Plumeria,sk89q/Plumeria
from plumeria.command import commands, channel_only from plumeria.message import Response @commands.register('roles', category='Discord') @channel_only async def roles(message): """ Gets the roles in the current server, including their name and ID. Intended for development purposes. Example:: /roles Response:: bot (160143463784458624), admin (160143463784458624) """ roles = filter(lambda r: r.name != "@everyone", message.channel.server.roles) return Response(", ".join(["{} ({})".format(r.name, r.id) for r in roles])) @commands.register('user id', ''userid', category='Discord') async def userid(message): """ Gets your own Discord user ID for development purposes. Example:: /userid Response:: 43463109290000434 """ return Response(message.author.id) Fix typo in the Discord plugin.
from plumeria.command import commands, channel_only from plumeria.message import Response @commands.register('roles', category='Discord') @channel_only async def roles(message): """ Gets the roles in the current server, including their name and ID. Intended for development purposes. Example:: /roles Response:: bot (160143463784458624), admin (160143463784458624) """ roles = filter(lambda r: r.name != "@everyone", message.channel.server.roles) return Response(", ".join(["{} ({})".format(r.name, r.id) for r in roles])) @commands.register('user id', 'userid', category='Discord') async def userid(message): """ Gets your own Discord user ID for development purposes. Example:: /userid Response:: 43463109290000434 """ return Response(message.author.id)
<commit_before>from plumeria.command import commands, channel_only from plumeria.message import Response @commands.register('roles', category='Discord') @channel_only async def roles(message): """ Gets the roles in the current server, including their name and ID. Intended for development purposes. Example:: /roles Response:: bot (160143463784458624), admin (160143463784458624) """ roles = filter(lambda r: r.name != "@everyone", message.channel.server.roles) return Response(", ".join(["{} ({})".format(r.name, r.id) for r in roles])) @commands.register('user id', ''userid', category='Discord') async def userid(message): """ Gets your own Discord user ID for development purposes. Example:: /userid Response:: 43463109290000434 """ return Response(message.author.id) <commit_msg>Fix typo in the Discord plugin.<commit_after>
from plumeria.command import commands, channel_only from plumeria.message import Response @commands.register('roles', category='Discord') @channel_only async def roles(message): """ Gets the roles in the current server, including their name and ID. Intended for development purposes. Example:: /roles Response:: bot (160143463784458624), admin (160143463784458624) """ roles = filter(lambda r: r.name != "@everyone", message.channel.server.roles) return Response(", ".join(["{} ({})".format(r.name, r.id) for r in roles])) @commands.register('user id', 'userid', category='Discord') async def userid(message): """ Gets your own Discord user ID for development purposes. Example:: /userid Response:: 43463109290000434 """ return Response(message.author.id)
from plumeria.command import commands, channel_only from plumeria.message import Response @commands.register('roles', category='Discord') @channel_only async def roles(message): """ Gets the roles in the current server, including their name and ID. Intended for development purposes. Example:: /roles Response:: bot (160143463784458624), admin (160143463784458624) """ roles = filter(lambda r: r.name != "@everyone", message.channel.server.roles) return Response(", ".join(["{} ({})".format(r.name, r.id) for r in roles])) @commands.register('user id', ''userid', category='Discord') async def userid(message): """ Gets your own Discord user ID for development purposes. Example:: /userid Response:: 43463109290000434 """ return Response(message.author.id) Fix typo in the Discord plugin.from plumeria.command import commands, channel_only from plumeria.message import Response @commands.register('roles', category='Discord') @channel_only async def roles(message): """ Gets the roles in the current server, including their name and ID. Intended for development purposes. Example:: /roles Response:: bot (160143463784458624), admin (160143463784458624) """ roles = filter(lambda r: r.name != "@everyone", message.channel.server.roles) return Response(", ".join(["{} ({})".format(r.name, r.id) for r in roles])) @commands.register('user id', 'userid', category='Discord') async def userid(message): """ Gets your own Discord user ID for development purposes. Example:: /userid Response:: 43463109290000434 """ return Response(message.author.id)
<commit_before>from plumeria.command import commands, channel_only from plumeria.message import Response @commands.register('roles', category='Discord') @channel_only async def roles(message): """ Gets the roles in the current server, including their name and ID. Intended for development purposes. Example:: /roles Response:: bot (160143463784458624), admin (160143463784458624) """ roles = filter(lambda r: r.name != "@everyone", message.channel.server.roles) return Response(", ".join(["{} ({})".format(r.name, r.id) for r in roles])) @commands.register('user id', ''userid', category='Discord') async def userid(message): """ Gets your own Discord user ID for development purposes. Example:: /userid Response:: 43463109290000434 """ return Response(message.author.id) <commit_msg>Fix typo in the Discord plugin.<commit_after>from plumeria.command import commands, channel_only from plumeria.message import Response @commands.register('roles', category='Discord') @channel_only async def roles(message): """ Gets the roles in the current server, including their name and ID. Intended for development purposes. Example:: /roles Response:: bot (160143463784458624), admin (160143463784458624) """ roles = filter(lambda r: r.name != "@everyone", message.channel.server.roles) return Response(", ".join(["{} ({})".format(r.name, r.id) for r in roles])) @commands.register('user id', 'userid', category='Discord') async def userid(message): """ Gets your own Discord user ID for development purposes. Example:: /userid Response:: 43463109290000434 """ return Response(message.author.id)
fedf1df20418169a377012c22bf81f758e2978e8
tests/test_dbg.py
tests/test_dbg.py
import pytest from boink.dbg_tests import (_test_add_single_kmer, _test_add_two_kmers, _test_kmer_degree, _test_kmer_in_degree, _test_kmer_out_degree) def test_add_single_kmer(): _test_add_single_kmer() def test_add_two_kmers(): _test_add_two_kmers() def test_kmer_degree(): _test_kmer_degree() def test_kmer_in_degree(): _test_kmer_in_degree() def test_kmer_out_degree(): _test_kmer_out_degree()
import pytest from utils import * from boink.dbg_tests import (_test_add_single_kmer, _test_add_two_kmers, _test_kmer_degree, _test_kmer_in_degree, _test_kmer_out_degree, _test_kmer_count, _test_add_loop) from boink.dbg import ExactDBG, kmers @pytest.fixture def G(K): return ExactDBG(K) def test_add_single_kmer(): _test_add_single_kmer() def test_add_two_kmers(): _test_add_two_kmers() def test_kmer_degree(): _test_kmer_degree() def test_kmer_in_degree(): _test_kmer_in_degree() def test_kmer_out_degree(): _test_kmer_out_degree() def test_kmer_count(): _test_kmer_count() def test_add_loop(random_sequence, K): seq = random_sequence() seq += seq[:K] _test_add_loop(seq, K) def test_right_tip(right_tip_structure, G, K): (sequence, tip), S = right_tip_structure G.add_sequence(sequence) for kmer in kmers(sequence[1:-1], K): assert G.kmer_count(kmer) == 1 assert G.kmer_degree(kmer) == 2 assert G.kmer_degree(sequence[:K]) == 1 assert G.kmer_degree(sequence[-K:]) == 1 G.add_sequence(tip) assert G.kmer_out_degree(sequence[S-K:S]) == 2 assert G.kmer_in_degree(sequence[S-K:S]) == 1 assert G.kmer_in_degree(tip[-K:]) == 1 assert G.kmer_out_degree(tip[S-K:S]) == 2 for kmer in kmers(tip[1:-2], K): assert G.kmer_count(kmer) == 2 assert G.kmer_degree(kmer) == 2
Add right tip structure tests
Add right tip structure tests
Python
mit
camillescott/boink,camillescott/boink,camillescott/boink,camillescott/boink
import pytest from boink.dbg_tests import (_test_add_single_kmer, _test_add_two_kmers, _test_kmer_degree, _test_kmer_in_degree, _test_kmer_out_degree) def test_add_single_kmer(): _test_add_single_kmer() def test_add_two_kmers(): _test_add_two_kmers() def test_kmer_degree(): _test_kmer_degree() def test_kmer_in_degree(): _test_kmer_in_degree() def test_kmer_out_degree(): _test_kmer_out_degree() Add right tip structure tests
import pytest from utils import * from boink.dbg_tests import (_test_add_single_kmer, _test_add_two_kmers, _test_kmer_degree, _test_kmer_in_degree, _test_kmer_out_degree, _test_kmer_count, _test_add_loop) from boink.dbg import ExactDBG, kmers @pytest.fixture def G(K): return ExactDBG(K) def test_add_single_kmer(): _test_add_single_kmer() def test_add_two_kmers(): _test_add_two_kmers() def test_kmer_degree(): _test_kmer_degree() def test_kmer_in_degree(): _test_kmer_in_degree() def test_kmer_out_degree(): _test_kmer_out_degree() def test_kmer_count(): _test_kmer_count() def test_add_loop(random_sequence, K): seq = random_sequence() seq += seq[:K] _test_add_loop(seq, K) def test_right_tip(right_tip_structure, G, K): (sequence, tip), S = right_tip_structure G.add_sequence(sequence) for kmer in kmers(sequence[1:-1], K): assert G.kmer_count(kmer) == 1 assert G.kmer_degree(kmer) == 2 assert G.kmer_degree(sequence[:K]) == 1 assert G.kmer_degree(sequence[-K:]) == 1 G.add_sequence(tip) assert G.kmer_out_degree(sequence[S-K:S]) == 2 assert G.kmer_in_degree(sequence[S-K:S]) == 1 assert G.kmer_in_degree(tip[-K:]) == 1 assert G.kmer_out_degree(tip[S-K:S]) == 2 for kmer in kmers(tip[1:-2], K): assert G.kmer_count(kmer) == 2 assert G.kmer_degree(kmer) == 2
<commit_before>import pytest from boink.dbg_tests import (_test_add_single_kmer, _test_add_two_kmers, _test_kmer_degree, _test_kmer_in_degree, _test_kmer_out_degree) def test_add_single_kmer(): _test_add_single_kmer() def test_add_two_kmers(): _test_add_two_kmers() def test_kmer_degree(): _test_kmer_degree() def test_kmer_in_degree(): _test_kmer_in_degree() def test_kmer_out_degree(): _test_kmer_out_degree() <commit_msg>Add right tip structure tests<commit_after>
import pytest from utils import * from boink.dbg_tests import (_test_add_single_kmer, _test_add_two_kmers, _test_kmer_degree, _test_kmer_in_degree, _test_kmer_out_degree, _test_kmer_count, _test_add_loop) from boink.dbg import ExactDBG, kmers @pytest.fixture def G(K): return ExactDBG(K) def test_add_single_kmer(): _test_add_single_kmer() def test_add_two_kmers(): _test_add_two_kmers() def test_kmer_degree(): _test_kmer_degree() def test_kmer_in_degree(): _test_kmer_in_degree() def test_kmer_out_degree(): _test_kmer_out_degree() def test_kmer_count(): _test_kmer_count() def test_add_loop(random_sequence, K): seq = random_sequence() seq += seq[:K] _test_add_loop(seq, K) def test_right_tip(right_tip_structure, G, K): (sequence, tip), S = right_tip_structure G.add_sequence(sequence) for kmer in kmers(sequence[1:-1], K): assert G.kmer_count(kmer) == 1 assert G.kmer_degree(kmer) == 2 assert G.kmer_degree(sequence[:K]) == 1 assert G.kmer_degree(sequence[-K:]) == 1 G.add_sequence(tip) assert G.kmer_out_degree(sequence[S-K:S]) == 2 assert G.kmer_in_degree(sequence[S-K:S]) == 1 assert G.kmer_in_degree(tip[-K:]) == 1 assert G.kmer_out_degree(tip[S-K:S]) == 2 for kmer in kmers(tip[1:-2], K): assert G.kmer_count(kmer) == 2 assert G.kmer_degree(kmer) == 2
import pytest from boink.dbg_tests import (_test_add_single_kmer, _test_add_two_kmers, _test_kmer_degree, _test_kmer_in_degree, _test_kmer_out_degree) def test_add_single_kmer(): _test_add_single_kmer() def test_add_two_kmers(): _test_add_two_kmers() def test_kmer_degree(): _test_kmer_degree() def test_kmer_in_degree(): _test_kmer_in_degree() def test_kmer_out_degree(): _test_kmer_out_degree() Add right tip structure testsimport pytest from utils import * from boink.dbg_tests import (_test_add_single_kmer, _test_add_two_kmers, _test_kmer_degree, _test_kmer_in_degree, _test_kmer_out_degree, _test_kmer_count, _test_add_loop) from boink.dbg import ExactDBG, kmers @pytest.fixture def G(K): return ExactDBG(K) def test_add_single_kmer(): _test_add_single_kmer() def test_add_two_kmers(): _test_add_two_kmers() def test_kmer_degree(): _test_kmer_degree() def test_kmer_in_degree(): _test_kmer_in_degree() def test_kmer_out_degree(): _test_kmer_out_degree() def test_kmer_count(): _test_kmer_count() def test_add_loop(random_sequence, K): seq = random_sequence() seq += seq[:K] _test_add_loop(seq, K) def test_right_tip(right_tip_structure, G, K): (sequence, tip), S = right_tip_structure G.add_sequence(sequence) for kmer in kmers(sequence[1:-1], K): assert G.kmer_count(kmer) == 1 assert G.kmer_degree(kmer) == 2 assert G.kmer_degree(sequence[:K]) == 1 assert G.kmer_degree(sequence[-K:]) == 1 G.add_sequence(tip) assert G.kmer_out_degree(sequence[S-K:S]) == 2 assert G.kmer_in_degree(sequence[S-K:S]) == 1 assert G.kmer_in_degree(tip[-K:]) == 1 assert G.kmer_out_degree(tip[S-K:S]) == 2 for kmer in kmers(tip[1:-2], K): assert G.kmer_count(kmer) == 2 assert G.kmer_degree(kmer) == 2
<commit_before>import pytest from boink.dbg_tests import (_test_add_single_kmer, _test_add_two_kmers, _test_kmer_degree, _test_kmer_in_degree, _test_kmer_out_degree) def test_add_single_kmer(): _test_add_single_kmer() def test_add_two_kmers(): _test_add_two_kmers() def test_kmer_degree(): _test_kmer_degree() def test_kmer_in_degree(): _test_kmer_in_degree() def test_kmer_out_degree(): _test_kmer_out_degree() <commit_msg>Add right tip structure tests<commit_after>import pytest from utils import * from boink.dbg_tests import (_test_add_single_kmer, _test_add_two_kmers, _test_kmer_degree, _test_kmer_in_degree, _test_kmer_out_degree, _test_kmer_count, _test_add_loop) from boink.dbg import ExactDBG, kmers @pytest.fixture def G(K): return ExactDBG(K) def test_add_single_kmer(): _test_add_single_kmer() def test_add_two_kmers(): _test_add_two_kmers() def test_kmer_degree(): _test_kmer_degree() def test_kmer_in_degree(): _test_kmer_in_degree() def test_kmer_out_degree(): _test_kmer_out_degree() def test_kmer_count(): _test_kmer_count() def test_add_loop(random_sequence, K): seq = random_sequence() seq += seq[:K] _test_add_loop(seq, K) def test_right_tip(right_tip_structure, G, K): (sequence, tip), S = right_tip_structure G.add_sequence(sequence) for kmer in kmers(sequence[1:-1], K): assert G.kmer_count(kmer) == 1 assert G.kmer_degree(kmer) == 2 assert G.kmer_degree(sequence[:K]) == 1 assert G.kmer_degree(sequence[-K:]) == 1 G.add_sequence(tip) assert G.kmer_out_degree(sequence[S-K:S]) == 2 assert G.kmer_in_degree(sequence[S-K:S]) == 1 assert G.kmer_in_degree(tip[-K:]) == 1 assert G.kmer_out_degree(tip[S-K:S]) == 2 for kmer in kmers(tip[1:-2], K): assert G.kmer_count(kmer) == 2 assert G.kmer_degree(kmer) == 2
568c3466844ec9b27fbe7e3a4e1bae772203923d
touch/__init__.py
touch/__init__.py
from pelican import signals import logging import os import time logger = logging.getLogger(__name__) def set_file_utime(path, datetime): mtime = time.mktime(datetime.timetuple()) logger.info('touching %s', path) os.utime(path, (mtime, mtime)) def touch_file(path, context): content = context.get('article', context.get('page')) page = context.get('articles_page') dates = context.get('dates') if content and hasattr(content, 'date'): set_file_utime(path, content.date) elif page: set_file_utime(path, max(x.date for x in page.object_list)) elif dates: set_file_utime(path, max(x.date for x in dates)) def register(): signals.content_written.connect(touch_file)
from pelican import signals import logging import os import time logger = logging.getLogger(__name__) def set_file_utime(path, datetime): mtime = time.mktime(datetime.timetuple()) logger.info('touching %s', path) os.utime(path, (mtime, mtime)) def touch_file(path, context): content = context.get('article', context.get('page')) page = context.get('articles_page') dates = context.get('dates') if content and hasattr(content, 'date'): set_file_utime(path, content.date) elif page: set_file_utime(path, max(x.date for x in page.object_list)) elif dates: set_file_utime(path, max(x.date for x in dates)) def touch_feed(path, context, feed): set_file_utime(path, max(x['pubdate'] for x in feed.items)) def register(): signals.content_written.connect(touch_file) signals.feed_written.connect(touch_feed)
Update timestamps of generated feeds as well
Update timestamps of generated feeds as well
Python
agpl-3.0
frickp/pelican-plugins,UHBiocomputation/pelican-plugins,xsteadfastx/pelican-plugins,mikitex70/pelican-plugins,jantman/pelican-plugins,proteansec/pelican-plugins,lindzey/pelican-plugins,farseerfc/pelican-plugins,davidmarquis/pelican-plugins,UHBiocomputation/pelican-plugins,makefu/pelican-plugins,mwcz/pelican-plugins,goerz/pelican-plugins,ingwinlu/pelican-plugins,xsteadfastx/pelican-plugins,gw0/pelican-plugins,ingwinlu/pelican-plugins,joachimneu/pelican-plugins,ziaa/pelican-plugins,phrawzty/pelican-plugins,davidmarquis/pelican-plugins,mortada/pelican-plugins,MarkusH/pelican-plugins,olgabot/pelican-plugins,doctorwidget/pelican-plugins,karya0/pelican-plugins,wilsonfreitas/pelican-plugins,jprine/pelican-plugins,makefu/pelican-plugins,jfosorio/pelican-plugins,jakevdp/pelican-plugins,gw0/pelican-plugins,pestrickland/pelican-plugins,M157q/pelican-plugins,andreas-h/pelican-plugins,joachimneu/pelican-plugins,proteansec/pelican-plugins,samueljohn/pelican-plugins,clokep/pelican-plugins,florianjacob/pelican-plugins,shireenrao/pelican-plugins,benjaminabel/pelican-plugins,xsteadfastx/pelican-plugins,wilsonfreitas/pelican-plugins,davidmarquis/pelican-plugins,cmacmackin/pelican-plugins,Neurita/pelican-plugins,amitsaha/pelican-plugins,doctorwidget/pelican-plugins,M157q/pelican-plugins,rlaboiss/pelican-plugins,jcdubacq/pelican-plugins,lindzey/pelican-plugins,joachimneu/pelican-plugins,pxquim/pelican-plugins,makefu/pelican-plugins,jcdubacq/pelican-plugins,gjreda/pelican-plugins,lindzey/pelican-plugins,M157q/pelican-plugins,phrawzty/pelican-plugins,jantman/pelican-plugins,mwcz/pelican-plugins,Neurita/pelican-plugins,cctags/pelican-plugins,frickp/pelican-plugins,andreas-h/pelican-plugins,frickp/pelican-plugins,pelson/pelican-plugins,Xion/pelican-plugins,barrysteyn/pelican-plugins,samueljohn/pelican-plugins,mortada/pelican-plugins,benjaminabel/pelican-plugins,lele1122/pelican-plugins,ziaa/pelican-plugins,kdheepak89/pelican-plugins,kdheepak89/pelican-plugins,florianjacob/pelican-plugins,pxquim/pelican-plugins,wilsonfreitas/pelican-plugins,talha131/pelican-plugins,howthebodyworks/pelican-plugins,pestrickland/pelican-plugins,pestrickland/pelican-plugins,prisae/pelican-plugins,lazycoder-ru/pelican-plugins,goerz/pelican-plugins,barrysteyn/pelican-plugins,publicus/pelican-plugins,FuzzJunket/pelican-plugins,talha131/pelican-plugins,Samael500/pelican-plugins,cmacmackin/pelican-plugins,cctags/pelican-plugins,Xion/pelican-plugins,FuzzJunket/pelican-plugins,olgabot/pelican-plugins,clokep/pelican-plugins,talha131/pelican-plugins,lazycoder-ru/pelican-plugins,jfosorio/pelican-plugins,jfosorio/pelican-plugins,seandavi/pelican-plugins,karya0/pelican-plugins,lele1122/pelican-plugins,mikitex70/pelican-plugins,yuanboshe/pelican-plugins,pelson/pelican-plugins,jakevdp/pelican-plugins,FuzzJunket/pelican-plugins,prisae/pelican-plugins,shireenrao/pelican-plugins,talha131/pelican-plugins,olgabot/pelican-plugins,mwcz/pelican-plugins,samueljohn/pelican-plugins,mwcz/pelican-plugins,howthebodyworks/pelican-plugins,andreas-h/pelican-plugins,goerz/pelican-plugins,davidmarquis/pelican-plugins,Samael500/pelican-plugins,pxquim/pelican-plugins,benjaminabel/pelican-plugins,mortada/pelican-plugins,seandavi/pelican-plugins,phrawzty/pelican-plugins,pxquim/pelican-plugins,prisae/pelican-plugins,publicus/pelican-plugins,talha131/pelican-plugins,Xion/pelican-plugins,barrysteyn/pelican-plugins,gjreda/pelican-plugins,FuzzJunket/pelican-plugins,karya0/pelican-plugins,howthebodyworks/pelican-plugins,danmackinlay/pelican-plugins,joachimneu/pelican-plugins,proteansec/pelican-plugins,cmacmackin/pelican-plugins,MarkusH/pelican-plugins,mitchins/pelican-plugins,doctorwidget/pelican-plugins,farseerfc/pelican-plugins,jantman/pelican-plugins,ziaa/pelican-plugins,cctags/pelican-plugins,olgabot/pelican-plugins,phrawzty/pelican-plugins,cctags/pelican-plugins,florianjacob/pelican-plugins,lele1122/pelican-plugins,goerz/pelican-plugins,yuanboshe/pelican-plugins,mikitex70/pelican-plugins,amitsaha/pelican-plugins,shireenrao/pelican-plugins,mitchins/pelican-plugins,frickp/pelican-plugins,ziaa/pelican-plugins,danmackinlay/pelican-plugins,yuanboshe/pelican-plugins,if1live/pelican-plugins,doctorwidget/pelican-plugins,mortada/pelican-plugins,wilsonfreitas/pelican-plugins,MarkusH/pelican-plugins,Samael500/pelican-plugins,publicus/pelican-plugins,benjaminabel/pelican-plugins,prisae/pelican-plugins,makefu/pelican-plugins,howthebodyworks/pelican-plugins,if1live/pelican-plugins,shireenrao/pelican-plugins,M157q/pelican-plugins,proteansec/pelican-plugins,farseerfc/pelican-plugins,xsteadfastx/pelican-plugins,Samael500/pelican-plugins,cmacmackin/pelican-plugins,samueljohn/pelican-plugins,farseerfc/pelican-plugins,clokep/pelican-plugins,Neurita/pelican-plugins,farseerfc/pelican-plugins,publicus/pelican-plugins,ingwinlu/pelican-plugins,danmackinlay/pelican-plugins,mikitex70/pelican-plugins,amitsaha/pelican-plugins,rlaboiss/pelican-plugins,jprine/pelican-plugins,lele1122/pelican-plugins,MarkusH/pelican-plugins,lazycoder-ru/pelican-plugins,mitchins/pelican-plugins,lindzey/pelican-plugins,yuanboshe/pelican-plugins,amitsaha/pelican-plugins,clokep/pelican-plugins,mortada/pelican-plugins,rlaboiss/pelican-plugins,seandavi/pelican-plugins,pelson/pelican-plugins,UHBiocomputation/pelican-plugins,gjreda/pelican-plugins,andreas-h/pelican-plugins,MarkusH/pelican-plugins,if1live/pelican-plugins,jantman/pelican-plugins,gjreda/pelican-plugins,lazycoder-ru/pelican-plugins,mitchins/pelican-plugins,barrysteyn/pelican-plugins,karya0/pelican-plugins,kdheepak89/pelican-plugins,if1live/pelican-plugins,seandavi/pelican-plugins,kdheepak89/pelican-plugins,pelson/pelican-plugins,jfosorio/pelican-plugins,florianjacob/pelican-plugins,jakevdp/pelican-plugins,danmackinlay/pelican-plugins,rlaboiss/pelican-plugins,jakevdp/pelican-plugins,ingwinlu/pelican-plugins,UHBiocomputation/pelican-plugins,Xion/pelican-plugins,pestrickland/pelican-plugins,Neurita/pelican-plugins
from pelican import signals import logging import os import time logger = logging.getLogger(__name__) def set_file_utime(path, datetime): mtime = time.mktime(datetime.timetuple()) logger.info('touching %s', path) os.utime(path, (mtime, mtime)) def touch_file(path, context): content = context.get('article', context.get('page')) page = context.get('articles_page') dates = context.get('dates') if content and hasattr(content, 'date'): set_file_utime(path, content.date) elif page: set_file_utime(path, max(x.date for x in page.object_list)) elif dates: set_file_utime(path, max(x.date for x in dates)) def register(): signals.content_written.connect(touch_file) Update timestamps of generated feeds as well
from pelican import signals import logging import os import time logger = logging.getLogger(__name__) def set_file_utime(path, datetime): mtime = time.mktime(datetime.timetuple()) logger.info('touching %s', path) os.utime(path, (mtime, mtime)) def touch_file(path, context): content = context.get('article', context.get('page')) page = context.get('articles_page') dates = context.get('dates') if content and hasattr(content, 'date'): set_file_utime(path, content.date) elif page: set_file_utime(path, max(x.date for x in page.object_list)) elif dates: set_file_utime(path, max(x.date for x in dates)) def touch_feed(path, context, feed): set_file_utime(path, max(x['pubdate'] for x in feed.items)) def register(): signals.content_written.connect(touch_file) signals.feed_written.connect(touch_feed)
<commit_before>from pelican import signals import logging import os import time logger = logging.getLogger(__name__) def set_file_utime(path, datetime): mtime = time.mktime(datetime.timetuple()) logger.info('touching %s', path) os.utime(path, (mtime, mtime)) def touch_file(path, context): content = context.get('article', context.get('page')) page = context.get('articles_page') dates = context.get('dates') if content and hasattr(content, 'date'): set_file_utime(path, content.date) elif page: set_file_utime(path, max(x.date for x in page.object_list)) elif dates: set_file_utime(path, max(x.date for x in dates)) def register(): signals.content_written.connect(touch_file) <commit_msg>Update timestamps of generated feeds as well<commit_after>
from pelican import signals import logging import os import time logger = logging.getLogger(__name__) def set_file_utime(path, datetime): mtime = time.mktime(datetime.timetuple()) logger.info('touching %s', path) os.utime(path, (mtime, mtime)) def touch_file(path, context): content = context.get('article', context.get('page')) page = context.get('articles_page') dates = context.get('dates') if content and hasattr(content, 'date'): set_file_utime(path, content.date) elif page: set_file_utime(path, max(x.date for x in page.object_list)) elif dates: set_file_utime(path, max(x.date for x in dates)) def touch_feed(path, context, feed): set_file_utime(path, max(x['pubdate'] for x in feed.items)) def register(): signals.content_written.connect(touch_file) signals.feed_written.connect(touch_feed)
from pelican import signals import logging import os import time logger = logging.getLogger(__name__) def set_file_utime(path, datetime): mtime = time.mktime(datetime.timetuple()) logger.info('touching %s', path) os.utime(path, (mtime, mtime)) def touch_file(path, context): content = context.get('article', context.get('page')) page = context.get('articles_page') dates = context.get('dates') if content and hasattr(content, 'date'): set_file_utime(path, content.date) elif page: set_file_utime(path, max(x.date for x in page.object_list)) elif dates: set_file_utime(path, max(x.date for x in dates)) def register(): signals.content_written.connect(touch_file) Update timestamps of generated feeds as wellfrom pelican import signals import logging import os import time logger = logging.getLogger(__name__) def set_file_utime(path, datetime): mtime = time.mktime(datetime.timetuple()) logger.info('touching %s', path) os.utime(path, (mtime, mtime)) def touch_file(path, context): content = context.get('article', context.get('page')) page = context.get('articles_page') dates = context.get('dates') if content and hasattr(content, 'date'): set_file_utime(path, content.date) elif page: set_file_utime(path, max(x.date for x in page.object_list)) elif dates: set_file_utime(path, max(x.date for x in dates)) def touch_feed(path, context, feed): set_file_utime(path, max(x['pubdate'] for x in feed.items)) def register(): signals.content_written.connect(touch_file) signals.feed_written.connect(touch_feed)
<commit_before>from pelican import signals import logging import os import time logger = logging.getLogger(__name__) def set_file_utime(path, datetime): mtime = time.mktime(datetime.timetuple()) logger.info('touching %s', path) os.utime(path, (mtime, mtime)) def touch_file(path, context): content = context.get('article', context.get('page')) page = context.get('articles_page') dates = context.get('dates') if content and hasattr(content, 'date'): set_file_utime(path, content.date) elif page: set_file_utime(path, max(x.date for x in page.object_list)) elif dates: set_file_utime(path, max(x.date for x in dates)) def register(): signals.content_written.connect(touch_file) <commit_msg>Update timestamps of generated feeds as well<commit_after>from pelican import signals import logging import os import time logger = logging.getLogger(__name__) def set_file_utime(path, datetime): mtime = time.mktime(datetime.timetuple()) logger.info('touching %s', path) os.utime(path, (mtime, mtime)) def touch_file(path, context): content = context.get('article', context.get('page')) page = context.get('articles_page') dates = context.get('dates') if content and hasattr(content, 'date'): set_file_utime(path, content.date) elif page: set_file_utime(path, max(x.date for x in page.object_list)) elif dates: set_file_utime(path, max(x.date for x in dates)) def touch_feed(path, context, feed): set_file_utime(path, max(x['pubdate'] for x in feed.items)) def register(): signals.content_written.connect(touch_file) signals.feed_written.connect(touch_feed)
99c8024b5568650d4efc9de197b48d93bb099267
eulfedora/__init__.py
eulfedora/__init__.py
# file eulfedora/__init__.py # # Copyright 2010,2011 Emory University Libraries # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __version_info__ = (1, 1, 0, 'dev') # Dot-connect all but the last. Last is dash-connected if not None. __version__ = '.'.join([str(i) for i in __version_info__[:-1]]) if __version_info__[-1] is not None: __version__ += ('-%s' % (__version_info__[-1],))
# file eulfedora/__init__.py # # Copyright 2010,2011 Emory University Libraries # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __version_info__ = (1, 1, 0, None) # Dot-connect all but the last. Last is dash-connected if not None. __version__ = '.'.join([str(i) for i in __version_info__[:-1]]) if __version_info__[-1] is not None: __version__ += ('-%s' % (__version_info__[-1],))
Set version to 1.1.0 final
Set version to 1.1.0 final
Python
apache-2.0
bodleian/eulfedora,WSULib/eulfedora
# file eulfedora/__init__.py # # Copyright 2010,2011 Emory University Libraries # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __version_info__ = (1, 1, 0, 'dev') # Dot-connect all but the last. Last is dash-connected if not None. __version__ = '.'.join([str(i) for i in __version_info__[:-1]]) if __version_info__[-1] is not None: __version__ += ('-%s' % (__version_info__[-1],)) Set version to 1.1.0 final
# file eulfedora/__init__.py # # Copyright 2010,2011 Emory University Libraries # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __version_info__ = (1, 1, 0, None) # Dot-connect all but the last. Last is dash-connected if not None. __version__ = '.'.join([str(i) for i in __version_info__[:-1]]) if __version_info__[-1] is not None: __version__ += ('-%s' % (__version_info__[-1],))
<commit_before># file eulfedora/__init__.py # # Copyright 2010,2011 Emory University Libraries # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __version_info__ = (1, 1, 0, 'dev') # Dot-connect all but the last. Last is dash-connected if not None. __version__ = '.'.join([str(i) for i in __version_info__[:-1]]) if __version_info__[-1] is not None: __version__ += ('-%s' % (__version_info__[-1],)) <commit_msg>Set version to 1.1.0 final<commit_after>
# file eulfedora/__init__.py # # Copyright 2010,2011 Emory University Libraries # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __version_info__ = (1, 1, 0, None) # Dot-connect all but the last. Last is dash-connected if not None. __version__ = '.'.join([str(i) for i in __version_info__[:-1]]) if __version_info__[-1] is not None: __version__ += ('-%s' % (__version_info__[-1],))
# file eulfedora/__init__.py # # Copyright 2010,2011 Emory University Libraries # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __version_info__ = (1, 1, 0, 'dev') # Dot-connect all but the last. Last is dash-connected if not None. __version__ = '.'.join([str(i) for i in __version_info__[:-1]]) if __version_info__[-1] is not None: __version__ += ('-%s' % (__version_info__[-1],)) Set version to 1.1.0 final# file eulfedora/__init__.py # # Copyright 2010,2011 Emory University Libraries # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __version_info__ = (1, 1, 0, None) # Dot-connect all but the last. Last is dash-connected if not None. __version__ = '.'.join([str(i) for i in __version_info__[:-1]]) if __version_info__[-1] is not None: __version__ += ('-%s' % (__version_info__[-1],))
<commit_before># file eulfedora/__init__.py # # Copyright 2010,2011 Emory University Libraries # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __version_info__ = (1, 1, 0, 'dev') # Dot-connect all but the last. Last is dash-connected if not None. __version__ = '.'.join([str(i) for i in __version_info__[:-1]]) if __version_info__[-1] is not None: __version__ += ('-%s' % (__version_info__[-1],)) <commit_msg>Set version to 1.1.0 final<commit_after># file eulfedora/__init__.py # # Copyright 2010,2011 Emory University Libraries # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __version_info__ = (1, 1, 0, None) # Dot-connect all but the last. Last is dash-connected if not None. __version__ = '.'.join([str(i) for i in __version_info__[:-1]]) if __version_info__[-1] is not None: __version__ += ('-%s' % (__version_info__[-1],))
cbd0855feb9164182b58b36ee487716fd5a33689
forms/subject.py
forms/subject.py
from flask_wtf import FlaskForm from wtforms import StringField from wtforms.validators import DataRequired, Length class AddSubjectForm(FlaskForm): code = StringField('Code', validators=[DataRequired()]) name = StringField('Name', validators=[DataRequired()]) major = StringField('Major') grade = StringField('Grade') weight = StringField('Weight') category = StringField('Category') curriculum = StringField('Curriculum') alias = StringField('Alias')
from flask_wtf import FlaskForm from wtforms import StringField from wtforms.validators import DataRequired class AddSubjectForm(FlaskForm): code = StringField('Code', validators=[DataRequired()]) name = StringField('Name', validators=[DataRequired()]) major = StringField('Major') grade = StringField('Grade') weight = StringField('Weight') category = StringField('Category') curriculum = StringField('Curriculum') alias = StringField('Alias')
Remove Unused Length imported from wtforms.validators, pylint.
Remove Unused Length imported from wtforms.validators, pylint.
Python
mit
openedoo/module_employee,openedoo/module_employee,openedoo/module_employee
from flask_wtf import FlaskForm from wtforms import StringField from wtforms.validators import DataRequired, Length class AddSubjectForm(FlaskForm): code = StringField('Code', validators=[DataRequired()]) name = StringField('Name', validators=[DataRequired()]) major = StringField('Major') grade = StringField('Grade') weight = StringField('Weight') category = StringField('Category') curriculum = StringField('Curriculum') alias = StringField('Alias') Remove Unused Length imported from wtforms.validators, pylint.
from flask_wtf import FlaskForm from wtforms import StringField from wtforms.validators import DataRequired class AddSubjectForm(FlaskForm): code = StringField('Code', validators=[DataRequired()]) name = StringField('Name', validators=[DataRequired()]) major = StringField('Major') grade = StringField('Grade') weight = StringField('Weight') category = StringField('Category') curriculum = StringField('Curriculum') alias = StringField('Alias')
<commit_before>from flask_wtf import FlaskForm from wtforms import StringField from wtforms.validators import DataRequired, Length class AddSubjectForm(FlaskForm): code = StringField('Code', validators=[DataRequired()]) name = StringField('Name', validators=[DataRequired()]) major = StringField('Major') grade = StringField('Grade') weight = StringField('Weight') category = StringField('Category') curriculum = StringField('Curriculum') alias = StringField('Alias') <commit_msg>Remove Unused Length imported from wtforms.validators, pylint.<commit_after>
from flask_wtf import FlaskForm from wtforms import StringField from wtforms.validators import DataRequired class AddSubjectForm(FlaskForm): code = StringField('Code', validators=[DataRequired()]) name = StringField('Name', validators=[DataRequired()]) major = StringField('Major') grade = StringField('Grade') weight = StringField('Weight') category = StringField('Category') curriculum = StringField('Curriculum') alias = StringField('Alias')
from flask_wtf import FlaskForm from wtforms import StringField from wtforms.validators import DataRequired, Length class AddSubjectForm(FlaskForm): code = StringField('Code', validators=[DataRequired()]) name = StringField('Name', validators=[DataRequired()]) major = StringField('Major') grade = StringField('Grade') weight = StringField('Weight') category = StringField('Category') curriculum = StringField('Curriculum') alias = StringField('Alias') Remove Unused Length imported from wtforms.validators, pylint.from flask_wtf import FlaskForm from wtforms import StringField from wtforms.validators import DataRequired class AddSubjectForm(FlaskForm): code = StringField('Code', validators=[DataRequired()]) name = StringField('Name', validators=[DataRequired()]) major = StringField('Major') grade = StringField('Grade') weight = StringField('Weight') category = StringField('Category') curriculum = StringField('Curriculum') alias = StringField('Alias')
<commit_before>from flask_wtf import FlaskForm from wtforms import StringField from wtforms.validators import DataRequired, Length class AddSubjectForm(FlaskForm): code = StringField('Code', validators=[DataRequired()]) name = StringField('Name', validators=[DataRequired()]) major = StringField('Major') grade = StringField('Grade') weight = StringField('Weight') category = StringField('Category') curriculum = StringField('Curriculum') alias = StringField('Alias') <commit_msg>Remove Unused Length imported from wtforms.validators, pylint.<commit_after>from flask_wtf import FlaskForm from wtforms import StringField from wtforms.validators import DataRequired class AddSubjectForm(FlaskForm): code = StringField('Code', validators=[DataRequired()]) name = StringField('Name', validators=[DataRequired()]) major = StringField('Major') grade = StringField('Grade') weight = StringField('Weight') category = StringField('Category') curriculum = StringField('Curriculum') alias = StringField('Alias')
394262effa690eda51ba9ee29aa86d98c683e17d
foundry/tests.py
foundry/tests.py
from django.core import management from django.test import TestCase from django.contrib.contenttypes.models import ContentType from post.models import Post from foundry.models import Member, Listing class TestCase(TestCase): def setUp(self): # Post-syncdb steps management.call_command('migrate', interactive=False) management.call_command('load_photosizes', interactive=False) # Editor self.editor, dc = Member.objects.get_or_create( username='editor', email='editor@test.com' ) # Posts for i in range(1, 5): post = Post.objects.create( title='Post %s' % i, content='<b>aaa</b>', owner=self.editor, state='published', ) post.sites = [1] post.save() setattr(self, 'post%s' % i, post) def test_listing(self): content_type = ContentType.objects.get(app_label='post', model='post') posts = Listing.objects.create( title='Posts', count=0, style='VerticalThumbnail', ) posts.content_type = [content_type] posts.sites = [1] posts.save() self.failUnless(self.post1.modelbase_obj in posts.queryset.all())
from django.core import management from django.utils import unittest from django.contrib.contenttypes.models import ContentType from django.test.client import Client from post.models import Post from foundry.models import Member, Listing class TestCase(unittest.TestCase): def setUp(self): self.client = Client() # Post-syncdb steps management.call_command('migrate', interactive=False) management.call_command('load_photosizes', interactive=False) # Editor self.editor, dc = Member.objects.get_or_create( username='editor', email='editor@test.com' ) # Posts for i in range(1, 5): post = Post.objects.create( title='Post %s' % i, content='<b>aaa</b>', owner=self.editor, state='published', ) post.sites = [1] post.save() setattr(self, 'post%s' % i, post) def test_listing(self): content_type = ContentType.objects.get(app_label='post', model='post') posts = Listing.objects.create( title='Posts', count=0, style='VerticalThumbnail', ) posts.content_type = [content_type] posts.sites = [1] posts.save() self.failUnless(self.post1.modelbase_obj in posts.queryset.all()) def test_pages(self): response =self.client.get('/login') self.assertEqual(response.status_code, 200) self.failIf(response.content.find('<form') == -1)
Add test to show login form is broken
Add test to show login form is broken
Python
bsd-3-clause
praekelt/jmbo-foundry,praekelt/jmbo-foundry,praekelt/jmbo-foundry
from django.core import management from django.test import TestCase from django.contrib.contenttypes.models import ContentType from post.models import Post from foundry.models import Member, Listing class TestCase(TestCase): def setUp(self): # Post-syncdb steps management.call_command('migrate', interactive=False) management.call_command('load_photosizes', interactive=False) # Editor self.editor, dc = Member.objects.get_or_create( username='editor', email='editor@test.com' ) # Posts for i in range(1, 5): post = Post.objects.create( title='Post %s' % i, content='<b>aaa</b>', owner=self.editor, state='published', ) post.sites = [1] post.save() setattr(self, 'post%s' % i, post) def test_listing(self): content_type = ContentType.objects.get(app_label='post', model='post') posts = Listing.objects.create( title='Posts', count=0, style='VerticalThumbnail', ) posts.content_type = [content_type] posts.sites = [1] posts.save() self.failUnless(self.post1.modelbase_obj in posts.queryset.all()) Add test to show login form is broken
from django.core import management from django.utils import unittest from django.contrib.contenttypes.models import ContentType from django.test.client import Client from post.models import Post from foundry.models import Member, Listing class TestCase(unittest.TestCase): def setUp(self): self.client = Client() # Post-syncdb steps management.call_command('migrate', interactive=False) management.call_command('load_photosizes', interactive=False) # Editor self.editor, dc = Member.objects.get_or_create( username='editor', email='editor@test.com' ) # Posts for i in range(1, 5): post = Post.objects.create( title='Post %s' % i, content='<b>aaa</b>', owner=self.editor, state='published', ) post.sites = [1] post.save() setattr(self, 'post%s' % i, post) def test_listing(self): content_type = ContentType.objects.get(app_label='post', model='post') posts = Listing.objects.create( title='Posts', count=0, style='VerticalThumbnail', ) posts.content_type = [content_type] posts.sites = [1] posts.save() self.failUnless(self.post1.modelbase_obj in posts.queryset.all()) def test_pages(self): response =self.client.get('/login') self.assertEqual(response.status_code, 200) self.failIf(response.content.find('<form') == -1)
<commit_before>from django.core import management from django.test import TestCase from django.contrib.contenttypes.models import ContentType from post.models import Post from foundry.models import Member, Listing class TestCase(TestCase): def setUp(self): # Post-syncdb steps management.call_command('migrate', interactive=False) management.call_command('load_photosizes', interactive=False) # Editor self.editor, dc = Member.objects.get_or_create( username='editor', email='editor@test.com' ) # Posts for i in range(1, 5): post = Post.objects.create( title='Post %s' % i, content='<b>aaa</b>', owner=self.editor, state='published', ) post.sites = [1] post.save() setattr(self, 'post%s' % i, post) def test_listing(self): content_type = ContentType.objects.get(app_label='post', model='post') posts = Listing.objects.create( title='Posts', count=0, style='VerticalThumbnail', ) posts.content_type = [content_type] posts.sites = [1] posts.save() self.failUnless(self.post1.modelbase_obj in posts.queryset.all()) <commit_msg>Add test to show login form is broken<commit_after>
from django.core import management from django.utils import unittest from django.contrib.contenttypes.models import ContentType from django.test.client import Client from post.models import Post from foundry.models import Member, Listing class TestCase(unittest.TestCase): def setUp(self): self.client = Client() # Post-syncdb steps management.call_command('migrate', interactive=False) management.call_command('load_photosizes', interactive=False) # Editor self.editor, dc = Member.objects.get_or_create( username='editor', email='editor@test.com' ) # Posts for i in range(1, 5): post = Post.objects.create( title='Post %s' % i, content='<b>aaa</b>', owner=self.editor, state='published', ) post.sites = [1] post.save() setattr(self, 'post%s' % i, post) def test_listing(self): content_type = ContentType.objects.get(app_label='post', model='post') posts = Listing.objects.create( title='Posts', count=0, style='VerticalThumbnail', ) posts.content_type = [content_type] posts.sites = [1] posts.save() self.failUnless(self.post1.modelbase_obj in posts.queryset.all()) def test_pages(self): response =self.client.get('/login') self.assertEqual(response.status_code, 200) self.failIf(response.content.find('<form') == -1)
from django.core import management from django.test import TestCase from django.contrib.contenttypes.models import ContentType from post.models import Post from foundry.models import Member, Listing class TestCase(TestCase): def setUp(self): # Post-syncdb steps management.call_command('migrate', interactive=False) management.call_command('load_photosizes', interactive=False) # Editor self.editor, dc = Member.objects.get_or_create( username='editor', email='editor@test.com' ) # Posts for i in range(1, 5): post = Post.objects.create( title='Post %s' % i, content='<b>aaa</b>', owner=self.editor, state='published', ) post.sites = [1] post.save() setattr(self, 'post%s' % i, post) def test_listing(self): content_type = ContentType.objects.get(app_label='post', model='post') posts = Listing.objects.create( title='Posts', count=0, style='VerticalThumbnail', ) posts.content_type = [content_type] posts.sites = [1] posts.save() self.failUnless(self.post1.modelbase_obj in posts.queryset.all()) Add test to show login form is brokenfrom django.core import management from django.utils import unittest from django.contrib.contenttypes.models import ContentType from django.test.client import Client from post.models import Post from foundry.models import Member, Listing class TestCase(unittest.TestCase): def setUp(self): self.client = Client() # Post-syncdb steps management.call_command('migrate', interactive=False) management.call_command('load_photosizes', interactive=False) # Editor self.editor, dc = Member.objects.get_or_create( username='editor', email='editor@test.com' ) # Posts for i in range(1, 5): post = Post.objects.create( title='Post %s' % i, content='<b>aaa</b>', owner=self.editor, state='published', ) post.sites = [1] post.save() setattr(self, 'post%s' % i, post) def test_listing(self): content_type = ContentType.objects.get(app_label='post', model='post') posts = Listing.objects.create( title='Posts', count=0, style='VerticalThumbnail', ) posts.content_type = [content_type] posts.sites = [1] posts.save() self.failUnless(self.post1.modelbase_obj in posts.queryset.all()) def test_pages(self): response =self.client.get('/login') self.assertEqual(response.status_code, 200) self.failIf(response.content.find('<form') == -1)
<commit_before>from django.core import management from django.test import TestCase from django.contrib.contenttypes.models import ContentType from post.models import Post from foundry.models import Member, Listing class TestCase(TestCase): def setUp(self): # Post-syncdb steps management.call_command('migrate', interactive=False) management.call_command('load_photosizes', interactive=False) # Editor self.editor, dc = Member.objects.get_or_create( username='editor', email='editor@test.com' ) # Posts for i in range(1, 5): post = Post.objects.create( title='Post %s' % i, content='<b>aaa</b>', owner=self.editor, state='published', ) post.sites = [1] post.save() setattr(self, 'post%s' % i, post) def test_listing(self): content_type = ContentType.objects.get(app_label='post', model='post') posts = Listing.objects.create( title='Posts', count=0, style='VerticalThumbnail', ) posts.content_type = [content_type] posts.sites = [1] posts.save() self.failUnless(self.post1.modelbase_obj in posts.queryset.all()) <commit_msg>Add test to show login form is broken<commit_after>from django.core import management from django.utils import unittest from django.contrib.contenttypes.models import ContentType from django.test.client import Client from post.models import Post from foundry.models import Member, Listing class TestCase(unittest.TestCase): def setUp(self): self.client = Client() # Post-syncdb steps management.call_command('migrate', interactive=False) management.call_command('load_photosizes', interactive=False) # Editor self.editor, dc = Member.objects.get_or_create( username='editor', email='editor@test.com' ) # Posts for i in range(1, 5): post = Post.objects.create( title='Post %s' % i, content='<b>aaa</b>', owner=self.editor, state='published', ) post.sites = [1] post.save() setattr(self, 'post%s' % i, post) def test_listing(self): content_type = ContentType.objects.get(app_label='post', model='post') posts = Listing.objects.create( title='Posts', count=0, style='VerticalThumbnail', ) posts.content_type = [content_type] posts.sites = [1] posts.save() self.failUnless(self.post1.modelbase_obj in posts.queryset.all()) def test_pages(self): response =self.client.get('/login') self.assertEqual(response.status_code, 200) self.failIf(response.content.find('<form') == -1)
332452cf7ccd6d3ee583be9a6aac27b14771263f
source/services/omdb_service.py
source/services/omdb_service.py
import requests from bs4 import BeautifulSoup from source.models.rt_rating import RTRating class OmdbService: __API_URL = 'http://www.omdbapi.com/?' def __init__(self, movie_id): self.id = movie_id def get_rt_rating(self): payload = {'i': self.id, 'plot': 'short', 'r': 'json', 'tomatoes': 'true'} response = requests.post(self.__API_URL, params=payload) movie_info = response.json() ratings = [] ratings.append(movie_info['tomatoMeter']) ratings.append(movie_info['tomatoUserMeter']) return RTRating(ratings)
import requests from bs4 import BeautifulSoup from source.models.rt_rating import RTRating class OmdbService: __API_URL = 'http://www.omdbapi.com/?' def __init__(self, movie_id): self.id = movie_id def get_rt_rating(self): payload = {'i': self.id, 'plot': 'short', 'r': 'json', 'tomatoes': 'true'} response = requests.post(self.__API_URL, params=payload) movie_info = response.json() scores = [] scores.append(movie_info['tomatoMeter']) scores.append(movie_info['tomatoUserMeter']) rt_rating = RTRating(scores) rt_rating.link = movie_info['tomatoURL'] return rt_rating
Add url to RTRating object
Add url to RTRating object
Python
mit
jeremyrea/caterblu,jeremyrea/caterblu,jeremyrea/caterblu,jeremyrea/caterblu
import requests from bs4 import BeautifulSoup from source.models.rt_rating import RTRating class OmdbService: __API_URL = 'http://www.omdbapi.com/?' def __init__(self, movie_id): self.id = movie_id def get_rt_rating(self): payload = {'i': self.id, 'plot': 'short', 'r': 'json', 'tomatoes': 'true'} response = requests.post(self.__API_URL, params=payload) movie_info = response.json() ratings = [] ratings.append(movie_info['tomatoMeter']) ratings.append(movie_info['tomatoUserMeter']) return RTRating(ratings) Add url to RTRating object
import requests from bs4 import BeautifulSoup from source.models.rt_rating import RTRating class OmdbService: __API_URL = 'http://www.omdbapi.com/?' def __init__(self, movie_id): self.id = movie_id def get_rt_rating(self): payload = {'i': self.id, 'plot': 'short', 'r': 'json', 'tomatoes': 'true'} response = requests.post(self.__API_URL, params=payload) movie_info = response.json() scores = [] scores.append(movie_info['tomatoMeter']) scores.append(movie_info['tomatoUserMeter']) rt_rating = RTRating(scores) rt_rating.link = movie_info['tomatoURL'] return rt_rating
<commit_before>import requests from bs4 import BeautifulSoup from source.models.rt_rating import RTRating class OmdbService: __API_URL = 'http://www.omdbapi.com/?' def __init__(self, movie_id): self.id = movie_id def get_rt_rating(self): payload = {'i': self.id, 'plot': 'short', 'r': 'json', 'tomatoes': 'true'} response = requests.post(self.__API_URL, params=payload) movie_info = response.json() ratings = [] ratings.append(movie_info['tomatoMeter']) ratings.append(movie_info['tomatoUserMeter']) return RTRating(ratings) <commit_msg>Add url to RTRating object<commit_after>
import requests from bs4 import BeautifulSoup from source.models.rt_rating import RTRating class OmdbService: __API_URL = 'http://www.omdbapi.com/?' def __init__(self, movie_id): self.id = movie_id def get_rt_rating(self): payload = {'i': self.id, 'plot': 'short', 'r': 'json', 'tomatoes': 'true'} response = requests.post(self.__API_URL, params=payload) movie_info = response.json() scores = [] scores.append(movie_info['tomatoMeter']) scores.append(movie_info['tomatoUserMeter']) rt_rating = RTRating(scores) rt_rating.link = movie_info['tomatoURL'] return rt_rating
import requests from bs4 import BeautifulSoup from source.models.rt_rating import RTRating class OmdbService: __API_URL = 'http://www.omdbapi.com/?' def __init__(self, movie_id): self.id = movie_id def get_rt_rating(self): payload = {'i': self.id, 'plot': 'short', 'r': 'json', 'tomatoes': 'true'} response = requests.post(self.__API_URL, params=payload) movie_info = response.json() ratings = [] ratings.append(movie_info['tomatoMeter']) ratings.append(movie_info['tomatoUserMeter']) return RTRating(ratings) Add url to RTRating objectimport requests from bs4 import BeautifulSoup from source.models.rt_rating import RTRating class OmdbService: __API_URL = 'http://www.omdbapi.com/?' def __init__(self, movie_id): self.id = movie_id def get_rt_rating(self): payload = {'i': self.id, 'plot': 'short', 'r': 'json', 'tomatoes': 'true'} response = requests.post(self.__API_URL, params=payload) movie_info = response.json() scores = [] scores.append(movie_info['tomatoMeter']) scores.append(movie_info['tomatoUserMeter']) rt_rating = RTRating(scores) rt_rating.link = movie_info['tomatoURL'] return rt_rating
<commit_before>import requests from bs4 import BeautifulSoup from source.models.rt_rating import RTRating class OmdbService: __API_URL = 'http://www.omdbapi.com/?' def __init__(self, movie_id): self.id = movie_id def get_rt_rating(self): payload = {'i': self.id, 'plot': 'short', 'r': 'json', 'tomatoes': 'true'} response = requests.post(self.__API_URL, params=payload) movie_info = response.json() ratings = [] ratings.append(movie_info['tomatoMeter']) ratings.append(movie_info['tomatoUserMeter']) return RTRating(ratings) <commit_msg>Add url to RTRating object<commit_after>import requests from bs4 import BeautifulSoup from source.models.rt_rating import RTRating class OmdbService: __API_URL = 'http://www.omdbapi.com/?' def __init__(self, movie_id): self.id = movie_id def get_rt_rating(self): payload = {'i': self.id, 'plot': 'short', 'r': 'json', 'tomatoes': 'true'} response = requests.post(self.__API_URL, params=payload) movie_info = response.json() scores = [] scores.append(movie_info['tomatoMeter']) scores.append(movie_info['tomatoUserMeter']) rt_rating = RTRating(scores) rt_rating.link = movie_info['tomatoURL'] return rt_rating
7ea80522ae56c314b2230fe95d3b5ae939181d40
cactus/logger.py
cactus/logger.py
import os import logging import types import json import six class JsonFormatter(logging.Formatter): def format(self, record): data = { "level": record.levelno, "levelName": record.levelname, "msg": logging.Formatter.format(self, record) } if type(record.args) is types.DictType: for k, v in six.iteritems(record.args): data[k] = v return json.dumps(data) def setup_logging(verbose, quiet): logger = logging.getLogger() handler = logging.StreamHandler() if os.environ.get('DESKTOPAPP'): log_level = logging.INFO handler.setFormatter(JsonFormatter()) else: from colorlog import ColoredFormatter formatter = ColoredFormatter( "%(log_color)s%(message)s", datefmt=None, reset=True, log_colors={ 'DEBUG': 'white', 'INFO': 'white', 'WARNING': 'bold_yellow', 'ERROR': 'bold_red', 'CRITICAL': 'bold_red', } ) if quiet: log_level = logging.WARNING elif verbose: log_level = logging.DEBUG else: log_level = logging.INFO handler.setFormatter(formatter) logger.setLevel(log_level) for h in logger.handlers: logger.removeHandler(h) logger.addHandler(handler)
import os import logging import types import json import six class JsonFormatter(logging.Formatter): def format(self, record): data = { "level": record.levelno, "levelName": record.levelname, "msg": logging.Formatter.format(self, record) } if type(record.args) is types.DictType: for k, v in six.iteritems(record.args): data[k] = v return json.dumps(data) def setup_logging(verbose, quiet): logger = logging.getLogger() handler = logging.StreamHandler() if os.environ.get('DESKTOPAPP'): log_level = logging.INFO handler.setFormatter(JsonFormatter()) else: from colorlog import ColoredFormatter formatter = ColoredFormatter( "%(log_color)s%(message)s%(reset)s", datefmt=None, reset=True, log_colors={ 'DEBUG': 'cyan', 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'bold_red', } ) if quiet: log_level = logging.WARNING elif verbose: log_level = logging.DEBUG else: log_level = logging.INFO handler.setFormatter(formatter) logger.setLevel(log_level) for h in logger.handlers: logger.removeHandler(h) logger.addHandler(handler)
Use common colors, Reset after message.
Use common colors, Reset after message. Switch to colors that don't mess up on using light color schemes.
Python
bsd-3-clause
koenbok/Cactus,koenbok/Cactus,eudicots/Cactus,koenbok/Cactus,eudicots/Cactus,eudicots/Cactus
import os import logging import types import json import six class JsonFormatter(logging.Formatter): def format(self, record): data = { "level": record.levelno, "levelName": record.levelname, "msg": logging.Formatter.format(self, record) } if type(record.args) is types.DictType: for k, v in six.iteritems(record.args): data[k] = v return json.dumps(data) def setup_logging(verbose, quiet): logger = logging.getLogger() handler = logging.StreamHandler() if os.environ.get('DESKTOPAPP'): log_level = logging.INFO handler.setFormatter(JsonFormatter()) else: from colorlog import ColoredFormatter formatter = ColoredFormatter( "%(log_color)s%(message)s", datefmt=None, reset=True, log_colors={ 'DEBUG': 'white', 'INFO': 'white', 'WARNING': 'bold_yellow', 'ERROR': 'bold_red', 'CRITICAL': 'bold_red', } ) if quiet: log_level = logging.WARNING elif verbose: log_level = logging.DEBUG else: log_level = logging.INFO handler.setFormatter(formatter) logger.setLevel(log_level) for h in logger.handlers: logger.removeHandler(h) logger.addHandler(handler) Use common colors, Reset after message. Switch to colors that don't mess up on using light color schemes.
import os import logging import types import json import six class JsonFormatter(logging.Formatter): def format(self, record): data = { "level": record.levelno, "levelName": record.levelname, "msg": logging.Formatter.format(self, record) } if type(record.args) is types.DictType: for k, v in six.iteritems(record.args): data[k] = v return json.dumps(data) def setup_logging(verbose, quiet): logger = logging.getLogger() handler = logging.StreamHandler() if os.environ.get('DESKTOPAPP'): log_level = logging.INFO handler.setFormatter(JsonFormatter()) else: from colorlog import ColoredFormatter formatter = ColoredFormatter( "%(log_color)s%(message)s%(reset)s", datefmt=None, reset=True, log_colors={ 'DEBUG': 'cyan', 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'bold_red', } ) if quiet: log_level = logging.WARNING elif verbose: log_level = logging.DEBUG else: log_level = logging.INFO handler.setFormatter(formatter) logger.setLevel(log_level) for h in logger.handlers: logger.removeHandler(h) logger.addHandler(handler)
<commit_before>import os import logging import types import json import six class JsonFormatter(logging.Formatter): def format(self, record): data = { "level": record.levelno, "levelName": record.levelname, "msg": logging.Formatter.format(self, record) } if type(record.args) is types.DictType: for k, v in six.iteritems(record.args): data[k] = v return json.dumps(data) def setup_logging(verbose, quiet): logger = logging.getLogger() handler = logging.StreamHandler() if os.environ.get('DESKTOPAPP'): log_level = logging.INFO handler.setFormatter(JsonFormatter()) else: from colorlog import ColoredFormatter formatter = ColoredFormatter( "%(log_color)s%(message)s", datefmt=None, reset=True, log_colors={ 'DEBUG': 'white', 'INFO': 'white', 'WARNING': 'bold_yellow', 'ERROR': 'bold_red', 'CRITICAL': 'bold_red', } ) if quiet: log_level = logging.WARNING elif verbose: log_level = logging.DEBUG else: log_level = logging.INFO handler.setFormatter(formatter) logger.setLevel(log_level) for h in logger.handlers: logger.removeHandler(h) logger.addHandler(handler) <commit_msg>Use common colors, Reset after message. Switch to colors that don't mess up on using light color schemes.<commit_after>
import os import logging import types import json import six class JsonFormatter(logging.Formatter): def format(self, record): data = { "level": record.levelno, "levelName": record.levelname, "msg": logging.Formatter.format(self, record) } if type(record.args) is types.DictType: for k, v in six.iteritems(record.args): data[k] = v return json.dumps(data) def setup_logging(verbose, quiet): logger = logging.getLogger() handler = logging.StreamHandler() if os.environ.get('DESKTOPAPP'): log_level = logging.INFO handler.setFormatter(JsonFormatter()) else: from colorlog import ColoredFormatter formatter = ColoredFormatter( "%(log_color)s%(message)s%(reset)s", datefmt=None, reset=True, log_colors={ 'DEBUG': 'cyan', 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'bold_red', } ) if quiet: log_level = logging.WARNING elif verbose: log_level = logging.DEBUG else: log_level = logging.INFO handler.setFormatter(formatter) logger.setLevel(log_level) for h in logger.handlers: logger.removeHandler(h) logger.addHandler(handler)
import os import logging import types import json import six class JsonFormatter(logging.Formatter): def format(self, record): data = { "level": record.levelno, "levelName": record.levelname, "msg": logging.Formatter.format(self, record) } if type(record.args) is types.DictType: for k, v in six.iteritems(record.args): data[k] = v return json.dumps(data) def setup_logging(verbose, quiet): logger = logging.getLogger() handler = logging.StreamHandler() if os.environ.get('DESKTOPAPP'): log_level = logging.INFO handler.setFormatter(JsonFormatter()) else: from colorlog import ColoredFormatter formatter = ColoredFormatter( "%(log_color)s%(message)s", datefmt=None, reset=True, log_colors={ 'DEBUG': 'white', 'INFO': 'white', 'WARNING': 'bold_yellow', 'ERROR': 'bold_red', 'CRITICAL': 'bold_red', } ) if quiet: log_level = logging.WARNING elif verbose: log_level = logging.DEBUG else: log_level = logging.INFO handler.setFormatter(formatter) logger.setLevel(log_level) for h in logger.handlers: logger.removeHandler(h) logger.addHandler(handler) Use common colors, Reset after message. Switch to colors that don't mess up on using light color schemes.import os import logging import types import json import six class JsonFormatter(logging.Formatter): def format(self, record): data = { "level": record.levelno, "levelName": record.levelname, "msg": logging.Formatter.format(self, record) } if type(record.args) is types.DictType: for k, v in six.iteritems(record.args): data[k] = v return json.dumps(data) def setup_logging(verbose, quiet): logger = logging.getLogger() handler = logging.StreamHandler() if os.environ.get('DESKTOPAPP'): log_level = logging.INFO handler.setFormatter(JsonFormatter()) else: from colorlog import ColoredFormatter formatter = ColoredFormatter( "%(log_color)s%(message)s%(reset)s", datefmt=None, reset=True, log_colors={ 'DEBUG': 'cyan', 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'bold_red', } ) if quiet: log_level = logging.WARNING elif verbose: log_level = logging.DEBUG else: log_level = logging.INFO handler.setFormatter(formatter) logger.setLevel(log_level) for h in logger.handlers: logger.removeHandler(h) logger.addHandler(handler)
<commit_before>import os import logging import types import json import six class JsonFormatter(logging.Formatter): def format(self, record): data = { "level": record.levelno, "levelName": record.levelname, "msg": logging.Formatter.format(self, record) } if type(record.args) is types.DictType: for k, v in six.iteritems(record.args): data[k] = v return json.dumps(data) def setup_logging(verbose, quiet): logger = logging.getLogger() handler = logging.StreamHandler() if os.environ.get('DESKTOPAPP'): log_level = logging.INFO handler.setFormatter(JsonFormatter()) else: from colorlog import ColoredFormatter formatter = ColoredFormatter( "%(log_color)s%(message)s", datefmt=None, reset=True, log_colors={ 'DEBUG': 'white', 'INFO': 'white', 'WARNING': 'bold_yellow', 'ERROR': 'bold_red', 'CRITICAL': 'bold_red', } ) if quiet: log_level = logging.WARNING elif verbose: log_level = logging.DEBUG else: log_level = logging.INFO handler.setFormatter(formatter) logger.setLevel(log_level) for h in logger.handlers: logger.removeHandler(h) logger.addHandler(handler) <commit_msg>Use common colors, Reset after message. Switch to colors that don't mess up on using light color schemes.<commit_after>import os import logging import types import json import six class JsonFormatter(logging.Formatter): def format(self, record): data = { "level": record.levelno, "levelName": record.levelname, "msg": logging.Formatter.format(self, record) } if type(record.args) is types.DictType: for k, v in six.iteritems(record.args): data[k] = v return json.dumps(data) def setup_logging(verbose, quiet): logger = logging.getLogger() handler = logging.StreamHandler() if os.environ.get('DESKTOPAPP'): log_level = logging.INFO handler.setFormatter(JsonFormatter()) else: from colorlog import ColoredFormatter formatter = ColoredFormatter( "%(log_color)s%(message)s%(reset)s", datefmt=None, reset=True, log_colors={ 'DEBUG': 'cyan', 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'bold_red', } ) if quiet: log_level = logging.WARNING elif verbose: log_level = logging.DEBUG else: log_level = logging.INFO handler.setFormatter(formatter) logger.setLevel(log_level) for h in logger.handlers: logger.removeHandler(h) logger.addHandler(handler)