Datasets:

commit
stringlengths
40
40
old_file
stringlengths
4
118
new_file
stringlengths
4
118
old_contents
stringlengths
10
2.94k
new_contents
stringlengths
21
3.18k
subject
stringlengths
16
444
message
stringlengths
17
2.63k
lang
stringclasses
1 value
license
stringclasses
13 values
repos
stringlengths
5
43k
ndiff
stringlengths
51
3.32k
instruction
stringlengths
16
444
content
stringlengths
133
4.32k
b501ee5dc2a41bf51f9f91c29501792338bf7269
automatron/backend/controller.py
automatron/backend/controller.py
from automatron.backend.plugin import PluginManager from automatron.controller.controller import IAutomatronClientActions from automatron.core.controller import BaseController class BackendController(BaseController): def __init__(self, config_file): BaseController.__init__(self, config_file) self.plugins = None def prepareService(self): # Load plugins self.plugins = PluginManager(self) def __getattr__(self, item): def proxy(*args): self.plugins.emit(IAutomatronClientActions[item], *args) return proxy
from functools import partial from automatron.backend.plugin import PluginManager from automatron.controller.controller import IAutomatronClientActions from automatron.core.controller import BaseController class BackendController(BaseController): def __init__(self, config_file): BaseController.__init__(self, config_file) self.plugins = None def prepareService(self): # Load plugins self.plugins = PluginManager(self) def __getattr__(self, item): return partial(self.plugins.emit, IAutomatronClientActions[item])
Use functools.partial for client action proxy.
Use functools.partial for client action proxy.
Python
mit
automatron/automatron
+ from functools import partial from automatron.backend.plugin import PluginManager from automatron.controller.controller import IAutomatronClientActions from automatron.core.controller import BaseController class BackendController(BaseController): def __init__(self, config_file): BaseController.__init__(self, config_file) self.plugins = None def prepareService(self): # Load plugins self.plugins = PluginManager(self) def __getattr__(self, item): - def proxy(*args): - self.plugins.emit(IAutomatronClientActions[item], *args) + return partial(self.plugins.emit, IAutomatronClientActions[item]) - return proxy
Use functools.partial for client action proxy.
## Code Before: from automatron.backend.plugin import PluginManager from automatron.controller.controller import IAutomatronClientActions from automatron.core.controller import BaseController class BackendController(BaseController): def __init__(self, config_file): BaseController.__init__(self, config_file) self.plugins = None def prepareService(self): # Load plugins self.plugins = PluginManager(self) def __getattr__(self, item): def proxy(*args): self.plugins.emit(IAutomatronClientActions[item], *args) return proxy ## Instruction: Use functools.partial for client action proxy. ## Code After: from functools import partial from automatron.backend.plugin import PluginManager from automatron.controller.controller import IAutomatronClientActions from automatron.core.controller import BaseController class BackendController(BaseController): def __init__(self, config_file): BaseController.__init__(self, config_file) self.plugins = None def prepareService(self): # Load plugins self.plugins = PluginManager(self) def __getattr__(self, item): return partial(self.plugins.emit, IAutomatronClientActions[item])
7925afd27ead247a017baf7a7dff97986904055f
comics/views.py
comics/views.py
from django.views import generic from gallery.models import GalleryImage from gallery import queries from .models import Arc, Issue class IndexView(generic.ListView): model = Arc template_name = "comics/index.html" context_object_name = "arcs" class IssueView(generic.DetailView): model = Issue template_name = "comics/issue.html" def get_queryset(self): query_set = super().get_queryset().filter(arc__slug=self.kwargs.get("arc_slug")) return query_set class ComicPageView(generic.DetailView): model = GalleryImage template_name = "comics/comic_page.html" def __init__(self): super().__init__() self.issue = None def get_queryset(self): # Find Issue, then get gallery self.issue = Issue.objects.filter(arc__slug=self.kwargs.get("arc_slug")).get( slug=self.kwargs.get("issue_slug") ) query_set = super().get_queryset().filter(gallery__id=self.issue.gallery.id) return query_set def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["issue"] = self.issue # Set in get_queryset() context["next"] = queries.get_next_image( self.issue.gallery, self.object.sort_order ) context["previous"] = queries.get_previous_image( self.issue.gallery, self.object.sort_order ) return context
from django.views import generic from gallery.models import GalleryImage from gallery import queries from .models import Arc, Issue class IndexView(generic.ListView): model = Arc template_name = "comics/index.html" context_object_name = "arcs" class IssueView(generic.DetailView): model = Issue template_name = "comics/issue.html" def get_queryset(self): query_set = super().get_queryset().filter(arc__slug=self.kwargs.get("arc_slug")) return query_set class ComicPageView(generic.DetailView): model = GalleryImage template_name = "comics/comic_page.html" def __init__(self): super().__init__() self.issue = None def get_queryset(self): # Find Issue, then get gallery self.issue = Issue.objects.filter(arc__slug=self.kwargs.get("arc_slug")).get( slug=self.kwargs.get("issue_slug") ) query_set = super().get_queryset().filter(gallery__id=self.issue.gallery.id) return query_set def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["issue"] = self.issue # Set in get_queryset() gallery = self.issue.gallery sort_order = self.object.sort_order context["next"] = queries.get_next_image(gallery, sort_order) context["previous"] = queries.get_previous_image(gallery, sort_order) return context
Make it look nicer, possibly micro seconds faster
Make it look nicer, possibly micro seconds faster
Python
mit
evanepio/dotmanca,evanepio/dotmanca,evanepio/dotmanca
from django.views import generic from gallery.models import GalleryImage from gallery import queries from .models import Arc, Issue class IndexView(generic.ListView): model = Arc template_name = "comics/index.html" context_object_name = "arcs" class IssueView(generic.DetailView): model = Issue template_name = "comics/issue.html" def get_queryset(self): query_set = super().get_queryset().filter(arc__slug=self.kwargs.get("arc_slug")) return query_set class ComicPageView(generic.DetailView): model = GalleryImage template_name = "comics/comic_page.html" def __init__(self): super().__init__() self.issue = None def get_queryset(self): # Find Issue, then get gallery self.issue = Issue.objects.filter(arc__slug=self.kwargs.get("arc_slug")).get( slug=self.kwargs.get("issue_slug") ) query_set = super().get_queryset().filter(gallery__id=self.issue.gallery.id) return query_set def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["issue"] = self.issue # Set in get_queryset() + + gallery = self.issue.gallery + sort_order = self.object.sort_order - context["next"] = queries.get_next_image( + context["next"] = queries.get_next_image(gallery, sort_order) - self.issue.gallery, self.object.sort_order - ) - context["previous"] = queries.get_previous_image( + context["previous"] = queries.get_previous_image(gallery, sort_order) - self.issue.gallery, self.object.sort_order - ) return context
Make it look nicer, possibly micro seconds faster
## Code Before: from django.views import generic from gallery.models import GalleryImage from gallery import queries from .models import Arc, Issue class IndexView(generic.ListView): model = Arc template_name = "comics/index.html" context_object_name = "arcs" class IssueView(generic.DetailView): model = Issue template_name = "comics/issue.html" def get_queryset(self): query_set = super().get_queryset().filter(arc__slug=self.kwargs.get("arc_slug")) return query_set class ComicPageView(generic.DetailView): model = GalleryImage template_name = "comics/comic_page.html" def __init__(self): super().__init__() self.issue = None def get_queryset(self): # Find Issue, then get gallery self.issue = Issue.objects.filter(arc__slug=self.kwargs.get("arc_slug")).get( slug=self.kwargs.get("issue_slug") ) query_set = super().get_queryset().filter(gallery__id=self.issue.gallery.id) return query_set def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["issue"] = self.issue # Set in get_queryset() context["next"] = queries.get_next_image( self.issue.gallery, self.object.sort_order ) context["previous"] = queries.get_previous_image( self.issue.gallery, self.object.sort_order ) return context ## Instruction: Make it look nicer, possibly micro seconds faster ## Code After: from django.views import generic from gallery.models import GalleryImage from gallery import queries from .models import Arc, Issue class IndexView(generic.ListView): model = Arc template_name = "comics/index.html" context_object_name = "arcs" class IssueView(generic.DetailView): model = Issue template_name = "comics/issue.html" def get_queryset(self): query_set = super().get_queryset().filter(arc__slug=self.kwargs.get("arc_slug")) return query_set class ComicPageView(generic.DetailView): model = GalleryImage template_name = "comics/comic_page.html" def __init__(self): super().__init__() self.issue = None def get_queryset(self): # Find Issue, then get gallery self.issue = Issue.objects.filter(arc__slug=self.kwargs.get("arc_slug")).get( slug=self.kwargs.get("issue_slug") ) query_set = super().get_queryset().filter(gallery__id=self.issue.gallery.id) return query_set def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["issue"] = self.issue # Set in get_queryset() gallery = self.issue.gallery sort_order = self.object.sort_order context["next"] = queries.get_next_image(gallery, sort_order) context["previous"] = queries.get_previous_image(gallery, sort_order) return context
04416cd9652a9fdc3ab58664ab4b96cbaff3f698
simuvex/s_event.py
simuvex/s_event.py
import itertools event_id_count = itertools.count() class SimEvent(object): #def __init__(self, address=None, stmt_idx=None, message=None, exception=None, traceback=None): def __init__(self, state, event_type, **kwargs): self.id = event_id_count.next() self.type = event_type self.ins_addr = state.scratch.ins_addr self.bbl_addr = state.scratch.bbl_addr self.stmt_idx = state.scratch.stmt_idx self.sim_procedure = state.scratch.sim_procedure.__class__ self.objects = dict(kwargs) def __repr__(self): return "<SimEvent %s %d, with fields %s>" % (self.type, self.id, self.objects.keys()) def _copy_event(self): c = self.__class__.__new__(self.__class__) c.id = self.id c.type = self.type c.bbl_addr = self.bbl_addr c.stmt_idx = self.stmt_idx c.sim_procedure = self.sim_procedure c.objects = dict(self.objects) return c
import itertools event_id_count = itertools.count() class SimEvent(object): #def __init__(self, address=None, stmt_idx=None, message=None, exception=None, traceback=None): def __init__(self, state, event_type, **kwargs): self.id = event_id_count.next() self.type = event_type self.ins_addr = state.scratch.ins_addr self.bbl_addr = state.scratch.bbl_addr self.stmt_idx = state.scratch.stmt_idx self.sim_procedure = None if state.scratch.sim_procedure is None else state.scratch.sim_procedure.__class__ self.objects = dict(kwargs) def __repr__(self): return "<SimEvent %s %d, with fields %s>" % (self.type, self.id, self.objects.keys()) def _copy_event(self): c = self.__class__.__new__(self.__class__) c.id = self.id c.type = self.type c.bbl_addr = self.bbl_addr c.stmt_idx = self.stmt_idx c.sim_procedure = self.sim_procedure c.objects = dict(self.objects) return c
Set None instead of NoneType to SimEvent.sim_procedure to make pickle happy.
Set None instead of NoneType to SimEvent.sim_procedure to make pickle happy.
Python
bsd-2-clause
axt/angr,schieb/angr,angr/angr,tyb0807/angr,f-prettyland/angr,tyb0807/angr,chubbymaggie/angr,chubbymaggie/angr,f-prettyland/angr,angr/angr,axt/angr,tyb0807/angr,iamahuman/angr,iamahuman/angr,chubbymaggie/angr,angr/simuvex,schieb/angr,iamahuman/angr,axt/angr,angr/angr,f-prettyland/angr,schieb/angr
import itertools event_id_count = itertools.count() class SimEvent(object): #def __init__(self, address=None, stmt_idx=None, message=None, exception=None, traceback=None): def __init__(self, state, event_type, **kwargs): self.id = event_id_count.next() self.type = event_type self.ins_addr = state.scratch.ins_addr self.bbl_addr = state.scratch.bbl_addr self.stmt_idx = state.scratch.stmt_idx - self.sim_procedure = state.scratch.sim_procedure.__class__ + self.sim_procedure = None if state.scratch.sim_procedure is None else state.scratch.sim_procedure.__class__ self.objects = dict(kwargs) def __repr__(self): return "<SimEvent %s %d, with fields %s>" % (self.type, self.id, self.objects.keys()) def _copy_event(self): c = self.__class__.__new__(self.__class__) c.id = self.id c.type = self.type c.bbl_addr = self.bbl_addr c.stmt_idx = self.stmt_idx c.sim_procedure = self.sim_procedure c.objects = dict(self.objects) return c
Set None instead of NoneType to SimEvent.sim_procedure to make pickle happy.
## Code Before: import itertools event_id_count = itertools.count() class SimEvent(object): #def __init__(self, address=None, stmt_idx=None, message=None, exception=None, traceback=None): def __init__(self, state, event_type, **kwargs): self.id = event_id_count.next() self.type = event_type self.ins_addr = state.scratch.ins_addr self.bbl_addr = state.scratch.bbl_addr self.stmt_idx = state.scratch.stmt_idx self.sim_procedure = state.scratch.sim_procedure.__class__ self.objects = dict(kwargs) def __repr__(self): return "<SimEvent %s %d, with fields %s>" % (self.type, self.id, self.objects.keys()) def _copy_event(self): c = self.__class__.__new__(self.__class__) c.id = self.id c.type = self.type c.bbl_addr = self.bbl_addr c.stmt_idx = self.stmt_idx c.sim_procedure = self.sim_procedure c.objects = dict(self.objects) return c ## Instruction: Set None instead of NoneType to SimEvent.sim_procedure to make pickle happy. ## Code After: import itertools event_id_count = itertools.count() class SimEvent(object): #def __init__(self, address=None, stmt_idx=None, message=None, exception=None, traceback=None): def __init__(self, state, event_type, **kwargs): self.id = event_id_count.next() self.type = event_type self.ins_addr = state.scratch.ins_addr self.bbl_addr = state.scratch.bbl_addr self.stmt_idx = state.scratch.stmt_idx self.sim_procedure = None if state.scratch.sim_procedure is None else state.scratch.sim_procedure.__class__ self.objects = dict(kwargs) def __repr__(self): return "<SimEvent %s %d, with fields %s>" % (self.type, self.id, self.objects.keys()) def _copy_event(self): c = self.__class__.__new__(self.__class__) c.id = self.id c.type = self.type c.bbl_addr = self.bbl_addr c.stmt_idx = self.stmt_idx c.sim_procedure = self.sim_procedure c.objects = dict(self.objects) return c
b1c1b28e58b59eac81954fb55570dfd389b99c0f
tests/acceptance/test_modify.py
tests/acceptance/test_modify.py
import datetime from nose.tools import assert_raises from scalymongo import Document from scalymongo.errors import ModifyFailedError from tests.acceptance.base_acceptance_test import BaseAcceptanceTest class ModifyableDocument(Document): __collection__ = __name__ __database__ = 'test' structure = { 'field': basestring, } class WhenModifyingDocumentAndPreconditionFails(BaseAcceptanceTest): def should_raise_ModifyFailedError(self): doc = self.connection.models.ModifyableDocument({'field': 'foo'}) doc.save() assert_raises( ModifyFailedError, doc.modify, {'field': 'not the correct value'}, {'$set': {'field': 'new value'}}, )
import datetime from nose.tools import assert_raises from scalymongo import Document from scalymongo.errors import ModifyFailedError from tests.acceptance.base_acceptance_test import BaseAcceptanceTest class BlogPostModifyExample(Document): __collection__ = __name__ __database__ = 'test' structure = { 'author': basestring, 'title': basestring, 'body': basestring, 'views': int, 'comments': [{ 'author': basestring, 'comment': basestring, 'rank': int, }], } default_values = { 'views': 0, } EXAMPLE_POST = { 'author': 'Alice', 'title': 'Writing Scalable Services with Python and MongoDB', 'body': 'Use ScalyMongo!', } class BlogPostTestCase(BaseAcceptanceTest): def setup(self): self.doc = self.connection.models.BlogPostModifyExample(EXAMPLE_POST) self.doc.save() def teardown(self): self.connection.models.BlogPostModifyExample.collection.drop() def is_document_up_to_date(self): """True if and only if ``self.doc`` reflects what's in the database.""" fresh_copy = self.connection.models.BlogPostModifyExample.find_one( self.doc.shard_key) return self.doc == fresh_copy def when_no_precondition_given_should_increment(self): self.doc.modify({'$inc': {'views': 1}}) assert self.doc.views == 1 self.doc.modify({'$inc': {'views': 5}}) assert self.doc.views == 6 assert self.is_document_up_to_date() def when_precondition_fails_should_raise_ModifyFailedError(self): assert_raises( ModifyFailedError, self.doc.modify, {'$set': {'author': 'Bob'}}, {'author': 'Not Alice'}, ) # The doc should not have been altered. assert self.doc.author == 'Alice' assert self.is_document_up_to_date() def when_precondition_passes_should_update_field(self): self.doc.modify( {'$set': {'views': 15}}, {'author': 'Alice'}, ) assert self.is_document_up_to_date()
Add more comprehensive testing of `modify`
acceptance: Add more comprehensive testing of `modify`
Python
bsd-3-clause
allancaffee/scaly-mongo
import datetime from nose.tools import assert_raises from scalymongo import Document from scalymongo.errors import ModifyFailedError from tests.acceptance.base_acceptance_test import BaseAcceptanceTest - class ModifyableDocument(Document): + class BlogPostModifyExample(Document): __collection__ = __name__ __database__ = 'test' structure = { + 'author': basestring, - 'field': basestring, + 'title': basestring, + 'body': basestring, + 'views': int, + 'comments': [{ + 'author': basestring, + 'comment': basestring, + 'rank': int, + }], + } + default_values = { + 'views': 0, } - class WhenModifyingDocumentAndPreconditionFails(BaseAcceptanceTest): + EXAMPLE_POST = { + 'author': 'Alice', + 'title': 'Writing Scalable Services with Python and MongoDB', + 'body': 'Use ScalyMongo!', + } - def should_raise_ModifyFailedError(self): - doc = self.connection.models.ModifyableDocument({'field': 'foo'}) + + class BlogPostTestCase(BaseAcceptanceTest): + + def setup(self): + self.doc = self.connection.models.BlogPostModifyExample(EXAMPLE_POST) - doc.save() + self.doc.save() + + def teardown(self): + self.connection.models.BlogPostModifyExample.collection.drop() + + def is_document_up_to_date(self): + """True if and only if ``self.doc`` reflects what's in the database.""" + fresh_copy = self.connection.models.BlogPostModifyExample.find_one( + self.doc.shard_key) + return self.doc == fresh_copy + + def when_no_precondition_given_should_increment(self): + self.doc.modify({'$inc': {'views': 1}}) + assert self.doc.views == 1 + + self.doc.modify({'$inc': {'views': 5}}) + assert self.doc.views == 6 + + assert self.is_document_up_to_date() + + def when_precondition_fails_should_raise_ModifyFailedError(self): assert_raises( ModifyFailedError, - doc.modify, + self.doc.modify, - {'field': 'not the correct value'}, - {'$set': {'field': 'new value'}}, + {'$set': {'author': 'Bob'}}, + {'author': 'Not Alice'}, ) + # The doc should not have been altered. + assert self.doc.author == 'Alice' + assert self.is_document_up_to_date() + + def when_precondition_passes_should_update_field(self): + self.doc.modify( + {'$set': {'views': 15}}, + {'author': 'Alice'}, + ) + + assert self.is_document_up_to_date() +
Add more comprehensive testing of `modify`
## Code Before: import datetime from nose.tools import assert_raises from scalymongo import Document from scalymongo.errors import ModifyFailedError from tests.acceptance.base_acceptance_test import BaseAcceptanceTest class ModifyableDocument(Document): __collection__ = __name__ __database__ = 'test' structure = { 'field': basestring, } class WhenModifyingDocumentAndPreconditionFails(BaseAcceptanceTest): def should_raise_ModifyFailedError(self): doc = self.connection.models.ModifyableDocument({'field': 'foo'}) doc.save() assert_raises( ModifyFailedError, doc.modify, {'field': 'not the correct value'}, {'$set': {'field': 'new value'}}, ) ## Instruction: Add more comprehensive testing of `modify` ## Code After: import datetime from nose.tools import assert_raises from scalymongo import Document from scalymongo.errors import ModifyFailedError from tests.acceptance.base_acceptance_test import BaseAcceptanceTest class BlogPostModifyExample(Document): __collection__ = __name__ __database__ = 'test' structure = { 'author': basestring, 'title': basestring, 'body': basestring, 'views': int, 'comments': [{ 'author': basestring, 'comment': basestring, 'rank': int, }], } default_values = { 'views': 0, } EXAMPLE_POST = { 'author': 'Alice', 'title': 'Writing Scalable Services with Python and MongoDB', 'body': 'Use ScalyMongo!', } class BlogPostTestCase(BaseAcceptanceTest): def setup(self): self.doc = self.connection.models.BlogPostModifyExample(EXAMPLE_POST) self.doc.save() def teardown(self): self.connection.models.BlogPostModifyExample.collection.drop() def is_document_up_to_date(self): """True if and only if ``self.doc`` reflects what's in the database.""" fresh_copy = self.connection.models.BlogPostModifyExample.find_one( self.doc.shard_key) return self.doc == fresh_copy def when_no_precondition_given_should_increment(self): self.doc.modify({'$inc': {'views': 1}}) assert self.doc.views == 1 self.doc.modify({'$inc': {'views': 5}}) assert self.doc.views == 6 assert self.is_document_up_to_date() def when_precondition_fails_should_raise_ModifyFailedError(self): assert_raises( ModifyFailedError, self.doc.modify, {'$set': {'author': 'Bob'}}, {'author': 'Not Alice'}, ) # The doc should not have been altered. assert self.doc.author == 'Alice' assert self.is_document_up_to_date() def when_precondition_passes_should_update_field(self): self.doc.modify( {'$set': {'views': 15}}, {'author': 'Alice'}, ) assert self.is_document_up_to_date()
445a150982f2119b340d95edc66940e0ec54afbd
lib/ansiblelint/rules/NoFormattingInWhenRule.py
lib/ansiblelint/rules/NoFormattingInWhenRule.py
from ansiblelint import AnsibleLintRule class NoFormattingInWhenRule(AnsibleLintRule): id = 'CINCH0001' shortdesc = 'No Jinja2 in when' description = '"when" lines should not include Jinja2 variables' tags = ['deprecated'] def _is_valid(self, when): if not isinstance(when, (str, unicode)): return True return when.find('{{') == -1 and when.find('}}') == -1 def matchplay(self, file, play): errors = [] if isinstance(play, dict): if 'roles' not in play: return errors for role in play['roles']: if self.matchtask(file, role): errors.append(({'when': role}, 'role "when" clause has Jinja2 templates')) if isinstance(play, list): for play_item in play: sub_errors = self.matchplay(file, play_item) if sub_errors: errors = errors + sub_errors return errors def matchtask(self, file, task): return 'when' in task and not self._is_valid(task['when'])
from ansiblelint import AnsibleLintRule try: from types import StringTypes except ImportError: # Python3 removed types.StringTypes StringTypes = str, class NoFormattingInWhenRule(AnsibleLintRule): id = 'CINCH0001' shortdesc = 'No Jinja2 in when' description = '"when" lines should not include Jinja2 variables' tags = ['deprecated'] def _is_valid(self, when): if not isinstance(when, StringTypes): return True return when.find('{{') == -1 and when.find('}}') == -1 def matchplay(self, file, play): errors = [] if isinstance(play, dict): if 'roles' not in play: return errors for role in play['roles']: if self.matchtask(file, role): errors.append(({'when': role}, 'role "when" clause has Jinja2 templates')) if isinstance(play, list): for play_item in play: sub_errors = self.matchplay(file, play_item) if sub_errors: errors = errors + sub_errors return errors def matchtask(self, file, task): return 'when' in task and not self._is_valid(task['when'])
Fix Python3 unicode test error
Fix Python3 unicode test error
Python
mit
willthames/ansible-lint,dataxu/ansible-lint,MatrixCrawler/ansible-lint
from ansiblelint import AnsibleLintRule + try: + from types import StringTypes + except ImportError: + # Python3 removed types.StringTypes + StringTypes = str, class NoFormattingInWhenRule(AnsibleLintRule): id = 'CINCH0001' shortdesc = 'No Jinja2 in when' description = '"when" lines should not include Jinja2 variables' tags = ['deprecated'] def _is_valid(self, when): - if not isinstance(when, (str, unicode)): + if not isinstance(when, StringTypes): return True return when.find('{{') == -1 and when.find('}}') == -1 def matchplay(self, file, play): errors = [] if isinstance(play, dict): if 'roles' not in play: return errors for role in play['roles']: if self.matchtask(file, role): errors.append(({'when': role}, 'role "when" clause has Jinja2 templates')) if isinstance(play, list): for play_item in play: sub_errors = self.matchplay(file, play_item) if sub_errors: errors = errors + sub_errors return errors def matchtask(self, file, task): return 'when' in task and not self._is_valid(task['when'])
Fix Python3 unicode test error
## Code Before: from ansiblelint import AnsibleLintRule class NoFormattingInWhenRule(AnsibleLintRule): id = 'CINCH0001' shortdesc = 'No Jinja2 in when' description = '"when" lines should not include Jinja2 variables' tags = ['deprecated'] def _is_valid(self, when): if not isinstance(when, (str, unicode)): return True return when.find('{{') == -1 and when.find('}}') == -1 def matchplay(self, file, play): errors = [] if isinstance(play, dict): if 'roles' not in play: return errors for role in play['roles']: if self.matchtask(file, role): errors.append(({'when': role}, 'role "when" clause has Jinja2 templates')) if isinstance(play, list): for play_item in play: sub_errors = self.matchplay(file, play_item) if sub_errors: errors = errors + sub_errors return errors def matchtask(self, file, task): return 'when' in task and not self._is_valid(task['when']) ## Instruction: Fix Python3 unicode test error ## Code After: from ansiblelint import AnsibleLintRule try: from types import StringTypes except ImportError: # Python3 removed types.StringTypes StringTypes = str, class NoFormattingInWhenRule(AnsibleLintRule): id = 'CINCH0001' shortdesc = 'No Jinja2 in when' description = '"when" lines should not include Jinja2 variables' tags = ['deprecated'] def _is_valid(self, when): if not isinstance(when, StringTypes): return True return when.find('{{') == -1 and when.find('}}') == -1 def matchplay(self, file, play): errors = [] if isinstance(play, dict): if 'roles' not in play: return errors for role in play['roles']: if self.matchtask(file, role): errors.append(({'when': role}, 'role "when" clause has Jinja2 templates')) if isinstance(play, list): for play_item in play: sub_errors = self.matchplay(file, play_item) if sub_errors: errors = errors + sub_errors return errors def matchtask(self, file, task): return 'when' in task and not self._is_valid(task['when'])
0e48b2130cc53caa9beb9a5f8ce09edbcc40f1b8
ggplotx/tests/test_geom_point.py
ggplotx/tests/test_geom_point.py
from __future__ import absolute_import, division, print_function import pandas as pd from ggplotx import ggplot, aes, geom_point def test_aesthetics(): df = pd.DataFrame({ 'a': range(5), 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9 }) p = (ggplot(df, aes(y='a')) + geom_point(aes(x='b')) + geom_point(aes(x='c', size='a')) + geom_point(aes(x='d', alpha='a'), size=10, show_legend=False) + geom_point(aes(x='e', shape='factor(a)'), size=10, show_legend=False) + geom_point(aes(x='f', color='factor(a)'), size=10, show_legend=False) + geom_point(aes(x='g', fill='a'), stroke=0, size=10, show_legend=False) + geom_point(aes(x='h', stroke='a'), fill='white', color='green', size=10) + geom_point(aes(x='i', shape='factor(a)'), fill='brown', stroke=2, size=10, show_legend=False)) assert p == 'aesthetics'
from __future__ import absolute_import, division, print_function import pandas as pd from ggplotx import ggplot, aes, geom_point, theme def test_aesthetics(): df = pd.DataFrame({ 'a': range(5), 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9 }) p = (ggplot(df, aes(y='a')) + geom_point(aes(x='b')) + geom_point(aes(x='c', size='a')) + geom_point(aes(x='d', alpha='a'), size=10, show_legend=False) + geom_point(aes(x='e', shape='factor(a)'), size=10, show_legend=False) + geom_point(aes(x='f', color='factor(a)'), size=10, show_legend=False) + geom_point(aes(x='g', fill='a'), stroke=0, size=10, show_legend=False) + geom_point(aes(x='h', stroke='a'), fill='white', color='green', size=10) + geom_point(aes(x='i', shape='factor(a)'), fill='brown', stroke=2, size=10, show_legend=False) + theme(facet_spacing={'right': 0.85})) assert p == 'aesthetics'
Add space on the RHS of geom_point test
Add space on the RHS of geom_point test
Python
mit
has2k1/plotnine,has2k1/plotnine
from __future__ import absolute_import, division, print_function import pandas as pd - from ggplotx import ggplot, aes, geom_point + from ggplotx import ggplot, aes, geom_point, theme def test_aesthetics(): df = pd.DataFrame({ 'a': range(5), 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9 }) p = (ggplot(df, aes(y='a')) + geom_point(aes(x='b')) + geom_point(aes(x='c', size='a')) + geom_point(aes(x='d', alpha='a'), size=10, show_legend=False) + geom_point(aes(x='e', shape='factor(a)'), size=10, show_legend=False) + geom_point(aes(x='f', color='factor(a)'), size=10, show_legend=False) + geom_point(aes(x='g', fill='a'), stroke=0, size=10, show_legend=False) + geom_point(aes(x='h', stroke='a'), fill='white', color='green', size=10) + geom_point(aes(x='i', shape='factor(a)'), - fill='brown', stroke=2, size=10, show_legend=False)) + fill='brown', stroke=2, size=10, show_legend=False) + + theme(facet_spacing={'right': 0.85})) assert p == 'aesthetics'
Add space on the RHS of geom_point test
## Code Before: from __future__ import absolute_import, division, print_function import pandas as pd from ggplotx import ggplot, aes, geom_point def test_aesthetics(): df = pd.DataFrame({ 'a': range(5), 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9 }) p = (ggplot(df, aes(y='a')) + geom_point(aes(x='b')) + geom_point(aes(x='c', size='a')) + geom_point(aes(x='d', alpha='a'), size=10, show_legend=False) + geom_point(aes(x='e', shape='factor(a)'), size=10, show_legend=False) + geom_point(aes(x='f', color='factor(a)'), size=10, show_legend=False) + geom_point(aes(x='g', fill='a'), stroke=0, size=10, show_legend=False) + geom_point(aes(x='h', stroke='a'), fill='white', color='green', size=10) + geom_point(aes(x='i', shape='factor(a)'), fill='brown', stroke=2, size=10, show_legend=False)) assert p == 'aesthetics' ## Instruction: Add space on the RHS of geom_point test ## Code After: from __future__ import absolute_import, division, print_function import pandas as pd from ggplotx import ggplot, aes, geom_point, theme def test_aesthetics(): df = pd.DataFrame({ 'a': range(5), 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9 }) p = (ggplot(df, aes(y='a')) + geom_point(aes(x='b')) + geom_point(aes(x='c', size='a')) + geom_point(aes(x='d', alpha='a'), size=10, show_legend=False) + geom_point(aes(x='e', shape='factor(a)'), size=10, show_legend=False) + geom_point(aes(x='f', color='factor(a)'), size=10, show_legend=False) + geom_point(aes(x='g', fill='a'), stroke=0, size=10, show_legend=False) + geom_point(aes(x='h', stroke='a'), fill='white', color='green', size=10) + geom_point(aes(x='i', shape='factor(a)'), fill='brown', stroke=2, size=10, show_legend=False) + theme(facet_spacing={'right': 0.85})) assert p == 'aesthetics'
7a24f314c426e55735836dd2f805d9e0364dc871
tarbell/hooks.py
tarbell/hooks.py
hooks = { 'newproject': [], # (site) 'generate': [], # (site, dir, extra_context) 'publish': [], # (site, s3) 'install': [], # (site, project) 'preview': [], # (site) 'server_start': [], # (site) 'server_stop': [], # (site) } class register_hook(object): """ Register hook with @register_hook("EVENT") where EVENT is "newproject" etc. """ def __init__(self, event): self.event = event def __call__(self, f): # Avoid weird duplication names = ['{0}.{1}'.format(func.__module__, func.func_name) for func in hooks[self.event]] if '{0}.{1}'.format(f.__module__, f.func_name) not in names: hooks[self.event].append(f) return f
hooks = { 'newproject': [], # (site) 'generate': [], # (site, dir, extra_context) 'publish': [], # (site, s3) 'install': [], # (site, project) 'preview': [], # (site) 'server_start': [], # (site) 'server_stop': [], # (site) } class register_hook(object): """ Register hook with @register_hook("EVENT") where EVENT is "newproject" etc. """ def __init__(self, event): self.event = event def __call__(self, f): # Avoid weird duplication names = ['{0}.{1}'.format(func.__module__, func.__name__) for func in hooks[self.event]] if '{0}.{1}'.format(f.__module__, f.__name__) not in names: hooks[self.event].append(f) return f
Switch to Python 3-friendly `function.__name__`
Switch to Python 3-friendly `function.__name__`
Python
bsd-3-clause
tarbell-project/tarbell,eyeseast/tarbell,tarbell-project/tarbell,eyeseast/tarbell
hooks = { 'newproject': [], # (site) 'generate': [], # (site, dir, extra_context) 'publish': [], # (site, s3) 'install': [], # (site, project) 'preview': [], # (site) 'server_start': [], # (site) 'server_stop': [], # (site) } class register_hook(object): """ Register hook with @register_hook("EVENT") where EVENT is "newproject" etc. """ def __init__(self, event): self.event = event def __call__(self, f): # Avoid weird duplication - names = ['{0}.{1}'.format(func.__module__, func.func_name) for func in hooks[self.event]] + names = ['{0}.{1}'.format(func.__module__, func.__name__) for func in hooks[self.event]] - if '{0}.{1}'.format(f.__module__, f.func_name) not in names: + if '{0}.{1}'.format(f.__module__, f.__name__) not in names: hooks[self.event].append(f) return f
Switch to Python 3-friendly `function.__name__`
## Code Before: hooks = { 'newproject': [], # (site) 'generate': [], # (site, dir, extra_context) 'publish': [], # (site, s3) 'install': [], # (site, project) 'preview': [], # (site) 'server_start': [], # (site) 'server_stop': [], # (site) } class register_hook(object): """ Register hook with @register_hook("EVENT") where EVENT is "newproject" etc. """ def __init__(self, event): self.event = event def __call__(self, f): # Avoid weird duplication names = ['{0}.{1}'.format(func.__module__, func.func_name) for func in hooks[self.event]] if '{0}.{1}'.format(f.__module__, f.func_name) not in names: hooks[self.event].append(f) return f ## Instruction: Switch to Python 3-friendly `function.__name__` ## Code After: hooks = { 'newproject': [], # (site) 'generate': [], # (site, dir, extra_context) 'publish': [], # (site, s3) 'install': [], # (site, project) 'preview': [], # (site) 'server_start': [], # (site) 'server_stop': [], # (site) } class register_hook(object): """ Register hook with @register_hook("EVENT") where EVENT is "newproject" etc. """ def __init__(self, event): self.event = event def __call__(self, f): # Avoid weird duplication names = ['{0}.{1}'.format(func.__module__, func.__name__) for func in hooks[self.event]] if '{0}.{1}'.format(f.__module__, f.__name__) not in names: hooks[self.event].append(f) return f
e08395a35c37fa7f7c0311cc4c7a71537b8b4227
tests/misc/print_exception.py
tests/misc/print_exception.py
try: import uio as io except ImportError: import io import sys if hasattr(sys, 'print_exception'): print_exception = sys.print_exception else: import traceback print_exception = lambda e, f: traceback.print_exception(None, e, sys.exc_info()[2], file=f) def print_exc(e): buf = io.StringIO() print_exception(e, buf) s = buf.getvalue() for l in s.split("\n"): # uPy on pyboard prints <stdin> as file, so remove filename. if l.startswith(" File "): l = l.split('"') print(l[0], l[2]) # uPy and CPy tracebacks differ in that CPy prints a source line for # each traceback entry. In this case, we know that offending line # has 4-space indent, so filter it out. elif not l.startswith(" "): print(l) # basic exception message try: 1/0 except Exception as e: print('caught') print_exc(e) # exception message with more than 1 source-code line def f(): g() def g(): 2/0 try: f() except Exception as e: print('caught') print_exc(e)
try: import uio as io except ImportError: import io import sys if hasattr(sys, 'print_exception'): print_exception = sys.print_exception else: import traceback print_exception = lambda e, f: traceback.print_exception(None, e, sys.exc_info()[2], file=f) def print_exc(e): buf = io.StringIO() print_exception(e, buf) s = buf.getvalue() for l in s.split("\n"): # uPy on pyboard prints <stdin> as file, so remove filename. if l.startswith(" File "): l = l.split('"') print(l[0], l[2]) # uPy and CPy tracebacks differ in that CPy prints a source line for # each traceback entry. In this case, we know that offending line # has 4-space indent, so filter it out. elif not l.startswith(" "): print(l) # basic exception message try: 1/0 except Exception as e: print('caught') print_exc(e) # exception message with more than 1 source-code line def f(): g() def g(): 2/0 try: f() except Exception as e: print('caught') print_exc(e) # Here we have a function with lots of bytecode generated for a single source-line, and # there is an error right at the end of the bytecode. It should report the correct line. def f(): f([1, 2], [1, 2], [1, 2], {1:1, 1:1, 1:1, 1:1, 1:1, 1:1, 1:X}) return 1 try: f() except Exception as e: print_exc(e)
Add test for line number printing with large bytecode chunk.
tests/misc: Add test for line number printing with large bytecode chunk.
Python
mit
henriknelson/micropython,AriZuu/micropython,AriZuu/micropython,micropython/micropython-esp32,micropython/micropython-esp32,PappaPeppar/micropython,MrSurly/micropython,MrSurly/micropython-esp32,infinnovation/micropython,trezor/micropython,micropython/micropython-esp32,lowRISC/micropython,torwag/micropython,PappaPeppar/micropython,swegener/micropython,MrSurly/micropython,Peetz0r/micropython-esp32,TDAbboud/micropython,hiway/micropython,kerneltask/micropython,cwyark/micropython,adafruit/micropython,trezor/micropython,adafruit/micropython,bvernoux/micropython,henriknelson/micropython,pramasoul/micropython,kerneltask/micropython,MrSurly/micropython-esp32,trezor/micropython,cwyark/micropython,torwag/micropython,hiway/micropython,adafruit/circuitpython,cwyark/micropython,tobbad/micropython,MrSurly/micropython,adafruit/circuitpython,henriknelson/micropython,MrSurly/micropython-esp32,pramasoul/micropython,tralamazza/micropython,pozetroninc/micropython,deshipu/micropython,cwyark/micropython,chrisdearman/micropython,adafruit/circuitpython,HenrikSolver/micropython,hiway/micropython,oopy/micropython,henriknelson/micropython,ryannathans/micropython,dmazzella/micropython,swegener/micropython,pramasoul/micropython,adafruit/circuitpython,pozetroninc/micropython,Peetz0r/micropython-esp32,blazewicz/micropython,toolmacher/micropython,ryannathans/micropython,alex-robbins/micropython,SHA2017-badge/micropython-esp32,bvernoux/micropython,chrisdearman/micropython,oopy/micropython,selste/micropython,pozetroninc/micropython,infinnovation/micropython,selste/micropython,pfalcon/micropython,puuu/micropython,SHA2017-badge/micropython-esp32,tralamazza/micropython,Peetz0r/micropython-esp32,Peetz0r/micropython-esp32,dmazzella/micropython,puuu/micropython,pfalcon/micropython,tobbad/micropython,chrisdearman/micropython,lowRISC/micropython,oopy/micropython,PappaPeppar/micropython,hiway/micropython,pfalcon/micropython,alex-robbins/micropython,cwyark/micropython,AriZuu/micropython,SHA2017-badge/micropython-esp32,TDAbboud/micropython,HenrikSolver/micropython,swegener/micropython,Peetz0r/micropython-esp32,MrSurly/micropython,torwag/micropython,alex-robbins/micropython,blazewicz/micropython,kerneltask/micropython,torwag/micropython,chrisdearman/micropython,trezor/micropython,alex-robbins/micropython,MrSurly/micropython-esp32,blazewicz/micropython,lowRISC/micropython,bvernoux/micropython,dmazzella/micropython,ryannathans/micropython,puuu/micropython,tobbad/micropython,ryannathans/micropython,pramasoul/micropython,AriZuu/micropython,Timmenem/micropython,blazewicz/micropython,bvernoux/micropython,tralamazza/micropython,MrSurly/micropython,swegener/micropython,blazewicz/micropython,deshipu/micropython,deshipu/micropython,trezor/micropython,selste/micropython,puuu/micropython,hiway/micropython,tralamazza/micropython,puuu/micropython,infinnovation/micropython,TDAbboud/micropython,TDAbboud/micropython,henriknelson/micropython,toolmacher/micropython,TDAbboud/micropython,selste/micropython,Timmenem/micropython,alex-robbins/micropython,pfalcon/micropython,oopy/micropython,AriZuu/micropython,lowRISC/micropython,pozetroninc/micropython,pramasoul/micropython,lowRISC/micropython,torwag/micropython,Timmenem/micropython,infinnovation/micropython,swegener/micropython,bvernoux/micropython,toolmacher/micropython,kerneltask/micropython,PappaPeppar/micropython,pfalcon/micropython,HenrikSolver/micropython,PappaPeppar/micropython,dmazzella/micropython,pozetroninc/micropython,tobbad/micropython,SHA2017-badge/micropython-esp32,deshipu/micropython,toolmacher/micropython,adafruit/micropython,HenrikSolver/micropython,SHA2017-badge/micropython-esp32,HenrikSolver/micropython,chrisdearman/micropython,adafruit/circuitpython,adafruit/micropython,Timmenem/micropython,micropython/micropython-esp32,infinnovation/micropython,micropython/micropython-esp32,deshipu/micropython,adafruit/circuitpython,adafruit/micropython,kerneltask/micropython,selste/micropython,Timmenem/micropython,toolmacher/micropython,ryannathans/micropython,oopy/micropython,tobbad/micropython,MrSurly/micropython-esp32
try: import uio as io except ImportError: import io import sys if hasattr(sys, 'print_exception'): print_exception = sys.print_exception else: import traceback print_exception = lambda e, f: traceback.print_exception(None, e, sys.exc_info()[2], file=f) def print_exc(e): buf = io.StringIO() print_exception(e, buf) s = buf.getvalue() for l in s.split("\n"): # uPy on pyboard prints <stdin> as file, so remove filename. if l.startswith(" File "): l = l.split('"') print(l[0], l[2]) # uPy and CPy tracebacks differ in that CPy prints a source line for # each traceback entry. In this case, we know that offending line # has 4-space indent, so filter it out. elif not l.startswith(" "): print(l) # basic exception message try: 1/0 except Exception as e: print('caught') print_exc(e) # exception message with more than 1 source-code line def f(): g() def g(): 2/0 try: f() except Exception as e: print('caught') print_exc(e) + # Here we have a function with lots of bytecode generated for a single source-line, and + # there is an error right at the end of the bytecode. It should report the correct line. + def f(): + f([1, 2], [1, 2], [1, 2], {1:1, 1:1, 1:1, 1:1, 1:1, 1:1, 1:X}) + return 1 + try: + f() + except Exception as e: + print_exc(e) +
Add test for line number printing with large bytecode chunk.
## Code Before: try: import uio as io except ImportError: import io import sys if hasattr(sys, 'print_exception'): print_exception = sys.print_exception else: import traceback print_exception = lambda e, f: traceback.print_exception(None, e, sys.exc_info()[2], file=f) def print_exc(e): buf = io.StringIO() print_exception(e, buf) s = buf.getvalue() for l in s.split("\n"): # uPy on pyboard prints <stdin> as file, so remove filename. if l.startswith(" File "): l = l.split('"') print(l[0], l[2]) # uPy and CPy tracebacks differ in that CPy prints a source line for # each traceback entry. In this case, we know that offending line # has 4-space indent, so filter it out. elif not l.startswith(" "): print(l) # basic exception message try: 1/0 except Exception as e: print('caught') print_exc(e) # exception message with more than 1 source-code line def f(): g() def g(): 2/0 try: f() except Exception as e: print('caught') print_exc(e) ## Instruction: Add test for line number printing with large bytecode chunk. ## Code After: try: import uio as io except ImportError: import io import sys if hasattr(sys, 'print_exception'): print_exception = sys.print_exception else: import traceback print_exception = lambda e, f: traceback.print_exception(None, e, sys.exc_info()[2], file=f) def print_exc(e): buf = io.StringIO() print_exception(e, buf) s = buf.getvalue() for l in s.split("\n"): # uPy on pyboard prints <stdin> as file, so remove filename. if l.startswith(" File "): l = l.split('"') print(l[0], l[2]) # uPy and CPy tracebacks differ in that CPy prints a source line for # each traceback entry. In this case, we know that offending line # has 4-space indent, so filter it out. elif not l.startswith(" "): print(l) # basic exception message try: 1/0 except Exception as e: print('caught') print_exc(e) # exception message with more than 1 source-code line def f(): g() def g(): 2/0 try: f() except Exception as e: print('caught') print_exc(e) # Here we have a function with lots of bytecode generated for a single source-line, and # there is an error right at the end of the bytecode. It should report the correct line. def f(): f([1, 2], [1, 2], [1, 2], {1:1, 1:1, 1:1, 1:1, 1:1, 1:1, 1:X}) return 1 try: f() except Exception as e: print_exc(e)
e5b503d0e66f8422412d0cdeac4ba4f55f14e420
spectrum/object.py
spectrum/object.py
class Object: """Represents a generic Spectrum object Supported Operations: +-----------+--------------------------------------+ | Operation | Description | +===========+======================================+ | x == y | Checks if two objects are equal. | +-----------+--------------------------------------+ | x != y | Checks if two objects are not equal. | +-----------+--------------------------------------+ This is the class that will be the base class of most objects, since most have an ID number. id : int The ID of the object """ def __init__(self, id): self.id = int(id) def __eq__(self, other): return isinstance(other, self.__class__) and other.id == self.id def __ne__(self, other): if isinstance(other, self.__class__): return other.id != self.id return True
class Object: """Represents a generic Spectrum object Supported Operations: +-----------+--------------------------------------+ | Operation | Description | +===========+======================================+ | x == y | Checks if two objects are equal. | +-----------+--------------------------------------+ | x != y | Checks if two objects are not equal. | +-----------+--------------------------------------+ This class is the base class of most objects, since most have an ID number. id : int The ID of the object """ def __init__(self, id): self.id = int(id) def __eq__(self, other): return isinstance(other, self.__class__) and other.id == self.id def __ne__(self, other): if isinstance(other, self.__class__): return other.id != self.id return True
Change wording from future to present tense
Documentation: Change wording from future to present tense
Python
mit
treefroog/spectrum.py
class Object: """Represents a generic Spectrum object Supported Operations: +-----------+--------------------------------------+ | Operation | Description | +===========+======================================+ | x == y | Checks if two objects are equal. | +-----------+--------------------------------------+ | x != y | Checks if two objects are not equal. | +-----------+--------------------------------------+ - This is the class that will be the base class of most objects, since most + This class is the base class of most objects, since most have an ID number. id : int The ID of the object """ def __init__(self, id): self.id = int(id) def __eq__(self, other): return isinstance(other, self.__class__) and other.id == self.id def __ne__(self, other): if isinstance(other, self.__class__): return other.id != self.id return True
Change wording from future to present tense
## Code Before: class Object: """Represents a generic Spectrum object Supported Operations: +-----------+--------------------------------------+ | Operation | Description | +===========+======================================+ | x == y | Checks if two objects are equal. | +-----------+--------------------------------------+ | x != y | Checks if two objects are not equal. | +-----------+--------------------------------------+ This is the class that will be the base class of most objects, since most have an ID number. id : int The ID of the object """ def __init__(self, id): self.id = int(id) def __eq__(self, other): return isinstance(other, self.__class__) and other.id == self.id def __ne__(self, other): if isinstance(other, self.__class__): return other.id != self.id return True ## Instruction: Change wording from future to present tense ## Code After: class Object: """Represents a generic Spectrum object Supported Operations: +-----------+--------------------------------------+ | Operation | Description | +===========+======================================+ | x == y | Checks if two objects are equal. | +-----------+--------------------------------------+ | x != y | Checks if two objects are not equal. | +-----------+--------------------------------------+ This class is the base class of most objects, since most have an ID number. id : int The ID of the object """ def __init__(self, id): self.id = int(id) def __eq__(self, other): return isinstance(other, self.__class__) and other.id == self.id def __ne__(self, other): if isinstance(other, self.__class__): return other.id != self.id return True
c06e28dae894823c0ae5385e0f9c047ceab8561c
zombies/tests.py
zombies/tests.py
from django.test import TestCase # Create your tests here. from django.test import TestCase from models import Story class StoryMethodTests(TestCase): def test_ensure_story_is_inserted(self): story = Story(name="Zombies on Campus",visits=1,description='Zombies desciption',picture='testpic') story.save() self.assertEquals((story.visits==1), True) self.assertEquals((story.name=='Zombies on Campus'), True) self.assertEquals((story.description=='Zombies desciption'), True) self.assertEquals((story.picture=='testpic'), True)
from django.test import TestCase # Create your tests here. from django.test import TestCase from models import Story, StoryPoint class StoryMethodTests(TestCase): def test_ensure_story_is_inserted(self): story = Story(name="Zombies on Campus",visits=1,description='Zombies desciption',picture='testpic') story.save() self.assertEquals((story.visits==1), True) self.assertEquals((story.name=='Zombies on Campus'), True) self.assertEquals((story.description=='Zombies desciption'), True) self.assertEquals((story.picture=='testpic'), True) def test_ensure_storyPoints_is_inserted(self): storyPoint = StoryPoint(description='You are in the library',choiceText='yes',experience=10,story_type='start',main_story_id_id=5,visits=1,story_point_id=1,picture='testpic2') storyPoint.save() self.assertEquals((storyPoint.description=='You are in the library'),True) self.assertEquals((storyPoint.choiceText=='yes'),True) self.assertEquals((storyPoint.experience==10),True) self.assertEquals((storyPoint.story_type=='start'),True) self.assertEquals((storyPoint.story_point_id==1),True) self.assertEquals((storyPoint.picture=='testpic2'),True) self.assertEquals((storyPoint.visits==1),True) self.assertEquals((storyPoint.main_story_id_id==5),True)
Test case 2 for table storypoint
Test case 2 for table storypoint
Python
apache-2.0
ITLabProject2016/internet_technology_lab_project,ITLabProject2016/internet_technology_lab_project,ITLabProject2016/internet_technology_lab_project
from django.test import TestCase # Create your tests here. from django.test import TestCase - from models import Story + from models import Story, StoryPoint class StoryMethodTests(TestCase): def test_ensure_story_is_inserted(self): story = Story(name="Zombies on Campus",visits=1,description='Zombies desciption',picture='testpic') story.save() self.assertEquals((story.visits==1), True) self.assertEquals((story.name=='Zombies on Campus'), True) self.assertEquals((story.description=='Zombies desciption'), True) - self.assertEquals((story.picture=='testpic'), True) + self.assertEquals((story.picture=='testpic'), True) + + + + def test_ensure_storyPoints_is_inserted(self): + + storyPoint = StoryPoint(description='You are in the library',choiceText='yes',experience=10,story_type='start',main_story_id_id=5,visits=1,story_point_id=1,picture='testpic2') + storyPoint.save() + self.assertEquals((storyPoint.description=='You are in the library'),True) + self.assertEquals((storyPoint.choiceText=='yes'),True) + self.assertEquals((storyPoint.experience==10),True) + self.assertEquals((storyPoint.story_type=='start'),True) + self.assertEquals((storyPoint.story_point_id==1),True) + self.assertEquals((storyPoint.picture=='testpic2'),True) + self.assertEquals((storyPoint.visits==1),True) + self.assertEquals((storyPoint.main_story_id_id==5),True) +
Test case 2 for table storypoint
## Code Before: from django.test import TestCase # Create your tests here. from django.test import TestCase from models import Story class StoryMethodTests(TestCase): def test_ensure_story_is_inserted(self): story = Story(name="Zombies on Campus",visits=1,description='Zombies desciption',picture='testpic') story.save() self.assertEquals((story.visits==1), True) self.assertEquals((story.name=='Zombies on Campus'), True) self.assertEquals((story.description=='Zombies desciption'), True) self.assertEquals((story.picture=='testpic'), True) ## Instruction: Test case 2 for table storypoint ## Code After: from django.test import TestCase # Create your tests here. from django.test import TestCase from models import Story, StoryPoint class StoryMethodTests(TestCase): def test_ensure_story_is_inserted(self): story = Story(name="Zombies on Campus",visits=1,description='Zombies desciption',picture='testpic') story.save() self.assertEquals((story.visits==1), True) self.assertEquals((story.name=='Zombies on Campus'), True) self.assertEquals((story.description=='Zombies desciption'), True) self.assertEquals((story.picture=='testpic'), True) def test_ensure_storyPoints_is_inserted(self): storyPoint = StoryPoint(description='You are in the library',choiceText='yes',experience=10,story_type='start',main_story_id_id=5,visits=1,story_point_id=1,picture='testpic2') storyPoint.save() self.assertEquals((storyPoint.description=='You are in the library'),True) self.assertEquals((storyPoint.choiceText=='yes'),True) self.assertEquals((storyPoint.experience==10),True) self.assertEquals((storyPoint.story_type=='start'),True) self.assertEquals((storyPoint.story_point_id==1),True) self.assertEquals((storyPoint.picture=='testpic2'),True) self.assertEquals((storyPoint.visits==1),True) self.assertEquals((storyPoint.main_story_id_id==5),True)
2baed20067fed71987bf7582fa9c9a5e53a63cb5
python/ql/test/experimental/library-tests/frameworks/stdlib/SafeAccessCheck.py
python/ql/test/experimental/library-tests/frameworks/stdlib/SafeAccessCheck.py
s = "taintedString" if s.startswith("tainted"): # $checks=s $branch=true pass
s = "taintedString" if s.startswith("tainted"): # $checks=s $branch=true pass sw = s.startswith # $f-:checks=s $f-:branch=true if sw("safe"): pass
Test false negative from review
Python: Test false negative from review
Python
mit
github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql
s = "taintedString" if s.startswith("tainted"): # $checks=s $branch=true pass + sw = s.startswith # $f-:checks=s $f-:branch=true + if sw("safe"): + pass +
Test false negative from review
## Code Before: s = "taintedString" if s.startswith("tainted"): # $checks=s $branch=true pass ## Instruction: Test false negative from review ## Code After: s = "taintedString" if s.startswith("tainted"): # $checks=s $branch=true pass sw = s.startswith # $f-:checks=s $f-:branch=true if sw("safe"): pass
46ae5bbeab37f8e2fe14607c01e385d746c2d163
pymt/components.py
pymt/components.py
from __future__ import print_function __all__ = [] import os import sys import warnings import importlib from glob import glob from .framework.bmi_bridge import bmi_factory from .babel import setup_babel_environ def import_csdms_components(): debug = os.environ.get('PYMT_DEBUG', False) setup_babel_environ() if debug: print('Importing components with the following environment') for k, v in os.environ.items(): print('- {key}: {val}'.format(key=k, val=v)) try: csdms_module = importlib.import_module('csdms') except ImportError: warnings.warn('Unable to import csdms. Not loading components.') else: if debug: print('imported csdms module') files = glob(os.path.join(csdms_module.__path__[0], '*so')) _COMPONENT_NAMES = [ os.path.splitext(os.path.basename(f))[0] for f in files] if debug: print('found the following components') for name in _COMPONENT_NAMES: print('- {name}'.format(name=name)) for name in _COMPONENT_NAMES: module_name = '.'.join(['csdms', name]) try: module = importlib.import_module(module_name) except ImportError: if debug: print('unable to import {mod}'.format(mod=module_name)) else: if debug: print('imported {mod}'.format(mod=module_name)) if name in module.__dict__: try: setattr(sys.modules[__name__], name, bmi_factory(module.__dict__[name])) __all__.append(name) except Exception as err: print('warning: found csdms.{name} but was unable ' 'to wrap it'.format(name=name)) if debug: print(err) import_csdms_components()
__all__ = [] import sys from .plugin import load_csdms_plugins for plugin in load_csdms_plugins(): __all__.append(plugin.__name__) setattr(sys.modules[__name__], plugin.__name__, plugin)
Move csdms-plugin loading to plugin module.
Move csdms-plugin loading to plugin module.
Python
mit
csdms/pymt,csdms/coupling,csdms/coupling
- from __future__ import print_function - __all__ = [] - import os import sys + from .plugin import load_csdms_plugins - import warnings - import importlib - from glob import glob - - from .framework.bmi_bridge import bmi_factory - from .babel import setup_babel_environ + for plugin in load_csdms_plugins(): + __all__.append(plugin.__name__) + setattr(sys.modules[__name__], plugin.__name__, plugin) - def import_csdms_components(): - debug = os.environ.get('PYMT_DEBUG', False) - setup_babel_environ() - if debug: - print('Importing components with the following environment') - for k, v in os.environ.items(): - print('- {key}: {val}'.format(key=k, val=v)) - try: - csdms_module = importlib.import_module('csdms') - except ImportError: - warnings.warn('Unable to import csdms. Not loading components.') - else: - if debug: - print('imported csdms module') - files = glob(os.path.join(csdms_module.__path__[0], '*so')) - _COMPONENT_NAMES = [ - os.path.splitext(os.path.basename(f))[0] for f in files] - - if debug: - print('found the following components') - for name in _COMPONENT_NAMES: - print('- {name}'.format(name=name)) - - for name in _COMPONENT_NAMES: - module_name = '.'.join(['csdms', name]) - try: - module = importlib.import_module(module_name) - except ImportError: - if debug: - print('unable to import {mod}'.format(mod=module_name)) - else: - if debug: - print('imported {mod}'.format(mod=module_name)) - - if name in module.__dict__: - try: - setattr(sys.modules[__name__], name, - bmi_factory(module.__dict__[name])) - __all__.append(name) - except Exception as err: - print('warning: found csdms.{name} but was unable ' - 'to wrap it'.format(name=name)) - if debug: - print(err) - - - import_csdms_components() -
Move csdms-plugin loading to plugin module.
## Code Before: from __future__ import print_function __all__ = [] import os import sys import warnings import importlib from glob import glob from .framework.bmi_bridge import bmi_factory from .babel import setup_babel_environ def import_csdms_components(): debug = os.environ.get('PYMT_DEBUG', False) setup_babel_environ() if debug: print('Importing components with the following environment') for k, v in os.environ.items(): print('- {key}: {val}'.format(key=k, val=v)) try: csdms_module = importlib.import_module('csdms') except ImportError: warnings.warn('Unable to import csdms. Not loading components.') else: if debug: print('imported csdms module') files = glob(os.path.join(csdms_module.__path__[0], '*so')) _COMPONENT_NAMES = [ os.path.splitext(os.path.basename(f))[0] for f in files] if debug: print('found the following components') for name in _COMPONENT_NAMES: print('- {name}'.format(name=name)) for name in _COMPONENT_NAMES: module_name = '.'.join(['csdms', name]) try: module = importlib.import_module(module_name) except ImportError: if debug: print('unable to import {mod}'.format(mod=module_name)) else: if debug: print('imported {mod}'.format(mod=module_name)) if name in module.__dict__: try: setattr(sys.modules[__name__], name, bmi_factory(module.__dict__[name])) __all__.append(name) except Exception as err: print('warning: found csdms.{name} but was unable ' 'to wrap it'.format(name=name)) if debug: print(err) import_csdms_components() ## Instruction: Move csdms-plugin loading to plugin module. ## Code After: __all__ = [] import sys from .plugin import load_csdms_plugins for plugin in load_csdms_plugins(): __all__.append(plugin.__name__) setattr(sys.modules[__name__], plugin.__name__, plugin)
1e66aba5a2c82b09a6485842948aad49c654efb4
scripts/load_topics_to_mongodb.py
scripts/load_topics_to_mongodb.py
import os import csv from pymongo import MongoClient print('Parsing topics') topics = {} with open('topics.csv', 'rb') as csvfile: reader = csv.reader(csvfile) for line in reader: if line[0] == 1: continue topics[line[0]] = line[1:] print('Connecting to MongoDB') mongodb_client = MongoClient(os.environ['MONGODB_URL']) db = mongodb_client.tvrain articles = db.articles for article in topics: articles.update({'_id': article}, {'$set': { 'topics': topics[article] }})
import os import sys import csv from pymongo import MongoClient print('Parsing topics') topics = {} with open(sys.argv[1], 'r') as csvfile: reader = csv.reader(csvfile) for line in reader: if line[0] == 1: continue topics[line[0]] = line[1:] print('Connecting to MongoDB') mongodb_client = MongoClient(os.environ['MONGODB_URL']) db = mongodb_client.tvrain articles = db.articles for article in topics: articles.update({'_id': article}, {'$set': { 'topics': topics[article] }})
Fix script for loading topics into mongodb
Fix script for loading topics into mongodb
Python
mit
xenx/recommendation_system,xenx/recommendation_system
import os + import sys import csv from pymongo import MongoClient print('Parsing topics') topics = {} - with open('topics.csv', 'rb') as csvfile: + with open(sys.argv[1], 'r') as csvfile: reader = csv.reader(csvfile) for line in reader: if line[0] == 1: continue topics[line[0]] = line[1:] print('Connecting to MongoDB') mongodb_client = MongoClient(os.environ['MONGODB_URL']) db = mongodb_client.tvrain articles = db.articles for article in topics: articles.update({'_id': article}, {'$set': { 'topics': topics[article] }})
Fix script for loading topics into mongodb
## Code Before: import os import csv from pymongo import MongoClient print('Parsing topics') topics = {} with open('topics.csv', 'rb') as csvfile: reader = csv.reader(csvfile) for line in reader: if line[0] == 1: continue topics[line[0]] = line[1:] print('Connecting to MongoDB') mongodb_client = MongoClient(os.environ['MONGODB_URL']) db = mongodb_client.tvrain articles = db.articles for article in topics: articles.update({'_id': article}, {'$set': { 'topics': topics[article] }}) ## Instruction: Fix script for loading topics into mongodb ## Code After: import os import sys import csv from pymongo import MongoClient print('Parsing topics') topics = {} with open(sys.argv[1], 'r') as csvfile: reader = csv.reader(csvfile) for line in reader: if line[0] == 1: continue topics[line[0]] = line[1:] print('Connecting to MongoDB') mongodb_client = MongoClient(os.environ['MONGODB_URL']) db = mongodb_client.tvrain articles = db.articles for article in topics: articles.update({'_id': article}, {'$set': { 'topics': topics[article] }})
eefa28f06620d568eda641b08c1caa9cff9a0c96
resourcemanager.py
resourcemanager.py
import animation sounds = {} images = {} animations = {} loaded_resources = False def load_resources(): """Fills the structure above with the resources for the game. """ if loaded_resources: return loaded_resources = True
import pygame from pygame.locals import * import animation sounds = {} images = {} animations = {} loaded_resources = False sound_defs = { "aoe" : "aoe.wav", "big hit" : "big_hit.wav", "burstfire" : "burstfire.wav", "explosion" : "explosion.wav", "fireball" : "fireball.wav", "hover" : "heavy_hover.wav", "high pitch" : "high_pitch.wav", "jump" : "jump.wav", "long swing" : "longswing.wav", "pickaxe" : "pickaxe.wav", "pickup" : "pickup.wav", "select" : "select.wav", "short swing" : "shortswing.wav", "spell" : "spell.wav", "summon" : "summon.wav", "teleport" : "teleport.wav" } def load_resources(): """Fills the structure above with the resources for the game. """ if loaded_resources: return loaded_resources = True for name, filename in sound_defs.iteritems(): sounds[name] = pygame.mixer.Sound(filename)
Add sound definitions to resource manager
Add sound definitions to resource manager
Python
mit
vwood/pyweek2013
+ + import pygame + from pygame.locals import * import animation sounds = {} images = {} animations = {} loaded_resources = False + + sound_defs = { + "aoe" : "aoe.wav", + "big hit" : "big_hit.wav", + "burstfire" : "burstfire.wav", + "explosion" : "explosion.wav", + "fireball" : "fireball.wav", + "hover" : "heavy_hover.wav", + "high pitch" : "high_pitch.wav", + "jump" : "jump.wav", + "long swing" : "longswing.wav", + "pickaxe" : "pickaxe.wav", + "pickup" : "pickup.wav", + "select" : "select.wav", + "short swing" : "shortswing.wav", + "spell" : "spell.wav", + "summon" : "summon.wav", + "teleport" : "teleport.wav" + } + def load_resources(): """Fills the structure above with the resources for the game. """ if loaded_resources: return loaded_resources = True + + for name, filename in sound_defs.iteritems(): + sounds[name] = pygame.mixer.Sound(filename)
Add sound definitions to resource manager
## Code Before: import animation sounds = {} images = {} animations = {} loaded_resources = False def load_resources(): """Fills the structure above with the resources for the game. """ if loaded_resources: return loaded_resources = True ## Instruction: Add sound definitions to resource manager ## Code After: import pygame from pygame.locals import * import animation sounds = {} images = {} animations = {} loaded_resources = False sound_defs = { "aoe" : "aoe.wav", "big hit" : "big_hit.wav", "burstfire" : "burstfire.wav", "explosion" : "explosion.wav", "fireball" : "fireball.wav", "hover" : "heavy_hover.wav", "high pitch" : "high_pitch.wav", "jump" : "jump.wav", "long swing" : "longswing.wav", "pickaxe" : "pickaxe.wav", "pickup" : "pickup.wav", "select" : "select.wav", "short swing" : "shortswing.wav", "spell" : "spell.wav", "summon" : "summon.wav", "teleport" : "teleport.wav" } def load_resources(): """Fills the structure above with the resources for the game. """ if loaded_resources: return loaded_resources = True for name, filename in sound_defs.iteritems(): sounds[name] = pygame.mixer.Sound(filename)
e578c90cc542d3cf825645fa9376796a1e7c31f9
lib/cache.py
lib/cache.py
import functools import logging import redis import config # Default options redis_opts = { 'host': 'localhost', 'port': 6379, 'db': 0, 'password': None } redis_conn = None cache_prefix = None def init(): global redis_conn, cache_prefix cfg = config.load() cache = cfg.cache if not cache: return logging.info('Enabling storage cache on Redis') if not isinstance(cache, dict): cache = {} for k, v in cache.iteritems(): redis_opts[k] = v logging.info('Redis config: {0}'.format(redis_opts)) redis_conn = redis.StrictRedis(host=redis_opts['host'], port=int(redis_opts['port']), db=int(redis_opts['db']), password=redis_opts['password']) cache_prefix = 'cache_path:{0}'.format(cfg.get('storage_path', '/')) def cache_key(key): return cache_prefix + key def put(f): @functools.wraps(f) def wrapper(*args): content = args[-1] key = args[-2] key = cache_key(key) redis_conn.set(key, content) return f(*args) if redis_conn is None: return f return wrapper def get(f): @functools.wraps(f) def wrapper(*args): key = args[-1] key = cache_key(key) content = redis_conn.get(key) if content is not None: return content # Refresh cache content = f(*args) redis_conn.set(key, content) return content if redis_conn is None: return f return wrapper def remove(f): @functools.wraps(f) def wrapper(*args): key = args[-1] key = cache_key(key) redis_conn.delete(key) return f(*args) if redis_conn is None: return f return wrapper init()
import functools import logging import redis import config # Default options redis_opts = { 'host': 'localhost', 'port': 6379, 'db': 0, 'password': None } redis_conn = None cache_prefix = None def init(): global redis_conn, cache_prefix cfg = config.load() cache = cfg.cache if not cache: return logging.info('Enabling storage cache on Redis') if not isinstance(cache, dict): cache = {} for k, v in cache.iteritems(): redis_opts[k] = v logging.info('Redis config: {0}'.format(redis_opts)) redis_conn = redis.StrictRedis(host=redis_opts['host'], port=int(redis_opts['port']), db=int(redis_opts['db']), password=redis_opts['password']) cache_prefix = 'cache_path:{0}'.format(cfg.get('storage_path', '/')) init()
Remove unneeded lru specific helper methods
Remove unneeded lru specific helper methods
Python
apache-2.0
dalvikchen/docker-registry,atyenoria/docker-registry,atyenoria/docker-registry,ewindisch/docker-registry,docker/docker-registry,ken-saka/docker-registry,wakermahmud/docker-registry,Carrotzpc/docker-registry,kireal/docker-registry,ewindisch/docker-registry,yuriyf/docker-registry,whuwxl/docker-registry,Haitianisgood/docker-registry,GoogleCloudPlatform/docker-registry-driver-gcs,dedalusdev/docker-registry,cnh/docker-registry,HubSpot/docker-registry,yuriyf/docker-registry,deis/docker-registry,csrwng/docker-registry,wakermahmud/docker-registry,mdshuai/docker-registry,cnh/docker-registry,dalvikchen/docker-registry,dedalusdev/docker-registry,deis/docker-registry,alephcloud/docker-registry,depay/docker-registry,stormltf/docker-registry,docker/docker-registry,scrapinghub/docker-registry,pombredanne/docker-registry,depay/docker-registry,liggitt/docker-registry,atyenoria/docker-registry,dhiltgen/docker-registry,ken-saka/docker-registry,shipyard/docker-registry,stormltf/docker-registry,pombredanne/docker-registry,ActiveState/docker-registry,dhiltgen/docker-registry,nunogt/docker-registry,dalvikchen/docker-registry,HubSpot/docker-registry,andrew-plunk/docker-registry,shakamunyi/docker-registry,yuriyf/docker-registry,kireal/docker-registry,kireal/docker-registry,dhiltgen/docker-registry,mdshuai/docker-registry,HubSpot/docker-registry,fabianofranz/docker-registry,cnh/docker-registry,Haitianisgood/docker-registry,ptisserand/docker-registry,catalyst-zero/docker-registry,ken-saka/docker-registry,tangkun75/docker-registry,shakamunyi/docker-registry,mdshuai/docker-registry,GoogleCloudPlatform/docker-registry-driver-gcs,liggitt/docker-registry,dedalusdev/docker-registry,whuwxl/docker-registry,Carrotzpc/docker-registry,wakermahmud/docker-registry,deis/docker-registry,scrapinghub/docker-registry,hpcloud/docker-registry,ActiveState/docker-registry,viljaste/docker-registry-1,OnePaaS/docker-registry,OnePaaS/docker-registry,catalyst-zero/docker-registry,shakamunyi/docker-registry,hpcloud/docker-registry,tangkun75/docker-registry,csrwng/docker-registry,hpcloud/docker-registry,shipyard/docker-registry,mboersma/docker-registry,hex108/docker-registry,tangkun75/docker-registry,hex108/docker-registry,dine1987/Docker,Haitianisgood/docker-registry,fabianofranz/docker-registry,mboersma/docker-registry,Carrotzpc/docker-registry,ptisserand/docker-registry,nunogt/docker-registry,dine1987/Docker,ptisserand/docker-registry,docker/docker-registry,OnePaaS/docker-registry,andrew-plunk/docker-registry,scrapinghub/docker-registry,ActiveState/docker-registry,nunogt/docker-registry,mboersma/docker-registry,alephcloud/docker-registry,alephcloud/docker-registry,depay/docker-registry,csrwng/docker-registry,fabianofranz/docker-registry,shipyard/docker-registry,hex108/docker-registry,stormltf/docker-registry,whuwxl/docker-registry,viljaste/docker-registry-1,pombredanne/docker-registry,ewindisch/docker-registry,andrew-plunk/docker-registry,dine1987/Docker,viljaste/docker-registry-1,liggitt/docker-registry,catalyst-zero/docker-registry
import functools import logging import redis import config # Default options redis_opts = { 'host': 'localhost', 'port': 6379, 'db': 0, 'password': None } redis_conn = None cache_prefix = None def init(): global redis_conn, cache_prefix cfg = config.load() cache = cfg.cache if not cache: return logging.info('Enabling storage cache on Redis') if not isinstance(cache, dict): cache = {} for k, v in cache.iteritems(): redis_opts[k] = v logging.info('Redis config: {0}'.format(redis_opts)) redis_conn = redis.StrictRedis(host=redis_opts['host'], port=int(redis_opts['port']), db=int(redis_opts['db']), password=redis_opts['password']) cache_prefix = 'cache_path:{0}'.format(cfg.get('storage_path', '/')) - def cache_key(key): - return cache_prefix + key - - - def put(f): - @functools.wraps(f) - def wrapper(*args): - content = args[-1] - key = args[-2] - key = cache_key(key) - redis_conn.set(key, content) - return f(*args) - if redis_conn is None: - return f - return wrapper - - - def get(f): - @functools.wraps(f) - def wrapper(*args): - key = args[-1] - key = cache_key(key) - content = redis_conn.get(key) - if content is not None: - return content - # Refresh cache - content = f(*args) - redis_conn.set(key, content) - return content - if redis_conn is None: - return f - return wrapper - - - def remove(f): - @functools.wraps(f) - def wrapper(*args): - key = args[-1] - key = cache_key(key) - redis_conn.delete(key) - return f(*args) - if redis_conn is None: - return f - return wrapper - - init()
Remove unneeded lru specific helper methods
## Code Before: import functools import logging import redis import config # Default options redis_opts = { 'host': 'localhost', 'port': 6379, 'db': 0, 'password': None } redis_conn = None cache_prefix = None def init(): global redis_conn, cache_prefix cfg = config.load() cache = cfg.cache if not cache: return logging.info('Enabling storage cache on Redis') if not isinstance(cache, dict): cache = {} for k, v in cache.iteritems(): redis_opts[k] = v logging.info('Redis config: {0}'.format(redis_opts)) redis_conn = redis.StrictRedis(host=redis_opts['host'], port=int(redis_opts['port']), db=int(redis_opts['db']), password=redis_opts['password']) cache_prefix = 'cache_path:{0}'.format(cfg.get('storage_path', '/')) def cache_key(key): return cache_prefix + key def put(f): @functools.wraps(f) def wrapper(*args): content = args[-1] key = args[-2] key = cache_key(key) redis_conn.set(key, content) return f(*args) if redis_conn is None: return f return wrapper def get(f): @functools.wraps(f) def wrapper(*args): key = args[-1] key = cache_key(key) content = redis_conn.get(key) if content is not None: return content # Refresh cache content = f(*args) redis_conn.set(key, content) return content if redis_conn is None: return f return wrapper def remove(f): @functools.wraps(f) def wrapper(*args): key = args[-1] key = cache_key(key) redis_conn.delete(key) return f(*args) if redis_conn is None: return f return wrapper init() ## Instruction: Remove unneeded lru specific helper methods ## Code After: import functools import logging import redis import config # Default options redis_opts = { 'host': 'localhost', 'port': 6379, 'db': 0, 'password': None } redis_conn = None cache_prefix = None def init(): global redis_conn, cache_prefix cfg = config.load() cache = cfg.cache if not cache: return logging.info('Enabling storage cache on Redis') if not isinstance(cache, dict): cache = {} for k, v in cache.iteritems(): redis_opts[k] = v logging.info('Redis config: {0}'.format(redis_opts)) redis_conn = redis.StrictRedis(host=redis_opts['host'], port=int(redis_opts['port']), db=int(redis_opts['db']), password=redis_opts['password']) cache_prefix = 'cache_path:{0}'.format(cfg.get('storage_path', '/')) init()
52bb18cf1249e3f48764a7ed4e9546439692c5cb
packages/Python/lldbsuite/test/functionalities/data-formatter/synthcapping/fooSynthProvider.py
packages/Python/lldbsuite/test/functionalities/data-formatter/synthcapping/fooSynthProvider.py
import lldb class fooSynthProvider: def __init__(self, valobj, dict): self.valobj = valobj; self.int_type = valobj.GetType().GetBasicType(lldb.eBasicTypeInt) def num_children(self): return 3; def get_child_at_index(self, index): if index == 0: child = self.valobj.GetChildMemberWithName('a'); if index == 1: child = self.valobj.CreateChildAtOffset ('fake_a', 1, self.int_type); if index == 2: child = self.valobj.GetChildMemberWithName('r'); return child; def get_child_index(self, name): if name == 'a': return 0; if name == 'fake_a': return 1; return 2;
import lldb class fooSynthProvider: def __init__(self, valobj, dict): self.valobj = valobj; self.int_type = valobj.GetType().GetBasicType(lldb.eBasicTypeInt) def num_children(self): return 3; def get_child_at_index(self, index): if index == 0: child = self.valobj.GetChildMemberWithName('a'); if index == 1: child = self.valobj.CreateChildAtOffset ('fake_a', 1, self.int_type); if index == 2: child = self.valobj.GetChildMemberWithName('r'); return child; def get_child_index(self, name): if name == 'a': return 0; if name == 'fake_a': return 1; return 2;
Fix TestSyntheticCapping for Python 3.
Fix TestSyntheticCapping for Python 3. In Python 3, whitespace inconsistences are errors. This synthetic provider had mixed tabs and spaces, as well as inconsistent indentation widths. This led to the file not being imported, and naturally the test failing. No functional change here, just whitespace. git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@258751 91177308-0d34-0410-b5e6-96231b3b80d8
Python
apache-2.0
llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb,apple/swift-lldb
import lldb class fooSynthProvider: - def __init__(self, valobj, dict): + def __init__(self, valobj, dict): - self.valobj = valobj; + self.valobj = valobj; - self.int_type = valobj.GetType().GetBasicType(lldb.eBasicTypeInt) + self.int_type = valobj.GetType().GetBasicType(lldb.eBasicTypeInt) - def num_children(self): + def num_children(self): - return 3; + return 3; - def get_child_at_index(self, index): + def get_child_at_index(self, index): - if index == 0: + if index == 0: - child = self.valobj.GetChildMemberWithName('a'); + child = self.valobj.GetChildMemberWithName('a'); - if index == 1: + if index == 1: - child = self.valobj.CreateChildAtOffset ('fake_a', 1, self.int_type); + child = self.valobj.CreateChildAtOffset ('fake_a', 1, self.int_type); - if index == 2: + if index == 2: - child = self.valobj.GetChildMemberWithName('r'); + child = self.valobj.GetChildMemberWithName('r'); - return child; + return child; - def get_child_index(self, name): + def get_child_index(self, name): - if name == 'a': + if name == 'a': - return 0; + return 0; - if name == 'fake_a': + if name == 'fake_a': - return 1; + return 1; - return 2; + return 2;
Fix TestSyntheticCapping for Python 3.
## Code Before: import lldb class fooSynthProvider: def __init__(self, valobj, dict): self.valobj = valobj; self.int_type = valobj.GetType().GetBasicType(lldb.eBasicTypeInt) def num_children(self): return 3; def get_child_at_index(self, index): if index == 0: child = self.valobj.GetChildMemberWithName('a'); if index == 1: child = self.valobj.CreateChildAtOffset ('fake_a', 1, self.int_type); if index == 2: child = self.valobj.GetChildMemberWithName('r'); return child; def get_child_index(self, name): if name == 'a': return 0; if name == 'fake_a': return 1; return 2; ## Instruction: Fix TestSyntheticCapping for Python 3. ## Code After: import lldb class fooSynthProvider: def __init__(self, valobj, dict): self.valobj = valobj; self.int_type = valobj.GetType().GetBasicType(lldb.eBasicTypeInt) def num_children(self): return 3; def get_child_at_index(self, index): if index == 0: child = self.valobj.GetChildMemberWithName('a'); if index == 1: child = self.valobj.CreateChildAtOffset ('fake_a', 1, self.int_type); if index == 2: child = self.valobj.GetChildMemberWithName('r'); return child; def get_child_index(self, name): if name == 'a': return 0; if name == 'fake_a': return 1; return 2;
f012d59f163a8b8a693dc894d211f077ae015d11
Instanssi/kompomaatti/tests.py
Instanssi/kompomaatti/tests.py
from django.test import TestCase from Instanssi.kompomaatti.models import Entry VALID_YOUTUBE_URLS = [ # must handle various protocols in the video URL "http://www.youtube.com/v/asdf123456", "https://www.youtube.com/v/asdf123456/", "//www.youtube.com/v/asdf123456", "www.youtube.com/v/asdf123456", # must handle various other ways to define the video "www.youtube.com/watch?v=asdf123456", "http://youtu.be/asdf123456", "http://youtu.be/asdf123456/" ] class KompomaattiTests(TestCase): def setUp(self): pass def test_youtube_urls(self): """Test that various YouTube URLs are parsed properly.""" for url in VALID_YOUTUBE_URLS: print("Test URL: %s" % url) self.assertEqual(Entry.youtube_url_to_id(url), "asdf123456")
from django.test import TestCase from Instanssi.kompomaatti.models import Entry VALID_YOUTUBE_URLS = [ # must handle various protocols and hostnames in the video URL "http://www.youtube.com/v/asdf123456", "https://www.youtube.com/v/asdf123456/", "//www.youtube.com/v/asdf123456", "www.youtube.com/v/asdf123456", "youtube.com/v/asdf123456/", # must handle various other ways to define the video "www.youtube.com/watch?v=asdf123456", "http://youtu.be/asdf123456", "https://youtu.be/asdf123456/" ] class KompomaattiTests(TestCase): def setUp(self): pass def test_youtube_urls(self): """Test YouTube video id extraction from URLs.""" for url in VALID_YOUTUBE_URLS: self.assertEqual(Entry.youtube_url_to_id(url), "asdf123456", msg="failing URL: %s" % url)
Add more test data; improve feedback on failing case
kompomaatti: Add more test data; improve feedback on failing case
Python
mit
Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org
from django.test import TestCase from Instanssi.kompomaatti.models import Entry VALID_YOUTUBE_URLS = [ - # must handle various protocols in the video URL + # must handle various protocols and hostnames in the video URL "http://www.youtube.com/v/asdf123456", "https://www.youtube.com/v/asdf123456/", "//www.youtube.com/v/asdf123456", "www.youtube.com/v/asdf123456", + "youtube.com/v/asdf123456/", # must handle various other ways to define the video "www.youtube.com/watch?v=asdf123456", "http://youtu.be/asdf123456", - "http://youtu.be/asdf123456/" + "https://youtu.be/asdf123456/" ] class KompomaattiTests(TestCase): def setUp(self): pass def test_youtube_urls(self): - """Test that various YouTube URLs are parsed properly.""" + """Test YouTube video id extraction from URLs.""" for url in VALID_YOUTUBE_URLS: - print("Test URL: %s" % url) - self.assertEqual(Entry.youtube_url_to_id(url), "asdf123456") + self.assertEqual(Entry.youtube_url_to_id(url), "asdf123456", + msg="failing URL: %s" % url)
Add more test data; improve feedback on failing case
## Code Before: from django.test import TestCase from Instanssi.kompomaatti.models import Entry VALID_YOUTUBE_URLS = [ # must handle various protocols in the video URL "http://www.youtube.com/v/asdf123456", "https://www.youtube.com/v/asdf123456/", "//www.youtube.com/v/asdf123456", "www.youtube.com/v/asdf123456", # must handle various other ways to define the video "www.youtube.com/watch?v=asdf123456", "http://youtu.be/asdf123456", "http://youtu.be/asdf123456/" ] class KompomaattiTests(TestCase): def setUp(self): pass def test_youtube_urls(self): """Test that various YouTube URLs are parsed properly.""" for url in VALID_YOUTUBE_URLS: print("Test URL: %s" % url) self.assertEqual(Entry.youtube_url_to_id(url), "asdf123456") ## Instruction: Add more test data; improve feedback on failing case ## Code After: from django.test import TestCase from Instanssi.kompomaatti.models import Entry VALID_YOUTUBE_URLS = [ # must handle various protocols and hostnames in the video URL "http://www.youtube.com/v/asdf123456", "https://www.youtube.com/v/asdf123456/", "//www.youtube.com/v/asdf123456", "www.youtube.com/v/asdf123456", "youtube.com/v/asdf123456/", # must handle various other ways to define the video "www.youtube.com/watch?v=asdf123456", "http://youtu.be/asdf123456", "https://youtu.be/asdf123456/" ] class KompomaattiTests(TestCase): def setUp(self): pass def test_youtube_urls(self): """Test YouTube video id extraction from URLs.""" for url in VALID_YOUTUBE_URLS: self.assertEqual(Entry.youtube_url_to_id(url), "asdf123456", msg="failing URL: %s" % url)
948c9c6ffb8a34e3acf00b8190bf65504f2bfaf6
app.py
app.py
import falcon from resources.waifu_message_resource import WaifuMessageResource api = falcon.API() api.add_route('/waifu/messages', WaifuMessageResource())
import falcon from resources.user_resource import UserResource, UserAuthResource from resources.waifu_message_resource import WaifuMessageResource from resources.waifu_resource import WaifuResource api = falcon.API() api.add_route('/user', UserResource()) api.add_route('/user/auth', UserAuthResource()) api.add_route('/waifu', WaifuResource()) api.add_route('/waifu/messages', WaifuMessageResource())
Add endpoints for all resources.
Add endpoints for all resources.
Python
cc0-1.0
sketchturnerr/WaifuSim-backend,sketchturnerr/WaifuSim-backend
import falcon + from resources.user_resource import UserResource, UserAuthResource from resources.waifu_message_resource import WaifuMessageResource + from resources.waifu_resource import WaifuResource api = falcon.API() + + api.add_route('/user', UserResource()) + api.add_route('/user/auth', UserAuthResource()) + api.add_route('/waifu', WaifuResource()) api.add_route('/waifu/messages', WaifuMessageResource())
Add endpoints for all resources.
## Code Before: import falcon from resources.waifu_message_resource import WaifuMessageResource api = falcon.API() api.add_route('/waifu/messages', WaifuMessageResource()) ## Instruction: Add endpoints for all resources. ## Code After: import falcon from resources.user_resource import UserResource, UserAuthResource from resources.waifu_message_resource import WaifuMessageResource from resources.waifu_resource import WaifuResource api = falcon.API() api.add_route('/user', UserResource()) api.add_route('/user/auth', UserAuthResource()) api.add_route('/waifu', WaifuResource()) api.add_route('/waifu/messages', WaifuMessageResource())
9d65eaa14bc3f04ea998ed7bc43b7c71e5d232f7
v3/scripts/testing/create-8gb-metadata.py
v3/scripts/testing/create-8gb-metadata.py
__author__ = 'eric' ''' Need to create some test data '''
__author__ = 'eric' ''' Need to create some test data 8 gigabytes dataset '''
Test script for generating metadata
Test script for generating metadata
Python
mit
TheShellLand/pies,TheShellLand/pies
__author__ = 'eric' ''' Need to create some test data + 8 gigabytes dataset ''' +
Test script for generating metadata
## Code Before: __author__ = 'eric' ''' Need to create some test data ''' ## Instruction: Test script for generating metadata ## Code After: __author__ = 'eric' ''' Need to create some test data 8 gigabytes dataset '''
53d09ddacc92a52219a3cd18bba606840b870fcd
vumi_http_proxy/test/test_servicemaker.py
vumi_http_proxy/test/test_servicemaker.py
from vumi_http_proxy.servicemaker import Options, ProxyWorkerServiceMaker from vumi_http_proxy import http_proxy from twisted.trial import unittest class TestOptions(unittest.TestCase): def test_defaults(self): options = Options() options.parseOptions([]) self.assertEqual(options["port"], 8080) self.assertEqual(str(options["interface"]), "0.0.0.0") def test_override(self): options = Options() options.parseOptions(["--port", 8000]) options.parseOptions(["--interface", "127.0.0.1"]) self.assertEqual(options["port"], "8000") self.assertEqual(str(options["interface"]), "127.0.0.1") class TestProxyWorkerServiceMaker(unittest.TestCase): def test_makeService(self): options = Options() options.parseOptions([]) servicemaker = ProxyWorkerServiceMaker() service = servicemaker.makeService(options) self.assertTrue(isinstance(service.factory, http_proxy.ProxyFactory)) self.assertEqual(service.endpoint._interface, '0.0.0.0') self.assertEqual(service.endpoint._port, 8080)
from vumi_http_proxy.servicemaker import ( Options, ProxyWorkerServiceMaker, client) from vumi_http_proxy import http_proxy from twisted.trial import unittest from vumi_http_proxy.test import helpers class TestOptions(unittest.TestCase): def test_defaults(self): options = Options() options.parseOptions([]) self.assertEqual(options["port"], 8080) self.assertEqual(str(options["interface"]), "0.0.0.0") def test_override(self): options = Options() options.parseOptions(["--port", 8000]) options.parseOptions(["--interface", "127.0.0.1"]) self.assertEqual(options["port"], "8000") self.assertEqual(str(options["interface"]), "127.0.0.1") class TestProxyWorkerServiceMaker(unittest.TestCase): def test_makeService(self): options = Options() options.parseOptions([]) self.patch(client, 'createResolver', lambda: helpers.TestResolver()) servicemaker = ProxyWorkerServiceMaker() service = servicemaker.makeService(options) self.assertTrue(isinstance(service.factory, http_proxy.ProxyFactory)) self.assertEqual(service.endpoint._interface, '0.0.0.0') self.assertEqual(service.endpoint._port, 8080)
Patch out DNS resolver in makeService tests.
Patch out DNS resolver in makeService tests.
Python
bsd-3-clause
praekelt/vumi-http-proxy,praekelt/vumi-http-proxy
- from vumi_http_proxy.servicemaker import Options, ProxyWorkerServiceMaker + from vumi_http_proxy.servicemaker import ( + Options, ProxyWorkerServiceMaker, client) from vumi_http_proxy import http_proxy from twisted.trial import unittest + from vumi_http_proxy.test import helpers class TestOptions(unittest.TestCase): def test_defaults(self): options = Options() options.parseOptions([]) self.assertEqual(options["port"], 8080) self.assertEqual(str(options["interface"]), "0.0.0.0") def test_override(self): options = Options() options.parseOptions(["--port", 8000]) options.parseOptions(["--interface", "127.0.0.1"]) self.assertEqual(options["port"], "8000") self.assertEqual(str(options["interface"]), "127.0.0.1") class TestProxyWorkerServiceMaker(unittest.TestCase): def test_makeService(self): options = Options() options.parseOptions([]) + self.patch(client, 'createResolver', lambda: helpers.TestResolver()) servicemaker = ProxyWorkerServiceMaker() service = servicemaker.makeService(options) self.assertTrue(isinstance(service.factory, http_proxy.ProxyFactory)) self.assertEqual(service.endpoint._interface, '0.0.0.0') self.assertEqual(service.endpoint._port, 8080)
Patch out DNS resolver in makeService tests.
## Code Before: from vumi_http_proxy.servicemaker import Options, ProxyWorkerServiceMaker from vumi_http_proxy import http_proxy from twisted.trial import unittest class TestOptions(unittest.TestCase): def test_defaults(self): options = Options() options.parseOptions([]) self.assertEqual(options["port"], 8080) self.assertEqual(str(options["interface"]), "0.0.0.0") def test_override(self): options = Options() options.parseOptions(["--port", 8000]) options.parseOptions(["--interface", "127.0.0.1"]) self.assertEqual(options["port"], "8000") self.assertEqual(str(options["interface"]), "127.0.0.1") class TestProxyWorkerServiceMaker(unittest.TestCase): def test_makeService(self): options = Options() options.parseOptions([]) servicemaker = ProxyWorkerServiceMaker() service = servicemaker.makeService(options) self.assertTrue(isinstance(service.factory, http_proxy.ProxyFactory)) self.assertEqual(service.endpoint._interface, '0.0.0.0') self.assertEqual(service.endpoint._port, 8080) ## Instruction: Patch out DNS resolver in makeService tests. ## Code After: from vumi_http_proxy.servicemaker import ( Options, ProxyWorkerServiceMaker, client) from vumi_http_proxy import http_proxy from twisted.trial import unittest from vumi_http_proxy.test import helpers class TestOptions(unittest.TestCase): def test_defaults(self): options = Options() options.parseOptions([]) self.assertEqual(options["port"], 8080) self.assertEqual(str(options["interface"]), "0.0.0.0") def test_override(self): options = Options() options.parseOptions(["--port", 8000]) options.parseOptions(["--interface", "127.0.0.1"]) self.assertEqual(options["port"], "8000") self.assertEqual(str(options["interface"]), "127.0.0.1") class TestProxyWorkerServiceMaker(unittest.TestCase): def test_makeService(self): options = Options() options.parseOptions([]) self.patch(client, 'createResolver', lambda: helpers.TestResolver()) servicemaker = ProxyWorkerServiceMaker() service = servicemaker.makeService(options) self.assertTrue(isinstance(service.factory, http_proxy.ProxyFactory)) self.assertEqual(service.endpoint._interface, '0.0.0.0') self.assertEqual(service.endpoint._port, 8080)
2cde3dbb69077054c6422cbe96e9b996be700d29
pulldb/api/subscriptions.py
pulldb/api/subscriptions.py
import json import logging from google.appengine.api import oauth from google.appengine.ext import ndb from pulldb import users from pulldb.api.base import OauthHandler, JsonModel from pulldb.base import create_app, Route from pulldb.models.subscriptions import Subscription, subscription_context class ListSubs(OauthHandler): def get(self): user_key = users.user_key(oauth.get_current_user(self.scope)) query = Subscription.query(ancestor=user_key) results = query.map(subscription_context) self.response.write(JsonModel().encode(list(results))) app = create_app([ Route('/api/subscriptions/list', 'pulldb.api.subscriptions.ListSubs'), ])
import json import logging from google.appengine.api import oauth from google.appengine.ext import ndb from pulldb import users from pulldb.api.base import OauthHandler, JsonModel from pulldb.base import create_app, Route from pulldb.models.subscriptions import Subscription, subscription_context class ListSubs(OauthHandler): def get(self): user_key = users.user_key(self.user) query = Subscription.query(ancestor=user_key) results = query.map(subscription_context) self.response.write(JsonModel().encode(list(results))) app = create_app([ Route('/api/subscriptions/list', 'pulldb.api.subscriptions.ListSubs'), ])
Make subscription handler less oauth dependant
Make subscription handler less oauth dependant
Python
mit
xchewtoyx/pulldb
import json import logging from google.appengine.api import oauth from google.appengine.ext import ndb from pulldb import users from pulldb.api.base import OauthHandler, JsonModel from pulldb.base import create_app, Route from pulldb.models.subscriptions import Subscription, subscription_context class ListSubs(OauthHandler): def get(self): - user_key = users.user_key(oauth.get_current_user(self.scope)) + user_key = users.user_key(self.user) query = Subscription.query(ancestor=user_key) results = query.map(subscription_context) self.response.write(JsonModel().encode(list(results))) app = create_app([ Route('/api/subscriptions/list', 'pulldb.api.subscriptions.ListSubs'), ])
Make subscription handler less oauth dependant
## Code Before: import json import logging from google.appengine.api import oauth from google.appengine.ext import ndb from pulldb import users from pulldb.api.base import OauthHandler, JsonModel from pulldb.base import create_app, Route from pulldb.models.subscriptions import Subscription, subscription_context class ListSubs(OauthHandler): def get(self): user_key = users.user_key(oauth.get_current_user(self.scope)) query = Subscription.query(ancestor=user_key) results = query.map(subscription_context) self.response.write(JsonModel().encode(list(results))) app = create_app([ Route('/api/subscriptions/list', 'pulldb.api.subscriptions.ListSubs'), ]) ## Instruction: Make subscription handler less oauth dependant ## Code After: import json import logging from google.appengine.api import oauth from google.appengine.ext import ndb from pulldb import users from pulldb.api.base import OauthHandler, JsonModel from pulldb.base import create_app, Route from pulldb.models.subscriptions import Subscription, subscription_context class ListSubs(OauthHandler): def get(self): user_key = users.user_key(self.user) query = Subscription.query(ancestor=user_key) results = query.map(subscription_context) self.response.write(JsonModel().encode(list(results))) app = create_app([ Route('/api/subscriptions/list', 'pulldb.api.subscriptions.ListSubs'), ])
709d4386a308ce8c0767eab1f2174ec321ea59fd
client/main.py
client/main.py
import requests import yaml def runLoop( config ): """ Runs indefinitely. On user input (card swipe), will gather the card number, send it to the server configured, and if it has been authorized, open the relay with a GPIO call. """ while True: swipe = input() cardNumber = swipe print( 'The last input was ' + cardNumber ) try: res = queryServer( cardNumber, config ) except requests.exceptions.Timeout: print( "Server timeout!" ) continue if res['isAuthorized']: # open the relay here pass def queryServer( cardNumber, config ): url = 'http://' + str( config['serverAddress'] ) + ':' + str( config['serverPort'] ) req = requests.get( url, { 'cardNumber': cardNumber, 'machineID': config['machineID'], 'machineType': config['machineType'] }, timeout=config['timeout'] ) return req.json() if __name__ == '__main__': # read and return a yaml file (called 'config.yaml' by default) and give it # back as a dictionary with open( 'config.yaml' ) as f: config = yaml.load( f ) # run the main loop runLoop( config )
import requests import yaml def runLoop( config ): """ Runs indefinitely. On user input (card swipe), will gather the card number, send it to the server configured, and if it has been authorized, open the relay with a GPIO call. """ while True: swipe = input() cardNumber = swipe print( 'The last input was ' + cardNumber ) try: res = requestAuthorization( cardNumber, config ) except requests.exceptions.Timeout: print( "Server timeout!" ) continue if res['isAuthorized']: # open the relay here pass def requestAuthorization( cardNumber, config ): url = 'http://' + str( config['serverAddress'] ) + ':' + str( config['serverPort'] ) path = '/users/checkAuthorization' req = requests.get( url + path, { 'cardNumber': cardNumber, 'machineID': config['machineID'], 'machineType': config['machineType'] }, timeout=config['timeout'] ) return req.json() if __name__ == '__main__': # read and return a yaml file (called 'config.yaml' by default) and give it # back as a dictionary with open( 'config.yaml' ) as f: config = yaml.load( f ) # run the main loop runLoop( config )
Rename funciton to match corresponding HTTP request
Rename funciton to match corresponding HTTP request
Python
mit
aradler/Card-lockout,aradler/Card-lockout,aradler/Card-lockout
import requests import yaml def runLoop( config ): """ Runs indefinitely. On user input (card swipe), will gather the card number, send it to the server configured, and if it has been authorized, open the relay with a GPIO call. """ while True: swipe = input() cardNumber = swipe print( 'The last input was ' + cardNumber ) try: - res = queryServer( cardNumber, config ) + res = requestAuthorization( cardNumber, config ) except requests.exceptions.Timeout: print( "Server timeout!" ) continue if res['isAuthorized']: # open the relay here pass - def queryServer( cardNumber, config ): + def requestAuthorization( cardNumber, config ): url = 'http://' + str( config['serverAddress'] ) + ':' + str( config['serverPort'] ) + path = '/users/checkAuthorization' - req = requests.get( url, { + req = requests.get( url + path, { 'cardNumber': cardNumber, 'machineID': config['machineID'], 'machineType': config['machineType'] }, timeout=config['timeout'] ) return req.json() if __name__ == '__main__': # read and return a yaml file (called 'config.yaml' by default) and give it # back as a dictionary with open( 'config.yaml' ) as f: config = yaml.load( f ) # run the main loop runLoop( config )
Rename funciton to match corresponding HTTP request
## Code Before: import requests import yaml def runLoop( config ): """ Runs indefinitely. On user input (card swipe), will gather the card number, send it to the server configured, and if it has been authorized, open the relay with a GPIO call. """ while True: swipe = input() cardNumber = swipe print( 'The last input was ' + cardNumber ) try: res = queryServer( cardNumber, config ) except requests.exceptions.Timeout: print( "Server timeout!" ) continue if res['isAuthorized']: # open the relay here pass def queryServer( cardNumber, config ): url = 'http://' + str( config['serverAddress'] ) + ':' + str( config['serverPort'] ) req = requests.get( url, { 'cardNumber': cardNumber, 'machineID': config['machineID'], 'machineType': config['machineType'] }, timeout=config['timeout'] ) return req.json() if __name__ == '__main__': # read and return a yaml file (called 'config.yaml' by default) and give it # back as a dictionary with open( 'config.yaml' ) as f: config = yaml.load( f ) # run the main loop runLoop( config ) ## Instruction: Rename funciton to match corresponding HTTP request ## Code After: import requests import yaml def runLoop( config ): """ Runs indefinitely. On user input (card swipe), will gather the card number, send it to the server configured, and if it has been authorized, open the relay with a GPIO call. """ while True: swipe = input() cardNumber = swipe print( 'The last input was ' + cardNumber ) try: res = requestAuthorization( cardNumber, config ) except requests.exceptions.Timeout: print( "Server timeout!" ) continue if res['isAuthorized']: # open the relay here pass def requestAuthorization( cardNumber, config ): url = 'http://' + str( config['serverAddress'] ) + ':' + str( config['serverPort'] ) path = '/users/checkAuthorization' req = requests.get( url + path, { 'cardNumber': cardNumber, 'machineID': config['machineID'], 'machineType': config['machineType'] }, timeout=config['timeout'] ) return req.json() if __name__ == '__main__': # read and return a yaml file (called 'config.yaml' by default) and give it # back as a dictionary with open( 'config.yaml' ) as f: config = yaml.load( f ) # run the main loop runLoop( config )
7206d68648c91790ac4fa14a3074c77c97c01636
mopidy/backends/base/__init__.py
mopidy/backends/base/__init__.py
import logging from .current_playlist import CurrentPlaylistController from .library import LibraryController, BaseLibraryProvider from .playback import PlaybackController, BasePlaybackProvider from .stored_playlists import (StoredPlaylistsController, BaseStoredPlaylistsProvider) logger = logging.getLogger('mopidy.backends.base') class Backend(object): #: The current playlist controller. An instance of #: :class:`mopidy.backends.base.CurrentPlaylistController`. current_playlist = None #: The library controller. An instance of # :class:`mopidy.backends.base.LibraryController`. library = None #: The sound mixer. An instance of :class:`mopidy.mixers.BaseMixer`. mixer = None #: The playback controller. An instance of #: :class:`mopidy.backends.base.PlaybackController`. playback = None #: The stored playlists controller. An instance of #: :class:`mopidy.backends.base.StoredPlaylistsController`. stored_playlists = None #: List of URI prefixes this backend can handle. uri_handlers = []
import logging from .current_playlist import CurrentPlaylistController from .library import LibraryController, BaseLibraryProvider from .playback import PlaybackController, BasePlaybackProvider from .stored_playlists import (StoredPlaylistsController, BaseStoredPlaylistsProvider) logger = logging.getLogger('mopidy.backends.base') class Backend(object): #: The current playlist controller. An instance of #: :class:`mopidy.backends.base.CurrentPlaylistController`. current_playlist = None #: The library controller. An instance of # :class:`mopidy.backends.base.LibraryController`. library = None #: The playback controller. An instance of #: :class:`mopidy.backends.base.PlaybackController`. playback = None #: The stored playlists controller. An instance of #: :class:`mopidy.backends.base.StoredPlaylistsController`. stored_playlists = None #: List of URI prefixes this backend can handle. uri_handlers = []
Remove mixer from the Backend API as it is independent
Remove mixer from the Backend API as it is independent
Python
apache-2.0
adamcik/mopidy,vrs01/mopidy,pacificIT/mopidy,jmarsik/mopidy,jcass77/mopidy,glogiotatidis/mopidy,kingosticks/mopidy,ZenithDK/mopidy,rawdlite/mopidy,glogiotatidis/mopidy,ZenithDK/mopidy,tkem/mopidy,kingosticks/mopidy,jmarsik/mopidy,SuperStarPL/mopidy,bencevans/mopidy,diandiankan/mopidy,quartz55/mopidy,glogiotatidis/mopidy,quartz55/mopidy,priestd09/mopidy,pacificIT/mopidy,SuperStarPL/mopidy,bacontext/mopidy,rawdlite/mopidy,mopidy/mopidy,bencevans/mopidy,pacificIT/mopidy,jodal/mopidy,diandiankan/mopidy,mopidy/mopidy,abarisain/mopidy,tkem/mopidy,SuperStarPL/mopidy,abarisain/mopidy,jmarsik/mopidy,woutervanwijk/mopidy,bacontext/mopidy,adamcik/mopidy,swak/mopidy,ZenithDK/mopidy,quartz55/mopidy,hkariti/mopidy,vrs01/mopidy,ali/mopidy,vrs01/mopidy,woutervanwijk/mopidy,ali/mopidy,jodal/mopidy,dbrgn/mopidy,jmarsik/mopidy,jcass77/mopidy,ali/mopidy,jcass77/mopidy,liamw9534/mopidy,pacificIT/mopidy,hkariti/mopidy,glogiotatidis/mopidy,dbrgn/mopidy,swak/mopidy,adamcik/mopidy,priestd09/mopidy,dbrgn/mopidy,mokieyue/mopidy,kingosticks/mopidy,tkem/mopidy,liamw9534/mopidy,rawdlite/mopidy,quartz55/mopidy,priestd09/mopidy,vrs01/mopidy,ali/mopidy,mokieyue/mopidy,bencevans/mopidy,bencevans/mopidy,mokieyue/mopidy,diandiankan/mopidy,bacontext/mopidy,jodal/mopidy,mopidy/mopidy,hkariti/mopidy,dbrgn/mopidy,ZenithDK/mopidy,tkem/mopidy,swak/mopidy,bacontext/mopidy,swak/mopidy,mokieyue/mopidy,rawdlite/mopidy,diandiankan/mopidy,hkariti/mopidy,SuperStarPL/mopidy
import logging from .current_playlist import CurrentPlaylistController from .library import LibraryController, BaseLibraryProvider from .playback import PlaybackController, BasePlaybackProvider from .stored_playlists import (StoredPlaylistsController, BaseStoredPlaylistsProvider) logger = logging.getLogger('mopidy.backends.base') class Backend(object): #: The current playlist controller. An instance of #: :class:`mopidy.backends.base.CurrentPlaylistController`. current_playlist = None #: The library controller. An instance of # :class:`mopidy.backends.base.LibraryController`. library = None - #: The sound mixer. An instance of :class:`mopidy.mixers.BaseMixer`. - mixer = None - #: The playback controller. An instance of #: :class:`mopidy.backends.base.PlaybackController`. playback = None #: The stored playlists controller. An instance of #: :class:`mopidy.backends.base.StoredPlaylistsController`. stored_playlists = None #: List of URI prefixes this backend can handle. uri_handlers = []
Remove mixer from the Backend API as it is independent
## Code Before: import logging from .current_playlist import CurrentPlaylistController from .library import LibraryController, BaseLibraryProvider from .playback import PlaybackController, BasePlaybackProvider from .stored_playlists import (StoredPlaylistsController, BaseStoredPlaylistsProvider) logger = logging.getLogger('mopidy.backends.base') class Backend(object): #: The current playlist controller. An instance of #: :class:`mopidy.backends.base.CurrentPlaylistController`. current_playlist = None #: The library controller. An instance of # :class:`mopidy.backends.base.LibraryController`. library = None #: The sound mixer. An instance of :class:`mopidy.mixers.BaseMixer`. mixer = None #: The playback controller. An instance of #: :class:`mopidy.backends.base.PlaybackController`. playback = None #: The stored playlists controller. An instance of #: :class:`mopidy.backends.base.StoredPlaylistsController`. stored_playlists = None #: List of URI prefixes this backend can handle. uri_handlers = [] ## Instruction: Remove mixer from the Backend API as it is independent ## Code After: import logging from .current_playlist import CurrentPlaylistController from .library import LibraryController, BaseLibraryProvider from .playback import PlaybackController, BasePlaybackProvider from .stored_playlists import (StoredPlaylistsController, BaseStoredPlaylistsProvider) logger = logging.getLogger('mopidy.backends.base') class Backend(object): #: The current playlist controller. An instance of #: :class:`mopidy.backends.base.CurrentPlaylistController`. current_playlist = None #: The library controller. An instance of # :class:`mopidy.backends.base.LibraryController`. library = None #: The playback controller. An instance of #: :class:`mopidy.backends.base.PlaybackController`. playback = None #: The stored playlists controller. An instance of #: :class:`mopidy.backends.base.StoredPlaylistsController`. stored_playlists = None #: List of URI prefixes this backend can handle. uri_handlers = []
b24af9c3e4105d7acd2e9e13545f24d5a69ae230
saleor/product/migrations/0018_auto_20161212_0725.py
saleor/product/migrations/0018_auto_20161212_0725.py
from __future__ import unicode_literals from django.db import migrations from django.utils.text import slugify def create_slugs(apps, schema_editor): Value = apps.get_model('product', 'AttributeChoiceValue') for value in Value.objects.all(): value.slug = slugify(value.display) value.save() class Migration(migrations.Migration): dependencies = [ ('product', '0017_attributechoicevalue_slug'), ] operations = [ migrations.RunPython(create_slugs), ]
from __future__ import unicode_literals from django.db import migrations from django.utils.text import slugify def create_slugs(apps, schema_editor): Value = apps.get_model('product', 'AttributeChoiceValue') for value in Value.objects.all(): value.slug = slugify(value.display) value.save() class Migration(migrations.Migration): dependencies = [ ('product', '0017_attributechoicevalue_slug'), ] operations = [ migrations.RunPython(create_slugs, migrations.RunPython.noop), ]
Allow to revert data migaration
Allow to revert data migaration
Python
bsd-3-clause
KenMutemi/saleor,maferelo/saleor,jreigel/saleor,KenMutemi/saleor,jreigel/saleor,itbabu/saleor,itbabu/saleor,HyperManTT/ECommerceSaleor,UITools/saleor,tfroehlich82/saleor,KenMutemi/saleor,mociepka/saleor,car3oon/saleor,tfroehlich82/saleor,HyperManTT/ECommerceSaleor,itbabu/saleor,UITools/saleor,UITools/saleor,UITools/saleor,UITools/saleor,car3oon/saleor,jreigel/saleor,mociepka/saleor,car3oon/saleor,HyperManTT/ECommerceSaleor,maferelo/saleor,maferelo/saleor,mociepka/saleor,tfroehlich82/saleor
from __future__ import unicode_literals from django.db import migrations from django.utils.text import slugify def create_slugs(apps, schema_editor): Value = apps.get_model('product', 'AttributeChoiceValue') for value in Value.objects.all(): value.slug = slugify(value.display) value.save() class Migration(migrations.Migration): dependencies = [ ('product', '0017_attributechoicevalue_slug'), ] operations = [ - migrations.RunPython(create_slugs), + migrations.RunPython(create_slugs, migrations.RunPython.noop), ]
Allow to revert data migaration
## Code Before: from __future__ import unicode_literals from django.db import migrations from django.utils.text import slugify def create_slugs(apps, schema_editor): Value = apps.get_model('product', 'AttributeChoiceValue') for value in Value.objects.all(): value.slug = slugify(value.display) value.save() class Migration(migrations.Migration): dependencies = [ ('product', '0017_attributechoicevalue_slug'), ] operations = [ migrations.RunPython(create_slugs), ] ## Instruction: Allow to revert data migaration ## Code After: from __future__ import unicode_literals from django.db import migrations from django.utils.text import slugify def create_slugs(apps, schema_editor): Value = apps.get_model('product', 'AttributeChoiceValue') for value in Value.objects.all(): value.slug = slugify(value.display) value.save() class Migration(migrations.Migration): dependencies = [ ('product', '0017_attributechoicevalue_slug'), ] operations = [ migrations.RunPython(create_slugs, migrations.RunPython.noop), ]
9d0e9af5844772c18ca24d4012642d4518b66dfc
tests/test_judicious.py
tests/test_judicious.py
"""Tests for `judicious` package.""" import pytest import judicious @pytest.fixture def response(): """Sample pytest fixture. See more at: http://doc.pytest.org/en/latest/fixture.html """ # import requests # return requests.get('https://github.com/audreyr/cookiecutter-pypackage') def test_content(response): """Sample pytest test function with the pytest fixture as an argument.""" # from bs4 import BeautifulSoup # assert 'GitHub' in BeautifulSoup(response.content).title.string
"""Tests for `judicious` package.""" import random import pytest import judicious def test_seeding(): r1 = random.random() r2 = random.random() judicious.seed("70d911d5-6d93-3c42-f9a4-53e493a79bff") r3 = random.random() r4 = random.random() judicious.seed("70d911d5-6d93-3c42-f9a4-53e493a79bff") r5 = random.random() r6 = random.random() judicious.seed() r7 = random.random() r8 = random.random() assert(r1 != r3) assert(r2 != r4) assert(r3 == r5) assert(r4 == r6) assert(r5 != r7) assert(r6 != r8) @pytest.fixture def response(): """Sample pytest fixture. See more at: http://doc.pytest.org/en/latest/fixture.html """ # import requests # return requests.get('https://github.com/audreyr/cookiecutter-pypackage') def test_content(response): """Sample pytest test function with the pytest fixture as an argument.""" # from bs4 import BeautifulSoup # assert 'GitHub' in BeautifulSoup(response.content).title.string
Add test of seeding PRNG
Add test of seeding PRNG
Python
mit
suchow/judicious,suchow/judicious,suchow/judicious
"""Tests for `judicious` package.""" + import random + import pytest + import judicious - import judicious + + def test_seeding(): + r1 = random.random() + r2 = random.random() + judicious.seed("70d911d5-6d93-3c42-f9a4-53e493a79bff") + r3 = random.random() + r4 = random.random() + judicious.seed("70d911d5-6d93-3c42-f9a4-53e493a79bff") + r5 = random.random() + r6 = random.random() + judicious.seed() + r7 = random.random() + r8 = random.random() + + assert(r1 != r3) + assert(r2 != r4) + assert(r3 == r5) + assert(r4 == r6) + assert(r5 != r7) + assert(r6 != r8) @pytest.fixture def response(): """Sample pytest fixture. See more at: http://doc.pytest.org/en/latest/fixture.html """ # import requests # return requests.get('https://github.com/audreyr/cookiecutter-pypackage') def test_content(response): """Sample pytest test function with the pytest fixture as an argument.""" # from bs4 import BeautifulSoup # assert 'GitHub' in BeautifulSoup(response.content).title.string
Add test of seeding PRNG
## Code Before: """Tests for `judicious` package.""" import pytest import judicious @pytest.fixture def response(): """Sample pytest fixture. See more at: http://doc.pytest.org/en/latest/fixture.html """ # import requests # return requests.get('https://github.com/audreyr/cookiecutter-pypackage') def test_content(response): """Sample pytest test function with the pytest fixture as an argument.""" # from bs4 import BeautifulSoup # assert 'GitHub' in BeautifulSoup(response.content).title.string ## Instruction: Add test of seeding PRNG ## Code After: """Tests for `judicious` package.""" import random import pytest import judicious def test_seeding(): r1 = random.random() r2 = random.random() judicious.seed("70d911d5-6d93-3c42-f9a4-53e493a79bff") r3 = random.random() r4 = random.random() judicious.seed("70d911d5-6d93-3c42-f9a4-53e493a79bff") r5 = random.random() r6 = random.random() judicious.seed() r7 = random.random() r8 = random.random() assert(r1 != r3) assert(r2 != r4) assert(r3 == r5) assert(r4 == r6) assert(r5 != r7) assert(r6 != r8) @pytest.fixture def response(): """Sample pytest fixture. See more at: http://doc.pytest.org/en/latest/fixture.html """ # import requests # return requests.get('https://github.com/audreyr/cookiecutter-pypackage') def test_content(response): """Sample pytest test function with the pytest fixture as an argument.""" # from bs4 import BeautifulSoup # assert 'GitHub' in BeautifulSoup(response.content).title.string
d46d908f5cfafcb6962207c45f923d3afb7f35a7
pyrobus/__init__.py
pyrobus/__init__.py
from .robot import Robot from .modules import *
import logging from .robot import Robot from .modules import * nh = logging.NullHandler() logging.getLogger(__name__).addHandler(nh)
Add null handler as default for logging.
Add null handler as default for logging.
Python
mit
pollen/pyrobus
+ import logging + from .robot import Robot from .modules import * + + nh = logging.NullHandler() + logging.getLogger(__name__).addHandler(nh) +
Add null handler as default for logging.
## Code Before: from .robot import Robot from .modules import * ## Instruction: Add null handler as default for logging. ## Code After: import logging from .robot import Robot from .modules import * nh = logging.NullHandler() logging.getLogger(__name__).addHandler(nh)
c220c0a474a660c4c1167d42fdd0d48599b1b593
tests/test_pathutils.py
tests/test_pathutils.py
from os.path import join import sublime import sys from unittest import TestCase version = sublime.version() try: from libsass import pathutils except ImportError: from sublime_libsass.libsass import pathutils class TestPathutils(TestCase): def test_subpaths(self): path = join('/foo','bar','baz') exprmt = pathutils.subpaths(path) expect = [ join('/foo','bar','baz'), join('/foo','bar'), join('/foo'), join('/') ] self.assertEqual(exprmt, expect) def test_grep_r(self): pathutils.os.walk = lambda x: [('/tmp','',['file.scss'])] self.assertEqual(pathutils.find_type_dirs('anything', '.scss'), ['/tmp']) self.assertEqual(pathutils.find_type_dirs('anything', ['.scss', '.sass']), ['/tmp']) self.assertEqual(pathutils.find_type_dirs('anything', '.sass'), []) self.assertEqual(pathutils.find_type_dirs('anything', ['.txt', '.csv']), [])
from os.path import join, realpath import os import sublime import sys from unittest import TestCase from functools import wraps def subl_patch(pkg, obj=None): def subl_deco(fn): @wraps(fn) def wrap(*args): nonlocal pkg o = [] if obj != None: o += [obj] pkg = pkg + '.' + obj try: mock = __import__(pkg, globals(), locals(), o, 0) except ImportError: pkg = realpath(__file__).split(os.sep)[-3] + '.' + pkg mock = __import__(pkg, globals(), locals(), o, 0) args += (mock,) fn(*args) return wrap return subl_deco class TestPathutils(TestCase): @subl_patch('libsass', 'pathutils') def test_subpaths(self, pathutils): path = join('/foo','bar','baz') exprmt = pathutils.subpaths(path) expect = [ join('/foo','bar','baz'), join('/foo','bar'), join('/foo'), join('/') ] self.assertEqual(exprmt, expect) @subl_patch('libsass', 'pathutils') def test_grep_r(self, pathutils): pathutils.os.walk = lambda x: [('/tmp','',['file.scss'])] self.assertEqual(pathutils.find_type_dirs('anything', '.scss'), ['/tmp']) self.assertEqual(pathutils.find_type_dirs('anything', ['.scss', '.sass']), ['/tmp']) self.assertEqual(pathutils.find_type_dirs('anything', '.sass'), []) self.assertEqual(pathutils.find_type_dirs('anything', ['.txt', '.csv']), [])
Make custom patch in package to test
Make custom patch in package to test
Python
mit
blitzrk/sublime_libsass,blitzrk/sublime_libsass
- from os.path import join + from os.path import join, realpath + import os import sublime import sys from unittest import TestCase + from functools import wraps - version = sublime.version() - try: - from libsass import pathutils + def subl_patch(pkg, obj=None): + def subl_deco(fn): + @wraps(fn) + def wrap(*args): + nonlocal pkg + o = [] + if obj != None: + o += [obj] + pkg = pkg + '.' + obj + try: + mock = __import__(pkg, globals(), locals(), o, 0) - except ImportError: + except ImportError: - from sublime_libsass.libsass import pathutils + pkg = realpath(__file__).split(os.sep)[-3] + '.' + pkg + mock = __import__(pkg, globals(), locals(), o, 0) + args += (mock,) + fn(*args) + return wrap + return subl_deco class TestPathutils(TestCase): + @subl_patch('libsass', 'pathutils') - def test_subpaths(self): + def test_subpaths(self, pathutils): path = join('/foo','bar','baz') exprmt = pathutils.subpaths(path) expect = [ join('/foo','bar','baz'), join('/foo','bar'), join('/foo'), join('/') ] self.assertEqual(exprmt, expect) + @subl_patch('libsass', 'pathutils') - def test_grep_r(self): + def test_grep_r(self, pathutils): pathutils.os.walk = lambda x: [('/tmp','',['file.scss'])] self.assertEqual(pathutils.find_type_dirs('anything', '.scss'), ['/tmp']) self.assertEqual(pathutils.find_type_dirs('anything', ['.scss', '.sass']), ['/tmp']) self.assertEqual(pathutils.find_type_dirs('anything', '.sass'), []) self.assertEqual(pathutils.find_type_dirs('anything', ['.txt', '.csv']), [])
Make custom patch in package to test
## Code Before: from os.path import join import sublime import sys from unittest import TestCase version = sublime.version() try: from libsass import pathutils except ImportError: from sublime_libsass.libsass import pathutils class TestPathutils(TestCase): def test_subpaths(self): path = join('/foo','bar','baz') exprmt = pathutils.subpaths(path) expect = [ join('/foo','bar','baz'), join('/foo','bar'), join('/foo'), join('/') ] self.assertEqual(exprmt, expect) def test_grep_r(self): pathutils.os.walk = lambda x: [('/tmp','',['file.scss'])] self.assertEqual(pathutils.find_type_dirs('anything', '.scss'), ['/tmp']) self.assertEqual(pathutils.find_type_dirs('anything', ['.scss', '.sass']), ['/tmp']) self.assertEqual(pathutils.find_type_dirs('anything', '.sass'), []) self.assertEqual(pathutils.find_type_dirs('anything', ['.txt', '.csv']), []) ## Instruction: Make custom patch in package to test ## Code After: from os.path import join, realpath import os import sublime import sys from unittest import TestCase from functools import wraps def subl_patch(pkg, obj=None): def subl_deco(fn): @wraps(fn) def wrap(*args): nonlocal pkg o = [] if obj != None: o += [obj] pkg = pkg + '.' + obj try: mock = __import__(pkg, globals(), locals(), o, 0) except ImportError: pkg = realpath(__file__).split(os.sep)[-3] + '.' + pkg mock = __import__(pkg, globals(), locals(), o, 0) args += (mock,) fn(*args) return wrap return subl_deco class TestPathutils(TestCase): @subl_patch('libsass', 'pathutils') def test_subpaths(self, pathutils): path = join('/foo','bar','baz') exprmt = pathutils.subpaths(path) expect = [ join('/foo','bar','baz'), join('/foo','bar'), join('/foo'), join('/') ] self.assertEqual(exprmt, expect) @subl_patch('libsass', 'pathutils') def test_grep_r(self, pathutils): pathutils.os.walk = lambda x: [('/tmp','',['file.scss'])] self.assertEqual(pathutils.find_type_dirs('anything', '.scss'), ['/tmp']) self.assertEqual(pathutils.find_type_dirs('anything', ['.scss', '.sass']), ['/tmp']) self.assertEqual(pathutils.find_type_dirs('anything', '.sass'), []) self.assertEqual(pathutils.find_type_dirs('anything', ['.txt', '.csv']), [])
9eddd3b5c4635637faead9d7eae73efd2e324bdb
recipes/tests/test_views.py
recipes/tests/test_views.py
from django.core.urlresolvers import resolve from django.http import HttpRequest from django.template.loader import render_to_string from django.test import TestCase from recipes.views import home_page from recipes.models import Recipe class HomePageViewTest(TestCase): def test_root_url_resolves_to_home_page_view(self): found = resolve('/') self.assertEqual(found.func, home_page) def test_home_page_inherits_from_base_template(self): response = self.client.get('/') self.assertTemplateUsed(response, 'rotd/base.html') def test_home_page_uses_correct_template(self): request = HttpRequest() response = home_page(request) expected = render_to_string('recipes/home.html') self.assertEqual(response.content.decode(), expected) def test_home_page_has_recipe(self): Recipe.objects.create(name='test') response = self.client.get('/') self.assertIsInstance(response.context['recipe'], Recipe) def test_home_page_shows_any_recipe_name(self): Recipe.objects.create(name='test recipe') request = HttpRequest() response = home_page(request).content.decode() self.assertTrue(any([(recipe.name in response) for recipe in Recipe.objects.all()]))
from django.core.urlresolvers import resolve from django.http import HttpRequest from django.template.loader import render_to_string from django.test import TestCase from recipes.views import home_page from recipes.models import Recipe class HomePageViewTest(TestCase): def test_root_url_resolves_to_home_page_view(self): found = resolve('/') self.assertEqual(found.func, home_page) def test_home_page_inherits_from_base_template(self): response = self.client.get('/') self.assertTemplateUsed(response, 'rotd/base.html') def test_home_page_uses_correct_template(self): response = self.client.get('/') self.assertTemplateUsed(response, 'recipes/home.html') def test_home_page_has_recipe(self): Recipe.objects.create(name='test') response = self.client.get('/') self.assertIsInstance(response.context['recipe'], Recipe) def test_home_page_shows_any_recipe_name(self): Recipe.objects.create(name='test recipe') request = HttpRequest() response = home_page(request).content.decode() self.assertTrue(any([(recipe.name in response) for recipe in Recipe.objects.all()]))
Use the test client to check all templates for correctness
Use the test client to check all templates for correctness
Python
agpl-3.0
XeryusTC/rotd,XeryusTC/rotd,XeryusTC/rotd
from django.core.urlresolvers import resolve from django.http import HttpRequest from django.template.loader import render_to_string from django.test import TestCase from recipes.views import home_page from recipes.models import Recipe class HomePageViewTest(TestCase): def test_root_url_resolves_to_home_page_view(self): found = resolve('/') self.assertEqual(found.func, home_page) def test_home_page_inherits_from_base_template(self): response = self.client.get('/') self.assertTemplateUsed(response, 'rotd/base.html') def test_home_page_uses_correct_template(self): + response = self.client.get('/') + self.assertTemplateUsed(response, 'recipes/home.html') - request = HttpRequest() - response = home_page(request) - expected = render_to_string('recipes/home.html') - self.assertEqual(response.content.decode(), expected) def test_home_page_has_recipe(self): Recipe.objects.create(name='test') response = self.client.get('/') self.assertIsInstance(response.context['recipe'], Recipe) def test_home_page_shows_any_recipe_name(self): Recipe.objects.create(name='test recipe') request = HttpRequest() response = home_page(request).content.decode() self.assertTrue(any([(recipe.name in response) for recipe in Recipe.objects.all()]))
Use the test client to check all templates for correctness
## Code Before: from django.core.urlresolvers import resolve from django.http import HttpRequest from django.template.loader import render_to_string from django.test import TestCase from recipes.views import home_page from recipes.models import Recipe class HomePageViewTest(TestCase): def test_root_url_resolves_to_home_page_view(self): found = resolve('/') self.assertEqual(found.func, home_page) def test_home_page_inherits_from_base_template(self): response = self.client.get('/') self.assertTemplateUsed(response, 'rotd/base.html') def test_home_page_uses_correct_template(self): request = HttpRequest() response = home_page(request) expected = render_to_string('recipes/home.html') self.assertEqual(response.content.decode(), expected) def test_home_page_has_recipe(self): Recipe.objects.create(name='test') response = self.client.get('/') self.assertIsInstance(response.context['recipe'], Recipe) def test_home_page_shows_any_recipe_name(self): Recipe.objects.create(name='test recipe') request = HttpRequest() response = home_page(request).content.decode() self.assertTrue(any([(recipe.name in response) for recipe in Recipe.objects.all()])) ## Instruction: Use the test client to check all templates for correctness ## Code After: from django.core.urlresolvers import resolve from django.http import HttpRequest from django.template.loader import render_to_string from django.test import TestCase from recipes.views import home_page from recipes.models import Recipe class HomePageViewTest(TestCase): def test_root_url_resolves_to_home_page_view(self): found = resolve('/') self.assertEqual(found.func, home_page) def test_home_page_inherits_from_base_template(self): response = self.client.get('/') self.assertTemplateUsed(response, 'rotd/base.html') def test_home_page_uses_correct_template(self): response = self.client.get('/') self.assertTemplateUsed(response, 'recipes/home.html') def test_home_page_has_recipe(self): Recipe.objects.create(name='test') response = self.client.get('/') self.assertIsInstance(response.context['recipe'], Recipe) def test_home_page_shows_any_recipe_name(self): Recipe.objects.create(name='test recipe') request = HttpRequest() response = home_page(request).content.decode() self.assertTrue(any([(recipe.name in response) for recipe in Recipe.objects.all()]))
c1edc666630c03b6d85d9749e0695a9f19dd7c13
src/collectd_scripts/handle_collectd_notification.py
src/collectd_scripts/handle_collectd_notification.py
import sys import os import salt.client def getNotification(): notification_dict = {} isEndOfDictionary = False for line in sys.stdin: if not line.strip(): isEndOfDictionary = True continue if isEndOfDictionary: break key, value = line.split(':') notification_dict[key] = value.lstrip()[:-1] return notification_dict, line def postTheNotificationToSaltMaster(): salt_payload = {} threshold_dict = {} caller = salt.client.Caller() threshold_dict['tags'], threshold_dict['message'] = getNotification() tag = "skyring/collectd/node/{0}/threshold/{1}/{2}".format( threshold_dict['tags']["Host"], threshold_dict['tags']["Plugin"], threshold_dict['tags']["Severity"]) caller.sminion.functions['event.send'](tag, threshold_dict) if __name__ == '__main__': postTheNotificationToSaltMaster()
import sys import os import salt.client def getNotification(): notification_dict = {} isEndOfDictionary = False for line in sys.stdin: if not line.strip(): isEndOfDictionary = True continue if isEndOfDictionary: break key, value = line.split(':') notification_dict[key] = value.lstrip()[:-1] return notification_dict, line def postTheNotificationToSaltMaster(): salt_payload = {} threshold_dict = {} caller = salt.client.Caller() threshold_dict['tags'], threshold_dict['message'] = getNotification() threshold_dict['severity'] = threshold_dict['tags']["Severity"] tag = "skyring/collectd/node/{0}/threshold/{1}/{2}".format( threshold_dict['tags']["Host"], threshold_dict['tags']["Plugin"], threshold_dict['tags']["Severity"]) caller.sminion.functions['event.send'](tag, threshold_dict) if __name__ == '__main__': postTheNotificationToSaltMaster()
Fix in collectd event notifier script.
Skynet: Fix in collectd event notifier script. This patch adds a fix to collectd event notifier script, by providing a value the "severity" field in the event that it sends to salt-master event bus. with out that event listener in the skyring server will fail to process it. Change-Id: I20b738468c8022a25024e4327434ae6dab43a123 Signed-off-by: nnDarshan <d2c6d450ab98b078f2f1942c995e6d92dd504bc8@gmail.com>
Python
apache-2.0
skyrings/skynet,skyrings/skynet
import sys import os import salt.client def getNotification(): notification_dict = {} isEndOfDictionary = False for line in sys.stdin: if not line.strip(): isEndOfDictionary = True continue if isEndOfDictionary: break key, value = line.split(':') notification_dict[key] = value.lstrip()[:-1] return notification_dict, line def postTheNotificationToSaltMaster(): salt_payload = {} threshold_dict = {} caller = salt.client.Caller() threshold_dict['tags'], threshold_dict['message'] = getNotification() + threshold_dict['severity'] = threshold_dict['tags']["Severity"] tag = "skyring/collectd/node/{0}/threshold/{1}/{2}".format( threshold_dict['tags']["Host"], threshold_dict['tags']["Plugin"], threshold_dict['tags']["Severity"]) caller.sminion.functions['event.send'](tag, threshold_dict) if __name__ == '__main__': postTheNotificationToSaltMaster()
Fix in collectd event notifier script.
## Code Before: import sys import os import salt.client def getNotification(): notification_dict = {} isEndOfDictionary = False for line in sys.stdin: if not line.strip(): isEndOfDictionary = True continue if isEndOfDictionary: break key, value = line.split(':') notification_dict[key] = value.lstrip()[:-1] return notification_dict, line def postTheNotificationToSaltMaster(): salt_payload = {} threshold_dict = {} caller = salt.client.Caller() threshold_dict['tags'], threshold_dict['message'] = getNotification() tag = "skyring/collectd/node/{0}/threshold/{1}/{2}".format( threshold_dict['tags']["Host"], threshold_dict['tags']["Plugin"], threshold_dict['tags']["Severity"]) caller.sminion.functions['event.send'](tag, threshold_dict) if __name__ == '__main__': postTheNotificationToSaltMaster() ## Instruction: Fix in collectd event notifier script. ## Code After: import sys import os import salt.client def getNotification(): notification_dict = {} isEndOfDictionary = False for line in sys.stdin: if not line.strip(): isEndOfDictionary = True continue if isEndOfDictionary: break key, value = line.split(':') notification_dict[key] = value.lstrip()[:-1] return notification_dict, line def postTheNotificationToSaltMaster(): salt_payload = {} threshold_dict = {} caller = salt.client.Caller() threshold_dict['tags'], threshold_dict['message'] = getNotification() threshold_dict['severity'] = threshold_dict['tags']["Severity"] tag = "skyring/collectd/node/{0}/threshold/{1}/{2}".format( threshold_dict['tags']["Host"], threshold_dict['tags']["Plugin"], threshold_dict['tags']["Severity"]) caller.sminion.functions['event.send'](tag, threshold_dict) if __name__ == '__main__': postTheNotificationToSaltMaster()
01e9df01bc17561d0f489f1647ce5e0c566372e5
flocker/provision/__init__.py
flocker/provision/__init__.py
from ._common import PackageSource from ._install import provision from ._rackspace import rackspace_provisioner from ._aws import aws_provisioner # import digitalocean_provisioner __all__ = [ 'PackageSource', 'provision', 'rackspace_provisioner', 'aws_provisioner' # digitalocean_provisioner ]
from ._common import PackageSource from ._install import provision from ._rackspace import rackspace_provisioner from ._aws import aws_provisioner from ._digitalocean import digitalocean_provisioner __all__ = [ 'PackageSource', 'provision', 'rackspace_provisioner', 'aws_provisioner', 'digitalocean_provisioner' ]
Make the digitalocean provisioner public
Make the digitalocean provisioner public
Python
apache-2.0
wallnerryan/flocker-profiles,1d4Nf6/flocker,hackday-profilers/flocker,moypray/flocker,mbrukman/flocker,hackday-profilers/flocker,agonzalezro/flocker,1d4Nf6/flocker,w4ngyi/flocker,moypray/flocker,agonzalezro/flocker,mbrukman/flocker,adamtheturtle/flocker,moypray/flocker,AndyHuu/flocker,achanda/flocker,lukemarsden/flocker,LaynePeng/flocker,lukemarsden/flocker,wallnerryan/flocker-profiles,Azulinho/flocker,achanda/flocker,adamtheturtle/flocker,jml/flocker,runcom/flocker,w4ngyi/flocker,agonzalezro/flocker,Azulinho/flocker,LaynePeng/flocker,w4ngyi/flocker,1d4Nf6/flocker,LaynePeng/flocker,runcom/flocker,runcom/flocker,mbrukman/flocker,Azulinho/flocker,lukemarsden/flocker,AndyHuu/flocker,hackday-profilers/flocker,wallnerryan/flocker-profiles,achanda/flocker,adamtheturtle/flocker,AndyHuu/flocker,jml/flocker,jml/flocker
from ._common import PackageSource from ._install import provision from ._rackspace import rackspace_provisioner from ._aws import aws_provisioner - # import digitalocean_provisioner + from ._digitalocean import digitalocean_provisioner __all__ = [ 'PackageSource', 'provision', - 'rackspace_provisioner', 'aws_provisioner' + 'rackspace_provisioner', 'aws_provisioner', 'digitalocean_provisioner' - # digitalocean_provisioner ]
Make the digitalocean provisioner public
## Code Before: from ._common import PackageSource from ._install import provision from ._rackspace import rackspace_provisioner from ._aws import aws_provisioner # import digitalocean_provisioner __all__ = [ 'PackageSource', 'provision', 'rackspace_provisioner', 'aws_provisioner' # digitalocean_provisioner ] ## Instruction: Make the digitalocean provisioner public ## Code After: from ._common import PackageSource from ._install import provision from ._rackspace import rackspace_provisioner from ._aws import aws_provisioner from ._digitalocean import digitalocean_provisioner __all__ = [ 'PackageSource', 'provision', 'rackspace_provisioner', 'aws_provisioner', 'digitalocean_provisioner' ]
c6f2ff563c08eb43ba3f33bc9aaa2647e78701d2
fenced_code_plus/__init__.py
fenced_code_plus/__init__.py
from fenced_code_plus import FencedCodePlusExtension from fenced_code_plus import makeExtension
from __future__ import absolute_import from fenced_code_plus.fenced_code_plus import FencedCodePlusExtension from fenced_code_plus.fenced_code_plus import makeExtension
Make import compatable with python3.5
Make import compatable with python3.5
Python
bsd-3-clause
amfarrell/fenced-code-plus
+ from __future__ import absolute_import - from fenced_code_plus import FencedCodePlusExtension - from fenced_code_plus import makeExtension + from fenced_code_plus.fenced_code_plus import FencedCodePlusExtension + from fenced_code_plus.fenced_code_plus import makeExtension +
Make import compatable with python3.5
## Code Before: from fenced_code_plus import FencedCodePlusExtension from fenced_code_plus import makeExtension ## Instruction: Make import compatable with python3.5 ## Code After: from __future__ import absolute_import from fenced_code_plus.fenced_code_plus import FencedCodePlusExtension from fenced_code_plus.fenced_code_plus import makeExtension
8b127a3d934470aa20fbff83d06ded2e37d00579
deferrable/delay.py
deferrable/delay.py
MAXIMUM_DELAY_SECONDS = 900
# SQS has a hard limit of 900 seconds, and Dockets # delay queues incur heavy performance penalties, # so this seems like a reasonable limit for all MAXIMUM_DELAY_SECONDS = 900
Add back some reasoning on the 900 number
Add back some reasoning on the 900 number
Python
mit
gamechanger/deferrable
+ # SQS has a hard limit of 900 seconds, and Dockets + # delay queues incur heavy performance penalties, + # so this seems like a reasonable limit for all MAXIMUM_DELAY_SECONDS = 900
Add back some reasoning on the 900 number
## Code Before: MAXIMUM_DELAY_SECONDS = 900 ## Instruction: Add back some reasoning on the 900 number ## Code After: # SQS has a hard limit of 900 seconds, and Dockets # delay queues incur heavy performance penalties, # so this seems like a reasonable limit for all MAXIMUM_DELAY_SECONDS = 900
e2909520e93e85286bd4393426377e48db243615
hastexo_social_auth/oauth2.py
hastexo_social_auth/oauth2.py
from social.backends.oauth import BaseOAuth2 class HastexoOAuth2(BaseOAuth2): """Hastexo OAuth2 authentication backend""" name = 'hastexo' AUTHORIZATION_URL = 'https://store.hastexo.com/o/authorize/' ACCESS_TOKEN_URL = 'https://store.hastexo.com/o/token/' ACCESS_TOKEN_METHOD = 'POST' SCOPE_SEPARATOR = ' ' def get_user_details(self, response): """Return user details from hastexo account""" return { 'username': response['username'], 'email': response.get('email', ''), 'first_name': '', 'last_name': '', } def user_data(self, access_token, *args, **kwargs): """Loads user data from service""" return self.get_json('https://store.hastexo.com/api/users/', params={ 'access_token': access_token })
from social.backends.oauth import BaseOAuth2 class HastexoOAuth2(BaseOAuth2): """Hastexo OAuth2 authentication backend""" name = 'hastexo' AUTHORIZATION_URL = 'https://store.hastexo.com/o/authorize/' ACCESS_TOKEN_URL = 'https://store.hastexo.com/o/token/' ACCESS_TOKEN_METHOD = 'POST' SCOPE_SEPARATOR = ' ' def get_user_details(self, response): """Return user details from hastexo account""" return { 'username': response.get('username'), 'email': response.get('email', ''), 'first_name': response.get('first_name', ''), 'last_name': response.get('last_name', '') } def user_data(self, access_token, *args, **kwargs): """Loads user data from service""" return self.get_json('https://store.hastexo.com/api/login/', params={ 'access_token': access_token })
Update user details API call
Update user details API call
Python
bsd-3-clause
hastexo/python-social-auth-hastexo,arbrandes/python-social-auth-hastexo
from social.backends.oauth import BaseOAuth2 class HastexoOAuth2(BaseOAuth2): """Hastexo OAuth2 authentication backend""" name = 'hastexo' AUTHORIZATION_URL = 'https://store.hastexo.com/o/authorize/' ACCESS_TOKEN_URL = 'https://store.hastexo.com/o/token/' ACCESS_TOKEN_METHOD = 'POST' SCOPE_SEPARATOR = ' ' def get_user_details(self, response): """Return user details from hastexo account""" return { - 'username': response['username'], + 'username': response.get('username'), 'email': response.get('email', ''), - 'first_name': '', - 'last_name': '', + 'first_name': response.get('first_name', ''), + 'last_name': response.get('last_name', '') } def user_data(self, access_token, *args, **kwargs): """Loads user data from service""" - return self.get_json('https://store.hastexo.com/api/users/', params={ + return self.get_json('https://store.hastexo.com/api/login/', params={ 'access_token': access_token })
Update user details API call
## Code Before: from social.backends.oauth import BaseOAuth2 class HastexoOAuth2(BaseOAuth2): """Hastexo OAuth2 authentication backend""" name = 'hastexo' AUTHORIZATION_URL = 'https://store.hastexo.com/o/authorize/' ACCESS_TOKEN_URL = 'https://store.hastexo.com/o/token/' ACCESS_TOKEN_METHOD = 'POST' SCOPE_SEPARATOR = ' ' def get_user_details(self, response): """Return user details from hastexo account""" return { 'username': response['username'], 'email': response.get('email', ''), 'first_name': '', 'last_name': '', } def user_data(self, access_token, *args, **kwargs): """Loads user data from service""" return self.get_json('https://store.hastexo.com/api/users/', params={ 'access_token': access_token }) ## Instruction: Update user details API call ## Code After: from social.backends.oauth import BaseOAuth2 class HastexoOAuth2(BaseOAuth2): """Hastexo OAuth2 authentication backend""" name = 'hastexo' AUTHORIZATION_URL = 'https://store.hastexo.com/o/authorize/' ACCESS_TOKEN_URL = 'https://store.hastexo.com/o/token/' ACCESS_TOKEN_METHOD = 'POST' SCOPE_SEPARATOR = ' ' def get_user_details(self, response): """Return user details from hastexo account""" return { 'username': response.get('username'), 'email': response.get('email', ''), 'first_name': response.get('first_name', ''), 'last_name': response.get('last_name', '') } def user_data(self, access_token, *args, **kwargs): """Loads user data from service""" return self.get_json('https://store.hastexo.com/api/login/', params={ 'access_token': access_token })
52cb80dd92ceabd7d2efe67c0a89f76cd701283b
statirator/main.py
statirator/main.py
import os import sys def main(): # init is a special case, cause we want to add statirator.core to # INSTALLED_APPS, and have the command picked up. we'll handle it in here if 'init' in sys.argv: from django.conf import settings settings.configure(INSTALLED_APPS=('statirator.core', )) elif 'test' in sys.argv: os.environ.setdefault( "DJANGO_SETTINGS_MODULE", "statirator.test_settings") from django.core import management management.execute_from_command_line() if __name__ == '__main__': main()
import os import sys def main(): if 'test' in sys.argv: os.environ.setdefault( "DJANGO_SETTINGS_MODULE", "statirator.test_settings") else: from django.conf import settings settings.configure(INSTALLED_APPS=('statirator.core', )) from django.core import management management.execute_from_command_line() if __name__ == '__main__': main()
Add statirator.core for all commands except test
Add statirator.core for all commands except test
Python
mit
MeirKriheli/statirator,MeirKriheli/statirator,MeirKriheli/statirator
import os import sys def main(): - # init is a special case, cause we want to add statirator.core to - # INSTALLED_APPS, and have the command picked up. we'll handle it in here - - if 'init' in sys.argv: + if 'test' in sys.argv: + os.environ.setdefault( + "DJANGO_SETTINGS_MODULE", "statirator.test_settings") + else: from django.conf import settings settings.configure(INSTALLED_APPS=('statirator.core', )) - elif 'test' in sys.argv: - os.environ.setdefault( - "DJANGO_SETTINGS_MODULE", "statirator.test_settings") from django.core import management management.execute_from_command_line() if __name__ == '__main__': main()
Add statirator.core for all commands except test
## Code Before: import os import sys def main(): # init is a special case, cause we want to add statirator.core to # INSTALLED_APPS, and have the command picked up. we'll handle it in here if 'init' in sys.argv: from django.conf import settings settings.configure(INSTALLED_APPS=('statirator.core', )) elif 'test' in sys.argv: os.environ.setdefault( "DJANGO_SETTINGS_MODULE", "statirator.test_settings") from django.core import management management.execute_from_command_line() if __name__ == '__main__': main() ## Instruction: Add statirator.core for all commands except test ## Code After: import os import sys def main(): if 'test' in sys.argv: os.environ.setdefault( "DJANGO_SETTINGS_MODULE", "statirator.test_settings") else: from django.conf import settings settings.configure(INSTALLED_APPS=('statirator.core', )) from django.core import management management.execute_from_command_line() if __name__ == '__main__': main()
c7ec2805d1c3dde9ff3bf8caacf0bac474a1d468
cybox/utils.py
cybox/utils.py
def test_value(value): if value.get('value') is not None: if value.get('value') is not None and len(str(value.get('value'))) > 0: return True else: return False else: return False
"""Common utility methods""" def test_value(value): """ Test if a dictionary contains a "value" key whose value is not None and has a length greater than 0. We explicitly want to return True even if the value is False or 0, since some parts of the standards are boolean or allow a 0 value, and we want to distinguish the case where the "value" key is omitted entirely. """ v = value.get('value', None) return (v is not None) and (len(str(v)) > 0)
Clean up and document 'test_value' function.
Clean up and document 'test_value' function.
Python
bsd-3-clause
CybOXProject/python-cybox
+ """Common utility methods""" + def test_value(value): + """ + Test if a dictionary contains a "value" key whose value is not None + and has a length greater than 0. - if value.get('value') is not None: - if value.get('value') is not None and len(str(value.get('value'))) > 0: - return True - else: - return False - else: - return False + We explicitly want to return True even if the value is False or 0, since + some parts of the standards are boolean or allow a 0 value, and we want to + distinguish the case where the "value" key is omitted entirely. + """ + v = value.get('value', None) + return (v is not None) and (len(str(v)) > 0) +
Clean up and document 'test_value' function.
## Code Before: def test_value(value): if value.get('value') is not None: if value.get('value') is not None and len(str(value.get('value'))) > 0: return True else: return False else: return False ## Instruction: Clean up and document 'test_value' function. ## Code After: """Common utility methods""" def test_value(value): """ Test if a dictionary contains a "value" key whose value is not None and has a length greater than 0. We explicitly want to return True even if the value is False or 0, since some parts of the standards are boolean or allow a 0 value, and we want to distinguish the case where the "value" key is omitted entirely. """ v = value.get('value', None) return (v is not None) and (len(str(v)) > 0)
3fc94b4cffcfd08b439386fb2b01aa1e12fec6d5
iati/core/tests/test_data.py
iati/core/tests/test_data.py
"""A module containing tests for the library representation of IATI data.""" import iati.core.data class TestDatasets(object): """A container for tests relating to Datasets""" pass
"""A module containing tests for the library representation of IATI data.""" import iati.core.data class TestDatasets(object): """A container for tests relating to Datasets""" def test_dataset_no_params(self): """Test Dataset creation with no parameters.""" pass def test_dataset_valid_xml_string(self): """Test Dataset creation with a valid XML string that is not IATI data.""" pass def test_dataset_valid_iati_string(self): """Test Dataset creation with a valid IATI XML string.""" pass def test_dataset_invalid_xml_string(self): """Test Dataset creation with a string that is not valid XML.""" pass def test_dataset_tree(self): """Test Dataset creation with an etree that is not valid IATI data.""" pass def test_dataset_iati_tree(self): """Test Dataset creation with a valid IATI etree.""" pass def test_dataset_no_params_strict(self): """Test Dataset creation with no parameters. Strict IATI checks are enabled. """ pass def test_dataset_valid_xml_string_strict(self): """Test Dataset creation with a valid XML string that is not IATI data. Strict IATI checks are enabled. """ pass def test_dataset_valid_iati_string_strict(self): """Test Dataset creation with a valid IATI XML string. Strict IATI checks are enabled. """ pass def test_dataset_invalid_xml_string_strict(self): """Test Dataset creation with a string that is not valid XML. Strict IATI checks are enabled. """ pass def test_dataset_tree_strict(self): """Test Dataset creation with an etree that is not valid IATI data. Strict IATI checks are enabled. """ pass def test_dataset_iati_tree_strict(self): """Test Dataset creation with a valid IATI etree. Strict IATI checks are enabled. """ pass
Test stubs for dataset creation
Test stubs for dataset creation
Python
mit
IATI/iati.core,IATI/iati.core
"""A module containing tests for the library representation of IATI data.""" import iati.core.data class TestDatasets(object): """A container for tests relating to Datasets""" + def test_dataset_no_params(self): + """Test Dataset creation with no parameters.""" - pass + pass + def test_dataset_valid_xml_string(self): + """Test Dataset creation with a valid XML string that is not IATI data.""" + pass + + def test_dataset_valid_iati_string(self): + """Test Dataset creation with a valid IATI XML string.""" + pass + + def test_dataset_invalid_xml_string(self): + """Test Dataset creation with a string that is not valid XML.""" + pass + + def test_dataset_tree(self): + """Test Dataset creation with an etree that is not valid IATI data.""" + pass + + def test_dataset_iati_tree(self): + """Test Dataset creation with a valid IATI etree.""" + pass + + def test_dataset_no_params_strict(self): + """Test Dataset creation with no parameters. + Strict IATI checks are enabled. + """ + pass + + def test_dataset_valid_xml_string_strict(self): + """Test Dataset creation with a valid XML string that is not IATI data. + Strict IATI checks are enabled. + """ + pass + + def test_dataset_valid_iati_string_strict(self): + """Test Dataset creation with a valid IATI XML string. + Strict IATI checks are enabled. + """ + pass + + def test_dataset_invalid_xml_string_strict(self): + """Test Dataset creation with a string that is not valid XML. + Strict IATI checks are enabled. + """ + pass + + def test_dataset_tree_strict(self): + """Test Dataset creation with an etree that is not valid IATI data. + Strict IATI checks are enabled. + """ + pass + + def test_dataset_iati_tree_strict(self): + """Test Dataset creation with a valid IATI etree. + Strict IATI checks are enabled. + """ + pass +
Test stubs for dataset creation
## Code Before: """A module containing tests for the library representation of IATI data.""" import iati.core.data class TestDatasets(object): """A container for tests relating to Datasets""" pass ## Instruction: Test stubs for dataset creation ## Code After: """A module containing tests for the library representation of IATI data.""" import iati.core.data class TestDatasets(object): """A container for tests relating to Datasets""" def test_dataset_no_params(self): """Test Dataset creation with no parameters.""" pass def test_dataset_valid_xml_string(self): """Test Dataset creation with a valid XML string that is not IATI data.""" pass def test_dataset_valid_iati_string(self): """Test Dataset creation with a valid IATI XML string.""" pass def test_dataset_invalid_xml_string(self): """Test Dataset creation with a string that is not valid XML.""" pass def test_dataset_tree(self): """Test Dataset creation with an etree that is not valid IATI data.""" pass def test_dataset_iati_tree(self): """Test Dataset creation with a valid IATI etree.""" pass def test_dataset_no_params_strict(self): """Test Dataset creation with no parameters. Strict IATI checks are enabled. """ pass def test_dataset_valid_xml_string_strict(self): """Test Dataset creation with a valid XML string that is not IATI data. Strict IATI checks are enabled. """ pass def test_dataset_valid_iati_string_strict(self): """Test Dataset creation with a valid IATI XML string. Strict IATI checks are enabled. """ pass def test_dataset_invalid_xml_string_strict(self): """Test Dataset creation with a string that is not valid XML. Strict IATI checks are enabled. """ pass def test_dataset_tree_strict(self): """Test Dataset creation with an etree that is not valid IATI data. Strict IATI checks are enabled. """ pass def test_dataset_iati_tree_strict(self): """Test Dataset creation with a valid IATI etree. Strict IATI checks are enabled. """ pass
da314ab34cb13c1de66b96da2eab1484639e124b
fiona/compat.py
fiona/compat.py
try: from collections import OrderedDict except ImportError: from ordereddict import OrderedDict
import collections from six.moves import UserDict try: from collections import OrderedDict except ImportError: from ordereddict import OrderedDict # Users can pass in objects that subclass a few different objects # More specifically, rasterio has a CRS() class that subclasses UserDict() # In Python 2 UserDict() is in its own module and does not subclass Mapping() DICT_TYPES = (dict, collections.Mapping, UserDict)
Add a DICT_TYPES variable so we can do isinstance() checks against all the builtin dict-like objects
Add a DICT_TYPES variable so we can do isinstance() checks against all the builtin dict-like objects
Python
bsd-3-clause
Toblerity/Fiona,rbuffat/Fiona,rbuffat/Fiona,Toblerity/Fiona
+ import collections + from six.moves import UserDict try: from collections import OrderedDict except ImportError: from ordereddict import OrderedDict + + # Users can pass in objects that subclass a few different objects + # More specifically, rasterio has a CRS() class that subclasses UserDict() + # In Python 2 UserDict() is in its own module and does not subclass Mapping() + DICT_TYPES = (dict, collections.Mapping, UserDict) +
Add a DICT_TYPES variable so we can do isinstance() checks against all the builtin dict-like objects
## Code Before: try: from collections import OrderedDict except ImportError: from ordereddict import OrderedDict ## Instruction: Add a DICT_TYPES variable so we can do isinstance() checks against all the builtin dict-like objects ## Code After: import collections from six.moves import UserDict try: from collections import OrderedDict except ImportError: from ordereddict import OrderedDict # Users can pass in objects that subclass a few different objects # More specifically, rasterio has a CRS() class that subclasses UserDict() # In Python 2 UserDict() is in its own module and does not subclass Mapping() DICT_TYPES = (dict, collections.Mapping, UserDict)
0ab048e8363a60d47ba780cb622a72343aaf65f2
tests/test_urls.py
tests/test_urls.py
from django.conf.urls import include, url from django.contrib import admin from django.http.response import HttpResponse admin.autodiscover() def empty_view(request): return HttpResponse() urlpatterns = [ url(r'^home/', empty_view, name="home"), url(r'^admin/', admin.site.urls), url(r'^djstripe/', include("djstripe.urls", namespace="djstripe")), url(r'^testapp/', include('tests.apps.testapp.urls')), url(r'^__debug__/', include('tests.apps.testapp.urls')), url( r'^testapp_namespaced/', include('tests.apps.testapp_namespaced.urls', namespace="testapp_namespaced") ), # Represents protected content url(r'^testapp_content/', include('tests.apps.testapp_content.urls')), # For testing fnmatches url(r"test_fnmatch/extra_text/$", empty_view, name="test_fnmatch"), # Default for DJSTRIPE_SUBSCRIPTION_REDIRECT url(r"subscribe/$", empty_view, name="test_url_subscribe") ]
from django.conf.urls import include, url from django.contrib import admin from django.http.response import HttpResponse admin.autodiscover() def empty_view(request): return HttpResponse() urlpatterns = [ url(r'^home/', empty_view, name="home"), url(r'^admin/', admin.site.urls), url(r'^djstripe/', include("djstripe.urls", namespace="djstripe")), url(r'^testapp/', include('tests.apps.testapp.urls')), url( r'^testapp_namespaced/', include('tests.apps.testapp_namespaced.urls', namespace="testapp_namespaced") ), # Represents protected content url(r'^testapp_content/', include('tests.apps.testapp_content.urls')), # For testing fnmatches url(r"test_fnmatch/extra_text/$", empty_view, name="test_fnmatch"), # Default for DJSTRIPE_SUBSCRIPTION_REDIRECT url(r"subscribe/$", empty_view, name="test_url_subscribe") ]
Remove useless url from test urls
Remove useless url from test urls
Python
mit
pydanny/dj-stripe,kavdev/dj-stripe,dj-stripe/dj-stripe,kavdev/dj-stripe,pydanny/dj-stripe,dj-stripe/dj-stripe
from django.conf.urls import include, url from django.contrib import admin from django.http.response import HttpResponse admin.autodiscover() def empty_view(request): return HttpResponse() urlpatterns = [ url(r'^home/', empty_view, name="home"), url(r'^admin/', admin.site.urls), url(r'^djstripe/', include("djstripe.urls", namespace="djstripe")), url(r'^testapp/', include('tests.apps.testapp.urls')), - url(r'^__debug__/', include('tests.apps.testapp.urls')), url( r'^testapp_namespaced/', include('tests.apps.testapp_namespaced.urls', namespace="testapp_namespaced") ), # Represents protected content url(r'^testapp_content/', include('tests.apps.testapp_content.urls')), # For testing fnmatches url(r"test_fnmatch/extra_text/$", empty_view, name="test_fnmatch"), # Default for DJSTRIPE_SUBSCRIPTION_REDIRECT url(r"subscribe/$", empty_view, name="test_url_subscribe") ]
Remove useless url from test urls
## Code Before: from django.conf.urls import include, url from django.contrib import admin from django.http.response import HttpResponse admin.autodiscover() def empty_view(request): return HttpResponse() urlpatterns = [ url(r'^home/', empty_view, name="home"), url(r'^admin/', admin.site.urls), url(r'^djstripe/', include("djstripe.urls", namespace="djstripe")), url(r'^testapp/', include('tests.apps.testapp.urls')), url(r'^__debug__/', include('tests.apps.testapp.urls')), url( r'^testapp_namespaced/', include('tests.apps.testapp_namespaced.urls', namespace="testapp_namespaced") ), # Represents protected content url(r'^testapp_content/', include('tests.apps.testapp_content.urls')), # For testing fnmatches url(r"test_fnmatch/extra_text/$", empty_view, name="test_fnmatch"), # Default for DJSTRIPE_SUBSCRIPTION_REDIRECT url(r"subscribe/$", empty_view, name="test_url_subscribe") ] ## Instruction: Remove useless url from test urls ## Code After: from django.conf.urls import include, url from django.contrib import admin from django.http.response import HttpResponse admin.autodiscover() def empty_view(request): return HttpResponse() urlpatterns = [ url(r'^home/', empty_view, name="home"), url(r'^admin/', admin.site.urls), url(r'^djstripe/', include("djstripe.urls", namespace="djstripe")), url(r'^testapp/', include('tests.apps.testapp.urls')), url( r'^testapp_namespaced/', include('tests.apps.testapp_namespaced.urls', namespace="testapp_namespaced") ), # Represents protected content url(r'^testapp_content/', include('tests.apps.testapp_content.urls')), # For testing fnmatches url(r"test_fnmatch/extra_text/$", empty_view, name="test_fnmatch"), # Default for DJSTRIPE_SUBSCRIPTION_REDIRECT url(r"subscribe/$", empty_view, name="test_url_subscribe") ]
305d04fc0841035bf744480261017c14ae3045b0
syntax_makefile.py
syntax_makefile.py
import wx.stc ident = "makefile" name = "Makefile" extensions = ["Makefile", "*.mk"] lexer = wx.stc.STC_LEX_MAKEFILE indent = 8 use_tabs = True stylespecs = ( (wx.stc.STC_STYLE_DEFAULT, ""), ) keywords = ""
import wx.stc ident = "makefile" name = "Makefile" extensions = ["*Makefile", "*makefile", "*.mk"] lexer = wx.stc.STC_LEX_MAKEFILE indent = 8 use_tabs = True stylespecs = ( (wx.stc.STC_STYLE_DEFAULT, ""), ) keywords = ""
Make files ending in makefile or Makefile.
Make files ending in makefile or Makefile.
Python
mit
shaurz/devo
import wx.stc ident = "makefile" name = "Makefile" - extensions = ["Makefile", "*.mk"] + extensions = ["*Makefile", "*makefile", "*.mk"] lexer = wx.stc.STC_LEX_MAKEFILE indent = 8 use_tabs = True stylespecs = ( (wx.stc.STC_STYLE_DEFAULT, ""), ) keywords = ""
Make files ending in makefile or Makefile.
## Code Before: import wx.stc ident = "makefile" name = "Makefile" extensions = ["Makefile", "*.mk"] lexer = wx.stc.STC_LEX_MAKEFILE indent = 8 use_tabs = True stylespecs = ( (wx.stc.STC_STYLE_DEFAULT, ""), ) keywords = "" ## Instruction: Make files ending in makefile or Makefile. ## Code After: import wx.stc ident = "makefile" name = "Makefile" extensions = ["*Makefile", "*makefile", "*.mk"] lexer = wx.stc.STC_LEX_MAKEFILE indent = 8 use_tabs = True stylespecs = ( (wx.stc.STC_STYLE_DEFAULT, ""), ) keywords = ""
19ac41a14875c6df2ed9ddf7b7b315ffb5c70819
tests/specs/test_yaml_file.py
tests/specs/test_yaml_file.py
import unittest try: from unittest import mock except ImportError: import mock from conda_env import env from conda_env.specs.yaml_file import YamlFileSpec class TestYAMLFile(unittest.TestCase): def test_no_environment_file(self): spec = YamlFileSpec(name=None, filename='not-a-file') self.assertEqual(spec.can_handle(), False) def test_environment_file_exist(self): with mock.patch.object(env, 'from_file', return_value={}): spec = YamlFileSpec(name=None, filename='environment.yaml') self.assertTrue(spec.can_handle()) def test_get_environment(self): with mock.patch.object(env, 'from_file', return_value={}): spec = YamlFileSpec(name=None, filename='environment.yaml') self.assertIsInstance(spec.environment, dict)
import unittest import random try: from unittest import mock except ImportError: import mock from conda_env import env from conda_env.specs.yaml_file import YamlFileSpec class TestYAMLFile(unittest.TestCase): def test_no_environment_file(self): spec = YamlFileSpec(name=None, filename='not-a-file') self.assertEqual(spec.can_handle(), False) def test_environment_file_exist(self): with mock.patch.object(env, 'from_file', return_value={}): spec = YamlFileSpec(name=None, filename='environment.yaml') self.assertTrue(spec.can_handle()) def test_get_environment(self): r = random.randint(100, 200) with mock.patch.object(env, 'from_file', return_value=r): spec = YamlFileSpec(name=None, filename='environment.yaml') self.assertEqual(spec.environment, r) def test_filename(self): filename = "filename_{}".format(random.randint(100, 200)) with mock.patch.object(env, 'from_file') as from_file: spec = YamlFileSpec(filename=filename) spec.environment from_file.assert_called_with(filename)
Add more tests to YamlFile class
Add more tests to YamlFile class
Python
bsd-3-clause
ESSS/conda-env,phobson/conda-env,conda/conda-env,asmeurer/conda-env,conda/conda-env,mikecroucher/conda-env,isaac-kit/conda-env,ESSS/conda-env,isaac-kit/conda-env,dan-blanchard/conda-env,phobson/conda-env,nicoddemus/conda-env,dan-blanchard/conda-env,asmeurer/conda-env,nicoddemus/conda-env,mikecroucher/conda-env
import unittest + import random try: from unittest import mock except ImportError: import mock from conda_env import env from conda_env.specs.yaml_file import YamlFileSpec class TestYAMLFile(unittest.TestCase): def test_no_environment_file(self): spec = YamlFileSpec(name=None, filename='not-a-file') self.assertEqual(spec.can_handle(), False) def test_environment_file_exist(self): with mock.patch.object(env, 'from_file', return_value={}): spec = YamlFileSpec(name=None, filename='environment.yaml') self.assertTrue(spec.can_handle()) def test_get_environment(self): + r = random.randint(100, 200) - with mock.patch.object(env, 'from_file', return_value={}): + with mock.patch.object(env, 'from_file', return_value=r): spec = YamlFileSpec(name=None, filename='environment.yaml') - self.assertIsInstance(spec.environment, dict) + self.assertEqual(spec.environment, r) + def test_filename(self): + filename = "filename_{}".format(random.randint(100, 200)) + with mock.patch.object(env, 'from_file') as from_file: + spec = YamlFileSpec(filename=filename) + spec.environment + from_file.assert_called_with(filename) +
Add more tests to YamlFile class
## Code Before: import unittest try: from unittest import mock except ImportError: import mock from conda_env import env from conda_env.specs.yaml_file import YamlFileSpec class TestYAMLFile(unittest.TestCase): def test_no_environment_file(self): spec = YamlFileSpec(name=None, filename='not-a-file') self.assertEqual(spec.can_handle(), False) def test_environment_file_exist(self): with mock.patch.object(env, 'from_file', return_value={}): spec = YamlFileSpec(name=None, filename='environment.yaml') self.assertTrue(spec.can_handle()) def test_get_environment(self): with mock.patch.object(env, 'from_file', return_value={}): spec = YamlFileSpec(name=None, filename='environment.yaml') self.assertIsInstance(spec.environment, dict) ## Instruction: Add more tests to YamlFile class ## Code After: import unittest import random try: from unittest import mock except ImportError: import mock from conda_env import env from conda_env.specs.yaml_file import YamlFileSpec class TestYAMLFile(unittest.TestCase): def test_no_environment_file(self): spec = YamlFileSpec(name=None, filename='not-a-file') self.assertEqual(spec.can_handle(), False) def test_environment_file_exist(self): with mock.patch.object(env, 'from_file', return_value={}): spec = YamlFileSpec(name=None, filename='environment.yaml') self.assertTrue(spec.can_handle()) def test_get_environment(self): r = random.randint(100, 200) with mock.patch.object(env, 'from_file', return_value=r): spec = YamlFileSpec(name=None, filename='environment.yaml') self.assertEqual(spec.environment, r) def test_filename(self): filename = "filename_{}".format(random.randint(100, 200)) with mock.patch.object(env, 'from_file') as from_file: spec = YamlFileSpec(filename=filename) spec.environment from_file.assert_called_with(filename)
ecc3a9c90d20699c6f0bf18600cf9bd755b56d65
rollbar/contrib/fastapi/utils.py
rollbar/contrib/fastapi/utils.py
import logging log = logging.getLogger(__name__) class FastAPIVersionError(Exception): def __init__(self, version, reason=''): err_msg = f'FastAPI {version}+ is required' if reason: err_msg += f' {reason}' log.error(err_msg) return super().__init__(err_msg)
import functools import logging import fastapi log = logging.getLogger(__name__) class FastAPIVersionError(Exception): def __init__(self, version, reason=''): err_msg = f'FastAPI {version}+ is required' if reason: err_msg += f' {reason}' log.error(err_msg) return super().__init__(err_msg) class fastapi_min_version: def __init__(self, min_version): self.min_version = min_version def __call__(self, func): @functools.wraps(func) def wrapper(*args, **kwargs): if fastapi.__version__ < self.min_version: raise FastAPIVersionError( '0.41.0', reason=f'to use {func.__name__}() function' ) return func(*args, **kwargs) return wrapper
Add decorator to check minimum required FastAPI version
Add decorator to check minimum required FastAPI version
Python
mit
rollbar/pyrollbar
+ import functools import logging + + import fastapi log = logging.getLogger(__name__) class FastAPIVersionError(Exception): def __init__(self, version, reason=''): err_msg = f'FastAPI {version}+ is required' if reason: err_msg += f' {reason}' log.error(err_msg) return super().__init__(err_msg) + + class fastapi_min_version: + def __init__(self, min_version): + self.min_version = min_version + + def __call__(self, func): + @functools.wraps(func) + def wrapper(*args, **kwargs): + if fastapi.__version__ < self.min_version: + raise FastAPIVersionError( + '0.41.0', reason=f'to use {func.__name__}() function' + ) + + return func(*args, **kwargs) + + return wrapper +
Add decorator to check minimum required FastAPI version
## Code Before: import logging log = logging.getLogger(__name__) class FastAPIVersionError(Exception): def __init__(self, version, reason=''): err_msg = f'FastAPI {version}+ is required' if reason: err_msg += f' {reason}' log.error(err_msg) return super().__init__(err_msg) ## Instruction: Add decorator to check minimum required FastAPI version ## Code After: import functools import logging import fastapi log = logging.getLogger(__name__) class FastAPIVersionError(Exception): def __init__(self, version, reason=''): err_msg = f'FastAPI {version}+ is required' if reason: err_msg += f' {reason}' log.error(err_msg) return super().__init__(err_msg) class fastapi_min_version: def __init__(self, min_version): self.min_version = min_version def __call__(self, func): @functools.wraps(func) def wrapper(*args, **kwargs): if fastapi.__version__ < self.min_version: raise FastAPIVersionError( '0.41.0', reason=f'to use {func.__name__}() function' ) return func(*args, **kwargs) return wrapper
8582126efa9907b06e9f9b183a0919feba9fb6b0
indra/literature/dart_client.py
indra/literature/dart_client.py
import logging import requests from indra.config import CONFIG_DICT logger = logging.getLogger(__name__) dart_uname = CONFIG_DICT['DART_WM_USERNAME'] dart_pwd = CONFIG_DICT['DART_WM_PASSWORD'] dart_url = 'https://indra-ingest-pipeline-rest-1.prod.dart.worldmodelers.com' \ '/dart/api/v1/readers/query' def query_dart_notifications(readers=None, versions=None, document_ids=None, timestamp=None): """ Parameters ---------- readers : list versions : list document_ids : list timestamp : dict("on"|"before"|"after",str) Returns ------- dict """ if all(v is None for v in [readers, versions, document_ids, timestamp]): return {} pd = {} if readers: pd['readers'] = readers if versions: pd['versions'] = versions if document_ids: pd['document_ids'] = document_ids if isinstance(timestamp, dict): pass # Check res = requests.post( dart_url, data={'metadata': None }, auth=(dart_uname, dart_pwd) ) if res.status_code != 200: logger.warning(f'Dart Notifications Endpoint returned with status' f' {res.status_code}: {res.text}') return {} return res.json()
import logging import requests from indra.config import get_config logger = logging.getLogger(__name__) dart_uname = get_config('DART_WM_USERNAME') dart_pwd = get_config('DART_WM_PASSWORD') dart_url = 'https://indra-ingest-pipeline-rest-1.prod.dart.worldmodelers.com' \ '/dart/api/v1/readers/query' def query_dart_notifications(readers=None, versions=None, document_ids=None, timestamp=None): """ Parameters ---------- readers : list versions : list document_ids : list timestamp : dict("on"|"before"|"after",str) Returns ------- dict """ if all(v is None for v in [readers, versions, document_ids, timestamp]): return {} pd = {} if readers: pd['readers'] = readers if versions: pd['versions'] = versions if document_ids: pd['document_ids'] = document_ids if isinstance(timestamp, dict): pass # Check res = requests.post( dart_url, data={'metadata': None }, auth=(dart_uname, dart_pwd) ) if res.status_code != 200: logger.warning(f'Dart Notifications Endpoint returned with status' f' {res.status_code}: {res.text}') return {} return res.json()
Use get_config instead of CONFIG_DICT
Use get_config instead of CONFIG_DICT
Python
bsd-2-clause
johnbachman/indra,johnbachman/belpy,johnbachman/belpy,sorgerlab/belpy,bgyori/indra,sorgerlab/belpy,johnbachman/indra,johnbachman/belpy,bgyori/indra,bgyori/indra,sorgerlab/indra,sorgerlab/indra,sorgerlab/indra,sorgerlab/belpy,johnbachman/indra
import logging import requests - from indra.config import CONFIG_DICT + from indra.config import get_config logger = logging.getLogger(__name__) - dart_uname = CONFIG_DICT['DART_WM_USERNAME'] - dart_pwd = CONFIG_DICT['DART_WM_PASSWORD'] + dart_uname = get_config('DART_WM_USERNAME') + dart_pwd = get_config('DART_WM_PASSWORD') dart_url = 'https://indra-ingest-pipeline-rest-1.prod.dart.worldmodelers.com' \ '/dart/api/v1/readers/query' def query_dart_notifications(readers=None, versions=None, document_ids=None, timestamp=None): """ Parameters ---------- readers : list versions : list document_ids : list timestamp : dict("on"|"before"|"after",str) Returns ------- dict """ if all(v is None for v in [readers, versions, document_ids, timestamp]): return {} pd = {} if readers: pd['readers'] = readers if versions: pd['versions'] = versions if document_ids: pd['document_ids'] = document_ids if isinstance(timestamp, dict): pass # Check res = requests.post( dart_url, data={'metadata': None }, auth=(dart_uname, dart_pwd) ) if res.status_code != 200: logger.warning(f'Dart Notifications Endpoint returned with status' f' {res.status_code}: {res.text}') return {} return res.json()
Use get_config instead of CONFIG_DICT
## Code Before: import logging import requests from indra.config import CONFIG_DICT logger = logging.getLogger(__name__) dart_uname = CONFIG_DICT['DART_WM_USERNAME'] dart_pwd = CONFIG_DICT['DART_WM_PASSWORD'] dart_url = 'https://indra-ingest-pipeline-rest-1.prod.dart.worldmodelers.com' \ '/dart/api/v1/readers/query' def query_dart_notifications(readers=None, versions=None, document_ids=None, timestamp=None): """ Parameters ---------- readers : list versions : list document_ids : list timestamp : dict("on"|"before"|"after",str) Returns ------- dict """ if all(v is None for v in [readers, versions, document_ids, timestamp]): return {} pd = {} if readers: pd['readers'] = readers if versions: pd['versions'] = versions if document_ids: pd['document_ids'] = document_ids if isinstance(timestamp, dict): pass # Check res = requests.post( dart_url, data={'metadata': None }, auth=(dart_uname, dart_pwd) ) if res.status_code != 200: logger.warning(f'Dart Notifications Endpoint returned with status' f' {res.status_code}: {res.text}') return {} return res.json() ## Instruction: Use get_config instead of CONFIG_DICT ## Code After: import logging import requests from indra.config import get_config logger = logging.getLogger(__name__) dart_uname = get_config('DART_WM_USERNAME') dart_pwd = get_config('DART_WM_PASSWORD') dart_url = 'https://indra-ingest-pipeline-rest-1.prod.dart.worldmodelers.com' \ '/dart/api/v1/readers/query' def query_dart_notifications(readers=None, versions=None, document_ids=None, timestamp=None): """ Parameters ---------- readers : list versions : list document_ids : list timestamp : dict("on"|"before"|"after",str) Returns ------- dict """ if all(v is None for v in [readers, versions, document_ids, timestamp]): return {} pd = {} if readers: pd['readers'] = readers if versions: pd['versions'] = versions if document_ids: pd['document_ids'] = document_ids if isinstance(timestamp, dict): pass # Check res = requests.post( dart_url, data={'metadata': None }, auth=(dart_uname, dart_pwd) ) if res.status_code != 200: logger.warning(f'Dart Notifications Endpoint returned with status' f' {res.status_code}: {res.text}') return {} return res.json()
ef42117ec2bd2a275dcea5f5a2d57322bbd21faa
wafer/talks/tests/fixtures.py
wafer/talks/tests/fixtures.py
from wafer.talks.models import Talk, TalkType from wafer.tests.utils import create_user def create_talk_type(name): """Create a talk type""" return TalkType.objects.create(name=name) def create_talk(title, status, username=None, user=None, talk_type=None): if username: user = create_user(username) talk = Talk.objects.create( title=title, status=status, corresponding_author_id=user.id) talk.authors.add(user) talk.notes = "Some notes for talk %s" % title talk.private_notes = "Some private notes for talk %s" % title talk.save() if talk_type: talk.talk_type = talk_type talk.save() return talk
from wafer.talks.models import Talk, TalkType from wafer.tests.utils import create_user def create_talk_type(name): """Create a talk type""" return TalkType.objects.create(name=name) def create_talk(title, status, username=None, user=None, talk_type=None): if sum((user is None, username is None)) != 1: raise ValueError('One of user OR username must be specified') if username: user = create_user(username) talk = Talk.objects.create( title=title, status=status, corresponding_author_id=user.id) talk.authors.add(user) talk.notes = "Some notes for talk %s" % title talk.private_notes = "Some private notes for talk %s" % title talk.save() if talk_type: talk.talk_type = talk_type talk.save() return talk
Check that user OR username is specified
Check that user OR username is specified
Python
isc
CTPUG/wafer,CTPUG/wafer,CTPUG/wafer,CTPUG/wafer
from wafer.talks.models import Talk, TalkType from wafer.tests.utils import create_user def create_talk_type(name): """Create a talk type""" return TalkType.objects.create(name=name) def create_talk(title, status, username=None, user=None, talk_type=None): + if sum((user is None, username is None)) != 1: + raise ValueError('One of user OR username must be specified') if username: user = create_user(username) talk = Talk.objects.create( title=title, status=status, corresponding_author_id=user.id) talk.authors.add(user) talk.notes = "Some notes for talk %s" % title talk.private_notes = "Some private notes for talk %s" % title talk.save() if talk_type: talk.talk_type = talk_type talk.save() return talk
Check that user OR username is specified
## Code Before: from wafer.talks.models import Talk, TalkType from wafer.tests.utils import create_user def create_talk_type(name): """Create a talk type""" return TalkType.objects.create(name=name) def create_talk(title, status, username=None, user=None, talk_type=None): if username: user = create_user(username) talk = Talk.objects.create( title=title, status=status, corresponding_author_id=user.id) talk.authors.add(user) talk.notes = "Some notes for talk %s" % title talk.private_notes = "Some private notes for talk %s" % title talk.save() if talk_type: talk.talk_type = talk_type talk.save() return talk ## Instruction: Check that user OR username is specified ## Code After: from wafer.talks.models import Talk, TalkType from wafer.tests.utils import create_user def create_talk_type(name): """Create a talk type""" return TalkType.objects.create(name=name) def create_talk(title, status, username=None, user=None, talk_type=None): if sum((user is None, username is None)) != 1: raise ValueError('One of user OR username must be specified') if username: user = create_user(username) talk = Talk.objects.create( title=title, status=status, corresponding_author_id=user.id) talk.authors.add(user) talk.notes = "Some notes for talk %s" % title talk.private_notes = "Some private notes for talk %s" % title talk.save() if talk_type: talk.talk_type = talk_type talk.save() return talk
a6d49059851450c7ea527941600564cb3f48cc72
flask_profiler/storage/base.py
flask_profiler/storage/base.py
class BaseStorage(object): """docstring for BaseStorage""" def __init__(self): super(BaseStorage, self).__init__() def filter(self, criteria): raise Exception("Not implemneted Error") def getSummary(self, criteria): raise Exception("Not implemneted Error") def insert(self, measurement): raise Exception("Not implemented Error") def delete(self, measurementId): raise Exception("Not imlemented Error")
class BaseStorage(object): """docstring for BaseStorage""" def __init__(self): super(BaseStorage, self).__init__() def filter(self, criteria): raise Exception("Not implemneted Error") def getSummary(self, criteria): raise Exception("Not implemneted Error") def insert(self, measurement): raise Exception("Not implemented Error") def delete(self, measurementId): raise Exception("Not imlemented Error") def truncate(self): raise Exception("Not imlemented Error")
Add tuncate method to BaseStorage class
Add tuncate method to BaseStorage class This will provide an interface for supporting any new database, there by, making the code more robust.
Python
mit
muatik/flask-profiler
class BaseStorage(object): """docstring for BaseStorage""" def __init__(self): super(BaseStorage, self).__init__() def filter(self, criteria): raise Exception("Not implemneted Error") def getSummary(self, criteria): raise Exception("Not implemneted Error") def insert(self, measurement): raise Exception("Not implemented Error") def delete(self, measurementId): raise Exception("Not imlemented Error") + def truncate(self): + raise Exception("Not imlemented Error") +
Add tuncate method to BaseStorage class
## Code Before: class BaseStorage(object): """docstring for BaseStorage""" def __init__(self): super(BaseStorage, self).__init__() def filter(self, criteria): raise Exception("Not implemneted Error") def getSummary(self, criteria): raise Exception("Not implemneted Error") def insert(self, measurement): raise Exception("Not implemented Error") def delete(self, measurementId): raise Exception("Not imlemented Error") ## Instruction: Add tuncate method to BaseStorage class ## Code After: class BaseStorage(object): """docstring for BaseStorage""" def __init__(self): super(BaseStorage, self).__init__() def filter(self, criteria): raise Exception("Not implemneted Error") def getSummary(self, criteria): raise Exception("Not implemneted Error") def insert(self, measurement): raise Exception("Not implemented Error") def delete(self, measurementId): raise Exception("Not imlemented Error") def truncate(self): raise Exception("Not imlemented Error")
d7299fd931ae62cc661b48dbc84aa161a395f1fa
fermipy/__init__.py
fermipy/__init__.py
import os __version__ = "unknown" try: from version import get_git_version __version__ = get_git_version() except Exception as message: print(message) __author__ = "Matthew Wood" PACKAGE_ROOT = os.path.abspath(os.path.dirname(__file__)) PACKAGE_DATA = os.path.join(PACKAGE_ROOT,'data') os.environ['FERMIPY_ROOT'] = PACKAGE_ROOT os.environ['FERMIPY_DATA_DIR'] = PACKAGE_DATA
from __future__ import absolute_import, division, print_function import os __version__ = "unknown" try: from .version import get_git_version __version__ = get_git_version() except Exception as message: print(message) __author__ = "Matthew Wood" PACKAGE_ROOT = os.path.abspath(os.path.dirname(__file__)) PACKAGE_DATA = os.path.join(PACKAGE_ROOT,'data') os.environ['FERMIPY_ROOT'] = PACKAGE_ROOT os.environ['FERMIPY_DATA_DIR'] = PACKAGE_DATA
Fix version module import for Python 3
Fix version module import for Python 3
Python
bsd-3-clause
jefemagril/fermipy,jefemagril/fermipy,jefemagril/fermipy,fermiPy/fermipy
+ from __future__ import absolute_import, division, print_function import os __version__ = "unknown" try: - from version import get_git_version + from .version import get_git_version __version__ = get_git_version() except Exception as message: print(message) __author__ = "Matthew Wood" PACKAGE_ROOT = os.path.abspath(os.path.dirname(__file__)) PACKAGE_DATA = os.path.join(PACKAGE_ROOT,'data') os.environ['FERMIPY_ROOT'] = PACKAGE_ROOT os.environ['FERMIPY_DATA_DIR'] = PACKAGE_DATA
Fix version module import for Python 3
## Code Before: import os __version__ = "unknown" try: from version import get_git_version __version__ = get_git_version() except Exception as message: print(message) __author__ = "Matthew Wood" PACKAGE_ROOT = os.path.abspath(os.path.dirname(__file__)) PACKAGE_DATA = os.path.join(PACKAGE_ROOT,'data') os.environ['FERMIPY_ROOT'] = PACKAGE_ROOT os.environ['FERMIPY_DATA_DIR'] = PACKAGE_DATA ## Instruction: Fix version module import for Python 3 ## Code After: from __future__ import absolute_import, division, print_function import os __version__ = "unknown" try: from .version import get_git_version __version__ = get_git_version() except Exception as message: print(message) __author__ = "Matthew Wood" PACKAGE_ROOT = os.path.abspath(os.path.dirname(__file__)) PACKAGE_DATA = os.path.join(PACKAGE_ROOT,'data') os.environ['FERMIPY_ROOT'] = PACKAGE_ROOT os.environ['FERMIPY_DATA_DIR'] = PACKAGE_DATA
67795baac1f7eb10fbfc90fda5a9f54949af6c24
ckanext/tayside/helpers.py
ckanext/tayside/helpers.py
from ckan import model from ckan.plugins import toolkit def _get_action(action, context_dict, data_dict): return toolkit.get_action(action)(context_dict, data_dict) def get_groups(): # Helper used on the homepage for showing groups data_dict = { 'sort': 'package_count', 'limit': 7, 'all_fields': True } groups = _get_action('group_list', {}, data_dict) return groups
from ckan import model from ckan.plugins import toolkit def _get_action(action, context_dict, data_dict): return toolkit.get_action(action)(context_dict, data_dict) def get_groups(): # Helper used on the homepage for showing groups data_dict = { 'sort': 'package_count', 'all_fields': True } groups = _get_action('group_list', {}, data_dict) return groups
Remove limit of 7 groups in homepage
Remove limit of 7 groups in homepage
Python
agpl-3.0
ViderumGlobal/ckanext-tayside,ViderumGlobal/ckanext-tayside,ViderumGlobal/ckanext-tayside,ViderumGlobal/ckanext-tayside
from ckan import model from ckan.plugins import toolkit def _get_action(action, context_dict, data_dict): return toolkit.get_action(action)(context_dict, data_dict) def get_groups(): # Helper used on the homepage for showing groups data_dict = { 'sort': 'package_count', - 'limit': 7, 'all_fields': True } groups = _get_action('group_list', {}, data_dict) return groups
Remove limit of 7 groups in homepage
## Code Before: from ckan import model from ckan.plugins import toolkit def _get_action(action, context_dict, data_dict): return toolkit.get_action(action)(context_dict, data_dict) def get_groups(): # Helper used on the homepage for showing groups data_dict = { 'sort': 'package_count', 'limit': 7, 'all_fields': True } groups = _get_action('group_list', {}, data_dict) return groups ## Instruction: Remove limit of 7 groups in homepage ## Code After: from ckan import model from ckan.plugins import toolkit def _get_action(action, context_dict, data_dict): return toolkit.get_action(action)(context_dict, data_dict) def get_groups(): # Helper used on the homepage for showing groups data_dict = { 'sort': 'package_count', 'all_fields': True } groups = _get_action('group_list', {}, data_dict) return groups
8fad8a4f1591fb4a7d7d1bdf932c5918197b475c
tests/client.py
tests/client.py
from htmltree import * def start(): console.log("Starting") newcontent = H1("Sanity check PASS", _class='test', style=dict(color='green')) console.log(newcontent.render(0)) document.body.innerHTML = newcontent.render() console.log("Finished") document.addEventListener('DOMContentLoaded', start)
from htmltree import * def start(): console.log("Starting") ## insert a style element at the end of the <head? cssrules = {'.test':{'color':'green', 'text-align':'center'}} style = Style(**cssrules) document.head.insertAdjacentHTML('beforeend', style.render()) ## Replace the <body> content newcontent = Div(H1("Sanity check PASS", _class='test')) document.body.innerHTML = newcontent.render() console.log("Finished") ## JS is event driven. ## Wait for DOM load to complete before firing ## our start() function. document.addEventListener('DOMContentLoaded', start)
Fix <style> rendering under Transcrypt.
Fix <style> rendering under Transcrypt. The hasattr test in renderCss() was failing when it shouldn't have. Fixed by removal. Updated tests/client.py to create and append a style element to detect problems related to Style() on the client side.
Python
mit
Michael-F-Ellis/htmltree
from htmltree import * def start(): console.log("Starting") + ## insert a style element at the end of the <head? + cssrules = {'.test':{'color':'green', 'text-align':'center'}} + style = Style(**cssrules) + document.head.insertAdjacentHTML('beforeend', style.render()) + + ## Replace the <body> content - newcontent = H1("Sanity check PASS", _class='test', style=dict(color='green')) + newcontent = Div(H1("Sanity check PASS", _class='test')) - console.log(newcontent.render(0)) document.body.innerHTML = newcontent.render() console.log("Finished") + + ## JS is event driven. + ## Wait for DOM load to complete before firing + ## our start() function. document.addEventListener('DOMContentLoaded', start)
Fix <style> rendering under Transcrypt.
## Code Before: from htmltree import * def start(): console.log("Starting") newcontent = H1("Sanity check PASS", _class='test', style=dict(color='green')) console.log(newcontent.render(0)) document.body.innerHTML = newcontent.render() console.log("Finished") document.addEventListener('DOMContentLoaded', start) ## Instruction: Fix <style> rendering under Transcrypt. ## Code After: from htmltree import * def start(): console.log("Starting") ## insert a style element at the end of the <head? cssrules = {'.test':{'color':'green', 'text-align':'center'}} style = Style(**cssrules) document.head.insertAdjacentHTML('beforeend', style.render()) ## Replace the <body> content newcontent = Div(H1("Sanity check PASS", _class='test')) document.body.innerHTML = newcontent.render() console.log("Finished") ## JS is event driven. ## Wait for DOM load to complete before firing ## our start() function. document.addEventListener('DOMContentLoaded', start)
e91eac0c667c74062672a1a2cdb7da2a910f8cf7
InvenTree/users/serializers.py
InvenTree/users/serializers.py
from rest_framework import serializers from django.contrib.auth.models import User class UserSerializer(serializers.HyperlinkedModelSerializer): """ Serializer for a User """ class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email',)
from rest_framework import serializers from django.contrib.auth.models import User class UserSerializer(serializers.HyperlinkedModelSerializer): """ Serializer for a User """ class Meta: model = User fields = ('pk', 'username', 'first_name', 'last_name', 'email',)
Include PK in user serializer
Include PK in user serializer
Python
mit
inventree/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,inventree/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,SchrodingersGat/InvenTree,SchrodingersGat/InvenTree
from rest_framework import serializers from django.contrib.auth.models import User class UserSerializer(serializers.HyperlinkedModelSerializer): """ Serializer for a User """ class Meta: model = User - fields = ('username', + fields = ('pk', + 'username', 'first_name', 'last_name', 'email',)
Include PK in user serializer
## Code Before: from rest_framework import serializers from django.contrib.auth.models import User class UserSerializer(serializers.HyperlinkedModelSerializer): """ Serializer for a User """ class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email',) ## Instruction: Include PK in user serializer ## Code After: from rest_framework import serializers from django.contrib.auth.models import User class UserSerializer(serializers.HyperlinkedModelSerializer): """ Serializer for a User """ class Meta: model = User fields = ('pk', 'username', 'first_name', 'last_name', 'email',)
bf9866e2c337f024fcc02de69456a235dc7ac07c
labs/lab-6/common.py
labs/lab-6/common.py
import time import sys import os from tspapi import API class Common(object): def __init__(self, ): self.api = API() self.usage_args = "" @staticmethod def usage(self, args): sys.stderr.write("usage: {0} {1}\n".format(os.path.basename(sys.argv[0]), args)) def send_measurements(self, measurements): """ Sends measurements using the Measurement API :param measurements: :return: None """ self.api.measurement_create_batch(measurements) def run(self): """ Main loop """ while True: print("Doing absolutely nothing") time.sleep(self.interval)
import time import sys import os from tspapi import API class Common(object): def __init__(self, ): self.api = API() self.usage_args = "" # Set our application id from the environment variable self.appl_id = os.environ['TSI_APPL_ID'] @staticmethod def usage(args): sys.stderr.write("usage: {0} {1}\n".format(os.path.basename(sys.argv[0]), args)) def send_measurements(self, measurements): """ Sends measurements using the Measurement API :param measurements: :return: None """ self.api.measurement_create_batch(measurements) def run(self): """ Main loop """ while True: print("Doing absolutely nothing") time.sleep(self.interval)
Add application id and static method for usage
Add application id and static method for usage
Python
apache-2.0
jdgwartney/tsi-lab,jdgwartney/tsi-lab,jdgwartney/tsi-lab,jdgwartney/tsi-lab,boundary/tsi-lab,boundary/tsi-lab,boundary/tsi-lab,boundary/tsi-lab
import time import sys import os from tspapi import API class Common(object): def __init__(self, ): self.api = API() self.usage_args = "" + # Set our application id from the environment variable + self.appl_id = os.environ['TSI_APPL_ID'] @staticmethod - def usage(self, args): + def usage(args): sys.stderr.write("usage: {0} {1}\n".format(os.path.basename(sys.argv[0]), args)) def send_measurements(self, measurements): """ Sends measurements using the Measurement API :param measurements: :return: None """ self.api.measurement_create_batch(measurements) def run(self): """ Main loop """ while True: print("Doing absolutely nothing") time.sleep(self.interval)
Add application id and static method for usage
## Code Before: import time import sys import os from tspapi import API class Common(object): def __init__(self, ): self.api = API() self.usage_args = "" @staticmethod def usage(self, args): sys.stderr.write("usage: {0} {1}\n".format(os.path.basename(sys.argv[0]), args)) def send_measurements(self, measurements): """ Sends measurements using the Measurement API :param measurements: :return: None """ self.api.measurement_create_batch(measurements) def run(self): """ Main loop """ while True: print("Doing absolutely nothing") time.sleep(self.interval) ## Instruction: Add application id and static method for usage ## Code After: import time import sys import os from tspapi import API class Common(object): def __init__(self, ): self.api = API() self.usage_args = "" # Set our application id from the environment variable self.appl_id = os.environ['TSI_APPL_ID'] @staticmethod def usage(args): sys.stderr.write("usage: {0} {1}\n".format(os.path.basename(sys.argv[0]), args)) def send_measurements(self, measurements): """ Sends measurements using the Measurement API :param measurements: :return: None """ self.api.measurement_create_batch(measurements) def run(self): """ Main loop """ while True: print("Doing absolutely nothing") time.sleep(self.interval)
eec24c2cff1b588b957215a867a85a148f4e71e9
tuneme/views.py
tuneme/views.py
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.shortcuts import render from molo.core.models import ArticlePage from molo.commenting.models import MoloComment from wagtail.wagtailsearch.models import Query def search(request, results_per_page=10): search_query = request.GET.get('q', None) page = request.GET.get('p', 1) if search_query: results = ArticlePage.objects.live().search(search_query) Query.get(search_query).add_hit() else: results = ArticlePage.objects.none() paginator = Paginator(results, results_per_page) try: search_results = paginator.page(page) except PageNotAnInteger: search_results = paginator.page(1) except EmptyPage: search_results = paginator.page(paginator.num_pages) return render(request, 'search/search_results.html', { 'search_query': search_query, 'search_results': search_results, 'results': results, }) def report_response(request, comment_pk): comment = MoloComment.objects.get(pk=comment_pk) return render(request, 'comments/report_response.html', { 'article': comment.content_object, })
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.shortcuts import render from django.utils.translation import get_language_from_request from molo.core.utils import get_locale_code from molo.core.models import ArticlePage from molo.commenting.models import MoloComment from wagtail.wagtailsearch.models import Query def search(request, results_per_page=10): search_query = request.GET.get('q', None) page = request.GET.get('p', 1) locale = get_locale_code(get_language_from_request(request)) if search_query: results = ArticlePage.objects.filter( languages__language__locale=locale).live().search(search_query) Query.get(search_query).add_hit() else: results = ArticlePage.objects.none() paginator = Paginator(results, results_per_page) try: search_results = paginator.page(page) except PageNotAnInteger: search_results = paginator.page(1) except EmptyPage: search_results = paginator.page(paginator.num_pages) return render(request, 'search/search_results.html', { 'search_query': search_query, 'search_results': search_results, 'results': results, }) def report_response(request, comment_pk): comment = MoloComment.objects.get(pk=comment_pk) return render(request, 'comments/report_response.html', { 'article': comment.content_object, })
Add multi-languages support for search
Add multi-languages support for search
Python
bsd-2-clause
praekelt/molo-tuneme,praekelt/molo-tuneme,praekelt/molo-tuneme,praekelt/molo-tuneme
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.shortcuts import render + from django.utils.translation import get_language_from_request + from molo.core.utils import get_locale_code from molo.core.models import ArticlePage from molo.commenting.models import MoloComment from wagtail.wagtailsearch.models import Query def search(request, results_per_page=10): search_query = request.GET.get('q', None) page = request.GET.get('p', 1) + locale = get_locale_code(get_language_from_request(request)) if search_query: - results = ArticlePage.objects.live().search(search_query) + results = ArticlePage.objects.filter( + languages__language__locale=locale).live().search(search_query) Query.get(search_query).add_hit() else: results = ArticlePage.objects.none() paginator = Paginator(results, results_per_page) try: search_results = paginator.page(page) except PageNotAnInteger: search_results = paginator.page(1) except EmptyPage: search_results = paginator.page(paginator.num_pages) return render(request, 'search/search_results.html', { 'search_query': search_query, 'search_results': search_results, 'results': results, }) def report_response(request, comment_pk): comment = MoloComment.objects.get(pk=comment_pk) return render(request, 'comments/report_response.html', { 'article': comment.content_object, })
Add multi-languages support for search
## Code Before: from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.shortcuts import render from molo.core.models import ArticlePage from molo.commenting.models import MoloComment from wagtail.wagtailsearch.models import Query def search(request, results_per_page=10): search_query = request.GET.get('q', None) page = request.GET.get('p', 1) if search_query: results = ArticlePage.objects.live().search(search_query) Query.get(search_query).add_hit() else: results = ArticlePage.objects.none() paginator = Paginator(results, results_per_page) try: search_results = paginator.page(page) except PageNotAnInteger: search_results = paginator.page(1) except EmptyPage: search_results = paginator.page(paginator.num_pages) return render(request, 'search/search_results.html', { 'search_query': search_query, 'search_results': search_results, 'results': results, }) def report_response(request, comment_pk): comment = MoloComment.objects.get(pk=comment_pk) return render(request, 'comments/report_response.html', { 'article': comment.content_object, }) ## Instruction: Add multi-languages support for search ## Code After: from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.shortcuts import render from django.utils.translation import get_language_from_request from molo.core.utils import get_locale_code from molo.core.models import ArticlePage from molo.commenting.models import MoloComment from wagtail.wagtailsearch.models import Query def search(request, results_per_page=10): search_query = request.GET.get('q', None) page = request.GET.get('p', 1) locale = get_locale_code(get_language_from_request(request)) if search_query: results = ArticlePage.objects.filter( languages__language__locale=locale).live().search(search_query) Query.get(search_query).add_hit() else: results = ArticlePage.objects.none() paginator = Paginator(results, results_per_page) try: search_results = paginator.page(page) except PageNotAnInteger: search_results = paginator.page(1) except EmptyPage: search_results = paginator.page(paginator.num_pages) return render(request, 'search/search_results.html', { 'search_query': search_query, 'search_results': search_results, 'results': results, }) def report_response(request, comment_pk): comment = MoloComment.objects.get(pk=comment_pk) return render(request, 'comments/report_response.html', { 'article': comment.content_object, })
46fc6c7f8f63ce747a30a35bb5fb33ff2d53a2c0
mackerel/host.py
mackerel/host.py
import re class Host(object): MACKEREL_INTERFACE_NAME_PATTERN = re.compile(r'^eth\d') def __init__(self, **kwargs): self.args = kwargs self.name = kwargs.get('name') self.meta = kwargs.get('meta') self.type = kwargs.get('type') self.status = kwargs.get('status') self.memo = kwargs.get('memo') self.is_retired = kwargs.get('isRetired') self.id = kwargs.get('id') self.created_at = kwargs.get('createdAt') self.roles = kwargs.get('roles') self.interfaces = kwargs.get('interfaces') def ip_addr(self): pass def mac_addr(self): pass
import re class Host(object): MACKEREL_INTERFACE_NAME_PATTERN = re.compile(r'^eth\d') def __init__(self, **kwargs): self.args = kwargs self.name = kwargs.get('name', None) self.meta = kwargs.get('meta', None) self.type = kwargs.get('type', None) self.status = kwargs.get('status', None) self.memo = kwargs.get('memo', None) self.is_retired = kwargs.get('isRetired', None) self.id = kwargs.get('id', None) self.created_at = kwargs.get('createdAt', None) self.roles = kwargs.get('roles', None) self.interfaces = kwargs.get('interfaces', None) def ip_addr(self): pass def mac_addr(self): pass
Add None if kwargs can not get.
Add None if kwargs can not get.
Python
bsd-3-clause
heavenshell/py-mackerel-client
import re class Host(object): MACKEREL_INTERFACE_NAME_PATTERN = re.compile(r'^eth\d') def __init__(self, **kwargs): self.args = kwargs - self.name = kwargs.get('name') + self.name = kwargs.get('name', None) - self.meta = kwargs.get('meta') + self.meta = kwargs.get('meta', None) - self.type = kwargs.get('type') + self.type = kwargs.get('type', None) - self.status = kwargs.get('status') + self.status = kwargs.get('status', None) - self.memo = kwargs.get('memo') + self.memo = kwargs.get('memo', None) - self.is_retired = kwargs.get('isRetired') + self.is_retired = kwargs.get('isRetired', None) - self.id = kwargs.get('id') + self.id = kwargs.get('id', None) - self.created_at = kwargs.get('createdAt') + self.created_at = kwargs.get('createdAt', None) - self.roles = kwargs.get('roles') + self.roles = kwargs.get('roles', None) - self.interfaces = kwargs.get('interfaces') + self.interfaces = kwargs.get('interfaces', None) def ip_addr(self): pass def mac_addr(self): pass
Add None if kwargs can not get.
## Code Before: import re class Host(object): MACKEREL_INTERFACE_NAME_PATTERN = re.compile(r'^eth\d') def __init__(self, **kwargs): self.args = kwargs self.name = kwargs.get('name') self.meta = kwargs.get('meta') self.type = kwargs.get('type') self.status = kwargs.get('status') self.memo = kwargs.get('memo') self.is_retired = kwargs.get('isRetired') self.id = kwargs.get('id') self.created_at = kwargs.get('createdAt') self.roles = kwargs.get('roles') self.interfaces = kwargs.get('interfaces') def ip_addr(self): pass def mac_addr(self): pass ## Instruction: Add None if kwargs can not get. ## Code After: import re class Host(object): MACKEREL_INTERFACE_NAME_PATTERN = re.compile(r'^eth\d') def __init__(self, **kwargs): self.args = kwargs self.name = kwargs.get('name', None) self.meta = kwargs.get('meta', None) self.type = kwargs.get('type', None) self.status = kwargs.get('status', None) self.memo = kwargs.get('memo', None) self.is_retired = kwargs.get('isRetired', None) self.id = kwargs.get('id', None) self.created_at = kwargs.get('createdAt', None) self.roles = kwargs.get('roles', None) self.interfaces = kwargs.get('interfaces', None) def ip_addr(self): pass def mac_addr(self): pass
63a893add1170c1e90cdb8eaea6c1e1c6a3a8e0a
9.py
9.py
def main(): pass if __name__ == "__main__": main()
import urllib import urllib2 from PIL import Image, ImageDraw un = 'huge' pw = 'file' url = 'http://www.pythonchallenge.com/pc/return/good.jpg' def setup_auth_handler(): password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() password_mgr.add_password(None, url, un, pw) handler = urllib2.HTTPBasicAuthHandler(password_mgr) opener = urllib2.build_opener(handler) opener.open(url) urllib2.install_opener(opener) def main(): setup_auth_handler() img = urllib2.urlopen('http://www.pythonchallenge.com/pc/return/good.jpg') im = Image.open(img) draw = ImageDraw.Draw(im) draw.line([(0, 0), im.size], fill=128) im.show() if __name__ == "__main__": main()
Add authentication handler for opening image.
Add authentication handler for opening image.
Python
mit
bm5w/pychal
+ import urllib + import urllib2 + from PIL import Image, ImageDraw + un = 'huge' + pw = 'file' + url = 'http://www.pythonchallenge.com/pc/return/good.jpg' + + + def setup_auth_handler(): + password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() + password_mgr.add_password(None, url, un, pw) + handler = urllib2.HTTPBasicAuthHandler(password_mgr) + opener = urllib2.build_opener(handler) + opener.open(url) + urllib2.install_opener(opener) def main(): - pass + setup_auth_handler() + img = urllib2.urlopen('http://www.pythonchallenge.com/pc/return/good.jpg') + im = Image.open(img) + draw = ImageDraw.Draw(im) + draw.line([(0, 0), im.size], fill=128) + im.show() if __name__ == "__main__": main()
Add authentication handler for opening image.
## Code Before: def main(): pass if __name__ == "__main__": main() ## Instruction: Add authentication handler for opening image. ## Code After: import urllib import urllib2 from PIL import Image, ImageDraw un = 'huge' pw = 'file' url = 'http://www.pythonchallenge.com/pc/return/good.jpg' def setup_auth_handler(): password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() password_mgr.add_password(None, url, un, pw) handler = urllib2.HTTPBasicAuthHandler(password_mgr) opener = urllib2.build_opener(handler) opener.open(url) urllib2.install_opener(opener) def main(): setup_auth_handler() img = urllib2.urlopen('http://www.pythonchallenge.com/pc/return/good.jpg') im = Image.open(img) draw = ImageDraw.Draw(im) draw.line([(0, 0), im.size], fill=128) im.show() if __name__ == "__main__": main()
52d32849f4cd38ca7a0fcfc0418e9e9580dd426a
kimochiconsumer/views.py
kimochiconsumer/views.py
from pyramid.view import view_config from pyramid.httpexceptions import ( HTTPNotFound, ) @view_config(route_name='page', renderer='templates/page.mako') @view_config(route_name='page_view', renderer='templates/page.mako') def page_view(request): if 'page_id' in request.matchdict: data = request.kimochi.page(request.matchdict['page_id']) else: data = request.kimochi.page('1') return data @view_config(route_name='gallery_view', renderer='templates/gallery.mako') def gallery_view(request): data = request.kimochi.gallery(request.matchdict['gallery_id']) if 'gallery' not in data or not data['gallery']: raise HTTPNotFound return data @view_config(route_name='gallery_image_view', renderer='templates/gallery_image.mako') def gallery_image_view(request): data = request.kimochi.gallery(request.matchdict['gallery_id']) if 'gallery' not in data or not data['gallery']: raise HTTPNotFound return data
from pyramid.view import view_config from pyramid.httpexceptions import ( HTTPNotFound, ) @view_config(route_name='page', renderer='templates/page.mako') @view_config(route_name='page_view', renderer='templates/page.mako') def page_view(request): if 'page_id' in request.matchdict: data = request.kimochi.page(request.matchdict['page_id']) else: data = request.kimochi.page('1') return data @view_config(route_name='gallery_view', renderer='templates/gallery.mako') def gallery_view(request): data = request.kimochi.gallery(request.matchdict['gallery_id']) if 'gallery' not in data or not data['gallery']: raise HTTPNotFound return data @view_config(route_name='gallery_image_view', renderer='templates/gallery_image.mako') def gallery_image_view(request): data = request.kimochi.gallery_image(request.matchdict['gallery_id'], request.matchdict['image_id']) if 'gallery' not in data or not data['gallery']: raise HTTPNotFound return data
Use the gallery_image method for required information
Use the gallery_image method for required information
Python
mit
matslindh/kimochi-consumer
from pyramid.view import view_config from pyramid.httpexceptions import ( HTTPNotFound, ) @view_config(route_name='page', renderer='templates/page.mako') @view_config(route_name='page_view', renderer='templates/page.mako') def page_view(request): if 'page_id' in request.matchdict: data = request.kimochi.page(request.matchdict['page_id']) else: data = request.kimochi.page('1') return data @view_config(route_name='gallery_view', renderer='templates/gallery.mako') def gallery_view(request): data = request.kimochi.gallery(request.matchdict['gallery_id']) if 'gallery' not in data or not data['gallery']: raise HTTPNotFound return data @view_config(route_name='gallery_image_view', renderer='templates/gallery_image.mako') def gallery_image_view(request): - data = request.kimochi.gallery(request.matchdict['gallery_id']) + data = request.kimochi.gallery_image(request.matchdict['gallery_id'], request.matchdict['image_id']) if 'gallery' not in data or not data['gallery']: raise HTTPNotFound return data
Use the gallery_image method for required information
## Code Before: from pyramid.view import view_config from pyramid.httpexceptions import ( HTTPNotFound, ) @view_config(route_name='page', renderer='templates/page.mako') @view_config(route_name='page_view', renderer='templates/page.mako') def page_view(request): if 'page_id' in request.matchdict: data = request.kimochi.page(request.matchdict['page_id']) else: data = request.kimochi.page('1') return data @view_config(route_name='gallery_view', renderer='templates/gallery.mako') def gallery_view(request): data = request.kimochi.gallery(request.matchdict['gallery_id']) if 'gallery' not in data or not data['gallery']: raise HTTPNotFound return data @view_config(route_name='gallery_image_view', renderer='templates/gallery_image.mako') def gallery_image_view(request): data = request.kimochi.gallery(request.matchdict['gallery_id']) if 'gallery' not in data or not data['gallery']: raise HTTPNotFound return data ## Instruction: Use the gallery_image method for required information ## Code After: from pyramid.view import view_config from pyramid.httpexceptions import ( HTTPNotFound, ) @view_config(route_name='page', renderer='templates/page.mako') @view_config(route_name='page_view', renderer='templates/page.mako') def page_view(request): if 'page_id' in request.matchdict: data = request.kimochi.page(request.matchdict['page_id']) else: data = request.kimochi.page('1') return data @view_config(route_name='gallery_view', renderer='templates/gallery.mako') def gallery_view(request): data = request.kimochi.gallery(request.matchdict['gallery_id']) if 'gallery' not in data or not data['gallery']: raise HTTPNotFound return data @view_config(route_name='gallery_image_view', renderer='templates/gallery_image.mako') def gallery_image_view(request): data = request.kimochi.gallery_image(request.matchdict['gallery_id'], request.matchdict['image_id']) if 'gallery' not in data or not data['gallery']: raise HTTPNotFound return data
cc6ce477550152135eed5a9e35bca8144be10111
groupmestats/plotly_helpers.py
groupmestats/plotly_helpers.py
import plotly def try_saving_plotly_figure(figure, filename): try: plotly.plotly.image.save_as(figure, filename) except plotly.exceptions.PlotlyError as e: if 'The response from plotly could not be translated.'in str(e): print("Failed to save plotly figure. <home>/.plotly/.credentials" " might not be configured correctly? " "Or you may have hit your plotly account's rate limit" " (http://help.plot.ly/api-rate-limits/)") else: raise # A green bar with slightly darker green line marker = dict( color='#4BB541', line=dict( color='#3A9931', width=1.5, ) )
import plotly def try_saving_plotly_figure(figure, filename): try: print("Saving plot to '%s'" % filename) plotly.plotly.image.save_as(figure, filename) except plotly.exceptions.PlotlyError as e: if 'The response from plotly could not be translated.'in str(e): print("Failed to save plotly figure. <home>/.plotly/.credentials" " might not be configured correctly? " "Or you may have hit your plotly account's rate limit" " (http://help.plot.ly/api-rate-limits/)") else: raise # A green bar with slightly darker green line marker = dict( color='#4BB541', line=dict( color='#3A9931', width=1.5, ) )
Print when saving plot to file
Print when saving plot to file
Python
mit
kjteske/groupmestats,kjteske/groupmestats
import plotly def try_saving_plotly_figure(figure, filename): try: + print("Saving plot to '%s'" % filename) plotly.plotly.image.save_as(figure, filename) except plotly.exceptions.PlotlyError as e: if 'The response from plotly could not be translated.'in str(e): print("Failed to save plotly figure. <home>/.plotly/.credentials" " might not be configured correctly? " "Or you may have hit your plotly account's rate limit" " (http://help.plot.ly/api-rate-limits/)") else: raise # A green bar with slightly darker green line marker = dict( color='#4BB541', line=dict( color='#3A9931', width=1.5, ) )
Print when saving plot to file
## Code Before: import plotly def try_saving_plotly_figure(figure, filename): try: plotly.plotly.image.save_as(figure, filename) except plotly.exceptions.PlotlyError as e: if 'The response from plotly could not be translated.'in str(e): print("Failed to save plotly figure. <home>/.plotly/.credentials" " might not be configured correctly? " "Or you may have hit your plotly account's rate limit" " (http://help.plot.ly/api-rate-limits/)") else: raise # A green bar with slightly darker green line marker = dict( color='#4BB541', line=dict( color='#3A9931', width=1.5, ) ) ## Instruction: Print when saving plot to file ## Code After: import plotly def try_saving_plotly_figure(figure, filename): try: print("Saving plot to '%s'" % filename) plotly.plotly.image.save_as(figure, filename) except plotly.exceptions.PlotlyError as e: if 'The response from plotly could not be translated.'in str(e): print("Failed to save plotly figure. <home>/.plotly/.credentials" " might not be configured correctly? " "Or you may have hit your plotly account's rate limit" " (http://help.plot.ly/api-rate-limits/)") else: raise # A green bar with slightly darker green line marker = dict( color='#4BB541', line=dict( color='#3A9931', width=1.5, ) )
e2ca99c9f3548fa0d4e46bdd3b309ebd0e658ffa
test/backend/wayland/conftest.py
test/backend/wayland/conftest.py
import contextlib import os from libqtile.backend.wayland.core import Core from test.helpers import Backend wlr_env = { "WLR_BACKENDS": "headless", "WLR_LIBINPUT_NO_DEVICES": "1", "WLR_RENDERER_ALLOW_SOFTWARE": "1", "WLR_RENDERER": "pixman", } @contextlib.contextmanager def wayland_environment(outputs): """This backend just needs some environmental variables set""" env = wlr_env.copy() env["WLR_HEADLESS_OUTPUTS"] = str(outputs) yield env class WaylandBackend(Backend): def __init__(self, env, args=()): self.env = env self.args = args self.core = Core self.manager = None def create(self): """This is used to instantiate the Core""" os.environ.update(self.env) return self.core(*self.args) def configure(self, manager): """This backend needs to get WAYLAND_DISPLAY variable.""" success, display = manager.c.eval("self.core.display_name") assert success self.env["WAYLAND_DISPLAY"] = display def fake_click(self, x, y): """Click at the specified coordinates""" raise NotImplementedError def get_all_windows(self): """Get a list of all windows in ascending order of Z position""" raise NotImplementedError
import contextlib import os import textwrap from libqtile.backend.wayland.core import Core from test.helpers import Backend wlr_env = { "WLR_BACKENDS": "headless", "WLR_LIBINPUT_NO_DEVICES": "1", "WLR_RENDERER_ALLOW_SOFTWARE": "1", "WLR_RENDERER": "pixman", } @contextlib.contextmanager def wayland_environment(outputs): """This backend just needs some environmental variables set""" env = wlr_env.copy() env["WLR_HEADLESS_OUTPUTS"] = str(outputs) yield env class WaylandBackend(Backend): def __init__(self, env, args=()): self.env = env self.args = args self.core = Core self.manager = None def create(self): """This is used to instantiate the Core""" os.environ.update(self.env) return self.core(*self.args) def configure(self, manager): """This backend needs to get WAYLAND_DISPLAY variable.""" success, display = manager.c.eval("self.core.display_name") assert success self.env["WAYLAND_DISPLAY"] = display def fake_click(self, x, y): """Click at the specified coordinates""" self.manager.c.eval(textwrap.dedent(""" self.core._focus_by_click() self.core._process_cursor_button(1, True) """)) def get_all_windows(self): """Get a list of all windows in ascending order of Z position""" success, result = self.manager.c.eval(textwrap.dedent(""" [win.wid for win in self.core.mapped_windows] """)) assert success return eval(result)
Add Wayland Backend.fake_click and Backend.get_all_windows methods
Add Wayland Backend.fake_click and Backend.get_all_windows methods These work by eval-ing in the test Qtile instance. It might be nicer to instead make these cmd_s on the `Core` if/when we expose cmd_ methods from the Core.
Python
mit
ramnes/qtile,ramnes/qtile,qtile/qtile,qtile/qtile
import contextlib import os + import textwrap from libqtile.backend.wayland.core import Core from test.helpers import Backend wlr_env = { "WLR_BACKENDS": "headless", "WLR_LIBINPUT_NO_DEVICES": "1", "WLR_RENDERER_ALLOW_SOFTWARE": "1", "WLR_RENDERER": "pixman", } @contextlib.contextmanager def wayland_environment(outputs): """This backend just needs some environmental variables set""" env = wlr_env.copy() env["WLR_HEADLESS_OUTPUTS"] = str(outputs) yield env class WaylandBackend(Backend): def __init__(self, env, args=()): self.env = env self.args = args self.core = Core self.manager = None def create(self): """This is used to instantiate the Core""" os.environ.update(self.env) return self.core(*self.args) def configure(self, manager): """This backend needs to get WAYLAND_DISPLAY variable.""" success, display = manager.c.eval("self.core.display_name") assert success self.env["WAYLAND_DISPLAY"] = display def fake_click(self, x, y): """Click at the specified coordinates""" - raise NotImplementedError + self.manager.c.eval(textwrap.dedent(""" + self.core._focus_by_click() + self.core._process_cursor_button(1, True) + """)) def get_all_windows(self): """Get a list of all windows in ascending order of Z position""" - raise NotImplementedError + success, result = self.manager.c.eval(textwrap.dedent(""" + [win.wid for win in self.core.mapped_windows] + """)) + assert success + return eval(result)
Add Wayland Backend.fake_click and Backend.get_all_windows methods
## Code Before: import contextlib import os from libqtile.backend.wayland.core import Core from test.helpers import Backend wlr_env = { "WLR_BACKENDS": "headless", "WLR_LIBINPUT_NO_DEVICES": "1", "WLR_RENDERER_ALLOW_SOFTWARE": "1", "WLR_RENDERER": "pixman", } @contextlib.contextmanager def wayland_environment(outputs): """This backend just needs some environmental variables set""" env = wlr_env.copy() env["WLR_HEADLESS_OUTPUTS"] = str(outputs) yield env class WaylandBackend(Backend): def __init__(self, env, args=()): self.env = env self.args = args self.core = Core self.manager = None def create(self): """This is used to instantiate the Core""" os.environ.update(self.env) return self.core(*self.args) def configure(self, manager): """This backend needs to get WAYLAND_DISPLAY variable.""" success, display = manager.c.eval("self.core.display_name") assert success self.env["WAYLAND_DISPLAY"] = display def fake_click(self, x, y): """Click at the specified coordinates""" raise NotImplementedError def get_all_windows(self): """Get a list of all windows in ascending order of Z position""" raise NotImplementedError ## Instruction: Add Wayland Backend.fake_click and Backend.get_all_windows methods ## Code After: import contextlib import os import textwrap from libqtile.backend.wayland.core import Core from test.helpers import Backend wlr_env = { "WLR_BACKENDS": "headless", "WLR_LIBINPUT_NO_DEVICES": "1", "WLR_RENDERER_ALLOW_SOFTWARE": "1", "WLR_RENDERER": "pixman", } @contextlib.contextmanager def wayland_environment(outputs): """This backend just needs some environmental variables set""" env = wlr_env.copy() env["WLR_HEADLESS_OUTPUTS"] = str(outputs) yield env class WaylandBackend(Backend): def __init__(self, env, args=()): self.env = env self.args = args self.core = Core self.manager = None def create(self): """This is used to instantiate the Core""" os.environ.update(self.env) return self.core(*self.args) def configure(self, manager): """This backend needs to get WAYLAND_DISPLAY variable.""" success, display = manager.c.eval("self.core.display_name") assert success self.env["WAYLAND_DISPLAY"] = display def fake_click(self, x, y): """Click at the specified coordinates""" self.manager.c.eval(textwrap.dedent(""" self.core._focus_by_click() self.core._process_cursor_button(1, True) """)) def get_all_windows(self): """Get a list of all windows in ascending order of Z position""" success, result = self.manager.c.eval(textwrap.dedent(""" [win.wid for win in self.core.mapped_windows] """)) assert success return eval(result)
33c26aab9ff4e391f9dde2bfe873f86db4ce126e
opal/tests/test_user_profile.py
opal/tests/test_user_profile.py
from django.test import TestCase from django.contrib.auth.models import User from opal.models import UserProfile, Team class UserProfileTest(TestCase): def setUp(self): self.user = User(username='testing') self.user.save() self.profile, _ = UserProfile.objects.get_or_create(user=self.user) def test_get_roles(self): self.assertEqual({'default': []}, self.profile.get_roles()) def test_get_teams(self): teams = list(Team.objects.filter(active=True, restricted=False)) user_teams = self.profile.get_teams() for t in teams: self.assertIn(t, user_teams)
from django.contrib.auth.models import User from django.test import TestCase from mock import patch from opal.models import UserProfile, Team class UserProfileTest(TestCase): def setUp(self): self.user = User(username='testing') self.user.save() self.profile, _ = UserProfile.objects.get_or_create(user=self.user) def test_get_roles(self): self.assertEqual({'default': []}, self.profile.get_roles()) def test_get_teams(self): teams = list(Team.objects.filter(active=True, restricted=False)) user_teams = self.profile.get_teams() for t in teams: self.assertIn(t, user_teams) def test_can_see_pid(self): with patch.object(UserProfile, 'get_roles') as mock_roles: mock_roles.return_value = dict(default=['scientist']) self.assertEqual(False, self.profile.can_see_pid) def test_explicit_access_only(self): with patch.object(UserProfile, 'get_roles') as mock_roles: mock_roles.return_value = dict(default=['scientist']) self.assertEqual(True, self.profile.explicit_access_only)
Add tests for userprofile properties
Add tests for userprofile properties
Python
agpl-3.0
khchine5/opal,khchine5/opal,khchine5/opal
+ from django.contrib.auth.models import User from django.test import TestCase + from mock import patch - - from django.contrib.auth.models import User from opal.models import UserProfile, Team class UserProfileTest(TestCase): def setUp(self): self.user = User(username='testing') self.user.save() self.profile, _ = UserProfile.objects.get_or_create(user=self.user) def test_get_roles(self): self.assertEqual({'default': []}, self.profile.get_roles()) def test_get_teams(self): teams = list(Team.objects.filter(active=True, restricted=False)) user_teams = self.profile.get_teams() for t in teams: - self.assertIn(t, user_teams) + self.assertIn(t, user_teams) + def test_can_see_pid(self): + with patch.object(UserProfile, 'get_roles') as mock_roles: + mock_roles.return_value = dict(default=['scientist']) + self.assertEqual(False, self.profile.can_see_pid) + + def test_explicit_access_only(self): + with patch.object(UserProfile, 'get_roles') as mock_roles: + mock_roles.return_value = dict(default=['scientist']) + self.assertEqual(True, self.profile.explicit_access_only) +
Add tests for userprofile properties
## Code Before: from django.test import TestCase from django.contrib.auth.models import User from opal.models import UserProfile, Team class UserProfileTest(TestCase): def setUp(self): self.user = User(username='testing') self.user.save() self.profile, _ = UserProfile.objects.get_or_create(user=self.user) def test_get_roles(self): self.assertEqual({'default': []}, self.profile.get_roles()) def test_get_teams(self): teams = list(Team.objects.filter(active=True, restricted=False)) user_teams = self.profile.get_teams() for t in teams: self.assertIn(t, user_teams) ## Instruction: Add tests for userprofile properties ## Code After: from django.contrib.auth.models import User from django.test import TestCase from mock import patch from opal.models import UserProfile, Team class UserProfileTest(TestCase): def setUp(self): self.user = User(username='testing') self.user.save() self.profile, _ = UserProfile.objects.get_or_create(user=self.user) def test_get_roles(self): self.assertEqual({'default': []}, self.profile.get_roles()) def test_get_teams(self): teams = list(Team.objects.filter(active=True, restricted=False)) user_teams = self.profile.get_teams() for t in teams: self.assertIn(t, user_teams) def test_can_see_pid(self): with patch.object(UserProfile, 'get_roles') as mock_roles: mock_roles.return_value = dict(default=['scientist']) self.assertEqual(False, self.profile.can_see_pid) def test_explicit_access_only(self): with patch.object(UserProfile, 'get_roles') as mock_roles: mock_roles.return_value = dict(default=['scientist']) self.assertEqual(True, self.profile.explicit_access_only)
5a82f76e3e95268fb1bbb297faa43e7f7cb59058
tests/perf_concrete_execution.py
tests/perf_concrete_execution.py
import os import time import logging import angr test_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', 'binaries', 'tests')) def test_tight_loop(arch): b = angr.Project(os.path.join(test_location, arch, "perf_tight_loops"), auto_load_libs=False) simgr = b.factory.simgr() # logging.getLogger('angr.sim_manager').setLevel(logging.INFO) start = time.time() simgr.explore() elapsed = time.time() - start print("Elapsed %f sec" % elapsed) print(simgr) if __name__ == "__main__": test_tight_loop("x86_64")
import os import time import logging import angr test_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', 'binaries', 'tests')) def test_tight_loop(arch): b = angr.Project(os.path.join(test_location, arch, "perf_tight_loops"), auto_load_libs=False) state = b.factory.full_init_state(plugins={'registers': angr.state_plugins.SimLightRegisters()}, remove_options={angr.sim_options.COPY_STATES}) simgr = b.factory.simgr(state) # logging.getLogger('angr.sim_manager').setLevel(logging.INFO) start = time.time() simgr.explore() elapsed = time.time() - start print("Elapsed %f sec" % elapsed) print(simgr) if __name__ == "__main__": test_tight_loop("x86_64")
Enable SimLightRegisters and remove COPY_STATES for the performance test case.
Enable SimLightRegisters and remove COPY_STATES for the performance test case.
Python
bsd-2-clause
angr/angr,schieb/angr,schieb/angr,iamahuman/angr,schieb/angr,iamahuman/angr,angr/angr,iamahuman/angr,angr/angr
import os import time import logging import angr test_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', 'binaries', 'tests')) def test_tight_loop(arch): b = angr.Project(os.path.join(test_location, arch, "perf_tight_loops"), auto_load_libs=False) + state = b.factory.full_init_state(plugins={'registers': angr.state_plugins.SimLightRegisters()}, + remove_options={angr.sim_options.COPY_STATES}) - simgr = b.factory.simgr() + simgr = b.factory.simgr(state) # logging.getLogger('angr.sim_manager').setLevel(logging.INFO) start = time.time() simgr.explore() elapsed = time.time() - start print("Elapsed %f sec" % elapsed) print(simgr) if __name__ == "__main__": test_tight_loop("x86_64")
Enable SimLightRegisters and remove COPY_STATES for the performance test case.
## Code Before: import os import time import logging import angr test_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', 'binaries', 'tests')) def test_tight_loop(arch): b = angr.Project(os.path.join(test_location, arch, "perf_tight_loops"), auto_load_libs=False) simgr = b.factory.simgr() # logging.getLogger('angr.sim_manager').setLevel(logging.INFO) start = time.time() simgr.explore() elapsed = time.time() - start print("Elapsed %f sec" % elapsed) print(simgr) if __name__ == "__main__": test_tight_loop("x86_64") ## Instruction: Enable SimLightRegisters and remove COPY_STATES for the performance test case. ## Code After: import os import time import logging import angr test_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', 'binaries', 'tests')) def test_tight_loop(arch): b = angr.Project(os.path.join(test_location, arch, "perf_tight_loops"), auto_load_libs=False) state = b.factory.full_init_state(plugins={'registers': angr.state_plugins.SimLightRegisters()}, remove_options={angr.sim_options.COPY_STATES}) simgr = b.factory.simgr(state) # logging.getLogger('angr.sim_manager').setLevel(logging.INFO) start = time.time() simgr.explore() elapsed = time.time() - start print("Elapsed %f sec" % elapsed) print(simgr) if __name__ == "__main__": test_tight_loop("x86_64")
db981f7616283992fd1d17a3b1bf7d300b8ee34f
proper_parens.py
proper_parens.py
from __future__ import unicode_literals <<<<<<< HEAD def check_statement1(value): output = 0 while output >= 0: for item in value: if item == ")": output -= 1 if output == -1: return -1 elif item == "(": output += 1 if output == 0: return 0 elif output > 1: return 1 ======= def check_statement(value): ''' Return 1, 0, or -1 if input is open, balanced, or broken. ''' output = 0 index = 0 while index < len(value) and output >= 0: # If the count is ever < 0, statement must be -1 (broken), end loop # If the index is out of range, end loop if value[index] == ")": # Subtract 1 for every close paren output -= 1 elif value[index] == "(": # Add 1 for every close paren output += 1 index += 1 if output == -1: # Check if output is -1 (broken) return output elif not output: # Check if output is 0 (balanced) return output else: # Must be 1 (open) if it makes it to here return 1 >>>>>>> 74dee1d09fdc09f93af3d15286336d7face4ba08
from __future__ import unicode_literals def check_statement(value): ''' Return 1, 0, or -1 if input is open, balanced, or broken. ''' output = 0 index = 0 while index < len(value) and output >= 0: # If the count is ever < 0, statement must be -1 (broken), end loop # If the index is out of range, end loop if value[index] == ")": # Subtract 1 for every close paren output -= 1 elif value[index] == "(": # Add 1 for every close paren output += 1 index += 1 if output == -1: # Check if output is -1 (broken) return output elif not output: # Check if output is 0 (balanced) return output else: # Must be 1 (open) if it makes it to here return 1
Fix proper parens merge conflict
Fix proper parens merge conflict
Python
mit
constanthatz/data-structures
from __future__ import unicode_literals - <<<<<<< HEAD - def check_statement1(value): - output = 0 - while output >= 0: - for item in value: - if item == ")": - output -= 1 - if output == -1: - return -1 - elif item == "(": - output += 1 - if output == 0: - return 0 - elif output > 1: - return 1 - ======= def check_statement(value): ''' Return 1, 0, or -1 if input is open, balanced, or broken. ''' output = 0 index = 0 while index < len(value) and output >= 0: # If the count is ever < 0, statement must be -1 (broken), end loop # If the index is out of range, end loop if value[index] == ")": # Subtract 1 for every close paren output -= 1 elif value[index] == "(": # Add 1 for every close paren output += 1 index += 1 if output == -1: # Check if output is -1 (broken) return output elif not output: # Check if output is 0 (balanced) return output else: # Must be 1 (open) if it makes it to here return 1 - >>>>>>> 74dee1d09fdc09f93af3d15286336d7face4ba08
Fix proper parens merge conflict
## Code Before: from __future__ import unicode_literals <<<<<<< HEAD def check_statement1(value): output = 0 while output >= 0: for item in value: if item == ")": output -= 1 if output == -1: return -1 elif item == "(": output += 1 if output == 0: return 0 elif output > 1: return 1 ======= def check_statement(value): ''' Return 1, 0, or -1 if input is open, balanced, or broken. ''' output = 0 index = 0 while index < len(value) and output >= 0: # If the count is ever < 0, statement must be -1 (broken), end loop # If the index is out of range, end loop if value[index] == ")": # Subtract 1 for every close paren output -= 1 elif value[index] == "(": # Add 1 for every close paren output += 1 index += 1 if output == -1: # Check if output is -1 (broken) return output elif not output: # Check if output is 0 (balanced) return output else: # Must be 1 (open) if it makes it to here return 1 >>>>>>> 74dee1d09fdc09f93af3d15286336d7face4ba08 ## Instruction: Fix proper parens merge conflict ## Code After: from __future__ import unicode_literals def check_statement(value): ''' Return 1, 0, or -1 if input is open, balanced, or broken. ''' output = 0 index = 0 while index < len(value) and output >= 0: # If the count is ever < 0, statement must be -1 (broken), end loop # If the index is out of range, end loop if value[index] == ")": # Subtract 1 for every close paren output -= 1 elif value[index] == "(": # Add 1 for every close paren output += 1 index += 1 if output == -1: # Check if output is -1 (broken) return output elif not output: # Check if output is 0 (balanced) return output else: # Must be 1 (open) if it makes it to here return 1
075b8ba1813360720fc8933dc5e167f92b4e3aaf
python/epidb/client/client.py
python/epidb/client/client.py
import urllib __version__ = '0.0~20090901.1' __user_agent__ = 'EpiDBClient v%s/python' % __version__ class EpiDBClientOpener(urllib.FancyURLopener): version = __user_agent__ class EpiDBClient: version = __version__ user_agent = __user_agent__ server = 'https://egg.science.uva.nl:7443' path_survey = '/survey/' def __init__(self, api_key=None): self.api_key = api_key def __epidb_call(self, url, param): data = urllib.urlencode(param) opener = EpiDBClientOpener() sock = opener.open(url, data) res = sock.read() sock.close() return res def survey_submit(self, data): param = { 'data': data } url = self.server + self.path_survey res = self.__epidb_call(url, param) return res
import urllib import urllib2 __version__ = '0.0~20090901.1' __user_agent__ = 'EpiDBClient v%s/python' % __version__ class EpiDBClient: version = __version__ user_agent = __user_agent__ server = 'https://egg.science.uva.nl:7443' path_survey = '/survey/' def __init__(self, api_key=None): self.api_key = api_key def __epidb_call(self, url, param): data = urllib.urlencode(param) req = urllib2.Request(url) req.add_header('User-Agent', self.user_agent) if self.api_key: req.add_header('Cookie', 'epidb-apikey=%s' % self.api_key) sock = urllib2.urlopen(req, data) res = sock.read() sock.close() return res def survey_submit(self, data): param = { 'data': data } url = self.server + self.path_survey res = self.__epidb_call(url, param) return res
Send api-key through HTTP cookie.
[python] Send api-key through HTTP cookie.
Python
agpl-3.0
ISIFoundation/influenzanet-epidb-client
import urllib + import urllib2 __version__ = '0.0~20090901.1' __user_agent__ = 'EpiDBClient v%s/python' % __version__ - - class EpiDBClientOpener(urllib.FancyURLopener): - version = __user_agent__ class EpiDBClient: version = __version__ user_agent = __user_agent__ server = 'https://egg.science.uva.nl:7443' path_survey = '/survey/' def __init__(self, api_key=None): self.api_key = api_key def __epidb_call(self, url, param): data = urllib.urlencode(param) - opener = EpiDBClientOpener() - sock = opener.open(url, data) + + req = urllib2.Request(url) + req.add_header('User-Agent', self.user_agent) + if self.api_key: + req.add_header('Cookie', 'epidb-apikey=%s' % self.api_key) + sock = urllib2.urlopen(req, data) res = sock.read() sock.close() return res def survey_submit(self, data): param = { 'data': data } url = self.server + self.path_survey res = self.__epidb_call(url, param) return res
Send api-key through HTTP cookie.
## Code Before: import urllib __version__ = '0.0~20090901.1' __user_agent__ = 'EpiDBClient v%s/python' % __version__ class EpiDBClientOpener(urllib.FancyURLopener): version = __user_agent__ class EpiDBClient: version = __version__ user_agent = __user_agent__ server = 'https://egg.science.uva.nl:7443' path_survey = '/survey/' def __init__(self, api_key=None): self.api_key = api_key def __epidb_call(self, url, param): data = urllib.urlencode(param) opener = EpiDBClientOpener() sock = opener.open(url, data) res = sock.read() sock.close() return res def survey_submit(self, data): param = { 'data': data } url = self.server + self.path_survey res = self.__epidb_call(url, param) return res ## Instruction: Send api-key through HTTP cookie. ## Code After: import urllib import urllib2 __version__ = '0.0~20090901.1' __user_agent__ = 'EpiDBClient v%s/python' % __version__ class EpiDBClient: version = __version__ user_agent = __user_agent__ server = 'https://egg.science.uva.nl:7443' path_survey = '/survey/' def __init__(self, api_key=None): self.api_key = api_key def __epidb_call(self, url, param): data = urllib.urlencode(param) req = urllib2.Request(url) req.add_header('User-Agent', self.user_agent) if self.api_key: req.add_header('Cookie', 'epidb-apikey=%s' % self.api_key) sock = urllib2.urlopen(req, data) res = sock.read() sock.close() return res def survey_submit(self, data): param = { 'data': data } url = self.server + self.path_survey res = self.__epidb_call(url, param) return res
d3933d58b2ebcb0fb0c6301344335ae018973774
n_pair_mc_loss.py
n_pair_mc_loss.py
from chainer import cuda from chainer.functions import matmul from chainer.functions import transpose from chainer.functions import softmax_cross_entropy from chainer.functions import batch_l2_norm_squared def n_pair_mc_loss(f, f_p, l2_reg): """Multi-class N-pair loss (N-pair-mc loss) function. Args: f (~chainer.Variable): Feature vectors. All examples must be different classes each other. f_p (~chainer.Variable): Positive examples corresponding to f. Each example must be the same class for each example in f. l2_reg (~float): A weight of L2 regularization for feature vectors. Returns: ~chainer.Variable: Loss value. See: `Improved Deep Metric Learning with Multi-class N-pair Loss \ Objective <https://papers.nips.cc/paper/6200-improved-deep-metric-\ learning-with-multi-class-n-pair-loss-objective>`_ """ logit = matmul(f, transpose(f_p)) N = len(logit.data) xp = cuda.get_array_module(logit.data) loss_sce = softmax_cross_entropy(logit, xp.arange(N)) l2_loss = sum(batch_l2_norm_squared(f) + batch_l2_norm_squared(f_p)) loss = loss_sce + l2_reg * l2_loss return loss
from chainer import cuda from chainer.functions import matmul from chainer.functions import transpose from chainer.functions import softmax_cross_entropy from chainer.functions import batch_l2_norm_squared def n_pair_mc_loss(f, f_p, l2_reg): """Multi-class N-pair loss (N-pair-mc loss) function. Args: f (~chainer.Variable): Feature vectors. All examples must be different classes each other. f_p (~chainer.Variable): Positive examples corresponding to f. Each example must be the same class for each example in f. l2_reg (~float): A weight of L2 regularization for feature vectors. Returns: ~chainer.Variable: Loss value. See: `Improved Deep Metric Learning with Multi-class N-pair Loss \ Objective <https://papers.nips.cc/paper/6200-improved-deep-metric-\ learning-with-multi-class-n-pair-loss-objective>`_ """ logit = matmul(f, transpose(f_p)) N = len(logit.data) xp = cuda.get_array_module(logit.data) loss_sce = softmax_cross_entropy(logit, xp.arange(N)) l2_loss = sum(batch_l2_norm_squared(f) + batch_l2_norm_squared(f_p)) / (2.0 * N) loss = loss_sce + l2_reg * l2_loss return loss
Modify to average the L2 norm loss of output vectors
Modify to average the L2 norm loss of output vectors
Python
mit
ronekko/deep_metric_learning
from chainer import cuda from chainer.functions import matmul from chainer.functions import transpose from chainer.functions import softmax_cross_entropy from chainer.functions import batch_l2_norm_squared def n_pair_mc_loss(f, f_p, l2_reg): """Multi-class N-pair loss (N-pair-mc loss) function. Args: f (~chainer.Variable): Feature vectors. All examples must be different classes each other. f_p (~chainer.Variable): Positive examples corresponding to f. Each example must be the same class for each example in f. l2_reg (~float): A weight of L2 regularization for feature vectors. Returns: ~chainer.Variable: Loss value. See: `Improved Deep Metric Learning with Multi-class N-pair Loss \ Objective <https://papers.nips.cc/paper/6200-improved-deep-metric-\ learning-with-multi-class-n-pair-loss-objective>`_ """ logit = matmul(f, transpose(f_p)) N = len(logit.data) xp = cuda.get_array_module(logit.data) loss_sce = softmax_cross_entropy(logit, xp.arange(N)) - l2_loss = sum(batch_l2_norm_squared(f) + batch_l2_norm_squared(f_p)) + l2_loss = sum(batch_l2_norm_squared(f) + + batch_l2_norm_squared(f_p)) / (2.0 * N) loss = loss_sce + l2_reg * l2_loss return loss
Modify to average the L2 norm loss of output vectors
## Code Before: from chainer import cuda from chainer.functions import matmul from chainer.functions import transpose from chainer.functions import softmax_cross_entropy from chainer.functions import batch_l2_norm_squared def n_pair_mc_loss(f, f_p, l2_reg): """Multi-class N-pair loss (N-pair-mc loss) function. Args: f (~chainer.Variable): Feature vectors. All examples must be different classes each other. f_p (~chainer.Variable): Positive examples corresponding to f. Each example must be the same class for each example in f. l2_reg (~float): A weight of L2 regularization for feature vectors. Returns: ~chainer.Variable: Loss value. See: `Improved Deep Metric Learning with Multi-class N-pair Loss \ Objective <https://papers.nips.cc/paper/6200-improved-deep-metric-\ learning-with-multi-class-n-pair-loss-objective>`_ """ logit = matmul(f, transpose(f_p)) N = len(logit.data) xp = cuda.get_array_module(logit.data) loss_sce = softmax_cross_entropy(logit, xp.arange(N)) l2_loss = sum(batch_l2_norm_squared(f) + batch_l2_norm_squared(f_p)) loss = loss_sce + l2_reg * l2_loss return loss ## Instruction: Modify to average the L2 norm loss of output vectors ## Code After: from chainer import cuda from chainer.functions import matmul from chainer.functions import transpose from chainer.functions import softmax_cross_entropy from chainer.functions import batch_l2_norm_squared def n_pair_mc_loss(f, f_p, l2_reg): """Multi-class N-pair loss (N-pair-mc loss) function. Args: f (~chainer.Variable): Feature vectors. All examples must be different classes each other. f_p (~chainer.Variable): Positive examples corresponding to f. Each example must be the same class for each example in f. l2_reg (~float): A weight of L2 regularization for feature vectors. Returns: ~chainer.Variable: Loss value. See: `Improved Deep Metric Learning with Multi-class N-pair Loss \ Objective <https://papers.nips.cc/paper/6200-improved-deep-metric-\ learning-with-multi-class-n-pair-loss-objective>`_ """ logit = matmul(f, transpose(f_p)) N = len(logit.data) xp = cuda.get_array_module(logit.data) loss_sce = softmax_cross_entropy(logit, xp.arange(N)) l2_loss = sum(batch_l2_norm_squared(f) + batch_l2_norm_squared(f_p)) / (2.0 * N) loss = loss_sce + l2_reg * l2_loss return loss
a094d29959243777fad47ea38b4497d891b9990e
data/data/models.py
data/data/models.py
from django.db import models from uuid import uuid4 import hashlib def _get_rand_hash(): uid = uuid4() return hashlib.sha1(str(uid)).hexdigest() def generate_token_secret(): return _get_rand_hash(), _get_rand_hash() class User(models.Model): username = models.CharField(max_length=200, unique=True) password = models.CharField(max_length=200) token = models.CharField(max_length=200, blank=True) secret = models.CharField(max_length=200, blank=True) def __unicode__(self): return self.username def save(self, *args, **kwargs): if not self.token: self.token, self.secret = generate_token_secret() return super(User, self).save(*args, **kwargs)
from django.db import models from uuid import uuid4 import hashlib def get_rand_hash(): uid = uuid4() return hashlib.sha1(str(uid)).hexdigest() class User(models.Model): username = models.CharField(max_length=200, unique=True) password = models.CharField(max_length=200) token = models.CharField(max_length=200, default=get_rand_hash) secret = models.CharField(max_length=200, default=get_rand_hash) def __unicode__(self): return self.username
Set token and secret by default
Set token and secret by default
Python
bsd-2-clause
honza/oauth-service,honza/oauth-service
from django.db import models from uuid import uuid4 import hashlib - def _get_rand_hash(): + def get_rand_hash(): uid = uuid4() return hashlib.sha1(str(uid)).hexdigest() - - - def generate_token_secret(): - return _get_rand_hash(), _get_rand_hash() class User(models.Model): username = models.CharField(max_length=200, unique=True) password = models.CharField(max_length=200) - token = models.CharField(max_length=200, blank=True) + token = models.CharField(max_length=200, default=get_rand_hash) - secret = models.CharField(max_length=200, blank=True) + secret = models.CharField(max_length=200, default=get_rand_hash) def __unicode__(self): return self.username - def save(self, *args, **kwargs): - if not self.token: - self.token, self.secret = generate_token_secret() - return super(User, self).save(*args, **kwargs) -
Set token and secret by default
## Code Before: from django.db import models from uuid import uuid4 import hashlib def _get_rand_hash(): uid = uuid4() return hashlib.sha1(str(uid)).hexdigest() def generate_token_secret(): return _get_rand_hash(), _get_rand_hash() class User(models.Model): username = models.CharField(max_length=200, unique=True) password = models.CharField(max_length=200) token = models.CharField(max_length=200, blank=True) secret = models.CharField(max_length=200, blank=True) def __unicode__(self): return self.username def save(self, *args, **kwargs): if not self.token: self.token, self.secret = generate_token_secret() return super(User, self).save(*args, **kwargs) ## Instruction: Set token and secret by default ## Code After: from django.db import models from uuid import uuid4 import hashlib def get_rand_hash(): uid = uuid4() return hashlib.sha1(str(uid)).hexdigest() class User(models.Model): username = models.CharField(max_length=200, unique=True) password = models.CharField(max_length=200) token = models.CharField(max_length=200, default=get_rand_hash) secret = models.CharField(max_length=200, default=get_rand_hash) def __unicode__(self): return self.username
d96b07d529ea7ced5cbe5f5accaa84485e14395a
Lib/test/test_tk.py
Lib/test/test_tk.py
from test import support # Skip test if _tkinter wasn't built. support.import_module('_tkinter') import tkinter from tkinter.test import runtktests import unittest import tkinter try: tkinter.Button() except tkinter.TclError as msg: # assuming tk is not available raise unittest.SkipTest("tk not available: %s" % msg) def test_main(enable_gui=False): if enable_gui: if support.use_resources is None: support.use_resources = ['gui'] elif 'gui' not in support.use_resources: support.use_resources.append('gui') support.run_unittest( *runtktests.get_tests(text=False, packages=['test_tkinter'])) if __name__ == '__main__': test_main(enable_gui=True)
from test import support # Skip test if _tkinter wasn't built. support.import_module('_tkinter') import tkinter from tkinter.test import runtktests import unittest try: tkinter.Button() except tkinter.TclError as msg: # assuming tk is not available raise unittest.SkipTest("tk not available: %s" % msg) def test_main(enable_gui=False): if enable_gui: if support.use_resources is None: support.use_resources = ['gui'] elif 'gui' not in support.use_resources: support.use_resources.append('gui') support.run_unittest( *runtktests.get_tests(text=False, packages=['test_tkinter'])) if __name__ == '__main__': test_main(enable_gui=True)
Remove redundant import of tkinter.
Remove redundant import of tkinter.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
from test import support # Skip test if _tkinter wasn't built. support.import_module('_tkinter') import tkinter from tkinter.test import runtktests import unittest - - - import tkinter try: tkinter.Button() except tkinter.TclError as msg: # assuming tk is not available raise unittest.SkipTest("tk not available: %s" % msg) def test_main(enable_gui=False): if enable_gui: if support.use_resources is None: support.use_resources = ['gui'] elif 'gui' not in support.use_resources: support.use_resources.append('gui') support.run_unittest( *runtktests.get_tests(text=False, packages=['test_tkinter'])) if __name__ == '__main__': test_main(enable_gui=True)
Remove redundant import of tkinter.
## Code Before: from test import support # Skip test if _tkinter wasn't built. support.import_module('_tkinter') import tkinter from tkinter.test import runtktests import unittest import tkinter try: tkinter.Button() except tkinter.TclError as msg: # assuming tk is not available raise unittest.SkipTest("tk not available: %s" % msg) def test_main(enable_gui=False): if enable_gui: if support.use_resources is None: support.use_resources = ['gui'] elif 'gui' not in support.use_resources: support.use_resources.append('gui') support.run_unittest( *runtktests.get_tests(text=False, packages=['test_tkinter'])) if __name__ == '__main__': test_main(enable_gui=True) ## Instruction: Remove redundant import of tkinter. ## Code After: from test import support # Skip test if _tkinter wasn't built. support.import_module('_tkinter') import tkinter from tkinter.test import runtktests import unittest try: tkinter.Button() except tkinter.TclError as msg: # assuming tk is not available raise unittest.SkipTest("tk not available: %s" % msg) def test_main(enable_gui=False): if enable_gui: if support.use_resources is None: support.use_resources = ['gui'] elif 'gui' not in support.use_resources: support.use_resources.append('gui') support.run_unittest( *runtktests.get_tests(text=False, packages=['test_tkinter'])) if __name__ == '__main__': test_main(enable_gui=True)
4d4de16969439c71f0e9e15b32b26bd4b7310e8f
Simulated_import.py
Simulated_import.py
from genes import golang from genes import web_cli # etc...
from genes import docker from genes import java # etc...
Change simulated around for existing modules
Change simulated around for existing modules
Python
mit
hatchery/Genepool2,hatchery/genepool
+ from genes import docker - from genes import golang + from genes import java - from genes import web_cli # etc...
Change simulated around for existing modules
## Code Before: from genes import golang from genes import web_cli # etc... ## Instruction: Change simulated around for existing modules ## Code After: from genes import docker from genes import java # etc...
f29377a4f7208d75490e550a732a24cb6f471f18
linked_list.py
linked_list.py
class Node(object): """ """ def __init__(self, value, pointer=None): self.value = value self.pointer = pointer class LinkedList(object): """ """ def __init__(self): self.length = 0 self.header = None def push(self, value): temp_node = self.header new_node = Node(value, temp_node) self.header = new_node # self.set_init_list(*value) # def set_init_list(self, *values): # for value in values: # self.length += 1
class Node(object): """ """ def __init__(self, value, pointer=None): self.value = value self.pointer = pointer class LinkedList(object): """ """ def __init__(self): self.length = 0 self.header = None def __len__(self): return self.length def push(self, value): temp_node = self.header new_node = Node(value, temp_node) self.header = new_node self.length += 1 def size(self): return len(self) # self.set_init_list(*value) # def set_init_list(self, *values): # for value in values: # self.length += 1
Add size and len finctions.
Add size and len finctions.
Python
mit
jefferyrayrussell/data-structures
class Node(object): """ """ def __init__(self, value, pointer=None): self.value = value self.pointer = pointer class LinkedList(object): """ """ def __init__(self): self.length = 0 self.header = None + def __len__(self): + return self.length + def push(self, value): temp_node = self.header new_node = Node(value, temp_node) self.header = new_node + self.length += 1 + + def size(self): + return len(self) # self.set_init_list(*value) # def set_init_list(self, *values): # for value in values: # self.length += 1
Add size and len finctions.
## Code Before: class Node(object): """ """ def __init__(self, value, pointer=None): self.value = value self.pointer = pointer class LinkedList(object): """ """ def __init__(self): self.length = 0 self.header = None def push(self, value): temp_node = self.header new_node = Node(value, temp_node) self.header = new_node # self.set_init_list(*value) # def set_init_list(self, *values): # for value in values: # self.length += 1 ## Instruction: Add size and len finctions. ## Code After: class Node(object): """ """ def __init__(self, value, pointer=None): self.value = value self.pointer = pointer class LinkedList(object): """ """ def __init__(self): self.length = 0 self.header = None def __len__(self): return self.length def push(self, value): temp_node = self.header new_node = Node(value, temp_node) self.header = new_node self.length += 1 def size(self): return len(self) # self.set_init_list(*value) # def set_init_list(self, *values): # for value in values: # self.length += 1
06e858fc86f8f34ccae521cb269c959569f53f97
script/sample/submitpython.py
script/sample/submitpython.py
from __future__ import print_function import multyvac multyvac.config.set_key(api_key='admin', api_secret_key='12345', api_url='http://docker:8000/v1') def add(a, b): return a + b jid = multyvac.submit(add, 3, 4) result = multyvac.get(jid).get_result() print("result = {}".format(result))
from __future__ import print_function import multyvac import os # Grab from the CLOUDPIPE_URL environment variable, otherwise assume they have # /etc/hosts configured to point to their docker api_url = os.environ.get('CLOUDPIPE_URL', 'http://docker:8000/v1') multyvac.config.set_key(api_key='admin', api_secret_key='12345', api_url=api_url) def add(a, b): return a + b jid = multyvac.submit(add, 3, 4) result = multyvac.get(jid).get_result() print("added {} and {} to get {}... in the cloud!".format(3,4,result))
Allow api_url in the script to be configurable
Allow api_url in the script to be configurable
Python
bsd-3-clause
cloudpipe/cloudpipe,cloudpipe/cloudpipe,cloudpipe/cloudpipe
from __future__ import print_function import multyvac + import os + # Grab from the CLOUDPIPE_URL environment variable, otherwise assume they have + # /etc/hosts configured to point to their docker + api_url = os.environ.get('CLOUDPIPE_URL', 'http://docker:8000/v1') + - multyvac.config.set_key(api_key='admin', api_secret_key='12345', api_url='http://docker:8000/v1') + multyvac.config.set_key(api_key='admin', api_secret_key='12345', api_url=api_url) def add(a, b): return a + b jid = multyvac.submit(add, 3, 4) result = multyvac.get(jid).get_result() - print("result = {}".format(result)) + print("added {} and {} to get {}... in the cloud!".format(3,4,result))
Allow api_url in the script to be configurable
## Code Before: from __future__ import print_function import multyvac multyvac.config.set_key(api_key='admin', api_secret_key='12345', api_url='http://docker:8000/v1') def add(a, b): return a + b jid = multyvac.submit(add, 3, 4) result = multyvac.get(jid).get_result() print("result = {}".format(result)) ## Instruction: Allow api_url in the script to be configurable ## Code After: from __future__ import print_function import multyvac import os # Grab from the CLOUDPIPE_URL environment variable, otherwise assume they have # /etc/hosts configured to point to their docker api_url = os.environ.get('CLOUDPIPE_URL', 'http://docker:8000/v1') multyvac.config.set_key(api_key='admin', api_secret_key='12345', api_url=api_url) def add(a, b): return a + b jid = multyvac.submit(add, 3, 4) result = multyvac.get(jid).get_result() print("added {} and {} to get {}... in the cloud!".format(3,4,result))
7f44c6a114f95c25b533c9b69988798ba3919d68
wger/email/forms.py
wger/email/forms.py
from django.utils.translation import ( pgettext, ugettext_lazy as _ ) from django.forms import ( Form, CharField, Textarea ) class EmailListForm(Form): ''' Small form to send emails ''' subject = CharField(label=pgettext('Subject', 'As in "email subject"')) body = CharField(widget=Textarea, label=pgettext('Content', 'As in "content of an email"'))
from django.utils.translation import ( pgettext, ugettext_lazy as _ ) from django.forms import ( Form, CharField, Textarea ) class EmailListForm(Form): ''' Small form to send emails ''' subject = CharField(label=pgettext('As in "email subject"', 'Subject')) body = CharField(widget=Textarea, label=pgettext('As in "content of an email"', 'Content'))
Use correct order of arguments of pgettext
Use correct order of arguments of pgettext
Python
agpl-3.0
rolandgeider/wger,rolandgeider/wger,wger-project/wger,DeveloperMal/wger,DeveloperMal/wger,wger-project/wger,rolandgeider/wger,kjagoo/wger_stark,petervanderdoes/wger,rolandgeider/wger,petervanderdoes/wger,wger-project/wger,wger-project/wger,petervanderdoes/wger,DeveloperMal/wger,kjagoo/wger_stark,kjagoo/wger_stark,petervanderdoes/wger,kjagoo/wger_stark,DeveloperMal/wger
from django.utils.translation import ( pgettext, ugettext_lazy as _ ) from django.forms import ( Form, CharField, Textarea ) class EmailListForm(Form): ''' Small form to send emails ''' - subject = CharField(label=pgettext('Subject', 'As in "email subject"')) + subject = CharField(label=pgettext('As in "email subject"', 'Subject')) - body = CharField(widget=Textarea, label=pgettext('Content', 'As in "content of an email"')) + body = CharField(widget=Textarea, label=pgettext('As in "content of an email"', 'Content'))
Use correct order of arguments of pgettext
## Code Before: from django.utils.translation import ( pgettext, ugettext_lazy as _ ) from django.forms import ( Form, CharField, Textarea ) class EmailListForm(Form): ''' Small form to send emails ''' subject = CharField(label=pgettext('Subject', 'As in "email subject"')) body = CharField(widget=Textarea, label=pgettext('Content', 'As in "content of an email"')) ## Instruction: Use correct order of arguments of pgettext ## Code After: from django.utils.translation import ( pgettext, ugettext_lazy as _ ) from django.forms import ( Form, CharField, Textarea ) class EmailListForm(Form): ''' Small form to send emails ''' subject = CharField(label=pgettext('As in "email subject"', 'Subject')) body = CharField(widget=Textarea, label=pgettext('As in "content of an email"', 'Content'))
47bf5652c621da89a72597b8198fbfde84c2049c
healthfun/person/models.py
healthfun/person/models.py
from django.core.urlresolvers import reverse from django.db import models from django.utils.translation import ugettext_lazy as _ class Person(models.Model): first_name = models.CharField(verbose_name=_(u"First Name"), max_length=75, blank=True) last_name = models.CharField(verbose_name=_(u"Last Name"), max_length=75, blank=True) height = models.IntegerField(blank=True) email = models.EmailField()
from django.core.urlresolvers import reverse from django.db import models from django.utils.translation import ugettext_lazy as _ class Person(models.Model): first_name = models.CharField(verbose_name=_(u"First Name"), max_length=75, blank=True) last_name = models.CharField(verbose_name=_(u"Last Name"), max_length=75, blank=True) height = models.IntegerField(blank=True) email = models.EmailField() def __unicode__ (self): return self.email
Use email to 'print' a person
Use email to 'print' a person
Python
agpl-3.0
frlan/healthfun
from django.core.urlresolvers import reverse from django.db import models from django.utils.translation import ugettext_lazy as _ class Person(models.Model): first_name = models.CharField(verbose_name=_(u"First Name"), max_length=75, blank=True) last_name = models.CharField(verbose_name=_(u"Last Name"), max_length=75, blank=True) height = models.IntegerField(blank=True) email = models.EmailField() + def __unicode__ (self): + return self.email +
Use email to 'print' a person
## Code Before: from django.core.urlresolvers import reverse from django.db import models from django.utils.translation import ugettext_lazy as _ class Person(models.Model): first_name = models.CharField(verbose_name=_(u"First Name"), max_length=75, blank=True) last_name = models.CharField(verbose_name=_(u"Last Name"), max_length=75, blank=True) height = models.IntegerField(blank=True) email = models.EmailField() ## Instruction: Use email to 'print' a person ## Code After: from django.core.urlresolvers import reverse from django.db import models from django.utils.translation import ugettext_lazy as _ class Person(models.Model): first_name = models.CharField(verbose_name=_(u"First Name"), max_length=75, blank=True) last_name = models.CharField(verbose_name=_(u"Last Name"), max_length=75, blank=True) height = models.IntegerField(blank=True) email = models.EmailField() def __unicode__ (self): return self.email
c24a7287d0ac540d6ef6dcf353b06ee42aaa7a43
serrano/decorators.py
serrano/decorators.py
from functools import wraps from django.conf import settings from django.http import HttpResponse from django.contrib.auth import authenticate, login def get_token(request): return request.REQUEST.get('token', '') def check_auth(func): @wraps(func) def inner(self, request, *args, **kwargs): auth_required = getattr(settings, 'SERRANO_AUTH_REQUIRED', False) user = getattr(request, 'user', None) # Attempt to authenticate if a token is present if not user or not user.is_authenticated(): token = get_token(request) user = authenticate(token=token) if user: login(request, user) elif auth_required: return HttpResponse(status=401) return func(self, request, *args, **kwargs) return inner
from functools import wraps from django.conf import settings from django.http import HttpResponse from django.contrib.auth import authenticate, login def get_token(request): "Attempts to retrieve a token from the request." if 'token' in request.REQUEST: return request.REQUEST['token'] if 'HTTP_API_TOKEN' in request.META: return request.META['HTTP_API_TOKEN'] return '' def check_auth(func): @wraps(func) def inner(self, request, *args, **kwargs): auth_required = getattr(settings, 'SERRANO_AUTH_REQUIRED', False) user = getattr(request, 'user', None) # Attempt to authenticate if a token is present if not user or not user.is_authenticated(): token = get_token(request) user = authenticate(token=token) if user: login(request, user) elif auth_required: return HttpResponse(status=401) return func(self, request, *args, **kwargs) return inner
Add support for extracting the token from request headers
Add support for extracting the token from request headers Clients can now set the `Api-Token` header instead of supplying the token as a GET or POST parameter.
Python
bsd-2-clause
chop-dbhi/serrano,rv816/serrano_night,rv816/serrano_night,chop-dbhi/serrano
from functools import wraps from django.conf import settings from django.http import HttpResponse from django.contrib.auth import authenticate, login def get_token(request): + "Attempts to retrieve a token from the request." + if 'token' in request.REQUEST: - return request.REQUEST.get('token', '') + return request.REQUEST['token'] + if 'HTTP_API_TOKEN' in request.META: + return request.META['HTTP_API_TOKEN'] + return '' def check_auth(func): @wraps(func) def inner(self, request, *args, **kwargs): auth_required = getattr(settings, 'SERRANO_AUTH_REQUIRED', False) user = getattr(request, 'user', None) # Attempt to authenticate if a token is present if not user or not user.is_authenticated(): token = get_token(request) user = authenticate(token=token) if user: login(request, user) elif auth_required: return HttpResponse(status=401) return func(self, request, *args, **kwargs) return inner
Add support for extracting the token from request headers
## Code Before: from functools import wraps from django.conf import settings from django.http import HttpResponse from django.contrib.auth import authenticate, login def get_token(request): return request.REQUEST.get('token', '') def check_auth(func): @wraps(func) def inner(self, request, *args, **kwargs): auth_required = getattr(settings, 'SERRANO_AUTH_REQUIRED', False) user = getattr(request, 'user', None) # Attempt to authenticate if a token is present if not user or not user.is_authenticated(): token = get_token(request) user = authenticate(token=token) if user: login(request, user) elif auth_required: return HttpResponse(status=401) return func(self, request, *args, **kwargs) return inner ## Instruction: Add support for extracting the token from request headers ## Code After: from functools import wraps from django.conf import settings from django.http import HttpResponse from django.contrib.auth import authenticate, login def get_token(request): "Attempts to retrieve a token from the request." if 'token' in request.REQUEST: return request.REQUEST['token'] if 'HTTP_API_TOKEN' in request.META: return request.META['HTTP_API_TOKEN'] return '' def check_auth(func): @wraps(func) def inner(self, request, *args, **kwargs): auth_required = getattr(settings, 'SERRANO_AUTH_REQUIRED', False) user = getattr(request, 'user', None) # Attempt to authenticate if a token is present if not user or not user.is_authenticated(): token = get_token(request) user = authenticate(token=token) if user: login(request, user) elif auth_required: return HttpResponse(status=401) return func(self, request, *args, **kwargs) return inner
cd5bfa0fb09835e4e33236ec4292a16ed5556088
tests/parser.py
tests/parser.py
from spec import Spec, skip, ok_, eq_, raises from invoke.parser import Parser, Context, Argument from invoke.collection import Collection class Parser_(Spec): def has_and_requires_initial_context(self): c = Context() p = Parser(initial=c) eq_(p.initial, c) def may_also_take_additional_contexts(self): c1 = Context('foo') c2 = Context('bar') p = Parser(initial=Context(), contexts=[c1, c2]) eq_(p.contexts['foo'], c1) eq_(p.contexts['bar'], c2) @raises(ValueError) def raises_ValueError_for_unnamed_Contexts_in_contexts(self): Parser(initial=Context(), contexts=[Context()]) class parse_argv: def parses_sys_argv_style_list_of_strings(self): "parses sys.argv-style list of strings" # Doesn't-blow-up tests FTL mytask = Context(name='mytask') mytask.add_arg('--arg') p = Parser(contexts=[mytask]) p.parse_argv(['mytask', '--arg']) def returns_ordered_list_of_tasks_and_their_args(self): skip() def returns_remainder(self): "returns -- style remainder string chunk" skip()
from spec import Spec, skip, ok_, eq_, raises from invoke.parser import Parser, Context, Argument from invoke.collection import Collection class Parser_(Spec): def can_take_initial_context(self): c = Context() p = Parser(initial=c) eq_(p.initial, c) def can_take_initial_and_other_contexts(self): c1 = Context('foo') c2 = Context('bar') p = Parser(initial=Context(), contexts=[c1, c2]) eq_(p.contexts['foo'], c1) eq_(p.contexts['bar'], c2) def can_take_just_other_contexts(self): c = Context('foo') p = Parser(contexts=[c]) eq_(p.contexts['foo'], c) @raises(ValueError) def raises_ValueError_for_unnamed_Contexts_in_contexts(self): Parser(initial=Context(), contexts=[Context()]) class parse_argv: def parses_sys_argv_style_list_of_strings(self): "parses sys.argv-style list of strings" # Doesn't-blow-up tests FTL mytask = Context(name='mytask') mytask.add_arg('--arg') p = Parser(contexts=[mytask]) p.parse_argv(['mytask', '--arg']) def returns_ordered_list_of_tasks_and_their_args(self): skip() def returns_remainder(self): "returns -- style remainder string chunk" skip()
Update tests to explicitly account for previous
Update tests to explicitly account for previous
Python
bsd-2-clause
mattrobenolt/invoke,frol/invoke,sophacles/invoke,pyinvoke/invoke,tyewang/invoke,frol/invoke,mattrobenolt/invoke,pfmoore/invoke,singingwolfboy/invoke,kejbaly2/invoke,pfmoore/invoke,pyinvoke/invoke,mkusz/invoke,alex/invoke,mkusz/invoke,kejbaly2/invoke
from spec import Spec, skip, ok_, eq_, raises from invoke.parser import Parser, Context, Argument from invoke.collection import Collection class Parser_(Spec): - def has_and_requires_initial_context(self): + def can_take_initial_context(self): c = Context() p = Parser(initial=c) eq_(p.initial, c) - def may_also_take_additional_contexts(self): + def can_take_initial_and_other_contexts(self): c1 = Context('foo') c2 = Context('bar') p = Parser(initial=Context(), contexts=[c1, c2]) eq_(p.contexts['foo'], c1) eq_(p.contexts['bar'], c2) + + def can_take_just_other_contexts(self): + c = Context('foo') + p = Parser(contexts=[c]) + eq_(p.contexts['foo'], c) @raises(ValueError) def raises_ValueError_for_unnamed_Contexts_in_contexts(self): Parser(initial=Context(), contexts=[Context()]) class parse_argv: def parses_sys_argv_style_list_of_strings(self): "parses sys.argv-style list of strings" # Doesn't-blow-up tests FTL mytask = Context(name='mytask') mytask.add_arg('--arg') p = Parser(contexts=[mytask]) p.parse_argv(['mytask', '--arg']) def returns_ordered_list_of_tasks_and_their_args(self): skip() def returns_remainder(self): "returns -- style remainder string chunk" skip()
Update tests to explicitly account for previous
## Code Before: from spec import Spec, skip, ok_, eq_, raises from invoke.parser import Parser, Context, Argument from invoke.collection import Collection class Parser_(Spec): def has_and_requires_initial_context(self): c = Context() p = Parser(initial=c) eq_(p.initial, c) def may_also_take_additional_contexts(self): c1 = Context('foo') c2 = Context('bar') p = Parser(initial=Context(), contexts=[c1, c2]) eq_(p.contexts['foo'], c1) eq_(p.contexts['bar'], c2) @raises(ValueError) def raises_ValueError_for_unnamed_Contexts_in_contexts(self): Parser(initial=Context(), contexts=[Context()]) class parse_argv: def parses_sys_argv_style_list_of_strings(self): "parses sys.argv-style list of strings" # Doesn't-blow-up tests FTL mytask = Context(name='mytask') mytask.add_arg('--arg') p = Parser(contexts=[mytask]) p.parse_argv(['mytask', '--arg']) def returns_ordered_list_of_tasks_and_their_args(self): skip() def returns_remainder(self): "returns -- style remainder string chunk" skip() ## Instruction: Update tests to explicitly account for previous ## Code After: from spec import Spec, skip, ok_, eq_, raises from invoke.parser import Parser, Context, Argument from invoke.collection import Collection class Parser_(Spec): def can_take_initial_context(self): c = Context() p = Parser(initial=c) eq_(p.initial, c) def can_take_initial_and_other_contexts(self): c1 = Context('foo') c2 = Context('bar') p = Parser(initial=Context(), contexts=[c1, c2]) eq_(p.contexts['foo'], c1) eq_(p.contexts['bar'], c2) def can_take_just_other_contexts(self): c = Context('foo') p = Parser(contexts=[c]) eq_(p.contexts['foo'], c) @raises(ValueError) def raises_ValueError_for_unnamed_Contexts_in_contexts(self): Parser(initial=Context(), contexts=[Context()]) class parse_argv: def parses_sys_argv_style_list_of_strings(self): "parses sys.argv-style list of strings" # Doesn't-blow-up tests FTL mytask = Context(name='mytask') mytask.add_arg('--arg') p = Parser(contexts=[mytask]) p.parse_argv(['mytask', '--arg']) def returns_ordered_list_of_tasks_and_their_args(self): skip() def returns_remainder(self): "returns -- style remainder string chunk" skip()
d01b09256f8fda4b222f3e26366817f4ac5b4c5a
zinnia/tests/test_admin_forms.py
zinnia/tests/test_admin_forms.py
"""Test cases for Zinnia's admin forms""" from django.test import TestCase from django.contrib.admin.widgets import RelatedFieldWidgetWrapper from zinnia.models import Category from zinnia.admin.forms import EntryAdminForm from zinnia.admin.forms import CategoryAdminForm class EntryAdminFormTestCase(TestCase): def test_categories_has_related_widget(self): form = EntryAdminForm() self.assertTrue( isinstance(form.fields['categories'].widget, RelatedFieldWidgetWrapper)) def test_initial_sites(self): form = EntryAdminForm() self.assertEqual( len(form.fields['sites'].initial), 1) class CategoryAdminFormTestCase(TestCase): def test_parent_has_related_widget(self): form = CategoryAdminForm() self.assertTrue( isinstance(form.fields['parent'].widget, RelatedFieldWidgetWrapper)) def test_clean_parent(self): category = Category.objects.create( title='Category 1', slug='cat-1') datas = {'parent': category.pk, 'title': category.title, 'slug': category.slug} form = CategoryAdminForm(datas, instance=category) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors['parent']), 1) subcategory = Category.objects.create( title='Category 2', slug='cat-2') self.assertEqual(subcategory.parent, None) datas = {'parent': category.pk, 'title': subcategory.title, 'slug': subcategory.slug} form = CategoryAdminForm(datas, instance=subcategory) self.assertTrue(form.is_valid())
"""Test cases for Zinnia's admin forms""" from django.test import TestCase from django.contrib.admin.widgets import RelatedFieldWidgetWrapper from zinnia.models import Category from zinnia.admin.forms import EntryAdminForm from zinnia.admin.forms import CategoryAdminForm class EntryAdminFormTestCase(TestCase): def test_categories_has_related_widget(self): form = EntryAdminForm() self.assertTrue( isinstance(form.fields['categories'].widget, RelatedFieldWidgetWrapper)) class CategoryAdminFormTestCase(TestCase): def test_parent_has_related_widget(self): form = CategoryAdminForm() self.assertTrue( isinstance(form.fields['parent'].widget, RelatedFieldWidgetWrapper)) def test_clean_parent(self): category = Category.objects.create( title='Category 1', slug='cat-1') datas = {'parent': category.pk, 'title': category.title, 'slug': category.slug} form = CategoryAdminForm(datas, instance=category) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors['parent']), 1) subcategory = Category.objects.create( title='Category 2', slug='cat-2') self.assertEqual(subcategory.parent, None) datas = {'parent': category.pk, 'title': subcategory.title, 'slug': subcategory.slug} form = CategoryAdminForm(datas, instance=subcategory) self.assertTrue(form.is_valid())
Remove now useless test for initial sites value in form
Remove now useless test for initial sites value in form
Python
bsd-3-clause
extertioner/django-blog-zinnia,Maplecroft/django-blog-zinnia,Zopieux/django-blog-zinnia,ghachey/django-blog-zinnia,dapeng0802/django-blog-zinnia,bywbilly/django-blog-zinnia,dapeng0802/django-blog-zinnia,Zopieux/django-blog-zinnia,aorzh/django-blog-zinnia,Zopieux/django-blog-zinnia,bywbilly/django-blog-zinnia,aorzh/django-blog-zinnia,aorzh/django-blog-zinnia,extertioner/django-blog-zinnia,ZuluPro/django-blog-zinnia,petecummings/django-blog-zinnia,Fantomas42/django-blog-zinnia,marctc/django-blog-zinnia,petecummings/django-blog-zinnia,ZuluPro/django-blog-zinnia,ZuluPro/django-blog-zinnia,Fantomas42/django-blog-zinnia,ghachey/django-blog-zinnia,Maplecroft/django-blog-zinnia,petecummings/django-blog-zinnia,marctc/django-blog-zinnia,bywbilly/django-blog-zinnia,extertioner/django-blog-zinnia,Maplecroft/django-blog-zinnia,Fantomas42/django-blog-zinnia,ghachey/django-blog-zinnia,dapeng0802/django-blog-zinnia,marctc/django-blog-zinnia
"""Test cases for Zinnia's admin forms""" from django.test import TestCase from django.contrib.admin.widgets import RelatedFieldWidgetWrapper from zinnia.models import Category from zinnia.admin.forms import EntryAdminForm from zinnia.admin.forms import CategoryAdminForm class EntryAdminFormTestCase(TestCase): def test_categories_has_related_widget(self): form = EntryAdminForm() self.assertTrue( isinstance(form.fields['categories'].widget, RelatedFieldWidgetWrapper)) - - def test_initial_sites(self): - form = EntryAdminForm() - self.assertEqual( - len(form.fields['sites'].initial), 1) class CategoryAdminFormTestCase(TestCase): def test_parent_has_related_widget(self): form = CategoryAdminForm() self.assertTrue( isinstance(form.fields['parent'].widget, RelatedFieldWidgetWrapper)) def test_clean_parent(self): category = Category.objects.create( title='Category 1', slug='cat-1') datas = {'parent': category.pk, 'title': category.title, 'slug': category.slug} form = CategoryAdminForm(datas, instance=category) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors['parent']), 1) subcategory = Category.objects.create( title='Category 2', slug='cat-2') self.assertEqual(subcategory.parent, None) datas = {'parent': category.pk, 'title': subcategory.title, 'slug': subcategory.slug} form = CategoryAdminForm(datas, instance=subcategory) self.assertTrue(form.is_valid())
Remove now useless test for initial sites value in form
## Code Before: """Test cases for Zinnia's admin forms""" from django.test import TestCase from django.contrib.admin.widgets import RelatedFieldWidgetWrapper from zinnia.models import Category from zinnia.admin.forms import EntryAdminForm from zinnia.admin.forms import CategoryAdminForm class EntryAdminFormTestCase(TestCase): def test_categories_has_related_widget(self): form = EntryAdminForm() self.assertTrue( isinstance(form.fields['categories'].widget, RelatedFieldWidgetWrapper)) def test_initial_sites(self): form = EntryAdminForm() self.assertEqual( len(form.fields['sites'].initial), 1) class CategoryAdminFormTestCase(TestCase): def test_parent_has_related_widget(self): form = CategoryAdminForm() self.assertTrue( isinstance(form.fields['parent'].widget, RelatedFieldWidgetWrapper)) def test_clean_parent(self): category = Category.objects.create( title='Category 1', slug='cat-1') datas = {'parent': category.pk, 'title': category.title, 'slug': category.slug} form = CategoryAdminForm(datas, instance=category) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors['parent']), 1) subcategory = Category.objects.create( title='Category 2', slug='cat-2') self.assertEqual(subcategory.parent, None) datas = {'parent': category.pk, 'title': subcategory.title, 'slug': subcategory.slug} form = CategoryAdminForm(datas, instance=subcategory) self.assertTrue(form.is_valid()) ## Instruction: Remove now useless test for initial sites value in form ## Code After: """Test cases for Zinnia's admin forms""" from django.test import TestCase from django.contrib.admin.widgets import RelatedFieldWidgetWrapper from zinnia.models import Category from zinnia.admin.forms import EntryAdminForm from zinnia.admin.forms import CategoryAdminForm class EntryAdminFormTestCase(TestCase): def test_categories_has_related_widget(self): form = EntryAdminForm() self.assertTrue( isinstance(form.fields['categories'].widget, RelatedFieldWidgetWrapper)) class CategoryAdminFormTestCase(TestCase): def test_parent_has_related_widget(self): form = CategoryAdminForm() self.assertTrue( isinstance(form.fields['parent'].widget, RelatedFieldWidgetWrapper)) def test_clean_parent(self): category = Category.objects.create( title='Category 1', slug='cat-1') datas = {'parent': category.pk, 'title': category.title, 'slug': category.slug} form = CategoryAdminForm(datas, instance=category) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors['parent']), 1) subcategory = Category.objects.create( title='Category 2', slug='cat-2') self.assertEqual(subcategory.parent, None) datas = {'parent': category.pk, 'title': subcategory.title, 'slug': subcategory.slug} form = CategoryAdminForm(datas, instance=subcategory) self.assertTrue(form.is_valid())
f096225138afff2a722b1b019eb94e14f8d18fc3
sutro/dispatcher.py
sutro/dispatcher.py
import random import gevent.queue class MessageDispatcher(object): def __init__(self, stats): self.consumers = {} self.stats = stats def get_connection_count(self): return sum(len(sockets) for sockets in self.consumers.itervalues()) def on_message_received(self, namespace, message): consumers = self.consumers.get(namespace, []) with self.stats.timer("sutro.dispatch"): for consumer in consumers: consumer.put(message) def listen(self, namespace, max_timeout): queue = gevent.queue.Queue() self.consumers.setdefault(namespace, []).append(queue) try: while True: # jitter the timeout a bit to ensure we don't herd timeout = max_timeout - random.uniform(0, max_timeout / 2) try: yield queue.get(block=True, timeout=timeout) except gevent.queue.Empty: yield None # ensure we're not starving others by spinning gevent.sleep() finally: self.consumers[namespace].remove(queue) if not self.consumers[namespace]: del self.consumers[namespace]
import posixpath import random import gevent.queue def _walk_namespace_hierarchy(namespace): assert namespace.startswith("/") yield namespace while namespace != "/": namespace = posixpath.dirname(namespace) yield namespace class MessageDispatcher(object): def __init__(self, stats): self.consumers = {} self.stats = stats def get_connection_count(self): return sum(len(sockets) for sockets in self.consumers.itervalues()) def on_message_received(self, namespace, message): consumers = self.consumers.get(namespace, []) with self.stats.timer("sutro.dispatch"): for consumer in consumers: consumer.put(message) def listen(self, namespace, max_timeout): queue = gevent.queue.Queue() namespace = namespace.rstrip("/") for ns in _walk_namespace_hierarchy(namespace): self.consumers.setdefault(ns, []).append(queue) try: while True: # jitter the timeout a bit to ensure we don't herd timeout = max_timeout - random.uniform(0, max_timeout / 2) try: yield queue.get(block=True, timeout=timeout) except gevent.queue.Empty: yield None # ensure we're not starving others by spinning gevent.sleep() finally: for ns in _walk_namespace_hierarchy(namespace): self.consumers[ns].remove(queue) if not self.consumers[ns]: del self.consumers[ns]
Make sockets listen to parent namespaces as well.
Make sockets listen to parent namespaces as well. For example, /live/test will now receive messages destined for /live/test, /live and /. This allows us to send messages to multiple endpoints at once such as refreshing all liveupdate threads or the like.
Python
bsd-3-clause
spladug/sutro,spladug/sutro
+ import posixpath import random import gevent.queue + + + def _walk_namespace_hierarchy(namespace): + assert namespace.startswith("/") + + yield namespace + while namespace != "/": + namespace = posixpath.dirname(namespace) + yield namespace class MessageDispatcher(object): def __init__(self, stats): self.consumers = {} self.stats = stats def get_connection_count(self): return sum(len(sockets) for sockets in self.consumers.itervalues()) def on_message_received(self, namespace, message): consumers = self.consumers.get(namespace, []) with self.stats.timer("sutro.dispatch"): for consumer in consumers: consumer.put(message) def listen(self, namespace, max_timeout): queue = gevent.queue.Queue() + + namespace = namespace.rstrip("/") + for ns in _walk_namespace_hierarchy(namespace): - self.consumers.setdefault(namespace, []).append(queue) + self.consumers.setdefault(ns, []).append(queue) try: while True: # jitter the timeout a bit to ensure we don't herd timeout = max_timeout - random.uniform(0, max_timeout / 2) try: yield queue.get(block=True, timeout=timeout) except gevent.queue.Empty: yield None # ensure we're not starving others by spinning gevent.sleep() finally: + for ns in _walk_namespace_hierarchy(namespace): - self.consumers[namespace].remove(queue) + self.consumers[ns].remove(queue) - if not self.consumers[namespace]: + if not self.consumers[ns]: - del self.consumers[namespace] + del self.consumers[ns]
Make sockets listen to parent namespaces as well.
## Code Before: import random import gevent.queue class MessageDispatcher(object): def __init__(self, stats): self.consumers = {} self.stats = stats def get_connection_count(self): return sum(len(sockets) for sockets in self.consumers.itervalues()) def on_message_received(self, namespace, message): consumers = self.consumers.get(namespace, []) with self.stats.timer("sutro.dispatch"): for consumer in consumers: consumer.put(message) def listen(self, namespace, max_timeout): queue = gevent.queue.Queue() self.consumers.setdefault(namespace, []).append(queue) try: while True: # jitter the timeout a bit to ensure we don't herd timeout = max_timeout - random.uniform(0, max_timeout / 2) try: yield queue.get(block=True, timeout=timeout) except gevent.queue.Empty: yield None # ensure we're not starving others by spinning gevent.sleep() finally: self.consumers[namespace].remove(queue) if not self.consumers[namespace]: del self.consumers[namespace] ## Instruction: Make sockets listen to parent namespaces as well. ## Code After: import posixpath import random import gevent.queue def _walk_namespace_hierarchy(namespace): assert namespace.startswith("/") yield namespace while namespace != "/": namespace = posixpath.dirname(namespace) yield namespace class MessageDispatcher(object): def __init__(self, stats): self.consumers = {} self.stats = stats def get_connection_count(self): return sum(len(sockets) for sockets in self.consumers.itervalues()) def on_message_received(self, namespace, message): consumers = self.consumers.get(namespace, []) with self.stats.timer("sutro.dispatch"): for consumer in consumers: consumer.put(message) def listen(self, namespace, max_timeout): queue = gevent.queue.Queue() namespace = namespace.rstrip("/") for ns in _walk_namespace_hierarchy(namespace): self.consumers.setdefault(ns, []).append(queue) try: while True: # jitter the timeout a bit to ensure we don't herd timeout = max_timeout - random.uniform(0, max_timeout / 2) try: yield queue.get(block=True, timeout=timeout) except gevent.queue.Empty: yield None # ensure we're not starving others by spinning gevent.sleep() finally: for ns in _walk_namespace_hierarchy(namespace): self.consumers[ns].remove(queue) if not self.consumers[ns]: del self.consumers[ns]
2ee1e8046323e2632c8cd8c8d88e3c313caabe1e
kobo/hub/forms.py
kobo/hub/forms.py
import django.forms as forms from django.db.models import Q class TaskSearchForm(forms.Form): search = forms.CharField(required=False) my = forms.BooleanField(required=False) def get_query(self, request): self.is_valid() search = self.cleaned_data["search"] my = self.cleaned_data["my"] query = Q() if search: query |= Q(method__icontains=search) query |= Q(owner__username__icontains=search) if my and request.user.is_authenticated(): query &= Q(owner=request.user) return query
import django.forms as forms from django.db.models import Q class TaskSearchForm(forms.Form): search = forms.CharField(required=False) my = forms.BooleanField(required=False) def get_query(self, request): self.is_valid() search = self.cleaned_data["search"] my = self.cleaned_data["my"] query = Q() if search: query |= Q(method__icontains=search) query |= Q(owner__username__icontains=search) query |= Q(label__icontains=search) if my and request.user.is_authenticated(): query &= Q(owner=request.user) return query
Enable searching in task list by label.
Enable searching in task list by label.
Python
lgpl-2.1
pombredanne/https-git.fedorahosted.org-git-kobo,release-engineering/kobo,release-engineering/kobo,release-engineering/kobo,pombredanne/https-git.fedorahosted.org-git-kobo,release-engineering/kobo,pombredanne/https-git.fedorahosted.org-git-kobo,pombredanne/https-git.fedorahosted.org-git-kobo
import django.forms as forms from django.db.models import Q class TaskSearchForm(forms.Form): search = forms.CharField(required=False) my = forms.BooleanField(required=False) def get_query(self, request): self.is_valid() search = self.cleaned_data["search"] my = self.cleaned_data["my"] query = Q() if search: query |= Q(method__icontains=search) query |= Q(owner__username__icontains=search) + query |= Q(label__icontains=search) if my and request.user.is_authenticated(): query &= Q(owner=request.user) return query
Enable searching in task list by label.
## Code Before: import django.forms as forms from django.db.models import Q class TaskSearchForm(forms.Form): search = forms.CharField(required=False) my = forms.BooleanField(required=False) def get_query(self, request): self.is_valid() search = self.cleaned_data["search"] my = self.cleaned_data["my"] query = Q() if search: query |= Q(method__icontains=search) query |= Q(owner__username__icontains=search) if my and request.user.is_authenticated(): query &= Q(owner=request.user) return query ## Instruction: Enable searching in task list by label. ## Code After: import django.forms as forms from django.db.models import Q class TaskSearchForm(forms.Form): search = forms.CharField(required=False) my = forms.BooleanField(required=False) def get_query(self, request): self.is_valid() search = self.cleaned_data["search"] my = self.cleaned_data["my"] query = Q() if search: query |= Q(method__icontains=search) query |= Q(owner__username__icontains=search) query |= Q(label__icontains=search) if my and request.user.is_authenticated(): query &= Q(owner=request.user) return query
56aa7fa21b218e047e9f3d7c2239aa6a22d9a5b1
kombu/__init__.py
kombu/__init__.py
"""AMQP Messaging Framework for Python""" VERSION = (1, 0, 0, "rc4") __version__ = ".".join(map(str, VERSION[0:3])) + "".join(VERSION[3:]) __author__ = "Ask Solem" __contact__ = "ask@celeryproject.org" __homepage__ = "http://github.com/ask/kombu/" __docformat__ = "restructuredtext" import os if not os.environ.get("KOMBU_NO_EVAL", False): from kombu.connection import BrokerConnection from kombu.entity import Exchange, Queue from kombu.messaging import Consumer, Producer
"""AMQP Messaging Framework for Python""" VERSION = (1, 0, 0, "rc4") __version__ = ".".join(map(str, VERSION[0:3])) + "".join(VERSION[3:]) __author__ = "Ask Solem" __contact__ = "ask@celeryproject.org" __homepage__ = "http://github.com/ask/kombu/" __docformat__ = "restructuredtext en" import os import sys if not os.environ.get("KOMBU_NO_EVAL", False): # Lazy loading. # - See werkzeug/__init__.py for the rationale behind this. from types import ModuleType all_by_module = { "kombu.connection": ["BrokerConnection"], "kombu.entity": ["Exchange", "Queue"], "kombu.messaging": ["Consumer", "Producer"], } object_origins = {} for module, items in all_by_module.iteritems(): for item in items: object_origins[item] = module class module(ModuleType): def __getattr__(self, name): if name in object_origins: module = __import__(object_origins[name], None, None, [name]) for extra_name in all_by_module[module.__name__]: setattr(self, extra_name, getattr(module, extra_name)) return getattr(module, name) return ModuleType.__getattribute__(self, name) def __dir__(self): result = list(new_module.__all__) result.extend(("__file__", "__path__", "__doc__", "__all__", "__docformat__", "__name__", "__path__", "VERSION", "__package__", "__version__", "__author__", "__contact__", "__homepage__", "__docformat__")) return result # keep a reference to this module so that it's not garbage collected old_module = sys.modules[__name__] new_module = sys.modules[__name__] = module(__name__) new_module.__dict__.update({ "__file__": __file__, "__path__": __path__, "__doc__": __doc__, "__all__": tuple(object_origins), "__version__": __version__, "__author__": __author__, "__contact__": __contact__, "__homepage__": __homepage__, "__docformat__": __docformat__, "VERSION": VERSION})
Load kombu root module lazily
Load kombu root module lazily
Python
bsd-3-clause
urbn/kombu,depop/kombu,bmbouter/kombu,WoLpH/kombu,ZoranPavlovic/kombu,depop/kombu,mathom/kombu,xujun10110/kombu,romank0/kombu,xujun10110/kombu,alex/kombu,numb3r3/kombu,alex/kombu,andresriancho/kombu,daevaorn/kombu,daevaorn/kombu,iris-edu-int/kombu,ZoranPavlovic/kombu,WoLpH/kombu,cce/kombu,mverrilli/kombu,disqus/kombu,cce/kombu,Elastica/kombu,numb3r3/kombu,Elastica/kombu,pantheon-systems/kombu,tkanemoto/kombu,romank0/kombu,bmbouter/kombu,iris-edu-int/kombu,disqus/kombu,andresriancho/kombu,jindongh/kombu,celery/kombu,tkanemoto/kombu,mathom/kombu,pantheon-systems/kombu,mverrilli/kombu,jindongh/kombu
"""AMQP Messaging Framework for Python""" VERSION = (1, 0, 0, "rc4") __version__ = ".".join(map(str, VERSION[0:3])) + "".join(VERSION[3:]) __author__ = "Ask Solem" __contact__ = "ask@celeryproject.org" __homepage__ = "http://github.com/ask/kombu/" - __docformat__ = "restructuredtext" + __docformat__ = "restructuredtext en" import os + import sys if not os.environ.get("KOMBU_NO_EVAL", False): - from kombu.connection import BrokerConnection - from kombu.entity import Exchange, Queue - from kombu.messaging import Consumer, Producer + # Lazy loading. + # - See werkzeug/__init__.py for the rationale behind this. + from types import ModuleType + all_by_module = { + "kombu.connection": ["BrokerConnection"], + "kombu.entity": ["Exchange", "Queue"], + "kombu.messaging": ["Consumer", "Producer"], + } + + object_origins = {} + for module, items in all_by_module.iteritems(): + for item in items: + object_origins[item] = module + + class module(ModuleType): + + def __getattr__(self, name): + if name in object_origins: + module = __import__(object_origins[name], None, None, [name]) + for extra_name in all_by_module[module.__name__]: + setattr(self, extra_name, getattr(module, extra_name)) + return getattr(module, name) + return ModuleType.__getattribute__(self, name) + + def __dir__(self): + result = list(new_module.__all__) + result.extend(("__file__", "__path__", "__doc__", "__all__", + "__docformat__", "__name__", "__path__", "VERSION", + "__package__", "__version__", "__author__", + "__contact__", "__homepage__", "__docformat__")) + return result + + # keep a reference to this module so that it's not garbage collected + old_module = sys.modules[__name__] + + new_module = sys.modules[__name__] = module(__name__) + new_module.__dict__.update({ + "__file__": __file__, + "__path__": __path__, + "__doc__": __doc__, + "__all__": tuple(object_origins), + "__version__": __version__, + "__author__": __author__, + "__contact__": __contact__, + "__homepage__": __homepage__, + "__docformat__": __docformat__, + "VERSION": VERSION}) +
Load kombu root module lazily
## Code Before: """AMQP Messaging Framework for Python""" VERSION = (1, 0, 0, "rc4") __version__ = ".".join(map(str, VERSION[0:3])) + "".join(VERSION[3:]) __author__ = "Ask Solem" __contact__ = "ask@celeryproject.org" __homepage__ = "http://github.com/ask/kombu/" __docformat__ = "restructuredtext" import os if not os.environ.get("KOMBU_NO_EVAL", False): from kombu.connection import BrokerConnection from kombu.entity import Exchange, Queue from kombu.messaging import Consumer, Producer ## Instruction: Load kombu root module lazily ## Code After: """AMQP Messaging Framework for Python""" VERSION = (1, 0, 0, "rc4") __version__ = ".".join(map(str, VERSION[0:3])) + "".join(VERSION[3:]) __author__ = "Ask Solem" __contact__ = "ask@celeryproject.org" __homepage__ = "http://github.com/ask/kombu/" __docformat__ = "restructuredtext en" import os import sys if not os.environ.get("KOMBU_NO_EVAL", False): # Lazy loading. # - See werkzeug/__init__.py for the rationale behind this. from types import ModuleType all_by_module = { "kombu.connection": ["BrokerConnection"], "kombu.entity": ["Exchange", "Queue"], "kombu.messaging": ["Consumer", "Producer"], } object_origins = {} for module, items in all_by_module.iteritems(): for item in items: object_origins[item] = module class module(ModuleType): def __getattr__(self, name): if name in object_origins: module = __import__(object_origins[name], None, None, [name]) for extra_name in all_by_module[module.__name__]: setattr(self, extra_name, getattr(module, extra_name)) return getattr(module, name) return ModuleType.__getattribute__(self, name) def __dir__(self): result = list(new_module.__all__) result.extend(("__file__", "__path__", "__doc__", "__all__", "__docformat__", "__name__", "__path__", "VERSION", "__package__", "__version__", "__author__", "__contact__", "__homepage__", "__docformat__")) return result # keep a reference to this module so that it's not garbage collected old_module = sys.modules[__name__] new_module = sys.modules[__name__] = module(__name__) new_module.__dict__.update({ "__file__": __file__, "__path__": __path__, "__doc__": __doc__, "__all__": tuple(object_origins), "__version__": __version__, "__author__": __author__, "__contact__": __contact__, "__homepage__": __homepage__, "__docformat__": __docformat__, "VERSION": VERSION})
f22a217e86602b138451801afd3cd3c1c6314655
bin/post_reports.py
bin/post_reports.py
import os import django from fitbit.slack import post_message IDS_TO_POST = os.environ['AUTOPOST'].split(',') if __name__ == '__main__': os.environ.setdefault("DJANGO_SETTINGS_MODULE", "fitbitslackbot.settings") django.setup() # Cannot import these until django is setup from fitbit.models import Token from fitbit.views import get_message for token in Token.objects.filter(fitbit_id__in=IDS_TO_POST): try: post_message(get_message(token.fitbit_id)) except Exception: print("Could not send message for {}".format(token.fitbit_id))
import os import django from fitbit.slack import post_message if __name__ == '__main__': os.environ.setdefault("DJANGO_SETTINGS_MODULE", "fitbitslackbot.settings") django.setup() # Cannot import these until django is setup from fitbit.models import Token from fitbit.views import get_message for token in Token.objects.all(): try: post_message(get_message(token.fitbit_id)) except Exception: print("Could not send message for {}".format(token.fitbit_id))
Send all user data to the slack
Send all user data to the slack
Python
apache-2.0
Bachmann1234/fitbitSlackBot,Bachmann1234/fitbitSlackBot
import os import django from fitbit.slack import post_message - IDS_TO_POST = os.environ['AUTOPOST'].split(',') if __name__ == '__main__': os.environ.setdefault("DJANGO_SETTINGS_MODULE", "fitbitslackbot.settings") django.setup() # Cannot import these until django is setup from fitbit.models import Token from fitbit.views import get_message - for token in Token.objects.filter(fitbit_id__in=IDS_TO_POST): + for token in Token.objects.all(): try: post_message(get_message(token.fitbit_id)) except Exception: print("Could not send message for {}".format(token.fitbit_id))
Send all user data to the slack
## Code Before: import os import django from fitbit.slack import post_message IDS_TO_POST = os.environ['AUTOPOST'].split(',') if __name__ == '__main__': os.environ.setdefault("DJANGO_SETTINGS_MODULE", "fitbitslackbot.settings") django.setup() # Cannot import these until django is setup from fitbit.models import Token from fitbit.views import get_message for token in Token.objects.filter(fitbit_id__in=IDS_TO_POST): try: post_message(get_message(token.fitbit_id)) except Exception: print("Could not send message for {}".format(token.fitbit_id)) ## Instruction: Send all user data to the slack ## Code After: import os import django from fitbit.slack import post_message if __name__ == '__main__': os.environ.setdefault("DJANGO_SETTINGS_MODULE", "fitbitslackbot.settings") django.setup() # Cannot import these until django is setup from fitbit.models import Token from fitbit.views import get_message for token in Token.objects.all(): try: post_message(get_message(token.fitbit_id)) except Exception: print("Could not send message for {}".format(token.fitbit_id))
83bb9f15ae8ceed3352232b26176b74607a08efb
tests/test_tools.py
tests/test_tools.py
"""Test the functions in the tools file.""" import bibpy.tools def test_version_format(): assert bibpy.tools.version_format().format('0.1.0') == '%(prog)s v0.1.0' program_name = dict(prog='tool_name') assert (bibpy.tools.version_format() % program_name).format('2.3') ==\ 'tool_name v2.3' def test_key_grammar(): pass def test_entry_grammar(): pass def test_field_grammar(): pass def test_numeric_grammar(): pass def test_parse_query(): assert bibpy.tools.parse_query('~Author') == ('entry', ['~', 'Author']) assert bibpy.tools.parse_query('!Author') == ('entry', ['!', 'Author']) def test_predicate_composition(): pass
"""Test the functions in the tools file.""" import bibpy.tools def test_version_format(): assert bibpy.tools.version_format().format('0.1.0') == '%(prog)s v0.1.0' program_name = dict(prog='tool_name') assert (bibpy.tools.version_format() % program_name).format('2.3') ==\ 'tool_name v2.3' def test_key_grammar(): pass def test_entry_grammar(): pass def test_field_grammar(): pass def test_numeric_grammar(): pass def test_parse_query(): assert bibpy.tools.parse_query('~Author') == ('entry', ['~', 'Author']) assert bibpy.tools.parse_query('!Author') == ('entry', ['!', 'Author']) def always_true(value): """A function that always returns True.""" return True def always_false(value): """A function that always returns False.""" return False def test_predicate_composition(): pred1 = bibpy.tools.compose_predicates([always_false, always_true, always_false], any) pred2 = bibpy.tools.compose_predicates([always_false, always_false, always_false], any) pred3 = bibpy.tools.compose_predicates([always_false, always_true], all) pred4 = bibpy.tools.compose_predicates([always_true, always_true], all) assert pred1(1) assert not pred2(1) assert not pred3(1) assert pred4(1)
Add test for predicate composition
Add test for predicate composition
Python
mit
MisanthropicBit/bibpy,MisanthropicBit/bibpy
"""Test the functions in the tools file.""" import bibpy.tools def test_version_format(): assert bibpy.tools.version_format().format('0.1.0') == '%(prog)s v0.1.0' program_name = dict(prog='tool_name') assert (bibpy.tools.version_format() % program_name).format('2.3') ==\ 'tool_name v2.3' def test_key_grammar(): pass def test_entry_grammar(): pass def test_field_grammar(): pass def test_numeric_grammar(): pass def test_parse_query(): assert bibpy.tools.parse_query('~Author') == ('entry', ['~', 'Author']) assert bibpy.tools.parse_query('!Author') == ('entry', ['!', 'Author']) + def always_true(value): + """A function that always returns True.""" + return True + + + def always_false(value): + """A function that always returns False.""" + return False + + def test_predicate_composition(): - pass + pred1 = bibpy.tools.compose_predicates([always_false, always_true, + always_false], any) + pred2 = bibpy.tools.compose_predicates([always_false, always_false, + always_false], any) + pred3 = bibpy.tools.compose_predicates([always_false, always_true], all) + pred4 = bibpy.tools.compose_predicates([always_true, always_true], all) + assert pred1(1) + assert not pred2(1) + assert not pred3(1) + assert pred4(1) +
Add test for predicate composition
## Code Before: """Test the functions in the tools file.""" import bibpy.tools def test_version_format(): assert bibpy.tools.version_format().format('0.1.0') == '%(prog)s v0.1.0' program_name = dict(prog='tool_name') assert (bibpy.tools.version_format() % program_name).format('2.3') ==\ 'tool_name v2.3' def test_key_grammar(): pass def test_entry_grammar(): pass def test_field_grammar(): pass def test_numeric_grammar(): pass def test_parse_query(): assert bibpy.tools.parse_query('~Author') == ('entry', ['~', 'Author']) assert bibpy.tools.parse_query('!Author') == ('entry', ['!', 'Author']) def test_predicate_composition(): pass ## Instruction: Add test for predicate composition ## Code After: """Test the functions in the tools file.""" import bibpy.tools def test_version_format(): assert bibpy.tools.version_format().format('0.1.0') == '%(prog)s v0.1.0' program_name = dict(prog='tool_name') assert (bibpy.tools.version_format() % program_name).format('2.3') ==\ 'tool_name v2.3' def test_key_grammar(): pass def test_entry_grammar(): pass def test_field_grammar(): pass def test_numeric_grammar(): pass def test_parse_query(): assert bibpy.tools.parse_query('~Author') == ('entry', ['~', 'Author']) assert bibpy.tools.parse_query('!Author') == ('entry', ['!', 'Author']) def always_true(value): """A function that always returns True.""" return True def always_false(value): """A function that always returns False.""" return False def test_predicate_composition(): pred1 = bibpy.tools.compose_predicates([always_false, always_true, always_false], any) pred2 = bibpy.tools.compose_predicates([always_false, always_false, always_false], any) pred3 = bibpy.tools.compose_predicates([always_false, always_true], all) pred4 = bibpy.tools.compose_predicates([always_true, always_true], all) assert pred1(1) assert not pred2(1) assert not pred3(1) assert pred4(1)
7b3276708417284242b4e0c9a13c6194dcc83aa7
quickstartup/contacts/views.py
quickstartup/contacts/views.py
from django.core.urlresolvers import reverse from django.views.generic import CreateView from django.utils.translation import ugettext_lazy as _ from django.contrib import messages from .forms import ContactForm class ContactView(CreateView): template_name = 'contacts/contact.html' form_class = ContactForm def get_success_url(self): return reverse("qs_contacts:contact") def form_valid(self, form): messages.success(self.request, _("Your message was sent successfully!")) return super(ContactView, self).form_valid(form)
from django.core.urlresolvers import reverse from django.views.generic import CreateView from django.utils.translation import ugettext_lazy as _ from django.contrib import messages from .forms import ContactForm class ContactView(CreateView): template_name = 'contacts/contact.html' form_class = ContactForm def get_success_url(self): return reverse("qs_contacts:contact") def form_valid(self, form): valid = super(ContactView, self).form_valid(form) messages.success(self.request, _("Your message was sent successfully!")) return valid
Set flash message *after* message sending
Set flash message *after* message sending
Python
mit
georgeyk/quickstartup,georgeyk/quickstartup,osantana/quickstartup,osantana/quickstartup,osantana/quickstartup,georgeyk/quickstartup
from django.core.urlresolvers import reverse from django.views.generic import CreateView from django.utils.translation import ugettext_lazy as _ from django.contrib import messages from .forms import ContactForm class ContactView(CreateView): template_name = 'contacts/contact.html' form_class = ContactForm def get_success_url(self): return reverse("qs_contacts:contact") def form_valid(self, form): + valid = super(ContactView, self).form_valid(form) messages.success(self.request, _("Your message was sent successfully!")) - return super(ContactView, self).form_valid(form) + return valid
Set flash message *after* message sending
## Code Before: from django.core.urlresolvers import reverse from django.views.generic import CreateView from django.utils.translation import ugettext_lazy as _ from django.contrib import messages from .forms import ContactForm class ContactView(CreateView): template_name = 'contacts/contact.html' form_class = ContactForm def get_success_url(self): return reverse("qs_contacts:contact") def form_valid(self, form): messages.success(self.request, _("Your message was sent successfully!")) return super(ContactView, self).form_valid(form) ## Instruction: Set flash message *after* message sending ## Code After: from django.core.urlresolvers import reverse from django.views.generic import CreateView from django.utils.translation import ugettext_lazy as _ from django.contrib import messages from .forms import ContactForm class ContactView(CreateView): template_name = 'contacts/contact.html' form_class = ContactForm def get_success_url(self): return reverse("qs_contacts:contact") def form_valid(self, form): valid = super(ContactView, self).form_valid(form) messages.success(self.request, _("Your message was sent successfully!")) return valid
77a5ecc7c406e4a6acf814a2f0381dc605e0d14c
leds/led_dance.py
leds/led_dance.py
import pyb def led_dance(delay): dots = {} control = pyb.Switch(1) while True: if not control.value(): dots[pyb.millis() % 25] = 16 for d in dots: pyb.pixel(d, dots[d]) if dots[d] == 0: del(dots[d]) else: dots[d] = int(dots[d]/2) pyb.delay(delay) led_dance(101)
import microbit def led_dance(delay): dots = [ [0]*5, [0]*5, [0]*5, [0]*5, [0]*5 ] microbit.display.set_display_mode(1) while True: dots[microbit.random(5)][microbit.random(5)] = 128 for i in range(5): for j in range(5): microbit.display.image.set_pixel_value(i, j, dots[i][j]) dots[i][j] = int(dots[i][j]/2) microbit.sleep(delay) led_dance(100)
Update for new version of micropython for microbit
Update for new version of micropython for microbit
Python
mit
jrmhaig/microbit_playground
- import pyb + import microbit def led_dance(delay): - dots = {} - control = pyb.Switch(1) + dots = [ [0]*5, [0]*5, [0]*5, [0]*5, [0]*5 ] + microbit.display.set_display_mode(1) while True: + dots[microbit.random(5)][microbit.random(5)] = 128 + for i in range(5): + for j in range(5): + microbit.display.image.set_pixel_value(i, j, dots[i][j]) - if not control.value(): - dots[pyb.millis() % 25] = 16 - for d in dots: - pyb.pixel(d, dots[d]) - if dots[d] == 0: - del(dots[d]) - else: - dots[d] = int(dots[d]/2) + dots[i][j] = int(dots[i][j]/2) - pyb.delay(delay) + microbit.sleep(delay) - led_dance(101) + led_dance(100)
Update for new version of micropython for microbit
## Code Before: import pyb def led_dance(delay): dots = {} control = pyb.Switch(1) while True: if not control.value(): dots[pyb.millis() % 25] = 16 for d in dots: pyb.pixel(d, dots[d]) if dots[d] == 0: del(dots[d]) else: dots[d] = int(dots[d]/2) pyb.delay(delay) led_dance(101) ## Instruction: Update for new version of micropython for microbit ## Code After: import microbit def led_dance(delay): dots = [ [0]*5, [0]*5, [0]*5, [0]*5, [0]*5 ] microbit.display.set_display_mode(1) while True: dots[microbit.random(5)][microbit.random(5)] = 128 for i in range(5): for j in range(5): microbit.display.image.set_pixel_value(i, j, dots[i][j]) dots[i][j] = int(dots[i][j]/2) microbit.sleep(delay) led_dance(100)
99a8147a31060442368d79ebeee231744183a6d1
tests/test_adam.py
tests/test_adam.py
import pytest from adam.adam import * def test_contains_asset(): storage = AssetStorage() a = Asset() storage['key'] = a assert storage['key'] == a def test_contains_key(): storage = AssetStorage() a = Asset() assert 'key' not in storage storage['key'] = a assert 'key' in storage def test_asset_is_versioned(): storage = AssetStorage() a = Asset() updated_a = Asset() storage['key'] = a storage['key'] = updated_a versions = storage.versions_of('key') assert len(versions) == 2 assert versions[0] == a assert versions[1] == updated_a def test_asset_is_deleted(): storage = AssetStorage() a = Asset() storage['key'] = a del storage['key'] assert 'key' not in storage def test_deleting_unkown_key_raises_exception(): storage = AssetStorage() with pytest.raises(KeyError): del storage['key'] def test_create_asset_from_wav(): reader = WavReader() asset = reader.read('tests/16-bit-mono.wav') assert asset.mime_type == 'audio/wav' assert asset.framerate == 48000 assert asset.channels == 1
import pytest from adam.adam import * def test_contains_asset(): storage = AssetStorage() a = Asset() storage['key'] = a assert storage['key'] == a def test_contains_key(): storage = AssetStorage() a = Asset() assert 'key' not in storage storage['key'] = a assert 'key' in storage def test_asset_is_versioned(): storage = AssetStorage() a = Asset() updated_a = Asset() storage['key'] = a storage['key'] = updated_a versions = storage.versions_of('key') assert len(versions) == 2 assert versions[0] == a assert versions[1] == updated_a def test_asset_is_deleted(): storage = AssetStorage() a = Asset() storage['key'] = a del storage['key'] assert 'key' not in storage def test_deleting_unkown_key_raises_exception(): storage = AssetStorage() with pytest.raises(KeyError): del storage['key'] def test_create_asset_from_wav(): reader = WavReader() asset = reader.read('tests/16-bit-mono.wav') assert asset.mime_type == 'audio/wav' assert asset.framerate == 48000 assert asset.channels == 1 assert asset.essence != None
Test for reading a wave file asserts that the essence is set.
Test for reading a wave file asserts that the essence is set.
Python
agpl-3.0
eseifert/madam
import pytest from adam.adam import * def test_contains_asset(): storage = AssetStorage() a = Asset() storage['key'] = a assert storage['key'] == a def test_contains_key(): storage = AssetStorage() a = Asset() assert 'key' not in storage storage['key'] = a assert 'key' in storage def test_asset_is_versioned(): storage = AssetStorage() a = Asset() updated_a = Asset() storage['key'] = a storage['key'] = updated_a versions = storage.versions_of('key') assert len(versions) == 2 assert versions[0] == a assert versions[1] == updated_a def test_asset_is_deleted(): storage = AssetStorage() a = Asset() storage['key'] = a del storage['key'] assert 'key' not in storage def test_deleting_unkown_key_raises_exception(): storage = AssetStorage() with pytest.raises(KeyError): del storage['key'] def test_create_asset_from_wav(): reader = WavReader() asset = reader.read('tests/16-bit-mono.wav') assert asset.mime_type == 'audio/wav' assert asset.framerate == 48000 assert asset.channels == 1 + assert asset.essence != None
Test for reading a wave file asserts that the essence is set.
## Code Before: import pytest from adam.adam import * def test_contains_asset(): storage = AssetStorage() a = Asset() storage['key'] = a assert storage['key'] == a def test_contains_key(): storage = AssetStorage() a = Asset() assert 'key' not in storage storage['key'] = a assert 'key' in storage def test_asset_is_versioned(): storage = AssetStorage() a = Asset() updated_a = Asset() storage['key'] = a storage['key'] = updated_a versions = storage.versions_of('key') assert len(versions) == 2 assert versions[0] == a assert versions[1] == updated_a def test_asset_is_deleted(): storage = AssetStorage() a = Asset() storage['key'] = a del storage['key'] assert 'key' not in storage def test_deleting_unkown_key_raises_exception(): storage = AssetStorage() with pytest.raises(KeyError): del storage['key'] def test_create_asset_from_wav(): reader = WavReader() asset = reader.read('tests/16-bit-mono.wav') assert asset.mime_type == 'audio/wav' assert asset.framerate == 48000 assert asset.channels == 1 ## Instruction: Test for reading a wave file asserts that the essence is set. ## Code After: import pytest from adam.adam import * def test_contains_asset(): storage = AssetStorage() a = Asset() storage['key'] = a assert storage['key'] == a def test_contains_key(): storage = AssetStorage() a = Asset() assert 'key' not in storage storage['key'] = a assert 'key' in storage def test_asset_is_versioned(): storage = AssetStorage() a = Asset() updated_a = Asset() storage['key'] = a storage['key'] = updated_a versions = storage.versions_of('key') assert len(versions) == 2 assert versions[0] == a assert versions[1] == updated_a def test_asset_is_deleted(): storage = AssetStorage() a = Asset() storage['key'] = a del storage['key'] assert 'key' not in storage def test_deleting_unkown_key_raises_exception(): storage = AssetStorage() with pytest.raises(KeyError): del storage['key'] def test_create_asset_from_wav(): reader = WavReader() asset = reader.read('tests/16-bit-mono.wav') assert asset.mime_type == 'audio/wav' assert asset.framerate == 48000 assert asset.channels == 1 assert asset.essence != None
268718b9ad28c8bad26a7fede52a88d51ac5a8da
tests/test_opts.py
tests/test_opts.py
import sys from skeletor import config from skeletor.config import Config from .base import BaseTestCase from .helpers import nostdout class OptsTests(BaseTestCase): def test_something(self): assert True
import optparse from skeletor.opts import Option from .base import BaseTestCase class OptsTests(BaseTestCase): def should_raise_exception_when_require_used_incorrectly(self): try: Option('-n', '--does_not_take_val', action="store_true", default=None, required=True) except optparse.OptionError: assert True
Test for custom option class
Test for custom option class
Python
bsd-3-clause
krak3n/Facio,krak3n/Facio,krak3n/Facio,krak3n/Facio,krak3n/Facio
- import sys + import optparse - from skeletor import config + from skeletor.opts import Option - from skeletor.config import Config from .base import BaseTestCase - from .helpers import nostdout class OptsTests(BaseTestCase): - def test_something(self): + def should_raise_exception_when_require_used_incorrectly(self): + try: + Option('-n', '--does_not_take_val', action="store_true", + default=None, required=True) + except optparse.OptionError: - assert True + assert True
Test for custom option class
## Code Before: import sys from skeletor import config from skeletor.config import Config from .base import BaseTestCase from .helpers import nostdout class OptsTests(BaseTestCase): def test_something(self): assert True ## Instruction: Test for custom option class ## Code After: import optparse from skeletor.opts import Option from .base import BaseTestCase class OptsTests(BaseTestCase): def should_raise_exception_when_require_used_incorrectly(self): try: Option('-n', '--does_not_take_val', action="store_true", default=None, required=True) except optparse.OptionError: assert True
3ebf82c7ef356de3c4d427cea3723737661522e8
pinax/waitinglist/management/commands/mail_out_survey_links.py
pinax/waitinglist/management/commands/mail_out_survey_links.py
from django.conf import settings from django.core.mail import EmailMessage from django.core.management.base import BaseCommand from django.template.loader import render_to_string from django.contrib.sites.models import Site from ...models import WaitingListEntry, Survey class Command(BaseCommand): help = "Email links to survey instances for those that never saw a survey" def handle(self, *args, **options): survey = Survey.objects.get(active=True) entries = WaitingListEntry.objects.filter(surveyinstance__isnull=True) for entry in entries: instance = survey.instances.create(entry=entry) site = Site.objects.get_current() protocol = getattr(settings, "DEFAULT_HTTP_PROTOCOL", "http") ctx = { "instance": instance, "site": site, "protocol": protocol, } subject = render_to_string("waitinglist/survey_invite_subject.txt", ctx) subject = subject.strip() message = render_to_string("waitinglist/survey_invite_body.txt", ctx) EmailMessage( subject, message, to=[entry.email], from_email=settings.WAITINGLIST_SURVEY_INVITE_FROM_EMAIL ).send()
from django.conf import settings from django.core.mail import EmailMessage from django.core.management.base import BaseCommand from django.template.loader import render_to_string from django.contrib.sites.models import Site from ...models import WaitingListEntry, Survey class Command(BaseCommand): help = "Email links to survey instances for those that never saw a survey" def handle(self, *args, **options): survey = Survey.objects.get(active=True) entries = WaitingListEntry.objects.filter(surveyinstance__isnull=True) for entry in entries: instance = survey.instances.create(entry=entry) site = Site.objects.get_current() protocol = getattr(settings, "DEFAULT_HTTP_PROTOCOL", "http") ctx = { "instance": instance, "site": site, "protocol": protocol, } subject = render_to_string("pinax/waitinglist/survey_invite_subject.txt", ctx) subject = subject.strip() message = render_to_string("pinax/waitinglist/survey_invite_body.txt", ctx) EmailMessage( subject, message, to=[entry.email], from_email=settings.WAITINGLIST_SURVEY_INVITE_FROM_EMAIL ).send()
Fix paths in mail out email management command
Fix paths in mail out email management command
Python
mit
pinax/pinax-waitinglist,pinax/pinax-waitinglist
from django.conf import settings from django.core.mail import EmailMessage from django.core.management.base import BaseCommand from django.template.loader import render_to_string from django.contrib.sites.models import Site from ...models import WaitingListEntry, Survey class Command(BaseCommand): help = "Email links to survey instances for those that never saw a survey" def handle(self, *args, **options): survey = Survey.objects.get(active=True) entries = WaitingListEntry.objects.filter(surveyinstance__isnull=True) for entry in entries: instance = survey.instances.create(entry=entry) site = Site.objects.get_current() protocol = getattr(settings, "DEFAULT_HTTP_PROTOCOL", "http") ctx = { "instance": instance, "site": site, "protocol": protocol, } - subject = render_to_string("waitinglist/survey_invite_subject.txt", ctx) + subject = render_to_string("pinax/waitinglist/survey_invite_subject.txt", ctx) subject = subject.strip() - message = render_to_string("waitinglist/survey_invite_body.txt", ctx) + message = render_to_string("pinax/waitinglist/survey_invite_body.txt", ctx) EmailMessage( subject, message, to=[entry.email], from_email=settings.WAITINGLIST_SURVEY_INVITE_FROM_EMAIL ).send()
Fix paths in mail out email management command
## Code Before: from django.conf import settings from django.core.mail import EmailMessage from django.core.management.base import BaseCommand from django.template.loader import render_to_string from django.contrib.sites.models import Site from ...models import WaitingListEntry, Survey class Command(BaseCommand): help = "Email links to survey instances for those that never saw a survey" def handle(self, *args, **options): survey = Survey.objects.get(active=True) entries = WaitingListEntry.objects.filter(surveyinstance__isnull=True) for entry in entries: instance = survey.instances.create(entry=entry) site = Site.objects.get_current() protocol = getattr(settings, "DEFAULT_HTTP_PROTOCOL", "http") ctx = { "instance": instance, "site": site, "protocol": protocol, } subject = render_to_string("waitinglist/survey_invite_subject.txt", ctx) subject = subject.strip() message = render_to_string("waitinglist/survey_invite_body.txt", ctx) EmailMessage( subject, message, to=[entry.email], from_email=settings.WAITINGLIST_SURVEY_INVITE_FROM_EMAIL ).send() ## Instruction: Fix paths in mail out email management command ## Code After: from django.conf import settings from django.core.mail import EmailMessage from django.core.management.base import BaseCommand from django.template.loader import render_to_string from django.contrib.sites.models import Site from ...models import WaitingListEntry, Survey class Command(BaseCommand): help = "Email links to survey instances for those that never saw a survey" def handle(self, *args, **options): survey = Survey.objects.get(active=True) entries = WaitingListEntry.objects.filter(surveyinstance__isnull=True) for entry in entries: instance = survey.instances.create(entry=entry) site = Site.objects.get_current() protocol = getattr(settings, "DEFAULT_HTTP_PROTOCOL", "http") ctx = { "instance": instance, "site": site, "protocol": protocol, } subject = render_to_string("pinax/waitinglist/survey_invite_subject.txt", ctx) subject = subject.strip() message = render_to_string("pinax/waitinglist/survey_invite_body.txt", ctx) EmailMessage( subject, message, to=[entry.email], from_email=settings.WAITINGLIST_SURVEY_INVITE_FROM_EMAIL ).send()
73c7161d4414a9259ee6123ee3d3540153f30b9e
purchase_edi_file/models/purchase_order_line.py
purchase_edi_file/models/purchase_order_line.py
from odoo import _, exceptions, models class PurchaseOrderLine(models.Model): _inherit = "purchase.order.line" def _get_lines_by_profiles(self, partner): profile_lines = { key: self.env["purchase.order.line"] for key in partner.edi_purchase_profile_ids } for line in self: product = line.product_id seller = product._select_seller(partner_id=partner) purchase_edi = seller.purchase_edi_id # Services should not appear in EDI file unless an EDI profile # is specifically on the supplier info. This way, we avoid # adding transport of potential discount or anything else # in the EDI file. if product.type == "service" and not purchase_edi: continue if purchase_edi: profile_lines[purchase_edi] |= line elif partner.default_purchase_profile_id: profile_lines[partner.default_purchase_profile_id] |= line else: raise exceptions.UserError( _("Some products don't have edi profile configured : %s") % (product.default_code,) ) return profile_lines
from odoo import _, exceptions, models class PurchaseOrderLine(models.Model): _inherit = "purchase.order.line" def _get_lines_by_profiles(self, partner): profile_lines = { key: self.env["purchase.order.line"] for key in partner.edi_purchase_profile_ids } for line in self: product = line.product_id seller = product._select_seller( partner_id=partner, quantity=line.product_uom_qty ) purchase_edi = seller.purchase_edi_id # Services should not appear in EDI file unless an EDI profile # is specifically on the supplier info. This way, we avoid # adding transport of potential discount or anything else # in the EDI file. if product.type == "service" and not purchase_edi: continue if purchase_edi: profile_lines[purchase_edi] |= line elif partner.default_purchase_profile_id: profile_lines[partner.default_purchase_profile_id] |= line else: raise exceptions.UserError( _("Some products don't have edi profile configured : %s") % (product.default_code,) ) return profile_lines
Add qty when searching seller because even if not passed a verification is made by default in _select_seller
Add qty when searching seller because even if not passed a verification is made by default in _select_seller
Python
agpl-3.0
akretion/ak-odoo-incubator,akretion/ak-odoo-incubator,akretion/ak-odoo-incubator,akretion/ak-odoo-incubator
from odoo import _, exceptions, models class PurchaseOrderLine(models.Model): _inherit = "purchase.order.line" def _get_lines_by_profiles(self, partner): profile_lines = { key: self.env["purchase.order.line"] for key in partner.edi_purchase_profile_ids } for line in self: product = line.product_id - seller = product._select_seller(partner_id=partner) + seller = product._select_seller( + partner_id=partner, quantity=line.product_uom_qty + ) purchase_edi = seller.purchase_edi_id # Services should not appear in EDI file unless an EDI profile # is specifically on the supplier info. This way, we avoid # adding transport of potential discount or anything else # in the EDI file. if product.type == "service" and not purchase_edi: continue if purchase_edi: profile_lines[purchase_edi] |= line elif partner.default_purchase_profile_id: profile_lines[partner.default_purchase_profile_id] |= line else: raise exceptions.UserError( _("Some products don't have edi profile configured : %s") % (product.default_code,) ) return profile_lines
Add qty when searching seller because even if not passed a verification is made by default in _select_seller
## Code Before: from odoo import _, exceptions, models class PurchaseOrderLine(models.Model): _inherit = "purchase.order.line" def _get_lines_by_profiles(self, partner): profile_lines = { key: self.env["purchase.order.line"] for key in partner.edi_purchase_profile_ids } for line in self: product = line.product_id seller = product._select_seller(partner_id=partner) purchase_edi = seller.purchase_edi_id # Services should not appear in EDI file unless an EDI profile # is specifically on the supplier info. This way, we avoid # adding transport of potential discount or anything else # in the EDI file. if product.type == "service" and not purchase_edi: continue if purchase_edi: profile_lines[purchase_edi] |= line elif partner.default_purchase_profile_id: profile_lines[partner.default_purchase_profile_id] |= line else: raise exceptions.UserError( _("Some products don't have edi profile configured : %s") % (product.default_code,) ) return profile_lines ## Instruction: Add qty when searching seller because even if not passed a verification is made by default in _select_seller ## Code After: from odoo import _, exceptions, models class PurchaseOrderLine(models.Model): _inherit = "purchase.order.line" def _get_lines_by_profiles(self, partner): profile_lines = { key: self.env["purchase.order.line"] for key in partner.edi_purchase_profile_ids } for line in self: product = line.product_id seller = product._select_seller( partner_id=partner, quantity=line.product_uom_qty ) purchase_edi = seller.purchase_edi_id # Services should not appear in EDI file unless an EDI profile # is specifically on the supplier info. This way, we avoid # adding transport of potential discount or anything else # in the EDI file. if product.type == "service" and not purchase_edi: continue if purchase_edi: profile_lines[purchase_edi] |= line elif partner.default_purchase_profile_id: profile_lines[partner.default_purchase_profile_id] |= line else: raise exceptions.UserError( _("Some products don't have edi profile configured : %s") % (product.default_code,) ) return profile_lines
701b935564521d64cc35dc51753493f4dc2782f6
python/ql/test/library-tests/frameworks/django/SqlExecution.py
python/ql/test/library-tests/frameworks/django/SqlExecution.py
from django.db import connection, models from django.db.models.expressions import RawSQL def test_plain(): cursor = connection.cursor() cursor.execute("some sql") # $getSql="some sql" def test_context(): with connection.cursor() as cursor: cursor.execute("some sql") # $getSql="some sql" cursor.execute(sql="some sql") # $getSql="some sql" class User(models.Model): pass def test_model(): User.objects.raw("some sql") # $getSql="some sql" User.objects.annotate(RawSQL("some sql")) # $getSql="some sql" User.objects.annotate(RawSQL("foo"), RawSQL("bar")) # $getSql="foo" getSql="bar" User.objects.annotate(val=RawSQL("some sql")) # $getSql="some sql" User.objects.extra("some sql") # $getSql="some sql" User.objects.extra(select="select", where="where", tables="tables", order_by="order_by") # $getSql="select" getSql="where" getSql="tables" getSql="order_by" raw = RawSQL("so raw") User.objects.annotate(val=raw) # $getSql="so raw"
from django.db import connection, models from django.db.models.expressions import RawSQL def test_plain(): cursor = connection.cursor() cursor.execute("some sql") # $getSql="some sql" def test_context(): with connection.cursor() as cursor: cursor.execute("some sql") # $getSql="some sql" cursor.execute(sql="some sql") # $getSql="some sql" class User(models.Model): pass def test_model(): User.objects.raw("some sql") # $getSql="some sql" User.objects.annotate(RawSQL("some sql")) # $getSql="some sql" User.objects.annotate(RawSQL("foo"), RawSQL("bar")) # $getSql="foo" getSql="bar" User.objects.annotate(val=RawSQL("some sql")) # $getSql="some sql" User.objects.extra("some sql") # $getSql="some sql" User.objects.extra(select="select", where="where", tables="tables", order_by="order_by") # $getSql="select" getSql="where" getSql="tables" getSql="order_by" raw = RawSQL("so raw") User.objects.annotate(val=raw) # $getSql="so raw" # chaining QuerySet calls User.objects.using("db-name").exclude(username="admin").extra("some sql") # $ MISSING: getSql="some sql"
Add example of QuerySet chain (django)
Python: Add example of QuerySet chain (django)
Python
mit
github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql
from django.db import connection, models from django.db.models.expressions import RawSQL def test_plain(): cursor = connection.cursor() cursor.execute("some sql") # $getSql="some sql" def test_context(): with connection.cursor() as cursor: cursor.execute("some sql") # $getSql="some sql" cursor.execute(sql="some sql") # $getSql="some sql" class User(models.Model): pass def test_model(): User.objects.raw("some sql") # $getSql="some sql" User.objects.annotate(RawSQL("some sql")) # $getSql="some sql" User.objects.annotate(RawSQL("foo"), RawSQL("bar")) # $getSql="foo" getSql="bar" User.objects.annotate(val=RawSQL("some sql")) # $getSql="some sql" User.objects.extra("some sql") # $getSql="some sql" User.objects.extra(select="select", where="where", tables="tables", order_by="order_by") # $getSql="select" getSql="where" getSql="tables" getSql="order_by" raw = RawSQL("so raw") User.objects.annotate(val=raw) # $getSql="so raw" + # chaining QuerySet calls + User.objects.using("db-name").exclude(username="admin").extra("some sql") # $ MISSING: getSql="some sql" +
Add example of QuerySet chain (django)
## Code Before: from django.db import connection, models from django.db.models.expressions import RawSQL def test_plain(): cursor = connection.cursor() cursor.execute("some sql") # $getSql="some sql" def test_context(): with connection.cursor() as cursor: cursor.execute("some sql") # $getSql="some sql" cursor.execute(sql="some sql") # $getSql="some sql" class User(models.Model): pass def test_model(): User.objects.raw("some sql") # $getSql="some sql" User.objects.annotate(RawSQL("some sql")) # $getSql="some sql" User.objects.annotate(RawSQL("foo"), RawSQL("bar")) # $getSql="foo" getSql="bar" User.objects.annotate(val=RawSQL("some sql")) # $getSql="some sql" User.objects.extra("some sql") # $getSql="some sql" User.objects.extra(select="select", where="where", tables="tables", order_by="order_by") # $getSql="select" getSql="where" getSql="tables" getSql="order_by" raw = RawSQL("so raw") User.objects.annotate(val=raw) # $getSql="so raw" ## Instruction: Add example of QuerySet chain (django) ## Code After: from django.db import connection, models from django.db.models.expressions import RawSQL def test_plain(): cursor = connection.cursor() cursor.execute("some sql") # $getSql="some sql" def test_context(): with connection.cursor() as cursor: cursor.execute("some sql") # $getSql="some sql" cursor.execute(sql="some sql") # $getSql="some sql" class User(models.Model): pass def test_model(): User.objects.raw("some sql") # $getSql="some sql" User.objects.annotate(RawSQL("some sql")) # $getSql="some sql" User.objects.annotate(RawSQL("foo"), RawSQL("bar")) # $getSql="foo" getSql="bar" User.objects.annotate(val=RawSQL("some sql")) # $getSql="some sql" User.objects.extra("some sql") # $getSql="some sql" User.objects.extra(select="select", where="where", tables="tables", order_by="order_by") # $getSql="select" getSql="where" getSql="tables" getSql="order_by" raw = RawSQL("so raw") User.objects.annotate(val=raw) # $getSql="so raw" # chaining QuerySet calls User.objects.using("db-name").exclude(username="admin").extra("some sql") # $ MISSING: getSql="some sql"
3fe0313d67857ec302cc20e0cdc30d658e41dd97
troposphere/ecr.py
troposphere/ecr.py
from . import AWSObject, AWSProperty, Tags from .compat import policytypes class LifecyclePolicy(AWSProperty): props = { 'LifecyclePolicyText': (basestring, False), 'RegistryId': (basestring, False), } class Repository(AWSObject): resource_type = "AWS::ECR::Repository" props = { 'ImageScanningConfiguration': (dict, False), 'ImageTagMutability': (basestring, False), 'LifecyclePolicy': (LifecyclePolicy, False), 'RepositoryName': (basestring, False), 'RepositoryPolicyText': (policytypes, False), 'Tags': (Tags, False), }
from . import AWSObject, AWSProperty, Tags from .compat import policytypes class PublicRepository(AWSObject): resource_type = "AWS::ECR::PublicRepository" props = { 'RepositoryCatalogData': (dict, False), 'RepositoryName': (basestring, False), 'RepositoryPolicyText': (policytypes, False), 'Tags': (Tags, False), } class RegistryPolicy(AWSObject): resource_type = "AWS::ECR::RegistryPolicy" props = { 'PolicyText': (policytypes, True), } class ReplicationDestination(AWSProperty): props = { 'Region': (basestring, True), 'RegistryId': (basestring, True), } class ReplicationRule(AWSProperty): props = { 'Destinations': ([ReplicationDestination], True), } class ReplicationConfigurationProperty(AWSProperty): props = { 'Rules': ([ReplicationRule], True), } class ReplicationConfiguration(AWSObject): resource_type = "AWS::ECR::Repository" props = { 'ReplicationConfigurationProperty': (ReplicationConfigurationProperty, True), } class LifecyclePolicy(AWSProperty): props = { 'LifecyclePolicyText': (basestring, False), 'RegistryId': (basestring, False), } class Repository(AWSObject): resource_type = "AWS::ECR::Repository" props = { 'ImageScanningConfiguration': (dict, False), 'ImageTagMutability': (basestring, False), 'LifecyclePolicy': (LifecyclePolicy, False), 'RepositoryName': (basestring, False), 'RepositoryPolicyText': (policytypes, False), 'Tags': (Tags, False), }
Update ECR per 2020-12-18 and 2021-02-04 changes
Update ECR per 2020-12-18 and 2021-02-04 changes
Python
bsd-2-clause
cloudtools/troposphere,cloudtools/troposphere
+ + from . import AWSObject, AWSProperty, Tags from .compat import policytypes + + + class PublicRepository(AWSObject): + resource_type = "AWS::ECR::PublicRepository" + + props = { + 'RepositoryCatalogData': (dict, False), + 'RepositoryName': (basestring, False), + 'RepositoryPolicyText': (policytypes, False), + 'Tags': (Tags, False), + } + + + class RegistryPolicy(AWSObject): + resource_type = "AWS::ECR::RegistryPolicy" + + props = { + 'PolicyText': (policytypes, True), + } + + + class ReplicationDestination(AWSProperty): + props = { + 'Region': (basestring, True), + 'RegistryId': (basestring, True), + } + + + class ReplicationRule(AWSProperty): + props = { + 'Destinations': ([ReplicationDestination], True), + } + + + class ReplicationConfigurationProperty(AWSProperty): + props = { + 'Rules': ([ReplicationRule], True), + } + + + class ReplicationConfiguration(AWSObject): + resource_type = "AWS::ECR::Repository" + + props = { + 'ReplicationConfigurationProperty': + (ReplicationConfigurationProperty, True), + } class LifecyclePolicy(AWSProperty): props = { 'LifecyclePolicyText': (basestring, False), 'RegistryId': (basestring, False), } class Repository(AWSObject): resource_type = "AWS::ECR::Repository" props = { 'ImageScanningConfiguration': (dict, False), 'ImageTagMutability': (basestring, False), 'LifecyclePolicy': (LifecyclePolicy, False), 'RepositoryName': (basestring, False), 'RepositoryPolicyText': (policytypes, False), 'Tags': (Tags, False), }
Update ECR per 2020-12-18 and 2021-02-04 changes
## Code Before: from . import AWSObject, AWSProperty, Tags from .compat import policytypes class LifecyclePolicy(AWSProperty): props = { 'LifecyclePolicyText': (basestring, False), 'RegistryId': (basestring, False), } class Repository(AWSObject): resource_type = "AWS::ECR::Repository" props = { 'ImageScanningConfiguration': (dict, False), 'ImageTagMutability': (basestring, False), 'LifecyclePolicy': (LifecyclePolicy, False), 'RepositoryName': (basestring, False), 'RepositoryPolicyText': (policytypes, False), 'Tags': (Tags, False), } ## Instruction: Update ECR per 2020-12-18 and 2021-02-04 changes ## Code After: from . import AWSObject, AWSProperty, Tags from .compat import policytypes class PublicRepository(AWSObject): resource_type = "AWS::ECR::PublicRepository" props = { 'RepositoryCatalogData': (dict, False), 'RepositoryName': (basestring, False), 'RepositoryPolicyText': (policytypes, False), 'Tags': (Tags, False), } class RegistryPolicy(AWSObject): resource_type = "AWS::ECR::RegistryPolicy" props = { 'PolicyText': (policytypes, True), } class ReplicationDestination(AWSProperty): props = { 'Region': (basestring, True), 'RegistryId': (basestring, True), } class ReplicationRule(AWSProperty): props = { 'Destinations': ([ReplicationDestination], True), } class ReplicationConfigurationProperty(AWSProperty): props = { 'Rules': ([ReplicationRule], True), } class ReplicationConfiguration(AWSObject): resource_type = "AWS::ECR::Repository" props = { 'ReplicationConfigurationProperty': (ReplicationConfigurationProperty, True), } class LifecyclePolicy(AWSProperty): props = { 'LifecyclePolicyText': (basestring, False), 'RegistryId': (basestring, False), } class Repository(AWSObject): resource_type = "AWS::ECR::Repository" props = { 'ImageScanningConfiguration': (dict, False), 'ImageTagMutability': (basestring, False), 'LifecyclePolicy': (LifecyclePolicy, False), 'RepositoryName': (basestring, False), 'RepositoryPolicyText': (policytypes, False), 'Tags': (Tags, False), }
5b7e2c7c4ad28634db9641a2b8c96f4d047ae503
arim/fields.py
arim/fields.py
import re from django import forms mac_pattern = re.compile("^[0-9a-f]{12}$") class MacAddrFormField(forms.CharField): def __init__(self, *args, **kwargs): kwargs['max_length'] = 17 super(MacAddrFormField, self).__init__(*args, **kwargs) def clean(self, value): value = super(MacAddrFormField, self).clean(value) value = filter(lambda x: x in "0123456789abcdef", value) if mac_pattern.match(value) is None: raise forms.ValidationError('Invalid MAC address') value = reduce(lambda x,y: x + ':' + y, (value[i:i+2] for i in xrange(0, 12, 2))) return value
import re from django import forms mac_pattern = re.compile("^[0-9a-f]{12}$") class MacAddrFormField(forms.CharField): def __init__(self, *args, **kwargs): kwargs['max_length'] = 17 super(MacAddrFormField, self).__init__(*args, **kwargs) def clean(self, value): value = super(MacAddrFormField, self).clean(value) value = value.lower().replace(':', '').replace('-', '') if mac_pattern.match(value) is None: raise forms.ValidationError('Invalid MAC address') value = reduce(lambda x,y: x + ':' + y, (value[i:i+2] for i in xrange(0, 12, 2))) return value
Revert "Properly handle non-hex characters in MAC"
Revert "Properly handle non-hex characters in MAC" This reverts commit 2734a3f0212c722fb9fe3698dfea0dbd8a14faa7.
Python
bsd-3-clause
OSU-Net/arim,drkitty/arim,OSU-Net/arim,drkitty/arim,drkitty/arim,OSU-Net/arim
import re from django import forms mac_pattern = re.compile("^[0-9a-f]{12}$") class MacAddrFormField(forms.CharField): def __init__(self, *args, **kwargs): kwargs['max_length'] = 17 super(MacAddrFormField, self).__init__(*args, **kwargs) def clean(self, value): value = super(MacAddrFormField, self).clean(value) + value = value.lower().replace(':', '').replace('-', '') - value = filter(lambda x: x in "0123456789abcdef", value) - if mac_pattern.match(value) is None: raise forms.ValidationError('Invalid MAC address') value = reduce(lambda x,y: x + ':' + y, (value[i:i+2] for i in xrange(0, 12, 2))) return value
Revert "Properly handle non-hex characters in MAC"
## Code Before: import re from django import forms mac_pattern = re.compile("^[0-9a-f]{12}$") class MacAddrFormField(forms.CharField): def __init__(self, *args, **kwargs): kwargs['max_length'] = 17 super(MacAddrFormField, self).__init__(*args, **kwargs) def clean(self, value): value = super(MacAddrFormField, self).clean(value) value = filter(lambda x: x in "0123456789abcdef", value) if mac_pattern.match(value) is None: raise forms.ValidationError('Invalid MAC address') value = reduce(lambda x,y: x + ':' + y, (value[i:i+2] for i in xrange(0, 12, 2))) return value ## Instruction: Revert "Properly handle non-hex characters in MAC" ## Code After: import re from django import forms mac_pattern = re.compile("^[0-9a-f]{12}$") class MacAddrFormField(forms.CharField): def __init__(self, *args, **kwargs): kwargs['max_length'] = 17 super(MacAddrFormField, self).__init__(*args, **kwargs) def clean(self, value): value = super(MacAddrFormField, self).clean(value) value = value.lower().replace(':', '').replace('-', '') if mac_pattern.match(value) is None: raise forms.ValidationError('Invalid MAC address') value = reduce(lambda x,y: x + ':' + y, (value[i:i+2] for i in xrange(0, 12, 2))) return value
bd3dad98976d5e02c4a941ae3c687174db78781d
src/WebCatch/catchLink.py
src/WebCatch/catchLink.py
import requests import re import os url = "https://www.autohome.com.cn/shanghai/" urlBox = [] def catchURL(url): file = requests.get(url,timeout=2) data = file.content links = re.findall(r'(https?://[^\s)";]+\.(\w|/)*)',str(data)) for i in links: try: currentURL = i[0] if currentURL not in urlBox: urlBox.append(currentURL) os.system("ssh pgadmin@10.211.55.8 psql test -c \ 'insert into url values(nextval('url_seq'), '"+ currentURL +"')'") print(currentURL) catchURL(currentURL) except Exception as e: pass continue catchURL(url)
import requests import re import os url = "https://www.autohome.com.cn/shanghai/" urlBox = [] def catchURL(url): file = requests.get(url,timeout=5) data = file.content links = re.findall(r'(https?://[^\s)";]+\.(\w|/)*)',str(data)) for i in links: try: currentURL = i[0] if currentURL not in urlBox: urlBox.append(currentURL) sql = """ ssh pgadmin@10.211.55.8 psql test -U pgadmin << EOF insert into url values(nextval(\'url_seq\'), \'"""+currentURL+"""\'); EOF """ print(sql) os.popen(sql) print(currentURL) catchURL(currentURL) except Exception as e: pass continue catchURL(url)
Put the crawled link into the database
Put the crawled link into the database
Python
mit
zhaodjie/py_learning
- import requests import re import os url = "https://www.autohome.com.cn/shanghai/" urlBox = [] def catchURL(url): file = requests.get(url,timeout=2) data = file.content links = re.findall(r'(https?://[^\s)";]+\.(\w|/)*)',str(data)) for i in links: try: currentURL = i[0] if currentURL not in urlBox: urlBox.append(currentURL) os.system("ssh pgadmin@10.211.55.8 psql test -c \ 'insert into url values(nextval('url_seq'), '"+ currentURL +"')'") print(currentURL) catchURL(currentURL) except Exception as e: pass continue catchURL(url) + import requests + import re + import os + + url = "https://www.autohome.com.cn/shanghai/" + urlBox = [] + def catchURL(url): + file = requests.get(url,timeout=5) + data = file.content + links = re.findall(r'(https?://[^\s)";]+\.(\w|/)*)',str(data)) + for i in links: + try: + currentURL = i[0] + if currentURL not in urlBox: + urlBox.append(currentURL) + sql = """ + ssh pgadmin@10.211.55.8 psql test -U pgadmin << EOF + insert into url values(nextval(\'url_seq\'), \'"""+currentURL+"""\'); + EOF + """ + print(sql) + os.popen(sql) + print(currentURL) + catchURL(currentURL) + except Exception as e: + pass + continue + + + + + catchURL(url)
Put the crawled link into the database
## Code Before: import requests import re import os url = "https://www.autohome.com.cn/shanghai/" urlBox = [] def catchURL(url): file = requests.get(url,timeout=2) data = file.content links = re.findall(r'(https?://[^\s)";]+\.(\w|/)*)',str(data)) for i in links: try: currentURL = i[0] if currentURL not in urlBox: urlBox.append(currentURL) os.system("ssh pgadmin@10.211.55.8 psql test -c \ 'insert into url values(nextval('url_seq'), '"+ currentURL +"')'") print(currentURL) catchURL(currentURL) except Exception as e: pass continue catchURL(url) ## Instruction: Put the crawled link into the database ## Code After: import requests import re import os url = "https://www.autohome.com.cn/shanghai/" urlBox = [] def catchURL(url): file = requests.get(url,timeout=5) data = file.content links = re.findall(r'(https?://[^\s)";]+\.(\w|/)*)',str(data)) for i in links: try: currentURL = i[0] if currentURL not in urlBox: urlBox.append(currentURL) sql = """ ssh pgadmin@10.211.55.8 psql test -U pgadmin << EOF insert into url values(nextval(\'url_seq\'), \'"""+currentURL+"""\'); EOF """ print(sql) os.popen(sql) print(currentURL) catchURL(currentURL) except Exception as e: pass continue catchURL(url)
e6ca7ef801115d16d809c563b657c3a63e828fb1
corehq/apps/locations/management/commands/location_last_modified.py
corehq/apps/locations/management/commands/location_last_modified.py
from django.core.management.base import BaseCommand from corehq.apps.locations.models import Location from dimagi.utils.couch.database import iter_docs from datetime import datetime class Command(BaseCommand): help = 'Populate last_modified field for locations' def handle(self, *args, **options): self.stdout.write("Processing locations...\n") relevant_ids = set([r['id'] for r in Location.get_db().view( 'commtrack/locations_by_code', reduce=False, ).all()]) to_save = [] for location in iter_docs(Location.get_db(), relevant_ids): if 'last_modified' not in location or not location['last_modified']: location['last_modified'] = datetime.now().isoformat() to_save.append(location) if len(to_save) > 500: Location.get_db().bulk_save(to_save) to_save = [] if to_save: Location.get_db().bulk_save(to_save)
from django.core.management.base import BaseCommand from corehq.apps.locations.models import Location from dimagi.utils.couch.database import iter_docs from datetime import datetime class Command(BaseCommand): help = 'Populate last_modified field for locations' def handle(self, *args, **options): self.stdout.write("Processing locations...\n") relevant_ids = set([r['id'] for r in Location.get_db().view( 'commtrack/locations_by_code', reduce=False, ).all()]) to_save = [] for location in iter_docs(Location.get_db(), relevant_ids): # exclude any psi domain to make this take a realistic # amount fo time if ( not location.get('last_modified', False) and 'psi' not in location.get('domain', '') ): location['last_modified'] = datetime.now().isoformat() to_save.append(location) if len(to_save) > 500: Location.get_db().bulk_save(to_save) to_save = [] if to_save: Location.get_db().bulk_save(to_save)
Exclude psi domains or this takes forever
Exclude psi domains or this takes forever
Python
bsd-3-clause
qedsoftware/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,SEL-Columbia/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,SEL-Columbia/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,SEL-Columbia/commcare-hq
from django.core.management.base import BaseCommand from corehq.apps.locations.models import Location from dimagi.utils.couch.database import iter_docs from datetime import datetime class Command(BaseCommand): help = 'Populate last_modified field for locations' def handle(self, *args, **options): self.stdout.write("Processing locations...\n") relevant_ids = set([r['id'] for r in Location.get_db().view( 'commtrack/locations_by_code', reduce=False, ).all()]) to_save = [] for location in iter_docs(Location.get_db(), relevant_ids): - if 'last_modified' not in location or not location['last_modified']: + # exclude any psi domain to make this take a realistic + # amount fo time + if ( + not location.get('last_modified', False) and + 'psi' not in location.get('domain', '') + ): location['last_modified'] = datetime.now().isoformat() to_save.append(location) if len(to_save) > 500: Location.get_db().bulk_save(to_save) to_save = [] if to_save: Location.get_db().bulk_save(to_save)
Exclude psi domains or this takes forever
## Code Before: from django.core.management.base import BaseCommand from corehq.apps.locations.models import Location from dimagi.utils.couch.database import iter_docs from datetime import datetime class Command(BaseCommand): help = 'Populate last_modified field for locations' def handle(self, *args, **options): self.stdout.write("Processing locations...\n") relevant_ids = set([r['id'] for r in Location.get_db().view( 'commtrack/locations_by_code', reduce=False, ).all()]) to_save = [] for location in iter_docs(Location.get_db(), relevant_ids): if 'last_modified' not in location or not location['last_modified']: location['last_modified'] = datetime.now().isoformat() to_save.append(location) if len(to_save) > 500: Location.get_db().bulk_save(to_save) to_save = [] if to_save: Location.get_db().bulk_save(to_save) ## Instruction: Exclude psi domains or this takes forever ## Code After: from django.core.management.base import BaseCommand from corehq.apps.locations.models import Location from dimagi.utils.couch.database import iter_docs from datetime import datetime class Command(BaseCommand): help = 'Populate last_modified field for locations' def handle(self, *args, **options): self.stdout.write("Processing locations...\n") relevant_ids = set([r['id'] for r in Location.get_db().view( 'commtrack/locations_by_code', reduce=False, ).all()]) to_save = [] for location in iter_docs(Location.get_db(), relevant_ids): # exclude any psi domain to make this take a realistic # amount fo time if ( not location.get('last_modified', False) and 'psi' not in location.get('domain', '') ): location['last_modified'] = datetime.now().isoformat() to_save.append(location) if len(to_save) > 500: Location.get_db().bulk_save(to_save) to_save = [] if to_save: Location.get_db().bulk_save(to_save)
352cb871a86abd926842a0624475db1f2ee2c0ce
TorGTK/list_elements.py
TorGTK/list_elements.py
from var import * from ui_elements import * from gi.repository import Gtk from torctl import * # ORGANIZATION OF THESE LISTS: # 1. Main list for all the elements # 2. A sublist for each element, with the first being a label, and the second # being the element itself # List for main listbox lb_main_elements = [ ["", init_menubutton("btnMainMenu", objs["menuMain"])], ["Enable Tor", init_switch("swEnable", enableTor)], ] # List for settings listbox lb_settings_elements = [ ["SOCKS Port", init_spinbutton("spinSocks", default_socks_port, 1024, 65535, 1)], ["Control Port", init_spinbutton("spinCtl", default_control_port, 1024, 65535, 1)], ]
from var import * from ui_elements import * from gi.repository import Gtk from torctl import * # ORGANIZATION OF THESE LISTS: # 1. Main list for all the elements # 2. A sublist for each element, with the first being a label, and the second # being the element itself # List for main listbox lb_main_elements = [ ["", init_menubutton("btnMainMenu", objs["menuMain"])], ["Enable Tor", init_switch("swEnable", enableTor)], ] # List for settings listbox lb_settings_elements = [ ["SOCKS Port", init_spinbutton("spinSocks", default_socks_port, 1024, 65535, 1)], ["Control Port", init_spinbutton("spinCtl", default_control_port, 1024, 65535, 1)], ["Exit Nodes", init_textfield("txtExit")], ]
Add field (not working yet) for Tor exit node selection
Add field (not working yet) for Tor exit node selection
Python
bsd-2-clause
neelchauhan/TorNova,neelchauhan/TorGTK
from var import * from ui_elements import * from gi.repository import Gtk from torctl import * # ORGANIZATION OF THESE LISTS: # 1. Main list for all the elements # 2. A sublist for each element, with the first being a label, and the second # being the element itself # List for main listbox lb_main_elements = [ ["", init_menubutton("btnMainMenu", objs["menuMain"])], ["Enable Tor", init_switch("swEnable", enableTor)], ] # List for settings listbox lb_settings_elements = [ ["SOCKS Port", init_spinbutton("spinSocks", default_socks_port, 1024, 65535, 1)], ["Control Port", init_spinbutton("spinCtl", default_control_port, 1024, 65535, 1)], + ["Exit Nodes", init_textfield("txtExit")], ]
Add field (not working yet) for Tor exit node selection
## Code Before: from var import * from ui_elements import * from gi.repository import Gtk from torctl import * # ORGANIZATION OF THESE LISTS: # 1. Main list for all the elements # 2. A sublist for each element, with the first being a label, and the second # being the element itself # List for main listbox lb_main_elements = [ ["", init_menubutton("btnMainMenu", objs["menuMain"])], ["Enable Tor", init_switch("swEnable", enableTor)], ] # List for settings listbox lb_settings_elements = [ ["SOCKS Port", init_spinbutton("spinSocks", default_socks_port, 1024, 65535, 1)], ["Control Port", init_spinbutton("spinCtl", default_control_port, 1024, 65535, 1)], ] ## Instruction: Add field (not working yet) for Tor exit node selection ## Code After: from var import * from ui_elements import * from gi.repository import Gtk from torctl import * # ORGANIZATION OF THESE LISTS: # 1. Main list for all the elements # 2. A sublist for each element, with the first being a label, and the second # being the element itself # List for main listbox lb_main_elements = [ ["", init_menubutton("btnMainMenu", objs["menuMain"])], ["Enable Tor", init_switch("swEnable", enableTor)], ] # List for settings listbox lb_settings_elements = [ ["SOCKS Port", init_spinbutton("spinSocks", default_socks_port, 1024, 65535, 1)], ["Control Port", init_spinbutton("spinCtl", default_control_port, 1024, 65535, 1)], ["Exit Nodes", init_textfield("txtExit")], ]
3f136f153cdc60c1dcc757a8a35ef116bb892a1c
python/prep_policekml.py
python/prep_policekml.py
import os from lxml import etree class prep_kml(): def __init__ (self, inputfile): self.inputfile = inputfile self.infile = os.path.basename(inputfile) self.feat_types = ['Placemark'] def get_feat_types(self): return self.feat_types def prepare_feature(self, feat_str): # Parse the xml string into something useful feat_elm = etree.fromstring(feat_str) feat_elm = self._prepare_feat_elm(feat_elm) return etree.tostring(feat_elm, encoding='UTF-8', pretty_print=True).decode('utf_8'); def _prepare_feat_elm(self, feat_elm): feat_elm = self._add_filename_elm(feat_elm) return feat_elm def _add_filename_elm(self, feat_elm): # Create an element with the fid elm = etree.SubElement(feat_elm, "name") elm.text = self.infile[:-4] elm = etree.SubElement(feat_elm, "description") elm.text = os.path.dirname(self.inputfile).split('/')[-1] return feat_elm
import os from lxml import etree class prep_kml(): def __init__(self, inputfile): self.inputfile = inputfile self.infile = os.path.basename(inputfile) self.feat_types = ['Placemark'] def get_feat_types(self): return self.feat_types def prepare_feature(self, feat_str): # Parse the xml string into something useful feat_elm = etree.fromstring(feat_str) feat_elm = self._prepare_feat_elm(feat_elm) return etree.tostring(feat_elm, encoding='UTF-8', pretty_print=True).decode('utf_8'); def _prepare_feat_elm(self, feat_elm): feat_elm = self._add_filename_elm(feat_elm) return feat_elm def _add_filename_elm(self, feat_elm): elm = etree.SubElement(feat_elm, "name") elm.text = self.infile[:-4] elm = etree.SubElement(feat_elm, "description") elm.text = os.path.dirname(self.inputfile).split('/')[-1] return feat_elm
Remove stray comment, update docstring and minor PEP8 changes
Remove stray comment, update docstring and minor PEP8 changes
Python
mit
AstunTechnology/Loader
import os from lxml import etree + class prep_kml(): - def __init__ (self, inputfile): + def __init__(self, inputfile): self.inputfile = inputfile self.infile = os.path.basename(inputfile) self.feat_types = ['Placemark'] def get_feat_types(self): return self.feat_types def prepare_feature(self, feat_str): # Parse the xml string into something useful feat_elm = etree.fromstring(feat_str) feat_elm = self._prepare_feat_elm(feat_elm) - + return etree.tostring(feat_elm, encoding='UTF-8', pretty_print=True).decode('utf_8'); def _prepare_feat_elm(self, feat_elm): feat_elm = self._add_filename_elm(feat_elm) - + return feat_elm def _add_filename_elm(self, feat_elm): - # Create an element with the fid + elm = etree.SubElement(feat_elm, "name") elm.text = self.infile[:-4] - + elm = etree.SubElement(feat_elm, "description") elm.text = os.path.dirname(self.inputfile).split('/')[-1] return feat_elm -
Remove stray comment, update docstring and minor PEP8 changes
## Code Before: import os from lxml import etree class prep_kml(): def __init__ (self, inputfile): self.inputfile = inputfile self.infile = os.path.basename(inputfile) self.feat_types = ['Placemark'] def get_feat_types(self): return self.feat_types def prepare_feature(self, feat_str): # Parse the xml string into something useful feat_elm = etree.fromstring(feat_str) feat_elm = self._prepare_feat_elm(feat_elm) return etree.tostring(feat_elm, encoding='UTF-8', pretty_print=True).decode('utf_8'); def _prepare_feat_elm(self, feat_elm): feat_elm = self._add_filename_elm(feat_elm) return feat_elm def _add_filename_elm(self, feat_elm): # Create an element with the fid elm = etree.SubElement(feat_elm, "name") elm.text = self.infile[:-4] elm = etree.SubElement(feat_elm, "description") elm.text = os.path.dirname(self.inputfile).split('/')[-1] return feat_elm ## Instruction: Remove stray comment, update docstring and minor PEP8 changes ## Code After: import os from lxml import etree class prep_kml(): def __init__(self, inputfile): self.inputfile = inputfile self.infile = os.path.basename(inputfile) self.feat_types = ['Placemark'] def get_feat_types(self): return self.feat_types def prepare_feature(self, feat_str): # Parse the xml string into something useful feat_elm = etree.fromstring(feat_str) feat_elm = self._prepare_feat_elm(feat_elm) return etree.tostring(feat_elm, encoding='UTF-8', pretty_print=True).decode('utf_8'); def _prepare_feat_elm(self, feat_elm): feat_elm = self._add_filename_elm(feat_elm) return feat_elm def _add_filename_elm(self, feat_elm): elm = etree.SubElement(feat_elm, "name") elm.text = self.infile[:-4] elm = etree.SubElement(feat_elm, "description") elm.text = os.path.dirname(self.inputfile).split('/')[-1] return feat_elm
fe65e85e0a29341a6eebbb1bafb28b8d1225abfc
harvester/rq_worker_sns_msgs.py
harvester/rq_worker_sns_msgs.py
'''A custom rq worker class to add start & stop SNS messages to all jobs''' import logging from rq.worker import Worker from harvester.sns_message import publish_to_harvesting logger = logging.getLogger(__name__) class SNSWorker(Worker): def execute_job(self, job, queue): """Spawns a work horse to perform the actual work and passes it a job. The worker will wait for the work horse and make sure it executes within the given timeout bounds, or will end the work horse with SIGALRM. """ worker_name = (self.key.rsplit(':', 1)[1]).rsplit('.', 1)[0] subject = 'Worker {} starting job {}'.format( worker_name, job.description) publish_to_harvesting(subject, subject) self.set_state('busy') self.fork_work_horse(job, queue) self.monitor_work_horse(job) subject = 'Worker {} finished job {}'.format( worker_name, job.description) publish_to_harvesting(subject, subject) self.set_state('idle')
'''A custom rq worker class to add start & stop SNS messages to all jobs''' import logging from rq.worker import Worker from harvester.sns_message import publish_to_harvesting logger = logging.getLogger(__name__) def exception_to_sns(job, *exc_info): '''Make an exception handler to report exceptions to SNS msg queue''' subject = 'FAILED: job {}'.format(job.description) message = 'ERROR: job {} failed\n{}'.format( job.description, exc_info[1]) logging.error(message) publish_to_harvesting(subject, message) class SNSWorker(Worker): def execute_job(self, job, queue): """Spawns a work horse to perform the actual work and passes it a job. The worker will wait for the work horse and make sure it executes within the given timeout bounds, or will end the work horse with SIGALRM. """ worker_name = (self.key.rsplit(':', 1)[1]).rsplit('.', 1)[0] subject = 'Worker {} starting job {}'.format( worker_name, job.description) #publish_to_harvesting(subject, subject) self.set_state('busy') self.fork_work_horse(job, queue) self.monitor_work_horse(job) subject = 'Worker {} finished job {}'.format( worker_name, job.description) #publish_to_harvesting(subject, subject) self.set_state('idle')
Add RQ exception handler to report to SNS topic
Add RQ exception handler to report to SNS topic
Python
bsd-3-clause
mredar/harvester,barbarahui/harvester,barbarahui/harvester,mredar/harvester,ucldc/harvester,ucldc/harvester
'''A custom rq worker class to add start & stop SNS messages to all jobs''' import logging from rq.worker import Worker from harvester.sns_message import publish_to_harvesting logger = logging.getLogger(__name__) + + + def exception_to_sns(job, *exc_info): + '''Make an exception handler to report exceptions to SNS msg queue''' + subject = 'FAILED: job {}'.format(job.description) + message = 'ERROR: job {} failed\n{}'.format( + job.description, + exc_info[1]) + logging.error(message) + publish_to_harvesting(subject, message) class SNSWorker(Worker): def execute_job(self, job, queue): """Spawns a work horse to perform the actual work and passes it a job. The worker will wait for the work horse and make sure it executes within the given timeout bounds, or will end the work horse with SIGALRM. """ worker_name = (self.key.rsplit(':', 1)[1]).rsplit('.', 1)[0] subject = 'Worker {} starting job {}'.format( worker_name, job.description) - publish_to_harvesting(subject, subject) + #publish_to_harvesting(subject, subject) self.set_state('busy') self.fork_work_horse(job, queue) self.monitor_work_horse(job) subject = 'Worker {} finished job {}'.format( worker_name, job.description) - publish_to_harvesting(subject, subject) + #publish_to_harvesting(subject, subject) self.set_state('idle')
Add RQ exception handler to report to SNS topic
## Code Before: '''A custom rq worker class to add start & stop SNS messages to all jobs''' import logging from rq.worker import Worker from harvester.sns_message import publish_to_harvesting logger = logging.getLogger(__name__) class SNSWorker(Worker): def execute_job(self, job, queue): """Spawns a work horse to perform the actual work and passes it a job. The worker will wait for the work horse and make sure it executes within the given timeout bounds, or will end the work horse with SIGALRM. """ worker_name = (self.key.rsplit(':', 1)[1]).rsplit('.', 1)[0] subject = 'Worker {} starting job {}'.format( worker_name, job.description) publish_to_harvesting(subject, subject) self.set_state('busy') self.fork_work_horse(job, queue) self.monitor_work_horse(job) subject = 'Worker {} finished job {}'.format( worker_name, job.description) publish_to_harvesting(subject, subject) self.set_state('idle') ## Instruction: Add RQ exception handler to report to SNS topic ## Code After: '''A custom rq worker class to add start & stop SNS messages to all jobs''' import logging from rq.worker import Worker from harvester.sns_message import publish_to_harvesting logger = logging.getLogger(__name__) def exception_to_sns(job, *exc_info): '''Make an exception handler to report exceptions to SNS msg queue''' subject = 'FAILED: job {}'.format(job.description) message = 'ERROR: job {} failed\n{}'.format( job.description, exc_info[1]) logging.error(message) publish_to_harvesting(subject, message) class SNSWorker(Worker): def execute_job(self, job, queue): """Spawns a work horse to perform the actual work and passes it a job. The worker will wait for the work horse and make sure it executes within the given timeout bounds, or will end the work horse with SIGALRM. """ worker_name = (self.key.rsplit(':', 1)[1]).rsplit('.', 1)[0] subject = 'Worker {} starting job {}'.format( worker_name, job.description) #publish_to_harvesting(subject, subject) self.set_state('busy') self.fork_work_horse(job, queue) self.monitor_work_horse(job) subject = 'Worker {} finished job {}'.format( worker_name, job.description) #publish_to_harvesting(subject, subject) self.set_state('idle')
e27088976467dd95ad2672123cb39dd54b78f413
blog/models.py
blog/models.py
from django.db import models from django.template.defaultfilters import slugify from django.core.urlresolvers import reverse_lazy class Category(models.Model): title = models.CharField(max_length=80) class Meta: verbose_name_plural = 'categories' def __unicode__(self): return self.title class Post(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(editable=False, unique=True) image = models.ImageField(upload_to='posts', blank=True, null=False) created_on = models.DateTimeField(auto_now_add=True) content = models.TextField() categories = models.ManyToManyField(Category) class Meta: ordering = ('created_on',) def __unicode__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Post, self).save(*args, **kwargs) def get_absolute_url(self): return reverse_lazy('blog:show_post', kwargs={'slug': self.slug})
from django.db import models from django.core.exceptions import ValidationError from django.template.defaultfilters import slugify from django.core.urlresolvers import reverse_lazy def validate_no_commas(value): if ',' in value: raise ValidationError('%s contains commas' % value) class Category(models.Model): title = models.CharField(max_length=80, validators=[validate_no_commas]) class Meta: verbose_name_plural = 'categories' def __unicode__(self): return self.title class Post(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(editable=False, unique=True) image = models.ImageField(upload_to='posts', blank=True, null=False) created_on = models.DateTimeField(auto_now_add=True) content = models.TextField() categories = models.ManyToManyField(Category) class Meta: ordering = ('created_on',) def __unicode__(self): return self.title def save(self, *args, **kwargs): self.slug = self.get_slug() super(Post, self).save(*args, **kwargs) def get_slug(self): return self.slug or slugify(self.title) def get_absolute_url(self): return reverse_lazy('blog:show_post', kwargs={'slug': self.slug})
Add validation in category and get_slug in post
Add validation in category and get_slug in post
Python
mit
jmcomets/jmcomets.github.io
from django.db import models + from django.core.exceptions import ValidationError from django.template.defaultfilters import slugify from django.core.urlresolvers import reverse_lazy + def validate_no_commas(value): + if ',' in value: + raise ValidationError('%s contains commas' % value) + class Category(models.Model): - title = models.CharField(max_length=80) + title = models.CharField(max_length=80, validators=[validate_no_commas]) class Meta: verbose_name_plural = 'categories' def __unicode__(self): return self.title class Post(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(editable=False, unique=True) image = models.ImageField(upload_to='posts', blank=True, null=False) created_on = models.DateTimeField(auto_now_add=True) content = models.TextField() categories = models.ManyToManyField(Category) class Meta: ordering = ('created_on',) def __unicode__(self): return self.title def save(self, *args, **kwargs): - self.slug = slugify(self.title) + self.slug = self.get_slug() super(Post, self).save(*args, **kwargs) + + def get_slug(self): + return self.slug or slugify(self.title) def get_absolute_url(self): return reverse_lazy('blog:show_post', kwargs={'slug': self.slug})
Add validation in category and get_slug in post
## Code Before: from django.db import models from django.template.defaultfilters import slugify from django.core.urlresolvers import reverse_lazy class Category(models.Model): title = models.CharField(max_length=80) class Meta: verbose_name_plural = 'categories' def __unicode__(self): return self.title class Post(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(editable=False, unique=True) image = models.ImageField(upload_to='posts', blank=True, null=False) created_on = models.DateTimeField(auto_now_add=True) content = models.TextField() categories = models.ManyToManyField(Category) class Meta: ordering = ('created_on',) def __unicode__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Post, self).save(*args, **kwargs) def get_absolute_url(self): return reverse_lazy('blog:show_post', kwargs={'slug': self.slug}) ## Instruction: Add validation in category and get_slug in post ## Code After: from django.db import models from django.core.exceptions import ValidationError from django.template.defaultfilters import slugify from django.core.urlresolvers import reverse_lazy def validate_no_commas(value): if ',' in value: raise ValidationError('%s contains commas' % value) class Category(models.Model): title = models.CharField(max_length=80, validators=[validate_no_commas]) class Meta: verbose_name_plural = 'categories' def __unicode__(self): return self.title class Post(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(editable=False, unique=True) image = models.ImageField(upload_to='posts', blank=True, null=False) created_on = models.DateTimeField(auto_now_add=True) content = models.TextField() categories = models.ManyToManyField(Category) class Meta: ordering = ('created_on',) def __unicode__(self): return self.title def save(self, *args, **kwargs): self.slug = self.get_slug() super(Post, self).save(*args, **kwargs) def get_slug(self): return self.slug or slugify(self.title) def get_absolute_url(self): return reverse_lazy('blog:show_post', kwargs={'slug': self.slug})
eff3195097e9599b87f5cec9bbae744b91ae16cf
buses/utils.py
buses/utils.py
import re def minify(template_source): template_source = re.sub(r'(\n *)+', '\n', template_source) template_source = re.sub(r'({%.+%})\n+', r'\1', template_source) return template_source
import re from haystack.utils import default_get_identifier def minify(template_source): template_source = re.sub(r'(\n *)+', '\n', template_source) template_source = re.sub(r'({%.+%})\n+', r'\1', template_source) return template_source def get_identifier(obj_or_string): if isinstance(obj_or_string, basestring): return obj_or_string return default_get_identifier(obj_or_string)
Add custom Hastack get_identifier function
Add custom Hastack get_identifier function
Python
mpl-2.0
jclgoodwin/bustimes.org.uk,jclgoodwin/bustimes.org.uk,stev-0/bustimes.org.uk,stev-0/bustimes.org.uk,stev-0/bustimes.org.uk,stev-0/bustimes.org.uk,stev-0/bustimes.org.uk,jclgoodwin/bustimes.org.uk,jclgoodwin/bustimes.org.uk
import re + from haystack.utils import default_get_identifier def minify(template_source): template_source = re.sub(r'(\n *)+', '\n', template_source) template_source = re.sub(r'({%.+%})\n+', r'\1', template_source) return template_source + def get_identifier(obj_or_string): + if isinstance(obj_or_string, basestring): + return obj_or_string + return default_get_identifier(obj_or_string) +
Add custom Hastack get_identifier function
## Code Before: import re def minify(template_source): template_source = re.sub(r'(\n *)+', '\n', template_source) template_source = re.sub(r'({%.+%})\n+', r'\1', template_source) return template_source ## Instruction: Add custom Hastack get_identifier function ## Code After: import re from haystack.utils import default_get_identifier def minify(template_source): template_source = re.sub(r'(\n *)+', '\n', template_source) template_source = re.sub(r'({%.+%})\n+', r'\1', template_source) return template_source def get_identifier(obj_or_string): if isinstance(obj_or_string, basestring): return obj_or_string return default_get_identifier(obj_or_string)
b9a7289c1f3466bb0caee1488a16dafbae327c6f
tartpy/eventloop.py
tartpy/eventloop.py
import queue import sched import threading import time from .singleton import Singleton class EventLoop(object, metaclass=Singleton): """A generic event loop object.""" def __init__(self): self.scheduler = sched.scheduler() def schedule(self, event): """Schedule an event. An `event` is a thunk. """ self.scheduler.enter(0, 1, event) def stop(self): """Stop the loop.""" pass def run(self, block=False): self.scheduler.run(blocking=block) def run_in_thread(self): self.thread = threading.Thread(target=self.run, args=(True,), name='event_loop') self.thread.daemon = True self.thread.start()
import queue import sched import threading import time from .singleton import Singleton class EventLoop(object, metaclass=Singleton): """A generic event loop object.""" def __init__(self): self.scheduler = sched.scheduler() def schedule(self, event): """Schedule an event. An `event` is a thunk. """ self.scheduler.enter(0, 1, event) def stop(self): """Stop the loop.""" pass def run(self, block=False): self.scheduler.run(blocking=block) def run_forever(self, wait=0.05): while True: self.run() time.sleep(wait) def run_in_thread(self): self.thread = threading.Thread(target=self.run_forever, name='event_loop') self.thread.daemon = True self.thread.start()
Fix threaded run of the new event loop
Fix threaded run of the new event loop
Python
mit
waltermoreira/tartpy
import queue import sched import threading import time from .singleton import Singleton class EventLoop(object, metaclass=Singleton): """A generic event loop object.""" def __init__(self): self.scheduler = sched.scheduler() def schedule(self, event): """Schedule an event. An `event` is a thunk. """ self.scheduler.enter(0, 1, event) def stop(self): """Stop the loop.""" pass def run(self, block=False): self.scheduler.run(blocking=block) + def run_forever(self, wait=0.05): + while True: + self.run() + time.sleep(wait) + def run_in_thread(self): - self.thread = threading.Thread(target=self.run, args=(True,), + self.thread = threading.Thread(target=self.run_forever, name='event_loop') self.thread.daemon = True self.thread.start()
Fix threaded run of the new event loop
## Code Before: import queue import sched import threading import time from .singleton import Singleton class EventLoop(object, metaclass=Singleton): """A generic event loop object.""" def __init__(self): self.scheduler = sched.scheduler() def schedule(self, event): """Schedule an event. An `event` is a thunk. """ self.scheduler.enter(0, 1, event) def stop(self): """Stop the loop.""" pass def run(self, block=False): self.scheduler.run(blocking=block) def run_in_thread(self): self.thread = threading.Thread(target=self.run, args=(True,), name='event_loop') self.thread.daemon = True self.thread.start() ## Instruction: Fix threaded run of the new event loop ## Code After: import queue import sched import threading import time from .singleton import Singleton class EventLoop(object, metaclass=Singleton): """A generic event loop object.""" def __init__(self): self.scheduler = sched.scheduler() def schedule(self, event): """Schedule an event. An `event` is a thunk. """ self.scheduler.enter(0, 1, event) def stop(self): """Stop the loop.""" pass def run(self, block=False): self.scheduler.run(blocking=block) def run_forever(self, wait=0.05): while True: self.run() time.sleep(wait) def run_in_thread(self): self.thread = threading.Thread(target=self.run_forever, name='event_loop') self.thread.daemon = True self.thread.start()
3409aa543b4f0a4c574afd7ff4fdd59d1bd8a4b0
tests/date_tests.py
tests/date_tests.py
__version__ = '$Id$' from tests.utils import unittest from pywikibot import date class TestDate(unittest.TestCase): """Test cases for date library""" def __init__(self, formatname): super(TestDate, self).__init__() self.formatname = formatname def testMapEntry(self, formatname): """The test ported from date.py""" step = 1 if formatname in date.decadeFormats: step = 10 predicate, start, stop = date.formatLimits[formatname] for code, convFunc in date.formats[formatname].items(): for value in range(start, stop, step): self.assertTrue( predicate(value), "date.formats['%(formatname)s']['%(code)s']:\n" "invalid value %(value)d" % locals()) newValue = convFunc(convFunc(value)) self.assertEqual( newValue, value, "date.formats['%(formatname)s']['%(code)s']:\n" "value %(newValue)d does not match %(value)s" % locals()) def runTest(self): """method called by unittest""" self.testMapEntry(self.formatname) def suite(): """Setup the test suite and register all test to different instances""" suite = unittest.TestSuite() suite.addTests(TestDate(formatname) for formatname in date.formats) return suite if __name__ == '__main__': try: unittest.TextTestRunner().run(suite()) except SystemExit: pass
__version__ = '$Id$' from tests.utils import unittest from pywikibot import date class TestDate(unittest.TestCase): """Test cases for date library""" def testMapEntry(self): """Test the validity of the pywikibot.date format maps.""" for formatName in date.formats: step = 1 if formatName in date.decadeFormats: step = 10 predicate, start, stop = date.formatLimits[formatName] for code, convFunc in date.formats[formatName].items(): for value in range(start, stop, step): self.assertTrue( predicate(value), "date.formats['%(formatName)s']['%(code)s']:\n" "invalid value %(value)d" % locals()) newValue = convFunc(convFunc(value)) self.assertEqual( newValue, value, "date.formats['%(formatName)s']['%(code)s']:\n" "value %(newValue)d does not match %(value)s" % locals()) if __name__ == '__main__': try: unittest.main() except SystemExit: pass
Revert "Progressing dots to show test is running"
Revert "Progressing dots to show test is running" Breaks tests; https://travis-ci.org/wikimedia/pywikibot-core/builds/26752150 This reverts commit 93379dbf499c58438917728b74862f282c15dba4. Change-Id: Iacb4cc9e6999d265b46c558ed3999c1198f87de0
Python
mit
hasteur/g13bot_tools_new,smalyshev/pywikibot-core,h4ck3rm1k3/pywikibot-core,TridevGuha/pywikibot-core,npdoty/pywikibot,icyflame/batman,valhallasw/pywikibot-core,darthbhyrava/pywikibot-local,hasteur/g13bot_tools_new,xZise/pywikibot-core,npdoty/pywikibot,magul/pywikibot-core,happy5214/pywikibot-core,VcamX/pywikibot-core,h4ck3rm1k3/pywikibot-core,happy5214/pywikibot-core,jayvdb/pywikibot-core,Darkdadaah/pywikibot-core,Darkdadaah/pywikibot-core,hasteur/g13bot_tools_new,emijrp/pywikibot-core,wikimedia/pywikibot-core,jayvdb/pywikibot-core,trishnaguha/pywikibot-core,PersianWikipedia/pywikibot-core,magul/pywikibot-core,wikimedia/pywikibot-core
__version__ = '$Id$' from tests.utils import unittest from pywikibot import date class TestDate(unittest.TestCase): """Test cases for date library""" - def __init__(self, formatname): - super(TestDate, self).__init__() - self.formatname = formatname + def testMapEntry(self): + """Test the validity of the pywikibot.date format maps.""" + for formatName in date.formats: + step = 1 + if formatName in date.decadeFormats: + step = 10 + predicate, start, stop = date.formatLimits[formatName] - def testMapEntry(self, formatname): - """The test ported from date.py""" - step = 1 - if formatname in date.decadeFormats: - step = 10 - predicate, start, stop = date.formatLimits[formatname] + for code, convFunc in date.formats[formatName].items(): + for value in range(start, stop, step): + self.assertTrue( + predicate(value), + "date.formats['%(formatName)s']['%(code)s']:\n" + "invalid value %(value)d" % locals()) - for code, convFunc in date.formats[formatname].items(): - for value in range(start, stop, step): - self.assertTrue( - predicate(value), - "date.formats['%(formatname)s']['%(code)s']:\n" - "invalid value %(value)d" % locals()) - - newValue = convFunc(convFunc(value)) + newValue = convFunc(convFunc(value)) - self.assertEqual( + self.assertEqual( - newValue, value, + newValue, value, - "date.formats['%(formatname)s']['%(code)s']:\n" + "date.formats['%(formatName)s']['%(code)s']:\n" - "value %(newValue)d does not match %(value)s" + "value %(newValue)d does not match %(value)s" - % locals()) + % locals()) - - def runTest(self): - """method called by unittest""" - self.testMapEntry(self.formatname) - - - def suite(): - """Setup the test suite and register all test to different instances""" - suite = unittest.TestSuite() - suite.addTests(TestDate(formatname) for formatname in date.formats) - return suite if __name__ == '__main__': try: - unittest.TextTestRunner().run(suite()) + unittest.main() except SystemExit: pass
Revert "Progressing dots to show test is running"
## Code Before: __version__ = '$Id$' from tests.utils import unittest from pywikibot import date class TestDate(unittest.TestCase): """Test cases for date library""" def __init__(self, formatname): super(TestDate, self).__init__() self.formatname = formatname def testMapEntry(self, formatname): """The test ported from date.py""" step = 1 if formatname in date.decadeFormats: step = 10 predicate, start, stop = date.formatLimits[formatname] for code, convFunc in date.formats[formatname].items(): for value in range(start, stop, step): self.assertTrue( predicate(value), "date.formats['%(formatname)s']['%(code)s']:\n" "invalid value %(value)d" % locals()) newValue = convFunc(convFunc(value)) self.assertEqual( newValue, value, "date.formats['%(formatname)s']['%(code)s']:\n" "value %(newValue)d does not match %(value)s" % locals()) def runTest(self): """method called by unittest""" self.testMapEntry(self.formatname) def suite(): """Setup the test suite and register all test to different instances""" suite = unittest.TestSuite() suite.addTests(TestDate(formatname) for formatname in date.formats) return suite if __name__ == '__main__': try: unittest.TextTestRunner().run(suite()) except SystemExit: pass ## Instruction: Revert "Progressing dots to show test is running" ## Code After: __version__ = '$Id$' from tests.utils import unittest from pywikibot import date class TestDate(unittest.TestCase): """Test cases for date library""" def testMapEntry(self): """Test the validity of the pywikibot.date format maps.""" for formatName in date.formats: step = 1 if formatName in date.decadeFormats: step = 10 predicate, start, stop = date.formatLimits[formatName] for code, convFunc in date.formats[formatName].items(): for value in range(start, stop, step): self.assertTrue( predicate(value), "date.formats['%(formatName)s']['%(code)s']:\n" "invalid value %(value)d" % locals()) newValue = convFunc(convFunc(value)) self.assertEqual( newValue, value, "date.formats['%(formatName)s']['%(code)s']:\n" "value %(newValue)d does not match %(value)s" % locals()) if __name__ == '__main__': try: unittest.main() except SystemExit: pass
9fbef73081b0cb608e32c91a57502aaefa0599cc
tests/test_basic.py
tests/test_basic.py
import unittest import os, sys PROJECT_ROOT = os.path.dirname(__file__) sys.path.append(os.path.join(PROJECT_ROOT, "..")) from CodeConverter import CodeConverter class TestBasic(unittest.TestCase): def setUp(self): pass def test_initialize(self): self.assertEqual(CodeConverter('foo').s, 'foo') if __name__ == '__main__': unittest.main()
import unittest import os, sys PROJECT_ROOT = os.path.dirname(__file__) sys.path.append(os.path.join(PROJECT_ROOT, "..")) from CodeConverter import CodeConverter class TestBasic(unittest.TestCase): def setUp(self): pass def test_initialize(self): self.assertEqual(CodeConverter('foo').s, 'foo') # def test_python_version(self): # # Python for Sublime Text 2 is 2.6.7 (r267:88850, Oct 11 2012, 20:15:00) # if sys.version_info[:3] != (2, 6, 7): # print 'Sublime Text 2 uses python 2.6.7' # print 'Your version is ' + '.'.join(str(x) for x in sys.version_info[:3]) # self.assertTrue(True) if __name__ == '__main__': unittest.main()
Add test to check python version
Add test to check python version
Python
mit
kyamaguchi/SublimeObjC2RubyMotion,kyamaguchi/SublimeObjC2RubyMotion
import unittest import os, sys PROJECT_ROOT = os.path.dirname(__file__) sys.path.append(os.path.join(PROJECT_ROOT, "..")) from CodeConverter import CodeConverter class TestBasic(unittest.TestCase): def setUp(self): pass def test_initialize(self): self.assertEqual(CodeConverter('foo').s, 'foo') + # def test_python_version(self): + # # Python for Sublime Text 2 is 2.6.7 (r267:88850, Oct 11 2012, 20:15:00) + # if sys.version_info[:3] != (2, 6, 7): + # print 'Sublime Text 2 uses python 2.6.7' + # print 'Your version is ' + '.'.join(str(x) for x in sys.version_info[:3]) + # self.assertTrue(True) + if __name__ == '__main__': unittest.main()
Add test to check python version
## Code Before: import unittest import os, sys PROJECT_ROOT = os.path.dirname(__file__) sys.path.append(os.path.join(PROJECT_ROOT, "..")) from CodeConverter import CodeConverter class TestBasic(unittest.TestCase): def setUp(self): pass def test_initialize(self): self.assertEqual(CodeConverter('foo').s, 'foo') if __name__ == '__main__': unittest.main() ## Instruction: Add test to check python version ## Code After: import unittest import os, sys PROJECT_ROOT = os.path.dirname(__file__) sys.path.append(os.path.join(PROJECT_ROOT, "..")) from CodeConverter import CodeConverter class TestBasic(unittest.TestCase): def setUp(self): pass def test_initialize(self): self.assertEqual(CodeConverter('foo').s, 'foo') # def test_python_version(self): # # Python for Sublime Text 2 is 2.6.7 (r267:88850, Oct 11 2012, 20:15:00) # if sys.version_info[:3] != (2, 6, 7): # print 'Sublime Text 2 uses python 2.6.7' # print 'Your version is ' + '.'.join(str(x) for x in sys.version_info[:3]) # self.assertTrue(True) if __name__ == '__main__': unittest.main()
741db5b16922ceca0c23a95caa143f9ff7baeee2
Api/app/types.py
Api/app/types.py
import graphene from graphene_django import DjangoObjectType from app import models class TagType(DjangoObjectType): class Meta: model = models.Tag interfaces = (graphene.relay.Node,) @classmethod def get_node(cls, id, context, info): return models.Tag.objects.get(pk=id) class TagConnection(graphene.relay.Connection): class Meta: node = TagType class ArticleType(DjangoObjectType): class Meta: model = models.Article interfaces = (graphene.relay.Node,) tags = graphene.relay.ConnectionField(TagConnection) @classmethod def get_node(cls, id, context, info): return models.Article.objects.get(pk=id) @graphene.resolve_only_args def resolve_tags(self): return self.tags.all()
import graphene from graphene_django import DjangoObjectType from graphene_django.filter import DjangoFilterConnectionField from app import models class TagType(DjangoObjectType): class Meta: model = models.Tag interfaces = (graphene.relay.Node,) articles = DjangoFilterConnectionField(lambda: ArticleType) @classmethod def get_node(cls, id, context, info): return models.Tag.objects.get(pk=id) class ArticleType(DjangoObjectType): class Meta: model = models.Article interfaces = (graphene.relay.Node,) tags = DjangoFilterConnectionField(lambda: TagType) @classmethod def get_node(cls, id, context, info): return models.Article.objects.get(pk=id)
Fix tag and article connections
Fix tag and article connections
Python
mit
rcatlin/ryancatlin-info,rcatlin/ryancatlin-info,rcatlin/ryancatlin-info,rcatlin/ryancatlin-info
import graphene from graphene_django import DjangoObjectType + from graphene_django.filter import DjangoFilterConnectionField from app import models - class TagType(DjangoObjectType): class Meta: model = models.Tag interfaces = (graphene.relay.Node,) + articles = DjangoFilterConnectionField(lambda: ArticleType) + @classmethod def get_node(cls, id, context, info): return models.Tag.objects.get(pk=id) - - - class TagConnection(graphene.relay.Connection): - class Meta: - node = TagType class ArticleType(DjangoObjectType): class Meta: model = models.Article interfaces = (graphene.relay.Node,) - tags = graphene.relay.ConnectionField(TagConnection) + tags = DjangoFilterConnectionField(lambda: TagType) @classmethod def get_node(cls, id, context, info): return models.Article.objects.get(pk=id) - @graphene.resolve_only_args - def resolve_tags(self): - return self.tags.all()
Fix tag and article connections
## Code Before: import graphene from graphene_django import DjangoObjectType from app import models class TagType(DjangoObjectType): class Meta: model = models.Tag interfaces = (graphene.relay.Node,) @classmethod def get_node(cls, id, context, info): return models.Tag.objects.get(pk=id) class TagConnection(graphene.relay.Connection): class Meta: node = TagType class ArticleType(DjangoObjectType): class Meta: model = models.Article interfaces = (graphene.relay.Node,) tags = graphene.relay.ConnectionField(TagConnection) @classmethod def get_node(cls, id, context, info): return models.Article.objects.get(pk=id) @graphene.resolve_only_args def resolve_tags(self): return self.tags.all() ## Instruction: Fix tag and article connections ## Code After: import graphene from graphene_django import DjangoObjectType from graphene_django.filter import DjangoFilterConnectionField from app import models class TagType(DjangoObjectType): class Meta: model = models.Tag interfaces = (graphene.relay.Node,) articles = DjangoFilterConnectionField(lambda: ArticleType) @classmethod def get_node(cls, id, context, info): return models.Tag.objects.get(pk=id) class ArticleType(DjangoObjectType): class Meta: model = models.Article interfaces = (graphene.relay.Node,) tags = DjangoFilterConnectionField(lambda: TagType) @classmethod def get_node(cls, id, context, info): return models.Article.objects.get(pk=id)
d7d2361bb27c8649e38b61b65ba193e5ea716ed5
blog/posts/helpers.py
blog/posts/helpers.py
from models import Post def get_post_url(post): post_year = str(post.publication_date.year) post_month = '%02d' % post.publication_date.month post_title = post.title url = u'/blog/' + post_year + '/' + post_month + '/' + post_title + '/' return url def post_as_components(post_text): ''' This function returns the components of a blog post for use with other functions. Given a Markdown formatted post, it returns a three-tuple. The first element is the blog title (not markdowned), the second is the first paragraph (in Markdown format) and the third is the entire post body (in Markdown format). ''' post_content = post_text.split('\n\n') title = post_content[0].strip('# ') first_para = post_content[1] body = u'\n\n'.join(post_content[1:]) return (title, first_para, body)
from models import Post from django.core.urlresolvers import reverse def get_post_url(post): post_year = str(post.publication_date.year) post_month = '%02d' % post.publication_date.month post_title = post.title #url = u'/blog/' + post_year + '/' + post_month + '/' + post_title + '/' url = reverse('blog_post', kwargs={'post_year': post_year, 'post_month': post_month, 'post_title': post_title}) return url def post_as_components(post_text): ''' This function returns the components of a blog post for use with other functions. Given a Markdown formatted post, it returns a three-tuple. The first element is the blog title (not markdowned), the second is the first paragraph (in Markdown format) and the third is the entire post body (in Markdown format). ''' post_content = post_text.split('\n\n') title = post_content[0].strip('# ') first_para = post_content[1] body = u'\n\n'.join(post_content[1:]) return (title, first_para, body)
Use named urls for get_post_url().
Use named urls for get_post_url(). The helper should not assume knowledge of the post url structure.
Python
mit
Lukasa/minimalog
from models import Post + from django.core.urlresolvers import reverse def get_post_url(post): post_year = str(post.publication_date.year) post_month = '%02d' % post.publication_date.month post_title = post.title - url = u'/blog/' + post_year + '/' + post_month + '/' + post_title + '/' + #url = u'/blog/' + post_year + '/' + post_month + '/' + post_title + '/' + url = reverse('blog_post', kwargs={'post_year': post_year, + 'post_month': post_month, + 'post_title': post_title}) return url def post_as_components(post_text): ''' This function returns the components of a blog post for use with other functions. Given a Markdown formatted post, it returns a three-tuple. The first element is the blog title (not markdowned), the second is the first paragraph (in Markdown format) and the third is the entire post body (in Markdown format). ''' post_content = post_text.split('\n\n') title = post_content[0].strip('# ') first_para = post_content[1] body = u'\n\n'.join(post_content[1:]) return (title, first_para, body)
Use named urls for get_post_url().
## Code Before: from models import Post def get_post_url(post): post_year = str(post.publication_date.year) post_month = '%02d' % post.publication_date.month post_title = post.title url = u'/blog/' + post_year + '/' + post_month + '/' + post_title + '/' return url def post_as_components(post_text): ''' This function returns the components of a blog post for use with other functions. Given a Markdown formatted post, it returns a three-tuple. The first element is the blog title (not markdowned), the second is the first paragraph (in Markdown format) and the third is the entire post body (in Markdown format). ''' post_content = post_text.split('\n\n') title = post_content[0].strip('# ') first_para = post_content[1] body = u'\n\n'.join(post_content[1:]) return (title, first_para, body) ## Instruction: Use named urls for get_post_url(). ## Code After: from models import Post from django.core.urlresolvers import reverse def get_post_url(post): post_year = str(post.publication_date.year) post_month = '%02d' % post.publication_date.month post_title = post.title #url = u'/blog/' + post_year + '/' + post_month + '/' + post_title + '/' url = reverse('blog_post', kwargs={'post_year': post_year, 'post_month': post_month, 'post_title': post_title}) return url def post_as_components(post_text): ''' This function returns the components of a blog post for use with other functions. Given a Markdown formatted post, it returns a three-tuple. The first element is the blog title (not markdowned), the second is the first paragraph (in Markdown format) and the third is the entire post body (in Markdown format). ''' post_content = post_text.split('\n\n') title = post_content[0].strip('# ') first_para = post_content[1] body = u'\n\n'.join(post_content[1:]) return (title, first_para, body)
77a6bb72318e9b02cbb1179cbbbacd3dd0bad55f
bookstore/__init__.py
bookstore/__init__.py
'''Bookstore Stores IPython notebooks automagically onto OpenStack clouds through Swift. ''' __title__ = 'bookstore' __version__ = '1.0.0' __build__ = 0x010000 __author__ = 'Kyle Kelley' __license__ = 'Apache 2.0' __copyright__ = 'Copyright 2013 Kyle Kelley' from . import swift from . import cloudfiles
'''Bookstore Stores IPython notebooks automagically onto OpenStack clouds through Swift. ''' __title__ = 'bookstore' __version__ = '1.0.0' __build__ = 0x010000 __author__ = 'Kyle Kelley' __license__ = 'Apache 2.0' __copyright__ = 'Copyright 2013 Kyle Kelley' #from . import swift #from . import cloudfiles from . import filenotebookmanager
Add unit test for bookstore
Add unit test for bookstore
Python
apache-2.0
wusung/ipython-notebook-store
'''Bookstore Stores IPython notebooks automagically onto OpenStack clouds through Swift. ''' __title__ = 'bookstore' __version__ = '1.0.0' __build__ = 0x010000 __author__ = 'Kyle Kelley' __license__ = 'Apache 2.0' __copyright__ = 'Copyright 2013 Kyle Kelley' - from . import swift + #from . import swift - from . import cloudfiles + #from . import cloudfiles + from . import filenotebookmanager
Add unit test for bookstore
## Code Before: '''Bookstore Stores IPython notebooks automagically onto OpenStack clouds through Swift. ''' __title__ = 'bookstore' __version__ = '1.0.0' __build__ = 0x010000 __author__ = 'Kyle Kelley' __license__ = 'Apache 2.0' __copyright__ = 'Copyright 2013 Kyle Kelley' from . import swift from . import cloudfiles ## Instruction: Add unit test for bookstore ## Code After: '''Bookstore Stores IPython notebooks automagically onto OpenStack clouds through Swift. ''' __title__ = 'bookstore' __version__ = '1.0.0' __build__ = 0x010000 __author__ = 'Kyle Kelley' __license__ = 'Apache 2.0' __copyright__ = 'Copyright 2013 Kyle Kelley' #from . import swift #from . import cloudfiles from . import filenotebookmanager
a1b4afc062b246dc347526202ef00a43992afa28
code/kmeans.py
code/kmeans.py
def distance(X, Y): d = 0 for row in range(len(X)): for col in range(len(X[row]): if X[row][col] != Y[row][col]: d += 1 return d #partitions the data into the sets closest to each centroid def fit(data, centroids): pass #returns k centroids which partition the data optimally into k clusters def cluster(data, k): pass #allows the user to assign character names to each centroid given def label(centroids): pass
from random import randint from copy import deepcopy from parse import parse #In this file, I am assuming that the 6 metadata entries at the front of each # raw data point hae been stripped off during initial parsing. #returns the distance between two data points def distance(X, Y): assert(len(X) == len(Y)) d = 0 for pixel in range(len(X)): if X[pixel] != Y[pixel]: d += 1 return d #Intelligently find some starting centroids, instead of choosing k random points. # Choose one random point to start with, then find the point with largest # sum of distances from all other centroids selected so far and make it a centroid # until k have been chosen. def find_initial_centroids(data, k): assert(len(data) >= k) data = deepcopy(data) centroids = [] i = randint(0, len(data - 1)) if k > 0: centroids.append(data[i]) while (len(centroids) < k): new_i = None max_distance = None for i in range(len(data)): total_distance = 0 for c in centroids: total_distance += distance(data[i], c) if (new_i == None) or (total_distance > max_distance): new_i = i max_distance = total_distance centroids.append(data.pop(i)) return centroids #Finds the representative centroid of a subset of data, based on the most # common pixel in each position def find_centroid(data): assert(len(data) > 0) centroid = [0]*len(data[0]) for i in range(len(centroid)): sum = 0 for point in data: sum += point[i] #Assuming pixel values are either 1 or 0 if (sum / len(data)) >= .5: #If a majority of pixels have value 1 centroid[i] = 1 return centroid #partitions the data into the sets closest to each centroid def fit(data, centroids): pass #returns k centroids which partition the data optimally into k clusters def cluster(data, k): centroids = find_initial_centroids(data, k)
Add helper to find representative centroid of a subset of data, add helper to generate initial k centroid intelligently
Add helper to find representative centroid of a subset of data, add helper to generate initial k centroid intelligently
Python
mit
mkaplan218/clusterverify
+ from random import randint + from copy import deepcopy + + from parse import parse + + #In this file, I am assuming that the 6 metadata entries at the front of each + # raw data point hae been stripped off during initial parsing. + + #returns the distance between two data points + def distance(X, Y): + assert(len(X) == len(Y)) + d = 0 - for row in range(len(X)): + for pixel in range(len(X)): + if X[pixel] != Y[pixel]: - for col in range(len(X[row]): - if X[row][col] != Y[row][col]: - d += 1 + d += 1 return d + #Intelligently find some starting centroids, instead of choosing k random points. + # Choose one random point to start with, then find the point with largest + # sum of distances from all other centroids selected so far and make it a centroid + # until k have been chosen. + + def find_initial_centroids(data, k): + assert(len(data) >= k) + data = deepcopy(data) + + centroids = [] + i = randint(0, len(data - 1)) + + if k > 0: + centroids.append(data[i]) + + while (len(centroids) < k): + new_i = None + max_distance = None + for i in range(len(data)): + total_distance = 0 + for c in centroids: + total_distance += distance(data[i], c) + if (new_i == None) or (total_distance > max_distance): + new_i = i + max_distance = total_distance + centroids.append(data.pop(i)) + + return centroids + + #Finds the representative centroid of a subset of data, based on the most + # common pixel in each position + + def find_centroid(data): + assert(len(data) > 0) + + centroid = [0]*len(data[0]) + for i in range(len(centroid)): + sum = 0 + for point in data: + sum += point[i] #Assuming pixel values are either 1 or 0 + if (sum / len(data)) >= .5: #If a majority of pixels have value 1 + centroid[i] = 1 + + return centroid + #partitions the data into the sets closest to each centroid + def fit(data, centroids): pass #returns k centroids which partition the data optimally into k clusters + def cluster(data, k): - pass + centroids = find_initial_centroids(data, k) + - #allows the user to assign character names to each centroid given - def label(centroids): - pass -
Add helper to find representative centroid of a subset of data, add helper to generate initial k centroid intelligently
## Code Before: def distance(X, Y): d = 0 for row in range(len(X)): for col in range(len(X[row]): if X[row][col] != Y[row][col]: d += 1 return d #partitions the data into the sets closest to each centroid def fit(data, centroids): pass #returns k centroids which partition the data optimally into k clusters def cluster(data, k): pass #allows the user to assign character names to each centroid given def label(centroids): pass ## Instruction: Add helper to find representative centroid of a subset of data, add helper to generate initial k centroid intelligently ## Code After: from random import randint from copy import deepcopy from parse import parse #In this file, I am assuming that the 6 metadata entries at the front of each # raw data point hae been stripped off during initial parsing. #returns the distance between two data points def distance(X, Y): assert(len(X) == len(Y)) d = 0 for pixel in range(len(X)): if X[pixel] != Y[pixel]: d += 1 return d #Intelligently find some starting centroids, instead of choosing k random points. # Choose one random point to start with, then find the point with largest # sum of distances from all other centroids selected so far and make it a centroid # until k have been chosen. def find_initial_centroids(data, k): assert(len(data) >= k) data = deepcopy(data) centroids = [] i = randint(0, len(data - 1)) if k > 0: centroids.append(data[i]) while (len(centroids) < k): new_i = None max_distance = None for i in range(len(data)): total_distance = 0 for c in centroids: total_distance += distance(data[i], c) if (new_i == None) or (total_distance > max_distance): new_i = i max_distance = total_distance centroids.append(data.pop(i)) return centroids #Finds the representative centroid of a subset of data, based on the most # common pixel in each position def find_centroid(data): assert(len(data) > 0) centroid = [0]*len(data[0]) for i in range(len(centroid)): sum = 0 for point in data: sum += point[i] #Assuming pixel values are either 1 or 0 if (sum / len(data)) >= .5: #If a majority of pixels have value 1 centroid[i] = 1 return centroid #partitions the data into the sets closest to each centroid def fit(data, centroids): pass #returns k centroids which partition the data optimally into k clusters def cluster(data, k): centroids = find_initial_centroids(data, k)
cd6429cd177e550d047408cc212b64648e0cbe6c
calc_cov.py
calc_cov.py
import mne import sys from mne import compute_covariance import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from my_settings import * reject = dict(grad=4000e-13, # T / m (gradiometers) mag=4e-12, # T (magnetometers) eeg=180e-6 # ) subject = sys.argv[1] epochs = mne.read_epochs(epochs_folder + "%s_trial_start-epo.fif" % subject) epochs.drop_bad_epochs(reject) fig = epochs.plot_drop_log(subject=subject, show=False) fig.savefig(epochs_folder + "pics/%s_drop_log.png" % subject) # Make noise cov cov = compute_covariance(epochs, tmin=None, tmax=0, method="shrunk") mne.write_cov(mne_folder + "%s-cov.fif" % subject, cov)
import mne import sys from mne import compute_covariance import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from my_settings import * subject = sys.argv[1] epochs = mne.read_epochs(epochs_folder + "%s_trial_start-epo.fif" % subject) epochs.drop_bad_epochs(reject=reject_params) fig = epochs.plot_drop_log(subject=subject, show=False) fig.savefig(epochs_folder + "pics/%s_drop_log.png" % subject) # Make noise cov cov = compute_covariance(epochs, tmin=None, tmax=-0.2, method="shrunk") mne.write_cov(mne_folder + "%s-cov.fif" % subject, cov)
Clean up and change cov time
Clean up and change cov time
Python
bsd-3-clause
MadsJensen/CAA,MadsJensen/CAA
import mne import sys from mne import compute_covariance import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from my_settings import * - reject = dict(grad=4000e-13, # T / m (gradiometers) - mag=4e-12, # T (magnetometers) - eeg=180e-6 # - ) - - subject = sys.argv[1] epochs = mne.read_epochs(epochs_folder + "%s_trial_start-epo.fif" % subject) - epochs.drop_bad_epochs(reject) + epochs.drop_bad_epochs(reject=reject_params) fig = epochs.plot_drop_log(subject=subject, show=False) fig.savefig(epochs_folder + "pics/%s_drop_log.png" % subject) # Make noise cov - cov = compute_covariance(epochs, tmin=None, tmax=0, + cov = compute_covariance(epochs, tmin=None, tmax=-0.2, method="shrunk") mne.write_cov(mne_folder + "%s-cov.fif" % subject, cov) -
Clean up and change cov time
## Code Before: import mne import sys from mne import compute_covariance import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from my_settings import * reject = dict(grad=4000e-13, # T / m (gradiometers) mag=4e-12, # T (magnetometers) eeg=180e-6 # ) subject = sys.argv[1] epochs = mne.read_epochs(epochs_folder + "%s_trial_start-epo.fif" % subject) epochs.drop_bad_epochs(reject) fig = epochs.plot_drop_log(subject=subject, show=False) fig.savefig(epochs_folder + "pics/%s_drop_log.png" % subject) # Make noise cov cov = compute_covariance(epochs, tmin=None, tmax=0, method="shrunk") mne.write_cov(mne_folder + "%s-cov.fif" % subject, cov) ## Instruction: Clean up and change cov time ## Code After: import mne import sys from mne import compute_covariance import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from my_settings import * subject = sys.argv[1] epochs = mne.read_epochs(epochs_folder + "%s_trial_start-epo.fif" % subject) epochs.drop_bad_epochs(reject=reject_params) fig = epochs.plot_drop_log(subject=subject, show=False) fig.savefig(epochs_folder + "pics/%s_drop_log.png" % subject) # Make noise cov cov = compute_covariance(epochs, tmin=None, tmax=-0.2, method="shrunk") mne.write_cov(mne_folder + "%s-cov.fif" % subject, cov)
bfd34a7aaf903c823d41068173c09bc5b1a251bc
test/sasdataloader/test/utest_sesans.py
test/sasdataloader/test/utest_sesans.py
import unittest from sas.sascalc.dataloader.loader import Loader import os.path class sesans_reader(unittest.TestCase): def setUp(self): self.loader = Loader() def test_sesans_load(self): """ Test .SES file loading """ f =self.loader.load("sphere3micron.ses") # self.assertEqual(f, 5) self.assertEqual(len(f.x), 40) self.assertEqual(f.x[0], 391.56) self.assertEqual(f.x[-1], 46099) self.assertEqual(f.y[-1], -0.19956) self.assertEqual(f.x_unit, "A") self.assertEqual(f.y_unit, "A-2 cm-1") self.assertEqual(f.sample.name, "Polystyrene 2 um in 53% H2O, 47% D2O") self.assertEqual(f.sample.thickness, 0.2) self.assertEqual(f.sample.zacceptance, (0.0168, "radians")) if __name__ == "__main__": unittest.main()
import unittest from sas.sascalc.dataloader.loader import Loader import os.path class sesans_reader(unittest.TestCase): def setUp(self): self.loader = Loader() def test_sesans_load(self): """ Test .SES file loading """ f =self.loader.load("sphere3micron.ses") # self.assertEqual(f, 5) self.assertEqual(len(f.x), 40) self.assertEqual(f.x[0], 391.56) self.assertEqual(f.x[-1], 46099) self.assertEqual(f.y[-1], -0.19956) self.assertEqual(f.x_unit, "A") self.assertEqual(f.y_unit, "A-2 cm-1") self.assertEqual(f.sample.name, "Polystyrene 2 um in 53% H2O, 47% D2O") self.assertEqual(f.sample.thickness, 0.2) self.assertEqual(f.sample.zacceptance, (0.0168, "radians")) self.assertEqual(f.isSesans, True) if __name__ == "__main__": unittest.main()
Test that .SES files are tagged as Sesans
Test that .SES files are tagged as Sesans
Python
bsd-3-clause
lewisodriscoll/sasview,lewisodriscoll/sasview,SasView/sasview,lewisodriscoll/sasview,SasView/sasview,SasView/sasview,SasView/sasview,lewisodriscoll/sasview,SasView/sasview,SasView/sasview,lewisodriscoll/sasview
import unittest from sas.sascalc.dataloader.loader import Loader import os.path class sesans_reader(unittest.TestCase): def setUp(self): self.loader = Loader() def test_sesans_load(self): """ Test .SES file loading """ f =self.loader.load("sphere3micron.ses") # self.assertEqual(f, 5) self.assertEqual(len(f.x), 40) self.assertEqual(f.x[0], 391.56) self.assertEqual(f.x[-1], 46099) self.assertEqual(f.y[-1], -0.19956) self.assertEqual(f.x_unit, "A") self.assertEqual(f.y_unit, "A-2 cm-1") self.assertEqual(f.sample.name, "Polystyrene 2 um in 53% H2O, 47% D2O") self.assertEqual(f.sample.thickness, 0.2) self.assertEqual(f.sample.zacceptance, (0.0168, "radians")) + self.assertEqual(f.isSesans, True) if __name__ == "__main__": unittest.main()
Test that .SES files are tagged as Sesans
## Code Before: import unittest from sas.sascalc.dataloader.loader import Loader import os.path class sesans_reader(unittest.TestCase): def setUp(self): self.loader = Loader() def test_sesans_load(self): """ Test .SES file loading """ f =self.loader.load("sphere3micron.ses") # self.assertEqual(f, 5) self.assertEqual(len(f.x), 40) self.assertEqual(f.x[0], 391.56) self.assertEqual(f.x[-1], 46099) self.assertEqual(f.y[-1], -0.19956) self.assertEqual(f.x_unit, "A") self.assertEqual(f.y_unit, "A-2 cm-1") self.assertEqual(f.sample.name, "Polystyrene 2 um in 53% H2O, 47% D2O") self.assertEqual(f.sample.thickness, 0.2) self.assertEqual(f.sample.zacceptance, (0.0168, "radians")) if __name__ == "__main__": unittest.main() ## Instruction: Test that .SES files are tagged as Sesans ## Code After: import unittest from sas.sascalc.dataloader.loader import Loader import os.path class sesans_reader(unittest.TestCase): def setUp(self): self.loader = Loader() def test_sesans_load(self): """ Test .SES file loading """ f =self.loader.load("sphere3micron.ses") # self.assertEqual(f, 5) self.assertEqual(len(f.x), 40) self.assertEqual(f.x[0], 391.56) self.assertEqual(f.x[-1], 46099) self.assertEqual(f.y[-1], -0.19956) self.assertEqual(f.x_unit, "A") self.assertEqual(f.y_unit, "A-2 cm-1") self.assertEqual(f.sample.name, "Polystyrene 2 um in 53% H2O, 47% D2O") self.assertEqual(f.sample.thickness, 0.2) self.assertEqual(f.sample.zacceptance, (0.0168, "radians")) self.assertEqual(f.isSesans, True) if __name__ == "__main__": unittest.main()