commit
stringlengths
40
40
old_file
stringlengths
4
118
new_file
stringlengths
4
118
old_contents
stringlengths
10
2.94k
new_contents
stringlengths
21
3.18k
subject
stringlengths
16
444
message
stringlengths
17
2.63k
lang
stringclasses
1 value
license
stringclasses
13 values
repos
stringlengths
5
43k
ndiff
stringlengths
52
3.32k
instruction
stringlengths
16
444
content
stringlengths
133
4.32k
fuzzy_diff
stringlengths
16
3.18k
384fd7ba49ad0cfcb173656a5e31475e8c9b49b3
setup.py
setup.py
from distutils.core import setup import nagios setup(name='nagios-api', version=nagios.version, description='Control nagios using an API', author='Mark Smith', author_email='[email protected]', license='BSD New (3-clause) License', long_description=open('README.md').read(), url='https://github.com/xb95/nagios-api', packages=['nagios'], scripts=['nagios-cli', 'nagios-api'], requires=[ 'diesel(>=3.0)', 'greenlet(==0.3.4)', 'requests' ] )
from distutils.core import setup import nagios setup(name='nagios-api', version=nagios.version, description='Control nagios using an API', author='Mark Smith', author_email='[email protected]', license='BSD New (3-clause) License', long_description=open('README.md').read(), url='https://github.com/xb95/nagios-api', packages=['nagios'], scripts=['nagios-cli', 'nagios-api'], install_requires=[ 'diesel>=3.0', 'greenlet==0.3.4', 'requests' ] )
Use install_requires arg so dependencies are installed
Use install_requires arg so dependencies are installed
Python
bsd-3-clause
zorkian/nagios-api,zorkian/nagios-api
from distutils.core import setup import nagios setup(name='nagios-api', version=nagios.version, description='Control nagios using an API', author='Mark Smith', author_email='[email protected]', license='BSD New (3-clause) License', long_description=open('README.md').read(), url='https://github.com/xb95/nagios-api', packages=['nagios'], scripts=['nagios-cli', 'nagios-api'], - requires=[ + install_requires=[ - 'diesel(>=3.0)', + 'diesel>=3.0', - 'greenlet(==0.3.4)', + 'greenlet==0.3.4', 'requests' ] )
Use install_requires arg so dependencies are installed
## Code Before: from distutils.core import setup import nagios setup(name='nagios-api', version=nagios.version, description='Control nagios using an API', author='Mark Smith', author_email='[email protected]', license='BSD New (3-clause) License', long_description=open('README.md').read(), url='https://github.com/xb95/nagios-api', packages=['nagios'], scripts=['nagios-cli', 'nagios-api'], requires=[ 'diesel(>=3.0)', 'greenlet(==0.3.4)', 'requests' ] ) ## Instruction: Use install_requires arg so dependencies are installed ## Code After: from distutils.core import setup import nagios setup(name='nagios-api', version=nagios.version, description='Control nagios using an API', author='Mark Smith', author_email='[email protected]', license='BSD New (3-clause) License', long_description=open('README.md').read(), url='https://github.com/xb95/nagios-api', packages=['nagios'], scripts=['nagios-cli', 'nagios-api'], install_requires=[ 'diesel>=3.0', 'greenlet==0.3.4', 'requests' ] )
... scripts=['nagios-cli', 'nagios-api'], install_requires=[ 'diesel>=3.0', 'greenlet==0.3.4', 'requests' ...
84062292b62d68a14981bcebf18c01feda26fb01
src/plotter/comparison_plotter.py
src/plotter/comparison_plotter.py
import matplotlib.pyplot as plt from .constants import PLOT class ComparisonPlotter: def __init__(self, data_list): self.trajectory_fig, self.trajectory_plot = plt.subplots(1, 1) self.position_fig, self.position_plot = plt.subplots(2, 1, sharex=True) self.position_error_fig, self.position_error_plot = plt.subplots(2, 1, sharex=True) self.control_action_fig, self.control_action_plot = plt.subplots(2, 1, sharex=True) temp_data = data_list[0] self.t = temp_data['t'] self.x_ref = temp_data['x_ref'] self.y_ref = temp_data['y_ref'] self.zeros = temp_data['zeros'] def plot_comparison(self): self.trajectory_plot.plot(self.x_ref, self.y_ref, 'r--', label=r'${\rm reference}$', lw=PLOT['line_width']) plt.show() if __name__ == '__main__': steps = 100 plotter = ComparisonPlotter( [ {'t': [i for i in range(steps)], 'x_ref': [0.5 * i for i in range(steps)], 'y_ref': [2.0 * i for i in range(steps)], 'zeros': [0.0 for _ in range(steps)],} ] ) plotter.plot_comparison()
import matplotlib.pyplot as plt from .plotter import Plotter from .constants import PLOT class ComparisonPlotter(Plotter): def __init__(self, data_list): temp_data = data_list[0] Plotter.__init__(self, temp_data['t'], temp_data['zeros']) self.trajectory_fig, self.trajectory_plot = plt.subplots(1, 1) self.position_fig, self.position_plot = plt.subplots(2, 1, sharex=True) self.position_error_fig, self.position_error_plot = plt.subplots(2, 1, sharex=True) self.control_action_fig, self.control_action_plot = plt.subplots(2, 1, sharex=True) self.x_ref = temp_data['x_ref'] self.y_ref = temp_data['y_ref'] def plot_comparison(self): self.trajectory_plot.plot(self.x_ref, self.y_ref, 'r--', label=r'${\rm reference}$', lw=PLOT['line_width']) plt.show()
Make class ComparisonPlotter inherit from Plotter
feat: Make class ComparisonPlotter inherit from Plotter
Python
mit
bit0001/trajectory_tracking,bit0001/trajectory_tracking
import matplotlib.pyplot as plt + from .plotter import Plotter from .constants import PLOT - class ComparisonPlotter: + class ComparisonPlotter(Plotter): def __init__(self, data_list): + temp_data = data_list[0] + Plotter.__init__(self, temp_data['t'], temp_data['zeros']) + self.trajectory_fig, self.trajectory_plot = plt.subplots(1, 1) self.position_fig, self.position_plot = plt.subplots(2, 1, sharex=True) self.position_error_fig, self.position_error_plot = plt.subplots(2, 1, sharex=True) self.control_action_fig, self.control_action_plot = plt.subplots(2, 1, sharex=True) - temp_data = data_list[0] - self.t = temp_data['t'] self.x_ref = temp_data['x_ref'] self.y_ref = temp_data['y_ref'] - self.zeros = temp_data['zeros'] def plot_comparison(self): self.trajectory_plot.plot(self.x_ref, self.y_ref, 'r--', label=r'${\rm reference}$', lw=PLOT['line_width']) plt.show() - if __name__ == '__main__': - steps = 100 - plotter = ComparisonPlotter( - [ - {'t': [i for i in range(steps)], - 'x_ref': [0.5 * i for i in range(steps)], - 'y_ref': [2.0 * i for i in range(steps)], - 'zeros': [0.0 for _ in range(steps)],} - ] - ) - plotter.plot_comparison() -
Make class ComparisonPlotter inherit from Plotter
## Code Before: import matplotlib.pyplot as plt from .constants import PLOT class ComparisonPlotter: def __init__(self, data_list): self.trajectory_fig, self.trajectory_plot = plt.subplots(1, 1) self.position_fig, self.position_plot = plt.subplots(2, 1, sharex=True) self.position_error_fig, self.position_error_plot = plt.subplots(2, 1, sharex=True) self.control_action_fig, self.control_action_plot = plt.subplots(2, 1, sharex=True) temp_data = data_list[0] self.t = temp_data['t'] self.x_ref = temp_data['x_ref'] self.y_ref = temp_data['y_ref'] self.zeros = temp_data['zeros'] def plot_comparison(self): self.trajectory_plot.plot(self.x_ref, self.y_ref, 'r--', label=r'${\rm reference}$', lw=PLOT['line_width']) plt.show() if __name__ == '__main__': steps = 100 plotter = ComparisonPlotter( [ {'t': [i for i in range(steps)], 'x_ref': [0.5 * i for i in range(steps)], 'y_ref': [2.0 * i for i in range(steps)], 'zeros': [0.0 for _ in range(steps)],} ] ) plotter.plot_comparison() ## Instruction: Make class ComparisonPlotter inherit from Plotter ## Code After: import matplotlib.pyplot as plt from .plotter import Plotter from .constants import PLOT class ComparisonPlotter(Plotter): def __init__(self, data_list): temp_data = data_list[0] Plotter.__init__(self, temp_data['t'], temp_data['zeros']) self.trajectory_fig, self.trajectory_plot = plt.subplots(1, 1) self.position_fig, self.position_plot = plt.subplots(2, 1, sharex=True) self.position_error_fig, self.position_error_plot = plt.subplots(2, 1, sharex=True) self.control_action_fig, self.control_action_plot = plt.subplots(2, 1, sharex=True) self.x_ref = temp_data['x_ref'] self.y_ref = temp_data['y_ref'] def plot_comparison(self): self.trajectory_plot.plot(self.x_ref, self.y_ref, 'r--', label=r'${\rm reference}$', lw=PLOT['line_width']) plt.show()
// ... existing code ... from .plotter import Plotter from .constants import PLOT // ... modified code ... class ComparisonPlotter(Plotter): def __init__(self, data_list): temp_data = data_list[0] Plotter.__init__(self, temp_data['t'], temp_data['zeros']) self.trajectory_fig, self.trajectory_plot = plt.subplots(1, 1) ... self.x_ref = temp_data['x_ref'] ... self.y_ref = temp_data['y_ref'] ... plt.show() // ... rest of the code ...
28627a41918be15037ba22e930a45d022e88388d
opps/articles/adminx.py
opps/articles/adminx.py
from .models import Post, Album, Link from opps.contrib import admin admin.site.register(Post) admin.site.register(Album) admin.site.register(Link)
from django.utils.translation import ugettext_lazy as _ from .models import Post, Album, Link from opps.containers.models import ContainerSource, ContainerImage from opps.contrib import admin from opps.contrib.admin.layout import * from xadmin.plugins.inline import Inline class ImageInline(object): model = ContainerImage style = 'accordion' class SourceInline(object): model = ContainerSource style = 'accordion' class PostAdmin(object): raw_id_fields = ['main_image', 'channel', 'albums'] inlines = [ImageInline, SourceInline] style_fields = {'system': "radio-inline"} form_layout = ( Main( TabHolder( Tab(_(u'Identification'), Fieldset('site', 'title', 'slug', 'get_http_absolute_url', 'short_url'), ), Tab(_(u'Content'), Fieldset('hat', 'short_title', 'headline', 'content', 'main_image', 'main_image_caption', 'image_thumb' 'tags'), Inline(ContainerImage), Inline(ContainerSource), ), Tab(_(u'Relationships'), Fieldset('channel', 'albums'), ), )), Side( Fieldset(_(u'Publication'), 'published', 'date_available', 'show_on_root_channel', 'in_containerboxes') ) ) reversion_enable = True admin.site.register(Post, PostAdmin) admin.site.register(Album) admin.site.register(Link)
Add Inline example on post model xadmin
Add Inline example on post model xadmin
Python
mit
jeanmask/opps,opps/opps,YACOWS/opps,williamroot/opps,opps/opps,jeanmask/opps,williamroot/opps,YACOWS/opps,opps/opps,williamroot/opps,jeanmask/opps,opps/opps,jeanmask/opps,williamroot/opps,YACOWS/opps,YACOWS/opps
+ from django.utils.translation import ugettext_lazy as _ from .models import Post, Album, Link + from opps.containers.models import ContainerSource, ContainerImage from opps.contrib import admin + from opps.contrib.admin.layout import * + from xadmin.plugins.inline import Inline + + class ImageInline(object): + model = ContainerImage + style = 'accordion' + + + class SourceInline(object): + model = ContainerSource + style = 'accordion' + + + class PostAdmin(object): + raw_id_fields = ['main_image', 'channel', 'albums'] + inlines = [ImageInline, SourceInline] + style_fields = {'system': "radio-inline"} + + form_layout = ( + Main( + TabHolder( + Tab(_(u'Identification'), + Fieldset('site', 'title', 'slug', + 'get_http_absolute_url', 'short_url'), + ), + Tab(_(u'Content'), + Fieldset('hat', 'short_title', 'headline', + 'content', 'main_image', 'main_image_caption', + 'image_thumb' 'tags'), + Inline(ContainerImage), + Inline(ContainerSource), + ), + Tab(_(u'Relationships'), + Fieldset('channel', 'albums'), + ), + )), + Side( + Fieldset(_(u'Publication'), 'published', 'date_available', + 'show_on_root_channel', 'in_containerboxes') + + ) + ) + + reversion_enable = True + + - admin.site.register(Post) + admin.site.register(Post, PostAdmin) admin.site.register(Album) admin.site.register(Link)
Add Inline example on post model xadmin
## Code Before: from .models import Post, Album, Link from opps.contrib import admin admin.site.register(Post) admin.site.register(Album) admin.site.register(Link) ## Instruction: Add Inline example on post model xadmin ## Code After: from django.utils.translation import ugettext_lazy as _ from .models import Post, Album, Link from opps.containers.models import ContainerSource, ContainerImage from opps.contrib import admin from opps.contrib.admin.layout import * from xadmin.plugins.inline import Inline class ImageInline(object): model = ContainerImage style = 'accordion' class SourceInline(object): model = ContainerSource style = 'accordion' class PostAdmin(object): raw_id_fields = ['main_image', 'channel', 'albums'] inlines = [ImageInline, SourceInline] style_fields = {'system': "radio-inline"} form_layout = ( Main( TabHolder( Tab(_(u'Identification'), Fieldset('site', 'title', 'slug', 'get_http_absolute_url', 'short_url'), ), Tab(_(u'Content'), Fieldset('hat', 'short_title', 'headline', 'content', 'main_image', 'main_image_caption', 'image_thumb' 'tags'), Inline(ContainerImage), Inline(ContainerSource), ), Tab(_(u'Relationships'), Fieldset('channel', 'albums'), ), )), Side( Fieldset(_(u'Publication'), 'published', 'date_available', 'show_on_root_channel', 'in_containerboxes') ) ) reversion_enable = True admin.site.register(Post, PostAdmin) admin.site.register(Album) admin.site.register(Link)
// ... existing code ... from django.utils.translation import ugettext_lazy as _ from .models import Post, Album, Link // ... modified code ... from opps.containers.models import ContainerSource, ContainerImage from opps.contrib import admin from opps.contrib.admin.layout import * from xadmin.plugins.inline import Inline class ImageInline(object): model = ContainerImage style = 'accordion' class SourceInline(object): model = ContainerSource style = 'accordion' class PostAdmin(object): raw_id_fields = ['main_image', 'channel', 'albums'] inlines = [ImageInline, SourceInline] style_fields = {'system': "radio-inline"} form_layout = ( Main( TabHolder( Tab(_(u'Identification'), Fieldset('site', 'title', 'slug', 'get_http_absolute_url', 'short_url'), ), Tab(_(u'Content'), Fieldset('hat', 'short_title', 'headline', 'content', 'main_image', 'main_image_caption', 'image_thumb' 'tags'), Inline(ContainerImage), Inline(ContainerSource), ), Tab(_(u'Relationships'), Fieldset('channel', 'albums'), ), )), Side( Fieldset(_(u'Publication'), 'published', 'date_available', 'show_on_root_channel', 'in_containerboxes') ) ) reversion_enable = True admin.site.register(Post, PostAdmin) admin.site.register(Album) // ... rest of the code ...
edd50431f9c99bcbc765cc85786ead60ba8ba6e4
admin/base/migrations/0002_groups.py
admin/base/migrations/0002_groups.py
from __future__ import unicode_literals from django.db import migrations from django.contrib.auth.models import Group import logging logger = logging.getLogger(__file__) def add_groups(*args): group, created = Group.objects.get_or_create(name='nodes_and_users') if created: logger.info('nodes_and_users group created') try: group = Group.objects.get(name='prereg_group') group.name = 'prereg' group.save() logger.info('prereg_group renamed to prereg') except Group.DoesNotExist: group, created = Group.objects.get_or_create(name='prereg') if created: logger.info('prereg group created') class Migration(migrations.Migration): dependencies = [ ('base', '0001_groups'), ] operations = [ migrations.RunPython(add_groups), ]
from __future__ import unicode_literals from django.db import migrations from django.contrib.auth.models import Group import logging logger = logging.getLogger(__file__) def add_groups(*args): group, created = Group.objects.get_or_create(name='nodes_and_users') if created: logger.info('nodes_and_users group created') try: group = Group.objects.get(name='prereg_group') group.name = 'prereg' group.save() logger.info('prereg_group renamed to prereg') except Group.DoesNotExist: group, created = Group.objects.get_or_create(name='prereg') if created: logger.info('prereg group created') def remove_groups(*args): Group.objects.filter(name='nodes_and_users').delete() group = Group.objects.get(name='prereg') group.name = 'prereg_group' group.save() class Migration(migrations.Migration): dependencies = [ ('base', '0001_groups'), ] operations = [ migrations.RunPython(add_groups, remove_groups), ]
Add reverse migration for new groups
Add reverse migration for new groups
Python
apache-2.0
brianjgeiger/osf.io,chennan47/osf.io,CenterForOpenScience/osf.io,sloria/osf.io,Johnetordoff/osf.io,leb2dg/osf.io,brianjgeiger/osf.io,monikagrabowska/osf.io,binoculars/osf.io,acshi/osf.io,chrisseto/osf.io,acshi/osf.io,crcresearch/osf.io,aaxelb/osf.io,erinspace/osf.io,brianjgeiger/osf.io,chrisseto/osf.io,erinspace/osf.io,baylee-d/osf.io,mfraezz/osf.io,cwisecarver/osf.io,CenterForOpenScience/osf.io,binoculars/osf.io,saradbowman/osf.io,acshi/osf.io,HalcyonChimera/osf.io,cslzchen/osf.io,monikagrabowska/osf.io,leb2dg/osf.io,chennan47/osf.io,Johnetordoff/osf.io,mfraezz/osf.io,CenterForOpenScience/osf.io,leb2dg/osf.io,felliott/osf.io,hmoco/osf.io,cwisecarver/osf.io,pattisdr/osf.io,chrisseto/osf.io,adlius/osf.io,pattisdr/osf.io,monikagrabowska/osf.io,adlius/osf.io,icereval/osf.io,baylee-d/osf.io,cslzchen/osf.io,felliott/osf.io,caneruguz/osf.io,TomBaxter/osf.io,caneruguz/osf.io,baylee-d/osf.io,TomBaxter/osf.io,HalcyonChimera/osf.io,aaxelb/osf.io,caseyrollins/osf.io,hmoco/osf.io,felliott/osf.io,cslzchen/osf.io,monikagrabowska/osf.io,aaxelb/osf.io,crcresearch/osf.io,mattclark/osf.io,cwisecarver/osf.io,laurenrevere/osf.io,hmoco/osf.io,saradbowman/osf.io,cslzchen/osf.io,HalcyonChimera/osf.io,pattisdr/osf.io,CenterForOpenScience/osf.io,monikagrabowska/osf.io,mfraezz/osf.io,icereval/osf.io,cwisecarver/osf.io,brianjgeiger/osf.io,TomBaxter/osf.io,laurenrevere/osf.io,sloria/osf.io,caseyrollins/osf.io,Nesiehr/osf.io,leb2dg/osf.io,acshi/osf.io,caseyrollins/osf.io,HalcyonChimera/osf.io,Nesiehr/osf.io,mattclark/osf.io,Johnetordoff/osf.io,Johnetordoff/osf.io,felliott/osf.io,icereval/osf.io,crcresearch/osf.io,mattclark/osf.io,acshi/osf.io,sloria/osf.io,caneruguz/osf.io,mfraezz/osf.io,binoculars/osf.io,adlius/osf.io,aaxelb/osf.io,caneruguz/osf.io,Nesiehr/osf.io,laurenrevere/osf.io,erinspace/osf.io,hmoco/osf.io,chrisseto/osf.io,Nesiehr/osf.io,chennan47/osf.io,adlius/osf.io
from __future__ import unicode_literals from django.db import migrations from django.contrib.auth.models import Group import logging logger = logging.getLogger(__file__) def add_groups(*args): group, created = Group.objects.get_or_create(name='nodes_and_users') if created: logger.info('nodes_and_users group created') try: group = Group.objects.get(name='prereg_group') group.name = 'prereg' group.save() logger.info('prereg_group renamed to prereg') except Group.DoesNotExist: group, created = Group.objects.get_or_create(name='prereg') if created: logger.info('prereg group created') + def remove_groups(*args): + Group.objects.filter(name='nodes_and_users').delete() + + group = Group.objects.get(name='prereg') + group.name = 'prereg_group' + group.save() + + class Migration(migrations.Migration): dependencies = [ ('base', '0001_groups'), ] operations = [ - migrations.RunPython(add_groups), + migrations.RunPython(add_groups, remove_groups), ]
Add reverse migration for new groups
## Code Before: from __future__ import unicode_literals from django.db import migrations from django.contrib.auth.models import Group import logging logger = logging.getLogger(__file__) def add_groups(*args): group, created = Group.objects.get_or_create(name='nodes_and_users') if created: logger.info('nodes_and_users group created') try: group = Group.objects.get(name='prereg_group') group.name = 'prereg' group.save() logger.info('prereg_group renamed to prereg') except Group.DoesNotExist: group, created = Group.objects.get_or_create(name='prereg') if created: logger.info('prereg group created') class Migration(migrations.Migration): dependencies = [ ('base', '0001_groups'), ] operations = [ migrations.RunPython(add_groups), ] ## Instruction: Add reverse migration for new groups ## Code After: from __future__ import unicode_literals from django.db import migrations from django.contrib.auth.models import Group import logging logger = logging.getLogger(__file__) def add_groups(*args): group, created = Group.objects.get_or_create(name='nodes_and_users') if created: logger.info('nodes_and_users group created') try: group = Group.objects.get(name='prereg_group') group.name = 'prereg' group.save() logger.info('prereg_group renamed to prereg') except Group.DoesNotExist: group, created = Group.objects.get_or_create(name='prereg') if created: logger.info('prereg group created') def remove_groups(*args): Group.objects.filter(name='nodes_and_users').delete() group = Group.objects.get(name='prereg') group.name = 'prereg_group' group.save() class Migration(migrations.Migration): dependencies = [ ('base', '0001_groups'), ] operations = [ migrations.RunPython(add_groups, remove_groups), ]
# ... existing code ... def remove_groups(*args): Group.objects.filter(name='nodes_and_users').delete() group = Group.objects.get(name='prereg') group.name = 'prereg_group' group.save() class Migration(migrations.Migration): # ... modified code ... operations = [ migrations.RunPython(add_groups, remove_groups), ] # ... rest of the code ...
9ccdbcc01d1bf6323256b8b8f19fa1446bb57d59
tests/unit/test_authenticate.py
tests/unit/test_authenticate.py
"""Test the DigitalOcean backed ACME DNS Authentication Class.""" from acmednsauth.authenticate import Authenticate from mock import call def test_valid_data_calls_digital_ocean_record_creation( mocker, api_key, hostname, domain, fqdn, auth_token): create_environment = { 'DO_API_KEY': api_key, 'DO_DOMAIN': domain, 'CERTBOT_DOMAIN': fqdn, 'CERTBOT_VALIDATION': auth_token, } record = mocker.patch('acmednsauth.authenticate.Record') Authenticate(environment=create_environment) record.assert_called_once_with(api_key, domain, hostname) record.has_calls([call().create(auth_token)])
"""Test the DigitalOcean backed ACME DNS Authentication Class.""" from acmednsauth.authenticate import Authenticate from mock import call def test_valid_data_calls_digital_ocean_record_creation( mocker, api_key, hostname, domain, fqdn, auth_token): create_environment = { 'DO_API_KEY': api_key, 'DO_DOMAIN': domain, 'CERTBOT_DOMAIN': fqdn, 'CERTBOT_VALIDATION': auth_token, } record = mocker.patch('acmednsauth.authenticate.Record') Authenticate(environment=create_environment) record.assert_called_once_with(api_key, domain, hostname) assert call().create(auth_token) in record.mock_calls
Fix Bug in Test Assertion
Fix Bug in Test Assertion Need to train myself better on red-green-refactor. The previous assert always passed, because I wasn't triggering an actual Mock method. I had to change to verifying that the call is in the list of calls. I've verified that it fails when the call isn't made from the code under test and that it passes when it is.
Python
apache-2.0
Jitsusama/lets-do-dns
"""Test the DigitalOcean backed ACME DNS Authentication Class.""" from acmednsauth.authenticate import Authenticate from mock import call def test_valid_data_calls_digital_ocean_record_creation( mocker, api_key, hostname, domain, fqdn, auth_token): create_environment = { 'DO_API_KEY': api_key, 'DO_DOMAIN': domain, 'CERTBOT_DOMAIN': fqdn, 'CERTBOT_VALIDATION': auth_token, } record = mocker.patch('acmednsauth.authenticate.Record') Authenticate(environment=create_environment) record.assert_called_once_with(api_key, domain, hostname) - record.has_calls([call().create(auth_token)]) + assert call().create(auth_token) in record.mock_calls
Fix Bug in Test Assertion
## Code Before: """Test the DigitalOcean backed ACME DNS Authentication Class.""" from acmednsauth.authenticate import Authenticate from mock import call def test_valid_data_calls_digital_ocean_record_creation( mocker, api_key, hostname, domain, fqdn, auth_token): create_environment = { 'DO_API_KEY': api_key, 'DO_DOMAIN': domain, 'CERTBOT_DOMAIN': fqdn, 'CERTBOT_VALIDATION': auth_token, } record = mocker.patch('acmednsauth.authenticate.Record') Authenticate(environment=create_environment) record.assert_called_once_with(api_key, domain, hostname) record.has_calls([call().create(auth_token)]) ## Instruction: Fix Bug in Test Assertion ## Code After: """Test the DigitalOcean backed ACME DNS Authentication Class.""" from acmednsauth.authenticate import Authenticate from mock import call def test_valid_data_calls_digital_ocean_record_creation( mocker, api_key, hostname, domain, fqdn, auth_token): create_environment = { 'DO_API_KEY': api_key, 'DO_DOMAIN': domain, 'CERTBOT_DOMAIN': fqdn, 'CERTBOT_VALIDATION': auth_token, } record = mocker.patch('acmednsauth.authenticate.Record') Authenticate(environment=create_environment) record.assert_called_once_with(api_key, domain, hostname) assert call().create(auth_token) in record.mock_calls
# ... existing code ... record.assert_called_once_with(api_key, domain, hostname) assert call().create(auth_token) in record.mock_calls # ... rest of the code ...
0da65e9051ec6bf0c72f8dcc856a76547a1a125d
drf_multiple_model/views.py
drf_multiple_model/views.py
from drf_multiple_model.mixins import FlatMultipleModelMixin, ObjectMultipleModelMixin from rest_framework.generics import GenericAPIView class FlatMultipleModelAPIView(FlatMultipleModelMixin, GenericAPIView): def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def initial(self, request, *args, **kwargs): super().initial(request, *args, **kwargs) if self.sorting_parameter_name in request.query_params: self.sorting_field = request.query_params.get(self.sorting_parameter_name) self.sort_descending = self.sorting_field[0] == '-' if self.sort_descending: self.sorting_field = self.sorting_field[1:] self.sorting_field = self.sorting_fields_map.get(self.sorting_field, self.sorting_field) def get_queryset(self): return None class ObjectMultipleModelAPIView(ObjectMultipleModelMixin, GenericAPIView): def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def get_queryset(self): return None
from drf_multiple_model.mixins import FlatMultipleModelMixin, ObjectMultipleModelMixin from rest_framework.generics import GenericAPIView class FlatMultipleModelAPIView(FlatMultipleModelMixin, GenericAPIView): def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def initial(self, request, *args, **kwargs): super(GenericAPIView, self).initial(request, *args, **kwargs) if self.sorting_parameter_name in request.query_params: # Extract sorting parameter from query string self.sorting_field = request.query_params.get(self.sorting_parameter_name) if self.sorting_field: # Handle sorting direction and sorting field mapping self.sort_descending = self.sorting_field[0] == '-' if self.sort_descending: self.sorting_field = self.sorting_field[1:] self.sorting_field = self.sorting_fields_map.get(self.sorting_field, self.sorting_field) def get_queryset(self): return None class ObjectMultipleModelAPIView(ObjectMultipleModelMixin, GenericAPIView): def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def get_queryset(self): return None
Fix initialization ofr sorting parameters
Fix initialization ofr sorting parameters
Python
mit
Axiologue/DjangoRestMultipleModels
from drf_multiple_model.mixins import FlatMultipleModelMixin, ObjectMultipleModelMixin from rest_framework.generics import GenericAPIView class FlatMultipleModelAPIView(FlatMultipleModelMixin, GenericAPIView): def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def initial(self, request, *args, **kwargs): - super().initial(request, *args, **kwargs) + super(GenericAPIView, self).initial(request, *args, **kwargs) if self.sorting_parameter_name in request.query_params: + # Extract sorting parameter from query string self.sorting_field = request.query_params.get(self.sorting_parameter_name) + + if self.sorting_field: + # Handle sorting direction and sorting field mapping self.sort_descending = self.sorting_field[0] == '-' if self.sort_descending: self.sorting_field = self.sorting_field[1:] self.sorting_field = self.sorting_fields_map.get(self.sorting_field, self.sorting_field) def get_queryset(self): return None class ObjectMultipleModelAPIView(ObjectMultipleModelMixin, GenericAPIView): def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def get_queryset(self): return None
Fix initialization ofr sorting parameters
## Code Before: from drf_multiple_model.mixins import FlatMultipleModelMixin, ObjectMultipleModelMixin from rest_framework.generics import GenericAPIView class FlatMultipleModelAPIView(FlatMultipleModelMixin, GenericAPIView): def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def initial(self, request, *args, **kwargs): super().initial(request, *args, **kwargs) if self.sorting_parameter_name in request.query_params: self.sorting_field = request.query_params.get(self.sorting_parameter_name) self.sort_descending = self.sorting_field[0] == '-' if self.sort_descending: self.sorting_field = self.sorting_field[1:] self.sorting_field = self.sorting_fields_map.get(self.sorting_field, self.sorting_field) def get_queryset(self): return None class ObjectMultipleModelAPIView(ObjectMultipleModelMixin, GenericAPIView): def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def get_queryset(self): return None ## Instruction: Fix initialization ofr sorting parameters ## Code After: from drf_multiple_model.mixins import FlatMultipleModelMixin, ObjectMultipleModelMixin from rest_framework.generics import GenericAPIView class FlatMultipleModelAPIView(FlatMultipleModelMixin, GenericAPIView): def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def initial(self, request, *args, **kwargs): super(GenericAPIView, self).initial(request, *args, **kwargs) if self.sorting_parameter_name in request.query_params: # Extract sorting parameter from query string self.sorting_field = request.query_params.get(self.sorting_parameter_name) if self.sorting_field: # Handle sorting direction and sorting field mapping self.sort_descending = self.sorting_field[0] == '-' if self.sort_descending: self.sorting_field = self.sorting_field[1:] self.sorting_field = self.sorting_fields_map.get(self.sorting_field, self.sorting_field) def get_queryset(self): return None class ObjectMultipleModelAPIView(ObjectMultipleModelMixin, GenericAPIView): def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def get_queryset(self): return None
// ... existing code ... def initial(self, request, *args, **kwargs): super(GenericAPIView, self).initial(request, *args, **kwargs) if self.sorting_parameter_name in request.query_params: # Extract sorting parameter from query string self.sorting_field = request.query_params.get(self.sorting_parameter_name) if self.sorting_field: # Handle sorting direction and sorting field mapping self.sort_descending = self.sorting_field[0] == '-' // ... rest of the code ...
59dd1dd68792b13ea75b4aaffc68983236d02ad3
config/urls.py
config/urls.py
from django.conf.urls import url, include from django.contrib import admin from django.views.generic import TemplateView from rest_framework.authtoken import views from apps.commands.urls import router urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', TemplateView.as_view(template_name='index.html')), # API url(r'^api/', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^api-token-auth/', views.obtain_auth_token) ]
from django.conf.urls import url, include from django.contrib import admin from django.views.generic import TemplateView from django.views.decorators.csrf import ensure_csrf_cookie from rest_framework.authtoken import views from apps.commands.urls import router urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', ensure_csrf_cookie(TemplateView.as_view(template_name='index.html'))), # API url(r'^api/', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^api-token-auth/', views.obtain_auth_token) ]
Make sure that we pass a CSRF cookie with value
Make sure that we pass a CSRF cookie with value We need to pass a CSRF cookie when we make a GET request because otherwise Angular would have no way of grabing the CSRF.
Python
mit
gopar/OhMyCommand,gopar/OhMyCommand,gopar/OhMyCommand
from django.conf.urls import url, include from django.contrib import admin from django.views.generic import TemplateView + from django.views.decorators.csrf import ensure_csrf_cookie from rest_framework.authtoken import views from apps.commands.urls import router urlpatterns = [ url(r'^admin/', admin.site.urls), - url(r'^$', TemplateView.as_view(template_name='index.html')), + url(r'^$', ensure_csrf_cookie(TemplateView.as_view(template_name='index.html'))), # API url(r'^api/', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^api-token-auth/', views.obtain_auth_token) ]
Make sure that we pass a CSRF cookie with value
## Code Before: from django.conf.urls import url, include from django.contrib import admin from django.views.generic import TemplateView from rest_framework.authtoken import views from apps.commands.urls import router urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', TemplateView.as_view(template_name='index.html')), # API url(r'^api/', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^api-token-auth/', views.obtain_auth_token) ] ## Instruction: Make sure that we pass a CSRF cookie with value ## Code After: from django.conf.urls import url, include from django.contrib import admin from django.views.generic import TemplateView from django.views.decorators.csrf import ensure_csrf_cookie from rest_framework.authtoken import views from apps.commands.urls import router urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', ensure_csrf_cookie(TemplateView.as_view(template_name='index.html'))), # API url(r'^api/', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^api-token-auth/', views.obtain_auth_token) ]
// ... existing code ... from django.views.generic import TemplateView from django.views.decorators.csrf import ensure_csrf_cookie // ... modified code ... url(r'^admin/', admin.site.urls), url(r'^$', ensure_csrf_cookie(TemplateView.as_view(template_name='index.html'))), # API // ... rest of the code ...
e120c264f16f89b197ff3416deaefb7f553611db
pages/urlconf_registry.py
pages/urlconf_registry.py
"""Django page CMS urlconf registry.""" from django.utils.translation import ugettext as _ class UrlconfAlreadyRegistered(Exception): """ An attempt was made to register a widget for Django page CMS more than once. """ class UrlconfNotFound(Exception): """ The requested widget was not found """ registry = [] def get_choices(): choices = [('', 'No delegation')] for reg in registry: if reg[2]: label = reg[2] else: label = reg[0] choices.append((reg[0], label)) return choices def register_urlconf(name, urlconf, label=None): for urlconf_tuple in registry: if urlconf_tuple[0] == name: raise UrlconfAlreadyRegistered( _('The urlconf %s has already been registered.') % name) urlconf_tuple = (name, urlconf, label, urlconf) registry.append(urlconf_tuple) def get_urlconf(name): for urlconf_tuple in registry: if urlconf_tuple[0] == name: return urlconf_tuple[1] raise UrlconfNotFound( _('The urlconf %s has not been registered.') % name)
"""Django page CMS urlconf registry.""" from django.utils.translation import ugettext as _ class UrlconfAlreadyRegistered(Exception): """ An attempt was made to register a urlconf for Django page CMS more than once. """ class UrlconfNotFound(Exception): """ The requested urlconf was not found """ registry = [] def get_choices(): choices = [('', 'No delegation')] for reg in registry: if reg[2]: label = reg[2] else: label = reg[0] choices.append((reg[0], label)) return choices def register_urlconf(name, urlconf, label=None): for urlconf_tuple in registry: if urlconf_tuple[0] == name: raise UrlconfAlreadyRegistered( _('The urlconf %s has already been registered.') % name) urlconf_tuple = (name, urlconf, label, urlconf) registry.append(urlconf_tuple) def get_urlconf(name): for urlconf_tuple in registry: if urlconf_tuple[0] == name: return urlconf_tuple[1] raise UrlconfNotFound( _('The urlconf %s has not been registered.') % name)
Fix typos in urlconf registry
Fix typos in urlconf registry
Python
bsd-3-clause
batiste/django-page-cms,remik/django-page-cms,oliciv/django-page-cms,oliciv/django-page-cms,remik/django-page-cms,pombredanne/django-page-cms-1,oliciv/django-page-cms,pombredanne/django-page-cms-1,remik/django-page-cms,akaihola/django-page-cms,batiste/django-page-cms,batiste/django-page-cms,akaihola/django-page-cms,remik/django-page-cms,pombredanne/django-page-cms-1,akaihola/django-page-cms
"""Django page CMS urlconf registry.""" from django.utils.translation import ugettext as _ class UrlconfAlreadyRegistered(Exception): """ - An attempt was made to register a widget for Django page CMS more + An attempt was made to register a urlconf for Django page CMS more than once. """ class UrlconfNotFound(Exception): """ - The requested widget was not found + The requested urlconf was not found """ registry = [] def get_choices(): choices = [('', 'No delegation')] for reg in registry: if reg[2]: label = reg[2] else: label = reg[0] choices.append((reg[0], label)) return choices def register_urlconf(name, urlconf, label=None): for urlconf_tuple in registry: if urlconf_tuple[0] == name: raise UrlconfAlreadyRegistered( _('The urlconf %s has already been registered.') % name) urlconf_tuple = (name, urlconf, label, urlconf) registry.append(urlconf_tuple) def get_urlconf(name): for urlconf_tuple in registry: if urlconf_tuple[0] == name: return urlconf_tuple[1] raise UrlconfNotFound( _('The urlconf %s has not been registered.') % name)
Fix typos in urlconf registry
## Code Before: """Django page CMS urlconf registry.""" from django.utils.translation import ugettext as _ class UrlconfAlreadyRegistered(Exception): """ An attempt was made to register a widget for Django page CMS more than once. """ class UrlconfNotFound(Exception): """ The requested widget was not found """ registry = [] def get_choices(): choices = [('', 'No delegation')] for reg in registry: if reg[2]: label = reg[2] else: label = reg[0] choices.append((reg[0], label)) return choices def register_urlconf(name, urlconf, label=None): for urlconf_tuple in registry: if urlconf_tuple[0] == name: raise UrlconfAlreadyRegistered( _('The urlconf %s has already been registered.') % name) urlconf_tuple = (name, urlconf, label, urlconf) registry.append(urlconf_tuple) def get_urlconf(name): for urlconf_tuple in registry: if urlconf_tuple[0] == name: return urlconf_tuple[1] raise UrlconfNotFound( _('The urlconf %s has not been registered.') % name) ## Instruction: Fix typos in urlconf registry ## Code After: """Django page CMS urlconf registry.""" from django.utils.translation import ugettext as _ class UrlconfAlreadyRegistered(Exception): """ An attempt was made to register a urlconf for Django page CMS more than once. """ class UrlconfNotFound(Exception): """ The requested urlconf was not found """ registry = [] def get_choices(): choices = [('', 'No delegation')] for reg in registry: if reg[2]: label = reg[2] else: label = reg[0] choices.append((reg[0], label)) return choices def register_urlconf(name, urlconf, label=None): for urlconf_tuple in registry: if urlconf_tuple[0] == name: raise UrlconfAlreadyRegistered( _('The urlconf %s has already been registered.') % name) urlconf_tuple = (name, urlconf, label, urlconf) registry.append(urlconf_tuple) def get_urlconf(name): for urlconf_tuple in registry: if urlconf_tuple[0] == name: return urlconf_tuple[1] raise UrlconfNotFound( _('The urlconf %s has not been registered.') % name)
// ... existing code ... """ An attempt was made to register a urlconf for Django page CMS more than once. // ... modified code ... """ The requested urlconf was not found """ // ... rest of the code ...
b5454286a2cfce07f4971b7bc56dd131402f8fe3
iati/__init__.py
iati/__init__.py
"""A top-level namespace package for IATI.""" __import__('pkg_resources').declare_namespace(__name__) from .codelists import Code, Codelist # noqa: F401 from .data import Dataset # noqa: F401 from .rulesets import Rule, Ruleset # noqa: F401 from .rulesets import RuleAtLeastOne, RuleDateOrder, RuleDependent, RuleNoMoreThanOne, RuleRegexMatches, RuleRegexNoMatches, RuleStartsWith, RuleSum, RuleUnique # noqa: F401 from .schemas import ActivitySchema, OrganisationSchema # noqa: F401
"""A top-level namespace package for IATI.""" from .codelists import Code, Codelist # noqa: F401 from .data import Dataset # noqa: F401 from .rulesets import Rule, Ruleset # noqa: F401 from .rulesets import RuleAtLeastOne, RuleDateOrder, RuleDependent, RuleNoMoreThanOne, RuleRegexMatches, RuleRegexNoMatches, RuleStartsWith, RuleSum, RuleUnique # noqa: F401 from .schemas import ActivitySchema, OrganisationSchema # noqa: F401 __import__('pkg_resources').declare_namespace(__name__)
Fix pylint error after iati.core -> iati
Fix pylint error after iati.core -> iati
Python
mit
IATI/iati.core,IATI/iati.core
"""A top-level namespace package for IATI.""" - __import__('pkg_resources').declare_namespace(__name__) - from .codelists import Code, Codelist # noqa: F401 from .data import Dataset # noqa: F401 from .rulesets import Rule, Ruleset # noqa: F401 from .rulesets import RuleAtLeastOne, RuleDateOrder, RuleDependent, RuleNoMoreThanOne, RuleRegexMatches, RuleRegexNoMatches, RuleStartsWith, RuleSum, RuleUnique # noqa: F401 from .schemas import ActivitySchema, OrganisationSchema # noqa: F401 + __import__('pkg_resources').declare_namespace(__name__) +
Fix pylint error after iati.core -> iati
## Code Before: """A top-level namespace package for IATI.""" __import__('pkg_resources').declare_namespace(__name__) from .codelists import Code, Codelist # noqa: F401 from .data import Dataset # noqa: F401 from .rulesets import Rule, Ruleset # noqa: F401 from .rulesets import RuleAtLeastOne, RuleDateOrder, RuleDependent, RuleNoMoreThanOne, RuleRegexMatches, RuleRegexNoMatches, RuleStartsWith, RuleSum, RuleUnique # noqa: F401 from .schemas import ActivitySchema, OrganisationSchema # noqa: F401 ## Instruction: Fix pylint error after iati.core -> iati ## Code After: """A top-level namespace package for IATI.""" from .codelists import Code, Codelist # noqa: F401 from .data import Dataset # noqa: F401 from .rulesets import Rule, Ruleset # noqa: F401 from .rulesets import RuleAtLeastOne, RuleDateOrder, RuleDependent, RuleNoMoreThanOne, RuleRegexMatches, RuleRegexNoMatches, RuleStartsWith, RuleSum, RuleUnique # noqa: F401 from .schemas import ActivitySchema, OrganisationSchema # noqa: F401 __import__('pkg_resources').declare_namespace(__name__)
# ... existing code ... """A top-level namespace package for IATI.""" from .codelists import Code, Codelist # noqa: F401 # ... modified code ... from .schemas import ActivitySchema, OrganisationSchema # noqa: F401 __import__('pkg_resources').declare_namespace(__name__) # ... rest of the code ...
9d0ba593ae5f7e23a1bd32573ad8e80dac6eb845
stalkr/cache.py
stalkr/cache.py
import os import requests class Cache: extensions = ["gif", "jpeg", "jpg", "png"] def __init__(self, directory): self.directory = directory if not os.path.isdir(directory): os.mkdir(directory) def get(self, key): for extension in self.extensions: filename = key + "." + extension path = os.path.join(self.directory, filename) if os.path.isfile(path): return path return None def set(self, key, url): res = requests.get(url) if res.status_code == 200: _, extension = os.path.splitext(url) filename = key + extension path = os.path.join(self.directory, filename) with open(path, "wb") as file: file.write(res.content) return True else: return False
import os import requests class UnknownExtensionException: def __init__(self, extension): self.extension = extension def __str__(self): return repr("{0}: unknown extension".format(self.extension)) class Cache: extensions = ["gif", "jpeg", "jpg", "png"] def __init__(self, directory): self.directory = directory if not os.path.isdir(directory): os.mkdir(directory) def get(self, key): for extension in self.extensions: filename = key + "." + extension path = os.path.join(self.directory, filename) if os.path.isfile(path): return path return None def set(self, key, url): res = requests.get(url) if res.status_code == 200: _, extension = os.path.splitext(url) if extension[1:] not in self.extensions: raise UnknownExtensionException(extension[1:]) filename = key + extension path = os.path.join(self.directory, filename) with open(path, "wb") as file: file.write(res.content) return True else: return False
Raise exception if the image file extension is unknown
Raise exception if the image file extension is unknown
Python
isc
helderm/stalkr,helderm/stalkr,helderm/stalkr,helderm/stalkr
import os import requests + + class UnknownExtensionException: + def __init__(self, extension): + self.extension = extension + + def __str__(self): + return repr("{0}: unknown extension".format(self.extension)) class Cache: extensions = ["gif", "jpeg", "jpg", "png"] def __init__(self, directory): self.directory = directory if not os.path.isdir(directory): os.mkdir(directory) def get(self, key): for extension in self.extensions: filename = key + "." + extension path = os.path.join(self.directory, filename) if os.path.isfile(path): return path return None def set(self, key, url): res = requests.get(url) if res.status_code == 200: _, extension = os.path.splitext(url) + if extension[1:] not in self.extensions: + raise UnknownExtensionException(extension[1:]) filename = key + extension path = os.path.join(self.directory, filename) with open(path, "wb") as file: file.write(res.content) return True else: return False
Raise exception if the image file extension is unknown
## Code Before: import os import requests class Cache: extensions = ["gif", "jpeg", "jpg", "png"] def __init__(self, directory): self.directory = directory if not os.path.isdir(directory): os.mkdir(directory) def get(self, key): for extension in self.extensions: filename = key + "." + extension path = os.path.join(self.directory, filename) if os.path.isfile(path): return path return None def set(self, key, url): res = requests.get(url) if res.status_code == 200: _, extension = os.path.splitext(url) filename = key + extension path = os.path.join(self.directory, filename) with open(path, "wb") as file: file.write(res.content) return True else: return False ## Instruction: Raise exception if the image file extension is unknown ## Code After: import os import requests class UnknownExtensionException: def __init__(self, extension): self.extension = extension def __str__(self): return repr("{0}: unknown extension".format(self.extension)) class Cache: extensions = ["gif", "jpeg", "jpg", "png"] def __init__(self, directory): self.directory = directory if not os.path.isdir(directory): os.mkdir(directory) def get(self, key): for extension in self.extensions: filename = key + "." + extension path = os.path.join(self.directory, filename) if os.path.isfile(path): return path return None def set(self, key, url): res = requests.get(url) if res.status_code == 200: _, extension = os.path.splitext(url) if extension[1:] not in self.extensions: raise UnknownExtensionException(extension[1:]) filename = key + extension path = os.path.join(self.directory, filename) with open(path, "wb") as file: file.write(res.content) return True else: return False
# ... existing code ... import requests class UnknownExtensionException: def __init__(self, extension): self.extension = extension def __str__(self): return repr("{0}: unknown extension".format(self.extension)) # ... modified code ... _, extension = os.path.splitext(url) if extension[1:] not in self.extensions: raise UnknownExtensionException(extension[1:]) filename = key + extension # ... rest of the code ...
ca2b02d551e9bb4c8625ae79f7878892673fa731
corehq/apps/es/domains.py
corehq/apps/es/domains.py
from .es_query import HQESQuery from . import filters class DomainES(HQESQuery): index = 'domains' @property def builtin_filters(self): return [ real_domains, commconnect_domains, created, ] + super(DomainES, self).builtin_filters def real_domains(): return filters.term("is_test", False) def commconnect_domains(): return filters.term("commconnect_enabled", True) def created(gt=None, gte=None, lt=None, lte=None): return filters.date_range('date_created', gt, gte, lt, lte)
from .es_query import HQESQuery from . import filters class DomainES(HQESQuery): index = 'domains' @property def builtin_filters(self): return [ real_domains, commcare_domains, commconnect_domains, commtrack_domains, created, ] + super(DomainES, self).builtin_filters def real_domains(): return filters.term("is_test", False) def commcare_domains(): return filters.AND(filters.term("commconnect_enabled", False), filters.term("commtrack_enabled", False)) def commconnect_domains(): return filters.term("commconnect_enabled", True) def commtrack_domains(): return filters.term("commtrack_enabled", True) def created(gt=None, gte=None, lt=None, lte=None): return filters.date_range('date_created', gt, gte, lt, lte)
Add CommCare, CommTrack filters for DomainES
Add CommCare, CommTrack filters for DomainES
Python
bsd-3-clause
qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,puttarajubr/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq
from .es_query import HQESQuery from . import filters class DomainES(HQESQuery): index = 'domains' @property def builtin_filters(self): return [ real_domains, + commcare_domains, commconnect_domains, + commtrack_domains, created, ] + super(DomainES, self).builtin_filters def real_domains(): return filters.term("is_test", False) + def commcare_domains(): + return filters.AND(filters.term("commconnect_enabled", False), + filters.term("commtrack_enabled", False)) + + def commconnect_domains(): return filters.term("commconnect_enabled", True) + + + def commtrack_domains(): + return filters.term("commtrack_enabled", True) def created(gt=None, gte=None, lt=None, lte=None): return filters.date_range('date_created', gt, gte, lt, lte)
Add CommCare, CommTrack filters for DomainES
## Code Before: from .es_query import HQESQuery from . import filters class DomainES(HQESQuery): index = 'domains' @property def builtin_filters(self): return [ real_domains, commconnect_domains, created, ] + super(DomainES, self).builtin_filters def real_domains(): return filters.term("is_test", False) def commconnect_domains(): return filters.term("commconnect_enabled", True) def created(gt=None, gte=None, lt=None, lte=None): return filters.date_range('date_created', gt, gte, lt, lte) ## Instruction: Add CommCare, CommTrack filters for DomainES ## Code After: from .es_query import HQESQuery from . import filters class DomainES(HQESQuery): index = 'domains' @property def builtin_filters(self): return [ real_domains, commcare_domains, commconnect_domains, commtrack_domains, created, ] + super(DomainES, self).builtin_filters def real_domains(): return filters.term("is_test", False) def commcare_domains(): return filters.AND(filters.term("commconnect_enabled", False), filters.term("commtrack_enabled", False)) def commconnect_domains(): return filters.term("commconnect_enabled", True) def commtrack_domains(): return filters.term("commtrack_enabled", True) def created(gt=None, gte=None, lt=None, lte=None): return filters.date_range('date_created', gt, gte, lt, lte)
... real_domains, commcare_domains, commconnect_domains, commtrack_domains, created, ... def commcare_domains(): return filters.AND(filters.term("commconnect_enabled", False), filters.term("commtrack_enabled", False)) def commconnect_domains(): ... def commtrack_domains(): return filters.term("commtrack_enabled", True) def created(gt=None, gte=None, lt=None, lte=None): ...
025c95a59b079d630c778646d5c82f5e0679b47c
sale_automatic_workflow/models/account_invoice.py
sale_automatic_workflow/models/account_invoice.py
from odoo import models, fields class AccountInvoice(models.Model): _inherit = "account.invoice" workflow_process_id = fields.Many2one( comodel_name='sale.workflow.process', string='Sale Workflow Process' )
from odoo import models, fields class AccountInvoice(models.Model): _inherit = "account.invoice" workflow_process_id = fields.Many2one( comodel_name='sale.workflow.process', string='Sale Workflow Process', copy=False, )
Fix issue on account.invoice about workflow_process_id: if a user duplicate an invoice, it copy also the workflow and validations (the reason of bugs)
[FIX] Fix issue on account.invoice about workflow_process_id: if a user duplicate an invoice, it copy also the workflow and validations (the reason of bugs)
Python
agpl-3.0
kittiu/sale-workflow,kittiu/sale-workflow
- from odoo import models, fields class AccountInvoice(models.Model): _inherit = "account.invoice" workflow_process_id = fields.Many2one( comodel_name='sale.workflow.process', - string='Sale Workflow Process' + string='Sale Workflow Process', + copy=False, )
Fix issue on account.invoice about workflow_process_id: if a user duplicate an invoice, it copy also the workflow and validations (the reason of bugs)
## Code Before: from odoo import models, fields class AccountInvoice(models.Model): _inherit = "account.invoice" workflow_process_id = fields.Many2one( comodel_name='sale.workflow.process', string='Sale Workflow Process' ) ## Instruction: Fix issue on account.invoice about workflow_process_id: if a user duplicate an invoice, it copy also the workflow and validations (the reason of bugs) ## Code After: from odoo import models, fields class AccountInvoice(models.Model): _inherit = "account.invoice" workflow_process_id = fields.Many2one( comodel_name='sale.workflow.process', string='Sale Workflow Process', copy=False, )
# ... existing code ... from odoo import models, fields # ... modified code ... comodel_name='sale.workflow.process', string='Sale Workflow Process', copy=False, ) # ... rest of the code ...
a06dc82df053ea47f8a39b46d938f52679b2cff5
grow/preprocessors/blogger_test.py
grow/preprocessors/blogger_test.py
from . import google_drive from grow.pods import pods from grow.pods import storage from grow.testing import testing import cStringIO import csv import json import unittest import yaml class BloggerTestCase(testing.TestCase): def test_run(self): pod = testing.create_pod() fields = { 'preprocessors': [{ 'name': 'blogger', 'kind': 'blogger', 'blog_id': '10861780', # Official Google blog. 'collection': '/content/posts/', 'markdown': True, 'authenticated': False, 'inject': True, }], } pod.write_yaml('/podspec.yaml', fields) fields = { '$path': '/{date}/{slug}/', '$view': '/views/base.html', } pod.write_yaml('/content/posts/_blueprint.yaml', fields) content = '{{doc.html|safe}}' pod.write_file('/views/base.html', content) # Weak test to verify preprocessor runs. pod.preprocess(['blogger']) # Verify inject. collection = pod.get_collection('/content/posts') doc = collection.docs()[0] preprocessor = pod.list_preprocessors()[0] preprocessor.inject(doc) if __name__ == '__main__': unittest.main()
from . import google_drive from grow.pods import pods from grow.pods import storage from grow.testing import testing import cStringIO import csv import json import unittest import yaml class BloggerTestCase(testing.TestCase): def test_run(self): pod = testing.create_pod() fields = { 'preprocessors': [{ 'name': 'blogger', 'kind': 'blogger', 'blog_id': '4154157974596966834', 'collection': '/content/posts/', 'markdown': True, 'authenticated': False, 'inject': True, }], } pod.write_yaml('/podspec.yaml', fields) fields = { '$path': '/{date}/{slug}/', '$view': '/views/base.html', } pod.write_yaml('/content/posts/_blueprint.yaml', fields) content = '{{doc.html|safe}}' pod.write_file('/views/base.html', content) # Weak test to verify preprocessor runs. pod.preprocess(['blogger']) # Verify inject. collection = pod.get_collection('/content/posts') doc = collection.docs()[0] preprocessor = pod.list_preprocessors()[0] preprocessor.inject(doc) if __name__ == '__main__': unittest.main()
Use different blog for test data.
Use different blog for test data.
Python
mit
grow/pygrow,denmojo/pygrow,denmojo/pygrow,denmojo/pygrow,grow/grow,grow/pygrow,grow/grow,grow/grow,grow/grow,grow/pygrow,denmojo/pygrow
from . import google_drive from grow.pods import pods from grow.pods import storage from grow.testing import testing import cStringIO import csv import json import unittest import yaml class BloggerTestCase(testing.TestCase): def test_run(self): pod = testing.create_pod() fields = { 'preprocessors': [{ 'name': 'blogger', 'kind': 'blogger', - 'blog_id': '10861780', # Official Google blog. + 'blog_id': '4154157974596966834', 'collection': '/content/posts/', 'markdown': True, 'authenticated': False, 'inject': True, }], } pod.write_yaml('/podspec.yaml', fields) fields = { '$path': '/{date}/{slug}/', '$view': '/views/base.html', } pod.write_yaml('/content/posts/_blueprint.yaml', fields) content = '{{doc.html|safe}}' pod.write_file('/views/base.html', content) # Weak test to verify preprocessor runs. pod.preprocess(['blogger']) # Verify inject. collection = pod.get_collection('/content/posts') doc = collection.docs()[0] preprocessor = pod.list_preprocessors()[0] preprocessor.inject(doc) if __name__ == '__main__': unittest.main()
Use different blog for test data.
## Code Before: from . import google_drive from grow.pods import pods from grow.pods import storage from grow.testing import testing import cStringIO import csv import json import unittest import yaml class BloggerTestCase(testing.TestCase): def test_run(self): pod = testing.create_pod() fields = { 'preprocessors': [{ 'name': 'blogger', 'kind': 'blogger', 'blog_id': '10861780', # Official Google blog. 'collection': '/content/posts/', 'markdown': True, 'authenticated': False, 'inject': True, }], } pod.write_yaml('/podspec.yaml', fields) fields = { '$path': '/{date}/{slug}/', '$view': '/views/base.html', } pod.write_yaml('/content/posts/_blueprint.yaml', fields) content = '{{doc.html|safe}}' pod.write_file('/views/base.html', content) # Weak test to verify preprocessor runs. pod.preprocess(['blogger']) # Verify inject. collection = pod.get_collection('/content/posts') doc = collection.docs()[0] preprocessor = pod.list_preprocessors()[0] preprocessor.inject(doc) if __name__ == '__main__': unittest.main() ## Instruction: Use different blog for test data. ## Code After: from . import google_drive from grow.pods import pods from grow.pods import storage from grow.testing import testing import cStringIO import csv import json import unittest import yaml class BloggerTestCase(testing.TestCase): def test_run(self): pod = testing.create_pod() fields = { 'preprocessors': [{ 'name': 'blogger', 'kind': 'blogger', 'blog_id': '4154157974596966834', 'collection': '/content/posts/', 'markdown': True, 'authenticated': False, 'inject': True, }], } pod.write_yaml('/podspec.yaml', fields) fields = { '$path': '/{date}/{slug}/', '$view': '/views/base.html', } pod.write_yaml('/content/posts/_blueprint.yaml', fields) content = '{{doc.html|safe}}' pod.write_file('/views/base.html', content) # Weak test to verify preprocessor runs. pod.preprocess(['blogger']) # Verify inject. collection = pod.get_collection('/content/posts') doc = collection.docs()[0] preprocessor = pod.list_preprocessors()[0] preprocessor.inject(doc) if __name__ == '__main__': unittest.main()
// ... existing code ... 'kind': 'blogger', 'blog_id': '4154157974596966834', 'collection': '/content/posts/', // ... rest of the code ...
b89a6a10e2a1beafe893faa6eec6e2562ded7492
local-celery.py
local-celery.py
import sys from deployer.celery import app if __name__ == '__main__': argv = sys.argv if len(sys.argv) > 1 else [__file__, '--loglevel=info'] app.worker_main(argv=argv)
import sys from deployer.celery import app if __name__ == '__main__': argv = sys.argv if len(sys.argv) > 1 else [__file__, '--loglevel=info'] app.conf.CELERYD_CONCURRENCY = 2 app.worker_main(argv=argv)
Set concurrency to 2 for local
Set concurrency to 2 for local
Python
mit
totem/cluster-deployer,totem/cluster-deployer,totem/cluster-deployer
import sys from deployer.celery import app if __name__ == '__main__': argv = sys.argv if len(sys.argv) > 1 else [__file__, '--loglevel=info'] + app.conf.CELERYD_CONCURRENCY = 2 app.worker_main(argv=argv)
Set concurrency to 2 for local
## Code Before: import sys from deployer.celery import app if __name__ == '__main__': argv = sys.argv if len(sys.argv) > 1 else [__file__, '--loglevel=info'] app.worker_main(argv=argv) ## Instruction: Set concurrency to 2 for local ## Code After: import sys from deployer.celery import app if __name__ == '__main__': argv = sys.argv if len(sys.argv) > 1 else [__file__, '--loglevel=info'] app.conf.CELERYD_CONCURRENCY = 2 app.worker_main(argv=argv)
// ... existing code ... argv = sys.argv if len(sys.argv) > 1 else [__file__, '--loglevel=info'] app.conf.CELERYD_CONCURRENCY = 2 app.worker_main(argv=argv) // ... rest of the code ...
2f6c82d74592c80b5042c0b808a658650896cbec
rebulk/__init__.py
rebulk/__init__.py
from .rebulk import Rebulk from .match import Match from .rules import Rule from .pattern import REGEX_AVAILABLE
from .rebulk import Rebulk from .match import Match from .rules import Rule, AppendMatchRule, RemoveMatchRule from .pattern import REGEX_AVAILABLE
Add global imports for rules classes
Add global imports for rules classes
Python
mit
Toilal/rebulk
from .rebulk import Rebulk from .match import Match - from .rules import Rule + from .rules import Rule, AppendMatchRule, RemoveMatchRule from .pattern import REGEX_AVAILABLE
Add global imports for rules classes
## Code Before: from .rebulk import Rebulk from .match import Match from .rules import Rule from .pattern import REGEX_AVAILABLE ## Instruction: Add global imports for rules classes ## Code After: from .rebulk import Rebulk from .match import Match from .rules import Rule, AppendMatchRule, RemoveMatchRule from .pattern import REGEX_AVAILABLE
... from .match import Match from .rules import Rule, AppendMatchRule, RemoveMatchRule from .pattern import REGEX_AVAILABLE ...
d8e5dce3489817a5065c045688b03f9e85c0b9a4
tests/data_structures/commons/binary_search_tree_unit_test.py
tests/data_structures/commons/binary_search_tree_unit_test.py
import unittest from pyalgs.data_structures.commons.binary_search_tree import BinarySearchTree class BinarySearchTreeUnitTest(unittest.TestCase): def test_binarySearchTree(self): bst = BinarySearchTree.create() bst.put("one", 1) bst.put("two", 2) bst.put("three", 3) bst.put("six", 6) bst.put("ten", 10) self.assertEqual(1, bst.get("one")) self.assertEqual(2, bst.get("two")) self.assertEqual(3, bst.get("three")) self.assertTrue(bst.contains_key("one")) self.assertTrue(bst.contains_key("two")) self.assertEqual(5, bst.size()) self.assertFalse(bst.is_empty()) bst.delete("one") self.assertFalse(bst.contains_key("one")) self.assertEqual(4, bst.size()) bst.delete("ten") self.assertFalse(bst.contains_key("ten")) self.assertEqual(3, bst.size()) bst.delete("three") self.assertFalse(bst.contains_key("three")) self.assertEqual(2, bst.size()) if __name__ == '__main__': unittest.main()
import unittest from pyalgs.data_structures.commons.binary_search_tree import BinarySearchTree class BinarySearchTreeUnitTest(unittest.TestCase): def test_binarySearchTree(self): bst = BinarySearchTree.create() bst.put("one", 1) bst.put("two", 2) bst.put("three", 3) bst.put("six", 6) bst.put("ten", 10) bst.put("ten", 10) self.assertEqual(1, bst.get("one")) self.assertEqual(2, bst.get("two")) self.assertEqual(3, bst.get("three")) self.assertTrue(bst.contains_key("one")) self.assertTrue(bst.contains_key("two")) self.assertEqual(5, bst.size()) self.assertFalse(bst.is_empty()) bst.delete("one") self.assertFalse(bst.contains_key("one")) self.assertEqual(4, bst.size()) bst.delete("ten") self.assertFalse(bst.contains_key("ten")) self.assertEqual(3, bst.size()) bst.delete("three") self.assertFalse(bst.contains_key("three")) self.assertEqual(2, bst.size()) for i in range(100): bst.put(str(i), i) self.assertEqual(i, bst.get(str(i))) for i in range(100): bst.delete(str(i)) self.assertFalse(bst.contains_key(str(i))) if __name__ == '__main__': unittest.main()
Increase the unit test coverage for the binary search tree
Increase the unit test coverage for the binary search tree
Python
bsd-3-clause
chen0040/pyalgs
import unittest from pyalgs.data_structures.commons.binary_search_tree import BinarySearchTree class BinarySearchTreeUnitTest(unittest.TestCase): def test_binarySearchTree(self): bst = BinarySearchTree.create() bst.put("one", 1) bst.put("two", 2) bst.put("three", 3) bst.put("six", 6) + bst.put("ten", 10) bst.put("ten", 10) self.assertEqual(1, bst.get("one")) self.assertEqual(2, bst.get("two")) self.assertEqual(3, bst.get("three")) self.assertTrue(bst.contains_key("one")) self.assertTrue(bst.contains_key("two")) self.assertEqual(5, bst.size()) self.assertFalse(bst.is_empty()) bst.delete("one") self.assertFalse(bst.contains_key("one")) self.assertEqual(4, bst.size()) bst.delete("ten") self.assertFalse(bst.contains_key("ten")) self.assertEqual(3, bst.size()) bst.delete("three") self.assertFalse(bst.contains_key("three")) self.assertEqual(2, bst.size()) + for i in range(100): + bst.put(str(i), i) + self.assertEqual(i, bst.get(str(i))) + + for i in range(100): + bst.delete(str(i)) + self.assertFalse(bst.contains_key(str(i))) + if __name__ == '__main__': unittest.main()
Increase the unit test coverage for the binary search tree
## Code Before: import unittest from pyalgs.data_structures.commons.binary_search_tree import BinarySearchTree class BinarySearchTreeUnitTest(unittest.TestCase): def test_binarySearchTree(self): bst = BinarySearchTree.create() bst.put("one", 1) bst.put("two", 2) bst.put("three", 3) bst.put("six", 6) bst.put("ten", 10) self.assertEqual(1, bst.get("one")) self.assertEqual(2, bst.get("two")) self.assertEqual(3, bst.get("three")) self.assertTrue(bst.contains_key("one")) self.assertTrue(bst.contains_key("two")) self.assertEqual(5, bst.size()) self.assertFalse(bst.is_empty()) bst.delete("one") self.assertFalse(bst.contains_key("one")) self.assertEqual(4, bst.size()) bst.delete("ten") self.assertFalse(bst.contains_key("ten")) self.assertEqual(3, bst.size()) bst.delete("three") self.assertFalse(bst.contains_key("three")) self.assertEqual(2, bst.size()) if __name__ == '__main__': unittest.main() ## Instruction: Increase the unit test coverage for the binary search tree ## Code After: import unittest from pyalgs.data_structures.commons.binary_search_tree import BinarySearchTree class BinarySearchTreeUnitTest(unittest.TestCase): def test_binarySearchTree(self): bst = BinarySearchTree.create() bst.put("one", 1) bst.put("two", 2) bst.put("three", 3) bst.put("six", 6) bst.put("ten", 10) bst.put("ten", 10) self.assertEqual(1, bst.get("one")) self.assertEqual(2, bst.get("two")) self.assertEqual(3, bst.get("three")) self.assertTrue(bst.contains_key("one")) self.assertTrue(bst.contains_key("two")) self.assertEqual(5, bst.size()) self.assertFalse(bst.is_empty()) bst.delete("one") self.assertFalse(bst.contains_key("one")) self.assertEqual(4, bst.size()) bst.delete("ten") self.assertFalse(bst.contains_key("ten")) self.assertEqual(3, bst.size()) bst.delete("three") self.assertFalse(bst.contains_key("three")) self.assertEqual(2, bst.size()) for i in range(100): bst.put(str(i), i) self.assertEqual(i, bst.get(str(i))) for i in range(100): bst.delete(str(i)) self.assertFalse(bst.contains_key(str(i))) if __name__ == '__main__': unittest.main()
// ... existing code ... bst.put("six", 6) bst.put("ten", 10) bst.put("ten", 10) // ... modified code ... for i in range(100): bst.put(str(i), i) self.assertEqual(i, bst.get(str(i))) for i in range(100): bst.delete(str(i)) self.assertFalse(bst.contains_key(str(i))) if __name__ == '__main__': // ... rest of the code ...
ecd201216562c8b802fada27e2f79cda5b05a4d5
cron/__init__.py
cron/__init__.py
import schedule import settings from .poll_pull_requests import poll_pull_requests as poll_pull_requests from .restart_homepage import restart_homepage as restart_homepage def schedule_jobs(): schedule.every(settings.PULL_REQUEST_POLLING_INTERVAL_SECONDS).seconds.do(poll_pull_requests) schedule.every(settings.FALLBACK_WINDOW).hours.do(check_fallback) schedule.every(120).seconds.do(restart_homepage)
import schedule import settings from .poll_pull_requests import poll_pull_requests as poll_pull_requests from .restart_homepage import restart_homepage as restart_homepage def schedule_jobs(): schedule.every(settings.PULL_REQUEST_POLLING_INTERVAL_SECONDS).seconds.do(poll_pull_requests) schedule.every(settings.FALLBACK_WINDOW_SECONDS).seconds.do(check_fallback) schedule.every(120).seconds.do(restart_homepage)
Change hours to seconds in cron job
Change hours to seconds in cron job
Python
mit
amoffat/Chaos,eukaryote31/chaos,phil-r/chaos,g19fanatic/chaos,phil-r/chaos,botchaos/Chaos,Chaosthebot/Chaos,mark-i-m/Chaos,chaosbot/Chaos,g19fanatic/chaos,phil-r/chaos,hongaar/chaos,rudehn/chaos,rudehn/chaos,Chaosthebot/Chaos,botchaos/Chaos,mpnordland/chaos,amoffat/Chaos,mark-i-m/Chaos,chaosbot/Chaos,amoffat/Chaos,amoffat/Chaos,mpnordland/chaos,eukaryote31/chaos,botchaos/Chaos,amoffat/Chaos,chaosbot/Chaos,mpnordland/chaos,eukaryote31/chaos,Chaosthebot/Chaos,rudehn/chaos,eamanu/Chaos,hongaar/chaos,g19fanatic/chaos,mpnordland/chaos,g19fanatic/chaos,eamanu/Chaos,g19fanatic/chaos,rudehn/chaos,Chaosthebot/Chaos,mark-i-m/Chaos,eukaryote31/chaos,mpnordland/chaos,eamanu/Chaos,eukaryote31/chaos,chaosbot/Chaos,hongaar/chaos,botchaos/Chaos,chaosbot/Chaos,phil-r/chaos,mark-i-m/Chaos,eamanu/Chaos,hongaar/chaos,rudehn/chaos,Chaosthebot/Chaos,hongaar/chaos,mark-i-m/Chaos,eamanu/Chaos,phil-r/chaos,botchaos/Chaos
import schedule import settings from .poll_pull_requests import poll_pull_requests as poll_pull_requests from .restart_homepage import restart_homepage as restart_homepage def schedule_jobs(): schedule.every(settings.PULL_REQUEST_POLLING_INTERVAL_SECONDS).seconds.do(poll_pull_requests) - schedule.every(settings.FALLBACK_WINDOW).hours.do(check_fallback) + schedule.every(settings.FALLBACK_WINDOW_SECONDS).seconds.do(check_fallback) schedule.every(120).seconds.do(restart_homepage)
Change hours to seconds in cron job
## Code Before: import schedule import settings from .poll_pull_requests import poll_pull_requests as poll_pull_requests from .restart_homepage import restart_homepage as restart_homepage def schedule_jobs(): schedule.every(settings.PULL_REQUEST_POLLING_INTERVAL_SECONDS).seconds.do(poll_pull_requests) schedule.every(settings.FALLBACK_WINDOW).hours.do(check_fallback) schedule.every(120).seconds.do(restart_homepage) ## Instruction: Change hours to seconds in cron job ## Code After: import schedule import settings from .poll_pull_requests import poll_pull_requests as poll_pull_requests from .restart_homepage import restart_homepage as restart_homepage def schedule_jobs(): schedule.every(settings.PULL_REQUEST_POLLING_INTERVAL_SECONDS).seconds.do(poll_pull_requests) schedule.every(settings.FALLBACK_WINDOW_SECONDS).seconds.do(check_fallback) schedule.every(120).seconds.do(restart_homepage)
... schedule.every(settings.PULL_REQUEST_POLLING_INTERVAL_SECONDS).seconds.do(poll_pull_requests) schedule.every(settings.FALLBACK_WINDOW_SECONDS).seconds.do(check_fallback) schedule.every(120).seconds.do(restart_homepage) ...
c0ab344235fdd7df8e32c499124596d20f9d9e52
src/tempel/forms.py
src/tempel/forms.py
from django import forms from tempel import utils class EntryForm(forms.Form): language = forms.ChoiceField(choices=utils.get_languages(), initial="python") content = forms.CharField(widget=forms.Textarea) private = forms.BooleanField(required=False)
from django import forms from tempel import utils class EntryForm(forms.Form): language = forms.ChoiceField(choices=utils.get_languages(), initial="python") content = forms.CharField(widget=forms.Textarea) private = forms.BooleanField(required=False) class EditForm(forms.Form): language = forms.ChoiceField(choices=utils.get_languages(), initial="python") content = forms.CharField(widget=forms.Textarea)
Add EditForm that does not have 'private' field.
Add EditForm that does not have 'private' field.
Python
agpl-3.0
fajran/tempel
from django import forms from tempel import utils class EntryForm(forms.Form): language = forms.ChoiceField(choices=utils.get_languages(), initial="python") content = forms.CharField(widget=forms.Textarea) private = forms.BooleanField(required=False) + class EditForm(forms.Form): + language = forms.ChoiceField(choices=utils.get_languages(), + initial="python") + content = forms.CharField(widget=forms.Textarea) +
Add EditForm that does not have 'private' field.
## Code Before: from django import forms from tempel import utils class EntryForm(forms.Form): language = forms.ChoiceField(choices=utils.get_languages(), initial="python") content = forms.CharField(widget=forms.Textarea) private = forms.BooleanField(required=False) ## Instruction: Add EditForm that does not have 'private' field. ## Code After: from django import forms from tempel import utils class EntryForm(forms.Form): language = forms.ChoiceField(choices=utils.get_languages(), initial="python") content = forms.CharField(widget=forms.Textarea) private = forms.BooleanField(required=False) class EditForm(forms.Form): language = forms.ChoiceField(choices=utils.get_languages(), initial="python") content = forms.CharField(widget=forms.Textarea)
// ... existing code ... class EditForm(forms.Form): language = forms.ChoiceField(choices=utils.get_languages(), initial="python") content = forms.CharField(widget=forms.Textarea) // ... rest of the code ...
fd19236999eccd9cbf049bc5b8917cd603974f97
centerline/__init__.py
centerline/__init__.py
from .centerline import Centerline __all__ = ['Centerline']
from __future__ import unicode_literals from . import utils from .centerline import Centerline __all__ = ['utils', 'Centerline']
Add the utils module to the package index
Add the utils module to the package index
Python
mit
fitodic/polygon-centerline,fitodic/centerline,fitodic/centerline
+ + from __future__ import unicode_literals + + from . import utils from .centerline import Centerline - __all__ = ['Centerline'] + __all__ = ['utils', 'Centerline']
Add the utils module to the package index
## Code Before: from .centerline import Centerline __all__ = ['Centerline'] ## Instruction: Add the utils module to the package index ## Code After: from __future__ import unicode_literals from . import utils from .centerline import Centerline __all__ = ['utils', 'Centerline']
// ... existing code ... from __future__ import unicode_literals from . import utils from .centerline import Centerline // ... modified code ... __all__ = ['utils', 'Centerline'] // ... rest of the code ...
3d2f9087e62006f8a5f19476ae23324a4cfa7793
regex.py
regex.py
import re import sys f = open ('/var/local/meTypesetTests/tests/testOutput/'+sys.argv[1] +'/nlm/out.xml', "r") print ("open operation complete") fd = f.read() s = '' fd = pattern = re.compile(r'(?:(&#\d*|>))(.*?)(?=(&#\d*|<))') for e in re.findall(pattern, fd): s += ' ' s += e[1] s = re.sub('-', ' ', s) s = re.sub(r'\,', ' ', s) s = re.sub(r'\.', ' ', s) s = re.sub('\'', '', s) s = re.sub(r'\;', ' ', s) s = re.sub('s', ' ', s) s = re.sub(r'\(.*?\)', ' ', s) s = re.sub(r'(\[.*?\])', ' ', s) f.close() o = open ( '/var/local/meTypesetTests/tests/regexOutput/'+sys.argv[1], "w") o.write(s) o.close()
import re import sys f = open ('/var/local/meTypesetTests/tests/testOutput/'+sys.argv[1] +'/nlm/out.xml', "r") print ("open operation complete") fd = f.read() s = '' fd = re.sub(r'\&lt.*?\&gt\;', ' ', fd) pattern = re.compile(r'(?:(&#\d*|>))(.*?)(?=(&#\d*|<))') for e in re.findall(pattern, fd): s += ' ' s += e[1] s = re.sub('-', ' ', s) s = re.sub(r'\,', ' ', s) s = re.sub(r'\.', ' ', s) s = re.sub('\'', '', s) s = re.sub(r'\;', ' ', s) s = re.sub('s', ' ', s) s = re.sub(r'\(.*?\)', ' ', s) s = re.sub(r'(\[.*?\])', ' ', s) f.close() o = open ( '/var/local/meTypesetTests/tests/regexOutput/'+sys.argv[1], "w") o.write(s) o.close()
Update of work over prior couple weeks.
Update of work over prior couple weeks.
Python
mit
jnicolls/meTypeset-Test,jnicolls/Joseph
import re import sys f = open ('/var/local/meTypesetTests/tests/testOutput/'+sys.argv[1] +'/nlm/out.xml', "r") print ("open operation complete") fd = f.read() s = '' - fd = + fd = re.sub(r'\&lt.*?\&gt\;', ' ', fd) + pattern = re.compile(r'(?:(&#\d*|>))(.*?)(?=(&#\d*|<))') for e in re.findall(pattern, fd): s += ' ' s += e[1] s = re.sub('-', ' ', s) s = re.sub(r'\,', ' ', s) s = re.sub(r'\.', ' ', s) s = re.sub('\'', '', s) s = re.sub(r'\;', ' ', s) s = re.sub('s', ' ', s) s = re.sub(r'\(.*?\)', ' ', s) s = re.sub(r'(\[.*?\])', ' ', s) f.close() o = open ( '/var/local/meTypesetTests/tests/regexOutput/'+sys.argv[1], "w") o.write(s) o.close()
Update of work over prior couple weeks.
## Code Before: import re import sys f = open ('/var/local/meTypesetTests/tests/testOutput/'+sys.argv[1] +'/nlm/out.xml', "r") print ("open operation complete") fd = f.read() s = '' fd = pattern = re.compile(r'(?:(&#\d*|>))(.*?)(?=(&#\d*|<))') for e in re.findall(pattern, fd): s += ' ' s += e[1] s = re.sub('-', ' ', s) s = re.sub(r'\,', ' ', s) s = re.sub(r'\.', ' ', s) s = re.sub('\'', '', s) s = re.sub(r'\;', ' ', s) s = re.sub('s', ' ', s) s = re.sub(r'\(.*?\)', ' ', s) s = re.sub(r'(\[.*?\])', ' ', s) f.close() o = open ( '/var/local/meTypesetTests/tests/regexOutput/'+sys.argv[1], "w") o.write(s) o.close() ## Instruction: Update of work over prior couple weeks. ## Code After: import re import sys f = open ('/var/local/meTypesetTests/tests/testOutput/'+sys.argv[1] +'/nlm/out.xml', "r") print ("open operation complete") fd = f.read() s = '' fd = re.sub(r'\&lt.*?\&gt\;', ' ', fd) pattern = re.compile(r'(?:(&#\d*|>))(.*?)(?=(&#\d*|<))') for e in re.findall(pattern, fd): s += ' ' s += e[1] s = re.sub('-', ' ', s) s = re.sub(r'\,', ' ', s) s = re.sub(r'\.', ' ', s) s = re.sub('\'', '', s) s = re.sub(r'\;', ' ', s) s = re.sub('s', ' ', s) s = re.sub(r'\(.*?\)', ' ', s) s = re.sub(r'(\[.*?\])', ' ', s) f.close() o = open ( '/var/local/meTypesetTests/tests/regexOutput/'+sys.argv[1], "w") o.write(s) o.close()
# ... existing code ... fd = re.sub(r'\&lt.*?\&gt\;', ' ', fd) pattern = re.compile(r'(?:(&#\d*|>))(.*?)(?=(&#\d*|<))') # ... rest of the code ...
1f8b54d22cee5653254514bf07c1b4cb1eb147cb
_grabconfig.py
_grabconfig.py
import os, shutil files = ["/etc/crontab", "/usr/local/bin/ssu", "/usr/local/bin/xyzzy", "/home/dagon/.bashrc","/home/dagon/.i3status.conf", "/home/dagon/.profile", "/home/dagon/.vimrc", "/home/dagon/.i3/config", "/home/dagon/.vim", "/home/dagon/.config/bless", "/home/dagon/.config/terminator", "/bla.txt"] for item in files: dest = os.getcwd() + item if os.path.isdir(item): try: shutil.rmtree(dest) except: pass shutil.copytree(item, dest) else: try: os.remove(dest) except: pass shutil.copyfile(item, dest)
import os, shutil files = ["/etc/crontab", "/usr/local/bin/ssu", "/usr/local/bin/xyzzy", "/home/dagon/.bashrc","/home/dagon/.i3status.conf", "/home/dagon/.profile", "/home/dagon/.vimrc", "/home/dagon/.i3/config", "/home/dagon/.vim", "/home/dagon/.config/bless", "/home/dagon/.config/terminator"] for item in files: dest = os.getcwd() + item if os.path.isdir(item): try: shutil.rmtree(dest) except: pass shutil.copytree(item, dest) else: try: os.remove(dest) except: pass shutil.copyfile(item, dest)
Remove test item from config grabbing script
Remove test item from config grabbing script
Python
unlicense
weloxux/dotfiles,weloxux/dotfiles
import os, shutil files = ["/etc/crontab", "/usr/local/bin/ssu", "/usr/local/bin/xyzzy", "/home/dagon/.bashrc","/home/dagon/.i3status.conf", "/home/dagon/.profile", "/home/dagon/.vimrc", "/home/dagon/.i3/config", "/home/dagon/.vim", - "/home/dagon/.config/bless", "/home/dagon/.config/terminator", "/bla.txt"] + "/home/dagon/.config/bless", "/home/dagon/.config/terminator"] for item in files: dest = os.getcwd() + item if os.path.isdir(item): try: shutil.rmtree(dest) except: pass shutil.copytree(item, dest) else: try: os.remove(dest) except: pass shutil.copyfile(item, dest)
Remove test item from config grabbing script
## Code Before: import os, shutil files = ["/etc/crontab", "/usr/local/bin/ssu", "/usr/local/bin/xyzzy", "/home/dagon/.bashrc","/home/dagon/.i3status.conf", "/home/dagon/.profile", "/home/dagon/.vimrc", "/home/dagon/.i3/config", "/home/dagon/.vim", "/home/dagon/.config/bless", "/home/dagon/.config/terminator", "/bla.txt"] for item in files: dest = os.getcwd() + item if os.path.isdir(item): try: shutil.rmtree(dest) except: pass shutil.copytree(item, dest) else: try: os.remove(dest) except: pass shutil.copyfile(item, dest) ## Instruction: Remove test item from config grabbing script ## Code After: import os, shutil files = ["/etc/crontab", "/usr/local/bin/ssu", "/usr/local/bin/xyzzy", "/home/dagon/.bashrc","/home/dagon/.i3status.conf", "/home/dagon/.profile", "/home/dagon/.vimrc", "/home/dagon/.i3/config", "/home/dagon/.vim", "/home/dagon/.config/bless", "/home/dagon/.config/terminator"] for item in files: dest = os.getcwd() + item if os.path.isdir(item): try: shutil.rmtree(dest) except: pass shutil.copytree(item, dest) else: try: os.remove(dest) except: pass shutil.copyfile(item, dest)
// ... existing code ... "/home/dagon/.bashrc","/home/dagon/.i3status.conf", "/home/dagon/.profile", "/home/dagon/.vimrc", "/home/dagon/.i3/config", "/home/dagon/.vim", "/home/dagon/.config/bless", "/home/dagon/.config/terminator"] // ... rest of the code ...
df1617a7518f66d87470f948e057e4d7d7d8f026
driller/tasks.py
driller/tasks.py
import redis from celery import Celery from .driller import Driller app = Celery('tasks', broker='amqp://guest@localhost//', backend='redis://localhost') redis_pool = redis.ConnectionPool(host='localhost', port=6379, db=1) @app.task def drill(binary, input, fuzz_bitmap, qemu_dir): redis_inst = redis.Redis(connection_pool=redis_pool) driller = Driller(binary, input, fuzz_bitmap, qemu_dir, redis=redis_inst) return driller.drill()
import redis from celery import Celery from .driller import Driller import config backend_url = "redis://%s:%d" % (config.REDIS_HOST, config.REDIS_PORT) app = Celery('tasks', broker=config.BROKER_URL, backend=backend_url) redis_pool = redis.ConnectionPool(host=config.REDIS_HOST, port=config.REDIS_PORT, db=config.REDIS_DB) @app.task def drill(binary, input, fuzz_bitmap, qemu_dir): redis_inst = redis.Redis(connection_pool=redis_pool) driller = Driller(binary, input, fuzz_bitmap, qemu_dir, redis=redis_inst) return driller.drill()
Connect to Celery using config options
Connect to Celery using config options
Python
bsd-2-clause
shellphish/driller
import redis from celery import Celery from .driller import Driller + import config - app = Celery('tasks', broker='amqp://guest@localhost//', backend='redis://localhost') - redis_pool = redis.ConnectionPool(host='localhost', port=6379, db=1) + backend_url = "redis://%s:%d" % (config.REDIS_HOST, config.REDIS_PORT) + app = Celery('tasks', broker=config.BROKER_URL, backend=backend_url) + redis_pool = redis.ConnectionPool(host=config.REDIS_HOST, port=config.REDIS_PORT, db=config.REDIS_DB) @app.task def drill(binary, input, fuzz_bitmap, qemu_dir): redis_inst = redis.Redis(connection_pool=redis_pool) driller = Driller(binary, input, fuzz_bitmap, qemu_dir, redis=redis_inst) return driller.drill()
Connect to Celery using config options
## Code Before: import redis from celery import Celery from .driller import Driller app = Celery('tasks', broker='amqp://guest@localhost//', backend='redis://localhost') redis_pool = redis.ConnectionPool(host='localhost', port=6379, db=1) @app.task def drill(binary, input, fuzz_bitmap, qemu_dir): redis_inst = redis.Redis(connection_pool=redis_pool) driller = Driller(binary, input, fuzz_bitmap, qemu_dir, redis=redis_inst) return driller.drill() ## Instruction: Connect to Celery using config options ## Code After: import redis from celery import Celery from .driller import Driller import config backend_url = "redis://%s:%d" % (config.REDIS_HOST, config.REDIS_PORT) app = Celery('tasks', broker=config.BROKER_URL, backend=backend_url) redis_pool = redis.ConnectionPool(host=config.REDIS_HOST, port=config.REDIS_PORT, db=config.REDIS_DB) @app.task def drill(binary, input, fuzz_bitmap, qemu_dir): redis_inst = redis.Redis(connection_pool=redis_pool) driller = Driller(binary, input, fuzz_bitmap, qemu_dir, redis=redis_inst) return driller.drill()
// ... existing code ... from .driller import Driller import config backend_url = "redis://%s:%d" % (config.REDIS_HOST, config.REDIS_PORT) app = Celery('tasks', broker=config.BROKER_URL, backend=backend_url) redis_pool = redis.ConnectionPool(host=config.REDIS_HOST, port=config.REDIS_PORT, db=config.REDIS_DB) // ... rest of the code ...
b16d634ee9390864da8de6f8d4e7f9e546c8f772
ifs/source/jenkins.py
ifs/source/jenkins.py
version_cmd = 'java -jar /usr/share/jenkins/jenkins.war --version' version_re = '(\d\.\d{3})' depends = ['wget'] install_script = """ wget -q -O - http://pkg.jenkins-ci.org/debian/jenkins-ci.org.key | apt-key add - echo "deb http://pkg.jenkins-ci.org/debian binary/" > /etc/apt/sources.list.d/jenkins.list apt-get update apt-get install -y jenkins """
version_cmd = 'java -jar /usr/share/jenkins/jenkins.war --version' version_re = '(\d\.\d{3})' depends = ['wget'] install_script = """ wget -q -O - http://pkg.jenkins-ci.org/debian/jenkins-ci.org.key | apt-key add - echo "deb http://pkg.jenkins-ci.org/debian binary/" > /etc/apt/sources.list.d/jenkins.list apt-get update -o Dir::Etc::sourcelist="sources.list.d/jenkins.list" -o Dir::Etc::sourceparts="-" -o APT::Get::List-Cleanup="0" apt-get install -y jenkins """
Update Jenkins source to only update the Jenkins repository
Update Jenkins source to only update the Jenkins repository
Python
isc
cbednarski/ifs-python,cbednarski/ifs-python
version_cmd = 'java -jar /usr/share/jenkins/jenkins.war --version' version_re = '(\d\.\d{3})' depends = ['wget'] install_script = """ wget -q -O - http://pkg.jenkins-ci.org/debian/jenkins-ci.org.key | apt-key add - echo "deb http://pkg.jenkins-ci.org/debian binary/" > /etc/apt/sources.list.d/jenkins.list - apt-get update + apt-get update -o Dir::Etc::sourcelist="sources.list.d/jenkins.list" -o Dir::Etc::sourceparts="-" -o APT::Get::List-Cleanup="0" apt-get install -y jenkins """
Update Jenkins source to only update the Jenkins repository
## Code Before: version_cmd = 'java -jar /usr/share/jenkins/jenkins.war --version' version_re = '(\d\.\d{3})' depends = ['wget'] install_script = """ wget -q -O - http://pkg.jenkins-ci.org/debian/jenkins-ci.org.key | apt-key add - echo "deb http://pkg.jenkins-ci.org/debian binary/" > /etc/apt/sources.list.d/jenkins.list apt-get update apt-get install -y jenkins """ ## Instruction: Update Jenkins source to only update the Jenkins repository ## Code After: version_cmd = 'java -jar /usr/share/jenkins/jenkins.war --version' version_re = '(\d\.\d{3})' depends = ['wget'] install_script = """ wget -q -O - http://pkg.jenkins-ci.org/debian/jenkins-ci.org.key | apt-key add - echo "deb http://pkg.jenkins-ci.org/debian binary/" > /etc/apt/sources.list.d/jenkins.list apt-get update -o Dir::Etc::sourcelist="sources.list.d/jenkins.list" -o Dir::Etc::sourceparts="-" -o APT::Get::List-Cleanup="0" apt-get install -y jenkins """
# ... existing code ... echo "deb http://pkg.jenkins-ci.org/debian binary/" > /etc/apt/sources.list.d/jenkins.list apt-get update -o Dir::Etc::sourcelist="sources.list.d/jenkins.list" -o Dir::Etc::sourceparts="-" -o APT::Get::List-Cleanup="0" apt-get install -y jenkins # ... rest of the code ...
c6ef5bcac4d5daddac97ff30ff18645249928ac0
nap/engine.py
nap/engine.py
import json try: import msgpack except ImportError: pass from decimal import Decimal from datetime import date, datetime, time class Engine(object): # The list of content types we match CONTENT_TYPES = [] def dumps(self, data): # pragma: no cover '''How to serialiser an object''' raise NotImplementedError def loads(self, data): # pragma: no cover '''How to deserialise a string''' raise NotImplementedError class JsonEngine(Engine): CONTENT_TYPES = ['application/json',] def dumps(self, data): return json.dumps(data) def loads(self, data): return json.loads(data) class MsgPackEngine(Engine): CONTENT_TYPES = ['application/x-msgpack',] def dumps(self, data): return msgpack.dumps(data) def loads(self, data): return msgpack.loads(data)
import json class Engine(object): # The list of content types we match CONTENT_TYPES = [] def dumps(self, data): # pragma: no cover '''How to serialiser an object''' raise NotImplementedError def loads(self, data): # pragma: no cover '''How to deserialise a string''' raise NotImplementedError class JsonEngine(Engine): CONTENT_TYPES = ['application/json',] def dumps(self, data): return json.dumps(data) def loads(self, data): return json.loads(data) try: import msgpack except ImportError: pass else: class MsgPackEngine(Engine): CONTENT_TYPES = ['application/x-msgpack',] def dumps(self, data): return msgpack.dumps(data) def loads(self, data): return msgpack.loads(data)
Remove unused imports Only define MsgPackEngine if we can import MsgPack
Remove unused imports Only define MsgPackEngine if we can import MsgPack
Python
bsd-3-clause
MarkusH/django-nap,limbera/django-nap
import json - try: - import msgpack - except ImportError: - pass - from decimal import Decimal - from datetime import date, datetime, time class Engine(object): # The list of content types we match CONTENT_TYPES = [] def dumps(self, data): # pragma: no cover '''How to serialiser an object''' raise NotImplementedError def loads(self, data): # pragma: no cover '''How to deserialise a string''' raise NotImplementedError + class JsonEngine(Engine): CONTENT_TYPES = ['application/json',] def dumps(self, data): return json.dumps(data) def loads(self, data): return json.loads(data) - class MsgPackEngine(Engine): - CONTENT_TYPES = ['application/x-msgpack',] - def dumps(self, data): - return msgpack.dumps(data) - def loads(self, data): - return msgpack.loads(data) + try: + import msgpack + except ImportError: + pass + else: + class MsgPackEngine(Engine): + CONTENT_TYPES = ['application/x-msgpack',] + def dumps(self, data): + return msgpack.dumps(data) + def loads(self, data): + return msgpack.loads(data) +
Remove unused imports Only define MsgPackEngine if we can import MsgPack
## Code Before: import json try: import msgpack except ImportError: pass from decimal import Decimal from datetime import date, datetime, time class Engine(object): # The list of content types we match CONTENT_TYPES = [] def dumps(self, data): # pragma: no cover '''How to serialiser an object''' raise NotImplementedError def loads(self, data): # pragma: no cover '''How to deserialise a string''' raise NotImplementedError class JsonEngine(Engine): CONTENT_TYPES = ['application/json',] def dumps(self, data): return json.dumps(data) def loads(self, data): return json.loads(data) class MsgPackEngine(Engine): CONTENT_TYPES = ['application/x-msgpack',] def dumps(self, data): return msgpack.dumps(data) def loads(self, data): return msgpack.loads(data) ## Instruction: Remove unused imports Only define MsgPackEngine if we can import MsgPack ## Code After: import json class Engine(object): # The list of content types we match CONTENT_TYPES = [] def dumps(self, data): # pragma: no cover '''How to serialiser an object''' raise NotImplementedError def loads(self, data): # pragma: no cover '''How to deserialise a string''' raise NotImplementedError class JsonEngine(Engine): CONTENT_TYPES = ['application/json',] def dumps(self, data): return json.dumps(data) def loads(self, data): return json.loads(data) try: import msgpack except ImportError: pass else: class MsgPackEngine(Engine): CONTENT_TYPES = ['application/x-msgpack',] def dumps(self, data): return msgpack.dumps(data) def loads(self, data): return msgpack.loads(data)
... import json ... class JsonEngine(Engine): ... try: import msgpack except ImportError: pass else: class MsgPackEngine(Engine): CONTENT_TYPES = ['application/x-msgpack',] def dumps(self, data): return msgpack.dumps(data) def loads(self, data): return msgpack.loads(data) ...
d7a3bcf72df3cededc4220f46f976a0daef539a6
marvin/tests/__init__.py
marvin/tests/__init__.py
from marvin import create_app import unittest class AppCreationTest(unittest.TestCase): def test_create_app(self): app = create_app(MY_CONFIG_VALUE='foo') self.assertEqual(app.config['MY_CONFIG_VALUE'], 'foo')
from marvin import create_app import os import tempfile import unittest class AppCreationTest(unittest.TestCase): def setUp(self): self.config_file = tempfile.NamedTemporaryFile(delete=False) self.config_file.write('OTHER_CONFIG = "bar"'.encode('utf-8')) self.config_file.close() def tearDown(self): os.remove(self.config_file.name) def test_create_app(self): app = create_app(MY_CONFIG_VALUE='foo') self.assertEqual(app.config['MY_CONFIG_VALUE'], 'foo') def test_create_app_with_config_file(self): app = create_app(self.config_file.name) self.assertEqual(app.config['OTHER_CONFIG'], 'bar') def test_create_app_both(self): app = create_app(self.config_file.name, EXTRA_PARAM='baz') self.assertEqual(app.config['OTHER_CONFIG'], 'bar') self.assertEqual(app.config['EXTRA_PARAM'], 'baz')
Add test for app creation with config file.
Add test for app creation with config file. Also be explicit about encoding when writing to file.
Python
mit
streamr/marvin,streamr/marvin,streamr/marvin
from marvin import create_app + import os + import tempfile import unittest class AppCreationTest(unittest.TestCase): + + def setUp(self): + self.config_file = tempfile.NamedTemporaryFile(delete=False) + self.config_file.write('OTHER_CONFIG = "bar"'.encode('utf-8')) + self.config_file.close() + + + def tearDown(self): + os.remove(self.config_file.name) + def test_create_app(self): app = create_app(MY_CONFIG_VALUE='foo') self.assertEqual(app.config['MY_CONFIG_VALUE'], 'foo') + + def test_create_app_with_config_file(self): + app = create_app(self.config_file.name) + self.assertEqual(app.config['OTHER_CONFIG'], 'bar') + + + def test_create_app_both(self): + app = create_app(self.config_file.name, EXTRA_PARAM='baz') + self.assertEqual(app.config['OTHER_CONFIG'], 'bar') + self.assertEqual(app.config['EXTRA_PARAM'], 'baz') +
Add test for app creation with config file.
## Code Before: from marvin import create_app import unittest class AppCreationTest(unittest.TestCase): def test_create_app(self): app = create_app(MY_CONFIG_VALUE='foo') self.assertEqual(app.config['MY_CONFIG_VALUE'], 'foo') ## Instruction: Add test for app creation with config file. ## Code After: from marvin import create_app import os import tempfile import unittest class AppCreationTest(unittest.TestCase): def setUp(self): self.config_file = tempfile.NamedTemporaryFile(delete=False) self.config_file.write('OTHER_CONFIG = "bar"'.encode('utf-8')) self.config_file.close() def tearDown(self): os.remove(self.config_file.name) def test_create_app(self): app = create_app(MY_CONFIG_VALUE='foo') self.assertEqual(app.config['MY_CONFIG_VALUE'], 'foo') def test_create_app_with_config_file(self): app = create_app(self.config_file.name) self.assertEqual(app.config['OTHER_CONFIG'], 'bar') def test_create_app_both(self): app = create_app(self.config_file.name, EXTRA_PARAM='baz') self.assertEqual(app.config['OTHER_CONFIG'], 'bar') self.assertEqual(app.config['EXTRA_PARAM'], 'baz')
... import os import tempfile import unittest ... def setUp(self): self.config_file = tempfile.NamedTemporaryFile(delete=False) self.config_file.write('OTHER_CONFIG = "bar"'.encode('utf-8')) self.config_file.close() def tearDown(self): os.remove(self.config_file.name) def test_create_app(self): ... self.assertEqual(app.config['MY_CONFIG_VALUE'], 'foo') def test_create_app_with_config_file(self): app = create_app(self.config_file.name) self.assertEqual(app.config['OTHER_CONFIG'], 'bar') def test_create_app_both(self): app = create_app(self.config_file.name, EXTRA_PARAM='baz') self.assertEqual(app.config['OTHER_CONFIG'], 'bar') self.assertEqual(app.config['EXTRA_PARAM'], 'baz') ...
754f5c968ad1dff3ae7f602d23baac1299731062
update_filelist.py
update_filelist.py
import os import re import subprocess dir_path = os.path.dirname(os.path.realpath(__file__)) filename = 'chatterino.pro' data = "" with open(filename, 'r') as project: data = project.read() sources = subprocess.getoutput("find ./src -type f -regex '.*\.cpp' | sed 's_\./_ _g'") sources = re.sub(r'$', r' \\\\', sources, flags=re.MULTILINE) sources += "\n" data = re.sub(r'^SOURCES(.|\r|\n)*?^$', 'SOURCES += \\\n' + sources, data, flags=re.MULTILINE) headers = subprocess.getoutput("find ./src -type f -regex '.*\.hpp' | sed 's_\./_ _g'") headers = re.sub(r'$', r' \\\\', headers, flags=re.MULTILINE) headers += "\n" data = re.sub(r'^HEADERS(.|\r|\n)*?^$', 'HEADERS += \\\n' + headers, data, flags=re.MULTILINE) with open(filename, 'w') as project: project.write(data)
import os import re import subprocess dir_path = os.path.dirname(os.path.realpath(__file__)) filename = 'chatterino.pro' data = "" with open(filename, 'r') as project: data = project.read() sources_list = subprocess.getoutput("find ./src -type f -regex '.*\.cpp' | sed 's_\./_ _g'").splitlines() sources_list.sort(key=str.lower) sources = "\n".join(sources_list) sources = re.sub(r'$', r' \\\\', sources, flags=re.MULTILINE) sources += "\n" data = re.sub(r'^SOURCES(.|\r|\n)*?^$', 'SOURCES += \\\n' + sources, data, flags=re.MULTILINE) headers_list = subprocess.getoutput("find ./src -type f -regex '.*\.hpp' | sed 's_\./_ _g'").splitlines() headers_list.sort(key=str.lower) headers = "\n".join(headers_list) headers = re.sub(r'$', r' \\\\', headers, flags=re.MULTILINE) headers += "\n" data = re.sub(r'^HEADERS(.|\r|\n)*?^$', 'HEADERS += \\\n' + headers, data, flags=re.MULTILINE) with open(filename, 'w') as project: project.write(data)
Sort file list before writing to project file
Sort file list before writing to project file Now using the built-in Python `list.sort` method to sort files. This should ensure consistent behavior on all systems and prevent unnecessary merge conflicts.
Python
mit
Cranken/chatterino2,hemirt/chatterino2,fourtf/chatterino2,Cranken/chatterino2,hemirt/chatterino2,Cranken/chatterino2,fourtf/chatterino2,Cranken/chatterino2,fourtf/chatterino2,hemirt/chatterino2,hemirt/chatterino2
import os import re import subprocess dir_path = os.path.dirname(os.path.realpath(__file__)) filename = 'chatterino.pro' data = "" with open(filename, 'r') as project: data = project.read() - sources = subprocess.getoutput("find ./src -type f -regex '.*\.cpp' | sed 's_\./_ _g'") + sources_list = subprocess.getoutput("find ./src -type f -regex '.*\.cpp' | sed 's_\./_ _g'").splitlines() + sources_list.sort(key=str.lower) + sources = "\n".join(sources_list) sources = re.sub(r'$', r' \\\\', sources, flags=re.MULTILINE) sources += "\n" data = re.sub(r'^SOURCES(.|\r|\n)*?^$', 'SOURCES += \\\n' + sources, data, flags=re.MULTILINE) - headers = subprocess.getoutput("find ./src -type f -regex '.*\.hpp' | sed 's_\./_ _g'") + headers_list = subprocess.getoutput("find ./src -type f -regex '.*\.hpp' | sed 's_\./_ _g'").splitlines() + headers_list.sort(key=str.lower) + headers = "\n".join(headers_list) headers = re.sub(r'$', r' \\\\', headers, flags=re.MULTILINE) headers += "\n" data = re.sub(r'^HEADERS(.|\r|\n)*?^$', 'HEADERS += \\\n' + headers, data, flags=re.MULTILINE) with open(filename, 'w') as project: project.write(data)
Sort file list before writing to project file
## Code Before: import os import re import subprocess dir_path = os.path.dirname(os.path.realpath(__file__)) filename = 'chatterino.pro' data = "" with open(filename, 'r') as project: data = project.read() sources = subprocess.getoutput("find ./src -type f -regex '.*\.cpp' | sed 's_\./_ _g'") sources = re.sub(r'$', r' \\\\', sources, flags=re.MULTILINE) sources += "\n" data = re.sub(r'^SOURCES(.|\r|\n)*?^$', 'SOURCES += \\\n' + sources, data, flags=re.MULTILINE) headers = subprocess.getoutput("find ./src -type f -regex '.*\.hpp' | sed 's_\./_ _g'") headers = re.sub(r'$', r' \\\\', headers, flags=re.MULTILINE) headers += "\n" data = re.sub(r'^HEADERS(.|\r|\n)*?^$', 'HEADERS += \\\n' + headers, data, flags=re.MULTILINE) with open(filename, 'w') as project: project.write(data) ## Instruction: Sort file list before writing to project file ## Code After: import os import re import subprocess dir_path = os.path.dirname(os.path.realpath(__file__)) filename = 'chatterino.pro' data = "" with open(filename, 'r') as project: data = project.read() sources_list = subprocess.getoutput("find ./src -type f -regex '.*\.cpp' | sed 's_\./_ _g'").splitlines() sources_list.sort(key=str.lower) sources = "\n".join(sources_list) sources = re.sub(r'$', r' \\\\', sources, flags=re.MULTILINE) sources += "\n" data = re.sub(r'^SOURCES(.|\r|\n)*?^$', 'SOURCES += \\\n' + sources, data, flags=re.MULTILINE) headers_list = subprocess.getoutput("find ./src -type f -regex '.*\.hpp' | sed 's_\./_ _g'").splitlines() headers_list.sort(key=str.lower) headers = "\n".join(headers_list) headers = re.sub(r'$', r' \\\\', headers, flags=re.MULTILINE) headers += "\n" data = re.sub(r'^HEADERS(.|\r|\n)*?^$', 'HEADERS += \\\n' + headers, data, flags=re.MULTILINE) with open(filename, 'w') as project: project.write(data)
... data = project.read() sources_list = subprocess.getoutput("find ./src -type f -regex '.*\.cpp' | sed 's_\./_ _g'").splitlines() sources_list.sort(key=str.lower) sources = "\n".join(sources_list) sources = re.sub(r'$', r' \\\\', sources, flags=re.MULTILINE) ... headers_list = subprocess.getoutput("find ./src -type f -regex '.*\.hpp' | sed 's_\./_ _g'").splitlines() headers_list.sort(key=str.lower) headers = "\n".join(headers_list) headers = re.sub(r'$', r' \\\\', headers, flags=re.MULTILINE) ...
617ac4a745afb07299c73977477f52911f3e6e4c
flask_skeleton_api/app.py
flask_skeleton_api/app.py
from flask import Flask, g, request import uuid import requests app = Flask(__name__) app.config.from_pyfile("config.py") @app.before_request def before_request(): # Sets the transaction trace id into the global object if it has been provided in the HTTP header from the caller. # Generate a new one if it has not. We will use this in log messages. trace_id = request.headers.get('X-Trace-ID', None) if trace_id is None: trace_id = uuid.uuid4().hex g.trace_id = trace_id # We also create a session-level requests object for the app to use with the header pre-set, so other APIs will receive it. # These lines can be removed if the app will not make requests to other LR APIs! g.requests = requests.Session() g.requests.headers.update({'X-Trace-ID': trace_id})
from flask import Flask, g, request import uuid import requests app = Flask(__name__) app.config.from_pyfile("config.py") @app.before_request def before_request(): # Sets the transaction trace id into the global object if it has been provided in the HTTP header from the caller. # Generate a new one if it has not. We will use this in log messages. trace_id = request.headers.get('X-Trace-ID', None) if trace_id is None: trace_id = uuid.uuid4().hex g.trace_id = trace_id # We also create a session-level requests object for the app to use with the header pre-set, so other APIs will receive it. # These lines can be removed if the app will not make requests to other LR APIs! g.requests = requests.Session() g.requests.headers.update({'X-Trace-ID': trace_id}) @app.after_request def after_request(response): # Add the API version (as in the interface spec, not the app) to the header. Semantic versioning applies - see the # API manual. A major version update will need to go in the URL. All changes should be documented though, for # reusing teams to take advantage of. response.headers["X-API-Version"] = "1.0.0" return response
Add API version into response header
Add API version into response header
Python
mit
matthew-shaw/thing-api
from flask import Flask, g, request import uuid import requests app = Flask(__name__) app.config.from_pyfile("config.py") @app.before_request def before_request(): # Sets the transaction trace id into the global object if it has been provided in the HTTP header from the caller. # Generate a new one if it has not. We will use this in log messages. trace_id = request.headers.get('X-Trace-ID', None) if trace_id is None: trace_id = uuid.uuid4().hex g.trace_id = trace_id # We also create a session-level requests object for the app to use with the header pre-set, so other APIs will receive it. # These lines can be removed if the app will not make requests to other LR APIs! g.requests = requests.Session() g.requests.headers.update({'X-Trace-ID': trace_id}) + + @app.after_request + def after_request(response): + # Add the API version (as in the interface spec, not the app) to the header. Semantic versioning applies - see the + # API manual. A major version update will need to go in the URL. All changes should be documented though, for + # reusing teams to take advantage of. + response.headers["X-API-Version"] = "1.0.0" + return response +
Add API version into response header
## Code Before: from flask import Flask, g, request import uuid import requests app = Flask(__name__) app.config.from_pyfile("config.py") @app.before_request def before_request(): # Sets the transaction trace id into the global object if it has been provided in the HTTP header from the caller. # Generate a new one if it has not. We will use this in log messages. trace_id = request.headers.get('X-Trace-ID', None) if trace_id is None: trace_id = uuid.uuid4().hex g.trace_id = trace_id # We also create a session-level requests object for the app to use with the header pre-set, so other APIs will receive it. # These lines can be removed if the app will not make requests to other LR APIs! g.requests = requests.Session() g.requests.headers.update({'X-Trace-ID': trace_id}) ## Instruction: Add API version into response header ## Code After: from flask import Flask, g, request import uuid import requests app = Flask(__name__) app.config.from_pyfile("config.py") @app.before_request def before_request(): # Sets the transaction trace id into the global object if it has been provided in the HTTP header from the caller. # Generate a new one if it has not. We will use this in log messages. trace_id = request.headers.get('X-Trace-ID', None) if trace_id is None: trace_id = uuid.uuid4().hex g.trace_id = trace_id # We also create a session-level requests object for the app to use with the header pre-set, so other APIs will receive it. # These lines can be removed if the app will not make requests to other LR APIs! g.requests = requests.Session() g.requests.headers.update({'X-Trace-ID': trace_id}) @app.after_request def after_request(response): # Add the API version (as in the interface spec, not the app) to the header. Semantic versioning applies - see the # API manual. A major version update will need to go in the URL. All changes should be documented though, for # reusing teams to take advantage of. response.headers["X-API-Version"] = "1.0.0" return response
... g.requests.headers.update({'X-Trace-ID': trace_id}) @app.after_request def after_request(response): # Add the API version (as in the interface spec, not the app) to the header. Semantic versioning applies - see the # API manual. A major version update will need to go in the URL. All changes should be documented though, for # reusing teams to take advantage of. response.headers["X-API-Version"] = "1.0.0" return response ...
2e9a6a2babb16f4ed9c3367b21ee28514d1988a8
srm/__main__.py
srm/__main__.py
import click from . import __version__, status @click.group() @click.version_option(__version__) def cli() -> None: """Main command-line entry method.""" cli.add_command(status.cli) if __name__ == '__main__': cli()
import click from . import __version__, status @click.group() @click.version_option(__version__) def cli() -> None: """Main command-line entry method.""" cli.add_command(status.cli) cli(prog_name='srm')
Set correct program name in 'help' output
Set correct program name in 'help' output
Python
mit
cmcginty/simple-rom-manager,cmcginty/simple-rom-manager
import click from . import __version__, status @click.group() @click.version_option(__version__) def cli() -> None: """Main command-line entry method.""" cli.add_command(status.cli) + cli(prog_name='srm') - if __name__ == '__main__': - cli() -
Set correct program name in 'help' output
## Code Before: import click from . import __version__, status @click.group() @click.version_option(__version__) def cli() -> None: """Main command-line entry method.""" cli.add_command(status.cli) if __name__ == '__main__': cli() ## Instruction: Set correct program name in 'help' output ## Code After: import click from . import __version__, status @click.group() @click.version_option(__version__) def cli() -> None: """Main command-line entry method.""" cli.add_command(status.cli) cli(prog_name='srm')
// ... existing code ... cli.add_command(status.cli) cli(prog_name='srm') // ... rest of the code ...
e01140053a2a906084d0ba50801b17d4ae7ce850
samples/unmanage_node.py
samples/unmanage_node.py
import requests from orionsdk import SwisClient from datetime import datetime, timedelta def main(): hostname = 'localhost' username = 'admin' password = '' swis = SwisClient(hostname, username, password) results = swis.query('SELECT TOP 1 NodeID FROM Orion.Nodes') interfaceId = results['results'][0]['NodeID'] netObjectId = 'N:{}'.format(interfaceId) now = datetime.utcnow() tomorrow = now + timedelta(days=1) swis.invoke('Orion.Nodes', 'Unmanage', netObjectId, now, tomorrow, False) requests.packages.urllib3.disable_warnings() if __name__ == '__main__': main()
import requests from orionsdk import SwisClient from datetime import datetime, timedelta def main(): hostname = 'localhost' username = 'admin' password = '' swis = SwisClient(hostname, username, password) results = swis.query('SELECT NodeID, Caption FROM Orion.Nodes WHERE IPAddress = @ip_addr', ip_addr='127.0.0.1') if results['results']: nodeId = results['results'][0]['NodeID'] caption = results['results'][0]['Caption'] netObjectId = 'N:{}'.format(nodeId) now = datetime.utcnow() tomorrow = now + timedelta(days=1) swis.invoke('Orion.Nodes', 'Unmanage', netObjectId, now, tomorrow, False) print('Done...{} will be unmanaged until {}'.format(caption, tomorrow)) else: print("Device doesn't Exist") requests.packages.urllib3.disable_warnings() if __name__ == '__main__': main()
Correct node variable name and validate results
Correct node variable name and validate results
Python
apache-2.0
solarwinds/orionsdk-python
import requests from orionsdk import SwisClient from datetime import datetime, timedelta def main(): hostname = 'localhost' username = 'admin' password = '' swis = SwisClient(hostname, username, password) - results = swis.query('SELECT TOP 1 NodeID FROM Orion.Nodes') + results = swis.query('SELECT NodeID, Caption FROM Orion.Nodes WHERE IPAddress = @ip_addr', ip_addr='127.0.0.1') + if results['results']: - interfaceId = results['results'][0]['NodeID'] + nodeId = results['results'][0]['NodeID'] + caption = results['results'][0]['Caption'] - netObjectId = 'N:{}'.format(interfaceId) + netObjectId = 'N:{}'.format(nodeId) - now = datetime.utcnow() + now = datetime.utcnow() - tomorrow = now + timedelta(days=1) + tomorrow = now + timedelta(days=1) - swis.invoke('Orion.Nodes', 'Unmanage', netObjectId, now, tomorrow, False) + swis.invoke('Orion.Nodes', 'Unmanage', netObjectId, now, tomorrow, False) + print('Done...{} will be unmanaged until {}'.format(caption, tomorrow)) + else: + print("Device doesn't Exist") requests.packages.urllib3.disable_warnings() if __name__ == '__main__': main()
Correct node variable name and validate results
## Code Before: import requests from orionsdk import SwisClient from datetime import datetime, timedelta def main(): hostname = 'localhost' username = 'admin' password = '' swis = SwisClient(hostname, username, password) results = swis.query('SELECT TOP 1 NodeID FROM Orion.Nodes') interfaceId = results['results'][0]['NodeID'] netObjectId = 'N:{}'.format(interfaceId) now = datetime.utcnow() tomorrow = now + timedelta(days=1) swis.invoke('Orion.Nodes', 'Unmanage', netObjectId, now, tomorrow, False) requests.packages.urllib3.disable_warnings() if __name__ == '__main__': main() ## Instruction: Correct node variable name and validate results ## Code After: import requests from orionsdk import SwisClient from datetime import datetime, timedelta def main(): hostname = 'localhost' username = 'admin' password = '' swis = SwisClient(hostname, username, password) results = swis.query('SELECT NodeID, Caption FROM Orion.Nodes WHERE IPAddress = @ip_addr', ip_addr='127.0.0.1') if results['results']: nodeId = results['results'][0]['NodeID'] caption = results['results'][0]['Caption'] netObjectId = 'N:{}'.format(nodeId) now = datetime.utcnow() tomorrow = now + timedelta(days=1) swis.invoke('Orion.Nodes', 'Unmanage', netObjectId, now, tomorrow, False) print('Done...{} will be unmanaged until {}'.format(caption, tomorrow)) else: print("Device doesn't Exist") requests.packages.urllib3.disable_warnings() if __name__ == '__main__': main()
// ... existing code ... swis = SwisClient(hostname, username, password) results = swis.query('SELECT NodeID, Caption FROM Orion.Nodes WHERE IPAddress = @ip_addr', ip_addr='127.0.0.1') if results['results']: nodeId = results['results'][0]['NodeID'] caption = results['results'][0]['Caption'] netObjectId = 'N:{}'.format(nodeId) now = datetime.utcnow() tomorrow = now + timedelta(days=1) swis.invoke('Orion.Nodes', 'Unmanage', netObjectId, now, tomorrow, False) print('Done...{} will be unmanaged until {}'.format(caption, tomorrow)) else: print("Device doesn't Exist") // ... rest of the code ...
33903a72a48a6d36792cec0f1fb3a6999c04b486
blendergltf/exporters/base.py
blendergltf/exporters/base.py
import json def _is_serializable(value): try: json.dumps(value) return True except TypeError: return False _IGNORED_CUSTOM_PROPS = [ '_RNA_UI', 'cycles', 'cycles_visibility', ] # pylint: disable=unused-argument class BaseExporter: gltf_key = '' blender_key = '' @classmethod def get_custom_properties(cls, blender_data): return { k: v.to_list() if hasattr(v, 'to_list') else v for k, v in blender_data.items() if k not in _IGNORED_CUSTOM_PROPS and _is_serializable(v) } @classmethod def check(cls, state, blender_data): return True @classmethod def default(cls, state, blender_data): return { 'name': blender_data.name } @classmethod def export(cls, state, blender_data): return {}
import json def _is_serializable(value): try: json.dumps(value) return True except TypeError: return False _IGNORED_CUSTOM_PROPS = [ '_RNA_UI', 'cycles', 'cycles_visibility', ] # pylint: disable=unused-argument class BaseExporter: gltf_key = '' blender_key = '' @classmethod def get_custom_properties(cls, blender_data): custom_props = { key: value.to_list() if hasattr(value, 'to_list') else value for key, value in blender_data.items() if key not in _IGNORED_CUSTOM_PROPS } custom_props = { key: value for key, value in custom_props.items() if _is_serializable(value) } return custom_props @classmethod def check(cls, state, blender_data): return True @classmethod def default(cls, state, blender_data): return { 'name': blender_data.name } @classmethod def export(cls, state, blender_data): return {}
Convert custom properties before checking for serializability
Convert custom properties before checking for serializability
Python
apache-2.0
Kupoman/blendergltf
import json def _is_serializable(value): try: json.dumps(value) return True except TypeError: return False _IGNORED_CUSTOM_PROPS = [ '_RNA_UI', 'cycles', 'cycles_visibility', ] # pylint: disable=unused-argument class BaseExporter: gltf_key = '' blender_key = '' @classmethod def get_custom_properties(cls, blender_data): - return { - k: v.to_list() if hasattr(v, 'to_list') else v for k, v in blender_data.items() + custom_props = { + key: value.to_list() if hasattr(value, 'to_list') else value + for key, value in blender_data.items() - if k not in _IGNORED_CUSTOM_PROPS and _is_serializable(v) + if key not in _IGNORED_CUSTOM_PROPS } + + custom_props = { + key: value for key, value in custom_props.items() + if _is_serializable(value) + } + + return custom_props @classmethod def check(cls, state, blender_data): return True @classmethod def default(cls, state, blender_data): return { 'name': blender_data.name } @classmethod def export(cls, state, blender_data): return {}
Convert custom properties before checking for serializability
## Code Before: import json def _is_serializable(value): try: json.dumps(value) return True except TypeError: return False _IGNORED_CUSTOM_PROPS = [ '_RNA_UI', 'cycles', 'cycles_visibility', ] # pylint: disable=unused-argument class BaseExporter: gltf_key = '' blender_key = '' @classmethod def get_custom_properties(cls, blender_data): return { k: v.to_list() if hasattr(v, 'to_list') else v for k, v in blender_data.items() if k not in _IGNORED_CUSTOM_PROPS and _is_serializable(v) } @classmethod def check(cls, state, blender_data): return True @classmethod def default(cls, state, blender_data): return { 'name': blender_data.name } @classmethod def export(cls, state, blender_data): return {} ## Instruction: Convert custom properties before checking for serializability ## Code After: import json def _is_serializable(value): try: json.dumps(value) return True except TypeError: return False _IGNORED_CUSTOM_PROPS = [ '_RNA_UI', 'cycles', 'cycles_visibility', ] # pylint: disable=unused-argument class BaseExporter: gltf_key = '' blender_key = '' @classmethod def get_custom_properties(cls, blender_data): custom_props = { key: value.to_list() if hasattr(value, 'to_list') else value for key, value in blender_data.items() if key not in _IGNORED_CUSTOM_PROPS } custom_props = { key: value for key, value in custom_props.items() if _is_serializable(value) } return custom_props @classmethod def check(cls, state, blender_data): return True @classmethod def default(cls, state, blender_data): return { 'name': blender_data.name } @classmethod def export(cls, state, blender_data): return {}
// ... existing code ... def get_custom_properties(cls, blender_data): custom_props = { key: value.to_list() if hasattr(value, 'to_list') else value for key, value in blender_data.items() if key not in _IGNORED_CUSTOM_PROPS } custom_props = { key: value for key, value in custom_props.items() if _is_serializable(value) } return custom_props // ... rest of the code ...
7ca12bb0d2b687c41f9e3b304cc2d7be37ca7a8d
tests/_test_mau_a_vs_an.py
tests/_test_mau_a_vs_an.py
"""Unit tests for MAU101.""" from check import Check from proselint.checks.garner import a_vs_an as chk class TestCheck(Check): """Test garner.a_vs_n.""" __test__ = True @property def this_check(self): """Boilerplate.""" return chk def test(self): """Ensure the test works correctly.""" assert self.check("""An apple a day keeps the doctor away.""") assert self.check("""The Epicurean garden.""") assert not self.check("""A apple a day keeps the doctor away.""") assert not self.check("""An apple an day keeps the doctor away.""") assert not self.check("""An apple an\nday keeps the doctor away.""")
"""Unit tests for MAU101.""" from check import Check from proselint.checks.garner import a_vs_an as chk class TestCheck(Check): """Test garner.a_vs_n.""" __test__ = True @property def this_check(self): """Boilerplate.""" return chk def test(self): """Ensure the test works correctly.""" assert self.passes("""An apple a day keeps the doctor away.""") assert self.passes("""The Epicurean garden.""") assert not self.passes("""A apple a day keeps the doctor away.""") assert not self.passes("""An apple an day keeps the doctor away.""") assert not self.passes("""An apple an\nday keeps the doctor away.""")
Change 'check' to 'passes' in a vs. an check
Change 'check' to 'passes' in a vs. an check
Python
bsd-3-clause
amperser/proselint,jstewmon/proselint,jstewmon/proselint,amperser/proselint,amperser/proselint,amperser/proselint,jstewmon/proselint,amperser/proselint
"""Unit tests for MAU101.""" from check import Check from proselint.checks.garner import a_vs_an as chk class TestCheck(Check): """Test garner.a_vs_n.""" __test__ = True @property def this_check(self): """Boilerplate.""" return chk def test(self): """Ensure the test works correctly.""" - assert self.check("""An apple a day keeps the doctor away.""") + assert self.passes("""An apple a day keeps the doctor away.""") - assert self.check("""The Epicurean garden.""") + assert self.passes("""The Epicurean garden.""") - assert not self.check("""A apple a day keeps the doctor away.""") + assert not self.passes("""A apple a day keeps the doctor away.""") - assert not self.check("""An apple an day keeps the doctor away.""") + assert not self.passes("""An apple an day keeps the doctor away.""") - assert not self.check("""An apple an\nday keeps the doctor away.""") + assert not self.passes("""An apple an\nday keeps the doctor away.""")
Change 'check' to 'passes' in a vs. an check
## Code Before: """Unit tests for MAU101.""" from check import Check from proselint.checks.garner import a_vs_an as chk class TestCheck(Check): """Test garner.a_vs_n.""" __test__ = True @property def this_check(self): """Boilerplate.""" return chk def test(self): """Ensure the test works correctly.""" assert self.check("""An apple a day keeps the doctor away.""") assert self.check("""The Epicurean garden.""") assert not self.check("""A apple a day keeps the doctor away.""") assert not self.check("""An apple an day keeps the doctor away.""") assert not self.check("""An apple an\nday keeps the doctor away.""") ## Instruction: Change 'check' to 'passes' in a vs. an check ## Code After: """Unit tests for MAU101.""" from check import Check from proselint.checks.garner import a_vs_an as chk class TestCheck(Check): """Test garner.a_vs_n.""" __test__ = True @property def this_check(self): """Boilerplate.""" return chk def test(self): """Ensure the test works correctly.""" assert self.passes("""An apple a day keeps the doctor away.""") assert self.passes("""The Epicurean garden.""") assert not self.passes("""A apple a day keeps the doctor away.""") assert not self.passes("""An apple an day keeps the doctor away.""") assert not self.passes("""An apple an\nday keeps the doctor away.""")
// ... existing code ... """Ensure the test works correctly.""" assert self.passes("""An apple a day keeps the doctor away.""") assert self.passes("""The Epicurean garden.""") assert not self.passes("""A apple a day keeps the doctor away.""") assert not self.passes("""An apple an day keeps the doctor away.""") assert not self.passes("""An apple an\nday keeps the doctor away.""") // ... rest of the code ...
247c4dcaf3e1c1f9c069ab8a2fc06cfcd75f8ea9
UM/Util.py
UM/Util.py
def parseBool(value): return value in [True, "True", "true", 1]
def parseBool(value): return value in [True, "True", "true", "Yes", "yes", 1]
Add "Yes" as an option for parsing bools
Add "Yes" as an option for parsing bools CURA-2204
Python
agpl-3.0
onitake/Uranium,onitake/Uranium
def parseBool(value): - return value in [True, "True", "true", 1] + return value in [True, "True", "true", "Yes", "yes", 1]
Add "Yes" as an option for parsing bools
## Code Before: def parseBool(value): return value in [True, "True", "true", 1] ## Instruction: Add "Yes" as an option for parsing bools ## Code After: def parseBool(value): return value in [True, "True", "true", "Yes", "yes", 1]
... def parseBool(value): return value in [True, "True", "true", "Yes", "yes", 1] ...
f54fd0bf65d731b4f25cfc2ddffb8d6f472e0d7c
examples/eiger_use_case.py
examples/eiger_use_case.py
'''Virtual datasets: The 'Eiger' use case https://support.hdfgroup.org/HDF5/docNewFeatures/VDS/HDF5-VDS-requirements-use-cases-2014-12-10.pdf ''' import h5py import numpy as np files = ['1.h5', '2.h5', '3.h5', '4.h5', '5.h5'] entry_key = 'data' # where the data is inside of the source files. sh = h5py.File(files[0], 'r')[entry_key].shape # get the first ones shape. layout = h5py.VirtualLayout(shape=(len(files),) + sh, dtype=np.float) M_start = 0 for i, filename in enumerate(files): M_end = M_start + sh[0] vsource = h5py.VirtualSource(filename, entry_key, shape=sh) layout[M_start:M_end:1, :, :] = vsource M_start = M_end with h5py.File("eiger_vds.h5", 'w', libver='latest') as f: f.create_virtual_dataset('data', layout, fillvalue=0)
'''Virtual datasets: The 'Eiger' use case https://support.hdfgroup.org/HDF5/docNewFeatures/VDS/HDF5-VDS-requirements-use-cases-2014-12-10.pdf ''' import h5py import numpy as np files = ['1.h5', '2.h5', '3.h5', '4.h5', '5.h5'] entry_key = 'data' # where the data is inside of the source files. sh = h5py.File(files[0], 'r')[entry_key].shape # get the first ones shape. layout = h5py.VirtualLayout(shape=(len(files) * sh[0], ) + sh[1:], dtype=np.float) M_start = 0 for i, filename in enumerate(files): M_end = M_start + sh[0] vsource = h5py.VirtualSource(filename, entry_key, shape=sh) layout[M_start:M_end:1, :, :] = vsource M_start = M_end with h5py.File("eiger_vds.h5", 'w', libver='latest') as f: f.create_virtual_dataset('data', layout, fillvalue=0)
Fix layout for Eiger example
Fix layout for Eiger example
Python
bsd-3-clause
h5py/h5py,h5py/h5py,h5py/h5py
'''Virtual datasets: The 'Eiger' use case https://support.hdfgroup.org/HDF5/docNewFeatures/VDS/HDF5-VDS-requirements-use-cases-2014-12-10.pdf ''' import h5py import numpy as np files = ['1.h5', '2.h5', '3.h5', '4.h5', '5.h5'] entry_key = 'data' # where the data is inside of the source files. sh = h5py.File(files[0], 'r')[entry_key].shape # get the first ones shape. - layout = h5py.VirtualLayout(shape=(len(files),) + sh, dtype=np.float) + layout = h5py.VirtualLayout(shape=(len(files) * sh[0], ) + sh[1:], dtype=np.float) M_start = 0 for i, filename in enumerate(files): M_end = M_start + sh[0] vsource = h5py.VirtualSource(filename, entry_key, shape=sh) layout[M_start:M_end:1, :, :] = vsource M_start = M_end with h5py.File("eiger_vds.h5", 'w', libver='latest') as f: f.create_virtual_dataset('data', layout, fillvalue=0)
Fix layout for Eiger example
## Code Before: '''Virtual datasets: The 'Eiger' use case https://support.hdfgroup.org/HDF5/docNewFeatures/VDS/HDF5-VDS-requirements-use-cases-2014-12-10.pdf ''' import h5py import numpy as np files = ['1.h5', '2.h5', '3.h5', '4.h5', '5.h5'] entry_key = 'data' # where the data is inside of the source files. sh = h5py.File(files[0], 'r')[entry_key].shape # get the first ones shape. layout = h5py.VirtualLayout(shape=(len(files),) + sh, dtype=np.float) M_start = 0 for i, filename in enumerate(files): M_end = M_start + sh[0] vsource = h5py.VirtualSource(filename, entry_key, shape=sh) layout[M_start:M_end:1, :, :] = vsource M_start = M_end with h5py.File("eiger_vds.h5", 'w', libver='latest') as f: f.create_virtual_dataset('data', layout, fillvalue=0) ## Instruction: Fix layout for Eiger example ## Code After: '''Virtual datasets: The 'Eiger' use case https://support.hdfgroup.org/HDF5/docNewFeatures/VDS/HDF5-VDS-requirements-use-cases-2014-12-10.pdf ''' import h5py import numpy as np files = ['1.h5', '2.h5', '3.h5', '4.h5', '5.h5'] entry_key = 'data' # where the data is inside of the source files. sh = h5py.File(files[0], 'r')[entry_key].shape # get the first ones shape. layout = h5py.VirtualLayout(shape=(len(files) * sh[0], ) + sh[1:], dtype=np.float) M_start = 0 for i, filename in enumerate(files): M_end = M_start + sh[0] vsource = h5py.VirtualSource(filename, entry_key, shape=sh) layout[M_start:M_end:1, :, :] = vsource M_start = M_end with h5py.File("eiger_vds.h5", 'w', libver='latest') as f: f.create_virtual_dataset('data', layout, fillvalue=0)
... layout = h5py.VirtualLayout(shape=(len(files) * sh[0], ) + sh[1:], dtype=np.float) M_start = 0 ...
46a0caa1bc162d11b26a996379170b2fc49f2940
mcbench/client.py
mcbench/client.py
import collections import redis BENCHMARK_FIELDS = [ 'author', 'author_url', 'date_submitted', 'date_updated', 'name', 'summary', 'tags', 'title', 'url' ] Benchmark = collections.namedtuple('Benchmark', ' '.join(BENCHMARK_FIELDS)) class McBenchClient(object): def __init__(self, redis): self.redis = redis def get_benchmark_by_id(self, benchmark_id): return Benchmark(**self.redis.hgetall('benchmark:%s' % benchmark_id)) def get_benchmark_by_name(self, name): benchmark_id = self.redis.get('benchmark:%s:id', name) return self.get_benchmark_by_id(benchmark_id) def insert_benchmark(self, benchmark): benchmark_id = self.redis.incr('global:next_benchmark_id') self.redis.set('benchmark:%s:id' % benchmark.name, benchmark_id) self.redis.hmset('benchmark:%s' % benchmark_id, benchmark._asdict()) def from_redis_url(redis_url): return McBenchClient(redis.from_url(redis_url))
import redis class Benchmark(object): def __init__(self, author, author_url, date_submitted, date_updated, name, summary, tags, title, url): self.author = author self.author_url = author_url self.date_submitted = date_submitted self.date_updated = date_updated self.name = name self.summary = summary self.tags = tags self.title = title self.url = url def __repr__(self): return '<Benchmark: %s>' % self.name class BenchmarkDoesNotExist(Exception): pass class BenchmarkAlreadyExists(Exception): pass class McBenchClient(object): def __init__(self, redis): self.redis = redis def get_benchmark_by_id(self, benchmark_id): data = self.redis.hgetall('benchmark:%s' % benchmark_id) if not data: raise BenchmarkDoesNotExist return Benchmark(**data) def get_benchmark_by_name(self, name): benchmark_id = self.redis.get('name:%s:id' % name) if benchmark_id is None: raise BenchmarkDoesNotExist return self.get_benchmark_by_id(benchmark_id) def get_all_benchmarks(self): return [self.get_benchmark_by_id(key[len('benchmark:'):]) for key in self.redis.keys('benchmark:*')] def insert_benchmark(self, benchmark): benchmark_id = self.redis.get('name:%s:id' % benchmark.name) if benchmark_id is not None: raise BenchmarkAlreadyExists benchmark_id = self.redis.incr('global:next_benchmark_id') self.redis.set('name:%s:id' % benchmark.name, benchmark_id) self.redis.hmset('benchmark:%s' % benchmark_id, vars(benchmark)) def from_redis_url(redis_url): return McBenchClient(redis.from_url(redis_url))
Make Benchmark a class, not a namedtuple.
Make Benchmark a class, not a namedtuple.
Python
mit
isbadawi/mcbench,isbadawi/mcbench
- import collections - import redis - BENCHMARK_FIELDS = [ - 'author', 'author_url', 'date_submitted', 'date_updated', - 'name', 'summary', 'tags', 'title', 'url' - ] - Benchmark = collections.namedtuple('Benchmark', ' '.join(BENCHMARK_FIELDS)) + class Benchmark(object): + def __init__(self, author, author_url, date_submitted, date_updated, + name, summary, tags, title, url): + self.author = author + self.author_url = author_url + self.date_submitted = date_submitted + self.date_updated = date_updated + self.name = name + self.summary = summary + self.tags = tags + self.title = title + self.url = url + + def __repr__(self): + return '<Benchmark: %s>' % self.name + + + class BenchmarkDoesNotExist(Exception): + pass + + + class BenchmarkAlreadyExists(Exception): + pass class McBenchClient(object): def __init__(self, redis): self.redis = redis def get_benchmark_by_id(self, benchmark_id): - return Benchmark(**self.redis.hgetall('benchmark:%s' % benchmark_id)) + data = self.redis.hgetall('benchmark:%s' % benchmark_id) + if not data: + raise BenchmarkDoesNotExist + return Benchmark(**data) def get_benchmark_by_name(self, name): - benchmark_id = self.redis.get('benchmark:%s:id', name) + benchmark_id = self.redis.get('name:%s:id' % name) + if benchmark_id is None: + raise BenchmarkDoesNotExist return self.get_benchmark_by_id(benchmark_id) + def get_all_benchmarks(self): + return [self.get_benchmark_by_id(key[len('benchmark:'):]) + for key in self.redis.keys('benchmark:*')] + def insert_benchmark(self, benchmark): + benchmark_id = self.redis.get('name:%s:id' % benchmark.name) + if benchmark_id is not None: + raise BenchmarkAlreadyExists benchmark_id = self.redis.incr('global:next_benchmark_id') - self.redis.set('benchmark:%s:id' % benchmark.name, benchmark_id) + self.redis.set('name:%s:id' % benchmark.name, benchmark_id) - self.redis.hmset('benchmark:%s' % benchmark_id, benchmark._asdict()) + self.redis.hmset('benchmark:%s' % benchmark_id, vars(benchmark)) def from_redis_url(redis_url): return McBenchClient(redis.from_url(redis_url))
Make Benchmark a class, not a namedtuple.
## Code Before: import collections import redis BENCHMARK_FIELDS = [ 'author', 'author_url', 'date_submitted', 'date_updated', 'name', 'summary', 'tags', 'title', 'url' ] Benchmark = collections.namedtuple('Benchmark', ' '.join(BENCHMARK_FIELDS)) class McBenchClient(object): def __init__(self, redis): self.redis = redis def get_benchmark_by_id(self, benchmark_id): return Benchmark(**self.redis.hgetall('benchmark:%s' % benchmark_id)) def get_benchmark_by_name(self, name): benchmark_id = self.redis.get('benchmark:%s:id', name) return self.get_benchmark_by_id(benchmark_id) def insert_benchmark(self, benchmark): benchmark_id = self.redis.incr('global:next_benchmark_id') self.redis.set('benchmark:%s:id' % benchmark.name, benchmark_id) self.redis.hmset('benchmark:%s' % benchmark_id, benchmark._asdict()) def from_redis_url(redis_url): return McBenchClient(redis.from_url(redis_url)) ## Instruction: Make Benchmark a class, not a namedtuple. ## Code After: import redis class Benchmark(object): def __init__(self, author, author_url, date_submitted, date_updated, name, summary, tags, title, url): self.author = author self.author_url = author_url self.date_submitted = date_submitted self.date_updated = date_updated self.name = name self.summary = summary self.tags = tags self.title = title self.url = url def __repr__(self): return '<Benchmark: %s>' % self.name class BenchmarkDoesNotExist(Exception): pass class BenchmarkAlreadyExists(Exception): pass class McBenchClient(object): def __init__(self, redis): self.redis = redis def get_benchmark_by_id(self, benchmark_id): data = self.redis.hgetall('benchmark:%s' % benchmark_id) if not data: raise BenchmarkDoesNotExist return Benchmark(**data) def get_benchmark_by_name(self, name): benchmark_id = self.redis.get('name:%s:id' % name) if benchmark_id is None: raise BenchmarkDoesNotExist return self.get_benchmark_by_id(benchmark_id) def get_all_benchmarks(self): return [self.get_benchmark_by_id(key[len('benchmark:'):]) for key in self.redis.keys('benchmark:*')] def insert_benchmark(self, benchmark): benchmark_id = self.redis.get('name:%s:id' % benchmark.name) if benchmark_id is not None: raise BenchmarkAlreadyExists benchmark_id = self.redis.incr('global:next_benchmark_id') self.redis.set('name:%s:id' % benchmark.name, benchmark_id) self.redis.hmset('benchmark:%s' % benchmark_id, vars(benchmark)) def from_redis_url(redis_url): return McBenchClient(redis.from_url(redis_url))
... import redis ... class Benchmark(object): def __init__(self, author, author_url, date_submitted, date_updated, name, summary, tags, title, url): self.author = author self.author_url = author_url self.date_submitted = date_submitted self.date_updated = date_updated self.name = name self.summary = summary self.tags = tags self.title = title self.url = url def __repr__(self): return '<Benchmark: %s>' % self.name class BenchmarkDoesNotExist(Exception): pass class BenchmarkAlreadyExists(Exception): pass ... def get_benchmark_by_id(self, benchmark_id): data = self.redis.hgetall('benchmark:%s' % benchmark_id) if not data: raise BenchmarkDoesNotExist return Benchmark(**data) ... def get_benchmark_by_name(self, name): benchmark_id = self.redis.get('name:%s:id' % name) if benchmark_id is None: raise BenchmarkDoesNotExist return self.get_benchmark_by_id(benchmark_id) ... def get_all_benchmarks(self): return [self.get_benchmark_by_id(key[len('benchmark:'):]) for key in self.redis.keys('benchmark:*')] def insert_benchmark(self, benchmark): benchmark_id = self.redis.get('name:%s:id' % benchmark.name) if benchmark_id is not None: raise BenchmarkAlreadyExists benchmark_id = self.redis.incr('global:next_benchmark_id') self.redis.set('name:%s:id' % benchmark.name, benchmark_id) self.redis.hmset('benchmark:%s' % benchmark_id, vars(benchmark)) ...
89b54d9c7fec213465446148e39612a2ac659ca2
test/common/test_openstack.py
test/common/test_openstack.py
import sys import unittest from mock import Mock from libcloud.common.openstack import OpenStackBaseConnection class OpenStackBaseConnectionTest(unittest.TestCase): def setUp(self): self.timeout = 10 OpenStackBaseConnection.conn_classes = (None, Mock()) self.connection = OpenStackBaseConnection('foo', 'bar', timeout=self.timeout, ex_force_auth_url='https://127.0.0.1') self.connection.driver = Mock() self.connection.driver.name = 'OpenStackDriver' def test_base_connection_timeout(self): self.connection.connect() self.assertEquals(self.connection.timeout, self.timeout) self.connection.conn_classes[1].assert_called_with(host='127.0.0.1', port=443, timeout=10) if __name__ == '__main__': sys.exit(unittest.main())
import sys import unittest from mock import Mock from libcloud.common.openstack import OpenStackBaseConnection from libcloud.utils.py3 import PY25 class OpenStackBaseConnectionTest(unittest.TestCase): def setUp(self): self.timeout = 10 OpenStackBaseConnection.conn_classes = (None, Mock()) self.connection = OpenStackBaseConnection('foo', 'bar', timeout=self.timeout, ex_force_auth_url='https://127.0.0.1') self.connection.driver = Mock() self.connection.driver.name = 'OpenStackDriver' def test_base_connection_timeout(self): self.connection.connect() self.assertEquals(self.connection.timeout, self.timeout) if PY25: self.connection.conn_classes[1].assert_called_with(host='127.0.0.1', port=443) else: self.connection.conn_classes[1].assert_called_with(host='127.0.0.1', port=443, timeout=10) if __name__ == '__main__': sys.exit(unittest.main())
Fix test so it works with python 2.5.
Fix test so it works with python 2.5. git-svn-id: 9ad005ce451fa0ce30ad6352b03eb45b36893355@1342997 13f79535-47bb-0310-9956-ffa450edef68
Python
apache-2.0
Jc2k/libcloud,marcinzaremba/libcloud,Scalr/libcloud,mathspace/libcloud,Verizon/libcloud,DimensionDataCBUSydney/libcloud,Cloud-Elasticity-Services/as-libcloud,lochiiconnectivity/libcloud,MrBasset/libcloud,sfriesel/libcloud,wrigri/libcloud,Itxaka/libcloud,erjohnso/libcloud,jerryblakley/libcloud,Scalr/libcloud,marcinzaremba/libcloud,JamesGuthrie/libcloud,watermelo/libcloud,iPlantCollaborativeOpenSource/libcloud,StackPointCloud/libcloud,niteoweb/libcloud,atsaki/libcloud,pquentin/libcloud,mistio/libcloud,wrigri/libcloud,cryptickp/libcloud,illfelder/libcloud,carletes/libcloud,andrewsomething/libcloud,kater169/libcloud,Itxaka/libcloud,aviweit/libcloud,apache/libcloud,illfelder/libcloud,SecurityCompass/libcloud,niteoweb/libcloud,SecurityCompass/libcloud,wrigri/libcloud,mtekel/libcloud,schaubl/libcloud,mistio/libcloud,wuyuewen/libcloud,ZuluPro/libcloud,vongazman/libcloud,munkiat/libcloud,cloudControl/libcloud,mathspace/libcloud,DimensionDataCBUSydney/libcloud,sgammon/libcloud,ninefold/libcloud,lochiiconnectivity/libcloud,ByteInternet/libcloud,jimbobhickville/libcloud,mtekel/libcloud,sahildua2305/libcloud,sahildua2305/libcloud,sahildua2305/libcloud,aleGpereira/libcloud,StackPointCloud/libcloud,kater169/libcloud,ClusterHQ/libcloud,niteoweb/libcloud,andrewsomething/libcloud,Scalr/libcloud,ByteInternet/libcloud,DimensionDataCBUSydney/libcloud,dcorbacho/libcloud,carletes/libcloud,carletes/libcloud,Verizon/libcloud,jimbobhickville/libcloud,wido/libcloud,iPlantCollaborativeOpenSource/libcloud,wuyuewen/libcloud,schaubl/libcloud,Kami/libcloud,wuyuewen/libcloud,munkiat/libcloud,sergiorua/libcloud,munkiat/libcloud,erjohnso/libcloud,pantheon-systems/libcloud,mathspace/libcloud,aviweit/libcloud,sergiorua/libcloud,thesquelched/libcloud,aviweit/libcloud,SecurityCompass/libcloud,mgogoulos/libcloud,thesquelched/libcloud,kater169/libcloud,curoverse/libcloud,NexusIS/libcloud,jerryblakley/libcloud,Kami/libcloud,marcinzaremba/libcloud,erjohnso/libcloud,cryptickp/libcloud,samuelchong/libcloud,aleGpereira/libcloud,curoverse/libcloud,sfriesel/libcloud,briancurtin/libcloud,samuelchong/libcloud,schaubl/libcloud,supertom/libcloud,vongazman/libcloud,sgammon/libcloud,MrBasset/libcloud,NexusIS/libcloud,Cloud-Elasticity-Services/as-libcloud,ZuluPro/libcloud,curoverse/libcloud,aleGpereira/libcloud,watermelo/libcloud,cloudControl/libcloud,pquentin/libcloud,dcorbacho/libcloud,apache/libcloud,JamesGuthrie/libcloud,briancurtin/libcloud,ZuluPro/libcloud,cloudControl/libcloud,t-tran/libcloud,smaffulli/libcloud,pantheon-systems/libcloud,watermelo/libcloud,briancurtin/libcloud,iPlantCollaborativeOpenSource/libcloud,Cloud-Elasticity-Services/as-libcloud,jimbobhickville/libcloud,StackPointCloud/libcloud,mistio/libcloud,vongazman/libcloud,andrewsomething/libcloud,atsaki/libcloud,supertom/libcloud,Jc2k/libcloud,techhat/libcloud,thesquelched/libcloud,pantheon-systems/libcloud,Verizon/libcloud,mbrukman/libcloud,techhat/libcloud,dcorbacho/libcloud,ByteInternet/libcloud,smaffulli/libcloud,t-tran/libcloud,wido/libcloud,atsaki/libcloud,mtekel/libcloud,Kami/libcloud,techhat/libcloud,smaffulli/libcloud,sfriesel/libcloud,t-tran/libcloud,ClusterHQ/libcloud,mbrukman/libcloud,mgogoulos/libcloud,apache/libcloud,pquentin/libcloud,NexusIS/libcloud,sergiorua/libcloud,mbrukman/libcloud,jerryblakley/libcloud,supertom/libcloud,mgogoulos/libcloud,MrBasset/libcloud,JamesGuthrie/libcloud,ninefold/libcloud,samuelchong/libcloud,lochiiconnectivity/libcloud,cryptickp/libcloud,illfelder/libcloud,Itxaka/libcloud,wido/libcloud
import sys import unittest from mock import Mock from libcloud.common.openstack import OpenStackBaseConnection + from libcloud.utils.py3 import PY25 class OpenStackBaseConnectionTest(unittest.TestCase): def setUp(self): self.timeout = 10 OpenStackBaseConnection.conn_classes = (None, Mock()) self.connection = OpenStackBaseConnection('foo', 'bar', timeout=self.timeout, ex_force_auth_url='https://127.0.0.1') self.connection.driver = Mock() self.connection.driver.name = 'OpenStackDriver' def test_base_connection_timeout(self): self.connection.connect() self.assertEquals(self.connection.timeout, self.timeout) + if PY25: - self.connection.conn_classes[1].assert_called_with(host='127.0.0.1', + self.connection.conn_classes[1].assert_called_with(host='127.0.0.1', + port=443) + else: + self.connection.conn_classes[1].assert_called_with(host='127.0.0.1', - port=443, + port=443, - timeout=10) + timeout=10) if __name__ == '__main__': sys.exit(unittest.main())
Fix test so it works with python 2.5.
## Code Before: import sys import unittest from mock import Mock from libcloud.common.openstack import OpenStackBaseConnection class OpenStackBaseConnectionTest(unittest.TestCase): def setUp(self): self.timeout = 10 OpenStackBaseConnection.conn_classes = (None, Mock()) self.connection = OpenStackBaseConnection('foo', 'bar', timeout=self.timeout, ex_force_auth_url='https://127.0.0.1') self.connection.driver = Mock() self.connection.driver.name = 'OpenStackDriver' def test_base_connection_timeout(self): self.connection.connect() self.assertEquals(self.connection.timeout, self.timeout) self.connection.conn_classes[1].assert_called_with(host='127.0.0.1', port=443, timeout=10) if __name__ == '__main__': sys.exit(unittest.main()) ## Instruction: Fix test so it works with python 2.5. ## Code After: import sys import unittest from mock import Mock from libcloud.common.openstack import OpenStackBaseConnection from libcloud.utils.py3 import PY25 class OpenStackBaseConnectionTest(unittest.TestCase): def setUp(self): self.timeout = 10 OpenStackBaseConnection.conn_classes = (None, Mock()) self.connection = OpenStackBaseConnection('foo', 'bar', timeout=self.timeout, ex_force_auth_url='https://127.0.0.1') self.connection.driver = Mock() self.connection.driver.name = 'OpenStackDriver' def test_base_connection_timeout(self): self.connection.connect() self.assertEquals(self.connection.timeout, self.timeout) if PY25: self.connection.conn_classes[1].assert_called_with(host='127.0.0.1', port=443) else: self.connection.conn_classes[1].assert_called_with(host='127.0.0.1', port=443, timeout=10) if __name__ == '__main__': sys.exit(unittest.main())
... from libcloud.common.openstack import OpenStackBaseConnection from libcloud.utils.py3 import PY25 ... self.assertEquals(self.connection.timeout, self.timeout) if PY25: self.connection.conn_classes[1].assert_called_with(host='127.0.0.1', port=443) else: self.connection.conn_classes[1].assert_called_with(host='127.0.0.1', port=443, timeout=10) ...
43d14f73055643a2e4921a58aa1bf5e14fdf8e74
linter.py
linter.py
import logging import re from SublimeLinter.lint import NodeLinter logger = logging.getLogger('SublimeLinter.plugin.tslint') class Tslint(NodeLinter): cmd = 'tslint --format verbose ${file}' regex = ( r'^(?:' r'(ERROR:\s+\((?P<error>.*)\))|' r'(WARNING:\s+\((?P<warning>.*)\))' r')?' r'.+?\[(?P<line>\d+), (?P<col>\d+)\]: ' r'(?P<message>.+)' ) tempfile_suffix = '-' defaults = { 'selector': 'source.ts, source.tsx' } def on_stderr(self, stderr): # suppress warnings like "rule requires type information" stderr = re.sub( 'Warning: .+\n', '', stderr) if stderr: self.notify_failure() logger.error(stderr)
import logging import re from SublimeLinter.lint import NodeLinter logger = logging.getLogger('SublimeLinter.plugin.tslint') class Tslint(NodeLinter): cmd = 'tslint --format verbose ${file}' regex = ( r'^(?:' r'(ERROR:\s+\((?P<error>.*)\))|' r'(WARNING:\s+\((?P<warning>.*)\))' r')?' r'\s+(?P<filename>.+?)' r'\[(?P<line>\d+), (?P<col>\d+)\]: ' r'(?P<message>.+)' ) tempfile_suffix = '-' defaults = { 'selector': 'source.ts, source.tsx' } def on_stderr(self, stderr): # suppress warnings like "rule requires type information" stderr = re.sub( 'Warning: .+\n', '', stderr) if stderr: self.notify_failure() logger.error(stderr)
Update regex to include filename capture group.
Update regex to include filename capture group.
Python
mit
lavrton/SublimeLinter-contrib-tslint
import logging import re from SublimeLinter.lint import NodeLinter logger = logging.getLogger('SublimeLinter.plugin.tslint') class Tslint(NodeLinter): cmd = 'tslint --format verbose ${file}' regex = ( r'^(?:' r'(ERROR:\s+\((?P<error>.*)\))|' r'(WARNING:\s+\((?P<warning>.*)\))' r')?' + r'\s+(?P<filename>.+?)' - r'.+?\[(?P<line>\d+), (?P<col>\d+)\]: ' + r'\[(?P<line>\d+), (?P<col>\d+)\]: ' r'(?P<message>.+)' ) tempfile_suffix = '-' defaults = { 'selector': 'source.ts, source.tsx' } def on_stderr(self, stderr): # suppress warnings like "rule requires type information" stderr = re.sub( 'Warning: .+\n', '', stderr) if stderr: self.notify_failure() logger.error(stderr)
Update regex to include filename capture group.
## Code Before: import logging import re from SublimeLinter.lint import NodeLinter logger = logging.getLogger('SublimeLinter.plugin.tslint') class Tslint(NodeLinter): cmd = 'tslint --format verbose ${file}' regex = ( r'^(?:' r'(ERROR:\s+\((?P<error>.*)\))|' r'(WARNING:\s+\((?P<warning>.*)\))' r')?' r'.+?\[(?P<line>\d+), (?P<col>\d+)\]: ' r'(?P<message>.+)' ) tempfile_suffix = '-' defaults = { 'selector': 'source.ts, source.tsx' } def on_stderr(self, stderr): # suppress warnings like "rule requires type information" stderr = re.sub( 'Warning: .+\n', '', stderr) if stderr: self.notify_failure() logger.error(stderr) ## Instruction: Update regex to include filename capture group. ## Code After: import logging import re from SublimeLinter.lint import NodeLinter logger = logging.getLogger('SublimeLinter.plugin.tslint') class Tslint(NodeLinter): cmd = 'tslint --format verbose ${file}' regex = ( r'^(?:' r'(ERROR:\s+\((?P<error>.*)\))|' r'(WARNING:\s+\((?P<warning>.*)\))' r')?' r'\s+(?P<filename>.+?)' r'\[(?P<line>\d+), (?P<col>\d+)\]: ' r'(?P<message>.+)' ) tempfile_suffix = '-' defaults = { 'selector': 'source.ts, source.tsx' } def on_stderr(self, stderr): # suppress warnings like "rule requires type information" stderr = re.sub( 'Warning: .+\n', '', stderr) if stderr: self.notify_failure() logger.error(stderr)
// ... existing code ... r')?' r'\s+(?P<filename>.+?)' r'\[(?P<line>\d+), (?P<col>\d+)\]: ' r'(?P<message>.+)' // ... rest of the code ...
c496be720461722ce482c981b4915365dd0df8ab
events/views.py
events/views.py
from django.contrib import messages from django.contrib.auth.decorators import login_required from django.views.generic.list import ListView from django.views.generic.detail import DetailView from base.util import class_view_decorator from base.views import RedirectBackView from .models import Event, EventUserRegistration class EventListView(ListView): model = Event context_object_name = 'events' class EventDetailView(DetailView): model = Event context_object_name = 'event' @class_view_decorator(login_required) class EventUserRegisterView(RedirectBackView): default_return_view = 'events_event_list' def dispatch(self, request, *args, **kwargs): event = Event.objects.get(pk=kwargs['event_id']) if event.registration_open(): registration = EventUserRegistration(user=request.user, event=event) registration.save() message = 'Successfully registered to the %s' % event messages.add_message(request, messages.INFO, message) else: message = 'Registration to the %s is not open.' % event messages.add_message(request, messages.ERROR, message) return super(EventUserRegisterView, self).dispatch(request, *args, **kwargs)
from django.contrib import messages from django.contrib.auth.decorators import login_required from django.utils.translation import ugettext_lazy as _ from django.views.generic.list import ListView from django.views.generic.detail import DetailView from base.util import class_view_decorator from base.views import RedirectBackView from .models import Event, EventUserRegistration class EventListView(ListView): model = Event context_object_name = 'events' class EventDetailView(DetailView): model = Event context_object_name = 'event' @class_view_decorator(login_required) class EventUserRegisterView(RedirectBackView): default_return_view = 'events_event_list' def dispatch(self, request, *args, **kwargs): event = Event.objects.get(pk=kwargs['event_id']) # Check if user is not already registered registrations = EventUserRegistration.objects.filter( user=request.user, event=event).count() if registrations: message = _('You are already registered to the %s') % event messages.add_message(request, messages.ERROR, message) return super(EventUserRegisterView, self).dispatch(request, *args, **kwargs) if event.registration_open(): registration = EventUserRegistration(user=request.user, event=event) registration.save() message = _('Successfully registered to the %s') % event messages.add_message(request, messages.INFO, message) else: message = _('Registration to the %s is not open.') % event messages.add_message(request, messages.ERROR, message) return super(EventUserRegisterView, self).dispatch(request, *args, **kwargs)
Raise error when user is registering to the event multiple times
events: Raise error when user is registering to the event multiple times
Python
mit
matus-stehlik/roots,rtrembecky/roots,tbabej/roots,rtrembecky/roots,matus-stehlik/roots,rtrembecky/roots,tbabej/roots,tbabej/roots,matus-stehlik/roots
from django.contrib import messages from django.contrib.auth.decorators import login_required + from django.utils.translation import ugettext_lazy as _ from django.views.generic.list import ListView from django.views.generic.detail import DetailView from base.util import class_view_decorator from base.views import RedirectBackView from .models import Event, EventUserRegistration class EventListView(ListView): model = Event context_object_name = 'events' class EventDetailView(DetailView): model = Event context_object_name = 'event' @class_view_decorator(login_required) class EventUserRegisterView(RedirectBackView): default_return_view = 'events_event_list' def dispatch(self, request, *args, **kwargs): event = Event.objects.get(pk=kwargs['event_id']) + # Check if user is not already registered + registrations = EventUserRegistration.objects.filter( + user=request.user, + event=event).count() + + if registrations: + message = _('You are already registered to the %s') % event + messages.add_message(request, messages.ERROR, message) + return super(EventUserRegisterView, self).dispatch(request, + *args, + **kwargs) + if event.registration_open(): registration = EventUserRegistration(user=request.user, event=event) registration.save() - message = 'Successfully registered to the %s' % event + message = _('Successfully registered to the %s') % event messages.add_message(request, messages.INFO, message) else: - message = 'Registration to the %s is not open.' % event + message = _('Registration to the %s is not open.') % event messages.add_message(request, messages.ERROR, message) return super(EventUserRegisterView, self).dispatch(request, *args, **kwargs)
Raise error when user is registering to the event multiple times
## Code Before: from django.contrib import messages from django.contrib.auth.decorators import login_required from django.views.generic.list import ListView from django.views.generic.detail import DetailView from base.util import class_view_decorator from base.views import RedirectBackView from .models import Event, EventUserRegistration class EventListView(ListView): model = Event context_object_name = 'events' class EventDetailView(DetailView): model = Event context_object_name = 'event' @class_view_decorator(login_required) class EventUserRegisterView(RedirectBackView): default_return_view = 'events_event_list' def dispatch(self, request, *args, **kwargs): event = Event.objects.get(pk=kwargs['event_id']) if event.registration_open(): registration = EventUserRegistration(user=request.user, event=event) registration.save() message = 'Successfully registered to the %s' % event messages.add_message(request, messages.INFO, message) else: message = 'Registration to the %s is not open.' % event messages.add_message(request, messages.ERROR, message) return super(EventUserRegisterView, self).dispatch(request, *args, **kwargs) ## Instruction: Raise error when user is registering to the event multiple times ## Code After: from django.contrib import messages from django.contrib.auth.decorators import login_required from django.utils.translation import ugettext_lazy as _ from django.views.generic.list import ListView from django.views.generic.detail import DetailView from base.util import class_view_decorator from base.views import RedirectBackView from .models import Event, EventUserRegistration class EventListView(ListView): model = Event context_object_name = 'events' class EventDetailView(DetailView): model = Event context_object_name = 'event' @class_view_decorator(login_required) class EventUserRegisterView(RedirectBackView): default_return_view = 'events_event_list' def dispatch(self, request, *args, **kwargs): event = Event.objects.get(pk=kwargs['event_id']) # Check if user is not already registered registrations = EventUserRegistration.objects.filter( user=request.user, event=event).count() if registrations: message = _('You are already registered to the %s') % event messages.add_message(request, messages.ERROR, message) return super(EventUserRegisterView, self).dispatch(request, *args, **kwargs) if event.registration_open(): registration = EventUserRegistration(user=request.user, event=event) registration.save() message = _('Successfully registered to the %s') % event messages.add_message(request, messages.INFO, message) else: message = _('Registration to the %s is not open.') % event messages.add_message(request, messages.ERROR, message) return super(EventUserRegisterView, self).dispatch(request, *args, **kwargs)
# ... existing code ... from django.contrib.auth.decorators import login_required from django.utils.translation import ugettext_lazy as _ from django.views.generic.list import ListView # ... modified code ... # Check if user is not already registered registrations = EventUserRegistration.objects.filter( user=request.user, event=event).count() if registrations: message = _('You are already registered to the %s') % event messages.add_message(request, messages.ERROR, message) return super(EventUserRegisterView, self).dispatch(request, *args, **kwargs) if event.registration_open(): ... message = _('Successfully registered to the %s') % event messages.add_message(request, messages.INFO, message) ... else: message = _('Registration to the %s is not open.') % event messages.add_message(request, messages.ERROR, message) # ... rest of the code ...
36e0821fcd871935e48ae10926be7594d42f13b8
knowledge_repo/converters/pdf.py
knowledge_repo/converters/pdf.py
from ..converter import KnowledgePostConverter from .html import HTMLConverter class PDFConverter(KnowledgePostConverter): ''' Use this as a template for new KnowledgePostConverters. ''' _registry_keys = ['pdf'] @property def dependencies(self): # Dependencies required for this converter on top of core knowledge-repo dependencies return ['weasyprint'] def from_file(self, filename, **opts): raise NotImplementedError def from_string(self, filename, **opts): raise NotImplementedError def to_file(self, filename, **opts): with open(filename, 'wb') as f: f.write(self.to_string()) def to_string(self, **opts): from weasyprint import HTML html = HTMLConverter(self.kp).to_string() return HTML(string=html).write_pdf()
from ..converter import KnowledgePostConverter from .html import HTMLConverter class PDFConverter(KnowledgePostConverter): ''' Use this as a template for new KnowledgePostConverters. ''' _registry_keys = ['pdf'] @property def dependencies(self): # Dependencies required for this converter on top of core knowledge-repo dependencies return ['weasyprint'] def from_file(self, filename, **opts): raise NotImplementedError def from_string(self, filename, **opts): raise NotImplementedError def to_file(self, filename, **opts): with open(filename, 'wb') as f: f.write(self.to_string()) def to_string(self, **opts): from weasyprint import HTML, CSS html = HTMLConverter(self.kp).to_string() return HTML(string=html).write_pdf(stylesheets=[CSS(string='body { font-family: Helvetica, sans-serif !important }')])
Change PDF font to Helvetica
Change PDF font to Helvetica Changing the PDF font from the default to Helvetica
Python
apache-2.0
airbnb/knowledge-repo,airbnb/knowledge-repo,airbnb/knowledge-repo,airbnb/knowledge-repo,airbnb/knowledge-repo
from ..converter import KnowledgePostConverter from .html import HTMLConverter class PDFConverter(KnowledgePostConverter): ''' Use this as a template for new KnowledgePostConverters. ''' _registry_keys = ['pdf'] @property def dependencies(self): # Dependencies required for this converter on top of core knowledge-repo dependencies return ['weasyprint'] def from_file(self, filename, **opts): raise NotImplementedError def from_string(self, filename, **opts): raise NotImplementedError def to_file(self, filename, **opts): with open(filename, 'wb') as f: f.write(self.to_string()) def to_string(self, **opts): - from weasyprint import HTML + from weasyprint import HTML, CSS html = HTMLConverter(self.kp).to_string() - return HTML(string=html).write_pdf() + return HTML(string=html).write_pdf(stylesheets=[CSS(string='body { font-family: Helvetica, sans-serif !important }')])
Change PDF font to Helvetica
## Code Before: from ..converter import KnowledgePostConverter from .html import HTMLConverter class PDFConverter(KnowledgePostConverter): ''' Use this as a template for new KnowledgePostConverters. ''' _registry_keys = ['pdf'] @property def dependencies(self): # Dependencies required for this converter on top of core knowledge-repo dependencies return ['weasyprint'] def from_file(self, filename, **opts): raise NotImplementedError def from_string(self, filename, **opts): raise NotImplementedError def to_file(self, filename, **opts): with open(filename, 'wb') as f: f.write(self.to_string()) def to_string(self, **opts): from weasyprint import HTML html = HTMLConverter(self.kp).to_string() return HTML(string=html).write_pdf() ## Instruction: Change PDF font to Helvetica ## Code After: from ..converter import KnowledgePostConverter from .html import HTMLConverter class PDFConverter(KnowledgePostConverter): ''' Use this as a template for new KnowledgePostConverters. ''' _registry_keys = ['pdf'] @property def dependencies(self): # Dependencies required for this converter on top of core knowledge-repo dependencies return ['weasyprint'] def from_file(self, filename, **opts): raise NotImplementedError def from_string(self, filename, **opts): raise NotImplementedError def to_file(self, filename, **opts): with open(filename, 'wb') as f: f.write(self.to_string()) def to_string(self, **opts): from weasyprint import HTML, CSS html = HTMLConverter(self.kp).to_string() return HTML(string=html).write_pdf(stylesheets=[CSS(string='body { font-family: Helvetica, sans-serif !important }')])
... def to_string(self, **opts): from weasyprint import HTML, CSS html = HTMLConverter(self.kp).to_string() return HTML(string=html).write_pdf(stylesheets=[CSS(string='body { font-family: Helvetica, sans-serif !important }')]) ...
952550b344e96236995ac72eaa0777fd356f21e2
infinity.py
infinity.py
try: from functools import total_ordering except ImportError: # Use Python 2.6 port from total_ordering import total_ordering @total_ordering class Infinity(object): """ An object that is greater than any other object (except itself). Inspired by https://pypi.python.org/pypi/Extremes Examples:: Infinity can be compared to any object: >>> from infinity import inf >>> import sys >>> inf > -sys.maxint True >>> inf > None True >>> inf > '' True >>> inf > datetime(2000, 20, 2) """ def __init__(self, positive=True): self.positive = positive def __neg__(self): return Infinity(not self.positive) def __gt__(self, other): if isinstance(other, self.__class__) and other.positive == self.positive: return False return self.positive def __eq__(self, other): if isinstance(other, self.__class__) and other.positive == self.positive: return True return False def __ne__(self, other): return not (self == other) def __bool__(self): return self.positive def __nonzero__(self): return self.positive def __str__(self): return '%sinf' % ('' if self.positive else '-') inf = Infinity()
try: from functools import total_ordering except ImportError: # Use Python 2.6 port from total_ordering import total_ordering @total_ordering class Infinity(object): """ An object that is greater than any other object (except itself). Inspired by https://pypi.python.org/pypi/Extremes Examples:: Infinity can be compared to any object: >>> from infinity import inf >>> import sys >>> inf > -sys.maxint True >>> inf > None True >>> inf > '' True >>> inf > datetime(2000, 20, 2) """ def __init__(self, positive=True): self.positive = positive def __neg__(self): return Infinity(not self.positive) def __gt__(self, other): if self == other: return False return self.positive def __eq__(self, other): if ( isinstance(other, self.__class__) and other.positive == self.positive ): return True return False def __ne__(self, other): return not (self == other) def __bool__(self): return self.positive def __nonzero__(self): return self.positive def __str__(self): return '%sinf' % ('' if self.positive else '-') def __float__(self): return float(str(self)) def __add__(self, other): if other == self: return self raise NotImplemented def timetuple(self): return tuple() inf = Infinity()
Add float coercion, datetime comparison support
Add float coercion, datetime comparison support
Python
bsd-3-clause
kvesteri/infinity
try: from functools import total_ordering except ImportError: # Use Python 2.6 port from total_ordering import total_ordering @total_ordering class Infinity(object): """ An object that is greater than any other object (except itself). Inspired by https://pypi.python.org/pypi/Extremes Examples:: Infinity can be compared to any object: >>> from infinity import inf >>> import sys >>> inf > -sys.maxint True >>> inf > None True >>> inf > '' True >>> inf > datetime(2000, 20, 2) """ def __init__(self, positive=True): self.positive = positive def __neg__(self): return Infinity(not self.positive) def __gt__(self, other): - if isinstance(other, self.__class__) and other.positive == self.positive: + if self == other: return False return self.positive def __eq__(self, other): - if isinstance(other, self.__class__) and other.positive == self.positive: + if ( + isinstance(other, self.__class__) and + other.positive == self.positive + ): return True return False def __ne__(self, other): return not (self == other) def __bool__(self): return self.positive def __nonzero__(self): return self.positive def __str__(self): return '%sinf' % ('' if self.positive else '-') + def __float__(self): + return float(str(self)) + + def __add__(self, other): + if other == self: + return self + raise NotImplemented + + def timetuple(self): + return tuple() inf = Infinity()
Add float coercion, datetime comparison support
## Code Before: try: from functools import total_ordering except ImportError: # Use Python 2.6 port from total_ordering import total_ordering @total_ordering class Infinity(object): """ An object that is greater than any other object (except itself). Inspired by https://pypi.python.org/pypi/Extremes Examples:: Infinity can be compared to any object: >>> from infinity import inf >>> import sys >>> inf > -sys.maxint True >>> inf > None True >>> inf > '' True >>> inf > datetime(2000, 20, 2) """ def __init__(self, positive=True): self.positive = positive def __neg__(self): return Infinity(not self.positive) def __gt__(self, other): if isinstance(other, self.__class__) and other.positive == self.positive: return False return self.positive def __eq__(self, other): if isinstance(other, self.__class__) and other.positive == self.positive: return True return False def __ne__(self, other): return not (self == other) def __bool__(self): return self.positive def __nonzero__(self): return self.positive def __str__(self): return '%sinf' % ('' if self.positive else '-') inf = Infinity() ## Instruction: Add float coercion, datetime comparison support ## Code After: try: from functools import total_ordering except ImportError: # Use Python 2.6 port from total_ordering import total_ordering @total_ordering class Infinity(object): """ An object that is greater than any other object (except itself). Inspired by https://pypi.python.org/pypi/Extremes Examples:: Infinity can be compared to any object: >>> from infinity import inf >>> import sys >>> inf > -sys.maxint True >>> inf > None True >>> inf > '' True >>> inf > datetime(2000, 20, 2) """ def __init__(self, positive=True): self.positive = positive def __neg__(self): return Infinity(not self.positive) def __gt__(self, other): if self == other: return False return self.positive def __eq__(self, other): if ( isinstance(other, self.__class__) and other.positive == self.positive ): return True return False def __ne__(self, other): return not (self == other) def __bool__(self): return self.positive def __nonzero__(self): return self.positive def __str__(self): return '%sinf' % ('' if self.positive else '-') def __float__(self): return float(str(self)) def __add__(self, other): if other == self: return self raise NotImplemented def timetuple(self): return tuple() inf = Infinity()
// ... existing code ... def __gt__(self, other): if self == other: return False // ... modified code ... def __eq__(self, other): if ( isinstance(other, self.__class__) and other.positive == self.positive ): return True ... def __float__(self): return float(str(self)) def __add__(self, other): if other == self: return self raise NotImplemented def timetuple(self): return tuple() // ... rest of the code ...
957c74c5083eaab466fc72e21afc929267191676
openedx/features/job_board/views.py
openedx/features/job_board/views.py
from django.views.generic.list import ListView from edxmako.shortcuts import render_to_response from .models import Job class JobListView(ListView): model = Job context_object_name = 'job_list' paginate_by = 10 template_name = 'features/job_board/job_list.html' ordering = ['-created'] template_engine = 'mako' def get_context_data(self, **kwargs): context = super(JobListView, self).get_context_data(**kwargs) context['total_job_count'] = Job.objects.all().count() return context def show_job_detail(request): return render_to_response('features/job_board/job_detail.html', {})
from django.views.generic.list import ListView from edxmako.shortcuts import render_to_response from .models import Job class JobListView(ListView): model = Job context_object_name = 'job_list' paginate_by = 10 template_name = 'features/job_board/job_list.html' ordering = ['-created'] template_engine = 'mako' def show_job_detail(request): return render_to_response('features/job_board/job_detail.html', {})
Remove get_context_data override and use the paginator total count instead
Remove get_context_data override and use the paginator total count instead
Python
agpl-3.0
philanthropy-u/edx-platform,philanthropy-u/edx-platform,philanthropy-u/edx-platform,philanthropy-u/edx-platform
from django.views.generic.list import ListView from edxmako.shortcuts import render_to_response from .models import Job class JobListView(ListView): model = Job context_object_name = 'job_list' paginate_by = 10 template_name = 'features/job_board/job_list.html' ordering = ['-created'] template_engine = 'mako' - def get_context_data(self, **kwargs): - context = super(JobListView, self).get_context_data(**kwargs) - context['total_job_count'] = Job.objects.all().count() - return context - def show_job_detail(request): return render_to_response('features/job_board/job_detail.html', {})
Remove get_context_data override and use the paginator total count instead
## Code Before: from django.views.generic.list import ListView from edxmako.shortcuts import render_to_response from .models import Job class JobListView(ListView): model = Job context_object_name = 'job_list' paginate_by = 10 template_name = 'features/job_board/job_list.html' ordering = ['-created'] template_engine = 'mako' def get_context_data(self, **kwargs): context = super(JobListView, self).get_context_data(**kwargs) context['total_job_count'] = Job.objects.all().count() return context def show_job_detail(request): return render_to_response('features/job_board/job_detail.html', {}) ## Instruction: Remove get_context_data override and use the paginator total count instead ## Code After: from django.views.generic.list import ListView from edxmako.shortcuts import render_to_response from .models import Job class JobListView(ListView): model = Job context_object_name = 'job_list' paginate_by = 10 template_name = 'features/job_board/job_list.html' ordering = ['-created'] template_engine = 'mako' def show_job_detail(request): return render_to_response('features/job_board/job_detail.html', {})
# ... existing code ... # ... rest of the code ...
f59adf7887d26c09257b16438a2d920861be3f33
eventtools/tests/_inject_app.py
eventtools/tests/_inject_app.py
from django.test import TestCase from django.conf import settings from django.db.models.loading import load_app from django.core.management import call_command from _fixture import fixture APP_NAME = 'eventtools.tests.eventtools_testapp' class TestCaseWithApp(TestCase): """Make sure to call super(..).setUp and tearDown on subclasses""" def setUp(self): self.__class__.__module__ = self.__class__.__name__ self.old_INSTALLED_APPS = settings.INSTALLED_APPS settings.INSTALLED_APPS += [APP_NAME] self._old_root_urlconf = settings.ROOT_URLCONF settings.ROOT_URLCONF = '%s.urls' % APP_NAME load_app(APP_NAME) call_command('flush', verbosity=0, interactive=False) call_command('syncdb', verbosity=0, interactive=False) self.ae = self.assertEqual fixture(self) def tearDown(self): settings.INSTALLED_APPS = self.old_INSTALLED_APPS settings.ROOT_URLCONF = self._old_root_urlconf
from django.db.models.loading import load_app from django.conf import settings from django.core.management import call_command from django.template.loaders import app_directories from django.template import loader from django.test import TestCase from _fixture import fixture APP_NAME = 'eventtools.tests.eventtools_testapp' class TestCaseWithApp(TestCase): """Make sure to call super(..).setUp and tearDown on subclasses""" def setUp(self): self.__class__.__module__ = self.__class__.__name__ self.old_INSTALLED_APPS = settings.INSTALLED_APPS settings.INSTALLED_APPS += [APP_NAME] self._old_root_urlconf = settings.ROOT_URLCONF settings.ROOT_URLCONF = '%s.urls' % APP_NAME load_app(APP_NAME) call_command('flush', verbosity=0, interactive=False) call_command('syncdb', verbosity=0, interactive=False) self.ae = self.assertEqual self._old_template_loaders = settings.TEMPLATE_LOADERS loaders = list(settings.TEMPLATE_LOADERS) try: loaders.remove('django.template.loaders.filesystem.Loader') settings.TEMPLATE_LOADERS = loaders self._refresh_cache() except ValueError: pass fixture(self) def tearDown(self): settings.INSTALLED_APPS = self.old_INSTALLED_APPS settings.ROOT_URLCONF = self._old_root_urlconf settings.TEMPLATE_LOADERS = self._old_template_loaders self._refresh_cache() def _refresh_cache(self): reload(app_directories) loader.template_source_loaders = None
Disable loading templates from project templates (use only the app ones). Makes all the views tests pass when ran as part of the suite of a larger project like NFSA. (Eventually, eventtools should just use testtools, this functionality is built in there)
Disable loading templates from project templates (use only the app ones). Makes all the views tests pass when ran as part of the suite of a larger project like NFSA. (Eventually, eventtools should just use testtools, this functionality is built in there)
Python
bsd-3-clause
ixc/glamkit-eventtools,ixc/glamkit-eventtools
+ from django.db.models.loading import load_app + from django.conf import settings + from django.core.management import call_command + from django.template.loaders import app_directories + from django.template import loader from django.test import TestCase + - from django.conf import settings - from django.db.models.loading import load_app - from django.core.management import call_command from _fixture import fixture APP_NAME = 'eventtools.tests.eventtools_testapp' class TestCaseWithApp(TestCase): """Make sure to call super(..).setUp and tearDown on subclasses""" def setUp(self): self.__class__.__module__ = self.__class__.__name__ self.old_INSTALLED_APPS = settings.INSTALLED_APPS settings.INSTALLED_APPS += [APP_NAME] self._old_root_urlconf = settings.ROOT_URLCONF settings.ROOT_URLCONF = '%s.urls' % APP_NAME load_app(APP_NAME) call_command('flush', verbosity=0, interactive=False) call_command('syncdb', verbosity=0, interactive=False) self.ae = self.assertEqual + self._old_template_loaders = settings.TEMPLATE_LOADERS + loaders = list(settings.TEMPLATE_LOADERS) + try: + loaders.remove('django.template.loaders.filesystem.Loader') + settings.TEMPLATE_LOADERS = loaders + self._refresh_cache() + except ValueError: + pass fixture(self) def tearDown(self): settings.INSTALLED_APPS = self.old_INSTALLED_APPS settings.ROOT_URLCONF = self._old_root_urlconf + settings.TEMPLATE_LOADERS = self._old_template_loaders + self._refresh_cache() + + def _refresh_cache(self): + reload(app_directories) + loader.template_source_loaders = None
Disable loading templates from project templates (use only the app ones). Makes all the views tests pass when ran as part of the suite of a larger project like NFSA. (Eventually, eventtools should just use testtools, this functionality is built in there)
## Code Before: from django.test import TestCase from django.conf import settings from django.db.models.loading import load_app from django.core.management import call_command from _fixture import fixture APP_NAME = 'eventtools.tests.eventtools_testapp' class TestCaseWithApp(TestCase): """Make sure to call super(..).setUp and tearDown on subclasses""" def setUp(self): self.__class__.__module__ = self.__class__.__name__ self.old_INSTALLED_APPS = settings.INSTALLED_APPS settings.INSTALLED_APPS += [APP_NAME] self._old_root_urlconf = settings.ROOT_URLCONF settings.ROOT_URLCONF = '%s.urls' % APP_NAME load_app(APP_NAME) call_command('flush', verbosity=0, interactive=False) call_command('syncdb', verbosity=0, interactive=False) self.ae = self.assertEqual fixture(self) def tearDown(self): settings.INSTALLED_APPS = self.old_INSTALLED_APPS settings.ROOT_URLCONF = self._old_root_urlconf ## Instruction: Disable loading templates from project templates (use only the app ones). Makes all the views tests pass when ran as part of the suite of a larger project like NFSA. (Eventually, eventtools should just use testtools, this functionality is built in there) ## Code After: from django.db.models.loading import load_app from django.conf import settings from django.core.management import call_command from django.template.loaders import app_directories from django.template import loader from django.test import TestCase from _fixture import fixture APP_NAME = 'eventtools.tests.eventtools_testapp' class TestCaseWithApp(TestCase): """Make sure to call super(..).setUp and tearDown on subclasses""" def setUp(self): self.__class__.__module__ = self.__class__.__name__ self.old_INSTALLED_APPS = settings.INSTALLED_APPS settings.INSTALLED_APPS += [APP_NAME] self._old_root_urlconf = settings.ROOT_URLCONF settings.ROOT_URLCONF = '%s.urls' % APP_NAME load_app(APP_NAME) call_command('flush', verbosity=0, interactive=False) call_command('syncdb', verbosity=0, interactive=False) self.ae = self.assertEqual self._old_template_loaders = settings.TEMPLATE_LOADERS loaders = list(settings.TEMPLATE_LOADERS) try: loaders.remove('django.template.loaders.filesystem.Loader') settings.TEMPLATE_LOADERS = loaders self._refresh_cache() except ValueError: pass fixture(self) def tearDown(self): settings.INSTALLED_APPS = self.old_INSTALLED_APPS settings.ROOT_URLCONF = self._old_root_urlconf settings.TEMPLATE_LOADERS = self._old_template_loaders self._refresh_cache() def _refresh_cache(self): reload(app_directories) loader.template_source_loaders = None
// ... existing code ... from django.db.models.loading import load_app from django.conf import settings from django.core.management import call_command from django.template.loaders import app_directories from django.template import loader from django.test import TestCase from _fixture import fixture // ... modified code ... self.ae = self.assertEqual self._old_template_loaders = settings.TEMPLATE_LOADERS loaders = list(settings.TEMPLATE_LOADERS) try: loaders.remove('django.template.loaders.filesystem.Loader') settings.TEMPLATE_LOADERS = loaders self._refresh_cache() except ValueError: pass fixture(self) ... settings.ROOT_URLCONF = self._old_root_urlconf settings.TEMPLATE_LOADERS = self._old_template_loaders self._refresh_cache() def _refresh_cache(self): reload(app_directories) loader.template_source_loaders = None // ... rest of the code ...
54c4e434276b242de56529e63bb6c5c61d891412
indico/modules/events/surveys/tasks.py
indico/modules/events/surveys/tasks.py
from __future__ import unicode_literals from celery.schedules import crontab from indico.core.celery import celery from indico.core.db import db from indico.modules.events.surveys.models.surveys import Survey @celery.periodic_task(name='survey_start_notifications', run_every=crontab(minute='*/30')) def send_start_notifications(): opened_surveys = Survey.find_all(~Survey.is_deleted, ~Survey.start_notification_sent, Survey.has_started, Survey.notifications_enabled) try: for survey in opened_surveys: survey.send_start_notification() finally: db.session.commit()
from __future__ import unicode_literals from celery.schedules import crontab from indico.core.celery import celery from indico.core.db import db from indico.modules.events.surveys.models.surveys import Survey @celery.periodic_task(name='survey_start_notifications', run_every=crontab(minute='*/30')) def send_start_notifications(): active_surveys = Survey.find_all(Survey.is_active, ~Survey.start_notification_sent, Survey.notifications_enabled) try: for survey in active_surveys: survey.send_start_notification() finally: db.session.commit()
Use safer condition for survey start notification
Use safer condition for survey start notification
Python
mit
mvidalgarcia/indico,ThiefMaster/indico,pferreir/indico,indico/indico,mic4ael/indico,DirkHoffmann/indico,ThiefMaster/indico,indico/indico,ThiefMaster/indico,indico/indico,mic4ael/indico,indico/indico,OmeGak/indico,OmeGak/indico,pferreir/indico,DirkHoffmann/indico,mic4ael/indico,DirkHoffmann/indico,OmeGak/indico,DirkHoffmann/indico,mic4ael/indico,mvidalgarcia/indico,pferreir/indico,ThiefMaster/indico,mvidalgarcia/indico,mvidalgarcia/indico,pferreir/indico,OmeGak/indico
from __future__ import unicode_literals from celery.schedules import crontab from indico.core.celery import celery from indico.core.db import db from indico.modules.events.surveys.models.surveys import Survey @celery.periodic_task(name='survey_start_notifications', run_every=crontab(minute='*/30')) def send_start_notifications(): - opened_surveys = Survey.find_all(~Survey.is_deleted, ~Survey.start_notification_sent, Survey.has_started, + active_surveys = Survey.find_all(Survey.is_active, ~Survey.start_notification_sent, Survey.notifications_enabled) - Survey.notifications_enabled) try: - for survey in opened_surveys: + for survey in active_surveys: survey.send_start_notification() finally: db.session.commit()
Use safer condition for survey start notification
## Code Before: from __future__ import unicode_literals from celery.schedules import crontab from indico.core.celery import celery from indico.core.db import db from indico.modules.events.surveys.models.surveys import Survey @celery.periodic_task(name='survey_start_notifications', run_every=crontab(minute='*/30')) def send_start_notifications(): opened_surveys = Survey.find_all(~Survey.is_deleted, ~Survey.start_notification_sent, Survey.has_started, Survey.notifications_enabled) try: for survey in opened_surveys: survey.send_start_notification() finally: db.session.commit() ## Instruction: Use safer condition for survey start notification ## Code After: from __future__ import unicode_literals from celery.schedules import crontab from indico.core.celery import celery from indico.core.db import db from indico.modules.events.surveys.models.surveys import Survey @celery.periodic_task(name='survey_start_notifications', run_every=crontab(minute='*/30')) def send_start_notifications(): active_surveys = Survey.find_all(Survey.is_active, ~Survey.start_notification_sent, Survey.notifications_enabled) try: for survey in active_surveys: survey.send_start_notification() finally: db.session.commit()
// ... existing code ... def send_start_notifications(): active_surveys = Survey.find_all(Survey.is_active, ~Survey.start_notification_sent, Survey.notifications_enabled) try: for survey in active_surveys: survey.send_start_notification() // ... rest of the code ...
631983a14f941fa745b6e7f4b32fe1ef697d5703
tests/mixers/denontest.py
tests/mixers/denontest.py
import unittest import os from mopidy.mixers.denon import DenonMixer class DenonMixerDeviceMock(object): def __init__(self): self._open = True self.ret_val = bytes('00') def write(self, x): pass def read(self, x): return self.ret_val def isOpen(self): return self._open def open(self): self._open = True class DenonMixerTest(unittest.TestCase): def setUp(self): self.m = DenonMixer() self.m._device = DenonMixerDeviceMock() def test_volume_set_to_min(self): self.m.volume = 0 self.assertEqual(self.m.volume, 0) def test_volume_set_to_max(self): self.m.volume = 100 self.assertEqual(self.m.volume, 99) def test_volume_set_to_below_min_results_in_min(self): self.m.volume = -10 self.assertEqual(self.m.volume, 0) def test_volume_set_to_above_max_results_in_max(self): self.m.volume = 110 self.assertEqual(self.m.volume, 99) def test_reopen_device(self): self.m._device._open = False self.m.volume = 10 self.assertTrue(self.m._device._open)
import unittest import os from mopidy.mixers.denon import DenonMixer class DenonMixerDeviceMock(object): def __init__(self): self._open = True self.ret_val = bytes('MV00\r') def write(self, x): if x[2] != '?': self.ret_val = bytes(x) def read(self, x): return self.ret_val def isOpen(self): return self._open def open(self): self._open = True class DenonMixerTest(unittest.TestCase): def setUp(self): self.m = DenonMixer() self.m._device = DenonMixerDeviceMock() def test_volume_set_to_min(self): self.m.volume = 0 self.assertEqual(self.m.volume, 0) def test_volume_set_to_max(self): self.m.volume = 100 self.assertEqual(self.m.volume, 99) def test_volume_set_to_below_min_results_in_min(self): self.m.volume = -10 self.assertEqual(self.m.volume, 0) def test_volume_set_to_above_max_results_in_max(self): self.m.volume = 110 self.assertEqual(self.m.volume, 99) def test_reopen_device(self): self.m._device._open = False self.m.volume = 10 self.assertTrue(self.m._device._open)
Update denon device mock to reflect mixer changes
Update denon device mock to reflect mixer changes
Python
apache-2.0
mokieyue/mopidy,diandiankan/mopidy,bacontext/mopidy,tkem/mopidy,bacontext/mopidy,priestd09/mopidy,ZenithDK/mopidy,tkem/mopidy,quartz55/mopidy,bencevans/mopidy,vrs01/mopidy,priestd09/mopidy,jodal/mopidy,glogiotatidis/mopidy,ZenithDK/mopidy,rawdlite/mopidy,dbrgn/mopidy,bencevans/mopidy,abarisain/mopidy,jmarsik/mopidy,ali/mopidy,hkariti/mopidy,hkariti/mopidy,swak/mopidy,kingosticks/mopidy,kingosticks/mopidy,SuperStarPL/mopidy,ZenithDK/mopidy,pacificIT/mopidy,vrs01/mopidy,SuperStarPL/mopidy,swak/mopidy,bencevans/mopidy,hkariti/mopidy,jmarsik/mopidy,jcass77/mopidy,diandiankan/mopidy,jmarsik/mopidy,mokieyue/mopidy,vrs01/mopidy,jcass77/mopidy,mokieyue/mopidy,dbrgn/mopidy,tkem/mopidy,ZenithDK/mopidy,pacificIT/mopidy,glogiotatidis/mopidy,adamcik/mopidy,jcass77/mopidy,bacontext/mopidy,woutervanwijk/mopidy,adamcik/mopidy,hkariti/mopidy,rawdlite/mopidy,abarisain/mopidy,mopidy/mopidy,quartz55/mopidy,jodal/mopidy,dbrgn/mopidy,liamw9534/mopidy,tkem/mopidy,mopidy/mopidy,jmarsik/mopidy,kingosticks/mopidy,pacificIT/mopidy,ali/mopidy,vrs01/mopidy,diandiankan/mopidy,SuperStarPL/mopidy,rawdlite/mopidy,mopidy/mopidy,swak/mopidy,diandiankan/mopidy,glogiotatidis/mopidy,woutervanwijk/mopidy,ali/mopidy,priestd09/mopidy,rawdlite/mopidy,quartz55/mopidy,bacontext/mopidy,liamw9534/mopidy,swak/mopidy,mokieyue/mopidy,adamcik/mopidy,quartz55/mopidy,SuperStarPL/mopidy,pacificIT/mopidy,bencevans/mopidy,ali/mopidy,jodal/mopidy,glogiotatidis/mopidy,dbrgn/mopidy
import unittest import os from mopidy.mixers.denon import DenonMixer class DenonMixerDeviceMock(object): def __init__(self): self._open = True - self.ret_val = bytes('00') + self.ret_val = bytes('MV00\r') def write(self, x): - pass + if x[2] != '?': + self.ret_val = bytes(x) def read(self, x): return self.ret_val def isOpen(self): return self._open def open(self): self._open = True class DenonMixerTest(unittest.TestCase): def setUp(self): self.m = DenonMixer() self.m._device = DenonMixerDeviceMock() def test_volume_set_to_min(self): self.m.volume = 0 self.assertEqual(self.m.volume, 0) def test_volume_set_to_max(self): self.m.volume = 100 self.assertEqual(self.m.volume, 99) def test_volume_set_to_below_min_results_in_min(self): self.m.volume = -10 self.assertEqual(self.m.volume, 0) def test_volume_set_to_above_max_results_in_max(self): self.m.volume = 110 self.assertEqual(self.m.volume, 99) def test_reopen_device(self): self.m._device._open = False self.m.volume = 10 self.assertTrue(self.m._device._open)
Update denon device mock to reflect mixer changes
## Code Before: import unittest import os from mopidy.mixers.denon import DenonMixer class DenonMixerDeviceMock(object): def __init__(self): self._open = True self.ret_val = bytes('00') def write(self, x): pass def read(self, x): return self.ret_val def isOpen(self): return self._open def open(self): self._open = True class DenonMixerTest(unittest.TestCase): def setUp(self): self.m = DenonMixer() self.m._device = DenonMixerDeviceMock() def test_volume_set_to_min(self): self.m.volume = 0 self.assertEqual(self.m.volume, 0) def test_volume_set_to_max(self): self.m.volume = 100 self.assertEqual(self.m.volume, 99) def test_volume_set_to_below_min_results_in_min(self): self.m.volume = -10 self.assertEqual(self.m.volume, 0) def test_volume_set_to_above_max_results_in_max(self): self.m.volume = 110 self.assertEqual(self.m.volume, 99) def test_reopen_device(self): self.m._device._open = False self.m.volume = 10 self.assertTrue(self.m._device._open) ## Instruction: Update denon device mock to reflect mixer changes ## Code After: import unittest import os from mopidy.mixers.denon import DenonMixer class DenonMixerDeviceMock(object): def __init__(self): self._open = True self.ret_val = bytes('MV00\r') def write(self, x): if x[2] != '?': self.ret_val = bytes(x) def read(self, x): return self.ret_val def isOpen(self): return self._open def open(self): self._open = True class DenonMixerTest(unittest.TestCase): def setUp(self): self.m = DenonMixer() self.m._device = DenonMixerDeviceMock() def test_volume_set_to_min(self): self.m.volume = 0 self.assertEqual(self.m.volume, 0) def test_volume_set_to_max(self): self.m.volume = 100 self.assertEqual(self.m.volume, 99) def test_volume_set_to_below_min_results_in_min(self): self.m.volume = -10 self.assertEqual(self.m.volume, 0) def test_volume_set_to_above_max_results_in_max(self): self.m.volume = 110 self.assertEqual(self.m.volume, 99) def test_reopen_device(self): self.m._device._open = False self.m.volume = 10 self.assertTrue(self.m._device._open)
... self._open = True self.ret_val = bytes('MV00\r') ... def write(self, x): if x[2] != '?': self.ret_val = bytes(x) def read(self, x): ...
235f8061caa667f7c9bc1f424e14326c22932547
Examples/Infovis/Python/cone_layout.py
Examples/Infovis/Python/cone_layout.py
from vtk import * reader = vtkXMLTreeReader() reader.SetFileName("vtkclasses.xml") reader.Update() print reader.GetOutput() view = vtkGraphLayoutView() view.AddRepresentationFromInputConnection(reader.GetOutputPort()) view.SetVertexLabelArrayName("id") view.SetVertexLabelVisibility(True) view.SetVertexColorArrayName("vertex id") view.SetColorVertices(True) view.SetLayoutStrategyToCone() view.SetInteractionModeTo3D() # Left mouse button causes 3D rotate instead of zoom view.SetLabelPlacementModeToLabelPlacer() theme = vtkViewTheme.CreateMellowTheme() theme.SetCellColor(.2,.2,.6) theme.SetLineWidth(2) theme.SetPointSize(10) view.ApplyViewTheme(theme) theme.FastDelete() window = vtkRenderWindow() window.SetSize(600, 600) view.SetupRenderWindow(window) view.GetRenderer().ResetCamera() window.Render() window.GetInteractor().Start()
from vtk import * reader = vtkXMLTreeReader() reader.SetFileName("vtkclasses.xml") view = vtkGraphLayoutView() view.AddRepresentationFromInputConnection(reader.GetOutputPort()) view.SetVertexLabelArrayName("id") view.SetVertexLabelVisibility(True) view.SetVertexColorArrayName("vertex id") view.SetColorVertices(True) view.SetLayoutStrategyToCone() view.SetInteractionModeTo3D() # Left mouse button causes 3D rotate instead of zoom view.SetLabelPlacementModeToLabelPlacer() theme = vtkViewTheme.CreateMellowTheme() theme.SetCellColor(.2,.2,.6) theme.SetLineWidth(2) theme.SetPointSize(10) view.ApplyViewTheme(theme) theme.FastDelete() window = vtkRenderWindow() window.SetSize(600, 600) view.SetupRenderWindow(window) view.GetRenderer().ResetCamera() window.Render() window.GetInteractor().Start()
Remove errant printout in python cone layout example.
ENH: Remove errant printout in python cone layout example.
Python
bsd-3-clause
daviddoria/PointGraphsPhase1,jmerkow/VTK,mspark93/VTK,hendradarwin/VTK,aashish24/VTK-old,Wuteyan/VTK,jmerkow/VTK,berendkleinhaneveld/VTK,msmolens/VTK,ashray/VTK-EVM,msmolens/VTK,hendradarwin/VTK,sumedhasingla/VTK,ashray/VTK-EVM,johnkit/vtk-dev,sumedhasingla/VTK,SimVascular/VTK,sankhesh/VTK,candy7393/VTK,jmerkow/VTK,spthaolt/VTK,candy7393/VTK,mspark93/VTK,mspark93/VTK,spthaolt/VTK,msmolens/VTK,Wuteyan/VTK,gram526/VTK,jeffbaumes/jeffbaumes-vtk,biddisco/VTK,sumedhasingla/VTK,demarle/VTK,aashish24/VTK-old,gram526/VTK,sankhesh/VTK,candy7393/VTK,cjh1/VTK,keithroe/vtkoptix,ashray/VTK-EVM,keithroe/vtkoptix,naucoin/VTKSlicerWidgets,biddisco/VTK,cjh1/VTK,msmolens/VTK,jeffbaumes/jeffbaumes-vtk,ashray/VTK-EVM,arnaudgelas/VTK,jeffbaumes/jeffbaumes-vtk,spthaolt/VTK,spthaolt/VTK,sankhesh/VTK,candy7393/VTK,keithroe/vtkoptix,spthaolt/VTK,SimVascular/VTK,collects/VTK,sankhesh/VTK,gram526/VTK,ashray/VTK-EVM,sumedhasingla/VTK,demarle/VTK,Wuteyan/VTK,jmerkow/VTK,candy7393/VTK,msmolens/VTK,berendkleinhaneveld/VTK,spthaolt/VTK,biddisco/VTK,SimVascular/VTK,collects/VTK,daviddoria/PointGraphsPhase1,jmerkow/VTK,hendradarwin/VTK,demarle/VTK,msmolens/VTK,biddisco/VTK,SimVascular/VTK,sumedhasingla/VTK,Wuteyan/VTK,johnkit/vtk-dev,msmolens/VTK,sankhesh/VTK,cjh1/VTK,aashish24/VTK-old,naucoin/VTKSlicerWidgets,keithroe/vtkoptix,johnkit/vtk-dev,sankhesh/VTK,jeffbaumes/jeffbaumes-vtk,daviddoria/PointGraphsPhase1,demarle/VTK,berendkleinhaneveld/VTK,cjh1/VTK,demarle/VTK,msmolens/VTK,aashish24/VTK-old,keithroe/vtkoptix,daviddoria/PointGraphsPhase1,biddisco/VTK,berendkleinhaneveld/VTK,naucoin/VTKSlicerWidgets,berendkleinhaneveld/VTK,cjh1/VTK,collects/VTK,johnkit/vtk-dev,naucoin/VTKSlicerWidgets,SimVascular/VTK,SimVascular/VTK,johnkit/vtk-dev,gram526/VTK,Wuteyan/VTK,jeffbaumes/jeffbaumes-vtk,hendradarwin/VTK,ashray/VTK-EVM,candy7393/VTK,jmerkow/VTK,keithroe/vtkoptix,arnaudgelas/VTK,sumedhasingla/VTK,naucoin/VTKSlicerWidgets,arnaudgelas/VTK,daviddoria/PointGraphsPhase1,johnkit/vtk-dev,gram526/VTK,gram526/VTK,jmerkow/VTK,sumedhasingla/VTK,arnaudgelas/VTK,hendradarwin/VTK,spthaolt/VTK,gram526/VTK,cjh1/VTK,biddisco/VTK,collects/VTK,berendkleinhaneveld/VTK,sankhesh/VTK,demarle/VTK,sumedhasingla/VTK,aashish24/VTK-old,aashish24/VTK-old,biddisco/VTK,mspark93/VTK,jeffbaumes/jeffbaumes-vtk,hendradarwin/VTK,mspark93/VTK,candy7393/VTK,candy7393/VTK,jmerkow/VTK,collects/VTK,keithroe/vtkoptix,keithroe/vtkoptix,Wuteyan/VTK,mspark93/VTK,collects/VTK,gram526/VTK,johnkit/vtk-dev,SimVascular/VTK,arnaudgelas/VTK,ashray/VTK-EVM,mspark93/VTK,hendradarwin/VTK,Wuteyan/VTK,mspark93/VTK,berendkleinhaneveld/VTK,SimVascular/VTK,naucoin/VTKSlicerWidgets,demarle/VTK,arnaudgelas/VTK,sankhesh/VTK,demarle/VTK,ashray/VTK-EVM,daviddoria/PointGraphsPhase1
from vtk import * reader = vtkXMLTreeReader() reader.SetFileName("vtkclasses.xml") - reader.Update() - print reader.GetOutput() view = vtkGraphLayoutView() view.AddRepresentationFromInputConnection(reader.GetOutputPort()) view.SetVertexLabelArrayName("id") view.SetVertexLabelVisibility(True) view.SetVertexColorArrayName("vertex id") view.SetColorVertices(True) view.SetLayoutStrategyToCone() view.SetInteractionModeTo3D() # Left mouse button causes 3D rotate instead of zoom view.SetLabelPlacementModeToLabelPlacer() theme = vtkViewTheme.CreateMellowTheme() theme.SetCellColor(.2,.2,.6) theme.SetLineWidth(2) theme.SetPointSize(10) view.ApplyViewTheme(theme) theme.FastDelete() window = vtkRenderWindow() window.SetSize(600, 600) view.SetupRenderWindow(window) view.GetRenderer().ResetCamera() window.Render() window.GetInteractor().Start()
Remove errant printout in python cone layout example.
## Code Before: from vtk import * reader = vtkXMLTreeReader() reader.SetFileName("vtkclasses.xml") reader.Update() print reader.GetOutput() view = vtkGraphLayoutView() view.AddRepresentationFromInputConnection(reader.GetOutputPort()) view.SetVertexLabelArrayName("id") view.SetVertexLabelVisibility(True) view.SetVertexColorArrayName("vertex id") view.SetColorVertices(True) view.SetLayoutStrategyToCone() view.SetInteractionModeTo3D() # Left mouse button causes 3D rotate instead of zoom view.SetLabelPlacementModeToLabelPlacer() theme = vtkViewTheme.CreateMellowTheme() theme.SetCellColor(.2,.2,.6) theme.SetLineWidth(2) theme.SetPointSize(10) view.ApplyViewTheme(theme) theme.FastDelete() window = vtkRenderWindow() window.SetSize(600, 600) view.SetupRenderWindow(window) view.GetRenderer().ResetCamera() window.Render() window.GetInteractor().Start() ## Instruction: Remove errant printout in python cone layout example. ## Code After: from vtk import * reader = vtkXMLTreeReader() reader.SetFileName("vtkclasses.xml") view = vtkGraphLayoutView() view.AddRepresentationFromInputConnection(reader.GetOutputPort()) view.SetVertexLabelArrayName("id") view.SetVertexLabelVisibility(True) view.SetVertexColorArrayName("vertex id") view.SetColorVertices(True) view.SetLayoutStrategyToCone() view.SetInteractionModeTo3D() # Left mouse button causes 3D rotate instead of zoom view.SetLabelPlacementModeToLabelPlacer() theme = vtkViewTheme.CreateMellowTheme() theme.SetCellColor(.2,.2,.6) theme.SetLineWidth(2) theme.SetPointSize(10) view.ApplyViewTheme(theme) theme.FastDelete() window = vtkRenderWindow() window.SetSize(600, 600) view.SetupRenderWindow(window) view.GetRenderer().ResetCamera() window.Render() window.GetInteractor().Start()
... reader.SetFileName("vtkclasses.xml") ...
55d4b7b939fc218d47a920761350aee7bee91eb9
opps/article/views.py
opps/article/views.py
from django.views.generic.detail import DetailView from django.views.generic.list import ListView from opps.article.models import Post class OppsList(ListView): context_object_name = "context" @property def template_name(self): return 'channel/{0}.html'.format(self.kwargs['channel__long_slug']) @property def queryset(self): if not self.kwargs.get('channel__long_slug'): return Post.objects.filter(channel__homepage=True).all() return Post.objects.filter( channel__long_slug=self.kwargs['channel__long_slug']).all() class OppsDetail(DetailView): context_object_name = "context" @property def template_name(self): return 'article/{0}/{1}.html'.format( self.kwargs['channel__long_slug'], self.kwargs['slug']) @property def queryset(self): return Post.objects.filter( channel__long_slug=self.kwargs['channel__long_slug'], slug=self.kwargs['slug']).all()
from django.views.generic.detail import DetailView from django.views.generic.list import ListView from opps.article.models import Post class OppsList(ListView): context_object_name = "context" @property def template_name(self): long_slug = self.kwargs.get('channel__long_slug', 'home') return 'channel/{0}.html'.format(long_slug) @property def queryset(self): if not self.kwargs.get('channel__long_slug'): return Post.objects.filter(channel__homepage=True).all() return Post.objects.filter( channel__long_slug=self.kwargs['channel__long_slug']).all() class OppsDetail(DetailView): context_object_name = "context" @property def template_name(self): return 'article/{0}/{1}.html'.format( self.kwargs['channel__long_slug'], self.kwargs['slug']) @property def queryset(self): return Post.objects.filter( channel__long_slug=self.kwargs['channel__long_slug'], slug=self.kwargs['slug']).all()
Fix template name on entry home page (/) on list page
Fix template name on entry home page (/) on list page
Python
mit
opps/opps,williamroot/opps,williamroot/opps,opps/opps,opps/opps,jeanmask/opps,jeanmask/opps,williamroot/opps,jeanmask/opps,YACOWS/opps,opps/opps,jeanmask/opps,YACOWS/opps,YACOWS/opps,YACOWS/opps,williamroot/opps
from django.views.generic.detail import DetailView from django.views.generic.list import ListView from opps.article.models import Post class OppsList(ListView): context_object_name = "context" @property def template_name(self): + long_slug = self.kwargs.get('channel__long_slug', 'home') - return 'channel/{0}.html'.format(self.kwargs['channel__long_slug']) + return 'channel/{0}.html'.format(long_slug) @property def queryset(self): if not self.kwargs.get('channel__long_slug'): return Post.objects.filter(channel__homepage=True).all() return Post.objects.filter( channel__long_slug=self.kwargs['channel__long_slug']).all() class OppsDetail(DetailView): context_object_name = "context" @property def template_name(self): return 'article/{0}/{1}.html'.format( self.kwargs['channel__long_slug'], self.kwargs['slug']) @property def queryset(self): return Post.objects.filter( channel__long_slug=self.kwargs['channel__long_slug'], slug=self.kwargs['slug']).all()
Fix template name on entry home page (/) on list page
## Code Before: from django.views.generic.detail import DetailView from django.views.generic.list import ListView from opps.article.models import Post class OppsList(ListView): context_object_name = "context" @property def template_name(self): return 'channel/{0}.html'.format(self.kwargs['channel__long_slug']) @property def queryset(self): if not self.kwargs.get('channel__long_slug'): return Post.objects.filter(channel__homepage=True).all() return Post.objects.filter( channel__long_slug=self.kwargs['channel__long_slug']).all() class OppsDetail(DetailView): context_object_name = "context" @property def template_name(self): return 'article/{0}/{1}.html'.format( self.kwargs['channel__long_slug'], self.kwargs['slug']) @property def queryset(self): return Post.objects.filter( channel__long_slug=self.kwargs['channel__long_slug'], slug=self.kwargs['slug']).all() ## Instruction: Fix template name on entry home page (/) on list page ## Code After: from django.views.generic.detail import DetailView from django.views.generic.list import ListView from opps.article.models import Post class OppsList(ListView): context_object_name = "context" @property def template_name(self): long_slug = self.kwargs.get('channel__long_slug', 'home') return 'channel/{0}.html'.format(long_slug) @property def queryset(self): if not self.kwargs.get('channel__long_slug'): return Post.objects.filter(channel__homepage=True).all() return Post.objects.filter( channel__long_slug=self.kwargs['channel__long_slug']).all() class OppsDetail(DetailView): context_object_name = "context" @property def template_name(self): return 'article/{0}/{1}.html'.format( self.kwargs['channel__long_slug'], self.kwargs['slug']) @property def queryset(self): return Post.objects.filter( channel__long_slug=self.kwargs['channel__long_slug'], slug=self.kwargs['slug']).all()
# ... existing code ... def template_name(self): long_slug = self.kwargs.get('channel__long_slug', 'home') return 'channel/{0}.html'.format(long_slug) # ... rest of the code ...
cdefa6cb4a91cbbac5d2680fe2e116a2a4ebb86b
recipe_scrapers/allrecipes.py
recipe_scrapers/allrecipes.py
from ._abstract import AbstractScraper class AllRecipes(AbstractScraper): @classmethod def host(cls): return "allrecipes.com" def author(self): # NB: In the schema.org 'Recipe' type, the 'author' property is a # single-value type, not an ItemList. # allrecipes.com seems to render the author property as a list # containing a single item under some circumstances. # In those cases, the SchemaOrg class will fail due to the unexpected # type, and this method is called as a fallback. # Rather than implement non-standard handling in SchemaOrg, this code # provides a (hopefully temporary!) allrecipes-specific workaround. author = self.schema.data.get("author") if author and type(author) == list and len(author) == 1: return author[0].get("name") def title(self): return self.schema.title() def total_time(self): return self.schema.total_time() def yields(self): return self.schema.yields() def image(self): return self.schema.image() def ingredients(self): return self.schema.ingredients() def instructions(self): return self.schema.instructions() def ratings(self): return self.schema.ratings()
from ._abstract import AbstractScraper class AllRecipes(AbstractScraper): @classmethod def host(cls): return "allrecipes.com" def author(self): # NB: In the schema.org 'Recipe' type, the 'author' property is a # single-value type, not an ItemList. # allrecipes.com seems to render the author property as a list # containing a single item under some circumstances. # In those cases, the SchemaOrg class will fail due to the unexpected # type, and this method is called as a fallback. # Rather than implement non-standard handling in SchemaOrg, this code # provides a (hopefully temporary!) allrecipes-specific workaround. author = self.schema.data.get("author") if author and isinstance(author, list) and len(author) == 1: return author[0].get("name") def title(self): return self.schema.title() def total_time(self): return self.schema.total_time() def yields(self): return self.schema.yields() def image(self): return self.schema.image() def ingredients(self): return self.schema.ingredients() def instructions(self): return self.schema.instructions() def ratings(self): return self.schema.ratings()
Use 'isinstance' in preference to 'type' method
Use 'isinstance' in preference to 'type' method
Python
mit
hhursev/recipe-scraper
from ._abstract import AbstractScraper class AllRecipes(AbstractScraper): @classmethod def host(cls): return "allrecipes.com" def author(self): # NB: In the schema.org 'Recipe' type, the 'author' property is a # single-value type, not an ItemList. # allrecipes.com seems to render the author property as a list # containing a single item under some circumstances. # In those cases, the SchemaOrg class will fail due to the unexpected # type, and this method is called as a fallback. # Rather than implement non-standard handling in SchemaOrg, this code # provides a (hopefully temporary!) allrecipes-specific workaround. author = self.schema.data.get("author") - if author and type(author) == list and len(author) == 1: + if author and isinstance(author, list) and len(author) == 1: return author[0].get("name") def title(self): return self.schema.title() def total_time(self): return self.schema.total_time() def yields(self): return self.schema.yields() def image(self): return self.schema.image() def ingredients(self): return self.schema.ingredients() def instructions(self): return self.schema.instructions() def ratings(self): return self.schema.ratings()
Use 'isinstance' in preference to 'type' method
## Code Before: from ._abstract import AbstractScraper class AllRecipes(AbstractScraper): @classmethod def host(cls): return "allrecipes.com" def author(self): # NB: In the schema.org 'Recipe' type, the 'author' property is a # single-value type, not an ItemList. # allrecipes.com seems to render the author property as a list # containing a single item under some circumstances. # In those cases, the SchemaOrg class will fail due to the unexpected # type, and this method is called as a fallback. # Rather than implement non-standard handling in SchemaOrg, this code # provides a (hopefully temporary!) allrecipes-specific workaround. author = self.schema.data.get("author") if author and type(author) == list and len(author) == 1: return author[0].get("name") def title(self): return self.schema.title() def total_time(self): return self.schema.total_time() def yields(self): return self.schema.yields() def image(self): return self.schema.image() def ingredients(self): return self.schema.ingredients() def instructions(self): return self.schema.instructions() def ratings(self): return self.schema.ratings() ## Instruction: Use 'isinstance' in preference to 'type' method ## Code After: from ._abstract import AbstractScraper class AllRecipes(AbstractScraper): @classmethod def host(cls): return "allrecipes.com" def author(self): # NB: In the schema.org 'Recipe' type, the 'author' property is a # single-value type, not an ItemList. # allrecipes.com seems to render the author property as a list # containing a single item under some circumstances. # In those cases, the SchemaOrg class will fail due to the unexpected # type, and this method is called as a fallback. # Rather than implement non-standard handling in SchemaOrg, this code # provides a (hopefully temporary!) allrecipes-specific workaround. author = self.schema.data.get("author") if author and isinstance(author, list) and len(author) == 1: return author[0].get("name") def title(self): return self.schema.title() def total_time(self): return self.schema.total_time() def yields(self): return self.schema.yields() def image(self): return self.schema.image() def ingredients(self): return self.schema.ingredients() def instructions(self): return self.schema.instructions() def ratings(self): return self.schema.ratings()
// ... existing code ... author = self.schema.data.get("author") if author and isinstance(author, list) and len(author) == 1: return author[0].get("name") // ... rest of the code ...
cf0110f2b1adc8fbf4b8305841961d67da33f8c7
pybo/bayesopt/policies/thompson.py
pybo/bayesopt/policies/thompson.py
# future imports from __future__ import division from __future__ import absolute_import from __future__ import print_function # use this to simplify (slightly) the Thompson implementation with sampled # models. from collections import deque # local imports from ..utils import params # exported symbols __all__ = ['Thompson'] @params('n') def Thompson(model, n=100): """ Implementation of Thompson sampling for continuous models using a finite approximation to the kernel matrix with `n` Fourier components. """ if hasattr(model, '__iter__'): model = deque(model, maxlen=1).pop() return model.sample_fourier(n).get
from __future__ import division from __future__ import absolute_import from __future__ import print_function from collections import deque from ..utils import params __all__ = ['Thompson'] @params('n') def Thompson(model, n=100, rng=None): """ Implementation of Thompson sampling for continuous models using a finite approximation to the kernel matrix with `n` Fourier components. """ if hasattr(model, '__iter__'): model = deque(model, maxlen=1).pop() return model.sample_fourier(n, rng).get
Fix Thompson to pay attention to the RNG.
Fix Thompson to pay attention to the RNG.
Python
bsd-2-clause
mwhoffman/pybo,jhartford/pybo
- # future imports from __future__ import division from __future__ import absolute_import from __future__ import print_function - # use this to simplify (slightly) the Thompson implementation with sampled - # models. from collections import deque - - # local imports from ..utils import params - # exported symbols __all__ = ['Thompson'] @params('n') - def Thompson(model, n=100): + def Thompson(model, n=100, rng=None): """ Implementation of Thompson sampling for continuous models using a finite approximation to the kernel matrix with `n` Fourier components. """ if hasattr(model, '__iter__'): model = deque(model, maxlen=1).pop() - return model.sample_fourier(n).get + return model.sample_fourier(n, rng).get
Fix Thompson to pay attention to the RNG.
## Code Before: # future imports from __future__ import division from __future__ import absolute_import from __future__ import print_function # use this to simplify (slightly) the Thompson implementation with sampled # models. from collections import deque # local imports from ..utils import params # exported symbols __all__ = ['Thompson'] @params('n') def Thompson(model, n=100): """ Implementation of Thompson sampling for continuous models using a finite approximation to the kernel matrix with `n` Fourier components. """ if hasattr(model, '__iter__'): model = deque(model, maxlen=1).pop() return model.sample_fourier(n).get ## Instruction: Fix Thompson to pay attention to the RNG. ## Code After: from __future__ import division from __future__ import absolute_import from __future__ import print_function from collections import deque from ..utils import params __all__ = ['Thompson'] @params('n') def Thompson(model, n=100, rng=None): """ Implementation of Thompson sampling for continuous models using a finite approximation to the kernel matrix with `n` Fourier components. """ if hasattr(model, '__iter__'): model = deque(model, maxlen=1).pop() return model.sample_fourier(n, rng).get
... from __future__ import division ... from collections import deque from ..utils import params ... __all__ = ['Thompson'] ... @params('n') def Thompson(model, n=100, rng=None): """ ... model = deque(model, maxlen=1).pop() return model.sample_fourier(n, rng).get ...
6122a8488613bdd7d5aaf80e7238cd2d80687a91
stock.py
stock.py
class Stock: def __init__(self, symbol): self.symbol = symbol self.price = None def update(self, timestamp, price): if price < 0: raise ValueError("price should not be negative") self.price = price
class Stock: def __init__(self, symbol): self.symbol = symbol self.price_history = [] @property def price(self): if self.price_history: return self.price_history[-1] else: return None def update(self, timestamp, price): if price < 0: raise ValueError("price should not be negative") self.price_history.append(price)
Update price attribute to price_history list as well as update function accordingly.
Update price attribute to price_history list as well as update function accordingly.
Python
mit
bsmukasa/stock_alerter
class Stock: def __init__(self, symbol): self.symbol = symbol - self.price = None + self.price_history = [] + + @property + def price(self): + if self.price_history: + return self.price_history[-1] + else: + return None def update(self, timestamp, price): if price < 0: raise ValueError("price should not be negative") - self.price = price + self.price_history.append(price)
Update price attribute to price_history list as well as update function accordingly.
## Code Before: class Stock: def __init__(self, symbol): self.symbol = symbol self.price = None def update(self, timestamp, price): if price < 0: raise ValueError("price should not be negative") self.price = price ## Instruction: Update price attribute to price_history list as well as update function accordingly. ## Code After: class Stock: def __init__(self, symbol): self.symbol = symbol self.price_history = [] @property def price(self): if self.price_history: return self.price_history[-1] else: return None def update(self, timestamp, price): if price < 0: raise ValueError("price should not be negative") self.price_history.append(price)
// ... existing code ... self.symbol = symbol self.price_history = [] @property def price(self): if self.price_history: return self.price_history[-1] else: return None // ... modified code ... raise ValueError("price should not be negative") self.price_history.append(price) // ... rest of the code ...
be4d21b5486f3bba5a4d844015d3d35630ac7d03
udata/auth/forms.py
udata/auth/forms.py
from __future__ import unicode_literals from flask_security.forms import RegisterForm from udata.forms import fields from udata.forms import validators class ExtendedRegisterForm(RegisterForm): first_name = fields.StringField( 'First Name', [validators.Required('First name is required')]) last_name = fields.StringField( 'Last Name', [validators.Required('Last name is required')])
from __future__ import unicode_literals from flask_security.forms import RegisterForm from udata.forms import fields from udata.forms import validators from udata.i18n import lazy_gettext as _ class ExtendedRegisterForm(RegisterForm): first_name = fields.StringField( _('First name'), [validators.Required(_('First name is required'))]) last_name = fields.StringField( _('Last name'), [validators.Required(_('Last name is required'))])
Apply i18n to First and Last name in registration form
Apply i18n to First and Last name in registration form
Python
agpl-3.0
etalab/udata,etalab/udata,etalab/udata,opendatateam/udata,opendatateam/udata,opendatateam/udata
from __future__ import unicode_literals from flask_security.forms import RegisterForm from udata.forms import fields from udata.forms import validators - + from udata.i18n import lazy_gettext as _ class ExtendedRegisterForm(RegisterForm): first_name = fields.StringField( - 'First Name', [validators.Required('First name is required')]) + _('First name'), [validators.Required(_('First name is required'))]) last_name = fields.StringField( - 'Last Name', [validators.Required('Last name is required')]) + _('Last name'), [validators.Required(_('Last name is required'))])
Apply i18n to First and Last name in registration form
## Code Before: from __future__ import unicode_literals from flask_security.forms import RegisterForm from udata.forms import fields from udata.forms import validators class ExtendedRegisterForm(RegisterForm): first_name = fields.StringField( 'First Name', [validators.Required('First name is required')]) last_name = fields.StringField( 'Last Name', [validators.Required('Last name is required')]) ## Instruction: Apply i18n to First and Last name in registration form ## Code After: from __future__ import unicode_literals from flask_security.forms import RegisterForm from udata.forms import fields from udata.forms import validators from udata.i18n import lazy_gettext as _ class ExtendedRegisterForm(RegisterForm): first_name = fields.StringField( _('First name'), [validators.Required(_('First name is required'))]) last_name = fields.StringField( _('Last name'), [validators.Required(_('Last name is required'))])
# ... existing code ... from udata.forms import validators from udata.i18n import lazy_gettext as _ # ... modified code ... first_name = fields.StringField( _('First name'), [validators.Required(_('First name is required'))]) last_name = fields.StringField( _('Last name'), [validators.Required(_('Last name is required'))]) # ... rest of the code ...
0dac29f30853498f6e9d82c8b791ced5ec21667c
models/00_settings.py
models/00_settings.py
import os import logging import json from logging.config import dictConfig from gluon.storage import Storage from gluon.contrib.appconfig import AppConfig # app_config use to cache values in production app_config = AppConfig(reload=True) # settings is used to avoid cached values in production settings = Storage() # LOGGING CONFIGURATIONS settings.logging_config = dict(main=os.path.join(request.folder, 'logging.json'), scheduler=os.path.join(request.folder, 'logging-scheduler.json')) # INITIALIZE LOGGING if os.path.exists(settings.logging_config['main']): try: config = json.loads(open(settings.logging_config['main']).read()) logging.config.dictConfig(config) except ValueError as e: pass logger = logging.getLogger(settings.app_name) # DATABASE CONFIGURATION # Check whether POSTGRES_ENABLED env var is set to True or not. # If so, generate connection string. if os.environ['POSTGRES_ENABLED'] == 'True': settings.db_uri = 'postgres://{u}:{p}@{h}:{po}/{db}'.format( u=app_config.get('postgres.username'), p=app_config.get('postgres.password'), h=app_config.get('postgres.hostname'), po=app_config.get('postgres.port'), db=app_config.get('postgres.database')) else: settings.db_uri = app_config.get('db.uri')
import os import logging import json from logging.config import dictConfig from gluon.storage import Storage from gluon.contrib.appconfig import AppConfig # app_config use to cache values in production app_config = AppConfig(reload=True) # settings is used to avoid cached values in production settings = Storage() # LOGGING CONFIGURATIONS settings.logging_config = dict(main=os.path.join(request.folder, 'logging.json'), scheduler=os.path.join(request.folder, 'logging-scheduler.json')) # INITIALIZE LOGGING if os.path.exists(settings.logging_config['main']): try: config = json.loads(open(settings.logging_config['main']).read()) logging.config.dictConfig(config) except ValueError as e: pass logger = logging.getLogger(settings.app_name) # DATABASE CONFIGURATION # Check whether POSTGRES_ENABLED env var is set to True or not. # If so, generate connection string. if app_config.has_key('postgres'): settings.db_uri = 'postgres://{u}:{p}@{h}:{po}/{db}'.format( u=app_config.get('postgres.username'), p=app_config.get('postgres.password'), h=app_config.get('postgres.hostname'), po=app_config.get('postgres.port'), db=app_config.get('postgres.database')) else: settings.db_uri = app_config.get('db.uri')
Check configuration file rather than env variable
Check configuration file rather than env variable
Python
apache-2.0
wefner/w2pfooty,wefner/w2pfooty,wefner/w2pfooty
import os import logging import json from logging.config import dictConfig from gluon.storage import Storage from gluon.contrib.appconfig import AppConfig # app_config use to cache values in production app_config = AppConfig(reload=True) # settings is used to avoid cached values in production settings = Storage() # LOGGING CONFIGURATIONS settings.logging_config = dict(main=os.path.join(request.folder, 'logging.json'), scheduler=os.path.join(request.folder, 'logging-scheduler.json')) # INITIALIZE LOGGING if os.path.exists(settings.logging_config['main']): try: config = json.loads(open(settings.logging_config['main']).read()) logging.config.dictConfig(config) except ValueError as e: pass logger = logging.getLogger(settings.app_name) # DATABASE CONFIGURATION # Check whether POSTGRES_ENABLED env var is set to True or not. # If so, generate connection string. - if os.environ['POSTGRES_ENABLED'] == 'True': + if app_config.has_key('postgres'): settings.db_uri = 'postgres://{u}:{p}@{h}:{po}/{db}'.format( u=app_config.get('postgres.username'), p=app_config.get('postgres.password'), h=app_config.get('postgres.hostname'), po=app_config.get('postgres.port'), db=app_config.get('postgres.database')) else: settings.db_uri = app_config.get('db.uri')
Check configuration file rather than env variable
## Code Before: import os import logging import json from logging.config import dictConfig from gluon.storage import Storage from gluon.contrib.appconfig import AppConfig # app_config use to cache values in production app_config = AppConfig(reload=True) # settings is used to avoid cached values in production settings = Storage() # LOGGING CONFIGURATIONS settings.logging_config = dict(main=os.path.join(request.folder, 'logging.json'), scheduler=os.path.join(request.folder, 'logging-scheduler.json')) # INITIALIZE LOGGING if os.path.exists(settings.logging_config['main']): try: config = json.loads(open(settings.logging_config['main']).read()) logging.config.dictConfig(config) except ValueError as e: pass logger = logging.getLogger(settings.app_name) # DATABASE CONFIGURATION # Check whether POSTGRES_ENABLED env var is set to True or not. # If so, generate connection string. if os.environ['POSTGRES_ENABLED'] == 'True': settings.db_uri = 'postgres://{u}:{p}@{h}:{po}/{db}'.format( u=app_config.get('postgres.username'), p=app_config.get('postgres.password'), h=app_config.get('postgres.hostname'), po=app_config.get('postgres.port'), db=app_config.get('postgres.database')) else: settings.db_uri = app_config.get('db.uri') ## Instruction: Check configuration file rather than env variable ## Code After: import os import logging import json from logging.config import dictConfig from gluon.storage import Storage from gluon.contrib.appconfig import AppConfig # app_config use to cache values in production app_config = AppConfig(reload=True) # settings is used to avoid cached values in production settings = Storage() # LOGGING CONFIGURATIONS settings.logging_config = dict(main=os.path.join(request.folder, 'logging.json'), scheduler=os.path.join(request.folder, 'logging-scheduler.json')) # INITIALIZE LOGGING if os.path.exists(settings.logging_config['main']): try: config = json.loads(open(settings.logging_config['main']).read()) logging.config.dictConfig(config) except ValueError as e: pass logger = logging.getLogger(settings.app_name) # DATABASE CONFIGURATION # Check whether POSTGRES_ENABLED env var is set to True or not. # If so, generate connection string. if app_config.has_key('postgres'): settings.db_uri = 'postgres://{u}:{p}@{h}:{po}/{db}'.format( u=app_config.get('postgres.username'), p=app_config.get('postgres.password'), h=app_config.get('postgres.hostname'), po=app_config.get('postgres.port'), db=app_config.get('postgres.database')) else: settings.db_uri = app_config.get('db.uri')
// ... existing code ... # If so, generate connection string. if app_config.has_key('postgres'): settings.db_uri = 'postgres://{u}:{p}@{h}:{po}/{db}'.format( // ... rest of the code ...
f312b856046cb46255971bcd30b8c418d7040455
__openerp__.py
__openerp__.py
{ 'name': 'Human Employee Streamline', 'version': '1.2', 'author': 'XCG Consulting', 'category': 'Human Resources', 'description': """ enchancements to the hr module to streamline its usage """, 'website': 'http://www.openerp-experts.com', 'depends': [ 'base', 'hr', ], 'data': [ 'security/ir.model.access.csv', 'security/record_rules.xml', 'admin_doc.xml', 'hr_employee.xml', ], 'test': [ ], 'installable': True, }
{ 'name': 'Human Employee Streamline', 'version': '1.2', 'author': 'XCG Consulting', 'category': 'Human Resources', 'description': """ enchancements to the hr module to streamline its usage """, 'website': 'http://www.openerp-experts.com', 'depends': [ 'base', 'hr', 'hr_contract', ], 'data': [ 'security/ir.model.access.csv', 'security/record_rules.xml', 'admin_doc.xml', 'hr_employee.xml', ], 'test': [ ], 'installable': True, }
Add dependencies on hr_contract as it should have been done
Add dependencies on hr_contract as it should have been done
Python
agpl-3.0
xcgd/hr_streamline
{ 'name': 'Human Employee Streamline', 'version': '1.2', 'author': 'XCG Consulting', 'category': 'Human Resources', 'description': """ enchancements to the hr module to streamline its usage """, 'website': 'http://www.openerp-experts.com', 'depends': [ 'base', 'hr', + 'hr_contract', ], 'data': [ 'security/ir.model.access.csv', 'security/record_rules.xml', 'admin_doc.xml', 'hr_employee.xml', ], 'test': [ ], 'installable': True, }
Add dependencies on hr_contract as it should have been done
## Code Before: { 'name': 'Human Employee Streamline', 'version': '1.2', 'author': 'XCG Consulting', 'category': 'Human Resources', 'description': """ enchancements to the hr module to streamline its usage """, 'website': 'http://www.openerp-experts.com', 'depends': [ 'base', 'hr', ], 'data': [ 'security/ir.model.access.csv', 'security/record_rules.xml', 'admin_doc.xml', 'hr_employee.xml', ], 'test': [ ], 'installable': True, } ## Instruction: Add dependencies on hr_contract as it should have been done ## Code After: { 'name': 'Human Employee Streamline', 'version': '1.2', 'author': 'XCG Consulting', 'category': 'Human Resources', 'description': """ enchancements to the hr module to streamline its usage """, 'website': 'http://www.openerp-experts.com', 'depends': [ 'base', 'hr', 'hr_contract', ], 'data': [ 'security/ir.model.access.csv', 'security/record_rules.xml', 'admin_doc.xml', 'hr_employee.xml', ], 'test': [ ], 'installable': True, }
# ... existing code ... 'hr', 'hr_contract', ], # ... rest of the code ...
c9da64ac1c90abdee8fc72488a4bef58a95aa7c6
biwako/bin/fields/compounds.py
biwako/bin/fields/compounds.py
import io from .base import Field, DynamicValue, FullyDecoded class SubStructure(Field): def __init__(self, structure, *args, **kwargs): self.structure = structure super(SubStructure, self).__init__(*args, **kwargs) def read(self, file): value = self.structure(file) value_bytes = b'' # Force the evaluation of the entire structure in # order to make sure other fields work properly for field in self.structure._fields: getattr(value, field.name) value_bytes += value._raw_values[field.name] raise FullyDecoded(value_bytes, value) def encode(self, obj, value): output = io.BytesIO() value.save(output) return output.getvalue() class List(Field): def __init__(self, field, *args, **kwargs): super(List, self).__init__(*args, **kwargs) self.field = field def read(self, file): value_bytes = b'' values = [] if self.instance: instance_field = field.for_instance(self.instance) for i in range(self.size): bytes, value = instance_field.read_value(file) value_bytes += bytes values.append(value) return values def encode(self, obj, values): encoded_values = [] for value in values: encoded_values.append(self.field.encode(obj, value)) return b''.join(encoded_values)
import io from .base import Field, DynamicValue, FullyDecoded class SubStructure(Field): def __init__(self, structure, *args, **kwargs): self.structure = structure super(SubStructure, self).__init__(*args, **kwargs) def read(self, file): value = self.structure(file) value_bytes = b'' # Force the evaluation of the entire structure in # order to make sure other fields work properly for field in self.structure._fields: getattr(value, field.name) value_bytes += value._raw_values[field.name] raise FullyDecoded(value_bytes, value) def encode(self, obj, value): output = io.BytesIO() value.save(output) return output.getvalue() class List(Field): def __init__(self, field, *args, **kwargs): super(List, self).__init__(*args, **kwargs) self.field = field def read(self, file): value_bytes = b'' values = [] if self.instance: instance_field = self.field.for_instance(self.instance) for i in range(self.size): bytes, value = instance_field.read_value(file) value_bytes += bytes values.append(value) raise FullyDecoded(value_bytes, values) def encode(self, obj, values): encoded_values = [] for value in values: encoded_values.append(self.field.encode(obj, value)) return b''.join(encoded_values)
Fix List to use the new decoding system
Fix List to use the new decoding system
Python
bsd-3-clause
gulopine/steel
import io from .base import Field, DynamicValue, FullyDecoded class SubStructure(Field): def __init__(self, structure, *args, **kwargs): self.structure = structure super(SubStructure, self).__init__(*args, **kwargs) def read(self, file): value = self.structure(file) value_bytes = b'' # Force the evaluation of the entire structure in # order to make sure other fields work properly for field in self.structure._fields: getattr(value, field.name) value_bytes += value._raw_values[field.name] raise FullyDecoded(value_bytes, value) def encode(self, obj, value): output = io.BytesIO() value.save(output) return output.getvalue() class List(Field): def __init__(self, field, *args, **kwargs): super(List, self).__init__(*args, **kwargs) self.field = field def read(self, file): value_bytes = b'' values = [] if self.instance: - instance_field = field.for_instance(self.instance) + instance_field = self.field.for_instance(self.instance) for i in range(self.size): bytes, value = instance_field.read_value(file) value_bytes += bytes values.append(value) - return values + raise FullyDecoded(value_bytes, values) def encode(self, obj, values): encoded_values = [] for value in values: encoded_values.append(self.field.encode(obj, value)) return b''.join(encoded_values)
Fix List to use the new decoding system
## Code Before: import io from .base import Field, DynamicValue, FullyDecoded class SubStructure(Field): def __init__(self, structure, *args, **kwargs): self.structure = structure super(SubStructure, self).__init__(*args, **kwargs) def read(self, file): value = self.structure(file) value_bytes = b'' # Force the evaluation of the entire structure in # order to make sure other fields work properly for field in self.structure._fields: getattr(value, field.name) value_bytes += value._raw_values[field.name] raise FullyDecoded(value_bytes, value) def encode(self, obj, value): output = io.BytesIO() value.save(output) return output.getvalue() class List(Field): def __init__(self, field, *args, **kwargs): super(List, self).__init__(*args, **kwargs) self.field = field def read(self, file): value_bytes = b'' values = [] if self.instance: instance_field = field.for_instance(self.instance) for i in range(self.size): bytes, value = instance_field.read_value(file) value_bytes += bytes values.append(value) return values def encode(self, obj, values): encoded_values = [] for value in values: encoded_values.append(self.field.encode(obj, value)) return b''.join(encoded_values) ## Instruction: Fix List to use the new decoding system ## Code After: import io from .base import Field, DynamicValue, FullyDecoded class SubStructure(Field): def __init__(self, structure, *args, **kwargs): self.structure = structure super(SubStructure, self).__init__(*args, **kwargs) def read(self, file): value = self.structure(file) value_bytes = b'' # Force the evaluation of the entire structure in # order to make sure other fields work properly for field in self.structure._fields: getattr(value, field.name) value_bytes += value._raw_values[field.name] raise FullyDecoded(value_bytes, value) def encode(self, obj, value): output = io.BytesIO() value.save(output) return output.getvalue() class List(Field): def __init__(self, field, *args, **kwargs): super(List, self).__init__(*args, **kwargs) self.field = field def read(self, file): value_bytes = b'' values = [] if self.instance: instance_field = self.field.for_instance(self.instance) for i in range(self.size): bytes, value = instance_field.read_value(file) value_bytes += bytes values.append(value) raise FullyDecoded(value_bytes, values) def encode(self, obj, values): encoded_values = [] for value in values: encoded_values.append(self.field.encode(obj, value)) return b''.join(encoded_values)
// ... existing code ... if self.instance: instance_field = self.field.for_instance(self.instance) // ... modified code ... values.append(value) raise FullyDecoded(value_bytes, values) // ... rest of the code ...
24a0fcbaea3bca88278f294f41e4b6abd1e82cf3
src/rocommand/__init__.py
src/rocommand/__init__.py
__version__ = "0.2.6" # Enhacements to handling of directories and external references
__version__ = "0.2.7" # Decouple MINIM constraints from target RO # ROSRS (v6) support, support evaluation of RODL/ROSRS objects # new annotation and linking options, annotations with CURIE (QName) properties # add ro remove command, fix URI escaping problems
Add comments summarizing changes in this version
Add comments summarizing changes in this version
Python
mit
wf4ever/ro-manager,wf4ever/ro-manager,wf4ever/ro-manager,wf4ever/ro-manager
- __version__ = "0.2.6" # Enhacements to handling of directories and external references + __version__ = "0.2.7" # Decouple MINIM constraints from target RO + # ROSRS (v6) support, support evaluation of RODL/ROSRS objects + # new annotation and linking options, annotations with CURIE (QName) properties + # add ro remove command, fix URI escaping problems +
Add comments summarizing changes in this version
## Code Before: __version__ = "0.2.6" # Enhacements to handling of directories and external references ## Instruction: Add comments summarizing changes in this version ## Code After: __version__ = "0.2.7" # Decouple MINIM constraints from target RO # ROSRS (v6) support, support evaluation of RODL/ROSRS objects # new annotation and linking options, annotations with CURIE (QName) properties # add ro remove command, fix URI escaping problems
... __version__ = "0.2.7" # Decouple MINIM constraints from target RO # ROSRS (v6) support, support evaluation of RODL/ROSRS objects # new annotation and linking options, annotations with CURIE (QName) properties # add ro remove command, fix URI escaping problems ...
88e5ecad9966057203a9cbecaeaecdca3e76b6da
tests/fake_filesystem.py
tests/fake_filesystem.py
import os import stat from StringIO import StringIO from types import StringTypes import paramiko as ssh class FakeFile(StringIO): def __init__(self, value=None, path=None): init = lambda x: StringIO.__init__(self, x) if value is None: init("") ftype = 'dir' size = 4096 else: init(value) ftype = 'file' size = len(value) attr = ssh.SFTPAttributes() attr.st_mode = {'file': stat.S_IFREG, 'dir': stat.S_IFDIR}[ftype] attr.st_size = size attr.filename = os.path.basename(path) self.attributes = attr def __str__(self): return self.getvalue() def write(self, value): StringIO.write(self, value) self.attributes.st_size = len(self.getvalue()) class FakeFilesystem(dict): def __init__(self, d=None): # Replicate input dictionary using our custom __setitem__ d = d or {} for key, value in d.iteritems(): self[key] = value def __setitem__(self, key, value): if isinstance(value, StringTypes) or value is None: value = FakeFile(value, key) super(FakeFilesystem, self).__setitem__(key, value)
import os import stat from StringIO import StringIO from types import StringTypes import paramiko as ssh class FakeFile(StringIO): def __init__(self, value=None, path=None): init = lambda x: StringIO.__init__(self, x) if value is None: init("") ftype = 'dir' size = 4096 else: init(value) ftype = 'file' size = len(value) attr = ssh.SFTPAttributes() attr.st_mode = {'file': stat.S_IFREG, 'dir': stat.S_IFDIR}[ftype] attr.st_size = size attr.filename = os.path.basename(path) self.attributes = attr def __str__(self): return self.getvalue() def write(self, value): StringIO.write(self, value) self.attributes.st_size = len(self.getvalue()) def close(self): """ Always hold fake files open. """ pass class FakeFilesystem(dict): def __init__(self, d=None): # Replicate input dictionary using our custom __setitem__ d = d or {} for key, value in d.iteritems(): self[key] = value def __setitem__(self, key, value): if isinstance(value, StringTypes) or value is None: value = FakeFile(value, key) super(FakeFilesystem, self).__setitem__(key, value)
Define noop close() for FakeFile
Define noop close() for FakeFile
Python
bsd-2-clause
kxxoling/fabric,rodrigc/fabric,qinrong/fabric,elijah513/fabric,bspink/fabric,MjAbuz/fabric,cmattoon/fabric,hrubi/fabric,felix-d/fabric,askulkarni2/fabric,SamuelMarks/fabric,mathiasertl/fabric,tekapo/fabric,StackStorm/fabric,ploxiln/fabric,kmonsoor/fabric,raimon49/fabric,haridsv/fabric,bitprophet/fabric,fernandezcuesta/fabric,itoed/fabric,rane-hs/fabric-py3,sdelements/fabric,likesxuqiang/fabric,bitmonk/fabric,getsentry/fabric,opavader/fabric,jaraco/fabric,xLegoz/fabric,TarasRudnyk/fabric,pgroudas/fabric,akaariai/fabric,rbramwell/fabric,amaniak/fabric,cgvarela/fabric,tolbkni/fabric,pashinin/fabric
import os import stat from StringIO import StringIO from types import StringTypes import paramiko as ssh class FakeFile(StringIO): def __init__(self, value=None, path=None): init = lambda x: StringIO.__init__(self, x) if value is None: init("") ftype = 'dir' size = 4096 else: init(value) ftype = 'file' size = len(value) attr = ssh.SFTPAttributes() attr.st_mode = {'file': stat.S_IFREG, 'dir': stat.S_IFDIR}[ftype] attr.st_size = size attr.filename = os.path.basename(path) self.attributes = attr def __str__(self): return self.getvalue() def write(self, value): StringIO.write(self, value) self.attributes.st_size = len(self.getvalue()) + def close(self): + """ + Always hold fake files open. + """ + pass + class FakeFilesystem(dict): def __init__(self, d=None): # Replicate input dictionary using our custom __setitem__ d = d or {} for key, value in d.iteritems(): self[key] = value def __setitem__(self, key, value): if isinstance(value, StringTypes) or value is None: value = FakeFile(value, key) super(FakeFilesystem, self).__setitem__(key, value)
Define noop close() for FakeFile
## Code Before: import os import stat from StringIO import StringIO from types import StringTypes import paramiko as ssh class FakeFile(StringIO): def __init__(self, value=None, path=None): init = lambda x: StringIO.__init__(self, x) if value is None: init("") ftype = 'dir' size = 4096 else: init(value) ftype = 'file' size = len(value) attr = ssh.SFTPAttributes() attr.st_mode = {'file': stat.S_IFREG, 'dir': stat.S_IFDIR}[ftype] attr.st_size = size attr.filename = os.path.basename(path) self.attributes = attr def __str__(self): return self.getvalue() def write(self, value): StringIO.write(self, value) self.attributes.st_size = len(self.getvalue()) class FakeFilesystem(dict): def __init__(self, d=None): # Replicate input dictionary using our custom __setitem__ d = d or {} for key, value in d.iteritems(): self[key] = value def __setitem__(self, key, value): if isinstance(value, StringTypes) or value is None: value = FakeFile(value, key) super(FakeFilesystem, self).__setitem__(key, value) ## Instruction: Define noop close() for FakeFile ## Code After: import os import stat from StringIO import StringIO from types import StringTypes import paramiko as ssh class FakeFile(StringIO): def __init__(self, value=None, path=None): init = lambda x: StringIO.__init__(self, x) if value is None: init("") ftype = 'dir' size = 4096 else: init(value) ftype = 'file' size = len(value) attr = ssh.SFTPAttributes() attr.st_mode = {'file': stat.S_IFREG, 'dir': stat.S_IFDIR}[ftype] attr.st_size = size attr.filename = os.path.basename(path) self.attributes = attr def __str__(self): return self.getvalue() def write(self, value): StringIO.write(self, value) self.attributes.st_size = len(self.getvalue()) def close(self): """ Always hold fake files open. """ pass class FakeFilesystem(dict): def __init__(self, d=None): # Replicate input dictionary using our custom __setitem__ d = d or {} for key, value in d.iteritems(): self[key] = value def __setitem__(self, key, value): if isinstance(value, StringTypes) or value is None: value = FakeFile(value, key) super(FakeFilesystem, self).__setitem__(key, value)
// ... existing code ... def close(self): """ Always hold fake files open. """ pass // ... rest of the code ...
475ff9a1b1eed0cd5f1b20f0a42926b735a4c163
txircd/modules/extra/conn_umodes.py
txircd/modules/extra/conn_umodes.py
from twisted.plugin import IPlugin from txircd.module_interface import IModuleData, ModuleData from txircd.utils import ModeType from zope.interface import implements class AutoUserModes(ModuleData): implements(IPlugin, IModuleData) name = "AutoUserModes" def actions(self): return [ ("welcome", 50, self.autoSetUserModes) ] def autoSetUserModes(self, user): try: modes = self.ircd.config["client_umodes_on_connect"] params = modes.split() modes = params.pop(0) parsedModes = [] for mode in modes: if mode not in self.ircd.userModeTypes: continue modeType = self.ircd.userModeTypes[mode] if modeType in (ModeType.List, ModeType.ParamOnUnset, ModeType.Param): parsedModes.append((True, mode, params.pop(0))) else: parsedModes.append((True, mode, None)) user.setModes(parsedModes, self.ircd.serverID) except KeyError: pass # No umodes defined. No action required. autoUserModes = AutoUserModes()
from twisted.plugin import IPlugin from txircd.module_interface import IModuleData, ModuleData from txircd.utils import ModeType from zope.interface import implements class AutoUserModes(ModuleData): implements(IPlugin, IModuleData) name = "AutoUserModes" def actions(self): return [ ("welcome", 50, self.autoSetUserModes) ] def autoSetUserModes(self, user): try: modes = self.ircd.config["client_umodes_on_connect"] params = modes.split() modes = params.pop(0) parsedModes = [] for mode in modes: if mode not in self.ircd.userModeTypes: continue modeType = self.ircd.userModeTypes[mode] if modeType != ModeType.NoParam: parsedModes.append((True, mode, params.pop(0))) else: parsedModes.append((True, mode, None)) user.setModes(parsedModes, self.ircd.serverID) except KeyError: pass # No umodes defined. No action required. autoUserModes = AutoUserModes()
Simplify the AutoUserModes mode type check
Simplify the AutoUserModes mode type check
Python
bsd-3-clause
ElementalAlchemist/txircd,Heufneutje/txircd
from twisted.plugin import IPlugin from txircd.module_interface import IModuleData, ModuleData from txircd.utils import ModeType from zope.interface import implements class AutoUserModes(ModuleData): implements(IPlugin, IModuleData) name = "AutoUserModes" def actions(self): return [ ("welcome", 50, self.autoSetUserModes) ] def autoSetUserModes(self, user): try: modes = self.ircd.config["client_umodes_on_connect"] params = modes.split() modes = params.pop(0) parsedModes = [] for mode in modes: if mode not in self.ircd.userModeTypes: continue modeType = self.ircd.userModeTypes[mode] - if modeType in (ModeType.List, ModeType.ParamOnUnset, ModeType.Param): + if modeType != ModeType.NoParam: parsedModes.append((True, mode, params.pop(0))) else: parsedModes.append((True, mode, None)) user.setModes(parsedModes, self.ircd.serverID) except KeyError: pass # No umodes defined. No action required. autoUserModes = AutoUserModes()
Simplify the AutoUserModes mode type check
## Code Before: from twisted.plugin import IPlugin from txircd.module_interface import IModuleData, ModuleData from txircd.utils import ModeType from zope.interface import implements class AutoUserModes(ModuleData): implements(IPlugin, IModuleData) name = "AutoUserModes" def actions(self): return [ ("welcome", 50, self.autoSetUserModes) ] def autoSetUserModes(self, user): try: modes = self.ircd.config["client_umodes_on_connect"] params = modes.split() modes = params.pop(0) parsedModes = [] for mode in modes: if mode not in self.ircd.userModeTypes: continue modeType = self.ircd.userModeTypes[mode] if modeType in (ModeType.List, ModeType.ParamOnUnset, ModeType.Param): parsedModes.append((True, mode, params.pop(0))) else: parsedModes.append((True, mode, None)) user.setModes(parsedModes, self.ircd.serverID) except KeyError: pass # No umodes defined. No action required. autoUserModes = AutoUserModes() ## Instruction: Simplify the AutoUserModes mode type check ## Code After: from twisted.plugin import IPlugin from txircd.module_interface import IModuleData, ModuleData from txircd.utils import ModeType from zope.interface import implements class AutoUserModes(ModuleData): implements(IPlugin, IModuleData) name = "AutoUserModes" def actions(self): return [ ("welcome", 50, self.autoSetUserModes) ] def autoSetUserModes(self, user): try: modes = self.ircd.config["client_umodes_on_connect"] params = modes.split() modes = params.pop(0) parsedModes = [] for mode in modes: if mode not in self.ircd.userModeTypes: continue modeType = self.ircd.userModeTypes[mode] if modeType != ModeType.NoParam: parsedModes.append((True, mode, params.pop(0))) else: parsedModes.append((True, mode, None)) user.setModes(parsedModes, self.ircd.serverID) except KeyError: pass # No umodes defined. No action required. autoUserModes = AutoUserModes()
# ... existing code ... modeType = self.ircd.userModeTypes[mode] if modeType != ModeType.NoParam: parsedModes.append((True, mode, params.pop(0))) # ... rest of the code ...
4c949cd171d50211ec8ebb95be423293ccb6f917
blog/admin.py
blog/admin.py
from django.contrib import admin from .models import Post @admin.register(Post) class PostAdmin(admin.ModelAdmin): # list view date_hierarchy = 'pub_date' list_display = ( 'title', 'pub_date', 'tag_count') list_filter = ('pub_date',) search_fields = ('title', 'text') # form view fieldsets = ( (None, { 'fields': ( 'title', 'slug', 'author', 'text', )}), ('Related', { 'fields': ( 'tags', 'startups')}), ) filter_horizontal = ('tags', 'startups',) prepopulated_fields = {"slug": ("title",)} def tag_count(self, post): return post.tags.count() tag_count.short_description = 'Number of Tags'
from django.contrib import admin from django.db.models import Count from .models import Post @admin.register(Post) class PostAdmin(admin.ModelAdmin): # list view date_hierarchy = 'pub_date' list_display = ( 'title', 'pub_date', 'tag_count') list_filter = ('pub_date',) search_fields = ('title', 'text') # form view fieldsets = ( (None, { 'fields': ( 'title', 'slug', 'author', 'text', )}), ('Related', { 'fields': ( 'tags', 'startups')}), ) filter_horizontal = ('tags', 'startups',) prepopulated_fields = {"slug": ("title",)} def get_queryset(self, request): queryset = super().get_queryset(request) return queryset.annotate( tag_number=Count('tags')) def tag_count(self, post): return post.tag_number tag_count.short_description = 'Number of Tags' tag_count.admin_order_field = 'tag_number'
Enable sorting of number of Post tags.
Ch23: Enable sorting of number of Post tags.
Python
bsd-2-clause
jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8
from django.contrib import admin + from django.db.models import Count from .models import Post @admin.register(Post) class PostAdmin(admin.ModelAdmin): # list view date_hierarchy = 'pub_date' list_display = ( 'title', 'pub_date', 'tag_count') list_filter = ('pub_date',) search_fields = ('title', 'text') # form view fieldsets = ( (None, { 'fields': ( 'title', 'slug', 'author', 'text', )}), ('Related', { 'fields': ( 'tags', 'startups')}), ) filter_horizontal = ('tags', 'startups',) prepopulated_fields = {"slug": ("title",)} + def get_queryset(self, request): + queryset = super().get_queryset(request) + return queryset.annotate( + tag_number=Count('tags')) + def tag_count(self, post): - return post.tags.count() + return post.tag_number tag_count.short_description = 'Number of Tags' + tag_count.admin_order_field = 'tag_number'
Enable sorting of number of Post tags.
## Code Before: from django.contrib import admin from .models import Post @admin.register(Post) class PostAdmin(admin.ModelAdmin): # list view date_hierarchy = 'pub_date' list_display = ( 'title', 'pub_date', 'tag_count') list_filter = ('pub_date',) search_fields = ('title', 'text') # form view fieldsets = ( (None, { 'fields': ( 'title', 'slug', 'author', 'text', )}), ('Related', { 'fields': ( 'tags', 'startups')}), ) filter_horizontal = ('tags', 'startups',) prepopulated_fields = {"slug": ("title",)} def tag_count(self, post): return post.tags.count() tag_count.short_description = 'Number of Tags' ## Instruction: Enable sorting of number of Post tags. ## Code After: from django.contrib import admin from django.db.models import Count from .models import Post @admin.register(Post) class PostAdmin(admin.ModelAdmin): # list view date_hierarchy = 'pub_date' list_display = ( 'title', 'pub_date', 'tag_count') list_filter = ('pub_date',) search_fields = ('title', 'text') # form view fieldsets = ( (None, { 'fields': ( 'title', 'slug', 'author', 'text', )}), ('Related', { 'fields': ( 'tags', 'startups')}), ) filter_horizontal = ('tags', 'startups',) prepopulated_fields = {"slug": ("title",)} def get_queryset(self, request): queryset = super().get_queryset(request) return queryset.annotate( tag_number=Count('tags')) def tag_count(self, post): return post.tag_number tag_count.short_description = 'Number of Tags' tag_count.admin_order_field = 'tag_number'
// ... existing code ... from django.contrib import admin from django.db.models import Count // ... modified code ... def get_queryset(self, request): queryset = super().get_queryset(request) return queryset.annotate( tag_number=Count('tags')) def tag_count(self, post): return post.tag_number tag_count.short_description = 'Number of Tags' tag_count.admin_order_field = 'tag_number' // ... rest of the code ...
de4f43613b5f3a8b6f49ace6b8e9585a242d7cb2
src/build.py
src/build.py
import sys import csnGUIHandler import csnGUIOptions import csnGenerator # Check command line arguments if len(sys.argv) != 3: sys.exit("Error: not enough arguments. You need to provide an option and a configuration file.") # Command line inputs options_file = sys.argv[1] config_file = sys.argv[2] # Create GUI handler handler = csnGUIHandler.Handler() # Read options options = csnGUIOptions.Options() options.Load( options_file ) # Read settings settings = csnGenerator.Settings() settings.Load( config_file ) # Set the options handler.SetOptions( options ) # Configure the project with the settings if settings.instance == "thirdParty": res = handler.ConfigureThirdPartyFolder(settings) else: res = handler.ConfigureProjectToBinFolder( settings, 1 ) sys.exit(res)
import sys import csnGUIHandler import csnGUIOptions import csnGenerator # Check command line arguments if len(sys.argv) != 3: sys.exit("Error: not enough arguments. You need to provide an option and a configuration file.") # Command line inputs options_file = sys.argv[1] config_file = sys.argv[2] # Create GUI handler handler = csnGUIHandler.Handler() # Read options options = csnGUIOptions.Options() options.Load( options_file ) # Read settings settings = csnGenerator.Settings() settings.Load( config_file ) # Set the options handler.SetOptions( options ) # Configure the project with the settings if settings.instance == "thirdParty": res = handler.ConfigureThirdPartyFolder(settings) else: res = handler.ConfigureProjectToBinFolder( settings, 1 ) # exit with error if there was a problem if res == false: sys.exit(1)
Exit with the proper value.
Exit with the proper value. git-svn-id: a26c1b3dc012bc7b166f1b96505d8277332098eb@265 9ffc3505-93cb-cd4b-9e5d-8a77f6415fcf
Python
bsd-3-clause
csnake-org/CSnake,csnake-org/CSnake,msteghofer/CSnake,msteghofer/CSnake,csnake-org/CSnake,msteghofer/CSnake
import sys import csnGUIHandler import csnGUIOptions import csnGenerator # Check command line arguments if len(sys.argv) != 3: sys.exit("Error: not enough arguments. You need to provide an option and a configuration file.") # Command line inputs options_file = sys.argv[1] config_file = sys.argv[2] # Create GUI handler handler = csnGUIHandler.Handler() # Read options options = csnGUIOptions.Options() options.Load( options_file ) # Read settings settings = csnGenerator.Settings() settings.Load( config_file ) # Set the options handler.SetOptions( options ) # Configure the project with the settings if settings.instance == "thirdParty": res = handler.ConfigureThirdPartyFolder(settings) else: res = handler.ConfigureProjectToBinFolder( settings, 1 ) + # exit with error if there was a problem + if res == false: - sys.exit(res) + sys.exit(1)
Exit with the proper value.
## Code Before: import sys import csnGUIHandler import csnGUIOptions import csnGenerator # Check command line arguments if len(sys.argv) != 3: sys.exit("Error: not enough arguments. You need to provide an option and a configuration file.") # Command line inputs options_file = sys.argv[1] config_file = sys.argv[2] # Create GUI handler handler = csnGUIHandler.Handler() # Read options options = csnGUIOptions.Options() options.Load( options_file ) # Read settings settings = csnGenerator.Settings() settings.Load( config_file ) # Set the options handler.SetOptions( options ) # Configure the project with the settings if settings.instance == "thirdParty": res = handler.ConfigureThirdPartyFolder(settings) else: res = handler.ConfigureProjectToBinFolder( settings, 1 ) sys.exit(res) ## Instruction: Exit with the proper value. ## Code After: import sys import csnGUIHandler import csnGUIOptions import csnGenerator # Check command line arguments if len(sys.argv) != 3: sys.exit("Error: not enough arguments. You need to provide an option and a configuration file.") # Command line inputs options_file = sys.argv[1] config_file = sys.argv[2] # Create GUI handler handler = csnGUIHandler.Handler() # Read options options = csnGUIOptions.Options() options.Load( options_file ) # Read settings settings = csnGenerator.Settings() settings.Load( config_file ) # Set the options handler.SetOptions( options ) # Configure the project with the settings if settings.instance == "thirdParty": res = handler.ConfigureThirdPartyFolder(settings) else: res = handler.ConfigureProjectToBinFolder( settings, 1 ) # exit with error if there was a problem if res == false: sys.exit(1)
# ... existing code ... res = handler.ConfigureProjectToBinFolder( settings, 1 ) # exit with error if there was a problem if res == false: sys.exit(1) # ... rest of the code ...
33fd4bba1f2c44e871051862db8071fadb0e9825
core-plugins/shared/1/dss/reporting-plugins/shared_create_metaproject/shared_create_metaproject.py
core-plugins/shared/1/dss/reporting-plugins/shared_create_metaproject/shared_create_metaproject.py
def process(transaction, parameters, tableBuilder): """Create a project with user-defined name in given space. """ # Prepare the return table tableBuilder.addHeader("success") tableBuilder.addHeader("message") # Add a row for the results row = tableBuilder.addRow() # Retrieve parameters from client metaprojectCode = parameters.get("metaprojectCode") username = parameters.get("userName") # Try retrieving the metaproject (tag) metaproject = transaction.getMetaproject(metaprojectCode, username) if metaproject is None: # Create the metaproject (tag) metaproject = transaction.createNewMetaproject(metaprojectCode, "Test", username) # Check that creation was succcessful if metaproject is None: success = "false" message = "Could not create metaproject " + metaprojectCode + "." else: success = "true" message = "Tag " + metaprojectCode + " successfully created." else: success = "false" message = "Tag " + metaprojectCode + " exists already." # Add the results to current row row.setCell("success", success) row.setCell("message", message)
def process(transaction, parameters, tableBuilder): """Create a project with user-defined name in given space. """ # Prepare the return table tableBuilder.addHeader("success") tableBuilder.addHeader("message") # Add a row for the results row = tableBuilder.addRow() # Retrieve parameters from client username = parameters.get("userName") metaprojectCode = parameters.get("metaprojectCode") metaprojectDescr = parameters.get("metaprojectDescr") if metaprojectDescr is None: metaprojectDescr = "" # Try retrieving the metaproject (tag) metaproject = transaction.getMetaproject(metaprojectCode, username) if metaproject is None: # Create the metaproject (tag) metaproject = transaction.createNewMetaproject(metaprojectCode, metaprojectDescr, username) # Check that creation was succcessful if metaproject is None: success = "false" message = "Could not create metaproject " + metaprojectCode + "." else: success = "true" message = "Tag " + metaprojectCode + " successfully created." else: success = "false" message = "Tag " + metaprojectCode + " exists already." # Add the results to current row row.setCell("success", success) row.setCell("message", message)
Create metaproject with user-provided description.
Create metaproject with user-provided description.
Python
apache-2.0
aarpon/obit_shared_core_technology,aarpon/obit_shared_core_technology,aarpon/obit_shared_core_technology
def process(transaction, parameters, tableBuilder): """Create a project with user-defined name in given space. """ # Prepare the return table tableBuilder.addHeader("success") tableBuilder.addHeader("message") # Add a row for the results row = tableBuilder.addRow() # Retrieve parameters from client + username = parameters.get("userName") metaprojectCode = parameters.get("metaprojectCode") - username = parameters.get("userName") + metaprojectDescr = parameters.get("metaprojectDescr") + if metaprojectDescr is None: + metaprojectDescr = "" # Try retrieving the metaproject (tag) metaproject = transaction.getMetaproject(metaprojectCode, username) if metaproject is None: # Create the metaproject (tag) metaproject = transaction.createNewMetaproject(metaprojectCode, - "Test", + metaprojectDescr, username) # Check that creation was succcessful if metaproject is None: success = "false" message = "Could not create metaproject " + metaprojectCode + "." else: success = "true" message = "Tag " + metaprojectCode + " successfully created." else: success = "false" message = "Tag " + metaprojectCode + " exists already." # Add the results to current row row.setCell("success", success) row.setCell("message", message)
Create metaproject with user-provided description.
## Code Before: def process(transaction, parameters, tableBuilder): """Create a project with user-defined name in given space. """ # Prepare the return table tableBuilder.addHeader("success") tableBuilder.addHeader("message") # Add a row for the results row = tableBuilder.addRow() # Retrieve parameters from client metaprojectCode = parameters.get("metaprojectCode") username = parameters.get("userName") # Try retrieving the metaproject (tag) metaproject = transaction.getMetaproject(metaprojectCode, username) if metaproject is None: # Create the metaproject (tag) metaproject = transaction.createNewMetaproject(metaprojectCode, "Test", username) # Check that creation was succcessful if metaproject is None: success = "false" message = "Could not create metaproject " + metaprojectCode + "." else: success = "true" message = "Tag " + metaprojectCode + " successfully created." else: success = "false" message = "Tag " + metaprojectCode + " exists already." # Add the results to current row row.setCell("success", success) row.setCell("message", message) ## Instruction: Create metaproject with user-provided description. ## Code After: def process(transaction, parameters, tableBuilder): """Create a project with user-defined name in given space. """ # Prepare the return table tableBuilder.addHeader("success") tableBuilder.addHeader("message") # Add a row for the results row = tableBuilder.addRow() # Retrieve parameters from client username = parameters.get("userName") metaprojectCode = parameters.get("metaprojectCode") metaprojectDescr = parameters.get("metaprojectDescr") if metaprojectDescr is None: metaprojectDescr = "" # Try retrieving the metaproject (tag) metaproject = transaction.getMetaproject(metaprojectCode, username) if metaproject is None: # Create the metaproject (tag) metaproject = transaction.createNewMetaproject(metaprojectCode, metaprojectDescr, username) # Check that creation was succcessful if metaproject is None: success = "false" message = "Could not create metaproject " + metaprojectCode + "." else: success = "true" message = "Tag " + metaprojectCode + " successfully created." else: success = "false" message = "Tag " + metaprojectCode + " exists already." # Add the results to current row row.setCell("success", success) row.setCell("message", message)
... # Retrieve parameters from client username = parameters.get("userName") metaprojectCode = parameters.get("metaprojectCode") metaprojectDescr = parameters.get("metaprojectDescr") if metaprojectDescr is None: metaprojectDescr = "" ... metaproject = transaction.createNewMetaproject(metaprojectCode, metaprojectDescr, username) ...
d99ad3de00ec8bb9b3a36de5f50bd4f48a08cbb1
test/acceptance/test_cli_vital.py
test/acceptance/test_cli_vital.py
import unittest from pathlib import Path import subprocess class TestVintDoNotDiedWhenLintingVital(unittest.TestCase): def assertVintStillAlive(self, cmd): try: got_output = subprocess.check_output(cmd, stderr=subprocess.STDOUT, universal_newlines=True) except subprocess.CalledProcessError as err: got_output = err.output unexpected_keyword = r'^Traceback' self.assertNotRegex(got_output, unexpected_keyword) def assertNotRegex(self, string, pattern): assertNotRegexpMatches = getattr(self, 'assertNotRegexpMatches', None) if assertNotRegexpMatches: assertNotRegexpMatches(string, pattern) return super(TestVintDoNotDiedWhenLintingVital, self).assertNotRegex(string, pattern) def test_not_died_when_linting_vital(self): vital_dir = str(Path('test', 'fixture', 'cli', 'vital.vim')) cmd = ['vint', vital_dir] self.assertVintStillAlive(cmd) if __name__ == '__main__': unittest.main()
import unittest from pathlib import Path import subprocess class TestVintDoNotDiedWhenLintingVital(unittest.TestCase): def assertVintStillAlive(self, cmd): try: got_output = subprocess.check_output(cmd, stderr=subprocess.STDOUT, universal_newlines=True) except subprocess.CalledProcessError as err: got_output = err.output unexpected_keyword = 'Traceback' self.assertFalse(unexpected_keyword in got_output, 'vint was died when linting vital.vim: ' + got_output) def test_survive_after_linting(self): vital_dir = str(Path('test', 'fixture', 'cli', 'vital.vim')) cmd = ['vint', vital_dir] self.assertVintStillAlive(cmd) if __name__ == '__main__': unittest.main()
Fix false-negative test caused by using fallbacked assertNotRegex
Fix false-negative test caused by using fallbacked assertNotRegex
Python
mit
Kuniwak/vint,RianFuro/vint,Kuniwak/vint,RianFuro/vint
import unittest from pathlib import Path import subprocess class TestVintDoNotDiedWhenLintingVital(unittest.TestCase): def assertVintStillAlive(self, cmd): try: got_output = subprocess.check_output(cmd, stderr=subprocess.STDOUT, universal_newlines=True) except subprocess.CalledProcessError as err: got_output = err.output - unexpected_keyword = r'^Traceback' + unexpected_keyword = 'Traceback' - self.assertNotRegex(got_output, unexpected_keyword) + self.assertFalse(unexpected_keyword in got_output, + 'vint was died when linting vital.vim: ' + got_output) + def test_survive_after_linting(self): - def assertNotRegex(self, string, pattern): - assertNotRegexpMatches = getattr(self, 'assertNotRegexpMatches', None) - if assertNotRegexpMatches: - assertNotRegexpMatches(string, pattern) - return - - super(TestVintDoNotDiedWhenLintingVital, self).assertNotRegex(string, pattern) - - - - def test_not_died_when_linting_vital(self): vital_dir = str(Path('test', 'fixture', 'cli', 'vital.vim')) cmd = ['vint', vital_dir] self.assertVintStillAlive(cmd) if __name__ == '__main__': unittest.main()
Fix false-negative test caused by using fallbacked assertNotRegex
## Code Before: import unittest from pathlib import Path import subprocess class TestVintDoNotDiedWhenLintingVital(unittest.TestCase): def assertVintStillAlive(self, cmd): try: got_output = subprocess.check_output(cmd, stderr=subprocess.STDOUT, universal_newlines=True) except subprocess.CalledProcessError as err: got_output = err.output unexpected_keyword = r'^Traceback' self.assertNotRegex(got_output, unexpected_keyword) def assertNotRegex(self, string, pattern): assertNotRegexpMatches = getattr(self, 'assertNotRegexpMatches', None) if assertNotRegexpMatches: assertNotRegexpMatches(string, pattern) return super(TestVintDoNotDiedWhenLintingVital, self).assertNotRegex(string, pattern) def test_not_died_when_linting_vital(self): vital_dir = str(Path('test', 'fixture', 'cli', 'vital.vim')) cmd = ['vint', vital_dir] self.assertVintStillAlive(cmd) if __name__ == '__main__': unittest.main() ## Instruction: Fix false-negative test caused by using fallbacked assertNotRegex ## Code After: import unittest from pathlib import Path import subprocess class TestVintDoNotDiedWhenLintingVital(unittest.TestCase): def assertVintStillAlive(self, cmd): try: got_output = subprocess.check_output(cmd, stderr=subprocess.STDOUT, universal_newlines=True) except subprocess.CalledProcessError as err: got_output = err.output unexpected_keyword = 'Traceback' self.assertFalse(unexpected_keyword in got_output, 'vint was died when linting vital.vim: ' + got_output) def test_survive_after_linting(self): vital_dir = str(Path('test', 'fixture', 'cli', 'vital.vim')) cmd = ['vint', vital_dir] self.assertVintStillAlive(cmd) if __name__ == '__main__': unittest.main()
# ... existing code ... unexpected_keyword = 'Traceback' self.assertFalse(unexpected_keyword in got_output, 'vint was died when linting vital.vim: ' + got_output) # ... modified code ... def test_survive_after_linting(self): vital_dir = str(Path('test', 'fixture', 'cli', 'vital.vim')) # ... rest of the code ...
847143cd60986c6558167a8ad28a778b09330a7c
gocd/server.py
gocd/server.py
import urllib2 from urlparse import urljoin from gocd.api import Pipeline class Server(object): def __init__(self, host, user=None, password=None): self.host = host self.user = user self.password = password if self.user and self.password: self._add_basic_auth() def get(self, path): return urllib2.urlopen(self._request(path)) def pipeline(self, name): return Pipeline(self, name) def _add_basic_auth(self): auth_handler = urllib2.HTTPBasicAuthHandler() auth_handler.add_password( realm='Cruise', # This seems to be hard coded. uri=self.host, user=self.user, passwd=self.password, ) urllib2.install_opener(urllib2.build_opener(auth_handler)) def _request(self, path, data=None, headers=None): default_headers = { 'User-Agent': 'py-gocd', } default_headers.update(headers or {}) return urllib2.Request( self._url(path), data=data, headers=default_headers ) def _url(self, path): return urljoin(self.host, path)
import urllib2 from urlparse import urljoin from gocd.api import Pipeline class Server(object): def __init__(self, host, user=None, password=None): self.host = host self.user = user self.password = password if self.user and self.password: self._add_basic_auth() def get(self, path): return urllib2.urlopen(self._request(path)) def pipeline(self, name): return Pipeline(self, name) def _add_basic_auth(self): auth_handler = urllib2.HTTPBasicAuthHandler( urllib2.HTTPPasswordMgrWithDefaultRealm() ) auth_handler.add_password( realm=None, uri=self.host, user=self.user, passwd=self.password, ) urllib2.install_opener(urllib2.build_opener(auth_handler)) def _request(self, path, data=None, headers=None): default_headers = { 'User-Agent': 'py-gocd', } default_headers.update(headers or {}) return urllib2.Request( self._url(path), data=data, headers=default_headers ) def _url(self, path): return urljoin(self.host, path)
Remove hard coded realm and assume any is fine
Remove hard coded realm and assume any is fine
Python
mit
henriquegemignani/py-gocd,gaqzi/py-gocd
import urllib2 from urlparse import urljoin from gocd.api import Pipeline class Server(object): def __init__(self, host, user=None, password=None): self.host = host self.user = user self.password = password if self.user and self.password: self._add_basic_auth() def get(self, path): return urllib2.urlopen(self._request(path)) def pipeline(self, name): return Pipeline(self, name) def _add_basic_auth(self): - auth_handler = urllib2.HTTPBasicAuthHandler() + auth_handler = urllib2.HTTPBasicAuthHandler( + urllib2.HTTPPasswordMgrWithDefaultRealm() + ) auth_handler.add_password( - realm='Cruise', # This seems to be hard coded. + realm=None, uri=self.host, user=self.user, passwd=self.password, ) urllib2.install_opener(urllib2.build_opener(auth_handler)) def _request(self, path, data=None, headers=None): default_headers = { 'User-Agent': 'py-gocd', } default_headers.update(headers or {}) return urllib2.Request( self._url(path), data=data, headers=default_headers ) def _url(self, path): return urljoin(self.host, path)
Remove hard coded realm and assume any is fine
## Code Before: import urllib2 from urlparse import urljoin from gocd.api import Pipeline class Server(object): def __init__(self, host, user=None, password=None): self.host = host self.user = user self.password = password if self.user and self.password: self._add_basic_auth() def get(self, path): return urllib2.urlopen(self._request(path)) def pipeline(self, name): return Pipeline(self, name) def _add_basic_auth(self): auth_handler = urllib2.HTTPBasicAuthHandler() auth_handler.add_password( realm='Cruise', # This seems to be hard coded. uri=self.host, user=self.user, passwd=self.password, ) urllib2.install_opener(urllib2.build_opener(auth_handler)) def _request(self, path, data=None, headers=None): default_headers = { 'User-Agent': 'py-gocd', } default_headers.update(headers or {}) return urllib2.Request( self._url(path), data=data, headers=default_headers ) def _url(self, path): return urljoin(self.host, path) ## Instruction: Remove hard coded realm and assume any is fine ## Code After: import urllib2 from urlparse import urljoin from gocd.api import Pipeline class Server(object): def __init__(self, host, user=None, password=None): self.host = host self.user = user self.password = password if self.user and self.password: self._add_basic_auth() def get(self, path): return urllib2.urlopen(self._request(path)) def pipeline(self, name): return Pipeline(self, name) def _add_basic_auth(self): auth_handler = urllib2.HTTPBasicAuthHandler( urllib2.HTTPPasswordMgrWithDefaultRealm() ) auth_handler.add_password( realm=None, uri=self.host, user=self.user, passwd=self.password, ) urllib2.install_opener(urllib2.build_opener(auth_handler)) def _request(self, path, data=None, headers=None): default_headers = { 'User-Agent': 'py-gocd', } default_headers.update(headers or {}) return urllib2.Request( self._url(path), data=data, headers=default_headers ) def _url(self, path): return urljoin(self.host, path)
# ... existing code ... def _add_basic_auth(self): auth_handler = urllib2.HTTPBasicAuthHandler( urllib2.HTTPPasswordMgrWithDefaultRealm() ) auth_handler.add_password( realm=None, uri=self.host, # ... rest of the code ...
07c2bdab605eb00bcc59a5540477819d1339e563
examples/minimal/views.py
examples/minimal/views.py
from cruditor.mixins import CruditorMixin from django.views.generic import TemplateView from examples.mixins import ExamplesMixin class DemoView(ExamplesMixin, CruditorMixin, TemplateView): title = 'Demo view' template_name = 'minimal/demo.html'
from cruditor.mixins import CruditorMixin from django.views.generic import TemplateView from examples.mixins import ExamplesMixin class DemoView(ExamplesMixin, CruditorMixin, TemplateView): title = 'Demo view' template_name = 'minimal/demo.html' def get_breadcrumb(self): return super().get_breadcrumb() + [{ 'url': '/', 'title': 'Additional breadcrumb' }, { 'title': 'Disabled item' }]
Add example for additional breadcrumb items.
Add example for additional breadcrumb items.
Python
mit
moccu/django-cruditor,moccu/django-cruditor,moccu/django-cruditor
from cruditor.mixins import CruditorMixin from django.views.generic import TemplateView from examples.mixins import ExamplesMixin class DemoView(ExamplesMixin, CruditorMixin, TemplateView): title = 'Demo view' template_name = 'minimal/demo.html' + def get_breadcrumb(self): + return super().get_breadcrumb() + [{ + 'url': '/', + 'title': 'Additional breadcrumb' + }, { + 'title': 'Disabled item' + }] +
Add example for additional breadcrumb items.
## Code Before: from cruditor.mixins import CruditorMixin from django.views.generic import TemplateView from examples.mixins import ExamplesMixin class DemoView(ExamplesMixin, CruditorMixin, TemplateView): title = 'Demo view' template_name = 'minimal/demo.html' ## Instruction: Add example for additional breadcrumb items. ## Code After: from cruditor.mixins import CruditorMixin from django.views.generic import TemplateView from examples.mixins import ExamplesMixin class DemoView(ExamplesMixin, CruditorMixin, TemplateView): title = 'Demo view' template_name = 'minimal/demo.html' def get_breadcrumb(self): return super().get_breadcrumb() + [{ 'url': '/', 'title': 'Additional breadcrumb' }, { 'title': 'Disabled item' }]
... template_name = 'minimal/demo.html' def get_breadcrumb(self): return super().get_breadcrumb() + [{ 'url': '/', 'title': 'Additional breadcrumb' }, { 'title': 'Disabled item' }] ...
9e02f92fc19b7f833b25d0273143e98261a3b484
democracy/admin/__init__.py
democracy/admin/__init__.py
from django.contrib import admin from nested_admin.nested import NestedAdmin, NestedStackedInline from democracy import models # Inlines class HearingImageInline(NestedStackedInline): model = models.HearingImage extra = 0 class SectionImageInline(NestedStackedInline): model = models.SectionImage extra = 0 class SectionInline(NestedStackedInline): model = models.Section extra = 1 inlines = [SectionImageInline] # Admins class HearingAdmin(NestedAdmin): inlines = [HearingImageInline, SectionInline] list_display = ("id", "published", "title", "open_at", "close_at", "force_closed") list_filter = ("published",) search_fields = ("id", "title") # Wire it up! admin.site.register(models.Label) admin.site.register(models.Hearing, HearingAdmin)
from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from nested_admin.nested import NestedAdmin, NestedStackedInline from democracy import models # Inlines class HearingImageInline(NestedStackedInline): model = models.HearingImage extra = 0 exclude = ("public", "title") class SectionImageInline(NestedStackedInline): model = models.SectionImage extra = 0 exclude = ("public", "title") class SectionInline(NestedStackedInline): model = models.Section extra = 1 inlines = [SectionImageInline] exclude = ("public", "commenting",) # Admins class HearingAdmin(NestedAdmin): inlines = [HearingImageInline, SectionInline] list_display = ("id", "published", "title", "open_at", "close_at", "force_closed") list_filter = ("published",) search_fields = ("id", "title") fieldsets = ( (None, { "fields": ("title", "abstract", "labels", "id") }), (_("Availability"), { "fields": ("published", "open_at", "close_at", "force_closed", "commenting") }), ) def save_related(self, request, form, formsets, change): super().save_related(request, form, formsets, change) hearing = form.instance assert isinstance(hearing, models.Hearing) hearing.sections.update(commenting=hearing.commenting) class LabelAdmin(admin.ModelAdmin): exclude = ("public",) # Wire it up! admin.site.register(models.Label, LabelAdmin) admin.site.register(models.Hearing, HearingAdmin)
Hide unnecessary fields in the admins
Hide unnecessary fields in the admins * Hide some unnecessary fields from Hearings * Hide Public and Commenting flags from Sections (Section commenting option follows that of hearings.) * Hide Public and Title fields from images * Hide Public field from labels Refs #118
Python
mit
vikoivun/kerrokantasi,stephawe/kerrokantasi,stephawe/kerrokantasi,City-of-Helsinki/kerrokantasi,City-of-Helsinki/kerrokantasi,stephawe/kerrokantasi,vikoivun/kerrokantasi,City-of-Helsinki/kerrokantasi,City-of-Helsinki/kerrokantasi,vikoivun/kerrokantasi
from django.contrib import admin + from django.utils.translation import ugettext_lazy as _ from nested_admin.nested import NestedAdmin, NestedStackedInline from democracy import models # Inlines class HearingImageInline(NestedStackedInline): model = models.HearingImage extra = 0 + exclude = ("public", "title") class SectionImageInline(NestedStackedInline): model = models.SectionImage extra = 0 + exclude = ("public", "title") class SectionInline(NestedStackedInline): model = models.Section extra = 1 inlines = [SectionImageInline] + exclude = ("public", "commenting",) # Admins class HearingAdmin(NestedAdmin): inlines = [HearingImageInline, SectionInline] list_display = ("id", "published", "title", "open_at", "close_at", "force_closed") list_filter = ("published",) search_fields = ("id", "title") + fieldsets = ( + (None, { + "fields": ("title", "abstract", "labels", "id") + }), + (_("Availability"), { + "fields": ("published", "open_at", "close_at", "force_closed", "commenting") + }), + ) + + def save_related(self, request, form, formsets, change): + super().save_related(request, form, formsets, change) + hearing = form.instance + assert isinstance(hearing, models.Hearing) + hearing.sections.update(commenting=hearing.commenting) + + + class LabelAdmin(admin.ModelAdmin): + exclude = ("public",) # Wire it up! - admin.site.register(models.Label) + admin.site.register(models.Label, LabelAdmin) admin.site.register(models.Hearing, HearingAdmin)
Hide unnecessary fields in the admins
## Code Before: from django.contrib import admin from nested_admin.nested import NestedAdmin, NestedStackedInline from democracy import models # Inlines class HearingImageInline(NestedStackedInline): model = models.HearingImage extra = 0 class SectionImageInline(NestedStackedInline): model = models.SectionImage extra = 0 class SectionInline(NestedStackedInline): model = models.Section extra = 1 inlines = [SectionImageInline] # Admins class HearingAdmin(NestedAdmin): inlines = [HearingImageInline, SectionInline] list_display = ("id", "published", "title", "open_at", "close_at", "force_closed") list_filter = ("published",) search_fields = ("id", "title") # Wire it up! admin.site.register(models.Label) admin.site.register(models.Hearing, HearingAdmin) ## Instruction: Hide unnecessary fields in the admins ## Code After: from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from nested_admin.nested import NestedAdmin, NestedStackedInline from democracy import models # Inlines class HearingImageInline(NestedStackedInline): model = models.HearingImage extra = 0 exclude = ("public", "title") class SectionImageInline(NestedStackedInline): model = models.SectionImage extra = 0 exclude = ("public", "title") class SectionInline(NestedStackedInline): model = models.Section extra = 1 inlines = [SectionImageInline] exclude = ("public", "commenting",) # Admins class HearingAdmin(NestedAdmin): inlines = [HearingImageInline, SectionInline] list_display = ("id", "published", "title", "open_at", "close_at", "force_closed") list_filter = ("published",) search_fields = ("id", "title") fieldsets = ( (None, { "fields": ("title", "abstract", "labels", "id") }), (_("Availability"), { "fields": ("published", "open_at", "close_at", "force_closed", "commenting") }), ) def save_related(self, request, form, formsets, change): super().save_related(request, form, formsets, change) hearing = form.instance assert isinstance(hearing, models.Hearing) hearing.sections.update(commenting=hearing.commenting) class LabelAdmin(admin.ModelAdmin): exclude = ("public",) # Wire it up! admin.site.register(models.Label, LabelAdmin) admin.site.register(models.Hearing, HearingAdmin)
... from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from nested_admin.nested import NestedAdmin, NestedStackedInline ... extra = 0 exclude = ("public", "title") ... extra = 0 exclude = ("public", "title") ... inlines = [SectionImageInline] exclude = ("public", "commenting",) ... search_fields = ("id", "title") fieldsets = ( (None, { "fields": ("title", "abstract", "labels", "id") }), (_("Availability"), { "fields": ("published", "open_at", "close_at", "force_closed", "commenting") }), ) def save_related(self, request, form, formsets, change): super().save_related(request, form, formsets, change) hearing = form.instance assert isinstance(hearing, models.Hearing) hearing.sections.update(commenting=hearing.commenting) class LabelAdmin(admin.ModelAdmin): exclude = ("public",) ... admin.site.register(models.Label, LabelAdmin) admin.site.register(models.Hearing, HearingAdmin) ...
16f7e964341b2a0861011b33d3e4aedd937cead5
usr/examples/14-WiFi-Shield/fw_update.py
usr/examples/14-WiFi-Shield/fw_update.py
import network # Init wlan module in Download mode. wlan = network.WINC(True) #print("Firmware version:", wlan.fw_version()) # Start the firmware update process. wlan.fw_update() #print("Firmware version:", wlan.fw_version())
import network # Init wlan module in Download mode. wlan = network.WINC(mode=network.WINC.MODE_FIRMWARE) print("Firmware version:", wlan.fw_version()) # Start the firmware update process. wlan.fw_update() print("Firmware version:", wlan.fw_version())
Fix WINC fw update script.
Fix WINC fw update script.
Python
mit
iabdalkader/openmv,kwagyeman/openmv,kwagyeman/openmv,openmv/openmv,kwagyeman/openmv,openmv/openmv,iabdalkader/openmv,openmv/openmv,iabdalkader/openmv,kwagyeman/openmv,iabdalkader/openmv,openmv/openmv
import network # Init wlan module in Download mode. - wlan = network.WINC(True) + wlan = network.WINC(mode=network.WINC.MODE_FIRMWARE) - #print("Firmware version:", wlan.fw_version()) + print("Firmware version:", wlan.fw_version()) # Start the firmware update process. wlan.fw_update() - #print("Firmware version:", wlan.fw_version()) + print("Firmware version:", wlan.fw_version())
Fix WINC fw update script.
## Code Before: import network # Init wlan module in Download mode. wlan = network.WINC(True) #print("Firmware version:", wlan.fw_version()) # Start the firmware update process. wlan.fw_update() #print("Firmware version:", wlan.fw_version()) ## Instruction: Fix WINC fw update script. ## Code After: import network # Init wlan module in Download mode. wlan = network.WINC(mode=network.WINC.MODE_FIRMWARE) print("Firmware version:", wlan.fw_version()) # Start the firmware update process. wlan.fw_update() print("Firmware version:", wlan.fw_version())
# ... existing code ... # Init wlan module in Download mode. wlan = network.WINC(mode=network.WINC.MODE_FIRMWARE) print("Firmware version:", wlan.fw_version()) # ... modified code ... wlan.fw_update() print("Firmware version:", wlan.fw_version()) # ... rest of the code ...
3d42553ae6acd452e122a1a89851e4693a89abde
build.py
build.py
import os from flask.ext.frozen import Freezer import webassets from content import app, assets bundle_files = [] for bundle in assets: assert isinstance(bundle, webassets.Bundle) print("Building bundle {}".format(bundle.output)) bundle.build(force=True, disable_cache=True) bundle_files.append(bundle.output) print("Freezing") app.config['FREEZER_DESTINATION'] = os.path.abspath("static") app.config['FREEZER_BASE_URL'] = "http://dabo.guru/" app.config['FREEZER_DESTINATION_IGNORE'] = bundle_files freezer = Freezer(app=app, with_static_files=False, with_no_argument_rules=True, log_url_for=True) freezer.freeze()
import os from flask.ext.frozen import Freezer import webassets from content import app, assets bundle_files = [] for bundle in assets: assert isinstance(bundle, webassets.Bundle) print("Building bundle {}".format(bundle.output)) bundle.build(force=True, disable_cache=True) bundle_files.append(bundle.output) # This is a copy of Freezer.no_argument_rules() modified to ignore certain paths def no_argument_rules_urls_with_ignore(): """URL generator for URL rules that take no arguments.""" ignored = app.config.get('FREEZER_IGNORE_ENDPOINTS', []) for rule in app.url_map.iter_rules(): if rule.endpoint not in ignored and not rule.arguments and 'GET' in rule.methods: yield rule.endpoint, {} app.config['FREEZER_DESTINATION'] = os.path.abspath("static") app.config['FREEZER_BASE_URL'] = "http://dabo.guru/" app.config['FREEZER_DESTINATION_IGNORE'] = bundle_files app.config['FREEZER_IGNORE_ENDPOINTS'] = ['oauth_respond', 'mc_api_name', 'mc_api_uuid', 'serve_markdown'] freezer = Freezer(app=app, with_static_files=False, with_no_argument_rules=False, log_url_for=True) freezer.register_generator(no_argument_rules_urls_with_ignore) print("Freezing") freezer.freeze()
Add workaround for frozen-flask generating static pages for dynamic api pages like /oauth/.
Add workaround for frozen-flask generating static pages for dynamic api pages like /oauth/.
Python
apache-2.0
daboross/dabo.guru,daboross/dabo.guru,daboross/dabo.guru,daboross/dabo.guru
import os from flask.ext.frozen import Freezer import webassets from content import app, assets bundle_files = [] for bundle in assets: assert isinstance(bundle, webassets.Bundle) print("Building bundle {}".format(bundle.output)) bundle.build(force=True, disable_cache=True) bundle_files.append(bundle.output) - print("Freezing") + + # This is a copy of Freezer.no_argument_rules() modified to ignore certain paths + def no_argument_rules_urls_with_ignore(): + """URL generator for URL rules that take no arguments.""" + ignored = app.config.get('FREEZER_IGNORE_ENDPOINTS', []) + for rule in app.url_map.iter_rules(): + if rule.endpoint not in ignored and not rule.arguments and 'GET' in rule.methods: + yield rule.endpoint, {} + app.config['FREEZER_DESTINATION'] = os.path.abspath("static") app.config['FREEZER_BASE_URL'] = "http://dabo.guru/" app.config['FREEZER_DESTINATION_IGNORE'] = bundle_files + app.config['FREEZER_IGNORE_ENDPOINTS'] = ['oauth_respond', 'mc_api_name', 'mc_api_uuid', 'serve_markdown'] - freezer = Freezer(app=app, with_static_files=False, with_no_argument_rules=True, log_url_for=True) + freezer = Freezer(app=app, with_static_files=False, with_no_argument_rules=False, log_url_for=True) + freezer.register_generator(no_argument_rules_urls_with_ignore) + print("Freezing") freezer.freeze()
Add workaround for frozen-flask generating static pages for dynamic api pages like /oauth/.
## Code Before: import os from flask.ext.frozen import Freezer import webassets from content import app, assets bundle_files = [] for bundle in assets: assert isinstance(bundle, webassets.Bundle) print("Building bundle {}".format(bundle.output)) bundle.build(force=True, disable_cache=True) bundle_files.append(bundle.output) print("Freezing") app.config['FREEZER_DESTINATION'] = os.path.abspath("static") app.config['FREEZER_BASE_URL'] = "http://dabo.guru/" app.config['FREEZER_DESTINATION_IGNORE'] = bundle_files freezer = Freezer(app=app, with_static_files=False, with_no_argument_rules=True, log_url_for=True) freezer.freeze() ## Instruction: Add workaround for frozen-flask generating static pages for dynamic api pages like /oauth/. ## Code After: import os from flask.ext.frozen import Freezer import webassets from content import app, assets bundle_files = [] for bundle in assets: assert isinstance(bundle, webassets.Bundle) print("Building bundle {}".format(bundle.output)) bundle.build(force=True, disable_cache=True) bundle_files.append(bundle.output) # This is a copy of Freezer.no_argument_rules() modified to ignore certain paths def no_argument_rules_urls_with_ignore(): """URL generator for URL rules that take no arguments.""" ignored = app.config.get('FREEZER_IGNORE_ENDPOINTS', []) for rule in app.url_map.iter_rules(): if rule.endpoint not in ignored and not rule.arguments and 'GET' in rule.methods: yield rule.endpoint, {} app.config['FREEZER_DESTINATION'] = os.path.abspath("static") app.config['FREEZER_BASE_URL'] = "http://dabo.guru/" app.config['FREEZER_DESTINATION_IGNORE'] = bundle_files app.config['FREEZER_IGNORE_ENDPOINTS'] = ['oauth_respond', 'mc_api_name', 'mc_api_uuid', 'serve_markdown'] freezer = Freezer(app=app, with_static_files=False, with_no_argument_rules=False, log_url_for=True) freezer.register_generator(no_argument_rules_urls_with_ignore) print("Freezing") freezer.freeze()
// ... existing code ... # This is a copy of Freezer.no_argument_rules() modified to ignore certain paths def no_argument_rules_urls_with_ignore(): """URL generator for URL rules that take no arguments.""" ignored = app.config.get('FREEZER_IGNORE_ENDPOINTS', []) for rule in app.url_map.iter_rules(): if rule.endpoint not in ignored and not rule.arguments and 'GET' in rule.methods: yield rule.endpoint, {} // ... modified code ... app.config['FREEZER_DESTINATION_IGNORE'] = bundle_files app.config['FREEZER_IGNORE_ENDPOINTS'] = ['oauth_respond', 'mc_api_name', 'mc_api_uuid', 'serve_markdown'] freezer = Freezer(app=app, with_static_files=False, with_no_argument_rules=False, log_url_for=True) freezer.register_generator(no_argument_rules_urls_with_ignore) print("Freezing") freezer.freeze() // ... rest of the code ...
31691ca909fe0b1816d89bb4ccf69974eca882a6
allauth/app_settings.py
allauth/app_settings.py
import django from django.conf import settings from django.core.exceptions import ImproperlyConfigured SOCIALACCOUNT_ENABLED = 'allauth.socialaccount' in settings.INSTALLED_APPS def check_context_processors(): allauth_ctx = 'allauth.socialaccount.context_processors.socialaccount' ctx_present = False if django.VERSION < (1, 8,): if allauth_ctx in settings.TEMPLATE_CONTEXT_PROCESSORS: ctx_present = True else: for engine in settings.TEMPLATES: if allauth_ctx in engine.get('OPTIONS', {})\ .get('context_processors', []): ctx_present = True break if not ctx_present: excmsg = ("socialaccount context processor " "not found in settings.TEMPLATE_CONTEXT_PROCESSORS." "See settings.py instructions here: " "https://github.com/pennersr/django-allauth#installation") raise ImproperlyConfigured(excmsg) if SOCIALACCOUNT_ENABLED: check_context_processors() LOGIN_REDIRECT_URL = getattr(settings, 'LOGIN_REDIRECT_URL', '/') USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User')
import django from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django import template SOCIALACCOUNT_ENABLED = 'allauth.socialaccount' in settings.INSTALLED_APPS def check_context_processors(): allauth_ctx = 'allauth.socialaccount.context_processors.socialaccount' ctx_present = False if django.VERSION < (1, 8,): if allauth_ctx in settings.TEMPLATE_CONTEXT_PROCESSORS: ctx_present = True else: for engine in template.engines.templates.values(): if allauth_ctx in engine.get('OPTIONS', {})\ .get('context_processors', []): ctx_present = True break if not ctx_present: excmsg = ("socialaccount context processor " "not found in settings.TEMPLATE_CONTEXT_PROCESSORS." "See settings.py instructions here: " "https://github.com/pennersr/django-allauth#installation") raise ImproperlyConfigured(excmsg) if SOCIALACCOUNT_ENABLED: check_context_processors() LOGIN_REDIRECT_URL = getattr(settings, 'LOGIN_REDIRECT_URL', '/') USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User')
Fix for checking the context processors on Django 1.8
Fix for checking the context processors on Django 1.8 If the user has not migrated their settings file to use the new TEMPLATES method in Django 1.8, settings.TEMPLATES is an empty list. Instead, if we check django.templates.engines it will be populated with the automatically migrated data from settings.TEMPLATE*.
Python
mit
cudadog/django-allauth,bitcity/django-allauth,petersanchez/django-allauth,bittner/django-allauth,manran/django-allauth,jscott1989/django-allauth,petersanchez/django-allauth,JshWright/django-allauth,italomaia/django-allauth,yarbelk/django-allauth,pankeshang/django-allauth,sih4sing5hong5/django-allauth,ZachLiuGIS/django-allauth,fabiocerqueira/django-allauth,aexeagmbh/django-allauth,dincamihai/django-allauth,italomaia/django-allauth,jscott1989/django-allauth,wli/django-allauth,80vs90/django-allauth,agriffis/django-allauth,igorgai/django-allauth,rsalmaso/django-allauth,spool/django-allauth,7WebPages/django-allauth,pennersr/django-allauth,ankitjain87/django-allauth,neo/django-allauth,yarbelk/django-allauth,pankeshang/django-allauth,agriffis/django-allauth,beswarm/django-allauth,manran/django-allauth,lmorchard/django-allauth,concentricsky/django-allauth,bopo/django-allauth,bitcity/django-allauth,hanasoo/django-allauth,aexeagmbh/django-allauth,github-account-because-they-want-it/django-allauth,erueloi/django-allauth,vuchau/django-allauth,bjorand/django-allauth,janusnic/django-allauth,janusnic/django-allauth,payamsm/django-allauth,SakuradaJun/django-allauth,rulz/django-allauth,davidrenne/django-allauth,beswarm/django-allauth,erueloi/django-allauth,alacritythief/django-allauth,wli/django-allauth,zhangziang/django-allauth,concentricsky/django-allauth,willharris/django-allauth,github-account-because-they-want-it/django-allauth,pankeshang/django-allauth,tigeraniya/django-allauth,github-account-because-they-want-it/django-allauth,kingofsystem/django-allauth,joshowen/django-allauth,bjorand/django-allauth,bitcity/django-allauth,kingofsystem/django-allauth,pztrick/django-allauth,ashwoods/django-allauth,alacritythief/django-allauth,fuzzpedal/django-allauth,hanasoo/django-allauth,tigeraniya/django-allauth,pennersr/django-allauth,beswarm/django-allauth,7WebPages/django-allauth,tigeraniya/django-allauth,avsd/django-allauth,janusnic/django-allauth,jscott1989/django-allauth,carltongibson/django-allauth,dincamihai/django-allauth,ashwoods/django-allauth,rulz/django-allauth,wayward710/django-allauth,owais/django-allauth,patricio-astudillo/django-allauth,80vs90/django-allauth,moreati/django-allauth,dincamihai/django-allauth,lmorchard/django-allauth,fabiocerqueira/django-allauth,italomaia/django-allauth,JshWright/django-allauth,lukeburden/django-allauth,payamsm/django-allauth,socialsweethearts/django-allauth,pranjalpatil/django-allauth,patricio-astudillo/django-allauth,zhangziang/django-allauth,nimbis/django-allauth,nimbis/django-allauth,davidrenne/django-allauth,rsalmaso/django-allauth,80vs90/django-allauth,AltSchool/django-allauth,joshowen/django-allauth,lukeburden/django-allauth,bopo/django-allauth,joshowen/django-allauth,AltSchool/django-allauth,aexeagmbh/django-allauth,carltongibson/django-allauth,sih4sing5hong5/django-allauth,hanasoo/django-allauth,igorgai/django-allauth,jwhitlock/django-allauth,payamsm/django-allauth,zhangziang/django-allauth,fuzzpedal/django-allauth,alacritythief/django-allauth,ZachLiuGIS/django-allauth,rsalmaso/django-allauth,cudadog/django-allauth,vuchau/django-allauth,wayward710/django-allauth,avsd/django-allauth,pranjalpatil/django-allauth,spool/django-allauth,petersanchez/django-allauth,wayward710/django-allauth,JshWright/django-allauth,sih4sing5hong5/django-allauth,owais/django-allauth,kingofsystem/django-allauth,7WebPages/django-allauth,concentricsky/django-allauth,ankitjain87/django-allauth,neo/django-allauth,lukeburden/django-allauth,SakuradaJun/django-allauth,willharris/django-allauth,yarbelk/django-allauth,agriffis/django-allauth,bopo/django-allauth,AltSchool/django-allauth,moreati/django-allauth,vuchau/django-allauth,pennersr/django-allauth,pztrick/django-allauth,erueloi/django-allauth,fabiocerqueira/django-allauth,davidrenne/django-allauth,pranjalpatil/django-allauth,pztrick/django-allauth,fuzzpedal/django-allauth,socialsweethearts/django-allauth,bittner/django-allauth,ZachLiuGIS/django-allauth,spool/django-allauth,lmorchard/django-allauth,carltongibson/django-allauth,ankitjain87/django-allauth,moreati/django-allauth,neo/django-allauth,cudadog/django-allauth,socialsweethearts/django-allauth,owais/django-allauth,ashwoods/django-allauth,rulz/django-allauth,jwhitlock/django-allauth,manran/django-allauth,SakuradaJun/django-allauth,nimbis/django-allauth,jwhitlock/django-allauth,patricio-astudillo/django-allauth,wli/django-allauth,avsd/django-allauth,bittner/django-allauth,willharris/django-allauth,igorgai/django-allauth,bjorand/django-allauth
import django from django.conf import settings from django.core.exceptions import ImproperlyConfigured + from django import template SOCIALACCOUNT_ENABLED = 'allauth.socialaccount' in settings.INSTALLED_APPS def check_context_processors(): allauth_ctx = 'allauth.socialaccount.context_processors.socialaccount' ctx_present = False if django.VERSION < (1, 8,): if allauth_ctx in settings.TEMPLATE_CONTEXT_PROCESSORS: ctx_present = True else: - for engine in settings.TEMPLATES: + for engine in template.engines.templates.values(): if allauth_ctx in engine.get('OPTIONS', {})\ .get('context_processors', []): ctx_present = True break if not ctx_present: excmsg = ("socialaccount context processor " "not found in settings.TEMPLATE_CONTEXT_PROCESSORS." "See settings.py instructions here: " "https://github.com/pennersr/django-allauth#installation") raise ImproperlyConfigured(excmsg) if SOCIALACCOUNT_ENABLED: check_context_processors() LOGIN_REDIRECT_URL = getattr(settings, 'LOGIN_REDIRECT_URL', '/') USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User')
Fix for checking the context processors on Django 1.8
## Code Before: import django from django.conf import settings from django.core.exceptions import ImproperlyConfigured SOCIALACCOUNT_ENABLED = 'allauth.socialaccount' in settings.INSTALLED_APPS def check_context_processors(): allauth_ctx = 'allauth.socialaccount.context_processors.socialaccount' ctx_present = False if django.VERSION < (1, 8,): if allauth_ctx in settings.TEMPLATE_CONTEXT_PROCESSORS: ctx_present = True else: for engine in settings.TEMPLATES: if allauth_ctx in engine.get('OPTIONS', {})\ .get('context_processors', []): ctx_present = True break if not ctx_present: excmsg = ("socialaccount context processor " "not found in settings.TEMPLATE_CONTEXT_PROCESSORS." "See settings.py instructions here: " "https://github.com/pennersr/django-allauth#installation") raise ImproperlyConfigured(excmsg) if SOCIALACCOUNT_ENABLED: check_context_processors() LOGIN_REDIRECT_URL = getattr(settings, 'LOGIN_REDIRECT_URL', '/') USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User') ## Instruction: Fix for checking the context processors on Django 1.8 ## Code After: import django from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django import template SOCIALACCOUNT_ENABLED = 'allauth.socialaccount' in settings.INSTALLED_APPS def check_context_processors(): allauth_ctx = 'allauth.socialaccount.context_processors.socialaccount' ctx_present = False if django.VERSION < (1, 8,): if allauth_ctx in settings.TEMPLATE_CONTEXT_PROCESSORS: ctx_present = True else: for engine in template.engines.templates.values(): if allauth_ctx in engine.get('OPTIONS', {})\ .get('context_processors', []): ctx_present = True break if not ctx_present: excmsg = ("socialaccount context processor " "not found in settings.TEMPLATE_CONTEXT_PROCESSORS." "See settings.py instructions here: " "https://github.com/pennersr/django-allauth#installation") raise ImproperlyConfigured(excmsg) if SOCIALACCOUNT_ENABLED: check_context_processors() LOGIN_REDIRECT_URL = getattr(settings, 'LOGIN_REDIRECT_URL', '/') USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User')
... from django.core.exceptions import ImproperlyConfigured from django import template ... else: for engine in template.engines.templates.values(): if allauth_ctx in engine.get('OPTIONS', {})\ ...
5ac7c07277ef1c7e714336e1b96571cdfea15a13
ktbs_bench_manager/benchable_graph.py
ktbs_bench_manager/benchable_graph.py
import logging from rdflib import Graph class BenchableGraph(object): """ Provides a convenient way to use a graph for benchmarks. """ def __init__(self, store, graph_id, store_config, graph_create=False): """ :param str store: Type of store to use. :param str graph_id: The graph identifier. :param store_config: Configuration to open the store. :type store_config: str or tuple :param bool graph_create: True to create the graph upon connecting. """ self.graph = Graph(store=store, identifier=graph_id) self._graph_id = graph_id self._store_config = store_config self._graph_create = graph_create def connect(self): """Connect to the store. For some configurations, the connection is postponed until needed (e.g. when doing a graph.query() or graph.add()). This behaviour comes from RDFLib implementation of graph.open(). """ return self.graph.open(configuration=self._store_config, create=self._graph_create) def close(self, commit_pending_transaction=True): """Close a connection to a store. :param bool commit_pending_transaction: True if to commit pending transaction before closing, False otherwise. .. note:: The graph.close() method is not implemented for SPARQL Store in RDFLib """ self.graph.close(commit_pending_transaction=commit_pending_transaction)
from rdflib import Graph class BenchableGraph(object): """ Provides a convenient way to use a graph for benchmarks. """ def __init__(self, store, graph_id, store_config, graph_create=False): """ :param str store: Type of store to use. :param str graph_id: The graph identifier. :param store_config: Configuration to open the store. :type store_config: str or tuple :param bool graph_create: True to create the graph upon connecting. """ self.graph = Graph(store=store, identifier=graph_id) self._graph_id = graph_id self._store_config = store_config self._graph_create = graph_create def connect(self): """Connect to the store. For some configurations, the connection is postponed until needed (e.g. when doing a graph.query() or graph.add()). This behaviour comes from RDFLib implementation of graph.open(). """ return self.graph.open(configuration=self._store_config, create=self._graph_create) def close(self, commit_pending_transaction=True): """Close a connection to a store. :param bool commit_pending_transaction: True if to commit pending transaction before closing, False otherwise. .. note:: The graph.close() method is not implemented for SPARQL Store in RDFLib """ self.graph.close(commit_pending_transaction=commit_pending_transaction)
Remove unnecessary import of logging
Remove unnecessary import of logging
Python
mit
vincent-octo/ktbs_bench_manager,vincent-octo/ktbs_bench_manager
- import logging - from rdflib import Graph class BenchableGraph(object): """ Provides a convenient way to use a graph for benchmarks. """ def __init__(self, store, graph_id, store_config, graph_create=False): """ :param str store: Type of store to use. :param str graph_id: The graph identifier. :param store_config: Configuration to open the store. :type store_config: str or tuple :param bool graph_create: True to create the graph upon connecting. """ self.graph = Graph(store=store, identifier=graph_id) self._graph_id = graph_id self._store_config = store_config self._graph_create = graph_create def connect(self): """Connect to the store. For some configurations, the connection is postponed until needed (e.g. when doing a graph.query() or graph.add()). This behaviour comes from RDFLib implementation of graph.open(). """ return self.graph.open(configuration=self._store_config, create=self._graph_create) def close(self, commit_pending_transaction=True): """Close a connection to a store. :param bool commit_pending_transaction: True if to commit pending transaction before closing, False otherwise. .. note:: The graph.close() method is not implemented for SPARQL Store in RDFLib """ self.graph.close(commit_pending_transaction=commit_pending_transaction)
Remove unnecessary import of logging
## Code Before: import logging from rdflib import Graph class BenchableGraph(object): """ Provides a convenient way to use a graph for benchmarks. """ def __init__(self, store, graph_id, store_config, graph_create=False): """ :param str store: Type of store to use. :param str graph_id: The graph identifier. :param store_config: Configuration to open the store. :type store_config: str or tuple :param bool graph_create: True to create the graph upon connecting. """ self.graph = Graph(store=store, identifier=graph_id) self._graph_id = graph_id self._store_config = store_config self._graph_create = graph_create def connect(self): """Connect to the store. For some configurations, the connection is postponed until needed (e.g. when doing a graph.query() or graph.add()). This behaviour comes from RDFLib implementation of graph.open(). """ return self.graph.open(configuration=self._store_config, create=self._graph_create) def close(self, commit_pending_transaction=True): """Close a connection to a store. :param bool commit_pending_transaction: True if to commit pending transaction before closing, False otherwise. .. note:: The graph.close() method is not implemented for SPARQL Store in RDFLib """ self.graph.close(commit_pending_transaction=commit_pending_transaction) ## Instruction: Remove unnecessary import of logging ## Code After: from rdflib import Graph class BenchableGraph(object): """ Provides a convenient way to use a graph for benchmarks. """ def __init__(self, store, graph_id, store_config, graph_create=False): """ :param str store: Type of store to use. :param str graph_id: The graph identifier. :param store_config: Configuration to open the store. :type store_config: str or tuple :param bool graph_create: True to create the graph upon connecting. """ self.graph = Graph(store=store, identifier=graph_id) self._graph_id = graph_id self._store_config = store_config self._graph_create = graph_create def connect(self): """Connect to the store. For some configurations, the connection is postponed until needed (e.g. when doing a graph.query() or graph.add()). This behaviour comes from RDFLib implementation of graph.open(). """ return self.graph.open(configuration=self._store_config, create=self._graph_create) def close(self, commit_pending_transaction=True): """Close a connection to a store. :param bool commit_pending_transaction: True if to commit pending transaction before closing, False otherwise. .. note:: The graph.close() method is not implemented for SPARQL Store in RDFLib """ self.graph.close(commit_pending_transaction=commit_pending_transaction)
... from rdflib import Graph ...
7daed119551dfc259a0eda0224ac2a6b701c5c14
app/main/services/process_request_json.py
app/main/services/process_request_json.py
import six from .query_builder import FILTER_FIELDS, TEXT_FIELDS from .conversions import strip_and_lowercase def process_values_for_matching(request_json, key): values = request_json[key] if isinstance(values, list): return [strip_and_lowercase(value) for value in values] elif isinstance(values, six.string_types): return strip_and_lowercase(values) return values def convert_request_json_into_index_json(request_json): filter_fields = [field for field in request_json if field in FILTER_FIELDS] for field in filter_fields: request_json["filter_" + field] = \ process_values_for_matching(request_json, field) if field not in TEXT_FIELDS: del request_json[field] return request_json
import six from .query_builder import FILTER_FIELDS, TEXT_FIELDS from .conversions import strip_and_lowercase FILTER_FIELDS_SET = set(FILTER_FIELDS) TEXT_FIELDS_SET = set(TEXT_FIELDS) def process_values_for_matching(values): if isinstance(values, list): return [strip_and_lowercase(value) for value in values] elif isinstance(values, six.string_types): return strip_and_lowercase(values) return values def convert_request_json_into_index_json(request_json): index_json = {} for field in request_json: if field in FILTER_FIELDS_SET: index_json["filter_" + field] = process_values_for_matching( request_json[field] ) if field in TEXT_FIELDS_SET: index_json[field] = request_json[field] return index_json
Drop any unknown request fields when converting into index document
Drop any unknown request fields when converting into index document Previously, convert_request_json_into_index_json relied on the request being sent through the dmutils.apiclient, which dropped any fields that aren't supposed to be indexed. This means that dmutils contains a copy of the filter and text fields lists. Instead, new converting functions only keeps text and filter fields from the request, so it can accept any service document for indexing.
Python
mit
RichardKnop/digitalmarketplace-search-api,alphagov/digitalmarketplace-search-api,RichardKnop/digitalmarketplace-search-api,alphagov/digitalmarketplace-search-api,RichardKnop/digitalmarketplace-search-api,RichardKnop/digitalmarketplace-search-api
import six from .query_builder import FILTER_FIELDS, TEXT_FIELDS from .conversions import strip_and_lowercase + FILTER_FIELDS_SET = set(FILTER_FIELDS) + TEXT_FIELDS_SET = set(TEXT_FIELDS) - def process_values_for_matching(request_json, key): - values = request_json[key] + def process_values_for_matching(values): if isinstance(values, list): return [strip_and_lowercase(value) for value in values] elif isinstance(values, six.string_types): return strip_and_lowercase(values) return values def convert_request_json_into_index_json(request_json): - filter_fields = [field for field in request_json if field in FILTER_FIELDS] + index_json = {} + for field in request_json: - for field in filter_fields: - request_json["filter_" + field] = \ - process_values_for_matching(request_json, field) - if field not in TEXT_FIELDS: + if field in FILTER_FIELDS_SET: + index_json["filter_" + field] = process_values_for_matching( - del request_json[field] + request_json[field] + ) + if field in TEXT_FIELDS_SET: + index_json[field] = request_json[field] - return request_json + return index_json
Drop any unknown request fields when converting into index document
## Code Before: import six from .query_builder import FILTER_FIELDS, TEXT_FIELDS from .conversions import strip_and_lowercase def process_values_for_matching(request_json, key): values = request_json[key] if isinstance(values, list): return [strip_and_lowercase(value) for value in values] elif isinstance(values, six.string_types): return strip_and_lowercase(values) return values def convert_request_json_into_index_json(request_json): filter_fields = [field for field in request_json if field in FILTER_FIELDS] for field in filter_fields: request_json["filter_" + field] = \ process_values_for_matching(request_json, field) if field not in TEXT_FIELDS: del request_json[field] return request_json ## Instruction: Drop any unknown request fields when converting into index document ## Code After: import six from .query_builder import FILTER_FIELDS, TEXT_FIELDS from .conversions import strip_and_lowercase FILTER_FIELDS_SET = set(FILTER_FIELDS) TEXT_FIELDS_SET = set(TEXT_FIELDS) def process_values_for_matching(values): if isinstance(values, list): return [strip_and_lowercase(value) for value in values] elif isinstance(values, six.string_types): return strip_and_lowercase(values) return values def convert_request_json_into_index_json(request_json): index_json = {} for field in request_json: if field in FILTER_FIELDS_SET: index_json["filter_" + field] = process_values_for_matching( request_json[field] ) if field in TEXT_FIELDS_SET: index_json[field] = request_json[field] return index_json
# ... existing code ... FILTER_FIELDS_SET = set(FILTER_FIELDS) TEXT_FIELDS_SET = set(TEXT_FIELDS) def process_values_for_matching(values): if isinstance(values, list): # ... modified code ... def convert_request_json_into_index_json(request_json): index_json = {} for field in request_json: if field in FILTER_FIELDS_SET: index_json["filter_" + field] = process_values_for_matching( request_json[field] ) if field in TEXT_FIELDS_SET: index_json[field] = request_json[field] return index_json # ... rest of the code ...
cab360d14a6b02cc1cf4649823acd2e2c683d240
utils/swift_build_support/swift_build_support/products/swift.py
utils/swift_build_support/swift_build_support/products/swift.py
from . import product class Swift(product.Product): def __init__(self, args, toolchain, source_dir, build_dir): product.Product.__init__(self, args, toolchain, source_dir, build_dir) # Add any runtime sanitizer arguments. self.cmake_options.extend(self._compute_runtime_use_sanitizer()) def _compute_runtime_use_sanitizer(self): sanitizer_list = [] if self.args.enable_tsan_runtime: sanitizer_list += ['Thread'] if len(sanitizer_list) == 0: return [] return ["-DSWIFT_RUNTIME_USE_SANITIZERS=%s" % ";".join(sanitizer_list)]
from . import product class Swift(product.Product): def __init__(self, args, toolchain, source_dir, build_dir): product.Product.__init__(self, args, toolchain, source_dir, build_dir) # Add any runtime sanitizer arguments. self.cmake_options.extend(self._runtime_sanitizer_flags) @property def _runtime_sanitizer_flags(self): sanitizer_list = [] if self.args.enable_tsan_runtime: sanitizer_list += ['Thread'] if len(sanitizer_list) == 0: return [] return ["-DSWIFT_RUNTIME_USE_SANITIZERS=%s" % ";".join(sanitizer_list)]
Change method _compute_runtime_use_sanitizer => property _runtime_sanitizer_flags. NFC.
[vacation-gardening] Change method _compute_runtime_use_sanitizer => property _runtime_sanitizer_flags. NFC.
Python
apache-2.0
parkera/swift,huonw/swift,CodaFi/swift,parkera/swift,codestergit/swift,austinzheng/swift,bitjammer/swift,glessard/swift,djwbrown/swift,bitjammer/swift,gottesmm/swift,lorentey/swift,tkremenek/swift,OscarSwanros/swift,milseman/swift,airspeedswift/swift,arvedviehweger/swift,CodaFi/swift,IngmarStein/swift,JaSpa/swift,atrick/swift,jckarter/swift,gribozavr/swift,karwa/swift,gregomni/swift,lorentey/swift,kperryua/swift,atrick/swift,shahmishal/swift,parkera/swift,jmgc/swift,codestergit/swift,jtbandes/swift,nathawes/swift,swiftix/swift,alblue/swift,roambotics/swift,swiftix/swift,uasys/swift,jmgc/swift,natecook1000/swift,brentdax/swift,harlanhaskins/swift,aschwaighofer/swift,danielmartin/swift,harlanhaskins/swift,rudkx/swift,sschiau/swift,deyton/swift,felix91gr/swift,JGiola/swift,practicalswift/swift,milseman/swift,modocache/swift,austinzheng/swift,roambotics/swift,IngmarStein/swift,danielmartin/swift,tkremenek/swift,danielmartin/swift,hughbe/swift,shahmishal/swift,amraboelela/swift,jopamer/swift,tinysun212/swift-windows,JGiola/swift,therealbnut/swift,lorentey/swift,jtbandes/swift,gribozavr/swift,arvedviehweger/swift,brentdax/swift,manavgabhawala/swift,alblue/swift,practicalswift/swift,kstaring/swift,amraboelela/swift,milseman/swift,harlanhaskins/swift,felix91gr/swift,OscarSwanros/swift,return/swift,ben-ng/swift,alblue/swift,gregomni/swift,sschiau/swift,practicalswift/swift,gottesmm/swift,JGiola/swift,harlanhaskins/swift,huonw/swift,bitjammer/swift,uasys/swift,calebd/swift,JaSpa/swift,kperryua/swift,bitjammer/swift,gregomni/swift,return/swift,jopamer/swift,shajrawi/swift,codestergit/swift,uasys/swift,devincoughlin/swift,Jnosh/swift,xedin/swift,rudkx/swift,benlangmuir/swift,stephentyrone/swift,apple/swift,nathawes/swift,frootloops/swift,ahoppen/swift,xwu/swift,therealbnut/swift,sschiau/swift,codestergit/swift,arvedviehweger/swift,allevato/swift,tjw/swift,calebd/swift,kstaring/swift,deyton/swift,benlangmuir/swift,bitjammer/swift,tardieu/swift,jtbandes/swift,alblue/swift,return/swift,jtbandes/swift,jopamer/swift,jckarter/swift,shahmishal/swift,djwbrown/swift,milseman/swift,natecook1000/swift,benlangmuir/swift,gmilos/swift,JaSpa/swift,karwa/swift,frootloops/swift,austinzheng/swift,manavgabhawala/swift,return/swift,jtbandes/swift,practicalswift/swift,shajrawi/swift,gottesmm/swift,frootloops/swift,practicalswift/swift,JGiola/swift,felix91gr/swift,kstaring/swift,glessard/swift,zisko/swift,nathawes/swift,danielmartin/swift,natecook1000/swift,swiftix/swift,djwbrown/swift,zisko/swift,codestergit/swift,sschiau/swift,CodaFi/swift,alblue/swift,allevato/swift,allevato/swift,stephentyrone/swift,hooman/swift,tkremenek/swift,rudkx/swift,hughbe/swift,austinzheng/swift,huonw/swift,shahmishal/swift,tinysun212/swift-windows,parkera/swift,arvedviehweger/swift,ahoppen/swift,tinysun212/swift-windows,milseman/swift,tjw/swift,kstaring/swift,xwu/swift,xwu/swift,codestergit/swift,tkremenek/swift,IngmarStein/swift,return/swift,swiftix/swift,frootloops/swift,modocache/swift,jtbandes/swift,tkremenek/swift,devincoughlin/swift,gribozavr/swift,jckarter/swift,atrick/swift,shajrawi/swift,deyton/swift,ben-ng/swift,calebd/swift,jckarter/swift,brentdax/swift,tardieu/swift,austinzheng/swift,parkera/swift,modocache/swift,ben-ng/swift,stephentyrone/swift,CodaFi/swift,JGiola/swift,xwu/swift,zisko/swift,tardieu/swift,OscarSwanros/swift,austinzheng/swift,OscarSwanros/swift,xwu/swift,shahmishal/swift,allevato/swift,huonw/swift,therealbnut/swift,tardieu/swift,sschiau/swift,ben-ng/swift,brentdax/swift,kperryua/swift,brentdax/swift,modocache/swift,shahmishal/swift,brentdax/swift,devincoughlin/swift,manavgabhawala/swift,calebd/swift,manavgabhawala/swift,kperryua/swift,hughbe/swift,nathawes/swift,airspeedswift/swift,austinzheng/swift,codestergit/swift,nathawes/swift,jopamer/swift,gribozavr/swift,kperryua/swift,gmilos/swift,xedin/swift,glessard/swift,tinysun212/swift-windows,ben-ng/swift,practicalswift/swift,ahoppen/swift,gottesmm/swift,kperryua/swift,airspeedswift/swift,aschwaighofer/swift,calebd/swift,Jnosh/swift,tkremenek/swift,xwu/swift,djwbrown/swift,roambotics/swift,gribozavr/swift,allevato/swift,xedin/swift,xwu/swift,benlangmuir/swift,gottesmm/swift,tkremenek/swift,brentdax/swift,OscarSwanros/swift,frootloops/swift,gottesmm/swift,Jnosh/swift,sschiau/swift,harlanhaskins/swift,CodaFi/swift,zisko/swift,therealbnut/swift,IngmarStein/swift,jckarter/swift,return/swift,deyton/swift,atrick/swift,parkera/swift,parkera/swift,therealbnut/swift,stephentyrone/swift,apple/swift,JaSpa/swift,uasys/swift,karwa/swift,JaSpa/swift,hooman/swift,tjw/swift,lorentey/swift,OscarSwanros/swift,shajrawi/swift,tinysun212/swift-windows,aschwaighofer/swift,apple/swift,devincoughlin/swift,natecook1000/swift,allevato/swift,natecook1000/swift,roambotics/swift,devincoughlin/swift,gmilos/swift,arvedviehweger/swift,danielmartin/swift,kperryua/swift,aschwaighofer/swift,lorentey/swift,lorentey/swift,amraboelela/swift,natecook1000/swift,return/swift,bitjammer/swift,aschwaighofer/swift,uasys/swift,xedin/swift,karwa/swift,gmilos/swift,kstaring/swift,gribozavr/swift,harlanhaskins/swift,deyton/swift,frootloops/swift,jckarter/swift,sschiau/swift,hooman/swift,xedin/swift,apple/swift,milseman/swift,glessard/swift,CodaFi/swift,felix91gr/swift,hooman/swift,harlanhaskins/swift,felix91gr/swift,gribozavr/swift,amraboelela/swift,karwa/swift,jmgc/swift,Jnosh/swift,gribozavr/swift,ben-ng/swift,jtbandes/swift,alblue/swift,tjw/swift,CodaFi/swift,benlangmuir/swift,devincoughlin/swift,swiftix/swift,gregomni/swift,lorentey/swift,ahoppen/swift,nathawes/swift,airspeedswift/swift,kstaring/swift,rudkx/swift,shajrawi/swift,OscarSwanros/swift,tinysun212/swift-windows,danielmartin/swift,huonw/swift,huonw/swift,manavgabhawala/swift,jopamer/swift,ahoppen/swift,Jnosh/swift,karwa/swift,shajrawi/swift,jmgc/swift,aschwaighofer/swift,sschiau/swift,alblue/swift,tardieu/swift,gmilos/swift,airspeedswift/swift,airspeedswift/swift,xedin/swift,felix91gr/swift,tjw/swift,xedin/swift,ben-ng/swift,aschwaighofer/swift,gottesmm/swift,frootloops/swift,gmilos/swift,calebd/swift,Jnosh/swift,stephentyrone/swift,apple/swift,zisko/swift,IngmarStein/swift,stephentyrone/swift,jmgc/swift,swiftix/swift,JGiola/swift,tardieu/swift,lorentey/swift,shahmishal/swift,djwbrown/swift,tardieu/swift,felix91gr/swift,JaSpa/swift,arvedviehweger/swift,jopamer/swift,manavgabhawala/swift,jopamer/swift,nathawes/swift,atrick/swift,tjw/swift,natecook1000/swift,Jnosh/swift,karwa/swift,modocache/swift,ahoppen/swift,uasys/swift,rudkx/swift,parkera/swift,modocache/swift,shahmishal/swift,allevato/swift,jmgc/swift,xedin/swift,jckarter/swift,stephentyrone/swift,danielmartin/swift,hughbe/swift,hooman/swift,airspeedswift/swift,swiftix/swift,practicalswift/swift,deyton/swift,gmilos/swift,devincoughlin/swift,arvedviehweger/swift,roambotics/swift,JaSpa/swift,gregomni/swift,kstaring/swift,glessard/swift,shajrawi/swift,roambotics/swift,milseman/swift,atrick/swift,amraboelela/swift,manavgabhawala/swift,hooman/swift,hughbe/swift,therealbnut/swift,huonw/swift,hughbe/swift,bitjammer/swift,therealbnut/swift,apple/swift,amraboelela/swift,devincoughlin/swift,rudkx/swift,modocache/swift,djwbrown/swift,glessard/swift,karwa/swift,uasys/swift,hooman/swift,gregomni/swift,benlangmuir/swift,hughbe/swift,shajrawi/swift,djwbrown/swift,tinysun212/swift-windows,IngmarStein/swift,amraboelela/swift,zisko/swift,deyton/swift,calebd/swift,jmgc/swift,zisko/swift,practicalswift/swift,IngmarStein/swift,tjw/swift
from . import product class Swift(product.Product): def __init__(self, args, toolchain, source_dir, build_dir): product.Product.__init__(self, args, toolchain, source_dir, build_dir) # Add any runtime sanitizer arguments. - self.cmake_options.extend(self._compute_runtime_use_sanitizer()) + self.cmake_options.extend(self._runtime_sanitizer_flags) + @property - def _compute_runtime_use_sanitizer(self): + def _runtime_sanitizer_flags(self): sanitizer_list = [] if self.args.enable_tsan_runtime: sanitizer_list += ['Thread'] if len(sanitizer_list) == 0: return [] return ["-DSWIFT_RUNTIME_USE_SANITIZERS=%s" % ";".join(sanitizer_list)]
Change method _compute_runtime_use_sanitizer => property _runtime_sanitizer_flags. NFC.
## Code Before: from . import product class Swift(product.Product): def __init__(self, args, toolchain, source_dir, build_dir): product.Product.__init__(self, args, toolchain, source_dir, build_dir) # Add any runtime sanitizer arguments. self.cmake_options.extend(self._compute_runtime_use_sanitizer()) def _compute_runtime_use_sanitizer(self): sanitizer_list = [] if self.args.enable_tsan_runtime: sanitizer_list += ['Thread'] if len(sanitizer_list) == 0: return [] return ["-DSWIFT_RUNTIME_USE_SANITIZERS=%s" % ";".join(sanitizer_list)] ## Instruction: Change method _compute_runtime_use_sanitizer => property _runtime_sanitizer_flags. NFC. ## Code After: from . import product class Swift(product.Product): def __init__(self, args, toolchain, source_dir, build_dir): product.Product.__init__(self, args, toolchain, source_dir, build_dir) # Add any runtime sanitizer arguments. self.cmake_options.extend(self._runtime_sanitizer_flags) @property def _runtime_sanitizer_flags(self): sanitizer_list = [] if self.args.enable_tsan_runtime: sanitizer_list += ['Thread'] if len(sanitizer_list) == 0: return [] return ["-DSWIFT_RUNTIME_USE_SANITIZERS=%s" % ";".join(sanitizer_list)]
// ... existing code ... # Add any runtime sanitizer arguments. self.cmake_options.extend(self._runtime_sanitizer_flags) @property def _runtime_sanitizer_flags(self): sanitizer_list = [] // ... rest of the code ...
2f1d32ba80816e3880a464a63d8f3f549a2be9e2
tests/__init__.py
tests/__init__.py
import os try: # 2.7 # pylint: disable = E0611,F0401 from unittest.case import SkipTest # pylint: enable = E0611,F0401 except ImportError: try: # Nose from nose.plugins.skip import SkipTest except ImportError: # Failsafe class SkipTest(Exception): pass from mopidy import settings # Nuke any local settings to ensure same test env all over settings.local.clear() def path_to_data_dir(name): path = os.path.dirname(__file__) path = os.path.join(path, 'data') path = os.path.abspath(path) return os.path.join(path, name)
import os try: # 2.7 # pylint: disable = E0611,F0401 from unittest.case import SkipTest # pylint: enable = E0611,F0401 except ImportError: try: # Nose from nose.plugins.skip import SkipTest except ImportError: # Failsafe class SkipTest(Exception): pass from mopidy import settings # Nuke any local settings to ensure same test env all over settings.local.clear() def path_to_data_dir(name): path = os.path.dirname(__file__) path = os.path.join(path, 'data') path = os.path.abspath(path) return os.path.join(path, name) class IsA(object): def __init__(self, klass): self.klass = klass def __eq__(self, rhs): try: return isinstance(rhs, self.klass) except TypeError: return type(rhs) == type(self.klass) def __ne__(self, rhs): return not self.__eq__(rhs) def __repr__(self): return str(self.klass) any_int = IsA(int) any_str = IsA(str) any_unicode = IsA(unicode)
Add IsA helper to tests to provde any_int, any_str and any_unicode
Add IsA helper to tests to provde any_int, any_str and any_unicode
Python
apache-2.0
bencevans/mopidy,diandiankan/mopidy,ZenithDK/mopidy,vrs01/mopidy,liamw9534/mopidy,dbrgn/mopidy,swak/mopidy,jodal/mopidy,SuperStarPL/mopidy,jmarsik/mopidy,bacontext/mopidy,woutervanwijk/mopidy,ali/mopidy,pacificIT/mopidy,woutervanwijk/mopidy,quartz55/mopidy,jmarsik/mopidy,dbrgn/mopidy,mokieyue/mopidy,bencevans/mopidy,mokieyue/mopidy,glogiotatidis/mopidy,adamcik/mopidy,hkariti/mopidy,tkem/mopidy,kingosticks/mopidy,rawdlite/mopidy,jodal/mopidy,mopidy/mopidy,adamcik/mopidy,jcass77/mopidy,jmarsik/mopidy,abarisain/mopidy,rawdlite/mopidy,mopidy/mopidy,swak/mopidy,jmarsik/mopidy,quartz55/mopidy,bencevans/mopidy,priestd09/mopidy,tkem/mopidy,SuperStarPL/mopidy,glogiotatidis/mopidy,glogiotatidis/mopidy,ali/mopidy,hkariti/mopidy,glogiotatidis/mopidy,pacificIT/mopidy,rawdlite/mopidy,ali/mopidy,priestd09/mopidy,kingosticks/mopidy,priestd09/mopidy,vrs01/mopidy,ZenithDK/mopidy,SuperStarPL/mopidy,pacificIT/mopidy,bacontext/mopidy,adamcik/mopidy,jcass77/mopidy,swak/mopidy,liamw9534/mopidy,vrs01/mopidy,ZenithDK/mopidy,mokieyue/mopidy,quartz55/mopidy,dbrgn/mopidy,jodal/mopidy,quartz55/mopidy,vrs01/mopidy,hkariti/mopidy,bacontext/mopidy,diandiankan/mopidy,bacontext/mopidy,abarisain/mopidy,kingosticks/mopidy,ZenithDK/mopidy,diandiankan/mopidy,diandiankan/mopidy,SuperStarPL/mopidy,tkem/mopidy,rawdlite/mopidy,hkariti/mopidy,jcass77/mopidy,dbrgn/mopidy,bencevans/mopidy,pacificIT/mopidy,mopidy/mopidy,tkem/mopidy,mokieyue/mopidy,ali/mopidy,swak/mopidy
import os try: # 2.7 # pylint: disable = E0611,F0401 from unittest.case import SkipTest # pylint: enable = E0611,F0401 except ImportError: try: # Nose from nose.plugins.skip import SkipTest except ImportError: # Failsafe class SkipTest(Exception): pass from mopidy import settings # Nuke any local settings to ensure same test env all over settings.local.clear() def path_to_data_dir(name): path = os.path.dirname(__file__) path = os.path.join(path, 'data') path = os.path.abspath(path) return os.path.join(path, name) + class IsA(object): + def __init__(self, klass): + self.klass = klass + def __eq__(self, rhs): + try: + return isinstance(rhs, self.klass) + except TypeError: + return type(rhs) == type(self.klass) + + def __ne__(self, rhs): + return not self.__eq__(rhs) + + def __repr__(self): + return str(self.klass) + + any_int = IsA(int) + any_str = IsA(str) + any_unicode = IsA(unicode) +
Add IsA helper to tests to provde any_int, any_str and any_unicode
## Code Before: import os try: # 2.7 # pylint: disable = E0611,F0401 from unittest.case import SkipTest # pylint: enable = E0611,F0401 except ImportError: try: # Nose from nose.plugins.skip import SkipTest except ImportError: # Failsafe class SkipTest(Exception): pass from mopidy import settings # Nuke any local settings to ensure same test env all over settings.local.clear() def path_to_data_dir(name): path = os.path.dirname(__file__) path = os.path.join(path, 'data') path = os.path.abspath(path) return os.path.join(path, name) ## Instruction: Add IsA helper to tests to provde any_int, any_str and any_unicode ## Code After: import os try: # 2.7 # pylint: disable = E0611,F0401 from unittest.case import SkipTest # pylint: enable = E0611,F0401 except ImportError: try: # Nose from nose.plugins.skip import SkipTest except ImportError: # Failsafe class SkipTest(Exception): pass from mopidy import settings # Nuke any local settings to ensure same test env all over settings.local.clear() def path_to_data_dir(name): path = os.path.dirname(__file__) path = os.path.join(path, 'data') path = os.path.abspath(path) return os.path.join(path, name) class IsA(object): def __init__(self, klass): self.klass = klass def __eq__(self, rhs): try: return isinstance(rhs, self.klass) except TypeError: return type(rhs) == type(self.klass) def __ne__(self, rhs): return not self.__eq__(rhs) def __repr__(self): return str(self.klass) any_int = IsA(int) any_str = IsA(str) any_unicode = IsA(unicode)
// ... existing code ... class IsA(object): def __init__(self, klass): self.klass = klass def __eq__(self, rhs): try: return isinstance(rhs, self.klass) except TypeError: return type(rhs) == type(self.klass) def __ne__(self, rhs): return not self.__eq__(rhs) def __repr__(self): return str(self.klass) any_int = IsA(int) any_str = IsA(str) any_unicode = IsA(unicode) // ... rest of the code ...
f87bab8a808e4bda3b3b7482633eaca069682b9e
build.py
build.py
import sys from cx_Freeze import setup, Executable base = None if sys.platform == "win32": base = "Win32GUI" executables = [ Executable('blockcheck.py', base=base) ] setup(name='blockcheck', version='0.1', description='BlockCheck', executables=executables, options = {'build_exe': {'init_script':'Console', 'compressed':'1'}}, )
import sys from cx_Freeze import setup, Executable base = None if sys.platform == "win32": base = "Win32GUI" executables = [ Executable('blockcheck.py', base=base) ] setup(name='blockcheck', version='0.0.5', description='BlockCheck', executables=executables, options = {'build_exe': {'init_script':'Console', 'compressed':'1', 'packages':'dns'}}, )
Include all the files from dns module and bump version
Include all the files from dns module and bump version
Python
mit
Acharvak/blockcheck,Renji/blockcheck,ValdikSS/blockcheck
import sys from cx_Freeze import setup, Executable base = None if sys.platform == "win32": base = "Win32GUI" executables = [ Executable('blockcheck.py', base=base) ] setup(name='blockcheck', - version='0.1', + version='0.0.5', description='BlockCheck', executables=executables, - options = {'build_exe': {'init_script':'Console', 'compressed':'1'}}, + options = {'build_exe': {'init_script':'Console', 'compressed':'1', 'packages':'dns'}}, ) +
Include all the files from dns module and bump version
## Code Before: import sys from cx_Freeze import setup, Executable base = None if sys.platform == "win32": base = "Win32GUI" executables = [ Executable('blockcheck.py', base=base) ] setup(name='blockcheck', version='0.1', description='BlockCheck', executables=executables, options = {'build_exe': {'init_script':'Console', 'compressed':'1'}}, ) ## Instruction: Include all the files from dns module and bump version ## Code After: import sys from cx_Freeze import setup, Executable base = None if sys.platform == "win32": base = "Win32GUI" executables = [ Executable('blockcheck.py', base=base) ] setup(name='blockcheck', version='0.0.5', description='BlockCheck', executables=executables, options = {'build_exe': {'init_script':'Console', 'compressed':'1', 'packages':'dns'}}, )
... setup(name='blockcheck', version='0.0.5', description='BlockCheck', ... executables=executables, options = {'build_exe': {'init_script':'Console', 'compressed':'1', 'packages':'dns'}}, ) ...
afbb9a9be46c6a9db02f6f3256c82b9939ce5c9e
src/rna_seq/forms.py
src/rna_seq/forms.py
from crispy_forms.bootstrap import FormActions from crispy_forms.helper import FormHelper from crispy_forms.layout import Div, Field, Fieldset, HTML, Layout, Submit from django.utils.functional import cached_property from django.utils.translation import ugettext_lazy as _ from analyses.forms import AbstractAnalysisCreateForm, AnalysisCommonLayout from .models import RNASeqModel class RNASeqCreateForm(AbstractAnalysisCreateForm): class Meta(AbstractAnalysisCreateForm.Meta): model = RNASeqModel fields = ( *AbstractAnalysisCreateForm.Meta.fields, 'quality_check', 'trim_adapter', 'rm_duplicate', ) widgets = { **AbstractAnalysisCreateForm.Meta.widgets, } @cached_property def helper(self): helper = FormHelper() helper.layout = Layout( AnalysisCommonLayout(analysis_type="RNA-Seq"), Fieldset( 'Quality Check', HTML( "<p>Examine and process the quality of the sequencing " "reads.</p>" ), Field('quality_check'), Field('trim_adapter'), Field('rm_duplicate'), ), FormActions( Submit( 'save', _('Create New Analysis'), css_class='btn-lg', ) ) ) helper.include_media = False return helper
from crispy_forms.helper import FormHelper from crispy_forms.bootstrap import InlineField from crispy_forms.layout import Div, Field, Fieldset, HTML, Layout from django.utils.functional import cached_property from django.utils.translation import ugettext_lazy as _ from analyses.forms import ( AbstractAnalysisCreateForm, AnalysisCommonLayout, AnalysisFormActions, Include, ) from .models import RNASeqModel class RNASeqCreateForm(AbstractAnalysisCreateForm): class Meta(AbstractAnalysisCreateForm.Meta): model = RNASeqModel fields = '__all__' widgets = { **AbstractAnalysisCreateForm.Meta.widgets, } @cached_property def helper(self): helper = super().helper helper.layout = Layout( AnalysisCommonLayout(analysis_type="RNA-Seq"), Fieldset( 'Quality Check', HTML( "<p>Examine and process the quality of the sequencing " "reads.</p>" ), Field('quality_check'), Field('trim_adapter'), Field('rm_duplicate'), ), AnalysisFormActions(), ) return helper
Use analysis base class form helper and form building blocks
Use analysis base class form helper and form building blocks
Python
mit
ccwang002/biocloud-server-kai,ccwang002/biocloud-server-kai,ccwang002/biocloud-server-kai
- from crispy_forms.bootstrap import FormActions from crispy_forms.helper import FormHelper + from crispy_forms.bootstrap import InlineField - from crispy_forms.layout import Div, Field, Fieldset, HTML, Layout, Submit + from crispy_forms.layout import Div, Field, Fieldset, HTML, Layout from django.utils.functional import cached_property from django.utils.translation import ugettext_lazy as _ - from analyses.forms import AbstractAnalysisCreateForm, AnalysisCommonLayout + from analyses.forms import ( + AbstractAnalysisCreateForm, + AnalysisCommonLayout, + AnalysisFormActions, + Include, + ) from .models import RNASeqModel class RNASeqCreateForm(AbstractAnalysisCreateForm): class Meta(AbstractAnalysisCreateForm.Meta): model = RNASeqModel - fields = ( + fields = '__all__' - *AbstractAnalysisCreateForm.Meta.fields, - 'quality_check', 'trim_adapter', 'rm_duplicate', - ) widgets = { **AbstractAnalysisCreateForm.Meta.widgets, } @cached_property def helper(self): - helper = FormHelper() + helper = super().helper helper.layout = Layout( AnalysisCommonLayout(analysis_type="RNA-Seq"), Fieldset( 'Quality Check', HTML( "<p>Examine and process the quality of the sequencing " "reads.</p>" ), Field('quality_check'), Field('trim_adapter'), Field('rm_duplicate'), ), - FormActions( + AnalysisFormActions(), - Submit( - 'save', _('Create New Analysis'), css_class='btn-lg', - ) - ) ) - helper.include_media = False return helper
Use analysis base class form helper and form building blocks
## Code Before: from crispy_forms.bootstrap import FormActions from crispy_forms.helper import FormHelper from crispy_forms.layout import Div, Field, Fieldset, HTML, Layout, Submit from django.utils.functional import cached_property from django.utils.translation import ugettext_lazy as _ from analyses.forms import AbstractAnalysisCreateForm, AnalysisCommonLayout from .models import RNASeqModel class RNASeqCreateForm(AbstractAnalysisCreateForm): class Meta(AbstractAnalysisCreateForm.Meta): model = RNASeqModel fields = ( *AbstractAnalysisCreateForm.Meta.fields, 'quality_check', 'trim_adapter', 'rm_duplicate', ) widgets = { **AbstractAnalysisCreateForm.Meta.widgets, } @cached_property def helper(self): helper = FormHelper() helper.layout = Layout( AnalysisCommonLayout(analysis_type="RNA-Seq"), Fieldset( 'Quality Check', HTML( "<p>Examine and process the quality of the sequencing " "reads.</p>" ), Field('quality_check'), Field('trim_adapter'), Field('rm_duplicate'), ), FormActions( Submit( 'save', _('Create New Analysis'), css_class='btn-lg', ) ) ) helper.include_media = False return helper ## Instruction: Use analysis base class form helper and form building blocks ## Code After: from crispy_forms.helper import FormHelper from crispy_forms.bootstrap import InlineField from crispy_forms.layout import Div, Field, Fieldset, HTML, Layout from django.utils.functional import cached_property from django.utils.translation import ugettext_lazy as _ from analyses.forms import ( AbstractAnalysisCreateForm, AnalysisCommonLayout, AnalysisFormActions, Include, ) from .models import RNASeqModel class RNASeqCreateForm(AbstractAnalysisCreateForm): class Meta(AbstractAnalysisCreateForm.Meta): model = RNASeqModel fields = '__all__' widgets = { **AbstractAnalysisCreateForm.Meta.widgets, } @cached_property def helper(self): helper = super().helper helper.layout = Layout( AnalysisCommonLayout(analysis_type="RNA-Seq"), Fieldset( 'Quality Check', HTML( "<p>Examine and process the quality of the sequencing " "reads.</p>" ), Field('quality_check'), Field('trim_adapter'), Field('rm_duplicate'), ), AnalysisFormActions(), ) return helper
# ... existing code ... from crispy_forms.helper import FormHelper from crispy_forms.bootstrap import InlineField from crispy_forms.layout import Div, Field, Fieldset, HTML, Layout from django.utils.functional import cached_property # ... modified code ... from analyses.forms import ( AbstractAnalysisCreateForm, AnalysisCommonLayout, AnalysisFormActions, Include, ) from .models import RNASeqModel ... model = RNASeqModel fields = '__all__' widgets = { ... def helper(self): helper = super().helper helper.layout = Layout( ... ), AnalysisFormActions(), ) return helper # ... rest of the code ...
e1d527d0676fd0b3a7a1f7b5e9b98ddc23a41cd6
storage_service/locations/tests/test_fixity_log.py
storage_service/locations/tests/test_fixity_log.py
from django.test import TestCase from locations import models class TestFixityLog(TestCase): fixtures = ['base.json', 'fixity_log.json'] def setUp(self): self.fl_object = models.FixityLog.objects.all()[0] #self.auth = requests.auth.HTTPBasicAuth(self.ds_object.user, self.ds_object.password) def test_has_required_attributes(self): assert self.fl_object.package assert self.fl_object.success assert self.fl_object.error_details assert self.fl_object.datetime_reported
from django.test import TestCase from locations import models class TestFixityLog(TestCase): fixtures = ['base.json', 'package.json', 'fixity_log.json'] def setUp(self): self.fl_object = models.FixityLog.objects.all()[0] #self.auth = requests.auth.HTTPBasicAuth(self.ds_object.user, self.ds_object.password) def test_has_required_attributes(self): assert self.fl_object.package assert self.fl_object.success assert self.fl_object.error_details assert self.fl_object.datetime_reported
Fix to storage service test.
Fix to storage service test.
Python
agpl-3.0
artefactual/archivematica-storage-service,artefactual/archivematica-storage-service,artefactual/archivematica-storage-service,artefactual/archivematica-storage-service
from django.test import TestCase from locations import models class TestFixityLog(TestCase): - fixtures = ['base.json', 'fixity_log.json'] + fixtures = ['base.json', 'package.json', 'fixity_log.json'] def setUp(self): self.fl_object = models.FixityLog.objects.all()[0] #self.auth = requests.auth.HTTPBasicAuth(self.ds_object.user, self.ds_object.password) def test_has_required_attributes(self): assert self.fl_object.package assert self.fl_object.success assert self.fl_object.error_details assert self.fl_object.datetime_reported
Fix to storage service test.
## Code Before: from django.test import TestCase from locations import models class TestFixityLog(TestCase): fixtures = ['base.json', 'fixity_log.json'] def setUp(self): self.fl_object = models.FixityLog.objects.all()[0] #self.auth = requests.auth.HTTPBasicAuth(self.ds_object.user, self.ds_object.password) def test_has_required_attributes(self): assert self.fl_object.package assert self.fl_object.success assert self.fl_object.error_details assert self.fl_object.datetime_reported ## Instruction: Fix to storage service test. ## Code After: from django.test import TestCase from locations import models class TestFixityLog(TestCase): fixtures = ['base.json', 'package.json', 'fixity_log.json'] def setUp(self): self.fl_object = models.FixityLog.objects.all()[0] #self.auth = requests.auth.HTTPBasicAuth(self.ds_object.user, self.ds_object.password) def test_has_required_attributes(self): assert self.fl_object.package assert self.fl_object.success assert self.fl_object.error_details assert self.fl_object.datetime_reported
... fixtures = ['base.json', 'package.json', 'fixity_log.json'] ...
c08013dc2fc32582e8636d84be3e2f68dafe11a0
controller.py
controller.py
"""NM-Controller accounts are used to provide secure access to the XMLRPC API. They are normal Unix accounts with a shell that tunnels XMLRPC requests to the API server.""" import accounts import logger import tools class Controller(accounts.Account): SHELL = '/usr/bin/forward_api_calls' # tunneling shell TYPE = 'controller' @staticmethod def create(name, vref = None): add_shell(Delegate.SHELL) logger.log_call('/usr/sbin/useradd', '-p', '*', '-s', Delegate.SHELL, name) @staticmethod def destroy(name): logger.log_call('/usr/sbin/userdel', '-r', name) def add_shell(shell): """Add <shell> to /etc/shells if it's not already there.""" etc_shells = open('/etc/shells') valid_shells = etc_shells.read().split() etc_shells.close() if shell not in valid_shells: etc_shells = open('/etc/shells', 'a') print >>etc_shells, shell etc_shells.close()
"""NM-Controller accounts are used to provide secure access to the XMLRPC API. They are normal Unix accounts with a shell that tunnels XMLRPC requests to the API server.""" import accounts import logger import tools class Controller(accounts.Account): SHELL = '/usr/bin/forward_api_calls' # tunneling shell TYPE = 'controller' @staticmethod def create(name, vref = None): add_shell(Controller.SHELL) logger.log_call('/usr/sbin/useradd', '-p', '*', '-s', Controller.SHELL, name) @staticmethod def destroy(name): logger.log_call('/usr/sbin/userdel', '-r', name) def add_shell(shell): """Add <shell> to /etc/shells if it's not already there.""" etc_shells = open('/etc/shells') valid_shells = etc_shells.read().split() etc_shells.close() if shell not in valid_shells: etc_shells = open('/etc/shells', 'a') print >>etc_shells, shell etc_shells.close()
Change to Controller from Delegate shell
Change to Controller from Delegate shell
Python
bsd-3-clause
dreibh/planetlab-lxc-nodemanager,planetlab/NodeManager,planetlab/NodeManager,planetlab/NodeManager,dreibh/planetlab-lxc-nodemanager,planetlab/NodeManager,dreibh/planetlab-lxc-nodemanager
"""NM-Controller accounts are used to provide secure access to the XMLRPC API. They are normal Unix accounts with a shell that tunnels XMLRPC requests to the API server.""" import accounts import logger import tools class Controller(accounts.Account): SHELL = '/usr/bin/forward_api_calls' # tunneling shell TYPE = 'controller' @staticmethod def create(name, vref = None): - add_shell(Delegate.SHELL) + add_shell(Controller.SHELL) - logger.log_call('/usr/sbin/useradd', '-p', '*', '-s', Delegate.SHELL, name) + logger.log_call('/usr/sbin/useradd', '-p', '*', '-s', Controller.SHELL, name) @staticmethod def destroy(name): logger.log_call('/usr/sbin/userdel', '-r', name) def add_shell(shell): """Add <shell> to /etc/shells if it's not already there.""" etc_shells = open('/etc/shells') valid_shells = etc_shells.read().split() etc_shells.close() if shell not in valid_shells: etc_shells = open('/etc/shells', 'a') print >>etc_shells, shell etc_shells.close()
Change to Controller from Delegate shell
## Code Before: """NM-Controller accounts are used to provide secure access to the XMLRPC API. They are normal Unix accounts with a shell that tunnels XMLRPC requests to the API server.""" import accounts import logger import tools class Controller(accounts.Account): SHELL = '/usr/bin/forward_api_calls' # tunneling shell TYPE = 'controller' @staticmethod def create(name, vref = None): add_shell(Delegate.SHELL) logger.log_call('/usr/sbin/useradd', '-p', '*', '-s', Delegate.SHELL, name) @staticmethod def destroy(name): logger.log_call('/usr/sbin/userdel', '-r', name) def add_shell(shell): """Add <shell> to /etc/shells if it's not already there.""" etc_shells = open('/etc/shells') valid_shells = etc_shells.read().split() etc_shells.close() if shell not in valid_shells: etc_shells = open('/etc/shells', 'a') print >>etc_shells, shell etc_shells.close() ## Instruction: Change to Controller from Delegate shell ## Code After: """NM-Controller accounts are used to provide secure access to the XMLRPC API. They are normal Unix accounts with a shell that tunnels XMLRPC requests to the API server.""" import accounts import logger import tools class Controller(accounts.Account): SHELL = '/usr/bin/forward_api_calls' # tunneling shell TYPE = 'controller' @staticmethod def create(name, vref = None): add_shell(Controller.SHELL) logger.log_call('/usr/sbin/useradd', '-p', '*', '-s', Controller.SHELL, name) @staticmethod def destroy(name): logger.log_call('/usr/sbin/userdel', '-r', name) def add_shell(shell): """Add <shell> to /etc/shells if it's not already there.""" etc_shells = open('/etc/shells') valid_shells = etc_shells.read().split() etc_shells.close() if shell not in valid_shells: etc_shells = open('/etc/shells', 'a') print >>etc_shells, shell etc_shells.close()
... def create(name, vref = None): add_shell(Controller.SHELL) logger.log_call('/usr/sbin/useradd', '-p', '*', '-s', Controller.SHELL, name) ...
a5130e32bffa1dbc4d83f349fc3653b690154d71
vumi/workers/vas2nets/workers.py
vumi/workers/vas2nets/workers.py
from twisted.python import log from twisted.internet.defer import inlineCallbacks, Deferred from vumi.message import Message from vumi.service import Worker class EchoWorker(Worker): @inlineCallbacks def startWorker(self): """called by the Worker class when the AMQP connections been established""" self.publisher = yield self.publish_to('sms.outbound.%(transport_name)s' % self.config) self.consumer = yield self.consume('sms.inbound.%(transport_name)s.%(shortcode)s' % self.config, self.handle_inbound_message) def handle_inbound_message(self, message): log.msg("Received: %s" % (message.payload,)) """Reply to the message with the same content""" data = message.payload reply = { 'to_msisdn': data['from_msisdn'], 'from_msisdn': data['to_msisdn'], 'message': data['message'], 'id': data['transport_message_id'], 'transport_network_id': data['transport_network_id'], } return self.publisher.publish_message(Message(**reply)) def stopWorker(self): """shutdown""" pass
from twisted.python import log from twisted.internet.defer import inlineCallbacks, Deferred from vumi.message import Message from vumi.service import Worker class EchoWorker(Worker): @inlineCallbacks def startWorker(self): """called by the Worker class when the AMQP connections been established""" self.publisher = yield self.publish_to('sms.outbound.%(transport_name)s' % self.config) self.consumer = yield self.consume('sms.inbound.%(transport_name)s.%(shortcode)s' % self.config, self.handle_inbound_message) def handle_inbound_message(self, message): log.msg("Received: %s" % (message.payload,)) """Reply to the message with the same content""" data = message.payload reply = { 'to_msisdn': data['from_msisdn'], 'from_msisdn': data['to_msisdn'], 'message': data['message'], 'id': data['transport_message_id'], 'transport_network_id': data['transport_network_id'], 'transport_keyword': data['transport_keyword'], } return self.publisher.publish_message(Message(**reply)) def stopWorker(self): """shutdown""" pass
Add keyword to echo worker.
Add keyword to echo worker.
Python
bsd-3-clause
TouK/vumi,vishwaprakashmishra/xmatrix,harrissoerja/vumi,TouK/vumi,vishwaprakashmishra/xmatrix,harrissoerja/vumi,vishwaprakashmishra/xmatrix,harrissoerja/vumi,TouK/vumi
from twisted.python import log from twisted.internet.defer import inlineCallbacks, Deferred from vumi.message import Message from vumi.service import Worker class EchoWorker(Worker): @inlineCallbacks def startWorker(self): """called by the Worker class when the AMQP connections been established""" self.publisher = yield self.publish_to('sms.outbound.%(transport_name)s' % self.config) self.consumer = yield self.consume('sms.inbound.%(transport_name)s.%(shortcode)s' % self.config, self.handle_inbound_message) def handle_inbound_message(self, message): log.msg("Received: %s" % (message.payload,)) """Reply to the message with the same content""" data = message.payload reply = { 'to_msisdn': data['from_msisdn'], 'from_msisdn': data['to_msisdn'], 'message': data['message'], 'id': data['transport_message_id'], 'transport_network_id': data['transport_network_id'], + 'transport_keyword': data['transport_keyword'], } return self.publisher.publish_message(Message(**reply)) def stopWorker(self): """shutdown""" pass
Add keyword to echo worker.
## Code Before: from twisted.python import log from twisted.internet.defer import inlineCallbacks, Deferred from vumi.message import Message from vumi.service import Worker class EchoWorker(Worker): @inlineCallbacks def startWorker(self): """called by the Worker class when the AMQP connections been established""" self.publisher = yield self.publish_to('sms.outbound.%(transport_name)s' % self.config) self.consumer = yield self.consume('sms.inbound.%(transport_name)s.%(shortcode)s' % self.config, self.handle_inbound_message) def handle_inbound_message(self, message): log.msg("Received: %s" % (message.payload,)) """Reply to the message with the same content""" data = message.payload reply = { 'to_msisdn': data['from_msisdn'], 'from_msisdn': data['to_msisdn'], 'message': data['message'], 'id': data['transport_message_id'], 'transport_network_id': data['transport_network_id'], } return self.publisher.publish_message(Message(**reply)) def stopWorker(self): """shutdown""" pass ## Instruction: Add keyword to echo worker. ## Code After: from twisted.python import log from twisted.internet.defer import inlineCallbacks, Deferred from vumi.message import Message from vumi.service import Worker class EchoWorker(Worker): @inlineCallbacks def startWorker(self): """called by the Worker class when the AMQP connections been established""" self.publisher = yield self.publish_to('sms.outbound.%(transport_name)s' % self.config) self.consumer = yield self.consume('sms.inbound.%(transport_name)s.%(shortcode)s' % self.config, self.handle_inbound_message) def handle_inbound_message(self, message): log.msg("Received: %s" % (message.payload,)) """Reply to the message with the same content""" data = message.payload reply = { 'to_msisdn': data['from_msisdn'], 'from_msisdn': data['to_msisdn'], 'message': data['message'], 'id': data['transport_message_id'], 'transport_network_id': data['transport_network_id'], 'transport_keyword': data['transport_keyword'], } return self.publisher.publish_message(Message(**reply)) def stopWorker(self): """shutdown""" pass
# ... existing code ... 'transport_network_id': data['transport_network_id'], 'transport_keyword': data['transport_keyword'], } # ... rest of the code ...
7bea8f5cb6f958225ce61a9f7ce439e9a80036ea
tests/unit/utils/cache_test.py
tests/unit/utils/cache_test.py
''' tests.unit.utils.cache_test ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Test the salt cache objects ''' # Import Salt Testing libs from salttesting import TestCase from salttesting.helpers import ensure_in_syspath ensure_in_syspath('../../') # Import salt libs from salt.utils import cache import time class CacheDictTestCase(TestCase): def test_sanity(self): ''' Make sure you can instantiate etc. ''' cd = cache.CacheDict(5) assert isinstance(cd, cache.CacheDict) # do some tests to make sure it looks like a dict assert 'foo' not in cd cd['foo'] = 'bar' assert cd['foo'] == 'bar' del cd['foo'] assert 'foo' not in cd def test_ttl(self): cd = cache.CacheDict(0.1) cd['foo'] = 'bar' assert 'foo' in cd assert cd['foo'] == 'bar' time.sleep(0.1) assert 'foo' not in cd # make sure that a get would get a regular old key error self.assertRaises(KeyError, cd.__getitem__, 'foo') if __name__ == '__main__': from integration import run_tests run_tests(CacheDictTestCase, needs_daemon=False)
''' tests.unit.utils.cache_test ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Test the salt cache objects ''' # Import Salt Testing libs from salttesting import TestCase from salttesting.helpers import ensure_in_syspath ensure_in_syspath('../../') # Import salt libs from salt.utils import cache import time class CacheDictTestCase(TestCase): def test_sanity(self): ''' Make sure you can instantiate etc. ''' cd = cache.CacheDict(5) self.assertIsInstance(cd, cache.CacheDict) # do some tests to make sure it looks like a dict self.assertNotIn('foo', cd) cd['foo'] = 'bar' self.assertEqual(cd['foo'], 'bar') del cd['foo'] self.assertNotIn('foo', cd) def test_ttl(self): cd = cache.CacheDict(0.1) cd['foo'] = 'bar' self.assertIn('foo', cd) self.assertEqual(cd['foo'], 'bar') time.sleep(0.1) self.assertNotIn('foo', cd) # make sure that a get would get a regular old key error self.assertRaises(KeyError, cd.__getitem__, 'foo') if __name__ == '__main__': from integration import run_tests run_tests(CacheDictTestCase, needs_daemon=False)
Change python asserts to unittest asserts
Change python asserts to unittest asserts
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
''' tests.unit.utils.cache_test ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Test the salt cache objects ''' # Import Salt Testing libs from salttesting import TestCase from salttesting.helpers import ensure_in_syspath ensure_in_syspath('../../') # Import salt libs from salt.utils import cache import time class CacheDictTestCase(TestCase): def test_sanity(self): ''' Make sure you can instantiate etc. ''' cd = cache.CacheDict(5) - assert isinstance(cd, cache.CacheDict) + self.assertIsInstance(cd, cache.CacheDict) # do some tests to make sure it looks like a dict - assert 'foo' not in cd + self.assertNotIn('foo', cd) cd['foo'] = 'bar' - assert cd['foo'] == 'bar' + self.assertEqual(cd['foo'], 'bar') del cd['foo'] - assert 'foo' not in cd + self.assertNotIn('foo', cd) def test_ttl(self): cd = cache.CacheDict(0.1) cd['foo'] = 'bar' - assert 'foo' in cd + self.assertIn('foo', cd) - assert cd['foo'] == 'bar' + self.assertEqual(cd['foo'], 'bar') time.sleep(0.1) - assert 'foo' not in cd + self.assertNotIn('foo', cd) + # make sure that a get would get a regular old key error self.assertRaises(KeyError, cd.__getitem__, 'foo') if __name__ == '__main__': from integration import run_tests run_tests(CacheDictTestCase, needs_daemon=False)
Change python asserts to unittest asserts
## Code Before: ''' tests.unit.utils.cache_test ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Test the salt cache objects ''' # Import Salt Testing libs from salttesting import TestCase from salttesting.helpers import ensure_in_syspath ensure_in_syspath('../../') # Import salt libs from salt.utils import cache import time class CacheDictTestCase(TestCase): def test_sanity(self): ''' Make sure you can instantiate etc. ''' cd = cache.CacheDict(5) assert isinstance(cd, cache.CacheDict) # do some tests to make sure it looks like a dict assert 'foo' not in cd cd['foo'] = 'bar' assert cd['foo'] == 'bar' del cd['foo'] assert 'foo' not in cd def test_ttl(self): cd = cache.CacheDict(0.1) cd['foo'] = 'bar' assert 'foo' in cd assert cd['foo'] == 'bar' time.sleep(0.1) assert 'foo' not in cd # make sure that a get would get a regular old key error self.assertRaises(KeyError, cd.__getitem__, 'foo') if __name__ == '__main__': from integration import run_tests run_tests(CacheDictTestCase, needs_daemon=False) ## Instruction: Change python asserts to unittest asserts ## Code After: ''' tests.unit.utils.cache_test ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Test the salt cache objects ''' # Import Salt Testing libs from salttesting import TestCase from salttesting.helpers import ensure_in_syspath ensure_in_syspath('../../') # Import salt libs from salt.utils import cache import time class CacheDictTestCase(TestCase): def test_sanity(self): ''' Make sure you can instantiate etc. ''' cd = cache.CacheDict(5) self.assertIsInstance(cd, cache.CacheDict) # do some tests to make sure it looks like a dict self.assertNotIn('foo', cd) cd['foo'] = 'bar' self.assertEqual(cd['foo'], 'bar') del cd['foo'] self.assertNotIn('foo', cd) def test_ttl(self): cd = cache.CacheDict(0.1) cd['foo'] = 'bar' self.assertIn('foo', cd) self.assertEqual(cd['foo'], 'bar') time.sleep(0.1) self.assertNotIn('foo', cd) # make sure that a get would get a regular old key error self.assertRaises(KeyError, cd.__getitem__, 'foo') if __name__ == '__main__': from integration import run_tests run_tests(CacheDictTestCase, needs_daemon=False)
# ... existing code ... cd = cache.CacheDict(5) self.assertIsInstance(cd, cache.CacheDict) # ... modified code ... # do some tests to make sure it looks like a dict self.assertNotIn('foo', cd) cd['foo'] = 'bar' self.assertEqual(cd['foo'], 'bar') del cd['foo'] self.assertNotIn('foo', cd) ... cd['foo'] = 'bar' self.assertIn('foo', cd) self.assertEqual(cd['foo'], 'bar') time.sleep(0.1) self.assertNotIn('foo', cd) # make sure that a get would get a regular old key error # ... rest of the code ...
a509cd74d1e49dd9f9585b8e4c43e88aaf2bc19d
tests/stonemason/service/tileserver/test_tileserver.py
tests/stonemason/service/tileserver/test_tileserver.py
import os import unittest from stonemason.service.tileserver import AppBuilder class TestExample(unittest.TestCase): def setUp(self): os.environ['EXAMPLE_APP_ENV'] = 'dev' app = AppBuilder().build() self.client = app.test_client() def test_app(self): resp = self.client.get('/') self.assertEqual(b'Hello World!', resp.data)
import os import unittest from stonemason.service.tileserver import AppBuilder class TestExample(unittest.TestCase): def setUp(self): os.environ['EXAMPLE_APP_MODE'] = 'development' app = AppBuilder().build(config='settings.py') self.client = app.test_client() def test_app(self): resp = self.client.get('/') self.assertEqual(b'Hello World!', resp.data)
Update tests for the test app
TEST: Update tests for the test app
Python
mit
Kotaimen/stonemason,Kotaimen/stonemason
import os import unittest from stonemason.service.tileserver import AppBuilder class TestExample(unittest.TestCase): def setUp(self): - os.environ['EXAMPLE_APP_ENV'] = 'dev' + os.environ['EXAMPLE_APP_MODE'] = 'development' - app = AppBuilder().build() + app = AppBuilder().build(config='settings.py') self.client = app.test_client() def test_app(self): resp = self.client.get('/') self.assertEqual(b'Hello World!', resp.data)
Update tests for the test app
## Code Before: import os import unittest from stonemason.service.tileserver import AppBuilder class TestExample(unittest.TestCase): def setUp(self): os.environ['EXAMPLE_APP_ENV'] = 'dev' app = AppBuilder().build() self.client = app.test_client() def test_app(self): resp = self.client.get('/') self.assertEqual(b'Hello World!', resp.data) ## Instruction: Update tests for the test app ## Code After: import os import unittest from stonemason.service.tileserver import AppBuilder class TestExample(unittest.TestCase): def setUp(self): os.environ['EXAMPLE_APP_MODE'] = 'development' app = AppBuilder().build(config='settings.py') self.client = app.test_client() def test_app(self): resp = self.client.get('/') self.assertEqual(b'Hello World!', resp.data)
... def setUp(self): os.environ['EXAMPLE_APP_MODE'] = 'development' app = AppBuilder().build(config='settings.py') self.client = app.test_client() ...
76244d9a9750d1e095884b3a453caffa6d1ef3c4
main/views/views.py
main/views/views.py
from django.shortcuts import render from main.models import UserProfile, Transaction, Task, Service from django.db.models import Avg def index(request): users = UserProfile.objects.all() return render(request, 'main/index.html', { 'users_top_spend': sorted(users, key=lambda a: a.spend(), reverse=True)[:4], 'users_top_balance': sorted(users, key=lambda a: a.balance(), reverse=True)[:4], 'users_last': UserProfile.objects.order_by('-user__date_joined')[:4], 'users_count': UserProfile.objects.count(), 'money_all': -UserProfile.objects.get(pk=1).balance(), 'money_avg': Transaction.objects.filter(status=True).exclude(user_from=1).aggregate(Avg('amount'))['amount__avg'] or 0, 'tasks': Task.objects.filter(status=True).order_by('-timestamp_create')[:10], 'services': Service.objects.filter(published=True).order_by('-created_at')[:10], })
from django.shortcuts import render from main.models import UserProfile, Transaction, Task, Service from django.db.models import Avg from voting.models import Vote def index(request): users = UserProfile.objects.all() tasks_last = Task.objects.filter(status=True).order_by('-timestamp_create')[:10] votes = Vote.objects.get_scores_in_bulk(tasks_last) tasks_last = list(filter(lambda x: x.id not in votes or votes[x.id]['score'] > 0, tasks_last)) services_last = Service.objects.filter(published=True).order_by('-created_at')[:10] votes = Vote.objects.get_scores_in_bulk(services_last) services_last = list(filter(lambda x: x.id not in votes or votes[x.id]['score'] > 0, services_last)) return render(request, 'main/index.html', { 'users_top_spend': sorted(users, key=lambda a: a.spend(), reverse=True)[:4], 'users_top_balance': sorted(users, key=lambda a: a.balance(), reverse=True)[:4], 'users_last': UserProfile.objects.order_by('-user__date_joined')[:4], 'users_count': UserProfile.objects.count(), 'money_all': -UserProfile.objects.get(pk=1).balance(), 'money_avg': Transaction.objects.filter(status=True).exclude(user_from=1).aggregate(Avg('amount'))['amount__avg'] or 0, 'tasks': tasks_last, 'services': services_last, })
Hide last task and services with negative score from main page
Hide last task and services with negative score from main page
Python
agpl-3.0
Davidyuk/witcoin,Davidyuk/witcoin
from django.shortcuts import render from main.models import UserProfile, Transaction, Task, Service from django.db.models import Avg + from voting.models import Vote def index(request): users = UserProfile.objects.all() + + tasks_last = Task.objects.filter(status=True).order_by('-timestamp_create')[:10] + votes = Vote.objects.get_scores_in_bulk(tasks_last) + tasks_last = list(filter(lambda x: x.id not in votes or votes[x.id]['score'] > 0, tasks_last)) + + services_last = Service.objects.filter(published=True).order_by('-created_at')[:10] + votes = Vote.objects.get_scores_in_bulk(services_last) + services_last = list(filter(lambda x: x.id not in votes or votes[x.id]['score'] > 0, services_last)) + return render(request, 'main/index.html', { 'users_top_spend': sorted(users, key=lambda a: a.spend(), reverse=True)[:4], 'users_top_balance': sorted(users, key=lambda a: a.balance(), reverse=True)[:4], 'users_last': UserProfile.objects.order_by('-user__date_joined')[:4], 'users_count': UserProfile.objects.count(), 'money_all': -UserProfile.objects.get(pk=1).balance(), 'money_avg': Transaction.objects.filter(status=True).exclude(user_from=1).aggregate(Avg('amount'))['amount__avg'] or 0, - 'tasks': Task.objects.filter(status=True).order_by('-timestamp_create')[:10], - 'services': Service.objects.filter(published=True).order_by('-created_at')[:10], + 'tasks': tasks_last, + 'services': services_last, })
Hide last task and services with negative score from main page
## Code Before: from django.shortcuts import render from main.models import UserProfile, Transaction, Task, Service from django.db.models import Avg def index(request): users = UserProfile.objects.all() return render(request, 'main/index.html', { 'users_top_spend': sorted(users, key=lambda a: a.spend(), reverse=True)[:4], 'users_top_balance': sorted(users, key=lambda a: a.balance(), reverse=True)[:4], 'users_last': UserProfile.objects.order_by('-user__date_joined')[:4], 'users_count': UserProfile.objects.count(), 'money_all': -UserProfile.objects.get(pk=1).balance(), 'money_avg': Transaction.objects.filter(status=True).exclude(user_from=1).aggregate(Avg('amount'))['amount__avg'] or 0, 'tasks': Task.objects.filter(status=True).order_by('-timestamp_create')[:10], 'services': Service.objects.filter(published=True).order_by('-created_at')[:10], }) ## Instruction: Hide last task and services with negative score from main page ## Code After: from django.shortcuts import render from main.models import UserProfile, Transaction, Task, Service from django.db.models import Avg from voting.models import Vote def index(request): users = UserProfile.objects.all() tasks_last = Task.objects.filter(status=True).order_by('-timestamp_create')[:10] votes = Vote.objects.get_scores_in_bulk(tasks_last) tasks_last = list(filter(lambda x: x.id not in votes or votes[x.id]['score'] > 0, tasks_last)) services_last = Service.objects.filter(published=True).order_by('-created_at')[:10] votes = Vote.objects.get_scores_in_bulk(services_last) services_last = list(filter(lambda x: x.id not in votes or votes[x.id]['score'] > 0, services_last)) return render(request, 'main/index.html', { 'users_top_spend': sorted(users, key=lambda a: a.spend(), reverse=True)[:4], 'users_top_balance': sorted(users, key=lambda a: a.balance(), reverse=True)[:4], 'users_last': UserProfile.objects.order_by('-user__date_joined')[:4], 'users_count': UserProfile.objects.count(), 'money_all': -UserProfile.objects.get(pk=1).balance(), 'money_avg': Transaction.objects.filter(status=True).exclude(user_from=1).aggregate(Avg('amount'))['amount__avg'] or 0, 'tasks': tasks_last, 'services': services_last, })
# ... existing code ... from django.db.models import Avg from voting.models import Vote # ... modified code ... users = UserProfile.objects.all() tasks_last = Task.objects.filter(status=True).order_by('-timestamp_create')[:10] votes = Vote.objects.get_scores_in_bulk(tasks_last) tasks_last = list(filter(lambda x: x.id not in votes or votes[x.id]['score'] > 0, tasks_last)) services_last = Service.objects.filter(published=True).order_by('-created_at')[:10] votes = Vote.objects.get_scores_in_bulk(services_last) services_last = list(filter(lambda x: x.id not in votes or votes[x.id]['score'] > 0, services_last)) return render(request, 'main/index.html', { ... 'money_avg': Transaction.objects.filter(status=True).exclude(user_from=1).aggregate(Avg('amount'))['amount__avg'] or 0, 'tasks': tasks_last, 'services': services_last, }) # ... rest of the code ...
368e2d6407cb021d80fe3679c65737581c3cc221
bliski_publikator/institutions/serializers.py
bliski_publikator/institutions/serializers.py
from rest_framework import serializers from .models import Institution class InstitutionSerializer(serializers.HyperlinkedModelSerializer): on_site = serializers.CharField(source='get_absolute_url', read_only=True) class Meta: model = Institution fields = ('on_site', 'url', 'name', 'slug', 'user', 'email', 'region', 'regon', 'krs', 'monitorings') extra_kwargs = { 'region': {'view_name': 'jednostkaadministracyjna-detail'} }
from rest_framework import serializers from .models import Institution class InstitutionSerializer(serializers.HyperlinkedModelSerializer): on_site = serializers.CharField(source='get_absolute_url', read_only=True) class Meta: model = Institution fields = ('on_site', 'url', 'name', 'slug', 'user', 'email', 'region', 'regon', 'krs', 'monitorings') extra_kwargs = { 'region': {'view_name': 'jednostkaadministracyjna-detail'}, 'user': {'read_only': True} }
Make user field read-only in InstitutionSerializer
Make user field read-only in InstitutionSerializer
Python
mit
watchdogpolska/bliski_publikator,watchdogpolska/bliski_publikator,watchdogpolska/bliski_publikator,watchdogpolska/bliski_publikator
from rest_framework import serializers from .models import Institution class InstitutionSerializer(serializers.HyperlinkedModelSerializer): on_site = serializers.CharField(source='get_absolute_url', read_only=True) class Meta: model = Institution fields = ('on_site', 'url', 'name', 'slug', 'user', 'email', 'region', 'regon', 'krs', 'monitorings') extra_kwargs = { - 'region': {'view_name': 'jednostkaadministracyjna-detail'} + 'region': {'view_name': 'jednostkaadministracyjna-detail'}, + 'user': {'read_only': True} }
Make user field read-only in InstitutionSerializer
## Code Before: from rest_framework import serializers from .models import Institution class InstitutionSerializer(serializers.HyperlinkedModelSerializer): on_site = serializers.CharField(source='get_absolute_url', read_only=True) class Meta: model = Institution fields = ('on_site', 'url', 'name', 'slug', 'user', 'email', 'region', 'regon', 'krs', 'monitorings') extra_kwargs = { 'region': {'view_name': 'jednostkaadministracyjna-detail'} } ## Instruction: Make user field read-only in InstitutionSerializer ## Code After: from rest_framework import serializers from .models import Institution class InstitutionSerializer(serializers.HyperlinkedModelSerializer): on_site = serializers.CharField(source='get_absolute_url', read_only=True) class Meta: model = Institution fields = ('on_site', 'url', 'name', 'slug', 'user', 'email', 'region', 'regon', 'krs', 'monitorings') extra_kwargs = { 'region': {'view_name': 'jednostkaadministracyjna-detail'}, 'user': {'read_only': True} }
// ... existing code ... extra_kwargs = { 'region': {'view_name': 'jednostkaadministracyjna-detail'}, 'user': {'read_only': True} } // ... rest of the code ...
e92339046fb47fc2275f432dfe3d998f702e40b2
pycalphad/tests/test_tdb.py
pycalphad/tests/test_tdb.py
import nose.tools from pycalphad import Database from sympy import SympifyError @nose.tools.raises(SympifyError) def test_tdb_popen_exploit(): "Prevent execution of arbitrary code using Popen." tdb_exploit_string = \ """ PARAMETER G(L12_FCC,AL,CR,NI:NI;0) 298.15 [].__class__.__base__.__subclasses__()[158]('/bin/ls'); 6000 N ! """ Database(tdb_exploit_string)
import nose.tools from pycalphad import Database @nose.tools.raises(ValueError, TypeError) def test_tdb_popen_exploit(): "Prevent execution of arbitrary code using Popen." tdb_exploit_string = \ """ PARAMETER G(L12_FCC,AL,CR,NI:NI;0) 298.15 [].__class__.__base__.__subclasses__()[158]('/bin/ls'); 6000 N ! """ Database(tdb_exploit_string)
Fix unit test for py26
Fix unit test for py26
Python
mit
tkphd/pycalphad,tkphd/pycalphad,tkphd/pycalphad
import nose.tools from pycalphad import Database - from sympy import SympifyError - @nose.tools.raises(SympifyError) + @nose.tools.raises(ValueError, TypeError) def test_tdb_popen_exploit(): "Prevent execution of arbitrary code using Popen." tdb_exploit_string = \ """ PARAMETER G(L12_FCC,AL,CR,NI:NI;0) 298.15 [].__class__.__base__.__subclasses__()[158]('/bin/ls'); 6000 N ! """ Database(tdb_exploit_string)
Fix unit test for py26
## Code Before: import nose.tools from pycalphad import Database from sympy import SympifyError @nose.tools.raises(SympifyError) def test_tdb_popen_exploit(): "Prevent execution of arbitrary code using Popen." tdb_exploit_string = \ """ PARAMETER G(L12_FCC,AL,CR,NI:NI;0) 298.15 [].__class__.__base__.__subclasses__()[158]('/bin/ls'); 6000 N ! """ Database(tdb_exploit_string) ## Instruction: Fix unit test for py26 ## Code After: import nose.tools from pycalphad import Database @nose.tools.raises(ValueError, TypeError) def test_tdb_popen_exploit(): "Prevent execution of arbitrary code using Popen." tdb_exploit_string = \ """ PARAMETER G(L12_FCC,AL,CR,NI:NI;0) 298.15 [].__class__.__base__.__subclasses__()[158]('/bin/ls'); 6000 N ! """ Database(tdb_exploit_string)
// ... existing code ... from pycalphad import Database @nose.tools.raises(ValueError, TypeError) def test_tdb_popen_exploit(): // ... rest of the code ...
5a6b19f956dfde65a1d8316fd4bebe4697846e45
connman_dispatcher/detect.py
connman_dispatcher/detect.py
import glib import dbus from dbus.mainloop.glib import DBusGMainLoop from pyee import EventEmitter import logbook logger = logbook.Logger('connman-dispatcher') __all__ = ['detector'] def property_changed(_, message): if message.get_member() == "PropertyChanged": _, state = message.get_args_list() if state == 'online' and not detector.is_online: logger.info('network state change: online' ) detector.emit('up') detector.is_online = True elif state == 'idle': logger.info('network state change: offline' ) detector.emit('down') detector.is_online = False detector = EventEmitter() detector.is_online = is_online() DBusGMainLoop(set_as_default=True) bus = dbus.SystemBus() bus.add_match_string_non_blocking("interface='net.connman.Manager'") bus.add_message_filter(property_changed) manager = dbus.Interface(bus.get_object('net.connman', "/"), 'net.connman.Manager') def is_online(): properties = manager.GetProperties() if properties['State'] == 'online': return True return False def run(): mainloop = glib.MainLoop() mainloop.run() detector.run = run detector.is_online = is_online
import glib import dbus from dbus.mainloop.glib import DBusGMainLoop from pyee import EventEmitter import logbook logger = logbook.Logger('connman-dispatcher') __all__ = ['detector'] def property_changed(_, message): if message.get_member() == "PropertyChanged": _, state = message.get_args_list() if state == 'online' and detector.state == 'offline': logger.info('network state change: online' ) detector.emit('up') detector.state = 'online' elif state == 'idle': logger.info('network state change: offline' ) detector.emit('down') detector.state = 'online' detector = EventEmitter() DBusGMainLoop(set_as_default=True) bus = dbus.SystemBus() bus.add_match_string_non_blocking("interface='net.connman.Manager'") bus.add_message_filter(property_changed) manager = dbus.Interface(bus.get_object('net.connman', "/"), 'net.connman.Manager') def is_online(): properties = manager.GetProperties() if properties['State'] == 'online': return True return False def run(): mainloop = glib.MainLoop() mainloop.run() detector.run = run detector.is_online = is_online detector.state = 'online' if is_online() else 'offline'
Use .state instead of .is_online to keep internal state
Use .state instead of .is_online to keep internal state
Python
isc
a-sk/connman-dispatcher
import glib import dbus from dbus.mainloop.glib import DBusGMainLoop from pyee import EventEmitter import logbook logger = logbook.Logger('connman-dispatcher') __all__ = ['detector'] def property_changed(_, message): if message.get_member() == "PropertyChanged": _, state = message.get_args_list() - if state == 'online' and not detector.is_online: + if state == 'online' and detector.state == 'offline': logger.info('network state change: online' ) detector.emit('up') - detector.is_online = True + detector.state = 'online' elif state == 'idle': logger.info('network state change: offline' ) detector.emit('down') - detector.is_online = False + detector.state = 'online' detector = EventEmitter() - detector.is_online = is_online() DBusGMainLoop(set_as_default=True) bus = dbus.SystemBus() bus.add_match_string_non_blocking("interface='net.connman.Manager'") bus.add_message_filter(property_changed) manager = dbus.Interface(bus.get_object('net.connman', "/"), 'net.connman.Manager') def is_online(): properties = manager.GetProperties() if properties['State'] == 'online': return True return False def run(): mainloop = glib.MainLoop() mainloop.run() detector.run = run detector.is_online = is_online + detector.state = 'online' if is_online() else 'offline'
Use .state instead of .is_online to keep internal state
## Code Before: import glib import dbus from dbus.mainloop.glib import DBusGMainLoop from pyee import EventEmitter import logbook logger = logbook.Logger('connman-dispatcher') __all__ = ['detector'] def property_changed(_, message): if message.get_member() == "PropertyChanged": _, state = message.get_args_list() if state == 'online' and not detector.is_online: logger.info('network state change: online' ) detector.emit('up') detector.is_online = True elif state == 'idle': logger.info('network state change: offline' ) detector.emit('down') detector.is_online = False detector = EventEmitter() detector.is_online = is_online() DBusGMainLoop(set_as_default=True) bus = dbus.SystemBus() bus.add_match_string_non_blocking("interface='net.connman.Manager'") bus.add_message_filter(property_changed) manager = dbus.Interface(bus.get_object('net.connman', "/"), 'net.connman.Manager') def is_online(): properties = manager.GetProperties() if properties['State'] == 'online': return True return False def run(): mainloop = glib.MainLoop() mainloop.run() detector.run = run detector.is_online = is_online ## Instruction: Use .state instead of .is_online to keep internal state ## Code After: import glib import dbus from dbus.mainloop.glib import DBusGMainLoop from pyee import EventEmitter import logbook logger = logbook.Logger('connman-dispatcher') __all__ = ['detector'] def property_changed(_, message): if message.get_member() == "PropertyChanged": _, state = message.get_args_list() if state == 'online' and detector.state == 'offline': logger.info('network state change: online' ) detector.emit('up') detector.state = 'online' elif state == 'idle': logger.info('network state change: offline' ) detector.emit('down') detector.state = 'online' detector = EventEmitter() DBusGMainLoop(set_as_default=True) bus = dbus.SystemBus() bus.add_match_string_non_blocking("interface='net.connman.Manager'") bus.add_message_filter(property_changed) manager = dbus.Interface(bus.get_object('net.connman', "/"), 'net.connman.Manager') def is_online(): properties = manager.GetProperties() if properties['State'] == 'online': return True return False def run(): mainloop = glib.MainLoop() mainloop.run() detector.run = run detector.is_online = is_online detector.state = 'online' if is_online() else 'offline'
// ... existing code ... _, state = message.get_args_list() if state == 'online' and detector.state == 'offline': logger.info('network state change: online' ) // ... modified code ... detector.emit('up') detector.state = 'online' elif state == 'idle': ... detector.emit('down') detector.state = 'online' ... detector = EventEmitter() DBusGMainLoop(set_as_default=True) ... detector.is_online = is_online detector.state = 'online' if is_online() else 'offline' // ... rest of the code ...
6aabf31aeb6766677f805bd4c0d5e4fc26522e53
tests/test_memory.py
tests/test_memory.py
import sys import weakref import pytest # type: ignore from hypothesis import given from ppb_vector import Vector2 from utils import floats, vectors class DummyVector: """A naïve representation of vectors.""" x: float y: float def __init__(self, x, y): self.x = float(x) self.y = float(y) @pytest.mark.skipif(sys.implementation.name != 'cpython', reason="PyPy optimises __slots__ automatically.") @given(x=floats(), y=floats()) def test_object_size(x, y): """Check that Vector2 is 2 times smaller than a naïve version.""" from pympler.asizeof import asizeof as sizeof # type: ignore assert sizeof(Vector2(x, y)) < sizeof(DummyVector(x, y)) / 2 @given(v=vectors()) def test_weak_ref(v): """Check that weak references can be made to Vector2s.""" assert weakref.ref(v) is not None
import sys import weakref import pytest # type: ignore from hypothesis import given from ppb_vector import Vector2 from utils import floats, vectors class DummyVector: """A naïve representation of vectors.""" x: float y: float def __init__(self, x, y): self.x = float(x) self.y = float(y) @pytest.mark.skipif(sys.implementation.name != 'cpython', reason="PyPy optimises __slots__ automatically.") @pytest.mark.skipif(sys.implementation.version.minor > 7, reason="Pympler 0.6 is broken under Python 3.8. See pympler#74") @given(x=floats(), y=floats()) def test_object_size(x, y): """Check that Vector2 is 2 times smaller than a naïve version.""" from pympler.asizeof import asizeof as sizeof # type: ignore assert sizeof(Vector2(x, y)) < sizeof(DummyVector(x, y)) / 2 @given(v=vectors()) def test_weak_ref(v): """Check that weak references can be made to Vector2s.""" assert weakref.ref(v) is not None
Disable test_object_size under CPython 3.8
tests/memory: Disable test_object_size under CPython 3.8
Python
artistic-2.0
ppb/ppb-vector,ppb/ppb-vector
import sys import weakref import pytest # type: ignore from hypothesis import given from ppb_vector import Vector2 from utils import floats, vectors class DummyVector: """A naïve representation of vectors.""" x: float y: float def __init__(self, x, y): self.x = float(x) self.y = float(y) @pytest.mark.skipif(sys.implementation.name != 'cpython', reason="PyPy optimises __slots__ automatically.") + @pytest.mark.skipif(sys.implementation.version.minor > 7, + reason="Pympler 0.6 is broken under Python 3.8. See pympler#74") @given(x=floats(), y=floats()) def test_object_size(x, y): """Check that Vector2 is 2 times smaller than a naïve version.""" from pympler.asizeof import asizeof as sizeof # type: ignore assert sizeof(Vector2(x, y)) < sizeof(DummyVector(x, y)) / 2 @given(v=vectors()) def test_weak_ref(v): """Check that weak references can be made to Vector2s.""" assert weakref.ref(v) is not None
Disable test_object_size under CPython 3.8
## Code Before: import sys import weakref import pytest # type: ignore from hypothesis import given from ppb_vector import Vector2 from utils import floats, vectors class DummyVector: """A naïve representation of vectors.""" x: float y: float def __init__(self, x, y): self.x = float(x) self.y = float(y) @pytest.mark.skipif(sys.implementation.name != 'cpython', reason="PyPy optimises __slots__ automatically.") @given(x=floats(), y=floats()) def test_object_size(x, y): """Check that Vector2 is 2 times smaller than a naïve version.""" from pympler.asizeof import asizeof as sizeof # type: ignore assert sizeof(Vector2(x, y)) < sizeof(DummyVector(x, y)) / 2 @given(v=vectors()) def test_weak_ref(v): """Check that weak references can be made to Vector2s.""" assert weakref.ref(v) is not None ## Instruction: Disable test_object_size under CPython 3.8 ## Code After: import sys import weakref import pytest # type: ignore from hypothesis import given from ppb_vector import Vector2 from utils import floats, vectors class DummyVector: """A naïve representation of vectors.""" x: float y: float def __init__(self, x, y): self.x = float(x) self.y = float(y) @pytest.mark.skipif(sys.implementation.name != 'cpython', reason="PyPy optimises __slots__ automatically.") @pytest.mark.skipif(sys.implementation.version.minor > 7, reason="Pympler 0.6 is broken under Python 3.8. See pympler#74") @given(x=floats(), y=floats()) def test_object_size(x, y): """Check that Vector2 is 2 times smaller than a naïve version.""" from pympler.asizeof import asizeof as sizeof # type: ignore assert sizeof(Vector2(x, y)) < sizeof(DummyVector(x, y)) / 2 @given(v=vectors()) def test_weak_ref(v): """Check that weak references can be made to Vector2s.""" assert weakref.ref(v) is not None
// ... existing code ... reason="PyPy optimises __slots__ automatically.") @pytest.mark.skipif(sys.implementation.version.minor > 7, reason="Pympler 0.6 is broken under Python 3.8. See pympler#74") @given(x=floats(), y=floats()) // ... rest of the code ...
c7650f69e1a1d7ff16e72a741b329b32636a5a3d
lizard_apps/views.py
lizard_apps/views.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from django.views.generic import TemplateView from lizard_apps.models import Screen class AppScreenView(TemplateView): content_type = "application/javascript" template_name = "lizard_apps/script.js" def screen(self): return Screen.objects.get(slug=self.kwargs['slug'])
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from django.views.generic import TemplateView from django.shortcuts import get_object_or_404 from lizard_apps.models import Screen class AppScreenView(TemplateView): content_type = "application/javascript" template_name = "lizard_apps/script.js" def screen(self): return get_object_or_404(Screen, slug=self.kwargs['slug'])
Return 404 instead of incorrect JS file when screen does not exist.
Return 404 instead of incorrect JS file when screen does not exist.
Python
mit
lizardsystem/lizard-apps,lizardsystem/lizard-apps
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from django.views.generic import TemplateView + from django.shortcuts import get_object_or_404 from lizard_apps.models import Screen class AppScreenView(TemplateView): content_type = "application/javascript" template_name = "lizard_apps/script.js" def screen(self): - return Screen.objects.get(slug=self.kwargs['slug']) + return get_object_or_404(Screen, slug=self.kwargs['slug'])
Return 404 instead of incorrect JS file when screen does not exist.
## Code Before: from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from django.views.generic import TemplateView from lizard_apps.models import Screen class AppScreenView(TemplateView): content_type = "application/javascript" template_name = "lizard_apps/script.js" def screen(self): return Screen.objects.get(slug=self.kwargs['slug']) ## Instruction: Return 404 instead of incorrect JS file when screen does not exist. ## Code After: from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from django.views.generic import TemplateView from django.shortcuts import get_object_or_404 from lizard_apps.models import Screen class AppScreenView(TemplateView): content_type = "application/javascript" template_name = "lizard_apps/script.js" def screen(self): return get_object_or_404(Screen, slug=self.kwargs['slug'])
// ... existing code ... from django.views.generic import TemplateView from django.shortcuts import get_object_or_404 // ... modified code ... def screen(self): return get_object_or_404(Screen, slug=self.kwargs['slug']) // ... rest of the code ...
a0ba91395dc02f92e58395e41db77af12439a507
arrow/__init__.py
arrow/__init__.py
from ._version import __version__ from .api import get, now, utcnow from .arrow import Arrow from .factory import ArrowFactory
from ._version import __version__ from .api import get, now, utcnow from .arrow import Arrow from .factory import ArrowFactory from .parser import ParserError
Add ParserError to the module exports.
Add ParserError to the module exports. Adding ParserError to the module exports allows users to easily catch that specific error. It also eases lookup of that error for tools like PyCharm.
Python
apache-2.0
crsmithdev/arrow
from ._version import __version__ from .api import get, now, utcnow from .arrow import Arrow from .factory import ArrowFactory + from .parser import ParserError
Add ParserError to the module exports.
## Code Before: from ._version import __version__ from .api import get, now, utcnow from .arrow import Arrow from .factory import ArrowFactory ## Instruction: Add ParserError to the module exports. ## Code After: from ._version import __version__ from .api import get, now, utcnow from .arrow import Arrow from .factory import ArrowFactory from .parser import ParserError
# ... existing code ... from .factory import ArrowFactory from .parser import ParserError # ... rest of the code ...
fca363dec1ff73e34e25084322d5a31dd6fbc1ee
simplestatistics/statistics/coefficient_of_variation.py
simplestatistics/statistics/coefficient_of_variation.py
from .standard_deviation import standard_deviation from .mean import mean def coefficient_of_variation(data): """ The `coefficient_of_variation`_ is the ratio of the standard deviation to the mean .. _`coefficient of variation`: https://en.wikipedia.org/wiki/Coefficient_of_variation Args: data: A list of numerical objects. Returns: A float object. Examples: >>> coefficient_of_variation([1, 2, 3]) 0.5 >>> coefficient_of_variation([1, 2, 3, 4]) 0.5163977794943222 >>> coefficient_of_variation([-1, 0, 1, 2, 3, 4]) 1.247219128924647 """ return standard_deviation(data) / mean(data)
from .standard_deviation import standard_deviation from .mean import mean def coefficient_of_variation(data, sample = True): """ The `coefficient of variation`_ is the ratio of the standard deviation to the mean. .. _`coefficient of variation`: https://en.wikipedia.org/wiki/Coefficient_of_variation Args: data: A list of numerical objects. Returns: A float object. Examples: >>> coefficient_of_variation([1, 2, 3]) 0.5 >>> ss.coefficient_of_variation([1, 2, 3], False) 0.408248290463863 >>> coefficient_of_variation([1, 2, 3, 4]) 0.5163977794943222 >>> coefficient_of_variation([-1, 0, 1, 2, 3, 4]) 1.247219128924647 """ return standard_deviation(data, sample) / mean(data)
Add sample param to CV function
Add sample param to CV function Boolean param to make possible to calculate coefficient of variation for population (default is sample).
Python
unknown
tmcw/simple-statistics-py,sheriferson/simplestatistics,sheriferson/simple-statistics-py
from .standard_deviation import standard_deviation from .mean import mean - def coefficient_of_variation(data): + def coefficient_of_variation(data, sample = True): """ - The `coefficient_of_variation`_ is the ratio of the standard deviation to the mean + The `coefficient of variation`_ is the ratio of the standard deviation to the mean. + .. _`coefficient of variation`: https://en.wikipedia.org/wiki/Coefficient_of_variation Args: data: A list of numerical objects. Returns: A float object. Examples: >>> coefficient_of_variation([1, 2, 3]) 0.5 + >>> ss.coefficient_of_variation([1, 2, 3], False) + 0.408248290463863 >>> coefficient_of_variation([1, 2, 3, 4]) 0.5163977794943222 >>> coefficient_of_variation([-1, 0, 1, 2, 3, 4]) 1.247219128924647 """ - return standard_deviation(data) / mean(data) + return standard_deviation(data, sample) / mean(data) - +
Add sample param to CV function
## Code Before: from .standard_deviation import standard_deviation from .mean import mean def coefficient_of_variation(data): """ The `coefficient_of_variation`_ is the ratio of the standard deviation to the mean .. _`coefficient of variation`: https://en.wikipedia.org/wiki/Coefficient_of_variation Args: data: A list of numerical objects. Returns: A float object. Examples: >>> coefficient_of_variation([1, 2, 3]) 0.5 >>> coefficient_of_variation([1, 2, 3, 4]) 0.5163977794943222 >>> coefficient_of_variation([-1, 0, 1, 2, 3, 4]) 1.247219128924647 """ return standard_deviation(data) / mean(data) ## Instruction: Add sample param to CV function ## Code After: from .standard_deviation import standard_deviation from .mean import mean def coefficient_of_variation(data, sample = True): """ The `coefficient of variation`_ is the ratio of the standard deviation to the mean. .. _`coefficient of variation`: https://en.wikipedia.org/wiki/Coefficient_of_variation Args: data: A list of numerical objects. Returns: A float object. Examples: >>> coefficient_of_variation([1, 2, 3]) 0.5 >>> ss.coefficient_of_variation([1, 2, 3], False) 0.408248290463863 >>> coefficient_of_variation([1, 2, 3, 4]) 0.5163977794943222 >>> coefficient_of_variation([-1, 0, 1, 2, 3, 4]) 1.247219128924647 """ return standard_deviation(data, sample) / mean(data)
# ... existing code ... def coefficient_of_variation(data, sample = True): """ The `coefficient of variation`_ is the ratio of the standard deviation to the mean. .. _`coefficient of variation`: https://en.wikipedia.org/wiki/Coefficient_of_variation # ... modified code ... 0.5 >>> ss.coefficient_of_variation([1, 2, 3], False) 0.408248290463863 >>> coefficient_of_variation([1, 2, 3, 4]) ... """ return standard_deviation(data, sample) / mean(data) # ... rest of the code ...
063d88ed5d5f48114cdf566433ae40d40a8674f4
nbgrader/utils.py
nbgrader/utils.py
import hashlib import autopep8 def is_grade(cell): """Returns True if the cell is a grade cell.""" if 'nbgrader' not in cell.metadata: return False return cell.metadata['nbgrader'].get('grade', False) def is_solution(cell): """Returns True if the cell is a solution cell.""" if 'nbgrader' not in cell.metadata: return False return cell.metadata['nbgrader'].get('solution', False) def determine_grade(cell): if not is_grade(cell): raise ValueError("cell is not a grade cell") max_points = float(cell.metadata['nbgrader']['points']) if cell.cell_type == 'code': for output in cell.outputs: if output.output_type == 'error': return 0, max_points return max_points, max_points else: return None, max_points def compute_checksum(cell): m = hashlib.md5() # fix minor whitespace issues that might have been added and then # add cell contents m.update(autopep8.fix_code(cell.source).rstrip()) # include number of points that the cell is worth if 'points' in cell.metadata.nbgrader: m.update(cell.metadata.nbgrader['points']) # include the grade_id if 'grade_id' in cell.metadata.nbgrader: m.update(cell.metadata.nbgrader['grade_id']) return m.hexdigest()
import hashlib import autopep8 def is_grade(cell): """Returns True if the cell is a grade cell.""" if 'nbgrader' not in cell.metadata: return False return cell.metadata['nbgrader'].get('grade', False) def is_solution(cell): """Returns True if the cell is a solution cell.""" if 'nbgrader' not in cell.metadata: return False return cell.metadata['nbgrader'].get('solution', False) def determine_grade(cell): if not is_grade(cell): raise ValueError("cell is not a grade cell") max_points = float(cell.metadata['nbgrader']['points']) if cell.cell_type == 'code': for output in cell.outputs: if output.output_type == 'error': return 0, max_points return max_points, max_points else: return None, max_points def compute_checksum(cell): m = hashlib.md5() # fix minor whitespace issues that might have been added and then # add cell contents m.update(autopep8.fix_code(cell.source).rstrip()) # include number of points that the cell is worth if 'points' in cell.metadata.nbgrader: m.update(str(float(cell.metadata.nbgrader['points']))) # include the grade_id if 'grade_id' in cell.metadata.nbgrader: m.update(cell.metadata.nbgrader['grade_id']) return m.hexdigest()
Make sure points in checksum are consistent
Make sure points in checksum are consistent
Python
bsd-3-clause
EdwardJKim/nbgrader,modulexcite/nbgrader,jupyter/nbgrader,jhamrick/nbgrader,jdfreder/nbgrader,dementrock/nbgrader,ellisonbg/nbgrader,ellisonbg/nbgrader,ellisonbg/nbgrader,jhamrick/nbgrader,alope107/nbgrader,dementrock/nbgrader,MatKallada/nbgrader,EdwardJKim/nbgrader,ellisonbg/nbgrader,MatKallada/nbgrader,jdfreder/nbgrader,jupyter/nbgrader,jupyter/nbgrader,EdwardJKim/nbgrader,modulexcite/nbgrader,jupyter/nbgrader,alope107/nbgrader,jhamrick/nbgrader,jupyter/nbgrader,jhamrick/nbgrader,EdwardJKim/nbgrader
import hashlib import autopep8 def is_grade(cell): """Returns True if the cell is a grade cell.""" if 'nbgrader' not in cell.metadata: return False return cell.metadata['nbgrader'].get('grade', False) def is_solution(cell): """Returns True if the cell is a solution cell.""" if 'nbgrader' not in cell.metadata: return False return cell.metadata['nbgrader'].get('solution', False) def determine_grade(cell): if not is_grade(cell): raise ValueError("cell is not a grade cell") max_points = float(cell.metadata['nbgrader']['points']) if cell.cell_type == 'code': for output in cell.outputs: if output.output_type == 'error': return 0, max_points return max_points, max_points else: return None, max_points def compute_checksum(cell): m = hashlib.md5() # fix minor whitespace issues that might have been added and then # add cell contents m.update(autopep8.fix_code(cell.source).rstrip()) # include number of points that the cell is worth if 'points' in cell.metadata.nbgrader: - m.update(cell.metadata.nbgrader['points']) + m.update(str(float(cell.metadata.nbgrader['points']))) # include the grade_id if 'grade_id' in cell.metadata.nbgrader: m.update(cell.metadata.nbgrader['grade_id']) return m.hexdigest()
Make sure points in checksum are consistent
## Code Before: import hashlib import autopep8 def is_grade(cell): """Returns True if the cell is a grade cell.""" if 'nbgrader' not in cell.metadata: return False return cell.metadata['nbgrader'].get('grade', False) def is_solution(cell): """Returns True if the cell is a solution cell.""" if 'nbgrader' not in cell.metadata: return False return cell.metadata['nbgrader'].get('solution', False) def determine_grade(cell): if not is_grade(cell): raise ValueError("cell is not a grade cell") max_points = float(cell.metadata['nbgrader']['points']) if cell.cell_type == 'code': for output in cell.outputs: if output.output_type == 'error': return 0, max_points return max_points, max_points else: return None, max_points def compute_checksum(cell): m = hashlib.md5() # fix minor whitespace issues that might have been added and then # add cell contents m.update(autopep8.fix_code(cell.source).rstrip()) # include number of points that the cell is worth if 'points' in cell.metadata.nbgrader: m.update(cell.metadata.nbgrader['points']) # include the grade_id if 'grade_id' in cell.metadata.nbgrader: m.update(cell.metadata.nbgrader['grade_id']) return m.hexdigest() ## Instruction: Make sure points in checksum are consistent ## Code After: import hashlib import autopep8 def is_grade(cell): """Returns True if the cell is a grade cell.""" if 'nbgrader' not in cell.metadata: return False return cell.metadata['nbgrader'].get('grade', False) def is_solution(cell): """Returns True if the cell is a solution cell.""" if 'nbgrader' not in cell.metadata: return False return cell.metadata['nbgrader'].get('solution', False) def determine_grade(cell): if not is_grade(cell): raise ValueError("cell is not a grade cell") max_points = float(cell.metadata['nbgrader']['points']) if cell.cell_type == 'code': for output in cell.outputs: if output.output_type == 'error': return 0, max_points return max_points, max_points else: return None, max_points def compute_checksum(cell): m = hashlib.md5() # fix minor whitespace issues that might have been added and then # add cell contents m.update(autopep8.fix_code(cell.source).rstrip()) # include number of points that the cell is worth if 'points' in cell.metadata.nbgrader: m.update(str(float(cell.metadata.nbgrader['points']))) # include the grade_id if 'grade_id' in cell.metadata.nbgrader: m.update(cell.metadata.nbgrader['grade_id']) return m.hexdigest()
# ... existing code ... if 'points' in cell.metadata.nbgrader: m.update(str(float(cell.metadata.nbgrader['points']))) # ... rest of the code ...
6f6199240009ac91da7e663030125df439d8fe7e
tests/test_trust_list.py
tests/test_trust_list.py
from __future__ import unicode_literals, division, absolute_import, print_function import unittest import sys from oscrypto import trust_list from asn1crypto.x509 import Certificate if sys.version_info < (3,): byte_cls = str else: byte_cls = bytes class TrustListTests(unittest.TestCase): def test_extract_from_system(self): certs = trust_list.extract_from_system() self.assertIsInstance(certs, list) for cert in certs: self.assertIsInstance(cert, byte_cls) _ = Certificate.load(cert).native
from __future__ import unicode_literals, division, absolute_import, print_function import unittest import sys from oscrypto import trust_list from asn1crypto.x509 import Certificate if sys.version_info < (3,): byte_cls = str else: byte_cls = bytes class TrustListTests(unittest.TestCase): def test_extract_from_system(self): certs = trust_list.extract_from_system() self.assertIsInstance(certs, list) self.assertLess(10, len(certs)) for cert in certs: self.assertIsInstance(cert, byte_cls) _ = Certificate.load(cert).native
Add more sanity checks to the trust list test
Add more sanity checks to the trust list test
Python
mit
wbond/oscrypto
from __future__ import unicode_literals, division, absolute_import, print_function import unittest import sys from oscrypto import trust_list from asn1crypto.x509 import Certificate if sys.version_info < (3,): byte_cls = str else: byte_cls = bytes class TrustListTests(unittest.TestCase): def test_extract_from_system(self): certs = trust_list.extract_from_system() self.assertIsInstance(certs, list) + self.assertLess(10, len(certs)) for cert in certs: self.assertIsInstance(cert, byte_cls) _ = Certificate.load(cert).native
Add more sanity checks to the trust list test
## Code Before: from __future__ import unicode_literals, division, absolute_import, print_function import unittest import sys from oscrypto import trust_list from asn1crypto.x509 import Certificate if sys.version_info < (3,): byte_cls = str else: byte_cls = bytes class TrustListTests(unittest.TestCase): def test_extract_from_system(self): certs = trust_list.extract_from_system() self.assertIsInstance(certs, list) for cert in certs: self.assertIsInstance(cert, byte_cls) _ = Certificate.load(cert).native ## Instruction: Add more sanity checks to the trust list test ## Code After: from __future__ import unicode_literals, division, absolute_import, print_function import unittest import sys from oscrypto import trust_list from asn1crypto.x509 import Certificate if sys.version_info < (3,): byte_cls = str else: byte_cls = bytes class TrustListTests(unittest.TestCase): def test_extract_from_system(self): certs = trust_list.extract_from_system() self.assertIsInstance(certs, list) self.assertLess(10, len(certs)) for cert in certs: self.assertIsInstance(cert, byte_cls) _ = Certificate.load(cert).native
# ... existing code ... self.assertIsInstance(certs, list) self.assertLess(10, len(certs)) for cert in certs: # ... rest of the code ...
e82045217fa262fbfe30563fef9945a67024d27f
project/creditor/management/commands/addrecurring.py
project/creditor/management/commands/addrecurring.py
from creditor.models import RecurringTransaction from django.core.management.base import BaseCommand, CommandError class Command(BaseCommand): help = 'Gets all RecurringTransactions and runs conditional_add_transaction()' def handle(self, *args, **options): for t in RecurringTransaction.objects.all(): ret = t.conditional_add_transaction() if ret: if options['verbosity'] > 1: print("Created transaction %s" % ret)
import datetime import itertools import dateutil.parser from creditor.models import RecurringTransaction from django.core.management.base import BaseCommand, CommandError from django.utils import timezone from asylum.utils import datetime_proxy, months class Command(BaseCommand): help = 'Gets all RecurringTransactions and runs conditional_add_transaction()' def add_arguments(self, parser): parser.add_argument('since', type=str, nargs='?', default=datetime_proxy(), help='Run for each month since the date, defaults to yesterday midnight') def handle(self, *args, **options): since_parsed = timezone.make_aware(dateutil.parser.parse(options['since'])) if options['verbosity'] > 2: print("Processing since %s" % since_parsed.isoformat()) for t in RecurringTransaction.objects.all(): if options['verbosity'] > 2: print("Processing: %s" % t) for month in months(since_parsed, timezone.now()): if options['verbosity'] > 2: print(" month %s" % month.isoformat()) ret = t.conditional_add_transaction(month) if ret: if options['verbosity'] > 1: print("Created transaction %s" % ret)
Add "since" parameter to this command
Add "since" parameter to this command Fixes #25
Python
mit
HelsinkiHacklab/asylum,hacklab-fi/asylum,rambo/asylum,rambo/asylum,HelsinkiHacklab/asylum,jautero/asylum,hacklab-fi/asylum,HelsinkiHacklab/asylum,rambo/asylum,HelsinkiHacklab/asylum,jautero/asylum,jautero/asylum,jautero/asylum,hacklab-fi/asylum,hacklab-fi/asylum,rambo/asylum
+ import datetime + import itertools + + import dateutil.parser from creditor.models import RecurringTransaction from django.core.management.base import BaseCommand, CommandError + from django.utils import timezone + + from asylum.utils import datetime_proxy, months class Command(BaseCommand): help = 'Gets all RecurringTransactions and runs conditional_add_transaction()' + def add_arguments(self, parser): + parser.add_argument('since', type=str, nargs='?', default=datetime_proxy(), help='Run for each month since the date, defaults to yesterday midnight') + def handle(self, *args, **options): + since_parsed = timezone.make_aware(dateutil.parser.parse(options['since'])) + if options['verbosity'] > 2: + print("Processing since %s" % since_parsed.isoformat()) + for t in RecurringTransaction.objects.all(): - ret = t.conditional_add_transaction() - if ret: + if options['verbosity'] > 2: + print("Processing: %s" % t) + for month in months(since_parsed, timezone.now()): - if options['verbosity'] > 1: + if options['verbosity'] > 2: + print(" month %s" % month.isoformat()) + ret = t.conditional_add_transaction(month) + if ret: + if options['verbosity'] > 1: - print("Created transaction %s" % ret) + print("Created transaction %s" % ret)
Add "since" parameter to this command
## Code Before: from creditor.models import RecurringTransaction from django.core.management.base import BaseCommand, CommandError class Command(BaseCommand): help = 'Gets all RecurringTransactions and runs conditional_add_transaction()' def handle(self, *args, **options): for t in RecurringTransaction.objects.all(): ret = t.conditional_add_transaction() if ret: if options['verbosity'] > 1: print("Created transaction %s" % ret) ## Instruction: Add "since" parameter to this command ## Code After: import datetime import itertools import dateutil.parser from creditor.models import RecurringTransaction from django.core.management.base import BaseCommand, CommandError from django.utils import timezone from asylum.utils import datetime_proxy, months class Command(BaseCommand): help = 'Gets all RecurringTransactions and runs conditional_add_transaction()' def add_arguments(self, parser): parser.add_argument('since', type=str, nargs='?', default=datetime_proxy(), help='Run for each month since the date, defaults to yesterday midnight') def handle(self, *args, **options): since_parsed = timezone.make_aware(dateutil.parser.parse(options['since'])) if options['verbosity'] > 2: print("Processing since %s" % since_parsed.isoformat()) for t in RecurringTransaction.objects.all(): if options['verbosity'] > 2: print("Processing: %s" % t) for month in months(since_parsed, timezone.now()): if options['verbosity'] > 2: print(" month %s" % month.isoformat()) ret = t.conditional_add_transaction(month) if ret: if options['verbosity'] > 1: print("Created transaction %s" % ret)
// ... existing code ... import datetime import itertools import dateutil.parser from creditor.models import RecurringTransaction // ... modified code ... from django.core.management.base import BaseCommand, CommandError from django.utils import timezone from asylum.utils import datetime_proxy, months ... def add_arguments(self, parser): parser.add_argument('since', type=str, nargs='?', default=datetime_proxy(), help='Run for each month since the date, defaults to yesterday midnight') def handle(self, *args, **options): since_parsed = timezone.make_aware(dateutil.parser.parse(options['since'])) if options['verbosity'] > 2: print("Processing since %s" % since_parsed.isoformat()) for t in RecurringTransaction.objects.all(): if options['verbosity'] > 2: print("Processing: %s" % t) for month in months(since_parsed, timezone.now()): if options['verbosity'] > 2: print(" month %s" % month.isoformat()) ret = t.conditional_add_transaction(month) if ret: if options['verbosity'] > 1: print("Created transaction %s" % ret) // ... rest of the code ...
7f212a9bacfce6612c6ec435174bf9c3eddd4652
pagoeta/apps/events/serializers.py
pagoeta/apps/events/serializers.py
from hvad.contrib.restframework import TranslatableModelSerializer from rest_framework import serializers from rest_framework.reverse import reverse from .models import Category, TargetGroup, TargetAge, Event from pagoeta.apps.core.functions import get_absolute_uri from pagoeta.apps.places.serializers import PlaceListSerializer class TypeField(serializers.RelatedField): def to_representation(self, value): return { 'code': value.code, 'name': value.name } class EventSerializer(TranslatableModelSerializer): category = TypeField(read_only=True) target_group = TypeField(read_only=True) targetGroup = target_group target_age = TypeField(read_only=True) targetAge = target_age place = PlaceListSerializer(read_only=True) # camelCase some field names startAt = serializers.DateTimeField(source='start_at', read_only=True) endAt = serializers.DateTimeField(source='end_at', read_only=True) isFeatured = serializers.BooleanField(source='is_featured', read_only=True) isVisible = serializers.BooleanField(source='is_visible', read_only=True) href = serializers.SerializerMethodField() class Meta(object): model = Event exclude = ('start_at', 'end_at', 'is_featured', 'is_visible', 'language_code') def get_href(self, obj): return get_absolute_uri(reverse('v1:event-detail', [obj.id]))
from hvad.contrib.restframework import TranslatableModelSerializer from rest_framework import serializers from rest_framework.reverse import reverse from .models import Category, TargetGroup, TargetAge, Event from pagoeta.apps.core.functions import get_absolute_uri from pagoeta.apps.places.serializers import PlaceListSerializer class TypeField(serializers.RelatedField): def to_representation(self, value): return { 'code': value.code, 'name': value.name } class EventSerializer(TranslatableModelSerializer): category = TypeField(read_only=True) place = PlaceListSerializer(read_only=True) # camelCase some field names targetGroup = TypeField(source='target_group', read_only=True) targetAge = TypeField(source='target_age', read_only=True) startAt = serializers.DateTimeField(source='start_at', read_only=True) endAt = serializers.DateTimeField(source='end_at', read_only=True) isFeatured = serializers.BooleanField(source='is_featured', read_only=True) isVisible = serializers.BooleanField(source='is_visible', read_only=True) href = serializers.SerializerMethodField() class Meta(object): model = Event exclude = ('target_group', 'target_age', 'start_at', 'end_at', 'is_featured', 'is_visible', 'language_code') def get_href(self, obj): return get_absolute_uri(reverse('v1:event-detail', [obj.id]))
Change camelCasing strategy for `target_age` and `target_group`
Change camelCasing strategy for `target_age` and `target_group`
Python
mit
zarautz/pagoeta,zarautz/pagoeta,zarautz/pagoeta
from hvad.contrib.restframework import TranslatableModelSerializer from rest_framework import serializers from rest_framework.reverse import reverse from .models import Category, TargetGroup, TargetAge, Event from pagoeta.apps.core.functions import get_absolute_uri from pagoeta.apps.places.serializers import PlaceListSerializer class TypeField(serializers.RelatedField): def to_representation(self, value): return { 'code': value.code, 'name': value.name } class EventSerializer(TranslatableModelSerializer): category = TypeField(read_only=True) - target_group = TypeField(read_only=True) - targetGroup = target_group - target_age = TypeField(read_only=True) - targetAge = target_age place = PlaceListSerializer(read_only=True) # camelCase some field names + targetGroup = TypeField(source='target_group', read_only=True) + targetAge = TypeField(source='target_age', read_only=True) startAt = serializers.DateTimeField(source='start_at', read_only=True) endAt = serializers.DateTimeField(source='end_at', read_only=True) isFeatured = serializers.BooleanField(source='is_featured', read_only=True) isVisible = serializers.BooleanField(source='is_visible', read_only=True) href = serializers.SerializerMethodField() class Meta(object): model = Event - exclude = ('start_at', 'end_at', 'is_featured', 'is_visible', 'language_code') + exclude = ('target_group', 'target_age', 'start_at', 'end_at', 'is_featured', 'is_visible', 'language_code') def get_href(self, obj): return get_absolute_uri(reverse('v1:event-detail', [obj.id]))
Change camelCasing strategy for `target_age` and `target_group`
## Code Before: from hvad.contrib.restframework import TranslatableModelSerializer from rest_framework import serializers from rest_framework.reverse import reverse from .models import Category, TargetGroup, TargetAge, Event from pagoeta.apps.core.functions import get_absolute_uri from pagoeta.apps.places.serializers import PlaceListSerializer class TypeField(serializers.RelatedField): def to_representation(self, value): return { 'code': value.code, 'name': value.name } class EventSerializer(TranslatableModelSerializer): category = TypeField(read_only=True) target_group = TypeField(read_only=True) targetGroup = target_group target_age = TypeField(read_only=True) targetAge = target_age place = PlaceListSerializer(read_only=True) # camelCase some field names startAt = serializers.DateTimeField(source='start_at', read_only=True) endAt = serializers.DateTimeField(source='end_at', read_only=True) isFeatured = serializers.BooleanField(source='is_featured', read_only=True) isVisible = serializers.BooleanField(source='is_visible', read_only=True) href = serializers.SerializerMethodField() class Meta(object): model = Event exclude = ('start_at', 'end_at', 'is_featured', 'is_visible', 'language_code') def get_href(self, obj): return get_absolute_uri(reverse('v1:event-detail', [obj.id])) ## Instruction: Change camelCasing strategy for `target_age` and `target_group` ## Code After: from hvad.contrib.restframework import TranslatableModelSerializer from rest_framework import serializers from rest_framework.reverse import reverse from .models import Category, TargetGroup, TargetAge, Event from pagoeta.apps.core.functions import get_absolute_uri from pagoeta.apps.places.serializers import PlaceListSerializer class TypeField(serializers.RelatedField): def to_representation(self, value): return { 'code': value.code, 'name': value.name } class EventSerializer(TranslatableModelSerializer): category = TypeField(read_only=True) place = PlaceListSerializer(read_only=True) # camelCase some field names targetGroup = TypeField(source='target_group', read_only=True) targetAge = TypeField(source='target_age', read_only=True) startAt = serializers.DateTimeField(source='start_at', read_only=True) endAt = serializers.DateTimeField(source='end_at', read_only=True) isFeatured = serializers.BooleanField(source='is_featured', read_only=True) isVisible = serializers.BooleanField(source='is_visible', read_only=True) href = serializers.SerializerMethodField() class Meta(object): model = Event exclude = ('target_group', 'target_age', 'start_at', 'end_at', 'is_featured', 'is_visible', 'language_code') def get_href(self, obj): return get_absolute_uri(reverse('v1:event-detail', [obj.id]))
# ... existing code ... category = TypeField(read_only=True) place = PlaceListSerializer(read_only=True) # ... modified code ... # camelCase some field names targetGroup = TypeField(source='target_group', read_only=True) targetAge = TypeField(source='target_age', read_only=True) startAt = serializers.DateTimeField(source='start_at', read_only=True) ... model = Event exclude = ('target_group', 'target_age', 'start_at', 'end_at', 'is_featured', 'is_visible', 'language_code') # ... rest of the code ...
ff460f9a3c7df3322271eeb5de3bead72fe121bc
bmi_tester/tests_pytest/test_grid_uniform_rectilinear.py
bmi_tester/tests_pytest/test_grid_uniform_rectilinear.py
import warnings import numpy as np def test_get_grid_shape(new_bmi, gid): """Test the grid shape.""" gtype = new_bmi.get_grid_type(gid) if gtype == 'uniform_rectilinear': ndim = new_bmi.get_grid_rank(gid) shape = np.empty(ndim, dtype=np.int32) try: rtn = new_bmi.get_grid_shape(gid, shape) except TypeError: warnings.warn('get_grid_shape should take two arguments') rtn = new_bmi.get_grid_shape(gid) shape[:] = rtn else: assert rtn is shape for dim in shape: assert dim > 0 if gtype == 'scalar': ndim = new_bmi.get_grid_rank(gid) shape = np.empty(ndim, dtype=np.int32) try: rtn = new_bmi.get_grid_shape(gid, shape) except TypeError: warnings.warn('get_grid_shape should take two arguments') rtn = new_bmi.get_grid_shape(gid) else: assert rtn is shape np.testing.assert_equal(shape, ()) def test_get_grid_spacing(new_bmi, gid): """Test the grid spacing.""" gtype = new_bmi.get_grid_type(gid) if gtype == 'uniform_rectilinear': ndim = new_bmi.get_grid_rank(gid) spacing = np.empty(ndim, dtype=float) assert spacing is new_bmi.get_grid_spacing(gid, spacing)
import warnings import numpy as np def test_get_grid_shape(new_bmi, gid): """Test the grid shape.""" gtype = new_bmi.get_grid_type(gid) if gtype == 'uniform_rectilinear': ndim = new_bmi.get_grid_rank(gid) shape = np.empty(ndim, dtype=np.int32) try: rtn = new_bmi.get_grid_shape(gid, shape) except TypeError: warnings.warn('get_grid_shape should take two arguments') rtn = new_bmi.get_grid_shape(gid) shape[:] = rtn else: assert rtn is shape for dim in shape: assert dim > 0 def test_get_grid_spacing(new_bmi, gid): """Test the grid spacing.""" gtype = new_bmi.get_grid_type(gid) if gtype == 'uniform_rectilinear': ndim = new_bmi.get_grid_rank(gid) spacing = np.empty(ndim, dtype=float) assert spacing is new_bmi.get_grid_spacing(gid, spacing)
Remove test for get_grid_shape for scalar grids.
Remove test for get_grid_shape for scalar grids.
Python
mit
csdms/bmi-tester
import warnings import numpy as np def test_get_grid_shape(new_bmi, gid): """Test the grid shape.""" gtype = new_bmi.get_grid_type(gid) if gtype == 'uniform_rectilinear': ndim = new_bmi.get_grid_rank(gid) shape = np.empty(ndim, dtype=np.int32) try: rtn = new_bmi.get_grid_shape(gid, shape) except TypeError: warnings.warn('get_grid_shape should take two arguments') rtn = new_bmi.get_grid_shape(gid) shape[:] = rtn else: assert rtn is shape for dim in shape: assert dim > 0 - if gtype == 'scalar': - ndim = new_bmi.get_grid_rank(gid) - - shape = np.empty(ndim, dtype=np.int32) - try: - rtn = new_bmi.get_grid_shape(gid, shape) - except TypeError: - warnings.warn('get_grid_shape should take two arguments') - rtn = new_bmi.get_grid_shape(gid) - else: - assert rtn is shape - np.testing.assert_equal(shape, ()) - def test_get_grid_spacing(new_bmi, gid): """Test the grid spacing.""" gtype = new_bmi.get_grid_type(gid) if gtype == 'uniform_rectilinear': ndim = new_bmi.get_grid_rank(gid) spacing = np.empty(ndim, dtype=float) assert spacing is new_bmi.get_grid_spacing(gid, spacing)
Remove test for get_grid_shape for scalar grids.
## Code Before: import warnings import numpy as np def test_get_grid_shape(new_bmi, gid): """Test the grid shape.""" gtype = new_bmi.get_grid_type(gid) if gtype == 'uniform_rectilinear': ndim = new_bmi.get_grid_rank(gid) shape = np.empty(ndim, dtype=np.int32) try: rtn = new_bmi.get_grid_shape(gid, shape) except TypeError: warnings.warn('get_grid_shape should take two arguments') rtn = new_bmi.get_grid_shape(gid) shape[:] = rtn else: assert rtn is shape for dim in shape: assert dim > 0 if gtype == 'scalar': ndim = new_bmi.get_grid_rank(gid) shape = np.empty(ndim, dtype=np.int32) try: rtn = new_bmi.get_grid_shape(gid, shape) except TypeError: warnings.warn('get_grid_shape should take two arguments') rtn = new_bmi.get_grid_shape(gid) else: assert rtn is shape np.testing.assert_equal(shape, ()) def test_get_grid_spacing(new_bmi, gid): """Test the grid spacing.""" gtype = new_bmi.get_grid_type(gid) if gtype == 'uniform_rectilinear': ndim = new_bmi.get_grid_rank(gid) spacing = np.empty(ndim, dtype=float) assert spacing is new_bmi.get_grid_spacing(gid, spacing) ## Instruction: Remove test for get_grid_shape for scalar grids. ## Code After: import warnings import numpy as np def test_get_grid_shape(new_bmi, gid): """Test the grid shape.""" gtype = new_bmi.get_grid_type(gid) if gtype == 'uniform_rectilinear': ndim = new_bmi.get_grid_rank(gid) shape = np.empty(ndim, dtype=np.int32) try: rtn = new_bmi.get_grid_shape(gid, shape) except TypeError: warnings.warn('get_grid_shape should take two arguments') rtn = new_bmi.get_grid_shape(gid) shape[:] = rtn else: assert rtn is shape for dim in shape: assert dim > 0 def test_get_grid_spacing(new_bmi, gid): """Test the grid spacing.""" gtype = new_bmi.get_grid_type(gid) if gtype == 'uniform_rectilinear': ndim = new_bmi.get_grid_rank(gid) spacing = np.empty(ndim, dtype=float) assert spacing is new_bmi.get_grid_spacing(gid, spacing)
... ...
a9d3f47098bc7499d62d4866883fa45622f01b74
app/main/errors.py
app/main/errors.py
from flask import render_template, current_app, request from . import main from ..helpers.search_helpers import get_template_data @main.app_errorhandler(404) def page_not_found(e): template_data = get_template_data(main, {}) return render_template("errors/404.html", **template_data), 404 @main.app_errorhandler(500) def page_not_found(e): template_data = get_template_data(main, {}) return render_template("errors/500.html", **template_data), 500
from flask import render_template, current_app, request from . import main from ..helpers.search_helpers import get_template_data from dmutils.apiclient import APIError @main.app_errorhandler(APIError) def api_error_handler(e): return _render_error_page(e.status_code) @main.app_errorhandler(404) def page_not_found(e): return _render_error_page(404) @main.app_errorhandler(500) def page_not_found(e): return _render_error_page(500) def _render_error_page(status_code): templates = { 404: "errors/404.html", 500: "errors/500.html", 503: "errors/500.html", } if status_code not in templates: status_code = 500 template_data = get_template_data(main, {}) return render_template(templates[status_code], **template_data), status_code
Add API error handling similar to supplier app
Add API error handling similar to supplier app Currently 404s returned by the API are resulting in 500s on the buyer app for invalid supplier requests. This change takes the model used in the supplier frontend to automatically handle uncaught APIErrors. It is not identical to the supplier app version because the default template data is generated in a different way.
Python
mit
alphagov/digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,AusDTO/dto-digitalmarketplace-buyer-frontend,AusDTO/dto-digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,AusDTO/dto-digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,AusDTO/dto-digitalmarketplace-buyer-frontend
from flask import render_template, current_app, request from . import main from ..helpers.search_helpers import get_template_data + from dmutils.apiclient import APIError + + + @main.app_errorhandler(APIError) + def api_error_handler(e): + return _render_error_page(e.status_code) @main.app_errorhandler(404) def page_not_found(e): + return _render_error_page(404) - template_data = get_template_data(main, {}) - return render_template("errors/404.html", **template_data), 404 @main.app_errorhandler(500) def page_not_found(e): + return _render_error_page(500) + + + def _render_error_page(status_code): + templates = { + 404: "errors/404.html", + 500: "errors/500.html", + 503: "errors/500.html", + } + if status_code not in templates: + status_code = 500 template_data = get_template_data(main, {}) - return render_template("errors/500.html", **template_data), 500 + return render_template(templates[status_code], **template_data), status_code +
Add API error handling similar to supplier app
## Code Before: from flask import render_template, current_app, request from . import main from ..helpers.search_helpers import get_template_data @main.app_errorhandler(404) def page_not_found(e): template_data = get_template_data(main, {}) return render_template("errors/404.html", **template_data), 404 @main.app_errorhandler(500) def page_not_found(e): template_data = get_template_data(main, {}) return render_template("errors/500.html", **template_data), 500 ## Instruction: Add API error handling similar to supplier app ## Code After: from flask import render_template, current_app, request from . import main from ..helpers.search_helpers import get_template_data from dmutils.apiclient import APIError @main.app_errorhandler(APIError) def api_error_handler(e): return _render_error_page(e.status_code) @main.app_errorhandler(404) def page_not_found(e): return _render_error_page(404) @main.app_errorhandler(500) def page_not_found(e): return _render_error_page(500) def _render_error_page(status_code): templates = { 404: "errors/404.html", 500: "errors/500.html", 503: "errors/500.html", } if status_code not in templates: status_code = 500 template_data = get_template_data(main, {}) return render_template(templates[status_code], **template_data), status_code
// ... existing code ... from ..helpers.search_helpers import get_template_data from dmutils.apiclient import APIError @main.app_errorhandler(APIError) def api_error_handler(e): return _render_error_page(e.status_code) // ... modified code ... def page_not_found(e): return _render_error_page(404) ... def page_not_found(e): return _render_error_page(500) def _render_error_page(status_code): templates = { 404: "errors/404.html", 500: "errors/500.html", 503: "errors/500.html", } if status_code not in templates: status_code = 500 template_data = get_template_data(main, {}) return render_template(templates[status_code], **template_data), status_code // ... rest of the code ...
77a6bb72318e9b02cbb1179cbbbacd3dd0bad55f
bookstore/__init__.py
bookstore/__init__.py
'''Bookstore Stores IPython notebooks automagically onto OpenStack clouds through Swift. ''' __title__ = 'bookstore' __version__ = '1.0.0' __build__ = 0x010000 __author__ = 'Kyle Kelley' __license__ = 'Apache 2.0' __copyright__ = 'Copyright 2013 Kyle Kelley' from . import swift from . import cloudfiles
'''Bookstore Stores IPython notebooks automagically onto OpenStack clouds through Swift. ''' __title__ = 'bookstore' __version__ = '1.0.0' __build__ = 0x010000 __author__ = 'Kyle Kelley' __license__ = 'Apache 2.0' __copyright__ = 'Copyright 2013 Kyle Kelley' #from . import swift #from . import cloudfiles from . import filenotebookmanager
Add unit test for bookstore
Add unit test for bookstore
Python
apache-2.0
wusung/ipython-notebook-store
'''Bookstore Stores IPython notebooks automagically onto OpenStack clouds through Swift. ''' __title__ = 'bookstore' __version__ = '1.0.0' __build__ = 0x010000 __author__ = 'Kyle Kelley' __license__ = 'Apache 2.0' __copyright__ = 'Copyright 2013 Kyle Kelley' - from . import swift + #from . import swift - from . import cloudfiles + #from . import cloudfiles + from . import filenotebookmanager
Add unit test for bookstore
## Code Before: '''Bookstore Stores IPython notebooks automagically onto OpenStack clouds through Swift. ''' __title__ = 'bookstore' __version__ = '1.0.0' __build__ = 0x010000 __author__ = 'Kyle Kelley' __license__ = 'Apache 2.0' __copyright__ = 'Copyright 2013 Kyle Kelley' from . import swift from . import cloudfiles ## Instruction: Add unit test for bookstore ## Code After: '''Bookstore Stores IPython notebooks automagically onto OpenStack clouds through Swift. ''' __title__ = 'bookstore' __version__ = '1.0.0' __build__ = 0x010000 __author__ = 'Kyle Kelley' __license__ = 'Apache 2.0' __copyright__ = 'Copyright 2013 Kyle Kelley' #from . import swift #from . import cloudfiles from . import filenotebookmanager
// ... existing code ... #from . import swift #from . import cloudfiles from . import filenotebookmanager // ... rest of the code ...
1c9feb7b2d9a4ac1a1d3bef42139ec5a7f26b95e
jsonrpcclient/__init__.py
jsonrpcclient/__init__.py
"""__init__.py""" import logging logger = logging.getLogger('jsonrpcclient') logger.addHandler(logging.StreamHandler()) from jsonrpcclient.server import Server
"""__init__.py""" import logging logger = logging.getLogger('jsonrpcclient') logger.addHandler(logging.StreamHandler()) logger.setLevel(logging.WARNING) from jsonrpcclient.server import Server
Set the loglevel again, seems like in certain situations, the default log level is 0
Set the loglevel again, seems like in certain situations, the default log level is 0
Python
mit
bcb/jsonrpcclient
"""__init__.py""" import logging logger = logging.getLogger('jsonrpcclient') logger.addHandler(logging.StreamHandler()) + logger.setLevel(logging.WARNING) from jsonrpcclient.server import Server
Set the loglevel again, seems like in certain situations, the default log level is 0
## Code Before: """__init__.py""" import logging logger = logging.getLogger('jsonrpcclient') logger.addHandler(logging.StreamHandler()) from jsonrpcclient.server import Server ## Instruction: Set the loglevel again, seems like in certain situations, the default log level is 0 ## Code After: """__init__.py""" import logging logger = logging.getLogger('jsonrpcclient') logger.addHandler(logging.StreamHandler()) logger.setLevel(logging.WARNING) from jsonrpcclient.server import Server
# ... existing code ... logger.addHandler(logging.StreamHandler()) logger.setLevel(logging.WARNING) # ... rest of the code ...
4dbeb34c0ca691ff4a9faf6d6a0fa9f67bacba5a
app/tests/conftest.py
app/tests/conftest.py
import os.path import pytest from alembic.command import upgrade from alembic.config import Config from app.database import sa, create_engine, create_db_session from app.models import Base HERE = os.path.dirname(os.path.abspath(__file__)) ALEMBIC_CONFIG = os.path.join(HERE, "..", "..", "alembic.ini") def apply_migrations(engine): """Applies all alembic migrations.""" from alembic.config import Config from alembic import command alembic_cfg = Config(ALEMBIC_CONFIG) with engine.begin() as connection: alembic_cfg.attributes['connection'] = connection command.upgrade(alembic_cfg, "head") @pytest.fixture(scope='session') def engine(request): """Session-wide test database.""" # create a SQLite DB in memory _engine = create_engine("sqlite://") # setup models in DB Base.metadata.create_all(_engine) return _engine @pytest.fixture(scope='function') def session(engine, request): """Creates a new database session for a test.""" _session = create_db_session(engine) connection = engine.connect() transaction = connection.begin() def fin(): transaction.rollback() connection.close() request.addfinalizer(fin) return _session
import os.path import pytest from alembic.command import upgrade from alembic.config import Config from app.database import db as _db from app.database import create_engine, create_db_session from app.models import Base HERE = os.path.dirname(os.path.abspath(__file__)) ALEMBIC_CONFIG = os.path.join(HERE, "..", "..", "alembic.ini") def apply_migrations(engine): """Applies all alembic migrations.""" from alembic.config import Config from alembic import command alembic_cfg = Config(ALEMBIC_CONFIG) with engine.begin() as connection: alembic_cfg.attributes['connection'] = connection command.upgrade(alembic_cfg, "head") @pytest.fixture(scope='session') def db(request): """Session-wide test database.""" # create a SQLite DB in memory _db.engine = create_engine("sqlite://") # setup models in DB Base.metadata.create_all(_db.engine) return _db @pytest.fixture(scope='function') def session(db, request): """Creates a new database session for a test.""" _session = create_db_session(db.engine) connection = db.engine.connect() transaction = connection.begin() def fin(): transaction.rollback() connection.close() request.addfinalizer(fin) return _session
Change engine fixture to use db obj
Change engine fixture to use db obj
Python
mit
PsyBorgs/redditanalyser,PsyBorgs/redditanalyser
import os.path import pytest from alembic.command import upgrade from alembic.config import Config + from app.database import db as _db - from app.database import sa, create_engine, create_db_session + from app.database import create_engine, create_db_session from app.models import Base HERE = os.path.dirname(os.path.abspath(__file__)) ALEMBIC_CONFIG = os.path.join(HERE, "..", "..", "alembic.ini") def apply_migrations(engine): """Applies all alembic migrations.""" from alembic.config import Config from alembic import command alembic_cfg = Config(ALEMBIC_CONFIG) with engine.begin() as connection: alembic_cfg.attributes['connection'] = connection command.upgrade(alembic_cfg, "head") @pytest.fixture(scope='session') - def engine(request): + def db(request): """Session-wide test database.""" # create a SQLite DB in memory - _engine = create_engine("sqlite://") + _db.engine = create_engine("sqlite://") # setup models in DB - Base.metadata.create_all(_engine) + Base.metadata.create_all(_db.engine) - return _engine + return _db @pytest.fixture(scope='function') - def session(engine, request): + def session(db, request): """Creates a new database session for a test.""" - _session = create_db_session(engine) + _session = create_db_session(db.engine) - connection = engine.connect() + connection = db.engine.connect() transaction = connection.begin() def fin(): transaction.rollback() connection.close() request.addfinalizer(fin) return _session
Change engine fixture to use db obj
## Code Before: import os.path import pytest from alembic.command import upgrade from alembic.config import Config from app.database import sa, create_engine, create_db_session from app.models import Base HERE = os.path.dirname(os.path.abspath(__file__)) ALEMBIC_CONFIG = os.path.join(HERE, "..", "..", "alembic.ini") def apply_migrations(engine): """Applies all alembic migrations.""" from alembic.config import Config from alembic import command alembic_cfg = Config(ALEMBIC_CONFIG) with engine.begin() as connection: alembic_cfg.attributes['connection'] = connection command.upgrade(alembic_cfg, "head") @pytest.fixture(scope='session') def engine(request): """Session-wide test database.""" # create a SQLite DB in memory _engine = create_engine("sqlite://") # setup models in DB Base.metadata.create_all(_engine) return _engine @pytest.fixture(scope='function') def session(engine, request): """Creates a new database session for a test.""" _session = create_db_session(engine) connection = engine.connect() transaction = connection.begin() def fin(): transaction.rollback() connection.close() request.addfinalizer(fin) return _session ## Instruction: Change engine fixture to use db obj ## Code After: import os.path import pytest from alembic.command import upgrade from alembic.config import Config from app.database import db as _db from app.database import create_engine, create_db_session from app.models import Base HERE = os.path.dirname(os.path.abspath(__file__)) ALEMBIC_CONFIG = os.path.join(HERE, "..", "..", "alembic.ini") def apply_migrations(engine): """Applies all alembic migrations.""" from alembic.config import Config from alembic import command alembic_cfg = Config(ALEMBIC_CONFIG) with engine.begin() as connection: alembic_cfg.attributes['connection'] = connection command.upgrade(alembic_cfg, "head") @pytest.fixture(scope='session') def db(request): """Session-wide test database.""" # create a SQLite DB in memory _db.engine = create_engine("sqlite://") # setup models in DB Base.metadata.create_all(_db.engine) return _db @pytest.fixture(scope='function') def session(db, request): """Creates a new database session for a test.""" _session = create_db_session(db.engine) connection = db.engine.connect() transaction = connection.begin() def fin(): transaction.rollback() connection.close() request.addfinalizer(fin) return _session
... from app.database import db as _db from app.database import create_engine, create_db_session from app.models import Base ... @pytest.fixture(scope='session') def db(request): """Session-wide test database.""" ... # create a SQLite DB in memory _db.engine = create_engine("sqlite://") ... # setup models in DB Base.metadata.create_all(_db.engine) return _db ... @pytest.fixture(scope='function') def session(db, request): """Creates a new database session for a test.""" _session = create_db_session(db.engine) connection = db.engine.connect() transaction = connection.begin() ...
71d56354fb053c6cef3dc2c8960f78f588327114
project/views.py
project/views.py
from django.shortcuts import render_to_response, render from django.http import HttpResponseRedirect from django.contrib.auth import login from forms import LoginForm def index(request): return render_to_response('index.html', {}) def login_view(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): user = form.cleaned_data['user'] if user is not None and user.is_active: login(request, user) return HttpResponseRedirect('/') else: form = LoginForm() return render(request, 'login.html', { 'form': form, })
from django.shortcuts import render_to_response, render from django.http import HttpResponseRedirect from django.contrib.auth import login from forms import LoginForm def index(request): return render_to_response('index.html', {}) def login_view(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): user = form.cleaned_data['user'] if user is not None and user.is_active: request.session['password'] = form.cleaned_data['password'] login(request, user) return HttpResponseRedirect('/') else: form = LoginForm() return render(request, 'login.html', { 'form': form, })
Store password in session after successful login.
Store password in session after successful login.
Python
agpl-3.0
InScience/DAMIS-old,InScience/DAMIS-old
from django.shortcuts import render_to_response, render from django.http import HttpResponseRedirect from django.contrib.auth import login from forms import LoginForm def index(request): return render_to_response('index.html', {}) def login_view(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): user = form.cleaned_data['user'] if user is not None and user.is_active: + request.session['password'] = form.cleaned_data['password'] login(request, user) return HttpResponseRedirect('/') else: form = LoginForm() return render(request, 'login.html', { 'form': form, })
Store password in session after successful login.
## Code Before: from django.shortcuts import render_to_response, render from django.http import HttpResponseRedirect from django.contrib.auth import login from forms import LoginForm def index(request): return render_to_response('index.html', {}) def login_view(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): user = form.cleaned_data['user'] if user is not None and user.is_active: login(request, user) return HttpResponseRedirect('/') else: form = LoginForm() return render(request, 'login.html', { 'form': form, }) ## Instruction: Store password in session after successful login. ## Code After: from django.shortcuts import render_to_response, render from django.http import HttpResponseRedirect from django.contrib.auth import login from forms import LoginForm def index(request): return render_to_response('index.html', {}) def login_view(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): user = form.cleaned_data['user'] if user is not None and user.is_active: request.session['password'] = form.cleaned_data['password'] login(request, user) return HttpResponseRedirect('/') else: form = LoginForm() return render(request, 'login.html', { 'form': form, })
// ... existing code ... if user is not None and user.is_active: request.session['password'] = form.cleaned_data['password'] login(request, user) // ... rest of the code ...
8ca16832b54c887e6e3a84d7018181bf7e55fba0
comrade/core/context_processors.py
comrade/core/context_processors.py
from django.conf import settings from django.contrib.sites.models import Site from settings import DeploymentType def default(request): context = {} context['DEPLOYMENT'] = settings.DEPLOYMENT context['site'] = Site.objects.get_current() if settings.DEPLOYMENT != DeploymentType.PRODUCTION: context['GIT_COMMIT'] = settings.GIT_COMMIT return context
from django.conf import settings from django.contrib.sites.models import Site from settings import DeploymentType def default(request): context = {} context['DEPLOYMENT'] = settings.DEPLOYMENT context['site'] = Site.objects.get_current() if settings.DEPLOYMENT != DeploymentType.PRODUCTION: context['GIT_COMMIT'] = settings.GIT_COMMIT return context def ssl_media(request): if request.is_secure(): ssl_media_url = settings.MEDIA_URL.replace('http://','https://') else: ssl_media_url = settings.MEDIA_URL return {'MEDIA_URL': ssl_media_url}
Add SSL media context processor.
Add SSL media context processor.
Python
mit
bueda/django-comrade
from django.conf import settings from django.contrib.sites.models import Site from settings import DeploymentType def default(request): context = {} context['DEPLOYMENT'] = settings.DEPLOYMENT context['site'] = Site.objects.get_current() if settings.DEPLOYMENT != DeploymentType.PRODUCTION: context['GIT_COMMIT'] = settings.GIT_COMMIT return context + def ssl_media(request): + if request.is_secure(): + ssl_media_url = settings.MEDIA_URL.replace('http://','https://') + else: + ssl_media_url = settings.MEDIA_URL + return {'MEDIA_URL': ssl_media_url} +
Add SSL media context processor.
## Code Before: from django.conf import settings from django.contrib.sites.models import Site from settings import DeploymentType def default(request): context = {} context['DEPLOYMENT'] = settings.DEPLOYMENT context['site'] = Site.objects.get_current() if settings.DEPLOYMENT != DeploymentType.PRODUCTION: context['GIT_COMMIT'] = settings.GIT_COMMIT return context ## Instruction: Add SSL media context processor. ## Code After: from django.conf import settings from django.contrib.sites.models import Site from settings import DeploymentType def default(request): context = {} context['DEPLOYMENT'] = settings.DEPLOYMENT context['site'] = Site.objects.get_current() if settings.DEPLOYMENT != DeploymentType.PRODUCTION: context['GIT_COMMIT'] = settings.GIT_COMMIT return context def ssl_media(request): if request.is_secure(): ssl_media_url = settings.MEDIA_URL.replace('http://','https://') else: ssl_media_url = settings.MEDIA_URL return {'MEDIA_URL': ssl_media_url}
... return context def ssl_media(request): if request.is_secure(): ssl_media_url = settings.MEDIA_URL.replace('http://','https://') else: ssl_media_url = settings.MEDIA_URL return {'MEDIA_URL': ssl_media_url} ...
935043dda123a030130571a2a4bb45b2b13f145c
addons/website_quote/__manifest__.py
addons/website_quote/__manifest__.py
{ 'name': 'Online Proposals', 'category': 'Website', 'summary': 'Sales', 'website': 'https://www.odoo.com/page/quote-builder', 'version': '1.0', 'description': "", 'depends': ['website', 'sale_management', 'mail', 'payment', 'website_mail', 'sale_payment'], 'data': [ 'data/website_quote_data.xml', 'report/sale_order_reports.xml', 'report/sale_order_templates.xml', 'report/website_quote_templates.xml', 'views/sale_order_views.xml', 'views/sale_quote_views.xml', 'views/website_quote_templates.xml', 'views/res_config_settings_views.xml', 'security/ir.model.access.csv', ], 'demo': [ 'data/website_quote_demo.xml' ], 'qweb': ['static/src/xml/*.xml'], 'installable': True, }
{ 'name': 'Online Proposals', 'category': 'Website', 'summary': 'Sales', 'website': 'https://www.odoo.com/page/quote-builder', 'version': '1.0', 'description': "", 'depends': ['website', 'sale_management', 'mail', 'payment', 'website_mail'], 'data': [ 'data/website_quote_data.xml', 'report/sale_order_reports.xml', 'report/sale_order_templates.xml', 'report/website_quote_templates.xml', 'views/sale_order_views.xml', 'views/sale_quote_views.xml', 'views/website_quote_templates.xml', 'views/res_config_settings_views.xml', 'security/ir.model.access.csv', ], 'demo': [ 'data/website_quote_demo.xml' ], 'qweb': ['static/src/xml/*.xml'], 'installable': True, }
Revert "[FIX] website_quote: make 'Pay & Confirm' work without website_sale"
Revert "[FIX] website_quote: make 'Pay & Confirm' work without website_sale" No dependency change in stable version This reverts commit 65a589eb54a1421baa71074701bea2873a83c75f.
Python
agpl-3.0
ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo
{ 'name': 'Online Proposals', 'category': 'Website', 'summary': 'Sales', 'website': 'https://www.odoo.com/page/quote-builder', 'version': '1.0', 'description': "", - 'depends': ['website', 'sale_management', 'mail', 'payment', 'website_mail', 'sale_payment'], + 'depends': ['website', 'sale_management', 'mail', 'payment', 'website_mail'], 'data': [ 'data/website_quote_data.xml', 'report/sale_order_reports.xml', 'report/sale_order_templates.xml', 'report/website_quote_templates.xml', 'views/sale_order_views.xml', 'views/sale_quote_views.xml', 'views/website_quote_templates.xml', 'views/res_config_settings_views.xml', 'security/ir.model.access.csv', ], 'demo': [ 'data/website_quote_demo.xml' ], 'qweb': ['static/src/xml/*.xml'], 'installable': True, }
Revert "[FIX] website_quote: make 'Pay & Confirm' work without website_sale"
## Code Before: { 'name': 'Online Proposals', 'category': 'Website', 'summary': 'Sales', 'website': 'https://www.odoo.com/page/quote-builder', 'version': '1.0', 'description': "", 'depends': ['website', 'sale_management', 'mail', 'payment', 'website_mail', 'sale_payment'], 'data': [ 'data/website_quote_data.xml', 'report/sale_order_reports.xml', 'report/sale_order_templates.xml', 'report/website_quote_templates.xml', 'views/sale_order_views.xml', 'views/sale_quote_views.xml', 'views/website_quote_templates.xml', 'views/res_config_settings_views.xml', 'security/ir.model.access.csv', ], 'demo': [ 'data/website_quote_demo.xml' ], 'qweb': ['static/src/xml/*.xml'], 'installable': True, } ## Instruction: Revert "[FIX] website_quote: make 'Pay & Confirm' work without website_sale" ## Code After: { 'name': 'Online Proposals', 'category': 'Website', 'summary': 'Sales', 'website': 'https://www.odoo.com/page/quote-builder', 'version': '1.0', 'description': "", 'depends': ['website', 'sale_management', 'mail', 'payment', 'website_mail'], 'data': [ 'data/website_quote_data.xml', 'report/sale_order_reports.xml', 'report/sale_order_templates.xml', 'report/website_quote_templates.xml', 'views/sale_order_views.xml', 'views/sale_quote_views.xml', 'views/website_quote_templates.xml', 'views/res_config_settings_views.xml', 'security/ir.model.access.csv', ], 'demo': [ 'data/website_quote_demo.xml' ], 'qweb': ['static/src/xml/*.xml'], 'installable': True, }
// ... existing code ... 'description': "", 'depends': ['website', 'sale_management', 'mail', 'payment', 'website_mail'], 'data': [ // ... rest of the code ...
d60ce9b23bcf2f8c60b2a8ce75eeba8779345b8b
Orange/tests/__init__.py
Orange/tests/__init__.py
import os import unittest from Orange.widgets.tests import test_setting_provider, \ test_settings_handler, test_context_handler, \ test_class_values_context_handler, test_domain_context_handler from Orange.widgets.data.tests import test_owselectcolumns try: from Orange.widgets.tests import test_widget run_widget_tests = True except ImportError: run_widget_tests = False def suite(): test_dir = os.path.dirname(__file__) all_tests = [ unittest.TestLoader().discover(test_dir), ] load = unittest.TestLoader().loadTestsFromModule all_tests.extend([ load(test_setting_provider), load(test_settings_handler), load(test_context_handler), load(test_class_values_context_handler), load(test_domain_context_handler), load(test_owselectcolumns) ]) if run_widget_tests: all_tests.extend([ load(test_widget), ]) return unittest.TestSuite(all_tests) test_suite = suite() if __name__ == '__main__': unittest.main(defaultTest='suite')
import os import unittest from Orange.widgets.tests import test_setting_provider, \ test_settings_handler, test_context_handler, \ test_class_values_context_handler, test_domain_context_handler from Orange.widgets.data.tests import test_owselectcolumns try: from Orange.widgets.tests import test_widget run_widget_tests = True except ImportError: run_widget_tests = False def suite(): test_dir = os.path.dirname(__file__) all_tests = [ unittest.TestLoader().discover(test_dir), ] load = unittest.TestLoader().loadTestsFromModule all_tests.extend([ load(test_setting_provider), load(test_settings_handler), load(test_context_handler), load(test_class_values_context_handler), load(test_domain_context_handler), load(test_owselectcolumns) ]) if run_widget_tests: all_tests.extend([ #load(test_widget), # does not run on travis ]) return unittest.TestSuite(all_tests) test_suite = suite() if __name__ == '__main__': unittest.main(defaultTest='suite')
Disable widget test. (does not run on travis)
Disable widget test. (does not run on travis)
Python
bsd-2-clause
marinkaz/orange3,cheral/orange3,qPCR4vir/orange3,kwikadi/orange3,kwikadi/orange3,kwikadi/orange3,cheral/orange3,qusp/orange3,marinkaz/orange3,cheral/orange3,qPCR4vir/orange3,qusp/orange3,qPCR4vir/orange3,marinkaz/orange3,marinkaz/orange3,kwikadi/orange3,cheral/orange3,kwikadi/orange3,qPCR4vir/orange3,qPCR4vir/orange3,qPCR4vir/orange3,cheral/orange3,marinkaz/orange3,cheral/orange3,kwikadi/orange3,qusp/orange3,marinkaz/orange3,qusp/orange3
import os import unittest from Orange.widgets.tests import test_setting_provider, \ test_settings_handler, test_context_handler, \ test_class_values_context_handler, test_domain_context_handler from Orange.widgets.data.tests import test_owselectcolumns try: from Orange.widgets.tests import test_widget run_widget_tests = True except ImportError: run_widget_tests = False def suite(): test_dir = os.path.dirname(__file__) all_tests = [ unittest.TestLoader().discover(test_dir), ] load = unittest.TestLoader().loadTestsFromModule all_tests.extend([ load(test_setting_provider), load(test_settings_handler), load(test_context_handler), load(test_class_values_context_handler), load(test_domain_context_handler), load(test_owselectcolumns) ]) if run_widget_tests: all_tests.extend([ - load(test_widget), + #load(test_widget), # does not run on travis ]) return unittest.TestSuite(all_tests) test_suite = suite() if __name__ == '__main__': unittest.main(defaultTest='suite')
Disable widget test. (does not run on travis)
## Code Before: import os import unittest from Orange.widgets.tests import test_setting_provider, \ test_settings_handler, test_context_handler, \ test_class_values_context_handler, test_domain_context_handler from Orange.widgets.data.tests import test_owselectcolumns try: from Orange.widgets.tests import test_widget run_widget_tests = True except ImportError: run_widget_tests = False def suite(): test_dir = os.path.dirname(__file__) all_tests = [ unittest.TestLoader().discover(test_dir), ] load = unittest.TestLoader().loadTestsFromModule all_tests.extend([ load(test_setting_provider), load(test_settings_handler), load(test_context_handler), load(test_class_values_context_handler), load(test_domain_context_handler), load(test_owselectcolumns) ]) if run_widget_tests: all_tests.extend([ load(test_widget), ]) return unittest.TestSuite(all_tests) test_suite = suite() if __name__ == '__main__': unittest.main(defaultTest='suite') ## Instruction: Disable widget test. (does not run on travis) ## Code After: import os import unittest from Orange.widgets.tests import test_setting_provider, \ test_settings_handler, test_context_handler, \ test_class_values_context_handler, test_domain_context_handler from Orange.widgets.data.tests import test_owselectcolumns try: from Orange.widgets.tests import test_widget run_widget_tests = True except ImportError: run_widget_tests = False def suite(): test_dir = os.path.dirname(__file__) all_tests = [ unittest.TestLoader().discover(test_dir), ] load = unittest.TestLoader().loadTestsFromModule all_tests.extend([ load(test_setting_provider), load(test_settings_handler), load(test_context_handler), load(test_class_values_context_handler), load(test_domain_context_handler), load(test_owselectcolumns) ]) if run_widget_tests: all_tests.extend([ #load(test_widget), # does not run on travis ]) return unittest.TestSuite(all_tests) test_suite = suite() if __name__ == '__main__': unittest.main(defaultTest='suite')
// ... existing code ... all_tests.extend([ #load(test_widget), # does not run on travis ]) // ... rest of the code ...
3df9cdb0f96e68fb6870f3ee261cd206d38fb787
octane/tests/test_app.py
octane/tests/test_app.py
import io from octane import app as o_app def test_help(): out, err = io.BytesIO(), io.BytesIO() app = o_app.OctaneApp(stdin=io.BytesIO(), stdout=out, stderr=err) try: app.run(["--help"]) except SystemExit as e: assert e.code == 0 assert not err.getvalue() assert 'Could not' not in out.getvalue()
import io import pytest from octane import app as o_app @pytest.fixture def octane_app(): return o_app.OctaneApp(stdin=io.BytesIO(), stdout=io.BytesIO(), stderr=io.BytesIO()) def test_help(octane_app): try: octane_app.run(["--help"]) except SystemExit as e: assert e.code == 0 assert not octane_app.stderr.getvalue() assert 'Could not' not in octane_app.stdout.getvalue()
Refactor test to use cool py.test's fixture
Refactor test to use cool py.test's fixture
Python
apache-2.0
Mirantis/octane,stackforge/fuel-octane,Mirantis/octane,stackforge/fuel-octane
import io + + import pytest from octane import app as o_app + @pytest.fixture + def octane_app(): + return o_app.OctaneApp(stdin=io.BytesIO(), stdout=io.BytesIO(), + stderr=io.BytesIO()) + + - def test_help(): + def test_help(octane_app): - out, err = io.BytesIO(), io.BytesIO() - app = o_app.OctaneApp(stdin=io.BytesIO(), stdout=out, stderr=err) try: - app.run(["--help"]) + octane_app.run(["--help"]) except SystemExit as e: assert e.code == 0 - assert not err.getvalue() + assert not octane_app.stderr.getvalue() - assert 'Could not' not in out.getvalue() + assert 'Could not' not in octane_app.stdout.getvalue()
Refactor test to use cool py.test's fixture
## Code Before: import io from octane import app as o_app def test_help(): out, err = io.BytesIO(), io.BytesIO() app = o_app.OctaneApp(stdin=io.BytesIO(), stdout=out, stderr=err) try: app.run(["--help"]) except SystemExit as e: assert e.code == 0 assert not err.getvalue() assert 'Could not' not in out.getvalue() ## Instruction: Refactor test to use cool py.test's fixture ## Code After: import io import pytest from octane import app as o_app @pytest.fixture def octane_app(): return o_app.OctaneApp(stdin=io.BytesIO(), stdout=io.BytesIO(), stderr=io.BytesIO()) def test_help(octane_app): try: octane_app.run(["--help"]) except SystemExit as e: assert e.code == 0 assert not octane_app.stderr.getvalue() assert 'Could not' not in octane_app.stdout.getvalue()
... import io import pytest ... @pytest.fixture def octane_app(): return o_app.OctaneApp(stdin=io.BytesIO(), stdout=io.BytesIO(), stderr=io.BytesIO()) def test_help(octane_app): try: octane_app.run(["--help"]) except SystemExit as e: ... assert e.code == 0 assert not octane_app.stderr.getvalue() assert 'Could not' not in octane_app.stdout.getvalue() ...
3e2746de9aae541880fe4cf643520a2577a3a0d5
tof_server/views.py
tof_server/views.py
"""This module provides views for application.""" from tof_server import app, versioning, mysql from flask import jsonify, make_response import string, random @app.route('/') def index(): """Server information""" return jsonify({ 'server-version' : versioning.SERVER_VERSION, 'client-versions' : versioning.CLIENT_VERSIONS }) @app.route('/players', methods=['POST']) def generate_new_id(): """Method for generating new unique player ids""" try: cursor = mysql.connection.cursor() new_pin = '' characters_pool = string.ascii_uppercase + string.digits for _ in range(8): new_pin = new_pin + random.SystemRandom().choice(characters_pool) insert_sql = "INSERT INTO players (auto_pin) VALUES (%s)" id_sql = "SELECT LAST_INSERT_ID()" cursor.execute(insert_sql, (new_pin,)) cursor.execute(id_sql) insert_data = cursor.fetchone() mysql.connection.commit() cursor.close() return jsonify({ 'id' : insert_data[0], 'pin' : new_pin }) except Exception as er_msg: return make_response(jsonify({ 'error' : str(er_msg) }), 500)
"""This module provides views for application.""" from tof_server import app, versioning, mysql from flask import jsonify, make_response import string, random @app.route('/') def index(): """Server information""" return jsonify({ 'server-version' : versioning.SERVER_VERSION, 'client-versions' : versioning.CLIENT_VERSIONS }) @app.route('/players', methods=['POST']) def generate_new_id(): """Method for generating new unique player ids""" cursor = mysql.connection.cursor() new_pin = '' characters_pool = string.ascii_uppercase + string.digits for _ in range(8): new_pin = new_pin + random.SystemRandom().choice(characters_pool) insert_sql = "INSERT INTO players (auto_pin) VALUES (%s)" id_sql = "SELECT LAST_INSERT_ID()" cursor.execute(insert_sql, (new_pin,)) cursor.execute(id_sql) insert_data = cursor.fetchone() mysql.connection.commit() cursor.close() return jsonify({ 'id' : insert_data[0], 'pin' : new_pin }) @app.route('/maps', methods=['POST']) def upload_new_map(): """Method for uploading new map""" return jsonify({ 'code' : 'dummy' }) @app.route('/maps/<string:map_code>', methods=['GET']) def download_map(map_code): """Method for downloading a map""" return jsonify({ 'code' : map_code, 'data' : 'dummy' })
Add stub methods for map handling
Add stub methods for map handling
Python
mit
P1X-in/Tanks-of-Freedom-Server
"""This module provides views for application.""" from tof_server import app, versioning, mysql from flask import jsonify, make_response import string, random @app.route('/') def index(): """Server information""" return jsonify({ 'server-version' : versioning.SERVER_VERSION, 'client-versions' : versioning.CLIENT_VERSIONS }) @app.route('/players', methods=['POST']) def generate_new_id(): """Method for generating new unique player ids""" - try: - cursor = mysql.connection.cursor() + cursor = mysql.connection.cursor() - new_pin = '' + new_pin = '' - characters_pool = string.ascii_uppercase + string.digits + characters_pool = string.ascii_uppercase + string.digits - for _ in range(8): + for _ in range(8): - new_pin = new_pin + random.SystemRandom().choice(characters_pool) + new_pin = new_pin + random.SystemRandom().choice(characters_pool) - insert_sql = "INSERT INTO players (auto_pin) VALUES (%s)" + insert_sql = "INSERT INTO players (auto_pin) VALUES (%s)" - id_sql = "SELECT LAST_INSERT_ID()" + id_sql = "SELECT LAST_INSERT_ID()" - cursor.execute(insert_sql, (new_pin,)) + cursor.execute(insert_sql, (new_pin,)) - cursor.execute(id_sql) + cursor.execute(id_sql) - insert_data = cursor.fetchone() + insert_data = cursor.fetchone() - mysql.connection.commit() + mysql.connection.commit() - cursor.close() + cursor.close() - return jsonify({ + return jsonify({ - 'id' : insert_data[0], + 'id' : insert_data[0], - 'pin' : new_pin + 'pin' : new_pin - }) + }) - except Exception as er_msg: - return make_response(jsonify({ - 'error' : str(er_msg) - }), 500) + @app.route('/maps', methods=['POST']) + def upload_new_map(): + """Method for uploading new map""" + return jsonify({ + 'code' : 'dummy' + }) + + @app.route('/maps/<string:map_code>', methods=['GET']) + def download_map(map_code): + """Method for downloading a map""" + return jsonify({ + 'code' : map_code, + 'data' : 'dummy' + }) +
Add stub methods for map handling
## Code Before: """This module provides views for application.""" from tof_server import app, versioning, mysql from flask import jsonify, make_response import string, random @app.route('/') def index(): """Server information""" return jsonify({ 'server-version' : versioning.SERVER_VERSION, 'client-versions' : versioning.CLIENT_VERSIONS }) @app.route('/players', methods=['POST']) def generate_new_id(): """Method for generating new unique player ids""" try: cursor = mysql.connection.cursor() new_pin = '' characters_pool = string.ascii_uppercase + string.digits for _ in range(8): new_pin = new_pin + random.SystemRandom().choice(characters_pool) insert_sql = "INSERT INTO players (auto_pin) VALUES (%s)" id_sql = "SELECT LAST_INSERT_ID()" cursor.execute(insert_sql, (new_pin,)) cursor.execute(id_sql) insert_data = cursor.fetchone() mysql.connection.commit() cursor.close() return jsonify({ 'id' : insert_data[0], 'pin' : new_pin }) except Exception as er_msg: return make_response(jsonify({ 'error' : str(er_msg) }), 500) ## Instruction: Add stub methods for map handling ## Code After: """This module provides views for application.""" from tof_server import app, versioning, mysql from flask import jsonify, make_response import string, random @app.route('/') def index(): """Server information""" return jsonify({ 'server-version' : versioning.SERVER_VERSION, 'client-versions' : versioning.CLIENT_VERSIONS }) @app.route('/players', methods=['POST']) def generate_new_id(): """Method for generating new unique player ids""" cursor = mysql.connection.cursor() new_pin = '' characters_pool = string.ascii_uppercase + string.digits for _ in range(8): new_pin = new_pin + random.SystemRandom().choice(characters_pool) insert_sql = "INSERT INTO players (auto_pin) VALUES (%s)" id_sql = "SELECT LAST_INSERT_ID()" cursor.execute(insert_sql, (new_pin,)) cursor.execute(id_sql) insert_data = cursor.fetchone() mysql.connection.commit() cursor.close() return jsonify({ 'id' : insert_data[0], 'pin' : new_pin }) @app.route('/maps', methods=['POST']) def upload_new_map(): """Method for uploading new map""" return jsonify({ 'code' : 'dummy' }) @app.route('/maps/<string:map_code>', methods=['GET']) def download_map(map_code): """Method for downloading a map""" return jsonify({ 'code' : map_code, 'data' : 'dummy' })
# ... existing code ... """Method for generating new unique player ids""" cursor = mysql.connection.cursor() new_pin = '' characters_pool = string.ascii_uppercase + string.digits for _ in range(8): new_pin = new_pin + random.SystemRandom().choice(characters_pool) insert_sql = "INSERT INTO players (auto_pin) VALUES (%s)" id_sql = "SELECT LAST_INSERT_ID()" cursor.execute(insert_sql, (new_pin,)) cursor.execute(id_sql) insert_data = cursor.fetchone() mysql.connection.commit() cursor.close() return jsonify({ 'id' : insert_data[0], 'pin' : new_pin }) @app.route('/maps', methods=['POST']) def upload_new_map(): """Method for uploading new map""" return jsonify({ 'code' : 'dummy' }) @app.route('/maps/<string:map_code>', methods=['GET']) def download_map(map_code): """Method for downloading a map""" return jsonify({ 'code' : map_code, 'data' : 'dummy' }) # ... rest of the code ...
23e57facea49ebc093d1da7a9ae6857cd2c8dad7
warehouse/defaults.py
warehouse/defaults.py
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals # The base domain name for this installation. Used to control linking to # sub-domains. SERVER_NAME = "warehouse.local" # The URI for our PostgreSQL database. SQLALCHEMY_DATABASE_URI = "postgres:///warehouse" # The type of Storage to use. Can be either Filesystem or S3. STORAGE = "Filesystem" # The hash to use in computing filenames. # Allowed values: md5, sha1, sha224, sha256, sha384, sha512, None STORAGE_HASH = "md5" # Base directory for storage when using the Filesystem. STORAGE_DIRECTORY = "data" # The name of the bucket that files will be stored in when using S3. # STORAGE_BUCKET = "<storage bucket>" # The S3 Key used to access S3 when using S3 Storage # S3_KEY = "<S3 Key>" # The S3 Secret used to access S# when using S3 Storage # S3_SECRET = "<S3 Secret>"
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals # The base domain name for this installation. Used to control linking to # sub-domains. SERVER_NAME = "warehouse.local" # The URI for our PostgreSQL database. SQLALCHEMY_DATABASE_URI = "postgres:///warehouse" # The URI for our Redis database. REDIS_URI = "redis://localhost:6379/0" # The type of Storage to use. Can be either Filesystem or S3. STORAGE = "Filesystem" # The hash to use in computing filenames. # Allowed values: md5, sha1, sha224, sha256, sha384, sha512, None STORAGE_HASH = "md5" # Base directory for storage when using the Filesystem. STORAGE_DIRECTORY = "data" # The name of the bucket that files will be stored in when using S3. # STORAGE_BUCKET = "<storage bucket>" # The S3 Key used to access S3 when using S3 Storage # S3_KEY = "<S3 Key>" # The S3 Secret used to access S# when using S3 Storage # S3_SECRET = "<S3 Secret>"
Add an explicit default for REDIS_URI
Add an explicit default for REDIS_URI
Python
bsd-2-clause
davidfischer/warehouse
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals # The base domain name for this installation. Used to control linking to # sub-domains. SERVER_NAME = "warehouse.local" # The URI for our PostgreSQL database. SQLALCHEMY_DATABASE_URI = "postgres:///warehouse" + + # The URI for our Redis database. + REDIS_URI = "redis://localhost:6379/0" # The type of Storage to use. Can be either Filesystem or S3. STORAGE = "Filesystem" # The hash to use in computing filenames. # Allowed values: md5, sha1, sha224, sha256, sha384, sha512, None STORAGE_HASH = "md5" # Base directory for storage when using the Filesystem. STORAGE_DIRECTORY = "data" # The name of the bucket that files will be stored in when using S3. # STORAGE_BUCKET = "<storage bucket>" # The S3 Key used to access S3 when using S3 Storage # S3_KEY = "<S3 Key>" # The S3 Secret used to access S# when using S3 Storage # S3_SECRET = "<S3 Secret>"
Add an explicit default for REDIS_URI
## Code Before: from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals # The base domain name for this installation. Used to control linking to # sub-domains. SERVER_NAME = "warehouse.local" # The URI for our PostgreSQL database. SQLALCHEMY_DATABASE_URI = "postgres:///warehouse" # The type of Storage to use. Can be either Filesystem or S3. STORAGE = "Filesystem" # The hash to use in computing filenames. # Allowed values: md5, sha1, sha224, sha256, sha384, sha512, None STORAGE_HASH = "md5" # Base directory for storage when using the Filesystem. STORAGE_DIRECTORY = "data" # The name of the bucket that files will be stored in when using S3. # STORAGE_BUCKET = "<storage bucket>" # The S3 Key used to access S3 when using S3 Storage # S3_KEY = "<S3 Key>" # The S3 Secret used to access S# when using S3 Storage # S3_SECRET = "<S3 Secret>" ## Instruction: Add an explicit default for REDIS_URI ## Code After: from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals # The base domain name for this installation. Used to control linking to # sub-domains. SERVER_NAME = "warehouse.local" # The URI for our PostgreSQL database. SQLALCHEMY_DATABASE_URI = "postgres:///warehouse" # The URI for our Redis database. REDIS_URI = "redis://localhost:6379/0" # The type of Storage to use. Can be either Filesystem or S3. STORAGE = "Filesystem" # The hash to use in computing filenames. # Allowed values: md5, sha1, sha224, sha256, sha384, sha512, None STORAGE_HASH = "md5" # Base directory for storage when using the Filesystem. STORAGE_DIRECTORY = "data" # The name of the bucket that files will be stored in when using S3. # STORAGE_BUCKET = "<storage bucket>" # The S3 Key used to access S3 when using S3 Storage # S3_KEY = "<S3 Key>" # The S3 Secret used to access S# when using S3 Storage # S3_SECRET = "<S3 Secret>"
// ... existing code ... SQLALCHEMY_DATABASE_URI = "postgres:///warehouse" # The URI for our Redis database. REDIS_URI = "redis://localhost:6379/0" // ... rest of the code ...