commit
stringlengths
40
40
old_file
stringlengths
4
118
new_file
stringlengths
4
118
old_contents
stringlengths
0
2.94k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
444
message
stringlengths
16
3.45k
lang
stringclasses
1 value
license
stringclasses
13 values
repos
stringlengths
5
43.2k
prompt
stringlengths
17
4.58k
response
stringlengths
1
4.43k
prompt_tagged
stringlengths
58
4.62k
response_tagged
stringlengths
1
4.43k
text
stringlengths
132
7.29k
text_tagged
stringlengths
173
7.33k
65e6c8466482464333e77a2892fd0ac33ab5c3cb
q_and_a/apps/token_auth/views.py
q_and_a/apps/token_auth/views.py
from django.views.generic import RedirectView from django.views.generic.detail import SingleObjectMixin from django.contrib.auth import login, authenticate, login from django.core.exceptions import PermissionDenied from django.core.urlresolvers import reverse class BaseAuthView(SingleObjectMixin, RedirectView): def get_redirect_url(self, *args, **kwargs): if not self.request.user.is_authenticated() \ and not hasattr(self.request.user, 'organisation_id'): auth_user = authenticate(auth_token=self.kwargs['token']) if not auth_user: raise PermissionDenied() login(self.request, auth_user) return reverse('organisation_questions')
from django.views.generic import RedirectView from django.views.generic.detail import SingleObjectMixin from django.contrib.auth import login, authenticate from django.core.exceptions import PermissionDenied from django.core.urlresolvers import reverse class BaseAuthView(SingleObjectMixin, RedirectView): def get_redirect_url(self, *args, **kwargs): if (not self.request.user.is_authenticated() and not hasattr(self.request.user, 'organisation_id')): auth_user = authenticate(auth_token=self.kwargs['token']) if not auth_user: raise PermissionDenied() login(self.request, auth_user) return reverse('organisation_questions')
Fix indent, PEP-8 style and remove dup import.
Fix indent, PEP-8 style and remove dup import.
Python
bsd-3-clause
DemocracyClub/candidate_questions,DemocracyClub/candidate_questions,DemocracyClub/candidate_questions
from django.views.generic import RedirectView from django.views.generic.detail import SingleObjectMixin from django.contrib.auth import login, authenticate, login from django.core.exceptions import PermissionDenied from django.core.urlresolvers import reverse class BaseAuthView(SingleObjectMixin, RedirectView): def get_redirect_url(self, *args, **kwargs): if not self.request.user.is_authenticated() \ and not hasattr(self.request.user, 'organisation_id'): auth_user = authenticate(auth_token=self.kwargs['token']) if not auth_user: raise PermissionDenied() login(self.request, auth_user) return reverse('organisation_questions') Fix indent, PEP-8 style and remove dup import.
from django.views.generic import RedirectView from django.views.generic.detail import SingleObjectMixin from django.contrib.auth import login, authenticate from django.core.exceptions import PermissionDenied from django.core.urlresolvers import reverse class BaseAuthView(SingleObjectMixin, RedirectView): def get_redirect_url(self, *args, **kwargs): if (not self.request.user.is_authenticated() and not hasattr(self.request.user, 'organisation_id')): auth_user = authenticate(auth_token=self.kwargs['token']) if not auth_user: raise PermissionDenied() login(self.request, auth_user) return reverse('organisation_questions')
<commit_before>from django.views.generic import RedirectView from django.views.generic.detail import SingleObjectMixin from django.contrib.auth import login, authenticate, login from django.core.exceptions import PermissionDenied from django.core.urlresolvers import reverse class BaseAuthView(SingleObjectMixin, RedirectView): def get_redirect_url(self, *args, **kwargs): if not self.request.user.is_authenticated() \ and not hasattr(self.request.user, 'organisation_id'): auth_user = authenticate(auth_token=self.kwargs['token']) if not auth_user: raise PermissionDenied() login(self.request, auth_user) return reverse('organisation_questions') <commit_msg>Fix indent, PEP-8 style and remove dup import.<commit_after>
from django.views.generic import RedirectView from django.views.generic.detail import SingleObjectMixin from django.contrib.auth import login, authenticate from django.core.exceptions import PermissionDenied from django.core.urlresolvers import reverse class BaseAuthView(SingleObjectMixin, RedirectView): def get_redirect_url(self, *args, **kwargs): if (not self.request.user.is_authenticated() and not hasattr(self.request.user, 'organisation_id')): auth_user = authenticate(auth_token=self.kwargs['token']) if not auth_user: raise PermissionDenied() login(self.request, auth_user) return reverse('organisation_questions')
from django.views.generic import RedirectView from django.views.generic.detail import SingleObjectMixin from django.contrib.auth import login, authenticate, login from django.core.exceptions import PermissionDenied from django.core.urlresolvers import reverse class BaseAuthView(SingleObjectMixin, RedirectView): def get_redirect_url(self, *args, **kwargs): if not self.request.user.is_authenticated() \ and not hasattr(self.request.user, 'organisation_id'): auth_user = authenticate(auth_token=self.kwargs['token']) if not auth_user: raise PermissionDenied() login(self.request, auth_user) return reverse('organisation_questions') Fix indent, PEP-8 style and remove dup import.from django.views.generic import RedirectView from django.views.generic.detail import SingleObjectMixin from django.contrib.auth import login, authenticate from django.core.exceptions import PermissionDenied from django.core.urlresolvers import reverse class BaseAuthView(SingleObjectMixin, RedirectView): def get_redirect_url(self, *args, **kwargs): if (not self.request.user.is_authenticated() and not hasattr(self.request.user, 'organisation_id')): auth_user = authenticate(auth_token=self.kwargs['token']) if not auth_user: raise PermissionDenied() login(self.request, auth_user) return reverse('organisation_questions')
<commit_before>from django.views.generic import RedirectView from django.views.generic.detail import SingleObjectMixin from django.contrib.auth import login, authenticate, login from django.core.exceptions import PermissionDenied from django.core.urlresolvers import reverse class BaseAuthView(SingleObjectMixin, RedirectView): def get_redirect_url(self, *args, **kwargs): if not self.request.user.is_authenticated() \ and not hasattr(self.request.user, 'organisation_id'): auth_user = authenticate(auth_token=self.kwargs['token']) if not auth_user: raise PermissionDenied() login(self.request, auth_user) return reverse('organisation_questions') <commit_msg>Fix indent, PEP-8 style and remove dup import.<commit_after>from django.views.generic import RedirectView from django.views.generic.detail import SingleObjectMixin from django.contrib.auth import login, authenticate from django.core.exceptions import PermissionDenied from django.core.urlresolvers import reverse class BaseAuthView(SingleObjectMixin, RedirectView): def get_redirect_url(self, *args, **kwargs): if (not self.request.user.is_authenticated() and not hasattr(self.request.user, 'organisation_id')): auth_user = authenticate(auth_token=self.kwargs['token']) if not auth_user: raise PermissionDenied() login(self.request, auth_user) return reverse('organisation_questions')
1405dac9cbd7cebdc34d9cba0ca585b494f30a71
plugins/Views/WireframeView/__init__.py
plugins/Views/WireframeView/__init__.py
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from . import WireframeView from UM.i18n import i18nCatalog i18n_catalog = i18nCatalog("uranium") def getMetaData(): return { "type": "view", "plugin": { "name": i18n_catalog.i18nc("@label", "Wireframe View"), "author": "Ultimaker", "version": "1.0", "description": i18n_catalog.i18nc("@info:whatsthis", "Provides a simple wireframe view"), "api": 2 }, "view": { "name": "Wireframe", "visible": False } } def register(app): return { "view": WireframeView.WireframeView() }
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from . import WireframeView from UM.i18n import i18nCatalog i18n_catalog = i18nCatalog("uranium") def getMetaData(): return { "type": "view", "plugin": { "name": i18n_catalog.i18nc("@label", "Wireframe View"), "author": "Ultimaker", "version": "1.0", "description": i18n_catalog.i18nc("@info:whatsthis", "Provides a simple wireframe view."), "api": 2 }, "view": { "name": "Wireframe", "visible": False } } def register(app): return { "view": WireframeView.WireframeView() }
Add period at end of plug-in description
Add period at end of plug-in description This is consistent with other plug-in descriptions. Contributes to issue CURA-1190.
Python
agpl-3.0
onitake/Uranium,onitake/Uranium
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from . import WireframeView from UM.i18n import i18nCatalog i18n_catalog = i18nCatalog("uranium") def getMetaData(): return { "type": "view", "plugin": { "name": i18n_catalog.i18nc("@label", "Wireframe View"), "author": "Ultimaker", "version": "1.0", "description": i18n_catalog.i18nc("@info:whatsthis", "Provides a simple wireframe view"), "api": 2 }, "view": { "name": "Wireframe", "visible": False } } def register(app): return { "view": WireframeView.WireframeView() } Add period at end of plug-in description This is consistent with other plug-in descriptions. Contributes to issue CURA-1190.
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from . import WireframeView from UM.i18n import i18nCatalog i18n_catalog = i18nCatalog("uranium") def getMetaData(): return { "type": "view", "plugin": { "name": i18n_catalog.i18nc("@label", "Wireframe View"), "author": "Ultimaker", "version": "1.0", "description": i18n_catalog.i18nc("@info:whatsthis", "Provides a simple wireframe view."), "api": 2 }, "view": { "name": "Wireframe", "visible": False } } def register(app): return { "view": WireframeView.WireframeView() }
<commit_before># Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from . import WireframeView from UM.i18n import i18nCatalog i18n_catalog = i18nCatalog("uranium") def getMetaData(): return { "type": "view", "plugin": { "name": i18n_catalog.i18nc("@label", "Wireframe View"), "author": "Ultimaker", "version": "1.0", "description": i18n_catalog.i18nc("@info:whatsthis", "Provides a simple wireframe view"), "api": 2 }, "view": { "name": "Wireframe", "visible": False } } def register(app): return { "view": WireframeView.WireframeView() } <commit_msg>Add period at end of plug-in description This is consistent with other plug-in descriptions. Contributes to issue CURA-1190.<commit_after>
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from . import WireframeView from UM.i18n import i18nCatalog i18n_catalog = i18nCatalog("uranium") def getMetaData(): return { "type": "view", "plugin": { "name": i18n_catalog.i18nc("@label", "Wireframe View"), "author": "Ultimaker", "version": "1.0", "description": i18n_catalog.i18nc("@info:whatsthis", "Provides a simple wireframe view."), "api": 2 }, "view": { "name": "Wireframe", "visible": False } } def register(app): return { "view": WireframeView.WireframeView() }
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from . import WireframeView from UM.i18n import i18nCatalog i18n_catalog = i18nCatalog("uranium") def getMetaData(): return { "type": "view", "plugin": { "name": i18n_catalog.i18nc("@label", "Wireframe View"), "author": "Ultimaker", "version": "1.0", "description": i18n_catalog.i18nc("@info:whatsthis", "Provides a simple wireframe view"), "api": 2 }, "view": { "name": "Wireframe", "visible": False } } def register(app): return { "view": WireframeView.WireframeView() } Add period at end of plug-in description This is consistent with other plug-in descriptions. Contributes to issue CURA-1190.# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from . import WireframeView from UM.i18n import i18nCatalog i18n_catalog = i18nCatalog("uranium") def getMetaData(): return { "type": "view", "plugin": { "name": i18n_catalog.i18nc("@label", "Wireframe View"), "author": "Ultimaker", "version": "1.0", "description": i18n_catalog.i18nc("@info:whatsthis", "Provides a simple wireframe view."), "api": 2 }, "view": { "name": "Wireframe", "visible": False } } def register(app): return { "view": WireframeView.WireframeView() }
<commit_before># Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from . import WireframeView from UM.i18n import i18nCatalog i18n_catalog = i18nCatalog("uranium") def getMetaData(): return { "type": "view", "plugin": { "name": i18n_catalog.i18nc("@label", "Wireframe View"), "author": "Ultimaker", "version": "1.0", "description": i18n_catalog.i18nc("@info:whatsthis", "Provides a simple wireframe view"), "api": 2 }, "view": { "name": "Wireframe", "visible": False } } def register(app): return { "view": WireframeView.WireframeView() } <commit_msg>Add period at end of plug-in description This is consistent with other plug-in descriptions. Contributes to issue CURA-1190.<commit_after># Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from . import WireframeView from UM.i18n import i18nCatalog i18n_catalog = i18nCatalog("uranium") def getMetaData(): return { "type": "view", "plugin": { "name": i18n_catalog.i18nc("@label", "Wireframe View"), "author": "Ultimaker", "version": "1.0", "description": i18n_catalog.i18nc("@info:whatsthis", "Provides a simple wireframe view."), "api": 2 }, "view": { "name": "Wireframe", "visible": False } } def register(app): return { "view": WireframeView.WireframeView() }
a03fe14d4dba7b9a54efdebeb768551bda53e3c1
admin/common_auth/models.py
admin/common_auth/models.py
from django.db import models class AdminProfile(models.Model): user = models.OneToOneField('osf.OSFUser', related_name='admin_profile') desk_token = models.CharField(max_length=45, blank=True) desk_token_secret = models.CharField(max_length=45, blank=True) class Meta: # custom permissions for use in the OSF Admin App permissions = ( ('mark_spam', 'Can mark comments, projects and registrations as spam'), ('view_spam', 'Can view nodes, comments, and projects marked as spam'), ('view_metrics', 'Can view metrics on the OSF Admin app'), ('view_prereg', 'Can view entries for the preregistration chellenge on the admin'), ('administer_prereg', 'Can update, comment on, and approve entries to the prereg challenge'), ('view_desk', 'Can view details about Desk users'), )
from django.db import models class AdminProfile(models.Model): user = models.OneToOneField('osf.OSFUser', related_name='admin_profile') desk_token = models.CharField(max_length=45, blank=True) desk_token_secret = models.CharField(max_length=45, blank=True) def __unicode__(self): return self.user.username class Meta: # custom permissions for use in the OSF Admin App permissions = ( ('mark_spam', 'Can mark comments, projects and registrations as spam'), ('view_spam', 'Can view nodes, comments, and projects marked as spam'), ('view_metrics', 'Can view metrics on the OSF Admin app'), ('view_prereg', 'Can view entries for the preregistration chellenge on the admin'), ('administer_prereg', 'Can update, comment on, and approve entries to the prereg challenge'), ('view_desk', 'Can view details about Desk users'), )
Fix the display name of admin profile in the admin admin
Fix the display name of admin profile in the admin admin
Python
apache-2.0
HalcyonChimera/osf.io,sloria/osf.io,CenterForOpenScience/osf.io,hmoco/osf.io,sloria/osf.io,chrisseto/osf.io,caneruguz/osf.io,monikagrabowska/osf.io,CenterForOpenScience/osf.io,icereval/osf.io,icereval/osf.io,TomBaxter/osf.io,brianjgeiger/osf.io,aaxelb/osf.io,cslzchen/osf.io,felliott/osf.io,chennan47/osf.io,binoculars/osf.io,monikagrabowska/osf.io,binoculars/osf.io,crcresearch/osf.io,brianjgeiger/osf.io,Nesiehr/osf.io,leb2dg/osf.io,icereval/osf.io,HalcyonChimera/osf.io,Johnetordoff/osf.io,adlius/osf.io,Nesiehr/osf.io,leb2dg/osf.io,caseyrollins/osf.io,Johnetordoff/osf.io,cwisecarver/osf.io,pattisdr/osf.io,saradbowman/osf.io,baylee-d/osf.io,Johnetordoff/osf.io,adlius/osf.io,leb2dg/osf.io,chennan47/osf.io,monikagrabowska/osf.io,laurenrevere/osf.io,acshi/osf.io,aaxelb/osf.io,cslzchen/osf.io,caneruguz/osf.io,sloria/osf.io,laurenrevere/osf.io,adlius/osf.io,Nesiehr/osf.io,CenterForOpenScience/osf.io,caneruguz/osf.io,chrisseto/osf.io,pattisdr/osf.io,cslzchen/osf.io,brianjgeiger/osf.io,mfraezz/osf.io,acshi/osf.io,erinspace/osf.io,mattclark/osf.io,baylee-d/osf.io,chennan47/osf.io,acshi/osf.io,crcresearch/osf.io,monikagrabowska/osf.io,hmoco/osf.io,hmoco/osf.io,aaxelb/osf.io,cwisecarver/osf.io,aaxelb/osf.io,TomBaxter/osf.io,binoculars/osf.io,adlius/osf.io,felliott/osf.io,leb2dg/osf.io,HalcyonChimera/osf.io,pattisdr/osf.io,felliott/osf.io,saradbowman/osf.io,felliott/osf.io,laurenrevere/osf.io,caneruguz/osf.io,cwisecarver/osf.io,chrisseto/osf.io,acshi/osf.io,chrisseto/osf.io,acshi/osf.io,baylee-d/osf.io,mfraezz/osf.io,monikagrabowska/osf.io,cslzchen/osf.io,mfraezz/osf.io,caseyrollins/osf.io,brianjgeiger/osf.io,hmoco/osf.io,caseyrollins/osf.io,mattclark/osf.io,mfraezz/osf.io,CenterForOpenScience/osf.io,erinspace/osf.io,HalcyonChimera/osf.io,Nesiehr/osf.io,crcresearch/osf.io,mattclark/osf.io,cwisecarver/osf.io,TomBaxter/osf.io,erinspace/osf.io,Johnetordoff/osf.io
from django.db import models class AdminProfile(models.Model): user = models.OneToOneField('osf.OSFUser', related_name='admin_profile') desk_token = models.CharField(max_length=45, blank=True) desk_token_secret = models.CharField(max_length=45, blank=True) class Meta: # custom permissions for use in the OSF Admin App permissions = ( ('mark_spam', 'Can mark comments, projects and registrations as spam'), ('view_spam', 'Can view nodes, comments, and projects marked as spam'), ('view_metrics', 'Can view metrics on the OSF Admin app'), ('view_prereg', 'Can view entries for the preregistration chellenge on the admin'), ('administer_prereg', 'Can update, comment on, and approve entries to the prereg challenge'), ('view_desk', 'Can view details about Desk users'), ) Fix the display name of admin profile in the admin admin
from django.db import models class AdminProfile(models.Model): user = models.OneToOneField('osf.OSFUser', related_name='admin_profile') desk_token = models.CharField(max_length=45, blank=True) desk_token_secret = models.CharField(max_length=45, blank=True) def __unicode__(self): return self.user.username class Meta: # custom permissions for use in the OSF Admin App permissions = ( ('mark_spam', 'Can mark comments, projects and registrations as spam'), ('view_spam', 'Can view nodes, comments, and projects marked as spam'), ('view_metrics', 'Can view metrics on the OSF Admin app'), ('view_prereg', 'Can view entries for the preregistration chellenge on the admin'), ('administer_prereg', 'Can update, comment on, and approve entries to the prereg challenge'), ('view_desk', 'Can view details about Desk users'), )
<commit_before>from django.db import models class AdminProfile(models.Model): user = models.OneToOneField('osf.OSFUser', related_name='admin_profile') desk_token = models.CharField(max_length=45, blank=True) desk_token_secret = models.CharField(max_length=45, blank=True) class Meta: # custom permissions for use in the OSF Admin App permissions = ( ('mark_spam', 'Can mark comments, projects and registrations as spam'), ('view_spam', 'Can view nodes, comments, and projects marked as spam'), ('view_metrics', 'Can view metrics on the OSF Admin app'), ('view_prereg', 'Can view entries for the preregistration chellenge on the admin'), ('administer_prereg', 'Can update, comment on, and approve entries to the prereg challenge'), ('view_desk', 'Can view details about Desk users'), ) <commit_msg>Fix the display name of admin profile in the admin admin<commit_after>
from django.db import models class AdminProfile(models.Model): user = models.OneToOneField('osf.OSFUser', related_name='admin_profile') desk_token = models.CharField(max_length=45, blank=True) desk_token_secret = models.CharField(max_length=45, blank=True) def __unicode__(self): return self.user.username class Meta: # custom permissions for use in the OSF Admin App permissions = ( ('mark_spam', 'Can mark comments, projects and registrations as spam'), ('view_spam', 'Can view nodes, comments, and projects marked as spam'), ('view_metrics', 'Can view metrics on the OSF Admin app'), ('view_prereg', 'Can view entries for the preregistration chellenge on the admin'), ('administer_prereg', 'Can update, comment on, and approve entries to the prereg challenge'), ('view_desk', 'Can view details about Desk users'), )
from django.db import models class AdminProfile(models.Model): user = models.OneToOneField('osf.OSFUser', related_name='admin_profile') desk_token = models.CharField(max_length=45, blank=True) desk_token_secret = models.CharField(max_length=45, blank=True) class Meta: # custom permissions for use in the OSF Admin App permissions = ( ('mark_spam', 'Can mark comments, projects and registrations as spam'), ('view_spam', 'Can view nodes, comments, and projects marked as spam'), ('view_metrics', 'Can view metrics on the OSF Admin app'), ('view_prereg', 'Can view entries for the preregistration chellenge on the admin'), ('administer_prereg', 'Can update, comment on, and approve entries to the prereg challenge'), ('view_desk', 'Can view details about Desk users'), ) Fix the display name of admin profile in the admin adminfrom django.db import models class AdminProfile(models.Model): user = models.OneToOneField('osf.OSFUser', related_name='admin_profile') desk_token = models.CharField(max_length=45, blank=True) desk_token_secret = models.CharField(max_length=45, blank=True) def __unicode__(self): return self.user.username class Meta: # custom permissions for use in the OSF Admin App permissions = ( ('mark_spam', 'Can mark comments, projects and registrations as spam'), ('view_spam', 'Can view nodes, comments, and projects marked as spam'), ('view_metrics', 'Can view metrics on the OSF Admin app'), ('view_prereg', 'Can view entries for the preregistration chellenge on the admin'), ('administer_prereg', 'Can update, comment on, and approve entries to the prereg challenge'), ('view_desk', 'Can view details about Desk users'), )
<commit_before>from django.db import models class AdminProfile(models.Model): user = models.OneToOneField('osf.OSFUser', related_name='admin_profile') desk_token = models.CharField(max_length=45, blank=True) desk_token_secret = models.CharField(max_length=45, blank=True) class Meta: # custom permissions for use in the OSF Admin App permissions = ( ('mark_spam', 'Can mark comments, projects and registrations as spam'), ('view_spam', 'Can view nodes, comments, and projects marked as spam'), ('view_metrics', 'Can view metrics on the OSF Admin app'), ('view_prereg', 'Can view entries for the preregistration chellenge on the admin'), ('administer_prereg', 'Can update, comment on, and approve entries to the prereg challenge'), ('view_desk', 'Can view details about Desk users'), ) <commit_msg>Fix the display name of admin profile in the admin admin<commit_after>from django.db import models class AdminProfile(models.Model): user = models.OneToOneField('osf.OSFUser', related_name='admin_profile') desk_token = models.CharField(max_length=45, blank=True) desk_token_secret = models.CharField(max_length=45, blank=True) def __unicode__(self): return self.user.username class Meta: # custom permissions for use in the OSF Admin App permissions = ( ('mark_spam', 'Can mark comments, projects and registrations as spam'), ('view_spam', 'Can view nodes, comments, and projects marked as spam'), ('view_metrics', 'Can view metrics on the OSF Admin app'), ('view_prereg', 'Can view entries for the preregistration chellenge on the admin'), ('administer_prereg', 'Can update, comment on, and approve entries to the prereg challenge'), ('view_desk', 'Can view details about Desk users'), )
88426415053f44202596e8bd573ca2ca6c056e04
schwifty/registry.py
schwifty/registry.py
import json from pkg_resources import resource_filename _registry = {} def has(name): return name in _registry def get(name): if not has(name): with open(resource_filename(__name__, name + '-registry.json'), 'r') as fp: save(name, json.load(fp)) return _registry[name] def save(name, data): _registry[name] = data def build_index(base_name, index_name, key, **predicate): def make_key(entry): return tuple(entry[k] for k in key) if isinstance(key, tuple) else entry[key] def match(entry): return all(entry[key] == value for key, value in predicate.items()) base = get(base_name) save(index_name, dict((make_key(entry), entry) for entry in base if match(entry))) def manipulate(name, func): registry = get(name) if isinstance(registry, dict): for key, value in registry.items(): registry[key] = func(key, value) elif isinstance(registry, list): registry = [func(item) for item in registry] save(name, registry)
import json from collections import defaultdict from pkg_resources import resource_filename _registry = {} def has(name): return name in _registry def get(name): if not has(name): with open(resource_filename(__name__, name + '-registry.json'), 'r') as fp: save(name, json.load(fp)) return _registry[name] def save(name, data): _registry[name] = data def build_index(base_name, index_name, key, accumulate=False, **predicate): def make_key(entry): return tuple(entry[k] for k in key) if isinstance(key, tuple) else entry[key] def match(entry): return all(entry[key] == value for key, value in predicate.items()) base = get(base_name) if accumulate: data = defaultdict(list) for entry in base: if not match(entry): continue data[make_key(entry)].append(entry) else: data = dict((make_key(entry), entry) for entry in base if match(entry)) save(index_name, data) def manipulate(name, func): registry = get(name) if isinstance(registry, dict): for key, value in registry.items(): registry[key] = func(key, value) elif isinstance(registry, list): registry = [func(item) for item in registry] save(name, registry)
Allow index to be accumulate values with same key
Allow index to be accumulate values with same key
Python
mit
figo-connect/schwifty
import json from pkg_resources import resource_filename _registry = {} def has(name): return name in _registry def get(name): if not has(name): with open(resource_filename(__name__, name + '-registry.json'), 'r') as fp: save(name, json.load(fp)) return _registry[name] def save(name, data): _registry[name] = data def build_index(base_name, index_name, key, **predicate): def make_key(entry): return tuple(entry[k] for k in key) if isinstance(key, tuple) else entry[key] def match(entry): return all(entry[key] == value for key, value in predicate.items()) base = get(base_name) save(index_name, dict((make_key(entry), entry) for entry in base if match(entry))) def manipulate(name, func): registry = get(name) if isinstance(registry, dict): for key, value in registry.items(): registry[key] = func(key, value) elif isinstance(registry, list): registry = [func(item) for item in registry] save(name, registry) Allow index to be accumulate values with same key
import json from collections import defaultdict from pkg_resources import resource_filename _registry = {} def has(name): return name in _registry def get(name): if not has(name): with open(resource_filename(__name__, name + '-registry.json'), 'r') as fp: save(name, json.load(fp)) return _registry[name] def save(name, data): _registry[name] = data def build_index(base_name, index_name, key, accumulate=False, **predicate): def make_key(entry): return tuple(entry[k] for k in key) if isinstance(key, tuple) else entry[key] def match(entry): return all(entry[key] == value for key, value in predicate.items()) base = get(base_name) if accumulate: data = defaultdict(list) for entry in base: if not match(entry): continue data[make_key(entry)].append(entry) else: data = dict((make_key(entry), entry) for entry in base if match(entry)) save(index_name, data) def manipulate(name, func): registry = get(name) if isinstance(registry, dict): for key, value in registry.items(): registry[key] = func(key, value) elif isinstance(registry, list): registry = [func(item) for item in registry] save(name, registry)
<commit_before>import json from pkg_resources import resource_filename _registry = {} def has(name): return name in _registry def get(name): if not has(name): with open(resource_filename(__name__, name + '-registry.json'), 'r') as fp: save(name, json.load(fp)) return _registry[name] def save(name, data): _registry[name] = data def build_index(base_name, index_name, key, **predicate): def make_key(entry): return tuple(entry[k] for k in key) if isinstance(key, tuple) else entry[key] def match(entry): return all(entry[key] == value for key, value in predicate.items()) base = get(base_name) save(index_name, dict((make_key(entry), entry) for entry in base if match(entry))) def manipulate(name, func): registry = get(name) if isinstance(registry, dict): for key, value in registry.items(): registry[key] = func(key, value) elif isinstance(registry, list): registry = [func(item) for item in registry] save(name, registry) <commit_msg>Allow index to be accumulate values with same key<commit_after>
import json from collections import defaultdict from pkg_resources import resource_filename _registry = {} def has(name): return name in _registry def get(name): if not has(name): with open(resource_filename(__name__, name + '-registry.json'), 'r') as fp: save(name, json.load(fp)) return _registry[name] def save(name, data): _registry[name] = data def build_index(base_name, index_name, key, accumulate=False, **predicate): def make_key(entry): return tuple(entry[k] for k in key) if isinstance(key, tuple) else entry[key] def match(entry): return all(entry[key] == value for key, value in predicate.items()) base = get(base_name) if accumulate: data = defaultdict(list) for entry in base: if not match(entry): continue data[make_key(entry)].append(entry) else: data = dict((make_key(entry), entry) for entry in base if match(entry)) save(index_name, data) def manipulate(name, func): registry = get(name) if isinstance(registry, dict): for key, value in registry.items(): registry[key] = func(key, value) elif isinstance(registry, list): registry = [func(item) for item in registry] save(name, registry)
import json from pkg_resources import resource_filename _registry = {} def has(name): return name in _registry def get(name): if not has(name): with open(resource_filename(__name__, name + '-registry.json'), 'r') as fp: save(name, json.load(fp)) return _registry[name] def save(name, data): _registry[name] = data def build_index(base_name, index_name, key, **predicate): def make_key(entry): return tuple(entry[k] for k in key) if isinstance(key, tuple) else entry[key] def match(entry): return all(entry[key] == value for key, value in predicate.items()) base = get(base_name) save(index_name, dict((make_key(entry), entry) for entry in base if match(entry))) def manipulate(name, func): registry = get(name) if isinstance(registry, dict): for key, value in registry.items(): registry[key] = func(key, value) elif isinstance(registry, list): registry = [func(item) for item in registry] save(name, registry) Allow index to be accumulate values with same keyimport json from collections import defaultdict from pkg_resources import resource_filename _registry = {} def has(name): return name in _registry def get(name): if not has(name): with open(resource_filename(__name__, name + '-registry.json'), 'r') as fp: save(name, json.load(fp)) return _registry[name] def save(name, data): _registry[name] = data def build_index(base_name, index_name, key, accumulate=False, **predicate): def make_key(entry): return tuple(entry[k] for k in key) if isinstance(key, tuple) else entry[key] def match(entry): return all(entry[key] == value for key, value in predicate.items()) base = get(base_name) if accumulate: data = defaultdict(list) for entry in base: if not match(entry): continue data[make_key(entry)].append(entry) else: data = dict((make_key(entry), entry) for entry in base if match(entry)) save(index_name, data) def manipulate(name, func): registry = get(name) if isinstance(registry, dict): for key, value in registry.items(): registry[key] = func(key, value) elif isinstance(registry, list): registry = [func(item) for item in registry] save(name, registry)
<commit_before>import json from pkg_resources import resource_filename _registry = {} def has(name): return name in _registry def get(name): if not has(name): with open(resource_filename(__name__, name + '-registry.json'), 'r') as fp: save(name, json.load(fp)) return _registry[name] def save(name, data): _registry[name] = data def build_index(base_name, index_name, key, **predicate): def make_key(entry): return tuple(entry[k] for k in key) if isinstance(key, tuple) else entry[key] def match(entry): return all(entry[key] == value for key, value in predicate.items()) base = get(base_name) save(index_name, dict((make_key(entry), entry) for entry in base if match(entry))) def manipulate(name, func): registry = get(name) if isinstance(registry, dict): for key, value in registry.items(): registry[key] = func(key, value) elif isinstance(registry, list): registry = [func(item) for item in registry] save(name, registry) <commit_msg>Allow index to be accumulate values with same key<commit_after>import json from collections import defaultdict from pkg_resources import resource_filename _registry = {} def has(name): return name in _registry def get(name): if not has(name): with open(resource_filename(__name__, name + '-registry.json'), 'r') as fp: save(name, json.load(fp)) return _registry[name] def save(name, data): _registry[name] = data def build_index(base_name, index_name, key, accumulate=False, **predicate): def make_key(entry): return tuple(entry[k] for k in key) if isinstance(key, tuple) else entry[key] def match(entry): return all(entry[key] == value for key, value in predicate.items()) base = get(base_name) if accumulate: data = defaultdict(list) for entry in base: if not match(entry): continue data[make_key(entry)].append(entry) else: data = dict((make_key(entry), entry) for entry in base if match(entry)) save(index_name, data) def manipulate(name, func): registry = get(name) if isinstance(registry, dict): for key, value in registry.items(): registry[key] = func(key, value) elif isinstance(registry, list): registry = [func(item) for item in registry] save(name, registry)
23978f4959684153bfcaccb7f6d2fadf04836449
proselint/checks/leonard/exclamation.py
proselint/checks/leonard/exclamation.py
# -*- coding: utf-8 -*- """Too much yelling. --- layout: post source: ??? source_url: ??? title: yelling date: 2014-06-10 12:31:19 categories: writing --- Too much yelling. """ from tools import existence_check, memoize @memoize def check_repeated_exclamations(text): """Check the text.""" err = "leonard.exclamation.multiple" msg = u"Stop yelling. Keep your exclamation points under control." regex = r"[^A-Z]\b((\s[A-Z]+){3,})" return existence_check( text, [regex], err, msg, require_padding=False, ignore_case=False, max_errors=1, dotall=True) @memoize def check_exclamations_ppm(text): """Make sure that the exclamatiion ppm is under 30.""" err = "leonard.exclamation.30ppm" msg = u"More than 30 ppm of exclamations. Keep them under control." count = text.count("!") num_words = text.count(" ") ppm = (count*1.0 / num_words) * 1e6 if ppm > 30: loc = text.find('!') return [(loc, loc+1, err, msg)] else: return []
# -*- coding: utf-8 -*- """Too much yelling. --- layout: post source: ??? source_url: ??? title: yelling date: 2014-06-10 12:31:19 categories: writing --- Too much yelling. """ from tools import existence_check, memoize @memoize def check_repeated_exclamations(text): """Check the text.""" err = "leonard.exclamation.multiple" msg = u"Stop yelling. Keep your exclamation points under control." regex = r"[^A-Z]\b((\s[A-Z]+){3,})" return existence_check( text, [regex], err, msg, require_padding=False, ignore_case=False, max_errors=1, dotall=True) @memoize def check_exclamations_ppm(text): """Make sure that the exclamatiion ppm is under 30.""" err = "leonard.exclamation.30ppm" msg = u"More than 30 ppm of exclamations. Keep them under control." count = text.count("!") num_words = len(text.split(" ")) ppm = (count*1.0 / num_words) * 1e6 if ppm > 30: loc = text.find('!') return [(loc, loc+1, err, msg)] else: return []
Fix bug in counting words
Fix bug in counting words Before, this broke with 1-word documents.
Python
bsd-3-clause
amperser/proselint,amperser/proselint,jstewmon/proselint,jstewmon/proselint,amperser/proselint,amperser/proselint,jstewmon/proselint,amperser/proselint
# -*- coding: utf-8 -*- """Too much yelling. --- layout: post source: ??? source_url: ??? title: yelling date: 2014-06-10 12:31:19 categories: writing --- Too much yelling. """ from tools import existence_check, memoize @memoize def check_repeated_exclamations(text): """Check the text.""" err = "leonard.exclamation.multiple" msg = u"Stop yelling. Keep your exclamation points under control." regex = r"[^A-Z]\b((\s[A-Z]+){3,})" return existence_check( text, [regex], err, msg, require_padding=False, ignore_case=False, max_errors=1, dotall=True) @memoize def check_exclamations_ppm(text): """Make sure that the exclamatiion ppm is under 30.""" err = "leonard.exclamation.30ppm" msg = u"More than 30 ppm of exclamations. Keep them under control." count = text.count("!") num_words = text.count(" ") ppm = (count*1.0 / num_words) * 1e6 if ppm > 30: loc = text.find('!') return [(loc, loc+1, err, msg)] else: return [] Fix bug in counting words Before, this broke with 1-word documents.
# -*- coding: utf-8 -*- """Too much yelling. --- layout: post source: ??? source_url: ??? title: yelling date: 2014-06-10 12:31:19 categories: writing --- Too much yelling. """ from tools import existence_check, memoize @memoize def check_repeated_exclamations(text): """Check the text.""" err = "leonard.exclamation.multiple" msg = u"Stop yelling. Keep your exclamation points under control." regex = r"[^A-Z]\b((\s[A-Z]+){3,})" return existence_check( text, [regex], err, msg, require_padding=False, ignore_case=False, max_errors=1, dotall=True) @memoize def check_exclamations_ppm(text): """Make sure that the exclamatiion ppm is under 30.""" err = "leonard.exclamation.30ppm" msg = u"More than 30 ppm of exclamations. Keep them under control." count = text.count("!") num_words = len(text.split(" ")) ppm = (count*1.0 / num_words) * 1e6 if ppm > 30: loc = text.find('!') return [(loc, loc+1, err, msg)] else: return []
<commit_before># -*- coding: utf-8 -*- """Too much yelling. --- layout: post source: ??? source_url: ??? title: yelling date: 2014-06-10 12:31:19 categories: writing --- Too much yelling. """ from tools import existence_check, memoize @memoize def check_repeated_exclamations(text): """Check the text.""" err = "leonard.exclamation.multiple" msg = u"Stop yelling. Keep your exclamation points under control." regex = r"[^A-Z]\b((\s[A-Z]+){3,})" return existence_check( text, [regex], err, msg, require_padding=False, ignore_case=False, max_errors=1, dotall=True) @memoize def check_exclamations_ppm(text): """Make sure that the exclamatiion ppm is under 30.""" err = "leonard.exclamation.30ppm" msg = u"More than 30 ppm of exclamations. Keep them under control." count = text.count("!") num_words = text.count(" ") ppm = (count*1.0 / num_words) * 1e6 if ppm > 30: loc = text.find('!') return [(loc, loc+1, err, msg)] else: return [] <commit_msg>Fix bug in counting words Before, this broke with 1-word documents.<commit_after>
# -*- coding: utf-8 -*- """Too much yelling. --- layout: post source: ??? source_url: ??? title: yelling date: 2014-06-10 12:31:19 categories: writing --- Too much yelling. """ from tools import existence_check, memoize @memoize def check_repeated_exclamations(text): """Check the text.""" err = "leonard.exclamation.multiple" msg = u"Stop yelling. Keep your exclamation points under control." regex = r"[^A-Z]\b((\s[A-Z]+){3,})" return existence_check( text, [regex], err, msg, require_padding=False, ignore_case=False, max_errors=1, dotall=True) @memoize def check_exclamations_ppm(text): """Make sure that the exclamatiion ppm is under 30.""" err = "leonard.exclamation.30ppm" msg = u"More than 30 ppm of exclamations. Keep them under control." count = text.count("!") num_words = len(text.split(" ")) ppm = (count*1.0 / num_words) * 1e6 if ppm > 30: loc = text.find('!') return [(loc, loc+1, err, msg)] else: return []
# -*- coding: utf-8 -*- """Too much yelling. --- layout: post source: ??? source_url: ??? title: yelling date: 2014-06-10 12:31:19 categories: writing --- Too much yelling. """ from tools import existence_check, memoize @memoize def check_repeated_exclamations(text): """Check the text.""" err = "leonard.exclamation.multiple" msg = u"Stop yelling. Keep your exclamation points under control." regex = r"[^A-Z]\b((\s[A-Z]+){3,})" return existence_check( text, [regex], err, msg, require_padding=False, ignore_case=False, max_errors=1, dotall=True) @memoize def check_exclamations_ppm(text): """Make sure that the exclamatiion ppm is under 30.""" err = "leonard.exclamation.30ppm" msg = u"More than 30 ppm of exclamations. Keep them under control." count = text.count("!") num_words = text.count(" ") ppm = (count*1.0 / num_words) * 1e6 if ppm > 30: loc = text.find('!') return [(loc, loc+1, err, msg)] else: return [] Fix bug in counting words Before, this broke with 1-word documents.# -*- coding: utf-8 -*- """Too much yelling. --- layout: post source: ??? source_url: ??? title: yelling date: 2014-06-10 12:31:19 categories: writing --- Too much yelling. """ from tools import existence_check, memoize @memoize def check_repeated_exclamations(text): """Check the text.""" err = "leonard.exclamation.multiple" msg = u"Stop yelling. Keep your exclamation points under control." regex = r"[^A-Z]\b((\s[A-Z]+){3,})" return existence_check( text, [regex], err, msg, require_padding=False, ignore_case=False, max_errors=1, dotall=True) @memoize def check_exclamations_ppm(text): """Make sure that the exclamatiion ppm is under 30.""" err = "leonard.exclamation.30ppm" msg = u"More than 30 ppm of exclamations. Keep them under control." count = text.count("!") num_words = len(text.split(" ")) ppm = (count*1.0 / num_words) * 1e6 if ppm > 30: loc = text.find('!') return [(loc, loc+1, err, msg)] else: return []
<commit_before># -*- coding: utf-8 -*- """Too much yelling. --- layout: post source: ??? source_url: ??? title: yelling date: 2014-06-10 12:31:19 categories: writing --- Too much yelling. """ from tools import existence_check, memoize @memoize def check_repeated_exclamations(text): """Check the text.""" err = "leonard.exclamation.multiple" msg = u"Stop yelling. Keep your exclamation points under control." regex = r"[^A-Z]\b((\s[A-Z]+){3,})" return existence_check( text, [regex], err, msg, require_padding=False, ignore_case=False, max_errors=1, dotall=True) @memoize def check_exclamations_ppm(text): """Make sure that the exclamatiion ppm is under 30.""" err = "leonard.exclamation.30ppm" msg = u"More than 30 ppm of exclamations. Keep them under control." count = text.count("!") num_words = text.count(" ") ppm = (count*1.0 / num_words) * 1e6 if ppm > 30: loc = text.find('!') return [(loc, loc+1, err, msg)] else: return [] <commit_msg>Fix bug in counting words Before, this broke with 1-word documents.<commit_after># -*- coding: utf-8 -*- """Too much yelling. --- layout: post source: ??? source_url: ??? title: yelling date: 2014-06-10 12:31:19 categories: writing --- Too much yelling. """ from tools import existence_check, memoize @memoize def check_repeated_exclamations(text): """Check the text.""" err = "leonard.exclamation.multiple" msg = u"Stop yelling. Keep your exclamation points under control." regex = r"[^A-Z]\b((\s[A-Z]+){3,})" return existence_check( text, [regex], err, msg, require_padding=False, ignore_case=False, max_errors=1, dotall=True) @memoize def check_exclamations_ppm(text): """Make sure that the exclamatiion ppm is under 30.""" err = "leonard.exclamation.30ppm" msg = u"More than 30 ppm of exclamations. Keep them under control." count = text.count("!") num_words = len(text.split(" ")) ppm = (count*1.0 / num_words) * 1e6 if ppm > 30: loc = text.find('!') return [(loc, loc+1, err, msg)] else: return []
cdbf1da3d784df57ffbd2529f4bad2f5fd8abdf1
brainx/__init__.py
brainx/__init__.py
"""Top-level init file for brainx package. """ def patch_nx(): """Temporary fix for NX's watts_strogatz routine, which has a bug in versions 1.1-1.3 """ import networkx as nx # Quick test to see if we get the broken version g = nx.watts_strogatz_graph(2, 0, 0) if g.number_of_nodes() != 2: # Buggy version detected. Create a patched version and apply it to nx nx._watts_strogatz_graph_ori = nx.watts_strogatz_graph def patched_ws(n, k, p, create_using=None, seed=None): if k<2: g = nx.Graph() g.add_nodes_from(range(n)) return g else: return nx._watts_strogatz_graph_ori(n, k, p, create_using, seed) patched_ws.__doc__ = nx._watts_strogatz_graph_ori.__doc__ # Applying monkeypatch now import warnings warnings.warn("Monkeypatching NetworkX's Watts-Strogatz routine") nx.watts_strogatz_graph = patched_ws patch_nx()
"""Top-level init file for brainx package. """ def patch_nx(): """Temporary fix for NX's watts_strogatz routine, which has a bug in versions 1.1-1.3 """ import networkx as nx # Quick test to see if we get the broken version g = nx.watts_strogatz_graph(2, 0, 0) if g.number_of_nodes() != 2: # Buggy version detected. Create a patched version and apply it to nx nx._watts_strogatz_graph_ori = nx.watts_strogatz_graph def patched_ws(n, k, p, seed=None): if k<2: g = nx.Graph() g.add_nodes_from(range(n)) return g else: return nx._watts_strogatz_graph_ori(n, k, p, seed) patched_ws.__doc__ = nx._watts_strogatz_graph_ori.__doc__ # Applying monkeypatch now import warnings warnings.warn("Monkeypatching NetworkX's Watts-Strogatz routine") nx.watts_strogatz_graph = patched_ws patch_nx()
Update watts-strogatz call to match new NetworkX API
Update watts-strogatz call to match new NetworkX API
Python
bsd-3-clause
nipy/brainx,stefanv/brainx,whitergh/brainx,jrcohen02/brainx_archive2
"""Top-level init file for brainx package. """ def patch_nx(): """Temporary fix for NX's watts_strogatz routine, which has a bug in versions 1.1-1.3 """ import networkx as nx # Quick test to see if we get the broken version g = nx.watts_strogatz_graph(2, 0, 0) if g.number_of_nodes() != 2: # Buggy version detected. Create a patched version and apply it to nx nx._watts_strogatz_graph_ori = nx.watts_strogatz_graph def patched_ws(n, k, p, create_using=None, seed=None): if k<2: g = nx.Graph() g.add_nodes_from(range(n)) return g else: return nx._watts_strogatz_graph_ori(n, k, p, create_using, seed) patched_ws.__doc__ = nx._watts_strogatz_graph_ori.__doc__ # Applying monkeypatch now import warnings warnings.warn("Monkeypatching NetworkX's Watts-Strogatz routine") nx.watts_strogatz_graph = patched_ws patch_nx() Update watts-strogatz call to match new NetworkX API
"""Top-level init file for brainx package. """ def patch_nx(): """Temporary fix for NX's watts_strogatz routine, which has a bug in versions 1.1-1.3 """ import networkx as nx # Quick test to see if we get the broken version g = nx.watts_strogatz_graph(2, 0, 0) if g.number_of_nodes() != 2: # Buggy version detected. Create a patched version and apply it to nx nx._watts_strogatz_graph_ori = nx.watts_strogatz_graph def patched_ws(n, k, p, seed=None): if k<2: g = nx.Graph() g.add_nodes_from(range(n)) return g else: return nx._watts_strogatz_graph_ori(n, k, p, seed) patched_ws.__doc__ = nx._watts_strogatz_graph_ori.__doc__ # Applying monkeypatch now import warnings warnings.warn("Monkeypatching NetworkX's Watts-Strogatz routine") nx.watts_strogatz_graph = patched_ws patch_nx()
<commit_before>"""Top-level init file for brainx package. """ def patch_nx(): """Temporary fix for NX's watts_strogatz routine, which has a bug in versions 1.1-1.3 """ import networkx as nx # Quick test to see if we get the broken version g = nx.watts_strogatz_graph(2, 0, 0) if g.number_of_nodes() != 2: # Buggy version detected. Create a patched version and apply it to nx nx._watts_strogatz_graph_ori = nx.watts_strogatz_graph def patched_ws(n, k, p, create_using=None, seed=None): if k<2: g = nx.Graph() g.add_nodes_from(range(n)) return g else: return nx._watts_strogatz_graph_ori(n, k, p, create_using, seed) patched_ws.__doc__ = nx._watts_strogatz_graph_ori.__doc__ # Applying monkeypatch now import warnings warnings.warn("Monkeypatching NetworkX's Watts-Strogatz routine") nx.watts_strogatz_graph = patched_ws patch_nx() <commit_msg>Update watts-strogatz call to match new NetworkX API<commit_after>
"""Top-level init file for brainx package. """ def patch_nx(): """Temporary fix for NX's watts_strogatz routine, which has a bug in versions 1.1-1.3 """ import networkx as nx # Quick test to see if we get the broken version g = nx.watts_strogatz_graph(2, 0, 0) if g.number_of_nodes() != 2: # Buggy version detected. Create a patched version and apply it to nx nx._watts_strogatz_graph_ori = nx.watts_strogatz_graph def patched_ws(n, k, p, seed=None): if k<2: g = nx.Graph() g.add_nodes_from(range(n)) return g else: return nx._watts_strogatz_graph_ori(n, k, p, seed) patched_ws.__doc__ = nx._watts_strogatz_graph_ori.__doc__ # Applying monkeypatch now import warnings warnings.warn("Monkeypatching NetworkX's Watts-Strogatz routine") nx.watts_strogatz_graph = patched_ws patch_nx()
"""Top-level init file for brainx package. """ def patch_nx(): """Temporary fix for NX's watts_strogatz routine, which has a bug in versions 1.1-1.3 """ import networkx as nx # Quick test to see if we get the broken version g = nx.watts_strogatz_graph(2, 0, 0) if g.number_of_nodes() != 2: # Buggy version detected. Create a patched version and apply it to nx nx._watts_strogatz_graph_ori = nx.watts_strogatz_graph def patched_ws(n, k, p, create_using=None, seed=None): if k<2: g = nx.Graph() g.add_nodes_from(range(n)) return g else: return nx._watts_strogatz_graph_ori(n, k, p, create_using, seed) patched_ws.__doc__ = nx._watts_strogatz_graph_ori.__doc__ # Applying monkeypatch now import warnings warnings.warn("Monkeypatching NetworkX's Watts-Strogatz routine") nx.watts_strogatz_graph = patched_ws patch_nx() Update watts-strogatz call to match new NetworkX API"""Top-level init file for brainx package. """ def patch_nx(): """Temporary fix for NX's watts_strogatz routine, which has a bug in versions 1.1-1.3 """ import networkx as nx # Quick test to see if we get the broken version g = nx.watts_strogatz_graph(2, 0, 0) if g.number_of_nodes() != 2: # Buggy version detected. Create a patched version and apply it to nx nx._watts_strogatz_graph_ori = nx.watts_strogatz_graph def patched_ws(n, k, p, seed=None): if k<2: g = nx.Graph() g.add_nodes_from(range(n)) return g else: return nx._watts_strogatz_graph_ori(n, k, p, seed) patched_ws.__doc__ = nx._watts_strogatz_graph_ori.__doc__ # Applying monkeypatch now import warnings warnings.warn("Monkeypatching NetworkX's Watts-Strogatz routine") nx.watts_strogatz_graph = patched_ws patch_nx()
<commit_before>"""Top-level init file for brainx package. """ def patch_nx(): """Temporary fix for NX's watts_strogatz routine, which has a bug in versions 1.1-1.3 """ import networkx as nx # Quick test to see if we get the broken version g = nx.watts_strogatz_graph(2, 0, 0) if g.number_of_nodes() != 2: # Buggy version detected. Create a patched version and apply it to nx nx._watts_strogatz_graph_ori = nx.watts_strogatz_graph def patched_ws(n, k, p, create_using=None, seed=None): if k<2: g = nx.Graph() g.add_nodes_from(range(n)) return g else: return nx._watts_strogatz_graph_ori(n, k, p, create_using, seed) patched_ws.__doc__ = nx._watts_strogatz_graph_ori.__doc__ # Applying monkeypatch now import warnings warnings.warn("Monkeypatching NetworkX's Watts-Strogatz routine") nx.watts_strogatz_graph = patched_ws patch_nx() <commit_msg>Update watts-strogatz call to match new NetworkX API<commit_after>"""Top-level init file for brainx package. """ def patch_nx(): """Temporary fix for NX's watts_strogatz routine, which has a bug in versions 1.1-1.3 """ import networkx as nx # Quick test to see if we get the broken version g = nx.watts_strogatz_graph(2, 0, 0) if g.number_of_nodes() != 2: # Buggy version detected. Create a patched version and apply it to nx nx._watts_strogatz_graph_ori = nx.watts_strogatz_graph def patched_ws(n, k, p, seed=None): if k<2: g = nx.Graph() g.add_nodes_from(range(n)) return g else: return nx._watts_strogatz_graph_ori(n, k, p, seed) patched_ws.__doc__ = nx._watts_strogatz_graph_ori.__doc__ # Applying monkeypatch now import warnings warnings.warn("Monkeypatching NetworkX's Watts-Strogatz routine") nx.watts_strogatz_graph = patched_ws patch_nx()
1642bf91ab9042fddb3fcdeb7d2d8d010979c978
disasm.py
disasm.py
import MOS6502 import instructions def disasm(memory, maxLines=0, address=-1): index = 0 lines = [] while index < len(memory): currInst = instructions.instructions[memory[index]] if address > 0: line = format(address+index, '04x') + ": " else: line = '' line += currInst.mnem + " " line += currInst.operType + " " if currInst.size > 1: if 'ABS' in currInst.operType: line += hex(memory[index+1] + (memory[index+2] << 8)) else: for i in range(1, currInst.size): line += hex(memory[index + i]) + " " lines.append(line) index += currInst.size if maxLines != 0 and len(lines) == maxLines: return lines return lines
import MOS6502 import instructions import code def disasm(memory, maxLines=0, address=-1): index = 0 lines = [] while index < len(memory): opcode = memory[index] if opcode not in instructions.instructions.keys(): print "Undefined opcode: " + hex(opcode) code.interact(local=locals()) currInst = instructions.instructions[memory[index]] if address > 0: line = format(address+index, '04x') + ": " else: line = '' line += currInst.mnem + " " line += currInst.operType + " " if currInst.size > 1: if 'ABS' in currInst.operType: line += hex(memory[index+1] + (memory[index+2] << 8)) else: for i in range(1, currInst.size): line += hex(memory[index + i]) + " " lines.append(line) index += currInst.size if maxLines != 0 and len(lines) == maxLines: return lines return lines
Add catch for undefined opcodes
Add catch for undefined opcodes
Python
bsd-2-clause
pusscat/refNes
import MOS6502 import instructions def disasm(memory, maxLines=0, address=-1): index = 0 lines = [] while index < len(memory): currInst = instructions.instructions[memory[index]] if address > 0: line = format(address+index, '04x') + ": " else: line = '' line += currInst.mnem + " " line += currInst.operType + " " if currInst.size > 1: if 'ABS' in currInst.operType: line += hex(memory[index+1] + (memory[index+2] << 8)) else: for i in range(1, currInst.size): line += hex(memory[index + i]) + " " lines.append(line) index += currInst.size if maxLines != 0 and len(lines) == maxLines: return lines return lines Add catch for undefined opcodes
import MOS6502 import instructions import code def disasm(memory, maxLines=0, address=-1): index = 0 lines = [] while index < len(memory): opcode = memory[index] if opcode not in instructions.instructions.keys(): print "Undefined opcode: " + hex(opcode) code.interact(local=locals()) currInst = instructions.instructions[memory[index]] if address > 0: line = format(address+index, '04x') + ": " else: line = '' line += currInst.mnem + " " line += currInst.operType + " " if currInst.size > 1: if 'ABS' in currInst.operType: line += hex(memory[index+1] + (memory[index+2] << 8)) else: for i in range(1, currInst.size): line += hex(memory[index + i]) + " " lines.append(line) index += currInst.size if maxLines != 0 and len(lines) == maxLines: return lines return lines
<commit_before>import MOS6502 import instructions def disasm(memory, maxLines=0, address=-1): index = 0 lines = [] while index < len(memory): currInst = instructions.instructions[memory[index]] if address > 0: line = format(address+index, '04x') + ": " else: line = '' line += currInst.mnem + " " line += currInst.operType + " " if currInst.size > 1: if 'ABS' in currInst.operType: line += hex(memory[index+1] + (memory[index+2] << 8)) else: for i in range(1, currInst.size): line += hex(memory[index + i]) + " " lines.append(line) index += currInst.size if maxLines != 0 and len(lines) == maxLines: return lines return lines <commit_msg>Add catch for undefined opcodes<commit_after>
import MOS6502 import instructions import code def disasm(memory, maxLines=0, address=-1): index = 0 lines = [] while index < len(memory): opcode = memory[index] if opcode not in instructions.instructions.keys(): print "Undefined opcode: " + hex(opcode) code.interact(local=locals()) currInst = instructions.instructions[memory[index]] if address > 0: line = format(address+index, '04x') + ": " else: line = '' line += currInst.mnem + " " line += currInst.operType + " " if currInst.size > 1: if 'ABS' in currInst.operType: line += hex(memory[index+1] + (memory[index+2] << 8)) else: for i in range(1, currInst.size): line += hex(memory[index + i]) + " " lines.append(line) index += currInst.size if maxLines != 0 and len(lines) == maxLines: return lines return lines
import MOS6502 import instructions def disasm(memory, maxLines=0, address=-1): index = 0 lines = [] while index < len(memory): currInst = instructions.instructions[memory[index]] if address > 0: line = format(address+index, '04x') + ": " else: line = '' line += currInst.mnem + " " line += currInst.operType + " " if currInst.size > 1: if 'ABS' in currInst.operType: line += hex(memory[index+1] + (memory[index+2] << 8)) else: for i in range(1, currInst.size): line += hex(memory[index + i]) + " " lines.append(line) index += currInst.size if maxLines != 0 and len(lines) == maxLines: return lines return lines Add catch for undefined opcodesimport MOS6502 import instructions import code def disasm(memory, maxLines=0, address=-1): index = 0 lines = [] while index < len(memory): opcode = memory[index] if opcode not in instructions.instructions.keys(): print "Undefined opcode: " + hex(opcode) code.interact(local=locals()) currInst = instructions.instructions[memory[index]] if address > 0: line = format(address+index, '04x') + ": " else: line = '' line += currInst.mnem + " " line += currInst.operType + " " if currInst.size > 1: if 'ABS' in currInst.operType: line += hex(memory[index+1] + (memory[index+2] << 8)) else: for i in range(1, currInst.size): line += hex(memory[index + i]) + " " lines.append(line) index += currInst.size if maxLines != 0 and len(lines) == maxLines: return lines return lines
<commit_before>import MOS6502 import instructions def disasm(memory, maxLines=0, address=-1): index = 0 lines = [] while index < len(memory): currInst = instructions.instructions[memory[index]] if address > 0: line = format(address+index, '04x') + ": " else: line = '' line += currInst.mnem + " " line += currInst.operType + " " if currInst.size > 1: if 'ABS' in currInst.operType: line += hex(memory[index+1] + (memory[index+2] << 8)) else: for i in range(1, currInst.size): line += hex(memory[index + i]) + " " lines.append(line) index += currInst.size if maxLines != 0 and len(lines) == maxLines: return lines return lines <commit_msg>Add catch for undefined opcodes<commit_after>import MOS6502 import instructions import code def disasm(memory, maxLines=0, address=-1): index = 0 lines = [] while index < len(memory): opcode = memory[index] if opcode not in instructions.instructions.keys(): print "Undefined opcode: " + hex(opcode) code.interact(local=locals()) currInst = instructions.instructions[memory[index]] if address > 0: line = format(address+index, '04x') + ": " else: line = '' line += currInst.mnem + " " line += currInst.operType + " " if currInst.size > 1: if 'ABS' in currInst.operType: line += hex(memory[index+1] + (memory[index+2] << 8)) else: for i in range(1, currInst.size): line += hex(memory[index + i]) + " " lines.append(line) index += currInst.size if maxLines != 0 and len(lines) == maxLines: return lines return lines
bb5d6d94d555a91b2f9da1258aee90146ccd9998
openstack/common/messaging/_executors/impl_eventlet.py
openstack/common/messaging/_executors/impl_eventlet.py
# Copyright 2013 Red Hat, Inc. # Copyright 2013 New Dream Network, LLC (DreamHost) # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import eventlet import greenlet from openstack.common.messaging._executors import base class EventletExecutor(base.ExecutorBase): def __init__(self, conf, listener, callback): super(EventletExecutor, self).__init__(conf, listener, callback) self._thread = None def start(self): if self._thread is not None: return def _executor_thread(): try: while True: except greenlet.GreenletExit: return self._thread = eventlet.spawn(_executor_thread) def stop(self): if self._thread is None: return self._thread.kill() def wait(self): if self._thread is None: return try: self._thread.wait() except greenlet.GreenletExit: pass self._thread = None
# Copyright 2013 Red Hat, Inc. # Copyright 2013 New Dream Network, LLC (DreamHost) # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import eventlet import greenlet from openstack.common.messaging._executors import base class EventletExecutor(base.ExecutorBase): def __init__(self, conf, listener, callback): super(EventletExecutor, self).__init__(conf, listener, callback) self._thread = None def start(self): if self._thread is not None: return def _executor_thread(): try: while True: self._process_one_message() except greenlet.GreenletExit: return self._thread = eventlet.spawn(_executor_thread) def stop(self): if self._thread is None: return self._thread.kill() def wait(self): if self._thread is None: return try: self._thread.wait() except greenlet.GreenletExit: pass self._thread = None
Add forgotten piece of eventlet executor
Add forgotten piece of eventlet executor
Python
apache-2.0
hkumarmk/oslo.messaging,dims/oslo.messaging,dukhlov/oslo.messaging,hkumarmk/oslo.messaging,ozamiatin/oslo.messaging,redhat-openstack/oslo.messaging,dukhlov/oslo.messaging,zhurongze/oslo.messaging,isyippee/oslo.messaging,viggates/oslo.messaging,markmc/oslo.messaging,apporc/oslo.messaging,apporc/oslo.messaging,stevei101/oslo.messaging,stevei101/oslo.messaging,magic0704/oslo.messaging,JioCloud/oslo.messaging,isyippee/oslo.messaging,citrix-openstack-build/oslo.messaging,ozamiatin/oslo.messaging,redhat-openstack/oslo.messaging,dims/oslo.messaging,zhurongze/oslo.messaging,magic0704/oslo.messaging,markmc/oslo.messaging,eayunstack/oslo.messaging
# Copyright 2013 Red Hat, Inc. # Copyright 2013 New Dream Network, LLC (DreamHost) # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import eventlet import greenlet from openstack.common.messaging._executors import base class EventletExecutor(base.ExecutorBase): def __init__(self, conf, listener, callback): super(EventletExecutor, self).__init__(conf, listener, callback) self._thread = None def start(self): if self._thread is not None: return def _executor_thread(): try: while True: except greenlet.GreenletExit: return self._thread = eventlet.spawn(_executor_thread) def stop(self): if self._thread is None: return self._thread.kill() def wait(self): if self._thread is None: return try: self._thread.wait() except greenlet.GreenletExit: pass self._thread = None Add forgotten piece of eventlet executor
# Copyright 2013 Red Hat, Inc. # Copyright 2013 New Dream Network, LLC (DreamHost) # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import eventlet import greenlet from openstack.common.messaging._executors import base class EventletExecutor(base.ExecutorBase): def __init__(self, conf, listener, callback): super(EventletExecutor, self).__init__(conf, listener, callback) self._thread = None def start(self): if self._thread is not None: return def _executor_thread(): try: while True: self._process_one_message() except greenlet.GreenletExit: return self._thread = eventlet.spawn(_executor_thread) def stop(self): if self._thread is None: return self._thread.kill() def wait(self): if self._thread is None: return try: self._thread.wait() except greenlet.GreenletExit: pass self._thread = None
<commit_before># Copyright 2013 Red Hat, Inc. # Copyright 2013 New Dream Network, LLC (DreamHost) # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import eventlet import greenlet from openstack.common.messaging._executors import base class EventletExecutor(base.ExecutorBase): def __init__(self, conf, listener, callback): super(EventletExecutor, self).__init__(conf, listener, callback) self._thread = None def start(self): if self._thread is not None: return def _executor_thread(): try: while True: except greenlet.GreenletExit: return self._thread = eventlet.spawn(_executor_thread) def stop(self): if self._thread is None: return self._thread.kill() def wait(self): if self._thread is None: return try: self._thread.wait() except greenlet.GreenletExit: pass self._thread = None <commit_msg>Add forgotten piece of eventlet executor<commit_after>
# Copyright 2013 Red Hat, Inc. # Copyright 2013 New Dream Network, LLC (DreamHost) # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import eventlet import greenlet from openstack.common.messaging._executors import base class EventletExecutor(base.ExecutorBase): def __init__(self, conf, listener, callback): super(EventletExecutor, self).__init__(conf, listener, callback) self._thread = None def start(self): if self._thread is not None: return def _executor_thread(): try: while True: self._process_one_message() except greenlet.GreenletExit: return self._thread = eventlet.spawn(_executor_thread) def stop(self): if self._thread is None: return self._thread.kill() def wait(self): if self._thread is None: return try: self._thread.wait() except greenlet.GreenletExit: pass self._thread = None
# Copyright 2013 Red Hat, Inc. # Copyright 2013 New Dream Network, LLC (DreamHost) # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import eventlet import greenlet from openstack.common.messaging._executors import base class EventletExecutor(base.ExecutorBase): def __init__(self, conf, listener, callback): super(EventletExecutor, self).__init__(conf, listener, callback) self._thread = None def start(self): if self._thread is not None: return def _executor_thread(): try: while True: except greenlet.GreenletExit: return self._thread = eventlet.spawn(_executor_thread) def stop(self): if self._thread is None: return self._thread.kill() def wait(self): if self._thread is None: return try: self._thread.wait() except greenlet.GreenletExit: pass self._thread = None Add forgotten piece of eventlet executor# Copyright 2013 Red Hat, Inc. # Copyright 2013 New Dream Network, LLC (DreamHost) # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import eventlet import greenlet from openstack.common.messaging._executors import base class EventletExecutor(base.ExecutorBase): def __init__(self, conf, listener, callback): super(EventletExecutor, self).__init__(conf, listener, callback) self._thread = None def start(self): if self._thread is not None: return def _executor_thread(): try: while True: self._process_one_message() except greenlet.GreenletExit: return self._thread = eventlet.spawn(_executor_thread) def stop(self): if self._thread is None: return self._thread.kill() def wait(self): if self._thread is None: return try: self._thread.wait() except greenlet.GreenletExit: pass self._thread = None
<commit_before># Copyright 2013 Red Hat, Inc. # Copyright 2013 New Dream Network, LLC (DreamHost) # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import eventlet import greenlet from openstack.common.messaging._executors import base class EventletExecutor(base.ExecutorBase): def __init__(self, conf, listener, callback): super(EventletExecutor, self).__init__(conf, listener, callback) self._thread = None def start(self): if self._thread is not None: return def _executor_thread(): try: while True: except greenlet.GreenletExit: return self._thread = eventlet.spawn(_executor_thread) def stop(self): if self._thread is None: return self._thread.kill() def wait(self): if self._thread is None: return try: self._thread.wait() except greenlet.GreenletExit: pass self._thread = None <commit_msg>Add forgotten piece of eventlet executor<commit_after># Copyright 2013 Red Hat, Inc. # Copyright 2013 New Dream Network, LLC (DreamHost) # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import eventlet import greenlet from openstack.common.messaging._executors import base class EventletExecutor(base.ExecutorBase): def __init__(self, conf, listener, callback): super(EventletExecutor, self).__init__(conf, listener, callback) self._thread = None def start(self): if self._thread is not None: return def _executor_thread(): try: while True: self._process_one_message() except greenlet.GreenletExit: return self._thread = eventlet.spawn(_executor_thread) def stop(self): if self._thread is None: return self._thread.kill() def wait(self): if self._thread is None: return try: self._thread.wait() except greenlet.GreenletExit: pass self._thread = None
fd98c81f315bf8c1699aed0b7eb46a7c1add73dd
eccodes/highlevel/message.py
eccodes/highlevel/message.py
import io import eccodes class Message: def __init__(self, handle): self.handle = handle def __del__(self): eccodes.codes_release(self.handle) def copy(self): return Message(eccodes.codes_clone(self.handle)) def __copy__(self): return self.copy() def get(self, name): return eccodes.codes_get(self.handle, name) def set(self, name, value): return eccodes.codes_set(self.handle, name, value) def get_array(self, name): return eccodes.codes_get_array(self.handle, name) def get_size(self, name): return eccodes.codes_get_size(self.handle, name) def get_data(self): return eccodes.codes_grib_get_data(self.handle) def set_array(self, name, value): return eccodes.codes_set_array(self.handle, name, value) def write_to(self, fileobj): assert isinstance(fileobj, io.IOBase) eccodes.codes_write(self.handle, fileobj) def get_buffer(self): return eccodes.codes_get_message(self.handle) @classmethod def from_samples(cls, name): return cls(eccodes.codes_grib_new_from_samples(name))
import io import eccodes class Message: def __init__(self, handle): self.handle = handle def __del__(self): try: eccodes.codes_release(self.handle) except Exception: pass def copy(self): return Message(eccodes.codes_clone(self.handle)) def __copy__(self): return self.copy() def get(self, name): return eccodes.codes_get(self.handle, name) def set(self, name, value): return eccodes.codes_set(self.handle, name, value) def get_array(self, name): return eccodes.codes_get_array(self.handle, name) def get_size(self, name): return eccodes.codes_get_size(self.handle, name) def get_data(self): return eccodes.codes_grib_get_data(self.handle) def set_array(self, name, value): return eccodes.codes_set_array(self.handle, name, value) def write_to(self, fileobj): assert isinstance(fileobj, io.IOBase) eccodes.codes_write(self.handle, fileobj) def get_buffer(self): return eccodes.codes_get_message(self.handle) @classmethod def from_samples(cls, name): return cls(eccodes.codes_grib_new_from_samples(name))
Make Message.__del__ immune to teardown errors
Make Message.__del__ immune to teardown errors
Python
apache-2.0
ecmwf/eccodes-python,ecmwf/eccodes-python
import io import eccodes class Message: def __init__(self, handle): self.handle = handle def __del__(self): eccodes.codes_release(self.handle) def copy(self): return Message(eccodes.codes_clone(self.handle)) def __copy__(self): return self.copy() def get(self, name): return eccodes.codes_get(self.handle, name) def set(self, name, value): return eccodes.codes_set(self.handle, name, value) def get_array(self, name): return eccodes.codes_get_array(self.handle, name) def get_size(self, name): return eccodes.codes_get_size(self.handle, name) def get_data(self): return eccodes.codes_grib_get_data(self.handle) def set_array(self, name, value): return eccodes.codes_set_array(self.handle, name, value) def write_to(self, fileobj): assert isinstance(fileobj, io.IOBase) eccodes.codes_write(self.handle, fileobj) def get_buffer(self): return eccodes.codes_get_message(self.handle) @classmethod def from_samples(cls, name): return cls(eccodes.codes_grib_new_from_samples(name))Make Message.__del__ immune to teardown errors
import io import eccodes class Message: def __init__(self, handle): self.handle = handle def __del__(self): try: eccodes.codes_release(self.handle) except Exception: pass def copy(self): return Message(eccodes.codes_clone(self.handle)) def __copy__(self): return self.copy() def get(self, name): return eccodes.codes_get(self.handle, name) def set(self, name, value): return eccodes.codes_set(self.handle, name, value) def get_array(self, name): return eccodes.codes_get_array(self.handle, name) def get_size(self, name): return eccodes.codes_get_size(self.handle, name) def get_data(self): return eccodes.codes_grib_get_data(self.handle) def set_array(self, name, value): return eccodes.codes_set_array(self.handle, name, value) def write_to(self, fileobj): assert isinstance(fileobj, io.IOBase) eccodes.codes_write(self.handle, fileobj) def get_buffer(self): return eccodes.codes_get_message(self.handle) @classmethod def from_samples(cls, name): return cls(eccodes.codes_grib_new_from_samples(name))
<commit_before> import io import eccodes class Message: def __init__(self, handle): self.handle = handle def __del__(self): eccodes.codes_release(self.handle) def copy(self): return Message(eccodes.codes_clone(self.handle)) def __copy__(self): return self.copy() def get(self, name): return eccodes.codes_get(self.handle, name) def set(self, name, value): return eccodes.codes_set(self.handle, name, value) def get_array(self, name): return eccodes.codes_get_array(self.handle, name) def get_size(self, name): return eccodes.codes_get_size(self.handle, name) def get_data(self): return eccodes.codes_grib_get_data(self.handle) def set_array(self, name, value): return eccodes.codes_set_array(self.handle, name, value) def write_to(self, fileobj): assert isinstance(fileobj, io.IOBase) eccodes.codes_write(self.handle, fileobj) def get_buffer(self): return eccodes.codes_get_message(self.handle) @classmethod def from_samples(cls, name): return cls(eccodes.codes_grib_new_from_samples(name))<commit_msg>Make Message.__del__ immune to teardown errors<commit_after>
import io import eccodes class Message: def __init__(self, handle): self.handle = handle def __del__(self): try: eccodes.codes_release(self.handle) except Exception: pass def copy(self): return Message(eccodes.codes_clone(self.handle)) def __copy__(self): return self.copy() def get(self, name): return eccodes.codes_get(self.handle, name) def set(self, name, value): return eccodes.codes_set(self.handle, name, value) def get_array(self, name): return eccodes.codes_get_array(self.handle, name) def get_size(self, name): return eccodes.codes_get_size(self.handle, name) def get_data(self): return eccodes.codes_grib_get_data(self.handle) def set_array(self, name, value): return eccodes.codes_set_array(self.handle, name, value) def write_to(self, fileobj): assert isinstance(fileobj, io.IOBase) eccodes.codes_write(self.handle, fileobj) def get_buffer(self): return eccodes.codes_get_message(self.handle) @classmethod def from_samples(cls, name): return cls(eccodes.codes_grib_new_from_samples(name))
import io import eccodes class Message: def __init__(self, handle): self.handle = handle def __del__(self): eccodes.codes_release(self.handle) def copy(self): return Message(eccodes.codes_clone(self.handle)) def __copy__(self): return self.copy() def get(self, name): return eccodes.codes_get(self.handle, name) def set(self, name, value): return eccodes.codes_set(self.handle, name, value) def get_array(self, name): return eccodes.codes_get_array(self.handle, name) def get_size(self, name): return eccodes.codes_get_size(self.handle, name) def get_data(self): return eccodes.codes_grib_get_data(self.handle) def set_array(self, name, value): return eccodes.codes_set_array(self.handle, name, value) def write_to(self, fileobj): assert isinstance(fileobj, io.IOBase) eccodes.codes_write(self.handle, fileobj) def get_buffer(self): return eccodes.codes_get_message(self.handle) @classmethod def from_samples(cls, name): return cls(eccodes.codes_grib_new_from_samples(name))Make Message.__del__ immune to teardown errors import io import eccodes class Message: def __init__(self, handle): self.handle = handle def __del__(self): try: eccodes.codes_release(self.handle) except Exception: pass def copy(self): return Message(eccodes.codes_clone(self.handle)) def __copy__(self): return self.copy() def get(self, name): return eccodes.codes_get(self.handle, name) def set(self, name, value): return eccodes.codes_set(self.handle, name, value) def get_array(self, name): return eccodes.codes_get_array(self.handle, name) def get_size(self, name): return eccodes.codes_get_size(self.handle, name) def get_data(self): return eccodes.codes_grib_get_data(self.handle) def set_array(self, name, value): return eccodes.codes_set_array(self.handle, name, value) def write_to(self, fileobj): assert isinstance(fileobj, io.IOBase) eccodes.codes_write(self.handle, fileobj) def get_buffer(self): return eccodes.codes_get_message(self.handle) @classmethod def from_samples(cls, name): return cls(eccodes.codes_grib_new_from_samples(name))
<commit_before> import io import eccodes class Message: def __init__(self, handle): self.handle = handle def __del__(self): eccodes.codes_release(self.handle) def copy(self): return Message(eccodes.codes_clone(self.handle)) def __copy__(self): return self.copy() def get(self, name): return eccodes.codes_get(self.handle, name) def set(self, name, value): return eccodes.codes_set(self.handle, name, value) def get_array(self, name): return eccodes.codes_get_array(self.handle, name) def get_size(self, name): return eccodes.codes_get_size(self.handle, name) def get_data(self): return eccodes.codes_grib_get_data(self.handle) def set_array(self, name, value): return eccodes.codes_set_array(self.handle, name, value) def write_to(self, fileobj): assert isinstance(fileobj, io.IOBase) eccodes.codes_write(self.handle, fileobj) def get_buffer(self): return eccodes.codes_get_message(self.handle) @classmethod def from_samples(cls, name): return cls(eccodes.codes_grib_new_from_samples(name))<commit_msg>Make Message.__del__ immune to teardown errors<commit_after> import io import eccodes class Message: def __init__(self, handle): self.handle = handle def __del__(self): try: eccodes.codes_release(self.handle) except Exception: pass def copy(self): return Message(eccodes.codes_clone(self.handle)) def __copy__(self): return self.copy() def get(self, name): return eccodes.codes_get(self.handle, name) def set(self, name, value): return eccodes.codes_set(self.handle, name, value) def get_array(self, name): return eccodes.codes_get_array(self.handle, name) def get_size(self, name): return eccodes.codes_get_size(self.handle, name) def get_data(self): return eccodes.codes_grib_get_data(self.handle) def set_array(self, name, value): return eccodes.codes_set_array(self.handle, name, value) def write_to(self, fileobj): assert isinstance(fileobj, io.IOBase) eccodes.codes_write(self.handle, fileobj) def get_buffer(self): return eccodes.codes_get_message(self.handle) @classmethod def from_samples(cls, name): return cls(eccodes.codes_grib_new_from_samples(name))
bc401d0073ddf9d693bd182317738d4be4f4ec70
benchexec/tools/witnesslint.py
benchexec/tools/witnesslint.py
# This file is part of BenchExec, a framework for reliable benchmarking: # https://github.com/sosy-lab/benchexec # # SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org> # # SPDX-License-Identifier: Apache-2.0 import benchexec.result as result import benchexec.tools.template class Tool(benchexec.tools.template.BaseTool2): """ Tool info for the witness checker (witnesslint) (https://github.com/sosy-lab/sv-witnesses) """ def executable(self, tool_locator): return tool_locator.find_executable("witnesslint.py") def name(self): return "witnesslint" def determine_result(self, run): if run.exit_code.value == 0: return result.RESULT_TRUE_PROP else: return result.RESULT_FALSE_PROP
# This file is part of BenchExec, a framework for reliable benchmarking: # https://github.com/sosy-lab/benchexec # # SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org> # # SPDX-License-Identifier: Apache-2.0 import benchexec.result as result import benchexec.tools.template class Tool(benchexec.tools.template.BaseTool2): """ Tool info for the witness checker (witnesslint) (https://github.com/sosy-lab/sv-witnesses) """ def executable(self, tool_locator): return tool_locator.find_executable("witnesslint.py") def name(self): return "witnesslint" def version(self, executable): version_string = self._version_from_tool(executable) return version_string.partition("version")[2].strip().split(" ")[0] def determine_result(self, run): if run.exit_code.value == 0: return result.RESULT_TRUE_PROP elif run.exit_code.value == 1: return result.RESULT_FALSE_PROP else: return result.RESULT_ERROR
Add version and distinguish linter error from faulty witness.
Add version and distinguish linter error from faulty witness.
Python
apache-2.0
ultimate-pa/benchexec,ultimate-pa/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,ultimate-pa/benchexec,dbeyer/benchexec,ultimate-pa/benchexec,dbeyer/benchexec,sosy-lab/benchexec,dbeyer/benchexec,sosy-lab/benchexec,ultimate-pa/benchexec,sosy-lab/benchexec,dbeyer/benchexec,ultimate-pa/benchexec
# This file is part of BenchExec, a framework for reliable benchmarking: # https://github.com/sosy-lab/benchexec # # SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org> # # SPDX-License-Identifier: Apache-2.0 import benchexec.result as result import benchexec.tools.template class Tool(benchexec.tools.template.BaseTool2): """ Tool info for the witness checker (witnesslint) (https://github.com/sosy-lab/sv-witnesses) """ def executable(self, tool_locator): return tool_locator.find_executable("witnesslint.py") def name(self): return "witnesslint" def determine_result(self, run): if run.exit_code.value == 0: return result.RESULT_TRUE_PROP else: return result.RESULT_FALSE_PROP Add version and distinguish linter error from faulty witness.
# This file is part of BenchExec, a framework for reliable benchmarking: # https://github.com/sosy-lab/benchexec # # SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org> # # SPDX-License-Identifier: Apache-2.0 import benchexec.result as result import benchexec.tools.template class Tool(benchexec.tools.template.BaseTool2): """ Tool info for the witness checker (witnesslint) (https://github.com/sosy-lab/sv-witnesses) """ def executable(self, tool_locator): return tool_locator.find_executable("witnesslint.py") def name(self): return "witnesslint" def version(self, executable): version_string = self._version_from_tool(executable) return version_string.partition("version")[2].strip().split(" ")[0] def determine_result(self, run): if run.exit_code.value == 0: return result.RESULT_TRUE_PROP elif run.exit_code.value == 1: return result.RESULT_FALSE_PROP else: return result.RESULT_ERROR
<commit_before># This file is part of BenchExec, a framework for reliable benchmarking: # https://github.com/sosy-lab/benchexec # # SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org> # # SPDX-License-Identifier: Apache-2.0 import benchexec.result as result import benchexec.tools.template class Tool(benchexec.tools.template.BaseTool2): """ Tool info for the witness checker (witnesslint) (https://github.com/sosy-lab/sv-witnesses) """ def executable(self, tool_locator): return tool_locator.find_executable("witnesslint.py") def name(self): return "witnesslint" def determine_result(self, run): if run.exit_code.value == 0: return result.RESULT_TRUE_PROP else: return result.RESULT_FALSE_PROP <commit_msg>Add version and distinguish linter error from faulty witness.<commit_after>
# This file is part of BenchExec, a framework for reliable benchmarking: # https://github.com/sosy-lab/benchexec # # SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org> # # SPDX-License-Identifier: Apache-2.0 import benchexec.result as result import benchexec.tools.template class Tool(benchexec.tools.template.BaseTool2): """ Tool info for the witness checker (witnesslint) (https://github.com/sosy-lab/sv-witnesses) """ def executable(self, tool_locator): return tool_locator.find_executable("witnesslint.py") def name(self): return "witnesslint" def version(self, executable): version_string = self._version_from_tool(executable) return version_string.partition("version")[2].strip().split(" ")[0] def determine_result(self, run): if run.exit_code.value == 0: return result.RESULT_TRUE_PROP elif run.exit_code.value == 1: return result.RESULT_FALSE_PROP else: return result.RESULT_ERROR
# This file is part of BenchExec, a framework for reliable benchmarking: # https://github.com/sosy-lab/benchexec # # SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org> # # SPDX-License-Identifier: Apache-2.0 import benchexec.result as result import benchexec.tools.template class Tool(benchexec.tools.template.BaseTool2): """ Tool info for the witness checker (witnesslint) (https://github.com/sosy-lab/sv-witnesses) """ def executable(self, tool_locator): return tool_locator.find_executable("witnesslint.py") def name(self): return "witnesslint" def determine_result(self, run): if run.exit_code.value == 0: return result.RESULT_TRUE_PROP else: return result.RESULT_FALSE_PROP Add version and distinguish linter error from faulty witness.# This file is part of BenchExec, a framework for reliable benchmarking: # https://github.com/sosy-lab/benchexec # # SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org> # # SPDX-License-Identifier: Apache-2.0 import benchexec.result as result import benchexec.tools.template class Tool(benchexec.tools.template.BaseTool2): """ Tool info for the witness checker (witnesslint) (https://github.com/sosy-lab/sv-witnesses) """ def executable(self, tool_locator): return tool_locator.find_executable("witnesslint.py") def name(self): return "witnesslint" def version(self, executable): version_string = self._version_from_tool(executable) return version_string.partition("version")[2].strip().split(" ")[0] def determine_result(self, run): if run.exit_code.value == 0: return result.RESULT_TRUE_PROP elif run.exit_code.value == 1: return result.RESULT_FALSE_PROP else: return result.RESULT_ERROR
<commit_before># This file is part of BenchExec, a framework for reliable benchmarking: # https://github.com/sosy-lab/benchexec # # SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org> # # SPDX-License-Identifier: Apache-2.0 import benchexec.result as result import benchexec.tools.template class Tool(benchexec.tools.template.BaseTool2): """ Tool info for the witness checker (witnesslint) (https://github.com/sosy-lab/sv-witnesses) """ def executable(self, tool_locator): return tool_locator.find_executable("witnesslint.py") def name(self): return "witnesslint" def determine_result(self, run): if run.exit_code.value == 0: return result.RESULT_TRUE_PROP else: return result.RESULT_FALSE_PROP <commit_msg>Add version and distinguish linter error from faulty witness.<commit_after># This file is part of BenchExec, a framework for reliable benchmarking: # https://github.com/sosy-lab/benchexec # # SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org> # # SPDX-License-Identifier: Apache-2.0 import benchexec.result as result import benchexec.tools.template class Tool(benchexec.tools.template.BaseTool2): """ Tool info for the witness checker (witnesslint) (https://github.com/sosy-lab/sv-witnesses) """ def executable(self, tool_locator): return tool_locator.find_executable("witnesslint.py") def name(self): return "witnesslint" def version(self, executable): version_string = self._version_from_tool(executable) return version_string.partition("version")[2].strip().split(" ")[0] def determine_result(self, run): if run.exit_code.value == 0: return result.RESULT_TRUE_PROP elif run.exit_code.value == 1: return result.RESULT_FALSE_PROP else: return result.RESULT_ERROR
ad0151eee0027237c8cdd433ef2f24bfa47af5df
pyreaclib/nucdata/tests/test_binding.py
pyreaclib/nucdata/tests/test_binding.py
# unit tests for Binding Energy database taken from AME 2016. import os from pyreaclib.nucdata import BindingTable class TestAME(object): @classmethod def setup_class(cls): """ this is run once for each class before any tests """ pass @classmethod def teardown_class(cls): """ this is run once for each class after all tests """ pass def setup_method(self): """ this is run before each test """ self.bintable = BindingTable() def teardown_method(self): """ this is run after each test """ self.bintable = None def test_get(self): nuc = self.bintable.get_nuclide(n=1, z=1) assert nuc.z == 1 assert nuc.n == 1 assert nuc.nucbind == 1.112283
# unit tests for Binding Energy database taken from AME 2016. import os from pyreaclib.nucdata import BindingTable class TestAME(object): @classmethod def setup_class(cls): """ this is run once for each class before any tests """ pass @classmethod def teardown_class(cls): """ this is run once for each class after all tests """ pass def setup_method(self): """ this is run before each test """ self.bintable = BindingTable() def teardown_method(self): """ this is run after each test """ self.bintable = None def test_get(self): nuc = self.bintable.get_nuclide(n=1, z=1) assert nuc.z == 1 assert nuc.n == 1 assert nuc.nucbind == 1.112283 nuc = self.bintable.get_nuclide(n=5, z=6) assert nuc.z == 6 assert nuc.n == 5 assert nuc.nucbind == 6.676456 nuc = self.bintable.get_nuclide(n=17, z=23) assert nuc.z == 23 assert nuc.n == 17 assert nuc.nucbind == 7.317 nuc = self.bintable.get_nuclide(n=90, z=78) assert nuc.z == 78 assert nuc.n == 90 assert nuc.nucbind == 7.773605
Add some more binding energy table tests.
Add some more binding energy table tests.
Python
bsd-3-clause
pyreaclib/pyreaclib
# unit tests for Binding Energy database taken from AME 2016. import os from pyreaclib.nucdata import BindingTable class TestAME(object): @classmethod def setup_class(cls): """ this is run once for each class before any tests """ pass @classmethod def teardown_class(cls): """ this is run once for each class after all tests """ pass def setup_method(self): """ this is run before each test """ self.bintable = BindingTable() def teardown_method(self): """ this is run after each test """ self.bintable = None def test_get(self): nuc = self.bintable.get_nuclide(n=1, z=1) assert nuc.z == 1 assert nuc.n == 1 assert nuc.nucbind == 1.112283 Add some more binding energy table tests.
# unit tests for Binding Energy database taken from AME 2016. import os from pyreaclib.nucdata import BindingTable class TestAME(object): @classmethod def setup_class(cls): """ this is run once for each class before any tests """ pass @classmethod def teardown_class(cls): """ this is run once for each class after all tests """ pass def setup_method(self): """ this is run before each test """ self.bintable = BindingTable() def teardown_method(self): """ this is run after each test """ self.bintable = None def test_get(self): nuc = self.bintable.get_nuclide(n=1, z=1) assert nuc.z == 1 assert nuc.n == 1 assert nuc.nucbind == 1.112283 nuc = self.bintable.get_nuclide(n=5, z=6) assert nuc.z == 6 assert nuc.n == 5 assert nuc.nucbind == 6.676456 nuc = self.bintable.get_nuclide(n=17, z=23) assert nuc.z == 23 assert nuc.n == 17 assert nuc.nucbind == 7.317 nuc = self.bintable.get_nuclide(n=90, z=78) assert nuc.z == 78 assert nuc.n == 90 assert nuc.nucbind == 7.773605
<commit_before># unit tests for Binding Energy database taken from AME 2016. import os from pyreaclib.nucdata import BindingTable class TestAME(object): @classmethod def setup_class(cls): """ this is run once for each class before any tests """ pass @classmethod def teardown_class(cls): """ this is run once for each class after all tests """ pass def setup_method(self): """ this is run before each test """ self.bintable = BindingTable() def teardown_method(self): """ this is run after each test """ self.bintable = None def test_get(self): nuc = self.bintable.get_nuclide(n=1, z=1) assert nuc.z == 1 assert nuc.n == 1 assert nuc.nucbind == 1.112283 <commit_msg>Add some more binding energy table tests.<commit_after>
# unit tests for Binding Energy database taken from AME 2016. import os from pyreaclib.nucdata import BindingTable class TestAME(object): @classmethod def setup_class(cls): """ this is run once for each class before any tests """ pass @classmethod def teardown_class(cls): """ this is run once for each class after all tests """ pass def setup_method(self): """ this is run before each test """ self.bintable = BindingTable() def teardown_method(self): """ this is run after each test """ self.bintable = None def test_get(self): nuc = self.bintable.get_nuclide(n=1, z=1) assert nuc.z == 1 assert nuc.n == 1 assert nuc.nucbind == 1.112283 nuc = self.bintable.get_nuclide(n=5, z=6) assert nuc.z == 6 assert nuc.n == 5 assert nuc.nucbind == 6.676456 nuc = self.bintable.get_nuclide(n=17, z=23) assert nuc.z == 23 assert nuc.n == 17 assert nuc.nucbind == 7.317 nuc = self.bintable.get_nuclide(n=90, z=78) assert nuc.z == 78 assert nuc.n == 90 assert nuc.nucbind == 7.773605
# unit tests for Binding Energy database taken from AME 2016. import os from pyreaclib.nucdata import BindingTable class TestAME(object): @classmethod def setup_class(cls): """ this is run once for each class before any tests """ pass @classmethod def teardown_class(cls): """ this is run once for each class after all tests """ pass def setup_method(self): """ this is run before each test """ self.bintable = BindingTable() def teardown_method(self): """ this is run after each test """ self.bintable = None def test_get(self): nuc = self.bintable.get_nuclide(n=1, z=1) assert nuc.z == 1 assert nuc.n == 1 assert nuc.nucbind == 1.112283 Add some more binding energy table tests.# unit tests for Binding Energy database taken from AME 2016. import os from pyreaclib.nucdata import BindingTable class TestAME(object): @classmethod def setup_class(cls): """ this is run once for each class before any tests """ pass @classmethod def teardown_class(cls): """ this is run once for each class after all tests """ pass def setup_method(self): """ this is run before each test """ self.bintable = BindingTable() def teardown_method(self): """ this is run after each test """ self.bintable = None def test_get(self): nuc = self.bintable.get_nuclide(n=1, z=1) assert nuc.z == 1 assert nuc.n == 1 assert nuc.nucbind == 1.112283 nuc = self.bintable.get_nuclide(n=5, z=6) assert nuc.z == 6 assert nuc.n == 5 assert nuc.nucbind == 6.676456 nuc = self.bintable.get_nuclide(n=17, z=23) assert nuc.z == 23 assert nuc.n == 17 assert nuc.nucbind == 7.317 nuc = self.bintable.get_nuclide(n=90, z=78) assert nuc.z == 78 assert nuc.n == 90 assert nuc.nucbind == 7.773605
<commit_before># unit tests for Binding Energy database taken from AME 2016. import os from pyreaclib.nucdata import BindingTable class TestAME(object): @classmethod def setup_class(cls): """ this is run once for each class before any tests """ pass @classmethod def teardown_class(cls): """ this is run once for each class after all tests """ pass def setup_method(self): """ this is run before each test """ self.bintable = BindingTable() def teardown_method(self): """ this is run after each test """ self.bintable = None def test_get(self): nuc = self.bintable.get_nuclide(n=1, z=1) assert nuc.z == 1 assert nuc.n == 1 assert nuc.nucbind == 1.112283 <commit_msg>Add some more binding energy table tests.<commit_after># unit tests for Binding Energy database taken from AME 2016. import os from pyreaclib.nucdata import BindingTable class TestAME(object): @classmethod def setup_class(cls): """ this is run once for each class before any tests """ pass @classmethod def teardown_class(cls): """ this is run once for each class after all tests """ pass def setup_method(self): """ this is run before each test """ self.bintable = BindingTable() def teardown_method(self): """ this is run after each test """ self.bintable = None def test_get(self): nuc = self.bintable.get_nuclide(n=1, z=1) assert nuc.z == 1 assert nuc.n == 1 assert nuc.nucbind == 1.112283 nuc = self.bintable.get_nuclide(n=5, z=6) assert nuc.z == 6 assert nuc.n == 5 assert nuc.nucbind == 6.676456 nuc = self.bintable.get_nuclide(n=17, z=23) assert nuc.z == 23 assert nuc.n == 17 assert nuc.nucbind == 7.317 nuc = self.bintable.get_nuclide(n=90, z=78) assert nuc.z == 78 assert nuc.n == 90 assert nuc.nucbind == 7.773605
a37f67d6dfbcbadfcce3fe05891e525e3d3f5033
catalog/project.py
catalog/project.py
# Skeleton Flask Project from flask import Flask app = Flask(__name__) # Pass in default file name as parameter # Decorators for methods to execute based on route(s) @app.route('/') @app.route('/hello') def HelloWorld(): return "Hello World." # __main__ is the default name given to the application run by the Python # interpreter. The below if statement only runs if this file is being executed # by it explicitly. If it's imported, the below won't run if __name__ == '__main__': app.debug = True # Will reload automatically when code changes app.run(host='0.0.0.0', port=5000) # Run on public IP, port 5000
from flask import Flask from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from database_setup import Base, Restaurant, MenuItem def createDBSession(): """Connect to database and return session""" engine = create_engine('sqlite:///restaurantmenu.db', echo=True) Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() return session app = Flask(__name__) # Pass in default file name as parameter # Decorators for methods to execute based on route(s) @app.route('/') @app.route('/restaurants/<int:restaurant_id>/') def restaurantMenu(restaurant_id): session = createDBSession() restaurant = session.query(Restaurant).\ filter(Restaurant.id == restaurant_id).one() items = session.query(MenuItem).\ filter(MenuItem.restaurant_id == restaurant.id).all() output = "" for item in items: output += ("<p><strong>%s</strong><br>%s<br>%s</p>") % ( item.name, item.price, item.description) return output # __main__ is the default name given to the application run by the Python # interpreter. The below if statement only runs if this file is being executed # by it explicitly. If it's imported, the below won't run if __name__ == '__main__': app.debug = True # Will reload automatically when code changes app.run(host='0.0.0.0', port=5000) # Run on public IP, port 5000
Add database imports and restaurant routes
feat: Add database imports and restaurant routes
Python
mit
rupert-ong/python-flask-crud,rupert-ong/python-flask-crud,rupert-ong/python-flask-crud
# Skeleton Flask Project from flask import Flask app = Flask(__name__) # Pass in default file name as parameter # Decorators for methods to execute based on route(s) @app.route('/') @app.route('/hello') def HelloWorld(): return "Hello World." # __main__ is the default name given to the application run by the Python # interpreter. The below if statement only runs if this file is being executed # by it explicitly. If it's imported, the below won't run if __name__ == '__main__': app.debug = True # Will reload automatically when code changes app.run(host='0.0.0.0', port=5000) # Run on public IP, port 5000 feat: Add database imports and restaurant routes
from flask import Flask from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from database_setup import Base, Restaurant, MenuItem def createDBSession(): """Connect to database and return session""" engine = create_engine('sqlite:///restaurantmenu.db', echo=True) Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() return session app = Flask(__name__) # Pass in default file name as parameter # Decorators for methods to execute based on route(s) @app.route('/') @app.route('/restaurants/<int:restaurant_id>/') def restaurantMenu(restaurant_id): session = createDBSession() restaurant = session.query(Restaurant).\ filter(Restaurant.id == restaurant_id).one() items = session.query(MenuItem).\ filter(MenuItem.restaurant_id == restaurant.id).all() output = "" for item in items: output += ("<p><strong>%s</strong><br>%s<br>%s</p>") % ( item.name, item.price, item.description) return output # __main__ is the default name given to the application run by the Python # interpreter. The below if statement only runs if this file is being executed # by it explicitly. If it's imported, the below won't run if __name__ == '__main__': app.debug = True # Will reload automatically when code changes app.run(host='0.0.0.0', port=5000) # Run on public IP, port 5000
<commit_before># Skeleton Flask Project from flask import Flask app = Flask(__name__) # Pass in default file name as parameter # Decorators for methods to execute based on route(s) @app.route('/') @app.route('/hello') def HelloWorld(): return "Hello World." # __main__ is the default name given to the application run by the Python # interpreter. The below if statement only runs if this file is being executed # by it explicitly. If it's imported, the below won't run if __name__ == '__main__': app.debug = True # Will reload automatically when code changes app.run(host='0.0.0.0', port=5000) # Run on public IP, port 5000 <commit_msg>feat: Add database imports and restaurant routes<commit_after>
from flask import Flask from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from database_setup import Base, Restaurant, MenuItem def createDBSession(): """Connect to database and return session""" engine = create_engine('sqlite:///restaurantmenu.db', echo=True) Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() return session app = Flask(__name__) # Pass in default file name as parameter # Decorators for methods to execute based on route(s) @app.route('/') @app.route('/restaurants/<int:restaurant_id>/') def restaurantMenu(restaurant_id): session = createDBSession() restaurant = session.query(Restaurant).\ filter(Restaurant.id == restaurant_id).one() items = session.query(MenuItem).\ filter(MenuItem.restaurant_id == restaurant.id).all() output = "" for item in items: output += ("<p><strong>%s</strong><br>%s<br>%s</p>") % ( item.name, item.price, item.description) return output # __main__ is the default name given to the application run by the Python # interpreter. The below if statement only runs if this file is being executed # by it explicitly. If it's imported, the below won't run if __name__ == '__main__': app.debug = True # Will reload automatically when code changes app.run(host='0.0.0.0', port=5000) # Run on public IP, port 5000
# Skeleton Flask Project from flask import Flask app = Flask(__name__) # Pass in default file name as parameter # Decorators for methods to execute based on route(s) @app.route('/') @app.route('/hello') def HelloWorld(): return "Hello World." # __main__ is the default name given to the application run by the Python # interpreter. The below if statement only runs if this file is being executed # by it explicitly. If it's imported, the below won't run if __name__ == '__main__': app.debug = True # Will reload automatically when code changes app.run(host='0.0.0.0', port=5000) # Run on public IP, port 5000 feat: Add database imports and restaurant routesfrom flask import Flask from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from database_setup import Base, Restaurant, MenuItem def createDBSession(): """Connect to database and return session""" engine = create_engine('sqlite:///restaurantmenu.db', echo=True) Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() return session app = Flask(__name__) # Pass in default file name as parameter # Decorators for methods to execute based on route(s) @app.route('/') @app.route('/restaurants/<int:restaurant_id>/') def restaurantMenu(restaurant_id): session = createDBSession() restaurant = session.query(Restaurant).\ filter(Restaurant.id == restaurant_id).one() items = session.query(MenuItem).\ filter(MenuItem.restaurant_id == restaurant.id).all() output = "" for item in items: output += ("<p><strong>%s</strong><br>%s<br>%s</p>") % ( item.name, item.price, item.description) return output # __main__ is the default name given to the application run by the Python # interpreter. The below if statement only runs if this file is being executed # by it explicitly. If it's imported, the below won't run if __name__ == '__main__': app.debug = True # Will reload automatically when code changes app.run(host='0.0.0.0', port=5000) # Run on public IP, port 5000
<commit_before># Skeleton Flask Project from flask import Flask app = Flask(__name__) # Pass in default file name as parameter # Decorators for methods to execute based on route(s) @app.route('/') @app.route('/hello') def HelloWorld(): return "Hello World." # __main__ is the default name given to the application run by the Python # interpreter. The below if statement only runs if this file is being executed # by it explicitly. If it's imported, the below won't run if __name__ == '__main__': app.debug = True # Will reload automatically when code changes app.run(host='0.0.0.0', port=5000) # Run on public IP, port 5000 <commit_msg>feat: Add database imports and restaurant routes<commit_after>from flask import Flask from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from database_setup import Base, Restaurant, MenuItem def createDBSession(): """Connect to database and return session""" engine = create_engine('sqlite:///restaurantmenu.db', echo=True) Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() return session app = Flask(__name__) # Pass in default file name as parameter # Decorators for methods to execute based on route(s) @app.route('/') @app.route('/restaurants/<int:restaurant_id>/') def restaurantMenu(restaurant_id): session = createDBSession() restaurant = session.query(Restaurant).\ filter(Restaurant.id == restaurant_id).one() items = session.query(MenuItem).\ filter(MenuItem.restaurant_id == restaurant.id).all() output = "" for item in items: output += ("<p><strong>%s</strong><br>%s<br>%s</p>") % ( item.name, item.price, item.description) return output # __main__ is the default name given to the application run by the Python # interpreter. The below if statement only runs if this file is being executed # by it explicitly. If it's imported, the below won't run if __name__ == '__main__': app.debug = True # Will reload automatically when code changes app.run(host='0.0.0.0', port=5000) # Run on public IP, port 5000
3d4a2ec91d6d13f19ea7ec0370a9fb3504c4633e
pywikibot/families/wikivoyage_family.py
pywikibot/families/wikivoyage_family.py
# -*- coding: utf-8 -*- __version__ = '$Id$' # The new wikivoyage family that is hosted at wikimedia from pywikibot import family class Family(family.WikimediaFamily): def __init__(self): super(Family, self).__init__() self.name = 'wikivoyage' self.languages_by_size = [ 'en', 'de', 'pt', 'fr', 'it', 'nl', 'pl', 'ru', 'es', 'vi', 'sv', 'he', 'ro', 'uk', 'el', ] self.langs = dict([(lang, '%s.wikivoyage.org' % lang) for lang in self.languages_by_size]) # Global bot allowed languages on http://meta.wikimedia.org/wiki/Bot_policy/Implementation#Current_implementation self.cross_allowed = ['es', 'ru', ] def shared_data_repository(self, code, transcluded=False): return ('wikidata', 'wikidata')
# -*- coding: utf-8 -*- __version__ = '$Id$' # The new wikivoyage family that is hosted at wikimedia from pywikibot import family class Family(family.WikimediaFamily): def __init__(self): super(Family, self).__init__() self.name = 'wikivoyage' self.languages_by_size = [ 'en', 'de', 'pt', 'fr', 'it', 'nl', 'pl', 'ru', 'es', 'vi', 'sv', 'he', 'zh', 'ro', 'uk', 'el', ] self.langs = dict([(lang, '%s.wikivoyage.org' % lang) for lang in self.languages_by_size]) # Global bot allowed languages on http://meta.wikimedia.org/wiki/Bot_policy/Implementation#Current_implementation self.cross_allowed = ['es', 'ru', ] def shared_data_repository(self, code, transcluded=False): return ('wikidata', 'wikidata')
Add lang 'zh' to family 'wikivoyage' , update from compat
Add lang 'zh' to family 'wikivoyage' , update from compat Change-Id: Ic6c64f356511d1f92eefe9e813c9564786b2b5a5
Python
mit
darthbhyrava/pywikibot-local,happy5214/pywikibot-core,xZise/pywikibot-core,TridevGuha/pywikibot-core,Darkdadaah/pywikibot-core,npdoty/pywikibot,hasteur/g13bot_tools_new,wikimedia/pywikibot-core,hasteur/g13bot_tools_new,jayvdb/pywikibot-core,PersianWikipedia/pywikibot-core,valhallasw/pywikibot-core,icyflame/batman,hasteur/g13bot_tools_new,smalyshev/pywikibot-core,emijrp/pywikibot-core,Darkdadaah/pywikibot-core,happy5214/pywikibot-core,jayvdb/pywikibot-core,magul/pywikibot-core,npdoty/pywikibot,h4ck3rm1k3/pywikibot-core,magul/pywikibot-core,h4ck3rm1k3/pywikibot-core,wikimedia/pywikibot-core,VcamX/pywikibot-core,trishnaguha/pywikibot-core
# -*- coding: utf-8 -*- __version__ = '$Id$' # The new wikivoyage family that is hosted at wikimedia from pywikibot import family class Family(family.WikimediaFamily): def __init__(self): super(Family, self).__init__() self.name = 'wikivoyage' self.languages_by_size = [ 'en', 'de', 'pt', 'fr', 'it', 'nl', 'pl', 'ru', 'es', 'vi', 'sv', 'he', 'ro', 'uk', 'el', ] self.langs = dict([(lang, '%s.wikivoyage.org' % lang) for lang in self.languages_by_size]) # Global bot allowed languages on http://meta.wikimedia.org/wiki/Bot_policy/Implementation#Current_implementation self.cross_allowed = ['es', 'ru', ] def shared_data_repository(self, code, transcluded=False): return ('wikidata', 'wikidata') Add lang 'zh' to family 'wikivoyage' , update from compat Change-Id: Ic6c64f356511d1f92eefe9e813c9564786b2b5a5
# -*- coding: utf-8 -*- __version__ = '$Id$' # The new wikivoyage family that is hosted at wikimedia from pywikibot import family class Family(family.WikimediaFamily): def __init__(self): super(Family, self).__init__() self.name = 'wikivoyage' self.languages_by_size = [ 'en', 'de', 'pt', 'fr', 'it', 'nl', 'pl', 'ru', 'es', 'vi', 'sv', 'he', 'zh', 'ro', 'uk', 'el', ] self.langs = dict([(lang, '%s.wikivoyage.org' % lang) for lang in self.languages_by_size]) # Global bot allowed languages on http://meta.wikimedia.org/wiki/Bot_policy/Implementation#Current_implementation self.cross_allowed = ['es', 'ru', ] def shared_data_repository(self, code, transcluded=False): return ('wikidata', 'wikidata')
<commit_before># -*- coding: utf-8 -*- __version__ = '$Id$' # The new wikivoyage family that is hosted at wikimedia from pywikibot import family class Family(family.WikimediaFamily): def __init__(self): super(Family, self).__init__() self.name = 'wikivoyage' self.languages_by_size = [ 'en', 'de', 'pt', 'fr', 'it', 'nl', 'pl', 'ru', 'es', 'vi', 'sv', 'he', 'ro', 'uk', 'el', ] self.langs = dict([(lang, '%s.wikivoyage.org' % lang) for lang in self.languages_by_size]) # Global bot allowed languages on http://meta.wikimedia.org/wiki/Bot_policy/Implementation#Current_implementation self.cross_allowed = ['es', 'ru', ] def shared_data_repository(self, code, transcluded=False): return ('wikidata', 'wikidata') <commit_msg>Add lang 'zh' to family 'wikivoyage' , update from compat Change-Id: Ic6c64f356511d1f92eefe9e813c9564786b2b5a5<commit_after>
# -*- coding: utf-8 -*- __version__ = '$Id$' # The new wikivoyage family that is hosted at wikimedia from pywikibot import family class Family(family.WikimediaFamily): def __init__(self): super(Family, self).__init__() self.name = 'wikivoyage' self.languages_by_size = [ 'en', 'de', 'pt', 'fr', 'it', 'nl', 'pl', 'ru', 'es', 'vi', 'sv', 'he', 'zh', 'ro', 'uk', 'el', ] self.langs = dict([(lang, '%s.wikivoyage.org' % lang) for lang in self.languages_by_size]) # Global bot allowed languages on http://meta.wikimedia.org/wiki/Bot_policy/Implementation#Current_implementation self.cross_allowed = ['es', 'ru', ] def shared_data_repository(self, code, transcluded=False): return ('wikidata', 'wikidata')
# -*- coding: utf-8 -*- __version__ = '$Id$' # The new wikivoyage family that is hosted at wikimedia from pywikibot import family class Family(family.WikimediaFamily): def __init__(self): super(Family, self).__init__() self.name = 'wikivoyage' self.languages_by_size = [ 'en', 'de', 'pt', 'fr', 'it', 'nl', 'pl', 'ru', 'es', 'vi', 'sv', 'he', 'ro', 'uk', 'el', ] self.langs = dict([(lang, '%s.wikivoyage.org' % lang) for lang in self.languages_by_size]) # Global bot allowed languages on http://meta.wikimedia.org/wiki/Bot_policy/Implementation#Current_implementation self.cross_allowed = ['es', 'ru', ] def shared_data_repository(self, code, transcluded=False): return ('wikidata', 'wikidata') Add lang 'zh' to family 'wikivoyage' , update from compat Change-Id: Ic6c64f356511d1f92eefe9e813c9564786b2b5a5# -*- coding: utf-8 -*- __version__ = '$Id$' # The new wikivoyage family that is hosted at wikimedia from pywikibot import family class Family(family.WikimediaFamily): def __init__(self): super(Family, self).__init__() self.name = 'wikivoyage' self.languages_by_size = [ 'en', 'de', 'pt', 'fr', 'it', 'nl', 'pl', 'ru', 'es', 'vi', 'sv', 'he', 'zh', 'ro', 'uk', 'el', ] self.langs = dict([(lang, '%s.wikivoyage.org' % lang) for lang in self.languages_by_size]) # Global bot allowed languages on http://meta.wikimedia.org/wiki/Bot_policy/Implementation#Current_implementation self.cross_allowed = ['es', 'ru', ] def shared_data_repository(self, code, transcluded=False): return ('wikidata', 'wikidata')
<commit_before># -*- coding: utf-8 -*- __version__ = '$Id$' # The new wikivoyage family that is hosted at wikimedia from pywikibot import family class Family(family.WikimediaFamily): def __init__(self): super(Family, self).__init__() self.name = 'wikivoyage' self.languages_by_size = [ 'en', 'de', 'pt', 'fr', 'it', 'nl', 'pl', 'ru', 'es', 'vi', 'sv', 'he', 'ro', 'uk', 'el', ] self.langs = dict([(lang, '%s.wikivoyage.org' % lang) for lang in self.languages_by_size]) # Global bot allowed languages on http://meta.wikimedia.org/wiki/Bot_policy/Implementation#Current_implementation self.cross_allowed = ['es', 'ru', ] def shared_data_repository(self, code, transcluded=False): return ('wikidata', 'wikidata') <commit_msg>Add lang 'zh' to family 'wikivoyage' , update from compat Change-Id: Ic6c64f356511d1f92eefe9e813c9564786b2b5a5<commit_after># -*- coding: utf-8 -*- __version__ = '$Id$' # The new wikivoyage family that is hosted at wikimedia from pywikibot import family class Family(family.WikimediaFamily): def __init__(self): super(Family, self).__init__() self.name = 'wikivoyage' self.languages_by_size = [ 'en', 'de', 'pt', 'fr', 'it', 'nl', 'pl', 'ru', 'es', 'vi', 'sv', 'he', 'zh', 'ro', 'uk', 'el', ] self.langs = dict([(lang, '%s.wikivoyage.org' % lang) for lang in self.languages_by_size]) # Global bot allowed languages on http://meta.wikimedia.org/wiki/Bot_policy/Implementation#Current_implementation self.cross_allowed = ['es', 'ru', ] def shared_data_repository(self, code, transcluded=False): return ('wikidata', 'wikidata')
629fab227cb5d564d6cb7d9469c76915eb6c72ac
backend/breach/helpers/network.py
backend/breach/helpers/network.py
import netifaces def get_interface(): return netifaces.gateways()['default'][netifaces.AF_INET][1]
import netifaces def get_interface(): return netifaces.gateways()['default'][netifaces.AF_INET][1] def get_local_IP(): def_gw_device = get_interface() return netifaces.ifaddresses(def_gw_device)[netifaces.AF_INET][0]['addr']
Add function to get the machine's local IP
Add function to get the machine's local IP
Python
mit
esarafianou/rupture,dimriou/rupture,dimriou/rupture,dimkarakostas/rupture,dimkarakostas/rupture,dimkarakostas/rupture,dionyziz/rupture,dimriou/rupture,dionyziz/rupture,dimkarakostas/rupture,esarafianou/rupture,dionyziz/rupture,dimriou/rupture,esarafianou/rupture,esarafianou/rupture,dimkarakostas/rupture,dimriou/rupture,dionyziz/rupture,dionyziz/rupture
import netifaces def get_interface(): return netifaces.gateways()['default'][netifaces.AF_INET][1] Add function to get the machine's local IP
import netifaces def get_interface(): return netifaces.gateways()['default'][netifaces.AF_INET][1] def get_local_IP(): def_gw_device = get_interface() return netifaces.ifaddresses(def_gw_device)[netifaces.AF_INET][0]['addr']
<commit_before>import netifaces def get_interface(): return netifaces.gateways()['default'][netifaces.AF_INET][1] <commit_msg>Add function to get the machine's local IP<commit_after>
import netifaces def get_interface(): return netifaces.gateways()['default'][netifaces.AF_INET][1] def get_local_IP(): def_gw_device = get_interface() return netifaces.ifaddresses(def_gw_device)[netifaces.AF_INET][0]['addr']
import netifaces def get_interface(): return netifaces.gateways()['default'][netifaces.AF_INET][1] Add function to get the machine's local IPimport netifaces def get_interface(): return netifaces.gateways()['default'][netifaces.AF_INET][1] def get_local_IP(): def_gw_device = get_interface() return netifaces.ifaddresses(def_gw_device)[netifaces.AF_INET][0]['addr']
<commit_before>import netifaces def get_interface(): return netifaces.gateways()['default'][netifaces.AF_INET][1] <commit_msg>Add function to get the machine's local IP<commit_after>import netifaces def get_interface(): return netifaces.gateways()['default'][netifaces.AF_INET][1] def get_local_IP(): def_gw_device = get_interface() return netifaces.ifaddresses(def_gw_device)[netifaces.AF_INET][0]['addr']
9dce07895a773998469aeed8c1cfb8476d4264eb
application.py
application.py
#!/usr/bin/env python import os from app import create_app from flask.ext.script import Manager application = create_app(os.getenv('FLASH_CONFIG') or 'development') manager = Manager(application) if __name__ == '__main__': manager.run()
#!/usr/bin/env python import os from app import create_app from flask.ext.script import Manager, Server application = create_app(os.getenv('FLASH_CONFIG') or 'development') manager = Manager(application) manager.add_command("runserver", Server(port=5001)) if __name__ == '__main__': manager.run()
Update to run on port 5001
Update to run on port 5001 For development we will want to run multiple apps, so they should each bind to a different port number.
Python
mit
RichardKnop/digitalmarketplace-search-api,RichardKnop/digitalmarketplace-search-api,RichardKnop/digitalmarketplace-search-api,RichardKnop/digitalmarketplace-search-api,alphagov/digitalmarketplace-search-api,alphagov/digitalmarketplace-search-api
#!/usr/bin/env python import os from app import create_app from flask.ext.script import Manager application = create_app(os.getenv('FLASH_CONFIG') or 'development') manager = Manager(application) if __name__ == '__main__': manager.run() Update to run on port 5001 For development we will want to run multiple apps, so they should each bind to a different port number.
#!/usr/bin/env python import os from app import create_app from flask.ext.script import Manager, Server application = create_app(os.getenv('FLASH_CONFIG') or 'development') manager = Manager(application) manager.add_command("runserver", Server(port=5001)) if __name__ == '__main__': manager.run()
<commit_before>#!/usr/bin/env python import os from app import create_app from flask.ext.script import Manager application = create_app(os.getenv('FLASH_CONFIG') or 'development') manager = Manager(application) if __name__ == '__main__': manager.run() <commit_msg>Update to run on port 5001 For development we will want to run multiple apps, so they should each bind to a different port number.<commit_after>
#!/usr/bin/env python import os from app import create_app from flask.ext.script import Manager, Server application = create_app(os.getenv('FLASH_CONFIG') or 'development') manager = Manager(application) manager.add_command("runserver", Server(port=5001)) if __name__ == '__main__': manager.run()
#!/usr/bin/env python import os from app import create_app from flask.ext.script import Manager application = create_app(os.getenv('FLASH_CONFIG') or 'development') manager = Manager(application) if __name__ == '__main__': manager.run() Update to run on port 5001 For development we will want to run multiple apps, so they should each bind to a different port number.#!/usr/bin/env python import os from app import create_app from flask.ext.script import Manager, Server application = create_app(os.getenv('FLASH_CONFIG') or 'development') manager = Manager(application) manager.add_command("runserver", Server(port=5001)) if __name__ == '__main__': manager.run()
<commit_before>#!/usr/bin/env python import os from app import create_app from flask.ext.script import Manager application = create_app(os.getenv('FLASH_CONFIG') or 'development') manager = Manager(application) if __name__ == '__main__': manager.run() <commit_msg>Update to run on port 5001 For development we will want to run multiple apps, so they should each bind to a different port number.<commit_after>#!/usr/bin/env python import os from app import create_app from flask.ext.script import Manager, Server application = create_app(os.getenv('FLASH_CONFIG') or 'development') manager = Manager(application) manager.add_command("runserver", Server(port=5001)) if __name__ == '__main__': manager.run()
384eab108578d372c9755cf1a1a22738f7cd3dea
app/utils/__init__.py
app/utils/__init__.py
# Copyright (C) 2014 Linaro Ltd. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from utils.log import get_log BASE_PATH = '/var/www/images/kernel-ci' LOG = get_log()
# Copyright (C) 2014 Linaro Ltd. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from utils.log import get_log BASE_PATH = '/var/www/images/kernel-ci' LOG = get_log() def is_hidden(value): """Verify if a file name or dir name is hidden (starts with .). :param value: The value to verify. :return True or False. """ hidden = False if value.startswith('.'): hidden = True return hidden
Create function to test hidden files/dirs.
Create function to test hidden files/dirs. Change-Id: I67e8d69fc85dfe58e4f127007c73f6888deff3e0
Python
agpl-3.0
joyxu/kernelci-backend,joyxu/kernelci-backend,kernelci/kernelci-backend,joyxu/kernelci-backend,kernelci/kernelci-backend
# Copyright (C) 2014 Linaro Ltd. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from utils.log import get_log BASE_PATH = '/var/www/images/kernel-ci' LOG = get_log() Create function to test hidden files/dirs. Change-Id: I67e8d69fc85dfe58e4f127007c73f6888deff3e0
# Copyright (C) 2014 Linaro Ltd. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from utils.log import get_log BASE_PATH = '/var/www/images/kernel-ci' LOG = get_log() def is_hidden(value): """Verify if a file name or dir name is hidden (starts with .). :param value: The value to verify. :return True or False. """ hidden = False if value.startswith('.'): hidden = True return hidden
<commit_before># Copyright (C) 2014 Linaro Ltd. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from utils.log import get_log BASE_PATH = '/var/www/images/kernel-ci' LOG = get_log() <commit_msg>Create function to test hidden files/dirs. Change-Id: I67e8d69fc85dfe58e4f127007c73f6888deff3e0<commit_after>
# Copyright (C) 2014 Linaro Ltd. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from utils.log import get_log BASE_PATH = '/var/www/images/kernel-ci' LOG = get_log() def is_hidden(value): """Verify if a file name or dir name is hidden (starts with .). :param value: The value to verify. :return True or False. """ hidden = False if value.startswith('.'): hidden = True return hidden
# Copyright (C) 2014 Linaro Ltd. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from utils.log import get_log BASE_PATH = '/var/www/images/kernel-ci' LOG = get_log() Create function to test hidden files/dirs. Change-Id: I67e8d69fc85dfe58e4f127007c73f6888deff3e0# Copyright (C) 2014 Linaro Ltd. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from utils.log import get_log BASE_PATH = '/var/www/images/kernel-ci' LOG = get_log() def is_hidden(value): """Verify if a file name or dir name is hidden (starts with .). :param value: The value to verify. :return True or False. """ hidden = False if value.startswith('.'): hidden = True return hidden
<commit_before># Copyright (C) 2014 Linaro Ltd. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from utils.log import get_log BASE_PATH = '/var/www/images/kernel-ci' LOG = get_log() <commit_msg>Create function to test hidden files/dirs. Change-Id: I67e8d69fc85dfe58e4f127007c73f6888deff3e0<commit_after># Copyright (C) 2014 Linaro Ltd. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from utils.log import get_log BASE_PATH = '/var/www/images/kernel-ci' LOG = get_log() def is_hidden(value): """Verify if a file name or dir name is hidden (starts with .). :param value: The value to verify. :return True or False. """ hidden = False if value.startswith('.'): hidden = True return hidden
74bfe9bf1501d5c31e2ab6d8dc174467e47e200e
app/dao/magazines_dao.py
app/dao/magazines_dao.py
from app import db from app.dao.decorators import transactional from app.models import Magazine def dao_get_magazines(): return Magazine.query.order_by(Magazine.created_at.desc()).all() def dao_get_magazine_by_old_id(old_id): return Magazine.query.filter_by(old_id=old_id).first()
from app import db from app.dao.decorators import transactional from app.models import Magazine def dao_get_magazines(): return Magazine.query.order_by(Magazine.created_at.desc()).all() def dao_get_magazine_by_id(id): return Magazine.query.filter_by(id=id).one() def dao_get_magazine_by_old_id(old_id): return Magazine.query.filter_by(old_id=old_id).first()
Add get magazine by id to magazine dao
Add get magazine by id to magazine dao
Python
mit
NewAcropolis/api,NewAcropolis/api,NewAcropolis/api
from app import db from app.dao.decorators import transactional from app.models import Magazine def dao_get_magazines(): return Magazine.query.order_by(Magazine.created_at.desc()).all() def dao_get_magazine_by_old_id(old_id): return Magazine.query.filter_by(old_id=old_id).first() Add get magazine by id to magazine dao
from app import db from app.dao.decorators import transactional from app.models import Magazine def dao_get_magazines(): return Magazine.query.order_by(Magazine.created_at.desc()).all() def dao_get_magazine_by_id(id): return Magazine.query.filter_by(id=id).one() def dao_get_magazine_by_old_id(old_id): return Magazine.query.filter_by(old_id=old_id).first()
<commit_before>from app import db from app.dao.decorators import transactional from app.models import Magazine def dao_get_magazines(): return Magazine.query.order_by(Magazine.created_at.desc()).all() def dao_get_magazine_by_old_id(old_id): return Magazine.query.filter_by(old_id=old_id).first() <commit_msg>Add get magazine by id to magazine dao<commit_after>
from app import db from app.dao.decorators import transactional from app.models import Magazine def dao_get_magazines(): return Magazine.query.order_by(Magazine.created_at.desc()).all() def dao_get_magazine_by_id(id): return Magazine.query.filter_by(id=id).one() def dao_get_magazine_by_old_id(old_id): return Magazine.query.filter_by(old_id=old_id).first()
from app import db from app.dao.decorators import transactional from app.models import Magazine def dao_get_magazines(): return Magazine.query.order_by(Magazine.created_at.desc()).all() def dao_get_magazine_by_old_id(old_id): return Magazine.query.filter_by(old_id=old_id).first() Add get magazine by id to magazine daofrom app import db from app.dao.decorators import transactional from app.models import Magazine def dao_get_magazines(): return Magazine.query.order_by(Magazine.created_at.desc()).all() def dao_get_magazine_by_id(id): return Magazine.query.filter_by(id=id).one() def dao_get_magazine_by_old_id(old_id): return Magazine.query.filter_by(old_id=old_id).first()
<commit_before>from app import db from app.dao.decorators import transactional from app.models import Magazine def dao_get_magazines(): return Magazine.query.order_by(Magazine.created_at.desc()).all() def dao_get_magazine_by_old_id(old_id): return Magazine.query.filter_by(old_id=old_id).first() <commit_msg>Add get magazine by id to magazine dao<commit_after>from app import db from app.dao.decorators import transactional from app.models import Magazine def dao_get_magazines(): return Magazine.query.order_by(Magazine.created_at.desc()).all() def dao_get_magazine_by_id(id): return Magazine.query.filter_by(id=id).one() def dao_get_magazine_by_old_id(old_id): return Magazine.query.filter_by(old_id=old_id).first()
065dd5aef4925e1c9519b083db26b36ab0cfe06c
scripts/master/factory/dart/channels.py
scripts/master/factory/dart/channels.py
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. class Channel(object): def __init__(self, name, branch, position, category_postfix, priority): self.branch = branch self.builder_postfix = '-' + name self.category_postfix = category_postfix self.name = name self.position = position self.priority = priority self.all_deps_path = '/' + branch + '/deps/all.deps' self.standalone_deps_path = '/' + branch + '/deps/standalone.deps' self.dartium_deps_path = '/' + branch + '/deps/dartium.deps' # The channel names are replicated in the slave.cfg files for all # dart waterfalls. If you change anything here please also change it there. CHANNELS = [ Channel('be', 'branches/bleeding_edge', 0, '', 4), Channel('dev', 'trunk', 1, '-dev', 2), Channel('stable', 'branches/1.3', 2, '-stable', 1), Channel('integration', 'branches/dartium_integration', 3, '-integration', 3), ] CHANNELS_BY_NAME = {} for c in CHANNELS: CHANNELS_BY_NAME[c.name] = c
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. class Channel(object): def __init__(self, name, branch, position, category_postfix, priority): self.branch = branch self.builder_postfix = '-' + name self.category_postfix = category_postfix self.name = name self.position = position self.priority = priority self.all_deps_path = '/' + branch + '/deps/all.deps' self.standalone_deps_path = '/' + branch + '/deps/standalone.deps' self.dartium_deps_path = '/' + branch + '/deps/dartium.deps' # The channel names are replicated in the slave.cfg files for all # dart waterfalls. If you change anything here please also change it there. CHANNELS = [ Channel('be', 'branches/bleeding_edge', 0, '', 4), Channel('dev', 'trunk', 1, '-dev', 2), Channel('stable', 'branches/1.4', 2, '-stable', 1), Channel('integration', 'branches/dartium_integration', 3, '-integration', 3), ] CHANNELS_BY_NAME = {} for c in CHANNELS: CHANNELS_BY_NAME[c.name] = c
Update stable builders to pull from 1.4 branch
Update stable builders to pull from 1.4 branch Review URL: https://codereview.chromium.org/295923003 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@271609 0039d316-1c4b-4281-b951-d872f2087c98
Python
bsd-3-clause
eunchong/build,eunchong/build,eunchong/build,eunchong/build
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. class Channel(object): def __init__(self, name, branch, position, category_postfix, priority): self.branch = branch self.builder_postfix = '-' + name self.category_postfix = category_postfix self.name = name self.position = position self.priority = priority self.all_deps_path = '/' + branch + '/deps/all.deps' self.standalone_deps_path = '/' + branch + '/deps/standalone.deps' self.dartium_deps_path = '/' + branch + '/deps/dartium.deps' # The channel names are replicated in the slave.cfg files for all # dart waterfalls. If you change anything here please also change it there. CHANNELS = [ Channel('be', 'branches/bleeding_edge', 0, '', 4), Channel('dev', 'trunk', 1, '-dev', 2), Channel('stable', 'branches/1.3', 2, '-stable', 1), Channel('integration', 'branches/dartium_integration', 3, '-integration', 3), ] CHANNELS_BY_NAME = {} for c in CHANNELS: CHANNELS_BY_NAME[c.name] = c Update stable builders to pull from 1.4 branch Review URL: https://codereview.chromium.org/295923003 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@271609 0039d316-1c4b-4281-b951-d872f2087c98
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. class Channel(object): def __init__(self, name, branch, position, category_postfix, priority): self.branch = branch self.builder_postfix = '-' + name self.category_postfix = category_postfix self.name = name self.position = position self.priority = priority self.all_deps_path = '/' + branch + '/deps/all.deps' self.standalone_deps_path = '/' + branch + '/deps/standalone.deps' self.dartium_deps_path = '/' + branch + '/deps/dartium.deps' # The channel names are replicated in the slave.cfg files for all # dart waterfalls. If you change anything here please also change it there. CHANNELS = [ Channel('be', 'branches/bleeding_edge', 0, '', 4), Channel('dev', 'trunk', 1, '-dev', 2), Channel('stable', 'branches/1.4', 2, '-stable', 1), Channel('integration', 'branches/dartium_integration', 3, '-integration', 3), ] CHANNELS_BY_NAME = {} for c in CHANNELS: CHANNELS_BY_NAME[c.name] = c
<commit_before># Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. class Channel(object): def __init__(self, name, branch, position, category_postfix, priority): self.branch = branch self.builder_postfix = '-' + name self.category_postfix = category_postfix self.name = name self.position = position self.priority = priority self.all_deps_path = '/' + branch + '/deps/all.deps' self.standalone_deps_path = '/' + branch + '/deps/standalone.deps' self.dartium_deps_path = '/' + branch + '/deps/dartium.deps' # The channel names are replicated in the slave.cfg files for all # dart waterfalls. If you change anything here please also change it there. CHANNELS = [ Channel('be', 'branches/bleeding_edge', 0, '', 4), Channel('dev', 'trunk', 1, '-dev', 2), Channel('stable', 'branches/1.3', 2, '-stable', 1), Channel('integration', 'branches/dartium_integration', 3, '-integration', 3), ] CHANNELS_BY_NAME = {} for c in CHANNELS: CHANNELS_BY_NAME[c.name] = c <commit_msg>Update stable builders to pull from 1.4 branch Review URL: https://codereview.chromium.org/295923003 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@271609 0039d316-1c4b-4281-b951-d872f2087c98<commit_after>
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. class Channel(object): def __init__(self, name, branch, position, category_postfix, priority): self.branch = branch self.builder_postfix = '-' + name self.category_postfix = category_postfix self.name = name self.position = position self.priority = priority self.all_deps_path = '/' + branch + '/deps/all.deps' self.standalone_deps_path = '/' + branch + '/deps/standalone.deps' self.dartium_deps_path = '/' + branch + '/deps/dartium.deps' # The channel names are replicated in the slave.cfg files for all # dart waterfalls. If you change anything here please also change it there. CHANNELS = [ Channel('be', 'branches/bleeding_edge', 0, '', 4), Channel('dev', 'trunk', 1, '-dev', 2), Channel('stable', 'branches/1.4', 2, '-stable', 1), Channel('integration', 'branches/dartium_integration', 3, '-integration', 3), ] CHANNELS_BY_NAME = {} for c in CHANNELS: CHANNELS_BY_NAME[c.name] = c
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. class Channel(object): def __init__(self, name, branch, position, category_postfix, priority): self.branch = branch self.builder_postfix = '-' + name self.category_postfix = category_postfix self.name = name self.position = position self.priority = priority self.all_deps_path = '/' + branch + '/deps/all.deps' self.standalone_deps_path = '/' + branch + '/deps/standalone.deps' self.dartium_deps_path = '/' + branch + '/deps/dartium.deps' # The channel names are replicated in the slave.cfg files for all # dart waterfalls. If you change anything here please also change it there. CHANNELS = [ Channel('be', 'branches/bleeding_edge', 0, '', 4), Channel('dev', 'trunk', 1, '-dev', 2), Channel('stable', 'branches/1.3', 2, '-stable', 1), Channel('integration', 'branches/dartium_integration', 3, '-integration', 3), ] CHANNELS_BY_NAME = {} for c in CHANNELS: CHANNELS_BY_NAME[c.name] = c Update stable builders to pull from 1.4 branch Review URL: https://codereview.chromium.org/295923003 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@271609 0039d316-1c4b-4281-b951-d872f2087c98# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. class Channel(object): def __init__(self, name, branch, position, category_postfix, priority): self.branch = branch self.builder_postfix = '-' + name self.category_postfix = category_postfix self.name = name self.position = position self.priority = priority self.all_deps_path = '/' + branch + '/deps/all.deps' self.standalone_deps_path = '/' + branch + '/deps/standalone.deps' self.dartium_deps_path = '/' + branch + '/deps/dartium.deps' # The channel names are replicated in the slave.cfg files for all # dart waterfalls. If you change anything here please also change it there. CHANNELS = [ Channel('be', 'branches/bleeding_edge', 0, '', 4), Channel('dev', 'trunk', 1, '-dev', 2), Channel('stable', 'branches/1.4', 2, '-stable', 1), Channel('integration', 'branches/dartium_integration', 3, '-integration', 3), ] CHANNELS_BY_NAME = {} for c in CHANNELS: CHANNELS_BY_NAME[c.name] = c
<commit_before># Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. class Channel(object): def __init__(self, name, branch, position, category_postfix, priority): self.branch = branch self.builder_postfix = '-' + name self.category_postfix = category_postfix self.name = name self.position = position self.priority = priority self.all_deps_path = '/' + branch + '/deps/all.deps' self.standalone_deps_path = '/' + branch + '/deps/standalone.deps' self.dartium_deps_path = '/' + branch + '/deps/dartium.deps' # The channel names are replicated in the slave.cfg files for all # dart waterfalls. If you change anything here please also change it there. CHANNELS = [ Channel('be', 'branches/bleeding_edge', 0, '', 4), Channel('dev', 'trunk', 1, '-dev', 2), Channel('stable', 'branches/1.3', 2, '-stable', 1), Channel('integration', 'branches/dartium_integration', 3, '-integration', 3), ] CHANNELS_BY_NAME = {} for c in CHANNELS: CHANNELS_BY_NAME[c.name] = c <commit_msg>Update stable builders to pull from 1.4 branch Review URL: https://codereview.chromium.org/295923003 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@271609 0039d316-1c4b-4281-b951-d872f2087c98<commit_after># Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. class Channel(object): def __init__(self, name, branch, position, category_postfix, priority): self.branch = branch self.builder_postfix = '-' + name self.category_postfix = category_postfix self.name = name self.position = position self.priority = priority self.all_deps_path = '/' + branch + '/deps/all.deps' self.standalone_deps_path = '/' + branch + '/deps/standalone.deps' self.dartium_deps_path = '/' + branch + '/deps/dartium.deps' # The channel names are replicated in the slave.cfg files for all # dart waterfalls. If you change anything here please also change it there. CHANNELS = [ Channel('be', 'branches/bleeding_edge', 0, '', 4), Channel('dev', 'trunk', 1, '-dev', 2), Channel('stable', 'branches/1.4', 2, '-stable', 1), Channel('integration', 'branches/dartium_integration', 3, '-integration', 3), ] CHANNELS_BY_NAME = {} for c in CHANNELS: CHANNELS_BY_NAME[c.name] = c
e9fe831427d59e2a5889d0e6744a6c9809b4ffd2
cellular.py
cellular.py
import random class TotalisticCellularAutomaton: def __init__(self): self.n_cells = 200 self.n_states = 5 self.symbols = ' .oO0' self.radius = 1 self.cells = [random.randrange(0, self.n_states) for _ in range(self.n_cells)] n_rules = (2*self.radius + 1) * (self.n_states - 1) self.rules = [0] + [random.randrange(0, self.n_states) for _ in range(n_rules)] def neighbor_sum(self, pos): return sum(self.cells[(pos+i)%self.n_cells] for i in range(-self.radius, self.radius+1)) def next_gen(self): self.cells = [self.rules[self.neighbor_sum(i)] for i in range(self.n_cells)] def print_gen(self): print(''.join(self.symbols[state] for state in self.cells)) def main(): ca = TotalisticCellularAutomaton() print(ca.rules) while True: ca.print_gen() ca.next_gen() if __name__ == '__main__': main()
import random from PIL import Image, ImageDraw class TotalisticCellularAutomaton: def __init__(self): self.n_cells = 200 self.n_states = 5 self.symbols = ' .oO0' self.radius = 1 self.cells = [random.randrange(0, self.n_states) for _ in range(self.n_cells)] self.colors = ['black', 'blue', 'yellow', 'orange', 'red'] n_rules = (2*self.radius + 1) * (self.n_states - 1) self.rules = [0] + [random.randrange(0, self.n_states) for _ in range(n_rules)] def neighbor_sum(self, pos): return sum(self.cells[(pos+i)%self.n_cells] for i in range(-self.radius, self.radius+1)) def next_gen(self): self.cells = [self.rules[self.neighbor_sum(i)] for i in range(self.n_cells)] def print_gen(self): print(''.join(self.symbols[state] for state in self.cells)) def draw_history(ca, history): n = len(history) m = len(history[0]) image = Image.new('RGB', (m, n)) draw = ImageDraw.Draw(image) for i in range(n): for j in range(m): state = history[i][j] draw.point((j, i), fill=ca.colors[state]) image.show() def main(): ca = TotalisticCellularAutomaton() print(ca.rules) history = [ca.cells] for x in range(1000): ca.next_gen() history.append(ca.cells) draw_history(ca, history) if __name__ == '__main__': main()
Add visualization of CA using Pillow
Add visualization of CA using Pillow
Python
unlicense
joseph346/cellular
import random class TotalisticCellularAutomaton: def __init__(self): self.n_cells = 200 self.n_states = 5 self.symbols = ' .oO0' self.radius = 1 self.cells = [random.randrange(0, self.n_states) for _ in range(self.n_cells)] n_rules = (2*self.radius + 1) * (self.n_states - 1) self.rules = [0] + [random.randrange(0, self.n_states) for _ in range(n_rules)] def neighbor_sum(self, pos): return sum(self.cells[(pos+i)%self.n_cells] for i in range(-self.radius, self.radius+1)) def next_gen(self): self.cells = [self.rules[self.neighbor_sum(i)] for i in range(self.n_cells)] def print_gen(self): print(''.join(self.symbols[state] for state in self.cells)) def main(): ca = TotalisticCellularAutomaton() print(ca.rules) while True: ca.print_gen() ca.next_gen() if __name__ == '__main__': main() Add visualization of CA using Pillow
import random from PIL import Image, ImageDraw class TotalisticCellularAutomaton: def __init__(self): self.n_cells = 200 self.n_states = 5 self.symbols = ' .oO0' self.radius = 1 self.cells = [random.randrange(0, self.n_states) for _ in range(self.n_cells)] self.colors = ['black', 'blue', 'yellow', 'orange', 'red'] n_rules = (2*self.radius + 1) * (self.n_states - 1) self.rules = [0] + [random.randrange(0, self.n_states) for _ in range(n_rules)] def neighbor_sum(self, pos): return sum(self.cells[(pos+i)%self.n_cells] for i in range(-self.radius, self.radius+1)) def next_gen(self): self.cells = [self.rules[self.neighbor_sum(i)] for i in range(self.n_cells)] def print_gen(self): print(''.join(self.symbols[state] for state in self.cells)) def draw_history(ca, history): n = len(history) m = len(history[0]) image = Image.new('RGB', (m, n)) draw = ImageDraw.Draw(image) for i in range(n): for j in range(m): state = history[i][j] draw.point((j, i), fill=ca.colors[state]) image.show() def main(): ca = TotalisticCellularAutomaton() print(ca.rules) history = [ca.cells] for x in range(1000): ca.next_gen() history.append(ca.cells) draw_history(ca, history) if __name__ == '__main__': main()
<commit_before>import random class TotalisticCellularAutomaton: def __init__(self): self.n_cells = 200 self.n_states = 5 self.symbols = ' .oO0' self.radius = 1 self.cells = [random.randrange(0, self.n_states) for _ in range(self.n_cells)] n_rules = (2*self.radius + 1) * (self.n_states - 1) self.rules = [0] + [random.randrange(0, self.n_states) for _ in range(n_rules)] def neighbor_sum(self, pos): return sum(self.cells[(pos+i)%self.n_cells] for i in range(-self.radius, self.radius+1)) def next_gen(self): self.cells = [self.rules[self.neighbor_sum(i)] for i in range(self.n_cells)] def print_gen(self): print(''.join(self.symbols[state] for state in self.cells)) def main(): ca = TotalisticCellularAutomaton() print(ca.rules) while True: ca.print_gen() ca.next_gen() if __name__ == '__main__': main() <commit_msg>Add visualization of CA using Pillow<commit_after>
import random from PIL import Image, ImageDraw class TotalisticCellularAutomaton: def __init__(self): self.n_cells = 200 self.n_states = 5 self.symbols = ' .oO0' self.radius = 1 self.cells = [random.randrange(0, self.n_states) for _ in range(self.n_cells)] self.colors = ['black', 'blue', 'yellow', 'orange', 'red'] n_rules = (2*self.radius + 1) * (self.n_states - 1) self.rules = [0] + [random.randrange(0, self.n_states) for _ in range(n_rules)] def neighbor_sum(self, pos): return sum(self.cells[(pos+i)%self.n_cells] for i in range(-self.radius, self.radius+1)) def next_gen(self): self.cells = [self.rules[self.neighbor_sum(i)] for i in range(self.n_cells)] def print_gen(self): print(''.join(self.symbols[state] for state in self.cells)) def draw_history(ca, history): n = len(history) m = len(history[0]) image = Image.new('RGB', (m, n)) draw = ImageDraw.Draw(image) for i in range(n): for j in range(m): state = history[i][j] draw.point((j, i), fill=ca.colors[state]) image.show() def main(): ca = TotalisticCellularAutomaton() print(ca.rules) history = [ca.cells] for x in range(1000): ca.next_gen() history.append(ca.cells) draw_history(ca, history) if __name__ == '__main__': main()
import random class TotalisticCellularAutomaton: def __init__(self): self.n_cells = 200 self.n_states = 5 self.symbols = ' .oO0' self.radius = 1 self.cells = [random.randrange(0, self.n_states) for _ in range(self.n_cells)] n_rules = (2*self.radius + 1) * (self.n_states - 1) self.rules = [0] + [random.randrange(0, self.n_states) for _ in range(n_rules)] def neighbor_sum(self, pos): return sum(self.cells[(pos+i)%self.n_cells] for i in range(-self.radius, self.radius+1)) def next_gen(self): self.cells = [self.rules[self.neighbor_sum(i)] for i in range(self.n_cells)] def print_gen(self): print(''.join(self.symbols[state] for state in self.cells)) def main(): ca = TotalisticCellularAutomaton() print(ca.rules) while True: ca.print_gen() ca.next_gen() if __name__ == '__main__': main() Add visualization of CA using Pillowimport random from PIL import Image, ImageDraw class TotalisticCellularAutomaton: def __init__(self): self.n_cells = 200 self.n_states = 5 self.symbols = ' .oO0' self.radius = 1 self.cells = [random.randrange(0, self.n_states) for _ in range(self.n_cells)] self.colors = ['black', 'blue', 'yellow', 'orange', 'red'] n_rules = (2*self.radius + 1) * (self.n_states - 1) self.rules = [0] + [random.randrange(0, self.n_states) for _ in range(n_rules)] def neighbor_sum(self, pos): return sum(self.cells[(pos+i)%self.n_cells] for i in range(-self.radius, self.radius+1)) def next_gen(self): self.cells = [self.rules[self.neighbor_sum(i)] for i in range(self.n_cells)] def print_gen(self): print(''.join(self.symbols[state] for state in self.cells)) def draw_history(ca, history): n = len(history) m = len(history[0]) image = Image.new('RGB', (m, n)) draw = ImageDraw.Draw(image) for i in range(n): for j in range(m): state = history[i][j] draw.point((j, i), fill=ca.colors[state]) image.show() def main(): ca = TotalisticCellularAutomaton() print(ca.rules) history = [ca.cells] for x in range(1000): ca.next_gen() history.append(ca.cells) draw_history(ca, history) if __name__ == '__main__': main()
<commit_before>import random class TotalisticCellularAutomaton: def __init__(self): self.n_cells = 200 self.n_states = 5 self.symbols = ' .oO0' self.radius = 1 self.cells = [random.randrange(0, self.n_states) for _ in range(self.n_cells)] n_rules = (2*self.radius + 1) * (self.n_states - 1) self.rules = [0] + [random.randrange(0, self.n_states) for _ in range(n_rules)] def neighbor_sum(self, pos): return sum(self.cells[(pos+i)%self.n_cells] for i in range(-self.radius, self.radius+1)) def next_gen(self): self.cells = [self.rules[self.neighbor_sum(i)] for i in range(self.n_cells)] def print_gen(self): print(''.join(self.symbols[state] for state in self.cells)) def main(): ca = TotalisticCellularAutomaton() print(ca.rules) while True: ca.print_gen() ca.next_gen() if __name__ == '__main__': main() <commit_msg>Add visualization of CA using Pillow<commit_after>import random from PIL import Image, ImageDraw class TotalisticCellularAutomaton: def __init__(self): self.n_cells = 200 self.n_states = 5 self.symbols = ' .oO0' self.radius = 1 self.cells = [random.randrange(0, self.n_states) for _ in range(self.n_cells)] self.colors = ['black', 'blue', 'yellow', 'orange', 'red'] n_rules = (2*self.radius + 1) * (self.n_states - 1) self.rules = [0] + [random.randrange(0, self.n_states) for _ in range(n_rules)] def neighbor_sum(self, pos): return sum(self.cells[(pos+i)%self.n_cells] for i in range(-self.radius, self.radius+1)) def next_gen(self): self.cells = [self.rules[self.neighbor_sum(i)] for i in range(self.n_cells)] def print_gen(self): print(''.join(self.symbols[state] for state in self.cells)) def draw_history(ca, history): n = len(history) m = len(history[0]) image = Image.new('RGB', (m, n)) draw = ImageDraw.Draw(image) for i in range(n): for j in range(m): state = history[i][j] draw.point((j, i), fill=ca.colors[state]) image.show() def main(): ca = TotalisticCellularAutomaton() print(ca.rules) history = [ca.cells] for x in range(1000): ca.next_gen() history.append(ca.cells) draw_history(ca, history) if __name__ == '__main__': main()
22f9fc8a56882f0595d051cb8c5d20fd97091e8c
custom/opm/tests/test_snapshot.py
custom/opm/tests/test_snapshot.py
from datetime import date from unittest import TestCase from couchforms.models import XFormInstance from ..constants import * from ..reports import get_report, BeneficiaryPaymentReport, MetReport from .case_reports import Report, OPMCase, MockCaseRow, MockDataProvider class TestGetReportUtil(TestCase): def get_report_class(self, report_class): obj_dict = { 'get_rows': lambda slf, datespan: [ OPMCase( forms=[], edd=date(2014, 11, 10), ), OPMCase( forms=[], dod=date(2014, 1, 12), ), OPMCase( forms=[], dod=date(2014, 3, 12), ), ], 'data_provider': MockDataProvider(), } return type(report_class.__name__, (Report, report_class), obj_dict) def test_basic_BPR(self): report_class = self.get_report_class(BeneficiaryPaymentReport) report = get_report(report_class, month=6, year=2014, block="Atri") report.rows def test_basic_CMR(self): report_class = self.get_report_class(MetReport) report = get_report(report_class, month=6, year=2014, block="Atri") report.rows
from datetime import date from unittest import TestCase from mock import patch from corehq.apps.users.models import CommCareUser from couchforms.models import XFormInstance from ..constants import * from ..reports import get_report, BeneficiaryPaymentReport, MetReport from .case_reports import Report, OPMCase, MockCaseRow, MockDataProvider class TestGetReportUtil(TestCase): def get_report_class(self, report_class): obj_dict = { 'get_rows': lambda slf, datespan: [ OPMCase( forms=[], edd=date(2014, 11, 10), ), OPMCase( forms=[], dod=date(2014, 1, 12), ), OPMCase( forms=[], dod=date(2014, 3, 12), ), ], 'data_provider': MockDataProvider(), } return type(report_class.__name__, (Report, report_class), obj_dict) def test_basic_BPR(self): report_class = self.get_report_class(BeneficiaryPaymentReport) report = get_report(report_class, month=6, year=2014, block="Atri") report.rows @patch.object(CommCareUser, 'by_domain', return_value=[]) def test_basic_CMR(self, user_mock): report_class = self.get_report_class(MetReport) report = get_report(report_class, month=6, year=2014, block="Atri") report.rows
Fix for test (add mock for CommCareUser)
Fix for test (add mock for CommCareUser)
Python
bsd-3-clause
puttarajubr/commcare-hq,puttarajubr/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
from datetime import date from unittest import TestCase from couchforms.models import XFormInstance from ..constants import * from ..reports import get_report, BeneficiaryPaymentReport, MetReport from .case_reports import Report, OPMCase, MockCaseRow, MockDataProvider class TestGetReportUtil(TestCase): def get_report_class(self, report_class): obj_dict = { 'get_rows': lambda slf, datespan: [ OPMCase( forms=[], edd=date(2014, 11, 10), ), OPMCase( forms=[], dod=date(2014, 1, 12), ), OPMCase( forms=[], dod=date(2014, 3, 12), ), ], 'data_provider': MockDataProvider(), } return type(report_class.__name__, (Report, report_class), obj_dict) def test_basic_BPR(self): report_class = self.get_report_class(BeneficiaryPaymentReport) report = get_report(report_class, month=6, year=2014, block="Atri") report.rows def test_basic_CMR(self): report_class = self.get_report_class(MetReport) report = get_report(report_class, month=6, year=2014, block="Atri") report.rows Fix for test (add mock for CommCareUser)
from datetime import date from unittest import TestCase from mock import patch from corehq.apps.users.models import CommCareUser from couchforms.models import XFormInstance from ..constants import * from ..reports import get_report, BeneficiaryPaymentReport, MetReport from .case_reports import Report, OPMCase, MockCaseRow, MockDataProvider class TestGetReportUtil(TestCase): def get_report_class(self, report_class): obj_dict = { 'get_rows': lambda slf, datespan: [ OPMCase( forms=[], edd=date(2014, 11, 10), ), OPMCase( forms=[], dod=date(2014, 1, 12), ), OPMCase( forms=[], dod=date(2014, 3, 12), ), ], 'data_provider': MockDataProvider(), } return type(report_class.__name__, (Report, report_class), obj_dict) def test_basic_BPR(self): report_class = self.get_report_class(BeneficiaryPaymentReport) report = get_report(report_class, month=6, year=2014, block="Atri") report.rows @patch.object(CommCareUser, 'by_domain', return_value=[]) def test_basic_CMR(self, user_mock): report_class = self.get_report_class(MetReport) report = get_report(report_class, month=6, year=2014, block="Atri") report.rows
<commit_before>from datetime import date from unittest import TestCase from couchforms.models import XFormInstance from ..constants import * from ..reports import get_report, BeneficiaryPaymentReport, MetReport from .case_reports import Report, OPMCase, MockCaseRow, MockDataProvider class TestGetReportUtil(TestCase): def get_report_class(self, report_class): obj_dict = { 'get_rows': lambda slf, datespan: [ OPMCase( forms=[], edd=date(2014, 11, 10), ), OPMCase( forms=[], dod=date(2014, 1, 12), ), OPMCase( forms=[], dod=date(2014, 3, 12), ), ], 'data_provider': MockDataProvider(), } return type(report_class.__name__, (Report, report_class), obj_dict) def test_basic_BPR(self): report_class = self.get_report_class(BeneficiaryPaymentReport) report = get_report(report_class, month=6, year=2014, block="Atri") report.rows def test_basic_CMR(self): report_class = self.get_report_class(MetReport) report = get_report(report_class, month=6, year=2014, block="Atri") report.rows <commit_msg>Fix for test (add mock for CommCareUser)<commit_after>
from datetime import date from unittest import TestCase from mock import patch from corehq.apps.users.models import CommCareUser from couchforms.models import XFormInstance from ..constants import * from ..reports import get_report, BeneficiaryPaymentReport, MetReport from .case_reports import Report, OPMCase, MockCaseRow, MockDataProvider class TestGetReportUtil(TestCase): def get_report_class(self, report_class): obj_dict = { 'get_rows': lambda slf, datespan: [ OPMCase( forms=[], edd=date(2014, 11, 10), ), OPMCase( forms=[], dod=date(2014, 1, 12), ), OPMCase( forms=[], dod=date(2014, 3, 12), ), ], 'data_provider': MockDataProvider(), } return type(report_class.__name__, (Report, report_class), obj_dict) def test_basic_BPR(self): report_class = self.get_report_class(BeneficiaryPaymentReport) report = get_report(report_class, month=6, year=2014, block="Atri") report.rows @patch.object(CommCareUser, 'by_domain', return_value=[]) def test_basic_CMR(self, user_mock): report_class = self.get_report_class(MetReport) report = get_report(report_class, month=6, year=2014, block="Atri") report.rows
from datetime import date from unittest import TestCase from couchforms.models import XFormInstance from ..constants import * from ..reports import get_report, BeneficiaryPaymentReport, MetReport from .case_reports import Report, OPMCase, MockCaseRow, MockDataProvider class TestGetReportUtil(TestCase): def get_report_class(self, report_class): obj_dict = { 'get_rows': lambda slf, datespan: [ OPMCase( forms=[], edd=date(2014, 11, 10), ), OPMCase( forms=[], dod=date(2014, 1, 12), ), OPMCase( forms=[], dod=date(2014, 3, 12), ), ], 'data_provider': MockDataProvider(), } return type(report_class.__name__, (Report, report_class), obj_dict) def test_basic_BPR(self): report_class = self.get_report_class(BeneficiaryPaymentReport) report = get_report(report_class, month=6, year=2014, block="Atri") report.rows def test_basic_CMR(self): report_class = self.get_report_class(MetReport) report = get_report(report_class, month=6, year=2014, block="Atri") report.rows Fix for test (add mock for CommCareUser)from datetime import date from unittest import TestCase from mock import patch from corehq.apps.users.models import CommCareUser from couchforms.models import XFormInstance from ..constants import * from ..reports import get_report, BeneficiaryPaymentReport, MetReport from .case_reports import Report, OPMCase, MockCaseRow, MockDataProvider class TestGetReportUtil(TestCase): def get_report_class(self, report_class): obj_dict = { 'get_rows': lambda slf, datespan: [ OPMCase( forms=[], edd=date(2014, 11, 10), ), OPMCase( forms=[], dod=date(2014, 1, 12), ), OPMCase( forms=[], dod=date(2014, 3, 12), ), ], 'data_provider': MockDataProvider(), } return type(report_class.__name__, (Report, report_class), obj_dict) def test_basic_BPR(self): report_class = self.get_report_class(BeneficiaryPaymentReport) report = get_report(report_class, month=6, year=2014, block="Atri") report.rows @patch.object(CommCareUser, 'by_domain', return_value=[]) def test_basic_CMR(self, user_mock): report_class = self.get_report_class(MetReport) report = get_report(report_class, month=6, year=2014, block="Atri") report.rows
<commit_before>from datetime import date from unittest import TestCase from couchforms.models import XFormInstance from ..constants import * from ..reports import get_report, BeneficiaryPaymentReport, MetReport from .case_reports import Report, OPMCase, MockCaseRow, MockDataProvider class TestGetReportUtil(TestCase): def get_report_class(self, report_class): obj_dict = { 'get_rows': lambda slf, datespan: [ OPMCase( forms=[], edd=date(2014, 11, 10), ), OPMCase( forms=[], dod=date(2014, 1, 12), ), OPMCase( forms=[], dod=date(2014, 3, 12), ), ], 'data_provider': MockDataProvider(), } return type(report_class.__name__, (Report, report_class), obj_dict) def test_basic_BPR(self): report_class = self.get_report_class(BeneficiaryPaymentReport) report = get_report(report_class, month=6, year=2014, block="Atri") report.rows def test_basic_CMR(self): report_class = self.get_report_class(MetReport) report = get_report(report_class, month=6, year=2014, block="Atri") report.rows <commit_msg>Fix for test (add mock for CommCareUser)<commit_after>from datetime import date from unittest import TestCase from mock import patch from corehq.apps.users.models import CommCareUser from couchforms.models import XFormInstance from ..constants import * from ..reports import get_report, BeneficiaryPaymentReport, MetReport from .case_reports import Report, OPMCase, MockCaseRow, MockDataProvider class TestGetReportUtil(TestCase): def get_report_class(self, report_class): obj_dict = { 'get_rows': lambda slf, datespan: [ OPMCase( forms=[], edd=date(2014, 11, 10), ), OPMCase( forms=[], dod=date(2014, 1, 12), ), OPMCase( forms=[], dod=date(2014, 3, 12), ), ], 'data_provider': MockDataProvider(), } return type(report_class.__name__, (Report, report_class), obj_dict) def test_basic_BPR(self): report_class = self.get_report_class(BeneficiaryPaymentReport) report = get_report(report_class, month=6, year=2014, block="Atri") report.rows @patch.object(CommCareUser, 'by_domain', return_value=[]) def test_basic_CMR(self, user_mock): report_class = self.get_report_class(MetReport) report = get_report(report_class, month=6, year=2014, block="Atri") report.rows
171849e3e3e12293b80ac80dde6fd12ba5476141
pysswords/db/credential.py
pysswords/db/credential.py
from collections import namedtuple import os import re import shutil import yaml Credential = namedtuple("Credential", "name login password comment") class CredentialExistsError(Exception): pass class CredentialNotFoundError(Exception): pass def expandpath(path, name, login): return os.path.join(path, name, "{}.pyssword".format(login)) def content(credential): return yaml.dump(credential) def asdict(credential): return credential._asdict() def asstring(credential): return "{} {} {}".format( credential.name, credential.login, credential.comment ) def exists(path, name, login): return True if os.path.isfile(expandpath(path, name, login)) else False def clean(path, name, login): if exists(path, name, login): os.remove(expandpath(path, name, login)) credential_dir = os.path.dirname(expandpath(path, name, login)) if not os.listdir(credential_dir): shutil.rmtree(credential_dir) def splitname(fullname): rgx = re.compile(r"(?:(?P<login>.+)?@)?(?P<name>.+)") if rgx.match(fullname): name = rgx.match(fullname).group("name") login = rgx.match(fullname).group("login") return name, login else: raise ValueError("Not a valid name") def asfullname(name, login): return "{}@{}".format(login if login else "", name)
from collections import namedtuple import os import re import shutil import yaml Credential = namedtuple("Credential", "name login password comment") class CredentialExistsError(Exception): pass class CredentialNotFoundError(Exception): pass def expandpath(path, name, login): return os.path.join(path, name, "{}.pyssword".format(login)) def content(credential): return yaml.dump(credential) def asdict(credential): return credential._asdict() def asstring(credential): return "{} {} {}".format( credential.name, credential.login, credential.comment ) def exists(path, name, login): return True if os.path.isfile(expandpath(path, name, login)) else False def clean(path, name, login): if exists(path, name, login): os.remove(expandpath(path, name, login)) credential_dir = os.path.dirname(expandpath(path, name, login)) if not os.listdir(credential_dir): shutil.rmtree(credential_dir) def splitname(fullname): rgx = re.compile(r"(?:(?P<login>.+?@?.+)?@)?(?P<name>.+)") if rgx.match(fullname): name = rgx.match(fullname).group("name") login = rgx.match(fullname).group("login") return name, login else: raise ValueError("Not a valid name") def asfullname(name, login): return "{}@{}".format(login if login else "", name)
Fix fullname syntax to handle login with (at) signs
Fix fullname syntax to handle login with (at) signs
Python
mit
marcwebbie/passpie,marcwebbie/passpie,scorphus/passpie,eiginn/passpie,scorphus/passpie,marcwebbie/pysswords,eiginn/passpie
from collections import namedtuple import os import re import shutil import yaml Credential = namedtuple("Credential", "name login password comment") class CredentialExistsError(Exception): pass class CredentialNotFoundError(Exception): pass def expandpath(path, name, login): return os.path.join(path, name, "{}.pyssword".format(login)) def content(credential): return yaml.dump(credential) def asdict(credential): return credential._asdict() def asstring(credential): return "{} {} {}".format( credential.name, credential.login, credential.comment ) def exists(path, name, login): return True if os.path.isfile(expandpath(path, name, login)) else False def clean(path, name, login): if exists(path, name, login): os.remove(expandpath(path, name, login)) credential_dir = os.path.dirname(expandpath(path, name, login)) if not os.listdir(credential_dir): shutil.rmtree(credential_dir) def splitname(fullname): rgx = re.compile(r"(?:(?P<login>.+)?@)?(?P<name>.+)") if rgx.match(fullname): name = rgx.match(fullname).group("name") login = rgx.match(fullname).group("login") return name, login else: raise ValueError("Not a valid name") def asfullname(name, login): return "{}@{}".format(login if login else "", name) Fix fullname syntax to handle login with (at) signs
from collections import namedtuple import os import re import shutil import yaml Credential = namedtuple("Credential", "name login password comment") class CredentialExistsError(Exception): pass class CredentialNotFoundError(Exception): pass def expandpath(path, name, login): return os.path.join(path, name, "{}.pyssword".format(login)) def content(credential): return yaml.dump(credential) def asdict(credential): return credential._asdict() def asstring(credential): return "{} {} {}".format( credential.name, credential.login, credential.comment ) def exists(path, name, login): return True if os.path.isfile(expandpath(path, name, login)) else False def clean(path, name, login): if exists(path, name, login): os.remove(expandpath(path, name, login)) credential_dir = os.path.dirname(expandpath(path, name, login)) if not os.listdir(credential_dir): shutil.rmtree(credential_dir) def splitname(fullname): rgx = re.compile(r"(?:(?P<login>.+?@?.+)?@)?(?P<name>.+)") if rgx.match(fullname): name = rgx.match(fullname).group("name") login = rgx.match(fullname).group("login") return name, login else: raise ValueError("Not a valid name") def asfullname(name, login): return "{}@{}".format(login if login else "", name)
<commit_before>from collections import namedtuple import os import re import shutil import yaml Credential = namedtuple("Credential", "name login password comment") class CredentialExistsError(Exception): pass class CredentialNotFoundError(Exception): pass def expandpath(path, name, login): return os.path.join(path, name, "{}.pyssword".format(login)) def content(credential): return yaml.dump(credential) def asdict(credential): return credential._asdict() def asstring(credential): return "{} {} {}".format( credential.name, credential.login, credential.comment ) def exists(path, name, login): return True if os.path.isfile(expandpath(path, name, login)) else False def clean(path, name, login): if exists(path, name, login): os.remove(expandpath(path, name, login)) credential_dir = os.path.dirname(expandpath(path, name, login)) if not os.listdir(credential_dir): shutil.rmtree(credential_dir) def splitname(fullname): rgx = re.compile(r"(?:(?P<login>.+)?@)?(?P<name>.+)") if rgx.match(fullname): name = rgx.match(fullname).group("name") login = rgx.match(fullname).group("login") return name, login else: raise ValueError("Not a valid name") def asfullname(name, login): return "{}@{}".format(login if login else "", name) <commit_msg>Fix fullname syntax to handle login with (at) signs<commit_after>
from collections import namedtuple import os import re import shutil import yaml Credential = namedtuple("Credential", "name login password comment") class CredentialExistsError(Exception): pass class CredentialNotFoundError(Exception): pass def expandpath(path, name, login): return os.path.join(path, name, "{}.pyssword".format(login)) def content(credential): return yaml.dump(credential) def asdict(credential): return credential._asdict() def asstring(credential): return "{} {} {}".format( credential.name, credential.login, credential.comment ) def exists(path, name, login): return True if os.path.isfile(expandpath(path, name, login)) else False def clean(path, name, login): if exists(path, name, login): os.remove(expandpath(path, name, login)) credential_dir = os.path.dirname(expandpath(path, name, login)) if not os.listdir(credential_dir): shutil.rmtree(credential_dir) def splitname(fullname): rgx = re.compile(r"(?:(?P<login>.+?@?.+)?@)?(?P<name>.+)") if rgx.match(fullname): name = rgx.match(fullname).group("name") login = rgx.match(fullname).group("login") return name, login else: raise ValueError("Not a valid name") def asfullname(name, login): return "{}@{}".format(login if login else "", name)
from collections import namedtuple import os import re import shutil import yaml Credential = namedtuple("Credential", "name login password comment") class CredentialExistsError(Exception): pass class CredentialNotFoundError(Exception): pass def expandpath(path, name, login): return os.path.join(path, name, "{}.pyssword".format(login)) def content(credential): return yaml.dump(credential) def asdict(credential): return credential._asdict() def asstring(credential): return "{} {} {}".format( credential.name, credential.login, credential.comment ) def exists(path, name, login): return True if os.path.isfile(expandpath(path, name, login)) else False def clean(path, name, login): if exists(path, name, login): os.remove(expandpath(path, name, login)) credential_dir = os.path.dirname(expandpath(path, name, login)) if not os.listdir(credential_dir): shutil.rmtree(credential_dir) def splitname(fullname): rgx = re.compile(r"(?:(?P<login>.+)?@)?(?P<name>.+)") if rgx.match(fullname): name = rgx.match(fullname).group("name") login = rgx.match(fullname).group("login") return name, login else: raise ValueError("Not a valid name") def asfullname(name, login): return "{}@{}".format(login if login else "", name) Fix fullname syntax to handle login with (at) signsfrom collections import namedtuple import os import re import shutil import yaml Credential = namedtuple("Credential", "name login password comment") class CredentialExistsError(Exception): pass class CredentialNotFoundError(Exception): pass def expandpath(path, name, login): return os.path.join(path, name, "{}.pyssword".format(login)) def content(credential): return yaml.dump(credential) def asdict(credential): return credential._asdict() def asstring(credential): return "{} {} {}".format( credential.name, credential.login, credential.comment ) def exists(path, name, login): return True if os.path.isfile(expandpath(path, name, login)) else False def clean(path, name, login): if exists(path, name, login): os.remove(expandpath(path, name, login)) credential_dir = os.path.dirname(expandpath(path, name, login)) if not os.listdir(credential_dir): shutil.rmtree(credential_dir) def splitname(fullname): rgx = re.compile(r"(?:(?P<login>.+?@?.+)?@)?(?P<name>.+)") if rgx.match(fullname): name = rgx.match(fullname).group("name") login = rgx.match(fullname).group("login") return name, login else: raise ValueError("Not a valid name") def asfullname(name, login): return "{}@{}".format(login if login else "", name)
<commit_before>from collections import namedtuple import os import re import shutil import yaml Credential = namedtuple("Credential", "name login password comment") class CredentialExistsError(Exception): pass class CredentialNotFoundError(Exception): pass def expandpath(path, name, login): return os.path.join(path, name, "{}.pyssword".format(login)) def content(credential): return yaml.dump(credential) def asdict(credential): return credential._asdict() def asstring(credential): return "{} {} {}".format( credential.name, credential.login, credential.comment ) def exists(path, name, login): return True if os.path.isfile(expandpath(path, name, login)) else False def clean(path, name, login): if exists(path, name, login): os.remove(expandpath(path, name, login)) credential_dir = os.path.dirname(expandpath(path, name, login)) if not os.listdir(credential_dir): shutil.rmtree(credential_dir) def splitname(fullname): rgx = re.compile(r"(?:(?P<login>.+)?@)?(?P<name>.+)") if rgx.match(fullname): name = rgx.match(fullname).group("name") login = rgx.match(fullname).group("login") return name, login else: raise ValueError("Not a valid name") def asfullname(name, login): return "{}@{}".format(login if login else "", name) <commit_msg>Fix fullname syntax to handle login with (at) signs<commit_after>from collections import namedtuple import os import re import shutil import yaml Credential = namedtuple("Credential", "name login password comment") class CredentialExistsError(Exception): pass class CredentialNotFoundError(Exception): pass def expandpath(path, name, login): return os.path.join(path, name, "{}.pyssword".format(login)) def content(credential): return yaml.dump(credential) def asdict(credential): return credential._asdict() def asstring(credential): return "{} {} {}".format( credential.name, credential.login, credential.comment ) def exists(path, name, login): return True if os.path.isfile(expandpath(path, name, login)) else False def clean(path, name, login): if exists(path, name, login): os.remove(expandpath(path, name, login)) credential_dir = os.path.dirname(expandpath(path, name, login)) if not os.listdir(credential_dir): shutil.rmtree(credential_dir) def splitname(fullname): rgx = re.compile(r"(?:(?P<login>.+?@?.+)?@)?(?P<name>.+)") if rgx.match(fullname): name = rgx.match(fullname).group("name") login = rgx.match(fullname).group("login") return name, login else: raise ValueError("Not a valid name") def asfullname(name, login): return "{}@{}".format(login if login else "", name)
5e03af4b0f920e97507b3ada6b4b925136ddbf07
froide/upload/serializers.py
froide/upload/serializers.py
from rest_framework import serializers from .models import Upload class UploadSerializer(serializers.ModelSerializer): class Meta: model = Upload fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['guid'].required = True
from rest_framework import serializers from .models import Upload class UploadSerializer(serializers.ModelSerializer): class Meta: model = Upload fields = '__all__' def __init__(self, *args, **kwargs): ''' Add required marker, so OpenAPI schema generator can remove it again -.- ''' super().__init__(*args, **kwargs) self.fields['guid'].required = True
Add some documentation for weird init
Add some documentation for weird init
Python
mit
fin/froide,stefanw/froide,stefanw/froide,fin/froide,fin/froide,fin/froide,stefanw/froide,stefanw/froide,stefanw/froide
from rest_framework import serializers from .models import Upload class UploadSerializer(serializers.ModelSerializer): class Meta: model = Upload fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['guid'].required = True Add some documentation for weird init
from rest_framework import serializers from .models import Upload class UploadSerializer(serializers.ModelSerializer): class Meta: model = Upload fields = '__all__' def __init__(self, *args, **kwargs): ''' Add required marker, so OpenAPI schema generator can remove it again -.- ''' super().__init__(*args, **kwargs) self.fields['guid'].required = True
<commit_before>from rest_framework import serializers from .models import Upload class UploadSerializer(serializers.ModelSerializer): class Meta: model = Upload fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['guid'].required = True <commit_msg>Add some documentation for weird init<commit_after>
from rest_framework import serializers from .models import Upload class UploadSerializer(serializers.ModelSerializer): class Meta: model = Upload fields = '__all__' def __init__(self, *args, **kwargs): ''' Add required marker, so OpenAPI schema generator can remove it again -.- ''' super().__init__(*args, **kwargs) self.fields['guid'].required = True
from rest_framework import serializers from .models import Upload class UploadSerializer(serializers.ModelSerializer): class Meta: model = Upload fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['guid'].required = True Add some documentation for weird initfrom rest_framework import serializers from .models import Upload class UploadSerializer(serializers.ModelSerializer): class Meta: model = Upload fields = '__all__' def __init__(self, *args, **kwargs): ''' Add required marker, so OpenAPI schema generator can remove it again -.- ''' super().__init__(*args, **kwargs) self.fields['guid'].required = True
<commit_before>from rest_framework import serializers from .models import Upload class UploadSerializer(serializers.ModelSerializer): class Meta: model = Upload fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['guid'].required = True <commit_msg>Add some documentation for weird init<commit_after>from rest_framework import serializers from .models import Upload class UploadSerializer(serializers.ModelSerializer): class Meta: model = Upload fields = '__all__' def __init__(self, *args, **kwargs): ''' Add required marker, so OpenAPI schema generator can remove it again -.- ''' super().__init__(*args, **kwargs) self.fields['guid'].required = True
5cb497d0741f6dbd29a6e41fa9f1cb3374e8f062
jsontosql.py
jsontosql.py
import os import os.path from json import loads import click from vendcrawler.scripts.vendcrawlerdb import VendCrawlerDB class JSONToSQL(object): def __init__(self, json, user, password, database): self.data = loads(json.read()) self.db = VendCrawlerDB(user, password, database) table = 'items' columns = ['item_id', 'item_name', 'vendor_id', 'shop_name', 'amount', 'price', 'map', 'datetime'] values = [] for items in data: for item in items: value = [int(item['id']), item['name'], int(item['vendor_id']), item['shop'], int(item['amount'].replace(',', '')), int(item['price'].replace(',', '')), item['map'], item['datetime']] values.append(value) self.vcdb.insert(table, columns, values) @click.command() @click.argument('json', type=click.File('r')) @click.argument('user') @click.argument('password') @click.argument('database') def cli(json, user, password, database): JSONToSQL(json, user, password, database) if __name__ == '__main__': cli()
import os import os.path from json import loads import click from vendcrawler.scripts.vendcrawlerdb import VendCrawlerDB class JSONToSQL(object): def __init__(self, json, user, password, database): data = loads(json.read()) db = VendCrawlerDB(user, password, database) table = 'items' columns = ['item_id', 'item_name', 'vendor_id', 'shop_name', 'amount', 'price', 'map', 'datetime'] values = [] for items in data: for item in items: value = [int(item['id']), item['name'], int(item['vendor_id']), item['shop'], int(item['amount'].replace(',', '')), int(item['price'].replace(',', '')), item['map'], item['datetime']] values.append(value) self.db.insert(table, columns, values) @click.command() @click.argument('json', type=click.File('r')) @click.argument('user') @click.argument('password') @click.argument('database') def cli(json, user, password, database): JSONToSQL(json, user, password, database) if __name__ == '__main__': cli()
Fix json to sql converter.
Fix json to sql converter.
Python
mit
josetaas/vendcrawler,josetaas/vendcrawler,josetaas/vendcrawler
import os import os.path from json import loads import click from vendcrawler.scripts.vendcrawlerdb import VendCrawlerDB class JSONToSQL(object): def __init__(self, json, user, password, database): self.data = loads(json.read()) self.db = VendCrawlerDB(user, password, database) table = 'items' columns = ['item_id', 'item_name', 'vendor_id', 'shop_name', 'amount', 'price', 'map', 'datetime'] values = [] for items in data: for item in items: value = [int(item['id']), item['name'], int(item['vendor_id']), item['shop'], int(item['amount'].replace(',', '')), int(item['price'].replace(',', '')), item['map'], item['datetime']] values.append(value) self.vcdb.insert(table, columns, values) @click.command() @click.argument('json', type=click.File('r')) @click.argument('user') @click.argument('password') @click.argument('database') def cli(json, user, password, database): JSONToSQL(json, user, password, database) if __name__ == '__main__': cli() Fix json to sql converter.
import os import os.path from json import loads import click from vendcrawler.scripts.vendcrawlerdb import VendCrawlerDB class JSONToSQL(object): def __init__(self, json, user, password, database): data = loads(json.read()) db = VendCrawlerDB(user, password, database) table = 'items' columns = ['item_id', 'item_name', 'vendor_id', 'shop_name', 'amount', 'price', 'map', 'datetime'] values = [] for items in data: for item in items: value = [int(item['id']), item['name'], int(item['vendor_id']), item['shop'], int(item['amount'].replace(',', '')), int(item['price'].replace(',', '')), item['map'], item['datetime']] values.append(value) self.db.insert(table, columns, values) @click.command() @click.argument('json', type=click.File('r')) @click.argument('user') @click.argument('password') @click.argument('database') def cli(json, user, password, database): JSONToSQL(json, user, password, database) if __name__ == '__main__': cli()
<commit_before>import os import os.path from json import loads import click from vendcrawler.scripts.vendcrawlerdb import VendCrawlerDB class JSONToSQL(object): def __init__(self, json, user, password, database): self.data = loads(json.read()) self.db = VendCrawlerDB(user, password, database) table = 'items' columns = ['item_id', 'item_name', 'vendor_id', 'shop_name', 'amount', 'price', 'map', 'datetime'] values = [] for items in data: for item in items: value = [int(item['id']), item['name'], int(item['vendor_id']), item['shop'], int(item['amount'].replace(',', '')), int(item['price'].replace(',', '')), item['map'], item['datetime']] values.append(value) self.vcdb.insert(table, columns, values) @click.command() @click.argument('json', type=click.File('r')) @click.argument('user') @click.argument('password') @click.argument('database') def cli(json, user, password, database): JSONToSQL(json, user, password, database) if __name__ == '__main__': cli() <commit_msg>Fix json to sql converter.<commit_after>
import os import os.path from json import loads import click from vendcrawler.scripts.vendcrawlerdb import VendCrawlerDB class JSONToSQL(object): def __init__(self, json, user, password, database): data = loads(json.read()) db = VendCrawlerDB(user, password, database) table = 'items' columns = ['item_id', 'item_name', 'vendor_id', 'shop_name', 'amount', 'price', 'map', 'datetime'] values = [] for items in data: for item in items: value = [int(item['id']), item['name'], int(item['vendor_id']), item['shop'], int(item['amount'].replace(',', '')), int(item['price'].replace(',', '')), item['map'], item['datetime']] values.append(value) self.db.insert(table, columns, values) @click.command() @click.argument('json', type=click.File('r')) @click.argument('user') @click.argument('password') @click.argument('database') def cli(json, user, password, database): JSONToSQL(json, user, password, database) if __name__ == '__main__': cli()
import os import os.path from json import loads import click from vendcrawler.scripts.vendcrawlerdb import VendCrawlerDB class JSONToSQL(object): def __init__(self, json, user, password, database): self.data = loads(json.read()) self.db = VendCrawlerDB(user, password, database) table = 'items' columns = ['item_id', 'item_name', 'vendor_id', 'shop_name', 'amount', 'price', 'map', 'datetime'] values = [] for items in data: for item in items: value = [int(item['id']), item['name'], int(item['vendor_id']), item['shop'], int(item['amount'].replace(',', '')), int(item['price'].replace(',', '')), item['map'], item['datetime']] values.append(value) self.vcdb.insert(table, columns, values) @click.command() @click.argument('json', type=click.File('r')) @click.argument('user') @click.argument('password') @click.argument('database') def cli(json, user, password, database): JSONToSQL(json, user, password, database) if __name__ == '__main__': cli() Fix json to sql converter.import os import os.path from json import loads import click from vendcrawler.scripts.vendcrawlerdb import VendCrawlerDB class JSONToSQL(object): def __init__(self, json, user, password, database): data = loads(json.read()) db = VendCrawlerDB(user, password, database) table = 'items' columns = ['item_id', 'item_name', 'vendor_id', 'shop_name', 'amount', 'price', 'map', 'datetime'] values = [] for items in data: for item in items: value = [int(item['id']), item['name'], int(item['vendor_id']), item['shop'], int(item['amount'].replace(',', '')), int(item['price'].replace(',', '')), item['map'], item['datetime']] values.append(value) self.db.insert(table, columns, values) @click.command() @click.argument('json', type=click.File('r')) @click.argument('user') @click.argument('password') @click.argument('database') def cli(json, user, password, database): JSONToSQL(json, user, password, database) if __name__ == '__main__': cli()
<commit_before>import os import os.path from json import loads import click from vendcrawler.scripts.vendcrawlerdb import VendCrawlerDB class JSONToSQL(object): def __init__(self, json, user, password, database): self.data = loads(json.read()) self.db = VendCrawlerDB(user, password, database) table = 'items' columns = ['item_id', 'item_name', 'vendor_id', 'shop_name', 'amount', 'price', 'map', 'datetime'] values = [] for items in data: for item in items: value = [int(item['id']), item['name'], int(item['vendor_id']), item['shop'], int(item['amount'].replace(',', '')), int(item['price'].replace(',', '')), item['map'], item['datetime']] values.append(value) self.vcdb.insert(table, columns, values) @click.command() @click.argument('json', type=click.File('r')) @click.argument('user') @click.argument('password') @click.argument('database') def cli(json, user, password, database): JSONToSQL(json, user, password, database) if __name__ == '__main__': cli() <commit_msg>Fix json to sql converter.<commit_after>import os import os.path from json import loads import click from vendcrawler.scripts.vendcrawlerdb import VendCrawlerDB class JSONToSQL(object): def __init__(self, json, user, password, database): data = loads(json.read()) db = VendCrawlerDB(user, password, database) table = 'items' columns = ['item_id', 'item_name', 'vendor_id', 'shop_name', 'amount', 'price', 'map', 'datetime'] values = [] for items in data: for item in items: value = [int(item['id']), item['name'], int(item['vendor_id']), item['shop'], int(item['amount'].replace(',', '')), int(item['price'].replace(',', '')), item['map'], item['datetime']] values.append(value) self.db.insert(table, columns, values) @click.command() @click.argument('json', type=click.File('r')) @click.argument('user') @click.argument('password') @click.argument('database') def cli(json, user, password, database): JSONToSQL(json, user, password, database) if __name__ == '__main__': cli()
4217f587606c4e326b4df97681ae4f5187b6e6d9
falmer/content/serializers.py
falmer/content/serializers.py
from django.conf import settings from django.urls import reverse from rest_framework import serializers from falmer.content.models import StaffMemberSnippet from falmer.matte.models import MatteImage def generate_image_url(image, filter_spec): from wagtail.wagtailimages.views.serve import generate_signature signature = generate_signature(image.id, filter_spec) url = reverse('wagtailimages_serve', args=(signature, image.id, filter_spec)) # Append image's original filename to the URL (optional) # url += image.file.name[len('original_images/'):] return settings.PUBLIC_HOST + url class WagtailImageSerializer(serializers.ModelSerializer): wagtail_image = serializers.SerializerMethodField() resource = serializers.SerializerMethodField() class Meta: model = MatteImage fields = ('id', 'wagtail_image', 'resource') def get_wagtail_image(self, image): return generate_image_url(image, 'fill-400x400') def get_resource(self, image): return image.file.name class SnippetSerializer(serializers.ModelSerializer): photo = WagtailImageSerializer() class Meta: model = StaffMemberSnippet fields = ('name', 'job_title', 'email', 'office_phone_number', 'mobile_phone_number', 'job_description', 'office_location', 'photo')
from django.conf import settings from django.urls import reverse from rest_framework import serializers from falmer.content.models import StaffMemberSnippet from falmer.matte.models import MatteImage def generate_image_url(image, filter_spec): from wagtail.wagtailimages.views.serve import generate_signature signature = generate_signature(image.id, filter_spec) url = reverse('wagtailimages_serve', args=(signature, image.id, filter_spec)) # Append image's original filename to the URL (optional) # url += image.file.name[len('original_images/'):] return settings.PUBLIC_HOST + url class WagtailImageSerializer(serializers.ModelSerializer): resource = serializers.SerializerMethodField() class Meta: model = MatteImage fields = ('id', 'resource') def get_resource(self, image): return image.file.name class SnippetSerializer(serializers.ModelSerializer): photo = WagtailImageSerializer() class Meta: model = StaffMemberSnippet fields = ('name', 'job_title', 'email', 'office_phone_number', 'mobile_phone_number', 'job_description', 'office_location', 'photo')
Remove wagtail_image from image resources
Remove wagtail_image from image resources
Python
mit
sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer
from django.conf import settings from django.urls import reverse from rest_framework import serializers from falmer.content.models import StaffMemberSnippet from falmer.matte.models import MatteImage def generate_image_url(image, filter_spec): from wagtail.wagtailimages.views.serve import generate_signature signature = generate_signature(image.id, filter_spec) url = reverse('wagtailimages_serve', args=(signature, image.id, filter_spec)) # Append image's original filename to the URL (optional) # url += image.file.name[len('original_images/'):] return settings.PUBLIC_HOST + url class WagtailImageSerializer(serializers.ModelSerializer): wagtail_image = serializers.SerializerMethodField() resource = serializers.SerializerMethodField() class Meta: model = MatteImage fields = ('id', 'wagtail_image', 'resource') def get_wagtail_image(self, image): return generate_image_url(image, 'fill-400x400') def get_resource(self, image): return image.file.name class SnippetSerializer(serializers.ModelSerializer): photo = WagtailImageSerializer() class Meta: model = StaffMemberSnippet fields = ('name', 'job_title', 'email', 'office_phone_number', 'mobile_phone_number', 'job_description', 'office_location', 'photo') Remove wagtail_image from image resources
from django.conf import settings from django.urls import reverse from rest_framework import serializers from falmer.content.models import StaffMemberSnippet from falmer.matte.models import MatteImage def generate_image_url(image, filter_spec): from wagtail.wagtailimages.views.serve import generate_signature signature = generate_signature(image.id, filter_spec) url = reverse('wagtailimages_serve', args=(signature, image.id, filter_spec)) # Append image's original filename to the URL (optional) # url += image.file.name[len('original_images/'):] return settings.PUBLIC_HOST + url class WagtailImageSerializer(serializers.ModelSerializer): resource = serializers.SerializerMethodField() class Meta: model = MatteImage fields = ('id', 'resource') def get_resource(self, image): return image.file.name class SnippetSerializer(serializers.ModelSerializer): photo = WagtailImageSerializer() class Meta: model = StaffMemberSnippet fields = ('name', 'job_title', 'email', 'office_phone_number', 'mobile_phone_number', 'job_description', 'office_location', 'photo')
<commit_before>from django.conf import settings from django.urls import reverse from rest_framework import serializers from falmer.content.models import StaffMemberSnippet from falmer.matte.models import MatteImage def generate_image_url(image, filter_spec): from wagtail.wagtailimages.views.serve import generate_signature signature = generate_signature(image.id, filter_spec) url = reverse('wagtailimages_serve', args=(signature, image.id, filter_spec)) # Append image's original filename to the URL (optional) # url += image.file.name[len('original_images/'):] return settings.PUBLIC_HOST + url class WagtailImageSerializer(serializers.ModelSerializer): wagtail_image = serializers.SerializerMethodField() resource = serializers.SerializerMethodField() class Meta: model = MatteImage fields = ('id', 'wagtail_image', 'resource') def get_wagtail_image(self, image): return generate_image_url(image, 'fill-400x400') def get_resource(self, image): return image.file.name class SnippetSerializer(serializers.ModelSerializer): photo = WagtailImageSerializer() class Meta: model = StaffMemberSnippet fields = ('name', 'job_title', 'email', 'office_phone_number', 'mobile_phone_number', 'job_description', 'office_location', 'photo') <commit_msg>Remove wagtail_image from image resources<commit_after>
from django.conf import settings from django.urls import reverse from rest_framework import serializers from falmer.content.models import StaffMemberSnippet from falmer.matte.models import MatteImage def generate_image_url(image, filter_spec): from wagtail.wagtailimages.views.serve import generate_signature signature = generate_signature(image.id, filter_spec) url = reverse('wagtailimages_serve', args=(signature, image.id, filter_spec)) # Append image's original filename to the URL (optional) # url += image.file.name[len('original_images/'):] return settings.PUBLIC_HOST + url class WagtailImageSerializer(serializers.ModelSerializer): resource = serializers.SerializerMethodField() class Meta: model = MatteImage fields = ('id', 'resource') def get_resource(self, image): return image.file.name class SnippetSerializer(serializers.ModelSerializer): photo = WagtailImageSerializer() class Meta: model = StaffMemberSnippet fields = ('name', 'job_title', 'email', 'office_phone_number', 'mobile_phone_number', 'job_description', 'office_location', 'photo')
from django.conf import settings from django.urls import reverse from rest_framework import serializers from falmer.content.models import StaffMemberSnippet from falmer.matte.models import MatteImage def generate_image_url(image, filter_spec): from wagtail.wagtailimages.views.serve import generate_signature signature = generate_signature(image.id, filter_spec) url = reverse('wagtailimages_serve', args=(signature, image.id, filter_spec)) # Append image's original filename to the URL (optional) # url += image.file.name[len('original_images/'):] return settings.PUBLIC_HOST + url class WagtailImageSerializer(serializers.ModelSerializer): wagtail_image = serializers.SerializerMethodField() resource = serializers.SerializerMethodField() class Meta: model = MatteImage fields = ('id', 'wagtail_image', 'resource') def get_wagtail_image(self, image): return generate_image_url(image, 'fill-400x400') def get_resource(self, image): return image.file.name class SnippetSerializer(serializers.ModelSerializer): photo = WagtailImageSerializer() class Meta: model = StaffMemberSnippet fields = ('name', 'job_title', 'email', 'office_phone_number', 'mobile_phone_number', 'job_description', 'office_location', 'photo') Remove wagtail_image from image resourcesfrom django.conf import settings from django.urls import reverse from rest_framework import serializers from falmer.content.models import StaffMemberSnippet from falmer.matte.models import MatteImage def generate_image_url(image, filter_spec): from wagtail.wagtailimages.views.serve import generate_signature signature = generate_signature(image.id, filter_spec) url = reverse('wagtailimages_serve', args=(signature, image.id, filter_spec)) # Append image's original filename to the URL (optional) # url += image.file.name[len('original_images/'):] return settings.PUBLIC_HOST + url class WagtailImageSerializer(serializers.ModelSerializer): resource = serializers.SerializerMethodField() class Meta: model = MatteImage fields = ('id', 'resource') def get_resource(self, image): return image.file.name class SnippetSerializer(serializers.ModelSerializer): photo = WagtailImageSerializer() class Meta: model = StaffMemberSnippet fields = ('name', 'job_title', 'email', 'office_phone_number', 'mobile_phone_number', 'job_description', 'office_location', 'photo')
<commit_before>from django.conf import settings from django.urls import reverse from rest_framework import serializers from falmer.content.models import StaffMemberSnippet from falmer.matte.models import MatteImage def generate_image_url(image, filter_spec): from wagtail.wagtailimages.views.serve import generate_signature signature = generate_signature(image.id, filter_spec) url = reverse('wagtailimages_serve', args=(signature, image.id, filter_spec)) # Append image's original filename to the URL (optional) # url += image.file.name[len('original_images/'):] return settings.PUBLIC_HOST + url class WagtailImageSerializer(serializers.ModelSerializer): wagtail_image = serializers.SerializerMethodField() resource = serializers.SerializerMethodField() class Meta: model = MatteImage fields = ('id', 'wagtail_image', 'resource') def get_wagtail_image(self, image): return generate_image_url(image, 'fill-400x400') def get_resource(self, image): return image.file.name class SnippetSerializer(serializers.ModelSerializer): photo = WagtailImageSerializer() class Meta: model = StaffMemberSnippet fields = ('name', 'job_title', 'email', 'office_phone_number', 'mobile_phone_number', 'job_description', 'office_location', 'photo') <commit_msg>Remove wagtail_image from image resources<commit_after>from django.conf import settings from django.urls import reverse from rest_framework import serializers from falmer.content.models import StaffMemberSnippet from falmer.matte.models import MatteImage def generate_image_url(image, filter_spec): from wagtail.wagtailimages.views.serve import generate_signature signature = generate_signature(image.id, filter_spec) url = reverse('wagtailimages_serve', args=(signature, image.id, filter_spec)) # Append image's original filename to the URL (optional) # url += image.file.name[len('original_images/'):] return settings.PUBLIC_HOST + url class WagtailImageSerializer(serializers.ModelSerializer): resource = serializers.SerializerMethodField() class Meta: model = MatteImage fields = ('id', 'resource') def get_resource(self, image): return image.file.name class SnippetSerializer(serializers.ModelSerializer): photo = WagtailImageSerializer() class Meta: model = StaffMemberSnippet fields = ('name', 'job_title', 'email', 'office_phone_number', 'mobile_phone_number', 'job_description', 'office_location', 'photo')
20c7905ea062fb6e83ddf641b0a12619044c39e3
blog/models.py
blog/models.py
from django.db import models from django.contrib.auth.models import User from hadrian.utils import slugs from ckeditor.fields import RichTextField from taggit.managers import TaggableManager from .managers import PostManager class Post(models.Model): title = models.CharField(blank=False, max_length=450) slug = models.SlugField(unique=True) image = models.ImageField(blank=True, upload_to='blog/images', null=True) body = RichTextField() excerpt = models.TextField(blank=True, null=True) meta_description = models.CharField(blank=True, max_length=350, help_text='Meta Description for SEO') author = models.ForeignKey(User) published_date = models.DateTimeField() published = models.BooleanField() tags = TaggableManager() objects = PostManager() def __unicode__(self): return self.title @property def get_author_display(self): return "%s %s" % (self.author.first_name, self.author.last_name) def save(self, *args, **kwargs): slugs.unique_slugify(self, self.title) super(Post, self).save(*args, **kwargs) @models.permalink def get_absolute_url(self): return ('post_detail_view', {}, {'slug': self.slug})
from django.db import models from django.contrib.auth.models import User from hadrian.utils import slugs from ckeditor.fields import RichTextField from taggit.managers import TaggableManager from .managers import PostManager class Post(models.Model): title = models.CharField(blank=False, max_length=450) slug = models.SlugField(unique=True) image = models.ImageField(blank=True, upload_to='blog/images', null=True) body = RichTextField() excerpt = models.TextField(blank=True, null=True) meta_description = models.CharField(blank=True, max_length=350, help_text='Meta Description for SEO') author = models.ForeignKey(User) published_date = models.DateTimeField() published = models.BooleanField() tags = TaggableManager() objects = PostManager() def __unicode__(self): return self.title @property def get_author_display(self): return "%s %s" % (self.author.first_name, self.author.last_name) def save(self, *args, **kwargs): slugs.unique_slugify(self, self.title) super(Post, self).save(*args, **kwargs) @models.permalink def get_absolute_url(self): return ('post_detail_view', {}, {'slug': self.slug}) class Meta: ordering = ['-published_date']
Add sort by publish date.
Add sort by publish date.
Python
bsd-3-clause
divisible-by-hero/dbh-blog
from django.db import models from django.contrib.auth.models import User from hadrian.utils import slugs from ckeditor.fields import RichTextField from taggit.managers import TaggableManager from .managers import PostManager class Post(models.Model): title = models.CharField(blank=False, max_length=450) slug = models.SlugField(unique=True) image = models.ImageField(blank=True, upload_to='blog/images', null=True) body = RichTextField() excerpt = models.TextField(blank=True, null=True) meta_description = models.CharField(blank=True, max_length=350, help_text='Meta Description for SEO') author = models.ForeignKey(User) published_date = models.DateTimeField() published = models.BooleanField() tags = TaggableManager() objects = PostManager() def __unicode__(self): return self.title @property def get_author_display(self): return "%s %s" % (self.author.first_name, self.author.last_name) def save(self, *args, **kwargs): slugs.unique_slugify(self, self.title) super(Post, self).save(*args, **kwargs) @models.permalink def get_absolute_url(self): return ('post_detail_view', {}, {'slug': self.slug}) Add sort by publish date.
from django.db import models from django.contrib.auth.models import User from hadrian.utils import slugs from ckeditor.fields import RichTextField from taggit.managers import TaggableManager from .managers import PostManager class Post(models.Model): title = models.CharField(blank=False, max_length=450) slug = models.SlugField(unique=True) image = models.ImageField(blank=True, upload_to='blog/images', null=True) body = RichTextField() excerpt = models.TextField(blank=True, null=True) meta_description = models.CharField(blank=True, max_length=350, help_text='Meta Description for SEO') author = models.ForeignKey(User) published_date = models.DateTimeField() published = models.BooleanField() tags = TaggableManager() objects = PostManager() def __unicode__(self): return self.title @property def get_author_display(self): return "%s %s" % (self.author.first_name, self.author.last_name) def save(self, *args, **kwargs): slugs.unique_slugify(self, self.title) super(Post, self).save(*args, **kwargs) @models.permalink def get_absolute_url(self): return ('post_detail_view', {}, {'slug': self.slug}) class Meta: ordering = ['-published_date']
<commit_before>from django.db import models from django.contrib.auth.models import User from hadrian.utils import slugs from ckeditor.fields import RichTextField from taggit.managers import TaggableManager from .managers import PostManager class Post(models.Model): title = models.CharField(blank=False, max_length=450) slug = models.SlugField(unique=True) image = models.ImageField(blank=True, upload_to='blog/images', null=True) body = RichTextField() excerpt = models.TextField(blank=True, null=True) meta_description = models.CharField(blank=True, max_length=350, help_text='Meta Description for SEO') author = models.ForeignKey(User) published_date = models.DateTimeField() published = models.BooleanField() tags = TaggableManager() objects = PostManager() def __unicode__(self): return self.title @property def get_author_display(self): return "%s %s" % (self.author.first_name, self.author.last_name) def save(self, *args, **kwargs): slugs.unique_slugify(self, self.title) super(Post, self).save(*args, **kwargs) @models.permalink def get_absolute_url(self): return ('post_detail_view', {}, {'slug': self.slug}) <commit_msg>Add sort by publish date.<commit_after>
from django.db import models from django.contrib.auth.models import User from hadrian.utils import slugs from ckeditor.fields import RichTextField from taggit.managers import TaggableManager from .managers import PostManager class Post(models.Model): title = models.CharField(blank=False, max_length=450) slug = models.SlugField(unique=True) image = models.ImageField(blank=True, upload_to='blog/images', null=True) body = RichTextField() excerpt = models.TextField(blank=True, null=True) meta_description = models.CharField(blank=True, max_length=350, help_text='Meta Description for SEO') author = models.ForeignKey(User) published_date = models.DateTimeField() published = models.BooleanField() tags = TaggableManager() objects = PostManager() def __unicode__(self): return self.title @property def get_author_display(self): return "%s %s" % (self.author.first_name, self.author.last_name) def save(self, *args, **kwargs): slugs.unique_slugify(self, self.title) super(Post, self).save(*args, **kwargs) @models.permalink def get_absolute_url(self): return ('post_detail_view', {}, {'slug': self.slug}) class Meta: ordering = ['-published_date']
from django.db import models from django.contrib.auth.models import User from hadrian.utils import slugs from ckeditor.fields import RichTextField from taggit.managers import TaggableManager from .managers import PostManager class Post(models.Model): title = models.CharField(blank=False, max_length=450) slug = models.SlugField(unique=True) image = models.ImageField(blank=True, upload_to='blog/images', null=True) body = RichTextField() excerpt = models.TextField(blank=True, null=True) meta_description = models.CharField(blank=True, max_length=350, help_text='Meta Description for SEO') author = models.ForeignKey(User) published_date = models.DateTimeField() published = models.BooleanField() tags = TaggableManager() objects = PostManager() def __unicode__(self): return self.title @property def get_author_display(self): return "%s %s" % (self.author.first_name, self.author.last_name) def save(self, *args, **kwargs): slugs.unique_slugify(self, self.title) super(Post, self).save(*args, **kwargs) @models.permalink def get_absolute_url(self): return ('post_detail_view', {}, {'slug': self.slug}) Add sort by publish date.from django.db import models from django.contrib.auth.models import User from hadrian.utils import slugs from ckeditor.fields import RichTextField from taggit.managers import TaggableManager from .managers import PostManager class Post(models.Model): title = models.CharField(blank=False, max_length=450) slug = models.SlugField(unique=True) image = models.ImageField(blank=True, upload_to='blog/images', null=True) body = RichTextField() excerpt = models.TextField(blank=True, null=True) meta_description = models.CharField(blank=True, max_length=350, help_text='Meta Description for SEO') author = models.ForeignKey(User) published_date = models.DateTimeField() published = models.BooleanField() tags = TaggableManager() objects = PostManager() def __unicode__(self): return self.title @property def get_author_display(self): return "%s %s" % (self.author.first_name, self.author.last_name) def save(self, *args, **kwargs): slugs.unique_slugify(self, self.title) super(Post, self).save(*args, **kwargs) @models.permalink def get_absolute_url(self): return ('post_detail_view', {}, {'slug': self.slug}) class Meta: ordering = ['-published_date']
<commit_before>from django.db import models from django.contrib.auth.models import User from hadrian.utils import slugs from ckeditor.fields import RichTextField from taggit.managers import TaggableManager from .managers import PostManager class Post(models.Model): title = models.CharField(blank=False, max_length=450) slug = models.SlugField(unique=True) image = models.ImageField(blank=True, upload_to='blog/images', null=True) body = RichTextField() excerpt = models.TextField(blank=True, null=True) meta_description = models.CharField(blank=True, max_length=350, help_text='Meta Description for SEO') author = models.ForeignKey(User) published_date = models.DateTimeField() published = models.BooleanField() tags = TaggableManager() objects = PostManager() def __unicode__(self): return self.title @property def get_author_display(self): return "%s %s" % (self.author.first_name, self.author.last_name) def save(self, *args, **kwargs): slugs.unique_slugify(self, self.title) super(Post, self).save(*args, **kwargs) @models.permalink def get_absolute_url(self): return ('post_detail_view', {}, {'slug': self.slug}) <commit_msg>Add sort by publish date.<commit_after>from django.db import models from django.contrib.auth.models import User from hadrian.utils import slugs from ckeditor.fields import RichTextField from taggit.managers import TaggableManager from .managers import PostManager class Post(models.Model): title = models.CharField(blank=False, max_length=450) slug = models.SlugField(unique=True) image = models.ImageField(blank=True, upload_to='blog/images', null=True) body = RichTextField() excerpt = models.TextField(blank=True, null=True) meta_description = models.CharField(blank=True, max_length=350, help_text='Meta Description for SEO') author = models.ForeignKey(User) published_date = models.DateTimeField() published = models.BooleanField() tags = TaggableManager() objects = PostManager() def __unicode__(self): return self.title @property def get_author_display(self): return "%s %s" % (self.author.first_name, self.author.last_name) def save(self, *args, **kwargs): slugs.unique_slugify(self, self.title) super(Post, self).save(*args, **kwargs) @models.permalink def get_absolute_url(self): return ('post_detail_view', {}, {'slug': self.slug}) class Meta: ordering = ['-published_date']
b452e9a42d507c000bf6d3068af425d9c0eda8fd
validation/validate_poi.py
validation/validate_poi.py
#!/usr/bin/python """ starter code for the validation mini-project the first step toward building your POI identifier! start by loading/formatting the data after that, it's not our code anymore--it's yours! """ import pickle import sys sys.path.append("../tools/") from feature_format import featureFormat, targetFeatureSplit data_dict = pickle.load(open("../final_project/final_project_dataset.pkl", "r") ) ### add more features to features_list! features_list = ["poi", "salary"] data = featureFormat(data_dict, features_list) labels, features = targetFeatureSplit(data) ### it's all yours from here forward!
#!/usr/bin/python """ starter code for the validation mini-project the first step toward building your POI identifier! start by loading/formatting the data after that, it's not our code anymore--it's yours! """ import pickle import sys sys.path.append("../tools/") from feature_format import featureFormat, targetFeatureSplit data_dict = pickle.load(open("../final_project/final_project_dataset.pkl", "r") ) ### first element is our labels, any added elements are predictor ### features. Keep this the same for the mini-project, but you'll ### have a different feature list when you do the final project. features_list = ["poi", "salary"] data = featureFormat(data_dict, features_list) labels, features = targetFeatureSplit(data) ### it's all yours from here forward!
Improve instructions for Lesson 13 mini-project.
Improve instructions for Lesson 13 mini-project.
Python
mit
selva86/python-machine-learning,ncfausti/udacity-machine-learning
#!/usr/bin/python """ starter code for the validation mini-project the first step toward building your POI identifier! start by loading/formatting the data after that, it's not our code anymore--it's yours! """ import pickle import sys sys.path.append("../tools/") from feature_format import featureFormat, targetFeatureSplit data_dict = pickle.load(open("../final_project/final_project_dataset.pkl", "r") ) ### add more features to features_list! features_list = ["poi", "salary"] data = featureFormat(data_dict, features_list) labels, features = targetFeatureSplit(data) ### it's all yours from here forward! Improve instructions for Lesson 13 mini-project.
#!/usr/bin/python """ starter code for the validation mini-project the first step toward building your POI identifier! start by loading/formatting the data after that, it's not our code anymore--it's yours! """ import pickle import sys sys.path.append("../tools/") from feature_format import featureFormat, targetFeatureSplit data_dict = pickle.load(open("../final_project/final_project_dataset.pkl", "r") ) ### first element is our labels, any added elements are predictor ### features. Keep this the same for the mini-project, but you'll ### have a different feature list when you do the final project. features_list = ["poi", "salary"] data = featureFormat(data_dict, features_list) labels, features = targetFeatureSplit(data) ### it's all yours from here forward!
<commit_before>#!/usr/bin/python """ starter code for the validation mini-project the first step toward building your POI identifier! start by loading/formatting the data after that, it's not our code anymore--it's yours! """ import pickle import sys sys.path.append("../tools/") from feature_format import featureFormat, targetFeatureSplit data_dict = pickle.load(open("../final_project/final_project_dataset.pkl", "r") ) ### add more features to features_list! features_list = ["poi", "salary"] data = featureFormat(data_dict, features_list) labels, features = targetFeatureSplit(data) ### it's all yours from here forward! <commit_msg>Improve instructions for Lesson 13 mini-project.<commit_after>
#!/usr/bin/python """ starter code for the validation mini-project the first step toward building your POI identifier! start by loading/formatting the data after that, it's not our code anymore--it's yours! """ import pickle import sys sys.path.append("../tools/") from feature_format import featureFormat, targetFeatureSplit data_dict = pickle.load(open("../final_project/final_project_dataset.pkl", "r") ) ### first element is our labels, any added elements are predictor ### features. Keep this the same for the mini-project, but you'll ### have a different feature list when you do the final project. features_list = ["poi", "salary"] data = featureFormat(data_dict, features_list) labels, features = targetFeatureSplit(data) ### it's all yours from here forward!
#!/usr/bin/python """ starter code for the validation mini-project the first step toward building your POI identifier! start by loading/formatting the data after that, it's not our code anymore--it's yours! """ import pickle import sys sys.path.append("../tools/") from feature_format import featureFormat, targetFeatureSplit data_dict = pickle.load(open("../final_project/final_project_dataset.pkl", "r") ) ### add more features to features_list! features_list = ["poi", "salary"] data = featureFormat(data_dict, features_list) labels, features = targetFeatureSplit(data) ### it's all yours from here forward! Improve instructions for Lesson 13 mini-project.#!/usr/bin/python """ starter code for the validation mini-project the first step toward building your POI identifier! start by loading/formatting the data after that, it's not our code anymore--it's yours! """ import pickle import sys sys.path.append("../tools/") from feature_format import featureFormat, targetFeatureSplit data_dict = pickle.load(open("../final_project/final_project_dataset.pkl", "r") ) ### first element is our labels, any added elements are predictor ### features. Keep this the same for the mini-project, but you'll ### have a different feature list when you do the final project. features_list = ["poi", "salary"] data = featureFormat(data_dict, features_list) labels, features = targetFeatureSplit(data) ### it's all yours from here forward!
<commit_before>#!/usr/bin/python """ starter code for the validation mini-project the first step toward building your POI identifier! start by loading/formatting the data after that, it's not our code anymore--it's yours! """ import pickle import sys sys.path.append("../tools/") from feature_format import featureFormat, targetFeatureSplit data_dict = pickle.load(open("../final_project/final_project_dataset.pkl", "r") ) ### add more features to features_list! features_list = ["poi", "salary"] data = featureFormat(data_dict, features_list) labels, features = targetFeatureSplit(data) ### it's all yours from here forward! <commit_msg>Improve instructions for Lesson 13 mini-project.<commit_after>#!/usr/bin/python """ starter code for the validation mini-project the first step toward building your POI identifier! start by loading/formatting the data after that, it's not our code anymore--it's yours! """ import pickle import sys sys.path.append("../tools/") from feature_format import featureFormat, targetFeatureSplit data_dict = pickle.load(open("../final_project/final_project_dataset.pkl", "r") ) ### first element is our labels, any added elements are predictor ### features. Keep this the same for the mini-project, but you'll ### have a different feature list when you do the final project. features_list = ["poi", "salary"] data = featureFormat(data_dict, features_list) labels, features = targetFeatureSplit(data) ### it's all yours from here forward!
bfe779aa65abaff7430b1870a1023b0d5b2e02f8
lib/pyfrc/tests/__init__.py
lib/pyfrc/tests/__init__.py
''' These generic test modules can be applied to :class:`wpilib.iterativerobot.IterativeRobot` and :class:`wpilib.samplerobot.SampleRobot` based robots. ''' # import basic tests from .basic import ( test_autonomous, test_disabled, test_operator_control, test_practice ) # import common test types from .docstring_test import test_docstrings # simple-specific test types from .fuzz_test import test_fuzz
''' These generic test modules can be applied to :class:`wpilib.iterativerobot.IterativeRobot` and :class:`wpilib.samplerobot.SampleRobot` based robots. ''' # import basic tests from .basic import ( test_autonomous, test_disabled, test_operator_control, test_practice ) # Other test types from .fuzz_test import test_fuzz
Remove docstring tests from default tests
Remove docstring tests from default tests
Python
mit
robotpy/pyfrc
''' These generic test modules can be applied to :class:`wpilib.iterativerobot.IterativeRobot` and :class:`wpilib.samplerobot.SampleRobot` based robots. ''' # import basic tests from .basic import ( test_autonomous, test_disabled, test_operator_control, test_practice ) # import common test types from .docstring_test import test_docstrings # simple-specific test types from .fuzz_test import test_fuzz Remove docstring tests from default tests
''' These generic test modules can be applied to :class:`wpilib.iterativerobot.IterativeRobot` and :class:`wpilib.samplerobot.SampleRobot` based robots. ''' # import basic tests from .basic import ( test_autonomous, test_disabled, test_operator_control, test_practice ) # Other test types from .fuzz_test import test_fuzz
<commit_before>''' These generic test modules can be applied to :class:`wpilib.iterativerobot.IterativeRobot` and :class:`wpilib.samplerobot.SampleRobot` based robots. ''' # import basic tests from .basic import ( test_autonomous, test_disabled, test_operator_control, test_practice ) # import common test types from .docstring_test import test_docstrings # simple-specific test types from .fuzz_test import test_fuzz <commit_msg>Remove docstring tests from default tests<commit_after>
''' These generic test modules can be applied to :class:`wpilib.iterativerobot.IterativeRobot` and :class:`wpilib.samplerobot.SampleRobot` based robots. ''' # import basic tests from .basic import ( test_autonomous, test_disabled, test_operator_control, test_practice ) # Other test types from .fuzz_test import test_fuzz
''' These generic test modules can be applied to :class:`wpilib.iterativerobot.IterativeRobot` and :class:`wpilib.samplerobot.SampleRobot` based robots. ''' # import basic tests from .basic import ( test_autonomous, test_disabled, test_operator_control, test_practice ) # import common test types from .docstring_test import test_docstrings # simple-specific test types from .fuzz_test import test_fuzz Remove docstring tests from default tests''' These generic test modules can be applied to :class:`wpilib.iterativerobot.IterativeRobot` and :class:`wpilib.samplerobot.SampleRobot` based robots. ''' # import basic tests from .basic import ( test_autonomous, test_disabled, test_operator_control, test_practice ) # Other test types from .fuzz_test import test_fuzz
<commit_before>''' These generic test modules can be applied to :class:`wpilib.iterativerobot.IterativeRobot` and :class:`wpilib.samplerobot.SampleRobot` based robots. ''' # import basic tests from .basic import ( test_autonomous, test_disabled, test_operator_control, test_practice ) # import common test types from .docstring_test import test_docstrings # simple-specific test types from .fuzz_test import test_fuzz <commit_msg>Remove docstring tests from default tests<commit_after>''' These generic test modules can be applied to :class:`wpilib.iterativerobot.IterativeRobot` and :class:`wpilib.samplerobot.SampleRobot` based robots. ''' # import basic tests from .basic import ( test_autonomous, test_disabled, test_operator_control, test_practice ) # Other test types from .fuzz_test import test_fuzz
fc09e847a5435581738a32f8aa158e7d03491b94
calico_containers/tests/st/test_container_to_host.py
calico_containers/tests/st/test_container_to_host.py
from subprocess import CalledProcessError from test_base import TestBase from tests.st.utils.docker_host import DockerHost class TestContainerToHost(TestBase): def test_container_to_host(self): """ Test that a container can ping the host. (Without using the docker network driver, since it doesn't support that yet.) This function is important for Mesos, since the containerized executor needs to exchange messages with the Mesos Slave process on the host. """ with DockerHost('host', dind=False) as host: host.calicoctl("profile add TEST") # Use standard docker bridge networking. node1 = host.create_workload("node1") # Add the nodes to Calico networking. host.calicoctl("container add %s 192.168.100.1" % node1) # Get the endpoint IDs for the containers ep1 = host.calicoctl("container %s endpoint-id show" % node1) # Now add the profiles. host.calicoctl("endpoint %s profile set TEST" % ep1) # Check it works. Note that the profile allows all outgoing # traffic by default, and conntrack should allow the reply. node1.assert_can_ping(host.ip, retries=10) # Test the teardown commands host.calicoctl("profile remove TEST") host.calicoctl("container remove %s" % node1) host.calicoctl("pool remove 192.168.0.0/16") host.calicoctl("node stop")
from subprocess import CalledProcessError from test_base import TestBase from tests.st.utils.docker_host import DockerHost class TestContainerToHost(TestBase): def test_container_to_host(self): """ Test that a container can ping the host. This function is important for Mesos, since the containerized executor needs to exchange messages with the Mesos Slave process on the host. Note also that we do not use the Docker Network driver for this test. The Docker Container Network Model defines a "network" as a group of endpoints that can communicate with each other, but are isolated from everything else. Thus, an endpoint of a Docker network should not be able to ping the host. """ with DockerHost('host', dind=False) as host: host.calicoctl("profile add TEST") # Use standard docker bridge networking. node1 = host.create_workload("node1") # Add the nodes to Calico networking. host.calicoctl("container add %s 192.168.100.1" % node1) # Get the endpoint IDs for the containers ep1 = host.calicoctl("container %s endpoint-id show" % node1) # Now add the profiles. host.calicoctl("endpoint %s profile set TEST" % ep1) # Check it works. Note that the profile allows all outgoing # traffic by default, and conntrack should allow the reply. node1.assert_can_ping(host.ip, retries=10)
Clarify test_containers_to_host not using libnetwork
Clarify test_containers_to_host not using libnetwork Former-commit-id: fbd7c3b5627ba288ac400944ee242f3369143291
Python
apache-2.0
plwhite/libcalico,TrimBiggs/libcalico,caseydavenport/libcalico,alexhersh/libcalico,insequent/libcalico,tomdee/libnetwork-plugin,projectcalico/libcalico,TrimBiggs/libnetwork-plugin,djosborne/libcalico,TrimBiggs/libnetwork-plugin,tomdee/libcalico,L-MA/libcalico,robbrockbank/libcalico,Symmetric/libcalico,projectcalico/libnetwork-plugin
from subprocess import CalledProcessError from test_base import TestBase from tests.st.utils.docker_host import DockerHost class TestContainerToHost(TestBase): def test_container_to_host(self): """ Test that a container can ping the host. (Without using the docker network driver, since it doesn't support that yet.) This function is important for Mesos, since the containerized executor needs to exchange messages with the Mesos Slave process on the host. """ with DockerHost('host', dind=False) as host: host.calicoctl("profile add TEST") # Use standard docker bridge networking. node1 = host.create_workload("node1") # Add the nodes to Calico networking. host.calicoctl("container add %s 192.168.100.1" % node1) # Get the endpoint IDs for the containers ep1 = host.calicoctl("container %s endpoint-id show" % node1) # Now add the profiles. host.calicoctl("endpoint %s profile set TEST" % ep1) # Check it works. Note that the profile allows all outgoing # traffic by default, and conntrack should allow the reply. node1.assert_can_ping(host.ip, retries=10) # Test the teardown commands host.calicoctl("profile remove TEST") host.calicoctl("container remove %s" % node1) host.calicoctl("pool remove 192.168.0.0/16") host.calicoctl("node stop") Clarify test_containers_to_host not using libnetwork Former-commit-id: fbd7c3b5627ba288ac400944ee242f3369143291
from subprocess import CalledProcessError from test_base import TestBase from tests.st.utils.docker_host import DockerHost class TestContainerToHost(TestBase): def test_container_to_host(self): """ Test that a container can ping the host. This function is important for Mesos, since the containerized executor needs to exchange messages with the Mesos Slave process on the host. Note also that we do not use the Docker Network driver for this test. The Docker Container Network Model defines a "network" as a group of endpoints that can communicate with each other, but are isolated from everything else. Thus, an endpoint of a Docker network should not be able to ping the host. """ with DockerHost('host', dind=False) as host: host.calicoctl("profile add TEST") # Use standard docker bridge networking. node1 = host.create_workload("node1") # Add the nodes to Calico networking. host.calicoctl("container add %s 192.168.100.1" % node1) # Get the endpoint IDs for the containers ep1 = host.calicoctl("container %s endpoint-id show" % node1) # Now add the profiles. host.calicoctl("endpoint %s profile set TEST" % ep1) # Check it works. Note that the profile allows all outgoing # traffic by default, and conntrack should allow the reply. node1.assert_can_ping(host.ip, retries=10)
<commit_before>from subprocess import CalledProcessError from test_base import TestBase from tests.st.utils.docker_host import DockerHost class TestContainerToHost(TestBase): def test_container_to_host(self): """ Test that a container can ping the host. (Without using the docker network driver, since it doesn't support that yet.) This function is important for Mesos, since the containerized executor needs to exchange messages with the Mesos Slave process on the host. """ with DockerHost('host', dind=False) as host: host.calicoctl("profile add TEST") # Use standard docker bridge networking. node1 = host.create_workload("node1") # Add the nodes to Calico networking. host.calicoctl("container add %s 192.168.100.1" % node1) # Get the endpoint IDs for the containers ep1 = host.calicoctl("container %s endpoint-id show" % node1) # Now add the profiles. host.calicoctl("endpoint %s profile set TEST" % ep1) # Check it works. Note that the profile allows all outgoing # traffic by default, and conntrack should allow the reply. node1.assert_can_ping(host.ip, retries=10) # Test the teardown commands host.calicoctl("profile remove TEST") host.calicoctl("container remove %s" % node1) host.calicoctl("pool remove 192.168.0.0/16") host.calicoctl("node stop") <commit_msg>Clarify test_containers_to_host not using libnetwork Former-commit-id: fbd7c3b5627ba288ac400944ee242f3369143291<commit_after>
from subprocess import CalledProcessError from test_base import TestBase from tests.st.utils.docker_host import DockerHost class TestContainerToHost(TestBase): def test_container_to_host(self): """ Test that a container can ping the host. This function is important for Mesos, since the containerized executor needs to exchange messages with the Mesos Slave process on the host. Note also that we do not use the Docker Network driver for this test. The Docker Container Network Model defines a "network" as a group of endpoints that can communicate with each other, but are isolated from everything else. Thus, an endpoint of a Docker network should not be able to ping the host. """ with DockerHost('host', dind=False) as host: host.calicoctl("profile add TEST") # Use standard docker bridge networking. node1 = host.create_workload("node1") # Add the nodes to Calico networking. host.calicoctl("container add %s 192.168.100.1" % node1) # Get the endpoint IDs for the containers ep1 = host.calicoctl("container %s endpoint-id show" % node1) # Now add the profiles. host.calicoctl("endpoint %s profile set TEST" % ep1) # Check it works. Note that the profile allows all outgoing # traffic by default, and conntrack should allow the reply. node1.assert_can_ping(host.ip, retries=10)
from subprocess import CalledProcessError from test_base import TestBase from tests.st.utils.docker_host import DockerHost class TestContainerToHost(TestBase): def test_container_to_host(self): """ Test that a container can ping the host. (Without using the docker network driver, since it doesn't support that yet.) This function is important for Mesos, since the containerized executor needs to exchange messages with the Mesos Slave process on the host. """ with DockerHost('host', dind=False) as host: host.calicoctl("profile add TEST") # Use standard docker bridge networking. node1 = host.create_workload("node1") # Add the nodes to Calico networking. host.calicoctl("container add %s 192.168.100.1" % node1) # Get the endpoint IDs for the containers ep1 = host.calicoctl("container %s endpoint-id show" % node1) # Now add the profiles. host.calicoctl("endpoint %s profile set TEST" % ep1) # Check it works. Note that the profile allows all outgoing # traffic by default, and conntrack should allow the reply. node1.assert_can_ping(host.ip, retries=10) # Test the teardown commands host.calicoctl("profile remove TEST") host.calicoctl("container remove %s" % node1) host.calicoctl("pool remove 192.168.0.0/16") host.calicoctl("node stop") Clarify test_containers_to_host not using libnetwork Former-commit-id: fbd7c3b5627ba288ac400944ee242f3369143291from subprocess import CalledProcessError from test_base import TestBase from tests.st.utils.docker_host import DockerHost class TestContainerToHost(TestBase): def test_container_to_host(self): """ Test that a container can ping the host. This function is important for Mesos, since the containerized executor needs to exchange messages with the Mesos Slave process on the host. Note also that we do not use the Docker Network driver for this test. The Docker Container Network Model defines a "network" as a group of endpoints that can communicate with each other, but are isolated from everything else. Thus, an endpoint of a Docker network should not be able to ping the host. """ with DockerHost('host', dind=False) as host: host.calicoctl("profile add TEST") # Use standard docker bridge networking. node1 = host.create_workload("node1") # Add the nodes to Calico networking. host.calicoctl("container add %s 192.168.100.1" % node1) # Get the endpoint IDs for the containers ep1 = host.calicoctl("container %s endpoint-id show" % node1) # Now add the profiles. host.calicoctl("endpoint %s profile set TEST" % ep1) # Check it works. Note that the profile allows all outgoing # traffic by default, and conntrack should allow the reply. node1.assert_can_ping(host.ip, retries=10)
<commit_before>from subprocess import CalledProcessError from test_base import TestBase from tests.st.utils.docker_host import DockerHost class TestContainerToHost(TestBase): def test_container_to_host(self): """ Test that a container can ping the host. (Without using the docker network driver, since it doesn't support that yet.) This function is important for Mesos, since the containerized executor needs to exchange messages with the Mesos Slave process on the host. """ with DockerHost('host', dind=False) as host: host.calicoctl("profile add TEST") # Use standard docker bridge networking. node1 = host.create_workload("node1") # Add the nodes to Calico networking. host.calicoctl("container add %s 192.168.100.1" % node1) # Get the endpoint IDs for the containers ep1 = host.calicoctl("container %s endpoint-id show" % node1) # Now add the profiles. host.calicoctl("endpoint %s profile set TEST" % ep1) # Check it works. Note that the profile allows all outgoing # traffic by default, and conntrack should allow the reply. node1.assert_can_ping(host.ip, retries=10) # Test the teardown commands host.calicoctl("profile remove TEST") host.calicoctl("container remove %s" % node1) host.calicoctl("pool remove 192.168.0.0/16") host.calicoctl("node stop") <commit_msg>Clarify test_containers_to_host not using libnetwork Former-commit-id: fbd7c3b5627ba288ac400944ee242f3369143291<commit_after>from subprocess import CalledProcessError from test_base import TestBase from tests.st.utils.docker_host import DockerHost class TestContainerToHost(TestBase): def test_container_to_host(self): """ Test that a container can ping the host. This function is important for Mesos, since the containerized executor needs to exchange messages with the Mesos Slave process on the host. Note also that we do not use the Docker Network driver for this test. The Docker Container Network Model defines a "network" as a group of endpoints that can communicate with each other, but are isolated from everything else. Thus, an endpoint of a Docker network should not be able to ping the host. """ with DockerHost('host', dind=False) as host: host.calicoctl("profile add TEST") # Use standard docker bridge networking. node1 = host.create_workload("node1") # Add the nodes to Calico networking. host.calicoctl("container add %s 192.168.100.1" % node1) # Get the endpoint IDs for the containers ep1 = host.calicoctl("container %s endpoint-id show" % node1) # Now add the profiles. host.calicoctl("endpoint %s profile set TEST" % ep1) # Check it works. Note that the profile allows all outgoing # traffic by default, and conntrack should allow the reply. node1.assert_can_ping(host.ip, retries=10)
37337298d881280a45dad7f0f47ad719feb4baa6
addons/bestja_configuration_fpbz/__openerp__.py
addons/bestja_configuration_fpbz/__openerp__.py
# -*- coding: utf-8 -*- { 'name': "Bestja: FBŻ", 'summary': "Installation configuration for FPBŻ", 'description': "Installation configuration for Federacja Polskich Banków Żywności", 'author': "Laboratorium EE", 'website': "http://www.laboratorium.ee", 'version': '0.1', 'category': 'Specific Industry Applications', 'depends': [ 'base', 'bestja_base', 'bestja_volunteer', 'bestja_volunteer_notes', 'bestja_organization', 'bestja_organization_hierarchy', 'bestja_project', 'bestja_offers', 'bestja_files', 'email_confirmation', 'quizzes', 'bestja_organization_warehouse' ], 'application': True, }
# -*- coding: utf-8 -*- { 'name': "Bestja: FBŻ", 'summary': "Installation configuration for FPBŻ", 'description': "Installation configuration for Federacja Polskich Banków Żywności", 'author': "Laboratorium EE", 'website': "http://www.laboratorium.ee", 'version': '0.1', 'category': 'Specific Industry Applications', 'depends': [ 'base', 'bestja_base', 'bestja_volunteer', 'bestja_volunteer_notes', 'bestja_organization', 'bestja_organization_hierarchy', 'bestja_project', 'bestja_project_hierarchy', 'bestja_offers', 'bestja_files', 'email_confirmation', 'quizzes', 'bestja_organization_warehouse' ], 'application': True, }
Add bestja_project_hierarchy to the list of FPBZ's modules
Add bestja_project_hierarchy to the list of FPBZ's modules
Python
agpl-3.0
ludwiktrammer/bestja,KamilWo/bestja,EE/bestja,KamilWo/bestja,ludwiktrammer/bestja,KrzysiekJ/bestja,EE/bestja,KrzysiekJ/bestja,KamilWo/bestja,ludwiktrammer/bestja,EE/bestja,KrzysiekJ/bestja
# -*- coding: utf-8 -*- { 'name': "Bestja: FBŻ", 'summary': "Installation configuration for FPBŻ", 'description': "Installation configuration for Federacja Polskich Banków Żywności", 'author': "Laboratorium EE", 'website': "http://www.laboratorium.ee", 'version': '0.1', 'category': 'Specific Industry Applications', 'depends': [ 'base', 'bestja_base', 'bestja_volunteer', 'bestja_volunteer_notes', 'bestja_organization', 'bestja_organization_hierarchy', 'bestja_project', 'bestja_offers', 'bestja_files', 'email_confirmation', 'quizzes', 'bestja_organization_warehouse' ], 'application': True, } Add bestja_project_hierarchy to the list of FPBZ's modules
# -*- coding: utf-8 -*- { 'name': "Bestja: FBŻ", 'summary': "Installation configuration for FPBŻ", 'description': "Installation configuration for Federacja Polskich Banków Żywności", 'author': "Laboratorium EE", 'website': "http://www.laboratorium.ee", 'version': '0.1', 'category': 'Specific Industry Applications', 'depends': [ 'base', 'bestja_base', 'bestja_volunteer', 'bestja_volunteer_notes', 'bestja_organization', 'bestja_organization_hierarchy', 'bestja_project', 'bestja_project_hierarchy', 'bestja_offers', 'bestja_files', 'email_confirmation', 'quizzes', 'bestja_organization_warehouse' ], 'application': True, }
<commit_before># -*- coding: utf-8 -*- { 'name': "Bestja: FBŻ", 'summary': "Installation configuration for FPBŻ", 'description': "Installation configuration for Federacja Polskich Banków Żywności", 'author': "Laboratorium EE", 'website': "http://www.laboratorium.ee", 'version': '0.1', 'category': 'Specific Industry Applications', 'depends': [ 'base', 'bestja_base', 'bestja_volunteer', 'bestja_volunteer_notes', 'bestja_organization', 'bestja_organization_hierarchy', 'bestja_project', 'bestja_offers', 'bestja_files', 'email_confirmation', 'quizzes', 'bestja_organization_warehouse' ], 'application': True, } <commit_msg>Add bestja_project_hierarchy to the list of FPBZ's modules<commit_after>
# -*- coding: utf-8 -*- { 'name': "Bestja: FBŻ", 'summary': "Installation configuration for FPBŻ", 'description': "Installation configuration for Federacja Polskich Banków Żywności", 'author': "Laboratorium EE", 'website': "http://www.laboratorium.ee", 'version': '0.1', 'category': 'Specific Industry Applications', 'depends': [ 'base', 'bestja_base', 'bestja_volunteer', 'bestja_volunteer_notes', 'bestja_organization', 'bestja_organization_hierarchy', 'bestja_project', 'bestja_project_hierarchy', 'bestja_offers', 'bestja_files', 'email_confirmation', 'quizzes', 'bestja_organization_warehouse' ], 'application': True, }
# -*- coding: utf-8 -*- { 'name': "Bestja: FBŻ", 'summary': "Installation configuration for FPBŻ", 'description': "Installation configuration for Federacja Polskich Banków Żywności", 'author': "Laboratorium EE", 'website': "http://www.laboratorium.ee", 'version': '0.1', 'category': 'Specific Industry Applications', 'depends': [ 'base', 'bestja_base', 'bestja_volunteer', 'bestja_volunteer_notes', 'bestja_organization', 'bestja_organization_hierarchy', 'bestja_project', 'bestja_offers', 'bestja_files', 'email_confirmation', 'quizzes', 'bestja_organization_warehouse' ], 'application': True, } Add bestja_project_hierarchy to the list of FPBZ's modules# -*- coding: utf-8 -*- { 'name': "Bestja: FBŻ", 'summary': "Installation configuration for FPBŻ", 'description': "Installation configuration for Federacja Polskich Banków Żywności", 'author': "Laboratorium EE", 'website': "http://www.laboratorium.ee", 'version': '0.1', 'category': 'Specific Industry Applications', 'depends': [ 'base', 'bestja_base', 'bestja_volunteer', 'bestja_volunteer_notes', 'bestja_organization', 'bestja_organization_hierarchy', 'bestja_project', 'bestja_project_hierarchy', 'bestja_offers', 'bestja_files', 'email_confirmation', 'quizzes', 'bestja_organization_warehouse' ], 'application': True, }
<commit_before># -*- coding: utf-8 -*- { 'name': "Bestja: FBŻ", 'summary': "Installation configuration for FPBŻ", 'description': "Installation configuration for Federacja Polskich Banków Żywności", 'author': "Laboratorium EE", 'website': "http://www.laboratorium.ee", 'version': '0.1', 'category': 'Specific Industry Applications', 'depends': [ 'base', 'bestja_base', 'bestja_volunteer', 'bestja_volunteer_notes', 'bestja_organization', 'bestja_organization_hierarchy', 'bestja_project', 'bestja_offers', 'bestja_files', 'email_confirmation', 'quizzes', 'bestja_organization_warehouse' ], 'application': True, } <commit_msg>Add bestja_project_hierarchy to the list of FPBZ's modules<commit_after># -*- coding: utf-8 -*- { 'name': "Bestja: FBŻ", 'summary': "Installation configuration for FPBŻ", 'description': "Installation configuration for Federacja Polskich Banków Żywności", 'author': "Laboratorium EE", 'website': "http://www.laboratorium.ee", 'version': '0.1', 'category': 'Specific Industry Applications', 'depends': [ 'base', 'bestja_base', 'bestja_volunteer', 'bestja_volunteer_notes', 'bestja_organization', 'bestja_organization_hierarchy', 'bestja_project', 'bestja_project_hierarchy', 'bestja_offers', 'bestja_files', 'email_confirmation', 'quizzes', 'bestja_organization_warehouse' ], 'application': True, }
b28a7e50bc90dc0292efefd7665a00d62245311a
app.py
app.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from flask import Flask, request, json from flask.ext.cors import CORS import database import rsser # Update data before application is allowed to start database.update_database() app = Flask(__name__) CORS(app) @app.route('/speakercast/speakers') def speakers(): speakers = [{'name': name, 'talks': count} for count, name in database.get_all_speaker_and_counts()] return json.dumps(speakers) @app.route('/speakercast/speakercast/generate', methods=['POST', 'OPTIONS']) def generate(): data = json.loads(request.data) speakers = data['speakers'] id_ = database.generate_id(speakers) return id_ @app.route('/speakercast/feed/<id>') def feed(id): speakers = database.get_speakers(id) if speakers is None: # TODO: Send some error return "ERROR" talks = database.get_talks(speakers) return rsser.create_rss_feed(talks=talks, speakers=list(speakers)) if __name__ == "__main__": app.run(debug=True)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from flask import Flask, request, json from flask.ext.cors import CORS import database import rsser # Update data before application is allowed to start database.update_database() app = Flask(__name__) CORS(app) @app.route('/speakercast/speakers') def speakers(): speakers = [{'name': name, 'talks': count} for count, name in database.get_all_speaker_and_counts()] return json.dumps(speakers) @app.route('/speakercast/generate', methods=['POST', 'OPTIONS']) def generate(): data = json.loads(request.data) speakers = data['speakers'] id_ = database.generate_id(speakers) return id_ @app.route('/speakercast/feed/<id>') def feed(id): speakers = database.get_speakers(id) if speakers is None: # TODO: Send some error return "ERROR" talks = database.get_talks(speakers) return rsser.create_rss_feed(talks=talks, speakers=list(speakers)) if __name__ == "__main__": app.run(debug=True)
Fix error with generate URL
Fix error with generate URL
Python
bsd-3-clause
philipbl/SpeakerCast,philipbl/talk_feed
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from flask import Flask, request, json from flask.ext.cors import CORS import database import rsser # Update data before application is allowed to start database.update_database() app = Flask(__name__) CORS(app) @app.route('/speakercast/speakers') def speakers(): speakers = [{'name': name, 'talks': count} for count, name in database.get_all_speaker_and_counts()] return json.dumps(speakers) @app.route('/speakercast/speakercast/generate', methods=['POST', 'OPTIONS']) def generate(): data = json.loads(request.data) speakers = data['speakers'] id_ = database.generate_id(speakers) return id_ @app.route('/speakercast/feed/<id>') def feed(id): speakers = database.get_speakers(id) if speakers is None: # TODO: Send some error return "ERROR" talks = database.get_talks(speakers) return rsser.create_rss_feed(talks=talks, speakers=list(speakers)) if __name__ == "__main__": app.run(debug=True) Fix error with generate URL
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from flask import Flask, request, json from flask.ext.cors import CORS import database import rsser # Update data before application is allowed to start database.update_database() app = Flask(__name__) CORS(app) @app.route('/speakercast/speakers') def speakers(): speakers = [{'name': name, 'talks': count} for count, name in database.get_all_speaker_and_counts()] return json.dumps(speakers) @app.route('/speakercast/generate', methods=['POST', 'OPTIONS']) def generate(): data = json.loads(request.data) speakers = data['speakers'] id_ = database.generate_id(speakers) return id_ @app.route('/speakercast/feed/<id>') def feed(id): speakers = database.get_speakers(id) if speakers is None: # TODO: Send some error return "ERROR" talks = database.get_talks(speakers) return rsser.create_rss_feed(talks=talks, speakers=list(speakers)) if __name__ == "__main__": app.run(debug=True)
<commit_before>#!/usr/bin/env python3 # -*- coding: utf-8 -*- from flask import Flask, request, json from flask.ext.cors import CORS import database import rsser # Update data before application is allowed to start database.update_database() app = Flask(__name__) CORS(app) @app.route('/speakercast/speakers') def speakers(): speakers = [{'name': name, 'talks': count} for count, name in database.get_all_speaker_and_counts()] return json.dumps(speakers) @app.route('/speakercast/speakercast/generate', methods=['POST', 'OPTIONS']) def generate(): data = json.loads(request.data) speakers = data['speakers'] id_ = database.generate_id(speakers) return id_ @app.route('/speakercast/feed/<id>') def feed(id): speakers = database.get_speakers(id) if speakers is None: # TODO: Send some error return "ERROR" talks = database.get_talks(speakers) return rsser.create_rss_feed(talks=talks, speakers=list(speakers)) if __name__ == "__main__": app.run(debug=True) <commit_msg>Fix error with generate URL<commit_after>
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from flask import Flask, request, json from flask.ext.cors import CORS import database import rsser # Update data before application is allowed to start database.update_database() app = Flask(__name__) CORS(app) @app.route('/speakercast/speakers') def speakers(): speakers = [{'name': name, 'talks': count} for count, name in database.get_all_speaker_and_counts()] return json.dumps(speakers) @app.route('/speakercast/generate', methods=['POST', 'OPTIONS']) def generate(): data = json.loads(request.data) speakers = data['speakers'] id_ = database.generate_id(speakers) return id_ @app.route('/speakercast/feed/<id>') def feed(id): speakers = database.get_speakers(id) if speakers is None: # TODO: Send some error return "ERROR" talks = database.get_talks(speakers) return rsser.create_rss_feed(talks=talks, speakers=list(speakers)) if __name__ == "__main__": app.run(debug=True)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from flask import Flask, request, json from flask.ext.cors import CORS import database import rsser # Update data before application is allowed to start database.update_database() app = Flask(__name__) CORS(app) @app.route('/speakercast/speakers') def speakers(): speakers = [{'name': name, 'talks': count} for count, name in database.get_all_speaker_and_counts()] return json.dumps(speakers) @app.route('/speakercast/speakercast/generate', methods=['POST', 'OPTIONS']) def generate(): data = json.loads(request.data) speakers = data['speakers'] id_ = database.generate_id(speakers) return id_ @app.route('/speakercast/feed/<id>') def feed(id): speakers = database.get_speakers(id) if speakers is None: # TODO: Send some error return "ERROR" talks = database.get_talks(speakers) return rsser.create_rss_feed(talks=talks, speakers=list(speakers)) if __name__ == "__main__": app.run(debug=True) Fix error with generate URL#!/usr/bin/env python3 # -*- coding: utf-8 -*- from flask import Flask, request, json from flask.ext.cors import CORS import database import rsser # Update data before application is allowed to start database.update_database() app = Flask(__name__) CORS(app) @app.route('/speakercast/speakers') def speakers(): speakers = [{'name': name, 'talks': count} for count, name in database.get_all_speaker_and_counts()] return json.dumps(speakers) @app.route('/speakercast/generate', methods=['POST', 'OPTIONS']) def generate(): data = json.loads(request.data) speakers = data['speakers'] id_ = database.generate_id(speakers) return id_ @app.route('/speakercast/feed/<id>') def feed(id): speakers = database.get_speakers(id) if speakers is None: # TODO: Send some error return "ERROR" talks = database.get_talks(speakers) return rsser.create_rss_feed(talks=talks, speakers=list(speakers)) if __name__ == "__main__": app.run(debug=True)
<commit_before>#!/usr/bin/env python3 # -*- coding: utf-8 -*- from flask import Flask, request, json from flask.ext.cors import CORS import database import rsser # Update data before application is allowed to start database.update_database() app = Flask(__name__) CORS(app) @app.route('/speakercast/speakers') def speakers(): speakers = [{'name': name, 'talks': count} for count, name in database.get_all_speaker_and_counts()] return json.dumps(speakers) @app.route('/speakercast/speakercast/generate', methods=['POST', 'OPTIONS']) def generate(): data = json.loads(request.data) speakers = data['speakers'] id_ = database.generate_id(speakers) return id_ @app.route('/speakercast/feed/<id>') def feed(id): speakers = database.get_speakers(id) if speakers is None: # TODO: Send some error return "ERROR" talks = database.get_talks(speakers) return rsser.create_rss_feed(talks=talks, speakers=list(speakers)) if __name__ == "__main__": app.run(debug=True) <commit_msg>Fix error with generate URL<commit_after>#!/usr/bin/env python3 # -*- coding: utf-8 -*- from flask import Flask, request, json from flask.ext.cors import CORS import database import rsser # Update data before application is allowed to start database.update_database() app = Flask(__name__) CORS(app) @app.route('/speakercast/speakers') def speakers(): speakers = [{'name': name, 'talks': count} for count, name in database.get_all_speaker_and_counts()] return json.dumps(speakers) @app.route('/speakercast/generate', methods=['POST', 'OPTIONS']) def generate(): data = json.loads(request.data) speakers = data['speakers'] id_ = database.generate_id(speakers) return id_ @app.route('/speakercast/feed/<id>') def feed(id): speakers = database.get_speakers(id) if speakers is None: # TODO: Send some error return "ERROR" talks = database.get_talks(speakers) return rsser.create_rss_feed(talks=talks, speakers=list(speakers)) if __name__ == "__main__": app.run(debug=True)
1c2fda3afffd998035bbb9912779ce7d4f918b64
app.py
app.py
#! /usr/bin/python2.7 # -*- coding: utf-8 -*- import re from flask import Flask, render_template from settings import BABEL_SETTINGS, SERVER_SETTINGS from utils.i18n import PopongBabel from utils.glossary import load as load_glossary app = Flask(__name__) app.debug = SERVER_SETTINGS['debug'] terms = load_glossary('static/data/crawlers/glossary/glossary.csv') PopongBabel(app, **BABEL_SETTINGS) @app.route('/') def home(): return render_template('glossary.html', terms=terms) def cmd_args(): from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument('-l', dest='locale', choices=app.LOCALES + ['auto'], default='auto') args = parser.parse_args() return args def main(): args = cmd_args() if args.locale and args.locale != 'auto': app.babel.locale_selector_func = lambda: args.locale app.run(**SERVER_SETTINGS) if __name__ == '__main__': main()
#! /usr/bin/python2.7 # -*- coding: utf-8 -*- from flask import Flask, render_template import os import re from settings import BABEL_SETTINGS, SERVER_SETTINGS from utils.i18n import PopongBabel from utils.glossary import load as load_glossary app = Flask(__name__) app.debug = SERVER_SETTINGS['debug'] p = os.path.join(app.root_path, 'static/data/crawlers/glossary/glossary.csv') terms = load_glossary(p) PopongBabel(app, **BABEL_SETTINGS) @app.route('/') def home(): return render_template('glossary.html', terms=terms) def cmd_args(): from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument('-l', dest='locale', choices=app.LOCALES + ['auto'], default='auto') args = parser.parse_args() return args def main(): args = cmd_args() if args.locale and args.locale != 'auto': app.babel.locale_selector_func = lambda: args.locale app.run(**SERVER_SETTINGS) if __name__ == '__main__': main()
Fix glossary file location to relative
Fix glossary file location to relative
Python
apache-2.0
teampopong/popong.com-glossary,teampopong/popong.com-glossary,teampopong/popong.com-glossary
#! /usr/bin/python2.7 # -*- coding: utf-8 -*- import re from flask import Flask, render_template from settings import BABEL_SETTINGS, SERVER_SETTINGS from utils.i18n import PopongBabel from utils.glossary import load as load_glossary app = Flask(__name__) app.debug = SERVER_SETTINGS['debug'] terms = load_glossary('static/data/crawlers/glossary/glossary.csv') PopongBabel(app, **BABEL_SETTINGS) @app.route('/') def home(): return render_template('glossary.html', terms=terms) def cmd_args(): from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument('-l', dest='locale', choices=app.LOCALES + ['auto'], default='auto') args = parser.parse_args() return args def main(): args = cmd_args() if args.locale and args.locale != 'auto': app.babel.locale_selector_func = lambda: args.locale app.run(**SERVER_SETTINGS) if __name__ == '__main__': main() Fix glossary file location to relative
#! /usr/bin/python2.7 # -*- coding: utf-8 -*- from flask import Flask, render_template import os import re from settings import BABEL_SETTINGS, SERVER_SETTINGS from utils.i18n import PopongBabel from utils.glossary import load as load_glossary app = Flask(__name__) app.debug = SERVER_SETTINGS['debug'] p = os.path.join(app.root_path, 'static/data/crawlers/glossary/glossary.csv') terms = load_glossary(p) PopongBabel(app, **BABEL_SETTINGS) @app.route('/') def home(): return render_template('glossary.html', terms=terms) def cmd_args(): from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument('-l', dest='locale', choices=app.LOCALES + ['auto'], default='auto') args = parser.parse_args() return args def main(): args = cmd_args() if args.locale and args.locale != 'auto': app.babel.locale_selector_func = lambda: args.locale app.run(**SERVER_SETTINGS) if __name__ == '__main__': main()
<commit_before>#! /usr/bin/python2.7 # -*- coding: utf-8 -*- import re from flask import Flask, render_template from settings import BABEL_SETTINGS, SERVER_SETTINGS from utils.i18n import PopongBabel from utils.glossary import load as load_glossary app = Flask(__name__) app.debug = SERVER_SETTINGS['debug'] terms = load_glossary('static/data/crawlers/glossary/glossary.csv') PopongBabel(app, **BABEL_SETTINGS) @app.route('/') def home(): return render_template('glossary.html', terms=terms) def cmd_args(): from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument('-l', dest='locale', choices=app.LOCALES + ['auto'], default='auto') args = parser.parse_args() return args def main(): args = cmd_args() if args.locale and args.locale != 'auto': app.babel.locale_selector_func = lambda: args.locale app.run(**SERVER_SETTINGS) if __name__ == '__main__': main() <commit_msg>Fix glossary file location to relative<commit_after>
#! /usr/bin/python2.7 # -*- coding: utf-8 -*- from flask import Flask, render_template import os import re from settings import BABEL_SETTINGS, SERVER_SETTINGS from utils.i18n import PopongBabel from utils.glossary import load as load_glossary app = Flask(__name__) app.debug = SERVER_SETTINGS['debug'] p = os.path.join(app.root_path, 'static/data/crawlers/glossary/glossary.csv') terms = load_glossary(p) PopongBabel(app, **BABEL_SETTINGS) @app.route('/') def home(): return render_template('glossary.html', terms=terms) def cmd_args(): from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument('-l', dest='locale', choices=app.LOCALES + ['auto'], default='auto') args = parser.parse_args() return args def main(): args = cmd_args() if args.locale and args.locale != 'auto': app.babel.locale_selector_func = lambda: args.locale app.run(**SERVER_SETTINGS) if __name__ == '__main__': main()
#! /usr/bin/python2.7 # -*- coding: utf-8 -*- import re from flask import Flask, render_template from settings import BABEL_SETTINGS, SERVER_SETTINGS from utils.i18n import PopongBabel from utils.glossary import load as load_glossary app = Flask(__name__) app.debug = SERVER_SETTINGS['debug'] terms = load_glossary('static/data/crawlers/glossary/glossary.csv') PopongBabel(app, **BABEL_SETTINGS) @app.route('/') def home(): return render_template('glossary.html', terms=terms) def cmd_args(): from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument('-l', dest='locale', choices=app.LOCALES + ['auto'], default='auto') args = parser.parse_args() return args def main(): args = cmd_args() if args.locale and args.locale != 'auto': app.babel.locale_selector_func = lambda: args.locale app.run(**SERVER_SETTINGS) if __name__ == '__main__': main() Fix glossary file location to relative#! /usr/bin/python2.7 # -*- coding: utf-8 -*- from flask import Flask, render_template import os import re from settings import BABEL_SETTINGS, SERVER_SETTINGS from utils.i18n import PopongBabel from utils.glossary import load as load_glossary app = Flask(__name__) app.debug = SERVER_SETTINGS['debug'] p = os.path.join(app.root_path, 'static/data/crawlers/glossary/glossary.csv') terms = load_glossary(p) PopongBabel(app, **BABEL_SETTINGS) @app.route('/') def home(): return render_template('glossary.html', terms=terms) def cmd_args(): from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument('-l', dest='locale', choices=app.LOCALES + ['auto'], default='auto') args = parser.parse_args() return args def main(): args = cmd_args() if args.locale and args.locale != 'auto': app.babel.locale_selector_func = lambda: args.locale app.run(**SERVER_SETTINGS) if __name__ == '__main__': main()
<commit_before>#! /usr/bin/python2.7 # -*- coding: utf-8 -*- import re from flask import Flask, render_template from settings import BABEL_SETTINGS, SERVER_SETTINGS from utils.i18n import PopongBabel from utils.glossary import load as load_glossary app = Flask(__name__) app.debug = SERVER_SETTINGS['debug'] terms = load_glossary('static/data/crawlers/glossary/glossary.csv') PopongBabel(app, **BABEL_SETTINGS) @app.route('/') def home(): return render_template('glossary.html', terms=terms) def cmd_args(): from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument('-l', dest='locale', choices=app.LOCALES + ['auto'], default='auto') args = parser.parse_args() return args def main(): args = cmd_args() if args.locale and args.locale != 'auto': app.babel.locale_selector_func = lambda: args.locale app.run(**SERVER_SETTINGS) if __name__ == '__main__': main() <commit_msg>Fix glossary file location to relative<commit_after>#! /usr/bin/python2.7 # -*- coding: utf-8 -*- from flask import Flask, render_template import os import re from settings import BABEL_SETTINGS, SERVER_SETTINGS from utils.i18n import PopongBabel from utils.glossary import load as load_glossary app = Flask(__name__) app.debug = SERVER_SETTINGS['debug'] p = os.path.join(app.root_path, 'static/data/crawlers/glossary/glossary.csv') terms = load_glossary(p) PopongBabel(app, **BABEL_SETTINGS) @app.route('/') def home(): return render_template('glossary.html', terms=terms) def cmd_args(): from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument('-l', dest='locale', choices=app.LOCALES + ['auto'], default='auto') args = parser.parse_args() return args def main(): args = cmd_args() if args.locale and args.locale != 'auto': app.babel.locale_selector_func = lambda: args.locale app.run(**SERVER_SETTINGS) if __name__ == '__main__': main()
f9a1ac08fdffc464010c7c493c43a475342c821b
bot.py
bot.py
import zirc, ssl, socket class Bot(zirc.Client): def __init__(self): self.connection = zirc.Socket(family=socket.AF_INET6, wrapper=ssl.wrap_socket) self.config = zirc.IRCConfig(host="irc.freenode.net", port=6697, nickname="wolfyzIRCBot", ident="zirc", realname="A zIRC bot", channels=["##wolfy1339"], sasl_user="BigWolfy1339", sasl_pass="" ) self.connect(self.config) self.start() def on_privmsg(bot, event, irc): irc.reply(event, "It works!") #Or alternatively: #irc.privmsg(event.target, "It works!") def on_all(irc, raw): print(raw) Bot()
import zirc import ssl import socket class Bot(zirc.Client): def __init__(self): self.connection = zirc.Socket(family=socket.AF_INET6, wrapper=ssl.wrap_socket) self.config = zirc.IRCConfig(host="irc.freenode.net", port=6697, nickname="wolfyzIRCBot", ident="zirc", realname="A zIRC bot", channels=["##wolfy1339"], sasl_user="BigWolfy1339", sasl_pass="" ) self.connect(self.config) self.start() def on_privmsg(bot, event, irc): irc.reply(event, "It works!") #Or alternatively: #irc.privmsg(event.target, "It works!") def on_all(irc, raw): print(raw) Bot()
Move imports to their own line
Move imports to their own line
Python
mit
wolfy1339/Python-IRC-Bot
import zirc, ssl, socket class Bot(zirc.Client): def __init__(self): self.connection = zirc.Socket(family=socket.AF_INET6, wrapper=ssl.wrap_socket) self.config = zirc.IRCConfig(host="irc.freenode.net", port=6697, nickname="wolfyzIRCBot", ident="zirc", realname="A zIRC bot", channels=["##wolfy1339"], sasl_user="BigWolfy1339", sasl_pass="" ) self.connect(self.config) self.start() def on_privmsg(bot, event, irc): irc.reply(event, "It works!") #Or alternatively: #irc.privmsg(event.target, "It works!") def on_all(irc, raw): print(raw) Bot() Move imports to their own line
import zirc import ssl import socket class Bot(zirc.Client): def __init__(self): self.connection = zirc.Socket(family=socket.AF_INET6, wrapper=ssl.wrap_socket) self.config = zirc.IRCConfig(host="irc.freenode.net", port=6697, nickname="wolfyzIRCBot", ident="zirc", realname="A zIRC bot", channels=["##wolfy1339"], sasl_user="BigWolfy1339", sasl_pass="" ) self.connect(self.config) self.start() def on_privmsg(bot, event, irc): irc.reply(event, "It works!") #Or alternatively: #irc.privmsg(event.target, "It works!") def on_all(irc, raw): print(raw) Bot()
<commit_before>import zirc, ssl, socket class Bot(zirc.Client): def __init__(self): self.connection = zirc.Socket(family=socket.AF_INET6, wrapper=ssl.wrap_socket) self.config = zirc.IRCConfig(host="irc.freenode.net", port=6697, nickname="wolfyzIRCBot", ident="zirc", realname="A zIRC bot", channels=["##wolfy1339"], sasl_user="BigWolfy1339", sasl_pass="" ) self.connect(self.config) self.start() def on_privmsg(bot, event, irc): irc.reply(event, "It works!") #Or alternatively: #irc.privmsg(event.target, "It works!") def on_all(irc, raw): print(raw) Bot() <commit_msg>Move imports to their own line<commit_after>
import zirc import ssl import socket class Bot(zirc.Client): def __init__(self): self.connection = zirc.Socket(family=socket.AF_INET6, wrapper=ssl.wrap_socket) self.config = zirc.IRCConfig(host="irc.freenode.net", port=6697, nickname="wolfyzIRCBot", ident="zirc", realname="A zIRC bot", channels=["##wolfy1339"], sasl_user="BigWolfy1339", sasl_pass="" ) self.connect(self.config) self.start() def on_privmsg(bot, event, irc): irc.reply(event, "It works!") #Or alternatively: #irc.privmsg(event.target, "It works!") def on_all(irc, raw): print(raw) Bot()
import zirc, ssl, socket class Bot(zirc.Client): def __init__(self): self.connection = zirc.Socket(family=socket.AF_INET6, wrapper=ssl.wrap_socket) self.config = zirc.IRCConfig(host="irc.freenode.net", port=6697, nickname="wolfyzIRCBot", ident="zirc", realname="A zIRC bot", channels=["##wolfy1339"], sasl_user="BigWolfy1339", sasl_pass="" ) self.connect(self.config) self.start() def on_privmsg(bot, event, irc): irc.reply(event, "It works!") #Or alternatively: #irc.privmsg(event.target, "It works!") def on_all(irc, raw): print(raw) Bot() Move imports to their own lineimport zirc import ssl import socket class Bot(zirc.Client): def __init__(self): self.connection = zirc.Socket(family=socket.AF_INET6, wrapper=ssl.wrap_socket) self.config = zirc.IRCConfig(host="irc.freenode.net", port=6697, nickname="wolfyzIRCBot", ident="zirc", realname="A zIRC bot", channels=["##wolfy1339"], sasl_user="BigWolfy1339", sasl_pass="" ) self.connect(self.config) self.start() def on_privmsg(bot, event, irc): irc.reply(event, "It works!") #Or alternatively: #irc.privmsg(event.target, "It works!") def on_all(irc, raw): print(raw) Bot()
<commit_before>import zirc, ssl, socket class Bot(zirc.Client): def __init__(self): self.connection = zirc.Socket(family=socket.AF_INET6, wrapper=ssl.wrap_socket) self.config = zirc.IRCConfig(host="irc.freenode.net", port=6697, nickname="wolfyzIRCBot", ident="zirc", realname="A zIRC bot", channels=["##wolfy1339"], sasl_user="BigWolfy1339", sasl_pass="" ) self.connect(self.config) self.start() def on_privmsg(bot, event, irc): irc.reply(event, "It works!") #Or alternatively: #irc.privmsg(event.target, "It works!") def on_all(irc, raw): print(raw) Bot() <commit_msg>Move imports to their own line<commit_after>import zirc import ssl import socket class Bot(zirc.Client): def __init__(self): self.connection = zirc.Socket(family=socket.AF_INET6, wrapper=ssl.wrap_socket) self.config = zirc.IRCConfig(host="irc.freenode.net", port=6697, nickname="wolfyzIRCBot", ident="zirc", realname="A zIRC bot", channels=["##wolfy1339"], sasl_user="BigWolfy1339", sasl_pass="" ) self.connect(self.config) self.start() def on_privmsg(bot, event, irc): irc.reply(event, "It works!") #Or alternatively: #irc.privmsg(event.target, "It works!") def on_all(irc, raw): print(raw) Bot()
292f78cfe2700ebcfdc83bfbd53717aec3d98d47
bowser/main.py
bowser/main.py
from bowser.Bot import Bot def main(): bot = Bot() try: token = open('token.txt').read().replace('\n', '') bot.run(token) except Exception as ex: bot.loop.run_until_complete(bot.close()) raise ex def init(): if __name__ == '__main__': main() init()
from bowser.Bot import Bot def main(): bot = Bot() try: token = open('token.txt').read().replace('\n', '') bot.run(token) except Exception as ex: raise ex finally: bot.loop.run_until_complete(bot.close()) def init(): if __name__ == '__main__': main() init()
Remove one of the unclosed client session warnings
test: Remove one of the unclosed client session warnings
Python
mit
kevinkjt2000/discord-minecraft-server-status
from bowser.Bot import Bot def main(): bot = Bot() try: token = open('token.txt').read().replace('\n', '') bot.run(token) except Exception as ex: bot.loop.run_until_complete(bot.close()) raise ex def init(): if __name__ == '__main__': main() init() test: Remove one of the unclosed client session warnings
from bowser.Bot import Bot def main(): bot = Bot() try: token = open('token.txt').read().replace('\n', '') bot.run(token) except Exception as ex: raise ex finally: bot.loop.run_until_complete(bot.close()) def init(): if __name__ == '__main__': main() init()
<commit_before>from bowser.Bot import Bot def main(): bot = Bot() try: token = open('token.txt').read().replace('\n', '') bot.run(token) except Exception as ex: bot.loop.run_until_complete(bot.close()) raise ex def init(): if __name__ == '__main__': main() init() <commit_msg>test: Remove one of the unclosed client session warnings<commit_after>
from bowser.Bot import Bot def main(): bot = Bot() try: token = open('token.txt').read().replace('\n', '') bot.run(token) except Exception as ex: raise ex finally: bot.loop.run_until_complete(bot.close()) def init(): if __name__ == '__main__': main() init()
from bowser.Bot import Bot def main(): bot = Bot() try: token = open('token.txt').read().replace('\n', '') bot.run(token) except Exception as ex: bot.loop.run_until_complete(bot.close()) raise ex def init(): if __name__ == '__main__': main() init() test: Remove one of the unclosed client session warningsfrom bowser.Bot import Bot def main(): bot = Bot() try: token = open('token.txt').read().replace('\n', '') bot.run(token) except Exception as ex: raise ex finally: bot.loop.run_until_complete(bot.close()) def init(): if __name__ == '__main__': main() init()
<commit_before>from bowser.Bot import Bot def main(): bot = Bot() try: token = open('token.txt').read().replace('\n', '') bot.run(token) except Exception as ex: bot.loop.run_until_complete(bot.close()) raise ex def init(): if __name__ == '__main__': main() init() <commit_msg>test: Remove one of the unclosed client session warnings<commit_after>from bowser.Bot import Bot def main(): bot = Bot() try: token = open('token.txt').read().replace('\n', '') bot.run(token) except Exception as ex: raise ex finally: bot.loop.run_until_complete(bot.close()) def init(): if __name__ == '__main__': main() init()
03d10411b11133a8f371fb94b4dc4476373190a8
IPython/core/magics/display.py
IPython/core/magics/display.py
"""Simple magics for display formats""" #----------------------------------------------------------------------------- # Copyright (c) 2012 The IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # Our own packages from IPython.core.display import display, Javascript, Latex, SVG, HTML from IPython.core.magic import ( Magics, magics_class, cell_magic ) #----------------------------------------------------------------------------- # Magic implementation classes #----------------------------------------------------------------------------- @magics_class class DisplayMagics(Magics): """Magics for displaying various output types with literals Defines javascript/latex/svg/html cell magics for writing blocks in those languages, to be rendered in the frontend. """ @cell_magic def javascript(self, line, cell): """Run the cell block of Javascript code""" display(Javascript(cell)) @cell_magic def latex(self, line, cell): """Render the cell as a block of latex This magic only renders the subset of latex defined by MathJax [here](https://docs.mathjax.org/en/v2.5-latest/tex.html).""" display(Latex(cell)) @cell_magic def svg(self, line, cell): """Render the cell as an SVG literal""" display(SVG(cell)) @cell_magic def html(self, line, cell): """Render the cell as a block of HTML""" display(HTML(cell))
"""Simple magics for display formats""" #----------------------------------------------------------------------------- # Copyright (c) 2012 The IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # Our own packages from IPython.core.display import display, Javascript, Latex, SVG, HTML from IPython.core.magic import ( Magics, magics_class, cell_magic ) #----------------------------------------------------------------------------- # Magic implementation classes #----------------------------------------------------------------------------- @magics_class class DisplayMagics(Magics): """Magics for displaying various output types with literals Defines javascript/latex/svg/html cell magics for writing blocks in those languages, to be rendered in the frontend. """ @cell_magic def javascript(self, line, cell): """Run the cell block of Javascript code""" display(Javascript(cell)) @cell_magic def latex(self, line, cell): """Render the cell as a block of latex The subset of latex which is support depends on the implementation in the client. In the Jupyter Notebook, this magic only renders the subset of latex defined by MathJax [here](https://docs.mathjax.org/en/v2.5-latest/tex.html).""" display(Latex(cell)) @cell_magic def svg(self, line, cell): """Render the cell as an SVG literal""" display(SVG(cell)) @cell_magic def html(self, line, cell): """Render the cell as a block of HTML""" display(HTML(cell))
Clarify that the MathJax comment is Notebook specific.
Clarify that the MathJax comment is Notebook specific.
Python
bsd-3-clause
ipython/ipython,ipython/ipython
"""Simple magics for display formats""" #----------------------------------------------------------------------------- # Copyright (c) 2012 The IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # Our own packages from IPython.core.display import display, Javascript, Latex, SVG, HTML from IPython.core.magic import ( Magics, magics_class, cell_magic ) #----------------------------------------------------------------------------- # Magic implementation classes #----------------------------------------------------------------------------- @magics_class class DisplayMagics(Magics): """Magics for displaying various output types with literals Defines javascript/latex/svg/html cell magics for writing blocks in those languages, to be rendered in the frontend. """ @cell_magic def javascript(self, line, cell): """Run the cell block of Javascript code""" display(Javascript(cell)) @cell_magic def latex(self, line, cell): """Render the cell as a block of latex This magic only renders the subset of latex defined by MathJax [here](https://docs.mathjax.org/en/v2.5-latest/tex.html).""" display(Latex(cell)) @cell_magic def svg(self, line, cell): """Render the cell as an SVG literal""" display(SVG(cell)) @cell_magic def html(self, line, cell): """Render the cell as a block of HTML""" display(HTML(cell)) Clarify that the MathJax comment is Notebook specific.
"""Simple magics for display formats""" #----------------------------------------------------------------------------- # Copyright (c) 2012 The IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # Our own packages from IPython.core.display import display, Javascript, Latex, SVG, HTML from IPython.core.magic import ( Magics, magics_class, cell_magic ) #----------------------------------------------------------------------------- # Magic implementation classes #----------------------------------------------------------------------------- @magics_class class DisplayMagics(Magics): """Magics for displaying various output types with literals Defines javascript/latex/svg/html cell magics for writing blocks in those languages, to be rendered in the frontend. """ @cell_magic def javascript(self, line, cell): """Run the cell block of Javascript code""" display(Javascript(cell)) @cell_magic def latex(self, line, cell): """Render the cell as a block of latex The subset of latex which is support depends on the implementation in the client. In the Jupyter Notebook, this magic only renders the subset of latex defined by MathJax [here](https://docs.mathjax.org/en/v2.5-latest/tex.html).""" display(Latex(cell)) @cell_magic def svg(self, line, cell): """Render the cell as an SVG literal""" display(SVG(cell)) @cell_magic def html(self, line, cell): """Render the cell as a block of HTML""" display(HTML(cell))
<commit_before>"""Simple magics for display formats""" #----------------------------------------------------------------------------- # Copyright (c) 2012 The IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # Our own packages from IPython.core.display import display, Javascript, Latex, SVG, HTML from IPython.core.magic import ( Magics, magics_class, cell_magic ) #----------------------------------------------------------------------------- # Magic implementation classes #----------------------------------------------------------------------------- @magics_class class DisplayMagics(Magics): """Magics for displaying various output types with literals Defines javascript/latex/svg/html cell magics for writing blocks in those languages, to be rendered in the frontend. """ @cell_magic def javascript(self, line, cell): """Run the cell block of Javascript code""" display(Javascript(cell)) @cell_magic def latex(self, line, cell): """Render the cell as a block of latex This magic only renders the subset of latex defined by MathJax [here](https://docs.mathjax.org/en/v2.5-latest/tex.html).""" display(Latex(cell)) @cell_magic def svg(self, line, cell): """Render the cell as an SVG literal""" display(SVG(cell)) @cell_magic def html(self, line, cell): """Render the cell as a block of HTML""" display(HTML(cell)) <commit_msg>Clarify that the MathJax comment is Notebook specific.<commit_after>
"""Simple magics for display formats""" #----------------------------------------------------------------------------- # Copyright (c) 2012 The IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # Our own packages from IPython.core.display import display, Javascript, Latex, SVG, HTML from IPython.core.magic import ( Magics, magics_class, cell_magic ) #----------------------------------------------------------------------------- # Magic implementation classes #----------------------------------------------------------------------------- @magics_class class DisplayMagics(Magics): """Magics for displaying various output types with literals Defines javascript/latex/svg/html cell magics for writing blocks in those languages, to be rendered in the frontend. """ @cell_magic def javascript(self, line, cell): """Run the cell block of Javascript code""" display(Javascript(cell)) @cell_magic def latex(self, line, cell): """Render the cell as a block of latex The subset of latex which is support depends on the implementation in the client. In the Jupyter Notebook, this magic only renders the subset of latex defined by MathJax [here](https://docs.mathjax.org/en/v2.5-latest/tex.html).""" display(Latex(cell)) @cell_magic def svg(self, line, cell): """Render the cell as an SVG literal""" display(SVG(cell)) @cell_magic def html(self, line, cell): """Render the cell as a block of HTML""" display(HTML(cell))
"""Simple magics for display formats""" #----------------------------------------------------------------------------- # Copyright (c) 2012 The IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # Our own packages from IPython.core.display import display, Javascript, Latex, SVG, HTML from IPython.core.magic import ( Magics, magics_class, cell_magic ) #----------------------------------------------------------------------------- # Magic implementation classes #----------------------------------------------------------------------------- @magics_class class DisplayMagics(Magics): """Magics for displaying various output types with literals Defines javascript/latex/svg/html cell magics for writing blocks in those languages, to be rendered in the frontend. """ @cell_magic def javascript(self, line, cell): """Run the cell block of Javascript code""" display(Javascript(cell)) @cell_magic def latex(self, line, cell): """Render the cell as a block of latex This magic only renders the subset of latex defined by MathJax [here](https://docs.mathjax.org/en/v2.5-latest/tex.html).""" display(Latex(cell)) @cell_magic def svg(self, line, cell): """Render the cell as an SVG literal""" display(SVG(cell)) @cell_magic def html(self, line, cell): """Render the cell as a block of HTML""" display(HTML(cell)) Clarify that the MathJax comment is Notebook specific."""Simple magics for display formats""" #----------------------------------------------------------------------------- # Copyright (c) 2012 The IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # Our own packages from IPython.core.display import display, Javascript, Latex, SVG, HTML from IPython.core.magic import ( Magics, magics_class, cell_magic ) #----------------------------------------------------------------------------- # Magic implementation classes #----------------------------------------------------------------------------- @magics_class class DisplayMagics(Magics): """Magics for displaying various output types with literals Defines javascript/latex/svg/html cell magics for writing blocks in those languages, to be rendered in the frontend. """ @cell_magic def javascript(self, line, cell): """Run the cell block of Javascript code""" display(Javascript(cell)) @cell_magic def latex(self, line, cell): """Render the cell as a block of latex The subset of latex which is support depends on the implementation in the client. In the Jupyter Notebook, this magic only renders the subset of latex defined by MathJax [here](https://docs.mathjax.org/en/v2.5-latest/tex.html).""" display(Latex(cell)) @cell_magic def svg(self, line, cell): """Render the cell as an SVG literal""" display(SVG(cell)) @cell_magic def html(self, line, cell): """Render the cell as a block of HTML""" display(HTML(cell))
<commit_before>"""Simple magics for display formats""" #----------------------------------------------------------------------------- # Copyright (c) 2012 The IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # Our own packages from IPython.core.display import display, Javascript, Latex, SVG, HTML from IPython.core.magic import ( Magics, magics_class, cell_magic ) #----------------------------------------------------------------------------- # Magic implementation classes #----------------------------------------------------------------------------- @magics_class class DisplayMagics(Magics): """Magics for displaying various output types with literals Defines javascript/latex/svg/html cell magics for writing blocks in those languages, to be rendered in the frontend. """ @cell_magic def javascript(self, line, cell): """Run the cell block of Javascript code""" display(Javascript(cell)) @cell_magic def latex(self, line, cell): """Render the cell as a block of latex This magic only renders the subset of latex defined by MathJax [here](https://docs.mathjax.org/en/v2.5-latest/tex.html).""" display(Latex(cell)) @cell_magic def svg(self, line, cell): """Render the cell as an SVG literal""" display(SVG(cell)) @cell_magic def html(self, line, cell): """Render the cell as a block of HTML""" display(HTML(cell)) <commit_msg>Clarify that the MathJax comment is Notebook specific.<commit_after>"""Simple magics for display formats""" #----------------------------------------------------------------------------- # Copyright (c) 2012 The IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # Our own packages from IPython.core.display import display, Javascript, Latex, SVG, HTML from IPython.core.magic import ( Magics, magics_class, cell_magic ) #----------------------------------------------------------------------------- # Magic implementation classes #----------------------------------------------------------------------------- @magics_class class DisplayMagics(Magics): """Magics for displaying various output types with literals Defines javascript/latex/svg/html cell magics for writing blocks in those languages, to be rendered in the frontend. """ @cell_magic def javascript(self, line, cell): """Run the cell block of Javascript code""" display(Javascript(cell)) @cell_magic def latex(self, line, cell): """Render the cell as a block of latex The subset of latex which is support depends on the implementation in the client. In the Jupyter Notebook, this magic only renders the subset of latex defined by MathJax [here](https://docs.mathjax.org/en/v2.5-latest/tex.html).""" display(Latex(cell)) @cell_magic def svg(self, line, cell): """Render the cell as an SVG literal""" display(SVG(cell)) @cell_magic def html(self, line, cell): """Render the cell as a block of HTML""" display(HTML(cell))
978106fb47ef5d9974678bc1ac2c71ce6e95a311
plugins/notes_plugin.py
plugins/notes_plugin.py
# -*- coding: utf-8 -*- # vim: set ts=4 et import sqlite3 from plugin import * class Plugin(BasePlugin): def on_load(self, reloading): self.db = sqlite3.connect('data/notes.db') c = self.db.cursor() c.execute('''CREATE TABLE IF NOT EXISTS notes (channel text, sender text, recipient text, message text)''') self.db.commit() def on_unload(self, reloading): self.db.close() @hook def note_trigger(self, msg, args, argstr): if not msg.channel: return data = {'channel': msg.param[0], 'sender': msg.nick} data['recipient'], data['message'] = argstr.split(None, 1) c = self.db.cursor() c.execute('INSERT INTO notes VALUES (:channel, :sender, :recipient, :message)', data) self.db.commit() @hook def privmsg_command(self, msg): if not msg.channel: return c = self.db.cursor() criteria = {'channel': msg.param[0], 'recipient': msg.nick} c.execute('SELECT sender, message FROM notes WHERE channel=:channel AND recipient=:recipient', criteria) rows = c.fetchall() if rows: for row in rows: msg.reply("Note: <%s> %s" % row) c.execute('DELETE FROM notes WHERE channel=:channel AND recipient=:recipient', criteria) self.db.commit()
# -*- coding: utf-8 -*- # vim: set ts=4 et import sqlite3 from plugin import * class Plugin(BasePlugin): def on_load(self, reloading): self.db = sqlite3.connect('data/notes.db') c = self.db.cursor() c.execute('''CREATE TABLE IF NOT EXISTS notes (channel text, sender text, recipient text, message text)''') self.db.commit() def on_unload(self, reloading): self.db.close() @hook def tell_trigger(self, msg, args, argstr): if not msg.channel: return data = {'channel': msg.param[0], 'sender': msg.nick} data['recipient'], data['message'] = argstr.split(None, 1) c = self.db.cursor() c.execute('INSERT INTO notes VALUES (:channel, :sender, :recipient, :message)', data) self.db.commit() msg.reply("Aye aye!") @hook def privmsg_command(self, msg): if not msg.channel: return c = self.db.cursor() criteria = {'channel': msg.param[0], 'recipient': msg.nick} c.execute('SELECT sender, message FROM notes WHERE channel=:channel AND recipient=:recipient', criteria) rows = c.fetchall() if rows: for row in rows: msg.reply("Note: <%s> %s" % row) c.execute('DELETE FROM notes WHERE channel=:channel AND recipient=:recipient', criteria) self.db.commit()
Change note trigger to tell, and make it reply
Change note trigger to tell, and make it reply
Python
mit
jrspruitt/jkent-pybot,jkent/jkent-pybot
# -*- coding: utf-8 -*- # vim: set ts=4 et import sqlite3 from plugin import * class Plugin(BasePlugin): def on_load(self, reloading): self.db = sqlite3.connect('data/notes.db') c = self.db.cursor() c.execute('''CREATE TABLE IF NOT EXISTS notes (channel text, sender text, recipient text, message text)''') self.db.commit() def on_unload(self, reloading): self.db.close() @hook def note_trigger(self, msg, args, argstr): if not msg.channel: return data = {'channel': msg.param[0], 'sender': msg.nick} data['recipient'], data['message'] = argstr.split(None, 1) c = self.db.cursor() c.execute('INSERT INTO notes VALUES (:channel, :sender, :recipient, :message)', data) self.db.commit() @hook def privmsg_command(self, msg): if not msg.channel: return c = self.db.cursor() criteria = {'channel': msg.param[0], 'recipient': msg.nick} c.execute('SELECT sender, message FROM notes WHERE channel=:channel AND recipient=:recipient', criteria) rows = c.fetchall() if rows: for row in rows: msg.reply("Note: <%s> %s" % row) c.execute('DELETE FROM notes WHERE channel=:channel AND recipient=:recipient', criteria) self.db.commit() Change note trigger to tell, and make it reply
# -*- coding: utf-8 -*- # vim: set ts=4 et import sqlite3 from plugin import * class Plugin(BasePlugin): def on_load(self, reloading): self.db = sqlite3.connect('data/notes.db') c = self.db.cursor() c.execute('''CREATE TABLE IF NOT EXISTS notes (channel text, sender text, recipient text, message text)''') self.db.commit() def on_unload(self, reloading): self.db.close() @hook def tell_trigger(self, msg, args, argstr): if not msg.channel: return data = {'channel': msg.param[0], 'sender': msg.nick} data['recipient'], data['message'] = argstr.split(None, 1) c = self.db.cursor() c.execute('INSERT INTO notes VALUES (:channel, :sender, :recipient, :message)', data) self.db.commit() msg.reply("Aye aye!") @hook def privmsg_command(self, msg): if not msg.channel: return c = self.db.cursor() criteria = {'channel': msg.param[0], 'recipient': msg.nick} c.execute('SELECT sender, message FROM notes WHERE channel=:channel AND recipient=:recipient', criteria) rows = c.fetchall() if rows: for row in rows: msg.reply("Note: <%s> %s" % row) c.execute('DELETE FROM notes WHERE channel=:channel AND recipient=:recipient', criteria) self.db.commit()
<commit_before># -*- coding: utf-8 -*- # vim: set ts=4 et import sqlite3 from plugin import * class Plugin(BasePlugin): def on_load(self, reloading): self.db = sqlite3.connect('data/notes.db') c = self.db.cursor() c.execute('''CREATE TABLE IF NOT EXISTS notes (channel text, sender text, recipient text, message text)''') self.db.commit() def on_unload(self, reloading): self.db.close() @hook def note_trigger(self, msg, args, argstr): if not msg.channel: return data = {'channel': msg.param[0], 'sender': msg.nick} data['recipient'], data['message'] = argstr.split(None, 1) c = self.db.cursor() c.execute('INSERT INTO notes VALUES (:channel, :sender, :recipient, :message)', data) self.db.commit() @hook def privmsg_command(self, msg): if not msg.channel: return c = self.db.cursor() criteria = {'channel': msg.param[0], 'recipient': msg.nick} c.execute('SELECT sender, message FROM notes WHERE channel=:channel AND recipient=:recipient', criteria) rows = c.fetchall() if rows: for row in rows: msg.reply("Note: <%s> %s" % row) c.execute('DELETE FROM notes WHERE channel=:channel AND recipient=:recipient', criteria) self.db.commit() <commit_msg>Change note trigger to tell, and make it reply<commit_after>
# -*- coding: utf-8 -*- # vim: set ts=4 et import sqlite3 from plugin import * class Plugin(BasePlugin): def on_load(self, reloading): self.db = sqlite3.connect('data/notes.db') c = self.db.cursor() c.execute('''CREATE TABLE IF NOT EXISTS notes (channel text, sender text, recipient text, message text)''') self.db.commit() def on_unload(self, reloading): self.db.close() @hook def tell_trigger(self, msg, args, argstr): if not msg.channel: return data = {'channel': msg.param[0], 'sender': msg.nick} data['recipient'], data['message'] = argstr.split(None, 1) c = self.db.cursor() c.execute('INSERT INTO notes VALUES (:channel, :sender, :recipient, :message)', data) self.db.commit() msg.reply("Aye aye!") @hook def privmsg_command(self, msg): if not msg.channel: return c = self.db.cursor() criteria = {'channel': msg.param[0], 'recipient': msg.nick} c.execute('SELECT sender, message FROM notes WHERE channel=:channel AND recipient=:recipient', criteria) rows = c.fetchall() if rows: for row in rows: msg.reply("Note: <%s> %s" % row) c.execute('DELETE FROM notes WHERE channel=:channel AND recipient=:recipient', criteria) self.db.commit()
# -*- coding: utf-8 -*- # vim: set ts=4 et import sqlite3 from plugin import * class Plugin(BasePlugin): def on_load(self, reloading): self.db = sqlite3.connect('data/notes.db') c = self.db.cursor() c.execute('''CREATE TABLE IF NOT EXISTS notes (channel text, sender text, recipient text, message text)''') self.db.commit() def on_unload(self, reloading): self.db.close() @hook def note_trigger(self, msg, args, argstr): if not msg.channel: return data = {'channel': msg.param[0], 'sender': msg.nick} data['recipient'], data['message'] = argstr.split(None, 1) c = self.db.cursor() c.execute('INSERT INTO notes VALUES (:channel, :sender, :recipient, :message)', data) self.db.commit() @hook def privmsg_command(self, msg): if not msg.channel: return c = self.db.cursor() criteria = {'channel': msg.param[0], 'recipient': msg.nick} c.execute('SELECT sender, message FROM notes WHERE channel=:channel AND recipient=:recipient', criteria) rows = c.fetchall() if rows: for row in rows: msg.reply("Note: <%s> %s" % row) c.execute('DELETE FROM notes WHERE channel=:channel AND recipient=:recipient', criteria) self.db.commit() Change note trigger to tell, and make it reply# -*- coding: utf-8 -*- # vim: set ts=4 et import sqlite3 from plugin import * class Plugin(BasePlugin): def on_load(self, reloading): self.db = sqlite3.connect('data/notes.db') c = self.db.cursor() c.execute('''CREATE TABLE IF NOT EXISTS notes (channel text, sender text, recipient text, message text)''') self.db.commit() def on_unload(self, reloading): self.db.close() @hook def tell_trigger(self, msg, args, argstr): if not msg.channel: return data = {'channel': msg.param[0], 'sender': msg.nick} data['recipient'], data['message'] = argstr.split(None, 1) c = self.db.cursor() c.execute('INSERT INTO notes VALUES (:channel, :sender, :recipient, :message)', data) self.db.commit() msg.reply("Aye aye!") @hook def privmsg_command(self, msg): if not msg.channel: return c = self.db.cursor() criteria = {'channel': msg.param[0], 'recipient': msg.nick} c.execute('SELECT sender, message FROM notes WHERE channel=:channel AND recipient=:recipient', criteria) rows = c.fetchall() if rows: for row in rows: msg.reply("Note: <%s> %s" % row) c.execute('DELETE FROM notes WHERE channel=:channel AND recipient=:recipient', criteria) self.db.commit()
<commit_before># -*- coding: utf-8 -*- # vim: set ts=4 et import sqlite3 from plugin import * class Plugin(BasePlugin): def on_load(self, reloading): self.db = sqlite3.connect('data/notes.db') c = self.db.cursor() c.execute('''CREATE TABLE IF NOT EXISTS notes (channel text, sender text, recipient text, message text)''') self.db.commit() def on_unload(self, reloading): self.db.close() @hook def note_trigger(self, msg, args, argstr): if not msg.channel: return data = {'channel': msg.param[0], 'sender': msg.nick} data['recipient'], data['message'] = argstr.split(None, 1) c = self.db.cursor() c.execute('INSERT INTO notes VALUES (:channel, :sender, :recipient, :message)', data) self.db.commit() @hook def privmsg_command(self, msg): if not msg.channel: return c = self.db.cursor() criteria = {'channel': msg.param[0], 'recipient': msg.nick} c.execute('SELECT sender, message FROM notes WHERE channel=:channel AND recipient=:recipient', criteria) rows = c.fetchall() if rows: for row in rows: msg.reply("Note: <%s> %s" % row) c.execute('DELETE FROM notes WHERE channel=:channel AND recipient=:recipient', criteria) self.db.commit() <commit_msg>Change note trigger to tell, and make it reply<commit_after># -*- coding: utf-8 -*- # vim: set ts=4 et import sqlite3 from plugin import * class Plugin(BasePlugin): def on_load(self, reloading): self.db = sqlite3.connect('data/notes.db') c = self.db.cursor() c.execute('''CREATE TABLE IF NOT EXISTS notes (channel text, sender text, recipient text, message text)''') self.db.commit() def on_unload(self, reloading): self.db.close() @hook def tell_trigger(self, msg, args, argstr): if not msg.channel: return data = {'channel': msg.param[0], 'sender': msg.nick} data['recipient'], data['message'] = argstr.split(None, 1) c = self.db.cursor() c.execute('INSERT INTO notes VALUES (:channel, :sender, :recipient, :message)', data) self.db.commit() msg.reply("Aye aye!") @hook def privmsg_command(self, msg): if not msg.channel: return c = self.db.cursor() criteria = {'channel': msg.param[0], 'recipient': msg.nick} c.execute('SELECT sender, message FROM notes WHERE channel=:channel AND recipient=:recipient', criteria) rows = c.fetchall() if rows: for row in rows: msg.reply("Note: <%s> %s" % row) c.execute('DELETE FROM notes WHERE channel=:channel AND recipient=:recipient', criteria) self.db.commit()
dab7eaadbc6fc0dd867358b096a846ec39bc0440
pnnl/models/__init__.py
pnnl/models/__init__.py
import importlib import logging from volttron.platform.agent import utils _log = logging.getLogger(__name__) utils.setup_logging() __version__ = "0.1" __all__ = ['Model'] class Model(object): def __init__(self, config, **kwargs): base_module = "volttron.pnnl.models." try: model_type = config["model_type"] except KeyError as e: _log.exception("Missing Model Type key: {}".format(e)) raise e _file, model_type = model_type.split(".") module = importlib.import_module(base_module + _file) model_class = getattr(module, model_type) self.model = model_class(config, self) def get_q(self, _set, sched_index, market_index, occupied): q = self.model.predict(_set, sched_index, market_index, occupied)
import importlib import logging from volttron.platform.agent import utils _log = logging.getLogger(__name__) utils.setup_logging() __version__ = "0.1" __all__ = ['Model'] class Model(object): def __init__(self, config, **kwargs): base_module = "volttron.pnnl.models." try: model_type = config["model_type"] except KeyError as e: _log.exception("Missing Model Type key: {}".format(e)) raise e _file, model_type = model_type.split(".") module = importlib.import_module(base_module + _file) model_class = getattr(module, model_type) self.model = model_class(config, self) def get_q(self, _set, sched_index, market_index, occupied): q = self.model.predict(_set, sched_index, market_index, occupied) return q
Add return statement to Model.get_q
Add return statement to Model.get_q
Python
bsd-3-clause
VOLTTRON/volttron-applications,VOLTTRON/volttron-applications,VOLTTRON/volttron-applications,VOLTTRON/volttron-applications,VOLTTRON/volttron-applications
import importlib import logging from volttron.platform.agent import utils _log = logging.getLogger(__name__) utils.setup_logging() __version__ = "0.1" __all__ = ['Model'] class Model(object): def __init__(self, config, **kwargs): base_module = "volttron.pnnl.models." try: model_type = config["model_type"] except KeyError as e: _log.exception("Missing Model Type key: {}".format(e)) raise e _file, model_type = model_type.split(".") module = importlib.import_module(base_module + _file) model_class = getattr(module, model_type) self.model = model_class(config, self) def get_q(self, _set, sched_index, market_index, occupied): q = self.model.predict(_set, sched_index, market_index, occupied) Add return statement to Model.get_q
import importlib import logging from volttron.platform.agent import utils _log = logging.getLogger(__name__) utils.setup_logging() __version__ = "0.1" __all__ = ['Model'] class Model(object): def __init__(self, config, **kwargs): base_module = "volttron.pnnl.models." try: model_type = config["model_type"] except KeyError as e: _log.exception("Missing Model Type key: {}".format(e)) raise e _file, model_type = model_type.split(".") module = importlib.import_module(base_module + _file) model_class = getattr(module, model_type) self.model = model_class(config, self) def get_q(self, _set, sched_index, market_index, occupied): q = self.model.predict(_set, sched_index, market_index, occupied) return q
<commit_before>import importlib import logging from volttron.platform.agent import utils _log = logging.getLogger(__name__) utils.setup_logging() __version__ = "0.1" __all__ = ['Model'] class Model(object): def __init__(self, config, **kwargs): base_module = "volttron.pnnl.models." try: model_type = config["model_type"] except KeyError as e: _log.exception("Missing Model Type key: {}".format(e)) raise e _file, model_type = model_type.split(".") module = importlib.import_module(base_module + _file) model_class = getattr(module, model_type) self.model = model_class(config, self) def get_q(self, _set, sched_index, market_index, occupied): q = self.model.predict(_set, sched_index, market_index, occupied) <commit_msg>Add return statement to Model.get_q<commit_after>
import importlib import logging from volttron.platform.agent import utils _log = logging.getLogger(__name__) utils.setup_logging() __version__ = "0.1" __all__ = ['Model'] class Model(object): def __init__(self, config, **kwargs): base_module = "volttron.pnnl.models." try: model_type = config["model_type"] except KeyError as e: _log.exception("Missing Model Type key: {}".format(e)) raise e _file, model_type = model_type.split(".") module = importlib.import_module(base_module + _file) model_class = getattr(module, model_type) self.model = model_class(config, self) def get_q(self, _set, sched_index, market_index, occupied): q = self.model.predict(_set, sched_index, market_index, occupied) return q
import importlib import logging from volttron.platform.agent import utils _log = logging.getLogger(__name__) utils.setup_logging() __version__ = "0.1" __all__ = ['Model'] class Model(object): def __init__(self, config, **kwargs): base_module = "volttron.pnnl.models." try: model_type = config["model_type"] except KeyError as e: _log.exception("Missing Model Type key: {}".format(e)) raise e _file, model_type = model_type.split(".") module = importlib.import_module(base_module + _file) model_class = getattr(module, model_type) self.model = model_class(config, self) def get_q(self, _set, sched_index, market_index, occupied): q = self.model.predict(_set, sched_index, market_index, occupied) Add return statement to Model.get_qimport importlib import logging from volttron.platform.agent import utils _log = logging.getLogger(__name__) utils.setup_logging() __version__ = "0.1" __all__ = ['Model'] class Model(object): def __init__(self, config, **kwargs): base_module = "volttron.pnnl.models." try: model_type = config["model_type"] except KeyError as e: _log.exception("Missing Model Type key: {}".format(e)) raise e _file, model_type = model_type.split(".") module = importlib.import_module(base_module + _file) model_class = getattr(module, model_type) self.model = model_class(config, self) def get_q(self, _set, sched_index, market_index, occupied): q = self.model.predict(_set, sched_index, market_index, occupied) return q
<commit_before>import importlib import logging from volttron.platform.agent import utils _log = logging.getLogger(__name__) utils.setup_logging() __version__ = "0.1" __all__ = ['Model'] class Model(object): def __init__(self, config, **kwargs): base_module = "volttron.pnnl.models." try: model_type = config["model_type"] except KeyError as e: _log.exception("Missing Model Type key: {}".format(e)) raise e _file, model_type = model_type.split(".") module = importlib.import_module(base_module + _file) model_class = getattr(module, model_type) self.model = model_class(config, self) def get_q(self, _set, sched_index, market_index, occupied): q = self.model.predict(_set, sched_index, market_index, occupied) <commit_msg>Add return statement to Model.get_q<commit_after>import importlib import logging from volttron.platform.agent import utils _log = logging.getLogger(__name__) utils.setup_logging() __version__ = "0.1" __all__ = ['Model'] class Model(object): def __init__(self, config, **kwargs): base_module = "volttron.pnnl.models." try: model_type = config["model_type"] except KeyError as e: _log.exception("Missing Model Type key: {}".format(e)) raise e _file, model_type = model_type.split(".") module = importlib.import_module(base_module + _file) model_class = getattr(module, model_type) self.model = model_class(config, self) def get_q(self, _set, sched_index, market_index, occupied): q = self.model.predict(_set, sched_index, market_index, occupied) return q
c5279db4e24499d6ee49f1b444087be50f74ed90
test_spec.py
test_spec.py
#!/usr/bin/python import unittest import os import json from entei import render SPECS_PATH = os.path.join('spec', 'specs') SPECS = [path for path in os.listdir(SPECS_PATH) if path.endswith('.json')] STACHE = render def _test_case_from_path(json_path): class MustacheTestCase(unittest.TestCase): """A simple yaml based test case""" def _test_from_object(obj): """Generate a unit test from a test object""" def test_case(self): result = STACHE(obj['template'], obj['data'], partials_dict=obj.get('partials', {})) self.assertEqual(result, obj['expected']) test_case.__doc__ = 'suite: {} desc: {}'.format(spec, obj['desc']) return test_case with open(json_path, 'r') as f: yaml = json.load(f) # Generates a unit test for each test object for test in yaml['tests']: vars()['test_'+test['name']] = _test_from_object(test) # Return the built class return MustacheTestCase # Create TestCase for each json file for spec in SPECS: # Ignore optional tests if spec[0] is not '~': globals()[spec] = _test_case_from_path(os.path.join(SPECS_PATH, spec)) # Run unit tests from command line if __name__ == "__main__": unittest.main()
#!/usr/bin/python import unittest import os import json from entei import render SPECS_PATH = os.path.join('spec', 'specs') SPECS = [path for path in os.listdir(SPECS_PATH) if path.endswith('.json')] STACHE = render def _test_case_from_path(json_path): json_path = '%s.json' % json_path class MustacheTestCase(unittest.TestCase): """A simple yaml based test case""" def _test_from_object(obj): """Generate a unit test from a test object""" def test_case(self): result = STACHE(obj['template'], obj['data'], partials_dict=obj.get('partials', {})) self.assertEqual(result, obj['expected']) test_case.__doc__ = 'suite: {} desc: {}'.format(spec, obj['desc']) return test_case with open(json_path, 'r') as f: yaml = json.load(f) # Generates a unit test for each test object for i, test in enumerate(yaml['tests']): vars()['test_%s' % i] = _test_from_object(test) # Return the built class return MustacheTestCase # Create TestCase for each json file for spec in SPECS: # Ignore optional tests if spec[0] is not '~': spec = spec.split('.')[0] globals()[spec] = _test_case_from_path(os.path.join(SPECS_PATH, spec)) # Run unit tests from command line if __name__ == "__main__": unittest.main()
Make unittests easier to deal with.
Make unittests easier to deal with. - Test everything ./test_spec.py - Test suite ./test_spec.py inverted - Test unit ./test_spec.py inverted.test_7
Python
mit
noahmorrison/chevron,noahmorrison/chevron
#!/usr/bin/python import unittest import os import json from entei import render SPECS_PATH = os.path.join('spec', 'specs') SPECS = [path for path in os.listdir(SPECS_PATH) if path.endswith('.json')] STACHE = render def _test_case_from_path(json_path): class MustacheTestCase(unittest.TestCase): """A simple yaml based test case""" def _test_from_object(obj): """Generate a unit test from a test object""" def test_case(self): result = STACHE(obj['template'], obj['data'], partials_dict=obj.get('partials', {})) self.assertEqual(result, obj['expected']) test_case.__doc__ = 'suite: {} desc: {}'.format(spec, obj['desc']) return test_case with open(json_path, 'r') as f: yaml = json.load(f) # Generates a unit test for each test object for test in yaml['tests']: vars()['test_'+test['name']] = _test_from_object(test) # Return the built class return MustacheTestCase # Create TestCase for each json file for spec in SPECS: # Ignore optional tests if spec[0] is not '~': globals()[spec] = _test_case_from_path(os.path.join(SPECS_PATH, spec)) # Run unit tests from command line if __name__ == "__main__": unittest.main() Make unittests easier to deal with. - Test everything ./test_spec.py - Test suite ./test_spec.py inverted - Test unit ./test_spec.py inverted.test_7
#!/usr/bin/python import unittest import os import json from entei import render SPECS_PATH = os.path.join('spec', 'specs') SPECS = [path for path in os.listdir(SPECS_PATH) if path.endswith('.json')] STACHE = render def _test_case_from_path(json_path): json_path = '%s.json' % json_path class MustacheTestCase(unittest.TestCase): """A simple yaml based test case""" def _test_from_object(obj): """Generate a unit test from a test object""" def test_case(self): result = STACHE(obj['template'], obj['data'], partials_dict=obj.get('partials', {})) self.assertEqual(result, obj['expected']) test_case.__doc__ = 'suite: {} desc: {}'.format(spec, obj['desc']) return test_case with open(json_path, 'r') as f: yaml = json.load(f) # Generates a unit test for each test object for i, test in enumerate(yaml['tests']): vars()['test_%s' % i] = _test_from_object(test) # Return the built class return MustacheTestCase # Create TestCase for each json file for spec in SPECS: # Ignore optional tests if spec[0] is not '~': spec = spec.split('.')[0] globals()[spec] = _test_case_from_path(os.path.join(SPECS_PATH, spec)) # Run unit tests from command line if __name__ == "__main__": unittest.main()
<commit_before>#!/usr/bin/python import unittest import os import json from entei import render SPECS_PATH = os.path.join('spec', 'specs') SPECS = [path for path in os.listdir(SPECS_PATH) if path.endswith('.json')] STACHE = render def _test_case_from_path(json_path): class MustacheTestCase(unittest.TestCase): """A simple yaml based test case""" def _test_from_object(obj): """Generate a unit test from a test object""" def test_case(self): result = STACHE(obj['template'], obj['data'], partials_dict=obj.get('partials', {})) self.assertEqual(result, obj['expected']) test_case.__doc__ = 'suite: {} desc: {}'.format(spec, obj['desc']) return test_case with open(json_path, 'r') as f: yaml = json.load(f) # Generates a unit test for each test object for test in yaml['tests']: vars()['test_'+test['name']] = _test_from_object(test) # Return the built class return MustacheTestCase # Create TestCase for each json file for spec in SPECS: # Ignore optional tests if spec[0] is not '~': globals()[spec] = _test_case_from_path(os.path.join(SPECS_PATH, spec)) # Run unit tests from command line if __name__ == "__main__": unittest.main() <commit_msg>Make unittests easier to deal with. - Test everything ./test_spec.py - Test suite ./test_spec.py inverted - Test unit ./test_spec.py inverted.test_7<commit_after>
#!/usr/bin/python import unittest import os import json from entei import render SPECS_PATH = os.path.join('spec', 'specs') SPECS = [path for path in os.listdir(SPECS_PATH) if path.endswith('.json')] STACHE = render def _test_case_from_path(json_path): json_path = '%s.json' % json_path class MustacheTestCase(unittest.TestCase): """A simple yaml based test case""" def _test_from_object(obj): """Generate a unit test from a test object""" def test_case(self): result = STACHE(obj['template'], obj['data'], partials_dict=obj.get('partials', {})) self.assertEqual(result, obj['expected']) test_case.__doc__ = 'suite: {} desc: {}'.format(spec, obj['desc']) return test_case with open(json_path, 'r') as f: yaml = json.load(f) # Generates a unit test for each test object for i, test in enumerate(yaml['tests']): vars()['test_%s' % i] = _test_from_object(test) # Return the built class return MustacheTestCase # Create TestCase for each json file for spec in SPECS: # Ignore optional tests if spec[0] is not '~': spec = spec.split('.')[0] globals()[spec] = _test_case_from_path(os.path.join(SPECS_PATH, spec)) # Run unit tests from command line if __name__ == "__main__": unittest.main()
#!/usr/bin/python import unittest import os import json from entei import render SPECS_PATH = os.path.join('spec', 'specs') SPECS = [path for path in os.listdir(SPECS_PATH) if path.endswith('.json')] STACHE = render def _test_case_from_path(json_path): class MustacheTestCase(unittest.TestCase): """A simple yaml based test case""" def _test_from_object(obj): """Generate a unit test from a test object""" def test_case(self): result = STACHE(obj['template'], obj['data'], partials_dict=obj.get('partials', {})) self.assertEqual(result, obj['expected']) test_case.__doc__ = 'suite: {} desc: {}'.format(spec, obj['desc']) return test_case with open(json_path, 'r') as f: yaml = json.load(f) # Generates a unit test for each test object for test in yaml['tests']: vars()['test_'+test['name']] = _test_from_object(test) # Return the built class return MustacheTestCase # Create TestCase for each json file for spec in SPECS: # Ignore optional tests if spec[0] is not '~': globals()[spec] = _test_case_from_path(os.path.join(SPECS_PATH, spec)) # Run unit tests from command line if __name__ == "__main__": unittest.main() Make unittests easier to deal with. - Test everything ./test_spec.py - Test suite ./test_spec.py inverted - Test unit ./test_spec.py inverted.test_7#!/usr/bin/python import unittest import os import json from entei import render SPECS_PATH = os.path.join('spec', 'specs') SPECS = [path for path in os.listdir(SPECS_PATH) if path.endswith('.json')] STACHE = render def _test_case_from_path(json_path): json_path = '%s.json' % json_path class MustacheTestCase(unittest.TestCase): """A simple yaml based test case""" def _test_from_object(obj): """Generate a unit test from a test object""" def test_case(self): result = STACHE(obj['template'], obj['data'], partials_dict=obj.get('partials', {})) self.assertEqual(result, obj['expected']) test_case.__doc__ = 'suite: {} desc: {}'.format(spec, obj['desc']) return test_case with open(json_path, 'r') as f: yaml = json.load(f) # Generates a unit test for each test object for i, test in enumerate(yaml['tests']): vars()['test_%s' % i] = _test_from_object(test) # Return the built class return MustacheTestCase # Create TestCase for each json file for spec in SPECS: # Ignore optional tests if spec[0] is not '~': spec = spec.split('.')[0] globals()[spec] = _test_case_from_path(os.path.join(SPECS_PATH, spec)) # Run unit tests from command line if __name__ == "__main__": unittest.main()
<commit_before>#!/usr/bin/python import unittest import os import json from entei import render SPECS_PATH = os.path.join('spec', 'specs') SPECS = [path for path in os.listdir(SPECS_PATH) if path.endswith('.json')] STACHE = render def _test_case_from_path(json_path): class MustacheTestCase(unittest.TestCase): """A simple yaml based test case""" def _test_from_object(obj): """Generate a unit test from a test object""" def test_case(self): result = STACHE(obj['template'], obj['data'], partials_dict=obj.get('partials', {})) self.assertEqual(result, obj['expected']) test_case.__doc__ = 'suite: {} desc: {}'.format(spec, obj['desc']) return test_case with open(json_path, 'r') as f: yaml = json.load(f) # Generates a unit test for each test object for test in yaml['tests']: vars()['test_'+test['name']] = _test_from_object(test) # Return the built class return MustacheTestCase # Create TestCase for each json file for spec in SPECS: # Ignore optional tests if spec[0] is not '~': globals()[spec] = _test_case_from_path(os.path.join(SPECS_PATH, spec)) # Run unit tests from command line if __name__ == "__main__": unittest.main() <commit_msg>Make unittests easier to deal with. - Test everything ./test_spec.py - Test suite ./test_spec.py inverted - Test unit ./test_spec.py inverted.test_7<commit_after>#!/usr/bin/python import unittest import os import json from entei import render SPECS_PATH = os.path.join('spec', 'specs') SPECS = [path for path in os.listdir(SPECS_PATH) if path.endswith('.json')] STACHE = render def _test_case_from_path(json_path): json_path = '%s.json' % json_path class MustacheTestCase(unittest.TestCase): """A simple yaml based test case""" def _test_from_object(obj): """Generate a unit test from a test object""" def test_case(self): result = STACHE(obj['template'], obj['data'], partials_dict=obj.get('partials', {})) self.assertEqual(result, obj['expected']) test_case.__doc__ = 'suite: {} desc: {}'.format(spec, obj['desc']) return test_case with open(json_path, 'r') as f: yaml = json.load(f) # Generates a unit test for each test object for i, test in enumerate(yaml['tests']): vars()['test_%s' % i] = _test_from_object(test) # Return the built class return MustacheTestCase # Create TestCase for each json file for spec in SPECS: # Ignore optional tests if spec[0] is not '~': spec = spec.split('.')[0] globals()[spec] = _test_case_from_path(os.path.join(SPECS_PATH, spec)) # Run unit tests from command line if __name__ == "__main__": unittest.main()
1b58fed32fe583863812613604383eb9d8821ee1
tools/sci.py
tools/sci.py
#!/usr/bin/env python # encoding: utf-8 from __future__ import division, print_function import numpy as np from scipy.integrate import ode def zodeint(func, y0, t): """Simple wraper around scipy.integrate.ode for complex valued problems. :param func: Right hand side of the equation dy/dt = f(t, y) :param y0: Initial value at t = t[0] :param t: Sequence of time points for whihc to solve for y :returns: y[len(t), len(y0)] """ integrator = ode(func) \ .set_integrator('zvode', with_jacobian=False) \ .set_initial_value(y0) y = np.empty((len(t), len(y0)), dtype=complex) y[0] = y0 for i in xrange(1, len(t)): integrator.integrate(t[i]) if not integrator.successful(): print('WARNING: Integrator failed') break y[i] = integrator.y return t[:i+1], y[:i+1]
#!/usr/bin/env python # encoding: utf-8 from __future__ import division, print_function import numpy as np from scipy.integrate import ode def zodeint(func, y0, t, **kwargs): """Simple wraper around scipy.integrate.ode for complex valued problems. :param func: Right hand side of the equation dy/dt = f(t, y) :param y0: Initial value at t = t[0] :param t: Sequence of time points for whihc to solve for y :returns: y[len(t), len(y0)] """ y0 = np.array([y0]) if np.isscalar(y0) else y0 integrator = ode(func) \ .set_integrator('zvode', with_jacobian=False, **kwargs) \ .set_initial_value(y0) y = np.empty((len(t), len(y0)), dtype=complex) y[0] = y0 for i in xrange(1, len(t)): integrator.integrate(t[i]) if not integrator.successful(): print('WARNING: Integrator failed') break y[i] = integrator.y return t[:i+1], y[:i+1]
Correct complex integrator for scalar equations
Correct complex integrator for scalar equations
Python
unlicense
dseuss/pythonlibs
#!/usr/bin/env python # encoding: utf-8 from __future__ import division, print_function import numpy as np from scipy.integrate import ode def zodeint(func, y0, t): """Simple wraper around scipy.integrate.ode for complex valued problems. :param func: Right hand side of the equation dy/dt = f(t, y) :param y0: Initial value at t = t[0] :param t: Sequence of time points for whihc to solve for y :returns: y[len(t), len(y0)] """ integrator = ode(func) \ .set_integrator('zvode', with_jacobian=False) \ .set_initial_value(y0) y = np.empty((len(t), len(y0)), dtype=complex) y[0] = y0 for i in xrange(1, len(t)): integrator.integrate(t[i]) if not integrator.successful(): print('WARNING: Integrator failed') break y[i] = integrator.y return t[:i+1], y[:i+1] Correct complex integrator for scalar equations
#!/usr/bin/env python # encoding: utf-8 from __future__ import division, print_function import numpy as np from scipy.integrate import ode def zodeint(func, y0, t, **kwargs): """Simple wraper around scipy.integrate.ode for complex valued problems. :param func: Right hand side of the equation dy/dt = f(t, y) :param y0: Initial value at t = t[0] :param t: Sequence of time points for whihc to solve for y :returns: y[len(t), len(y0)] """ y0 = np.array([y0]) if np.isscalar(y0) else y0 integrator = ode(func) \ .set_integrator('zvode', with_jacobian=False, **kwargs) \ .set_initial_value(y0) y = np.empty((len(t), len(y0)), dtype=complex) y[0] = y0 for i in xrange(1, len(t)): integrator.integrate(t[i]) if not integrator.successful(): print('WARNING: Integrator failed') break y[i] = integrator.y return t[:i+1], y[:i+1]
<commit_before>#!/usr/bin/env python # encoding: utf-8 from __future__ import division, print_function import numpy as np from scipy.integrate import ode def zodeint(func, y0, t): """Simple wraper around scipy.integrate.ode for complex valued problems. :param func: Right hand side of the equation dy/dt = f(t, y) :param y0: Initial value at t = t[0] :param t: Sequence of time points for whihc to solve for y :returns: y[len(t), len(y0)] """ integrator = ode(func) \ .set_integrator('zvode', with_jacobian=False) \ .set_initial_value(y0) y = np.empty((len(t), len(y0)), dtype=complex) y[0] = y0 for i in xrange(1, len(t)): integrator.integrate(t[i]) if not integrator.successful(): print('WARNING: Integrator failed') break y[i] = integrator.y return t[:i+1], y[:i+1] <commit_msg>Correct complex integrator for scalar equations<commit_after>
#!/usr/bin/env python # encoding: utf-8 from __future__ import division, print_function import numpy as np from scipy.integrate import ode def zodeint(func, y0, t, **kwargs): """Simple wraper around scipy.integrate.ode for complex valued problems. :param func: Right hand side of the equation dy/dt = f(t, y) :param y0: Initial value at t = t[0] :param t: Sequence of time points for whihc to solve for y :returns: y[len(t), len(y0)] """ y0 = np.array([y0]) if np.isscalar(y0) else y0 integrator = ode(func) \ .set_integrator('zvode', with_jacobian=False, **kwargs) \ .set_initial_value(y0) y = np.empty((len(t), len(y0)), dtype=complex) y[0] = y0 for i in xrange(1, len(t)): integrator.integrate(t[i]) if not integrator.successful(): print('WARNING: Integrator failed') break y[i] = integrator.y return t[:i+1], y[:i+1]
#!/usr/bin/env python # encoding: utf-8 from __future__ import division, print_function import numpy as np from scipy.integrate import ode def zodeint(func, y0, t): """Simple wraper around scipy.integrate.ode for complex valued problems. :param func: Right hand side of the equation dy/dt = f(t, y) :param y0: Initial value at t = t[0] :param t: Sequence of time points for whihc to solve for y :returns: y[len(t), len(y0)] """ integrator = ode(func) \ .set_integrator('zvode', with_jacobian=False) \ .set_initial_value(y0) y = np.empty((len(t), len(y0)), dtype=complex) y[0] = y0 for i in xrange(1, len(t)): integrator.integrate(t[i]) if not integrator.successful(): print('WARNING: Integrator failed') break y[i] = integrator.y return t[:i+1], y[:i+1] Correct complex integrator for scalar equations#!/usr/bin/env python # encoding: utf-8 from __future__ import division, print_function import numpy as np from scipy.integrate import ode def zodeint(func, y0, t, **kwargs): """Simple wraper around scipy.integrate.ode for complex valued problems. :param func: Right hand side of the equation dy/dt = f(t, y) :param y0: Initial value at t = t[0] :param t: Sequence of time points for whihc to solve for y :returns: y[len(t), len(y0)] """ y0 = np.array([y0]) if np.isscalar(y0) else y0 integrator = ode(func) \ .set_integrator('zvode', with_jacobian=False, **kwargs) \ .set_initial_value(y0) y = np.empty((len(t), len(y0)), dtype=complex) y[0] = y0 for i in xrange(1, len(t)): integrator.integrate(t[i]) if not integrator.successful(): print('WARNING: Integrator failed') break y[i] = integrator.y return t[:i+1], y[:i+1]
<commit_before>#!/usr/bin/env python # encoding: utf-8 from __future__ import division, print_function import numpy as np from scipy.integrate import ode def zodeint(func, y0, t): """Simple wraper around scipy.integrate.ode for complex valued problems. :param func: Right hand side of the equation dy/dt = f(t, y) :param y0: Initial value at t = t[0] :param t: Sequence of time points for whihc to solve for y :returns: y[len(t), len(y0)] """ integrator = ode(func) \ .set_integrator('zvode', with_jacobian=False) \ .set_initial_value(y0) y = np.empty((len(t), len(y0)), dtype=complex) y[0] = y0 for i in xrange(1, len(t)): integrator.integrate(t[i]) if not integrator.successful(): print('WARNING: Integrator failed') break y[i] = integrator.y return t[:i+1], y[:i+1] <commit_msg>Correct complex integrator for scalar equations<commit_after>#!/usr/bin/env python # encoding: utf-8 from __future__ import division, print_function import numpy as np from scipy.integrate import ode def zodeint(func, y0, t, **kwargs): """Simple wraper around scipy.integrate.ode for complex valued problems. :param func: Right hand side of the equation dy/dt = f(t, y) :param y0: Initial value at t = t[0] :param t: Sequence of time points for whihc to solve for y :returns: y[len(t), len(y0)] """ y0 = np.array([y0]) if np.isscalar(y0) else y0 integrator = ode(func) \ .set_integrator('zvode', with_jacobian=False, **kwargs) \ .set_initial_value(y0) y = np.empty((len(t), len(y0)), dtype=complex) y[0] = y0 for i in xrange(1, len(t)): integrator.integrate(t[i]) if not integrator.successful(): print('WARNING: Integrator failed') break y[i] = integrator.y return t[:i+1], y[:i+1]
2facb0c8794c9529ccb17631a90b0ee181c4eb5b
xml_json_import/__init__.py
xml_json_import/__init__.py
from django.conf import settings from os import path class XmlJsonImportModuleException(Exception): pass if not hasattr(settings, 'XSLT_FILES_DIR'): raise XmlJsonImportModuleException('Settings must contain XSLT_FILES_DIR parameter') if not path.exists(settings.XSLT_FILES_DIR): raise XmlJsonImportModuleException('Directory specified by XSLT_FILES_DIR does not exist')
from django.conf import settings from os import path, listdir from lxml import etree class XmlJsonImportModuleException(Exception): pass if not hasattr(settings, 'XSLT_FILES_DIR'): raise XmlJsonImportModuleException('Settings must contain XSLT_FILES_DIR parameter') if not path.exists(settings.XSLT_FILES_DIR): raise XmlJsonImportModuleException('Directory specified by XSLT_FILES_DIR does not exist') for filename in listdir(settings.XSLT_FILES_DIR): filepath = path.join(settings.XSLT_FILES_DIR, filename) if path.isfile(filepath): try: xslt_etree = etree.parse(filepath) except etree.XMLSyntaxError as er: raise XmlJsonImportModuleException('File ' + filepath + ' is not a valid XML file: ' + str(er)) try: transform = etree.XSLT(xslt_etree) except etree.XSLTParseError as er: raise XmlJsonImportModuleException('File ' + filepath + ' is not a valid XSLT file: ' + str(er))
Add exception handling for invalid XSLT files
Add exception handling for invalid XSLT files
Python
mit
lev-veshnyakov/django-import-data,lev-veshnyakov/django-import-data
from django.conf import settings from os import path class XmlJsonImportModuleException(Exception): pass if not hasattr(settings, 'XSLT_FILES_DIR'): raise XmlJsonImportModuleException('Settings must contain XSLT_FILES_DIR parameter') if not path.exists(settings.XSLT_FILES_DIR): raise XmlJsonImportModuleException('Directory specified by XSLT_FILES_DIR does not exist') Add exception handling for invalid XSLT files
from django.conf import settings from os import path, listdir from lxml import etree class XmlJsonImportModuleException(Exception): pass if not hasattr(settings, 'XSLT_FILES_DIR'): raise XmlJsonImportModuleException('Settings must contain XSLT_FILES_DIR parameter') if not path.exists(settings.XSLT_FILES_DIR): raise XmlJsonImportModuleException('Directory specified by XSLT_FILES_DIR does not exist') for filename in listdir(settings.XSLT_FILES_DIR): filepath = path.join(settings.XSLT_FILES_DIR, filename) if path.isfile(filepath): try: xslt_etree = etree.parse(filepath) except etree.XMLSyntaxError as er: raise XmlJsonImportModuleException('File ' + filepath + ' is not a valid XML file: ' + str(er)) try: transform = etree.XSLT(xslt_etree) except etree.XSLTParseError as er: raise XmlJsonImportModuleException('File ' + filepath + ' is not a valid XSLT file: ' + str(er))
<commit_before>from django.conf import settings from os import path class XmlJsonImportModuleException(Exception): pass if not hasattr(settings, 'XSLT_FILES_DIR'): raise XmlJsonImportModuleException('Settings must contain XSLT_FILES_DIR parameter') if not path.exists(settings.XSLT_FILES_DIR): raise XmlJsonImportModuleException('Directory specified by XSLT_FILES_DIR does not exist') <commit_msg>Add exception handling for invalid XSLT files<commit_after>
from django.conf import settings from os import path, listdir from lxml import etree class XmlJsonImportModuleException(Exception): pass if not hasattr(settings, 'XSLT_FILES_DIR'): raise XmlJsonImportModuleException('Settings must contain XSLT_FILES_DIR parameter') if not path.exists(settings.XSLT_FILES_DIR): raise XmlJsonImportModuleException('Directory specified by XSLT_FILES_DIR does not exist') for filename in listdir(settings.XSLT_FILES_DIR): filepath = path.join(settings.XSLT_FILES_DIR, filename) if path.isfile(filepath): try: xslt_etree = etree.parse(filepath) except etree.XMLSyntaxError as er: raise XmlJsonImportModuleException('File ' + filepath + ' is not a valid XML file: ' + str(er)) try: transform = etree.XSLT(xslt_etree) except etree.XSLTParseError as er: raise XmlJsonImportModuleException('File ' + filepath + ' is not a valid XSLT file: ' + str(er))
from django.conf import settings from os import path class XmlJsonImportModuleException(Exception): pass if not hasattr(settings, 'XSLT_FILES_DIR'): raise XmlJsonImportModuleException('Settings must contain XSLT_FILES_DIR parameter') if not path.exists(settings.XSLT_FILES_DIR): raise XmlJsonImportModuleException('Directory specified by XSLT_FILES_DIR does not exist') Add exception handling for invalid XSLT filesfrom django.conf import settings from os import path, listdir from lxml import etree class XmlJsonImportModuleException(Exception): pass if not hasattr(settings, 'XSLT_FILES_DIR'): raise XmlJsonImportModuleException('Settings must contain XSLT_FILES_DIR parameter') if not path.exists(settings.XSLT_FILES_DIR): raise XmlJsonImportModuleException('Directory specified by XSLT_FILES_DIR does not exist') for filename in listdir(settings.XSLT_FILES_DIR): filepath = path.join(settings.XSLT_FILES_DIR, filename) if path.isfile(filepath): try: xslt_etree = etree.parse(filepath) except etree.XMLSyntaxError as er: raise XmlJsonImportModuleException('File ' + filepath + ' is not a valid XML file: ' + str(er)) try: transform = etree.XSLT(xslt_etree) except etree.XSLTParseError as er: raise XmlJsonImportModuleException('File ' + filepath + ' is not a valid XSLT file: ' + str(er))
<commit_before>from django.conf import settings from os import path class XmlJsonImportModuleException(Exception): pass if not hasattr(settings, 'XSLT_FILES_DIR'): raise XmlJsonImportModuleException('Settings must contain XSLT_FILES_DIR parameter') if not path.exists(settings.XSLT_FILES_DIR): raise XmlJsonImportModuleException('Directory specified by XSLT_FILES_DIR does not exist') <commit_msg>Add exception handling for invalid XSLT files<commit_after>from django.conf import settings from os import path, listdir from lxml import etree class XmlJsonImportModuleException(Exception): pass if not hasattr(settings, 'XSLT_FILES_DIR'): raise XmlJsonImportModuleException('Settings must contain XSLT_FILES_DIR parameter') if not path.exists(settings.XSLT_FILES_DIR): raise XmlJsonImportModuleException('Directory specified by XSLT_FILES_DIR does not exist') for filename in listdir(settings.XSLT_FILES_DIR): filepath = path.join(settings.XSLT_FILES_DIR, filename) if path.isfile(filepath): try: xslt_etree = etree.parse(filepath) except etree.XMLSyntaxError as er: raise XmlJsonImportModuleException('File ' + filepath + ' is not a valid XML file: ' + str(er)) try: transform = etree.XSLT(xslt_etree) except etree.XSLTParseError as er: raise XmlJsonImportModuleException('File ' + filepath + ' is not a valid XSLT file: ' + str(er))
0a38c3f83174042ca4967bff925036af2339808f
job-logs/python/check_log.py
job-logs/python/check_log.py
import sys import argparse import csv def examine_log(filename, save_raw=False): """ Download job log files from Amazon EC2 machines parameters: filename - beginning date to start downloading from work_directory - directory to download files to """ input_file =- open(filename, 'r') csv_input = csv.reader(input_file) error = 0 for row in csv_input: if len(row) != 87: error += 1 print error sys.stderr.write("{0} lines skipped due to errors".format(error_lines)) return None if __name__ == '__main__': parser = argparse.ArgumentParser(description='Process ATLAS job records') parser.add_argument('--filename', dest='filename', default=None, help='filename of input file') parser.add_argument('--save-raw', dest='save_raw', action='store_true', help='Save raw log files instead of replacing in place') args = parser.parse_args(sys.argv[1:]) examine_log(args.filename, args.save_raw)
#!/usr/bin/env python import sys import argparse import csv def examine_log(filename, save_raw=False): """ Download job log files from Amazon EC2 machines parameters: filename - beginning date to start downloading from work_directory - directory to download files to """ input_file = open(filename, 'r') bad_file = open('badlines.csv', 'w') csv_input = csv.reader(input_file) error = 0 lines = 0 for row in csv_input: lines += 1 if len(row) != 87: error += 1 bad_file.write(" ".join(row) + "\n") continue sys.stderr.write("{0} lines skipped due to errors".format(error)) sys.stderr.write("{0} lines processed".format(lines)) sys.stderr.write("{0}% bad lines ".format(float(error)/float(lines))) return None if __name__ == '__main__': parser = argparse.ArgumentParser(description='Process ATLAS job records') parser.add_argument('--filename', dest='filename', default=None, help='filename of input file') parser.add_argument('--save-raw', dest='save_raw', action='store_true', help='Save raw log files instead of replacing in place') args = parser.parse_args(sys.argv[1:]) examine_log(args.filename, args.save_raw)
Write bad lines to file for examination
Write bad lines to file for examination
Python
apache-2.0
DHTC-Tools/logstash-confs,DHTC-Tools/logstash-confs,DHTC-Tools/logstash-confs
import sys import argparse import csv def examine_log(filename, save_raw=False): """ Download job log files from Amazon EC2 machines parameters: filename - beginning date to start downloading from work_directory - directory to download files to """ input_file =- open(filename, 'r') csv_input = csv.reader(input_file) error = 0 for row in csv_input: if len(row) != 87: error += 1 print error sys.stderr.write("{0} lines skipped due to errors".format(error_lines)) return None if __name__ == '__main__': parser = argparse.ArgumentParser(description='Process ATLAS job records') parser.add_argument('--filename', dest='filename', default=None, help='filename of input file') parser.add_argument('--save-raw', dest='save_raw', action='store_true', help='Save raw log files instead of replacing in place') args = parser.parse_args(sys.argv[1:]) examine_log(args.filename, args.save_raw)Write bad lines to file for examination
#!/usr/bin/env python import sys import argparse import csv def examine_log(filename, save_raw=False): """ Download job log files from Amazon EC2 machines parameters: filename - beginning date to start downloading from work_directory - directory to download files to """ input_file = open(filename, 'r') bad_file = open('badlines.csv', 'w') csv_input = csv.reader(input_file) error = 0 lines = 0 for row in csv_input: lines += 1 if len(row) != 87: error += 1 bad_file.write(" ".join(row) + "\n") continue sys.stderr.write("{0} lines skipped due to errors".format(error)) sys.stderr.write("{0} lines processed".format(lines)) sys.stderr.write("{0}% bad lines ".format(float(error)/float(lines))) return None if __name__ == '__main__': parser = argparse.ArgumentParser(description='Process ATLAS job records') parser.add_argument('--filename', dest='filename', default=None, help='filename of input file') parser.add_argument('--save-raw', dest='save_raw', action='store_true', help='Save raw log files instead of replacing in place') args = parser.parse_args(sys.argv[1:]) examine_log(args.filename, args.save_raw)
<commit_before>import sys import argparse import csv def examine_log(filename, save_raw=False): """ Download job log files from Amazon EC2 machines parameters: filename - beginning date to start downloading from work_directory - directory to download files to """ input_file =- open(filename, 'r') csv_input = csv.reader(input_file) error = 0 for row in csv_input: if len(row) != 87: error += 1 print error sys.stderr.write("{0} lines skipped due to errors".format(error_lines)) return None if __name__ == '__main__': parser = argparse.ArgumentParser(description='Process ATLAS job records') parser.add_argument('--filename', dest='filename', default=None, help='filename of input file') parser.add_argument('--save-raw', dest='save_raw', action='store_true', help='Save raw log files instead of replacing in place') args = parser.parse_args(sys.argv[1:]) examine_log(args.filename, args.save_raw)<commit_msg>Write bad lines to file for examination<commit_after>
#!/usr/bin/env python import sys import argparse import csv def examine_log(filename, save_raw=False): """ Download job log files from Amazon EC2 machines parameters: filename - beginning date to start downloading from work_directory - directory to download files to """ input_file = open(filename, 'r') bad_file = open('badlines.csv', 'w') csv_input = csv.reader(input_file) error = 0 lines = 0 for row in csv_input: lines += 1 if len(row) != 87: error += 1 bad_file.write(" ".join(row) + "\n") continue sys.stderr.write("{0} lines skipped due to errors".format(error)) sys.stderr.write("{0} lines processed".format(lines)) sys.stderr.write("{0}% bad lines ".format(float(error)/float(lines))) return None if __name__ == '__main__': parser = argparse.ArgumentParser(description='Process ATLAS job records') parser.add_argument('--filename', dest='filename', default=None, help='filename of input file') parser.add_argument('--save-raw', dest='save_raw', action='store_true', help='Save raw log files instead of replacing in place') args = parser.parse_args(sys.argv[1:]) examine_log(args.filename, args.save_raw)
import sys import argparse import csv def examine_log(filename, save_raw=False): """ Download job log files from Amazon EC2 machines parameters: filename - beginning date to start downloading from work_directory - directory to download files to """ input_file =- open(filename, 'r') csv_input = csv.reader(input_file) error = 0 for row in csv_input: if len(row) != 87: error += 1 print error sys.stderr.write("{0} lines skipped due to errors".format(error_lines)) return None if __name__ == '__main__': parser = argparse.ArgumentParser(description='Process ATLAS job records') parser.add_argument('--filename', dest='filename', default=None, help='filename of input file') parser.add_argument('--save-raw', dest='save_raw', action='store_true', help='Save raw log files instead of replacing in place') args = parser.parse_args(sys.argv[1:]) examine_log(args.filename, args.save_raw)Write bad lines to file for examination#!/usr/bin/env python import sys import argparse import csv def examine_log(filename, save_raw=False): """ Download job log files from Amazon EC2 machines parameters: filename - beginning date to start downloading from work_directory - directory to download files to """ input_file = open(filename, 'r') bad_file = open('badlines.csv', 'w') csv_input = csv.reader(input_file) error = 0 lines = 0 for row in csv_input: lines += 1 if len(row) != 87: error += 1 bad_file.write(" ".join(row) + "\n") continue sys.stderr.write("{0} lines skipped due to errors".format(error)) sys.stderr.write("{0} lines processed".format(lines)) sys.stderr.write("{0}% bad lines ".format(float(error)/float(lines))) return None if __name__ == '__main__': parser = argparse.ArgumentParser(description='Process ATLAS job records') parser.add_argument('--filename', dest='filename', default=None, help='filename of input file') parser.add_argument('--save-raw', dest='save_raw', action='store_true', help='Save raw log files instead of replacing in place') args = parser.parse_args(sys.argv[1:]) examine_log(args.filename, args.save_raw)
<commit_before>import sys import argparse import csv def examine_log(filename, save_raw=False): """ Download job log files from Amazon EC2 machines parameters: filename - beginning date to start downloading from work_directory - directory to download files to """ input_file =- open(filename, 'r') csv_input = csv.reader(input_file) error = 0 for row in csv_input: if len(row) != 87: error += 1 print error sys.stderr.write("{0} lines skipped due to errors".format(error_lines)) return None if __name__ == '__main__': parser = argparse.ArgumentParser(description='Process ATLAS job records') parser.add_argument('--filename', dest='filename', default=None, help='filename of input file') parser.add_argument('--save-raw', dest='save_raw', action='store_true', help='Save raw log files instead of replacing in place') args = parser.parse_args(sys.argv[1:]) examine_log(args.filename, args.save_raw)<commit_msg>Write bad lines to file for examination<commit_after>#!/usr/bin/env python import sys import argparse import csv def examine_log(filename, save_raw=False): """ Download job log files from Amazon EC2 machines parameters: filename - beginning date to start downloading from work_directory - directory to download files to """ input_file = open(filename, 'r') bad_file = open('badlines.csv', 'w') csv_input = csv.reader(input_file) error = 0 lines = 0 for row in csv_input: lines += 1 if len(row) != 87: error += 1 bad_file.write(" ".join(row) + "\n") continue sys.stderr.write("{0} lines skipped due to errors".format(error)) sys.stderr.write("{0} lines processed".format(lines)) sys.stderr.write("{0}% bad lines ".format(float(error)/float(lines))) return None if __name__ == '__main__': parser = argparse.ArgumentParser(description='Process ATLAS job records') parser.add_argument('--filename', dest='filename', default=None, help='filename of input file') parser.add_argument('--save-raw', dest='save_raw', action='store_true', help='Save raw log files instead of replacing in place') args = parser.parse_args(sys.argv[1:]) examine_log(args.filename, args.save_raw)
ee8acd5a476b0dcce9b79f70e4c70186ea4d5dc0
miniutils.py
miniutils.py
import __builtin__ def any(it): for obj in it: if obj: return True def all(it): for obj in it: if not obj: return False return True def max(it, key=None): if key is not None: k, value = max((key(value), value) for value in it) return value return max(it) def min(it, key=None): if key is not None: k, value = min((key(value), value) for value in it) return value return min(it) class Condition(object): """ This wraps a condition so that it can be shared by everyone and modified by whomever wants to. """ def __init__(self, value): self.value = value def __nonzero__(self): return self.value class ComparableObjectMixin(object): def __hash__(self): "Implement in subclasses" raise NotImplementedError def __eq__(self, other): "Implement in subclasses" return NotImplemented
import __builtin__ def any(it): for obj in it: if obj: return True return False def all(it): for obj in it: if not obj: return False return True def max(it, key=None): if key is not None: k, value = max((key(value), value) for value in it) return value return max(it) def min(it, key=None): if key is not None: k, value = min((key(value), value) for value in it) return value return min(it) class Condition(object): """ This wraps a condition so that it can be shared by everyone and modified by whomever wants to. """ def __init__(self, value): self.value = value def __nonzero__(self): return self.value class ComparableObjectMixin(object): def __hash__(self): "Implement in subclasses" raise NotImplementedError def __eq__(self, other): "Implement in subclasses" return NotImplemented
Return an actual bool from any()
Return an actual bool from any()
Python
bsd-2-clause
markflorisson/minivect,markflorisson/minivect
import __builtin__ def any(it): for obj in it: if obj: return True def all(it): for obj in it: if not obj: return False return True def max(it, key=None): if key is not None: k, value = max((key(value), value) for value in it) return value return max(it) def min(it, key=None): if key is not None: k, value = min((key(value), value) for value in it) return value return min(it) class Condition(object): """ This wraps a condition so that it can be shared by everyone and modified by whomever wants to. """ def __init__(self, value): self.value = value def __nonzero__(self): return self.value class ComparableObjectMixin(object): def __hash__(self): "Implement in subclasses" raise NotImplementedError def __eq__(self, other): "Implement in subclasses" return NotImplementedReturn an actual bool from any()
import __builtin__ def any(it): for obj in it: if obj: return True return False def all(it): for obj in it: if not obj: return False return True def max(it, key=None): if key is not None: k, value = max((key(value), value) for value in it) return value return max(it) def min(it, key=None): if key is not None: k, value = min((key(value), value) for value in it) return value return min(it) class Condition(object): """ This wraps a condition so that it can be shared by everyone and modified by whomever wants to. """ def __init__(self, value): self.value = value def __nonzero__(self): return self.value class ComparableObjectMixin(object): def __hash__(self): "Implement in subclasses" raise NotImplementedError def __eq__(self, other): "Implement in subclasses" return NotImplemented
<commit_before>import __builtin__ def any(it): for obj in it: if obj: return True def all(it): for obj in it: if not obj: return False return True def max(it, key=None): if key is not None: k, value = max((key(value), value) for value in it) return value return max(it) def min(it, key=None): if key is not None: k, value = min((key(value), value) for value in it) return value return min(it) class Condition(object): """ This wraps a condition so that it can be shared by everyone and modified by whomever wants to. """ def __init__(self, value): self.value = value def __nonzero__(self): return self.value class ComparableObjectMixin(object): def __hash__(self): "Implement in subclasses" raise NotImplementedError def __eq__(self, other): "Implement in subclasses" return NotImplemented<commit_msg>Return an actual bool from any()<commit_after>
import __builtin__ def any(it): for obj in it: if obj: return True return False def all(it): for obj in it: if not obj: return False return True def max(it, key=None): if key is not None: k, value = max((key(value), value) for value in it) return value return max(it) def min(it, key=None): if key is not None: k, value = min((key(value), value) for value in it) return value return min(it) class Condition(object): """ This wraps a condition so that it can be shared by everyone and modified by whomever wants to. """ def __init__(self, value): self.value = value def __nonzero__(self): return self.value class ComparableObjectMixin(object): def __hash__(self): "Implement in subclasses" raise NotImplementedError def __eq__(self, other): "Implement in subclasses" return NotImplemented
import __builtin__ def any(it): for obj in it: if obj: return True def all(it): for obj in it: if not obj: return False return True def max(it, key=None): if key is not None: k, value = max((key(value), value) for value in it) return value return max(it) def min(it, key=None): if key is not None: k, value = min((key(value), value) for value in it) return value return min(it) class Condition(object): """ This wraps a condition so that it can be shared by everyone and modified by whomever wants to. """ def __init__(self, value): self.value = value def __nonzero__(self): return self.value class ComparableObjectMixin(object): def __hash__(self): "Implement in subclasses" raise NotImplementedError def __eq__(self, other): "Implement in subclasses" return NotImplementedReturn an actual bool from any()import __builtin__ def any(it): for obj in it: if obj: return True return False def all(it): for obj in it: if not obj: return False return True def max(it, key=None): if key is not None: k, value = max((key(value), value) for value in it) return value return max(it) def min(it, key=None): if key is not None: k, value = min((key(value), value) for value in it) return value return min(it) class Condition(object): """ This wraps a condition so that it can be shared by everyone and modified by whomever wants to. """ def __init__(self, value): self.value = value def __nonzero__(self): return self.value class ComparableObjectMixin(object): def __hash__(self): "Implement in subclasses" raise NotImplementedError def __eq__(self, other): "Implement in subclasses" return NotImplemented
<commit_before>import __builtin__ def any(it): for obj in it: if obj: return True def all(it): for obj in it: if not obj: return False return True def max(it, key=None): if key is not None: k, value = max((key(value), value) for value in it) return value return max(it) def min(it, key=None): if key is not None: k, value = min((key(value), value) for value in it) return value return min(it) class Condition(object): """ This wraps a condition so that it can be shared by everyone and modified by whomever wants to. """ def __init__(self, value): self.value = value def __nonzero__(self): return self.value class ComparableObjectMixin(object): def __hash__(self): "Implement in subclasses" raise NotImplementedError def __eq__(self, other): "Implement in subclasses" return NotImplemented<commit_msg>Return an actual bool from any()<commit_after>import __builtin__ def any(it): for obj in it: if obj: return True return False def all(it): for obj in it: if not obj: return False return True def max(it, key=None): if key is not None: k, value = max((key(value), value) for value in it) return value return max(it) def min(it, key=None): if key is not None: k, value = min((key(value), value) for value in it) return value return min(it) class Condition(object): """ This wraps a condition so that it can be shared by everyone and modified by whomever wants to. """ def __init__(self, value): self.value = value def __nonzero__(self): return self.value class ComparableObjectMixin(object): def __hash__(self): "Implement in subclasses" raise NotImplementedError def __eq__(self, other): "Implement in subclasses" return NotImplemented
e5803617b27144cb88563b3533b66f0b96482143
guv/green/time.py
guv/green/time.py
__time = __import__('time') from ..patcher import slurp_properties __patched__ = ['sleep'] slurp_properties(__time, globals(), ignore=__patched__, srckeys=dir(__time)) from ..greenthread import sleep sleep # silence pyflakes
"""Greenified :mod:`time` module The only thing that needs to be patched from :mod:`time` is :func:`time.sleep` to yield instead of block the thread. """ __time = __import__('time') from ..patcher import slurp_properties __patched__ = ['sleep'] slurp_properties(__time, globals(), ignore=__patched__, srckeys=dir(__time)) from .. import greenthread sleep = greenthread.sleep
Declare sleep as a global instead of relying on import
Declare sleep as a global instead of relying on import This is a nicer way to define it in the greenified module. Unused imports may accidentally disappear after using your IDE's "optimize imports" function.
Python
mit
veegee/guv,veegee/guv
__time = __import__('time') from ..patcher import slurp_properties __patched__ = ['sleep'] slurp_properties(__time, globals(), ignore=__patched__, srckeys=dir(__time)) from ..greenthread import sleep sleep # silence pyflakes Declare sleep as a global instead of relying on import This is a nicer way to define it in the greenified module. Unused imports may accidentally disappear after using your IDE's "optimize imports" function.
"""Greenified :mod:`time` module The only thing that needs to be patched from :mod:`time` is :func:`time.sleep` to yield instead of block the thread. """ __time = __import__('time') from ..patcher import slurp_properties __patched__ = ['sleep'] slurp_properties(__time, globals(), ignore=__patched__, srckeys=dir(__time)) from .. import greenthread sleep = greenthread.sleep
<commit_before>__time = __import__('time') from ..patcher import slurp_properties __patched__ = ['sleep'] slurp_properties(__time, globals(), ignore=__patched__, srckeys=dir(__time)) from ..greenthread import sleep sleep # silence pyflakes <commit_msg>Declare sleep as a global instead of relying on import This is a nicer way to define it in the greenified module. Unused imports may accidentally disappear after using your IDE's "optimize imports" function.<commit_after>
"""Greenified :mod:`time` module The only thing that needs to be patched from :mod:`time` is :func:`time.sleep` to yield instead of block the thread. """ __time = __import__('time') from ..patcher import slurp_properties __patched__ = ['sleep'] slurp_properties(__time, globals(), ignore=__patched__, srckeys=dir(__time)) from .. import greenthread sleep = greenthread.sleep
__time = __import__('time') from ..patcher import slurp_properties __patched__ = ['sleep'] slurp_properties(__time, globals(), ignore=__patched__, srckeys=dir(__time)) from ..greenthread import sleep sleep # silence pyflakes Declare sleep as a global instead of relying on import This is a nicer way to define it in the greenified module. Unused imports may accidentally disappear after using your IDE's "optimize imports" function."""Greenified :mod:`time` module The only thing that needs to be patched from :mod:`time` is :func:`time.sleep` to yield instead of block the thread. """ __time = __import__('time') from ..patcher import slurp_properties __patched__ = ['sleep'] slurp_properties(__time, globals(), ignore=__patched__, srckeys=dir(__time)) from .. import greenthread sleep = greenthread.sleep
<commit_before>__time = __import__('time') from ..patcher import slurp_properties __patched__ = ['sleep'] slurp_properties(__time, globals(), ignore=__patched__, srckeys=dir(__time)) from ..greenthread import sleep sleep # silence pyflakes <commit_msg>Declare sleep as a global instead of relying on import This is a nicer way to define it in the greenified module. Unused imports may accidentally disappear after using your IDE's "optimize imports" function.<commit_after>"""Greenified :mod:`time` module The only thing that needs to be patched from :mod:`time` is :func:`time.sleep` to yield instead of block the thread. """ __time = __import__('time') from ..patcher import slurp_properties __patched__ = ['sleep'] slurp_properties(__time, globals(), ignore=__patched__, srckeys=dir(__time)) from .. import greenthread sleep = greenthread.sleep
3a0b65b6698eea40c949a11e733a7f0337fe6e11
kolibri/plugins/app/utils.py
kolibri/plugins/app/utils.py
from kolibri.plugins.app.kolibri_plugin import App from kolibri.plugins.registry import registered_plugins SHARE_FILE = "share_file" CAPABILITES = (SHARE_FILE,) class AppInterface(object): __slot__ = "_capabilities" def __init__(self): self._capabilities = {} def __contains__(self, capability): return capability in self._capabilities def register(self, **kwargs): for capability in CAPABILITES: if capability in kwargs: self._capabilities[capability] = kwargs[capability] @property def enabled(self): return App in registered_plugins @property def capabilities(self): if self.enabled: return {key: (key in self._capabilities) for key in CAPABILITES} return {key: False for key in CAPABILITES} def share_file(self, filename, message): if SHARE_FILE not in self._capabilities: raise NotImplementedError("Sharing files is not supported on this platform") return self._capabilities[SHARE_FILE](filename=filename, message=message) interface = AppInterface()
from django.core.urlresolvers import reverse from kolibri.plugins.app.kolibri_plugin import App from kolibri.plugins.registry import registered_plugins SHARE_FILE = "share_file" CAPABILITES = (SHARE_FILE,) class AppInterface(object): __slot__ = "_capabilities" def __init__(self): self._capabilities = {} def __contains__(self, capability): return capability in self._capabilities def register(self, **kwargs): for capability in CAPABILITES: if capability in kwargs: self._capabilities[capability] = kwargs[capability] def get_initialize_url(self, next_url=None): if not self.enabled: raise RuntimeError("App plugin is not enabled") # Import here to prevent a circular import from kolibri.core.device.models import DeviceAppKey url = reverse( "kolibri:kolibri.plugins.app:initialize", args=(DeviceAppKey.get_app_key(),) ) if next_url is None: return url return url + "?next={}".format(next_url) @property def enabled(self): return App in registered_plugins @property def capabilities(self): if self.enabled: return {key: (key in self._capabilities) for key in CAPABILITES} return {key: False for key in CAPABILITES} def share_file(self, filename, message): if SHARE_FILE not in self._capabilities: raise NotImplementedError("Sharing files is not supported on this platform") return self._capabilities[SHARE_FILE](filename=filename, message=message) interface = AppInterface()
Add method to get initialize url.
Add method to get initialize url.
Python
mit
indirectlylit/kolibri,learningequality/kolibri,indirectlylit/kolibri,indirectlylit/kolibri,indirectlylit/kolibri,learningequality/kolibri,learningequality/kolibri,learningequality/kolibri
from kolibri.plugins.app.kolibri_plugin import App from kolibri.plugins.registry import registered_plugins SHARE_FILE = "share_file" CAPABILITES = (SHARE_FILE,) class AppInterface(object): __slot__ = "_capabilities" def __init__(self): self._capabilities = {} def __contains__(self, capability): return capability in self._capabilities def register(self, **kwargs): for capability in CAPABILITES: if capability in kwargs: self._capabilities[capability] = kwargs[capability] @property def enabled(self): return App in registered_plugins @property def capabilities(self): if self.enabled: return {key: (key in self._capabilities) for key in CAPABILITES} return {key: False for key in CAPABILITES} def share_file(self, filename, message): if SHARE_FILE not in self._capabilities: raise NotImplementedError("Sharing files is not supported on this platform") return self._capabilities[SHARE_FILE](filename=filename, message=message) interface = AppInterface() Add method to get initialize url.
from django.core.urlresolvers import reverse from kolibri.plugins.app.kolibri_plugin import App from kolibri.plugins.registry import registered_plugins SHARE_FILE = "share_file" CAPABILITES = (SHARE_FILE,) class AppInterface(object): __slot__ = "_capabilities" def __init__(self): self._capabilities = {} def __contains__(self, capability): return capability in self._capabilities def register(self, **kwargs): for capability in CAPABILITES: if capability in kwargs: self._capabilities[capability] = kwargs[capability] def get_initialize_url(self, next_url=None): if not self.enabled: raise RuntimeError("App plugin is not enabled") # Import here to prevent a circular import from kolibri.core.device.models import DeviceAppKey url = reverse( "kolibri:kolibri.plugins.app:initialize", args=(DeviceAppKey.get_app_key(),) ) if next_url is None: return url return url + "?next={}".format(next_url) @property def enabled(self): return App in registered_plugins @property def capabilities(self): if self.enabled: return {key: (key in self._capabilities) for key in CAPABILITES} return {key: False for key in CAPABILITES} def share_file(self, filename, message): if SHARE_FILE not in self._capabilities: raise NotImplementedError("Sharing files is not supported on this platform") return self._capabilities[SHARE_FILE](filename=filename, message=message) interface = AppInterface()
<commit_before>from kolibri.plugins.app.kolibri_plugin import App from kolibri.plugins.registry import registered_plugins SHARE_FILE = "share_file" CAPABILITES = (SHARE_FILE,) class AppInterface(object): __slot__ = "_capabilities" def __init__(self): self._capabilities = {} def __contains__(self, capability): return capability in self._capabilities def register(self, **kwargs): for capability in CAPABILITES: if capability in kwargs: self._capabilities[capability] = kwargs[capability] @property def enabled(self): return App in registered_plugins @property def capabilities(self): if self.enabled: return {key: (key in self._capabilities) for key in CAPABILITES} return {key: False for key in CAPABILITES} def share_file(self, filename, message): if SHARE_FILE not in self._capabilities: raise NotImplementedError("Sharing files is not supported on this platform") return self._capabilities[SHARE_FILE](filename=filename, message=message) interface = AppInterface() <commit_msg>Add method to get initialize url.<commit_after>
from django.core.urlresolvers import reverse from kolibri.plugins.app.kolibri_plugin import App from kolibri.plugins.registry import registered_plugins SHARE_FILE = "share_file" CAPABILITES = (SHARE_FILE,) class AppInterface(object): __slot__ = "_capabilities" def __init__(self): self._capabilities = {} def __contains__(self, capability): return capability in self._capabilities def register(self, **kwargs): for capability in CAPABILITES: if capability in kwargs: self._capabilities[capability] = kwargs[capability] def get_initialize_url(self, next_url=None): if not self.enabled: raise RuntimeError("App plugin is not enabled") # Import here to prevent a circular import from kolibri.core.device.models import DeviceAppKey url = reverse( "kolibri:kolibri.plugins.app:initialize", args=(DeviceAppKey.get_app_key(),) ) if next_url is None: return url return url + "?next={}".format(next_url) @property def enabled(self): return App in registered_plugins @property def capabilities(self): if self.enabled: return {key: (key in self._capabilities) for key in CAPABILITES} return {key: False for key in CAPABILITES} def share_file(self, filename, message): if SHARE_FILE not in self._capabilities: raise NotImplementedError("Sharing files is not supported on this platform") return self._capabilities[SHARE_FILE](filename=filename, message=message) interface = AppInterface()
from kolibri.plugins.app.kolibri_plugin import App from kolibri.plugins.registry import registered_plugins SHARE_FILE = "share_file" CAPABILITES = (SHARE_FILE,) class AppInterface(object): __slot__ = "_capabilities" def __init__(self): self._capabilities = {} def __contains__(self, capability): return capability in self._capabilities def register(self, **kwargs): for capability in CAPABILITES: if capability in kwargs: self._capabilities[capability] = kwargs[capability] @property def enabled(self): return App in registered_plugins @property def capabilities(self): if self.enabled: return {key: (key in self._capabilities) for key in CAPABILITES} return {key: False for key in CAPABILITES} def share_file(self, filename, message): if SHARE_FILE not in self._capabilities: raise NotImplementedError("Sharing files is not supported on this platform") return self._capabilities[SHARE_FILE](filename=filename, message=message) interface = AppInterface() Add method to get initialize url.from django.core.urlresolvers import reverse from kolibri.plugins.app.kolibri_plugin import App from kolibri.plugins.registry import registered_plugins SHARE_FILE = "share_file" CAPABILITES = (SHARE_FILE,) class AppInterface(object): __slot__ = "_capabilities" def __init__(self): self._capabilities = {} def __contains__(self, capability): return capability in self._capabilities def register(self, **kwargs): for capability in CAPABILITES: if capability in kwargs: self._capabilities[capability] = kwargs[capability] def get_initialize_url(self, next_url=None): if not self.enabled: raise RuntimeError("App plugin is not enabled") # Import here to prevent a circular import from kolibri.core.device.models import DeviceAppKey url = reverse( "kolibri:kolibri.plugins.app:initialize", args=(DeviceAppKey.get_app_key(),) ) if next_url is None: return url return url + "?next={}".format(next_url) @property def enabled(self): return App in registered_plugins @property def capabilities(self): if self.enabled: return {key: (key in self._capabilities) for key in CAPABILITES} return {key: False for key in CAPABILITES} def share_file(self, filename, message): if SHARE_FILE not in self._capabilities: raise NotImplementedError("Sharing files is not supported on this platform") return self._capabilities[SHARE_FILE](filename=filename, message=message) interface = AppInterface()
<commit_before>from kolibri.plugins.app.kolibri_plugin import App from kolibri.plugins.registry import registered_plugins SHARE_FILE = "share_file" CAPABILITES = (SHARE_FILE,) class AppInterface(object): __slot__ = "_capabilities" def __init__(self): self._capabilities = {} def __contains__(self, capability): return capability in self._capabilities def register(self, **kwargs): for capability in CAPABILITES: if capability in kwargs: self._capabilities[capability] = kwargs[capability] @property def enabled(self): return App in registered_plugins @property def capabilities(self): if self.enabled: return {key: (key in self._capabilities) for key in CAPABILITES} return {key: False for key in CAPABILITES} def share_file(self, filename, message): if SHARE_FILE not in self._capabilities: raise NotImplementedError("Sharing files is not supported on this platform") return self._capabilities[SHARE_FILE](filename=filename, message=message) interface = AppInterface() <commit_msg>Add method to get initialize url.<commit_after>from django.core.urlresolvers import reverse from kolibri.plugins.app.kolibri_plugin import App from kolibri.plugins.registry import registered_plugins SHARE_FILE = "share_file" CAPABILITES = (SHARE_FILE,) class AppInterface(object): __slot__ = "_capabilities" def __init__(self): self._capabilities = {} def __contains__(self, capability): return capability in self._capabilities def register(self, **kwargs): for capability in CAPABILITES: if capability in kwargs: self._capabilities[capability] = kwargs[capability] def get_initialize_url(self, next_url=None): if not self.enabled: raise RuntimeError("App plugin is not enabled") # Import here to prevent a circular import from kolibri.core.device.models import DeviceAppKey url = reverse( "kolibri:kolibri.plugins.app:initialize", args=(DeviceAppKey.get_app_key(),) ) if next_url is None: return url return url + "?next={}".format(next_url) @property def enabled(self): return App in registered_plugins @property def capabilities(self): if self.enabled: return {key: (key in self._capabilities) for key in CAPABILITES} return {key: False for key in CAPABILITES} def share_file(self, filename, message): if SHARE_FILE not in self._capabilities: raise NotImplementedError("Sharing files is not supported on this platform") return self._capabilities[SHARE_FILE](filename=filename, message=message) interface = AppInterface()
c269debb2819db246483551d512c33b784bbfd22
test.py
test.py
print "----- import lua -----" import lua print "----- lg = lua.globals() -----" lg = lua.globals() print "----- lg.foo = \"bar\" -----" lg.foo = 'bar' print "----- lg.tmp = [] -----" lg.tmp = [] print "----- print lg.tmp -----" print lg.tmp print "----- lua.execute(\"xxx = {1,2,3,foo={4,5}}\") -----" lua.execute("xxx = {1,2,3,foo={4,5}}") print "----- print lg.xxx[1] -----" print lg.xxx[1] print "----- print lg.xxx[2] -----" print lg.xxx[2] print "----- print lg.xxx[3] -----" print lg.xxx[3] print "----- print lg.xxx['foo'][1] -----" print lg.xxx['foo'][1]
print "----- import lua -----" import lua print "----- lg = lua.globals() -----" lg = lua.globals() print "lg:", lg print "lg._G:", lg._G print "lg['_G']:", lg['_G'] print "----- lg.foo = \"bar\" -----" lg.foo = 'bar' print "----- lg.tmp = [] -----" lg.tmp = [] print "----- print lg.tmp -----" print lg.tmp print "----- lua.execute(\"xxx = {1,2,3,foo={4,5}}\") -----" lua.execute("xxx = {1,2,3,foo={4,5}}") print "----- print lg.xxx[1] -----" print lg.xxx[1] print "----- print lg.xxx[2] -----" print lg.xxx[2] print "----- print lg.xxx[3] -----" print lg.xxx[3] print "----- print lg.xxx['foo'][1] -----" print lg.xxx['foo'][1] print "lua.require =", lua.require try: lua.require("foo") except: print "lua.require('foo') raised an exception"
Test Lua's globals() and require() from Python
Test Lua's globals() and require() from Python
Python
lgpl-2.1
albanD/lunatic-python,bastibe/lunatic-python,bastibe/lunatic-python,greatwolf/lunatic-python,alexsilva/lunatic-python,greatwolf/lunatic-python,hughperkins/lunatic-python,alexsilva/lunatic-python,hughperkins/lunatic-python,alexsilva/lunatic-python,albanD/lunatic-python
print "----- import lua -----" import lua print "----- lg = lua.globals() -----" lg = lua.globals() print "----- lg.foo = \"bar\" -----" lg.foo = 'bar' print "----- lg.tmp = [] -----" lg.tmp = [] print "----- print lg.tmp -----" print lg.tmp print "----- lua.execute(\"xxx = {1,2,3,foo={4,5}}\") -----" lua.execute("xxx = {1,2,3,foo={4,5}}") print "----- print lg.xxx[1] -----" print lg.xxx[1] print "----- print lg.xxx[2] -----" print lg.xxx[2] print "----- print lg.xxx[3] -----" print lg.xxx[3] print "----- print lg.xxx['foo'][1] -----" print lg.xxx['foo'][1] Test Lua's globals() and require() from Python
print "----- import lua -----" import lua print "----- lg = lua.globals() -----" lg = lua.globals() print "lg:", lg print "lg._G:", lg._G print "lg['_G']:", lg['_G'] print "----- lg.foo = \"bar\" -----" lg.foo = 'bar' print "----- lg.tmp = [] -----" lg.tmp = [] print "----- print lg.tmp -----" print lg.tmp print "----- lua.execute(\"xxx = {1,2,3,foo={4,5}}\") -----" lua.execute("xxx = {1,2,3,foo={4,5}}") print "----- print lg.xxx[1] -----" print lg.xxx[1] print "----- print lg.xxx[2] -----" print lg.xxx[2] print "----- print lg.xxx[3] -----" print lg.xxx[3] print "----- print lg.xxx['foo'][1] -----" print lg.xxx['foo'][1] print "lua.require =", lua.require try: lua.require("foo") except: print "lua.require('foo') raised an exception"
<commit_before>print "----- import lua -----" import lua print "----- lg = lua.globals() -----" lg = lua.globals() print "----- lg.foo = \"bar\" -----" lg.foo = 'bar' print "----- lg.tmp = [] -----" lg.tmp = [] print "----- print lg.tmp -----" print lg.tmp print "----- lua.execute(\"xxx = {1,2,3,foo={4,5}}\") -----" lua.execute("xxx = {1,2,3,foo={4,5}}") print "----- print lg.xxx[1] -----" print lg.xxx[1] print "----- print lg.xxx[2] -----" print lg.xxx[2] print "----- print lg.xxx[3] -----" print lg.xxx[3] print "----- print lg.xxx['foo'][1] -----" print lg.xxx['foo'][1] <commit_msg>Test Lua's globals() and require() from Python<commit_after>
print "----- import lua -----" import lua print "----- lg = lua.globals() -----" lg = lua.globals() print "lg:", lg print "lg._G:", lg._G print "lg['_G']:", lg['_G'] print "----- lg.foo = \"bar\" -----" lg.foo = 'bar' print "----- lg.tmp = [] -----" lg.tmp = [] print "----- print lg.tmp -----" print lg.tmp print "----- lua.execute(\"xxx = {1,2,3,foo={4,5}}\") -----" lua.execute("xxx = {1,2,3,foo={4,5}}") print "----- print lg.xxx[1] -----" print lg.xxx[1] print "----- print lg.xxx[2] -----" print lg.xxx[2] print "----- print lg.xxx[3] -----" print lg.xxx[3] print "----- print lg.xxx['foo'][1] -----" print lg.xxx['foo'][1] print "lua.require =", lua.require try: lua.require("foo") except: print "lua.require('foo') raised an exception"
print "----- import lua -----" import lua print "----- lg = lua.globals() -----" lg = lua.globals() print "----- lg.foo = \"bar\" -----" lg.foo = 'bar' print "----- lg.tmp = [] -----" lg.tmp = [] print "----- print lg.tmp -----" print lg.tmp print "----- lua.execute(\"xxx = {1,2,3,foo={4,5}}\") -----" lua.execute("xxx = {1,2,3,foo={4,5}}") print "----- print lg.xxx[1] -----" print lg.xxx[1] print "----- print lg.xxx[2] -----" print lg.xxx[2] print "----- print lg.xxx[3] -----" print lg.xxx[3] print "----- print lg.xxx['foo'][1] -----" print lg.xxx['foo'][1] Test Lua's globals() and require() from Pythonprint "----- import lua -----" import lua print "----- lg = lua.globals() -----" lg = lua.globals() print "lg:", lg print "lg._G:", lg._G print "lg['_G']:", lg['_G'] print "----- lg.foo = \"bar\" -----" lg.foo = 'bar' print "----- lg.tmp = [] -----" lg.tmp = [] print "----- print lg.tmp -----" print lg.tmp print "----- lua.execute(\"xxx = {1,2,3,foo={4,5}}\") -----" lua.execute("xxx = {1,2,3,foo={4,5}}") print "----- print lg.xxx[1] -----" print lg.xxx[1] print "----- print lg.xxx[2] -----" print lg.xxx[2] print "----- print lg.xxx[3] -----" print lg.xxx[3] print "----- print lg.xxx['foo'][1] -----" print lg.xxx['foo'][1] print "lua.require =", lua.require try: lua.require("foo") except: print "lua.require('foo') raised an exception"
<commit_before>print "----- import lua -----" import lua print "----- lg = lua.globals() -----" lg = lua.globals() print "----- lg.foo = \"bar\" -----" lg.foo = 'bar' print "----- lg.tmp = [] -----" lg.tmp = [] print "----- print lg.tmp -----" print lg.tmp print "----- lua.execute(\"xxx = {1,2,3,foo={4,5}}\") -----" lua.execute("xxx = {1,2,3,foo={4,5}}") print "----- print lg.xxx[1] -----" print lg.xxx[1] print "----- print lg.xxx[2] -----" print lg.xxx[2] print "----- print lg.xxx[3] -----" print lg.xxx[3] print "----- print lg.xxx['foo'][1] -----" print lg.xxx['foo'][1] <commit_msg>Test Lua's globals() and require() from Python<commit_after>print "----- import lua -----" import lua print "----- lg = lua.globals() -----" lg = lua.globals() print "lg:", lg print "lg._G:", lg._G print "lg['_G']:", lg['_G'] print "----- lg.foo = \"bar\" -----" lg.foo = 'bar' print "----- lg.tmp = [] -----" lg.tmp = [] print "----- print lg.tmp -----" print lg.tmp print "----- lua.execute(\"xxx = {1,2,3,foo={4,5}}\") -----" lua.execute("xxx = {1,2,3,foo={4,5}}") print "----- print lg.xxx[1] -----" print lg.xxx[1] print "----- print lg.xxx[2] -----" print lg.xxx[2] print "----- print lg.xxx[3] -----" print lg.xxx[3] print "----- print lg.xxx['foo'][1] -----" print lg.xxx['foo'][1] print "lua.require =", lua.require try: lua.require("foo") except: print "lua.require('foo') raised an exception"
33e1b3e5fd5e9985f57cf83545c0b9053f8b9e4d
trex/urls.py
trex/urls.py
# -*- coding: utf-8 -*- # # (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com> # # See LICENSE comming with the source of 'trex' for details. # from django.conf.urls import patterns, include, url from django.contrib import admin from trex.views.project import ( ProjectListCreateAPIView, ProjectDetailAPIView) urlpatterns = patterns( '', url(r"^admin/", include(admin.site.urls)), url(r"^projects/$", ProjectListCreateAPIView.as_view(), name="project-list"), url(r"^projects/(?P<pk>[0-9]+)/$", ProjectDetailAPIView.as_view(), name="project-details"), )
# -*- coding: utf-8 -*- # # (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com> # # See LICENSE comming with the source of 'trex' for details. # from django.conf.urls import patterns, include, url from django.contrib import admin from trex.views.project import ( ProjectListCreateAPIView, ProjectDetailAPIView) urlpatterns = patterns( '', url(r"^admin/", include(admin.site.urls)), url(r"^projects/$", ProjectListCreateAPIView.as_view(), name="project-list"), url(r"^projects/(?P<pk>[0-9]+)/$", ProjectDetailAPIView.as_view(), name="project-detail"), )
Use standard view name for project details
Use standard view name for project details restframework by default user <modelname>-detail as view name for detail model api views.
Python
mit
bjoernricks/trex,bjoernricks/trex
# -*- coding: utf-8 -*- # # (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com> # # See LICENSE comming with the source of 'trex' for details. # from django.conf.urls import patterns, include, url from django.contrib import admin from trex.views.project import ( ProjectListCreateAPIView, ProjectDetailAPIView) urlpatterns = patterns( '', url(r"^admin/", include(admin.site.urls)), url(r"^projects/$", ProjectListCreateAPIView.as_view(), name="project-list"), url(r"^projects/(?P<pk>[0-9]+)/$", ProjectDetailAPIView.as_view(), name="project-details"), ) Use standard view name for project details restframework by default user <modelname>-detail as view name for detail model api views.
# -*- coding: utf-8 -*- # # (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com> # # See LICENSE comming with the source of 'trex' for details. # from django.conf.urls import patterns, include, url from django.contrib import admin from trex.views.project import ( ProjectListCreateAPIView, ProjectDetailAPIView) urlpatterns = patterns( '', url(r"^admin/", include(admin.site.urls)), url(r"^projects/$", ProjectListCreateAPIView.as_view(), name="project-list"), url(r"^projects/(?P<pk>[0-9]+)/$", ProjectDetailAPIView.as_view(), name="project-detail"), )
<commit_before># -*- coding: utf-8 -*- # # (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com> # # See LICENSE comming with the source of 'trex' for details. # from django.conf.urls import patterns, include, url from django.contrib import admin from trex.views.project import ( ProjectListCreateAPIView, ProjectDetailAPIView) urlpatterns = patterns( '', url(r"^admin/", include(admin.site.urls)), url(r"^projects/$", ProjectListCreateAPIView.as_view(), name="project-list"), url(r"^projects/(?P<pk>[0-9]+)/$", ProjectDetailAPIView.as_view(), name="project-details"), ) <commit_msg>Use standard view name for project details restframework by default user <modelname>-detail as view name for detail model api views.<commit_after>
# -*- coding: utf-8 -*- # # (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com> # # See LICENSE comming with the source of 'trex' for details. # from django.conf.urls import patterns, include, url from django.contrib import admin from trex.views.project import ( ProjectListCreateAPIView, ProjectDetailAPIView) urlpatterns = patterns( '', url(r"^admin/", include(admin.site.urls)), url(r"^projects/$", ProjectListCreateAPIView.as_view(), name="project-list"), url(r"^projects/(?P<pk>[0-9]+)/$", ProjectDetailAPIView.as_view(), name="project-detail"), )
# -*- coding: utf-8 -*- # # (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com> # # See LICENSE comming with the source of 'trex' for details. # from django.conf.urls import patterns, include, url from django.contrib import admin from trex.views.project import ( ProjectListCreateAPIView, ProjectDetailAPIView) urlpatterns = patterns( '', url(r"^admin/", include(admin.site.urls)), url(r"^projects/$", ProjectListCreateAPIView.as_view(), name="project-list"), url(r"^projects/(?P<pk>[0-9]+)/$", ProjectDetailAPIView.as_view(), name="project-details"), ) Use standard view name for project details restframework by default user <modelname>-detail as view name for detail model api views.# -*- coding: utf-8 -*- # # (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com> # # See LICENSE comming with the source of 'trex' for details. # from django.conf.urls import patterns, include, url from django.contrib import admin from trex.views.project import ( ProjectListCreateAPIView, ProjectDetailAPIView) urlpatterns = patterns( '', url(r"^admin/", include(admin.site.urls)), url(r"^projects/$", ProjectListCreateAPIView.as_view(), name="project-list"), url(r"^projects/(?P<pk>[0-9]+)/$", ProjectDetailAPIView.as_view(), name="project-detail"), )
<commit_before># -*- coding: utf-8 -*- # # (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com> # # See LICENSE comming with the source of 'trex' for details. # from django.conf.urls import patterns, include, url from django.contrib import admin from trex.views.project import ( ProjectListCreateAPIView, ProjectDetailAPIView) urlpatterns = patterns( '', url(r"^admin/", include(admin.site.urls)), url(r"^projects/$", ProjectListCreateAPIView.as_view(), name="project-list"), url(r"^projects/(?P<pk>[0-9]+)/$", ProjectDetailAPIView.as_view(), name="project-details"), ) <commit_msg>Use standard view name for project details restframework by default user <modelname>-detail as view name for detail model api views.<commit_after># -*- coding: utf-8 -*- # # (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com> # # See LICENSE comming with the source of 'trex' for details. # from django.conf.urls import patterns, include, url from django.contrib import admin from trex.views.project import ( ProjectListCreateAPIView, ProjectDetailAPIView) urlpatterns = patterns( '', url(r"^admin/", include(admin.site.urls)), url(r"^projects/$", ProjectListCreateAPIView.as_view(), name="project-list"), url(r"^projects/(?P<pk>[0-9]+)/$", ProjectDetailAPIView.as_view(), name="project-detail"), )
551325699aa1554b589b008f6bebdf2dfd1e1405
test/expression_command/radar_9531204/TestPrintfAfterUp.py
test/expression_command/radar_9531204/TestPrintfAfterUp.py
""" The evaluating printf(...) after break stop and then up a stack frame. """ import os, time import unittest2 import lldb from lldbtest import * class Radar9531204TestCase(TestBase): mydir = os.path.join("expression_command", "radar_9531204") # rdar://problem/9531204 @unittest2.expectedFailure def test_expr_commands(self): """The evaluating printf(...) after break stop and then up a stack frame.""" self.buildDefault() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) self.expect("breakpoint set -n foo", BREAKPOINT_CREATED, startstr = "Breakpoint created: 1: name = 'foo', locations = 1") self.runCmd("run", RUN_SUCCEEDED) self.runCmd("frame variable") # This works fine. self.runCmd('expression (int)printf("value is: %d.\\n", value);') # rdar://problem/9531204 # "Error dematerializing struct" error when evaluating expressions "up" on the stack self.runCmd('up') # frame select -r 1 self.runCmd("frame variable") # This does not currently. self.runCmd('expression (int)printf("argc is: %d.\\n", argc)') if __name__ == '__main__': import atexit lldb.SBDebugger.Initialize() atexit.register(lambda: lldb.SBDebugger.Terminate()) unittest2.main()
""" The evaluating printf(...) after break stop and then up a stack frame. """ import os, time import unittest2 import lldb from lldbtest import * class Radar9531204TestCase(TestBase): mydir = os.path.join("expression_command", "radar_9531204") # rdar://problem/9531204 def test_expr_commands(self): """The evaluating printf(...) after break stop and then up a stack frame.""" self.buildDefault() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) self.expect("breakpoint set -n foo", BREAKPOINT_CREATED, startstr = "Breakpoint created: 1: name = 'foo', locations = 1") self.runCmd("run", RUN_SUCCEEDED) self.runCmd("frame variable") # This works fine. self.runCmd('expression (int)printf("value is: %d.\\n", value);') # rdar://problem/9531204 # "Error dematerializing struct" error when evaluating expressions "up" on the stack self.runCmd('up') # frame select -r 1 self.runCmd("frame variable") # This does not currently. self.runCmd('expression (int)printf("argc is: %d.\\n", argc)') if __name__ == '__main__': import atexit lldb.SBDebugger.Initialize() atexit.register(lambda: lldb.SBDebugger.Terminate()) unittest2.main()
Remove the expectedFailure decorator. The test has been passing for some time now.
Remove the expectedFailure decorator. The test has been passing for some time now. git-svn-id: b33bab8abb5b18c12ee100cd7761ab452d00b2b0@138452 91177308-0d34-0410-b5e6-96231b3b80d8
Python
apache-2.0
llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb
""" The evaluating printf(...) after break stop and then up a stack frame. """ import os, time import unittest2 import lldb from lldbtest import * class Radar9531204TestCase(TestBase): mydir = os.path.join("expression_command", "radar_9531204") # rdar://problem/9531204 @unittest2.expectedFailure def test_expr_commands(self): """The evaluating printf(...) after break stop and then up a stack frame.""" self.buildDefault() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) self.expect("breakpoint set -n foo", BREAKPOINT_CREATED, startstr = "Breakpoint created: 1: name = 'foo', locations = 1") self.runCmd("run", RUN_SUCCEEDED) self.runCmd("frame variable") # This works fine. self.runCmd('expression (int)printf("value is: %d.\\n", value);') # rdar://problem/9531204 # "Error dematerializing struct" error when evaluating expressions "up" on the stack self.runCmd('up') # frame select -r 1 self.runCmd("frame variable") # This does not currently. self.runCmd('expression (int)printf("argc is: %d.\\n", argc)') if __name__ == '__main__': import atexit lldb.SBDebugger.Initialize() atexit.register(lambda: lldb.SBDebugger.Terminate()) unittest2.main() Remove the expectedFailure decorator. The test has been passing for some time now. git-svn-id: b33bab8abb5b18c12ee100cd7761ab452d00b2b0@138452 91177308-0d34-0410-b5e6-96231b3b80d8
""" The evaluating printf(...) after break stop and then up a stack frame. """ import os, time import unittest2 import lldb from lldbtest import * class Radar9531204TestCase(TestBase): mydir = os.path.join("expression_command", "radar_9531204") # rdar://problem/9531204 def test_expr_commands(self): """The evaluating printf(...) after break stop and then up a stack frame.""" self.buildDefault() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) self.expect("breakpoint set -n foo", BREAKPOINT_CREATED, startstr = "Breakpoint created: 1: name = 'foo', locations = 1") self.runCmd("run", RUN_SUCCEEDED) self.runCmd("frame variable") # This works fine. self.runCmd('expression (int)printf("value is: %d.\\n", value);') # rdar://problem/9531204 # "Error dematerializing struct" error when evaluating expressions "up" on the stack self.runCmd('up') # frame select -r 1 self.runCmd("frame variable") # This does not currently. self.runCmd('expression (int)printf("argc is: %d.\\n", argc)') if __name__ == '__main__': import atexit lldb.SBDebugger.Initialize() atexit.register(lambda: lldb.SBDebugger.Terminate()) unittest2.main()
<commit_before>""" The evaluating printf(...) after break stop and then up a stack frame. """ import os, time import unittest2 import lldb from lldbtest import * class Radar9531204TestCase(TestBase): mydir = os.path.join("expression_command", "radar_9531204") # rdar://problem/9531204 @unittest2.expectedFailure def test_expr_commands(self): """The evaluating printf(...) after break stop and then up a stack frame.""" self.buildDefault() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) self.expect("breakpoint set -n foo", BREAKPOINT_CREATED, startstr = "Breakpoint created: 1: name = 'foo', locations = 1") self.runCmd("run", RUN_SUCCEEDED) self.runCmd("frame variable") # This works fine. self.runCmd('expression (int)printf("value is: %d.\\n", value);') # rdar://problem/9531204 # "Error dematerializing struct" error when evaluating expressions "up" on the stack self.runCmd('up') # frame select -r 1 self.runCmd("frame variable") # This does not currently. self.runCmd('expression (int)printf("argc is: %d.\\n", argc)') if __name__ == '__main__': import atexit lldb.SBDebugger.Initialize() atexit.register(lambda: lldb.SBDebugger.Terminate()) unittest2.main() <commit_msg>Remove the expectedFailure decorator. The test has been passing for some time now. git-svn-id: b33bab8abb5b18c12ee100cd7761ab452d00b2b0@138452 91177308-0d34-0410-b5e6-96231b3b80d8<commit_after>
""" The evaluating printf(...) after break stop and then up a stack frame. """ import os, time import unittest2 import lldb from lldbtest import * class Radar9531204TestCase(TestBase): mydir = os.path.join("expression_command", "radar_9531204") # rdar://problem/9531204 def test_expr_commands(self): """The evaluating printf(...) after break stop and then up a stack frame.""" self.buildDefault() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) self.expect("breakpoint set -n foo", BREAKPOINT_CREATED, startstr = "Breakpoint created: 1: name = 'foo', locations = 1") self.runCmd("run", RUN_SUCCEEDED) self.runCmd("frame variable") # This works fine. self.runCmd('expression (int)printf("value is: %d.\\n", value);') # rdar://problem/9531204 # "Error dematerializing struct" error when evaluating expressions "up" on the stack self.runCmd('up') # frame select -r 1 self.runCmd("frame variable") # This does not currently. self.runCmd('expression (int)printf("argc is: %d.\\n", argc)') if __name__ == '__main__': import atexit lldb.SBDebugger.Initialize() atexit.register(lambda: lldb.SBDebugger.Terminate()) unittest2.main()
""" The evaluating printf(...) after break stop and then up a stack frame. """ import os, time import unittest2 import lldb from lldbtest import * class Radar9531204TestCase(TestBase): mydir = os.path.join("expression_command", "radar_9531204") # rdar://problem/9531204 @unittest2.expectedFailure def test_expr_commands(self): """The evaluating printf(...) after break stop and then up a stack frame.""" self.buildDefault() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) self.expect("breakpoint set -n foo", BREAKPOINT_CREATED, startstr = "Breakpoint created: 1: name = 'foo', locations = 1") self.runCmd("run", RUN_SUCCEEDED) self.runCmd("frame variable") # This works fine. self.runCmd('expression (int)printf("value is: %d.\\n", value);') # rdar://problem/9531204 # "Error dematerializing struct" error when evaluating expressions "up" on the stack self.runCmd('up') # frame select -r 1 self.runCmd("frame variable") # This does not currently. self.runCmd('expression (int)printf("argc is: %d.\\n", argc)') if __name__ == '__main__': import atexit lldb.SBDebugger.Initialize() atexit.register(lambda: lldb.SBDebugger.Terminate()) unittest2.main() Remove the expectedFailure decorator. The test has been passing for some time now. git-svn-id: b33bab8abb5b18c12ee100cd7761ab452d00b2b0@138452 91177308-0d34-0410-b5e6-96231b3b80d8""" The evaluating printf(...) after break stop and then up a stack frame. """ import os, time import unittest2 import lldb from lldbtest import * class Radar9531204TestCase(TestBase): mydir = os.path.join("expression_command", "radar_9531204") # rdar://problem/9531204 def test_expr_commands(self): """The evaluating printf(...) after break stop and then up a stack frame.""" self.buildDefault() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) self.expect("breakpoint set -n foo", BREAKPOINT_CREATED, startstr = "Breakpoint created: 1: name = 'foo', locations = 1") self.runCmd("run", RUN_SUCCEEDED) self.runCmd("frame variable") # This works fine. self.runCmd('expression (int)printf("value is: %d.\\n", value);') # rdar://problem/9531204 # "Error dematerializing struct" error when evaluating expressions "up" on the stack self.runCmd('up') # frame select -r 1 self.runCmd("frame variable") # This does not currently. self.runCmd('expression (int)printf("argc is: %d.\\n", argc)') if __name__ == '__main__': import atexit lldb.SBDebugger.Initialize() atexit.register(lambda: lldb.SBDebugger.Terminate()) unittest2.main()
<commit_before>""" The evaluating printf(...) after break stop and then up a stack frame. """ import os, time import unittest2 import lldb from lldbtest import * class Radar9531204TestCase(TestBase): mydir = os.path.join("expression_command", "radar_9531204") # rdar://problem/9531204 @unittest2.expectedFailure def test_expr_commands(self): """The evaluating printf(...) after break stop and then up a stack frame.""" self.buildDefault() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) self.expect("breakpoint set -n foo", BREAKPOINT_CREATED, startstr = "Breakpoint created: 1: name = 'foo', locations = 1") self.runCmd("run", RUN_SUCCEEDED) self.runCmd("frame variable") # This works fine. self.runCmd('expression (int)printf("value is: %d.\\n", value);') # rdar://problem/9531204 # "Error dematerializing struct" error when evaluating expressions "up" on the stack self.runCmd('up') # frame select -r 1 self.runCmd("frame variable") # This does not currently. self.runCmd('expression (int)printf("argc is: %d.\\n", argc)') if __name__ == '__main__': import atexit lldb.SBDebugger.Initialize() atexit.register(lambda: lldb.SBDebugger.Terminate()) unittest2.main() <commit_msg>Remove the expectedFailure decorator. The test has been passing for some time now. git-svn-id: b33bab8abb5b18c12ee100cd7761ab452d00b2b0@138452 91177308-0d34-0410-b5e6-96231b3b80d8<commit_after>""" The evaluating printf(...) after break stop and then up a stack frame. """ import os, time import unittest2 import lldb from lldbtest import * class Radar9531204TestCase(TestBase): mydir = os.path.join("expression_command", "radar_9531204") # rdar://problem/9531204 def test_expr_commands(self): """The evaluating printf(...) after break stop and then up a stack frame.""" self.buildDefault() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) self.expect("breakpoint set -n foo", BREAKPOINT_CREATED, startstr = "Breakpoint created: 1: name = 'foo', locations = 1") self.runCmd("run", RUN_SUCCEEDED) self.runCmd("frame variable") # This works fine. self.runCmd('expression (int)printf("value is: %d.\\n", value);') # rdar://problem/9531204 # "Error dematerializing struct" error when evaluating expressions "up" on the stack self.runCmd('up') # frame select -r 1 self.runCmd("frame variable") # This does not currently. self.runCmd('expression (int)printf("argc is: %d.\\n", argc)') if __name__ == '__main__': import atexit lldb.SBDebugger.Initialize() atexit.register(lambda: lldb.SBDebugger.Terminate()) unittest2.main()
e14a92e26fe3a8fd14617a57dbf3d4630ba1e50b
impala_udt.py
impala_udt.py
""" A simple demonstration of Impala UDF generation. """ from numba.ext.impala import udf, IntVal, FunctionContext @udf(IntVal(FunctionContext, IntVal, IntVal)) def add_udf(context, arg1, arg2): if arg1.is_null or arg2.is_null: return IntVal.null return IntVal(arg1.val + arg2.val) # Simply print the module IR print(add_udf.llvm_module)
""" A simple demonstration of Impala UDF generation. """ from numba.ext.impala import (udf, IntVal, FunctionContext, BooleanVal, DoubleVal, TinyIntVal) @udf(IntVal(FunctionContext, IntVal, IntVal)) def add_udf(context, arg1, arg2): if arg1.is_null or arg2.is_null: return IntVal.null return IntVal(arg1.val + arg2.val) # Simply print the module IR print(add_udf.llvm_module) @udf(BooleanVal(FunctionContext, DoubleVal, TinyIntVal)) def exercise_double_tinyint_bool(context, arg1, arg2): if arg1.is_null or arg2.is_null: return BooleanVal.null lt = arg1.val < arg2.val return BooleanVal(lt) print(exercise_double_tinyint_bool.llvm_module)
Add simple test to exercise DoubleVal, TinyIntVal and BooleanVal
Add simple test to exercise DoubleVal, TinyIntVal and BooleanVal
Python
bsd-2-clause
cpcloud/numba,GaZ3ll3/numba,sklam/numba,seibert/numba,stuartarchibald/numba,IntelLabs/numba,stefanseefeld/numba,GaZ3ll3/numba,gdementen/numba,jriehl/numba,gmarkall/numba,ssarangi/numba,seibert/numba,pitrou/numba,ssarangi/numba,stonebig/numba,stuartarchibald/numba,numba/numba,numba/numba,cpcloud/numba,sklam/numba,stefanseefeld/numba,cpcloud/numba,pombredanne/numba,stefanseefeld/numba,jriehl/numba,ssarangi/numba,GaZ3ll3/numba,gmarkall/numba,pitrou/numba,pombredanne/numba,GaZ3ll3/numba,gdementen/numba,GaZ3ll3/numba,gdementen/numba,stonebig/numba,numba/numba,pombredanne/numba,cpcloud/numba,IntelLabs/numba,seibert/numba,stonebig/numba,jriehl/numba,numba/numba,stefanseefeld/numba,seibert/numba,gdementen/numba,gmarkall/numba,cpcloud/numba,pitrou/numba,pitrou/numba,pombredanne/numba,IntelLabs/numba,stuartarchibald/numba,sklam/numba,sklam/numba,numba/numba,jriehl/numba,stefanseefeld/numba,pitrou/numba,ssarangi/numba,stonebig/numba,gmarkall/numba,pombredanne/numba,IntelLabs/numba,stuartarchibald/numba,IntelLabs/numba,stuartarchibald/numba,stonebig/numba,sklam/numba,ssarangi/numba,gdementen/numba,seibert/numba,jriehl/numba,gmarkall/numba
""" A simple demonstration of Impala UDF generation. """ from numba.ext.impala import udf, IntVal, FunctionContext @udf(IntVal(FunctionContext, IntVal, IntVal)) def add_udf(context, arg1, arg2): if arg1.is_null or arg2.is_null: return IntVal.null return IntVal(arg1.val + arg2.val) # Simply print the module IR print(add_udf.llvm_module) Add simple test to exercise DoubleVal, TinyIntVal and BooleanVal
""" A simple demonstration of Impala UDF generation. """ from numba.ext.impala import (udf, IntVal, FunctionContext, BooleanVal, DoubleVal, TinyIntVal) @udf(IntVal(FunctionContext, IntVal, IntVal)) def add_udf(context, arg1, arg2): if arg1.is_null or arg2.is_null: return IntVal.null return IntVal(arg1.val + arg2.val) # Simply print the module IR print(add_udf.llvm_module) @udf(BooleanVal(FunctionContext, DoubleVal, TinyIntVal)) def exercise_double_tinyint_bool(context, arg1, arg2): if arg1.is_null or arg2.is_null: return BooleanVal.null lt = arg1.val < arg2.val return BooleanVal(lt) print(exercise_double_tinyint_bool.llvm_module)
<commit_before>""" A simple demonstration of Impala UDF generation. """ from numba.ext.impala import udf, IntVal, FunctionContext @udf(IntVal(FunctionContext, IntVal, IntVal)) def add_udf(context, arg1, arg2): if arg1.is_null or arg2.is_null: return IntVal.null return IntVal(arg1.val + arg2.val) # Simply print the module IR print(add_udf.llvm_module) <commit_msg>Add simple test to exercise DoubleVal, TinyIntVal and BooleanVal<commit_after>
""" A simple demonstration of Impala UDF generation. """ from numba.ext.impala import (udf, IntVal, FunctionContext, BooleanVal, DoubleVal, TinyIntVal) @udf(IntVal(FunctionContext, IntVal, IntVal)) def add_udf(context, arg1, arg2): if arg1.is_null or arg2.is_null: return IntVal.null return IntVal(arg1.val + arg2.val) # Simply print the module IR print(add_udf.llvm_module) @udf(BooleanVal(FunctionContext, DoubleVal, TinyIntVal)) def exercise_double_tinyint_bool(context, arg1, arg2): if arg1.is_null or arg2.is_null: return BooleanVal.null lt = arg1.val < arg2.val return BooleanVal(lt) print(exercise_double_tinyint_bool.llvm_module)
""" A simple demonstration of Impala UDF generation. """ from numba.ext.impala import udf, IntVal, FunctionContext @udf(IntVal(FunctionContext, IntVal, IntVal)) def add_udf(context, arg1, arg2): if arg1.is_null or arg2.is_null: return IntVal.null return IntVal(arg1.val + arg2.val) # Simply print the module IR print(add_udf.llvm_module) Add simple test to exercise DoubleVal, TinyIntVal and BooleanVal""" A simple demonstration of Impala UDF generation. """ from numba.ext.impala import (udf, IntVal, FunctionContext, BooleanVal, DoubleVal, TinyIntVal) @udf(IntVal(FunctionContext, IntVal, IntVal)) def add_udf(context, arg1, arg2): if arg1.is_null or arg2.is_null: return IntVal.null return IntVal(arg1.val + arg2.val) # Simply print the module IR print(add_udf.llvm_module) @udf(BooleanVal(FunctionContext, DoubleVal, TinyIntVal)) def exercise_double_tinyint_bool(context, arg1, arg2): if arg1.is_null or arg2.is_null: return BooleanVal.null lt = arg1.val < arg2.val return BooleanVal(lt) print(exercise_double_tinyint_bool.llvm_module)
<commit_before>""" A simple demonstration of Impala UDF generation. """ from numba.ext.impala import udf, IntVal, FunctionContext @udf(IntVal(FunctionContext, IntVal, IntVal)) def add_udf(context, arg1, arg2): if arg1.is_null or arg2.is_null: return IntVal.null return IntVal(arg1.val + arg2.val) # Simply print the module IR print(add_udf.llvm_module) <commit_msg>Add simple test to exercise DoubleVal, TinyIntVal and BooleanVal<commit_after>""" A simple demonstration of Impala UDF generation. """ from numba.ext.impala import (udf, IntVal, FunctionContext, BooleanVal, DoubleVal, TinyIntVal) @udf(IntVal(FunctionContext, IntVal, IntVal)) def add_udf(context, arg1, arg2): if arg1.is_null or arg2.is_null: return IntVal.null return IntVal(arg1.val + arg2.val) # Simply print the module IR print(add_udf.llvm_module) @udf(BooleanVal(FunctionContext, DoubleVal, TinyIntVal)) def exercise_double_tinyint_bool(context, arg1, arg2): if arg1.is_null or arg2.is_null: return BooleanVal.null lt = arg1.val < arg2.val return BooleanVal(lt) print(exercise_double_tinyint_bool.llvm_module)
d61540551943df57aa0dece5e44e130309dcafec
requests/packages/__init__.py
requests/packages/__init__.py
from __future__ import absolute_import from . import urllib3
""" pip._vendor is for vendoring dependencies of pip to prevent needing pip to depend on something external. Files inside of pip._vendor should be considered immutable and should only be updated to versions from upstream. """ from __future__ import absolute_import import sys class VendorAlias(object): def __init__(self): self._vendor_name = __name__ self._vendor_pkg = self._vendor_name + "." def find_module(self, fullname, path=None): if fullname.startswith(self._vendor_pkg): return self def load_module(self, name): # Ensure that this only works for the vendored name if not name.startswith(self._vendor_pkg): raise ImportError( "Cannot import %s, must be a subpackage of '%s'." % ( name, self._vendor_name, ) ) # Check to see if we already have this item in sys.modules, if we do # then simply return that. if name in sys.modules: return sys.modules[name] # Check to see if we can import the vendor name try: # We do this dance here because we want to try and import this # module without hitting a recursion error because of a bunch of # VendorAlias instances on sys.meta_path real_meta_path = sys.meta_path[:] try: sys.meta_path = [ m for m in sys.meta_path if not isinstance(m, VendorAlias) ] __import__(name) module = sys.modules[name] finally: # Re-add any additions to sys.meta_path that were made while # during the import we just did, otherwise things like # pip._vendor.six.moves will fail. for m in sys.meta_path: if m not in real_meta_path: real_meta_path.append(m) # Restore sys.meta_path with any new items. sys.meta_path = real_meta_path except ImportError: # We can't import the vendor name, so we'll try to import the # "real" name. real_name = name[len(self._vendor_pkg):] try: __import__(real_name) module = sys.modules[real_name] except ImportError: raise ImportError("No module named '%s'" % (name,)) # If we've gotten here we've found the module we're looking for, either # as part of our vendored package, or as the real name, so we'll add # it to sys.modules as the vendored name so that we don't have to do # the lookup again. sys.modules[name] = module # Finally, return the loaded module return module sys.meta_path.append(VendorAlias())
Copy pip's import machinery wholesale
Copy pip's import machinery wholesale
Python
apache-2.0
psf/requests
from __future__ import absolute_import from . import urllib3 Copy pip's import machinery wholesale
""" pip._vendor is for vendoring dependencies of pip to prevent needing pip to depend on something external. Files inside of pip._vendor should be considered immutable and should only be updated to versions from upstream. """ from __future__ import absolute_import import sys class VendorAlias(object): def __init__(self): self._vendor_name = __name__ self._vendor_pkg = self._vendor_name + "." def find_module(self, fullname, path=None): if fullname.startswith(self._vendor_pkg): return self def load_module(self, name): # Ensure that this only works for the vendored name if not name.startswith(self._vendor_pkg): raise ImportError( "Cannot import %s, must be a subpackage of '%s'." % ( name, self._vendor_name, ) ) # Check to see if we already have this item in sys.modules, if we do # then simply return that. if name in sys.modules: return sys.modules[name] # Check to see if we can import the vendor name try: # We do this dance here because we want to try and import this # module without hitting a recursion error because of a bunch of # VendorAlias instances on sys.meta_path real_meta_path = sys.meta_path[:] try: sys.meta_path = [ m for m in sys.meta_path if not isinstance(m, VendorAlias) ] __import__(name) module = sys.modules[name] finally: # Re-add any additions to sys.meta_path that were made while # during the import we just did, otherwise things like # pip._vendor.six.moves will fail. for m in sys.meta_path: if m not in real_meta_path: real_meta_path.append(m) # Restore sys.meta_path with any new items. sys.meta_path = real_meta_path except ImportError: # We can't import the vendor name, so we'll try to import the # "real" name. real_name = name[len(self._vendor_pkg):] try: __import__(real_name) module = sys.modules[real_name] except ImportError: raise ImportError("No module named '%s'" % (name,)) # If we've gotten here we've found the module we're looking for, either # as part of our vendored package, or as the real name, so we'll add # it to sys.modules as the vendored name so that we don't have to do # the lookup again. sys.modules[name] = module # Finally, return the loaded module return module sys.meta_path.append(VendorAlias())
<commit_before>from __future__ import absolute_import from . import urllib3 <commit_msg>Copy pip's import machinery wholesale<commit_after>
""" pip._vendor is for vendoring dependencies of pip to prevent needing pip to depend on something external. Files inside of pip._vendor should be considered immutable and should only be updated to versions from upstream. """ from __future__ import absolute_import import sys class VendorAlias(object): def __init__(self): self._vendor_name = __name__ self._vendor_pkg = self._vendor_name + "." def find_module(self, fullname, path=None): if fullname.startswith(self._vendor_pkg): return self def load_module(self, name): # Ensure that this only works for the vendored name if not name.startswith(self._vendor_pkg): raise ImportError( "Cannot import %s, must be a subpackage of '%s'." % ( name, self._vendor_name, ) ) # Check to see if we already have this item in sys.modules, if we do # then simply return that. if name in sys.modules: return sys.modules[name] # Check to see if we can import the vendor name try: # We do this dance here because we want to try and import this # module without hitting a recursion error because of a bunch of # VendorAlias instances on sys.meta_path real_meta_path = sys.meta_path[:] try: sys.meta_path = [ m for m in sys.meta_path if not isinstance(m, VendorAlias) ] __import__(name) module = sys.modules[name] finally: # Re-add any additions to sys.meta_path that were made while # during the import we just did, otherwise things like # pip._vendor.six.moves will fail. for m in sys.meta_path: if m not in real_meta_path: real_meta_path.append(m) # Restore sys.meta_path with any new items. sys.meta_path = real_meta_path except ImportError: # We can't import the vendor name, so we'll try to import the # "real" name. real_name = name[len(self._vendor_pkg):] try: __import__(real_name) module = sys.modules[real_name] except ImportError: raise ImportError("No module named '%s'" % (name,)) # If we've gotten here we've found the module we're looking for, either # as part of our vendored package, or as the real name, so we'll add # it to sys.modules as the vendored name so that we don't have to do # the lookup again. sys.modules[name] = module # Finally, return the loaded module return module sys.meta_path.append(VendorAlias())
from __future__ import absolute_import from . import urllib3 Copy pip's import machinery wholesale""" pip._vendor is for vendoring dependencies of pip to prevent needing pip to depend on something external. Files inside of pip._vendor should be considered immutable and should only be updated to versions from upstream. """ from __future__ import absolute_import import sys class VendorAlias(object): def __init__(self): self._vendor_name = __name__ self._vendor_pkg = self._vendor_name + "." def find_module(self, fullname, path=None): if fullname.startswith(self._vendor_pkg): return self def load_module(self, name): # Ensure that this only works for the vendored name if not name.startswith(self._vendor_pkg): raise ImportError( "Cannot import %s, must be a subpackage of '%s'." % ( name, self._vendor_name, ) ) # Check to see if we already have this item in sys.modules, if we do # then simply return that. if name in sys.modules: return sys.modules[name] # Check to see if we can import the vendor name try: # We do this dance here because we want to try and import this # module without hitting a recursion error because of a bunch of # VendorAlias instances on sys.meta_path real_meta_path = sys.meta_path[:] try: sys.meta_path = [ m for m in sys.meta_path if not isinstance(m, VendorAlias) ] __import__(name) module = sys.modules[name] finally: # Re-add any additions to sys.meta_path that were made while # during the import we just did, otherwise things like # pip._vendor.six.moves will fail. for m in sys.meta_path: if m not in real_meta_path: real_meta_path.append(m) # Restore sys.meta_path with any new items. sys.meta_path = real_meta_path except ImportError: # We can't import the vendor name, so we'll try to import the # "real" name. real_name = name[len(self._vendor_pkg):] try: __import__(real_name) module = sys.modules[real_name] except ImportError: raise ImportError("No module named '%s'" % (name,)) # If we've gotten here we've found the module we're looking for, either # as part of our vendored package, or as the real name, so we'll add # it to sys.modules as the vendored name so that we don't have to do # the lookup again. sys.modules[name] = module # Finally, return the loaded module return module sys.meta_path.append(VendorAlias())
<commit_before>from __future__ import absolute_import from . import urllib3 <commit_msg>Copy pip's import machinery wholesale<commit_after>""" pip._vendor is for vendoring dependencies of pip to prevent needing pip to depend on something external. Files inside of pip._vendor should be considered immutable and should only be updated to versions from upstream. """ from __future__ import absolute_import import sys class VendorAlias(object): def __init__(self): self._vendor_name = __name__ self._vendor_pkg = self._vendor_name + "." def find_module(self, fullname, path=None): if fullname.startswith(self._vendor_pkg): return self def load_module(self, name): # Ensure that this only works for the vendored name if not name.startswith(self._vendor_pkg): raise ImportError( "Cannot import %s, must be a subpackage of '%s'." % ( name, self._vendor_name, ) ) # Check to see if we already have this item in sys.modules, if we do # then simply return that. if name in sys.modules: return sys.modules[name] # Check to see if we can import the vendor name try: # We do this dance here because we want to try and import this # module without hitting a recursion error because of a bunch of # VendorAlias instances on sys.meta_path real_meta_path = sys.meta_path[:] try: sys.meta_path = [ m for m in sys.meta_path if not isinstance(m, VendorAlias) ] __import__(name) module = sys.modules[name] finally: # Re-add any additions to sys.meta_path that were made while # during the import we just did, otherwise things like # pip._vendor.six.moves will fail. for m in sys.meta_path: if m not in real_meta_path: real_meta_path.append(m) # Restore sys.meta_path with any new items. sys.meta_path = real_meta_path except ImportError: # We can't import the vendor name, so we'll try to import the # "real" name. real_name = name[len(self._vendor_pkg):] try: __import__(real_name) module = sys.modules[real_name] except ImportError: raise ImportError("No module named '%s'" % (name,)) # If we've gotten here we've found the module we're looking for, either # as part of our vendored package, or as the real name, so we'll add # it to sys.modules as the vendored name so that we don't have to do # the lookup again. sys.modules[name] = module # Finally, return the loaded module return module sys.meta_path.append(VendorAlias())
c90c851391a32472d9937930543698d09ee017e9
distarray/tests/test_client.py
distarray/tests/test_client.py
import unittest import numpy as np from IPython.parallel import Client from distarray.client import DistArrayContext class TestDistArrayContext(unittest.TestCase): def setUp(self): self.client = Client() self.dv = self.client[:] def test_create_DAC(self): '''Can we create a plain vanilla context?''' dac = DistArrayContext(self.dv) self.assertIs(dac.view, self.dv) def test_create_DAC_with_targets(self): '''Can we create a context with a subset of engines?''' dac = DistArrayContext(self.dv, targets=[0, 1]) self.assertIs(dac.view, self.dv) class TestDistArrayProxy(unittest.TestCase): def setUp(self): self.client = Client() self.dv = self.client[:] self.dac = DistArrayContext(self.dv) self.dap = self.dac.fromndarray(np.arange(100)) def test_getitem(self): self.assertEqual(self.dap[55], 55) if __name__ == '__main__': unittest.main(verbosity=2)
import unittest import numpy as np from IPython.parallel import Client from distarray.client import DistArrayContext class TestDistArrayContext(unittest.TestCase): def setUp(self): self.client = Client() self.dv = self.client[:] def test_create_DAC(self): '''Can we create a plain vanilla context?''' dac = DistArrayContext(self.dv) self.assertIs(dac.view, self.dv) def test_create_DAC_with_targets(self): '''Can we create a context with a subset of engines?''' dac = DistArrayContext(self.dv, targets=[0, 1]) self.assertIs(dac.view, self.dv) class TestDistArrayProxy(unittest.TestCase): def setUp(self): self.client = Client() self.dv = self.client[:] self.dac = DistArrayContext(self.dv) self.dap = self.dac.fromndarray(np.arange(100)) def test_getitem(self): self.assertEqual(self.dap[55], 55) def test_setitem(self): self.dap[35] = 9999 print self.dap[35] if __name__ == '__main__': unittest.main(verbosity=2)
Add failing test for DistArrayProxy.__setitem__
Add failing test for DistArrayProxy.__setitem__
Python
bsd-3-clause
enthought/distarray,RaoUmer/distarray,RaoUmer/distarray,enthought/distarray
import unittest import numpy as np from IPython.parallel import Client from distarray.client import DistArrayContext class TestDistArrayContext(unittest.TestCase): def setUp(self): self.client = Client() self.dv = self.client[:] def test_create_DAC(self): '''Can we create a plain vanilla context?''' dac = DistArrayContext(self.dv) self.assertIs(dac.view, self.dv) def test_create_DAC_with_targets(self): '''Can we create a context with a subset of engines?''' dac = DistArrayContext(self.dv, targets=[0, 1]) self.assertIs(dac.view, self.dv) class TestDistArrayProxy(unittest.TestCase): def setUp(self): self.client = Client() self.dv = self.client[:] self.dac = DistArrayContext(self.dv) self.dap = self.dac.fromndarray(np.arange(100)) def test_getitem(self): self.assertEqual(self.dap[55], 55) if __name__ == '__main__': unittest.main(verbosity=2) Add failing test for DistArrayProxy.__setitem__
import unittest import numpy as np from IPython.parallel import Client from distarray.client import DistArrayContext class TestDistArrayContext(unittest.TestCase): def setUp(self): self.client = Client() self.dv = self.client[:] def test_create_DAC(self): '''Can we create a plain vanilla context?''' dac = DistArrayContext(self.dv) self.assertIs(dac.view, self.dv) def test_create_DAC_with_targets(self): '''Can we create a context with a subset of engines?''' dac = DistArrayContext(self.dv, targets=[0, 1]) self.assertIs(dac.view, self.dv) class TestDistArrayProxy(unittest.TestCase): def setUp(self): self.client = Client() self.dv = self.client[:] self.dac = DistArrayContext(self.dv) self.dap = self.dac.fromndarray(np.arange(100)) def test_getitem(self): self.assertEqual(self.dap[55], 55) def test_setitem(self): self.dap[35] = 9999 print self.dap[35] if __name__ == '__main__': unittest.main(verbosity=2)
<commit_before>import unittest import numpy as np from IPython.parallel import Client from distarray.client import DistArrayContext class TestDistArrayContext(unittest.TestCase): def setUp(self): self.client = Client() self.dv = self.client[:] def test_create_DAC(self): '''Can we create a plain vanilla context?''' dac = DistArrayContext(self.dv) self.assertIs(dac.view, self.dv) def test_create_DAC_with_targets(self): '''Can we create a context with a subset of engines?''' dac = DistArrayContext(self.dv, targets=[0, 1]) self.assertIs(dac.view, self.dv) class TestDistArrayProxy(unittest.TestCase): def setUp(self): self.client = Client() self.dv = self.client[:] self.dac = DistArrayContext(self.dv) self.dap = self.dac.fromndarray(np.arange(100)) def test_getitem(self): self.assertEqual(self.dap[55], 55) if __name__ == '__main__': unittest.main(verbosity=2) <commit_msg>Add failing test for DistArrayProxy.__setitem__<commit_after>
import unittest import numpy as np from IPython.parallel import Client from distarray.client import DistArrayContext class TestDistArrayContext(unittest.TestCase): def setUp(self): self.client = Client() self.dv = self.client[:] def test_create_DAC(self): '''Can we create a plain vanilla context?''' dac = DistArrayContext(self.dv) self.assertIs(dac.view, self.dv) def test_create_DAC_with_targets(self): '''Can we create a context with a subset of engines?''' dac = DistArrayContext(self.dv, targets=[0, 1]) self.assertIs(dac.view, self.dv) class TestDistArrayProxy(unittest.TestCase): def setUp(self): self.client = Client() self.dv = self.client[:] self.dac = DistArrayContext(self.dv) self.dap = self.dac.fromndarray(np.arange(100)) def test_getitem(self): self.assertEqual(self.dap[55], 55) def test_setitem(self): self.dap[35] = 9999 print self.dap[35] if __name__ == '__main__': unittest.main(verbosity=2)
import unittest import numpy as np from IPython.parallel import Client from distarray.client import DistArrayContext class TestDistArrayContext(unittest.TestCase): def setUp(self): self.client = Client() self.dv = self.client[:] def test_create_DAC(self): '''Can we create a plain vanilla context?''' dac = DistArrayContext(self.dv) self.assertIs(dac.view, self.dv) def test_create_DAC_with_targets(self): '''Can we create a context with a subset of engines?''' dac = DistArrayContext(self.dv, targets=[0, 1]) self.assertIs(dac.view, self.dv) class TestDistArrayProxy(unittest.TestCase): def setUp(self): self.client = Client() self.dv = self.client[:] self.dac = DistArrayContext(self.dv) self.dap = self.dac.fromndarray(np.arange(100)) def test_getitem(self): self.assertEqual(self.dap[55], 55) if __name__ == '__main__': unittest.main(verbosity=2) Add failing test for DistArrayProxy.__setitem__import unittest import numpy as np from IPython.parallel import Client from distarray.client import DistArrayContext class TestDistArrayContext(unittest.TestCase): def setUp(self): self.client = Client() self.dv = self.client[:] def test_create_DAC(self): '''Can we create a plain vanilla context?''' dac = DistArrayContext(self.dv) self.assertIs(dac.view, self.dv) def test_create_DAC_with_targets(self): '''Can we create a context with a subset of engines?''' dac = DistArrayContext(self.dv, targets=[0, 1]) self.assertIs(dac.view, self.dv) class TestDistArrayProxy(unittest.TestCase): def setUp(self): self.client = Client() self.dv = self.client[:] self.dac = DistArrayContext(self.dv) self.dap = self.dac.fromndarray(np.arange(100)) def test_getitem(self): self.assertEqual(self.dap[55], 55) def test_setitem(self): self.dap[35] = 9999 print self.dap[35] if __name__ == '__main__': unittest.main(verbosity=2)
<commit_before>import unittest import numpy as np from IPython.parallel import Client from distarray.client import DistArrayContext class TestDistArrayContext(unittest.TestCase): def setUp(self): self.client = Client() self.dv = self.client[:] def test_create_DAC(self): '''Can we create a plain vanilla context?''' dac = DistArrayContext(self.dv) self.assertIs(dac.view, self.dv) def test_create_DAC_with_targets(self): '''Can we create a context with a subset of engines?''' dac = DistArrayContext(self.dv, targets=[0, 1]) self.assertIs(dac.view, self.dv) class TestDistArrayProxy(unittest.TestCase): def setUp(self): self.client = Client() self.dv = self.client[:] self.dac = DistArrayContext(self.dv) self.dap = self.dac.fromndarray(np.arange(100)) def test_getitem(self): self.assertEqual(self.dap[55], 55) if __name__ == '__main__': unittest.main(verbosity=2) <commit_msg>Add failing test for DistArrayProxy.__setitem__<commit_after>import unittest import numpy as np from IPython.parallel import Client from distarray.client import DistArrayContext class TestDistArrayContext(unittest.TestCase): def setUp(self): self.client = Client() self.dv = self.client[:] def test_create_DAC(self): '''Can we create a plain vanilla context?''' dac = DistArrayContext(self.dv) self.assertIs(dac.view, self.dv) def test_create_DAC_with_targets(self): '''Can we create a context with a subset of engines?''' dac = DistArrayContext(self.dv, targets=[0, 1]) self.assertIs(dac.view, self.dv) class TestDistArrayProxy(unittest.TestCase): def setUp(self): self.client = Client() self.dv = self.client[:] self.dac = DistArrayContext(self.dv) self.dap = self.dac.fromndarray(np.arange(100)) def test_getitem(self): self.assertEqual(self.dap[55], 55) def test_setitem(self): self.dap[35] = 9999 print self.dap[35] if __name__ == '__main__': unittest.main(verbosity=2)
b7047bd09a6bda21dfd1c69cc4cdd08ae328a03b
autotests/tests/sample_false_assert.py
autotests/tests/sample_false_assert.py
import time from unittest import TestCase class Sample(TestCase): def test_sameple_with_big_timeout(self): print("Testing false assert") self.assertEquals(1, 2)
from unittest import TestCase class Sample(TestCase): def test_sameple_with_big_timeout(self): print("Testing false assert") self.assertEqual(1, 2)
Fix deprecated use of function on sample test
Fix deprecated use of function on sample test
Python
mit
jfelipefilho/test-manager,jfelipefilho/test-manager,jfelipefilho/test-manager
import time from unittest import TestCase class Sample(TestCase): def test_sameple_with_big_timeout(self): print("Testing false assert") self.assertEquals(1, 2) Fix deprecated use of function on sample test
from unittest import TestCase class Sample(TestCase): def test_sameple_with_big_timeout(self): print("Testing false assert") self.assertEqual(1, 2)
<commit_before>import time from unittest import TestCase class Sample(TestCase): def test_sameple_with_big_timeout(self): print("Testing false assert") self.assertEquals(1, 2) <commit_msg>Fix deprecated use of function on sample test<commit_after>
from unittest import TestCase class Sample(TestCase): def test_sameple_with_big_timeout(self): print("Testing false assert") self.assertEqual(1, 2)
import time from unittest import TestCase class Sample(TestCase): def test_sameple_with_big_timeout(self): print("Testing false assert") self.assertEquals(1, 2) Fix deprecated use of function on sample testfrom unittest import TestCase class Sample(TestCase): def test_sameple_with_big_timeout(self): print("Testing false assert") self.assertEqual(1, 2)
<commit_before>import time from unittest import TestCase class Sample(TestCase): def test_sameple_with_big_timeout(self): print("Testing false assert") self.assertEquals(1, 2) <commit_msg>Fix deprecated use of function on sample test<commit_after>from unittest import TestCase class Sample(TestCase): def test_sameple_with_big_timeout(self): print("Testing false assert") self.assertEqual(1, 2)
6d8b6cfe9e2de860b4b39a1e0f0bb8fa45e6b96f
manage.py
manage.py
#-*- coding: utf-8 -*- from flask.ext.script import Manager, prompt, prompt_bool, prompt_pass from db_create import ( init_db, drop_db, init_admin_user, init_entry, init_category, init_tag ) from flask.ext.migrate import MigrateCommand from logpot.app import app import os if os.path.exists('.env'): print('Importing environment from .env...') for line in open('.env'): var = line.strip().split('=') if len(var) == 2: os.environ[var[0]] = var[1] manager = Manager(app) manager.add_command('db', MigrateCommand) @manager.command def run(): app.run(threaded=True) @manager.command def initialize(): if prompt_bool("Are you sure you want to create DB and initialize?"): drop_db() init_db() if init_admin(): init_category() init_tag() init_entry() print('Success!') @manager.command def init_admin(): name = prompt('Resister admin user.\n[?] input username: ') email = prompt('[?] input email: ') password = prompt_pass('[?] input password: ') confirm_password = prompt_pass('[?] input password again: ') if not password == confirm_password: print('Password does not match.') return False else: init_admin_user(name, email, password) return True if __name__ == "__main__": manager.run()
#-*- coding: utf-8 -*- import os if os.path.exists('.env'): print('Importing environment from .env...') for line in open('.env'): var = line.strip().split('=') if len(var) == 2: os.environ[var[0]] = var[1] from flask.ext.script import Manager, prompt, prompt_bool, prompt_pass from db_create import ( init_db, drop_db, init_admin_user, init_entry, init_category, init_tag ) from flask.ext.migrate import MigrateCommand from logpot.app import app manager = Manager(app) manager.add_command('db', MigrateCommand) @manager.command def run(): app.run(threaded=True) @manager.command def initialize(): if prompt_bool("Are you sure you want to create DB and initialize?"): drop_db() init_db() if init_admin(): init_category() init_tag() init_entry() print('Success!') @manager.command def init_admin(): name = prompt('Resister admin user.\n[?] input username: ') email = prompt('[?] input email: ') password = prompt_pass('[?] input password: ') confirm_password = prompt_pass('[?] input password again: ') if not password == confirm_password: print('Password does not match.') return False else: init_admin_user(name, email, password) return True if __name__ == "__main__": manager.run()
Fix import location of environment variables
Fix import location of environment variables
Python
mit
moremorefor/Logpot,moremorefor/Logpot,moremorefor/Logpot
#-*- coding: utf-8 -*- from flask.ext.script import Manager, prompt, prompt_bool, prompt_pass from db_create import ( init_db, drop_db, init_admin_user, init_entry, init_category, init_tag ) from flask.ext.migrate import MigrateCommand from logpot.app import app import os if os.path.exists('.env'): print('Importing environment from .env...') for line in open('.env'): var = line.strip().split('=') if len(var) == 2: os.environ[var[0]] = var[1] manager = Manager(app) manager.add_command('db', MigrateCommand) @manager.command def run(): app.run(threaded=True) @manager.command def initialize(): if prompt_bool("Are you sure you want to create DB and initialize?"): drop_db() init_db() if init_admin(): init_category() init_tag() init_entry() print('Success!') @manager.command def init_admin(): name = prompt('Resister admin user.\n[?] input username: ') email = prompt('[?] input email: ') password = prompt_pass('[?] input password: ') confirm_password = prompt_pass('[?] input password again: ') if not password == confirm_password: print('Password does not match.') return False else: init_admin_user(name, email, password) return True if __name__ == "__main__": manager.run() Fix import location of environment variables
#-*- coding: utf-8 -*- import os if os.path.exists('.env'): print('Importing environment from .env...') for line in open('.env'): var = line.strip().split('=') if len(var) == 2: os.environ[var[0]] = var[1] from flask.ext.script import Manager, prompt, prompt_bool, prompt_pass from db_create import ( init_db, drop_db, init_admin_user, init_entry, init_category, init_tag ) from flask.ext.migrate import MigrateCommand from logpot.app import app manager = Manager(app) manager.add_command('db', MigrateCommand) @manager.command def run(): app.run(threaded=True) @manager.command def initialize(): if prompt_bool("Are you sure you want to create DB and initialize?"): drop_db() init_db() if init_admin(): init_category() init_tag() init_entry() print('Success!') @manager.command def init_admin(): name = prompt('Resister admin user.\n[?] input username: ') email = prompt('[?] input email: ') password = prompt_pass('[?] input password: ') confirm_password = prompt_pass('[?] input password again: ') if not password == confirm_password: print('Password does not match.') return False else: init_admin_user(name, email, password) return True if __name__ == "__main__": manager.run()
<commit_before>#-*- coding: utf-8 -*- from flask.ext.script import Manager, prompt, prompt_bool, prompt_pass from db_create import ( init_db, drop_db, init_admin_user, init_entry, init_category, init_tag ) from flask.ext.migrate import MigrateCommand from logpot.app import app import os if os.path.exists('.env'): print('Importing environment from .env...') for line in open('.env'): var = line.strip().split('=') if len(var) == 2: os.environ[var[0]] = var[1] manager = Manager(app) manager.add_command('db', MigrateCommand) @manager.command def run(): app.run(threaded=True) @manager.command def initialize(): if prompt_bool("Are you sure you want to create DB and initialize?"): drop_db() init_db() if init_admin(): init_category() init_tag() init_entry() print('Success!') @manager.command def init_admin(): name = prompt('Resister admin user.\n[?] input username: ') email = prompt('[?] input email: ') password = prompt_pass('[?] input password: ') confirm_password = prompt_pass('[?] input password again: ') if not password == confirm_password: print('Password does not match.') return False else: init_admin_user(name, email, password) return True if __name__ == "__main__": manager.run() <commit_msg>Fix import location of environment variables<commit_after>
#-*- coding: utf-8 -*- import os if os.path.exists('.env'): print('Importing environment from .env...') for line in open('.env'): var = line.strip().split('=') if len(var) == 2: os.environ[var[0]] = var[1] from flask.ext.script import Manager, prompt, prompt_bool, prompt_pass from db_create import ( init_db, drop_db, init_admin_user, init_entry, init_category, init_tag ) from flask.ext.migrate import MigrateCommand from logpot.app import app manager = Manager(app) manager.add_command('db', MigrateCommand) @manager.command def run(): app.run(threaded=True) @manager.command def initialize(): if prompt_bool("Are you sure you want to create DB and initialize?"): drop_db() init_db() if init_admin(): init_category() init_tag() init_entry() print('Success!') @manager.command def init_admin(): name = prompt('Resister admin user.\n[?] input username: ') email = prompt('[?] input email: ') password = prompt_pass('[?] input password: ') confirm_password = prompt_pass('[?] input password again: ') if not password == confirm_password: print('Password does not match.') return False else: init_admin_user(name, email, password) return True if __name__ == "__main__": manager.run()
#-*- coding: utf-8 -*- from flask.ext.script import Manager, prompt, prompt_bool, prompt_pass from db_create import ( init_db, drop_db, init_admin_user, init_entry, init_category, init_tag ) from flask.ext.migrate import MigrateCommand from logpot.app import app import os if os.path.exists('.env'): print('Importing environment from .env...') for line in open('.env'): var = line.strip().split('=') if len(var) == 2: os.environ[var[0]] = var[1] manager = Manager(app) manager.add_command('db', MigrateCommand) @manager.command def run(): app.run(threaded=True) @manager.command def initialize(): if prompt_bool("Are you sure you want to create DB and initialize?"): drop_db() init_db() if init_admin(): init_category() init_tag() init_entry() print('Success!') @manager.command def init_admin(): name = prompt('Resister admin user.\n[?] input username: ') email = prompt('[?] input email: ') password = prompt_pass('[?] input password: ') confirm_password = prompt_pass('[?] input password again: ') if not password == confirm_password: print('Password does not match.') return False else: init_admin_user(name, email, password) return True if __name__ == "__main__": manager.run() Fix import location of environment variables#-*- coding: utf-8 -*- import os if os.path.exists('.env'): print('Importing environment from .env...') for line in open('.env'): var = line.strip().split('=') if len(var) == 2: os.environ[var[0]] = var[1] from flask.ext.script import Manager, prompt, prompt_bool, prompt_pass from db_create import ( init_db, drop_db, init_admin_user, init_entry, init_category, init_tag ) from flask.ext.migrate import MigrateCommand from logpot.app import app manager = Manager(app) manager.add_command('db', MigrateCommand) @manager.command def run(): app.run(threaded=True) @manager.command def initialize(): if prompt_bool("Are you sure you want to create DB and initialize?"): drop_db() init_db() if init_admin(): init_category() init_tag() init_entry() print('Success!') @manager.command def init_admin(): name = prompt('Resister admin user.\n[?] input username: ') email = prompt('[?] input email: ') password = prompt_pass('[?] input password: ') confirm_password = prompt_pass('[?] input password again: ') if not password == confirm_password: print('Password does not match.') return False else: init_admin_user(name, email, password) return True if __name__ == "__main__": manager.run()
<commit_before>#-*- coding: utf-8 -*- from flask.ext.script import Manager, prompt, prompt_bool, prompt_pass from db_create import ( init_db, drop_db, init_admin_user, init_entry, init_category, init_tag ) from flask.ext.migrate import MigrateCommand from logpot.app import app import os if os.path.exists('.env'): print('Importing environment from .env...') for line in open('.env'): var = line.strip().split('=') if len(var) == 2: os.environ[var[0]] = var[1] manager = Manager(app) manager.add_command('db', MigrateCommand) @manager.command def run(): app.run(threaded=True) @manager.command def initialize(): if prompt_bool("Are you sure you want to create DB and initialize?"): drop_db() init_db() if init_admin(): init_category() init_tag() init_entry() print('Success!') @manager.command def init_admin(): name = prompt('Resister admin user.\n[?] input username: ') email = prompt('[?] input email: ') password = prompt_pass('[?] input password: ') confirm_password = prompt_pass('[?] input password again: ') if not password == confirm_password: print('Password does not match.') return False else: init_admin_user(name, email, password) return True if __name__ == "__main__": manager.run() <commit_msg>Fix import location of environment variables<commit_after>#-*- coding: utf-8 -*- import os if os.path.exists('.env'): print('Importing environment from .env...') for line in open('.env'): var = line.strip().split('=') if len(var) == 2: os.environ[var[0]] = var[1] from flask.ext.script import Manager, prompt, prompt_bool, prompt_pass from db_create import ( init_db, drop_db, init_admin_user, init_entry, init_category, init_tag ) from flask.ext.migrate import MigrateCommand from logpot.app import app manager = Manager(app) manager.add_command('db', MigrateCommand) @manager.command def run(): app.run(threaded=True) @manager.command def initialize(): if prompt_bool("Are you sure you want to create DB and initialize?"): drop_db() init_db() if init_admin(): init_category() init_tag() init_entry() print('Success!') @manager.command def init_admin(): name = prompt('Resister admin user.\n[?] input username: ') email = prompt('[?] input email: ') password = prompt_pass('[?] input password: ') confirm_password = prompt_pass('[?] input password again: ') if not password == confirm_password: print('Password does not match.') return False else: init_admin_user(name, email, password) return True if __name__ == "__main__": manager.run()
d76b9a46515825bdea114efdf9cedf52e2033cc6
16/016_power_digit_sum.py
16/016_power_digit_sum.py
"""Power Digit Sum 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 21000? """ assert sum(int(x) for x in str(2 ** 1000)) == 1366
"""Power Digit Sum 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 21000? """ assert sum(int(x) for x in str(2 ** 1000)) == 1366
Remove redundant empty line at end of file
Remove redundant empty line at end of file There is no need to have multiple empty lines in the end.
Python
mit
the-gigi/project-euler,the-gigi/project-euler,the-gigi/project-euler
"""Power Digit Sum 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 21000? """ assert sum(int(x) for x in str(2 ** 1000)) == 1366 Remove redundant empty line at end of file There is no need to have multiple empty lines in the end.
"""Power Digit Sum 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 21000? """ assert sum(int(x) for x in str(2 ** 1000)) == 1366
<commit_before>"""Power Digit Sum 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 21000? """ assert sum(int(x) for x in str(2 ** 1000)) == 1366 <commit_msg>Remove redundant empty line at end of file There is no need to have multiple empty lines in the end.<commit_after>
"""Power Digit Sum 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 21000? """ assert sum(int(x) for x in str(2 ** 1000)) == 1366
"""Power Digit Sum 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 21000? """ assert sum(int(x) for x in str(2 ** 1000)) == 1366 Remove redundant empty line at end of file There is no need to have multiple empty lines in the end."""Power Digit Sum 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 21000? """ assert sum(int(x) for x in str(2 ** 1000)) == 1366
<commit_before>"""Power Digit Sum 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 21000? """ assert sum(int(x) for x in str(2 ** 1000)) == 1366 <commit_msg>Remove redundant empty line at end of file There is no need to have multiple empty lines in the end.<commit_after>"""Power Digit Sum 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 21000? """ assert sum(int(x) for x in str(2 ** 1000)) == 1366
52f1c57c2aebd6d371ce95d35442c5eb6f59ea0b
zerver/migrations/0127_disallow_chars_in_stream_and_user_name.py
zerver/migrations/0127_disallow_chars_in_stream_and_user_name.py
# -*- coding: utf-8 -*- from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('zerver', '0126_prereg_remove_users_without_realm'), ] operations = [ # There was a migration here, which wasn't ready for wide deployment # and was backed out. This placeholder is left behind to avoid # confusing the migration engine on any installs that applied the # migration. (Fortunately no reverse migration is needed.) ]
# -*- coding: utf-8 -*- from typing import Any, List from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('zerver', '0126_prereg_remove_users_without_realm'), ] operations = [ # There was a migration here, which wasn't ready for wide deployment # and was backed out. This placeholder is left behind to avoid # confusing the migration engine on any installs that applied the # migration. (Fortunately no reverse migration is needed.) ] # type: List[Any]
Fix mypy error in placeholder migration.
migrations: Fix mypy error in placeholder migration.
Python
apache-2.0
eeshangarg/zulip,timabbott/zulip,brainwane/zulip,tommyip/zulip,zulip/zulip,rishig/zulip,punchagan/zulip,eeshangarg/zulip,hackerkid/zulip,punchagan/zulip,shubhamdhama/zulip,brainwane/zulip,rishig/zulip,punchagan/zulip,hackerkid/zulip,showell/zulip,andersk/zulip,jackrzhang/zulip,tommyip/zulip,synicalsyntax/zulip,timabbott/zulip,hackerkid/zulip,kou/zulip,synicalsyntax/zulip,rht/zulip,rishig/zulip,timabbott/zulip,eeshangarg/zulip,jackrzhang/zulip,rishig/zulip,brainwane/zulip,andersk/zulip,shubhamdhama/zulip,synicalsyntax/zulip,rht/zulip,synicalsyntax/zulip,kou/zulip,rht/zulip,hackerkid/zulip,shubhamdhama/zulip,punchagan/zulip,timabbott/zulip,dhcrzf/zulip,showell/zulip,brainwane/zulip,jackrzhang/zulip,dhcrzf/zulip,showell/zulip,eeshangarg/zulip,rht/zulip,timabbott/zulip,andersk/zulip,tommyip/zulip,tommyip/zulip,kou/zulip,showell/zulip,zulip/zulip,timabbott/zulip,dhcrzf/zulip,dhcrzf/zulip,punchagan/zulip,zulip/zulip,jackrzhang/zulip,zulip/zulip,tommyip/zulip,brainwane/zulip,hackerkid/zulip,andersk/zulip,zulip/zulip,brainwane/zulip,dhcrzf/zulip,showell/zulip,rishig/zulip,tommyip/zulip,andersk/zulip,andersk/zulip,shubhamdhama/zulip,eeshangarg/zulip,eeshangarg/zulip,tommyip/zulip,synicalsyntax/zulip,dhcrzf/zulip,rht/zulip,hackerkid/zulip,punchagan/zulip,rishig/zulip,showell/zulip,zulip/zulip,zulip/zulip,shubhamdhama/zulip,synicalsyntax/zulip,shubhamdhama/zulip,rht/zulip,kou/zulip,rht/zulip,jackrzhang/zulip,kou/zulip,kou/zulip,jackrzhang/zulip,andersk/zulip,synicalsyntax/zulip,shubhamdhama/zulip,brainwane/zulip,kou/zulip,punchagan/zulip,rishig/zulip,hackerkid/zulip,timabbott/zulip,eeshangarg/zulip,dhcrzf/zulip,jackrzhang/zulip,showell/zulip
# -*- coding: utf-8 -*- from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('zerver', '0126_prereg_remove_users_without_realm'), ] operations = [ # There was a migration here, which wasn't ready for wide deployment # and was backed out. This placeholder is left behind to avoid # confusing the migration engine on any installs that applied the # migration. (Fortunately no reverse migration is needed.) ] migrations: Fix mypy error in placeholder migration.
# -*- coding: utf-8 -*- from typing import Any, List from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('zerver', '0126_prereg_remove_users_without_realm'), ] operations = [ # There was a migration here, which wasn't ready for wide deployment # and was backed out. This placeholder is left behind to avoid # confusing the migration engine on any installs that applied the # migration. (Fortunately no reverse migration is needed.) ] # type: List[Any]
<commit_before># -*- coding: utf-8 -*- from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('zerver', '0126_prereg_remove_users_without_realm'), ] operations = [ # There was a migration here, which wasn't ready for wide deployment # and was backed out. This placeholder is left behind to avoid # confusing the migration engine on any installs that applied the # migration. (Fortunately no reverse migration is needed.) ] <commit_msg>migrations: Fix mypy error in placeholder migration.<commit_after>
# -*- coding: utf-8 -*- from typing import Any, List from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('zerver', '0126_prereg_remove_users_without_realm'), ] operations = [ # There was a migration here, which wasn't ready for wide deployment # and was backed out. This placeholder is left behind to avoid # confusing the migration engine on any installs that applied the # migration. (Fortunately no reverse migration is needed.) ] # type: List[Any]
# -*- coding: utf-8 -*- from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('zerver', '0126_prereg_remove_users_without_realm'), ] operations = [ # There was a migration here, which wasn't ready for wide deployment # and was backed out. This placeholder is left behind to avoid # confusing the migration engine on any installs that applied the # migration. (Fortunately no reverse migration is needed.) ] migrations: Fix mypy error in placeholder migration.# -*- coding: utf-8 -*- from typing import Any, List from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('zerver', '0126_prereg_remove_users_without_realm'), ] operations = [ # There was a migration here, which wasn't ready for wide deployment # and was backed out. This placeholder is left behind to avoid # confusing the migration engine on any installs that applied the # migration. (Fortunately no reverse migration is needed.) ] # type: List[Any]
<commit_before># -*- coding: utf-8 -*- from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('zerver', '0126_prereg_remove_users_without_realm'), ] operations = [ # There was a migration here, which wasn't ready for wide deployment # and was backed out. This placeholder is left behind to avoid # confusing the migration engine on any installs that applied the # migration. (Fortunately no reverse migration is needed.) ] <commit_msg>migrations: Fix mypy error in placeholder migration.<commit_after># -*- coding: utf-8 -*- from typing import Any, List from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('zerver', '0126_prereg_remove_users_without_realm'), ] operations = [ # There was a migration here, which wasn't ready for wide deployment # and was backed out. This placeholder is left behind to avoid # confusing the migration engine on any installs that applied the # migration. (Fortunately no reverse migration is needed.) ] # type: List[Any]
4649ea618a4f41f5a2f54eb73806d3e1b98e5e00
Python/number-complement.py
Python/number-complement.py
# Time: O(1) # Space: O(1) # Given a positive integer, output its complement number. # The complement strategy is to flip the bits of its binary representation. # # Note: # The given integer is guaranteed to fit within the range of a 32-bit signed integer. # You could assume no leading zero bit in the integer’s binary representation. # Example 1: # Input: 5 # Output: 2 # Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2. # Example 2: # Input: 1 # Output: 0 # Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0. class Solution(object): def findComplement(self, num): """ :type num: int :rtype: int """ return 2 ** (len(bin(num)) - 2) - 1 - num class Solution2(object): def findComplement(self, num): i = 1 while i <= num: i <<= 1 return (i - 1) ^ num
# Time: O(1) # Space: O(1) # Given a positive integer, output its complement number. # The complement strategy is to flip the bits of its binary representation. # # Note: # The given integer is guaranteed to fit within the range of a 32-bit signed integer. # You could assume no leading zero bit in the integer’s binary representation. # Example 1: # Input: 5 # Output: 2 # Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2. # Example 2: # Input: 1 # Output: 0 # Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0. class Solution(object): def findComplement(self, num): """ :type num: int :rtype: int """ return 2 ** (len(bin(num)) - 2) - 1 - num class Solution2(object): def findComplement(self, num): i = 1 while i <= num: i <<= 1 return (i - 1) ^ num class Solution3(object): def findComplement(self, num): bits = '{0:b}'.format(num) complement_bits = ''.join('1' if bit == '0' else '0' for bit in bits) return int(complement_bits, 2)
Add another solution for 'Number complement' problem
Add another solution for 'Number complement' problem
Python
mit
kamyu104/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,kamyu104/LeetCode,kamyu104/LeetCode,kamyu104/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,kamyu104/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,tudennis/LeetCode---kamyu104-11-24-2015,tudennis/LeetCode---kamyu104-11-24-2015
# Time: O(1) # Space: O(1) # Given a positive integer, output its complement number. # The complement strategy is to flip the bits of its binary representation. # # Note: # The given integer is guaranteed to fit within the range of a 32-bit signed integer. # You could assume no leading zero bit in the integer’s binary representation. # Example 1: # Input: 5 # Output: 2 # Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2. # Example 2: # Input: 1 # Output: 0 # Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0. class Solution(object): def findComplement(self, num): """ :type num: int :rtype: int """ return 2 ** (len(bin(num)) - 2) - 1 - num class Solution2(object): def findComplement(self, num): i = 1 while i <= num: i <<= 1 return (i - 1) ^ num Add another solution for 'Number complement' problem
# Time: O(1) # Space: O(1) # Given a positive integer, output its complement number. # The complement strategy is to flip the bits of its binary representation. # # Note: # The given integer is guaranteed to fit within the range of a 32-bit signed integer. # You could assume no leading zero bit in the integer’s binary representation. # Example 1: # Input: 5 # Output: 2 # Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2. # Example 2: # Input: 1 # Output: 0 # Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0. class Solution(object): def findComplement(self, num): """ :type num: int :rtype: int """ return 2 ** (len(bin(num)) - 2) - 1 - num class Solution2(object): def findComplement(self, num): i = 1 while i <= num: i <<= 1 return (i - 1) ^ num class Solution3(object): def findComplement(self, num): bits = '{0:b}'.format(num) complement_bits = ''.join('1' if bit == '0' else '0' for bit in bits) return int(complement_bits, 2)
<commit_before># Time: O(1) # Space: O(1) # Given a positive integer, output its complement number. # The complement strategy is to flip the bits of its binary representation. # # Note: # The given integer is guaranteed to fit within the range of a 32-bit signed integer. # You could assume no leading zero bit in the integer’s binary representation. # Example 1: # Input: 5 # Output: 2 # Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2. # Example 2: # Input: 1 # Output: 0 # Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0. class Solution(object): def findComplement(self, num): """ :type num: int :rtype: int """ return 2 ** (len(bin(num)) - 2) - 1 - num class Solution2(object): def findComplement(self, num): i = 1 while i <= num: i <<= 1 return (i - 1) ^ num <commit_msg>Add another solution for 'Number complement' problem<commit_after>
# Time: O(1) # Space: O(1) # Given a positive integer, output its complement number. # The complement strategy is to flip the bits of its binary representation. # # Note: # The given integer is guaranteed to fit within the range of a 32-bit signed integer. # You could assume no leading zero bit in the integer’s binary representation. # Example 1: # Input: 5 # Output: 2 # Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2. # Example 2: # Input: 1 # Output: 0 # Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0. class Solution(object): def findComplement(self, num): """ :type num: int :rtype: int """ return 2 ** (len(bin(num)) - 2) - 1 - num class Solution2(object): def findComplement(self, num): i = 1 while i <= num: i <<= 1 return (i - 1) ^ num class Solution3(object): def findComplement(self, num): bits = '{0:b}'.format(num) complement_bits = ''.join('1' if bit == '0' else '0' for bit in bits) return int(complement_bits, 2)
# Time: O(1) # Space: O(1) # Given a positive integer, output its complement number. # The complement strategy is to flip the bits of its binary representation. # # Note: # The given integer is guaranteed to fit within the range of a 32-bit signed integer. # You could assume no leading zero bit in the integer’s binary representation. # Example 1: # Input: 5 # Output: 2 # Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2. # Example 2: # Input: 1 # Output: 0 # Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0. class Solution(object): def findComplement(self, num): """ :type num: int :rtype: int """ return 2 ** (len(bin(num)) - 2) - 1 - num class Solution2(object): def findComplement(self, num): i = 1 while i <= num: i <<= 1 return (i - 1) ^ num Add another solution for 'Number complement' problem# Time: O(1) # Space: O(1) # Given a positive integer, output its complement number. # The complement strategy is to flip the bits of its binary representation. # # Note: # The given integer is guaranteed to fit within the range of a 32-bit signed integer. # You could assume no leading zero bit in the integer’s binary representation. # Example 1: # Input: 5 # Output: 2 # Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2. # Example 2: # Input: 1 # Output: 0 # Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0. class Solution(object): def findComplement(self, num): """ :type num: int :rtype: int """ return 2 ** (len(bin(num)) - 2) - 1 - num class Solution2(object): def findComplement(self, num): i = 1 while i <= num: i <<= 1 return (i - 1) ^ num class Solution3(object): def findComplement(self, num): bits = '{0:b}'.format(num) complement_bits = ''.join('1' if bit == '0' else '0' for bit in bits) return int(complement_bits, 2)
<commit_before># Time: O(1) # Space: O(1) # Given a positive integer, output its complement number. # The complement strategy is to flip the bits of its binary representation. # # Note: # The given integer is guaranteed to fit within the range of a 32-bit signed integer. # You could assume no leading zero bit in the integer’s binary representation. # Example 1: # Input: 5 # Output: 2 # Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2. # Example 2: # Input: 1 # Output: 0 # Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0. class Solution(object): def findComplement(self, num): """ :type num: int :rtype: int """ return 2 ** (len(bin(num)) - 2) - 1 - num class Solution2(object): def findComplement(self, num): i = 1 while i <= num: i <<= 1 return (i - 1) ^ num <commit_msg>Add another solution for 'Number complement' problem<commit_after># Time: O(1) # Space: O(1) # Given a positive integer, output its complement number. # The complement strategy is to flip the bits of its binary representation. # # Note: # The given integer is guaranteed to fit within the range of a 32-bit signed integer. # You could assume no leading zero bit in the integer’s binary representation. # Example 1: # Input: 5 # Output: 2 # Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2. # Example 2: # Input: 1 # Output: 0 # Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0. class Solution(object): def findComplement(self, num): """ :type num: int :rtype: int """ return 2 ** (len(bin(num)) - 2) - 1 - num class Solution2(object): def findComplement(self, num): i = 1 while i <= num: i <<= 1 return (i - 1) ^ num class Solution3(object): def findComplement(self, num): bits = '{0:b}'.format(num) complement_bits = ''.join('1' if bit == '0' else '0' for bit in bits) return int(complement_bits, 2)
a4b3c62660f394bb6205f5a4bd915782752ddb8d
byceps/announce/discord/connections.py
byceps/announce/discord/connections.py
""" byceps.announce.discord.connections ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Announce events on Discord. :Copyright: 2006-2020 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from typing import Optional from ...events.board import BoardPostingCreated, BoardTopicCreated from ...events.news import NewsItemPublished from ...signals import board as board_signals from ...signals import news as news_signals from ...util.jobqueue import enqueue from . import board, news # board @board_signals.topic_created.connect def _on_board_topic_created( sender, *, event: Optional[BoardTopicCreated] = None ) -> None: enqueue(board.announce_board_topic_created, event) @board_signals.posting_created.connect def _on_board_posting_created( sender, *, event: Optional[BoardPostingCreated] = None ) -> None: enqueue(board.announce_board_posting_created, event) # news @news_signals.item_published.connect def _on_news_item_published( sender, *, event: Optional[NewsItemPublished] = None ) -> None: enqueue(news.announce_news_item_published, event)
""" byceps.announce.discord.connections ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Announce events on Discord. :Copyright: 2006-2020 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from typing import Optional from ...events.base import _BaseEvent from ...events.board import BoardPostingCreated, BoardTopicCreated from ...events.news import NewsItemPublished from ...signals import board as board_signals from ...signals import news as news_signals from ...util.jobqueue import enqueue from . import board, news EVENT_TYPES_TO_HANDLERS = { BoardTopicCreated: board.announce_board_topic_created, BoardPostingCreated: board.announce_board_posting_created, NewsItemPublished: news.announce_news_item_published, } @board_signals.topic_created.connect @board_signals.posting_created.connect @news_signals.item_published.connect def _on_event(sender, *, event: Optional[_BaseEvent] = None) -> None: event_type = type(event) handler = EVENT_TYPES_TO_HANDLERS.get(event_type) if handler is None: return None enqueue(handler, event)
Compress Discord event connectors into single function
Compress Discord event connectors into single function
Python
bsd-3-clause
homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps
""" byceps.announce.discord.connections ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Announce events on Discord. :Copyright: 2006-2020 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from typing import Optional from ...events.board import BoardPostingCreated, BoardTopicCreated from ...events.news import NewsItemPublished from ...signals import board as board_signals from ...signals import news as news_signals from ...util.jobqueue import enqueue from . import board, news # board @board_signals.topic_created.connect def _on_board_topic_created( sender, *, event: Optional[BoardTopicCreated] = None ) -> None: enqueue(board.announce_board_topic_created, event) @board_signals.posting_created.connect def _on_board_posting_created( sender, *, event: Optional[BoardPostingCreated] = None ) -> None: enqueue(board.announce_board_posting_created, event) # news @news_signals.item_published.connect def _on_news_item_published( sender, *, event: Optional[NewsItemPublished] = None ) -> None: enqueue(news.announce_news_item_published, event) Compress Discord event connectors into single function
""" byceps.announce.discord.connections ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Announce events on Discord. :Copyright: 2006-2020 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from typing import Optional from ...events.base import _BaseEvent from ...events.board import BoardPostingCreated, BoardTopicCreated from ...events.news import NewsItemPublished from ...signals import board as board_signals from ...signals import news as news_signals from ...util.jobqueue import enqueue from . import board, news EVENT_TYPES_TO_HANDLERS = { BoardTopicCreated: board.announce_board_topic_created, BoardPostingCreated: board.announce_board_posting_created, NewsItemPublished: news.announce_news_item_published, } @board_signals.topic_created.connect @board_signals.posting_created.connect @news_signals.item_published.connect def _on_event(sender, *, event: Optional[_BaseEvent] = None) -> None: event_type = type(event) handler = EVENT_TYPES_TO_HANDLERS.get(event_type) if handler is None: return None enqueue(handler, event)
<commit_before>""" byceps.announce.discord.connections ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Announce events on Discord. :Copyright: 2006-2020 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from typing import Optional from ...events.board import BoardPostingCreated, BoardTopicCreated from ...events.news import NewsItemPublished from ...signals import board as board_signals from ...signals import news as news_signals from ...util.jobqueue import enqueue from . import board, news # board @board_signals.topic_created.connect def _on_board_topic_created( sender, *, event: Optional[BoardTopicCreated] = None ) -> None: enqueue(board.announce_board_topic_created, event) @board_signals.posting_created.connect def _on_board_posting_created( sender, *, event: Optional[BoardPostingCreated] = None ) -> None: enqueue(board.announce_board_posting_created, event) # news @news_signals.item_published.connect def _on_news_item_published( sender, *, event: Optional[NewsItemPublished] = None ) -> None: enqueue(news.announce_news_item_published, event) <commit_msg>Compress Discord event connectors into single function<commit_after>
""" byceps.announce.discord.connections ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Announce events on Discord. :Copyright: 2006-2020 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from typing import Optional from ...events.base import _BaseEvent from ...events.board import BoardPostingCreated, BoardTopicCreated from ...events.news import NewsItemPublished from ...signals import board as board_signals from ...signals import news as news_signals from ...util.jobqueue import enqueue from . import board, news EVENT_TYPES_TO_HANDLERS = { BoardTopicCreated: board.announce_board_topic_created, BoardPostingCreated: board.announce_board_posting_created, NewsItemPublished: news.announce_news_item_published, } @board_signals.topic_created.connect @board_signals.posting_created.connect @news_signals.item_published.connect def _on_event(sender, *, event: Optional[_BaseEvent] = None) -> None: event_type = type(event) handler = EVENT_TYPES_TO_HANDLERS.get(event_type) if handler is None: return None enqueue(handler, event)
""" byceps.announce.discord.connections ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Announce events on Discord. :Copyright: 2006-2020 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from typing import Optional from ...events.board import BoardPostingCreated, BoardTopicCreated from ...events.news import NewsItemPublished from ...signals import board as board_signals from ...signals import news as news_signals from ...util.jobqueue import enqueue from . import board, news # board @board_signals.topic_created.connect def _on_board_topic_created( sender, *, event: Optional[BoardTopicCreated] = None ) -> None: enqueue(board.announce_board_topic_created, event) @board_signals.posting_created.connect def _on_board_posting_created( sender, *, event: Optional[BoardPostingCreated] = None ) -> None: enqueue(board.announce_board_posting_created, event) # news @news_signals.item_published.connect def _on_news_item_published( sender, *, event: Optional[NewsItemPublished] = None ) -> None: enqueue(news.announce_news_item_published, event) Compress Discord event connectors into single function""" byceps.announce.discord.connections ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Announce events on Discord. :Copyright: 2006-2020 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from typing import Optional from ...events.base import _BaseEvent from ...events.board import BoardPostingCreated, BoardTopicCreated from ...events.news import NewsItemPublished from ...signals import board as board_signals from ...signals import news as news_signals from ...util.jobqueue import enqueue from . import board, news EVENT_TYPES_TO_HANDLERS = { BoardTopicCreated: board.announce_board_topic_created, BoardPostingCreated: board.announce_board_posting_created, NewsItemPublished: news.announce_news_item_published, } @board_signals.topic_created.connect @board_signals.posting_created.connect @news_signals.item_published.connect def _on_event(sender, *, event: Optional[_BaseEvent] = None) -> None: event_type = type(event) handler = EVENT_TYPES_TO_HANDLERS.get(event_type) if handler is None: return None enqueue(handler, event)
<commit_before>""" byceps.announce.discord.connections ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Announce events on Discord. :Copyright: 2006-2020 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from typing import Optional from ...events.board import BoardPostingCreated, BoardTopicCreated from ...events.news import NewsItemPublished from ...signals import board as board_signals from ...signals import news as news_signals from ...util.jobqueue import enqueue from . import board, news # board @board_signals.topic_created.connect def _on_board_topic_created( sender, *, event: Optional[BoardTopicCreated] = None ) -> None: enqueue(board.announce_board_topic_created, event) @board_signals.posting_created.connect def _on_board_posting_created( sender, *, event: Optional[BoardPostingCreated] = None ) -> None: enqueue(board.announce_board_posting_created, event) # news @news_signals.item_published.connect def _on_news_item_published( sender, *, event: Optional[NewsItemPublished] = None ) -> None: enqueue(news.announce_news_item_published, event) <commit_msg>Compress Discord event connectors into single function<commit_after>""" byceps.announce.discord.connections ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Announce events on Discord. :Copyright: 2006-2020 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from typing import Optional from ...events.base import _BaseEvent from ...events.board import BoardPostingCreated, BoardTopicCreated from ...events.news import NewsItemPublished from ...signals import board as board_signals from ...signals import news as news_signals from ...util.jobqueue import enqueue from . import board, news EVENT_TYPES_TO_HANDLERS = { BoardTopicCreated: board.announce_board_topic_created, BoardPostingCreated: board.announce_board_posting_created, NewsItemPublished: news.announce_news_item_published, } @board_signals.topic_created.connect @board_signals.posting_created.connect @news_signals.item_published.connect def _on_event(sender, *, event: Optional[_BaseEvent] = None) -> None: event_type = type(event) handler = EVENT_TYPES_TO_HANDLERS.get(event_type) if handler is None: return None enqueue(handler, event)
acccb727054d919a2a36854d8bac502274ed3bdd
mp3-formatter/rename_mp3.py
mp3-formatter/rename_mp3.py
#!/usr/bin/python3 import ID3 import os import sys def read_tracklist(): tracklist = [] for line in sys.stdin: tracklist.append(line) return tracklist tracklist = read_tracklist() mp3_extension = ".mp3" files_all = os.listdir('.') files = [] for f in files_all: # Prune directories if not os.path.isfile(f): continue # Prune non-MP3 files filename, extension = os.path.splitext(f) if extension != mp3_extension: continue # Prune this file f_temp = os.path.abspath(f) if f_temp == os.path.abspath(__file__): continue files.append(f) if len(files) != len(tracklist): raise RuntimeError( str(len(tracklist)) + " file names were given but " + str(len(files)) + " files were found.") sys.exit() files.sort() i = 0 for f in files: os.rename(f, tracklist[i] + mp3_extension) i += 1
#!/usr/bin/python3 import ID3 import os import sys def read_tracklist(): tracklist = [] for line in sys.stdin: tracklist.append(line) return tracklist def match_length(files, tracklist): if len(files) != len(tracklist): raise RuntimeError( str(len(tracklist)) + " file names were given but " + str(len(files)) + " files were found.") tracklist = read_tracklist() mp3_extension = ".mp3" files_all = os.listdir('.') files = [] for f in files_all: # Prune directories if not os.path.isfile(f): continue # Prune non-MP3 files filename, extension = os.path.splitext(f) if extension != mp3_extension: continue # Prune this file f_temp = os.path.abspath(f) if f_temp == os.path.abspath(__file__): continue files.append(f) match_length(files, tracklist) files.sort() i = 0 for f in files: os.rename(f, tracklist[i] + mp3_extension) i += 1
Move files/tracklist count check to function
MP3: Move files/tracklist count check to function
Python
mit
jleung51/scripts,jleung51/scripts,jleung51/scripts
#!/usr/bin/python3 import ID3 import os import sys def read_tracklist(): tracklist = [] for line in sys.stdin: tracklist.append(line) return tracklist tracklist = read_tracklist() mp3_extension = ".mp3" files_all = os.listdir('.') files = [] for f in files_all: # Prune directories if not os.path.isfile(f): continue # Prune non-MP3 files filename, extension = os.path.splitext(f) if extension != mp3_extension: continue # Prune this file f_temp = os.path.abspath(f) if f_temp == os.path.abspath(__file__): continue files.append(f) if len(files) != len(tracklist): raise RuntimeError( str(len(tracklist)) + " file names were given but " + str(len(files)) + " files were found.") sys.exit() files.sort() i = 0 for f in files: os.rename(f, tracklist[i] + mp3_extension) i += 1 MP3: Move files/tracklist count check to function
#!/usr/bin/python3 import ID3 import os import sys def read_tracklist(): tracklist = [] for line in sys.stdin: tracklist.append(line) return tracklist def match_length(files, tracklist): if len(files) != len(tracklist): raise RuntimeError( str(len(tracklist)) + " file names were given but " + str(len(files)) + " files were found.") tracklist = read_tracklist() mp3_extension = ".mp3" files_all = os.listdir('.') files = [] for f in files_all: # Prune directories if not os.path.isfile(f): continue # Prune non-MP3 files filename, extension = os.path.splitext(f) if extension != mp3_extension: continue # Prune this file f_temp = os.path.abspath(f) if f_temp == os.path.abspath(__file__): continue files.append(f) match_length(files, tracklist) files.sort() i = 0 for f in files: os.rename(f, tracklist[i] + mp3_extension) i += 1
<commit_before>#!/usr/bin/python3 import ID3 import os import sys def read_tracklist(): tracklist = [] for line in sys.stdin: tracklist.append(line) return tracklist tracklist = read_tracklist() mp3_extension = ".mp3" files_all = os.listdir('.') files = [] for f in files_all: # Prune directories if not os.path.isfile(f): continue # Prune non-MP3 files filename, extension = os.path.splitext(f) if extension != mp3_extension: continue # Prune this file f_temp = os.path.abspath(f) if f_temp == os.path.abspath(__file__): continue files.append(f) if len(files) != len(tracklist): raise RuntimeError( str(len(tracklist)) + " file names were given but " + str(len(files)) + " files were found.") sys.exit() files.sort() i = 0 for f in files: os.rename(f, tracklist[i] + mp3_extension) i += 1 <commit_msg>MP3: Move files/tracklist count check to function<commit_after>
#!/usr/bin/python3 import ID3 import os import sys def read_tracklist(): tracklist = [] for line in sys.stdin: tracklist.append(line) return tracklist def match_length(files, tracklist): if len(files) != len(tracklist): raise RuntimeError( str(len(tracklist)) + " file names were given but " + str(len(files)) + " files were found.") tracklist = read_tracklist() mp3_extension = ".mp3" files_all = os.listdir('.') files = [] for f in files_all: # Prune directories if not os.path.isfile(f): continue # Prune non-MP3 files filename, extension = os.path.splitext(f) if extension != mp3_extension: continue # Prune this file f_temp = os.path.abspath(f) if f_temp == os.path.abspath(__file__): continue files.append(f) match_length(files, tracklist) files.sort() i = 0 for f in files: os.rename(f, tracklist[i] + mp3_extension) i += 1
#!/usr/bin/python3 import ID3 import os import sys def read_tracklist(): tracklist = [] for line in sys.stdin: tracklist.append(line) return tracklist tracklist = read_tracklist() mp3_extension = ".mp3" files_all = os.listdir('.') files = [] for f in files_all: # Prune directories if not os.path.isfile(f): continue # Prune non-MP3 files filename, extension = os.path.splitext(f) if extension != mp3_extension: continue # Prune this file f_temp = os.path.abspath(f) if f_temp == os.path.abspath(__file__): continue files.append(f) if len(files) != len(tracklist): raise RuntimeError( str(len(tracklist)) + " file names were given but " + str(len(files)) + " files were found.") sys.exit() files.sort() i = 0 for f in files: os.rename(f, tracklist[i] + mp3_extension) i += 1 MP3: Move files/tracklist count check to function#!/usr/bin/python3 import ID3 import os import sys def read_tracklist(): tracklist = [] for line in sys.stdin: tracklist.append(line) return tracklist def match_length(files, tracklist): if len(files) != len(tracklist): raise RuntimeError( str(len(tracklist)) + " file names were given but " + str(len(files)) + " files were found.") tracklist = read_tracklist() mp3_extension = ".mp3" files_all = os.listdir('.') files = [] for f in files_all: # Prune directories if not os.path.isfile(f): continue # Prune non-MP3 files filename, extension = os.path.splitext(f) if extension != mp3_extension: continue # Prune this file f_temp = os.path.abspath(f) if f_temp == os.path.abspath(__file__): continue files.append(f) match_length(files, tracklist) files.sort() i = 0 for f in files: os.rename(f, tracklist[i] + mp3_extension) i += 1
<commit_before>#!/usr/bin/python3 import ID3 import os import sys def read_tracklist(): tracklist = [] for line in sys.stdin: tracklist.append(line) return tracklist tracklist = read_tracklist() mp3_extension = ".mp3" files_all = os.listdir('.') files = [] for f in files_all: # Prune directories if not os.path.isfile(f): continue # Prune non-MP3 files filename, extension = os.path.splitext(f) if extension != mp3_extension: continue # Prune this file f_temp = os.path.abspath(f) if f_temp == os.path.abspath(__file__): continue files.append(f) if len(files) != len(tracklist): raise RuntimeError( str(len(tracklist)) + " file names were given but " + str(len(files)) + " files were found.") sys.exit() files.sort() i = 0 for f in files: os.rename(f, tracklist[i] + mp3_extension) i += 1 <commit_msg>MP3: Move files/tracklist count check to function<commit_after>#!/usr/bin/python3 import ID3 import os import sys def read_tracklist(): tracklist = [] for line in sys.stdin: tracklist.append(line) return tracklist def match_length(files, tracklist): if len(files) != len(tracklist): raise RuntimeError( str(len(tracklist)) + " file names were given but " + str(len(files)) + " files were found.") tracklist = read_tracklist() mp3_extension = ".mp3" files_all = os.listdir('.') files = [] for f in files_all: # Prune directories if not os.path.isfile(f): continue # Prune non-MP3 files filename, extension = os.path.splitext(f) if extension != mp3_extension: continue # Prune this file f_temp = os.path.abspath(f) if f_temp == os.path.abspath(__file__): continue files.append(f) match_length(files, tracklist) files.sort() i = 0 for f in files: os.rename(f, tracklist[i] + mp3_extension) i += 1
86dbcaee58bbd529984f36a14aba777ac336ca34
myfedora/lib/app_globals.py
myfedora/lib/app_globals.py
"""The application's Globals object""" from app_factory import AppFactoryDict class Globals(object): """Globals acts as a container for objects available throughout the life of the application """ def __init__(self): """One instance of Globals is created during application initialization and is available during requests via the 'g' variable """ self.widgets = {'home': {}, 'canvas': {}, 'profile': {}, 'preview': {}, 'config':{}} # {viewtype: {name: Widget instance}} self.resourceviews = AppFactoryDict() # {name: ResourceView instance} self.apps = AppFactoryDict() # {name: App instance} # Our comet data streamer, responsible for polling the data # streams, and providing data to the widgets #from myfedora.streams import DataStreamer #self.datastreamer = DataStreamer() FEED_CACHE = "/tmp/moksha-feeds" from shove import Shove from feedcache.cache import Cache self.feed_storage = Shove('file://' + FEED_CACHE) self.feed_cache = Cache(self.feed_storage)
"""The application's Globals object""" from app_factory import AppFactoryDict class Globals(object): """Globals acts as a container for objects available throughout the life of the application """ def __init__(self): """One instance of Globals is created during application initialization and is available during requests via the 'g' variable """ self.widgets = {'home': {}, 'canvas': {}, 'profile': {}, 'preview': {}, 'config':{}} # {viewtype: {name: Widget instance}} self.resourceviews = AppFactoryDict() # {name: ResourceView instance} self.apps = AppFactoryDict() # {name: App instance} # Our comet data streamer, responsible for polling the data # streams, and providing data to the widgets #from myfedora.streams import DataStreamer #self.datastreamer = DataStreamer() #FEED_CACHE = "/tmp/moksha-feeds" #from shove import Shove #from feedcache.cache import Cache #self.feed_storage = Shove('file://' + FEED_CACHE) #self.feed_cache = Cache(self.feed_storage)
Comment out the Shove object, as we are not using it yet
Comment out the Shove object, as we are not using it yet
Python
agpl-3.0
Fale/fedora-packages,fedora-infra/fedora-packages,Fale/fedora-packages,fedora-infra/fedora-packages,Fale/fedora-packages,fedora-infra/fedora-packages,fedora-infra/fedora-packages
"""The application's Globals object""" from app_factory import AppFactoryDict class Globals(object): """Globals acts as a container for objects available throughout the life of the application """ def __init__(self): """One instance of Globals is created during application initialization and is available during requests via the 'g' variable """ self.widgets = {'home': {}, 'canvas': {}, 'profile': {}, 'preview': {}, 'config':{}} # {viewtype: {name: Widget instance}} self.resourceviews = AppFactoryDict() # {name: ResourceView instance} self.apps = AppFactoryDict() # {name: App instance} # Our comet data streamer, responsible for polling the data # streams, and providing data to the widgets #from myfedora.streams import DataStreamer #self.datastreamer = DataStreamer() FEED_CACHE = "/tmp/moksha-feeds" from shove import Shove from feedcache.cache import Cache self.feed_storage = Shove('file://' + FEED_CACHE) self.feed_cache = Cache(self.feed_storage) Comment out the Shove object, as we are not using it yet
"""The application's Globals object""" from app_factory import AppFactoryDict class Globals(object): """Globals acts as a container for objects available throughout the life of the application """ def __init__(self): """One instance of Globals is created during application initialization and is available during requests via the 'g' variable """ self.widgets = {'home': {}, 'canvas': {}, 'profile': {}, 'preview': {}, 'config':{}} # {viewtype: {name: Widget instance}} self.resourceviews = AppFactoryDict() # {name: ResourceView instance} self.apps = AppFactoryDict() # {name: App instance} # Our comet data streamer, responsible for polling the data # streams, and providing data to the widgets #from myfedora.streams import DataStreamer #self.datastreamer = DataStreamer() #FEED_CACHE = "/tmp/moksha-feeds" #from shove import Shove #from feedcache.cache import Cache #self.feed_storage = Shove('file://' + FEED_CACHE) #self.feed_cache = Cache(self.feed_storage)
<commit_before>"""The application's Globals object""" from app_factory import AppFactoryDict class Globals(object): """Globals acts as a container for objects available throughout the life of the application """ def __init__(self): """One instance of Globals is created during application initialization and is available during requests via the 'g' variable """ self.widgets = {'home': {}, 'canvas': {}, 'profile': {}, 'preview': {}, 'config':{}} # {viewtype: {name: Widget instance}} self.resourceviews = AppFactoryDict() # {name: ResourceView instance} self.apps = AppFactoryDict() # {name: App instance} # Our comet data streamer, responsible for polling the data # streams, and providing data to the widgets #from myfedora.streams import DataStreamer #self.datastreamer = DataStreamer() FEED_CACHE = "/tmp/moksha-feeds" from shove import Shove from feedcache.cache import Cache self.feed_storage = Shove('file://' + FEED_CACHE) self.feed_cache = Cache(self.feed_storage) <commit_msg>Comment out the Shove object, as we are not using it yet<commit_after>
"""The application's Globals object""" from app_factory import AppFactoryDict class Globals(object): """Globals acts as a container for objects available throughout the life of the application """ def __init__(self): """One instance of Globals is created during application initialization and is available during requests via the 'g' variable """ self.widgets = {'home': {}, 'canvas': {}, 'profile': {}, 'preview': {}, 'config':{}} # {viewtype: {name: Widget instance}} self.resourceviews = AppFactoryDict() # {name: ResourceView instance} self.apps = AppFactoryDict() # {name: App instance} # Our comet data streamer, responsible for polling the data # streams, and providing data to the widgets #from myfedora.streams import DataStreamer #self.datastreamer = DataStreamer() #FEED_CACHE = "/tmp/moksha-feeds" #from shove import Shove #from feedcache.cache import Cache #self.feed_storage = Shove('file://' + FEED_CACHE) #self.feed_cache = Cache(self.feed_storage)
"""The application's Globals object""" from app_factory import AppFactoryDict class Globals(object): """Globals acts as a container for objects available throughout the life of the application """ def __init__(self): """One instance of Globals is created during application initialization and is available during requests via the 'g' variable """ self.widgets = {'home': {}, 'canvas': {}, 'profile': {}, 'preview': {}, 'config':{}} # {viewtype: {name: Widget instance}} self.resourceviews = AppFactoryDict() # {name: ResourceView instance} self.apps = AppFactoryDict() # {name: App instance} # Our comet data streamer, responsible for polling the data # streams, and providing data to the widgets #from myfedora.streams import DataStreamer #self.datastreamer = DataStreamer() FEED_CACHE = "/tmp/moksha-feeds" from shove import Shove from feedcache.cache import Cache self.feed_storage = Shove('file://' + FEED_CACHE) self.feed_cache = Cache(self.feed_storage) Comment out the Shove object, as we are not using it yet"""The application's Globals object""" from app_factory import AppFactoryDict class Globals(object): """Globals acts as a container for objects available throughout the life of the application """ def __init__(self): """One instance of Globals is created during application initialization and is available during requests via the 'g' variable """ self.widgets = {'home': {}, 'canvas': {}, 'profile': {}, 'preview': {}, 'config':{}} # {viewtype: {name: Widget instance}} self.resourceviews = AppFactoryDict() # {name: ResourceView instance} self.apps = AppFactoryDict() # {name: App instance} # Our comet data streamer, responsible for polling the data # streams, and providing data to the widgets #from myfedora.streams import DataStreamer #self.datastreamer = DataStreamer() #FEED_CACHE = "/tmp/moksha-feeds" #from shove import Shove #from feedcache.cache import Cache #self.feed_storage = Shove('file://' + FEED_CACHE) #self.feed_cache = Cache(self.feed_storage)
<commit_before>"""The application's Globals object""" from app_factory import AppFactoryDict class Globals(object): """Globals acts as a container for objects available throughout the life of the application """ def __init__(self): """One instance of Globals is created during application initialization and is available during requests via the 'g' variable """ self.widgets = {'home': {}, 'canvas': {}, 'profile': {}, 'preview': {}, 'config':{}} # {viewtype: {name: Widget instance}} self.resourceviews = AppFactoryDict() # {name: ResourceView instance} self.apps = AppFactoryDict() # {name: App instance} # Our comet data streamer, responsible for polling the data # streams, and providing data to the widgets #from myfedora.streams import DataStreamer #self.datastreamer = DataStreamer() FEED_CACHE = "/tmp/moksha-feeds" from shove import Shove from feedcache.cache import Cache self.feed_storage = Shove('file://' + FEED_CACHE) self.feed_cache = Cache(self.feed_storage) <commit_msg>Comment out the Shove object, as we are not using it yet<commit_after>"""The application's Globals object""" from app_factory import AppFactoryDict class Globals(object): """Globals acts as a container for objects available throughout the life of the application """ def __init__(self): """One instance of Globals is created during application initialization and is available during requests via the 'g' variable """ self.widgets = {'home': {}, 'canvas': {}, 'profile': {}, 'preview': {}, 'config':{}} # {viewtype: {name: Widget instance}} self.resourceviews = AppFactoryDict() # {name: ResourceView instance} self.apps = AppFactoryDict() # {name: App instance} # Our comet data streamer, responsible for polling the data # streams, and providing data to the widgets #from myfedora.streams import DataStreamer #self.datastreamer = DataStreamer() #FEED_CACHE = "/tmp/moksha-feeds" #from shove import Shove #from feedcache.cache import Cache #self.feed_storage = Shove('file://' + FEED_CACHE) #self.feed_cache = Cache(self.feed_storage)
fc2b587d792c19afe00caf129057afa686bdc684
web_utils.py
web_utils.py
"""Collection of HTTP helpers.""" from functools import partial, wraps from inspect import iscoroutine from aiohttp.web import json_response def async_json_out(orig_method=None, *, status=200, content_type='application/json', **dec_kwargs): """Turn dict output of an HTTP handler into JSON response. Decorates aiohttp request handlers. """ if orig_method is None: return partial(async_json_out, status=200, content_type='application/json', **dec_kwargs) @wraps(orig_method) async def wrapper(*args, **kwargs): dict_resp = orig_method(*args, **kwargs) if iscoroutine(dict_resp): dict_resp = await dict_resp try: status = dict_resp['status'] except KeyError: dict_resp['status'] = status return json_response( dict_resp, status=status, content_type=content_type, **dec_kwargs ) return wrapper
"""Collection of HTTP helpers.""" from functools import partial, wraps from inspect import iscoroutine from aiohttp.web import ( json_response, HTTPError, HTTPSuccessful, HTTPRedirection ) def async_json_out(orig_method=None, *, status=200, content_type='application/json', **dec_kwargs): """Turn dict output of an HTTP handler into JSON response. Decorates aiohttp request handlers. """ if orig_method is None: return partial(async_json_out, status=200, content_type='application/json', **dec_kwargs) @wraps(orig_method) async def wrapper(*args, **kwargs): try: dict_resp = orig_method(*args, **kwargs) if iscoroutine(dict_resp): dict_resp = await dict_resp except (HTTPSuccessful, HTTPRedirection): raise except HTTPError as he: if he.empty_body: raise status = he.status_code, dict_resp = { 'error': he.body, } try: status = dict_resp['status'] except KeyError: dict_resp['status'] = status return json_response( dict_resp, status=status, content_type=content_type, **dec_kwargs ) return wrapper
Handle HTTP errors raised within web handlers
Handle HTTP errors raised within web handlers
Python
mit
open-craft-guild/aio-feature-flags
"""Collection of HTTP helpers.""" from functools import partial, wraps from inspect import iscoroutine from aiohttp.web import json_response def async_json_out(orig_method=None, *, status=200, content_type='application/json', **dec_kwargs): """Turn dict output of an HTTP handler into JSON response. Decorates aiohttp request handlers. """ if orig_method is None: return partial(async_json_out, status=200, content_type='application/json', **dec_kwargs) @wraps(orig_method) async def wrapper(*args, **kwargs): dict_resp = orig_method(*args, **kwargs) if iscoroutine(dict_resp): dict_resp = await dict_resp try: status = dict_resp['status'] except KeyError: dict_resp['status'] = status return json_response( dict_resp, status=status, content_type=content_type, **dec_kwargs ) return wrapper Handle HTTP errors raised within web handlers
"""Collection of HTTP helpers.""" from functools import partial, wraps from inspect import iscoroutine from aiohttp.web import ( json_response, HTTPError, HTTPSuccessful, HTTPRedirection ) def async_json_out(orig_method=None, *, status=200, content_type='application/json', **dec_kwargs): """Turn dict output of an HTTP handler into JSON response. Decorates aiohttp request handlers. """ if orig_method is None: return partial(async_json_out, status=200, content_type='application/json', **dec_kwargs) @wraps(orig_method) async def wrapper(*args, **kwargs): try: dict_resp = orig_method(*args, **kwargs) if iscoroutine(dict_resp): dict_resp = await dict_resp except (HTTPSuccessful, HTTPRedirection): raise except HTTPError as he: if he.empty_body: raise status = he.status_code, dict_resp = { 'error': he.body, } try: status = dict_resp['status'] except KeyError: dict_resp['status'] = status return json_response( dict_resp, status=status, content_type=content_type, **dec_kwargs ) return wrapper
<commit_before>"""Collection of HTTP helpers.""" from functools import partial, wraps from inspect import iscoroutine from aiohttp.web import json_response def async_json_out(orig_method=None, *, status=200, content_type='application/json', **dec_kwargs): """Turn dict output of an HTTP handler into JSON response. Decorates aiohttp request handlers. """ if orig_method is None: return partial(async_json_out, status=200, content_type='application/json', **dec_kwargs) @wraps(orig_method) async def wrapper(*args, **kwargs): dict_resp = orig_method(*args, **kwargs) if iscoroutine(dict_resp): dict_resp = await dict_resp try: status = dict_resp['status'] except KeyError: dict_resp['status'] = status return json_response( dict_resp, status=status, content_type=content_type, **dec_kwargs ) return wrapper <commit_msg>Handle HTTP errors raised within web handlers<commit_after>
"""Collection of HTTP helpers.""" from functools import partial, wraps from inspect import iscoroutine from aiohttp.web import ( json_response, HTTPError, HTTPSuccessful, HTTPRedirection ) def async_json_out(orig_method=None, *, status=200, content_type='application/json', **dec_kwargs): """Turn dict output of an HTTP handler into JSON response. Decorates aiohttp request handlers. """ if orig_method is None: return partial(async_json_out, status=200, content_type='application/json', **dec_kwargs) @wraps(orig_method) async def wrapper(*args, **kwargs): try: dict_resp = orig_method(*args, **kwargs) if iscoroutine(dict_resp): dict_resp = await dict_resp except (HTTPSuccessful, HTTPRedirection): raise except HTTPError as he: if he.empty_body: raise status = he.status_code, dict_resp = { 'error': he.body, } try: status = dict_resp['status'] except KeyError: dict_resp['status'] = status return json_response( dict_resp, status=status, content_type=content_type, **dec_kwargs ) return wrapper
"""Collection of HTTP helpers.""" from functools import partial, wraps from inspect import iscoroutine from aiohttp.web import json_response def async_json_out(orig_method=None, *, status=200, content_type='application/json', **dec_kwargs): """Turn dict output of an HTTP handler into JSON response. Decorates aiohttp request handlers. """ if orig_method is None: return partial(async_json_out, status=200, content_type='application/json', **dec_kwargs) @wraps(orig_method) async def wrapper(*args, **kwargs): dict_resp = orig_method(*args, **kwargs) if iscoroutine(dict_resp): dict_resp = await dict_resp try: status = dict_resp['status'] except KeyError: dict_resp['status'] = status return json_response( dict_resp, status=status, content_type=content_type, **dec_kwargs ) return wrapper Handle HTTP errors raised within web handlers"""Collection of HTTP helpers.""" from functools import partial, wraps from inspect import iscoroutine from aiohttp.web import ( json_response, HTTPError, HTTPSuccessful, HTTPRedirection ) def async_json_out(orig_method=None, *, status=200, content_type='application/json', **dec_kwargs): """Turn dict output of an HTTP handler into JSON response. Decorates aiohttp request handlers. """ if orig_method is None: return partial(async_json_out, status=200, content_type='application/json', **dec_kwargs) @wraps(orig_method) async def wrapper(*args, **kwargs): try: dict_resp = orig_method(*args, **kwargs) if iscoroutine(dict_resp): dict_resp = await dict_resp except (HTTPSuccessful, HTTPRedirection): raise except HTTPError as he: if he.empty_body: raise status = he.status_code, dict_resp = { 'error': he.body, } try: status = dict_resp['status'] except KeyError: dict_resp['status'] = status return json_response( dict_resp, status=status, content_type=content_type, **dec_kwargs ) return wrapper
<commit_before>"""Collection of HTTP helpers.""" from functools import partial, wraps from inspect import iscoroutine from aiohttp.web import json_response def async_json_out(orig_method=None, *, status=200, content_type='application/json', **dec_kwargs): """Turn dict output of an HTTP handler into JSON response. Decorates aiohttp request handlers. """ if orig_method is None: return partial(async_json_out, status=200, content_type='application/json', **dec_kwargs) @wraps(orig_method) async def wrapper(*args, **kwargs): dict_resp = orig_method(*args, **kwargs) if iscoroutine(dict_resp): dict_resp = await dict_resp try: status = dict_resp['status'] except KeyError: dict_resp['status'] = status return json_response( dict_resp, status=status, content_type=content_type, **dec_kwargs ) return wrapper <commit_msg>Handle HTTP errors raised within web handlers<commit_after>"""Collection of HTTP helpers.""" from functools import partial, wraps from inspect import iscoroutine from aiohttp.web import ( json_response, HTTPError, HTTPSuccessful, HTTPRedirection ) def async_json_out(orig_method=None, *, status=200, content_type='application/json', **dec_kwargs): """Turn dict output of an HTTP handler into JSON response. Decorates aiohttp request handlers. """ if orig_method is None: return partial(async_json_out, status=200, content_type='application/json', **dec_kwargs) @wraps(orig_method) async def wrapper(*args, **kwargs): try: dict_resp = orig_method(*args, **kwargs) if iscoroutine(dict_resp): dict_resp = await dict_resp except (HTTPSuccessful, HTTPRedirection): raise except HTTPError as he: if he.empty_body: raise status = he.status_code, dict_resp = { 'error': he.body, } try: status = dict_resp['status'] except KeyError: dict_resp['status'] = status return json_response( dict_resp, status=status, content_type=content_type, **dec_kwargs ) return wrapper
73f4c29d47e23b26483733ab25ea33367657f758
test/selenium/src/lib/page/modal/create_new_object.py
test/selenium/src/lib/page/modal/create_new_object.py
# Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: jernej@reciprocitylabs.com # Maintained By: jernej@reciprocitylabs.com """Modals for creating new objects""" from lib.page.modal import base class NewProgramModal(base.ProgramModal, base.CreateNewObjectModal): """Class representing a program modal visible after creating a new program from LHN""" class NewControlModal(base.ControlModal, base.CreateNewObjectModal): """Class representing a control modal visible after creating a new control from LHN""" class NewOrgGroupModal(base.OrgGroupModal, base.CreateNewObjectModal): """Class representing an org group modal visible after creating a new org group from LHN""" class NewRiskModal(base.RiskModal, base.CreateNewObjectModal): """Class representing a risk modal visible after creating a new risk from LHN"""
# Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: jernej@reciprocitylabs.com # Maintained By: jernej@reciprocitylabs.com """Modals for creating new objects""" from lib.page.modal import base class NewProgramModal(base.ProgramModal, base.CreateNewObjectModal): """Class representing a program modal visible after creating a new program from LHN""" class NewControlModal(base.ControlModal, base.CreateNewObjectModal): """Class representing a control modal visible after creating a new control from LHN""" class NewOrgGroupModal(base.OrgGroupModal, base.CreateNewObjectModal): """Class representing an org group modal visible after creating a new org group from LHN""" class NewRiskModal(base.RiskModal, base.CreateNewObjectModal): """Class representing a risk modal visible after creating a new risk from LHN""" class NewRequestModal(base.RequestModal, base.CreateNewObjectModal): """Class representing an request modal visible after creating a new request from LHN""" class NewIssueModal(base.IssueModal, base.CreateNewObjectModal): """Class representing an issue visible after creating a new issue from LHN"""
Add modals for creating objects
Add modals for creating objects
Python
apache-2.0
plamut/ggrc-core,edofic/ggrc-core,VinnieJohns/ggrc-core,plamut/ggrc-core,andrei-karalionak/ggrc-core,selahssea/ggrc-core,edofic/ggrc-core,j0gurt/ggrc-core,prasannav7/ggrc-core,andrei-karalionak/ggrc-core,VinnieJohns/ggrc-core,j0gurt/ggrc-core,VinnieJohns/ggrc-core,edofic/ggrc-core,josthkko/ggrc-core,j0gurt/ggrc-core,AleksNeStu/ggrc-core,kr41/ggrc-core,kr41/ggrc-core,edofic/ggrc-core,NejcZupec/ggrc-core,plamut/ggrc-core,AleksNeStu/ggrc-core,selahssea/ggrc-core,j0gurt/ggrc-core,prasannav7/ggrc-core,NejcZupec/ggrc-core,AleksNeStu/ggrc-core,josthkko/ggrc-core,prasannav7/ggrc-core,plamut/ggrc-core,AleksNeStu/ggrc-core,selahssea/ggrc-core,kr41/ggrc-core,prasannav7/ggrc-core,NejcZupec/ggrc-core,VinnieJohns/ggrc-core,selahssea/ggrc-core,NejcZupec/ggrc-core,andrei-karalionak/ggrc-core,kr41/ggrc-core,josthkko/ggrc-core,andrei-karalionak/ggrc-core,josthkko/ggrc-core
# Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: jernej@reciprocitylabs.com # Maintained By: jernej@reciprocitylabs.com """Modals for creating new objects""" from lib.page.modal import base class NewProgramModal(base.ProgramModal, base.CreateNewObjectModal): """Class representing a program modal visible after creating a new program from LHN""" class NewControlModal(base.ControlModal, base.CreateNewObjectModal): """Class representing a control modal visible after creating a new control from LHN""" class NewOrgGroupModal(base.OrgGroupModal, base.CreateNewObjectModal): """Class representing an org group modal visible after creating a new org group from LHN""" class NewRiskModal(base.RiskModal, base.CreateNewObjectModal): """Class representing a risk modal visible after creating a new risk from LHN""" Add modals for creating objects
# Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: jernej@reciprocitylabs.com # Maintained By: jernej@reciprocitylabs.com """Modals for creating new objects""" from lib.page.modal import base class NewProgramModal(base.ProgramModal, base.CreateNewObjectModal): """Class representing a program modal visible after creating a new program from LHN""" class NewControlModal(base.ControlModal, base.CreateNewObjectModal): """Class representing a control modal visible after creating a new control from LHN""" class NewOrgGroupModal(base.OrgGroupModal, base.CreateNewObjectModal): """Class representing an org group modal visible after creating a new org group from LHN""" class NewRiskModal(base.RiskModal, base.CreateNewObjectModal): """Class representing a risk modal visible after creating a new risk from LHN""" class NewRequestModal(base.RequestModal, base.CreateNewObjectModal): """Class representing an request modal visible after creating a new request from LHN""" class NewIssueModal(base.IssueModal, base.CreateNewObjectModal): """Class representing an issue visible after creating a new issue from LHN"""
<commit_before># Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: jernej@reciprocitylabs.com # Maintained By: jernej@reciprocitylabs.com """Modals for creating new objects""" from lib.page.modal import base class NewProgramModal(base.ProgramModal, base.CreateNewObjectModal): """Class representing a program modal visible after creating a new program from LHN""" class NewControlModal(base.ControlModal, base.CreateNewObjectModal): """Class representing a control modal visible after creating a new control from LHN""" class NewOrgGroupModal(base.OrgGroupModal, base.CreateNewObjectModal): """Class representing an org group modal visible after creating a new org group from LHN""" class NewRiskModal(base.RiskModal, base.CreateNewObjectModal): """Class representing a risk modal visible after creating a new risk from LHN""" <commit_msg>Add modals for creating objects<commit_after>
# Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: jernej@reciprocitylabs.com # Maintained By: jernej@reciprocitylabs.com """Modals for creating new objects""" from lib.page.modal import base class NewProgramModal(base.ProgramModal, base.CreateNewObjectModal): """Class representing a program modal visible after creating a new program from LHN""" class NewControlModal(base.ControlModal, base.CreateNewObjectModal): """Class representing a control modal visible after creating a new control from LHN""" class NewOrgGroupModal(base.OrgGroupModal, base.CreateNewObjectModal): """Class representing an org group modal visible after creating a new org group from LHN""" class NewRiskModal(base.RiskModal, base.CreateNewObjectModal): """Class representing a risk modal visible after creating a new risk from LHN""" class NewRequestModal(base.RequestModal, base.CreateNewObjectModal): """Class representing an request modal visible after creating a new request from LHN""" class NewIssueModal(base.IssueModal, base.CreateNewObjectModal): """Class representing an issue visible after creating a new issue from LHN"""
# Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: jernej@reciprocitylabs.com # Maintained By: jernej@reciprocitylabs.com """Modals for creating new objects""" from lib.page.modal import base class NewProgramModal(base.ProgramModal, base.CreateNewObjectModal): """Class representing a program modal visible after creating a new program from LHN""" class NewControlModal(base.ControlModal, base.CreateNewObjectModal): """Class representing a control modal visible after creating a new control from LHN""" class NewOrgGroupModal(base.OrgGroupModal, base.CreateNewObjectModal): """Class representing an org group modal visible after creating a new org group from LHN""" class NewRiskModal(base.RiskModal, base.CreateNewObjectModal): """Class representing a risk modal visible after creating a new risk from LHN""" Add modals for creating objects# Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: jernej@reciprocitylabs.com # Maintained By: jernej@reciprocitylabs.com """Modals for creating new objects""" from lib.page.modal import base class NewProgramModal(base.ProgramModal, base.CreateNewObjectModal): """Class representing a program modal visible after creating a new program from LHN""" class NewControlModal(base.ControlModal, base.CreateNewObjectModal): """Class representing a control modal visible after creating a new control from LHN""" class NewOrgGroupModal(base.OrgGroupModal, base.CreateNewObjectModal): """Class representing an org group modal visible after creating a new org group from LHN""" class NewRiskModal(base.RiskModal, base.CreateNewObjectModal): """Class representing a risk modal visible after creating a new risk from LHN""" class NewRequestModal(base.RequestModal, base.CreateNewObjectModal): """Class representing an request modal visible after creating a new request from LHN""" class NewIssueModal(base.IssueModal, base.CreateNewObjectModal): """Class representing an issue visible after creating a new issue from LHN"""
<commit_before># Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: jernej@reciprocitylabs.com # Maintained By: jernej@reciprocitylabs.com """Modals for creating new objects""" from lib.page.modal import base class NewProgramModal(base.ProgramModal, base.CreateNewObjectModal): """Class representing a program modal visible after creating a new program from LHN""" class NewControlModal(base.ControlModal, base.CreateNewObjectModal): """Class representing a control modal visible after creating a new control from LHN""" class NewOrgGroupModal(base.OrgGroupModal, base.CreateNewObjectModal): """Class representing an org group modal visible after creating a new org group from LHN""" class NewRiskModal(base.RiskModal, base.CreateNewObjectModal): """Class representing a risk modal visible after creating a new risk from LHN""" <commit_msg>Add modals for creating objects<commit_after># Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: jernej@reciprocitylabs.com # Maintained By: jernej@reciprocitylabs.com """Modals for creating new objects""" from lib.page.modal import base class NewProgramModal(base.ProgramModal, base.CreateNewObjectModal): """Class representing a program modal visible after creating a new program from LHN""" class NewControlModal(base.ControlModal, base.CreateNewObjectModal): """Class representing a control modal visible after creating a new control from LHN""" class NewOrgGroupModal(base.OrgGroupModal, base.CreateNewObjectModal): """Class representing an org group modal visible after creating a new org group from LHN""" class NewRiskModal(base.RiskModal, base.CreateNewObjectModal): """Class representing a risk modal visible after creating a new risk from LHN""" class NewRequestModal(base.RequestModal, base.CreateNewObjectModal): """Class representing an request modal visible after creating a new request from LHN""" class NewIssueModal(base.IssueModal, base.CreateNewObjectModal): """Class representing an issue visible after creating a new issue from LHN"""
53309f9c85739a57388902804e875d67404957b2
modules/add_random.py
modules/add_random.py
def add_random(self, command): import random global selected_songs filelist = [] for root, dirs, files in os.walk(MUSIC_PATH): for name in files: root = root.replace(MUSIC_PATH + os.sep, "") filelist.append(os.path.join(root, name)) numsongs = int(self.confman.get_value("add_random", "NUMBER_OF_SONGS", 10)) for i in range(1,numsongs): if len(selected_songs) == len(filelist): selected_songs = [] filepath = "" while 1: filepath = filelist[random.randint(0, len(filelist)-1)] if not filepath.endswith(".m3u") and not filepath in selected_songs and not NICK + "_intros" + os.sep in filepath: break selected_songs.append(filepath) try: self.conman.mpc.add(filepath) except mpd.MPDError: pass selected_songs = [] self.map_command("random", add_random) self.map_help("random", ".random - adds 10 random tracks to the queue")
def add_random(self, command): import random global selected_songs filelist = [] for root, dirs, files in os.walk(MUSIC_PATH): for name in files: root = root.replace(MUSIC_PATH + os.sep, "") filelist.append(os.path.join(root, name)) numsongs = int(self.confman.get_value("add_random", "NUMBER_OF_SONGS", 10)) for i in range(1,numsongs): if len(selected_songs) == len(filelist): selected_songs = [] filepath = "" while 1: filepath = filelist[random.randint(0, len(filelist)-1)] if not filepath.endswith(".m3u") and not filepath in selected_songs and not NICK + "_intros" + os.sep in filepath: break selected_songs.append(filepath) try: self.conman.mpc.add(filepath) except mpd.MPDError: pass selected_songs = [] self.map_command("random", add_random) self.map_help("random", ".random - adds %s random tracks to the queue" % self.confman.get_value("add_random", "NUMBER_OF_SONGS", 10))
Fix random module's help message
Fix random module's help message
Python
agpl-3.0
Flat/JiyuuBot,Zaexu/JiyuuBot
def add_random(self, command): import random global selected_songs filelist = [] for root, dirs, files in os.walk(MUSIC_PATH): for name in files: root = root.replace(MUSIC_PATH + os.sep, "") filelist.append(os.path.join(root, name)) numsongs = int(self.confman.get_value("add_random", "NUMBER_OF_SONGS", 10)) for i in range(1,numsongs): if len(selected_songs) == len(filelist): selected_songs = [] filepath = "" while 1: filepath = filelist[random.randint(0, len(filelist)-1)] if not filepath.endswith(".m3u") and not filepath in selected_songs and not NICK + "_intros" + os.sep in filepath: break selected_songs.append(filepath) try: self.conman.mpc.add(filepath) except mpd.MPDError: pass selected_songs = [] self.map_command("random", add_random) self.map_help("random", ".random - adds 10 random tracks to the queue") Fix random module's help message
def add_random(self, command): import random global selected_songs filelist = [] for root, dirs, files in os.walk(MUSIC_PATH): for name in files: root = root.replace(MUSIC_PATH + os.sep, "") filelist.append(os.path.join(root, name)) numsongs = int(self.confman.get_value("add_random", "NUMBER_OF_SONGS", 10)) for i in range(1,numsongs): if len(selected_songs) == len(filelist): selected_songs = [] filepath = "" while 1: filepath = filelist[random.randint(0, len(filelist)-1)] if not filepath.endswith(".m3u") and not filepath in selected_songs and not NICK + "_intros" + os.sep in filepath: break selected_songs.append(filepath) try: self.conman.mpc.add(filepath) except mpd.MPDError: pass selected_songs = [] self.map_command("random", add_random) self.map_help("random", ".random - adds %s random tracks to the queue" % self.confman.get_value("add_random", "NUMBER_OF_SONGS", 10))
<commit_before>def add_random(self, command): import random global selected_songs filelist = [] for root, dirs, files in os.walk(MUSIC_PATH): for name in files: root = root.replace(MUSIC_PATH + os.sep, "") filelist.append(os.path.join(root, name)) numsongs = int(self.confman.get_value("add_random", "NUMBER_OF_SONGS", 10)) for i in range(1,numsongs): if len(selected_songs) == len(filelist): selected_songs = [] filepath = "" while 1: filepath = filelist[random.randint(0, len(filelist)-1)] if not filepath.endswith(".m3u") and not filepath in selected_songs and not NICK + "_intros" + os.sep in filepath: break selected_songs.append(filepath) try: self.conman.mpc.add(filepath) except mpd.MPDError: pass selected_songs = [] self.map_command("random", add_random) self.map_help("random", ".random - adds 10 random tracks to the queue") <commit_msg>Fix random module's help message<commit_after>
def add_random(self, command): import random global selected_songs filelist = [] for root, dirs, files in os.walk(MUSIC_PATH): for name in files: root = root.replace(MUSIC_PATH + os.sep, "") filelist.append(os.path.join(root, name)) numsongs = int(self.confman.get_value("add_random", "NUMBER_OF_SONGS", 10)) for i in range(1,numsongs): if len(selected_songs) == len(filelist): selected_songs = [] filepath = "" while 1: filepath = filelist[random.randint(0, len(filelist)-1)] if not filepath.endswith(".m3u") and not filepath in selected_songs and not NICK + "_intros" + os.sep in filepath: break selected_songs.append(filepath) try: self.conman.mpc.add(filepath) except mpd.MPDError: pass selected_songs = [] self.map_command("random", add_random) self.map_help("random", ".random - adds %s random tracks to the queue" % self.confman.get_value("add_random", "NUMBER_OF_SONGS", 10))
def add_random(self, command): import random global selected_songs filelist = [] for root, dirs, files in os.walk(MUSIC_PATH): for name in files: root = root.replace(MUSIC_PATH + os.sep, "") filelist.append(os.path.join(root, name)) numsongs = int(self.confman.get_value("add_random", "NUMBER_OF_SONGS", 10)) for i in range(1,numsongs): if len(selected_songs) == len(filelist): selected_songs = [] filepath = "" while 1: filepath = filelist[random.randint(0, len(filelist)-1)] if not filepath.endswith(".m3u") and not filepath in selected_songs and not NICK + "_intros" + os.sep in filepath: break selected_songs.append(filepath) try: self.conman.mpc.add(filepath) except mpd.MPDError: pass selected_songs = [] self.map_command("random", add_random) self.map_help("random", ".random - adds 10 random tracks to the queue") Fix random module's help messagedef add_random(self, command): import random global selected_songs filelist = [] for root, dirs, files in os.walk(MUSIC_PATH): for name in files: root = root.replace(MUSIC_PATH + os.sep, "") filelist.append(os.path.join(root, name)) numsongs = int(self.confman.get_value("add_random", "NUMBER_OF_SONGS", 10)) for i in range(1,numsongs): if len(selected_songs) == len(filelist): selected_songs = [] filepath = "" while 1: filepath = filelist[random.randint(0, len(filelist)-1)] if not filepath.endswith(".m3u") and not filepath in selected_songs and not NICK + "_intros" + os.sep in filepath: break selected_songs.append(filepath) try: self.conman.mpc.add(filepath) except mpd.MPDError: pass selected_songs = [] self.map_command("random", add_random) self.map_help("random", ".random - adds %s random tracks to the queue" % self.confman.get_value("add_random", "NUMBER_OF_SONGS", 10))
<commit_before>def add_random(self, command): import random global selected_songs filelist = [] for root, dirs, files in os.walk(MUSIC_PATH): for name in files: root = root.replace(MUSIC_PATH + os.sep, "") filelist.append(os.path.join(root, name)) numsongs = int(self.confman.get_value("add_random", "NUMBER_OF_SONGS", 10)) for i in range(1,numsongs): if len(selected_songs) == len(filelist): selected_songs = [] filepath = "" while 1: filepath = filelist[random.randint(0, len(filelist)-1)] if not filepath.endswith(".m3u") and not filepath in selected_songs and not NICK + "_intros" + os.sep in filepath: break selected_songs.append(filepath) try: self.conman.mpc.add(filepath) except mpd.MPDError: pass selected_songs = [] self.map_command("random", add_random) self.map_help("random", ".random - adds 10 random tracks to the queue") <commit_msg>Fix random module's help message<commit_after>def add_random(self, command): import random global selected_songs filelist = [] for root, dirs, files in os.walk(MUSIC_PATH): for name in files: root = root.replace(MUSIC_PATH + os.sep, "") filelist.append(os.path.join(root, name)) numsongs = int(self.confman.get_value("add_random", "NUMBER_OF_SONGS", 10)) for i in range(1,numsongs): if len(selected_songs) == len(filelist): selected_songs = [] filepath = "" while 1: filepath = filelist[random.randint(0, len(filelist)-1)] if not filepath.endswith(".m3u") and not filepath in selected_songs and not NICK + "_intros" + os.sep in filepath: break selected_songs.append(filepath) try: self.conman.mpc.add(filepath) except mpd.MPDError: pass selected_songs = [] self.map_command("random", add_random) self.map_help("random", ".random - adds %s random tracks to the queue" % self.confman.get_value("add_random", "NUMBER_OF_SONGS", 10))
440593615adca029b11575e604d251c7b68942b4
api/licenses/serializers.py
api/licenses/serializers.py
from rest_framework import serializers as ser from api.base.serializers import ( JSONAPISerializer, LinksField, IDField, TypeField ) from api.base.utils import absolute_reverse class LicenseSerializer(JSONAPISerializer): filterable_fields = frozenset([ 'name', 'id', ]) non_anonymized_fields = ['type'] id = IDField(source='_id', read_only=True) type = TypeField() name = ser.CharField(required=True, help_text='License name') text = ser.CharField(required=True, help_text='Full text of the license') required_fields = ser.ListField(source='properties', read_only=True, help_text='Fields required for this license (provided to help front-end validators)') links = LinksField({'self': 'get_absolute_url'}) class Meta: type_ = 'licenses' def get_absolute_url(self, obj): return absolute_reverse('licenses:license-detail', kwargs={ 'license_id': obj._id, 'version': self.context['request'].parser_context['kwargs']['version'] })
from rest_framework import serializers as ser from api.base.serializers import ( JSONAPISerializer, LinksField, IDField, TypeField ) from api.base.utils import absolute_reverse class LicenseSerializer(JSONAPISerializer): filterable_fields = frozenset([ 'name', 'id', ]) non_anonymized_fields = ['type'] id = IDField(source='_id', read_only=True) type = TypeField() name = ser.CharField(required=True, help_text='License name') text = ser.CharField(required=True, help_text='Full text of the license') url = ser.URLField(required=False, help_text='URL for the license') required_fields = ser.ListField(source='properties', read_only=True, help_text='Fields required for this license (provided to help front-end validators)') links = LinksField({'self': 'get_absolute_url'}) class Meta: type_ = 'licenses' def get_absolute_url(self, obj): return absolute_reverse('licenses:license-detail', kwargs={ 'license_id': obj._id, 'version': self.context['request'].parser_context['kwargs']['version'] })
Add url to the license api serializer
Add url to the license api serializer
Python
apache-2.0
felliott/osf.io,baylee-d/osf.io,sloria/osf.io,baylee-d/osf.io,HalcyonChimera/osf.io,adlius/osf.io,HalcyonChimera/osf.io,CenterForOpenScience/osf.io,brianjgeiger/osf.io,felliott/osf.io,mfraezz/osf.io,cslzchen/osf.io,icereval/osf.io,felliott/osf.io,adlius/osf.io,Johnetordoff/osf.io,HalcyonChimera/osf.io,brianjgeiger/osf.io,baylee-d/osf.io,caseyrollins/osf.io,aaxelb/osf.io,Johnetordoff/osf.io,saradbowman/osf.io,mfraezz/osf.io,adlius/osf.io,Johnetordoff/osf.io,HalcyonChimera/osf.io,mattclark/osf.io,CenterForOpenScience/osf.io,brianjgeiger/osf.io,cslzchen/osf.io,caseyrollins/osf.io,saradbowman/osf.io,CenterForOpenScience/osf.io,pattisdr/osf.io,adlius/osf.io,Johnetordoff/osf.io,CenterForOpenScience/osf.io,pattisdr/osf.io,aaxelb/osf.io,aaxelb/osf.io,mfraezz/osf.io,erinspace/osf.io,pattisdr/osf.io,mattclark/osf.io,erinspace/osf.io,icereval/osf.io,cslzchen/osf.io,caseyrollins/osf.io,aaxelb/osf.io,cslzchen/osf.io,mfraezz/osf.io,felliott/osf.io,brianjgeiger/osf.io,sloria/osf.io,icereval/osf.io,mattclark/osf.io,sloria/osf.io,erinspace/osf.io
from rest_framework import serializers as ser from api.base.serializers import ( JSONAPISerializer, LinksField, IDField, TypeField ) from api.base.utils import absolute_reverse class LicenseSerializer(JSONAPISerializer): filterable_fields = frozenset([ 'name', 'id', ]) non_anonymized_fields = ['type'] id = IDField(source='_id', read_only=True) type = TypeField() name = ser.CharField(required=True, help_text='License name') text = ser.CharField(required=True, help_text='Full text of the license') required_fields = ser.ListField(source='properties', read_only=True, help_text='Fields required for this license (provided to help front-end validators)') links = LinksField({'self': 'get_absolute_url'}) class Meta: type_ = 'licenses' def get_absolute_url(self, obj): return absolute_reverse('licenses:license-detail', kwargs={ 'license_id': obj._id, 'version': self.context['request'].parser_context['kwargs']['version'] }) Add url to the license api serializer
from rest_framework import serializers as ser from api.base.serializers import ( JSONAPISerializer, LinksField, IDField, TypeField ) from api.base.utils import absolute_reverse class LicenseSerializer(JSONAPISerializer): filterable_fields = frozenset([ 'name', 'id', ]) non_anonymized_fields = ['type'] id = IDField(source='_id', read_only=True) type = TypeField() name = ser.CharField(required=True, help_text='License name') text = ser.CharField(required=True, help_text='Full text of the license') url = ser.URLField(required=False, help_text='URL for the license') required_fields = ser.ListField(source='properties', read_only=True, help_text='Fields required for this license (provided to help front-end validators)') links = LinksField({'self': 'get_absolute_url'}) class Meta: type_ = 'licenses' def get_absolute_url(self, obj): return absolute_reverse('licenses:license-detail', kwargs={ 'license_id': obj._id, 'version': self.context['request'].parser_context['kwargs']['version'] })
<commit_before>from rest_framework import serializers as ser from api.base.serializers import ( JSONAPISerializer, LinksField, IDField, TypeField ) from api.base.utils import absolute_reverse class LicenseSerializer(JSONAPISerializer): filterable_fields = frozenset([ 'name', 'id', ]) non_anonymized_fields = ['type'] id = IDField(source='_id', read_only=True) type = TypeField() name = ser.CharField(required=True, help_text='License name') text = ser.CharField(required=True, help_text='Full text of the license') required_fields = ser.ListField(source='properties', read_only=True, help_text='Fields required for this license (provided to help front-end validators)') links = LinksField({'self': 'get_absolute_url'}) class Meta: type_ = 'licenses' def get_absolute_url(self, obj): return absolute_reverse('licenses:license-detail', kwargs={ 'license_id': obj._id, 'version': self.context['request'].parser_context['kwargs']['version'] }) <commit_msg>Add url to the license api serializer<commit_after>
from rest_framework import serializers as ser from api.base.serializers import ( JSONAPISerializer, LinksField, IDField, TypeField ) from api.base.utils import absolute_reverse class LicenseSerializer(JSONAPISerializer): filterable_fields = frozenset([ 'name', 'id', ]) non_anonymized_fields = ['type'] id = IDField(source='_id', read_only=True) type = TypeField() name = ser.CharField(required=True, help_text='License name') text = ser.CharField(required=True, help_text='Full text of the license') url = ser.URLField(required=False, help_text='URL for the license') required_fields = ser.ListField(source='properties', read_only=True, help_text='Fields required for this license (provided to help front-end validators)') links = LinksField({'self': 'get_absolute_url'}) class Meta: type_ = 'licenses' def get_absolute_url(self, obj): return absolute_reverse('licenses:license-detail', kwargs={ 'license_id': obj._id, 'version': self.context['request'].parser_context['kwargs']['version'] })
from rest_framework import serializers as ser from api.base.serializers import ( JSONAPISerializer, LinksField, IDField, TypeField ) from api.base.utils import absolute_reverse class LicenseSerializer(JSONAPISerializer): filterable_fields = frozenset([ 'name', 'id', ]) non_anonymized_fields = ['type'] id = IDField(source='_id', read_only=True) type = TypeField() name = ser.CharField(required=True, help_text='License name') text = ser.CharField(required=True, help_text='Full text of the license') required_fields = ser.ListField(source='properties', read_only=True, help_text='Fields required for this license (provided to help front-end validators)') links = LinksField({'self': 'get_absolute_url'}) class Meta: type_ = 'licenses' def get_absolute_url(self, obj): return absolute_reverse('licenses:license-detail', kwargs={ 'license_id': obj._id, 'version': self.context['request'].parser_context['kwargs']['version'] }) Add url to the license api serializerfrom rest_framework import serializers as ser from api.base.serializers import ( JSONAPISerializer, LinksField, IDField, TypeField ) from api.base.utils import absolute_reverse class LicenseSerializer(JSONAPISerializer): filterable_fields = frozenset([ 'name', 'id', ]) non_anonymized_fields = ['type'] id = IDField(source='_id', read_only=True) type = TypeField() name = ser.CharField(required=True, help_text='License name') text = ser.CharField(required=True, help_text='Full text of the license') url = ser.URLField(required=False, help_text='URL for the license') required_fields = ser.ListField(source='properties', read_only=True, help_text='Fields required for this license (provided to help front-end validators)') links = LinksField({'self': 'get_absolute_url'}) class Meta: type_ = 'licenses' def get_absolute_url(self, obj): return absolute_reverse('licenses:license-detail', kwargs={ 'license_id': obj._id, 'version': self.context['request'].parser_context['kwargs']['version'] })
<commit_before>from rest_framework import serializers as ser from api.base.serializers import ( JSONAPISerializer, LinksField, IDField, TypeField ) from api.base.utils import absolute_reverse class LicenseSerializer(JSONAPISerializer): filterable_fields = frozenset([ 'name', 'id', ]) non_anonymized_fields = ['type'] id = IDField(source='_id', read_only=True) type = TypeField() name = ser.CharField(required=True, help_text='License name') text = ser.CharField(required=True, help_text='Full text of the license') required_fields = ser.ListField(source='properties', read_only=True, help_text='Fields required for this license (provided to help front-end validators)') links = LinksField({'self': 'get_absolute_url'}) class Meta: type_ = 'licenses' def get_absolute_url(self, obj): return absolute_reverse('licenses:license-detail', kwargs={ 'license_id': obj._id, 'version': self.context['request'].parser_context['kwargs']['version'] }) <commit_msg>Add url to the license api serializer<commit_after>from rest_framework import serializers as ser from api.base.serializers import ( JSONAPISerializer, LinksField, IDField, TypeField ) from api.base.utils import absolute_reverse class LicenseSerializer(JSONAPISerializer): filterable_fields = frozenset([ 'name', 'id', ]) non_anonymized_fields = ['type'] id = IDField(source='_id', read_only=True) type = TypeField() name = ser.CharField(required=True, help_text='License name') text = ser.CharField(required=True, help_text='Full text of the license') url = ser.URLField(required=False, help_text='URL for the license') required_fields = ser.ListField(source='properties', read_only=True, help_text='Fields required for this license (provided to help front-end validators)') links = LinksField({'self': 'get_absolute_url'}) class Meta: type_ = 'licenses' def get_absolute_url(self, obj): return absolute_reverse('licenses:license-detail', kwargs={ 'license_id': obj._id, 'version': self.context['request'].parser_context['kwargs']['version'] })
edcce0e44c453f459e82774efeb0996457d84306
integration_tests/tests/test_experiment_detumbling.py
integration_tests/tests/test_experiment_detumbling.py
from datetime import timedelta, datetime import telecommand from obc.experiments import ExperimentType from system import auto_power_on from tests.base import BaseTest from utils import TestEvent class TestExperimentDetumbling(BaseTest): @auto_power_on(auto_power_on=False) def __init__(self, *args, **kwargs): super(TestExperimentDetumbling, self).__init__(*args, **kwargs) def _start(self): e = TestEvent() def on_reset(_): e.set() self.system.comm.on_hardware_reset = on_reset self.system.obc.power_on(clean_state=True) self.system.obc.wait_to_start() e.wait_for_change(1) def test_should_perform_experiment(self): self._start() start_time = datetime.now() self.system.rtc.set_response_time(start_time) self.system.comm.put_frame(telecommand.PerformDetumblingExperiment(duration=timedelta(hours=4))) self.system.obc.wait_for_experiment(ExperimentType.Detumbling, 40) self.system.obc.advance_time(timedelta(hours=4).total_seconds() * 1000) self.system.rtc.set_response_time(start_time + timedelta(hours=4)) self.system.obc.wait_for_experiment(None, 20)
from datetime import timedelta, datetime import telecommand from obc.experiments import ExperimentType from system import auto_power_on from tests.base import BaseTest from utils import TestEvent class TestExperimentDetumbling(BaseTest): @auto_power_on(auto_power_on=False) def __init__(self, *args, **kwargs): super(TestExperimentDetumbling, self).__init__(*args, **kwargs) def _start(self): e = TestEvent() def on_reset(_): e.set() self.system.comm.on_hardware_reset = on_reset self.system.obc.power_on(clean_state=True) self.system.obc.wait_to_start() e.wait_for_change(1) def test_should_perform_experiment(self): self._start() start_time = datetime.now() self.system.rtc.set_response_time(start_time) self.system.comm.put_frame(telecommand.PerformDetumblingExperiment(duration=timedelta(hours=4))) self.system.obc.wait_for_experiment(ExperimentType.Detumbling, 40) self.system.obc.advance_time(timedelta(hours=4, minutes=1).total_seconds() * 1000) self.system.rtc.set_response_time(start_time + timedelta(hours=4, minutes=1)) self.system.obc.wait_for_experiment(None, 20)
Fix race condition in detumbling experiment test
Fix race condition in detumbling experiment test In detumbling experiment test, experiment was commanded to run for 4 hours. After that OBC time was advanced also by 4 hours, however it was not enough as during next mission loop OBC time was few milliseconds before scheduled experiment end.
Python
agpl-3.0
PW-Sat2/PWSat2OBC,PW-Sat2/PWSat2OBC,PW-Sat2/PWSat2OBC,PW-Sat2/PWSat2OBC
from datetime import timedelta, datetime import telecommand from obc.experiments import ExperimentType from system import auto_power_on from tests.base import BaseTest from utils import TestEvent class TestExperimentDetumbling(BaseTest): @auto_power_on(auto_power_on=False) def __init__(self, *args, **kwargs): super(TestExperimentDetumbling, self).__init__(*args, **kwargs) def _start(self): e = TestEvent() def on_reset(_): e.set() self.system.comm.on_hardware_reset = on_reset self.system.obc.power_on(clean_state=True) self.system.obc.wait_to_start() e.wait_for_change(1) def test_should_perform_experiment(self): self._start() start_time = datetime.now() self.system.rtc.set_response_time(start_time) self.system.comm.put_frame(telecommand.PerformDetumblingExperiment(duration=timedelta(hours=4))) self.system.obc.wait_for_experiment(ExperimentType.Detumbling, 40) self.system.obc.advance_time(timedelta(hours=4).total_seconds() * 1000) self.system.rtc.set_response_time(start_time + timedelta(hours=4)) self.system.obc.wait_for_experiment(None, 20) Fix race condition in detumbling experiment test In detumbling experiment test, experiment was commanded to run for 4 hours. After that OBC time was advanced also by 4 hours, however it was not enough as during next mission loop OBC time was few milliseconds before scheduled experiment end.
from datetime import timedelta, datetime import telecommand from obc.experiments import ExperimentType from system import auto_power_on from tests.base import BaseTest from utils import TestEvent class TestExperimentDetumbling(BaseTest): @auto_power_on(auto_power_on=False) def __init__(self, *args, **kwargs): super(TestExperimentDetumbling, self).__init__(*args, **kwargs) def _start(self): e = TestEvent() def on_reset(_): e.set() self.system.comm.on_hardware_reset = on_reset self.system.obc.power_on(clean_state=True) self.system.obc.wait_to_start() e.wait_for_change(1) def test_should_perform_experiment(self): self._start() start_time = datetime.now() self.system.rtc.set_response_time(start_time) self.system.comm.put_frame(telecommand.PerformDetumblingExperiment(duration=timedelta(hours=4))) self.system.obc.wait_for_experiment(ExperimentType.Detumbling, 40) self.system.obc.advance_time(timedelta(hours=4, minutes=1).total_seconds() * 1000) self.system.rtc.set_response_time(start_time + timedelta(hours=4, minutes=1)) self.system.obc.wait_for_experiment(None, 20)
<commit_before>from datetime import timedelta, datetime import telecommand from obc.experiments import ExperimentType from system import auto_power_on from tests.base import BaseTest from utils import TestEvent class TestExperimentDetumbling(BaseTest): @auto_power_on(auto_power_on=False) def __init__(self, *args, **kwargs): super(TestExperimentDetumbling, self).__init__(*args, **kwargs) def _start(self): e = TestEvent() def on_reset(_): e.set() self.system.comm.on_hardware_reset = on_reset self.system.obc.power_on(clean_state=True) self.system.obc.wait_to_start() e.wait_for_change(1) def test_should_perform_experiment(self): self._start() start_time = datetime.now() self.system.rtc.set_response_time(start_time) self.system.comm.put_frame(telecommand.PerformDetumblingExperiment(duration=timedelta(hours=4))) self.system.obc.wait_for_experiment(ExperimentType.Detumbling, 40) self.system.obc.advance_time(timedelta(hours=4).total_seconds() * 1000) self.system.rtc.set_response_time(start_time + timedelta(hours=4)) self.system.obc.wait_for_experiment(None, 20) <commit_msg>Fix race condition in detumbling experiment test In detumbling experiment test, experiment was commanded to run for 4 hours. After that OBC time was advanced also by 4 hours, however it was not enough as during next mission loop OBC time was few milliseconds before scheduled experiment end.<commit_after>
from datetime import timedelta, datetime import telecommand from obc.experiments import ExperimentType from system import auto_power_on from tests.base import BaseTest from utils import TestEvent class TestExperimentDetumbling(BaseTest): @auto_power_on(auto_power_on=False) def __init__(self, *args, **kwargs): super(TestExperimentDetumbling, self).__init__(*args, **kwargs) def _start(self): e = TestEvent() def on_reset(_): e.set() self.system.comm.on_hardware_reset = on_reset self.system.obc.power_on(clean_state=True) self.system.obc.wait_to_start() e.wait_for_change(1) def test_should_perform_experiment(self): self._start() start_time = datetime.now() self.system.rtc.set_response_time(start_time) self.system.comm.put_frame(telecommand.PerformDetumblingExperiment(duration=timedelta(hours=4))) self.system.obc.wait_for_experiment(ExperimentType.Detumbling, 40) self.system.obc.advance_time(timedelta(hours=4, minutes=1).total_seconds() * 1000) self.system.rtc.set_response_time(start_time + timedelta(hours=4, minutes=1)) self.system.obc.wait_for_experiment(None, 20)
from datetime import timedelta, datetime import telecommand from obc.experiments import ExperimentType from system import auto_power_on from tests.base import BaseTest from utils import TestEvent class TestExperimentDetumbling(BaseTest): @auto_power_on(auto_power_on=False) def __init__(self, *args, **kwargs): super(TestExperimentDetumbling, self).__init__(*args, **kwargs) def _start(self): e = TestEvent() def on_reset(_): e.set() self.system.comm.on_hardware_reset = on_reset self.system.obc.power_on(clean_state=True) self.system.obc.wait_to_start() e.wait_for_change(1) def test_should_perform_experiment(self): self._start() start_time = datetime.now() self.system.rtc.set_response_time(start_time) self.system.comm.put_frame(telecommand.PerformDetumblingExperiment(duration=timedelta(hours=4))) self.system.obc.wait_for_experiment(ExperimentType.Detumbling, 40) self.system.obc.advance_time(timedelta(hours=4).total_seconds() * 1000) self.system.rtc.set_response_time(start_time + timedelta(hours=4)) self.system.obc.wait_for_experiment(None, 20) Fix race condition in detumbling experiment test In detumbling experiment test, experiment was commanded to run for 4 hours. After that OBC time was advanced also by 4 hours, however it was not enough as during next mission loop OBC time was few milliseconds before scheduled experiment end.from datetime import timedelta, datetime import telecommand from obc.experiments import ExperimentType from system import auto_power_on from tests.base import BaseTest from utils import TestEvent class TestExperimentDetumbling(BaseTest): @auto_power_on(auto_power_on=False) def __init__(self, *args, **kwargs): super(TestExperimentDetumbling, self).__init__(*args, **kwargs) def _start(self): e = TestEvent() def on_reset(_): e.set() self.system.comm.on_hardware_reset = on_reset self.system.obc.power_on(clean_state=True) self.system.obc.wait_to_start() e.wait_for_change(1) def test_should_perform_experiment(self): self._start() start_time = datetime.now() self.system.rtc.set_response_time(start_time) self.system.comm.put_frame(telecommand.PerformDetumblingExperiment(duration=timedelta(hours=4))) self.system.obc.wait_for_experiment(ExperimentType.Detumbling, 40) self.system.obc.advance_time(timedelta(hours=4, minutes=1).total_seconds() * 1000) self.system.rtc.set_response_time(start_time + timedelta(hours=4, minutes=1)) self.system.obc.wait_for_experiment(None, 20)
<commit_before>from datetime import timedelta, datetime import telecommand from obc.experiments import ExperimentType from system import auto_power_on from tests.base import BaseTest from utils import TestEvent class TestExperimentDetumbling(BaseTest): @auto_power_on(auto_power_on=False) def __init__(self, *args, **kwargs): super(TestExperimentDetumbling, self).__init__(*args, **kwargs) def _start(self): e = TestEvent() def on_reset(_): e.set() self.system.comm.on_hardware_reset = on_reset self.system.obc.power_on(clean_state=True) self.system.obc.wait_to_start() e.wait_for_change(1) def test_should_perform_experiment(self): self._start() start_time = datetime.now() self.system.rtc.set_response_time(start_time) self.system.comm.put_frame(telecommand.PerformDetumblingExperiment(duration=timedelta(hours=4))) self.system.obc.wait_for_experiment(ExperimentType.Detumbling, 40) self.system.obc.advance_time(timedelta(hours=4).total_seconds() * 1000) self.system.rtc.set_response_time(start_time + timedelta(hours=4)) self.system.obc.wait_for_experiment(None, 20) <commit_msg>Fix race condition in detumbling experiment test In detumbling experiment test, experiment was commanded to run for 4 hours. After that OBC time was advanced also by 4 hours, however it was not enough as during next mission loop OBC time was few milliseconds before scheduled experiment end.<commit_after>from datetime import timedelta, datetime import telecommand from obc.experiments import ExperimentType from system import auto_power_on from tests.base import BaseTest from utils import TestEvent class TestExperimentDetumbling(BaseTest): @auto_power_on(auto_power_on=False) def __init__(self, *args, **kwargs): super(TestExperimentDetumbling, self).__init__(*args, **kwargs) def _start(self): e = TestEvent() def on_reset(_): e.set() self.system.comm.on_hardware_reset = on_reset self.system.obc.power_on(clean_state=True) self.system.obc.wait_to_start() e.wait_for_change(1) def test_should_perform_experiment(self): self._start() start_time = datetime.now() self.system.rtc.set_response_time(start_time) self.system.comm.put_frame(telecommand.PerformDetumblingExperiment(duration=timedelta(hours=4))) self.system.obc.wait_for_experiment(ExperimentType.Detumbling, 40) self.system.obc.advance_time(timedelta(hours=4, minutes=1).total_seconds() * 1000) self.system.rtc.set_response_time(start_time + timedelta(hours=4, minutes=1)) self.system.obc.wait_for_experiment(None, 20)
0fca8a2c694db53d214d927606e2b0fed78ae31c
knights/dj.py
knights/dj.py
from django.template import TemplateDoesNotExist, TemplateSyntaxError # NOQA from django.template.backends.base import BaseEngine from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy from . import compiler from . import loader class KnightsTemplater(BaseEngine): def __init__(self, params): params = params.copy() options = params.pop('OPTIONS').copy() super(KnightsTemplater, self).__init__(params) for path in params.get('DIRS', []): loader.add_path(path) def from_string(self, template_code): tmpl = compiler.kompile(template_code) return Template(tmpl) def get_template(self, template_name): tmpl = loader.load_template(template_name) if tmpl is None: raise TemplateDoesNotExist(template_name) return Template(tmpl) class Template(object): def __init__(self, template): self.template = template def render(self, context=None, request=None): if context is None: context = {} if request is not None: context['request'] = request context['csrf_input'] = csrf_input_lazy(request) context['csrf_token'] = csrf_token_lazy(request) return self.template()(context)
from collections import defaultdict from django.template import TemplateDoesNotExist, TemplateSyntaxError # NOQA from django.template.backends.base import BaseEngine from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy from . import compiler from . import loader class KnightsTemplater(BaseEngine): def __init__(self, params): params = params.copy() options = params.pop('OPTIONS').copy() super(KnightsTemplater, self).__init__(params) for path in params.get('DIRS', []): loader.add_path(path) def from_string(self, template_code): tmpl = compiler.kompile(template_code) return Template(tmpl) def get_template(self, template_name): tmpl = loader.load_template(template_name) if tmpl is None: raise TemplateDoesNotExist(template_name) return Template(tmpl) class Template(object): def __init__(self, template): self.template = template def render(self, context=None, request=None): if context is None: context = {} if request is not None: context['request'] = request context['csrf_input'] = csrf_input_lazy(request) context['csrf_token'] = csrf_token_lazy(request) ctx = defaultdict(str) ctx.update(context) return self.template(ctx)
Make context a defaultdict so unknown values yield empty string
Make context a defaultdict so unknown values yield empty string
Python
mit
funkybob/knights-templater,funkybob/knights-templater
from django.template import TemplateDoesNotExist, TemplateSyntaxError # NOQA from django.template.backends.base import BaseEngine from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy from . import compiler from . import loader class KnightsTemplater(BaseEngine): def __init__(self, params): params = params.copy() options = params.pop('OPTIONS').copy() super(KnightsTemplater, self).__init__(params) for path in params.get('DIRS', []): loader.add_path(path) def from_string(self, template_code): tmpl = compiler.kompile(template_code) return Template(tmpl) def get_template(self, template_name): tmpl = loader.load_template(template_name) if tmpl is None: raise TemplateDoesNotExist(template_name) return Template(tmpl) class Template(object): def __init__(self, template): self.template = template def render(self, context=None, request=None): if context is None: context = {} if request is not None: context['request'] = request context['csrf_input'] = csrf_input_lazy(request) context['csrf_token'] = csrf_token_lazy(request) return self.template()(context) Make context a defaultdict so unknown values yield empty string
from collections import defaultdict from django.template import TemplateDoesNotExist, TemplateSyntaxError # NOQA from django.template.backends.base import BaseEngine from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy from . import compiler from . import loader class KnightsTemplater(BaseEngine): def __init__(self, params): params = params.copy() options = params.pop('OPTIONS').copy() super(KnightsTemplater, self).__init__(params) for path in params.get('DIRS', []): loader.add_path(path) def from_string(self, template_code): tmpl = compiler.kompile(template_code) return Template(tmpl) def get_template(self, template_name): tmpl = loader.load_template(template_name) if tmpl is None: raise TemplateDoesNotExist(template_name) return Template(tmpl) class Template(object): def __init__(self, template): self.template = template def render(self, context=None, request=None): if context is None: context = {} if request is not None: context['request'] = request context['csrf_input'] = csrf_input_lazy(request) context['csrf_token'] = csrf_token_lazy(request) ctx = defaultdict(str) ctx.update(context) return self.template(ctx)
<commit_before>from django.template import TemplateDoesNotExist, TemplateSyntaxError # NOQA from django.template.backends.base import BaseEngine from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy from . import compiler from . import loader class KnightsTemplater(BaseEngine): def __init__(self, params): params = params.copy() options = params.pop('OPTIONS').copy() super(KnightsTemplater, self).__init__(params) for path in params.get('DIRS', []): loader.add_path(path) def from_string(self, template_code): tmpl = compiler.kompile(template_code) return Template(tmpl) def get_template(self, template_name): tmpl = loader.load_template(template_name) if tmpl is None: raise TemplateDoesNotExist(template_name) return Template(tmpl) class Template(object): def __init__(self, template): self.template = template def render(self, context=None, request=None): if context is None: context = {} if request is not None: context['request'] = request context['csrf_input'] = csrf_input_lazy(request) context['csrf_token'] = csrf_token_lazy(request) return self.template()(context) <commit_msg>Make context a defaultdict so unknown values yield empty string<commit_after>
from collections import defaultdict from django.template import TemplateDoesNotExist, TemplateSyntaxError # NOQA from django.template.backends.base import BaseEngine from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy from . import compiler from . import loader class KnightsTemplater(BaseEngine): def __init__(self, params): params = params.copy() options = params.pop('OPTIONS').copy() super(KnightsTemplater, self).__init__(params) for path in params.get('DIRS', []): loader.add_path(path) def from_string(self, template_code): tmpl = compiler.kompile(template_code) return Template(tmpl) def get_template(self, template_name): tmpl = loader.load_template(template_name) if tmpl is None: raise TemplateDoesNotExist(template_name) return Template(tmpl) class Template(object): def __init__(self, template): self.template = template def render(self, context=None, request=None): if context is None: context = {} if request is not None: context['request'] = request context['csrf_input'] = csrf_input_lazy(request) context['csrf_token'] = csrf_token_lazy(request) ctx = defaultdict(str) ctx.update(context) return self.template(ctx)
from django.template import TemplateDoesNotExist, TemplateSyntaxError # NOQA from django.template.backends.base import BaseEngine from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy from . import compiler from . import loader class KnightsTemplater(BaseEngine): def __init__(self, params): params = params.copy() options = params.pop('OPTIONS').copy() super(KnightsTemplater, self).__init__(params) for path in params.get('DIRS', []): loader.add_path(path) def from_string(self, template_code): tmpl = compiler.kompile(template_code) return Template(tmpl) def get_template(self, template_name): tmpl = loader.load_template(template_name) if tmpl is None: raise TemplateDoesNotExist(template_name) return Template(tmpl) class Template(object): def __init__(self, template): self.template = template def render(self, context=None, request=None): if context is None: context = {} if request is not None: context['request'] = request context['csrf_input'] = csrf_input_lazy(request) context['csrf_token'] = csrf_token_lazy(request) return self.template()(context) Make context a defaultdict so unknown values yield empty stringfrom collections import defaultdict from django.template import TemplateDoesNotExist, TemplateSyntaxError # NOQA from django.template.backends.base import BaseEngine from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy from . import compiler from . import loader class KnightsTemplater(BaseEngine): def __init__(self, params): params = params.copy() options = params.pop('OPTIONS').copy() super(KnightsTemplater, self).__init__(params) for path in params.get('DIRS', []): loader.add_path(path) def from_string(self, template_code): tmpl = compiler.kompile(template_code) return Template(tmpl) def get_template(self, template_name): tmpl = loader.load_template(template_name) if tmpl is None: raise TemplateDoesNotExist(template_name) return Template(tmpl) class Template(object): def __init__(self, template): self.template = template def render(self, context=None, request=None): if context is None: context = {} if request is not None: context['request'] = request context['csrf_input'] = csrf_input_lazy(request) context['csrf_token'] = csrf_token_lazy(request) ctx = defaultdict(str) ctx.update(context) return self.template(ctx)
<commit_before>from django.template import TemplateDoesNotExist, TemplateSyntaxError # NOQA from django.template.backends.base import BaseEngine from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy from . import compiler from . import loader class KnightsTemplater(BaseEngine): def __init__(self, params): params = params.copy() options = params.pop('OPTIONS').copy() super(KnightsTemplater, self).__init__(params) for path in params.get('DIRS', []): loader.add_path(path) def from_string(self, template_code): tmpl = compiler.kompile(template_code) return Template(tmpl) def get_template(self, template_name): tmpl = loader.load_template(template_name) if tmpl is None: raise TemplateDoesNotExist(template_name) return Template(tmpl) class Template(object): def __init__(self, template): self.template = template def render(self, context=None, request=None): if context is None: context = {} if request is not None: context['request'] = request context['csrf_input'] = csrf_input_lazy(request) context['csrf_token'] = csrf_token_lazy(request) return self.template()(context) <commit_msg>Make context a defaultdict so unknown values yield empty string<commit_after>from collections import defaultdict from django.template import TemplateDoesNotExist, TemplateSyntaxError # NOQA from django.template.backends.base import BaseEngine from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy from . import compiler from . import loader class KnightsTemplater(BaseEngine): def __init__(self, params): params = params.copy() options = params.pop('OPTIONS').copy() super(KnightsTemplater, self).__init__(params) for path in params.get('DIRS', []): loader.add_path(path) def from_string(self, template_code): tmpl = compiler.kompile(template_code) return Template(tmpl) def get_template(self, template_name): tmpl = loader.load_template(template_name) if tmpl is None: raise TemplateDoesNotExist(template_name) return Template(tmpl) class Template(object): def __init__(self, template): self.template = template def render(self, context=None, request=None): if context is None: context = {} if request is not None: context['request'] = request context['csrf_input'] = csrf_input_lazy(request) context['csrf_token'] = csrf_token_lazy(request) ctx = defaultdict(str) ctx.update(context) return self.template(ctx)
58c8e2d04b38ea951ae01ae0930df206fd657d8a
tests/utils/test_helpers.py
tests/utils/test_helpers.py
from app.models import Post from app.utils.helpers import get_or_create from tests.general import AppTestCase class TestUtils(AppTestCase): def test_get_or_create(self): post1, created1 = get_or_create(Post, title='foo', body='bar') post1.save() post2, created2 = get_or_create(Post, title='foo', body='bar') self.assertTrue(created1) self.assertFalse(created2) self.assertEquals(post1, post2)
from app.models import Post from app.utils.helpers import get_or_create from tests.general import AppTestCase class TestHelpers(AppTestCase): def test_get_or_create(self): post1, created1 = get_or_create(Post, title='foo', body='bar') post1.save() post2, created2 = get_or_create(Post, title='foo', body='bar') self.assertTrue(created1) self.assertFalse(created2) self.assertEquals(post1, post2)
Rename TestUtils test case to TestHelpers
Rename TestUtils test case to TestHelpers
Python
mit
Encrylize/flask-blogger,Encrylize/flask-blogger,Encrylize/flask-blogger
from app.models import Post from app.utils.helpers import get_or_create from tests.general import AppTestCase class TestUtils(AppTestCase): def test_get_or_create(self): post1, created1 = get_or_create(Post, title='foo', body='bar') post1.save() post2, created2 = get_or_create(Post, title='foo', body='bar') self.assertTrue(created1) self.assertFalse(created2) self.assertEquals(post1, post2) Rename TestUtils test case to TestHelpers
from app.models import Post from app.utils.helpers import get_or_create from tests.general import AppTestCase class TestHelpers(AppTestCase): def test_get_or_create(self): post1, created1 = get_or_create(Post, title='foo', body='bar') post1.save() post2, created2 = get_or_create(Post, title='foo', body='bar') self.assertTrue(created1) self.assertFalse(created2) self.assertEquals(post1, post2)
<commit_before>from app.models import Post from app.utils.helpers import get_or_create from tests.general import AppTestCase class TestUtils(AppTestCase): def test_get_or_create(self): post1, created1 = get_or_create(Post, title='foo', body='bar') post1.save() post2, created2 = get_or_create(Post, title='foo', body='bar') self.assertTrue(created1) self.assertFalse(created2) self.assertEquals(post1, post2) <commit_msg>Rename TestUtils test case to TestHelpers<commit_after>
from app.models import Post from app.utils.helpers import get_or_create from tests.general import AppTestCase class TestHelpers(AppTestCase): def test_get_or_create(self): post1, created1 = get_or_create(Post, title='foo', body='bar') post1.save() post2, created2 = get_or_create(Post, title='foo', body='bar') self.assertTrue(created1) self.assertFalse(created2) self.assertEquals(post1, post2)
from app.models import Post from app.utils.helpers import get_or_create from tests.general import AppTestCase class TestUtils(AppTestCase): def test_get_or_create(self): post1, created1 = get_or_create(Post, title='foo', body='bar') post1.save() post2, created2 = get_or_create(Post, title='foo', body='bar') self.assertTrue(created1) self.assertFalse(created2) self.assertEquals(post1, post2) Rename TestUtils test case to TestHelpersfrom app.models import Post from app.utils.helpers import get_or_create from tests.general import AppTestCase class TestHelpers(AppTestCase): def test_get_or_create(self): post1, created1 = get_or_create(Post, title='foo', body='bar') post1.save() post2, created2 = get_or_create(Post, title='foo', body='bar') self.assertTrue(created1) self.assertFalse(created2) self.assertEquals(post1, post2)
<commit_before>from app.models import Post from app.utils.helpers import get_or_create from tests.general import AppTestCase class TestUtils(AppTestCase): def test_get_or_create(self): post1, created1 = get_or_create(Post, title='foo', body='bar') post1.save() post2, created2 = get_or_create(Post, title='foo', body='bar') self.assertTrue(created1) self.assertFalse(created2) self.assertEquals(post1, post2) <commit_msg>Rename TestUtils test case to TestHelpers<commit_after>from app.models import Post from app.utils.helpers import get_or_create from tests.general import AppTestCase class TestHelpers(AppTestCase): def test_get_or_create(self): post1, created1 = get_or_create(Post, title='foo', body='bar') post1.save() post2, created2 = get_or_create(Post, title='foo', body='bar') self.assertTrue(created1) self.assertFalse(created2) self.assertEquals(post1, post2)
ab55f28592956cc6c9abbea31c2b0d66e13cddc1
src/pygrapes/adapter/__init__.py
src/pygrapes/adapter/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = "mib" __date__ = "$2011-01-22 12:02:41$" from abstract import Abstract from local import Local __all__ = ['Abstract', 'Local']
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = "mib" __date__ = "$2011-01-22 12:02:41$" from pygrapes.util import not_implemented from pygrapes.adapter.abstract import Abstract from pygrapes.adapter.local import Local try: from pygrapes.adapter.zeromq import Zmq except ImportError: Zmq = not_implemented('A working pyzmq lib is required!') try: from pygrapes.adapter.amqp import Amqp except ImportError: Amqp = not_implemented('A working amqplib lib is required!') __all__ = ['Abstract', 'Amqp', 'Local', 'Zmq']
Load conditionally all available adapters in order to make them available right inside pygrapes.adapter module
Load conditionally all available adapters in order to make them available right inside pygrapes.adapter module
Python
bsd-3-clause
michalbachowski/pygrapes,michalbachowski/pygrapes,michalbachowski/pygrapes
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = "mib" __date__ = "$2011-01-22 12:02:41$" from abstract import Abstract from local import Local __all__ = ['Abstract', 'Local'] Load conditionally all available adapters in order to make them available right inside pygrapes.adapter module
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = "mib" __date__ = "$2011-01-22 12:02:41$" from pygrapes.util import not_implemented from pygrapes.adapter.abstract import Abstract from pygrapes.adapter.local import Local try: from pygrapes.adapter.zeromq import Zmq except ImportError: Zmq = not_implemented('A working pyzmq lib is required!') try: from pygrapes.adapter.amqp import Amqp except ImportError: Amqp = not_implemented('A working amqplib lib is required!') __all__ = ['Abstract', 'Amqp', 'Local', 'Zmq']
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = "mib" __date__ = "$2011-01-22 12:02:41$" from abstract import Abstract from local import Local __all__ = ['Abstract', 'Local'] <commit_msg>Load conditionally all available adapters in order to make them available right inside pygrapes.adapter module<commit_after>
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = "mib" __date__ = "$2011-01-22 12:02:41$" from pygrapes.util import not_implemented from pygrapes.adapter.abstract import Abstract from pygrapes.adapter.local import Local try: from pygrapes.adapter.zeromq import Zmq except ImportError: Zmq = not_implemented('A working pyzmq lib is required!') try: from pygrapes.adapter.amqp import Amqp except ImportError: Amqp = not_implemented('A working amqplib lib is required!') __all__ = ['Abstract', 'Amqp', 'Local', 'Zmq']
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = "mib" __date__ = "$2011-01-22 12:02:41$" from abstract import Abstract from local import Local __all__ = ['Abstract', 'Local'] Load conditionally all available adapters in order to make them available right inside pygrapes.adapter module#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = "mib" __date__ = "$2011-01-22 12:02:41$" from pygrapes.util import not_implemented from pygrapes.adapter.abstract import Abstract from pygrapes.adapter.local import Local try: from pygrapes.adapter.zeromq import Zmq except ImportError: Zmq = not_implemented('A working pyzmq lib is required!') try: from pygrapes.adapter.amqp import Amqp except ImportError: Amqp = not_implemented('A working amqplib lib is required!') __all__ = ['Abstract', 'Amqp', 'Local', 'Zmq']
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = "mib" __date__ = "$2011-01-22 12:02:41$" from abstract import Abstract from local import Local __all__ = ['Abstract', 'Local'] <commit_msg>Load conditionally all available adapters in order to make them available right inside pygrapes.adapter module<commit_after>#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = "mib" __date__ = "$2011-01-22 12:02:41$" from pygrapes.util import not_implemented from pygrapes.adapter.abstract import Abstract from pygrapes.adapter.local import Local try: from pygrapes.adapter.zeromq import Zmq except ImportError: Zmq = not_implemented('A working pyzmq lib is required!') try: from pygrapes.adapter.amqp import Amqp except ImportError: Amqp = not_implemented('A working amqplib lib is required!') __all__ = ['Abstract', 'Amqp', 'Local', 'Zmq']
464c52d5ffd3ea4262bf826e11e6b890976bf589
cherrypy/wsgiserver/__init__.py
cherrypy/wsgiserver/__init__.py
__all__ = ['HTTPRequest', 'HTTPConnection', 'HTTPServer', 'SizeCheckWrapper', 'KnownLengthRFile', 'ChunkedRFile', 'MaxSizeExceeded', 'NoSSLError', 'FatalSSLAlert', 'WorkerThread', 'ThreadPool', 'SSLAdapter', 'CherryPyWSGIServer', 'Gateway', 'WSGIGateway', 'WSGIGateway_10', 'WSGIGateway_u0', 'WSGIPathInfoDispatcher', 'get_ssl_adapter_class'] import sys if sys.version_info < (3, 0): from wsgiserver2 import * else: # Le sigh. Boo for backward-incompatible syntax. exec('from .wsgiserver3 import *')
__all__ = ['HTTPRequest', 'HTTPConnection', 'HTTPServer', 'SizeCheckWrapper', 'KnownLengthRFile', 'ChunkedRFile', 'MaxSizeExceeded', 'NoSSLError', 'FatalSSLAlert', 'WorkerThread', 'ThreadPool', 'SSLAdapter', 'CherryPyWSGIServer', 'Gateway', 'WSGIGateway', 'WSGIGateway_10', 'WSGIGateway_u0', 'WSGIPathInfoDispatcher', 'get_ssl_adapter_class'] import sys if sys.version_info < (3, 0): from .wsgiserver2 import * else: from .wsgiserver3 import *
Use uniform syntax for wsgiserver imports
Use uniform syntax for wsgiserver imports
Python
bsd-3-clause
cherrypy/cherrypy,cherrypy/cheroot,Safihre/cherrypy,cherrypy/cherrypy,Safihre/cherrypy
__all__ = ['HTTPRequest', 'HTTPConnection', 'HTTPServer', 'SizeCheckWrapper', 'KnownLengthRFile', 'ChunkedRFile', 'MaxSizeExceeded', 'NoSSLError', 'FatalSSLAlert', 'WorkerThread', 'ThreadPool', 'SSLAdapter', 'CherryPyWSGIServer', 'Gateway', 'WSGIGateway', 'WSGIGateway_10', 'WSGIGateway_u0', 'WSGIPathInfoDispatcher', 'get_ssl_adapter_class'] import sys if sys.version_info < (3, 0): from wsgiserver2 import * else: # Le sigh. Boo for backward-incompatible syntax. exec('from .wsgiserver3 import *') Use uniform syntax for wsgiserver imports
__all__ = ['HTTPRequest', 'HTTPConnection', 'HTTPServer', 'SizeCheckWrapper', 'KnownLengthRFile', 'ChunkedRFile', 'MaxSizeExceeded', 'NoSSLError', 'FatalSSLAlert', 'WorkerThread', 'ThreadPool', 'SSLAdapter', 'CherryPyWSGIServer', 'Gateway', 'WSGIGateway', 'WSGIGateway_10', 'WSGIGateway_u0', 'WSGIPathInfoDispatcher', 'get_ssl_adapter_class'] import sys if sys.version_info < (3, 0): from .wsgiserver2 import * else: from .wsgiserver3 import *
<commit_before>__all__ = ['HTTPRequest', 'HTTPConnection', 'HTTPServer', 'SizeCheckWrapper', 'KnownLengthRFile', 'ChunkedRFile', 'MaxSizeExceeded', 'NoSSLError', 'FatalSSLAlert', 'WorkerThread', 'ThreadPool', 'SSLAdapter', 'CherryPyWSGIServer', 'Gateway', 'WSGIGateway', 'WSGIGateway_10', 'WSGIGateway_u0', 'WSGIPathInfoDispatcher', 'get_ssl_adapter_class'] import sys if sys.version_info < (3, 0): from wsgiserver2 import * else: # Le sigh. Boo for backward-incompatible syntax. exec('from .wsgiserver3 import *') <commit_msg>Use uniform syntax for wsgiserver imports<commit_after>
__all__ = ['HTTPRequest', 'HTTPConnection', 'HTTPServer', 'SizeCheckWrapper', 'KnownLengthRFile', 'ChunkedRFile', 'MaxSizeExceeded', 'NoSSLError', 'FatalSSLAlert', 'WorkerThread', 'ThreadPool', 'SSLAdapter', 'CherryPyWSGIServer', 'Gateway', 'WSGIGateway', 'WSGIGateway_10', 'WSGIGateway_u0', 'WSGIPathInfoDispatcher', 'get_ssl_adapter_class'] import sys if sys.version_info < (3, 0): from .wsgiserver2 import * else: from .wsgiserver3 import *
__all__ = ['HTTPRequest', 'HTTPConnection', 'HTTPServer', 'SizeCheckWrapper', 'KnownLengthRFile', 'ChunkedRFile', 'MaxSizeExceeded', 'NoSSLError', 'FatalSSLAlert', 'WorkerThread', 'ThreadPool', 'SSLAdapter', 'CherryPyWSGIServer', 'Gateway', 'WSGIGateway', 'WSGIGateway_10', 'WSGIGateway_u0', 'WSGIPathInfoDispatcher', 'get_ssl_adapter_class'] import sys if sys.version_info < (3, 0): from wsgiserver2 import * else: # Le sigh. Boo for backward-incompatible syntax. exec('from .wsgiserver3 import *') Use uniform syntax for wsgiserver imports__all__ = ['HTTPRequest', 'HTTPConnection', 'HTTPServer', 'SizeCheckWrapper', 'KnownLengthRFile', 'ChunkedRFile', 'MaxSizeExceeded', 'NoSSLError', 'FatalSSLAlert', 'WorkerThread', 'ThreadPool', 'SSLAdapter', 'CherryPyWSGIServer', 'Gateway', 'WSGIGateway', 'WSGIGateway_10', 'WSGIGateway_u0', 'WSGIPathInfoDispatcher', 'get_ssl_adapter_class'] import sys if sys.version_info < (3, 0): from .wsgiserver2 import * else: from .wsgiserver3 import *
<commit_before>__all__ = ['HTTPRequest', 'HTTPConnection', 'HTTPServer', 'SizeCheckWrapper', 'KnownLengthRFile', 'ChunkedRFile', 'MaxSizeExceeded', 'NoSSLError', 'FatalSSLAlert', 'WorkerThread', 'ThreadPool', 'SSLAdapter', 'CherryPyWSGIServer', 'Gateway', 'WSGIGateway', 'WSGIGateway_10', 'WSGIGateway_u0', 'WSGIPathInfoDispatcher', 'get_ssl_adapter_class'] import sys if sys.version_info < (3, 0): from wsgiserver2 import * else: # Le sigh. Boo for backward-incompatible syntax. exec('from .wsgiserver3 import *') <commit_msg>Use uniform syntax for wsgiserver imports<commit_after>__all__ = ['HTTPRequest', 'HTTPConnection', 'HTTPServer', 'SizeCheckWrapper', 'KnownLengthRFile', 'ChunkedRFile', 'MaxSizeExceeded', 'NoSSLError', 'FatalSSLAlert', 'WorkerThread', 'ThreadPool', 'SSLAdapter', 'CherryPyWSGIServer', 'Gateway', 'WSGIGateway', 'WSGIGateway_10', 'WSGIGateway_u0', 'WSGIPathInfoDispatcher', 'get_ssl_adapter_class'] import sys if sys.version_info < (3, 0): from .wsgiserver2 import * else: from .wsgiserver3 import *
3b5ac5f7e0b10b06be042037278634fc42bd9b35
tmc/models/document_type.py
tmc/models/document_type.py
# -*- coding: utf-8 -*- from odoo import models, fields, _ class Document_Type(models.Model): _name = 'tmc.document_type' name = fields.Char( string='Document Type' ) abbreviation = fields.Char( size=3, required=True ) model = fields.Char( required=True ) _sql_constraints = [ ('name_unique', 'UNIQUE(name)', _('Document type name must be unique')), ('abbreviation_unique', 'UNIQUE(abbreviation)', _('Document type abbreviation must be unique')) ]
# -*- coding: utf-8 -*- from odoo import _, fields, models class Document_Type(models.Model): _name = 'tmc.document_type' name = fields.Char( string='Document Type' ) abbreviation = fields.Char( size=4, required=True ) model = fields.Char( required=True ) _sql_constraints = [ ('name_unique', 'UNIQUE(name)', _('Document type name must be unique')), ('abbreviation_unique', 'UNIQUE(abbreviation)', _('Document type abbreviation must be unique')) ]
Increase size for abbreviation field
[FIX] Increase size for abbreviation field
Python
agpl-3.0
tmcrosario/odoo-tmc
# -*- coding: utf-8 -*- from odoo import models, fields, _ class Document_Type(models.Model): _name = 'tmc.document_type' name = fields.Char( string='Document Type' ) abbreviation = fields.Char( size=3, required=True ) model = fields.Char( required=True ) _sql_constraints = [ ('name_unique', 'UNIQUE(name)', _('Document type name must be unique')), ('abbreviation_unique', 'UNIQUE(abbreviation)', _('Document type abbreviation must be unique')) ] [FIX] Increase size for abbreviation field
# -*- coding: utf-8 -*- from odoo import _, fields, models class Document_Type(models.Model): _name = 'tmc.document_type' name = fields.Char( string='Document Type' ) abbreviation = fields.Char( size=4, required=True ) model = fields.Char( required=True ) _sql_constraints = [ ('name_unique', 'UNIQUE(name)', _('Document type name must be unique')), ('abbreviation_unique', 'UNIQUE(abbreviation)', _('Document type abbreviation must be unique')) ]
<commit_before># -*- coding: utf-8 -*- from odoo import models, fields, _ class Document_Type(models.Model): _name = 'tmc.document_type' name = fields.Char( string='Document Type' ) abbreviation = fields.Char( size=3, required=True ) model = fields.Char( required=True ) _sql_constraints = [ ('name_unique', 'UNIQUE(name)', _('Document type name must be unique')), ('abbreviation_unique', 'UNIQUE(abbreviation)', _('Document type abbreviation must be unique')) ] <commit_msg>[FIX] Increase size for abbreviation field<commit_after>
# -*- coding: utf-8 -*- from odoo import _, fields, models class Document_Type(models.Model): _name = 'tmc.document_type' name = fields.Char( string='Document Type' ) abbreviation = fields.Char( size=4, required=True ) model = fields.Char( required=True ) _sql_constraints = [ ('name_unique', 'UNIQUE(name)', _('Document type name must be unique')), ('abbreviation_unique', 'UNIQUE(abbreviation)', _('Document type abbreviation must be unique')) ]
# -*- coding: utf-8 -*- from odoo import models, fields, _ class Document_Type(models.Model): _name = 'tmc.document_type' name = fields.Char( string='Document Type' ) abbreviation = fields.Char( size=3, required=True ) model = fields.Char( required=True ) _sql_constraints = [ ('name_unique', 'UNIQUE(name)', _('Document type name must be unique')), ('abbreviation_unique', 'UNIQUE(abbreviation)', _('Document type abbreviation must be unique')) ] [FIX] Increase size for abbreviation field# -*- coding: utf-8 -*- from odoo import _, fields, models class Document_Type(models.Model): _name = 'tmc.document_type' name = fields.Char( string='Document Type' ) abbreviation = fields.Char( size=4, required=True ) model = fields.Char( required=True ) _sql_constraints = [ ('name_unique', 'UNIQUE(name)', _('Document type name must be unique')), ('abbreviation_unique', 'UNIQUE(abbreviation)', _('Document type abbreviation must be unique')) ]
<commit_before># -*- coding: utf-8 -*- from odoo import models, fields, _ class Document_Type(models.Model): _name = 'tmc.document_type' name = fields.Char( string='Document Type' ) abbreviation = fields.Char( size=3, required=True ) model = fields.Char( required=True ) _sql_constraints = [ ('name_unique', 'UNIQUE(name)', _('Document type name must be unique')), ('abbreviation_unique', 'UNIQUE(abbreviation)', _('Document type abbreviation must be unique')) ] <commit_msg>[FIX] Increase size for abbreviation field<commit_after># -*- coding: utf-8 -*- from odoo import _, fields, models class Document_Type(models.Model): _name = 'tmc.document_type' name = fields.Char( string='Document Type' ) abbreviation = fields.Char( size=4, required=True ) model = fields.Char( required=True ) _sql_constraints = [ ('name_unique', 'UNIQUE(name)', _('Document type name must be unique')), ('abbreviation_unique', 'UNIQUE(abbreviation)', _('Document type abbreviation must be unique')) ]
b3f7b677edb0a87abff2ef64dadb64547d757d6b
elasticsearch_django/migrations/0004_auto_20161129_1135.py
elasticsearch_django/migrations/0004_auto_20161129_1135.py
# Generated by Django 1.9 on 2016-11-29 11:35 from django.db import migrations from ..db.fields import JSONField class Migration(migrations.Migration): dependencies = [("elasticsearch_django", "0003_auto_20160926_2021")] operations = [ migrations.AlterField( model_name="searchquery", name="hits", field=JSONField( help_text="The list of meta info for each of the query matches returned." ), ), migrations.AlterField( model_name="searchquery", name="query", field=JSONField(help_text="The raw ElasticSearch DSL query."), ), ]
# Generated by Django 1.9 on 2016-11-29 11:35 from django.contrib.postgres.fields import JSONField from django.db import migrations class Migration(migrations.Migration): dependencies = [("elasticsearch_django", "0003_auto_20160926_2021")] operations = [ migrations.AlterField( model_name="searchquery", name="hits", field=JSONField( help_text="The list of meta info for each of the query matches returned." ), ), migrations.AlterField( model_name="searchquery", name="query", field=JSONField(help_text="The raw ElasticSearch DSL query."), ), ]
Update migration to use native JSONField
Update migration to use native JSONField
Python
mit
yunojuno/elasticsearch-django
# Generated by Django 1.9 on 2016-11-29 11:35 from django.db import migrations from ..db.fields import JSONField class Migration(migrations.Migration): dependencies = [("elasticsearch_django", "0003_auto_20160926_2021")] operations = [ migrations.AlterField( model_name="searchquery", name="hits", field=JSONField( help_text="The list of meta info for each of the query matches returned." ), ), migrations.AlterField( model_name="searchquery", name="query", field=JSONField(help_text="The raw ElasticSearch DSL query."), ), ] Update migration to use native JSONField
# Generated by Django 1.9 on 2016-11-29 11:35 from django.contrib.postgres.fields import JSONField from django.db import migrations class Migration(migrations.Migration): dependencies = [("elasticsearch_django", "0003_auto_20160926_2021")] operations = [ migrations.AlterField( model_name="searchquery", name="hits", field=JSONField( help_text="The list of meta info for each of the query matches returned." ), ), migrations.AlterField( model_name="searchquery", name="query", field=JSONField(help_text="The raw ElasticSearch DSL query."), ), ]
<commit_before># Generated by Django 1.9 on 2016-11-29 11:35 from django.db import migrations from ..db.fields import JSONField class Migration(migrations.Migration): dependencies = [("elasticsearch_django", "0003_auto_20160926_2021")] operations = [ migrations.AlterField( model_name="searchquery", name="hits", field=JSONField( help_text="The list of meta info for each of the query matches returned." ), ), migrations.AlterField( model_name="searchquery", name="query", field=JSONField(help_text="The raw ElasticSearch DSL query."), ), ] <commit_msg>Update migration to use native JSONField<commit_after>
# Generated by Django 1.9 on 2016-11-29 11:35 from django.contrib.postgres.fields import JSONField from django.db import migrations class Migration(migrations.Migration): dependencies = [("elasticsearch_django", "0003_auto_20160926_2021")] operations = [ migrations.AlterField( model_name="searchquery", name="hits", field=JSONField( help_text="The list of meta info for each of the query matches returned." ), ), migrations.AlterField( model_name="searchquery", name="query", field=JSONField(help_text="The raw ElasticSearch DSL query."), ), ]
# Generated by Django 1.9 on 2016-11-29 11:35 from django.db import migrations from ..db.fields import JSONField class Migration(migrations.Migration): dependencies = [("elasticsearch_django", "0003_auto_20160926_2021")] operations = [ migrations.AlterField( model_name="searchquery", name="hits", field=JSONField( help_text="The list of meta info for each of the query matches returned." ), ), migrations.AlterField( model_name="searchquery", name="query", field=JSONField(help_text="The raw ElasticSearch DSL query."), ), ] Update migration to use native JSONField# Generated by Django 1.9 on 2016-11-29 11:35 from django.contrib.postgres.fields import JSONField from django.db import migrations class Migration(migrations.Migration): dependencies = [("elasticsearch_django", "0003_auto_20160926_2021")] operations = [ migrations.AlterField( model_name="searchquery", name="hits", field=JSONField( help_text="The list of meta info for each of the query matches returned." ), ), migrations.AlterField( model_name="searchquery", name="query", field=JSONField(help_text="The raw ElasticSearch DSL query."), ), ]
<commit_before># Generated by Django 1.9 on 2016-11-29 11:35 from django.db import migrations from ..db.fields import JSONField class Migration(migrations.Migration): dependencies = [("elasticsearch_django", "0003_auto_20160926_2021")] operations = [ migrations.AlterField( model_name="searchquery", name="hits", field=JSONField( help_text="The list of meta info for each of the query matches returned." ), ), migrations.AlterField( model_name="searchquery", name="query", field=JSONField(help_text="The raw ElasticSearch DSL query."), ), ] <commit_msg>Update migration to use native JSONField<commit_after># Generated by Django 1.9 on 2016-11-29 11:35 from django.contrib.postgres.fields import JSONField from django.db import migrations class Migration(migrations.Migration): dependencies = [("elasticsearch_django", "0003_auto_20160926_2021")] operations = [ migrations.AlterField( model_name="searchquery", name="hits", field=JSONField( help_text="The list of meta info for each of the query matches returned." ), ), migrations.AlterField( model_name="searchquery", name="query", field=JSONField(help_text="The raw ElasticSearch DSL query."), ), ]
529c98ec0a7c5a3fefa4da6cdf2f6a58b5487ebc
openquake/__init__.py
openquake/__init__.py
# -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (C) 2010-2016 GEM Foundation # # OpenQuake is free software: you can redistribute it and/or modify it # under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # OpenQuake is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with OpenQuake. If not, see <http://www.gnu.org/licenses/>. __import__('pkg_resources').declare_namespace(__name__)
# -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (C) 2010-2016 GEM Foundation # # OpenQuake is free software: you can redistribute it and/or modify it # under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # OpenQuake is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with OpenQuake. If not, see <http://www.gnu.org/licenses/>. # Make the namespace compatible with old setuptools, like the one # provided by QGIS 2.1x on Windows try: __import__('pkg_resources').declare_namespace(__name__) except ImportError: __path__ = __import__('pkgutil').extend_path(__path__, __name__)
Make the openquake namespace compatible with old setuptools
Make the openquake namespace compatible with old setuptools Former-commit-id: e5f4dc01e94694bf9bfcae3ecd6eca34a33a24eb
Python
agpl-3.0
gem/oq-engine,gem/oq-engine,gem/oq-engine,gem/oq-engine,gem/oq-engine
# -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (C) 2010-2016 GEM Foundation # # OpenQuake is free software: you can redistribute it and/or modify it # under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # OpenQuake is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with OpenQuake. If not, see <http://www.gnu.org/licenses/>. __import__('pkg_resources').declare_namespace(__name__) Make the openquake namespace compatible with old setuptools Former-commit-id: e5f4dc01e94694bf9bfcae3ecd6eca34a33a24eb
# -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (C) 2010-2016 GEM Foundation # # OpenQuake is free software: you can redistribute it and/or modify it # under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # OpenQuake is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with OpenQuake. If not, see <http://www.gnu.org/licenses/>. # Make the namespace compatible with old setuptools, like the one # provided by QGIS 2.1x on Windows try: __import__('pkg_resources').declare_namespace(__name__) except ImportError: __path__ = __import__('pkgutil').extend_path(__path__, __name__)
<commit_before># -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (C) 2010-2016 GEM Foundation # # OpenQuake is free software: you can redistribute it and/or modify it # under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # OpenQuake is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with OpenQuake. If not, see <http://www.gnu.org/licenses/>. __import__('pkg_resources').declare_namespace(__name__) <commit_msg>Make the openquake namespace compatible with old setuptools Former-commit-id: e5f4dc01e94694bf9bfcae3ecd6eca34a33a24eb<commit_after>
# -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (C) 2010-2016 GEM Foundation # # OpenQuake is free software: you can redistribute it and/or modify it # under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # OpenQuake is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with OpenQuake. If not, see <http://www.gnu.org/licenses/>. # Make the namespace compatible with old setuptools, like the one # provided by QGIS 2.1x on Windows try: __import__('pkg_resources').declare_namespace(__name__) except ImportError: __path__ = __import__('pkgutil').extend_path(__path__, __name__)
# -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (C) 2010-2016 GEM Foundation # # OpenQuake is free software: you can redistribute it and/or modify it # under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # OpenQuake is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with OpenQuake. If not, see <http://www.gnu.org/licenses/>. __import__('pkg_resources').declare_namespace(__name__) Make the openquake namespace compatible with old setuptools Former-commit-id: e5f4dc01e94694bf9bfcae3ecd6eca34a33a24eb# -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (C) 2010-2016 GEM Foundation # # OpenQuake is free software: you can redistribute it and/or modify it # under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # OpenQuake is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with OpenQuake. If not, see <http://www.gnu.org/licenses/>. # Make the namespace compatible with old setuptools, like the one # provided by QGIS 2.1x on Windows try: __import__('pkg_resources').declare_namespace(__name__) except ImportError: __path__ = __import__('pkgutil').extend_path(__path__, __name__)
<commit_before># -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (C) 2010-2016 GEM Foundation # # OpenQuake is free software: you can redistribute it and/or modify it # under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # OpenQuake is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with OpenQuake. If not, see <http://www.gnu.org/licenses/>. __import__('pkg_resources').declare_namespace(__name__) <commit_msg>Make the openquake namespace compatible with old setuptools Former-commit-id: e5f4dc01e94694bf9bfcae3ecd6eca34a33a24eb<commit_after># -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (C) 2010-2016 GEM Foundation # # OpenQuake is free software: you can redistribute it and/or modify it # under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # OpenQuake is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with OpenQuake. If not, see <http://www.gnu.org/licenses/>. # Make the namespace compatible with old setuptools, like the one # provided by QGIS 2.1x on Windows try: __import__('pkg_resources').declare_namespace(__name__) except ImportError: __path__ = __import__('pkgutil').extend_path(__path__, __name__)
a9848a6af66b672845b876f3b2e1e7c3a8805e0c
wagtailstartproject/legacy_project_template/project_name/wsgi.py
wagtailstartproject/legacy_project_template/project_name/wsgi.py
""" WSGI config for {{ project_name }} project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/{{ docs_version }}/howto/deployment/wsgi/ """ from __future__ import absolute_import, unicode_literals import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "{{ project_name }}.settings.dev") application = get_wsgi_application()
""" WSGI config for {{ project_name }} project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/{{ docs_version }}/howto/deployment/wsgi/ """ from __future__ import absolute_import, unicode_literals import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "{{ project_name }}.settings") application = get_wsgi_application()
Adjust DJANGO_SETTINGS_MODULE to point to settings module
Adjust DJANGO_SETTINGS_MODULE to point to settings module
Python
mit
leukeleu/wagtail-startproject,leukeleu/wagtail-startproject
""" WSGI config for {{ project_name }} project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/{{ docs_version }}/howto/deployment/wsgi/ """ from __future__ import absolute_import, unicode_literals import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "{{ project_name }}.settings.dev") application = get_wsgi_application() Adjust DJANGO_SETTINGS_MODULE to point to settings module
""" WSGI config for {{ project_name }} project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/{{ docs_version }}/howto/deployment/wsgi/ """ from __future__ import absolute_import, unicode_literals import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "{{ project_name }}.settings") application = get_wsgi_application()
<commit_before>""" WSGI config for {{ project_name }} project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/{{ docs_version }}/howto/deployment/wsgi/ """ from __future__ import absolute_import, unicode_literals import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "{{ project_name }}.settings.dev") application = get_wsgi_application() <commit_msg>Adjust DJANGO_SETTINGS_MODULE to point to settings module<commit_after>
""" WSGI config for {{ project_name }} project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/{{ docs_version }}/howto/deployment/wsgi/ """ from __future__ import absolute_import, unicode_literals import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "{{ project_name }}.settings") application = get_wsgi_application()
""" WSGI config for {{ project_name }} project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/{{ docs_version }}/howto/deployment/wsgi/ """ from __future__ import absolute_import, unicode_literals import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "{{ project_name }}.settings.dev") application = get_wsgi_application() Adjust DJANGO_SETTINGS_MODULE to point to settings module""" WSGI config for {{ project_name }} project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/{{ docs_version }}/howto/deployment/wsgi/ """ from __future__ import absolute_import, unicode_literals import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "{{ project_name }}.settings") application = get_wsgi_application()
<commit_before>""" WSGI config for {{ project_name }} project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/{{ docs_version }}/howto/deployment/wsgi/ """ from __future__ import absolute_import, unicode_literals import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "{{ project_name }}.settings.dev") application = get_wsgi_application() <commit_msg>Adjust DJANGO_SETTINGS_MODULE to point to settings module<commit_after>""" WSGI config for {{ project_name }} project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/{{ docs_version }}/howto/deployment/wsgi/ """ from __future__ import absolute_import, unicode_literals import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "{{ project_name }}.settings") application = get_wsgi_application()
0c8e67f51ac6271ea4fed1f524144cfccbf6e215
form_designer/contrib/cms_plugins/form_designer_form/migrations/0001_initial.py
form_designer/contrib/cms_plugins/form_designer_form/migrations/0001_initial.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cms', '0001_initial'), ('form_designer', '0001_initial'), ] operations = [ migrations.CreateModel( name='CMSFormDefinition', fields=[ ('cmsplugin_ptr', models.OneToOneField(serialize=False, auto_created=True, primary_key=True, to='cms.CMSPlugin', parent_link=True)), ('form_definition', models.ForeignKey(verbose_name='form', to='form_designer.FormDefinition')), ], options={ 'abstract': False, }, bases=('cms.cmsplugin',), ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals import cms from django.db import migrations, models from pkg_resources import parse_version as V # Django CMS 3.3.1 is oldest release where the change affects. # Refs https://github.com/divio/django-cms/commit/871a164 if V(cms.__version__) >= V('3.3.1'): field_kwargs = {'related_name': 'form_designer_form_cmsformdefinition'} else: field_kwargs = {} class Migration(migrations.Migration): dependencies = [ ('cms', '0001_initial'), ('form_designer', '0001_initial'), ] operations = [ migrations.CreateModel( name='CMSFormDefinition', fields=[ ('cmsplugin_ptr', models.OneToOneField( serialize=False, auto_created=True, primary_key=True, to='cms.CMSPlugin', parent_link=True, **field_kwargs)), ('form_definition', models.ForeignKey( verbose_name='form', to='form_designer.FormDefinition')), ], options={ 'abstract': False, }, bases=( 'cms.cmsplugin', ), ), ]
Add related name for cmsplugin ptr
Add related name for cmsplugin ptr Add the related name for the cmsplugin_ptr field if the Django CMS version is 3.3.1 or newer. The related name is added to the base model in Django CMS see: https://github.com/divio/django-cms/commit/871a16433f713249ee20b52574803f51941ac20c
Python
bsd-3-clause
andersinno/django-form-designer,kcsry/django-form-designer,andersinno/django-form-designer-ai,andersinno/django-form-designer,andersinno/django-form-designer-ai,kcsry/django-form-designer
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cms', '0001_initial'), ('form_designer', '0001_initial'), ] operations = [ migrations.CreateModel( name='CMSFormDefinition', fields=[ ('cmsplugin_ptr', models.OneToOneField(serialize=False, auto_created=True, primary_key=True, to='cms.CMSPlugin', parent_link=True)), ('form_definition', models.ForeignKey(verbose_name='form', to='form_designer.FormDefinition')), ], options={ 'abstract': False, }, bases=('cms.cmsplugin',), ), ] Add related name for cmsplugin ptr Add the related name for the cmsplugin_ptr field if the Django CMS version is 3.3.1 or newer. The related name is added to the base model in Django CMS see: https://github.com/divio/django-cms/commit/871a16433f713249ee20b52574803f51941ac20c
# -*- coding: utf-8 -*- from __future__ import unicode_literals import cms from django.db import migrations, models from pkg_resources import parse_version as V # Django CMS 3.3.1 is oldest release where the change affects. # Refs https://github.com/divio/django-cms/commit/871a164 if V(cms.__version__) >= V('3.3.1'): field_kwargs = {'related_name': 'form_designer_form_cmsformdefinition'} else: field_kwargs = {} class Migration(migrations.Migration): dependencies = [ ('cms', '0001_initial'), ('form_designer', '0001_initial'), ] operations = [ migrations.CreateModel( name='CMSFormDefinition', fields=[ ('cmsplugin_ptr', models.OneToOneField( serialize=False, auto_created=True, primary_key=True, to='cms.CMSPlugin', parent_link=True, **field_kwargs)), ('form_definition', models.ForeignKey( verbose_name='form', to='form_designer.FormDefinition')), ], options={ 'abstract': False, }, bases=( 'cms.cmsplugin', ), ), ]
<commit_before># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cms', '0001_initial'), ('form_designer', '0001_initial'), ] operations = [ migrations.CreateModel( name='CMSFormDefinition', fields=[ ('cmsplugin_ptr', models.OneToOneField(serialize=False, auto_created=True, primary_key=True, to='cms.CMSPlugin', parent_link=True)), ('form_definition', models.ForeignKey(verbose_name='form', to='form_designer.FormDefinition')), ], options={ 'abstract': False, }, bases=('cms.cmsplugin',), ), ] <commit_msg>Add related name for cmsplugin ptr Add the related name for the cmsplugin_ptr field if the Django CMS version is 3.3.1 or newer. The related name is added to the base model in Django CMS see: https://github.com/divio/django-cms/commit/871a16433f713249ee20b52574803f51941ac20c<commit_after>
# -*- coding: utf-8 -*- from __future__ import unicode_literals import cms from django.db import migrations, models from pkg_resources import parse_version as V # Django CMS 3.3.1 is oldest release where the change affects. # Refs https://github.com/divio/django-cms/commit/871a164 if V(cms.__version__) >= V('3.3.1'): field_kwargs = {'related_name': 'form_designer_form_cmsformdefinition'} else: field_kwargs = {} class Migration(migrations.Migration): dependencies = [ ('cms', '0001_initial'), ('form_designer', '0001_initial'), ] operations = [ migrations.CreateModel( name='CMSFormDefinition', fields=[ ('cmsplugin_ptr', models.OneToOneField( serialize=False, auto_created=True, primary_key=True, to='cms.CMSPlugin', parent_link=True, **field_kwargs)), ('form_definition', models.ForeignKey( verbose_name='form', to='form_designer.FormDefinition')), ], options={ 'abstract': False, }, bases=( 'cms.cmsplugin', ), ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cms', '0001_initial'), ('form_designer', '0001_initial'), ] operations = [ migrations.CreateModel( name='CMSFormDefinition', fields=[ ('cmsplugin_ptr', models.OneToOneField(serialize=False, auto_created=True, primary_key=True, to='cms.CMSPlugin', parent_link=True)), ('form_definition', models.ForeignKey(verbose_name='form', to='form_designer.FormDefinition')), ], options={ 'abstract': False, }, bases=('cms.cmsplugin',), ), ] Add related name for cmsplugin ptr Add the related name for the cmsplugin_ptr field if the Django CMS version is 3.3.1 or newer. The related name is added to the base model in Django CMS see: https://github.com/divio/django-cms/commit/871a16433f713249ee20b52574803f51941ac20c# -*- coding: utf-8 -*- from __future__ import unicode_literals import cms from django.db import migrations, models from pkg_resources import parse_version as V # Django CMS 3.3.1 is oldest release where the change affects. # Refs https://github.com/divio/django-cms/commit/871a164 if V(cms.__version__) >= V('3.3.1'): field_kwargs = {'related_name': 'form_designer_form_cmsformdefinition'} else: field_kwargs = {} class Migration(migrations.Migration): dependencies = [ ('cms', '0001_initial'), ('form_designer', '0001_initial'), ] operations = [ migrations.CreateModel( name='CMSFormDefinition', fields=[ ('cmsplugin_ptr', models.OneToOneField( serialize=False, auto_created=True, primary_key=True, to='cms.CMSPlugin', parent_link=True, **field_kwargs)), ('form_definition', models.ForeignKey( verbose_name='form', to='form_designer.FormDefinition')), ], options={ 'abstract': False, }, bases=( 'cms.cmsplugin', ), ), ]
<commit_before># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cms', '0001_initial'), ('form_designer', '0001_initial'), ] operations = [ migrations.CreateModel( name='CMSFormDefinition', fields=[ ('cmsplugin_ptr', models.OneToOneField(serialize=False, auto_created=True, primary_key=True, to='cms.CMSPlugin', parent_link=True)), ('form_definition', models.ForeignKey(verbose_name='form', to='form_designer.FormDefinition')), ], options={ 'abstract': False, }, bases=('cms.cmsplugin',), ), ] <commit_msg>Add related name for cmsplugin ptr Add the related name for the cmsplugin_ptr field if the Django CMS version is 3.3.1 or newer. The related name is added to the base model in Django CMS see: https://github.com/divio/django-cms/commit/871a16433f713249ee20b52574803f51941ac20c<commit_after># -*- coding: utf-8 -*- from __future__ import unicode_literals import cms from django.db import migrations, models from pkg_resources import parse_version as V # Django CMS 3.3.1 is oldest release where the change affects. # Refs https://github.com/divio/django-cms/commit/871a164 if V(cms.__version__) >= V('3.3.1'): field_kwargs = {'related_name': 'form_designer_form_cmsformdefinition'} else: field_kwargs = {} class Migration(migrations.Migration): dependencies = [ ('cms', '0001_initial'), ('form_designer', '0001_initial'), ] operations = [ migrations.CreateModel( name='CMSFormDefinition', fields=[ ('cmsplugin_ptr', models.OneToOneField( serialize=False, auto_created=True, primary_key=True, to='cms.CMSPlugin', parent_link=True, **field_kwargs)), ('form_definition', models.ForeignKey( verbose_name='form', to='form_designer.FormDefinition')), ], options={ 'abstract': False, }, bases=( 'cms.cmsplugin', ), ), ]
4bbfdfc63cdfa0a6f54b09683033f23a71115547
src/pyws/protocols/rest.py
src/pyws/protocols/rest.py
from functools import partial from pyws.errors import BadRequest from pyws.functions.args.types.complex import List from pyws.response import Response from pyws.utils import json from pyws.protocols.base import Protocol __all__ = ('RestProtocol', 'JsonProtocol', ) create_response = partial(Response, content_type='application/json') create_error_response = partial(create_response, status=Response.STATUS_ERROR) class RestProtocol(Protocol): name = 'rest' def get_function(self, request): return request.tail def get_arguments(self, request, arguments): result = {} for field in arguments.fields: value = request.GET.get(field.name) if issubclass(field.type, List): result[field.name] = value elif field.name in request.GET: result[field.name] = value[0] return result def get_response(self, result, name, return_type): return create_response(json.dumps({'result': result})) def get_error_response(self, error): return create_error_response( json.dumps({'error': self.get_error(error)})) class JsonProtocol(RestProtocol): name = 'json' def get_arguments(self, request, arguments): try: return json.loads(request.text) except ValueError: raise BadRequest()
from functools import partial from pyws.errors import BadRequest from pyws.functions.args.types.complex import List from pyws.response import Response from pyws.utils import json class encoder( json.JSONEncoder ): # JSON Serializer with datetime support def default(self,obj): if isinstance(obj, datetime.datetime): return obj.isoformat() return json.JSONEncoder.default( self,obj) from pyws.protocols.base import Protocol __all__ = ('RestProtocol', 'JsonProtocol', ) create_response = partial(Response, content_type='application/json') create_error_response = partial(create_response, status=Response.STATUS_ERROR) class RestProtocol(Protocol): name = 'rest' def get_function(self, request): return request.tail def get_arguments(self, request, arguments): result = {} for field in arguments.fields: value = request.GET.get(field.name) if issubclass(field.type, List): result[field.name] = value elif field.name in request.GET: result[field.name] = value[0] return result def get_response(self, result, name, return_type): return create_response(json.dumps({'result': result},cls=encoder)) def get_error_response(self, error): return create_error_response( json.dumps({'error': self.get_error(error)})) class JsonProtocol(RestProtocol): name = 'json' def get_arguments(self, request, arguments): try: return json.loads(request.text) except ValueError: raise BadRequest()
Add custom JSON serialize for Python datetime
Add custom JSON serialize for Python datetime This adds a custom JSON serializer class which stringifies Python datetime objects in to ISO 8601. JSON does not specify a date/time format, and many parsers break trying to parse a Date() javascript object. 8601 seems a resonable compromise.
Python
mit
stepank/pyws,stepank/pyws,stepank/pyws,stepank/pyws,stepank/pyws
from functools import partial from pyws.errors import BadRequest from pyws.functions.args.types.complex import List from pyws.response import Response from pyws.utils import json from pyws.protocols.base import Protocol __all__ = ('RestProtocol', 'JsonProtocol', ) create_response = partial(Response, content_type='application/json') create_error_response = partial(create_response, status=Response.STATUS_ERROR) class RestProtocol(Protocol): name = 'rest' def get_function(self, request): return request.tail def get_arguments(self, request, arguments): result = {} for field in arguments.fields: value = request.GET.get(field.name) if issubclass(field.type, List): result[field.name] = value elif field.name in request.GET: result[field.name] = value[0] return result def get_response(self, result, name, return_type): return create_response(json.dumps({'result': result})) def get_error_response(self, error): return create_error_response( json.dumps({'error': self.get_error(error)})) class JsonProtocol(RestProtocol): name = 'json' def get_arguments(self, request, arguments): try: return json.loads(request.text) except ValueError: raise BadRequest() Add custom JSON serialize for Python datetime This adds a custom JSON serializer class which stringifies Python datetime objects in to ISO 8601. JSON does not specify a date/time format, and many parsers break trying to parse a Date() javascript object. 8601 seems a resonable compromise.
from functools import partial from pyws.errors import BadRequest from pyws.functions.args.types.complex import List from pyws.response import Response from pyws.utils import json class encoder( json.JSONEncoder ): # JSON Serializer with datetime support def default(self,obj): if isinstance(obj, datetime.datetime): return obj.isoformat() return json.JSONEncoder.default( self,obj) from pyws.protocols.base import Protocol __all__ = ('RestProtocol', 'JsonProtocol', ) create_response = partial(Response, content_type='application/json') create_error_response = partial(create_response, status=Response.STATUS_ERROR) class RestProtocol(Protocol): name = 'rest' def get_function(self, request): return request.tail def get_arguments(self, request, arguments): result = {} for field in arguments.fields: value = request.GET.get(field.name) if issubclass(field.type, List): result[field.name] = value elif field.name in request.GET: result[field.name] = value[0] return result def get_response(self, result, name, return_type): return create_response(json.dumps({'result': result},cls=encoder)) def get_error_response(self, error): return create_error_response( json.dumps({'error': self.get_error(error)})) class JsonProtocol(RestProtocol): name = 'json' def get_arguments(self, request, arguments): try: return json.loads(request.text) except ValueError: raise BadRequest()
<commit_before>from functools import partial from pyws.errors import BadRequest from pyws.functions.args.types.complex import List from pyws.response import Response from pyws.utils import json from pyws.protocols.base import Protocol __all__ = ('RestProtocol', 'JsonProtocol', ) create_response = partial(Response, content_type='application/json') create_error_response = partial(create_response, status=Response.STATUS_ERROR) class RestProtocol(Protocol): name = 'rest' def get_function(self, request): return request.tail def get_arguments(self, request, arguments): result = {} for field in arguments.fields: value = request.GET.get(field.name) if issubclass(field.type, List): result[field.name] = value elif field.name in request.GET: result[field.name] = value[0] return result def get_response(self, result, name, return_type): return create_response(json.dumps({'result': result})) def get_error_response(self, error): return create_error_response( json.dumps({'error': self.get_error(error)})) class JsonProtocol(RestProtocol): name = 'json' def get_arguments(self, request, arguments): try: return json.loads(request.text) except ValueError: raise BadRequest() <commit_msg>Add custom JSON serialize for Python datetime This adds a custom JSON serializer class which stringifies Python datetime objects in to ISO 8601. JSON does not specify a date/time format, and many parsers break trying to parse a Date() javascript object. 8601 seems a resonable compromise.<commit_after>
from functools import partial from pyws.errors import BadRequest from pyws.functions.args.types.complex import List from pyws.response import Response from pyws.utils import json class encoder( json.JSONEncoder ): # JSON Serializer with datetime support def default(self,obj): if isinstance(obj, datetime.datetime): return obj.isoformat() return json.JSONEncoder.default( self,obj) from pyws.protocols.base import Protocol __all__ = ('RestProtocol', 'JsonProtocol', ) create_response = partial(Response, content_type='application/json') create_error_response = partial(create_response, status=Response.STATUS_ERROR) class RestProtocol(Protocol): name = 'rest' def get_function(self, request): return request.tail def get_arguments(self, request, arguments): result = {} for field in arguments.fields: value = request.GET.get(field.name) if issubclass(field.type, List): result[field.name] = value elif field.name in request.GET: result[field.name] = value[0] return result def get_response(self, result, name, return_type): return create_response(json.dumps({'result': result},cls=encoder)) def get_error_response(self, error): return create_error_response( json.dumps({'error': self.get_error(error)})) class JsonProtocol(RestProtocol): name = 'json' def get_arguments(self, request, arguments): try: return json.loads(request.text) except ValueError: raise BadRequest()
from functools import partial from pyws.errors import BadRequest from pyws.functions.args.types.complex import List from pyws.response import Response from pyws.utils import json from pyws.protocols.base import Protocol __all__ = ('RestProtocol', 'JsonProtocol', ) create_response = partial(Response, content_type='application/json') create_error_response = partial(create_response, status=Response.STATUS_ERROR) class RestProtocol(Protocol): name = 'rest' def get_function(self, request): return request.tail def get_arguments(self, request, arguments): result = {} for field in arguments.fields: value = request.GET.get(field.name) if issubclass(field.type, List): result[field.name] = value elif field.name in request.GET: result[field.name] = value[0] return result def get_response(self, result, name, return_type): return create_response(json.dumps({'result': result})) def get_error_response(self, error): return create_error_response( json.dumps({'error': self.get_error(error)})) class JsonProtocol(RestProtocol): name = 'json' def get_arguments(self, request, arguments): try: return json.loads(request.text) except ValueError: raise BadRequest() Add custom JSON serialize for Python datetime This adds a custom JSON serializer class which stringifies Python datetime objects in to ISO 8601. JSON does not specify a date/time format, and many parsers break trying to parse a Date() javascript object. 8601 seems a resonable compromise.from functools import partial from pyws.errors import BadRequest from pyws.functions.args.types.complex import List from pyws.response import Response from pyws.utils import json class encoder( json.JSONEncoder ): # JSON Serializer with datetime support def default(self,obj): if isinstance(obj, datetime.datetime): return obj.isoformat() return json.JSONEncoder.default( self,obj) from pyws.protocols.base import Protocol __all__ = ('RestProtocol', 'JsonProtocol', ) create_response = partial(Response, content_type='application/json') create_error_response = partial(create_response, status=Response.STATUS_ERROR) class RestProtocol(Protocol): name = 'rest' def get_function(self, request): return request.tail def get_arguments(self, request, arguments): result = {} for field in arguments.fields: value = request.GET.get(field.name) if issubclass(field.type, List): result[field.name] = value elif field.name in request.GET: result[field.name] = value[0] return result def get_response(self, result, name, return_type): return create_response(json.dumps({'result': result},cls=encoder)) def get_error_response(self, error): return create_error_response( json.dumps({'error': self.get_error(error)})) class JsonProtocol(RestProtocol): name = 'json' def get_arguments(self, request, arguments): try: return json.loads(request.text) except ValueError: raise BadRequest()
<commit_before>from functools import partial from pyws.errors import BadRequest from pyws.functions.args.types.complex import List from pyws.response import Response from pyws.utils import json from pyws.protocols.base import Protocol __all__ = ('RestProtocol', 'JsonProtocol', ) create_response = partial(Response, content_type='application/json') create_error_response = partial(create_response, status=Response.STATUS_ERROR) class RestProtocol(Protocol): name = 'rest' def get_function(self, request): return request.tail def get_arguments(self, request, arguments): result = {} for field in arguments.fields: value = request.GET.get(field.name) if issubclass(field.type, List): result[field.name] = value elif field.name in request.GET: result[field.name] = value[0] return result def get_response(self, result, name, return_type): return create_response(json.dumps({'result': result})) def get_error_response(self, error): return create_error_response( json.dumps({'error': self.get_error(error)})) class JsonProtocol(RestProtocol): name = 'json' def get_arguments(self, request, arguments): try: return json.loads(request.text) except ValueError: raise BadRequest() <commit_msg>Add custom JSON serialize for Python datetime This adds a custom JSON serializer class which stringifies Python datetime objects in to ISO 8601. JSON does not specify a date/time format, and many parsers break trying to parse a Date() javascript object. 8601 seems a resonable compromise.<commit_after>from functools import partial from pyws.errors import BadRequest from pyws.functions.args.types.complex import List from pyws.response import Response from pyws.utils import json class encoder( json.JSONEncoder ): # JSON Serializer with datetime support def default(self,obj): if isinstance(obj, datetime.datetime): return obj.isoformat() return json.JSONEncoder.default( self,obj) from pyws.protocols.base import Protocol __all__ = ('RestProtocol', 'JsonProtocol', ) create_response = partial(Response, content_type='application/json') create_error_response = partial(create_response, status=Response.STATUS_ERROR) class RestProtocol(Protocol): name = 'rest' def get_function(self, request): return request.tail def get_arguments(self, request, arguments): result = {} for field in arguments.fields: value = request.GET.get(field.name) if issubclass(field.type, List): result[field.name] = value elif field.name in request.GET: result[field.name] = value[0] return result def get_response(self, result, name, return_type): return create_response(json.dumps({'result': result},cls=encoder)) def get_error_response(self, error): return create_error_response( json.dumps({'error': self.get_error(error)})) class JsonProtocol(RestProtocol): name = 'json' def get_arguments(self, request, arguments): try: return json.loads(request.text) except ValueError: raise BadRequest()
b0aad0ba83557fc529e803547f93a54d272f5817
fmn/lib/tests/example_rules.py
fmn/lib/tests/example_rules.py
""" Some example rules for the test suite. """ def wat_rule(config, message): return message['wat'] == 'blah' def not_wat_rule(config, message): return message['wat'] != 'blah'
""" Some example rules for the test suite. """ import fmn.lib.hinting def wat_rule(config, message): return message['wat'] == 'blah' def not_wat_rule(config, message): return message['wat'] != 'blah' @fmn.lib.hinting.hint(categories=['whatever']) def hint_masked_rule(config, message, argument1): """ This is a docstring. For real, it is a docstring. """ return True
Add example rule for test.
Add example rule for test.
Python
lgpl-2.1
jeremycline/fmn,jeremycline/fmn,jeremycline/fmn
""" Some example rules for the test suite. """ def wat_rule(config, message): return message['wat'] == 'blah' def not_wat_rule(config, message): return message['wat'] != 'blah' Add example rule for test.
""" Some example rules for the test suite. """ import fmn.lib.hinting def wat_rule(config, message): return message['wat'] == 'blah' def not_wat_rule(config, message): return message['wat'] != 'blah' @fmn.lib.hinting.hint(categories=['whatever']) def hint_masked_rule(config, message, argument1): """ This is a docstring. For real, it is a docstring. """ return True
<commit_before>""" Some example rules for the test suite. """ def wat_rule(config, message): return message['wat'] == 'blah' def not_wat_rule(config, message): return message['wat'] != 'blah' <commit_msg>Add example rule for test.<commit_after>
""" Some example rules for the test suite. """ import fmn.lib.hinting def wat_rule(config, message): return message['wat'] == 'blah' def not_wat_rule(config, message): return message['wat'] != 'blah' @fmn.lib.hinting.hint(categories=['whatever']) def hint_masked_rule(config, message, argument1): """ This is a docstring. For real, it is a docstring. """ return True
""" Some example rules for the test suite. """ def wat_rule(config, message): return message['wat'] == 'blah' def not_wat_rule(config, message): return message['wat'] != 'blah' Add example rule for test.""" Some example rules for the test suite. """ import fmn.lib.hinting def wat_rule(config, message): return message['wat'] == 'blah' def not_wat_rule(config, message): return message['wat'] != 'blah' @fmn.lib.hinting.hint(categories=['whatever']) def hint_masked_rule(config, message, argument1): """ This is a docstring. For real, it is a docstring. """ return True
<commit_before>""" Some example rules for the test suite. """ def wat_rule(config, message): return message['wat'] == 'blah' def not_wat_rule(config, message): return message['wat'] != 'blah' <commit_msg>Add example rule for test.<commit_after>""" Some example rules for the test suite. """ import fmn.lib.hinting def wat_rule(config, message): return message['wat'] == 'blah' def not_wat_rule(config, message): return message['wat'] != 'blah' @fmn.lib.hinting.hint(categories=['whatever']) def hint_masked_rule(config, message, argument1): """ This is a docstring. For real, it is a docstring. """ return True
d145d2fe8666d4dbbc104bb563fc43415bd8802c
downloaders/downloader_factory.py
downloaders/downloader_factory.py
import logging from argparse import Namespace from downloaders import downloader from downloaders.downloader import Downloader from downloaders.reddit_downloader import RedditDownloader LOGGER = logging.getLogger(__name__) FOURCHAN_FILE_PATTERN = "4chan*_%s.*" IMGUR_SITE_FILE_PATTERN = "imgur*_%s.*" class DownloaderFactory: _DOWNLOADERS = { "imgur": Downloader(IMGUR_SITE_FILE_PATTERN), "4chan": Downloader(FOURCHAN_FILE_PATTERN), "reddit": RedditDownloader() } @staticmethod def get_downloader(args: Namespace) -> downloader.Downloader: downloader = None # We don't need to parse anything for reddit, so we can just return the Downloader if args.site == "reddit": return DownloaderFactory._DOWNLOADERS.get("reddit") if not args.url: raise ValueError("No URL was specified") for key in DownloaderFactory._DOWNLOADERS: if key in args.url: LOGGER.debug(f"Choosing the {key} downloader") return DownloaderFactory._DOWNLOADERS[key] if not downloader: LOGGER.warning("The domain in %s is not supported..." % args.url) return downloader
import logging from argparse import Namespace from downloaders import downloader from downloaders.downloader import Downloader from downloaders.reddit_downloader import RedditDownloader LOGGER = logging.getLogger(__name__) FOURCHAN_FILE_PATTERN = "4chan*_%s.*" IMGUR_SITE_FILE_PATTERN = "imgur*_%s.*" class DownloaderFactory: _DOWNLOADERS = { "imgur": Downloader(IMGUR_SITE_FILE_PATTERN), "4chan": Downloader(FOURCHAN_FILE_PATTERN), "reddit": RedditDownloader() } @staticmethod def get_downloader(args: Namespace) -> downloader.Downloader: downloader = None # We don't need to parse anything for reddit, so we can just return the Downloader if args.site == "reddit": return DownloaderFactory._DOWNLOADERS.get("reddit") if not args.url: raise ValueError("No URL was specified") if "reddit" in args.url: LOGGER.error(f"{args.url} seems to be hosted on reddit, please switch to reddit mode to download images!") raise ValueError("Reddit downloading not supported in URL mode!") for key in DownloaderFactory._DOWNLOADERS: if key in args.url: LOGGER.debug(f"Choosing the {key} downloader") return DownloaderFactory._DOWNLOADERS[key] if not downloader: LOGGER.warning("The domain in %s is not supported..." % args.url) return downloader
Add valitation for reddit domains when in URL mode
Add valitation for reddit domains when in URL mode
Python
apache-2.0
CharlieCorner/pymage_downloader
import logging from argparse import Namespace from downloaders import downloader from downloaders.downloader import Downloader from downloaders.reddit_downloader import RedditDownloader LOGGER = logging.getLogger(__name__) FOURCHAN_FILE_PATTERN = "4chan*_%s.*" IMGUR_SITE_FILE_PATTERN = "imgur*_%s.*" class DownloaderFactory: _DOWNLOADERS = { "imgur": Downloader(IMGUR_SITE_FILE_PATTERN), "4chan": Downloader(FOURCHAN_FILE_PATTERN), "reddit": RedditDownloader() } @staticmethod def get_downloader(args: Namespace) -> downloader.Downloader: downloader = None # We don't need to parse anything for reddit, so we can just return the Downloader if args.site == "reddit": return DownloaderFactory._DOWNLOADERS.get("reddit") if not args.url: raise ValueError("No URL was specified") for key in DownloaderFactory._DOWNLOADERS: if key in args.url: LOGGER.debug(f"Choosing the {key} downloader") return DownloaderFactory._DOWNLOADERS[key] if not downloader: LOGGER.warning("The domain in %s is not supported..." % args.url) return downloader Add valitation for reddit domains when in URL mode
import logging from argparse import Namespace from downloaders import downloader from downloaders.downloader import Downloader from downloaders.reddit_downloader import RedditDownloader LOGGER = logging.getLogger(__name__) FOURCHAN_FILE_PATTERN = "4chan*_%s.*" IMGUR_SITE_FILE_PATTERN = "imgur*_%s.*" class DownloaderFactory: _DOWNLOADERS = { "imgur": Downloader(IMGUR_SITE_FILE_PATTERN), "4chan": Downloader(FOURCHAN_FILE_PATTERN), "reddit": RedditDownloader() } @staticmethod def get_downloader(args: Namespace) -> downloader.Downloader: downloader = None # We don't need to parse anything for reddit, so we can just return the Downloader if args.site == "reddit": return DownloaderFactory._DOWNLOADERS.get("reddit") if not args.url: raise ValueError("No URL was specified") if "reddit" in args.url: LOGGER.error(f"{args.url} seems to be hosted on reddit, please switch to reddit mode to download images!") raise ValueError("Reddit downloading not supported in URL mode!") for key in DownloaderFactory._DOWNLOADERS: if key in args.url: LOGGER.debug(f"Choosing the {key} downloader") return DownloaderFactory._DOWNLOADERS[key] if not downloader: LOGGER.warning("The domain in %s is not supported..." % args.url) return downloader
<commit_before>import logging from argparse import Namespace from downloaders import downloader from downloaders.downloader import Downloader from downloaders.reddit_downloader import RedditDownloader LOGGER = logging.getLogger(__name__) FOURCHAN_FILE_PATTERN = "4chan*_%s.*" IMGUR_SITE_FILE_PATTERN = "imgur*_%s.*" class DownloaderFactory: _DOWNLOADERS = { "imgur": Downloader(IMGUR_SITE_FILE_PATTERN), "4chan": Downloader(FOURCHAN_FILE_PATTERN), "reddit": RedditDownloader() } @staticmethod def get_downloader(args: Namespace) -> downloader.Downloader: downloader = None # We don't need to parse anything for reddit, so we can just return the Downloader if args.site == "reddit": return DownloaderFactory._DOWNLOADERS.get("reddit") if not args.url: raise ValueError("No URL was specified") for key in DownloaderFactory._DOWNLOADERS: if key in args.url: LOGGER.debug(f"Choosing the {key} downloader") return DownloaderFactory._DOWNLOADERS[key] if not downloader: LOGGER.warning("The domain in %s is not supported..." % args.url) return downloader <commit_msg>Add valitation for reddit domains when in URL mode<commit_after>
import logging from argparse import Namespace from downloaders import downloader from downloaders.downloader import Downloader from downloaders.reddit_downloader import RedditDownloader LOGGER = logging.getLogger(__name__) FOURCHAN_FILE_PATTERN = "4chan*_%s.*" IMGUR_SITE_FILE_PATTERN = "imgur*_%s.*" class DownloaderFactory: _DOWNLOADERS = { "imgur": Downloader(IMGUR_SITE_FILE_PATTERN), "4chan": Downloader(FOURCHAN_FILE_PATTERN), "reddit": RedditDownloader() } @staticmethod def get_downloader(args: Namespace) -> downloader.Downloader: downloader = None # We don't need to parse anything for reddit, so we can just return the Downloader if args.site == "reddit": return DownloaderFactory._DOWNLOADERS.get("reddit") if not args.url: raise ValueError("No URL was specified") if "reddit" in args.url: LOGGER.error(f"{args.url} seems to be hosted on reddit, please switch to reddit mode to download images!") raise ValueError("Reddit downloading not supported in URL mode!") for key in DownloaderFactory._DOWNLOADERS: if key in args.url: LOGGER.debug(f"Choosing the {key} downloader") return DownloaderFactory._DOWNLOADERS[key] if not downloader: LOGGER.warning("The domain in %s is not supported..." % args.url) return downloader
import logging from argparse import Namespace from downloaders import downloader from downloaders.downloader import Downloader from downloaders.reddit_downloader import RedditDownloader LOGGER = logging.getLogger(__name__) FOURCHAN_FILE_PATTERN = "4chan*_%s.*" IMGUR_SITE_FILE_PATTERN = "imgur*_%s.*" class DownloaderFactory: _DOWNLOADERS = { "imgur": Downloader(IMGUR_SITE_FILE_PATTERN), "4chan": Downloader(FOURCHAN_FILE_PATTERN), "reddit": RedditDownloader() } @staticmethod def get_downloader(args: Namespace) -> downloader.Downloader: downloader = None # We don't need to parse anything for reddit, so we can just return the Downloader if args.site == "reddit": return DownloaderFactory._DOWNLOADERS.get("reddit") if not args.url: raise ValueError("No URL was specified") for key in DownloaderFactory._DOWNLOADERS: if key in args.url: LOGGER.debug(f"Choosing the {key} downloader") return DownloaderFactory._DOWNLOADERS[key] if not downloader: LOGGER.warning("The domain in %s is not supported..." % args.url) return downloader Add valitation for reddit domains when in URL modeimport logging from argparse import Namespace from downloaders import downloader from downloaders.downloader import Downloader from downloaders.reddit_downloader import RedditDownloader LOGGER = logging.getLogger(__name__) FOURCHAN_FILE_PATTERN = "4chan*_%s.*" IMGUR_SITE_FILE_PATTERN = "imgur*_%s.*" class DownloaderFactory: _DOWNLOADERS = { "imgur": Downloader(IMGUR_SITE_FILE_PATTERN), "4chan": Downloader(FOURCHAN_FILE_PATTERN), "reddit": RedditDownloader() } @staticmethod def get_downloader(args: Namespace) -> downloader.Downloader: downloader = None # We don't need to parse anything for reddit, so we can just return the Downloader if args.site == "reddit": return DownloaderFactory._DOWNLOADERS.get("reddit") if not args.url: raise ValueError("No URL was specified") if "reddit" in args.url: LOGGER.error(f"{args.url} seems to be hosted on reddit, please switch to reddit mode to download images!") raise ValueError("Reddit downloading not supported in URL mode!") for key in DownloaderFactory._DOWNLOADERS: if key in args.url: LOGGER.debug(f"Choosing the {key} downloader") return DownloaderFactory._DOWNLOADERS[key] if not downloader: LOGGER.warning("The domain in %s is not supported..." % args.url) return downloader
<commit_before>import logging from argparse import Namespace from downloaders import downloader from downloaders.downloader import Downloader from downloaders.reddit_downloader import RedditDownloader LOGGER = logging.getLogger(__name__) FOURCHAN_FILE_PATTERN = "4chan*_%s.*" IMGUR_SITE_FILE_PATTERN = "imgur*_%s.*" class DownloaderFactory: _DOWNLOADERS = { "imgur": Downloader(IMGUR_SITE_FILE_PATTERN), "4chan": Downloader(FOURCHAN_FILE_PATTERN), "reddit": RedditDownloader() } @staticmethod def get_downloader(args: Namespace) -> downloader.Downloader: downloader = None # We don't need to parse anything for reddit, so we can just return the Downloader if args.site == "reddit": return DownloaderFactory._DOWNLOADERS.get("reddit") if not args.url: raise ValueError("No URL was specified") for key in DownloaderFactory._DOWNLOADERS: if key in args.url: LOGGER.debug(f"Choosing the {key} downloader") return DownloaderFactory._DOWNLOADERS[key] if not downloader: LOGGER.warning("The domain in %s is not supported..." % args.url) return downloader <commit_msg>Add valitation for reddit domains when in URL mode<commit_after>import logging from argparse import Namespace from downloaders import downloader from downloaders.downloader import Downloader from downloaders.reddit_downloader import RedditDownloader LOGGER = logging.getLogger(__name__) FOURCHAN_FILE_PATTERN = "4chan*_%s.*" IMGUR_SITE_FILE_PATTERN = "imgur*_%s.*" class DownloaderFactory: _DOWNLOADERS = { "imgur": Downloader(IMGUR_SITE_FILE_PATTERN), "4chan": Downloader(FOURCHAN_FILE_PATTERN), "reddit": RedditDownloader() } @staticmethod def get_downloader(args: Namespace) -> downloader.Downloader: downloader = None # We don't need to parse anything for reddit, so we can just return the Downloader if args.site == "reddit": return DownloaderFactory._DOWNLOADERS.get("reddit") if not args.url: raise ValueError("No URL was specified") if "reddit" in args.url: LOGGER.error(f"{args.url} seems to be hosted on reddit, please switch to reddit mode to download images!") raise ValueError("Reddit downloading not supported in URL mode!") for key in DownloaderFactory._DOWNLOADERS: if key in args.url: LOGGER.debug(f"Choosing the {key} downloader") return DownloaderFactory._DOWNLOADERS[key] if not downloader: LOGGER.warning("The domain in %s is not supported..." % args.url) return downloader
7aa7eb3b27ddf4d27f62fb7e201f1cbf9b4a04e7
detectem/ws.py
detectem/ws.py
import sys try: from bottle import run, post, request except ImportError: print("Install bottle to use the web service ..") sys.exit(0) from detectem.cli import get_detection_results @post('/detect') def do_detection(): url = request.forms.get('url') return get_detection_results(url, format='json') run(host='localhost', port=5723)
import sys try: from bottle import run, post, request except ImportError: print("Install bottle to use the web service ..") sys.exit(0) from detectem.cli import get_detection_results @post('/detect') def do_detection(): url = request.forms.get('url') return get_detection_results(url, format='json') run(host='0.0.0.0', port=5723)
Update webservice to listen at any interface
Update webservice to listen at any interface
Python
mit
spectresearch/detectem
import sys try: from bottle import run, post, request except ImportError: print("Install bottle to use the web service ..") sys.exit(0) from detectem.cli import get_detection_results @post('/detect') def do_detection(): url = request.forms.get('url') return get_detection_results(url, format='json') run(host='localhost', port=5723) Update webservice to listen at any interface
import sys try: from bottle import run, post, request except ImportError: print("Install bottle to use the web service ..") sys.exit(0) from detectem.cli import get_detection_results @post('/detect') def do_detection(): url = request.forms.get('url') return get_detection_results(url, format='json') run(host='0.0.0.0', port=5723)
<commit_before>import sys try: from bottle import run, post, request except ImportError: print("Install bottle to use the web service ..") sys.exit(0) from detectem.cli import get_detection_results @post('/detect') def do_detection(): url = request.forms.get('url') return get_detection_results(url, format='json') run(host='localhost', port=5723) <commit_msg>Update webservice to listen at any interface<commit_after>
import sys try: from bottle import run, post, request except ImportError: print("Install bottle to use the web service ..") sys.exit(0) from detectem.cli import get_detection_results @post('/detect') def do_detection(): url = request.forms.get('url') return get_detection_results(url, format='json') run(host='0.0.0.0', port=5723)
import sys try: from bottle import run, post, request except ImportError: print("Install bottle to use the web service ..") sys.exit(0) from detectem.cli import get_detection_results @post('/detect') def do_detection(): url = request.forms.get('url') return get_detection_results(url, format='json') run(host='localhost', port=5723) Update webservice to listen at any interfaceimport sys try: from bottle import run, post, request except ImportError: print("Install bottle to use the web service ..") sys.exit(0) from detectem.cli import get_detection_results @post('/detect') def do_detection(): url = request.forms.get('url') return get_detection_results(url, format='json') run(host='0.0.0.0', port=5723)
<commit_before>import sys try: from bottle import run, post, request except ImportError: print("Install bottle to use the web service ..") sys.exit(0) from detectem.cli import get_detection_results @post('/detect') def do_detection(): url = request.forms.get('url') return get_detection_results(url, format='json') run(host='localhost', port=5723) <commit_msg>Update webservice to listen at any interface<commit_after>import sys try: from bottle import run, post, request except ImportError: print("Install bottle to use the web service ..") sys.exit(0) from detectem.cli import get_detection_results @post('/detect') def do_detection(): url = request.forms.get('url') return get_detection_results(url, format='json') run(host='0.0.0.0', port=5723)
9adb2bd399e2c438dc65884ece14445c8b8e970a
cisco_olt_http/client.py
cisco_olt_http/client.py
import logging import requests import xmltodict from urllib.parse import urljoin LOGGER = logging.getLogger('cisco_olt_http.client') class Client(object): def __init__(self, base_url): self.base_url = base_url self.session = requests.Session() # token is incremented before each operation self.token = -1 def login(self, username, password): login_data = { 'myusername': username, 'mypassword': password, 'button': 'Login', 'textfield': 'UX_EQUIPNAME', } response = self._req('login.htm', data=login_data) response.raise_for_status() return response def _op(self, op, incr_token=True): if incr_token is True: self.token += 1 return op.execute() def _req(self, url, **options): url = urljoin(self.base_url, url) LOGGER.debug('Request to: %s with options: %s', url, options) response = self.session.post(url, **options) LOGGER.debug( 'Response status: %s content: %s', response.status_code, response.content) return response
import logging import requests import xmltodict from urllib.parse import urljoin LOGGER = logging.getLogger('cisco_olt_http.client') class Client(object): def __init__(self, base_url): self.base_url = base_url self.session = requests.Session() # token is incremented before each operation self._token = -1 @property def token(self): self._token += 1 return self._token def login(self, username, password): login_data = { 'myusername': username, 'mypassword': password, 'button': 'Login', 'textfield': 'UX_EQUIPNAME', } response = self._req('login.htm', data=login_data) response.raise_for_status() return response def _req(self, url, **options): url = urljoin(self.base_url, url) LOGGER.debug('Request to: %s with options: %s', url, options) response = self.session.post(url, **options) LOGGER.debug( 'Response status: %s content: %s', response.status_code, response.content) return response
Change token atrribute to property
Change token atrribute to property
Python
mit
Vnet-as/cisco-olt-http-client,beezz/cisco-olt-http-client
import logging import requests import xmltodict from urllib.parse import urljoin LOGGER = logging.getLogger('cisco_olt_http.client') class Client(object): def __init__(self, base_url): self.base_url = base_url self.session = requests.Session() # token is incremented before each operation self.token = -1 def login(self, username, password): login_data = { 'myusername': username, 'mypassword': password, 'button': 'Login', 'textfield': 'UX_EQUIPNAME', } response = self._req('login.htm', data=login_data) response.raise_for_status() return response def _op(self, op, incr_token=True): if incr_token is True: self.token += 1 return op.execute() def _req(self, url, **options): url = urljoin(self.base_url, url) LOGGER.debug('Request to: %s with options: %s', url, options) response = self.session.post(url, **options) LOGGER.debug( 'Response status: %s content: %s', response.status_code, response.content) return response Change token atrribute to property
import logging import requests import xmltodict from urllib.parse import urljoin LOGGER = logging.getLogger('cisco_olt_http.client') class Client(object): def __init__(self, base_url): self.base_url = base_url self.session = requests.Session() # token is incremented before each operation self._token = -1 @property def token(self): self._token += 1 return self._token def login(self, username, password): login_data = { 'myusername': username, 'mypassword': password, 'button': 'Login', 'textfield': 'UX_EQUIPNAME', } response = self._req('login.htm', data=login_data) response.raise_for_status() return response def _req(self, url, **options): url = urljoin(self.base_url, url) LOGGER.debug('Request to: %s with options: %s', url, options) response = self.session.post(url, **options) LOGGER.debug( 'Response status: %s content: %s', response.status_code, response.content) return response
<commit_before>import logging import requests import xmltodict from urllib.parse import urljoin LOGGER = logging.getLogger('cisco_olt_http.client') class Client(object): def __init__(self, base_url): self.base_url = base_url self.session = requests.Session() # token is incremented before each operation self.token = -1 def login(self, username, password): login_data = { 'myusername': username, 'mypassword': password, 'button': 'Login', 'textfield': 'UX_EQUIPNAME', } response = self._req('login.htm', data=login_data) response.raise_for_status() return response def _op(self, op, incr_token=True): if incr_token is True: self.token += 1 return op.execute() def _req(self, url, **options): url = urljoin(self.base_url, url) LOGGER.debug('Request to: %s with options: %s', url, options) response = self.session.post(url, **options) LOGGER.debug( 'Response status: %s content: %s', response.status_code, response.content) return response <commit_msg>Change token atrribute to property<commit_after>
import logging import requests import xmltodict from urllib.parse import urljoin LOGGER = logging.getLogger('cisco_olt_http.client') class Client(object): def __init__(self, base_url): self.base_url = base_url self.session = requests.Session() # token is incremented before each operation self._token = -1 @property def token(self): self._token += 1 return self._token def login(self, username, password): login_data = { 'myusername': username, 'mypassword': password, 'button': 'Login', 'textfield': 'UX_EQUIPNAME', } response = self._req('login.htm', data=login_data) response.raise_for_status() return response def _req(self, url, **options): url = urljoin(self.base_url, url) LOGGER.debug('Request to: %s with options: %s', url, options) response = self.session.post(url, **options) LOGGER.debug( 'Response status: %s content: %s', response.status_code, response.content) return response
import logging import requests import xmltodict from urllib.parse import urljoin LOGGER = logging.getLogger('cisco_olt_http.client') class Client(object): def __init__(self, base_url): self.base_url = base_url self.session = requests.Session() # token is incremented before each operation self.token = -1 def login(self, username, password): login_data = { 'myusername': username, 'mypassword': password, 'button': 'Login', 'textfield': 'UX_EQUIPNAME', } response = self._req('login.htm', data=login_data) response.raise_for_status() return response def _op(self, op, incr_token=True): if incr_token is True: self.token += 1 return op.execute() def _req(self, url, **options): url = urljoin(self.base_url, url) LOGGER.debug('Request to: %s with options: %s', url, options) response = self.session.post(url, **options) LOGGER.debug( 'Response status: %s content: %s', response.status_code, response.content) return response Change token atrribute to propertyimport logging import requests import xmltodict from urllib.parse import urljoin LOGGER = logging.getLogger('cisco_olt_http.client') class Client(object): def __init__(self, base_url): self.base_url = base_url self.session = requests.Session() # token is incremented before each operation self._token = -1 @property def token(self): self._token += 1 return self._token def login(self, username, password): login_data = { 'myusername': username, 'mypassword': password, 'button': 'Login', 'textfield': 'UX_EQUIPNAME', } response = self._req('login.htm', data=login_data) response.raise_for_status() return response def _req(self, url, **options): url = urljoin(self.base_url, url) LOGGER.debug('Request to: %s with options: %s', url, options) response = self.session.post(url, **options) LOGGER.debug( 'Response status: %s content: %s', response.status_code, response.content) return response
<commit_before>import logging import requests import xmltodict from urllib.parse import urljoin LOGGER = logging.getLogger('cisco_olt_http.client') class Client(object): def __init__(self, base_url): self.base_url = base_url self.session = requests.Session() # token is incremented before each operation self.token = -1 def login(self, username, password): login_data = { 'myusername': username, 'mypassword': password, 'button': 'Login', 'textfield': 'UX_EQUIPNAME', } response = self._req('login.htm', data=login_data) response.raise_for_status() return response def _op(self, op, incr_token=True): if incr_token is True: self.token += 1 return op.execute() def _req(self, url, **options): url = urljoin(self.base_url, url) LOGGER.debug('Request to: %s with options: %s', url, options) response = self.session.post(url, **options) LOGGER.debug( 'Response status: %s content: %s', response.status_code, response.content) return response <commit_msg>Change token atrribute to property<commit_after>import logging import requests import xmltodict from urllib.parse import urljoin LOGGER = logging.getLogger('cisco_olt_http.client') class Client(object): def __init__(self, base_url): self.base_url = base_url self.session = requests.Session() # token is incremented before each operation self._token = -1 @property def token(self): self._token += 1 return self._token def login(self, username, password): login_data = { 'myusername': username, 'mypassword': password, 'button': 'Login', 'textfield': 'UX_EQUIPNAME', } response = self._req('login.htm', data=login_data) response.raise_for_status() return response def _req(self, url, **options): url = urljoin(self.base_url, url) LOGGER.debug('Request to: %s with options: %s', url, options) response = self.session.post(url, **options) LOGGER.debug( 'Response status: %s content: %s', response.status_code, response.content) return response
24e3c89f0093bafd9618dd5c3eb5ad147be0f4c3
project/apps/api/filters.py
project/apps/api/filters.py
import rest_framework_filters as filters from .models import ( Chart, Convention, Group, Person, Venue, ) class ChartFilter(filters.FilterSet): class Meta: model = Chart fields = { 'name': filters.ALL_LOOKUPS, } class ConventionFilter(filters.FilterSet): class Meta: model = Convention fields = { 'status': filters.ALL_LOOKUPS, 'year': filters.ALL_LOOKUPS, } class GroupFilter(filters.FilterSet): class Meta: model = Group fields = { 'name': filters.ALL_LOOKUPS, } class PersonFilter(filters.FilterSet): class Meta: model = Person fields = { 'name': filters.ALL_LOOKUPS, } class VenueFilter(filters.FilterSet): class Meta: model = Venue fields = { 'name': filters.ALL_LOOKUPS, }
import rest_framework_filters as filters from .models import ( Chart, Convention, Group, Person, Venue, ) class ChartFilter(filters.FilterSet): class Meta: model = Chart fields = { 'name': filters.ALL_LOOKUPS, } class ConventionFilter(filters.FilterSet): class Meta: model = Convention fields = { 'status': filters.ALL_LOOKUPS, 'year': filters.ALL_LOOKUPS, 'season': filters.ALL_LOOKUPS, } class GroupFilter(filters.FilterSet): class Meta: model = Group fields = { 'name': filters.ALL_LOOKUPS, } class PersonFilter(filters.FilterSet): class Meta: model = Person fields = { 'name': filters.ALL_LOOKUPS, } class VenueFilter(filters.FilterSet): class Meta: model = Venue fields = { 'name': filters.ALL_LOOKUPS, }
Add season to Convention filter
Add season to Convention filter
Python
bsd-2-clause
barberscore/barberscore-api,barberscore/barberscore-api,dbinetti/barberscore,barberscore/barberscore-api,dbinetti/barberscore,dbinetti/barberscore-django,dbinetti/barberscore-django,barberscore/barberscore-api
import rest_framework_filters as filters from .models import ( Chart, Convention, Group, Person, Venue, ) class ChartFilter(filters.FilterSet): class Meta: model = Chart fields = { 'name': filters.ALL_LOOKUPS, } class ConventionFilter(filters.FilterSet): class Meta: model = Convention fields = { 'status': filters.ALL_LOOKUPS, 'year': filters.ALL_LOOKUPS, } class GroupFilter(filters.FilterSet): class Meta: model = Group fields = { 'name': filters.ALL_LOOKUPS, } class PersonFilter(filters.FilterSet): class Meta: model = Person fields = { 'name': filters.ALL_LOOKUPS, } class VenueFilter(filters.FilterSet): class Meta: model = Venue fields = { 'name': filters.ALL_LOOKUPS, } Add season to Convention filter
import rest_framework_filters as filters from .models import ( Chart, Convention, Group, Person, Venue, ) class ChartFilter(filters.FilterSet): class Meta: model = Chart fields = { 'name': filters.ALL_LOOKUPS, } class ConventionFilter(filters.FilterSet): class Meta: model = Convention fields = { 'status': filters.ALL_LOOKUPS, 'year': filters.ALL_LOOKUPS, 'season': filters.ALL_LOOKUPS, } class GroupFilter(filters.FilterSet): class Meta: model = Group fields = { 'name': filters.ALL_LOOKUPS, } class PersonFilter(filters.FilterSet): class Meta: model = Person fields = { 'name': filters.ALL_LOOKUPS, } class VenueFilter(filters.FilterSet): class Meta: model = Venue fields = { 'name': filters.ALL_LOOKUPS, }
<commit_before>import rest_framework_filters as filters from .models import ( Chart, Convention, Group, Person, Venue, ) class ChartFilter(filters.FilterSet): class Meta: model = Chart fields = { 'name': filters.ALL_LOOKUPS, } class ConventionFilter(filters.FilterSet): class Meta: model = Convention fields = { 'status': filters.ALL_LOOKUPS, 'year': filters.ALL_LOOKUPS, } class GroupFilter(filters.FilterSet): class Meta: model = Group fields = { 'name': filters.ALL_LOOKUPS, } class PersonFilter(filters.FilterSet): class Meta: model = Person fields = { 'name': filters.ALL_LOOKUPS, } class VenueFilter(filters.FilterSet): class Meta: model = Venue fields = { 'name': filters.ALL_LOOKUPS, } <commit_msg>Add season to Convention filter<commit_after>
import rest_framework_filters as filters from .models import ( Chart, Convention, Group, Person, Venue, ) class ChartFilter(filters.FilterSet): class Meta: model = Chart fields = { 'name': filters.ALL_LOOKUPS, } class ConventionFilter(filters.FilterSet): class Meta: model = Convention fields = { 'status': filters.ALL_LOOKUPS, 'year': filters.ALL_LOOKUPS, 'season': filters.ALL_LOOKUPS, } class GroupFilter(filters.FilterSet): class Meta: model = Group fields = { 'name': filters.ALL_LOOKUPS, } class PersonFilter(filters.FilterSet): class Meta: model = Person fields = { 'name': filters.ALL_LOOKUPS, } class VenueFilter(filters.FilterSet): class Meta: model = Venue fields = { 'name': filters.ALL_LOOKUPS, }
import rest_framework_filters as filters from .models import ( Chart, Convention, Group, Person, Venue, ) class ChartFilter(filters.FilterSet): class Meta: model = Chart fields = { 'name': filters.ALL_LOOKUPS, } class ConventionFilter(filters.FilterSet): class Meta: model = Convention fields = { 'status': filters.ALL_LOOKUPS, 'year': filters.ALL_LOOKUPS, } class GroupFilter(filters.FilterSet): class Meta: model = Group fields = { 'name': filters.ALL_LOOKUPS, } class PersonFilter(filters.FilterSet): class Meta: model = Person fields = { 'name': filters.ALL_LOOKUPS, } class VenueFilter(filters.FilterSet): class Meta: model = Venue fields = { 'name': filters.ALL_LOOKUPS, } Add season to Convention filterimport rest_framework_filters as filters from .models import ( Chart, Convention, Group, Person, Venue, ) class ChartFilter(filters.FilterSet): class Meta: model = Chart fields = { 'name': filters.ALL_LOOKUPS, } class ConventionFilter(filters.FilterSet): class Meta: model = Convention fields = { 'status': filters.ALL_LOOKUPS, 'year': filters.ALL_LOOKUPS, 'season': filters.ALL_LOOKUPS, } class GroupFilter(filters.FilterSet): class Meta: model = Group fields = { 'name': filters.ALL_LOOKUPS, } class PersonFilter(filters.FilterSet): class Meta: model = Person fields = { 'name': filters.ALL_LOOKUPS, } class VenueFilter(filters.FilterSet): class Meta: model = Venue fields = { 'name': filters.ALL_LOOKUPS, }
<commit_before>import rest_framework_filters as filters from .models import ( Chart, Convention, Group, Person, Venue, ) class ChartFilter(filters.FilterSet): class Meta: model = Chart fields = { 'name': filters.ALL_LOOKUPS, } class ConventionFilter(filters.FilterSet): class Meta: model = Convention fields = { 'status': filters.ALL_LOOKUPS, 'year': filters.ALL_LOOKUPS, } class GroupFilter(filters.FilterSet): class Meta: model = Group fields = { 'name': filters.ALL_LOOKUPS, } class PersonFilter(filters.FilterSet): class Meta: model = Person fields = { 'name': filters.ALL_LOOKUPS, } class VenueFilter(filters.FilterSet): class Meta: model = Venue fields = { 'name': filters.ALL_LOOKUPS, } <commit_msg>Add season to Convention filter<commit_after>import rest_framework_filters as filters from .models import ( Chart, Convention, Group, Person, Venue, ) class ChartFilter(filters.FilterSet): class Meta: model = Chart fields = { 'name': filters.ALL_LOOKUPS, } class ConventionFilter(filters.FilterSet): class Meta: model = Convention fields = { 'status': filters.ALL_LOOKUPS, 'year': filters.ALL_LOOKUPS, 'season': filters.ALL_LOOKUPS, } class GroupFilter(filters.FilterSet): class Meta: model = Group fields = { 'name': filters.ALL_LOOKUPS, } class PersonFilter(filters.FilterSet): class Meta: model = Person fields = { 'name': filters.ALL_LOOKUPS, } class VenueFilter(filters.FilterSet): class Meta: model = Venue fields = { 'name': filters.ALL_LOOKUPS, }
43732458a09c136cc64b0c1c46584c9ba1ed5300
exploratory_analysis/time_scan.py
exploratory_analysis/time_scan.py
import os from utils import Reader if __name__ == '__main__': working_directory = os.getcwd() files = Reader.read_directory(working_directory) for f in files: tweets = Reader.read_file(f) for tweet in tweets: print '{}, {}'.format(tweet.verb(), tweet.timestamp())
import os from utils import Reader if __name__ == '__main__': working_directory = os.getcwd() files = Reader.read_directory(working_directory) for f in files: tweets = Reader.read_file(f) eng_tweets = filter(lambda t: t.language() == 'en', tweets) for tweet in tweets: print '{}, {}, {}'.format(tweet.verb(), tweet.timestamp(), tweet.body())
Return only english tweet and print the body of the tweet for analysis via other tools
Return only english tweet and print the body of the tweet for analysis via other tools
Python
apache-2.0
chuajiesheng/twitter-sentiment-analysis
import os from utils import Reader if __name__ == '__main__': working_directory = os.getcwd() files = Reader.read_directory(working_directory) for f in files: tweets = Reader.read_file(f) for tweet in tweets: print '{}, {}'.format(tweet.verb(), tweet.timestamp()) Return only english tweet and print the body of the tweet for analysis via other tools
import os from utils import Reader if __name__ == '__main__': working_directory = os.getcwd() files = Reader.read_directory(working_directory) for f in files: tweets = Reader.read_file(f) eng_tweets = filter(lambda t: t.language() == 'en', tweets) for tweet in tweets: print '{}, {}, {}'.format(tweet.verb(), tweet.timestamp(), tweet.body())
<commit_before>import os from utils import Reader if __name__ == '__main__': working_directory = os.getcwd() files = Reader.read_directory(working_directory) for f in files: tweets = Reader.read_file(f) for tweet in tweets: print '{}, {}'.format(tweet.verb(), tweet.timestamp()) <commit_msg>Return only english tweet and print the body of the tweet for analysis via other tools<commit_after>
import os from utils import Reader if __name__ == '__main__': working_directory = os.getcwd() files = Reader.read_directory(working_directory) for f in files: tweets = Reader.read_file(f) eng_tweets = filter(lambda t: t.language() == 'en', tweets) for tweet in tweets: print '{}, {}, {}'.format(tweet.verb(), tweet.timestamp(), tweet.body())
import os from utils import Reader if __name__ == '__main__': working_directory = os.getcwd() files = Reader.read_directory(working_directory) for f in files: tweets = Reader.read_file(f) for tweet in tweets: print '{}, {}'.format(tweet.verb(), tweet.timestamp()) Return only english tweet and print the body of the tweet for analysis via other toolsimport os from utils import Reader if __name__ == '__main__': working_directory = os.getcwd() files = Reader.read_directory(working_directory) for f in files: tweets = Reader.read_file(f) eng_tweets = filter(lambda t: t.language() == 'en', tweets) for tweet in tweets: print '{}, {}, {}'.format(tweet.verb(), tweet.timestamp(), tweet.body())
<commit_before>import os from utils import Reader if __name__ == '__main__': working_directory = os.getcwd() files = Reader.read_directory(working_directory) for f in files: tweets = Reader.read_file(f) for tweet in tweets: print '{}, {}'.format(tweet.verb(), tweet.timestamp()) <commit_msg>Return only english tweet and print the body of the tweet for analysis via other tools<commit_after>import os from utils import Reader if __name__ == '__main__': working_directory = os.getcwd() files = Reader.read_directory(working_directory) for f in files: tweets = Reader.read_file(f) eng_tweets = filter(lambda t: t.language() == 'en', tweets) for tweet in tweets: print '{}, {}, {}'.format(tweet.verb(), tweet.timestamp(), tweet.body())
9808f1933d83102ee7aa1a5f176433740975af88
pytest-devpi-server/tests/integration/test_devpi_server.py
pytest-devpi-server/tests/integration/test_devpi_server.py
import json NEW_INDEX = { 'result': { 'acl_toxresult_upload': [':ANONYMOUS:'], 'acl_upload': ['testuser'], 'bases': [], 'mirror_whitelist': [], 'projects': [], 'pypi_whitelist': [], 'type': 'stage', 'volatile': True }, 'type': 'indexconfig' } def test_server(devpi_server): res = devpi_server.api('getjson', '/{}/{}'.format(devpi_server.user, devpi_server.index)) assert json.loads(res) == NEW_INDEX def test_upload(devpi_server): pkg_dir = devpi_server.workspace / 'pkg' pkg_dir.mkdir_p() setup_py = pkg_dir / 'setup.py' setup_py.write_text(""" from setuptools import setup setup(name='test-foo', version='1.2.3') """) pkg_dir.chdir() devpi_server.api('upload') res = devpi_server.api('getjson', '/{}/{}'.format(devpi_server.user, devpi_server.index)) assert json.loads(res)['result']['projects'] == ['test-foo'] def test_function_index(devpi_server, devpi_function_index): res = devpi_server.api('getjson', '/{}/test_function_index'.format(devpi_server.user)) assert json.loads(res) == NEW_INDEX
import json NEW_INDEX = { u"result": { u"acl_toxresult_upload": [u":ANONYMOUS:"], u"acl_upload": [u"testuser"], u"bases": [], u"mirror_whitelist": [], u"projects": [], u"type": u"stage", u"volatile": True, }, u"type": u"indexconfig", } def test_server(devpi_server): res = devpi_server.api('getjson', '/{}/{}'.format(devpi_server.user, devpi_server.index)) assert json.loads(res) == NEW_INDEX def test_upload(devpi_server): pkg_dir = devpi_server.workspace / 'pkg' pkg_dir.mkdir_p() setup_py = pkg_dir / 'setup.py' setup_py.write_text(""" from setuptools import setup setup(name='test-foo', version='1.2.3') """) pkg_dir.chdir() devpi_server.api('upload') res = devpi_server.api('getjson', '/{}/{}'.format(devpi_server.user, devpi_server.index)) assert json.loads(res)['result']['projects'] == ['test-foo'] def test_function_index(devpi_server, devpi_function_index): res = devpi_server.api('getjson', '/{}/test_function_index'.format(devpi_server.user)) assert json.loads(res) == NEW_INDEX
Update devpi server index lookup result to fix integration test
Update devpi server index lookup result to fix integration test
Python
mit
manahl/pytest-plugins,manahl/pytest-plugins
import json NEW_INDEX = { 'result': { 'acl_toxresult_upload': [':ANONYMOUS:'], 'acl_upload': ['testuser'], 'bases': [], 'mirror_whitelist': [], 'projects': [], 'pypi_whitelist': [], 'type': 'stage', 'volatile': True }, 'type': 'indexconfig' } def test_server(devpi_server): res = devpi_server.api('getjson', '/{}/{}'.format(devpi_server.user, devpi_server.index)) assert json.loads(res) == NEW_INDEX def test_upload(devpi_server): pkg_dir = devpi_server.workspace / 'pkg' pkg_dir.mkdir_p() setup_py = pkg_dir / 'setup.py' setup_py.write_text(""" from setuptools import setup setup(name='test-foo', version='1.2.3') """) pkg_dir.chdir() devpi_server.api('upload') res = devpi_server.api('getjson', '/{}/{}'.format(devpi_server.user, devpi_server.index)) assert json.loads(res)['result']['projects'] == ['test-foo'] def test_function_index(devpi_server, devpi_function_index): res = devpi_server.api('getjson', '/{}/test_function_index'.format(devpi_server.user)) assert json.loads(res) == NEW_INDEX Update devpi server index lookup result to fix integration test
import json NEW_INDEX = { u"result": { u"acl_toxresult_upload": [u":ANONYMOUS:"], u"acl_upload": [u"testuser"], u"bases": [], u"mirror_whitelist": [], u"projects": [], u"type": u"stage", u"volatile": True, }, u"type": u"indexconfig", } def test_server(devpi_server): res = devpi_server.api('getjson', '/{}/{}'.format(devpi_server.user, devpi_server.index)) assert json.loads(res) == NEW_INDEX def test_upload(devpi_server): pkg_dir = devpi_server.workspace / 'pkg' pkg_dir.mkdir_p() setup_py = pkg_dir / 'setup.py' setup_py.write_text(""" from setuptools import setup setup(name='test-foo', version='1.2.3') """) pkg_dir.chdir() devpi_server.api('upload') res = devpi_server.api('getjson', '/{}/{}'.format(devpi_server.user, devpi_server.index)) assert json.loads(res)['result']['projects'] == ['test-foo'] def test_function_index(devpi_server, devpi_function_index): res = devpi_server.api('getjson', '/{}/test_function_index'.format(devpi_server.user)) assert json.loads(res) == NEW_INDEX
<commit_before>import json NEW_INDEX = { 'result': { 'acl_toxresult_upload': [':ANONYMOUS:'], 'acl_upload': ['testuser'], 'bases': [], 'mirror_whitelist': [], 'projects': [], 'pypi_whitelist': [], 'type': 'stage', 'volatile': True }, 'type': 'indexconfig' } def test_server(devpi_server): res = devpi_server.api('getjson', '/{}/{}'.format(devpi_server.user, devpi_server.index)) assert json.loads(res) == NEW_INDEX def test_upload(devpi_server): pkg_dir = devpi_server.workspace / 'pkg' pkg_dir.mkdir_p() setup_py = pkg_dir / 'setup.py' setup_py.write_text(""" from setuptools import setup setup(name='test-foo', version='1.2.3') """) pkg_dir.chdir() devpi_server.api('upload') res = devpi_server.api('getjson', '/{}/{}'.format(devpi_server.user, devpi_server.index)) assert json.loads(res)['result']['projects'] == ['test-foo'] def test_function_index(devpi_server, devpi_function_index): res = devpi_server.api('getjson', '/{}/test_function_index'.format(devpi_server.user)) assert json.loads(res) == NEW_INDEX <commit_msg>Update devpi server index lookup result to fix integration test<commit_after>
import json NEW_INDEX = { u"result": { u"acl_toxresult_upload": [u":ANONYMOUS:"], u"acl_upload": [u"testuser"], u"bases": [], u"mirror_whitelist": [], u"projects": [], u"type": u"stage", u"volatile": True, }, u"type": u"indexconfig", } def test_server(devpi_server): res = devpi_server.api('getjson', '/{}/{}'.format(devpi_server.user, devpi_server.index)) assert json.loads(res) == NEW_INDEX def test_upload(devpi_server): pkg_dir = devpi_server.workspace / 'pkg' pkg_dir.mkdir_p() setup_py = pkg_dir / 'setup.py' setup_py.write_text(""" from setuptools import setup setup(name='test-foo', version='1.2.3') """) pkg_dir.chdir() devpi_server.api('upload') res = devpi_server.api('getjson', '/{}/{}'.format(devpi_server.user, devpi_server.index)) assert json.loads(res)['result']['projects'] == ['test-foo'] def test_function_index(devpi_server, devpi_function_index): res = devpi_server.api('getjson', '/{}/test_function_index'.format(devpi_server.user)) assert json.loads(res) == NEW_INDEX
import json NEW_INDEX = { 'result': { 'acl_toxresult_upload': [':ANONYMOUS:'], 'acl_upload': ['testuser'], 'bases': [], 'mirror_whitelist': [], 'projects': [], 'pypi_whitelist': [], 'type': 'stage', 'volatile': True }, 'type': 'indexconfig' } def test_server(devpi_server): res = devpi_server.api('getjson', '/{}/{}'.format(devpi_server.user, devpi_server.index)) assert json.loads(res) == NEW_INDEX def test_upload(devpi_server): pkg_dir = devpi_server.workspace / 'pkg' pkg_dir.mkdir_p() setup_py = pkg_dir / 'setup.py' setup_py.write_text(""" from setuptools import setup setup(name='test-foo', version='1.2.3') """) pkg_dir.chdir() devpi_server.api('upload') res = devpi_server.api('getjson', '/{}/{}'.format(devpi_server.user, devpi_server.index)) assert json.loads(res)['result']['projects'] == ['test-foo'] def test_function_index(devpi_server, devpi_function_index): res = devpi_server.api('getjson', '/{}/test_function_index'.format(devpi_server.user)) assert json.loads(res) == NEW_INDEX Update devpi server index lookup result to fix integration testimport json NEW_INDEX = { u"result": { u"acl_toxresult_upload": [u":ANONYMOUS:"], u"acl_upload": [u"testuser"], u"bases": [], u"mirror_whitelist": [], u"projects": [], u"type": u"stage", u"volatile": True, }, u"type": u"indexconfig", } def test_server(devpi_server): res = devpi_server.api('getjson', '/{}/{}'.format(devpi_server.user, devpi_server.index)) assert json.loads(res) == NEW_INDEX def test_upload(devpi_server): pkg_dir = devpi_server.workspace / 'pkg' pkg_dir.mkdir_p() setup_py = pkg_dir / 'setup.py' setup_py.write_text(""" from setuptools import setup setup(name='test-foo', version='1.2.3') """) pkg_dir.chdir() devpi_server.api('upload') res = devpi_server.api('getjson', '/{}/{}'.format(devpi_server.user, devpi_server.index)) assert json.loads(res)['result']['projects'] == ['test-foo'] def test_function_index(devpi_server, devpi_function_index): res = devpi_server.api('getjson', '/{}/test_function_index'.format(devpi_server.user)) assert json.loads(res) == NEW_INDEX
<commit_before>import json NEW_INDEX = { 'result': { 'acl_toxresult_upload': [':ANONYMOUS:'], 'acl_upload': ['testuser'], 'bases': [], 'mirror_whitelist': [], 'projects': [], 'pypi_whitelist': [], 'type': 'stage', 'volatile': True }, 'type': 'indexconfig' } def test_server(devpi_server): res = devpi_server.api('getjson', '/{}/{}'.format(devpi_server.user, devpi_server.index)) assert json.loads(res) == NEW_INDEX def test_upload(devpi_server): pkg_dir = devpi_server.workspace / 'pkg' pkg_dir.mkdir_p() setup_py = pkg_dir / 'setup.py' setup_py.write_text(""" from setuptools import setup setup(name='test-foo', version='1.2.3') """) pkg_dir.chdir() devpi_server.api('upload') res = devpi_server.api('getjson', '/{}/{}'.format(devpi_server.user, devpi_server.index)) assert json.loads(res)['result']['projects'] == ['test-foo'] def test_function_index(devpi_server, devpi_function_index): res = devpi_server.api('getjson', '/{}/test_function_index'.format(devpi_server.user)) assert json.loads(res) == NEW_INDEX <commit_msg>Update devpi server index lookup result to fix integration test<commit_after>import json NEW_INDEX = { u"result": { u"acl_toxresult_upload": [u":ANONYMOUS:"], u"acl_upload": [u"testuser"], u"bases": [], u"mirror_whitelist": [], u"projects": [], u"type": u"stage", u"volatile": True, }, u"type": u"indexconfig", } def test_server(devpi_server): res = devpi_server.api('getjson', '/{}/{}'.format(devpi_server.user, devpi_server.index)) assert json.loads(res) == NEW_INDEX def test_upload(devpi_server): pkg_dir = devpi_server.workspace / 'pkg' pkg_dir.mkdir_p() setup_py = pkg_dir / 'setup.py' setup_py.write_text(""" from setuptools import setup setup(name='test-foo', version='1.2.3') """) pkg_dir.chdir() devpi_server.api('upload') res = devpi_server.api('getjson', '/{}/{}'.format(devpi_server.user, devpi_server.index)) assert json.loads(res)['result']['projects'] == ['test-foo'] def test_function_index(devpi_server, devpi_function_index): res = devpi_server.api('getjson', '/{}/test_function_index'.format(devpi_server.user)) assert json.loads(res) == NEW_INDEX
e3f1531ff0583f5710d7067b3f31a2ae65f8a747
stackviz_deployer/db/database.py
stackviz_deployer/db/database.py
# Copyright 2016 Hewlett-Packard Development Company, L.P. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import declarative_base engine = create_engine('mysql+pymysql://stackviz:stackviz@localhost/stackviz', pool_recycle=3600) session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine)) Base = declarative_base() Base.query = session.query_property() def init_db(): # noinspection PyUnresolvedReferences import stackviz_deployer.db.models Base.metadata.create_all(bind=engine)
# Copyright 2016 Hewlett-Packard Development Company, L.P. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import os from sqlalchemy import create_engine from sqlalchemy.engine.url import URL from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import declarative_base # override using environment variables if available url = URL('mysql+pymysql', username=os.environ.get('MYSQL_ENV_MYSQL_USER', 'stackviz'), password=os.environ.get('MYSQL_ENV_MYSQL_PASSWORD', 'stackviz'), host=os.environ.get('MYSQL_PORT_3306_TCP_ADDR', 'localhost'), port=int(os.environ.get('MYSQL_PORT_3306_TCP_POST', '3306')), database=os.environ.get('MYSQL_ENV_MYSQL_DATABASE', 'stackviz')) engine = create_engine(url, pool_recycle=3600) session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine)) Base = declarative_base() Base.query = session.query_property() def init_db(): # noinspection PyUnresolvedReferences import stackviz_deployer.db.models Base.metadata.create_all(bind=engine)
Allow environment variable overrides for DB connection.
Allow environment variable overrides for DB connection. This allows docker-style environment variables to override the default database connection info.
Python
apache-2.0
timothyb89/stackviz-deployer,timothyb89/stackviz-deployer,timothyb89/stackviz-deployer
# Copyright 2016 Hewlett-Packard Development Company, L.P. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import declarative_base engine = create_engine('mysql+pymysql://stackviz:stackviz@localhost/stackviz', pool_recycle=3600) session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine)) Base = declarative_base() Base.query = session.query_property() def init_db(): # noinspection PyUnresolvedReferences import stackviz_deployer.db.models Base.metadata.create_all(bind=engine) Allow environment variable overrides for DB connection. This allows docker-style environment variables to override the default database connection info.
# Copyright 2016 Hewlett-Packard Development Company, L.P. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import os from sqlalchemy import create_engine from sqlalchemy.engine.url import URL from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import declarative_base # override using environment variables if available url = URL('mysql+pymysql', username=os.environ.get('MYSQL_ENV_MYSQL_USER', 'stackviz'), password=os.environ.get('MYSQL_ENV_MYSQL_PASSWORD', 'stackviz'), host=os.environ.get('MYSQL_PORT_3306_TCP_ADDR', 'localhost'), port=int(os.environ.get('MYSQL_PORT_3306_TCP_POST', '3306')), database=os.environ.get('MYSQL_ENV_MYSQL_DATABASE', 'stackviz')) engine = create_engine(url, pool_recycle=3600) session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine)) Base = declarative_base() Base.query = session.query_property() def init_db(): # noinspection PyUnresolvedReferences import stackviz_deployer.db.models Base.metadata.create_all(bind=engine)
<commit_before># Copyright 2016 Hewlett-Packard Development Company, L.P. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import declarative_base engine = create_engine('mysql+pymysql://stackviz:stackviz@localhost/stackviz', pool_recycle=3600) session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine)) Base = declarative_base() Base.query = session.query_property() def init_db(): # noinspection PyUnresolvedReferences import stackviz_deployer.db.models Base.metadata.create_all(bind=engine) <commit_msg>Allow environment variable overrides for DB connection. This allows docker-style environment variables to override the default database connection info.<commit_after>
# Copyright 2016 Hewlett-Packard Development Company, L.P. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import os from sqlalchemy import create_engine from sqlalchemy.engine.url import URL from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import declarative_base # override using environment variables if available url = URL('mysql+pymysql', username=os.environ.get('MYSQL_ENV_MYSQL_USER', 'stackviz'), password=os.environ.get('MYSQL_ENV_MYSQL_PASSWORD', 'stackviz'), host=os.environ.get('MYSQL_PORT_3306_TCP_ADDR', 'localhost'), port=int(os.environ.get('MYSQL_PORT_3306_TCP_POST', '3306')), database=os.environ.get('MYSQL_ENV_MYSQL_DATABASE', 'stackviz')) engine = create_engine(url, pool_recycle=3600) session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine)) Base = declarative_base() Base.query = session.query_property() def init_db(): # noinspection PyUnresolvedReferences import stackviz_deployer.db.models Base.metadata.create_all(bind=engine)
# Copyright 2016 Hewlett-Packard Development Company, L.P. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import declarative_base engine = create_engine('mysql+pymysql://stackviz:stackviz@localhost/stackviz', pool_recycle=3600) session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine)) Base = declarative_base() Base.query = session.query_property() def init_db(): # noinspection PyUnresolvedReferences import stackviz_deployer.db.models Base.metadata.create_all(bind=engine) Allow environment variable overrides for DB connection. This allows docker-style environment variables to override the default database connection info.# Copyright 2016 Hewlett-Packard Development Company, L.P. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import os from sqlalchemy import create_engine from sqlalchemy.engine.url import URL from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import declarative_base # override using environment variables if available url = URL('mysql+pymysql', username=os.environ.get('MYSQL_ENV_MYSQL_USER', 'stackviz'), password=os.environ.get('MYSQL_ENV_MYSQL_PASSWORD', 'stackviz'), host=os.environ.get('MYSQL_PORT_3306_TCP_ADDR', 'localhost'), port=int(os.environ.get('MYSQL_PORT_3306_TCP_POST', '3306')), database=os.environ.get('MYSQL_ENV_MYSQL_DATABASE', 'stackviz')) engine = create_engine(url, pool_recycle=3600) session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine)) Base = declarative_base() Base.query = session.query_property() def init_db(): # noinspection PyUnresolvedReferences import stackviz_deployer.db.models Base.metadata.create_all(bind=engine)
<commit_before># Copyright 2016 Hewlett-Packard Development Company, L.P. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import declarative_base engine = create_engine('mysql+pymysql://stackviz:stackviz@localhost/stackviz', pool_recycle=3600) session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine)) Base = declarative_base() Base.query = session.query_property() def init_db(): # noinspection PyUnresolvedReferences import stackviz_deployer.db.models Base.metadata.create_all(bind=engine) <commit_msg>Allow environment variable overrides for DB connection. This allows docker-style environment variables to override the default database connection info.<commit_after># Copyright 2016 Hewlett-Packard Development Company, L.P. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import os from sqlalchemy import create_engine from sqlalchemy.engine.url import URL from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import declarative_base # override using environment variables if available url = URL('mysql+pymysql', username=os.environ.get('MYSQL_ENV_MYSQL_USER', 'stackviz'), password=os.environ.get('MYSQL_ENV_MYSQL_PASSWORD', 'stackviz'), host=os.environ.get('MYSQL_PORT_3306_TCP_ADDR', 'localhost'), port=int(os.environ.get('MYSQL_PORT_3306_TCP_POST', '3306')), database=os.environ.get('MYSQL_ENV_MYSQL_DATABASE', 'stackviz')) engine = create_engine(url, pool_recycle=3600) session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine)) Base = declarative_base() Base.query = session.query_property() def init_db(): # noinspection PyUnresolvedReferences import stackviz_deployer.db.models Base.metadata.create_all(bind=engine)
fa1d67d3fc10f1c5a2c253b3c3609db4be9c599c
src/foremast/pipeline/create_pipeline_manual.py
src/foremast/pipeline/create_pipeline_manual.py
# Foremast - Pipeline Tooling # # Copyright 2016 Gogo, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Create manual Pipeline for Spinnaker.""" from ..utils.lookups import FileLookup from .create_pipeline import SpinnakerPipeline class SpinnakerPipelineManual(SpinnakerPipeline): """Manual JSON configured Spinnaker Pipelines.""" def create_pipeline(self): """Use JSON files to create Pipelines.""" self.log.info('Uploading manual Pipelines: %s') lookup = FileLookup(git_short=self.generated.gitlab()['main'], runway_dir=self.runway_dir) for json_file in self.settings['pipeline']['pipeline_files']: json_text = lookup.get(filename=json_file) self.post_pipeline(json_text) return True
# Foremast - Pipeline Tooling # # Copyright 2016 Gogo, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Create manual Pipeline for Spinnaker.""" from ..utils.lookups import FileLookup from .create_pipeline import SpinnakerPipeline class SpinnakerPipelineManual(SpinnakerPipeline): """Manual JSON configured Spinnaker Pipelines.""" def create_pipeline(self): """Use JSON files to create Pipelines.""" self.log.info('Uploading manual Pipelines: %s') lookup = FileLookup(git_short=self.generated.gitlab()['main'], runway_dir=self.runway_dir) for json_file in self.settings['pipeline']['pipeline_files']: json_dict = lookup.json(filename=json_file) json_dict['name'] = json_file self.post_pipeline(json_dict) return True
Use filename for Pipeline name
fix: Use filename for Pipeline name See also: #72
Python
apache-2.0
gogoair/foremast,gogoair/foremast
# Foremast - Pipeline Tooling # # Copyright 2016 Gogo, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Create manual Pipeline for Spinnaker.""" from ..utils.lookups import FileLookup from .create_pipeline import SpinnakerPipeline class SpinnakerPipelineManual(SpinnakerPipeline): """Manual JSON configured Spinnaker Pipelines.""" def create_pipeline(self): """Use JSON files to create Pipelines.""" self.log.info('Uploading manual Pipelines: %s') lookup = FileLookup(git_short=self.generated.gitlab()['main'], runway_dir=self.runway_dir) for json_file in self.settings['pipeline']['pipeline_files']: json_text = lookup.get(filename=json_file) self.post_pipeline(json_text) return True fix: Use filename for Pipeline name See also: #72
# Foremast - Pipeline Tooling # # Copyright 2016 Gogo, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Create manual Pipeline for Spinnaker.""" from ..utils.lookups import FileLookup from .create_pipeline import SpinnakerPipeline class SpinnakerPipelineManual(SpinnakerPipeline): """Manual JSON configured Spinnaker Pipelines.""" def create_pipeline(self): """Use JSON files to create Pipelines.""" self.log.info('Uploading manual Pipelines: %s') lookup = FileLookup(git_short=self.generated.gitlab()['main'], runway_dir=self.runway_dir) for json_file in self.settings['pipeline']['pipeline_files']: json_dict = lookup.json(filename=json_file) json_dict['name'] = json_file self.post_pipeline(json_dict) return True
<commit_before># Foremast - Pipeline Tooling # # Copyright 2016 Gogo, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Create manual Pipeline for Spinnaker.""" from ..utils.lookups import FileLookup from .create_pipeline import SpinnakerPipeline class SpinnakerPipelineManual(SpinnakerPipeline): """Manual JSON configured Spinnaker Pipelines.""" def create_pipeline(self): """Use JSON files to create Pipelines.""" self.log.info('Uploading manual Pipelines: %s') lookup = FileLookup(git_short=self.generated.gitlab()['main'], runway_dir=self.runway_dir) for json_file in self.settings['pipeline']['pipeline_files']: json_text = lookup.get(filename=json_file) self.post_pipeline(json_text) return True <commit_msg>fix: Use filename for Pipeline name See also: #72<commit_after>
# Foremast - Pipeline Tooling # # Copyright 2016 Gogo, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Create manual Pipeline for Spinnaker.""" from ..utils.lookups import FileLookup from .create_pipeline import SpinnakerPipeline class SpinnakerPipelineManual(SpinnakerPipeline): """Manual JSON configured Spinnaker Pipelines.""" def create_pipeline(self): """Use JSON files to create Pipelines.""" self.log.info('Uploading manual Pipelines: %s') lookup = FileLookup(git_short=self.generated.gitlab()['main'], runway_dir=self.runway_dir) for json_file in self.settings['pipeline']['pipeline_files']: json_dict = lookup.json(filename=json_file) json_dict['name'] = json_file self.post_pipeline(json_dict) return True
# Foremast - Pipeline Tooling # # Copyright 2016 Gogo, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Create manual Pipeline for Spinnaker.""" from ..utils.lookups import FileLookup from .create_pipeline import SpinnakerPipeline class SpinnakerPipelineManual(SpinnakerPipeline): """Manual JSON configured Spinnaker Pipelines.""" def create_pipeline(self): """Use JSON files to create Pipelines.""" self.log.info('Uploading manual Pipelines: %s') lookup = FileLookup(git_short=self.generated.gitlab()['main'], runway_dir=self.runway_dir) for json_file in self.settings['pipeline']['pipeline_files']: json_text = lookup.get(filename=json_file) self.post_pipeline(json_text) return True fix: Use filename for Pipeline name See also: #72# Foremast - Pipeline Tooling # # Copyright 2016 Gogo, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Create manual Pipeline for Spinnaker.""" from ..utils.lookups import FileLookup from .create_pipeline import SpinnakerPipeline class SpinnakerPipelineManual(SpinnakerPipeline): """Manual JSON configured Spinnaker Pipelines.""" def create_pipeline(self): """Use JSON files to create Pipelines.""" self.log.info('Uploading manual Pipelines: %s') lookup = FileLookup(git_short=self.generated.gitlab()['main'], runway_dir=self.runway_dir) for json_file in self.settings['pipeline']['pipeline_files']: json_dict = lookup.json(filename=json_file) json_dict['name'] = json_file self.post_pipeline(json_dict) return True
<commit_before># Foremast - Pipeline Tooling # # Copyright 2016 Gogo, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Create manual Pipeline for Spinnaker.""" from ..utils.lookups import FileLookup from .create_pipeline import SpinnakerPipeline class SpinnakerPipelineManual(SpinnakerPipeline): """Manual JSON configured Spinnaker Pipelines.""" def create_pipeline(self): """Use JSON files to create Pipelines.""" self.log.info('Uploading manual Pipelines: %s') lookup = FileLookup(git_short=self.generated.gitlab()['main'], runway_dir=self.runway_dir) for json_file in self.settings['pipeline']['pipeline_files']: json_text = lookup.get(filename=json_file) self.post_pipeline(json_text) return True <commit_msg>fix: Use filename for Pipeline name See also: #72<commit_after># Foremast - Pipeline Tooling # # Copyright 2016 Gogo, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Create manual Pipeline for Spinnaker.""" from ..utils.lookups import FileLookup from .create_pipeline import SpinnakerPipeline class SpinnakerPipelineManual(SpinnakerPipeline): """Manual JSON configured Spinnaker Pipelines.""" def create_pipeline(self): """Use JSON files to create Pipelines.""" self.log.info('Uploading manual Pipelines: %s') lookup = FileLookup(git_short=self.generated.gitlab()['main'], runway_dir=self.runway_dir) for json_file in self.settings['pipeline']['pipeline_files']: json_dict = lookup.json(filename=json_file) json_dict['name'] = json_file self.post_pipeline(json_dict) return True
8c982822009cb414411bc4488591e35c8d4a8bcb
migrations/0007_make_ds_name_unique.py
migrations/0007_make_ds_name_unique.py
from redash.models import db if __name__ == '__main__': db.connect_db() with db.database.transaction(): # Make sure all data sources names are unique. db.database.execute_sql("""UPDATE data_sources SET name = name || ' ' || id;""") # Add unique constraint on data_sources.name. db.database.execute_sql("ALTER TABLE data_sources ADD CONSTRAINT unique_name UNIQUE (name);") db.close_db(None)
from redash.models import db if __name__ == '__main__': db.connect_db() with db.database.transaction(): # Make sure all data sources names are unique. db.database.execute_sql(""" UPDATE data_sources SET name = new_names.name FROM ( SELECT id, name || ' ' || id as name FROM (SELECT id, name, rank() OVER (PARTITION BY name ORDER BY created_at ASC) FROM data_sources) ds WHERE rank > 1 ) AS new_names WHERE data_sources.id = new_names.id; """) # Add unique constraint on data_sources.name. db.database.execute_sql("ALTER TABLE data_sources ADD CONSTRAINT unique_name UNIQUE (name);") db.close_db(None)
Rename only data sources with duplicates
Rename only data sources with duplicates
Python
bsd-2-clause
stefanseifert/redash,akariv/redash,M32Media/redash,EverlyWell/redash,imsally/redash,ninneko/redash,crowdworks/redash,alexanderlz/redash,akariv/redash,easytaxibr/redash,pubnative/redash,stefanseifert/redash,denisov-vlad/redash,alexanderlz/redash,pubnative/redash,jmvasquez/redashtest,easytaxibr/redash,EverlyWell/redash,amino-data/redash,rockwotj/redash,chriszs/redash,moritz9/redash,rockwotj/redash,hudl/redash,getredash/redash,moritz9/redash,hudl/redash,crowdworks/redash,chriszs/redash,hudl/redash,stefanseifert/redash,M32Media/redash,ninneko/redash,jmvasquez/redashtest,vishesh92/redash,guaguadev/redash,guaguadev/redash,vishesh92/redash,denisov-vlad/redash,rockwotj/redash,useabode/redash,guaguadev/redash,stefanseifert/redash,akariv/redash,getredash/redash,chriszs/redash,ninneko/redash,pubnative/redash,44px/redash,getredash/redash,amino-data/redash,easytaxibr/redash,ninneko/redash,rockwotj/redash,easytaxibr/redash,guaguadev/redash,EverlyWell/redash,vishesh92/redash,guaguadev/redash,pubnative/redash,jmvasquez/redashtest,useabode/redash,M32Media/redash,44px/redash,44px/redash,EverlyWell/redash,denisov-vlad/redash,imsally/redash,imsally/redash,hudl/redash,moritz9/redash,ninneko/redash,imsally/redash,easytaxibr/redash,44px/redash,getredash/redash,amino-data/redash,denisov-vlad/redash,chriszs/redash,pubnative/redash,jmvasquez/redashtest,crowdworks/redash,akariv/redash,amino-data/redash,crowdworks/redash,alexanderlz/redash,jmvasquez/redashtest,vishesh92/redash,alexanderlz/redash,denisov-vlad/redash,stefanseifert/redash,getredash/redash,akariv/redash,useabode/redash,M32Media/redash,useabode/redash,moritz9/redash
from redash.models import db if __name__ == '__main__': db.connect_db() with db.database.transaction(): # Make sure all data sources names are unique. db.database.execute_sql("""UPDATE data_sources SET name = name || ' ' || id;""") # Add unique constraint on data_sources.name. db.database.execute_sql("ALTER TABLE data_sources ADD CONSTRAINT unique_name UNIQUE (name);") db.close_db(None) Rename only data sources with duplicates
from redash.models import db if __name__ == '__main__': db.connect_db() with db.database.transaction(): # Make sure all data sources names are unique. db.database.execute_sql(""" UPDATE data_sources SET name = new_names.name FROM ( SELECT id, name || ' ' || id as name FROM (SELECT id, name, rank() OVER (PARTITION BY name ORDER BY created_at ASC) FROM data_sources) ds WHERE rank > 1 ) AS new_names WHERE data_sources.id = new_names.id; """) # Add unique constraint on data_sources.name. db.database.execute_sql("ALTER TABLE data_sources ADD CONSTRAINT unique_name UNIQUE (name);") db.close_db(None)
<commit_before>from redash.models import db if __name__ == '__main__': db.connect_db() with db.database.transaction(): # Make sure all data sources names are unique. db.database.execute_sql("""UPDATE data_sources SET name = name || ' ' || id;""") # Add unique constraint on data_sources.name. db.database.execute_sql("ALTER TABLE data_sources ADD CONSTRAINT unique_name UNIQUE (name);") db.close_db(None) <commit_msg>Rename only data sources with duplicates<commit_after>
from redash.models import db if __name__ == '__main__': db.connect_db() with db.database.transaction(): # Make sure all data sources names are unique. db.database.execute_sql(""" UPDATE data_sources SET name = new_names.name FROM ( SELECT id, name || ' ' || id as name FROM (SELECT id, name, rank() OVER (PARTITION BY name ORDER BY created_at ASC) FROM data_sources) ds WHERE rank > 1 ) AS new_names WHERE data_sources.id = new_names.id; """) # Add unique constraint on data_sources.name. db.database.execute_sql("ALTER TABLE data_sources ADD CONSTRAINT unique_name UNIQUE (name);") db.close_db(None)
from redash.models import db if __name__ == '__main__': db.connect_db() with db.database.transaction(): # Make sure all data sources names are unique. db.database.execute_sql("""UPDATE data_sources SET name = name || ' ' || id;""") # Add unique constraint on data_sources.name. db.database.execute_sql("ALTER TABLE data_sources ADD CONSTRAINT unique_name UNIQUE (name);") db.close_db(None) Rename only data sources with duplicatesfrom redash.models import db if __name__ == '__main__': db.connect_db() with db.database.transaction(): # Make sure all data sources names are unique. db.database.execute_sql(""" UPDATE data_sources SET name = new_names.name FROM ( SELECT id, name || ' ' || id as name FROM (SELECT id, name, rank() OVER (PARTITION BY name ORDER BY created_at ASC) FROM data_sources) ds WHERE rank > 1 ) AS new_names WHERE data_sources.id = new_names.id; """) # Add unique constraint on data_sources.name. db.database.execute_sql("ALTER TABLE data_sources ADD CONSTRAINT unique_name UNIQUE (name);") db.close_db(None)
<commit_before>from redash.models import db if __name__ == '__main__': db.connect_db() with db.database.transaction(): # Make sure all data sources names are unique. db.database.execute_sql("""UPDATE data_sources SET name = name || ' ' || id;""") # Add unique constraint on data_sources.name. db.database.execute_sql("ALTER TABLE data_sources ADD CONSTRAINT unique_name UNIQUE (name);") db.close_db(None) <commit_msg>Rename only data sources with duplicates<commit_after>from redash.models import db if __name__ == '__main__': db.connect_db() with db.database.transaction(): # Make sure all data sources names are unique. db.database.execute_sql(""" UPDATE data_sources SET name = new_names.name FROM ( SELECT id, name || ' ' || id as name FROM (SELECT id, name, rank() OVER (PARTITION BY name ORDER BY created_at ASC) FROM data_sources) ds WHERE rank > 1 ) AS new_names WHERE data_sources.id = new_names.id; """) # Add unique constraint on data_sources.name. db.database.execute_sql("ALTER TABLE data_sources ADD CONSTRAINT unique_name UNIQUE (name);") db.close_db(None)
db0be000a99e0dac7c9d37817cfd5000b7121ef3
stream/rest/views.py
stream/rest/views.py
# Author: Braedy Kuzma from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.renderers import JSONRenderer import uuid from dash.models import Post from .serializers import PostSerializer # Initially taken from # http://www.django-rest-framework.org/tutorial/1-serialization/ class JSONResponse(HttpResponse): """ An HttpResponse that renders its content into JSON. """ def __init__(self, data, **kwargs): content = JSONRenderer().render(data) kwargs['content_type'] = 'application/json' super(JSONResponse, self).__init__(content, **kwargs) @csrf_exempt def post(request, pid=None): """ REST view of Post. pid = Post id (uuid4) """ try: uuid.UUID(pid) except ValueError: return HttpResponse(status=500) # Bad uuid = malformed client request try: post = Post.objects.get(id=pid) except Post.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = PostSerializer(post) return JSONResponse(serializer.data) elif request.method == 'DELETE': post.delete() return HttpResponse(status=204)
# Author: Braedy Kuzma from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.renderers import JSONRenderer import uuid from dash.models import Post from .serializers import PostSerializer # Initially taken from # http://www.django-rest-framework.org/tutorial/1-serialization/ class JSONResponse(HttpResponse): """ An HttpResponse that renders its content into JSON. """ def __init__(self, data, **kwargs): content = JSONRenderer().render(data) kwargs['content_type'] = 'application/json' super(JSONResponse, self).__init__(content, **kwargs) @csrf_exempt def post(request, pid=None): """ REST view of Post. pid = Post id (uuid4) """ try: uuid.UUID(pid) except ValueError: return HttpResponse(status=500) # Bad uuid = malformed client request try: post = Post.objects.get(id=pid) except Post.DoesNotExist: return HttpResponse(status=404) except Post.MultipleObjectsReturned: return HttpResponse(status=500) # Some how the UUID matched multiple # posts if request.method == 'GET': serializer = PostSerializer(post) return JSONResponse(serializer.data) elif request.method == 'DELETE': post.delete() return HttpResponse(status=204)
Add multiple objects returned error.
Add multiple objects returned error.
Python
apache-2.0
CMPUT404W17T06/CMPUT404-project,CMPUT404W17T06/CMPUT404-project,CMPUT404W17T06/CMPUT404-project
# Author: Braedy Kuzma from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.renderers import JSONRenderer import uuid from dash.models import Post from .serializers import PostSerializer # Initially taken from # http://www.django-rest-framework.org/tutorial/1-serialization/ class JSONResponse(HttpResponse): """ An HttpResponse that renders its content into JSON. """ def __init__(self, data, **kwargs): content = JSONRenderer().render(data) kwargs['content_type'] = 'application/json' super(JSONResponse, self).__init__(content, **kwargs) @csrf_exempt def post(request, pid=None): """ REST view of Post. pid = Post id (uuid4) """ try: uuid.UUID(pid) except ValueError: return HttpResponse(status=500) # Bad uuid = malformed client request try: post = Post.objects.get(id=pid) except Post.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = PostSerializer(post) return JSONResponse(serializer.data) elif request.method == 'DELETE': post.delete() return HttpResponse(status=204) Add multiple objects returned error.
# Author: Braedy Kuzma from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.renderers import JSONRenderer import uuid from dash.models import Post from .serializers import PostSerializer # Initially taken from # http://www.django-rest-framework.org/tutorial/1-serialization/ class JSONResponse(HttpResponse): """ An HttpResponse that renders its content into JSON. """ def __init__(self, data, **kwargs): content = JSONRenderer().render(data) kwargs['content_type'] = 'application/json' super(JSONResponse, self).__init__(content, **kwargs) @csrf_exempt def post(request, pid=None): """ REST view of Post. pid = Post id (uuid4) """ try: uuid.UUID(pid) except ValueError: return HttpResponse(status=500) # Bad uuid = malformed client request try: post = Post.objects.get(id=pid) except Post.DoesNotExist: return HttpResponse(status=404) except Post.MultipleObjectsReturned: return HttpResponse(status=500) # Some how the UUID matched multiple # posts if request.method == 'GET': serializer = PostSerializer(post) return JSONResponse(serializer.data) elif request.method == 'DELETE': post.delete() return HttpResponse(status=204)
<commit_before># Author: Braedy Kuzma from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.renderers import JSONRenderer import uuid from dash.models import Post from .serializers import PostSerializer # Initially taken from # http://www.django-rest-framework.org/tutorial/1-serialization/ class JSONResponse(HttpResponse): """ An HttpResponse that renders its content into JSON. """ def __init__(self, data, **kwargs): content = JSONRenderer().render(data) kwargs['content_type'] = 'application/json' super(JSONResponse, self).__init__(content, **kwargs) @csrf_exempt def post(request, pid=None): """ REST view of Post. pid = Post id (uuid4) """ try: uuid.UUID(pid) except ValueError: return HttpResponse(status=500) # Bad uuid = malformed client request try: post = Post.objects.get(id=pid) except Post.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = PostSerializer(post) return JSONResponse(serializer.data) elif request.method == 'DELETE': post.delete() return HttpResponse(status=204) <commit_msg>Add multiple objects returned error.<commit_after>
# Author: Braedy Kuzma from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.renderers import JSONRenderer import uuid from dash.models import Post from .serializers import PostSerializer # Initially taken from # http://www.django-rest-framework.org/tutorial/1-serialization/ class JSONResponse(HttpResponse): """ An HttpResponse that renders its content into JSON. """ def __init__(self, data, **kwargs): content = JSONRenderer().render(data) kwargs['content_type'] = 'application/json' super(JSONResponse, self).__init__(content, **kwargs) @csrf_exempt def post(request, pid=None): """ REST view of Post. pid = Post id (uuid4) """ try: uuid.UUID(pid) except ValueError: return HttpResponse(status=500) # Bad uuid = malformed client request try: post = Post.objects.get(id=pid) except Post.DoesNotExist: return HttpResponse(status=404) except Post.MultipleObjectsReturned: return HttpResponse(status=500) # Some how the UUID matched multiple # posts if request.method == 'GET': serializer = PostSerializer(post) return JSONResponse(serializer.data) elif request.method == 'DELETE': post.delete() return HttpResponse(status=204)
# Author: Braedy Kuzma from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.renderers import JSONRenderer import uuid from dash.models import Post from .serializers import PostSerializer # Initially taken from # http://www.django-rest-framework.org/tutorial/1-serialization/ class JSONResponse(HttpResponse): """ An HttpResponse that renders its content into JSON. """ def __init__(self, data, **kwargs): content = JSONRenderer().render(data) kwargs['content_type'] = 'application/json' super(JSONResponse, self).__init__(content, **kwargs) @csrf_exempt def post(request, pid=None): """ REST view of Post. pid = Post id (uuid4) """ try: uuid.UUID(pid) except ValueError: return HttpResponse(status=500) # Bad uuid = malformed client request try: post = Post.objects.get(id=pid) except Post.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = PostSerializer(post) return JSONResponse(serializer.data) elif request.method == 'DELETE': post.delete() return HttpResponse(status=204) Add multiple objects returned error.# Author: Braedy Kuzma from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.renderers import JSONRenderer import uuid from dash.models import Post from .serializers import PostSerializer # Initially taken from # http://www.django-rest-framework.org/tutorial/1-serialization/ class JSONResponse(HttpResponse): """ An HttpResponse that renders its content into JSON. """ def __init__(self, data, **kwargs): content = JSONRenderer().render(data) kwargs['content_type'] = 'application/json' super(JSONResponse, self).__init__(content, **kwargs) @csrf_exempt def post(request, pid=None): """ REST view of Post. pid = Post id (uuid4) """ try: uuid.UUID(pid) except ValueError: return HttpResponse(status=500) # Bad uuid = malformed client request try: post = Post.objects.get(id=pid) except Post.DoesNotExist: return HttpResponse(status=404) except Post.MultipleObjectsReturned: return HttpResponse(status=500) # Some how the UUID matched multiple # posts if request.method == 'GET': serializer = PostSerializer(post) return JSONResponse(serializer.data) elif request.method == 'DELETE': post.delete() return HttpResponse(status=204)
<commit_before># Author: Braedy Kuzma from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.renderers import JSONRenderer import uuid from dash.models import Post from .serializers import PostSerializer # Initially taken from # http://www.django-rest-framework.org/tutorial/1-serialization/ class JSONResponse(HttpResponse): """ An HttpResponse that renders its content into JSON. """ def __init__(self, data, **kwargs): content = JSONRenderer().render(data) kwargs['content_type'] = 'application/json' super(JSONResponse, self).__init__(content, **kwargs) @csrf_exempt def post(request, pid=None): """ REST view of Post. pid = Post id (uuid4) """ try: uuid.UUID(pid) except ValueError: return HttpResponse(status=500) # Bad uuid = malformed client request try: post = Post.objects.get(id=pid) except Post.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = PostSerializer(post) return JSONResponse(serializer.data) elif request.method == 'DELETE': post.delete() return HttpResponse(status=204) <commit_msg>Add multiple objects returned error.<commit_after># Author: Braedy Kuzma from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.renderers import JSONRenderer import uuid from dash.models import Post from .serializers import PostSerializer # Initially taken from # http://www.django-rest-framework.org/tutorial/1-serialization/ class JSONResponse(HttpResponse): """ An HttpResponse that renders its content into JSON. """ def __init__(self, data, **kwargs): content = JSONRenderer().render(data) kwargs['content_type'] = 'application/json' super(JSONResponse, self).__init__(content, **kwargs) @csrf_exempt def post(request, pid=None): """ REST view of Post. pid = Post id (uuid4) """ try: uuid.UUID(pid) except ValueError: return HttpResponse(status=500) # Bad uuid = malformed client request try: post = Post.objects.get(id=pid) except Post.DoesNotExist: return HttpResponse(status=404) except Post.MultipleObjectsReturned: return HttpResponse(status=500) # Some how the UUID matched multiple # posts if request.method == 'GET': serializer = PostSerializer(post) return JSONResponse(serializer.data) elif request.method == 'DELETE': post.delete() return HttpResponse(status=204)
902e4ce0848cc2c3afa7192a85d413ed2919c798
csunplugged/tests/plugging_it_in/models/test_testcase.py
csunplugged/tests/plugging_it_in/models/test_testcase.py
from plugging_it_in.models import TestCase from tests.BaseTestWithDB import BaseTestWithDB from tests.topics.TopicsTestDataGenerator import TopicsTestDataGenerator class TestCaseModelTest(BaseTestWithDB): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.test_data = TopicsTestDataGenerator() def create_testcase(self): topic = self.test_data.create_topic(1) difficulty = self.test_data.create_difficulty_level(1) challenge = self.test_data.create_programming_challenge(topic, 1, difficulty) self.test_data.create_programming_challenge_test_case(1, challenge) self.test_case = TestCase.objects.get(id=1) def test_testcase_verbose_model_name(self): self.create_testcase() verbose_name = self.test_case._meta.verbose_name self.assertEquals(verbose_name, "Test Case")
from tests.BaseTestWithDB import BaseTestWithDB from tests.topics.TopicsTestDataGenerator import TopicsTestDataGenerator class TestCaseModelTest(BaseTestWithDB): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.test_data = TopicsTestDataGenerator() def create_testcase(self): topic = self.test_data.create_topic(1) difficulty = self.test_data.create_difficulty_level(1) challenge = self.test_data.create_programming_challenge(topic, 1, difficulty) self.test_case = self.test_data.create_programming_challenge_test_case(1, challenge) def test_testcase_verbose_model_name(self): self.create_testcase() verbose_name = self.test_case._meta.verbose_name self.assertEquals(verbose_name, "Test Case")
Fix models unit test for plugging it in
Fix models unit test for plugging it in
Python
mit
uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged
from plugging_it_in.models import TestCase from tests.BaseTestWithDB import BaseTestWithDB from tests.topics.TopicsTestDataGenerator import TopicsTestDataGenerator class TestCaseModelTest(BaseTestWithDB): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.test_data = TopicsTestDataGenerator() def create_testcase(self): topic = self.test_data.create_topic(1) difficulty = self.test_data.create_difficulty_level(1) challenge = self.test_data.create_programming_challenge(topic, 1, difficulty) self.test_data.create_programming_challenge_test_case(1, challenge) self.test_case = TestCase.objects.get(id=1) def test_testcase_verbose_model_name(self): self.create_testcase() verbose_name = self.test_case._meta.verbose_name self.assertEquals(verbose_name, "Test Case") Fix models unit test for plugging it in
from tests.BaseTestWithDB import BaseTestWithDB from tests.topics.TopicsTestDataGenerator import TopicsTestDataGenerator class TestCaseModelTest(BaseTestWithDB): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.test_data = TopicsTestDataGenerator() def create_testcase(self): topic = self.test_data.create_topic(1) difficulty = self.test_data.create_difficulty_level(1) challenge = self.test_data.create_programming_challenge(topic, 1, difficulty) self.test_case = self.test_data.create_programming_challenge_test_case(1, challenge) def test_testcase_verbose_model_name(self): self.create_testcase() verbose_name = self.test_case._meta.verbose_name self.assertEquals(verbose_name, "Test Case")
<commit_before>from plugging_it_in.models import TestCase from tests.BaseTestWithDB import BaseTestWithDB from tests.topics.TopicsTestDataGenerator import TopicsTestDataGenerator class TestCaseModelTest(BaseTestWithDB): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.test_data = TopicsTestDataGenerator() def create_testcase(self): topic = self.test_data.create_topic(1) difficulty = self.test_data.create_difficulty_level(1) challenge = self.test_data.create_programming_challenge(topic, 1, difficulty) self.test_data.create_programming_challenge_test_case(1, challenge) self.test_case = TestCase.objects.get(id=1) def test_testcase_verbose_model_name(self): self.create_testcase() verbose_name = self.test_case._meta.verbose_name self.assertEquals(verbose_name, "Test Case") <commit_msg>Fix models unit test for plugging it in<commit_after>
from tests.BaseTestWithDB import BaseTestWithDB from tests.topics.TopicsTestDataGenerator import TopicsTestDataGenerator class TestCaseModelTest(BaseTestWithDB): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.test_data = TopicsTestDataGenerator() def create_testcase(self): topic = self.test_data.create_topic(1) difficulty = self.test_data.create_difficulty_level(1) challenge = self.test_data.create_programming_challenge(topic, 1, difficulty) self.test_case = self.test_data.create_programming_challenge_test_case(1, challenge) def test_testcase_verbose_model_name(self): self.create_testcase() verbose_name = self.test_case._meta.verbose_name self.assertEquals(verbose_name, "Test Case")
from plugging_it_in.models import TestCase from tests.BaseTestWithDB import BaseTestWithDB from tests.topics.TopicsTestDataGenerator import TopicsTestDataGenerator class TestCaseModelTest(BaseTestWithDB): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.test_data = TopicsTestDataGenerator() def create_testcase(self): topic = self.test_data.create_topic(1) difficulty = self.test_data.create_difficulty_level(1) challenge = self.test_data.create_programming_challenge(topic, 1, difficulty) self.test_data.create_programming_challenge_test_case(1, challenge) self.test_case = TestCase.objects.get(id=1) def test_testcase_verbose_model_name(self): self.create_testcase() verbose_name = self.test_case._meta.verbose_name self.assertEquals(verbose_name, "Test Case") Fix models unit test for plugging it infrom tests.BaseTestWithDB import BaseTestWithDB from tests.topics.TopicsTestDataGenerator import TopicsTestDataGenerator class TestCaseModelTest(BaseTestWithDB): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.test_data = TopicsTestDataGenerator() def create_testcase(self): topic = self.test_data.create_topic(1) difficulty = self.test_data.create_difficulty_level(1) challenge = self.test_data.create_programming_challenge(topic, 1, difficulty) self.test_case = self.test_data.create_programming_challenge_test_case(1, challenge) def test_testcase_verbose_model_name(self): self.create_testcase() verbose_name = self.test_case._meta.verbose_name self.assertEquals(verbose_name, "Test Case")
<commit_before>from plugging_it_in.models import TestCase from tests.BaseTestWithDB import BaseTestWithDB from tests.topics.TopicsTestDataGenerator import TopicsTestDataGenerator class TestCaseModelTest(BaseTestWithDB): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.test_data = TopicsTestDataGenerator() def create_testcase(self): topic = self.test_data.create_topic(1) difficulty = self.test_data.create_difficulty_level(1) challenge = self.test_data.create_programming_challenge(topic, 1, difficulty) self.test_data.create_programming_challenge_test_case(1, challenge) self.test_case = TestCase.objects.get(id=1) def test_testcase_verbose_model_name(self): self.create_testcase() verbose_name = self.test_case._meta.verbose_name self.assertEquals(verbose_name, "Test Case") <commit_msg>Fix models unit test for plugging it in<commit_after>from tests.BaseTestWithDB import BaseTestWithDB from tests.topics.TopicsTestDataGenerator import TopicsTestDataGenerator class TestCaseModelTest(BaseTestWithDB): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.test_data = TopicsTestDataGenerator() def create_testcase(self): topic = self.test_data.create_topic(1) difficulty = self.test_data.create_difficulty_level(1) challenge = self.test_data.create_programming_challenge(topic, 1, difficulty) self.test_case = self.test_data.create_programming_challenge_test_case(1, challenge) def test_testcase_verbose_model_name(self): self.create_testcase() verbose_name = self.test_case._meta.verbose_name self.assertEquals(verbose_name, "Test Case")
ae655d0979816892f4cb0a4f8a9b3cbe910d7248
stock_request_direction/models/stock_request_order.py
stock_request_direction/models/stock_request_order.py
# Copyright (c) 2019 Open Source Integrators # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import api, fields, models class StockRequestOrder(models.Model): _inherit = "stock.request.order" direction = fields.Selection( [("outbound", "Outbound"), ("inbound", "Inbound")], string="Direction", states={"draft": [("readonly", False)]}, readonly=True, ) @api.onchange("direction") def _onchange_location_id(self): if self.direction == "outbound": # Stock Location set to Partner Locations/Customers self.location_id = self.company_id.partner_id.property_stock_customer.id else: # Otherwise the Stock Location of the Warehouse self.location_id = self.warehouse_id.lot_stock_id.id @api.onchange('warehouse_id') def _onchange_warehouse_id(self): if self.direction: self.direction = False for stock_request in self.stock_request_ids: if stock_request.route_id: stock_request.route_id = False def change_childs(self): super().change_childs() if not self._context.get("no_change_childs", False): for line in self.stock_request_ids: line.direction = self.direction
# Copyright (c) 2019 Open Source Integrators # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import api, fields, models class StockRequestOrder(models.Model): _inherit = "stock.request.order" direction = fields.Selection( [("outbound", "Outbound"), ("inbound", "Inbound")], string="Direction", states={"draft": [("readonly", False)]}, readonly=True, ) @api.onchange("warehouse_id", "direction") def _onchange_location_id(self): if self.direction == "outbound": # Stock Location set to Partner Locations/Customers self.location_id = self.company_id.partner_id.property_stock_customer.id else: # Otherwise the Stock Location of the Warehouse self.location_id = self.warehouse_id.lot_stock_id.id for stock_request in self.stock_request_ids: if stock_request.route_id: stock_request.route_id = False def change_childs(self): super().change_childs() if not self._context.get("no_change_childs", False): for line in self.stock_request_ids: line.direction = self.direction
Add warehouse_id to existing onchange.
[IMP] Add warehouse_id to existing onchange.
Python
agpl-3.0
OCA/stock-logistics-warehouse,OCA/stock-logistics-warehouse,OCA/stock-logistics-warehouse,OCA/stock-logistics-warehouse
# Copyright (c) 2019 Open Source Integrators # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import api, fields, models class StockRequestOrder(models.Model): _inherit = "stock.request.order" direction = fields.Selection( [("outbound", "Outbound"), ("inbound", "Inbound")], string="Direction", states={"draft": [("readonly", False)]}, readonly=True, ) @api.onchange("direction") def _onchange_location_id(self): if self.direction == "outbound": # Stock Location set to Partner Locations/Customers self.location_id = self.company_id.partner_id.property_stock_customer.id else: # Otherwise the Stock Location of the Warehouse self.location_id = self.warehouse_id.lot_stock_id.id @api.onchange('warehouse_id') def _onchange_warehouse_id(self): if self.direction: self.direction = False for stock_request in self.stock_request_ids: if stock_request.route_id: stock_request.route_id = False def change_childs(self): super().change_childs() if not self._context.get("no_change_childs", False): for line in self.stock_request_ids: line.direction = self.direction [IMP] Add warehouse_id to existing onchange.
# Copyright (c) 2019 Open Source Integrators # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import api, fields, models class StockRequestOrder(models.Model): _inherit = "stock.request.order" direction = fields.Selection( [("outbound", "Outbound"), ("inbound", "Inbound")], string="Direction", states={"draft": [("readonly", False)]}, readonly=True, ) @api.onchange("warehouse_id", "direction") def _onchange_location_id(self): if self.direction == "outbound": # Stock Location set to Partner Locations/Customers self.location_id = self.company_id.partner_id.property_stock_customer.id else: # Otherwise the Stock Location of the Warehouse self.location_id = self.warehouse_id.lot_stock_id.id for stock_request in self.stock_request_ids: if stock_request.route_id: stock_request.route_id = False def change_childs(self): super().change_childs() if not self._context.get("no_change_childs", False): for line in self.stock_request_ids: line.direction = self.direction
<commit_before># Copyright (c) 2019 Open Source Integrators # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import api, fields, models class StockRequestOrder(models.Model): _inherit = "stock.request.order" direction = fields.Selection( [("outbound", "Outbound"), ("inbound", "Inbound")], string="Direction", states={"draft": [("readonly", False)]}, readonly=True, ) @api.onchange("direction") def _onchange_location_id(self): if self.direction == "outbound": # Stock Location set to Partner Locations/Customers self.location_id = self.company_id.partner_id.property_stock_customer.id else: # Otherwise the Stock Location of the Warehouse self.location_id = self.warehouse_id.lot_stock_id.id @api.onchange('warehouse_id') def _onchange_warehouse_id(self): if self.direction: self.direction = False for stock_request in self.stock_request_ids: if stock_request.route_id: stock_request.route_id = False def change_childs(self): super().change_childs() if not self._context.get("no_change_childs", False): for line in self.stock_request_ids: line.direction = self.direction <commit_msg>[IMP] Add warehouse_id to existing onchange.<commit_after>
# Copyright (c) 2019 Open Source Integrators # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import api, fields, models class StockRequestOrder(models.Model): _inherit = "stock.request.order" direction = fields.Selection( [("outbound", "Outbound"), ("inbound", "Inbound")], string="Direction", states={"draft": [("readonly", False)]}, readonly=True, ) @api.onchange("warehouse_id", "direction") def _onchange_location_id(self): if self.direction == "outbound": # Stock Location set to Partner Locations/Customers self.location_id = self.company_id.partner_id.property_stock_customer.id else: # Otherwise the Stock Location of the Warehouse self.location_id = self.warehouse_id.lot_stock_id.id for stock_request in self.stock_request_ids: if stock_request.route_id: stock_request.route_id = False def change_childs(self): super().change_childs() if not self._context.get("no_change_childs", False): for line in self.stock_request_ids: line.direction = self.direction
# Copyright (c) 2019 Open Source Integrators # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import api, fields, models class StockRequestOrder(models.Model): _inherit = "stock.request.order" direction = fields.Selection( [("outbound", "Outbound"), ("inbound", "Inbound")], string="Direction", states={"draft": [("readonly", False)]}, readonly=True, ) @api.onchange("direction") def _onchange_location_id(self): if self.direction == "outbound": # Stock Location set to Partner Locations/Customers self.location_id = self.company_id.partner_id.property_stock_customer.id else: # Otherwise the Stock Location of the Warehouse self.location_id = self.warehouse_id.lot_stock_id.id @api.onchange('warehouse_id') def _onchange_warehouse_id(self): if self.direction: self.direction = False for stock_request in self.stock_request_ids: if stock_request.route_id: stock_request.route_id = False def change_childs(self): super().change_childs() if not self._context.get("no_change_childs", False): for line in self.stock_request_ids: line.direction = self.direction [IMP] Add warehouse_id to existing onchange.# Copyright (c) 2019 Open Source Integrators # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import api, fields, models class StockRequestOrder(models.Model): _inherit = "stock.request.order" direction = fields.Selection( [("outbound", "Outbound"), ("inbound", "Inbound")], string="Direction", states={"draft": [("readonly", False)]}, readonly=True, ) @api.onchange("warehouse_id", "direction") def _onchange_location_id(self): if self.direction == "outbound": # Stock Location set to Partner Locations/Customers self.location_id = self.company_id.partner_id.property_stock_customer.id else: # Otherwise the Stock Location of the Warehouse self.location_id = self.warehouse_id.lot_stock_id.id for stock_request in self.stock_request_ids: if stock_request.route_id: stock_request.route_id = False def change_childs(self): super().change_childs() if not self._context.get("no_change_childs", False): for line in self.stock_request_ids: line.direction = self.direction
<commit_before># Copyright (c) 2019 Open Source Integrators # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import api, fields, models class StockRequestOrder(models.Model): _inherit = "stock.request.order" direction = fields.Selection( [("outbound", "Outbound"), ("inbound", "Inbound")], string="Direction", states={"draft": [("readonly", False)]}, readonly=True, ) @api.onchange("direction") def _onchange_location_id(self): if self.direction == "outbound": # Stock Location set to Partner Locations/Customers self.location_id = self.company_id.partner_id.property_stock_customer.id else: # Otherwise the Stock Location of the Warehouse self.location_id = self.warehouse_id.lot_stock_id.id @api.onchange('warehouse_id') def _onchange_warehouse_id(self): if self.direction: self.direction = False for stock_request in self.stock_request_ids: if stock_request.route_id: stock_request.route_id = False def change_childs(self): super().change_childs() if not self._context.get("no_change_childs", False): for line in self.stock_request_ids: line.direction = self.direction <commit_msg>[IMP] Add warehouse_id to existing onchange.<commit_after># Copyright (c) 2019 Open Source Integrators # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import api, fields, models class StockRequestOrder(models.Model): _inherit = "stock.request.order" direction = fields.Selection( [("outbound", "Outbound"), ("inbound", "Inbound")], string="Direction", states={"draft": [("readonly", False)]}, readonly=True, ) @api.onchange("warehouse_id", "direction") def _onchange_location_id(self): if self.direction == "outbound": # Stock Location set to Partner Locations/Customers self.location_id = self.company_id.partner_id.property_stock_customer.id else: # Otherwise the Stock Location of the Warehouse self.location_id = self.warehouse_id.lot_stock_id.id for stock_request in self.stock_request_ids: if stock_request.route_id: stock_request.route_id = False def change_childs(self): super().change_childs() if not self._context.get("no_change_childs", False): for line in self.stock_request_ids: line.direction = self.direction
010d3501afce9ae9ae79a01d5c2e6118a9009df2
tests/cupy_tests/random_tests/test_sample.py
tests/cupy_tests/random_tests/test_sample.py
import unittest from cupy import testing @testing.gpu class TestSample(unittest.TestCase): _multiprocess_can_split_ = True
import mock import unittest import numpy from cupy import random from cupy import testing @testing.gpu class TestSample(unittest.TestCase): _multiprocess_can_split_ = True def setUp(self): random.random_sample = mock.Mock() def test_rand(self): random.rand(1, 2, 3, dtype=numpy.float32) random.random_sample.assert_call_once_with((1, 2, 3), numpy.float32) def test_rand_invalid_argument(self): with self.assertRaises(TypeError): random.rand(1, 2, 3, unnecessary='unnecessary_argument') def test_randn(self): random.randn(1, 2, 3, dtype=numpy.float32) random.random_sample.assert_call_once_with((1, 2, 3), numpy.float32) def test_randn_invalid_argument(self): with self.assertRaises(TypeError): random.randn(1, 2, 3, unnecessary='unnecessary_argument')
Add unittest for rand and randn
Add unittest for rand and randn
Python
mit
delta2323/chainer,okuta/chainer,kiyukuta/chainer,cupy/cupy,sinhrks/chainer,kashif/chainer,tscohen/chainer,ktnyt/chainer,hvy/chainer,cemoody/chainer,niboshi/chainer,kikusu/chainer,jnishi/chainer,okuta/chainer,niboshi/chainer,ronekko/chainer,benob/chainer,truongdq/chainer,cupy/cupy,aonotas/chainer,ktnyt/chainer,benob/chainer,chainer/chainer,cupy/cupy,chainer/chainer,jnishi/chainer,jnishi/chainer,keisuke-umezawa/chainer,okuta/chainer,hvy/chainer,AlpacaDB/chainer,niboshi/chainer,hvy/chainer,muupan/chainer,okuta/chainer,t-abe/chainer,chainer/chainer,kikusu/chainer,muupan/chainer,keisuke-umezawa/chainer,hvy/chainer,niboshi/chainer,keisuke-umezawa/chainer,keisuke-umezawa/chainer,jnishi/chainer,pfnet/chainer,minhpqn/chainer,cupy/cupy,ktnyt/chainer,rezoo/chainer,anaruse/chainer,AlpacaDB/chainer,wkentaro/chainer,wkentaro/chainer,wkentaro/chainer,chainer/chainer,truongdq/chainer,wkentaro/chainer,sinhrks/chainer,ktnyt/chainer,tkerola/chainer,t-abe/chainer,ysekky/chainer
import unittest from cupy import testing @testing.gpu class TestSample(unittest.TestCase): _multiprocess_can_split_ = True Add unittest for rand and randn
import mock import unittest import numpy from cupy import random from cupy import testing @testing.gpu class TestSample(unittest.TestCase): _multiprocess_can_split_ = True def setUp(self): random.random_sample = mock.Mock() def test_rand(self): random.rand(1, 2, 3, dtype=numpy.float32) random.random_sample.assert_call_once_with((1, 2, 3), numpy.float32) def test_rand_invalid_argument(self): with self.assertRaises(TypeError): random.rand(1, 2, 3, unnecessary='unnecessary_argument') def test_randn(self): random.randn(1, 2, 3, dtype=numpy.float32) random.random_sample.assert_call_once_with((1, 2, 3), numpy.float32) def test_randn_invalid_argument(self): with self.assertRaises(TypeError): random.randn(1, 2, 3, unnecessary='unnecessary_argument')
<commit_before>import unittest from cupy import testing @testing.gpu class TestSample(unittest.TestCase): _multiprocess_can_split_ = True <commit_msg>Add unittest for rand and randn<commit_after>
import mock import unittest import numpy from cupy import random from cupy import testing @testing.gpu class TestSample(unittest.TestCase): _multiprocess_can_split_ = True def setUp(self): random.random_sample = mock.Mock() def test_rand(self): random.rand(1, 2, 3, dtype=numpy.float32) random.random_sample.assert_call_once_with((1, 2, 3), numpy.float32) def test_rand_invalid_argument(self): with self.assertRaises(TypeError): random.rand(1, 2, 3, unnecessary='unnecessary_argument') def test_randn(self): random.randn(1, 2, 3, dtype=numpy.float32) random.random_sample.assert_call_once_with((1, 2, 3), numpy.float32) def test_randn_invalid_argument(self): with self.assertRaises(TypeError): random.randn(1, 2, 3, unnecessary='unnecessary_argument')
import unittest from cupy import testing @testing.gpu class TestSample(unittest.TestCase): _multiprocess_can_split_ = True Add unittest for rand and randnimport mock import unittest import numpy from cupy import random from cupy import testing @testing.gpu class TestSample(unittest.TestCase): _multiprocess_can_split_ = True def setUp(self): random.random_sample = mock.Mock() def test_rand(self): random.rand(1, 2, 3, dtype=numpy.float32) random.random_sample.assert_call_once_with((1, 2, 3), numpy.float32) def test_rand_invalid_argument(self): with self.assertRaises(TypeError): random.rand(1, 2, 3, unnecessary='unnecessary_argument') def test_randn(self): random.randn(1, 2, 3, dtype=numpy.float32) random.random_sample.assert_call_once_with((1, 2, 3), numpy.float32) def test_randn_invalid_argument(self): with self.assertRaises(TypeError): random.randn(1, 2, 3, unnecessary='unnecessary_argument')
<commit_before>import unittest from cupy import testing @testing.gpu class TestSample(unittest.TestCase): _multiprocess_can_split_ = True <commit_msg>Add unittest for rand and randn<commit_after>import mock import unittest import numpy from cupy import random from cupy import testing @testing.gpu class TestSample(unittest.TestCase): _multiprocess_can_split_ = True def setUp(self): random.random_sample = mock.Mock() def test_rand(self): random.rand(1, 2, 3, dtype=numpy.float32) random.random_sample.assert_call_once_with((1, 2, 3), numpy.float32) def test_rand_invalid_argument(self): with self.assertRaises(TypeError): random.rand(1, 2, 3, unnecessary='unnecessary_argument') def test_randn(self): random.randn(1, 2, 3, dtype=numpy.float32) random.random_sample.assert_call_once_with((1, 2, 3), numpy.float32) def test_randn_invalid_argument(self): with self.assertRaises(TypeError): random.randn(1, 2, 3, unnecessary='unnecessary_argument')
baf65a0c73a21e5080006a2f5e6be71abdc1feff
tests/test_class_to_config.py
tests/test_class_to_config.py
from __future__ import absolute_import, division, print_function import os import attr import pytest import environ @environ.config(prefix="APP") class AppConfig(object): host = environ.var("127.0.0.1") port = environ.var(5000, converter=int) def test_default(): cfg = AppConfig.from_environ() assert cfg.host == "127.0.0.1" assert cfg.port == 5000 def test_env(): env = {"APP_HOST": "0.0.0.0"} cfg = AppConfig.from_environ(environ=env) assert cfg.host == "0.0.0.0" assert cfg.port == 5000
from __future__ import absolute_import, division, print_function import environ @environ.config(prefix="APP") class AppConfig(object): host = environ.var("127.0.0.1") port = environ.var(5000, converter=int) def test_default(): cfg = AppConfig.from_environ() assert cfg.host == "127.0.0.1" assert cfg.port == 5000 def test_env(): env = {"APP_HOST": "0.0.0.0"} cfg = AppConfig.from_environ(environ=env) assert cfg.host == "0.0.0.0" assert cfg.port == 5000
Fix formatting, remove unused vars
Fix formatting, remove unused vars
Python
apache-2.0
hynek/environ_config
from __future__ import absolute_import, division, print_function import os import attr import pytest import environ @environ.config(prefix="APP") class AppConfig(object): host = environ.var("127.0.0.1") port = environ.var(5000, converter=int) def test_default(): cfg = AppConfig.from_environ() assert cfg.host == "127.0.0.1" assert cfg.port == 5000 def test_env(): env = {"APP_HOST": "0.0.0.0"} cfg = AppConfig.from_environ(environ=env) assert cfg.host == "0.0.0.0" assert cfg.port == 5000 Fix formatting, remove unused vars
from __future__ import absolute_import, division, print_function import environ @environ.config(prefix="APP") class AppConfig(object): host = environ.var("127.0.0.1") port = environ.var(5000, converter=int) def test_default(): cfg = AppConfig.from_environ() assert cfg.host == "127.0.0.1" assert cfg.port == 5000 def test_env(): env = {"APP_HOST": "0.0.0.0"} cfg = AppConfig.from_environ(environ=env) assert cfg.host == "0.0.0.0" assert cfg.port == 5000
<commit_before>from __future__ import absolute_import, division, print_function import os import attr import pytest import environ @environ.config(prefix="APP") class AppConfig(object): host = environ.var("127.0.0.1") port = environ.var(5000, converter=int) def test_default(): cfg = AppConfig.from_environ() assert cfg.host == "127.0.0.1" assert cfg.port == 5000 def test_env(): env = {"APP_HOST": "0.0.0.0"} cfg = AppConfig.from_environ(environ=env) assert cfg.host == "0.0.0.0" assert cfg.port == 5000 <commit_msg>Fix formatting, remove unused vars<commit_after>
from __future__ import absolute_import, division, print_function import environ @environ.config(prefix="APP") class AppConfig(object): host = environ.var("127.0.0.1") port = environ.var(5000, converter=int) def test_default(): cfg = AppConfig.from_environ() assert cfg.host == "127.0.0.1" assert cfg.port == 5000 def test_env(): env = {"APP_HOST": "0.0.0.0"} cfg = AppConfig.from_environ(environ=env) assert cfg.host == "0.0.0.0" assert cfg.port == 5000
from __future__ import absolute_import, division, print_function import os import attr import pytest import environ @environ.config(prefix="APP") class AppConfig(object): host = environ.var("127.0.0.1") port = environ.var(5000, converter=int) def test_default(): cfg = AppConfig.from_environ() assert cfg.host == "127.0.0.1" assert cfg.port == 5000 def test_env(): env = {"APP_HOST": "0.0.0.0"} cfg = AppConfig.from_environ(environ=env) assert cfg.host == "0.0.0.0" assert cfg.port == 5000 Fix formatting, remove unused varsfrom __future__ import absolute_import, division, print_function import environ @environ.config(prefix="APP") class AppConfig(object): host = environ.var("127.0.0.1") port = environ.var(5000, converter=int) def test_default(): cfg = AppConfig.from_environ() assert cfg.host == "127.0.0.1" assert cfg.port == 5000 def test_env(): env = {"APP_HOST": "0.0.0.0"} cfg = AppConfig.from_environ(environ=env) assert cfg.host == "0.0.0.0" assert cfg.port == 5000
<commit_before>from __future__ import absolute_import, division, print_function import os import attr import pytest import environ @environ.config(prefix="APP") class AppConfig(object): host = environ.var("127.0.0.1") port = environ.var(5000, converter=int) def test_default(): cfg = AppConfig.from_environ() assert cfg.host == "127.0.0.1" assert cfg.port == 5000 def test_env(): env = {"APP_HOST": "0.0.0.0"} cfg = AppConfig.from_environ(environ=env) assert cfg.host == "0.0.0.0" assert cfg.port == 5000 <commit_msg>Fix formatting, remove unused vars<commit_after>from __future__ import absolute_import, division, print_function import environ @environ.config(prefix="APP") class AppConfig(object): host = environ.var("127.0.0.1") port = environ.var(5000, converter=int) def test_default(): cfg = AppConfig.from_environ() assert cfg.host == "127.0.0.1" assert cfg.port == 5000 def test_env(): env = {"APP_HOST": "0.0.0.0"} cfg = AppConfig.from_environ(environ=env) assert cfg.host == "0.0.0.0" assert cfg.port == 5000
884071638140d4f351fde68e81117ce95f418557
tetrahydra/tests/test_core.py
tetrahydra/tests/test_core.py
"""Test core functions.""" import numpy as np from tetrahydra.core import closure, perturb, power def test_closure(): """Test closure operator.""" # Given data = np.random.random([2, 3]) expected = np.ones(2) # When output = np.sum(closure(data), axis=1) # Then assert output == pytest.approx(expected) def test_perturb(): """Test perturbation operator.""" # Given data = np.random.random([2, 3]) p_vals = np.array([1., 2., 3.]) # perturbation values expected = data * p_vals # When output = perturb(data, p_vals, reclose=False) # Then assert np.all(output == expected) def test_power(): """Test powering operator.""" # Given data = np.random.random([2, 3]) expected = data**np.pi # When output = power(data, np.pi, reclose=False) # Then assert np.all(output == expected)
"""Test core functions.""" import pytest import numpy as np from tetrahydra.core import closure, perturb, power def test_closure(): """Test closure operator.""" # Given data = np.random.random([2, 3]) expected = np.ones(2) # When output = np.sum(closure(data), axis=1) # Then assert output == pytest.approx(expected) def test_perturb(): """Test perturbation operator.""" # Given data = np.random.random([2, 3]) p_vals = np.array([1., 2., 3.]) # perturbation values expected = data * p_vals # When output = perturb(data, p_vals, reclose=False) # Then assert np.all(output == expected) def test_power(): """Test powering operator.""" # Given data = np.random.random([2, 3]) expected = data**np.pi # When output = power(data, np.pi, reclose=False) # Then assert np.all(output == expected)
Revert prev commit in this file.
Revert prev commit in this file.
Python
bsd-3-clause
ofgulban/tetrahydra
"""Test core functions.""" import numpy as np from tetrahydra.core import closure, perturb, power def test_closure(): """Test closure operator.""" # Given data = np.random.random([2, 3]) expected = np.ones(2) # When output = np.sum(closure(data), axis=1) # Then assert output == pytest.approx(expected) def test_perturb(): """Test perturbation operator.""" # Given data = np.random.random([2, 3]) p_vals = np.array([1., 2., 3.]) # perturbation values expected = data * p_vals # When output = perturb(data, p_vals, reclose=False) # Then assert np.all(output == expected) def test_power(): """Test powering operator.""" # Given data = np.random.random([2, 3]) expected = data**np.pi # When output = power(data, np.pi, reclose=False) # Then assert np.all(output == expected) Revert prev commit in this file.
"""Test core functions.""" import pytest import numpy as np from tetrahydra.core import closure, perturb, power def test_closure(): """Test closure operator.""" # Given data = np.random.random([2, 3]) expected = np.ones(2) # When output = np.sum(closure(data), axis=1) # Then assert output == pytest.approx(expected) def test_perturb(): """Test perturbation operator.""" # Given data = np.random.random([2, 3]) p_vals = np.array([1., 2., 3.]) # perturbation values expected = data * p_vals # When output = perturb(data, p_vals, reclose=False) # Then assert np.all(output == expected) def test_power(): """Test powering operator.""" # Given data = np.random.random([2, 3]) expected = data**np.pi # When output = power(data, np.pi, reclose=False) # Then assert np.all(output == expected)
<commit_before>"""Test core functions.""" import numpy as np from tetrahydra.core import closure, perturb, power def test_closure(): """Test closure operator.""" # Given data = np.random.random([2, 3]) expected = np.ones(2) # When output = np.sum(closure(data), axis=1) # Then assert output == pytest.approx(expected) def test_perturb(): """Test perturbation operator.""" # Given data = np.random.random([2, 3]) p_vals = np.array([1., 2., 3.]) # perturbation values expected = data * p_vals # When output = perturb(data, p_vals, reclose=False) # Then assert np.all(output == expected) def test_power(): """Test powering operator.""" # Given data = np.random.random([2, 3]) expected = data**np.pi # When output = power(data, np.pi, reclose=False) # Then assert np.all(output == expected) <commit_msg>Revert prev commit in this file.<commit_after>
"""Test core functions.""" import pytest import numpy as np from tetrahydra.core import closure, perturb, power def test_closure(): """Test closure operator.""" # Given data = np.random.random([2, 3]) expected = np.ones(2) # When output = np.sum(closure(data), axis=1) # Then assert output == pytest.approx(expected) def test_perturb(): """Test perturbation operator.""" # Given data = np.random.random([2, 3]) p_vals = np.array([1., 2., 3.]) # perturbation values expected = data * p_vals # When output = perturb(data, p_vals, reclose=False) # Then assert np.all(output == expected) def test_power(): """Test powering operator.""" # Given data = np.random.random([2, 3]) expected = data**np.pi # When output = power(data, np.pi, reclose=False) # Then assert np.all(output == expected)
"""Test core functions.""" import numpy as np from tetrahydra.core import closure, perturb, power def test_closure(): """Test closure operator.""" # Given data = np.random.random([2, 3]) expected = np.ones(2) # When output = np.sum(closure(data), axis=1) # Then assert output == pytest.approx(expected) def test_perturb(): """Test perturbation operator.""" # Given data = np.random.random([2, 3]) p_vals = np.array([1., 2., 3.]) # perturbation values expected = data * p_vals # When output = perturb(data, p_vals, reclose=False) # Then assert np.all(output == expected) def test_power(): """Test powering operator.""" # Given data = np.random.random([2, 3]) expected = data**np.pi # When output = power(data, np.pi, reclose=False) # Then assert np.all(output == expected) Revert prev commit in this file."""Test core functions.""" import pytest import numpy as np from tetrahydra.core import closure, perturb, power def test_closure(): """Test closure operator.""" # Given data = np.random.random([2, 3]) expected = np.ones(2) # When output = np.sum(closure(data), axis=1) # Then assert output == pytest.approx(expected) def test_perturb(): """Test perturbation operator.""" # Given data = np.random.random([2, 3]) p_vals = np.array([1., 2., 3.]) # perturbation values expected = data * p_vals # When output = perturb(data, p_vals, reclose=False) # Then assert np.all(output == expected) def test_power(): """Test powering operator.""" # Given data = np.random.random([2, 3]) expected = data**np.pi # When output = power(data, np.pi, reclose=False) # Then assert np.all(output == expected)
<commit_before>"""Test core functions.""" import numpy as np from tetrahydra.core import closure, perturb, power def test_closure(): """Test closure operator.""" # Given data = np.random.random([2, 3]) expected = np.ones(2) # When output = np.sum(closure(data), axis=1) # Then assert output == pytest.approx(expected) def test_perturb(): """Test perturbation operator.""" # Given data = np.random.random([2, 3]) p_vals = np.array([1., 2., 3.]) # perturbation values expected = data * p_vals # When output = perturb(data, p_vals, reclose=False) # Then assert np.all(output == expected) def test_power(): """Test powering operator.""" # Given data = np.random.random([2, 3]) expected = data**np.pi # When output = power(data, np.pi, reclose=False) # Then assert np.all(output == expected) <commit_msg>Revert prev commit in this file.<commit_after>"""Test core functions.""" import pytest import numpy as np from tetrahydra.core import closure, perturb, power def test_closure(): """Test closure operator.""" # Given data = np.random.random([2, 3]) expected = np.ones(2) # When output = np.sum(closure(data), axis=1) # Then assert output == pytest.approx(expected) def test_perturb(): """Test perturbation operator.""" # Given data = np.random.random([2, 3]) p_vals = np.array([1., 2., 3.]) # perturbation values expected = data * p_vals # When output = perturb(data, p_vals, reclose=False) # Then assert np.all(output == expected) def test_power(): """Test powering operator.""" # Given data = np.random.random([2, 3]) expected = data**np.pi # When output = power(data, np.pi, reclose=False) # Then assert np.all(output == expected)
b0e39088d326557192486a24c87df3b68bf617ce
api/models.py
api/models.py
from django.db import models class Page(models.Model): """A Page in Dyanote.""" created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, default='') parent = models.ForeignKey('api.Page', null=True, related_name='children') body = models.TextField(blank=True, default='') author = models.ForeignKey('auth.User', related_name='pages') NORMAL = 0 ROOT = 1 TRASH = 2 FLAGS = ( (NORMAL, 'Normal page'), (ROOT, 'Root page'), (TRASH, 'Trash page'), ) flags = models.IntegerField(choices=FLAGS, default=NORMAL) class Meta: ordering = ('created',)
from django.db import models class Page(models.Model): """A Page in Dyanote.""" created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, default='') parent = models.ForeignKey('api.Page', null=True, blank=True, related_name='children') body = models.TextField(blank=True, default='') author = models.ForeignKey('auth.User', related_name='pages') NORMAL = 0 ROOT = 1 TRASH = 2 FLAGS = ( (NORMAL, 'Normal page'), (ROOT, 'Root page'), (TRASH, 'Trash page'), ) flags = models.IntegerField(choices=FLAGS, default=NORMAL) class Meta: ordering = ('created',)
Mark Page's parent field as 'blank'
Mark Page's parent field as 'blank'
Python
mit
MatteoNardi/dyanote-server,MatteoNardi/dyanote-server
from django.db import models class Page(models.Model): """A Page in Dyanote.""" created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, default='') parent = models.ForeignKey('api.Page', null=True, related_name='children') body = models.TextField(blank=True, default='') author = models.ForeignKey('auth.User', related_name='pages') NORMAL = 0 ROOT = 1 TRASH = 2 FLAGS = ( (NORMAL, 'Normal page'), (ROOT, 'Root page'), (TRASH, 'Trash page'), ) flags = models.IntegerField(choices=FLAGS, default=NORMAL) class Meta: ordering = ('created',) Mark Page's parent field as 'blank'
from django.db import models class Page(models.Model): """A Page in Dyanote.""" created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, default='') parent = models.ForeignKey('api.Page', null=True, blank=True, related_name='children') body = models.TextField(blank=True, default='') author = models.ForeignKey('auth.User', related_name='pages') NORMAL = 0 ROOT = 1 TRASH = 2 FLAGS = ( (NORMAL, 'Normal page'), (ROOT, 'Root page'), (TRASH, 'Trash page'), ) flags = models.IntegerField(choices=FLAGS, default=NORMAL) class Meta: ordering = ('created',)
<commit_before>from django.db import models class Page(models.Model): """A Page in Dyanote.""" created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, default='') parent = models.ForeignKey('api.Page', null=True, related_name='children') body = models.TextField(blank=True, default='') author = models.ForeignKey('auth.User', related_name='pages') NORMAL = 0 ROOT = 1 TRASH = 2 FLAGS = ( (NORMAL, 'Normal page'), (ROOT, 'Root page'), (TRASH, 'Trash page'), ) flags = models.IntegerField(choices=FLAGS, default=NORMAL) class Meta: ordering = ('created',) <commit_msg>Mark Page's parent field as 'blank'<commit_after>
from django.db import models class Page(models.Model): """A Page in Dyanote.""" created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, default='') parent = models.ForeignKey('api.Page', null=True, blank=True, related_name='children') body = models.TextField(blank=True, default='') author = models.ForeignKey('auth.User', related_name='pages') NORMAL = 0 ROOT = 1 TRASH = 2 FLAGS = ( (NORMAL, 'Normal page'), (ROOT, 'Root page'), (TRASH, 'Trash page'), ) flags = models.IntegerField(choices=FLAGS, default=NORMAL) class Meta: ordering = ('created',)
from django.db import models class Page(models.Model): """A Page in Dyanote.""" created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, default='') parent = models.ForeignKey('api.Page', null=True, related_name='children') body = models.TextField(blank=True, default='') author = models.ForeignKey('auth.User', related_name='pages') NORMAL = 0 ROOT = 1 TRASH = 2 FLAGS = ( (NORMAL, 'Normal page'), (ROOT, 'Root page'), (TRASH, 'Trash page'), ) flags = models.IntegerField(choices=FLAGS, default=NORMAL) class Meta: ordering = ('created',) Mark Page's parent field as 'blank'from django.db import models class Page(models.Model): """A Page in Dyanote.""" created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, default='') parent = models.ForeignKey('api.Page', null=True, blank=True, related_name='children') body = models.TextField(blank=True, default='') author = models.ForeignKey('auth.User', related_name='pages') NORMAL = 0 ROOT = 1 TRASH = 2 FLAGS = ( (NORMAL, 'Normal page'), (ROOT, 'Root page'), (TRASH, 'Trash page'), ) flags = models.IntegerField(choices=FLAGS, default=NORMAL) class Meta: ordering = ('created',)
<commit_before>from django.db import models class Page(models.Model): """A Page in Dyanote.""" created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, default='') parent = models.ForeignKey('api.Page', null=True, related_name='children') body = models.TextField(blank=True, default='') author = models.ForeignKey('auth.User', related_name='pages') NORMAL = 0 ROOT = 1 TRASH = 2 FLAGS = ( (NORMAL, 'Normal page'), (ROOT, 'Root page'), (TRASH, 'Trash page'), ) flags = models.IntegerField(choices=FLAGS, default=NORMAL) class Meta: ordering = ('created',) <commit_msg>Mark Page's parent field as 'blank'<commit_after>from django.db import models class Page(models.Model): """A Page in Dyanote.""" created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, default='') parent = models.ForeignKey('api.Page', null=True, blank=True, related_name='children') body = models.TextField(blank=True, default='') author = models.ForeignKey('auth.User', related_name='pages') NORMAL = 0 ROOT = 1 TRASH = 2 FLAGS = ( (NORMAL, 'Normal page'), (ROOT, 'Root page'), (TRASH, 'Trash page'), ) flags = models.IntegerField(choices=FLAGS, default=NORMAL) class Meta: ordering = ('created',)
1231c5e2c9fd4edc033e6021372950ca9b89c2f1
ansible/module_utils/dcos.py
ansible/module_utils/dcos.py
import requests def dcos_api(method, endpoint, body=None, params=None): url = "{url}acs/api/v1{endpoint}".format( url=params['dcos_credentials']['url'], endpoint=endpoint) headers = { 'Content-Type': 'application/json', 'Authorization': "token={}".format(params['dcos_credentials']['token']), } verify = params.get('ssl_verify', True) if method == 'GET': response = requests.get(url, headers=headers, verify=verify) elif method == 'PUT': response = requests.put(url, json=body, headers=headers, verify=verify) elif method == 'PATCH': response = requests.patch(url, json=body, headers=headers, verify=verify) elif method == 'DELETE': response = requests.delete(url, headers=headers, verify=verify) try: response_json = response.json() except: response_json = {} return { 'url': url, 'status_code': response.status_code, 'text': response.text, 'json': response_json, 'request_body': body, 'request_headers': headers, }
import requests import urlparse def dcos_api(method, endpoint, body=None, params=None): result = urlparse.urlsplit(params['dcos_credentials']['url']) netloc = result.netloc.split('@')[-1] result = result._replace(netloc=netloc) path = "acs/api/v1{endpoint}".format(endpoint=endpoint) result = result._replace(path=path) url = urlparse.urlunsplit(result) headers = { 'Content-Type': 'application/json', 'Authorization': "token={}".format(params['dcos_credentials']['token']), } verify = params.get('ssl_verify', True) if method == 'GET': response = requests.get(url, headers=headers, verify=verify) elif method == 'PUT': response = requests.put(url, json=body, headers=headers, verify=verify) elif method == 'PATCH': response = requests.patch(url, json=body, headers=headers, verify=verify) elif method == 'DELETE': response = requests.delete(url, headers=headers, verify=verify) try: response_json = response.json() except: response_json = {} return { 'url': url, 'status_code': response.status_code, 'text': response.text, 'json': response_json, 'request_body': body, 'request_headers': headers, }
Fix for urls with user/pass
Fix for urls with user/pass
Python
mit
TerryHowe/ansible-modules-dcos,TerryHowe/ansible-modules-dcos
import requests def dcos_api(method, endpoint, body=None, params=None): url = "{url}acs/api/v1{endpoint}".format( url=params['dcos_credentials']['url'], endpoint=endpoint) headers = { 'Content-Type': 'application/json', 'Authorization': "token={}".format(params['dcos_credentials']['token']), } verify = params.get('ssl_verify', True) if method == 'GET': response = requests.get(url, headers=headers, verify=verify) elif method == 'PUT': response = requests.put(url, json=body, headers=headers, verify=verify) elif method == 'PATCH': response = requests.patch(url, json=body, headers=headers, verify=verify) elif method == 'DELETE': response = requests.delete(url, headers=headers, verify=verify) try: response_json = response.json() except: response_json = {} return { 'url': url, 'status_code': response.status_code, 'text': response.text, 'json': response_json, 'request_body': body, 'request_headers': headers, } Fix for urls with user/pass
import requests import urlparse def dcos_api(method, endpoint, body=None, params=None): result = urlparse.urlsplit(params['dcos_credentials']['url']) netloc = result.netloc.split('@')[-1] result = result._replace(netloc=netloc) path = "acs/api/v1{endpoint}".format(endpoint=endpoint) result = result._replace(path=path) url = urlparse.urlunsplit(result) headers = { 'Content-Type': 'application/json', 'Authorization': "token={}".format(params['dcos_credentials']['token']), } verify = params.get('ssl_verify', True) if method == 'GET': response = requests.get(url, headers=headers, verify=verify) elif method == 'PUT': response = requests.put(url, json=body, headers=headers, verify=verify) elif method == 'PATCH': response = requests.patch(url, json=body, headers=headers, verify=verify) elif method == 'DELETE': response = requests.delete(url, headers=headers, verify=verify) try: response_json = response.json() except: response_json = {} return { 'url': url, 'status_code': response.status_code, 'text': response.text, 'json': response_json, 'request_body': body, 'request_headers': headers, }
<commit_before>import requests def dcos_api(method, endpoint, body=None, params=None): url = "{url}acs/api/v1{endpoint}".format( url=params['dcos_credentials']['url'], endpoint=endpoint) headers = { 'Content-Type': 'application/json', 'Authorization': "token={}".format(params['dcos_credentials']['token']), } verify = params.get('ssl_verify', True) if method == 'GET': response = requests.get(url, headers=headers, verify=verify) elif method == 'PUT': response = requests.put(url, json=body, headers=headers, verify=verify) elif method == 'PATCH': response = requests.patch(url, json=body, headers=headers, verify=verify) elif method == 'DELETE': response = requests.delete(url, headers=headers, verify=verify) try: response_json = response.json() except: response_json = {} return { 'url': url, 'status_code': response.status_code, 'text': response.text, 'json': response_json, 'request_body': body, 'request_headers': headers, } <commit_msg>Fix for urls with user/pass<commit_after>
import requests import urlparse def dcos_api(method, endpoint, body=None, params=None): result = urlparse.urlsplit(params['dcos_credentials']['url']) netloc = result.netloc.split('@')[-1] result = result._replace(netloc=netloc) path = "acs/api/v1{endpoint}".format(endpoint=endpoint) result = result._replace(path=path) url = urlparse.urlunsplit(result) headers = { 'Content-Type': 'application/json', 'Authorization': "token={}".format(params['dcos_credentials']['token']), } verify = params.get('ssl_verify', True) if method == 'GET': response = requests.get(url, headers=headers, verify=verify) elif method == 'PUT': response = requests.put(url, json=body, headers=headers, verify=verify) elif method == 'PATCH': response = requests.patch(url, json=body, headers=headers, verify=verify) elif method == 'DELETE': response = requests.delete(url, headers=headers, verify=verify) try: response_json = response.json() except: response_json = {} return { 'url': url, 'status_code': response.status_code, 'text': response.text, 'json': response_json, 'request_body': body, 'request_headers': headers, }
import requests def dcos_api(method, endpoint, body=None, params=None): url = "{url}acs/api/v1{endpoint}".format( url=params['dcos_credentials']['url'], endpoint=endpoint) headers = { 'Content-Type': 'application/json', 'Authorization': "token={}".format(params['dcos_credentials']['token']), } verify = params.get('ssl_verify', True) if method == 'GET': response = requests.get(url, headers=headers, verify=verify) elif method == 'PUT': response = requests.put(url, json=body, headers=headers, verify=verify) elif method == 'PATCH': response = requests.patch(url, json=body, headers=headers, verify=verify) elif method == 'DELETE': response = requests.delete(url, headers=headers, verify=verify) try: response_json = response.json() except: response_json = {} return { 'url': url, 'status_code': response.status_code, 'text': response.text, 'json': response_json, 'request_body': body, 'request_headers': headers, } Fix for urls with user/passimport requests import urlparse def dcos_api(method, endpoint, body=None, params=None): result = urlparse.urlsplit(params['dcos_credentials']['url']) netloc = result.netloc.split('@')[-1] result = result._replace(netloc=netloc) path = "acs/api/v1{endpoint}".format(endpoint=endpoint) result = result._replace(path=path) url = urlparse.urlunsplit(result) headers = { 'Content-Type': 'application/json', 'Authorization': "token={}".format(params['dcos_credentials']['token']), } verify = params.get('ssl_verify', True) if method == 'GET': response = requests.get(url, headers=headers, verify=verify) elif method == 'PUT': response = requests.put(url, json=body, headers=headers, verify=verify) elif method == 'PATCH': response = requests.patch(url, json=body, headers=headers, verify=verify) elif method == 'DELETE': response = requests.delete(url, headers=headers, verify=verify) try: response_json = response.json() except: response_json = {} return { 'url': url, 'status_code': response.status_code, 'text': response.text, 'json': response_json, 'request_body': body, 'request_headers': headers, }
<commit_before>import requests def dcos_api(method, endpoint, body=None, params=None): url = "{url}acs/api/v1{endpoint}".format( url=params['dcos_credentials']['url'], endpoint=endpoint) headers = { 'Content-Type': 'application/json', 'Authorization': "token={}".format(params['dcos_credentials']['token']), } verify = params.get('ssl_verify', True) if method == 'GET': response = requests.get(url, headers=headers, verify=verify) elif method == 'PUT': response = requests.put(url, json=body, headers=headers, verify=verify) elif method == 'PATCH': response = requests.patch(url, json=body, headers=headers, verify=verify) elif method == 'DELETE': response = requests.delete(url, headers=headers, verify=verify) try: response_json = response.json() except: response_json = {} return { 'url': url, 'status_code': response.status_code, 'text': response.text, 'json': response_json, 'request_body': body, 'request_headers': headers, } <commit_msg>Fix for urls with user/pass<commit_after>import requests import urlparse def dcos_api(method, endpoint, body=None, params=None): result = urlparse.urlsplit(params['dcos_credentials']['url']) netloc = result.netloc.split('@')[-1] result = result._replace(netloc=netloc) path = "acs/api/v1{endpoint}".format(endpoint=endpoint) result = result._replace(path=path) url = urlparse.urlunsplit(result) headers = { 'Content-Type': 'application/json', 'Authorization': "token={}".format(params['dcos_credentials']['token']), } verify = params.get('ssl_verify', True) if method == 'GET': response = requests.get(url, headers=headers, verify=verify) elif method == 'PUT': response = requests.put(url, json=body, headers=headers, verify=verify) elif method == 'PATCH': response = requests.patch(url, json=body, headers=headers, verify=verify) elif method == 'DELETE': response = requests.delete(url, headers=headers, verify=verify) try: response_json = response.json() except: response_json = {} return { 'url': url, 'status_code': response.status_code, 'text': response.text, 'json': response_json, 'request_body': body, 'request_headers': headers, }
027c7ba3036540f678ea757fa20dcb46edb079dc
mozillians/users/migrations/0038_auto_20180815_0108.py
mozillians/users/migrations/0038_auto_20180815_0108.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2018-08-15 08:08 from __future__ import unicode_literals from django.db import migrations from django.conf import settings def add_missing_employee_vouches(apps, schema_editor): UserProfile = apps.get_model('users', 'UserProfile') IdpProfile = apps.get_model('users', 'IdpProfile') for profile in UserProfile.objects.all(): emails = [idp.email for idp in IdpProfile.objects.filter(profile=profile)] email_exists = any([email for email in set(emails) if email.split('@')[1] in settings.AUTO_VOUCH_DOMAINS]) if email_exists and not profile.vouches_received.filter( description=settings.AUTO_VOUCH_REASON, autovouch=True).exists(): profile.vouch(None, settings.AUTO_VOUCH_REASON, autovouch=True) def backwards(apps, schema_editor): pass class Migration(migrations.Migration): dependencies = [ ('users', '0037_auto_20180720_0305'), ] operations = [ migrations.RunPython(add_missing_employee_vouches, backwards), ]
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2018-08-15 08:08 from __future__ import unicode_literals from django.db import migrations from django.conf import settings from django.utils.timezone import now def add_missing_employee_vouches(apps, schema_editor): UserProfile = apps.get_model('users', 'UserProfile') IdpProfile = apps.get_model('users', 'IdpProfile') for profile in UserProfile.objects.all(): emails = [idp.email for idp in IdpProfile.objects.filter(profile=profile)] email_exists = any([email for email in set(emails) if email.split('@')[1] in settings.AUTO_VOUCH_DOMAINS]) if email_exists and not profile.vouches_received.filter( description=settings.AUTO_VOUCH_REASON, autovouch=True).exists(): profile.vouches_received.create( voucher=None, date=now(), description=settings.AUTO_VOUCH_REASON, autovouch=True ) def backwards(apps, schema_editor): pass class Migration(migrations.Migration): dependencies = [ ('users', '0037_auto_20180720_0305'), ] operations = [ migrations.RunPython(add_missing_employee_vouches, backwards), ]
Fix datamigration definition, model methods not available when migrating.
Fix datamigration definition, model methods not available when migrating.
Python
bsd-3-clause
akatsoulas/mozillians,mozilla/mozillians,akatsoulas/mozillians,mozilla/mozillians,akatsoulas/mozillians,mozilla/mozillians,akatsoulas/mozillians,mozilla/mozillians
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2018-08-15 08:08 from __future__ import unicode_literals from django.db import migrations from django.conf import settings def add_missing_employee_vouches(apps, schema_editor): UserProfile = apps.get_model('users', 'UserProfile') IdpProfile = apps.get_model('users', 'IdpProfile') for profile in UserProfile.objects.all(): emails = [idp.email for idp in IdpProfile.objects.filter(profile=profile)] email_exists = any([email for email in set(emails) if email.split('@')[1] in settings.AUTO_VOUCH_DOMAINS]) if email_exists and not profile.vouches_received.filter( description=settings.AUTO_VOUCH_REASON, autovouch=True).exists(): profile.vouch(None, settings.AUTO_VOUCH_REASON, autovouch=True) def backwards(apps, schema_editor): pass class Migration(migrations.Migration): dependencies = [ ('users', '0037_auto_20180720_0305'), ] operations = [ migrations.RunPython(add_missing_employee_vouches, backwards), ] Fix datamigration definition, model methods not available when migrating.
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2018-08-15 08:08 from __future__ import unicode_literals from django.db import migrations from django.conf import settings from django.utils.timezone import now def add_missing_employee_vouches(apps, schema_editor): UserProfile = apps.get_model('users', 'UserProfile') IdpProfile = apps.get_model('users', 'IdpProfile') for profile in UserProfile.objects.all(): emails = [idp.email for idp in IdpProfile.objects.filter(profile=profile)] email_exists = any([email for email in set(emails) if email.split('@')[1] in settings.AUTO_VOUCH_DOMAINS]) if email_exists and not profile.vouches_received.filter( description=settings.AUTO_VOUCH_REASON, autovouch=True).exists(): profile.vouches_received.create( voucher=None, date=now(), description=settings.AUTO_VOUCH_REASON, autovouch=True ) def backwards(apps, schema_editor): pass class Migration(migrations.Migration): dependencies = [ ('users', '0037_auto_20180720_0305'), ] operations = [ migrations.RunPython(add_missing_employee_vouches, backwards), ]
<commit_before># -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2018-08-15 08:08 from __future__ import unicode_literals from django.db import migrations from django.conf import settings def add_missing_employee_vouches(apps, schema_editor): UserProfile = apps.get_model('users', 'UserProfile') IdpProfile = apps.get_model('users', 'IdpProfile') for profile in UserProfile.objects.all(): emails = [idp.email for idp in IdpProfile.objects.filter(profile=profile)] email_exists = any([email for email in set(emails) if email.split('@')[1] in settings.AUTO_VOUCH_DOMAINS]) if email_exists and not profile.vouches_received.filter( description=settings.AUTO_VOUCH_REASON, autovouch=True).exists(): profile.vouch(None, settings.AUTO_VOUCH_REASON, autovouch=True) def backwards(apps, schema_editor): pass class Migration(migrations.Migration): dependencies = [ ('users', '0037_auto_20180720_0305'), ] operations = [ migrations.RunPython(add_missing_employee_vouches, backwards), ] <commit_msg>Fix datamigration definition, model methods not available when migrating.<commit_after>
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2018-08-15 08:08 from __future__ import unicode_literals from django.db import migrations from django.conf import settings from django.utils.timezone import now def add_missing_employee_vouches(apps, schema_editor): UserProfile = apps.get_model('users', 'UserProfile') IdpProfile = apps.get_model('users', 'IdpProfile') for profile in UserProfile.objects.all(): emails = [idp.email for idp in IdpProfile.objects.filter(profile=profile)] email_exists = any([email for email in set(emails) if email.split('@')[1] in settings.AUTO_VOUCH_DOMAINS]) if email_exists and not profile.vouches_received.filter( description=settings.AUTO_VOUCH_REASON, autovouch=True).exists(): profile.vouches_received.create( voucher=None, date=now(), description=settings.AUTO_VOUCH_REASON, autovouch=True ) def backwards(apps, schema_editor): pass class Migration(migrations.Migration): dependencies = [ ('users', '0037_auto_20180720_0305'), ] operations = [ migrations.RunPython(add_missing_employee_vouches, backwards), ]
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2018-08-15 08:08 from __future__ import unicode_literals from django.db import migrations from django.conf import settings def add_missing_employee_vouches(apps, schema_editor): UserProfile = apps.get_model('users', 'UserProfile') IdpProfile = apps.get_model('users', 'IdpProfile') for profile in UserProfile.objects.all(): emails = [idp.email for idp in IdpProfile.objects.filter(profile=profile)] email_exists = any([email for email in set(emails) if email.split('@')[1] in settings.AUTO_VOUCH_DOMAINS]) if email_exists and not profile.vouches_received.filter( description=settings.AUTO_VOUCH_REASON, autovouch=True).exists(): profile.vouch(None, settings.AUTO_VOUCH_REASON, autovouch=True) def backwards(apps, schema_editor): pass class Migration(migrations.Migration): dependencies = [ ('users', '0037_auto_20180720_0305'), ] operations = [ migrations.RunPython(add_missing_employee_vouches, backwards), ] Fix datamigration definition, model methods not available when migrating.# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2018-08-15 08:08 from __future__ import unicode_literals from django.db import migrations from django.conf import settings from django.utils.timezone import now def add_missing_employee_vouches(apps, schema_editor): UserProfile = apps.get_model('users', 'UserProfile') IdpProfile = apps.get_model('users', 'IdpProfile') for profile in UserProfile.objects.all(): emails = [idp.email for idp in IdpProfile.objects.filter(profile=profile)] email_exists = any([email for email in set(emails) if email.split('@')[1] in settings.AUTO_VOUCH_DOMAINS]) if email_exists and not profile.vouches_received.filter( description=settings.AUTO_VOUCH_REASON, autovouch=True).exists(): profile.vouches_received.create( voucher=None, date=now(), description=settings.AUTO_VOUCH_REASON, autovouch=True ) def backwards(apps, schema_editor): pass class Migration(migrations.Migration): dependencies = [ ('users', '0037_auto_20180720_0305'), ] operations = [ migrations.RunPython(add_missing_employee_vouches, backwards), ]
<commit_before># -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2018-08-15 08:08 from __future__ import unicode_literals from django.db import migrations from django.conf import settings def add_missing_employee_vouches(apps, schema_editor): UserProfile = apps.get_model('users', 'UserProfile') IdpProfile = apps.get_model('users', 'IdpProfile') for profile in UserProfile.objects.all(): emails = [idp.email for idp in IdpProfile.objects.filter(profile=profile)] email_exists = any([email for email in set(emails) if email.split('@')[1] in settings.AUTO_VOUCH_DOMAINS]) if email_exists and not profile.vouches_received.filter( description=settings.AUTO_VOUCH_REASON, autovouch=True).exists(): profile.vouch(None, settings.AUTO_VOUCH_REASON, autovouch=True) def backwards(apps, schema_editor): pass class Migration(migrations.Migration): dependencies = [ ('users', '0037_auto_20180720_0305'), ] operations = [ migrations.RunPython(add_missing_employee_vouches, backwards), ] <commit_msg>Fix datamigration definition, model methods not available when migrating.<commit_after># -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2018-08-15 08:08 from __future__ import unicode_literals from django.db import migrations from django.conf import settings from django.utils.timezone import now def add_missing_employee_vouches(apps, schema_editor): UserProfile = apps.get_model('users', 'UserProfile') IdpProfile = apps.get_model('users', 'IdpProfile') for profile in UserProfile.objects.all(): emails = [idp.email for idp in IdpProfile.objects.filter(profile=profile)] email_exists = any([email for email in set(emails) if email.split('@')[1] in settings.AUTO_VOUCH_DOMAINS]) if email_exists and not profile.vouches_received.filter( description=settings.AUTO_VOUCH_REASON, autovouch=True).exists(): profile.vouches_received.create( voucher=None, date=now(), description=settings.AUTO_VOUCH_REASON, autovouch=True ) def backwards(apps, schema_editor): pass class Migration(migrations.Migration): dependencies = [ ('users', '0037_auto_20180720_0305'), ] operations = [ migrations.RunPython(add_missing_employee_vouches, backwards), ]
81768b4a3ae0afc71ab7e07f0d3c45eaf0d1b5a7
Importacions_F1_Q1/Fact_impF1_eliminar_Ja_existeix.py
Importacions_F1_Q1/Fact_impF1_eliminar_Ja_existeix.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from ooop import OOOP import configdb O = OOOP(**configdb.ooop) imp_obj = O.GiscedataFacturacioImportacioLinia imp_del_ids = imp_obj.search([('state','=','erroni'),('info','like','Ja existeix una factura')]) imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like','XML erroni')]) imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like',"XML no es correspon al tipus F1")]) imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like',"Document invàlid")]) total = len(imp_del_ids) n = 0 for imp_del_id in imp_del_ids: try: imp_obj.unlink([imp_del_id]) n +=1 print "%d/%d" % (n,total) except Exception, e: print e
#!/usr/bin/env python # -*- coding: utf-8 -*- from ooop import OOOP import configdb O = OOOP(**configdb.ooop) imp_obj = O.GiscedataFacturacioImportacioLinia imp_del_ids = imp_obj.search([('state','=','erroni'),('info','like',"Aquest fitxer XML ja s'ha processat en els següents IDs")]) #imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like','XML erroni')]) imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like',"XML no es correspon al tipus F1")]) imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like',"Document invàlid")]) total = len(imp_del_ids) n = 0 for imp_del_id in imp_del_ids: try: imp_obj.unlink([imp_del_id]) n +=1 print "%d/%d" % (n,total) except Exception, e: print e
Refactor to new F1 erro's message
Refactor to new F1 erro's message
Python
agpl-3.0
Som-Energia/invoice-janitor
#!/usr/bin/env python # -*- coding: utf-8 -*- from ooop import OOOP import configdb O = OOOP(**configdb.ooop) imp_obj = O.GiscedataFacturacioImportacioLinia imp_del_ids = imp_obj.search([('state','=','erroni'),('info','like','Ja existeix una factura')]) imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like','XML erroni')]) imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like',"XML no es correspon al tipus F1")]) imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like',"Document invàlid")]) total = len(imp_del_ids) n = 0 for imp_del_id in imp_del_ids: try: imp_obj.unlink([imp_del_id]) n +=1 print "%d/%d" % (n,total) except Exception, e: print e Refactor to new F1 erro's message
#!/usr/bin/env python # -*- coding: utf-8 -*- from ooop import OOOP import configdb O = OOOP(**configdb.ooop) imp_obj = O.GiscedataFacturacioImportacioLinia imp_del_ids = imp_obj.search([('state','=','erroni'),('info','like',"Aquest fitxer XML ja s'ha processat en els següents IDs")]) #imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like','XML erroni')]) imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like',"XML no es correspon al tipus F1")]) imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like',"Document invàlid")]) total = len(imp_del_ids) n = 0 for imp_del_id in imp_del_ids: try: imp_obj.unlink([imp_del_id]) n +=1 print "%d/%d" % (n,total) except Exception, e: print e
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- from ooop import OOOP import configdb O = OOOP(**configdb.ooop) imp_obj = O.GiscedataFacturacioImportacioLinia imp_del_ids = imp_obj.search([('state','=','erroni'),('info','like','Ja existeix una factura')]) imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like','XML erroni')]) imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like',"XML no es correspon al tipus F1")]) imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like',"Document invàlid")]) total = len(imp_del_ids) n = 0 for imp_del_id in imp_del_ids: try: imp_obj.unlink([imp_del_id]) n +=1 print "%d/%d" % (n,total) except Exception, e: print e <commit_msg>Refactor to new F1 erro's message<commit_after>
#!/usr/bin/env python # -*- coding: utf-8 -*- from ooop import OOOP import configdb O = OOOP(**configdb.ooop) imp_obj = O.GiscedataFacturacioImportacioLinia imp_del_ids = imp_obj.search([('state','=','erroni'),('info','like',"Aquest fitxer XML ja s'ha processat en els següents IDs")]) #imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like','XML erroni')]) imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like',"XML no es correspon al tipus F1")]) imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like',"Document invàlid")]) total = len(imp_del_ids) n = 0 for imp_del_id in imp_del_ids: try: imp_obj.unlink([imp_del_id]) n +=1 print "%d/%d" % (n,total) except Exception, e: print e
#!/usr/bin/env python # -*- coding: utf-8 -*- from ooop import OOOP import configdb O = OOOP(**configdb.ooop) imp_obj = O.GiscedataFacturacioImportacioLinia imp_del_ids = imp_obj.search([('state','=','erroni'),('info','like','Ja existeix una factura')]) imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like','XML erroni')]) imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like',"XML no es correspon al tipus F1")]) imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like',"Document invàlid")]) total = len(imp_del_ids) n = 0 for imp_del_id in imp_del_ids: try: imp_obj.unlink([imp_del_id]) n +=1 print "%d/%d" % (n,total) except Exception, e: print e Refactor to new F1 erro's message#!/usr/bin/env python # -*- coding: utf-8 -*- from ooop import OOOP import configdb O = OOOP(**configdb.ooop) imp_obj = O.GiscedataFacturacioImportacioLinia imp_del_ids = imp_obj.search([('state','=','erroni'),('info','like',"Aquest fitxer XML ja s'ha processat en els següents IDs")]) #imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like','XML erroni')]) imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like',"XML no es correspon al tipus F1")]) imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like',"Document invàlid")]) total = len(imp_del_ids) n = 0 for imp_del_id in imp_del_ids: try: imp_obj.unlink([imp_del_id]) n +=1 print "%d/%d" % (n,total) except Exception, e: print e
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- from ooop import OOOP import configdb O = OOOP(**configdb.ooop) imp_obj = O.GiscedataFacturacioImportacioLinia imp_del_ids = imp_obj.search([('state','=','erroni'),('info','like','Ja existeix una factura')]) imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like','XML erroni')]) imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like',"XML no es correspon al tipus F1")]) imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like',"Document invàlid")]) total = len(imp_del_ids) n = 0 for imp_del_id in imp_del_ids: try: imp_obj.unlink([imp_del_id]) n +=1 print "%d/%d" % (n,total) except Exception, e: print e <commit_msg>Refactor to new F1 erro's message<commit_after>#!/usr/bin/env python # -*- coding: utf-8 -*- from ooop import OOOP import configdb O = OOOP(**configdb.ooop) imp_obj = O.GiscedataFacturacioImportacioLinia imp_del_ids = imp_obj.search([('state','=','erroni'),('info','like',"Aquest fitxer XML ja s'ha processat en els següents IDs")]) #imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like','XML erroni')]) imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like',"XML no es correspon al tipus F1")]) imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like',"Document invàlid")]) total = len(imp_del_ids) n = 0 for imp_del_id in imp_del_ids: try: imp_obj.unlink([imp_del_id]) n +=1 print "%d/%d" % (n,total) except Exception, e: print e
0974a39c758a4ff3282e5441568befa79e50ead4
plugins/twilio/twilio_sms.py
plugins/twilio/twilio_sms.py
from twilio.rest import TwilioRestClient from alerta.app import app from alerta.plugins import PluginBase LOG = app.logger TWILIO_ACCOUNT_SID = 'ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' TWILIO_AUTH_TOKEN = '' TWILIO_TO_NUMBER = '' TWILIO_FROM_NUMBER = '' class SendSMSMessage(PluginBase): def pre_receive(self, alert): return alert def post_receive(self, alert): if alert.repeat: return message = "%s: %s alert for %s - %s is %s" % ( alert.environment, alert.severity.capitalize(), ','.join(alert.service), alert.resource, alert.event ) client = TwilioRestClient(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN) message = client.messages.create(body=message, to=TWILIO_TO_NUMBER, from_=TWILIO_FROM_NUMBER) LOG.info("Twilio SMS Message ID: %s", message.sid)
import os from twilio.rest import TwilioRestClient from alerta.app import app from alerta.plugins import PluginBase LOG = app.logger TWILIO_ACCOUNT_SID = os.environ.get('TWILIO_ACCOUNT_SID') TWILIO_AUTH_TOKEN = os.environ.get('TWILIO_AUTH_TOKEN') TWILIO_TO_NUMBER = os.environ.get('TWILIO_TO_NUMBER') TWILIO_FROM_NUMBER = os.environ.get('TWILIO_FROM_NUMBER') class SendSMSMessage(PluginBase): def pre_receive(self, alert): return alert def post_receive(self, alert): if alert.repeat: return message = "%s: %s alert for %s - %s is %s" % ( alert.environment, alert.severity.capitalize(), ','.join(alert.service), alert.resource, alert.event ) client = TwilioRestClient(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN) message = client.messages.create(body=message, to=TWILIO_TO_NUMBER, from_=TWILIO_FROM_NUMBER) LOG.info("Twilio SMS Message ID: %s", message.sid)
Use env vars to config twilio sms plugin
Use env vars to config twilio sms plugin
Python
mit
alerta/alerta-contrib,alerta/alerta-contrib,msupino/alerta-contrib,alerta/alerta-contrib,msupino/alerta-contrib
from twilio.rest import TwilioRestClient from alerta.app import app from alerta.plugins import PluginBase LOG = app.logger TWILIO_ACCOUNT_SID = 'ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' TWILIO_AUTH_TOKEN = '' TWILIO_TO_NUMBER = '' TWILIO_FROM_NUMBER = '' class SendSMSMessage(PluginBase): def pre_receive(self, alert): return alert def post_receive(self, alert): if alert.repeat: return message = "%s: %s alert for %s - %s is %s" % ( alert.environment, alert.severity.capitalize(), ','.join(alert.service), alert.resource, alert.event ) client = TwilioRestClient(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN) message = client.messages.create(body=message, to=TWILIO_TO_NUMBER, from_=TWILIO_FROM_NUMBER) LOG.info("Twilio SMS Message ID: %s", message.sid) Use env vars to config twilio sms plugin
import os from twilio.rest import TwilioRestClient from alerta.app import app from alerta.plugins import PluginBase LOG = app.logger TWILIO_ACCOUNT_SID = os.environ.get('TWILIO_ACCOUNT_SID') TWILIO_AUTH_TOKEN = os.environ.get('TWILIO_AUTH_TOKEN') TWILIO_TO_NUMBER = os.environ.get('TWILIO_TO_NUMBER') TWILIO_FROM_NUMBER = os.environ.get('TWILIO_FROM_NUMBER') class SendSMSMessage(PluginBase): def pre_receive(self, alert): return alert def post_receive(self, alert): if alert.repeat: return message = "%s: %s alert for %s - %s is %s" % ( alert.environment, alert.severity.capitalize(), ','.join(alert.service), alert.resource, alert.event ) client = TwilioRestClient(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN) message = client.messages.create(body=message, to=TWILIO_TO_NUMBER, from_=TWILIO_FROM_NUMBER) LOG.info("Twilio SMS Message ID: %s", message.sid)
<commit_before> from twilio.rest import TwilioRestClient from alerta.app import app from alerta.plugins import PluginBase LOG = app.logger TWILIO_ACCOUNT_SID = 'ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' TWILIO_AUTH_TOKEN = '' TWILIO_TO_NUMBER = '' TWILIO_FROM_NUMBER = '' class SendSMSMessage(PluginBase): def pre_receive(self, alert): return alert def post_receive(self, alert): if alert.repeat: return message = "%s: %s alert for %s - %s is %s" % ( alert.environment, alert.severity.capitalize(), ','.join(alert.service), alert.resource, alert.event ) client = TwilioRestClient(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN) message = client.messages.create(body=message, to=TWILIO_TO_NUMBER, from_=TWILIO_FROM_NUMBER) LOG.info("Twilio SMS Message ID: %s", message.sid) <commit_msg>Use env vars to config twilio sms plugin<commit_after>
import os from twilio.rest import TwilioRestClient from alerta.app import app from alerta.plugins import PluginBase LOG = app.logger TWILIO_ACCOUNT_SID = os.environ.get('TWILIO_ACCOUNT_SID') TWILIO_AUTH_TOKEN = os.environ.get('TWILIO_AUTH_TOKEN') TWILIO_TO_NUMBER = os.environ.get('TWILIO_TO_NUMBER') TWILIO_FROM_NUMBER = os.environ.get('TWILIO_FROM_NUMBER') class SendSMSMessage(PluginBase): def pre_receive(self, alert): return alert def post_receive(self, alert): if alert.repeat: return message = "%s: %s alert for %s - %s is %s" % ( alert.environment, alert.severity.capitalize(), ','.join(alert.service), alert.resource, alert.event ) client = TwilioRestClient(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN) message = client.messages.create(body=message, to=TWILIO_TO_NUMBER, from_=TWILIO_FROM_NUMBER) LOG.info("Twilio SMS Message ID: %s", message.sid)
from twilio.rest import TwilioRestClient from alerta.app import app from alerta.plugins import PluginBase LOG = app.logger TWILIO_ACCOUNT_SID = 'ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' TWILIO_AUTH_TOKEN = '' TWILIO_TO_NUMBER = '' TWILIO_FROM_NUMBER = '' class SendSMSMessage(PluginBase): def pre_receive(self, alert): return alert def post_receive(self, alert): if alert.repeat: return message = "%s: %s alert for %s - %s is %s" % ( alert.environment, alert.severity.capitalize(), ','.join(alert.service), alert.resource, alert.event ) client = TwilioRestClient(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN) message = client.messages.create(body=message, to=TWILIO_TO_NUMBER, from_=TWILIO_FROM_NUMBER) LOG.info("Twilio SMS Message ID: %s", message.sid) Use env vars to config twilio sms plugin import os from twilio.rest import TwilioRestClient from alerta.app import app from alerta.plugins import PluginBase LOG = app.logger TWILIO_ACCOUNT_SID = os.environ.get('TWILIO_ACCOUNT_SID') TWILIO_AUTH_TOKEN = os.environ.get('TWILIO_AUTH_TOKEN') TWILIO_TO_NUMBER = os.environ.get('TWILIO_TO_NUMBER') TWILIO_FROM_NUMBER = os.environ.get('TWILIO_FROM_NUMBER') class SendSMSMessage(PluginBase): def pre_receive(self, alert): return alert def post_receive(self, alert): if alert.repeat: return message = "%s: %s alert for %s - %s is %s" % ( alert.environment, alert.severity.capitalize(), ','.join(alert.service), alert.resource, alert.event ) client = TwilioRestClient(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN) message = client.messages.create(body=message, to=TWILIO_TO_NUMBER, from_=TWILIO_FROM_NUMBER) LOG.info("Twilio SMS Message ID: %s", message.sid)
<commit_before> from twilio.rest import TwilioRestClient from alerta.app import app from alerta.plugins import PluginBase LOG = app.logger TWILIO_ACCOUNT_SID = 'ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' TWILIO_AUTH_TOKEN = '' TWILIO_TO_NUMBER = '' TWILIO_FROM_NUMBER = '' class SendSMSMessage(PluginBase): def pre_receive(self, alert): return alert def post_receive(self, alert): if alert.repeat: return message = "%s: %s alert for %s - %s is %s" % ( alert.environment, alert.severity.capitalize(), ','.join(alert.service), alert.resource, alert.event ) client = TwilioRestClient(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN) message = client.messages.create(body=message, to=TWILIO_TO_NUMBER, from_=TWILIO_FROM_NUMBER) LOG.info("Twilio SMS Message ID: %s", message.sid) <commit_msg>Use env vars to config twilio sms plugin<commit_after> import os from twilio.rest import TwilioRestClient from alerta.app import app from alerta.plugins import PluginBase LOG = app.logger TWILIO_ACCOUNT_SID = os.environ.get('TWILIO_ACCOUNT_SID') TWILIO_AUTH_TOKEN = os.environ.get('TWILIO_AUTH_TOKEN') TWILIO_TO_NUMBER = os.environ.get('TWILIO_TO_NUMBER') TWILIO_FROM_NUMBER = os.environ.get('TWILIO_FROM_NUMBER') class SendSMSMessage(PluginBase): def pre_receive(self, alert): return alert def post_receive(self, alert): if alert.repeat: return message = "%s: %s alert for %s - %s is %s" % ( alert.environment, alert.severity.capitalize(), ','.join(alert.service), alert.resource, alert.event ) client = TwilioRestClient(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN) message = client.messages.create(body=message, to=TWILIO_TO_NUMBER, from_=TWILIO_FROM_NUMBER) LOG.info("Twilio SMS Message ID: %s", message.sid)
a4cffc0e74f9dd972357eb9dc49a57e10f1fe944
core/forms.py
core/forms.py
from collections import namedtuple from django import forms IMAGE = "img" UploadType = namedtuple("UploadType", ["directory", "label"]) FILE_TYPE_CHOICES = ( UploadType(directory=IMAGE, label="Image"), UploadType(directory="thumb", label="Thumbnail"), UploadType(directory="doc", label="Document"), UploadType(directory="code", label="Code"), UploadType(directory="pres", label="Presentation"), ) class UploadForm(forms.Form): upload_file = forms.FileField() upload_type = forms.ChoiceField(choices=FILE_TYPE_CHOICES, initial=IMAGE)
from collections import namedtuple from django import forms IMAGE = "img" UploadType = namedtuple("UploadType", ["directory", "label"]) FILE_TYPE_CHOICES = ( UploadType(directory=IMAGE, label="Image"), UploadType(directory="thumb", label="Thumbnail"), UploadType(directory="doc", label="Document"), UploadType(directory="code", label="Code"), UploadType(directory="pres", label="Presentation"), ) class UploadForm(forms.Form): upload_file = forms.FileField() upload_type = forms.ChoiceField(choices=FILE_TYPE_CHOICES, initial=IMAGE) def clean_upload_file(self): data = self.cleaned_data["upload_file"] if " " in data.name: raise forms.ValidationError("Spaces in filename not allowed") return data
Check names of files for spaces
Check names of files for spaces
Python
bsd-3-clause
ahernp/DMCM,ahernp/DMCM,ahernp/DMCM
from collections import namedtuple from django import forms IMAGE = "img" UploadType = namedtuple("UploadType", ["directory", "label"]) FILE_TYPE_CHOICES = ( UploadType(directory=IMAGE, label="Image"), UploadType(directory="thumb", label="Thumbnail"), UploadType(directory="doc", label="Document"), UploadType(directory="code", label="Code"), UploadType(directory="pres", label="Presentation"), ) class UploadForm(forms.Form): upload_file = forms.FileField() upload_type = forms.ChoiceField(choices=FILE_TYPE_CHOICES, initial=IMAGE) Check names of files for spaces
from collections import namedtuple from django import forms IMAGE = "img" UploadType = namedtuple("UploadType", ["directory", "label"]) FILE_TYPE_CHOICES = ( UploadType(directory=IMAGE, label="Image"), UploadType(directory="thumb", label="Thumbnail"), UploadType(directory="doc", label="Document"), UploadType(directory="code", label="Code"), UploadType(directory="pres", label="Presentation"), ) class UploadForm(forms.Form): upload_file = forms.FileField() upload_type = forms.ChoiceField(choices=FILE_TYPE_CHOICES, initial=IMAGE) def clean_upload_file(self): data = self.cleaned_data["upload_file"] if " " in data.name: raise forms.ValidationError("Spaces in filename not allowed") return data
<commit_before>from collections import namedtuple from django import forms IMAGE = "img" UploadType = namedtuple("UploadType", ["directory", "label"]) FILE_TYPE_CHOICES = ( UploadType(directory=IMAGE, label="Image"), UploadType(directory="thumb", label="Thumbnail"), UploadType(directory="doc", label="Document"), UploadType(directory="code", label="Code"), UploadType(directory="pres", label="Presentation"), ) class UploadForm(forms.Form): upload_file = forms.FileField() upload_type = forms.ChoiceField(choices=FILE_TYPE_CHOICES, initial=IMAGE) <commit_msg>Check names of files for spaces<commit_after>
from collections import namedtuple from django import forms IMAGE = "img" UploadType = namedtuple("UploadType", ["directory", "label"]) FILE_TYPE_CHOICES = ( UploadType(directory=IMAGE, label="Image"), UploadType(directory="thumb", label="Thumbnail"), UploadType(directory="doc", label="Document"), UploadType(directory="code", label="Code"), UploadType(directory="pres", label="Presentation"), ) class UploadForm(forms.Form): upload_file = forms.FileField() upload_type = forms.ChoiceField(choices=FILE_TYPE_CHOICES, initial=IMAGE) def clean_upload_file(self): data = self.cleaned_data["upload_file"] if " " in data.name: raise forms.ValidationError("Spaces in filename not allowed") return data
from collections import namedtuple from django import forms IMAGE = "img" UploadType = namedtuple("UploadType", ["directory", "label"]) FILE_TYPE_CHOICES = ( UploadType(directory=IMAGE, label="Image"), UploadType(directory="thumb", label="Thumbnail"), UploadType(directory="doc", label="Document"), UploadType(directory="code", label="Code"), UploadType(directory="pres", label="Presentation"), ) class UploadForm(forms.Form): upload_file = forms.FileField() upload_type = forms.ChoiceField(choices=FILE_TYPE_CHOICES, initial=IMAGE) Check names of files for spacesfrom collections import namedtuple from django import forms IMAGE = "img" UploadType = namedtuple("UploadType", ["directory", "label"]) FILE_TYPE_CHOICES = ( UploadType(directory=IMAGE, label="Image"), UploadType(directory="thumb", label="Thumbnail"), UploadType(directory="doc", label="Document"), UploadType(directory="code", label="Code"), UploadType(directory="pres", label="Presentation"), ) class UploadForm(forms.Form): upload_file = forms.FileField() upload_type = forms.ChoiceField(choices=FILE_TYPE_CHOICES, initial=IMAGE) def clean_upload_file(self): data = self.cleaned_data["upload_file"] if " " in data.name: raise forms.ValidationError("Spaces in filename not allowed") return data
<commit_before>from collections import namedtuple from django import forms IMAGE = "img" UploadType = namedtuple("UploadType", ["directory", "label"]) FILE_TYPE_CHOICES = ( UploadType(directory=IMAGE, label="Image"), UploadType(directory="thumb", label="Thumbnail"), UploadType(directory="doc", label="Document"), UploadType(directory="code", label="Code"), UploadType(directory="pres", label="Presentation"), ) class UploadForm(forms.Form): upload_file = forms.FileField() upload_type = forms.ChoiceField(choices=FILE_TYPE_CHOICES, initial=IMAGE) <commit_msg>Check names of files for spaces<commit_after>from collections import namedtuple from django import forms IMAGE = "img" UploadType = namedtuple("UploadType", ["directory", "label"]) FILE_TYPE_CHOICES = ( UploadType(directory=IMAGE, label="Image"), UploadType(directory="thumb", label="Thumbnail"), UploadType(directory="doc", label="Document"), UploadType(directory="code", label="Code"), UploadType(directory="pres", label="Presentation"), ) class UploadForm(forms.Form): upload_file = forms.FileField() upload_type = forms.ChoiceField(choices=FILE_TYPE_CHOICES, initial=IMAGE) def clean_upload_file(self): data = self.cleaned_data["upload_file"] if " " in data.name: raise forms.ValidationError("Spaces in filename not allowed") return data
63ef169253dbf4f9673880bccc29d97e62fdf19d
astropy/tests/image_tests.py
astropy/tests/image_tests.py
import matplotlib from matplotlib import pyplot as plt from ..utils.decorators import wraps MPL_VERSION = matplotlib.__version__ ROOT = "http://{server}/testing/astropy/2018-02-01T23:31:45.013149/{mpl_version}/" IMAGE_REFERENCE_DIR = ROOT.format(server='astropy.github.io/astropy-data', mpl_version=MPL_VERSION[:3] + '.x') def ignore_matplotlibrc(func): # This is a decorator for tests that use matplotlib but not pytest-mpl # (which already handles rcParams) @wraps(func) def wrapper(*args, **kwargs): with plt.style.context({}, after_reset=True): return func(*args, **kwargs) return wrapper
import matplotlib from matplotlib import pyplot as plt from ..utils.decorators import wraps MPL_VERSION = matplotlib.__version__ ROOT = "http://{server}/testing/astropy/2018-02-01T23:31:45.013149/{mpl_version}/" IMAGE_REFERENCE_DIR = ROOT.format(server='data.astropy.org', mpl_version=MPL_VERSION[:3] + '.x') def ignore_matplotlibrc(func): # This is a decorator for tests that use matplotlib but not pytest-mpl # (which already handles rcParams) @wraps(func) def wrapper(*args, **kwargs): with plt.style.context({}, after_reset=True): return func(*args, **kwargs) return wrapper
Fix reference URL for images
Fix reference URL for images
Python
bsd-3-clause
pllim/astropy,larrybradley/astropy,bsipocz/astropy,StuartLittlefair/astropy,pllim/astropy,larrybradley/astropy,dhomeier/astropy,DougBurke/astropy,mhvk/astropy,saimn/astropy,larrybradley/astropy,dhomeier/astropy,lpsinger/astropy,MSeifert04/astropy,lpsinger/astropy,funbaker/astropy,DougBurke/astropy,saimn/astropy,StuartLittlefair/astropy,saimn/astropy,astropy/astropy,mhvk/astropy,astropy/astropy,lpsinger/astropy,stargaser/astropy,mhvk/astropy,StuartLittlefair/astropy,MSeifert04/astropy,DougBurke/astropy,astropy/astropy,pllim/astropy,pllim/astropy,stargaser/astropy,funbaker/astropy,mhvk/astropy,bsipocz/astropy,bsipocz/astropy,MSeifert04/astropy,MSeifert04/astropy,DougBurke/astropy,larrybradley/astropy,funbaker/astropy,astropy/astropy,aleksandr-bakanov/astropy,aleksandr-bakanov/astropy,saimn/astropy,aleksandr-bakanov/astropy,dhomeier/astropy,lpsinger/astropy,mhvk/astropy,dhomeier/astropy,dhomeier/astropy,pllim/astropy,StuartLittlefair/astropy,lpsinger/astropy,larrybradley/astropy,StuartLittlefair/astropy,funbaker/astropy,aleksandr-bakanov/astropy,bsipocz/astropy,stargaser/astropy,saimn/astropy,astropy/astropy,stargaser/astropy
import matplotlib from matplotlib import pyplot as plt from ..utils.decorators import wraps MPL_VERSION = matplotlib.__version__ ROOT = "http://{server}/testing/astropy/2018-02-01T23:31:45.013149/{mpl_version}/" IMAGE_REFERENCE_DIR = ROOT.format(server='astropy.github.io/astropy-data', mpl_version=MPL_VERSION[:3] + '.x') def ignore_matplotlibrc(func): # This is a decorator for tests that use matplotlib but not pytest-mpl # (which already handles rcParams) @wraps(func) def wrapper(*args, **kwargs): with plt.style.context({}, after_reset=True): return func(*args, **kwargs) return wrapper Fix reference URL for images
import matplotlib from matplotlib import pyplot as plt from ..utils.decorators import wraps MPL_VERSION = matplotlib.__version__ ROOT = "http://{server}/testing/astropy/2018-02-01T23:31:45.013149/{mpl_version}/" IMAGE_REFERENCE_DIR = ROOT.format(server='data.astropy.org', mpl_version=MPL_VERSION[:3] + '.x') def ignore_matplotlibrc(func): # This is a decorator for tests that use matplotlib but not pytest-mpl # (which already handles rcParams) @wraps(func) def wrapper(*args, **kwargs): with plt.style.context({}, after_reset=True): return func(*args, **kwargs) return wrapper
<commit_before>import matplotlib from matplotlib import pyplot as plt from ..utils.decorators import wraps MPL_VERSION = matplotlib.__version__ ROOT = "http://{server}/testing/astropy/2018-02-01T23:31:45.013149/{mpl_version}/" IMAGE_REFERENCE_DIR = ROOT.format(server='astropy.github.io/astropy-data', mpl_version=MPL_VERSION[:3] + '.x') def ignore_matplotlibrc(func): # This is a decorator for tests that use matplotlib but not pytest-mpl # (which already handles rcParams) @wraps(func) def wrapper(*args, **kwargs): with plt.style.context({}, after_reset=True): return func(*args, **kwargs) return wrapper <commit_msg>Fix reference URL for images<commit_after>
import matplotlib from matplotlib import pyplot as plt from ..utils.decorators import wraps MPL_VERSION = matplotlib.__version__ ROOT = "http://{server}/testing/astropy/2018-02-01T23:31:45.013149/{mpl_version}/" IMAGE_REFERENCE_DIR = ROOT.format(server='data.astropy.org', mpl_version=MPL_VERSION[:3] + '.x') def ignore_matplotlibrc(func): # This is a decorator for tests that use matplotlib but not pytest-mpl # (which already handles rcParams) @wraps(func) def wrapper(*args, **kwargs): with plt.style.context({}, after_reset=True): return func(*args, **kwargs) return wrapper
import matplotlib from matplotlib import pyplot as plt from ..utils.decorators import wraps MPL_VERSION = matplotlib.__version__ ROOT = "http://{server}/testing/astropy/2018-02-01T23:31:45.013149/{mpl_version}/" IMAGE_REFERENCE_DIR = ROOT.format(server='astropy.github.io/astropy-data', mpl_version=MPL_VERSION[:3] + '.x') def ignore_matplotlibrc(func): # This is a decorator for tests that use matplotlib but not pytest-mpl # (which already handles rcParams) @wraps(func) def wrapper(*args, **kwargs): with plt.style.context({}, after_reset=True): return func(*args, **kwargs) return wrapper Fix reference URL for imagesimport matplotlib from matplotlib import pyplot as plt from ..utils.decorators import wraps MPL_VERSION = matplotlib.__version__ ROOT = "http://{server}/testing/astropy/2018-02-01T23:31:45.013149/{mpl_version}/" IMAGE_REFERENCE_DIR = ROOT.format(server='data.astropy.org', mpl_version=MPL_VERSION[:3] + '.x') def ignore_matplotlibrc(func): # This is a decorator for tests that use matplotlib but not pytest-mpl # (which already handles rcParams) @wraps(func) def wrapper(*args, **kwargs): with plt.style.context({}, after_reset=True): return func(*args, **kwargs) return wrapper
<commit_before>import matplotlib from matplotlib import pyplot as plt from ..utils.decorators import wraps MPL_VERSION = matplotlib.__version__ ROOT = "http://{server}/testing/astropy/2018-02-01T23:31:45.013149/{mpl_version}/" IMAGE_REFERENCE_DIR = ROOT.format(server='astropy.github.io/astropy-data', mpl_version=MPL_VERSION[:3] + '.x') def ignore_matplotlibrc(func): # This is a decorator for tests that use matplotlib but not pytest-mpl # (which already handles rcParams) @wraps(func) def wrapper(*args, **kwargs): with plt.style.context({}, after_reset=True): return func(*args, **kwargs) return wrapper <commit_msg>Fix reference URL for images<commit_after>import matplotlib from matplotlib import pyplot as plt from ..utils.decorators import wraps MPL_VERSION = matplotlib.__version__ ROOT = "http://{server}/testing/astropy/2018-02-01T23:31:45.013149/{mpl_version}/" IMAGE_REFERENCE_DIR = ROOT.format(server='data.astropy.org', mpl_version=MPL_VERSION[:3] + '.x') def ignore_matplotlibrc(func): # This is a decorator for tests that use matplotlib but not pytest-mpl # (which already handles rcParams) @wraps(func) def wrapper(*args, **kwargs): with plt.style.context({}, after_reset=True): return func(*args, **kwargs) return wrapper
35fde537a48e4abbc98b065924fad784533cd4ee
jsonconfigparser/test/__init__.py
jsonconfigparser/test/__init__.py
import unittest from jsonconfigparser import JSONConfigParser class JSONConfigTestCase(unittest.TestCase): def test_init(self): JSONConfigParser() def test_read_string(self): string = '[section]\n' + \ '# comment comment\n' + \ 'foo = "bar"\n' + \ '\n' + \ '[section2]\n' + \ 'bar = "baz"\n' cf = JSONConfigParser() cf.read_string(string) self.assertEqual(cf.get('section', 'foo'), 'bar') def test_get(self): cf = JSONConfigParser() cf.add_section('section') cf.set('section', 'section', 'set-in-section') self.assertEqual(cf.get('section', 'section'), 'set-in-section') cf.set(cf.default_section, 'defaults', 'set-in-defaults') self.assertEqual(cf.get('section', 'defaults'), 'set-in-defaults') self.assertEqual(cf.get('section', 'vars', vars={'vars': 'set-in-vars'}), 'set-in-vars') self.assertEqual(cf.get('section', 'unset', 'fallback'), 'fallback') suite = unittest.TestLoader().loadTestsFromTestCase(JSONConfigTestCase)
import unittest import tempfile from jsonconfigparser import JSONConfigParser class JSONConfigTestCase(unittest.TestCase): def test_init(self): JSONConfigParser() def test_read_string(self): string = '[section]\n' + \ '# comment comment\n' + \ 'foo = "bar"\n' + \ '\n' + \ '[section2]\n' + \ 'bar = "baz"\n' cf = JSONConfigParser() cf.read_string(string) self.assertEqual(cf.get('section', 'foo'), 'bar') def test_read_file(self): string = '[section]\n' + \ 'foo = "bar"' fp = tempfile.NamedTemporaryFile('w+') fp.write(string) fp.seek(0) cf = JSONConfigParser() cf.read_file(fp) self.assertEqual(cf.get('section', 'foo'), 'bar') def test_get(self): cf = JSONConfigParser() cf.add_section('section') cf.set('section', 'section', 'set-in-section') self.assertEqual(cf.get('section', 'section'), 'set-in-section') cf.set(cf.default_section, 'defaults', 'set-in-defaults') self.assertEqual(cf.get('section', 'defaults'), 'set-in-defaults') self.assertEqual(cf.get('section', 'vars', vars={'vars': 'set-in-vars'}), 'set-in-vars') self.assertEqual(cf.get('section', 'unset', 'fallback'), 'fallback') suite = unittest.TestLoader().loadTestsFromTestCase(JSONConfigTestCase)
Add basic test for read_file method
Add basic test for read_file method
Python
bsd-3-clause
bwhmather/json-config-parser
import unittest from jsonconfigparser import JSONConfigParser class JSONConfigTestCase(unittest.TestCase): def test_init(self): JSONConfigParser() def test_read_string(self): string = '[section]\n' + \ '# comment comment\n' + \ 'foo = "bar"\n' + \ '\n' + \ '[section2]\n' + \ 'bar = "baz"\n' cf = JSONConfigParser() cf.read_string(string) self.assertEqual(cf.get('section', 'foo'), 'bar') def test_get(self): cf = JSONConfigParser() cf.add_section('section') cf.set('section', 'section', 'set-in-section') self.assertEqual(cf.get('section', 'section'), 'set-in-section') cf.set(cf.default_section, 'defaults', 'set-in-defaults') self.assertEqual(cf.get('section', 'defaults'), 'set-in-defaults') self.assertEqual(cf.get('section', 'vars', vars={'vars': 'set-in-vars'}), 'set-in-vars') self.assertEqual(cf.get('section', 'unset', 'fallback'), 'fallback') suite = unittest.TestLoader().loadTestsFromTestCase(JSONConfigTestCase) Add basic test for read_file method
import unittest import tempfile from jsonconfigparser import JSONConfigParser class JSONConfigTestCase(unittest.TestCase): def test_init(self): JSONConfigParser() def test_read_string(self): string = '[section]\n' + \ '# comment comment\n' + \ 'foo = "bar"\n' + \ '\n' + \ '[section2]\n' + \ 'bar = "baz"\n' cf = JSONConfigParser() cf.read_string(string) self.assertEqual(cf.get('section', 'foo'), 'bar') def test_read_file(self): string = '[section]\n' + \ 'foo = "bar"' fp = tempfile.NamedTemporaryFile('w+') fp.write(string) fp.seek(0) cf = JSONConfigParser() cf.read_file(fp) self.assertEqual(cf.get('section', 'foo'), 'bar') def test_get(self): cf = JSONConfigParser() cf.add_section('section') cf.set('section', 'section', 'set-in-section') self.assertEqual(cf.get('section', 'section'), 'set-in-section') cf.set(cf.default_section, 'defaults', 'set-in-defaults') self.assertEqual(cf.get('section', 'defaults'), 'set-in-defaults') self.assertEqual(cf.get('section', 'vars', vars={'vars': 'set-in-vars'}), 'set-in-vars') self.assertEqual(cf.get('section', 'unset', 'fallback'), 'fallback') suite = unittest.TestLoader().loadTestsFromTestCase(JSONConfigTestCase)
<commit_before>import unittest from jsonconfigparser import JSONConfigParser class JSONConfigTestCase(unittest.TestCase): def test_init(self): JSONConfigParser() def test_read_string(self): string = '[section]\n' + \ '# comment comment\n' + \ 'foo = "bar"\n' + \ '\n' + \ '[section2]\n' + \ 'bar = "baz"\n' cf = JSONConfigParser() cf.read_string(string) self.assertEqual(cf.get('section', 'foo'), 'bar') def test_get(self): cf = JSONConfigParser() cf.add_section('section') cf.set('section', 'section', 'set-in-section') self.assertEqual(cf.get('section', 'section'), 'set-in-section') cf.set(cf.default_section, 'defaults', 'set-in-defaults') self.assertEqual(cf.get('section', 'defaults'), 'set-in-defaults') self.assertEqual(cf.get('section', 'vars', vars={'vars': 'set-in-vars'}), 'set-in-vars') self.assertEqual(cf.get('section', 'unset', 'fallback'), 'fallback') suite = unittest.TestLoader().loadTestsFromTestCase(JSONConfigTestCase) <commit_msg>Add basic test for read_file method<commit_after>
import unittest import tempfile from jsonconfigparser import JSONConfigParser class JSONConfigTestCase(unittest.TestCase): def test_init(self): JSONConfigParser() def test_read_string(self): string = '[section]\n' + \ '# comment comment\n' + \ 'foo = "bar"\n' + \ '\n' + \ '[section2]\n' + \ 'bar = "baz"\n' cf = JSONConfigParser() cf.read_string(string) self.assertEqual(cf.get('section', 'foo'), 'bar') def test_read_file(self): string = '[section]\n' + \ 'foo = "bar"' fp = tempfile.NamedTemporaryFile('w+') fp.write(string) fp.seek(0) cf = JSONConfigParser() cf.read_file(fp) self.assertEqual(cf.get('section', 'foo'), 'bar') def test_get(self): cf = JSONConfigParser() cf.add_section('section') cf.set('section', 'section', 'set-in-section') self.assertEqual(cf.get('section', 'section'), 'set-in-section') cf.set(cf.default_section, 'defaults', 'set-in-defaults') self.assertEqual(cf.get('section', 'defaults'), 'set-in-defaults') self.assertEqual(cf.get('section', 'vars', vars={'vars': 'set-in-vars'}), 'set-in-vars') self.assertEqual(cf.get('section', 'unset', 'fallback'), 'fallback') suite = unittest.TestLoader().loadTestsFromTestCase(JSONConfigTestCase)
import unittest from jsonconfigparser import JSONConfigParser class JSONConfigTestCase(unittest.TestCase): def test_init(self): JSONConfigParser() def test_read_string(self): string = '[section]\n' + \ '# comment comment\n' + \ 'foo = "bar"\n' + \ '\n' + \ '[section2]\n' + \ 'bar = "baz"\n' cf = JSONConfigParser() cf.read_string(string) self.assertEqual(cf.get('section', 'foo'), 'bar') def test_get(self): cf = JSONConfigParser() cf.add_section('section') cf.set('section', 'section', 'set-in-section') self.assertEqual(cf.get('section', 'section'), 'set-in-section') cf.set(cf.default_section, 'defaults', 'set-in-defaults') self.assertEqual(cf.get('section', 'defaults'), 'set-in-defaults') self.assertEqual(cf.get('section', 'vars', vars={'vars': 'set-in-vars'}), 'set-in-vars') self.assertEqual(cf.get('section', 'unset', 'fallback'), 'fallback') suite = unittest.TestLoader().loadTestsFromTestCase(JSONConfigTestCase) Add basic test for read_file methodimport unittest import tempfile from jsonconfigparser import JSONConfigParser class JSONConfigTestCase(unittest.TestCase): def test_init(self): JSONConfigParser() def test_read_string(self): string = '[section]\n' + \ '# comment comment\n' + \ 'foo = "bar"\n' + \ '\n' + \ '[section2]\n' + \ 'bar = "baz"\n' cf = JSONConfigParser() cf.read_string(string) self.assertEqual(cf.get('section', 'foo'), 'bar') def test_read_file(self): string = '[section]\n' + \ 'foo = "bar"' fp = tempfile.NamedTemporaryFile('w+') fp.write(string) fp.seek(0) cf = JSONConfigParser() cf.read_file(fp) self.assertEqual(cf.get('section', 'foo'), 'bar') def test_get(self): cf = JSONConfigParser() cf.add_section('section') cf.set('section', 'section', 'set-in-section') self.assertEqual(cf.get('section', 'section'), 'set-in-section') cf.set(cf.default_section, 'defaults', 'set-in-defaults') self.assertEqual(cf.get('section', 'defaults'), 'set-in-defaults') self.assertEqual(cf.get('section', 'vars', vars={'vars': 'set-in-vars'}), 'set-in-vars') self.assertEqual(cf.get('section', 'unset', 'fallback'), 'fallback') suite = unittest.TestLoader().loadTestsFromTestCase(JSONConfigTestCase)
<commit_before>import unittest from jsonconfigparser import JSONConfigParser class JSONConfigTestCase(unittest.TestCase): def test_init(self): JSONConfigParser() def test_read_string(self): string = '[section]\n' + \ '# comment comment\n' + \ 'foo = "bar"\n' + \ '\n' + \ '[section2]\n' + \ 'bar = "baz"\n' cf = JSONConfigParser() cf.read_string(string) self.assertEqual(cf.get('section', 'foo'), 'bar') def test_get(self): cf = JSONConfigParser() cf.add_section('section') cf.set('section', 'section', 'set-in-section') self.assertEqual(cf.get('section', 'section'), 'set-in-section') cf.set(cf.default_section, 'defaults', 'set-in-defaults') self.assertEqual(cf.get('section', 'defaults'), 'set-in-defaults') self.assertEqual(cf.get('section', 'vars', vars={'vars': 'set-in-vars'}), 'set-in-vars') self.assertEqual(cf.get('section', 'unset', 'fallback'), 'fallback') suite = unittest.TestLoader().loadTestsFromTestCase(JSONConfigTestCase) <commit_msg>Add basic test for read_file method<commit_after>import unittest import tempfile from jsonconfigparser import JSONConfigParser class JSONConfigTestCase(unittest.TestCase): def test_init(self): JSONConfigParser() def test_read_string(self): string = '[section]\n' + \ '# comment comment\n' + \ 'foo = "bar"\n' + \ '\n' + \ '[section2]\n' + \ 'bar = "baz"\n' cf = JSONConfigParser() cf.read_string(string) self.assertEqual(cf.get('section', 'foo'), 'bar') def test_read_file(self): string = '[section]\n' + \ 'foo = "bar"' fp = tempfile.NamedTemporaryFile('w+') fp.write(string) fp.seek(0) cf = JSONConfigParser() cf.read_file(fp) self.assertEqual(cf.get('section', 'foo'), 'bar') def test_get(self): cf = JSONConfigParser() cf.add_section('section') cf.set('section', 'section', 'set-in-section') self.assertEqual(cf.get('section', 'section'), 'set-in-section') cf.set(cf.default_section, 'defaults', 'set-in-defaults') self.assertEqual(cf.get('section', 'defaults'), 'set-in-defaults') self.assertEqual(cf.get('section', 'vars', vars={'vars': 'set-in-vars'}), 'set-in-vars') self.assertEqual(cf.get('section', 'unset', 'fallback'), 'fallback') suite = unittest.TestLoader().loadTestsFromTestCase(JSONConfigTestCase)
15ad87b055e4974ed1f57383b432274652511fb8
tests/pytests/unit/test_crypt.py
tests/pytests/unit/test_crypt.py
""" tests.pytests.unit.test_crypt ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Unit tests for salt's crypt module """ import pytest import salt.crypt import salt.utils.files def test_get_rsa_pub_key_bad_key(tmp_path): """ get_rsa_pub_key raises InvalidKeyError when encoutering a bad key """ key_path = tmp_path / "key" with salt.utils.files.fopen(key_path, "w") as fp: fp.write("") with pytest.raises(salt.crypt.InvalidKeyError): salt.crypt.get_rsa_pub_key(key_path)
""" tests.pytests.unit.test_crypt ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Unit tests for salt's crypt module """ import pytest import salt.crypt import salt.utils.files def test_get_rsa_pub_key_bad_key(tmp_path): """ get_rsa_pub_key raises InvalidKeyError when encoutering a bad key """ key_path = str(tmp_path / "key") with salt.utils.files.fopen(key_path, "w") as fp: fp.write("") with pytest.raises(salt.crypt.InvalidKeyError): salt.crypt.get_rsa_pub_key(key_path)
Fix test on older pythons
Fix test on older pythons
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
""" tests.pytests.unit.test_crypt ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Unit tests for salt's crypt module """ import pytest import salt.crypt import salt.utils.files def test_get_rsa_pub_key_bad_key(tmp_path): """ get_rsa_pub_key raises InvalidKeyError when encoutering a bad key """ key_path = tmp_path / "key" with salt.utils.files.fopen(key_path, "w") as fp: fp.write("") with pytest.raises(salt.crypt.InvalidKeyError): salt.crypt.get_rsa_pub_key(key_path) Fix test on older pythons
""" tests.pytests.unit.test_crypt ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Unit tests for salt's crypt module """ import pytest import salt.crypt import salt.utils.files def test_get_rsa_pub_key_bad_key(tmp_path): """ get_rsa_pub_key raises InvalidKeyError when encoutering a bad key """ key_path = str(tmp_path / "key") with salt.utils.files.fopen(key_path, "w") as fp: fp.write("") with pytest.raises(salt.crypt.InvalidKeyError): salt.crypt.get_rsa_pub_key(key_path)
<commit_before>""" tests.pytests.unit.test_crypt ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Unit tests for salt's crypt module """ import pytest import salt.crypt import salt.utils.files def test_get_rsa_pub_key_bad_key(tmp_path): """ get_rsa_pub_key raises InvalidKeyError when encoutering a bad key """ key_path = tmp_path / "key" with salt.utils.files.fopen(key_path, "w") as fp: fp.write("") with pytest.raises(salt.crypt.InvalidKeyError): salt.crypt.get_rsa_pub_key(key_path) <commit_msg>Fix test on older pythons<commit_after>
""" tests.pytests.unit.test_crypt ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Unit tests for salt's crypt module """ import pytest import salt.crypt import salt.utils.files def test_get_rsa_pub_key_bad_key(tmp_path): """ get_rsa_pub_key raises InvalidKeyError when encoutering a bad key """ key_path = str(tmp_path / "key") with salt.utils.files.fopen(key_path, "w") as fp: fp.write("") with pytest.raises(salt.crypt.InvalidKeyError): salt.crypt.get_rsa_pub_key(key_path)
""" tests.pytests.unit.test_crypt ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Unit tests for salt's crypt module """ import pytest import salt.crypt import salt.utils.files def test_get_rsa_pub_key_bad_key(tmp_path): """ get_rsa_pub_key raises InvalidKeyError when encoutering a bad key """ key_path = tmp_path / "key" with salt.utils.files.fopen(key_path, "w") as fp: fp.write("") with pytest.raises(salt.crypt.InvalidKeyError): salt.crypt.get_rsa_pub_key(key_path) Fix test on older pythons""" tests.pytests.unit.test_crypt ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Unit tests for salt's crypt module """ import pytest import salt.crypt import salt.utils.files def test_get_rsa_pub_key_bad_key(tmp_path): """ get_rsa_pub_key raises InvalidKeyError when encoutering a bad key """ key_path = str(tmp_path / "key") with salt.utils.files.fopen(key_path, "w") as fp: fp.write("") with pytest.raises(salt.crypt.InvalidKeyError): salt.crypt.get_rsa_pub_key(key_path)
<commit_before>""" tests.pytests.unit.test_crypt ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Unit tests for salt's crypt module """ import pytest import salt.crypt import salt.utils.files def test_get_rsa_pub_key_bad_key(tmp_path): """ get_rsa_pub_key raises InvalidKeyError when encoutering a bad key """ key_path = tmp_path / "key" with salt.utils.files.fopen(key_path, "w") as fp: fp.write("") with pytest.raises(salt.crypt.InvalidKeyError): salt.crypt.get_rsa_pub_key(key_path) <commit_msg>Fix test on older pythons<commit_after>""" tests.pytests.unit.test_crypt ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Unit tests for salt's crypt module """ import pytest import salt.crypt import salt.utils.files def test_get_rsa_pub_key_bad_key(tmp_path): """ get_rsa_pub_key raises InvalidKeyError when encoutering a bad key """ key_path = str(tmp_path / "key") with salt.utils.files.fopen(key_path, "w") as fp: fp.write("") with pytest.raises(salt.crypt.InvalidKeyError): salt.crypt.get_rsa_pub_key(key_path)
e50aee5973a2593546d1308b5ba77cd0905dd2be
app/models.py
app/models.py
# Data Models # (C) Poren Chiang 2020 import dataclasses from ntuweather import Weather from sqlalchemy import Table, Column, DateTime, Integer, Float from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class WeatherData(Base): """Represents a weather record saved in the database.""" __tablename__ = 'weather_data' id = Column(Integer, primary_key=True) date = Column(DateTime(timezone=True), index=True) temperature = Column(Float) pressure = Column(Float) humidity = Column(Float) wind_speed = Column(Float) wind_direction = Column(Integer) rain_per_hour = Column(Float) rain_per_minute = Column(Float) ground_temperature = Column(Float) def __repr__(self): return f"<WeatherData(date='{self.date.isoformat()}', temperature={self.temperature})>" def weather(self): self_dict = {field.name: self.__dict__.get(field.name) for field in dataclasses.fields(Weather)} return Weather(**self_dict) @classmethod def fromweather(cls, weather): fields = dataclasses.asdict(weather) del fields['provider'] # We don’t store provider name as there would be only one. return cls(**fields)
# Data Models # (C) Poren Chiang 2020 import dataclasses from ntuweather import Weather from sqlalchemy import Table, Column, DateTime, Integer, Float from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class WeatherData(Base): """Represents a weather record saved in the database.""" __tablename__ = 'weather_data' id = Column(Integer, primary_key=True) date = Column(DateTime(timezone=True), index=True) temperature = Column(Float) pressure = Column(Float) humidity = Column(Float) wind_speed = Column(Float) wind_direction = Column(Integer) rain_per_hour = Column(Float) rain_per_minute = Column(Float) ground_temperature = Column(Float) def __repr__(self): return f"<WeatherData(date='{self.date.isoformat()}', temperature={self.temperature})>" def weather(self): self_dict = {field.name: self.__dict__.get(field.name) for field in dataclasses.fields(Weather)} return Weather(**self_dict) @classmethod def fromweather(cls, weather): fields = dataclasses.asdict(weather) del fields['provider'] # We don’t store provider name as there would be only one. del fields['valid'] # We only store valid weather data, hence. return cls(**fields)
Fix excessive fields in conversion
Fix excessive fields in conversion
Python
agpl-3.0
rschiang/ntu-weather,rschiang/ntu-weather
# Data Models # (C) Poren Chiang 2020 import dataclasses from ntuweather import Weather from sqlalchemy import Table, Column, DateTime, Integer, Float from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class WeatherData(Base): """Represents a weather record saved in the database.""" __tablename__ = 'weather_data' id = Column(Integer, primary_key=True) date = Column(DateTime(timezone=True), index=True) temperature = Column(Float) pressure = Column(Float) humidity = Column(Float) wind_speed = Column(Float) wind_direction = Column(Integer) rain_per_hour = Column(Float) rain_per_minute = Column(Float) ground_temperature = Column(Float) def __repr__(self): return f"<WeatherData(date='{self.date.isoformat()}', temperature={self.temperature})>" def weather(self): self_dict = {field.name: self.__dict__.get(field.name) for field in dataclasses.fields(Weather)} return Weather(**self_dict) @classmethod def fromweather(cls, weather): fields = dataclasses.asdict(weather) del fields['provider'] # We don’t store provider name as there would be only one. return cls(**fields) Fix excessive fields in conversion
# Data Models # (C) Poren Chiang 2020 import dataclasses from ntuweather import Weather from sqlalchemy import Table, Column, DateTime, Integer, Float from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class WeatherData(Base): """Represents a weather record saved in the database.""" __tablename__ = 'weather_data' id = Column(Integer, primary_key=True) date = Column(DateTime(timezone=True), index=True) temperature = Column(Float) pressure = Column(Float) humidity = Column(Float) wind_speed = Column(Float) wind_direction = Column(Integer) rain_per_hour = Column(Float) rain_per_minute = Column(Float) ground_temperature = Column(Float) def __repr__(self): return f"<WeatherData(date='{self.date.isoformat()}', temperature={self.temperature})>" def weather(self): self_dict = {field.name: self.__dict__.get(field.name) for field in dataclasses.fields(Weather)} return Weather(**self_dict) @classmethod def fromweather(cls, weather): fields = dataclasses.asdict(weather) del fields['provider'] # We don’t store provider name as there would be only one. del fields['valid'] # We only store valid weather data, hence. return cls(**fields)
<commit_before># Data Models # (C) Poren Chiang 2020 import dataclasses from ntuweather import Weather from sqlalchemy import Table, Column, DateTime, Integer, Float from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class WeatherData(Base): """Represents a weather record saved in the database.""" __tablename__ = 'weather_data' id = Column(Integer, primary_key=True) date = Column(DateTime(timezone=True), index=True) temperature = Column(Float) pressure = Column(Float) humidity = Column(Float) wind_speed = Column(Float) wind_direction = Column(Integer) rain_per_hour = Column(Float) rain_per_minute = Column(Float) ground_temperature = Column(Float) def __repr__(self): return f"<WeatherData(date='{self.date.isoformat()}', temperature={self.temperature})>" def weather(self): self_dict = {field.name: self.__dict__.get(field.name) for field in dataclasses.fields(Weather)} return Weather(**self_dict) @classmethod def fromweather(cls, weather): fields = dataclasses.asdict(weather) del fields['provider'] # We don’t store provider name as there would be only one. return cls(**fields) <commit_msg>Fix excessive fields in conversion<commit_after>
# Data Models # (C) Poren Chiang 2020 import dataclasses from ntuweather import Weather from sqlalchemy import Table, Column, DateTime, Integer, Float from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class WeatherData(Base): """Represents a weather record saved in the database.""" __tablename__ = 'weather_data' id = Column(Integer, primary_key=True) date = Column(DateTime(timezone=True), index=True) temperature = Column(Float) pressure = Column(Float) humidity = Column(Float) wind_speed = Column(Float) wind_direction = Column(Integer) rain_per_hour = Column(Float) rain_per_minute = Column(Float) ground_temperature = Column(Float) def __repr__(self): return f"<WeatherData(date='{self.date.isoformat()}', temperature={self.temperature})>" def weather(self): self_dict = {field.name: self.__dict__.get(field.name) for field in dataclasses.fields(Weather)} return Weather(**self_dict) @classmethod def fromweather(cls, weather): fields = dataclasses.asdict(weather) del fields['provider'] # We don’t store provider name as there would be only one. del fields['valid'] # We only store valid weather data, hence. return cls(**fields)
# Data Models # (C) Poren Chiang 2020 import dataclasses from ntuweather import Weather from sqlalchemy import Table, Column, DateTime, Integer, Float from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class WeatherData(Base): """Represents a weather record saved in the database.""" __tablename__ = 'weather_data' id = Column(Integer, primary_key=True) date = Column(DateTime(timezone=True), index=True) temperature = Column(Float) pressure = Column(Float) humidity = Column(Float) wind_speed = Column(Float) wind_direction = Column(Integer) rain_per_hour = Column(Float) rain_per_minute = Column(Float) ground_temperature = Column(Float) def __repr__(self): return f"<WeatherData(date='{self.date.isoformat()}', temperature={self.temperature})>" def weather(self): self_dict = {field.name: self.__dict__.get(field.name) for field in dataclasses.fields(Weather)} return Weather(**self_dict) @classmethod def fromweather(cls, weather): fields = dataclasses.asdict(weather) del fields['provider'] # We don’t store provider name as there would be only one. return cls(**fields) Fix excessive fields in conversion# Data Models # (C) Poren Chiang 2020 import dataclasses from ntuweather import Weather from sqlalchemy import Table, Column, DateTime, Integer, Float from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class WeatherData(Base): """Represents a weather record saved in the database.""" __tablename__ = 'weather_data' id = Column(Integer, primary_key=True) date = Column(DateTime(timezone=True), index=True) temperature = Column(Float) pressure = Column(Float) humidity = Column(Float) wind_speed = Column(Float) wind_direction = Column(Integer) rain_per_hour = Column(Float) rain_per_minute = Column(Float) ground_temperature = Column(Float) def __repr__(self): return f"<WeatherData(date='{self.date.isoformat()}', temperature={self.temperature})>" def weather(self): self_dict = {field.name: self.__dict__.get(field.name) for field in dataclasses.fields(Weather)} return Weather(**self_dict) @classmethod def fromweather(cls, weather): fields = dataclasses.asdict(weather) del fields['provider'] # We don’t store provider name as there would be only one. del fields['valid'] # We only store valid weather data, hence. return cls(**fields)
<commit_before># Data Models # (C) Poren Chiang 2020 import dataclasses from ntuweather import Weather from sqlalchemy import Table, Column, DateTime, Integer, Float from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class WeatherData(Base): """Represents a weather record saved in the database.""" __tablename__ = 'weather_data' id = Column(Integer, primary_key=True) date = Column(DateTime(timezone=True), index=True) temperature = Column(Float) pressure = Column(Float) humidity = Column(Float) wind_speed = Column(Float) wind_direction = Column(Integer) rain_per_hour = Column(Float) rain_per_minute = Column(Float) ground_temperature = Column(Float) def __repr__(self): return f"<WeatherData(date='{self.date.isoformat()}', temperature={self.temperature})>" def weather(self): self_dict = {field.name: self.__dict__.get(field.name) for field in dataclasses.fields(Weather)} return Weather(**self_dict) @classmethod def fromweather(cls, weather): fields = dataclasses.asdict(weather) del fields['provider'] # We don’t store provider name as there would be only one. return cls(**fields) <commit_msg>Fix excessive fields in conversion<commit_after># Data Models # (C) Poren Chiang 2020 import dataclasses from ntuweather import Weather from sqlalchemy import Table, Column, DateTime, Integer, Float from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class WeatherData(Base): """Represents a weather record saved in the database.""" __tablename__ = 'weather_data' id = Column(Integer, primary_key=True) date = Column(DateTime(timezone=True), index=True) temperature = Column(Float) pressure = Column(Float) humidity = Column(Float) wind_speed = Column(Float) wind_direction = Column(Integer) rain_per_hour = Column(Float) rain_per_minute = Column(Float) ground_temperature = Column(Float) def __repr__(self): return f"<WeatherData(date='{self.date.isoformat()}', temperature={self.temperature})>" def weather(self): self_dict = {field.name: self.__dict__.get(field.name) for field in dataclasses.fields(Weather)} return Weather(**self_dict) @classmethod def fromweather(cls, weather): fields = dataclasses.asdict(weather) del fields['provider'] # We don’t store provider name as there would be only one. del fields['valid'] # We only store valid weather data, hence. return cls(**fields)
281d3c43cc393059ce43fa32e3563883649fda08
global_mod.py
global_mod.py
#!/usr/bin/env python version = "v0.0.23" modes = ['monitor', 'wallet', 'peers', 'block', 'tx', 'console', 'net', 'forks', 'quit']
#!/usr/bin/env python version = "v0.1.0-dev" modes = ['monitor', 'wallet', 'peers', 'block', 'tx', 'console', 'net', 'forks', 'quit']
Change version number to indicate development version
Change version number to indicate development version
Python
mit
esotericnonsense/bitcoind-ncurses,azeteki/bitcoind-ncurses
#!/usr/bin/env python version = "v0.0.23" modes = ['monitor', 'wallet', 'peers', 'block', 'tx', 'console', 'net', 'forks', 'quit'] Change version number to indicate development version
#!/usr/bin/env python version = "v0.1.0-dev" modes = ['monitor', 'wallet', 'peers', 'block', 'tx', 'console', 'net', 'forks', 'quit']
<commit_before>#!/usr/bin/env python version = "v0.0.23" modes = ['monitor', 'wallet', 'peers', 'block', 'tx', 'console', 'net', 'forks', 'quit'] <commit_msg>Change version number to indicate development version<commit_after>
#!/usr/bin/env python version = "v0.1.0-dev" modes = ['monitor', 'wallet', 'peers', 'block', 'tx', 'console', 'net', 'forks', 'quit']
#!/usr/bin/env python version = "v0.0.23" modes = ['monitor', 'wallet', 'peers', 'block', 'tx', 'console', 'net', 'forks', 'quit'] Change version number to indicate development version#!/usr/bin/env python version = "v0.1.0-dev" modes = ['monitor', 'wallet', 'peers', 'block', 'tx', 'console', 'net', 'forks', 'quit']
<commit_before>#!/usr/bin/env python version = "v0.0.23" modes = ['monitor', 'wallet', 'peers', 'block', 'tx', 'console', 'net', 'forks', 'quit'] <commit_msg>Change version number to indicate development version<commit_after>#!/usr/bin/env python version = "v0.1.0-dev" modes = ['monitor', 'wallet', 'peers', 'block', 'tx', 'console', 'net', 'forks', 'quit']
338c904eb9efc01e9c84c8ec91d810227582e1e3
tests/test_postgres_processor.py
tests/test_postgres_processor.py
import pytest from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from scrapi.linter.document import NormalizedDocument, RawDocument # Need to force cassandra to ignore set keyspace from scrapi.processing.postgres import PostgresProcessor, Document from . import utils test_db = PostgresProcessor() engine = create_engine('postgresql://localhost/scrapi', echo=True) session = sessionmaker(bind=engine)() NORMALIZED = NormalizedDocument(utils.RECORD) RAW = RawDocument(utils.RAW_DOC) def test_process_raw(): test_db.process_raw(RAW) queryset = Document(docID='someID', source=RAW['source']) assert queryset.docID == RAW.attributes['docID']
import pytest from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from scrapi.linter.document import NormalizedDocument, RawDocument from scrapi.processing.postgres import PostgresProcessor, Document from . import utils test_db = PostgresProcessor() engine = create_engine('postgresql://localhost/test', echo=True) session = sessionmaker(bind=engine)() NORMALIZED = NormalizedDocument(utils.RECORD) RAW = RawDocument(utils.RAW_DOC) @pytest.mark.postgres def test_process_raw(): test_db.process_raw(RAW) queryset = Document(docID='someID', source=RAW['source']) assert queryset.docID == RAW.attributes['docID']
Remove test db setup from postgres processor
Remove test db setup from postgres processor
Python
apache-2.0
CenterForOpenScience/scrapi,mehanig/scrapi,erinspace/scrapi,CenterForOpenScience/scrapi,erinspace/scrapi,mehanig/scrapi,fabianvf/scrapi,felliott/scrapi,felliott/scrapi,fabianvf/scrapi
import pytest from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from scrapi.linter.document import NormalizedDocument, RawDocument # Need to force cassandra to ignore set keyspace from scrapi.processing.postgres import PostgresProcessor, Document from . import utils test_db = PostgresProcessor() engine = create_engine('postgresql://localhost/scrapi', echo=True) session = sessionmaker(bind=engine)() NORMALIZED = NormalizedDocument(utils.RECORD) RAW = RawDocument(utils.RAW_DOC) def test_process_raw(): test_db.process_raw(RAW) queryset = Document(docID='someID', source=RAW['source']) assert queryset.docID == RAW.attributes['docID'] Remove test db setup from postgres processor
import pytest from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from scrapi.linter.document import NormalizedDocument, RawDocument from scrapi.processing.postgres import PostgresProcessor, Document from . import utils test_db = PostgresProcessor() engine = create_engine('postgresql://localhost/test', echo=True) session = sessionmaker(bind=engine)() NORMALIZED = NormalizedDocument(utils.RECORD) RAW = RawDocument(utils.RAW_DOC) @pytest.mark.postgres def test_process_raw(): test_db.process_raw(RAW) queryset = Document(docID='someID', source=RAW['source']) assert queryset.docID == RAW.attributes['docID']
<commit_before>import pytest from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from scrapi.linter.document import NormalizedDocument, RawDocument # Need to force cassandra to ignore set keyspace from scrapi.processing.postgres import PostgresProcessor, Document from . import utils test_db = PostgresProcessor() engine = create_engine('postgresql://localhost/scrapi', echo=True) session = sessionmaker(bind=engine)() NORMALIZED = NormalizedDocument(utils.RECORD) RAW = RawDocument(utils.RAW_DOC) def test_process_raw(): test_db.process_raw(RAW) queryset = Document(docID='someID', source=RAW['source']) assert queryset.docID == RAW.attributes['docID'] <commit_msg>Remove test db setup from postgres processor<commit_after>
import pytest from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from scrapi.linter.document import NormalizedDocument, RawDocument from scrapi.processing.postgres import PostgresProcessor, Document from . import utils test_db = PostgresProcessor() engine = create_engine('postgresql://localhost/test', echo=True) session = sessionmaker(bind=engine)() NORMALIZED = NormalizedDocument(utils.RECORD) RAW = RawDocument(utils.RAW_DOC) @pytest.mark.postgres def test_process_raw(): test_db.process_raw(RAW) queryset = Document(docID='someID', source=RAW['source']) assert queryset.docID == RAW.attributes['docID']
import pytest from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from scrapi.linter.document import NormalizedDocument, RawDocument # Need to force cassandra to ignore set keyspace from scrapi.processing.postgres import PostgresProcessor, Document from . import utils test_db = PostgresProcessor() engine = create_engine('postgresql://localhost/scrapi', echo=True) session = sessionmaker(bind=engine)() NORMALIZED = NormalizedDocument(utils.RECORD) RAW = RawDocument(utils.RAW_DOC) def test_process_raw(): test_db.process_raw(RAW) queryset = Document(docID='someID', source=RAW['source']) assert queryset.docID == RAW.attributes['docID'] Remove test db setup from postgres processorimport pytest from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from scrapi.linter.document import NormalizedDocument, RawDocument from scrapi.processing.postgres import PostgresProcessor, Document from . import utils test_db = PostgresProcessor() engine = create_engine('postgresql://localhost/test', echo=True) session = sessionmaker(bind=engine)() NORMALIZED = NormalizedDocument(utils.RECORD) RAW = RawDocument(utils.RAW_DOC) @pytest.mark.postgres def test_process_raw(): test_db.process_raw(RAW) queryset = Document(docID='someID', source=RAW['source']) assert queryset.docID == RAW.attributes['docID']
<commit_before>import pytest from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from scrapi.linter.document import NormalizedDocument, RawDocument # Need to force cassandra to ignore set keyspace from scrapi.processing.postgres import PostgresProcessor, Document from . import utils test_db = PostgresProcessor() engine = create_engine('postgresql://localhost/scrapi', echo=True) session = sessionmaker(bind=engine)() NORMALIZED = NormalizedDocument(utils.RECORD) RAW = RawDocument(utils.RAW_DOC) def test_process_raw(): test_db.process_raw(RAW) queryset = Document(docID='someID', source=RAW['source']) assert queryset.docID == RAW.attributes['docID'] <commit_msg>Remove test db setup from postgres processor<commit_after>import pytest from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from scrapi.linter.document import NormalizedDocument, RawDocument from scrapi.processing.postgres import PostgresProcessor, Document from . import utils test_db = PostgresProcessor() engine = create_engine('postgresql://localhost/test', echo=True) session = sessionmaker(bind=engine)() NORMALIZED = NormalizedDocument(utils.RECORD) RAW = RawDocument(utils.RAW_DOC) @pytest.mark.postgres def test_process_raw(): test_db.process_raw(RAW) queryset = Document(docID='someID', source=RAW['source']) assert queryset.docID == RAW.attributes['docID']